@dxtmisha/scripts 0.10.11 → 0.10.13

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,17 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [0.10.13] - 2026-08-06
6
+
7
+ ### Changed
8
+ - **AI Workspace Memory**: Updated `aiCodeGlobalPrompt` templates (EN & RU) and root `ai-prompt.md` to restrict `ai-memory.md` updates strictly to explicit developer requests or critical architectural rules.
9
+ - **DesignTypes**: Refined AI prompt summary generation in `toAiPromptName` to produce high-density topic and trigger criteria descriptions, and fixed prompt string joining formatting.
10
+
11
+
12
+
13
+ ### Changed
14
+ - **AI Generators & Design Types**: Added support for generating `ai-mcp.json` resources in `LibraryAiPrompt`, updated `DesignTypes.toAiEdit` JSDoc instructions, updated `AiZAiLite` prompt parameters, and updated package metadata (`ai-memory.md`).
15
+
5
16
  ## [0.10.11] - 2026-08-05
6
17
 
7
18
  ### Changed
@@ -2,4 +2,6 @@
2
2
 
3
3
  import { LibraryAiPrompt } from '../src/classes/Library/LibraryAiPrompt'
4
4
 
5
- new LibraryAiPrompt().make()
5
+ const isMcp = process.argv?.[2] === 'true' || process.argv?.[2] === '1'
6
+
7
+ new LibraryAiPrompt([], isMcp).make()
package/package.json CHANGED
@@ -1,20 +1,26 @@
1
1
  {
2
2
  "name": "@dxtmisha/scripts",
3
3
  "private": false,
4
- "version": "0.10.11",
4
+ "version": "0.10.13",
5
5
  "type": "module",
6
- "description": "Development scripts and CLI tools for DXT UI projects - automated component generation, library building and project management tools",
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": [
8
- "scripts",
9
8
  "cli",
10
- "development",
11
- "component-generator",
12
- "ui-library",
13
- "dxt-ui",
9
+ "scripts",
14
10
  "automation",
11
+ "generators",
12
+ "scaffolding",
15
13
  "build-tools",
14
+ "component-generator",
15
+ "figma-sync",
16
+ "ai-tools",
17
+ "ai-prompts",
18
+ "storybook",
19
+ "documentation",
16
20
  "typescript",
17
- "vue"
21
+ "vue",
22
+ "dxt",
23
+ "dxt-ui"
18
24
  ],
19
25
  "author": "dxtmisha@gmail.com",
20
26
  "license": "MIT",
@@ -70,17 +76,23 @@
70
76
  "node": ">=20.0.0"
71
77
  },
72
78
  "dependencies": {
79
+ "@ai-sdk/xai": "*",
80
+ "@anthropic-ai/claude-agent-sdk": "*",
73
81
  "@anthropic-ai/sdk": "*",
74
- "@dxtmisha/configuration": "*",
75
82
  "@dxtmisha/functional": "*",
76
83
  "@dxtmisha/functional-basic": "*",
77
84
  "@dxtmisha/media": "*",
78
- "@dxtmisha/styles": "*",
79
- "@dxtmisha/wiki": "*",
80
85
  "@google/genai": "*",
86
+ "@napi-rs/canvas": "*",
87
+ "ai": "*",
81
88
  "openai": "*",
82
89
  "puppeteer": "*",
90
+ "sass": "*",
83
91
  "typescript": "*",
92
+ "vite-node": "*",
84
93
  "vue": "*"
94
+ },
95
+ "devDependencies": {
96
+ "@dxtmisha/wiki": "*"
85
97
  }
86
98
  }
@@ -1,26 +1,77 @@
1
- import { OpenAI } from 'openai'
2
- import { AiOpenAiLite } from './AiOpenAiLite'
1
+ import { createXai, type XaiProvider } from '@ai-sdk/xai'
2
+ import { generateText } from 'ai'
3
+ import { forEach } from '@dxtmisha/functional-basic'
4
+
5
+ import { AiAbstract } from './AiAbstract'
3
6
 
4
7
  /**
5
- * Z.ai (Zhipu AI) implementation extending AiOpenAiLite.
6
- * Performs requests to the OpenAI-compatible Z.ai endpoint.
8
+ * xAI (Grok) implementation of AiAbstract using @ai-sdk/xai and ai SDK.
9
+ * Performs text generation requests via Grok models (e.g. grok-4.5).
7
10
  *
8
- * Реализация Z.ai (Zhipu AI) расширяющая AiOpenAiLite.
9
- * Выполняет запросы к OpenAI-совместимому эндпоинту Z.ai.
11
+ * Реализация xAI (Grok) поверх AiAbstract с использованием @ai-sdk/xai и ai SDK.
12
+ * Выполняет запросы генерации текста через модели Grok (например, grok-4.5).
10
13
  *
11
14
  * Responsibilities / Ответственности:
12
- * - Initialize OpenAI client with Z.ai baseURL / Инициализировать клиент OpenAI с baseURL Z.ai
15
+ * - Initialize xAI client provider / Инициализировать провайдер клиента xAI
16
+ * - Execute generateText via Grok responses model / Выполнять generateText через модель ответов Grok
13
17
  */
14
- export class AiZAiLite extends AiOpenAiLite {
18
+ export class AiZAiLite extends AiAbstract<XaiProvider> {
15
19
  /**
16
- * Initializes OpenAI client instance configured for Z.ai.
20
+ * Initializes xAI client provider instance.
17
21
  *
18
- * Инициализирует экземпляр клиента OpenAI, настроенный для Z.ai.
22
+ * Инициализирует экземпляр провайдера клиента xAI.
19
23
  */
20
- protected override init(): void {
21
- this.ai = new OpenAI({
22
- apiKey: this.key,
23
- baseURL: 'https://api.z.ai/api/paas/v4'
24
+ protected init(): void {
25
+ this.ai = createXai({
26
+ apiKey: this.key
24
27
  })
25
28
  }
29
+
30
+ /**
31
+ * Implementation hook: convert accumulated images to model-specific format.
32
+ *
33
+ * Хук реализации: преобразовать накопленные изображения в формат, специфичный для модели.
34
+ */
35
+ protected toImages(): any[] {
36
+ return forEach(this.images, image => ({
37
+ type: 'image',
38
+ image: `data:${image.mime};base64,${image.base64}`
39
+ }))
40
+ }
41
+
42
+ /**
43
+ * Implementation hook: convert accumulated contents to model-specific format.
44
+ *
45
+ * Хук реализации: преобразовать накопленное содержимое в формат, специфичный для модели.
46
+ */
47
+ protected toContents(): any[] {
48
+ return forEach(this.contents, content => ({
49
+ type: 'text',
50
+ text: content
51
+ }))
52
+ }
53
+
54
+ /**
55
+ * Performs content generation request using xAI responses model and returns textual result.
56
+ *
57
+ * Выполняет запрос генерации контента с использованием модели ответов xAI и возвращает текстовый результат.
58
+ * @param model - Model identifier (e.g., 'grok-4.5') / Идентификатор модели
59
+ * @param contents - Composed contents for generation / Собранный контент для генерации
60
+ * @returns Generated text response / Сгенерированный текстовый ответ
61
+ */
62
+ protected async response(
63
+ model: string,
64
+ contents: string
65
+ ): Promise<string> {
66
+ const client = this.ai ?? createXai({ apiKey: this.key })
67
+ const activeModel = model || 'grok-4.5'
68
+
69
+ const { text } = await generateText({
70
+ model: client.responses(activeModel as any),
71
+ prompt: contents,
72
+ ...this.config
73
+ })
74
+
75
+ return text ?? ''
76
+ }
26
77
  }
@@ -310,6 +310,8 @@ export class DesignTypes {
310
310
  const ai = useAi()
311
311
 
312
312
  if (ai) {
313
+ ai.addPrompt('You are a world-class senior developer and an exceptional technical writer.')
314
+ ai.addPrompt('CRITICAL DIRECTIVE: No data stored in history, previous chat messages, or prior conversation context must influence the result. Process strictly and exclusively the data provided in the text below.')
313
315
  ai.addPrompt(prompt)
314
316
  ai.addPrompt(`File Content: ${content}`)
315
317
 
@@ -407,24 +409,20 @@ export class DesignTypes {
407
409
  */
408
410
  protected async toAiPrompts(list: DesignTypesList): Promise<string> {
409
411
  const projectName = this.getProjectName()
410
- const promptList = await Promise.all(
411
- forEach(list, async (item) => {
412
- const content = await this.toAiPromptName(item.content)
412
+ const prompts: string[] = []
413
413
 
414
- if (isFilled(content)) {
415
- return `- '${UI_MODULES}/${projectName}/${item.path}': ${content}`
416
- }
417
-
418
- return ''
419
- })
420
- )
414
+ for (const item of list) {
415
+ const content = await this.toAiPromptName(item.content)
421
416
 
422
- const prompts = promptList.filter(Boolean).join('\n')
417
+ if (isFilled(content)) {
418
+ prompts.push(`- '${UI_MODULES}/${projectName}/${item.path}': ${content}`)
419
+ }
420
+ }
423
421
 
424
- if (prompts) {
422
+ if (prompts.length > 0) {
425
423
  return '## Mandatory Rules\n'
426
- + 'Read the corresponding file if your task relates to:\n'
427
- + `${prompts}`
424
+ + 'Read the corresponding file ONLY when working on a task related to (even if not working directly with this package):\n'
425
+ + `${prompts.join('\n')}`
428
426
  }
429
427
 
430
428
  return ''
@@ -439,18 +437,19 @@ export class DesignTypes {
439
437
  protected async toAiPromptName(content: string): Promise<string> {
440
438
  const generate = await this.toAi(
441
439
  content,
442
- 'Goal: Generate an EXTREMELY SHORT, high-density topic summary for an AI coding assistant describing what rules/topics are covered in this prompt document.\n\n'
440
+ 'Goal: Generate an EXTREMELY SHORT, high-density trigger and topic summary for an AI coding assistant describing what rules/topics are covered AND under what specific tasks, conditions, or use cases this document must be studied.\n\n'
443
441
  + 'CRITICAL RESTRICTIONS:\n'
444
- + '- The output MUST be EXTREMELY CONCISE: 1 short sentence or clause (maximum 10-15 words).\n'
445
- + '- Do NOT include repetitive filler like "When working with...", "you MUST study this document", or "in order to follow...".\n'
442
+ + '- The output MUST be EXTREMELY CONCISE: 1-2 short sentence or clause (maximum 30-35 words).\n'
443
+ + '- Clearly specify BOTH the key topics/rules AND the specific scenarios, tasks, or triggers when this document must be read.\n'
444
+ + '- Do NOT include repetitive filler like "you MUST study this document", "in order to follow...", or "when working with...".\n'
446
445
  + '- Analyze ONLY the text explicitly provided in this prompt.\n'
447
446
  + '- Do NOT include file paths, URLs, quotes, or markdown syntax.\n\n'
448
447
  + 'EXAMPLES OF GOOD OUTPUT:\n'
449
- + '- "Class structure, typing standards, SSR safety, and primitive helpers"\n'
450
- + '- "HTTP client, storage management, localization, and DOM event helpers"\n'
451
- + '- "MDX documentation generation rules for TypeScript classes"\n\n'
448
+ + '- "Class structure, typing standards, SSR safety, and primitive utility functions"\n'
449
+ + '- "HTTP client, storage management, localization formatting, and DOM event helpers"\n'
450
+ + '- "Implementing or wrapping D1 components, slot/event types, or customizing theme variables"\n\n'
452
451
  + 'OUTPUT REQUIREMENTS:\n'
453
- + 'Return ONLY the resulting short topic summary. No markdown code blocks (```), no labels, no quotes, and no conversational text.'
452
+ + 'Return ONLY the resulting short trigger and topic summary. No markdown code blocks (```), no labels, no quotes, and no conversational text.'
454
453
  )
455
454
 
456
455
  return generate ?? ''
@@ -476,7 +475,7 @@ export class DesignTypes {
476
475
  ) {
477
476
  resources.push({
478
477
  uri: `${projectName}/${item.path}`,
479
- name: data.name,
478
+ name: `${data.name} (${projectName})`,
480
479
  mimeType: data.mimeType ?? 'text/markdown',
481
480
  description: data.description
482
481
  })
@@ -0,0 +1,67 @@
1
+ import { PropertiesFile } from '../Properties/PropertiesFile'
2
+
3
+ import {
4
+ UI_FILE_AI_MCP
5
+ } from '../../config'
6
+
7
+ /**
8
+ * Class representing an MCP item in the AI prompt generation process.
9
+ * Handles reading `ai-mcp.json` configuration files for a package directory.
10
+ *
11
+ * Класс, представляющий элемент MCP в процессе создания промпта для ИИ.
12
+ * Управляет чтением конфигурационных файлов `ai-mcp.json` для директории пакета.
13
+ */
14
+ export class LibraryAiMcpItem {
15
+ /**
16
+ * Constructor for LibraryAiMcpItem.
17
+ *
18
+ * Конструктор для LibraryAiMcpItem.
19
+ * @param dir Path segments to the directory / Сегменты пути к директории
20
+ */
21
+ constructor(
22
+ protected readonly dir: string[] = []
23
+ ) { }
24
+
25
+ /**
26
+ * Checks if the ai-mcp.json file exists in the directory.
27
+ *
28
+ * Проверяет, существует ли файл ai-mcp.json в директории.
29
+ * @returns true if ai-mcp.json file exists / true, если файл ai-mcp.json существует
30
+ */
31
+ isMcp(): boolean {
32
+ return PropertiesFile.is(this.getPath(UI_FILE_AI_MCP))
33
+ }
34
+
35
+ /**
36
+ * Reads and returns the list of MCP resource definitions from ai-mcp.json.
37
+ *
38
+ * Читает и возвращает список определений ресурсов MCP из ai-mcp.json.
39
+ * @returns list of MCP resource items or undefined / список элементов ресурсов MCP или undefined
40
+ */
41
+ make(): Record<string, any>[] | undefined {
42
+ if (this.isMcp()) {
43
+ const data = PropertiesFile.readFile<Record<string, any>[]>(this.getPath(UI_FILE_AI_MCP))
44
+
45
+ if (
46
+ Array.isArray(data)
47
+ && data.length > 0
48
+ ) {
49
+ return data
50
+ }
51
+ }
52
+
53
+ return undefined
54
+ }
55
+
56
+ /**
57
+ * Constructs a full path for a file within the item's directory.
58
+ *
59
+ * Создает полный путь к файлу внутри директории элемента.
60
+ * @param dirFile File name / Имя файла
61
+ * @returns path segments / сегменты пути
62
+ * @protected
63
+ */
64
+ protected getPath(dirFile: string): string[] {
65
+ return [...this.dir, dirFile]
66
+ }
67
+ }
@@ -1,4 +1,5 @@
1
1
  import {
2
+ UI_FILE_AI_MCP,
2
3
  UI_FILE_AI_PROMPT_INSTRUCTION,
3
4
  UI_FILE_AI_PROMPT_PROMPT,
4
5
  UI_MODULES
@@ -35,9 +36,11 @@ export class LibraryAiPrompt {
35
36
  *
36
37
  * Конструктор для LibraryAiPrompt.
37
38
  * @param dirs Additional directories to scan / Дополнительные директории для сканирования
39
+ * @param isMcp Flag indicating whether to generate MCP configuration file / Флаг, указывающий, нужно ли генерировать конфигурационный файл MCP
38
40
  */
39
41
  constructor(
40
- dirs: string[] = []
42
+ dirs: string[] = [],
43
+ protected readonly isMcp: boolean = false
41
44
  ) {
42
45
  this.dirs = [
43
46
  ...LIBRARY_AI_PROMPT_LIST_DIRS,
@@ -68,6 +71,7 @@ Consolidated documentation, architectural guidelines, and mandatory rules for th
68
71
  this.getGlobalPrompt(),
69
72
  this.getVuePrompt()
70
73
  ]
74
+ const mcpData: Record<string, any>[] = []
71
75
 
72
76
  if (list.length > 0) {
73
77
  list.forEach((item) => {
@@ -76,6 +80,14 @@ Consolidated documentation, architectural guidelines, and mandatory rules for th
76
80
  if (prompt) {
77
81
  prompts.push(prompt)
78
82
  }
83
+
84
+ if (this.isMcp) {
85
+ const mcp = item.getMcp()
86
+
87
+ if (mcp) {
88
+ mcpData.push(...mcp)
89
+ }
90
+ }
79
91
  })
80
92
  }
81
93
 
@@ -87,6 +99,10 @@ Consolidated documentation, architectural guidelines, and mandatory rules for th
87
99
 
88
100
  this.write(prompts)
89
101
 
102
+ if (this.isMcp) {
103
+ this.writeMcp(mcpData)
104
+ }
105
+
90
106
  console.log('end')
91
107
  }
92
108
 
@@ -216,4 +232,21 @@ ${globalPromptText}
216
232
 
217
233
  return this
218
234
  }
235
+
236
+ /**
237
+ * Writes the collected MCP definitions to a file.
238
+ *
239
+ * Записывает собранные определения MCP в файл.
240
+ * @param mcpData list of MCP resource definitions / список определений ресурсов MCP
241
+ * @returns this instance / этот экземпляр
242
+ * @protected
243
+ */
244
+ protected writeMcp(mcpData: Record<string, any>[]): this {
245
+ PropertiesFile.writeByPath(
246
+ UI_FILE_AI_MCP,
247
+ mcpData
248
+ )
249
+
250
+ return this
251
+ }
219
252
  }
@@ -1,12 +1,13 @@
1
1
  import { PropertiesFile } from '../Properties/PropertiesFile'
2
+ import { LibraryAiMcpItem } from './LibraryAiMcpItem'
3
+ import { getPackageJson } from '../../functions/getPackageJson'
2
4
 
3
5
  import {
4
6
  UI_DIR_AI_PROMPT_SCREENSHOT,
5
7
  UI_FILE_AI_PROMPT_DESCRIPTION,
8
+ UI_FILE_AI_PROMPT_DEVELOPER,
6
9
  UI_FILE_AI_PROMPT_INFO,
7
- UI_FILE_AI_PROMPT_TYPES,
8
- UI_FILE_PACKAGE,
9
- UI_FILE_AI_PROMPT_DEVELOPER
10
+ UI_FILE_AI_PROMPT_TYPES
10
11
  } from '../../config'
11
12
 
12
13
  /**
@@ -19,8 +20,8 @@ import {
19
20
  * для создания насыщенного контекстом промпта для ИИ.
20
21
  */
21
22
  export class LibraryAiPromptItem {
22
- /** Cached partition of package.json. / Кэш содержимого файла package.json. */
23
- protected packageJson?: Record<string, any>
23
+ /** Item instance for working with MCP files. / Экземпляр элемента для работы с файлами MCP. */
24
+ protected readonly itemMcp: LibraryAiMcpItem
24
25
 
25
26
  /**
26
27
  * Constructor for LibraryAiPromptItem.
@@ -31,6 +32,27 @@ export class LibraryAiPromptItem {
31
32
  constructor(
32
33
  protected readonly dir: string[] = []
33
34
  ) {
35
+ this.itemMcp = new LibraryAiMcpItem(this.dir)
36
+ }
37
+
38
+ /**
39
+ * Returns directory path segments.
40
+ *
41
+ * Возвращает сегменты пути к директории.
42
+ * @returns path segments / сегменты пути
43
+ */
44
+ getDir(): string[] {
45
+ return this.dir
46
+ }
47
+
48
+ /**
49
+ * Reads and returns the list of MCP resource definitions from ai-mcp.json.
50
+ *
51
+ * Читает и возвращает список определений ресурсов MCP из ai-mcp.json.
52
+ * @returns list of MCP resource items or undefined / список элементов ресурсов MCP или undefined
53
+ */
54
+ getMcp(): Record<string, any>[] | undefined {
55
+ return this.itemMcp.make()
34
56
  }
35
57
 
36
58
  /**
@@ -40,7 +62,7 @@ export class LibraryAiPromptItem {
40
62
  * @returns project name or 'none' / название проекта или 'none'
41
63
  */
42
64
  getProjectName(): string {
43
- return this.getPackageJson().name ?? 'none'
65
+ return getPackageJson(this.dir)?.name ?? 'none'
44
66
  }
45
67
 
46
68
  /**
@@ -55,6 +77,7 @@ export class LibraryAiPromptItem {
55
77
  || this.isTypes()
56
78
  || this.isScreenshot()
57
79
  || this.isDeveloper()
80
+ || this.isMcp()
58
81
  }
59
82
 
60
83
  /**
@@ -88,13 +111,13 @@ export class LibraryAiPromptItem {
88
111
  }
89
112
 
90
113
  /**
91
- * Checks if the types file exists.
114
+ * Checks if the ai-mcp.json file exists.
92
115
  *
93
- * Проверяет, существует ли файл с типами.
94
- * @returns true if types file exists / true, если файл типов существует
116
+ * Проверяет, существует ли файл ai-mcp.json.
117
+ * @returns true if ai-mcp.json file exists / true, если файл ai-mcp.json существует
95
118
  */
96
- isTypes(): boolean {
97
- return PropertiesFile.is(this.getPath(UI_FILE_AI_PROMPT_TYPES))
119
+ isMcp(): boolean {
120
+ return this.itemMcp.isMcp()
98
121
  }
99
122
 
100
123
  /**
@@ -107,6 +130,16 @@ export class LibraryAiPromptItem {
107
130
  return PropertiesFile.is(this.getPath(UI_DIR_AI_PROMPT_SCREENSHOT))
108
131
  }
109
132
 
133
+ /**
134
+ * Checks if the types file exists.
135
+ *
136
+ * Проверяет, существует ли файл с типами.
137
+ * @returns true if types file exists / true, если файл типов существует
138
+ */
139
+ isTypes(): boolean {
140
+ return PropertiesFile.is(this.getPath(UI_FILE_AI_PROMPT_TYPES))
141
+ }
142
+
110
143
  /**
111
144
  * Gathers all available prompt content and formats it as a single string.
112
145
  *
@@ -137,63 +170,6 @@ ${data.join('\n\n')}
137
170
  return undefined
138
171
  }
139
172
 
140
- /**
141
- * Constructs a full path for a file within the item's directory.
142
- *
143
- * Создает полный путь к файлу внутри директории элемента.
144
- * @param dirFile File name / Имя файла
145
- * @returns path segments / сегменты пути
146
- * @protected
147
- */
148
- protected getPath(dirFile: string): string[] {
149
- return [...this.dir, dirFile]
150
- }
151
-
152
- /**
153
- * Returns the directory path as a string joined by a slash.
154
- *
155
- * Возвращает путь к директории в виде строки, объединенной слешем.
156
- * @returns path string / строка пути
157
- * @protected
158
- */
159
- protected getPathString(): string {
160
- return this.dir.join('/')
161
- }
162
-
163
- /**
164
- * Retrieves and caches package.json content.
165
- *
166
- * Получает и кэширует содержимое файла package.json.
167
- * @returns package.json object / объект package.json
168
- * @protected
169
- */
170
- protected getPackageJson(): Record<string, any> {
171
- if (!this.packageJson) {
172
- const path = this.getPath(UI_FILE_PACKAGE)
173
- this.packageJson = PropertiesFile.readFile(path) ?? {}
174
- }
175
-
176
- return this.packageJson
177
- }
178
-
179
- /**
180
- * Reads content of a file by its name relative to the item's directory.
181
- *
182
- * Читает содержимое файла по его имени относительно директории элемента.
183
- * @param dirFile File name / Имя файла
184
- * @returns file content / содержимое файла
185
- * @protected
186
- */
187
- protected readFile(dirFile: string): string {
188
- const file = PropertiesFile.readFileOnly(this.getPath(dirFile))
189
-
190
- if (file) {
191
- return file.replace(/([ '"`]|^)\.\//g, `$1${this.getPathString()}/`)
192
- }
193
-
194
- return ''
195
- }
196
-
197
173
  /**
198
174
  * Formats and returns the description section for the prompt.
199
175
  *
@@ -255,23 +231,26 @@ ${this.readFile(UI_FILE_AI_PROMPT_INFO)}
255
231
  }
256
232
 
257
233
  /**
258
- * Formats and returns the types section for the prompt.
234
+ * Constructs a full path for a file within the item's directory.
259
235
  *
260
- * Форматирует и возвращает секцию типов для промпта.
261
- * @returns formatted types reference or undefined / отформатированная ссылка на типы или undefined
236
+ * Создает полный путь к файлу внутри директории элемента.
237
+ * @param dirFile File name / Имя файла
238
+ * @returns path segments / сегменты пути
262
239
  * @protected
263
240
  */
264
- protected getTypes(): string | undefined {
265
- if (this.isTypes()) {
266
- console.log('-- Types')
267
-
268
- return `
269
- ## Package Type Definitions (Must Read in Full When Working with Package)
270
- '${this.getPathString()}/${UI_FILE_AI_PROMPT_TYPES}'
271
- `.trim()
272
- }
241
+ protected getPath(dirFile: string): string[] {
242
+ return [...this.dir, dirFile]
243
+ }
273
244
 
274
- return undefined
245
+ /**
246
+ * Returns the directory path as a string joined by a slash.
247
+ *
248
+ * Возвращает путь к директории в виде строки, объединенной слешем.
249
+ * @returns path string / строка пути
250
+ * @protected
251
+ */
252
+ protected getPathString(): string {
253
+ return this.dir.join('/')
275
254
  }
276
255
 
277
256
  /**
@@ -311,4 +290,42 @@ ${screenshot}
311
290
 
312
291
  return undefined
313
292
  }
293
+
294
+ /**
295
+ * Formats and returns the types section for the prompt.
296
+ *
297
+ * Форматирует и возвращает секцию типов для промпта.
298
+ * @returns formatted types reference or undefined / отформатированная ссылка на типы или undefined
299
+ * @protected
300
+ */
301
+ protected getTypes(): string | undefined {
302
+ if (this.isTypes()) {
303
+ console.log('-- Types')
304
+
305
+ return `
306
+ ## Package Type Definitions (Must Read in Full When Working with Package)
307
+ '${this.getPathString()}/${UI_FILE_AI_PROMPT_TYPES}'
308
+ `.trim()
309
+ }
310
+
311
+ return undefined
312
+ }
313
+
314
+ /**
315
+ * Reads content of a file by its name relative to the item's directory.
316
+ *
317
+ * Читает содержимое файла по его имени относительно директории элемента.
318
+ * @param dirFile File name / Имя файла
319
+ * @returns file content / содержимое файла
320
+ * @protected
321
+ */
322
+ protected readFile(dirFile: string): string {
323
+ const file = PropertiesFile.readFileOnly(this.getPath(dirFile))
324
+
325
+ if (file) {
326
+ return file.replace(/([ '"`]|^)\.\//g, `$1${this.getPathString()}/`)
327
+ }
328
+
329
+ return ''
330
+ }
314
331
  }
@@ -1,11 +1,19 @@
1
- import { PropertiesFile } from '../classes/Properties/PropertiesFile'
1
+ import { PropertiesFile, type PropertiesFilePath } from '../classes/Properties/PropertiesFile'
2
2
  import { UI_FILE_PACKAGE } from '../config'
3
3
 
4
4
  /**
5
5
  * Returns the package.json file content.
6
6
  *
7
7
  * Возвращает содержимое файла package.json.
8
+ * @param path path to directory or package.json file / путь к директории или файлу package.json
8
9
  */
9
- export function getPackageJson(): Record<string, any> | undefined {
10
+ export function getPackageJson(path?: PropertiesFilePath): Record<string, any> | undefined {
11
+ if (path) {
12
+ const targetPath = PropertiesFile.isDir(path)
13
+ ? PropertiesFile.getPathFile(path, UI_FILE_PACKAGE, '')
14
+ : path
15
+ return PropertiesFile.readFile<Record<string, any>>(targetPath)
16
+ }
17
+
10
18
  return PropertiesFile.readFile<Record<string, any>>(UI_FILE_PACKAGE)
11
19
  }
package/src/library.ts CHANGED
@@ -1,67 +1,68 @@
1
- // Classes
2
- export * from './classes/Ai/AiAbstract'
3
- export * from './classes/Ai/AiClaude'
4
- export * from './classes/Ai/AiClaudeAgent'
5
- export * from './classes/Ai/AiClaudeAgentLite'
6
- export * from './classes/Ai/AiClaudeCli'
7
- export * from './classes/Ai/AiClaudeCliLite'
8
- export * from './classes/Ai/AiClaudeLite'
9
- export * from './classes/Ai/AiDoc'
10
- export * from './classes/Ai/AiDocItem'
11
- export * from './classes/Ai/AiDocItemAbstract'
12
- export * from './classes/Ai/AiDocItemClasses'
13
- export * from './classes/Ai/AiDocItemComposables'
14
- export * from './classes/Ai/AiDocType'
15
- export * from './classes/Ai/AiGoogle'
16
- export * from './classes/Ai/AiGoogleCli'
17
- export * from './classes/Ai/AiGoogleCliLite'
18
- export * from './classes/Ai/AiGoogleLite'
19
- export * from './classes/Ai/AiOpenAi'
20
- export * from './classes/Ai/AiOpenAiLite'
21
- export * from './classes/Ai/AiZAi'
22
- export * from './classes/Ai/AiZAiLite'
23
- export * from './classes/Ai/ApiTmp'
24
- export * from './classes/BrowserItem'
25
- export * from './classes/Build/BuildFunctional'
26
- export * from './classes/Build/BuildPackages'
27
- export * from './classes/Build/BuildPublishPackages'
28
- export * from './classes/BuildItem'
29
- export * from './classes/Design/DesignFigma'
30
- export * from './classes/Design/DesignScreenshot'
31
- export * from './classes/Design/DesignTypes'
32
- export * from './classes/Design/DesignTypescript'
33
- export * from './classes/Design/DesignWikiStorm'
34
- export * from './classes/Design/DesignWikiStormItem'
35
- export * from './classes/FigmaApi'
36
- export * from './classes/Git/GitRead'
37
- export * from './classes/Library/LibraryAiPrompt'
38
- export * from './classes/Library/LibraryAiPromptItem'
39
- export * from './classes/Library/LibraryAiWiki'
40
- export * from './classes/Library/LibraryAiWikiItem'
41
- export * from './classes/Library/LibraryExport'
42
- export * from './classes/Library/LibraryList'
43
- export * from './classes/Library/LibraryPlugin'
44
- export * from './classes/Library/LibraryTypes'
45
- export * from './classes/Package/PackageFile'
46
- export * from './classes/Properties/PropertiesFile'
47
-
48
- // Composables
49
- export * from './composables/useAi'
50
-
51
- // Functions
52
- export * from './functions/getConfigAi'
53
- export * from './functions/getDirname'
54
- export * from './functions/getPackageJson'
55
- export * from './functions/hasNativeDirname'
56
- export * from './functions/run'
57
-
58
- // Types
59
- export * from './types/aiTypes'
60
- export * from './types/configTypes'
61
- export * from './types/designTypes'
62
- export * from './types/figmaApiTypes'
63
- export * from './types/gitTypes'
64
- export * from './types/libraryTypes'
65
- export * from './types/propertyTypes'
66
- export * from './types/screenshotTypes'
67
- export * from './types/webTypes'
1
+ // Classes
2
+ export * from './classes/Ai/AiAbstract'
3
+ export * from './classes/Ai/AiClaude'
4
+ export * from './classes/Ai/AiClaudeAgent'
5
+ export * from './classes/Ai/AiClaudeAgentLite'
6
+ export * from './classes/Ai/AiClaudeCli'
7
+ export * from './classes/Ai/AiClaudeCliLite'
8
+ export * from './classes/Ai/AiClaudeLite'
9
+ export * from './classes/Ai/AiDoc'
10
+ export * from './classes/Ai/AiDocItem'
11
+ export * from './classes/Ai/AiDocItemAbstract'
12
+ export * from './classes/Ai/AiDocItemClasses'
13
+ export * from './classes/Ai/AiDocItemComposables'
14
+ export * from './classes/Ai/AiDocType'
15
+ export * from './classes/Ai/AiGoogle'
16
+ export * from './classes/Ai/AiGoogleCli'
17
+ export * from './classes/Ai/AiGoogleCliLite'
18
+ export * from './classes/Ai/AiGoogleLite'
19
+ export * from './classes/Ai/AiOpenAi'
20
+ export * from './classes/Ai/AiOpenAiLite'
21
+ export * from './classes/Ai/AiZAi'
22
+ export * from './classes/Ai/AiZAiLite'
23
+ export * from './classes/Ai/ApiTmp'
24
+ export * from './classes/BrowserItem'
25
+ export * from './classes/Build/BuildFunctional'
26
+ export * from './classes/Build/BuildPackages'
27
+ export * from './classes/Build/BuildPublishPackages'
28
+ export * from './classes/BuildItem'
29
+ export * from './classes/Design/DesignFigma'
30
+ export * from './classes/Design/DesignScreenshot'
31
+ export * from './classes/Design/DesignTypes'
32
+ export * from './classes/Design/DesignTypescript'
33
+ export * from './classes/Design/DesignWikiStorm'
34
+ export * from './classes/Design/DesignWikiStormItem'
35
+ export * from './classes/FigmaApi'
36
+ export * from './classes/Git/GitRead'
37
+ export * from './classes/Library/LibraryAiMcpItem'
38
+ export * from './classes/Library/LibraryAiPrompt'
39
+ export * from './classes/Library/LibraryAiPromptItem'
40
+ export * from './classes/Library/LibraryAiWiki'
41
+ export * from './classes/Library/LibraryAiWikiItem'
42
+ export * from './classes/Library/LibraryExport'
43
+ export * from './classes/Library/LibraryList'
44
+ export * from './classes/Library/LibraryPlugin'
45
+ export * from './classes/Library/LibraryTypes'
46
+ export * from './classes/Package/PackageFile'
47
+ export * from './classes/Properties/PropertiesFile'
48
+
49
+ // Composables
50
+ export * from './composables/useAi'
51
+
52
+ // Functions
53
+ export * from './functions/getConfigAi'
54
+ export * from './functions/getDirname'
55
+ export * from './functions/getPackageJson'
56
+ export * from './functions/hasNativeDirname'
57
+ export * from './functions/run'
58
+
59
+ // Types
60
+ export * from './types/aiTypes'
61
+ export * from './types/configTypes'
62
+ export * from './types/designTypes'
63
+ export * from './types/figmaApiTypes'
64
+ export * from './types/gitTypes'
65
+ export * from './types/libraryTypes'
66
+ export * from './types/propertyTypes'
67
+ export * from './types/screenshotTypes'
68
+ export * from './types/webTypes'
@@ -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 it on developer feedback. **CRITICAL**: Any remark from the developer that has value for the future (e.g., code style, dos and don'ts) MUST be saved here. If the developer explicitly asks to save or remember something, you MUST save it. Do NOT store change logs or absolute paths (use relative). Keep it focused strictly on architectural constraints and developer preferences.
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.
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`)**: Активно ПРИМЕНЯЙ ее правила (высший приоритет). Обновляй при правках от разработчика. **ВАЖНО**: Любое замечание от разработчика, которое имеет ценность для будущего (например, стиль кода, что надо делать, а что нет), ДОЛЖНО быть сохранено здесь. Также, если разработчик просит сохранить или запомнить какую-либо информацию, ты ОБЯЗАН это сделать. ЗАПРЕЩЕНО хранить историю изменений (changelogs) и абсолютные пути (только относительные). Только актуальные стандарты и предпочтения разработчика.
20
+ 10. **Память ИИ (`ai-memory.md`)**: Активно ПРИМЕНЯЙ ее правила (высший приоритет). Обновляй локальный `ai-memory.md` **ТОЛЬКО** по явной команде разработчика (напр., «запомни», «сохрани в память») или при критических архитектурных правках/правилах. ЗАПРЕЩЕНО добавлять всё подряд, историю изменений (changelogs) и абсолютные пути (только относительные). Храни только действительно важные архитектурные ограничения и явные указания разработчика.
21
21
  11. **Обязательный полный самоаудит**: При создании новых сущностей ОБЯЗАТЕЛЬНО проверяй ВЕСЬ файл целиком. Строго контролируй отсутствие дублирования (DRY) и соблюдение всех правил проекта. *Исключение: мелкие правки существующего кода не требуют полного аудита.*