@matreshka/bff 0.9.0

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 (275) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +35 -0
  3. package/dist/components/actions/server-action.d.ts +30 -0
  4. package/dist/components/actions/server-action.js +23 -0
  5. package/dist/components/aliases/button.d.ts +17 -0
  6. package/dist/components/aliases/button.js +54 -0
  7. package/dist/components/aliases/column.d.ts +11 -0
  8. package/dist/components/aliases/column.js +31 -0
  9. package/dist/components/aliases/row.d.ts +11 -0
  10. package/dist/components/aliases/row.js +31 -0
  11. package/dist/components/aliases/surface.d.ts +11 -0
  12. package/dist/components/aliases/surface.js +30 -0
  13. package/dist/components/app.d.ts +5 -0
  14. package/dist/components/app.js +12 -0
  15. package/dist/components/board.d.ts +58 -0
  16. package/dist/components/board.js +152 -0
  17. package/dist/components/boot.d.ts +2 -0
  18. package/dist/components/boot.js +39 -0
  19. package/dist/components/camera.d.ts +77 -0
  20. package/dist/components/camera.js +116 -0
  21. package/dist/components/charts/bar-chart.d.ts +14 -0
  22. package/dist/components/charts/bar-chart.js +27 -0
  23. package/dist/components/charts/chart.d.ts +69 -0
  24. package/dist/components/charts/chart.js +42 -0
  25. package/dist/components/charts/doughnut-chart.d.ts +14 -0
  26. package/dist/components/charts/doughnut-chart.js +27 -0
  27. package/dist/components/charts/line-chart.d.ts +14 -0
  28. package/dist/components/charts/line-chart.js +27 -0
  29. package/dist/components/charts/pie-chart.d.ts +14 -0
  30. package/dist/components/charts/pie-chart.js +27 -0
  31. package/dist/components/charts/polar-area-chart.d.ts +14 -0
  32. package/dist/components/charts/polar-area-chart.js +27 -0
  33. package/dist/components/charts/radar-chart.d.ts +14 -0
  34. package/dist/components/charts/radar-chart.js +27 -0
  35. package/dist/components/component.d.ts +159 -0
  36. package/dist/components/component.js +380 -0
  37. package/dist/components/container.d.ts +48 -0
  38. package/dist/components/container.js +80 -0
  39. package/dist/components/dialog.d.ts +83 -0
  40. package/dist/components/dialog.js +120 -0
  41. package/dist/components/entry-component.d.ts +34 -0
  42. package/dist/components/entry-component.js +74 -0
  43. package/dist/components/enum/password-input-kind.d.ts +1 -0
  44. package/dist/components/enum/password-input-kind.js +5 -0
  45. package/dist/components/enum/popover-position-area.d.ts +1 -0
  46. package/dist/components/enum/popover-position-area.js +5 -0
  47. package/dist/components/enum/text-input-kind.d.ts +1 -0
  48. package/dist/components/enum/text-input-kind.js +5 -0
  49. package/dist/components/enum/textarea-resize.d.ts +1 -0
  50. package/dist/components/enum/textarea-resize.js +5 -0
  51. package/dist/components/file-upload-area.d.ts +79 -0
  52. package/dist/components/file-upload-area.js +138 -0
  53. package/dist/components/for-each.d.ts +188 -0
  54. package/dist/components/for-each.js +362 -0
  55. package/dist/components/form.d.ts +62 -0
  56. package/dist/components/form.js +92 -0
  57. package/dist/components/grid.d.ts +80 -0
  58. package/dist/components/grid.js +79 -0
  59. package/dist/components/index.d.ts +55 -0
  60. package/dist/components/index.js +76 -0
  61. package/dist/components/inputs/input-component.d.ts +37 -0
  62. package/dist/components/inputs/input-component.js +30 -0
  63. package/dist/components/inputs/number-input.d.ts +45 -0
  64. package/dist/components/inputs/number-input.js +43 -0
  65. package/dist/components/inputs/password-input.d.ts +28 -0
  66. package/dist/components/inputs/password-input.js +42 -0
  67. package/dist/components/inputs/text-editor.d.ts +91 -0
  68. package/dist/components/inputs/text-editor.js +282 -0
  69. package/dist/components/inputs/text-input.d.ts +48 -0
  70. package/dist/components/inputs/text-input.js +40 -0
  71. package/dist/components/inputs/textarea.d.ts +36 -0
  72. package/dist/components/inputs/textarea.js +42 -0
  73. package/dist/components/item-list/flatten-nested-items.d.ts +11 -0
  74. package/dist/components/item-list/flatten-nested-items.js +100 -0
  75. package/dist/components/item-list/index.d.ts +5 -0
  76. package/dist/components/item-list/index.js +21 -0
  77. package/dist/components/item-list/item-list-host.d.ts +10 -0
  78. package/dist/components/item-list/item-list-host.js +2 -0
  79. package/dist/components/item-list/item-list.d.ts +68 -0
  80. package/dist/components/item-list/item-list.js +206 -0
  81. package/dist/components/item-list/list-from-ref-context.d.ts +11 -0
  82. package/dist/components/item-list/list-from-ref-context.js +27 -0
  83. package/dist/components/item-list/nested-items-host-support.d.ts +36 -0
  84. package/dist/components/item-list/nested-items-host-support.js +109 -0
  85. package/dist/components/item-list/types.d.ts +40 -0
  86. package/dist/components/item-list/types.js +13 -0
  87. package/dist/components/line.d.ts +43 -0
  88. package/dist/components/line.js +35 -0
  89. package/dist/components/map.d.ts +83 -0
  90. package/dist/components/map.js +146 -0
  91. package/dist/components/outputs/currency.d.ts +63 -0
  92. package/dist/components/outputs/currency.js +42 -0
  93. package/dist/components/outputs/datetime.d.ts +69 -0
  94. package/dist/components/outputs/datetime.js +49 -0
  95. package/dist/components/outputs/icon.d.ts +43 -0
  96. package/dist/components/outputs/icon.js +38 -0
  97. package/dist/components/outputs/iframe.d.ts +48 -0
  98. package/dist/components/outputs/iframe.js +44 -0
  99. package/dist/components/outputs/image.d.ts +73 -0
  100. package/dist/components/outputs/image.js +63 -0
  101. package/dist/components/outputs/number.d.ts +39 -0
  102. package/dist/components/outputs/number.js +47 -0
  103. package/dist/components/outputs/output-component.d.ts +58 -0
  104. package/dist/components/outputs/output-component.js +50 -0
  105. package/dist/components/outputs/progress-bar.d.ts +33 -0
  106. package/dist/components/outputs/progress-bar.js +42 -0
  107. package/dist/components/outputs/progress-spinner.d.ts +37 -0
  108. package/dist/components/outputs/progress-spinner.js +43 -0
  109. package/dist/components/outputs/qr-code.d.ts +28 -0
  110. package/dist/components/outputs/qr-code.js +40 -0
  111. package/dist/components/outputs/text.d.ts +57 -0
  112. package/dist/components/outputs/text.js +78 -0
  113. package/dist/components/outputs/vector.d.ts +47 -0
  114. package/dist/components/outputs/vector.js +53 -0
  115. package/dist/components/page.d.ts +96 -0
  116. package/dist/components/page.js +127 -0
  117. package/dist/components/popover.d.ts +63 -0
  118. package/dist/components/popover.js +96 -0
  119. package/dist/components/stack.d.ts +158 -0
  120. package/dist/components/stack.js +146 -0
  121. package/dist/components/types/component-sequence.d.ts +3 -0
  122. package/dist/components/types/component-sequence.js +2 -0
  123. package/dist/components/types/container-overlay.d.ts +3 -0
  124. package/dist/components/types/container-overlay.js +2 -0
  125. package/dist/components/utils/component-factory-shared.d.ts +4 -0
  126. package/dist/components/utils/component-factory-shared.js +12 -0
  127. package/dist/core/actions/action.d.ts +35 -0
  128. package/dist/core/actions/action.js +45 -0
  129. package/dist/core/actions/animate-component.d.ts +58 -0
  130. package/dist/core/actions/animate-component.js +57 -0
  131. package/dist/core/actions/local-action.d.ts +8 -0
  132. package/dist/core/actions/local-action.js +12 -0
  133. package/dist/core/actions/set-context-value.d.ts +18 -0
  134. package/dist/core/actions/set-context-value.js +32 -0
  135. package/dist/core/actions/set-context-values.d.ts +34 -0
  136. package/dist/core/actions/set-context-values.js +30 -0
  137. package/dist/core/actions/toggle-context-value.d.ts +21 -0
  138. package/dist/core/actions/toggle-context-value.js +30 -0
  139. package/dist/core/actions/write-text-to-clipboard.d.ts +30 -0
  140. package/dist/core/actions/write-text-to-clipboard.js +44 -0
  141. package/dist/core/boot.d.ts +2 -0
  142. package/dist/core/boot.js +8 -0
  143. package/dist/core/client-context.d.ts +7 -0
  144. package/dist/core/client-context.js +20 -0
  145. package/dist/core/client.d.ts +133 -0
  146. package/dist/core/client.js +292 -0
  147. package/dist/core/conditions/condition-group.d.ts +14 -0
  148. package/dist/core/conditions/condition-group.js +30 -0
  149. package/dist/core/conditions/condition-operand.d.ts +27 -0
  150. package/dist/core/conditions/condition-operand.js +15 -0
  151. package/dist/core/conditions/condition.d.ts +27 -0
  152. package/dist/core/conditions/condition.js +35 -0
  153. package/dist/core/conditions/context-array-includes.d.ts +32 -0
  154. package/dist/core/conditions/context-array-includes.js +52 -0
  155. package/dist/core/conditions/context-array-length.d.ts +86 -0
  156. package/dist/core/conditions/context-array-length.js +155 -0
  157. package/dist/core/conditions/context-value-defined.d.ts +12 -0
  158. package/dist/core/conditions/context-value-defined.js +21 -0
  159. package/dist/core/conditions/context-value-equal.d.ts +14 -0
  160. package/dist/core/conditions/context-value-equal.js +26 -0
  161. package/dist/core/conditions/context-value-in.d.ts +17 -0
  162. package/dist/core/conditions/context-value-in.js +26 -0
  163. package/dist/core/conditions/context-value-not-equal.d.ts +14 -0
  164. package/dist/core/conditions/context-value-not-equal.js +26 -0
  165. package/dist/core/conditions/context-value-undefined.d.ts +12 -0
  166. package/dist/core/conditions/context-value-undefined.js +21 -0
  167. package/dist/core/conditions/desktop-device.d.ts +11 -0
  168. package/dist/core/conditions/desktop-device.js +21 -0
  169. package/dist/core/conditions/groups.d.ts +71 -0
  170. package/dist/core/conditions/groups.js +74 -0
  171. package/dist/core/conditions/index.d.ts +17 -0
  172. package/dist/core/conditions/index.js +33 -0
  173. package/dist/core/conditions/mobile-device.d.ts +11 -0
  174. package/dist/core/conditions/mobile-device.js +21 -0
  175. package/dist/core/conditions/not-desktop-device.d.ts +11 -0
  176. package/dist/core/conditions/not-desktop-device.js +21 -0
  177. package/dist/core/conditions/not-mobile-device.d.ts +11 -0
  178. package/dist/core/conditions/not-mobile-device.js +21 -0
  179. package/dist/core/conditions/not-tablet-device.d.ts +11 -0
  180. package/dist/core/conditions/not-tablet-device.js +21 -0
  181. package/dist/core/conditions/tablet-device.d.ts +11 -0
  182. package/dist/core/conditions/tablet-device.js +21 -0
  183. package/dist/core/context/context-ref.d.ts +48 -0
  184. package/dist/core/context/context-ref.js +58 -0
  185. package/dist/core/context/context.d.ts +121 -0
  186. package/dist/core/context/context.js +353 -0
  187. package/dist/core/entry-context.d.ts +14 -0
  188. package/dist/core/entry-context.js +31 -0
  189. package/dist/core/gateway-connection.d.ts +29 -0
  190. package/dist/core/gateway-connection.js +146 -0
  191. package/dist/core/index.d.ts +30 -0
  192. package/dist/core/index.js +46 -0
  193. package/dist/core/matreshka.d.ts +61 -0
  194. package/dist/core/matreshka.js +186 -0
  195. package/dist/core/router.d.ts +38 -0
  196. package/dist/core/router.js +116 -0
  197. package/dist/core/types/client-settings.d.ts +31 -0
  198. package/dist/core/types/client-settings.js +2 -0
  199. package/dist/core/types/component-instance.d.ts +25 -0
  200. package/dist/core/types/component-instance.js +42 -0
  201. package/dist/core/types/component-tree-node.d.ts +11 -0
  202. package/dist/core/types/component-tree-node.js +18 -0
  203. package/dist/core/types/componentable.d.ts +21 -0
  204. package/dist/core/types/componentable.js +2 -0
  205. package/dist/core/types/context-ref-primitive-value.d.ts +5 -0
  206. package/dist/core/types/context-ref-primitive-value.js +2 -0
  207. package/dist/core/types/message.d.ts +15 -0
  208. package/dist/core/types/message.js +2 -0
  209. package/dist/core/types/mixed-with-callbacks-array.d.ts +9 -0
  210. package/dist/core/types/mixed-with-callbacks-array.js +2 -0
  211. package/dist/core/types/native-picker-context-ref.d.ts +7 -0
  212. package/dist/core/types/native-picker-context-ref.js +2 -0
  213. package/dist/core/types/pageable.d.ts +15 -0
  214. package/dist/core/types/pageable.js +2 -0
  215. package/dist/core/types/standalone-component.d.ts +9 -0
  216. package/dist/core/types/standalone-component.js +2 -0
  217. package/dist/core/types/status-code.d.ts +319 -0
  218. package/dist/core/types/status-code.js +322 -0
  219. package/dist/core/utils/calculate-components.d.ts +13 -0
  220. package/dist/core/utils/calculate-components.js +40 -0
  221. package/dist/core/utils/color-token-id.d.ts +11 -0
  222. package/dist/core/utils/color-token-id.js +24 -0
  223. package/dist/core/utils/deep-pick.d.ts +2 -0
  224. package/dist/core/utils/deep-pick.js +54 -0
  225. package/dist/core/utils/hex-to-hsl.d.ts +14 -0
  226. package/dist/core/utils/hex-to-hsl.js +49 -0
  227. package/dist/core/utils/incoming-message-observer.d.ts +9 -0
  228. package/dist/core/utils/incoming-message-observer.js +23 -0
  229. package/dist/core/utils/merge-deep.d.ts +8 -0
  230. package/dist/core/utils/merge-deep.js +39 -0
  231. package/dist/core/utils/objects-diff.d.ts +13 -0
  232. package/dist/core/utils/objects-diff.js +56 -0
  233. package/dist/core/utils/parse-context-path.d.ts +4 -0
  234. package/dist/core/utils/parse-context-path.js +16 -0
  235. package/dist/core/utils/replace-context-keys.d.ts +12 -0
  236. package/dist/core/utils/replace-context-keys.js +90 -0
  237. package/dist/core/utils/serialize-component-tree.d.ts +9 -0
  238. package/dist/core/utils/serialize-component-tree.js +24 -0
  239. package/dist/core/utils/set-object-property.d.ts +2 -0
  240. package/dist/core/utils/set-object-property.js +29 -0
  241. package/dist/core/utils/track-created-instances.d.ts +10 -0
  242. package/dist/core/utils/track-created-instances.js +18 -0
  243. package/dist/core/version.d.ts +1 -0
  244. package/dist/core/version.js +21 -0
  245. package/dist/index.d.ts +3 -0
  246. package/dist/index.js +19 -0
  247. package/dist/platforms/android-platform.d.ts +6 -0
  248. package/dist/platforms/android-platform.js +10 -0
  249. package/dist/platforms/browser-platform.d.ts +79 -0
  250. package/dist/platforms/browser-platform.js +143 -0
  251. package/dist/platforms/client-platform.d.ts +6 -0
  252. package/dist/platforms/client-platform.js +10 -0
  253. package/dist/platforms/index.d.ts +12 -0
  254. package/dist/platforms/index.js +28 -0
  255. package/dist/platforms/ios-platform.d.ts +6 -0
  256. package/dist/platforms/ios-platform.js +10 -0
  257. package/dist/platforms/max-mini-app-platform.d.ts +45 -0
  258. package/dist/platforms/max-mini-app-platform.js +87 -0
  259. package/dist/platforms/mobile-platform.d.ts +117 -0
  260. package/dist/platforms/mobile-platform.js +316 -0
  261. package/dist/platforms/platform.d.ts +109 -0
  262. package/dist/platforms/platform.js +224 -0
  263. package/dist/platforms/pwa-platform.d.ts +6 -0
  264. package/dist/platforms/pwa-platform.js +10 -0
  265. package/dist/platforms/server-platform.d.ts +6 -0
  266. package/dist/platforms/server-platform.js +10 -0
  267. package/dist/platforms/telegram-mini-app-platform.d.ts +87 -0
  268. package/dist/platforms/telegram-mini-app-platform.js +166 -0
  269. package/dist/platforms/utils/client-platform.d.ts +4 -0
  270. package/dist/platforms/utils/client-platform.js +38 -0
  271. package/dist/platforms/utils/mobile-ble-services.d.ts +3 -0
  272. package/dist/platforms/utils/mobile-ble-services.js +31 -0
  273. package/dist/platforms/web-platform.d.ts +9 -0
  274. package/dist/platforms/web-platform.js +13 -0
  275. package/package.json +109 -0
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.objectsDiff = void 0;
4
+ /**
5
+ * Вычисляет разницу между двумя объектами и возвращает изменённые поля.
6
+ *
7
+ * Поддерживает вложенные объекты. Если изменились все поля вложенного объекта —
8
+ * возвращает его целиком. В противном случае возвращает только изменённые поля.
9
+ *
10
+ * @param oldObj Исходный объект.
11
+ * @param newObj Новый объект.
12
+ * @param prefix Префикс для формирования ключей (используется при рекурсии).
13
+ * @param diff Промежуточное хранилище отличий (используется при рекурсии).
14
+ * @returns Объект с отличиями, где ключ — путь к полю, значение — новое значение.
15
+ */
16
+ const objectsDiff = (oldObj, newObj, prefix = "", diff = {}) => {
17
+ const oldObjectsKeys = Object.keys(oldObj);
18
+ const newObjectsKeys = Object.keys(newObj);
19
+ new Set(oldObjectsKeys.concat(newObjectsKeys)).forEach((key) => {
20
+ // Перебор всех ключей
21
+ if (typeof oldObj[key] === "object" &&
22
+ typeof newObj[key] === "object" &&
23
+ oldObj[key] !== null &&
24
+ newObj[key] !== null) {
25
+ // Проверка на массивы - если это массивы, сравниваем их по ссылке
26
+ if (Array.isArray(oldObj[key]) || Array.isArray(newObj[key])) {
27
+ // Если один из них массив, а другой нет, или это разные ссылки - считаем измененным
28
+ if (Array.isArray(oldObj[key]) !== Array.isArray(newObj[key]) ||
29
+ oldObj[key] !== newObj[key]) {
30
+ diff[prefix + key] = newObj[key];
31
+ }
32
+ }
33
+ else {
34
+ // если они оба объекты, могли измениться поля внутри
35
+ const nestedDiff = (0, exports.objectsDiff)(oldObj[key], newObj[key], prefix + key + ".");
36
+ if (Object.keys(nestedDiff).length) {
37
+ // Важно понять тип полей, которые изменились
38
+ if (Object.keys(nestedDiff).length >=
39
+ Math.max(Object.keys(oldObj[key]).length, Object.keys(newObj[key]).length) /
40
+ 2) {
41
+ // Изменилось больше половины свойств объекта (можно менять условия), тогда меняем сущность целиком для экономии трафика
42
+ diff[prefix + key] = newObj[key];
43
+ }
44
+ else {
45
+ diff = { ...diff, ...nestedDiff };
46
+ }
47
+ }
48
+ }
49
+ }
50
+ else if (oldObj[key] !== newObj[key]) {
51
+ diff[prefix + key] = newObj[key];
52
+ }
53
+ });
54
+ return diff;
55
+ };
56
+ exports.objectsDiff = objectsDiff;
@@ -0,0 +1,4 @@
1
+ export declare function parseContextPath(path: string): {
2
+ contextId: string;
3
+ key: string;
4
+ };
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseContextPath = parseContextPath;
4
+ function parseContextPath(path) {
5
+ const firstDotIndex = path.indexOf(".");
6
+ if (firstDotIndex === -1) {
7
+ return {
8
+ contextId: path,
9
+ key: "",
10
+ };
11
+ }
12
+ return {
13
+ contextId: path.slice(0, firstDotIndex),
14
+ key: path.slice(firstDotIndex + 1),
15
+ };
16
+ }
@@ -0,0 +1,12 @@
1
+ import { Context } from "../context/context";
2
+ /**
3
+ * Заменяет плейсхолдеры вида `{ключ}` в строке значениями из объекта контекста.
4
+ *
5
+ * Поддерживает значения по умолчанию через `=` внутри плейсхолдера, например: `{name=Гость}`.
6
+ * Рекурсивно обрабатывает случаи, когда после замены появляются новые плейсхолдеры.
7
+ *
8
+ * @param str Строка с плейсхолдерами.
9
+ * @param resolveContext Поиск контекста по id.
10
+ * @returns Строка с заменёнными плейсхолдерами.
11
+ */
12
+ export declare function replaceContextKeys(str: string, resolveContext: (contextId: string) => Context<any> | undefined): string;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.replaceContextKeys = replaceContextKeys;
4
+ const fetch_from_object_1 = require("@matreshka/shared/utils/fetch-from-object");
5
+ const parse_context_path_1 = require("./parse-context-path");
6
+ /**
7
+ * Заменяет плейсхолдеры вида `{ключ}` в строке значениями из объекта контекста.
8
+ *
9
+ * Поддерживает значения по умолчанию через `=` внутри плейсхолдера, например: `{name=Гость}`.
10
+ * Рекурсивно обрабатывает случаи, когда после замены появляются новые плейсхолдеры.
11
+ *
12
+ * @param str Строка с плейсхолдерами.
13
+ * @param resolveContext Поиск контекста по id.
14
+ * @returns Строка с заменёнными плейсхолдерами.
15
+ */
16
+ function replaceContextKeys(str, resolveContext) {
17
+ const contextKeys = findContextKeys(str);
18
+ contextKeys.forEach((rule) => {
19
+ const parts = rule.split("="); // Может быть значение по умолчанию, например {name=Иван}
20
+ const path = parts[0];
21
+ const defaultValue = parts[1] ?? "";
22
+ const pathInfo = (0, parse_context_path_1.parseContextPath)(path);
23
+ const context = resolveContext(pathInfo.contextId);
24
+ if (!context) {
25
+ throw new Error(`Context ${pathInfo.contextId} not found`);
26
+ }
27
+ if (!context.inited()) {
28
+ throw new Error(`Context ${pathInfo.contextId} not initialized`);
29
+ }
30
+ const value = (0, fetch_from_object_1.fetchFromObject)(context.data$.getValue(), pathInfo.key);
31
+ str = replaceAll(str, `@{${path}}`, value ?? defaultValue);
32
+ });
33
+ const restContextKeys = findContextKeys(str);
34
+ if (restContextKeys.length) {
35
+ // После замены появились новые замены
36
+ return replaceContextKeys(str, resolveContext);
37
+ }
38
+ return str;
39
+ }
40
+ /**
41
+ * Находит все плейсхолдеры вида `@{ключ}` в строке, исключая уже обработанные.
42
+ *
43
+ * Плейсхолдеры с подстрокой `%%%` игнорируются, чтобы избежать повторной обработки.
44
+ *
45
+ * @param str Строка для анализа.
46
+ * @returns Массив уникальных ключей, найденных в строке.
47
+ */
48
+ function findContextKeys(str) {
49
+ const result = new Set();
50
+ let start_pos, end_pos;
51
+ do {
52
+ end_pos = str.indexOf("}");
53
+ if (end_pos !== -1) {
54
+ start_pos = str.substring(0, end_pos).lastIndexOf("{");
55
+ if (start_pos !== -1) {
56
+ const contextKey = str.substring(start_pos + 1, end_pos);
57
+ if (contextKey.indexOf("%%%") === -1) {
58
+ result.add(contextKey);
59
+ str = replaceAll(str, `{${contextKey}}`, `%%%`);
60
+ }
61
+ else {
62
+ start_pos = -1;
63
+ }
64
+ }
65
+ }
66
+ } while (start_pos !== -1 && end_pos !== -1);
67
+ return [...result];
68
+ }
69
+ /**
70
+ * Заменяет все вхождения подстроки в строке на заданное значение.
71
+ *
72
+ * Использует регулярное выражение с экранированием.
73
+ *
74
+ * @param str Исходная строка.
75
+ * @param find Подстрока для поиска.
76
+ * @param replace Подстрока для замены.
77
+ * @returns Строка с произведённой заменой.
78
+ */
79
+ function replaceAll(str, find, replace) {
80
+ return str.replace(new RegExp(escapeRegExp(find), "g"), replace);
81
+ }
82
+ /**
83
+ * Экранирует специальные символы в строке для безопасного использования в RegExp.
84
+ *
85
+ * @param string Строка, подготавливаемая к использованию в регулярном выражении.
86
+ * @returns Экранированная строка.
87
+ */
88
+ function escapeRegExp(string) {
89
+ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
90
+ }
@@ -0,0 +1,9 @@
1
+ import type { Overlay as SharedOverlay } from "@matreshka/shared/types/container-overlay";
2
+ import type { ServerComponentConfig } from "@matreshka/shared/types/server-component-config";
3
+ import type { Overlay } from "../../components/types/container-overlay";
4
+ import { type ComponentTreeNode } from "../types/component-tree-node";
5
+ export type SerializedComponentPayload = ServerComponentConfig;
6
+ export declare function serializeComponentList(components: readonly ComponentTreeNode[]): SerializedComponentPayload[];
7
+ export declare function serializeOverlays(overlays: readonly Overlay[]): SharedOverlay<ServerComponentConfig>[];
8
+ export declare function serializeForEachSlot(slot: ComponentTreeNode | ComponentTreeNode[]): SerializedComponentPayload | SerializedComponentPayload[];
9
+ export declare function serializeForEachSlots(slots: (ComponentTreeNode | ComponentTreeNode[])[]): Array<SerializedComponentPayload | SerializedComponentPayload[]>;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.serializeComponentList = serializeComponentList;
4
+ exports.serializeOverlays = serializeOverlays;
5
+ exports.serializeForEachSlot = serializeForEachSlot;
6
+ exports.serializeForEachSlots = serializeForEachSlots;
7
+ function serializeComponentList(components) {
8
+ return components.map((c) => c.serialize());
9
+ }
10
+ function serializeOverlays(overlays) {
11
+ return overlays.map((o) => ({
12
+ anchors: o.anchors,
13
+ component: o.component.serialize(),
14
+ }));
15
+ }
16
+ function serializeForEachSlot(slot) {
17
+ if (Array.isArray(slot)) {
18
+ return serializeComponentList(slot);
19
+ }
20
+ return slot.serialize();
21
+ }
22
+ function serializeForEachSlots(slots) {
23
+ return slots.map((slot) => serializeForEachSlot(slot));
24
+ }
@@ -0,0 +1,2 @@
1
+ import { Paths, PathValue } from "ts-essentials";
2
+ export declare function setObjectProperty<T extends Record<string, unknown>, K extends Paths<T>>(object: T, key: K, value: PathValue<T, K>): void;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setObjectProperty = setObjectProperty;
4
+ function setObjectProperty(object, key, value) {
5
+ const path = key.split(".");
6
+ let target = object;
7
+ path.forEach((part, index) => {
8
+ if (index < path.length - 1) {
9
+ // Последний элемент участвует в вычислениях, но не в формировании
10
+ if (target[part] === undefined) {
11
+ if (/^[0-9]*$/.test(path[index + 1])) {
12
+ // Если следующий элемент число, значит нужно создать массив
13
+ target[part] = [];
14
+ }
15
+ else {
16
+ // Иначе объект
17
+ target[part] = {};
18
+ }
19
+ }
20
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
21
+ target = target[part];
22
+ }
23
+ });
24
+ target[path[path.length - 1]] = value;
25
+ if (typeof value === "undefined" && Array.isArray(target)) {
26
+ // На случай если элемент массива становится undefined, нужно его удалить из массива
27
+ target.splice(parseInt(path[path.length - 1]), 1);
28
+ }
29
+ }
@@ -0,0 +1,10 @@
1
+ import type { ComponentInstance } from "../types/component-instance";
2
+ /**
3
+ * Выполняет код и возвращает instances, созданные внутри через {@link Component.createInstance}.
4
+ */
5
+ export declare function runWithCreatedInstanceTracking<T>(fn: () => T): {
6
+ result: T;
7
+ instances: ComponentInstance[];
8
+ };
9
+ /** @internal */
10
+ export declare function trackCreatedInstance(instance: ComponentInstance): void;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runWithCreatedInstanceTracking = runWithCreatedInstanceTracking;
4
+ exports.trackCreatedInstance = trackCreatedInstance;
5
+ const node_async_hooks_1 = require("node:async_hooks");
6
+ const createdInstancesStorage = new node_async_hooks_1.AsyncLocalStorage();
7
+ /**
8
+ * Выполняет код и возвращает instances, созданные внутри через {@link Component.createInstance}.
9
+ */
10
+ function runWithCreatedInstanceTracking(fn) {
11
+ const created = [];
12
+ const result = createdInstancesStorage.run(created, fn);
13
+ return { result, instances: [...created] };
14
+ }
15
+ /** @internal */
16
+ function trackCreatedInstance(instance) {
17
+ createdInstancesStorage.getStore()?.push(instance);
18
+ }
@@ -0,0 +1 @@
1
+ export declare const version: string;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.version = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ function loadPackageJson(fromDir) {
7
+ let dir = fromDir;
8
+ for (;;) {
9
+ try {
10
+ return JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(dir, "package.json"), "utf8"));
11
+ }
12
+ catch {
13
+ const parent = (0, node_path_1.dirname)(dir);
14
+ if (parent === dir) {
15
+ throw new Error("package.json not found");
16
+ }
17
+ dir = parent;
18
+ }
19
+ }
20
+ }
21
+ exports.version = loadPackageJson(__dirname).version;
@@ -0,0 +1,3 @@
1
+ export * from "./components";
2
+ export * from "./core";
3
+ export * from "./platforms";
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./components"), exports);
18
+ __exportStar(require("./core"), exports);
19
+ __exportStar(require("./platforms"), exports);
@@ -0,0 +1,6 @@
1
+ import { MobilePlatform } from "./mobile-platform";
2
+ /**
3
+ * Класс платформы для устройств под управлением Android.
4
+ */
5
+ export declare class AndroidPlatform extends MobilePlatform {
6
+ }
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AndroidPlatform = void 0;
4
+ const mobile_platform_1 = require("./mobile-platform");
5
+ /**
6
+ * Класс платформы для устройств под управлением Android.
7
+ */
8
+ class AndroidPlatform extends mobile_platform_1.MobilePlatform {
9
+ }
10
+ exports.AndroidPlatform = AndroidPlatform;
@@ -0,0 +1,79 @@
1
+ import { WebPlatform } from "./web-platform";
2
+ /**
3
+ * Платформа для браузерной версии клиента.
4
+ *
5
+ * Расширяет `WebPlatform`, добавляя методы для взаимодействия с API браузера.
6
+ */
7
+ export declare class BrowserPlatform extends WebPlatform {
8
+ /**
9
+ * Запрашивает геолокацию пользователя в веб-клиенте.
10
+ *
11
+ * @param config Объект с обработчиками успешного получения геолокации и отмены.
12
+ */
13
+ getGeolocation(config: {
14
+ onSuccess: (position: {
15
+ latitude: number;
16
+ longitude: number;
17
+ }) => void;
18
+ onError?: (error: string) => void;
19
+ }): void;
20
+ /**
21
+ * Добавляет событие в календарь клиента.
22
+ *
23
+ * @param data Данные события: начало, конец, описание, место проведения и заголовок.
24
+ */
25
+ addEventToCalendar(data: {
26
+ start: string | EpochTimeStamp;
27
+ end?: string | EpochTimeStamp;
28
+ summary: string;
29
+ location?: string;
30
+ description?: string;
31
+ }): void;
32
+ /**
33
+ * Сохраняет CSV-файл на устройстве пользователя.
34
+ *
35
+ * @param filename Имя файла (будет добавлено расширение `.csv`, если не указано).
36
+ * @param content Двумерный массив строк, представляющий содержимое CSV.
37
+ */
38
+ downloadCsvContent(filename: string, content: string[][]): void;
39
+ /**
40
+ * Инициирует загрузку файла по указанному URL.
41
+ *
42
+ * @param url Ссылка на файл.
43
+ * @param filename Имя сохраняемого файла.
44
+ */
45
+ downloadFile(url: string, filename: string): void;
46
+ /**
47
+ * Открывает файл во встроенном просмотрщике браузера (PDF, изображения и т.д.).
48
+ *
49
+ * @param url Ссылка на файл (blob: или HTTP).
50
+ */
51
+ openFile(url: string): void;
52
+ /**
53
+ * Делится содержимым через системное диалоговое окно обмена.
54
+ *
55
+ * @param data Объект с текстом, ссылкой и/или заголовком.
56
+ */
57
+ share(data: {
58
+ url?: string;
59
+ title?: string;
60
+ text?: string;
61
+ }): void;
62
+ /**
63
+ * Запрашивает разрешение на push-уведомления и обрабатывает результат.
64
+ *
65
+ * @param config Объект с колбэками: `onGranted` при успехе, `onError` при ошибке.
66
+ */
67
+ registerPushNotifications(config: {
68
+ publicKey: string;
69
+ onGranted: (subscription: {
70
+ endpoint: string;
71
+ expirationTime?: EpochTimeStamp | null;
72
+ keys: {
73
+ auth: string;
74
+ p256dh: string;
75
+ };
76
+ }) => void;
77
+ onError?: (text: string) => void;
78
+ }): void;
79
+ }
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BrowserPlatform = void 0;
4
+ const browser_add_event_to_calendar_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/browser/browser-add-event-to-calendar-message");
5
+ const browser_download_csv_content_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/browser/browser-download-csv-content-message");
6
+ const browser_download_file_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/browser/browser-download-file-message");
7
+ const browser_get_geolocation_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/browser/browser-get-geolocation-message");
8
+ const browser_open_file_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/browser/browser-open-file-message");
9
+ const browser_request_push_notifications_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/browser/browser-request-push-notifications-message");
10
+ const browser_share_message_1 = require("@matreshka/shared/messages/bff-to-client/platforms/browser/browser-share-message");
11
+ const error_message_1 = require("@matreshka/shared/messages/client-to-bff/error-message");
12
+ const browser_get_geolocation_success_message_1 = require("@matreshka/shared/messages/client-to-bff/platforms/browser/browser-get-geolocation-success-message");
13
+ const browser_request_push_notifications_action_granted_message_1 = require("@matreshka/shared/messages/client-to-bff/platforms/browser/browser-request-push-notifications-action-granted-message");
14
+ const rxjs_1 = require("rxjs");
15
+ const v4_1 = require("zod/v4");
16
+ const incoming_message_observer_1 = require("../core/utils/incoming-message-observer");
17
+ const web_platform_1 = require("./web-platform");
18
+ const pushSubscriptionGrantedMessageSchema = v4_1.z.strictObject({
19
+ subscription: v4_1.z.strictObject({
20
+ endpoint: v4_1.z.string(),
21
+ expirationTime: v4_1.z.number().nullable().optional(),
22
+ keys: v4_1.z.strictObject({
23
+ auth: v4_1.z.string(),
24
+ p256dh: v4_1.z.string(),
25
+ }),
26
+ }),
27
+ });
28
+ const errorMessagePayloadSchema = v4_1.z.strictObject({
29
+ message: v4_1.z.string(),
30
+ });
31
+ /**
32
+ * Платформа для браузерной версии клиента.
33
+ *
34
+ * Расширяет `WebPlatform`, добавляя методы для взаимодействия с API браузера.
35
+ */
36
+ class BrowserPlatform extends web_platform_1.WebPlatform {
37
+ /**
38
+ * Запрашивает геолокацию пользователя в веб-клиенте.
39
+ *
40
+ * @param config Объект с обработчиками успешного получения геолокации и отмены.
41
+ */
42
+ getGeolocation(config) {
43
+ const scope = "platform-action-" + crypto.randomUUID();
44
+ const subscription = this.client.incomingMessage$
45
+ .pipe((0, rxjs_1.filter)((unsafeMessage) => unsafeMessage.scope === scope))
46
+ .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (unsafeMessage) => {
47
+ subscription.unsubscribe();
48
+ if (unsafeMessage instanceof browser_get_geolocation_success_message_1.BrowserGetGeolocationSuccessMessage) {
49
+ const messagePayload = v4_1.z
50
+ .strictObject({
51
+ latitude: v4_1.z.number(),
52
+ longitude: v4_1.z.number(),
53
+ })
54
+ .parse(unsafeMessage.payload);
55
+ config.onSuccess(messagePayload);
56
+ return;
57
+ }
58
+ if (unsafeMessage instanceof error_message_1.ErrorMessage) {
59
+ const messagePayload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
60
+ if (typeof config.onError === "function") {
61
+ config.onError(messagePayload.message);
62
+ }
63
+ }
64
+ }));
65
+ this.client.outcomingMessage$.next(new browser_get_geolocation_message_1.BrowserGetGeolocationMessage(scope));
66
+ }
67
+ /**
68
+ * Добавляет событие в календарь клиента.
69
+ *
70
+ * @param data Данные события: начало, конец, описание, место проведения и заголовок.
71
+ */
72
+ addEventToCalendar(data) {
73
+ this.client.outcomingMessage$.next(new browser_add_event_to_calendar_message_1.BrowserAddEventToCalendarMessage(data));
74
+ }
75
+ /**
76
+ * Сохраняет CSV-файл на устройстве пользователя.
77
+ *
78
+ * @param filename Имя файла (будет добавлено расширение `.csv`, если не указано).
79
+ * @param content Двумерный массив строк, представляющий содержимое CSV.
80
+ */
81
+ downloadCsvContent(filename, content) {
82
+ this.client.outcomingMessage$.next(new browser_download_csv_content_message_1.BrowserDownloadCsvContentMessage({
83
+ filename: filename.endsWith(".csv") ? filename : filename + ".csv",
84
+ content,
85
+ }));
86
+ }
87
+ /**
88
+ * Инициирует загрузку файла по указанному URL.
89
+ *
90
+ * @param url Ссылка на файл.
91
+ * @param filename Имя сохраняемого файла.
92
+ */
93
+ downloadFile(url, filename) {
94
+ // https://developer.mozilla.org/ru/docs/Web/HTML/Element/a#Attributes
95
+ // Принудительная загрузка файлов, которые браузер может открыть, а не скачать (изображения и pdf), будет только для того же домена, иначе будет срабатывать открытие, либо будет игнорировать приоритетный filename
96
+ this.client.outcomingMessage$.next(new browser_download_file_message_1.BrowserDownloadFileMessage({ url, filename }));
97
+ }
98
+ /**
99
+ * Открывает файл во встроенном просмотрщике браузера (PDF, изображения и т.д.).
100
+ *
101
+ * @param url Ссылка на файл (blob: или HTTP).
102
+ */
103
+ openFile(url) {
104
+ this.client.outcomingMessage$.next(new browser_open_file_message_1.BrowserOpenFileMessage({ url }));
105
+ }
106
+ /**
107
+ * Делится содержимым через системное диалоговое окно обмена.
108
+ *
109
+ * @param data Объект с текстом, ссылкой и/или заголовком.
110
+ */
111
+ share(data) {
112
+ this.client.outcomingMessage$.next(new browser_share_message_1.BrowserShareMessage(data));
113
+ }
114
+ /**
115
+ * Запрашивает разрешение на push-уведомления и обрабатывает результат.
116
+ *
117
+ * @param config Объект с колбэками: `onGranted` при успехе, `onError` при ошибке.
118
+ */
119
+ registerPushNotifications(config) {
120
+ const scope = "platform-action-" + crypto.randomUUID();
121
+ const subscription = this.client.incomingMessage$
122
+ .pipe((0, rxjs_1.filter)((unsafeMessage) => unsafeMessage.scope === scope))
123
+ .subscribe((0, incoming_message_observer_1.incomingMessageObserver)(this.client, (unsafeMessage) => {
124
+ subscription.unsubscribe();
125
+ if (unsafeMessage instanceof
126
+ browser_request_push_notifications_action_granted_message_1.BrowserRequestPushNotificationsActionGrantedMessage) {
127
+ const messagePayload = pushSubscriptionGrantedMessageSchema.parse(unsafeMessage.payload);
128
+ config.onGranted(messagePayload.subscription);
129
+ return;
130
+ }
131
+ if (unsafeMessage instanceof error_message_1.ErrorMessage) {
132
+ const messagePayload = errorMessagePayloadSchema.parse(unsafeMessage.payload);
133
+ if ("onError" in config) {
134
+ config.onError(messagePayload.message);
135
+ }
136
+ }
137
+ }));
138
+ this.client.outcomingMessage$.next(new browser_request_push_notifications_message_1.BrowserRequestPushNotificationsMessage(scope, {
139
+ publicKey: config.publicKey,
140
+ }));
141
+ }
142
+ }
143
+ exports.BrowserPlatform = BrowserPlatform;
@@ -0,0 +1,6 @@
1
+ import { Platform } from "./platform";
2
+ /**
3
+ * Абстрактный класс, реализующий любую клиентскую платформу.
4
+ */
5
+ export declare abstract class ClientPlatform extends Platform {
6
+ }
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ClientPlatform = void 0;
4
+ const platform_1 = require("./platform");
5
+ /**
6
+ * Абстрактный класс, реализующий любую клиентскую платформу.
7
+ */
8
+ class ClientPlatform extends platform_1.Platform {
9
+ }
10
+ exports.ClientPlatform = ClientPlatform;
@@ -0,0 +1,12 @@
1
+ export * from "./android-platform";
2
+ export * from "./browser-platform";
3
+ export * from "./client-platform";
4
+ export * from "./ios-platform";
5
+ export * from "./max-mini-app-platform";
6
+ export * from "./mobile-platform";
7
+ export * from "./platform";
8
+ export * from "./pwa-platform";
9
+ export * from "./server-platform";
10
+ export * from "./telegram-mini-app-platform";
11
+ export * from "./utils/client-platform";
12
+ export * from "./web-platform";
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./android-platform"), exports);
18
+ __exportStar(require("./browser-platform"), exports);
19
+ __exportStar(require("./client-platform"), exports);
20
+ __exportStar(require("./ios-platform"), exports);
21
+ __exportStar(require("./max-mini-app-platform"), exports);
22
+ __exportStar(require("./mobile-platform"), exports);
23
+ __exportStar(require("./platform"), exports);
24
+ __exportStar(require("./pwa-platform"), exports);
25
+ __exportStar(require("./server-platform"), exports);
26
+ __exportStar(require("./telegram-mini-app-platform"), exports);
27
+ __exportStar(require("./utils/client-platform"), exports);
28
+ __exportStar(require("./web-platform"), exports);
@@ -0,0 +1,6 @@
1
+ import { MobilePlatform } from "./mobile-platform";
2
+ /**
3
+ * Платформа iOS, реализующая поведение мобильной платформы для устройств Apple.
4
+ */
5
+ export declare class IosPlatform extends MobilePlatform {
6
+ }