@dxtmisha/scripts 0.10.13 → 0.10.15

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,11 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [0.10.15] - 2026-08-10
6
+
7
+ ### Added
8
+ - **AI Prompt Self-Audit Directive**: Added `getAuditPrompt` method in `LibraryAiPrompt` to append a strict, mandatory self-audit directive (`## Mandatory Final Self-Audit (CRITICAL GUARD & STRICT COMPLIANCE)`) at the end of generated AI prompt files (`ai-prompt.md`), instructing AI models to re-study and audit all generated code against project rules before concluding work.
9
+
5
10
  ## [0.10.13] - 2026-08-06
6
11
 
7
12
  ### Changed
@@ -2,8 +2,10 @@
2
2
 
3
3
  import { DesignTypes } from '../src/classes/Design/DesignTypes'
4
4
 
5
- const dir: string = process.argv?.[2] ?? 'dist'
5
+ const isRaw: boolean = process.argv?.[2] === 'raw' || process.argv?.[2] === '1' || process.argv?.[2] === 'true'
6
+ const dir: string = process.argv?.[3]
7
+ const resourcesDir: string = process.argv?.[4]
6
8
 
7
- new DesignTypes(dir)
9
+ new DesignTypes(dir, resourcesDir, isRaw)
8
10
  .make()
9
11
  .then()
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dxtmisha/scripts",
3
3
  "private": false,
4
- "version": "0.10.13",
4
+ "version": "0.10.15",
5
5
  "type": "module",
6
6
  "description": "CLI tools, AI integration scripts, and automation utilities for DXT UI — automated component scaffolding, Figma layout generation, library packaging, documentation building, screenshot captures, and AI prompt processing.",
7
7
  "keywords": [
@@ -14,7 +14,7 @@
14
14
  "component-generator",
15
15
  "figma-sync",
16
16
  "ai-tools",
17
- "ai-prompts",
17
+ "ai-resources",
18
18
  "storybook",
19
19
  "documentation",
20
20
  "typescript",
@@ -106,4 +106,3 @@ export class AiClaudeCliLite extends AiAbstract<{}> {
106
106
  })
107
107
  }
108
108
  }
109
-
@@ -1,9 +1,25 @@
1
1
  import { FigmaApi } from '../FigmaApi'
2
2
  import { PropertiesConfig } from '../Properties/PropertiesConfig.ts'
3
3
 
4
+ /**
5
+ * Class for downloading and processing design assets from Figma API.
6
+ * Serves as an abstraction for initializing SVG graphics and frame exports from specified Figma files.
7
+ *
8
+ * Класс для скачивания и обработки дизайн-ассетов из Figma API.
9
+ * Служит абстракцией для инициализации SVG-графики и экспорта кадров из указанных файлов Figma.
10
+ */
4
11
  export class DesignFigma {
12
+ /** Figma REST API client instance / Экземпляр клиента REST API Figma */
5
13
  protected readonly api: FigmaApi
6
14
 
15
+ /**
16
+ * Creates an instance of DesignFigma.
17
+ *
18
+ * Создает экземпляр DesignFigma.
19
+ * @param fileKey unique Figma file identifier / уникальный идентификатор файла Figma
20
+ * @param nodeId target node or frame identifier in Figma file / идентификатор целевого узла или кадра в файле Figma
21
+ * @param token Figma API access token / токен доступа к API Figma
22
+ */
7
23
  constructor(
8
24
  protected readonly fileKey: string,
9
25
  protected readonly nodeId?: string,
@@ -12,10 +28,21 @@ export class DesignFigma {
12
28
  this.api = new FigmaApi(token, fileKey, nodeId)
13
29
  }
14
30
 
31
+ /**
32
+ * Executes the main workflow for retrieving and logging Figma design image assets.
33
+ *
34
+ * Выполняет основной процесс получения и логирования графических ассетов дизайна Figma.
35
+ */
15
36
  async make(): Promise<void> {
16
37
  console.log('Design Figma', await this.initImage())
17
38
  }
18
39
 
40
+ /**
41
+ * Requests SVG image export URLs for the specified node from Figma API.
42
+ *
43
+ * Запрашивает URL-адреса экспорта SVG-изображений для указанного узла через API Figma.
44
+ * @returns map of node IDs to SVG image URLs, or undefined on error / карта ID узлов к URL SVG-изображений или undefined в случае ошибки
45
+ */
19
46
  async initImage(): Promise<Record<string, string> | undefined> {
20
47
  const image = await this.api.fileImages({
21
48
  ids: this.nodeId as string,
@@ -29,10 +29,12 @@ export class DesignTypes {
29
29
  * Конструктор для DesignTypes.
30
30
  * @param dir input directory path containing declaration files / входной путь к директории, содержащей файлы деклараций
31
31
  * @param promptsDir input directory path containing prompt files / входной путь к директории, содержащей файлы промптов
32
+ * @param isRaw flag disabling AI processing to create raw types and empty description / флаг отключения ИИ обработки для создания сырых типов и пустого описания
32
33
  */
33
34
  constructor(
34
35
  protected readonly dir: string = 'dist',
35
- protected readonly promptsDir: string = 'ai-prompts'
36
+ protected readonly promptsDir: string = 'ai-resources',
37
+ protected readonly isRaw: boolean = false
36
38
  ) {
37
39
  ServerStorage.setErrorStatus(true)
38
40
  this.dirArray = this.dir.split('/')
@@ -49,38 +51,43 @@ export class DesignTypes {
49
51
  const files = this.getListByFilter()
50
52
  const jsFiles = this.getListByFilterJs()
51
53
 
52
- const fullContent = this.toOneFile(files)
54
+ const fullContent = this.cleanContent(this.toOneFile(files))
53
55
  const fullJsContent = this.toOneFile(jsFiles)
54
56
 
55
- const aiContent = await this.toAiEdit(fullContent, fullJsContent)
57
+ const aiContent = this.isRaw
58
+ ? fullContent
59
+ : await this.toAiEdit(fullContent, fullJsContent)
60
+ let fullDescription = ''
61
+ let mcpPrompts: DesignMcpResources | undefined
62
+
56
63
  this.save(aiContent)
57
64
 
58
- const aiDescription = await this.toAiDescription(fullContent, fullJsContent)
65
+ if (!this.isRaw) {
66
+ const aiDescription = await this.toAiDescription(fullContent, fullJsContent)
59
67
 
60
- const promptList = this.getListPrompts()
61
- const prompts = await this.toAiPrompts(promptList)
68
+ const promptList = this.getListPrompts()
69
+ const prompts = await this.toAiPrompts(promptList)
62
70
 
63
- const fullDescription = `${aiDescription}\n${prompts}`
64
- this.saveDescription(fullDescription)
71
+ fullDescription = `${aiDescription}\n${prompts}`
72
+
73
+ const mcpList: DesignTypesList = [
74
+ {
75
+ path: UI_FILE_AI_TYPES,
76
+ content: aiContent
77
+ },
78
+ {
79
+ path: UI_FILE_AI_DESCRIPTION,
80
+ content: fullDescription
81
+ },
82
+ ...promptList
83
+ ]
65
84
 
66
- const mcpList: DesignTypesList = [
67
- {
68
- path: UI_FILE_AI_TYPES,
69
- content: aiContent
70
- },
71
- {
72
- path: UI_FILE_AI_DESCRIPTION,
73
- content: fullDescription
74
- },
75
- ...promptList
76
- ]
77
-
78
- const mcpPrompts = await this.toAiMcpPrompts(mcpList)
79
-
80
- if (mcpPrompts) {
81
- this.saveMcp(mcpPrompts)
85
+ mcpPrompts = await this.toAiMcpPrompts(mcpList)
82
86
  }
83
87
 
88
+ this.saveDescription(fullDescription)
89
+ this.saveMcp(mcpPrompts ?? [])
90
+
84
91
  console.log('DesignTypes: AI types saved.')
85
92
  }
86
93
 
@@ -243,10 +250,11 @@ export class DesignTypes {
243
250
  const packageJson = getPackageJson()
244
251
 
245
252
  if (packageJson) {
253
+ const versionStr = packageJson.version ? ` (v${packageJson.version})` : ''
246
254
  PropertiesFile.writeByPath(
247
255
  UI_FILE_AI_TYPES,
248
256
  [
249
- `All these methods are in the ${packageJson.name} library.`,
257
+ `All these methods are in the ${packageJson.name}${versionStr} library.`,
250
258
  '',
251
259
  content
252
260
  ].join('\n')
@@ -307,6 +315,10 @@ export class DesignTypes {
307
315
  prompt: string,
308
316
  code?: string
309
317
  ): Promise<string | undefined> {
318
+ if (this.isRaw) {
319
+ return undefined
320
+ }
321
+
310
322
  const ai = useAi()
311
323
 
312
324
  if (ai) {
@@ -329,6 +341,28 @@ export class DesignTypes {
329
341
  return undefined
330
342
  }
331
343
 
344
+ /**
345
+ * Cleans up the content by removing imports, local exports, and empty lines.
346
+ *
347
+ * Очищает контент, удаляя импорты, локальные экспорты и пустые строки.
348
+ * @param content content to clean / контент для очистки
349
+ */
350
+ protected cleanContent(content: string): string {
351
+ return content
352
+ // Remove multi-line and single-line imports (only local files)
353
+ .replace(/^import\s+(?:{[^}]+}|[^{]+)\s+from\s+['"]\.[^'"]+['"];?/gm, '')
354
+ .replace(/^import\s+['"]\.[^'"]+['"];?/gm, '')
355
+ // Remove local internal re-exports (e.g., export * from "./...")
356
+ .replace(/^export\s+(?:\*|{[^}]+})\s+from\s+['"]\.[^'"]+['"];?/gm, '')
357
+ // Remove single-line private and protected properties
358
+ .replace(/^\s*(?:private|protected)\s+[^({]+;/gm, '')
359
+ // Remove lines that only contain inline comments
360
+ .replace(/^\s*\/\/.*$/gm, '')
361
+ // Remove empty lines
362
+ .replace(/^\s*[\r\n]/gm, '')
363
+ .trim()
364
+ }
365
+
332
366
  /**
333
367
  * Sends content to AI for optimization.
334
368
  *
@@ -43,12 +43,12 @@ export class DesignWikiStorm {
43
43
 
44
44
  if (packageFile) {
45
45
  const data: WebTypesVueJson = {
46
- $schema: 'https://raw.githubusercontent.com/JetBrains/web-types/master/schema/web-types.json',
47
- framework: 'vue',
48
- name: toCamelCaseFirst(PropertiesConfig.getDesignName()),
49
- version: packageFile.version,
46
+ '$schema': 'https://raw.githubusercontent.com/JetBrains/web-types/master/schema/web-types.json',
47
+ 'framework': 'vue',
48
+ 'name': toCamelCaseFirst(PropertiesConfig.getDesignName()),
49
+ 'version': packageFile.version,
50
50
  'js-types-syntax': 'typescript',
51
- contributions: {
51
+ 'contributions': {
52
52
  html: {
53
53
  'description-markup': 'markdown',
54
54
  'vue-components': await this.getComponents()
@@ -127,7 +127,7 @@ export class DesignWikiStormItem {
127
127
  const slots: WebTypesSlots = []
128
128
 
129
129
  data.slots.forEach(
130
- slot => {
130
+ (slot) => {
131
131
  const vueProperties: WebTypesProperty[] = (slot.properties ?? []).map(p => ({
132
132
  name: p.name,
133
133
  type: p.type ? this.cleanType(p.type) : undefined,
@@ -160,7 +160,7 @@ export class DesignWikiStormItem {
160
160
  const events: WebTypesEventItem[] = []
161
161
 
162
162
  data.events.forEach(
163
- event => {
163
+ (event) => {
164
164
  let typeString = '() => void'
165
165
  if (event.properties && event.properties.length > 0) {
166
166
  const args = event.properties
@@ -6,10 +6,10 @@ import {
6
6
 
7
7
  /**
8
8
  * Class representing an MCP item in the AI prompt generation process.
9
- * Handles reading `ai-mcp.json` configuration files for a package directory.
9
+ * Handles reading `ai-mcp-resources.json` configuration files for a package directory.
10
10
  *
11
11
  * Класс, представляющий элемент MCP в процессе создания промпта для ИИ.
12
- * Управляет чтением конфигурационных файлов `ai-mcp.json` для директории пакета.
12
+ * Управляет чтением конфигурационных файлов `ai-mcp-resources.json` для директории пакета.
13
13
  */
14
14
  export class LibraryAiMcpItem {
15
15
  /**
@@ -23,19 +23,19 @@ export class LibraryAiMcpItem {
23
23
  ) { }
24
24
 
25
25
  /**
26
- * Checks if the ai-mcp.json file exists in the directory.
26
+ * Checks if the ai-mcp-resources.json file exists in the directory.
27
27
  *
28
- * Проверяет, существует ли файл ai-mcp.json в директории.
29
- * @returns true if ai-mcp.json file exists / true, если файл ai-mcp.json существует
28
+ * Проверяет, существует ли файл ai-mcp-resources.json в директории.
29
+ * @returns true if ai-mcp-resources.json file exists / true, если файл ai-mcp-resources.json существует
30
30
  */
31
31
  isMcp(): boolean {
32
32
  return PropertiesFile.is(this.getPath(UI_FILE_AI_MCP))
33
33
  }
34
34
 
35
35
  /**
36
- * Reads and returns the list of MCP resource definitions from ai-mcp.json.
36
+ * Reads and returns the list of MCP resource definitions from ai-mcp-resources.json.
37
37
  *
38
- * Читает и возвращает список определений ресурсов MCP из ai-mcp.json.
38
+ * Читает и возвращает список определений ресурсов MCP из ai-mcp-resources.json.
39
39
  * @returns list of MCP resource items or undefined / список элементов ресурсов MCP или undefined
40
40
  */
41
41
  make(): Record<string, any>[] | undefined {
@@ -1,5 +1,5 @@
1
1
  import {
2
- UI_FILE_AI_MCP,
2
+ UI_FILE_AI_MCP_ALL,
3
3
  UI_FILE_AI_PROMPT_INSTRUCTION,
4
4
  UI_FILE_AI_PROMPT_PROMPT,
5
5
  UI_MODULES
@@ -97,6 +97,8 @@ Consolidated documentation, architectural guidelines, and mandatory rules for th
97
97
  prompts.push(instruction)
98
98
  }
99
99
 
100
+ prompts.push(this.getAuditPrompt())
101
+
100
102
  this.write(prompts)
101
103
 
102
104
  if (this.isMcp) {
@@ -118,6 +120,26 @@ Consolidated documentation, architectural guidelines, and mandatory rules for th
118
120
  return dirs.some(path => this.exFileOnDirs.test(path))
119
121
  }
120
122
 
123
+ /**
124
+ * Retrieves the final self-audit prompt for AI code verification.
125
+ *
126
+ * Получает итоговый промпт самоаудита для проверки кода ИИ.
127
+ * @returns formatted audit prompt / отформатированный промпт аудита
128
+ * @protected
129
+ */
130
+ protected getAuditPrompt(): string {
131
+ return `
132
+ ## Mandatory Final Self-Audit (CRITICAL GUARD & STRICT COMPLIANCE)
133
+
134
+ 🔴 **STOP! BEFORE DECLARING WORK COMPLETE OR ENDING YOUR TURN, YOU MUST AUDIT ALL CODE!** 🔴
135
+
136
+ 1. **Mandatory Full Re-Study**: Inspect EVERY single line of code created or modified in this task.
137
+ 2. **Rule-by-Rule Compliance Check**: Cross-reference all code changes against ALL architectural conventions, coding standards, JSDoc/TSDoc guidelines, and package rules defined in \`ai-prompt.md\`.
138
+ 3. **Zero Ignored Rules**: Ensure NO project rule, typing constraint, or code structure guideline was bypassed, forgotten, or ignored.
139
+ 4. **Self-Correction**: If any discrepancy, missing typing, bad JSDoc formatting, or rule violation is found during this audit, fix it IMMEDIATELY before concluding your turn.
140
+ `.trim()
141
+ }
142
+
121
143
  /**
122
144
  * Retrieves high-priority instructions from a specific file.
123
145
  *
@@ -243,7 +265,7 @@ ${globalPromptText}
243
265
  */
244
266
  protected writeMcp(mcpData: Record<string, any>[]): this {
245
267
  PropertiesFile.writeByPath(
246
- UI_FILE_AI_MCP,
268
+ UI_FILE_AI_MCP_ALL,
247
269
  mcpData
248
270
  )
249
271
 
@@ -46,9 +46,9 @@ export class LibraryAiPromptItem {
46
46
  }
47
47
 
48
48
  /**
49
- * Reads and returns the list of MCP resource definitions from ai-mcp.json.
49
+ * Reads and returns the list of MCP resource definitions from ai-mcp-resources.json.
50
50
  *
51
- * Читает и возвращает список определений ресурсов MCP из ai-mcp.json.
51
+ * Читает и возвращает список определений ресурсов MCP из ai-mcp-resources.json.
52
52
  * @returns list of MCP resource items or undefined / список элементов ресурсов MCP или undefined
53
53
  */
54
54
  getMcp(): Record<string, any>[] | undefined {
@@ -111,10 +111,10 @@ export class LibraryAiPromptItem {
111
111
  }
112
112
 
113
113
  /**
114
- * Checks if the ai-mcp.json file exists.
114
+ * Checks if the ai-mcp-resources.json file exists.
115
115
  *
116
- * Проверяет, существует ли файл ai-mcp.json.
117
- * @returns true if ai-mcp.json file exists / true, если файл ai-mcp.json существует
116
+ * Проверяет, существует ли файл ai-mcp-resources.json.
117
+ * @returns true if ai-mcp-resources.json file exists / true, если файл ai-mcp-resources.json существует
118
118
  */
119
119
  isMcp(): boolean {
120
120
  return this.itemMcp.isMcp()
package/src/config.ts CHANGED
@@ -121,7 +121,9 @@ export const UI_FILE_AI_TYPES = 'ai-types.md'
121
121
  /** AI description file name / Название файла с описанием AI */
122
122
  export const UI_FILE_AI_DESCRIPTION = 'ai-description.md'
123
123
  /** AI MCP resources file name / Название файла с ресурсами MCP AI */
124
- export const UI_FILE_AI_MCP = 'ai-mcp.json'
124
+ export const UI_FILE_AI_MCP = 'ai-mcp-resources.json'
125
+ /** AI MCP all resources file name / Название файла со всеми ресурсами MCP AI */
126
+ export const UI_FILE_AI_MCP_ALL = 'ai-mcp-all-resources.json'
125
127
  /** Style SCSS file name / Название файла стилей SCSS */
126
128
  export const UI_FILE_STYLE_SCSS = 'style.scss'
127
129
  /** UI properties SCSS file name / Название файла свойств UI в SCSS */
@@ -17,12 +17,12 @@
17
17
  "publish-to-npm": "npm publish --access public"
18
18
  },
19
19
  "files": [
20
- "ai-prompts/",
20
+ "ai-resources/",
21
21
  "ai-screenshot/",
22
22
  "dist",
23
23
  "ai-description.md",
24
24
  "ai-doc.md",
25
- "ai-mcp.json",
25
+ "ai-mcp-resources.json",
26
26
  "ai-types.md",
27
27
  "CHANGELOG.md",
28
28
  "LICENSE",
@@ -17,5 +17,5 @@ Strictly follow these rules for flawless dxt-ui code:
17
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
18
  8. **Aesthetics & Conciseness**: Group logically. Save tokens by avoiding redundant comments if code is self-explanatory.
19
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 local `ai-memory.md` **ONLY** upon explicit developer command (e.g., "remember", "save to memory") or for critical architectural rules/fixes. Do NOT add routine edits indiscriminately, change logs, or absolute paths (use relative only). Keep it focused strictly on critical architectural constraints and explicit developer instructions.
20
+ 10. **AI Workspace Memory (`ai-memory.md`)**: Actively APPLY its rules (highest priority). Update local `ai-memory.md` **ONLY** upon explicit developer command (e.g., "remember", "save to memory") or for critical architectural rules/fixes. **STRICTLY FORBIDDEN** to overwrite or delete existing file contents: you MUST **ONLY append** new directives to the end of the file. Do NOT add routine edits indiscriminately, change logs, or absolute paths (use relative only). Keep it focused strictly on critical architectural constraints and explicit developer instructions.
21
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.*
@@ -17,5 +17,5 @@
17
17
  7. **Безопасность и Производительность**: Защищенный код (`?.`, `??`, guard clauses). Явный `try-catch` для асинхронности. Не скрывай ошибки. Избегай тяжелых операций в циклах/реактивности.
18
18
  8. **Эстетика и Лаконичность**: Логическая группировка. Экономь токены, избегая избыточных комментариев, если код очевиден.
19
19
  9. **Строгое следование инструкциям**: Выполняй команды без додумывания, но предлагай уместные технические оптимизации, придерживаясь плана.
20
- 10. **Память ИИ (`ai-memory.md`)**: Активно ПРИМЕНЯЙ ее правила (высший приоритет). Обновляй локальный `ai-memory.md` **ТОЛЬКО** по явной команде разработчика (напр., «запомни», «сохрани в память») или при критических архитектурных правках/правилах. ЗАПРЕЩЕНО добавлять всё подряд, историю изменений (changelogs) и абсолютные пути (только относительные). Храни только действительно важные архитектурные ограничения и явные указания разработчика.
20
+ 10. **Память ИИ (`ai-memory.md`)**: Активно ПРИМЕНЯЙ ее правила (высший приоритет). Обновляй локальный `ai-memory.md` **ТОЛЬКО** по явной команде разработчика (напр., «запомни», «сохрани в память») или при критических архитектурных правках/правилах. **СТРОГО ЗАПРЕЩЕНО** полностью переписывать или удалять содержимое файла: записи разрешено **ТОЛЬКО дополнять** (append) в конец существующего содержимого. ЗАПРЕЩЕНО добавлять всё подряд, историю изменений (changelogs) и абсолютные пути (только относительные). Храни только действительно важные архитектурные ограничения и явные указания разработчика.
21
21
  11. **Обязательный полный самоаудит**: При создании новых сущностей ОБЯЗАТЕЛЬНО проверяй ВЕСЬ файл целиком. Строго контролируй отсутствие дублирования (DRY) и соблюдение всех правил проекта. *Исключение: мелкие правки существующего кода не требуют полного аудита.*
@@ -120,12 +120,12 @@ export type WebTypesVueComponentItem = WebTypesInfo & {
120
120
  * Корневой объект для JSON Web Types.
121
121
  */
122
122
  export type WebTypesVueJson = {
123
- $schema: string
124
- framework: 'vue'
125
- name: string
126
- version: string
123
+ '$schema': string
124
+ 'framework': 'vue'
125
+ 'name': string
126
+ 'version': string
127
127
  'js-types-syntax'?: 'typescript'
128
- contributions: {
128
+ 'contributions': {
129
129
  html: {
130
130
  'description-markup': 'markdown'
131
131
  'vue-components': WebTypesVueComponentItem[]