@dxtmisha/scripts 0.6.3 → 0.7.6

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.
Files changed (121) hide show
  1. package/bin/ai-doc.ts +1 -3
  2. package/bin/build-functional.ts +5 -0
  3. package/bin/design-flags.ts +5 -0
  4. package/bin/design-wiki-storm.ts +9 -0
  5. package/package.json +14 -8
  6. package/src/classes/Ai/AiAbstract.ts +14 -1
  7. package/src/classes/Ai/AiGoogleLite.ts +2 -1
  8. package/src/classes/Build/__tests__/buildFunctional.test.ts +43 -0
  9. package/src/classes/Build/buildFunctional.ts +54 -0
  10. package/src/classes/Component/ComponentCreator.ts +1 -0
  11. package/src/classes/Component/ComponentItem.ts +15 -0
  12. package/src/classes/Component/ComponentWiki.ts +8 -0
  13. package/src/classes/Component/ComponentWikiFile.ts +2 -0
  14. package/src/classes/Component/__tests__/ComponentCreator.test.ts +71 -0
  15. package/src/classes/Component/__tests__/ComponentItem.test.ts +71 -0
  16. package/src/classes/Design/DesignCommand.ts +65 -10
  17. package/src/classes/Design/DesignComponent.ts +303 -39
  18. package/src/classes/Design/DesignConstructor.ts +49 -20
  19. package/src/classes/Design/DesignConstructors.ts +61 -2
  20. package/src/classes/Design/DesignFlags.ts +215 -0
  21. package/src/classes/Design/DesignReplace.ts +11 -7
  22. package/src/classes/Design/DesignStructure.ts +8 -6
  23. package/src/classes/Design/DesignStructureClasses.ts +8 -4
  24. package/src/classes/Design/DesignStructureItemAbstract.ts +11 -2
  25. package/src/classes/Design/DesignStructureRead.ts +8 -4
  26. package/src/classes/Design/DesignStructureStyles.ts +8 -4
  27. package/src/classes/Design/DesignTypes.ts +53 -28
  28. package/src/classes/Design/DesignTypescript.ts +11 -2
  29. package/src/classes/Design/DesignUi.ts +74 -4
  30. package/src/classes/Design/DesignWiki.ts +4 -6
  31. package/src/classes/Design/DesignWikiStorm.ts +94 -0
  32. package/src/classes/Design/DesignWikiStormItem.ts +246 -0
  33. package/src/classes/Git/GitRead.ts +1 -0
  34. package/src/classes/Git/__tests__/GitRead.test.ts +70 -0
  35. package/src/classes/Library/LibraryAiWiki.ts +127 -0
  36. package/src/classes/Library/LibraryAiWikiItem.ts +79 -0
  37. package/src/classes/Library/LibraryExport.ts +0 -2
  38. package/src/classes/Library/LibraryFlags.ts +9 -7
  39. package/src/classes/Library/LibraryItems.ts +22 -13
  40. package/src/classes/Library/LibraryList.ts +189 -0
  41. package/src/classes/Library/LibraryMedia.ts +22 -8
  42. package/src/classes/Library/LibraryPlugin.ts +73 -0
  43. package/src/classes/Library/LibraryTypes.ts +130 -0
  44. package/src/classes/Package/PackageInit.ts +12 -4
  45. package/src/classes/Package/PackageItem.ts +16 -5
  46. package/src/classes/Properties/Properties.ts +14 -3
  47. package/src/classes/Properties/PropertiesCache.ts +19 -20
  48. package/src/classes/Properties/PropertiesConfig.ts +46 -26
  49. package/src/classes/Properties/PropertiesConvector.ts +10 -6
  50. package/src/classes/Properties/PropertiesFile.ts +27 -31
  51. package/src/classes/Properties/PropertiesImport.ts +10 -7
  52. package/src/classes/Properties/PropertiesItems.ts +19 -12
  53. package/src/classes/Properties/PropertiesKeys.ts +15 -9
  54. package/src/classes/Properties/PropertiesMain.ts +13 -7
  55. package/src/classes/Properties/PropertiesPalette.ts +12 -6
  56. package/src/classes/Properties/PropertiesPath.ts +17 -11
  57. package/src/classes/Properties/PropertiesScss.ts +10 -8
  58. package/src/classes/Properties/PropertiesSeparator.ts +9 -11
  59. package/src/classes/Properties/PropertiesSettings.ts +8 -6
  60. package/src/classes/Properties/PropertiesStandard.ts +5 -6
  61. package/src/classes/Properties/PropertiesTool.ts +16 -9
  62. package/src/classes/Properties/PropertiesTypes.ts +12 -12
  63. package/src/classes/Properties/PropertiesValues.ts +14 -14
  64. package/src/classes/Properties/PropertiesWrap.ts +5 -6
  65. package/src/classes/Properties/convector/convectorColor.ts +5 -3
  66. package/src/classes/Properties/to/PropertiesToAbstract.ts +18 -4
  67. package/src/classes/Styles/Styles.ts +1 -0
  68. package/src/composables/__tests__/useAi.test.ts +75 -0
  69. package/src/config.ts +9 -0
  70. package/src/functions/__tests__/getComponentPaths.test.ts +19 -0
  71. package/src/functions/__tests__/getConfigAi.test.ts +26 -0
  72. package/src/functions/__tests__/getConstructorProperties.test.ts +51 -0
  73. package/src/functions/__tests__/getDirname.test.ts +31 -0
  74. package/src/functions/__tests__/getNameDirByPaths.test.ts +40 -0
  75. package/src/functions/__tests__/getPackageJson.test.ts +34 -0
  76. package/src/functions/__tests__/hasNativeDirname.test.ts +18 -0
  77. package/src/functions/__tests__/toPathStandardSep.test.ts +31 -0
  78. package/src/functions/getConfigAi.ts +3 -2
  79. package/src/functions/toPathStandardSep.ts +1 -1
  80. package/src/library-ai.ts +0 -1
  81. package/src/library.ts +10 -0
  82. package/src/media/properties/css.ts +3 -1
  83. package/src/media/templates/component/{DesignComponentWikiAi.vue → DesignComponentAiWiki.vue} +2 -2
  84. package/src/media/templates/component/props.ts +2 -3
  85. package/src/media/templates/component/styleToken.scss +1 -1
  86. package/src/media/templates/component/wiki.ts +6 -12
  87. package/src/media/templates/component/wikiData.ts +28 -0
  88. package/src/media/templates/constructors/props.ts +3 -4
  89. package/src/media/templates/packages/figma/README.md +1 -0
  90. package/src/media/templates/packages/figma/ai.sample.config.ts +2 -0
  91. package/src/media/templates/packages/figma/design.config.json +3 -0
  92. package/src/media/templates/packages/figma/index.html +12 -0
  93. package/src/media/templates/packages/figma/manifest.json +25 -0
  94. package/src/media/templates/packages/figma/package.json +37 -0
  95. package/src/media/templates/packages/figma/src/App.vue +9 -0
  96. package/src/media/templates/packages/figma/src/classes/_.gitignore.txt +1 -0
  97. package/src/media/templates/packages/figma/src/code.ts +16 -0
  98. package/src/media/templates/packages/figma/src/components/_.gitignore.txt +1 -0
  99. package/src/media/templates/packages/figma/src/composables/_.gitignore.txt +1 -0
  100. package/src/media/templates/packages/figma/src/functions/_.gitignore.txt +1 -0
  101. package/src/media/templates/packages/figma/src/library.ts +0 -0
  102. package/src/media/templates/packages/figma/src/main.ts +4 -0
  103. package/src/media/templates/packages/figma/src/media/_.gitignore.txt +1 -0
  104. package/src/media/templates/packages/figma/src/storybook/_.gitignore.txt +1 -0
  105. package/src/media/templates/packages/figma/src/types/_.gitignore.txt +1 -0
  106. package/src/media/templates/packages/figma/src/vite-env.d.ts +1 -0
  107. package/src/media/templates/packages/figma/tsconfig.app.json +12 -0
  108. package/src/media/templates/packages/figma/tsconfig.json +7 -0
  109. package/src/media/templates/packages/figma/tsconfig.node.json +8 -0
  110. package/src/media/templates/packages/figma/vite.config.ts +7 -0
  111. package/src/media/templates/packages/library/src/main.ts +1 -1
  112. package/src/media/templates/packages/project/design.config.json +3 -0
  113. package/src/media/templates/packages/project/index.html +1 -2
  114. package/src/media/templates/packages/project/public/_.gitignore.txt +0 -0
  115. package/src/media/templates/packages/project/src/main.ts +2 -1
  116. package/src/media/templates/packages/project/src/vite-env.d.ts +1 -0
  117. package/src/types/configTypes.ts +6 -0
  118. package/src/types/designTypes.ts +12 -0
  119. package/src/types/libraryTypes.ts +1 -1
  120. package/src/types/webTypes.ts +105 -0
  121. /package/src/media/templates/packages/{library/public/_.gitignore.txt → figma/src/config.ts} +0 -0
@@ -20,9 +20,11 @@ type PropertiesCacheSystem = {
20
20
  }
21
21
 
22
22
  /**
23
- * Processing for storing temporary files.
23
+ * Static orchestrator for managing persistent file caching in the design system.
24
+ * Provides a structured mechanism for storing transformed tokens, tracking file dependencies, and ensuring incremental build performance by avoiding redundant processing.
24
25
  *
25
- * Обработка для хранения временных файлов.
26
+ * Статический оркестратор для управления постоянным файловым кэшированием в дизайн-системе.
27
+ * Предоставляет структурированный механизм для хранения трансформированных токенов, отслеживания зависимостей файлов и обеспечения производительности инкрементальной сборки за счет исключения повторной обработки.
26
28
  */
27
29
  export class PropertiesCache {
28
30
  private static time = 0
@@ -31,16 +33,13 @@ export class PropertiesCache {
31
33
  private static readonly listenerName: string[] = ['global']
32
34
 
33
35
  /**
34
- * Reads data from the cache or updates the cache if the data is outdated.
36
+ * Retrieves data from the cache or executes the callback to regenerate and store it if the cache is missing or outdated.
35
37
  *
36
- * Читает данные из кэша или обновляет кэш, если данные устарели.
37
- * @param path path to the file/ путь к файлу
38
- * @param name file name/ название файла
39
- * @param callback if the file is not found, the callback function is called
40
- * and its result is saved in the current file /
41
- * если файл не найден, вызывается функция обратного вызова (callback) и её
42
- * результат сохраняется в текущем файле
43
- * @param extension file extension by default is json/ расширение файла по умолчанию - json
38
+ * Извлекает данные из кэша или выполняет функцию обратного вызова для регенерации и сохранения данных, если кэш отсутствует или устарел.
39
+ * @param path the logical path structure for the cache file/ логическая структура пути для файла кэша
40
+ * @param name the unique identifier for the cache entry/ уникальный идентификатор записи кэша
41
+ * @param callback the generator function to execute on cache miss/ функция-генератор, выполняемая при отсутствии данных в кэше
42
+ * @param extension the file extension, typically 'json'/ расширение файла, обычно 'json'
44
43
  */
45
44
  static get<T extends PropertiesFileValue>(
46
45
  path: PropertiesFilePath,
@@ -67,10 +66,10 @@ export class PropertiesCache {
67
66
  }
68
67
 
69
68
  /**
70
- * Returns the content of the file by the specified path
69
+ * Directly reads a file and registers it as a dependency for the currently active cache listener.
71
70
  *
72
- * Возвращает содержимое файла по указанному пути.
73
- * @param path filename/ имя файла
71
+ * Напрямую читает файл и регистрирует его как зависимость для текущего активного слушателя кэша.
72
+ * @param path the path to the file to be read/ путь к считываемому файлу
74
73
  */
75
74
  static read<R>(path: PropertiesFilePath): R | undefined {
76
75
  if (PropertiesFile.is(path)) {
@@ -89,20 +88,20 @@ export class PropertiesCache {
89
88
  }
90
89
 
91
90
  /**
92
- * Saves intermediate data
91
+ * Persists intermediate results to the temporary step-based cache directory.
93
92
  *
94
- * Сохраняет промежуточные данные.
95
- * @param name file name/ название файла
96
- * @param value values for storage/ значения для хранения
93
+ * Сохраняет промежуточные результаты во временную директорию пошагового кэша.
94
+ * @param name the name of the cached step result/ название кэшированного результата шага
95
+ * @param value the data structure to persist/ структура данных для сохранения
97
96
  */
98
97
  static write<T extends PropertiesFileValue>(name: string, value: T): void {
99
98
  this.writeFile<T>(DIR_STEP, name, value)
100
99
  }
101
100
 
102
101
  /**
103
- * Clear cached data
102
+ * Recursively removes all cached data from the `.cache` directory.
104
103
  *
105
- * Очистить кешированные данные.
104
+ * Рекурсивно удаляет все кэшированные данные из директории `.cache`.
106
105
  */
107
106
  static clear(): void {
108
107
  PropertiesFile.removeDir(this.getPath([]))
@@ -13,116 +13,136 @@ import {
13
13
  } from '../../config'
14
14
 
15
15
  /**
16
- * Class for retrieving configuration data.
16
+ * Static configuration orchestrator for the design system.
17
+ * Responsible for locating, loading, and merging the `design-ui.json` configuration file, handling recursive extensions, and providing a centralized interface for accessing project-wide settings including naming, separators, and AI integration parameters.
17
18
  *
18
- * Класс для получения данных конфигурации.
19
+ * Статический оркестратор конфигурации для дизайн-системы.
20
+ * Отвечает за поиск, загрузку и слияние файла конфигурации `design-ui.json`, обработку рекурсивных расширений и предоставление централизованного интерфейса для доступа к общепроектным настройкам, включая именование, разделители и параметры интеграции ИИ.
19
21
  */
20
22
  export class PropertiesConfig {
21
23
  protected static config: DesignUiConfig
22
24
 
23
25
  /**
24
- * Returns the project name.
26
+ * Retrieves the global project identifier.
25
27
  *
26
- * Возвращает название проекта.
28
+ * Получает глобальный идентификатор проекта.
27
29
  */
28
30
  static getProjectName(): string {
29
31
  return this.config.project ?? 'ui'
30
32
  }
31
33
 
32
34
  /**
33
- * Returns the project name.
35
+ * Retrieves the primary design system name.
34
36
  *
35
- * Возвращает название проекта.
37
+ * Получает основное название дизайн-системы.
36
38
  */
37
39
  static getDesignName(): string {
38
40
  return this.config.name ?? 'ui'
39
41
  }
40
42
 
41
43
  /**
42
- * Returns the separator symbol.
44
+ * Returns alternative design system aliases.
43
45
  *
44
- * Возвращает символ разделителя.
46
+ * Возвращает альтернативные алиасы дизайн-системы.
47
+ */
48
+ static getDesignAlternativeName(): string[] | undefined {
49
+ return this.config?.alternativeName
50
+ }
51
+
52
+ /**
53
+ * Returns the token path separator character.
54
+ *
55
+ * Возвращает символ-разделитель пути токена.
45
56
  */
46
57
  static getSeparator(): string {
47
58
  return this.config.separator ?? '/'
48
59
  }
49
60
 
50
61
  /**
51
- * Returns the base name of the separator.
62
+ * Returns the identifier for the base level separator.
52
63
  *
53
- * Возвращает базовое название разделителя.
64
+ * Возвращает идентификатор для базового разделителя.
54
65
  */
55
66
  static getSeparatorBasicName(): string {
56
67
  return this.config.separatorBasicName ?? 'basic'
57
68
  }
58
69
 
59
70
  /**
60
- * Returns the limit of separator characters in a single key.
71
+ * Returns the maximum depth for token path segments.
61
72
  *
62
- * Возвращает лимит символов-разделителей в одном ключе.
73
+ * Возвращает максимальную глубину сегментов пути токена.
63
74
  */
64
75
  static getSeparatorLimit(): number {
65
76
  return this.config.separatorLimit ?? 6
66
77
  }
67
78
 
68
79
  /**
69
- * Returns the wiki language.
80
+ * Returns the primary language for documentation generation.
70
81
  *
71
- * Возвращает язык wiki.
82
+ * Возвращает основной язык для генерации документации.
72
83
  */
73
84
  static getWikiLanguage(): string {
74
85
  return this.config.wikiLanguage ?? 'en'
75
86
  }
76
87
 
77
88
  /**
78
- * Returns the package prefix.
89
+ * Returns the prefix for generated npm packages.
79
90
  *
80
- * Возвращает префикс пакета.
91
+ * Возвращает префикс для генерируемых npm-пакетов.
81
92
  */
82
93
  static getPackagePrefix(): string | undefined {
83
94
  return this.config.packagePrefix ?? undefined
84
95
  }
85
96
 
86
97
  /**
87
- * Returns the AI type.
98
+ * Returns the configured AI provider type.
88
99
  *
89
- * Возвращает тип ИИ.
100
+ * Возвращает настроенный тип ИИ-провайдера.
90
101
  */
91
102
  static getAiType(): AiType {
92
103
  return this.config.aiType ?? 'gemini'
93
104
  }
94
105
 
95
106
  /**
96
- * Returns the AI model.
107
+ * Returns the specific AI model identifier.
97
108
  *
98
- * Возвращает модель ИИ.
109
+ * Возвращает конкретный идентификатор модели ИИ.
99
110
  */
100
111
  static getAiModel(): string {
101
112
  return this.config.aiModel ?? ''
102
113
  }
103
114
 
104
115
  /**
105
- * Returns the AI API key.
116
+ * Returns the secure API key for AI authentication.
106
117
  *
107
- * Возвращает API ключ ИИ.
118
+ * Возвращает безопасный API-ключ для аутентификации ИИ.
108
119
  */
109
120
  static getAiKey(): string {
110
121
  return this.config.aiKey ?? ''
111
122
  }
112
123
 
113
124
  /**
114
- * Returns the directories for AI documentation generation.
125
+ * Returns the AI configuration object.
126
+ *
127
+ * Возвращает объект конфигурации ИИ.
128
+ */
129
+ static getAiConfig(): Record<string, any> {
130
+ return this.config.aiConfig ?? {}
131
+ }
132
+
133
+ /**
134
+ * Returns the list of directories targeted for AI-driven documentation.
115
135
  *
116
- * Возвращает каталоги для генерации AI документации.
136
+ * Возвращает список директорий, предназначенных для автоматической документации через ИИ.
117
137
  */
118
138
  static getAiDocDirectory(): string[] {
119
139
  return this.config.aiDocDirectory ?? UI_AI_DOC_DIRECTORY
120
140
  }
121
141
 
122
142
  /**
123
- * Returns the Storybook path for AI documentation generation.
143
+ * Returns the export path for Storybook-compatible AI documentation.
124
144
  *
125
- * Возвращает путь Storybook для генерации AI документации.
145
+ * Возвращает путь экспорта для AI-документации, совместимой со Storybook.
126
146
  */
127
147
  static getAiDocStorybookPath(): string {
128
148
  return this.config.aiDocStorybookPath ?? UI_AI_DOC_STORYBOOK
@@ -17,16 +17,20 @@ const LIST: Record<string, (item: PropertyItemInput) => void> = {
17
17
  }
18
18
 
19
19
  /**
20
- * Class for data type conversion.<br>
21
- * Класс для преобразования типов данных.
20
+ * Static utility for semantic token transformation.
21
+ * This class orchestrates the conversion of raw property values into specialized design formats (e.g., color processing, typography synthesis, shadow normalization) by dispatching items to specific convectors based on their metadata type.
22
+ *
23
+ * Статическая утилита для семантического преобразования токенов.
24
+ * Этот класс координирует преобразование необработанных значений свойств в специализированные форматы дизайна (например, обработка цвета, синтез типографики, нормализация теней), распределяя элементы по конкретным конвертерам на основе их типа метаданных.
22
25
  */
23
26
  export class PropertiesConvector {
24
27
  /**
25
- * Basic value transformation.
28
+ * Recursively transforms property lists or individual data structures.
29
+ * Identifies the property type and applies the corresponding specialized convector if available, or continues recursive traversal for nested objects.
26
30
  *
27
- * Базовое преобразование значения.
28
- * @param properties an array that needs to be transformed/
29
- * массив, который нужно преобразовать
31
+ * Рекурсивно преобразует списки свойств или отдельные структуры данных.
32
+ * Определяет тип свойства и применяет соответствующий специализированный конвертер, если он доступен, или продолжает рекурсивный обход для вложенных объектов.
33
+ * @param properties the property cluster to be transformed / кластер свойств для преобразования
30
34
  */
31
35
  static to(properties: PropertyListOrData): void {
32
36
  forEach(properties, (item) => {
@@ -7,39 +7,36 @@ import { hasNativeDirname } from '../../functions/hasNativeDirname'
7
7
  import { UI_FILE_INDEX, UI_MODULES, UI_PROJECT_NAME } from '../../config'
8
8
 
9
9
  export type PropertiesFilePath = string | string[]
10
- export type PropertiesFileValue<T = any> = string | Record<string, T>
10
+ export type PropertiesFileValue<T = any> = string | Record<string, T> | Buffer
11
11
 
12
12
  const dirnamePath = hasNativeDirname() ? __dirname : requirePath.dirname(fileURLToPath(import.meta.url))
13
13
 
14
14
  /**
15
- * A class for working with files.
15
+ * Universal static utility for filesystem orchestration.
16
+ * This class provides a standardized interface for all IO operations within the design system, including path normalization, recursive directory traversal, synchronized file reading/writing, and metadata retrieval. It abstracts platform-specific path differences and ensures consistent data handling across the toolchain.
16
17
  *
17
- * Класс для работы с файлами.
18
+ * Универсальная статическая утилита для оркестрации файловой системы.
19
+ * Этот класс предоставляет стандартизированный интерфейс для всех операций ввода-вывода в рамках дизайн-системы, включая нормализацию путей, рекурсивный обход директорий, синхронное чтение/запись файлов и получение метаданных. Он абстрагирует различия путей в разных ОС и обеспечивает согласованную обработку данных во всей цепочке инструментов.
18
20
  */
19
21
  export class PropertiesFile {
20
22
  protected static root: string
21
23
  protected static module: boolean
22
24
 
23
25
  /**
24
- * The fs.existsSync() method is used to synchronously check if a file already
25
- * exists in the given path or not. It returns a boolean value which indicates
26
- * the presence of a file.
26
+ * Synchronously checks for the existence of a file or directory at the specified path.
27
27
  *
28
- * Метод fs.existsSync() используется для синхронной проверки наличия файла в
29
- * указанном пути. Он возвращает логическое значение, которое указывает на
30
- * наличие файла.
31
- * @param path it holds the path of the file that has to be checked /
32
- * это содержит путь к файлу, который необходимо проверить
28
+ * Синхронно проверяет существование файла или директории по указанному пути.
29
+ * @param path target filesystem path to verify / целевой путь в файловой системе для проверки
33
30
  */
34
31
  static is(path: PropertiesFilePath): boolean {
35
32
  return requireFs.existsSync(this.joinPath(path))
36
33
  }
37
34
 
38
35
  /**
39
- * Checks whether it is a directory.
36
+ * Determines if the specified path points to a directory.
40
37
  *
41
- * Проверяет, является ли это директорией.
42
- * @param path name of the element being checked/ название проверяемого элемента
38
+ * Определяет, указывает ли указанный путь на директорию.
39
+ * @param path path to the filesystem element / путь к элементу файловой системы
43
40
  */
44
41
  static isDir(path: PropertiesFilePath): boolean {
45
42
  if (this.is(path)) {
@@ -59,13 +56,10 @@ export class PropertiesFile {
59
56
  }
60
57
 
61
58
  /**
62
- * The path.joinPath() method joins all given path segments together using the
63
- * platform-specific separator as a delimiter, then normalizes the resulting path.
59
+ * Joins multiple path segments into a single normalized path string using the OS separator.
64
60
  *
65
- * Метод path.joinPath() объединяет все указанные сегменты пути с использованием
66
- * специфического для платформы разделителя в качестве разделителя,
67
- * а затем нормализует полученный путь.
68
- * @param path a sequence of path segments/ последовательность сегментов пути
61
+ * Объединяет несколько сегментов пути в одну нормализованную строку пути, используя разделитель ОС.
62
+ * @param path array or string of path segments / массив или строка сегментов пути
69
63
  */
70
64
  static joinPath(path: PropertiesFilePath): string {
71
65
  const pathArray = forEach(
@@ -344,10 +338,10 @@ export class PropertiesFile {
344
338
  }
345
339
 
346
340
  /**
347
- * Returns the contents of the path.
341
+ * Synchronously reads and parses the contents of a file (JSON or raw text).
348
342
  *
349
- * Возвращает содержимое пути.
350
- * @param path filename/ имя файла
343
+ * Синхронно читает и парсит содержимое файла (JSON или обычный текст).
344
+ * @param path path to the target file / путь к целевому файлу
351
345
  */
352
346
  static readFile<R>(path: PropertiesFilePath): R | undefined {
353
347
  if (this.is(path)) {
@@ -391,13 +385,13 @@ export class PropertiesFile {
391
385
  }
392
386
 
393
387
  /**
394
- * Writing data to a file.
388
+ * Writes data to a file at the specified location, automatically creating directories and formatting objects as JSON by default.
395
389
  *
396
- * Запись данных в файл.
397
- * @param path path to the file/ путь к файлу
398
- * @param name file name/ название файла
399
- * @param value values for storage/ значения для хранения
400
- * @param extension file extension by default is ts/ расширение файла по умолчанию - ts
390
+ * Записывает данные в файл по указанному адресу, автоматически создавая директории и форматируя объекты в JSON по умолчанию.
391
+ * @param path base directory path / путь к базовой директории
392
+ * @param name target filename (without extension if extension provided) / имя целевого файла
393
+ * @param value data to be stored / данные для хранения
394
+ * @param extension file extension (defaults to 'json') / расширение файла (по умолчанию 'json')
401
395
  */
402
396
  static write<T extends PropertiesFileValue>(
403
397
  path: PropertiesFilePath,
@@ -417,16 +411,18 @@ export class PropertiesFile {
417
411
  * Записывает по выбранному пути.
418
412
  * @param path path to the file/ путь к файлу
419
413
  * @param value values for storage/ значения для хранения
414
+ * @param transform whether to transform the value/ преобразовывать ли значение
420
415
  */
421
416
  static writeByPath<T extends PropertiesFileValue>(
422
417
  path: PropertiesFilePath,
423
- value: T
418
+ value: T,
419
+ transform: boolean = true
424
420
  ): void {
425
421
  this.createDir(path)
426
422
 
427
423
  requireFs.writeFileSync(
428
424
  this.joinPath(path),
429
- typeof value === 'object' ? JSON.stringify(value) : value
425
+ transform && typeof value === 'object' ? JSON.stringify(value, undefined, 2) : value as any
430
426
  )
431
427
  }
432
428
 
@@ -20,9 +20,11 @@ import {
20
20
  } from '../../types/propertyTypes'
21
21
 
22
22
  /**
23
- * Class for working with external files, which adds them to the current list of properties.
23
+ * Resolver for external property references.
24
+ * This class orchestrates the inclusion of external design tokens into the primary property tree. It identifies file references, resolves paths (including nested directory imports and specific object path deep-linking via hashes), and merges the external data into the current configuration cluster.
24
25
  *
25
- * Класс для работы с внешними файлами, который подключает их к текущему списку свойств.
26
+ * Резолвер внешних ссылок на свойства.
27
+ * Этот класс координирует включение внешних токенов дизайна в основное дерево свойств. Он идентифицирует ссылки на файлы, разрешает пути (включая импорт вложенных директорий и глубокие ссылки на конкретные объекты через хеш) и объединяет внешние данные с текущим кластером конфигурации.
26
28
  */
27
29
  export class PropertiesImport {
28
30
  /**
@@ -38,12 +40,13 @@ export class PropertiesImport {
38
40
  }
39
41
 
40
42
  /**
41
- * Method that adds external files to the current property.
43
+ * Resolves and merges external file references within a property cluster.
44
+ * Iterates through the properties, looks for items of type 'file', and recursively imports their content, supporting deep-linking (e.g., 'file.json#path.to.data').
42
45
  *
43
- * Метод подключает внешние файлы к текущему свойству.
44
- * @param properties An array that needs to be transformed/
45
- * Массив, который нужно преобразовать
46
- * @param root path to the directory/ путь к директории
46
+ * Разрешает и объединяет ссылки на внешние файлы внутри кластера свойств.
47
+ * Итерирует по свойствам, ищет элементы типа 'file' и рекурсивно импортирует их содержимое, поддерживая глубокие ссылки (например, 'file.json#path.to.data').
48
+ * @param properties the property list to process / список свойств для обработки
49
+ * @param root the base path segments for resolution / базовые сегменты пути для разрешения
47
50
  */
48
51
  to(
49
52
  properties = this.properties,
@@ -31,9 +31,11 @@ const SUPPORT_NAME = [
31
31
  ]
32
32
 
33
33
  /**
34
- * Class for working with a list of all properties.
34
+ * Coordinator for design property collections.
35
+ * This class provides a high-level API for traversing, searching, and extracting metadata from complex design token trees. It manages state related to design focusing (filtering view to a specific design set), converts complex path strings into normalized keys, and facilitates deep recursive iteration for token processing engines.
35
36
  *
36
- * Класс для работы со списком всех свойств.
37
+ * Координатор коллекций свойств дизайна.
38
+ * Этот класс предоставляет высокоуровневый API для обхода, поиска и извлечения метаданных из сложных деревьев токенов дизайна. Он управляет состоянием, связанным с фокусировкой дизайна (фильтрация представления для конкретного набора дизайнов), преобразует сложные строки путей в нормализованные ключи и упрощает глубокую рекурсивную итерацию для движков обработки токенов.
37
39
  */
38
40
  export class PropertiesItems {
39
41
  private focusDesign?: string
@@ -65,9 +67,11 @@ export class PropertiesItems {
65
67
  }
66
68
 
67
69
  /**
68
- * Getting full structure property.
70
+ * Retrieves the current property structure.
71
+ * If a focus design is set, returns only the subset corresponding to that design and common constructor data; otherwise, returns the full collection.
69
72
  *
70
- * Получение полной структуры свойства.
73
+ * Получает текущую структуру свойств.
74
+ * Если установлен фокус на дизайн, возвращает только подмножество, соответствующее этому дизайну и общим данным конструктора; в противном случае возвращает полную коллекцию.
71
75
  */
72
76
  get(): PropertyList {
73
77
  if (this.focusDesign) {
@@ -114,10 +118,12 @@ export class PropertiesItems {
114
118
  }
115
119
 
116
120
  /**
117
- * Returns the full information about the element by its link.
121
+ * Resolves comprehensive metadata for a property element by its dotted index.
122
+ * Decodes the index, traverses the tree to find the target node, and synthesizes a detailed info object including parent hierarchy, name normalization, and raw values.
118
123
  *
119
- * Возвращает полную информацию об элементе по его ссылке.
120
- * @param index index for splitting/ индекс для разделения
124
+ * Разрешает полные метаданные элемента свойства по его индексу через точку.
125
+ * Декодирует индекс, обходит дерево для поиска целевого узла и синтезирует подробный объект информации, включая иерархию родителей, нормализацию имен и необработанные значения.
126
+ * @param index index for splitting / индекс для разделения
121
127
  */
122
128
  getInfo(index: string): PropertyItemsItem | undefined {
123
129
  const keys = this.getKeys(index)
@@ -376,12 +382,13 @@ export class PropertiesItems {
376
382
  }
377
383
 
378
384
  /**
379
- * Recursively applies a custom function to each element of the property.
385
+ * Performs a deep recursive traversal of the property tree.
386
+ * Executes a callback for every node discovered. If a specific property node is provided, the traversal is restricted to its children; otherwise, the entire tree is visited.
380
387
  *
381
- * Рекурсивно применяет пользовательскую функцию к каждому элементу свойства.
382
- * @param callback the callback function is executed for each element/
383
- * выполняется функция обратного вызова (callback) для каждого элемента
384
- * @param property
388
+ * Выполняет глубокий рекурсивный обход дерева свойств.
389
+ * Выполняет callback для каждого обнаруженного узла. Если предоставлен конкретный узел свойства, обход ограничивается его дочерними элементами; в противном случае посещается все дерево.
390
+ * @param callback the callback function to execute for each element / функция обратного вызова для каждого элемента
391
+ * @param property optional start node for traversal / опциональный начальный узел для обхода
385
392
  */
386
393
  each<T>(
387
394
  callback: PropertyItemsCallback<T>,
@@ -8,16 +8,20 @@ import { PropertiesTypes } from './PropertiesTypes'
8
8
  import { type PropertyItem } from '../../types/propertyTypes'
9
9
 
10
10
  /**
11
- * Key with all special keys for token processing.
11
+ * Parser and transformer for property key semantics.
12
+ * This static utility class handles the identification of special system keys (like metadata or internal references) and orchestrates the transformation of raw key names into normalized, context-aware tokens (e.g., prepending media types or converting to camelCase).
12
13
  *
13
- * Ключ со всеми специальными ключами для обработки токенов.
14
+ * Парсер и трансформер семантики ключей свойств.
15
+ * Этот статический вспомогательный класс обрабатывает идентификацию специальных системных ключей (таких как метаданные или внутренние ссылки) и координирует преобразование необработанных имен ключей в нормализованные токены с учетом контекста (например, добавление типов медиа или преобразование в camelCase).
14
16
  */
15
17
  export class PropertiesKeys {
16
18
  /**
17
- * Checks if the variable is a special value.
19
+ * Identifies if a key is a protected system metadata key or an internal reference.
20
+ * Special keys include 'value', 'type', 'description', and any key starting with an underscore (internal engine states).
18
21
  *
19
- * Проверяет, является ли переменная специальным значением.
20
- * @param key key name/ название ключа
22
+ * Определяет, является ли ключ защищенным системным ключом метаданных или внутренней ссылкой.
23
+ * Специальные ключи включают 'value', 'type', 'description' и любой ключ, начинающийся с подчеркивания (внутренние состояния движка).
24
+ * @param key the key name to verify / название ключа для проверки
21
25
  */
22
26
  static isSpecialKey(key: string | number): key is keyof PropertyItem {
23
27
  return typeof key === 'string' && (
@@ -48,11 +52,13 @@ export class PropertiesKeys {
48
52
  }
49
53
 
50
54
  /**
51
- * Returns the property name, discarding its prefix.
55
+ * Normalizes a raw key name by removing metadata prefixes and applying casing rules.
56
+ * Strips internal type symbols and leading pipes, then optionally converts the result to camelCase (unless the name is a path separator).
52
57
  *
53
- * Возвращает имя свойства, отбрасывая его префикс.
54
- * @param name key name/ название ключа
55
- * @param camelCase to convert case/ преобразуйте этот текст в верхний регистр
58
+ * Нормализует необработанное имя ключа, удаляя префиксы метаданных и применяя правила регистра.
59
+ * Очищает внутренние символы типов и ведущие вертикальные черты, затем опционально преобразует результат в camelCase (если имя не является разделителем пути).
60
+ * @param name the raw key name / необработанное имя ключа
61
+ * @param camelCase whether to apply camelCase transformation / нужно ли применять преобразование в camelCase
56
62
  */
57
63
  static getName(name: string, camelCase = true): string {
58
64
  const newName = name
@@ -19,9 +19,11 @@ import type {
19
19
  const DIR_NAME = 'main'
20
20
 
21
21
  /**
22
- * A class for transforming global tokens.
22
+ * Orchestrator for global design token transformation.
23
+ * This class serves as the primary engine for loading, validating, and normalizing "main" tokens across all supported designs. It coordinates a multi-stage pipeline—including semantic conversion, reference import, and structural wrapping—to synthesize a unified property tree ready for consumption by external builders.
23
24
  *
24
- * Класс для преобразования глобальных токенов.
25
+ * Оркестратор глобальной трансформации токенов дизайна.
26
+ * Этот класс служит основным движком для загрузки, валидации и нормализации «основных» (main) токенов во всех поддерживаемых дизайнах. Он координирует многоэтапный конвейер — включая семантическую конвертацию, импорт ссылок и структурную обертку — для синтеза унифицированного дерева свойств, готового к использованию внешними строителями.
25
27
  */
26
28
  export class PropertiesMain {
27
29
  /**
@@ -34,9 +36,11 @@ export class PropertiesMain {
34
36
  }
35
37
 
36
38
  /**
37
- * Returns all main tokens.
39
+ * Executes the full transformation pipeline for all main design tokens.
40
+ * Discovers token files via the path manager, then sequentially applies reading, conversion, standardization, link resolution, and structural wrapping for every design entry.
38
41
  *
39
- * Возвращает все основные токены.
42
+ * Выполняет полный конвейер трансформации для всех основных токенов дизайна.
43
+ * Обнаруживает файлы токенов через менеджер путей, затем последовательно применяет чтение, конвертацию, стандартизацию, разрешение ссылок и структурную обертку для каждой записи дизайна.
40
44
  */
41
45
  get(): PropertyList {
42
46
  return this.path.toAll(DIR_NAME, (
@@ -66,10 +70,12 @@ export class PropertiesMain {
66
70
  }
67
71
 
68
72
  /**
69
- * We get the main property taking into account the change of settings.
73
+ * Synchronizes global tokens with a provided settings cluster.
74
+ * Retrieves the full set of main tokens and deeply merges internal state flags from the settings list into the corresponding nodes of the global tree.
70
75
  *
71
- * Получаем главное свойство с учетом изменения настроек.
72
- * @param list list of settings/ список настроек
76
+ * Синхронизирует глобальные токены с предоставленным кластером настроек.
77
+ * Получает полный набор основных токенов и глубоко объединяет флаги внутреннего состояния из списка настроек в соответствующие узлы глобального дерева.
78
+ * @param list the settings cluster to apply / кластер настроек для применения
73
79
  */
74
80
  getBySettings(list: PropertyList): PropertyList {
75
81
  const data = this.get()