poe-svelte-ui-lib 2.7.0 → 2.8.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 (54) hide show
  1. package/README.md +13 -12
  2. package/dist/Button/Button.svelte +8 -5
  3. package/dist/Button/README.md +3 -2
  4. package/dist/FileAttach/FileAttach.svelte +6 -5
  5. package/dist/FileAttach/README.md +20 -19
  6. package/dist/InfoHint.svelte +2 -1
  7. package/dist/Input/Input.svelte +9 -4
  8. package/dist/Input/README.md +2 -2
  9. package/dist/Select/README.md +1 -1
  10. package/dist/Select/Select.svelte +5 -4
  11. package/dist/Table/README.md +5 -1
  12. package/dist/Table/Table.svelte +56 -12
  13. package/dist/Table/TableProps.svelte +4 -3
  14. package/dist/Table/XPoeDebugModal.svelte +6 -3
  15. package/dist/Table/xPoeDebugColumns.d.ts +1 -1
  16. package/dist/Table/xPoeDebugColumns.js +35 -4
  17. package/dist/Tabs/README.md +1 -0
  18. package/dist/Tabs/Tabs.svelte +6 -5
  19. package/dist/WidgetDeviceInfo/WidgetDeviceInfo.svelte +1 -1
  20. package/dist/WidgetFileSystem/WidgetFileSystem.svelte +1 -1
  21. package/dist/dictionaries/README.md +77 -0
  22. package/dist/{protocols/dictionary.yaml → dictionaries/commands.yaml} +1 -1
  23. package/dist/dictionaries/firmware/api_har.h +109 -0
  24. package/dist/dictionaries/firmware/api_msg.h +57 -0
  25. package/dist/{protocols/dictionaryCodes.js → dictionaries/generated/commands.js} +1 -1
  26. package/dist/dictionaries/generated/messages.d.ts +19 -0
  27. package/dist/dictionaries/generated/messages.js +84 -0
  28. package/dist/dictionaries/messages.yaml +57 -0
  29. package/dist/libIcons/ArrowIcon.svelte +1 -1
  30. package/dist/libIcons/ButtonClear.svelte +1 -1
  31. package/dist/libIcons/CrossIcon.svelte +1 -1
  32. package/dist/libIcons/InfoIcon.svelte +1 -1
  33. package/dist/libIcons/Library.svelte +1 -1
  34. package/dist/libIcons/MoveVerticalIcon.svelte +1 -1
  35. package/dist/locales/translations.d.ts +20 -0
  36. package/dist/locales/translations.js +4 -0
  37. package/dist/options.js +1 -1
  38. package/dist/popup.d.ts +1 -0
  39. package/dist/popup.js +12 -0
  40. package/dist/protocols/PROTOCOL.md +168 -32
  41. package/dist/protocols/dictionary.d.ts +1 -1
  42. package/dist/protocols/dictionary.js +2 -2
  43. package/dist/protocols/index.d.ts +2 -1
  44. package/dist/protocols/index.js +4 -2
  45. package/dist/protocols/messages.d.ts +15 -0
  46. package/dist/protocols/messages.js +31 -0
  47. package/dist/protocols/xPoeDebug.d.ts +6 -1
  48. package/dist/protocols/xPoeDebug.js +41 -17
  49. package/dist/protocols/xPoeDebugView.d.ts +4 -1
  50. package/dist/protocols/xPoeDebugView.js +37 -65
  51. package/dist/protocols/xPoeYaml.d.ts +6 -0
  52. package/dist/protocols/xPoeYaml.js +294 -0
  53. package/package.json +2 -2
  54. /package/dist/{protocols/dictionaryCodes.d.ts → dictionaries/generated/commands.d.ts} +0 -0
@@ -1,10 +1,11 @@
1
1
  /* xPOE-Debug - UART-консоль как ещё одна шина: пакеты poe_cbor_pkt [[TrgBusID, SrcBusID, HAR, Payload, CRC16], …] вперемешку с текстом загрузчика. Логи - OK! DebugLog, Payload [уровень, тег, текст|байты, FHS]; графики - OK! DebugPlot, Payload {"Группа.Имя": float32} */
2
2
  import { cborToValue } from "./cbor/value.js";
3
- import { jsonToCbor } from "./cbor/json.js";
4
3
  import { DEFAULT_DICTIONARY } from "./dictionary.js";
4
+ import { DEFAULT_LANGUAGE } from "../locales/languages.js";
5
5
  import { createFramer } from "./framer.js";
6
6
  import { hexToBytes } from "./hex.js";
7
- import { formatXPoeDebugValue } from "./xPoeDebugView.js";
7
+ import { formatXPoeDebugValue, xPoeDebugMessage } from "./xPoeDebugView.js";
8
+ import { yamlFlowToCbor } from "./xPoeYaml.js";
8
9
  import { decodePacket, encodePacket, formatBusId, packetStart } from "./packet.js";
9
10
  export const DEBUG_LOG_ARGUMENT = "DebugLog";
10
11
  const MAX_TEXT_TAIL = 4096;
@@ -46,20 +47,38 @@ const frameItem = (object, dictionary) => {
46
47
  freeHeap: argument === DEBUG_LOG_ARGUMENT && Array.isArray(payload) && typeof payload[3] === "number" ? String(payload[3]) : "",
47
48
  };
48
49
  };
49
- export const xPoeDebugRow = (item) => item.type === "raw"
50
- ? { trgId: "", srcId: "", har: "", header: "RAW", argument: "", value: item.text, valueBytes: new Uint8Array(), payload: undefined, crc: "", freeHeap: "" }
51
- : {
50
+ /* lang - язык сообщений устройства (приложение передаёт getLanguage()) */
51
+ export const xPoeDebugRow = (item, lang = DEFAULT_LANGUAGE) => {
52
+ if (item.type === "raw")
53
+ return {
54
+ trgId: "",
55
+ srcId: "",
56
+ har: "",
57
+ header: "RAW",
58
+ argument: "",
59
+ reply: false,
60
+ value: item.text,
61
+ valueBytes: new Uint8Array(),
62
+ payload: undefined,
63
+ crc: "",
64
+ freeHeap: "",
65
+ };
66
+ const message = xPoeDebugMessage(item.payload, lang);
67
+ return {
52
68
  trgId: formatBusId(item.trgId),
53
69
  srcId: formatBusId(item.srcId),
54
70
  har: item.har.toString(16).toUpperCase().padStart(4, "0"),
55
71
  header: item.crcOk ? item.header : "⚠️",
56
72
  argument: item.argument,
73
+ reply: item.reply,
57
74
  value: formatXPoeDebugValue(item.payload, item.valueBytes),
58
75
  valueBytes: item.valueBytes,
59
76
  payload: item.payload,
60
77
  crc: item.crc,
61
78
  freeHeap: item.freeHeap,
79
+ ...(message && { message: message.text, level: message.level }),
62
80
  };
81
+ };
63
82
  /* Потоковый разбор: пакеты в любом месте разреза, текст - построчно, мусор сдвигается по байту; пауза дольше gapMs обрывает недособранный пакет, а недописанную строку текста выдаёт как есть. Имена аргументов - из dictionary (по умолчанию встроенного) */
64
83
  export const createXPoeDebugParser = ({ dictionary = DEFAULT_DICTIONARY, ...options } = {}) => {
65
84
  const framer = createFramer(options);
@@ -92,26 +111,31 @@ export const createXPoeDebugParser = ({ dictionary = DEFAULT_DICTIONARY, ...opti
92
111
  reset: framer.reset,
93
112
  };
94
113
  };
95
- /* Готовые байты Payload только явным синтаксисом: h'0A 1B' (как показывает formatXPoeDebugValue) или 0x0A1B */
96
- const HEX_VALUE = /^(?:h'([0-9A-Fa-f\s]*)'|0[xX]([0-9A-Fa-f]+))$/;
97
- /* Поле Value: h'..' или 0x.. - готовые байты Payload (CBOR) как есть, всё остальное - JSON в CBOR («12» - число 12), пусто - пустой Payload */
114
+ /* Готовые байты Payload (CBOR как есть) - только 0x0A1B */
115
+ const RAW_VALUE = /^0[xX]([0-9A-Fa-f]*)$/;
116
+ /* Поле Value: 0x.. - готовые байты Payload как есть; поток YAML, как в строке VALUE, и JSON как его часть (в JSON строки Base64 под ключами на BIN - байты): «A: 1, B: [1, 2]» (корневая карта без скобок), h'0A1B' - байтовая строка, «12» - число, "12" - строка; пусто - пустой Payload */
98
117
  export const xPoeDebugValueFromText = (text) => {
99
118
  const trimmed = (text ?? "").trim();
100
119
  if (!trimmed)
101
120
  return new Uint8Array();
102
- const hex = HEX_VALUE.exec(trimmed);
103
- if (hex) {
104
- const bytes = hexToBytes(hex[1] ?? hex[2]);
105
- if (!bytes)
106
- throw new Error(`Value: нечётное число HEX-цифр: ${trimmed}`);
121
+ const raw = RAW_VALUE.exec(trimmed);
122
+ if (raw) {
123
+ const bytes = hexToBytes(raw[1]);
124
+ if (!bytes?.length)
125
+ throw new Error(`Value: после 0x нужны HEX-цифры парами: ${trimmed}`);
107
126
  return bytes;
108
127
  }
109
- let parsed;
128
+ let json = true;
110
129
  try {
111
- parsed = JSON.parse(trimmed);
130
+ JSON.parse(trimmed);
112
131
  }
113
132
  catch {
114
- throw new Error(`Value не является ни HEX (h'..' или 0x..), ни JSON: ${trimmed}`);
133
+ json = false;
134
+ }
135
+ try {
136
+ return yamlFlowToCbor(trimmed, json);
137
+ }
138
+ catch (err) {
139
+ throw new Error(`Value не разобран (YAML, JSON или 0x..): ${err instanceof Error ? err.message : err}: ${trimmed}`);
115
140
  }
116
- return jsonToCbor(parsed);
117
141
  };
@@ -1,2 +1,5 @@
1
+ import { type LanguageCode } from "../locales/languages.js";
2
+ import { type FormattedDeviceMessage } from "./messages.js";
3
+ export declare const xPoeDebugMessage: (payload: unknown, lang?: LanguageCode) => FormattedDeviceMessage | null;
1
4
  export declare const formatXPoeDebugValue: (payload: unknown, bytes: Uint8Array) => string;
2
- export declare const formatXPoeDebugPretty: (payload: unknown, html?: boolean) => string | null;
5
+ export declare const formatXPoeDebugPretty: (payload: unknown, html?: boolean, bytes?: Uint8Array) => string | null;
@@ -1,55 +1,54 @@
1
- /* Вид Payload xPOE-Debug: кратко в строку таблицы и развёрнуто для окна; Payload декодирован один раз при разборе (xPoeDebugRow) */
1
+ /* Вид Payload xPOE-Debug: кратко в строку таблицы и развёрнуто для окна как пришёл, сообщение устройства - отдельно (xPoeDebugMessage); Payload декодирован один раз при разборе (xPoeDebugRow) */
2
2
  import { escapeHtml } from "../html.js";
3
+ import { DEFAULT_LANGUAGE } from "../locales/languages.js";
4
+ import { decodeCbor } from "./cbor/decoder.js";
3
5
  import { bytesToHex } from "./hex.js";
6
+ import { formatYamlBlock, formatYamlFlow } from "./xPoeYaml.js";
7
+ import { formatDeviceMessage, parseDebugLogMessage } from "./messages.js";
4
8
  const LOG_LEVELS = { 1: "🔴", 2: "🟡", 3: "🟢", 4: "🔵" };
5
- /* float32 с провода - кратчайшая запись, дающая то же float32 (0.12, а не 0.12000000476837158); double и целые - как есть */
6
- const shortNumber = (value) => {
7
- if (Number.isInteger(value) || !Number.isFinite(value) || Math.fround(value) !== value)
8
- return value;
9
- for (let digits = 1; digits <= 9; digits++) {
10
- const short = Number(value.toPrecision(digits));
11
- if (Math.fround(short) === value)
12
- return short;
9
+ /* Payload для вида - как на проводе (порядок пар, ключи-числа, uint64), из исходных байт; без байт - декодированный payload */
10
+ const wireValue = (payload, bytes) => {
11
+ if (!bytes?.length)
12
+ return payload;
13
+ try {
14
+ return decodeCbor(bytes);
15
+ }
16
+ catch {
17
+ return payload;
13
18
  }
14
- return value;
15
- };
16
- const normalizeCborValue = (value) => {
17
- if (typeof value === "number")
18
- return shortNumber(value);
19
- if (typeof value === "bigint")
20
- return String(value);
21
- if (value instanceof Uint8Array)
22
- return `h'${bytesToHex(value, " ")}'`;
23
- if (Array.isArray(value))
24
- return value.map(normalizeCborValue);
25
- if (value instanceof Map)
26
- return Object.fromEntries([...value].map(([key, item]) => [String(key), normalizeCborValue(item)]));
27
- if (value && typeof value === "object")
28
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeCborValue(item)]));
29
- return value;
30
- };
31
- const compactValue = (value) => {
32
- if (typeof value === "string")
33
- return value;
34
- if (value instanceof Uint8Array)
35
- return `bytes(${value.length}): ${bytesToHex(value, " ")}`;
36
- return JSON.stringify(normalizeCborValue(value)) ?? String(value);
37
19
  };
20
+ /* Байты DebugLog - с длиной, HEX через пробел */
21
+ const logBytes = (bytes) => `bytes(${bytes.length}): ${bytesToHex(bytes, " ")}`;
38
22
  const isDebugLog = (value) => Array.isArray(value) &&
39
23
  value.length === 4 &&
40
24
  typeof value[0] === "number" &&
41
25
  !!LOG_LEVELS[value[0]] &&
42
26
  typeof value[1] === "string" &&
43
27
  (typeof value[2] === "string" || value[2] instanceof Uint8Array);
44
- /* Payload в строку таблицы: DebugLog [уровень, тег, текст|байты, FHS] - уровень · тег · текст, CBOR - JSON, не CBOR - HEX байт */
28
+ /* Поле карты Payload (CBOR-карта приходит Map или объектом) */
29
+ const mapField = (value, key) => value instanceof Map ? value.get(key) : value && typeof value === "object" && !Array.isArray(value) ? value[key] : undefined;
30
+ /* Сообщение устройства в Payload на языке lang: DebugLog с текстом "MSG <код> ..." или карта {Message, Args} (ответ ER!); нет - null. В строку VALUE не входит */
31
+ export const xPoeDebugMessage = (payload, lang = DEFAULT_LANGUAGE) => {
32
+ if (isDebugLog(payload)) {
33
+ const message = typeof payload[2] === "string" ? parseDebugLogMessage(payload[2]) : null;
34
+ return message && formatDeviceMessage(message.Message, message.Args, lang);
35
+ }
36
+ const code = mapField(payload, "Message");
37
+ if (typeof code !== "number")
38
+ return null;
39
+ const args = mapField(payload, "Args");
40
+ return formatDeviceMessage(code, Array.isArray(args) ? args.filter((a) => typeof a === "string" || typeof a === "number") : [], lang);
41
+ };
42
+ /* Payload в строку таблицы как пришёл: DebugLog [уровень, тег, текст|байты, FHS] - уровень · тег · текст, CBOR - поток YAML (корневая карта без скобок: «A: 1, B: [1, 2]»; читается обратно полем Value), не CBOR - HEX байт */
45
43
  export const formatXPoeDebugValue = (payload, bytes) => {
46
44
  if (payload === undefined)
47
45
  return bytesToHex(bytes, " ");
48
46
  if (!isDebugLog(payload))
49
- return compactValue(payload);
50
- const detail = compactValue(payload[2]);
47
+ return formatYamlFlow(wireValue(payload, bytes));
48
+ const detail = typeof payload[2] === "string" ? payload[2] : logBytes(payload[2]);
51
49
  return `${LOG_LEVELS[payload[0]]} · ${payload[1]}${detail ? ` · ${detail}` : ""}`;
52
50
  };
51
+ /* Цвета развёрнутого вида - палитра темы: ключи, строки, числа, логические, null, байты */
53
52
  const PRETTY_COLORS = {
54
53
  key: "--blue-text",
55
54
  string: "--purple-text",
@@ -62,41 +61,14 @@ const plain = (_kind, text) => text;
62
61
  const colored = (kind, text) => `<span style="color:var(${PRETTY_COLORS[kind]})">${escapeHtml(text)}</span>`;
63
62
  /* Байты строками по 16 - для дампа DebugLog */
64
63
  const hexRows = (bytes) => (bytesToHex(bytes, " ").match(/.{1,48}/g) ?? []).map((row) => row.trim()).join("\n");
65
- /* Карты и массивы с отступом 2, по одному элементу на строку; скобки и запятые - без цвета */
66
- const prettyValue = (value, paint, indent = "") => {
67
- if (value === null || value === undefined)
68
- return paint("null", "null");
69
- if (typeof value === "string")
70
- return paint("string", JSON.stringify(value));
71
- if (typeof value === "number")
72
- return paint("number", String(shortNumber(value)));
73
- if (typeof value === "bigint")
74
- return paint("number", String(value));
75
- if (typeof value === "boolean")
76
- return paint("boolean", String(value));
77
- if (value instanceof Uint8Array)
78
- return paint("bytes", `h'${bytesToHex(value, " ")}'`);
79
- const inner = `${indent} `;
80
- if (Array.isArray(value)) {
81
- if (!value.length)
82
- return "[]";
83
- return `[\n${value.map((item) => inner + prettyValue(item, paint, inner)).join(",\n")}\n${indent}]`;
84
- }
85
- const entries = value instanceof Map ? [...value.entries()] : Object.entries(value);
86
- if (!entries.length)
87
- return "{}";
88
- return `{\n${entries.map(([key, item]) => `${inner}${paint("key", `${JSON.stringify(String(key))}:`)} ${prettyValue(item, paint, inner)}`).join(",\n")}\n${indent}}`;
89
- };
90
- /* Payload развёрнуто: карты и массивы с отступами, DebugLog - уровень и тег, ниже текст или дамп по 16 байт и FHS; html - готовый HTML в цветах темы (данные экранированы); не CBOR - null */
91
- export const formatXPoeDebugPretty = (payload, html = false) => {
64
+ /* Payload развёрнуто: блочный YAML с отступом 2 (скаляр - как в строке таблицы), DebugLog - уровень и тег, ниже текст как пришёл или дамп по 16 байт и FHS; html - готовый HTML в цветах темы (данные экранированы); bytes - исходные байты Payload (порядок пар как на проводе); не CBOR - null */
65
+ export const formatXPoeDebugPretty = (payload, html = false, bytes) => {
92
66
  if (payload === undefined)
93
67
  return null;
94
68
  const paint = html ? colored : plain;
95
69
  const raw = (text) => (html ? escapeHtml(text) : text);
96
- if (typeof payload === "string")
97
- return raw(payload);
98
70
  if (!isDebugLog(payload))
99
- return prettyValue(payload, paint);
71
+ return formatYamlBlock(wireValue(payload, bytes), paint);
100
72
  const [level, tag, detail, fhs] = payload;
101
73
  const body = detail instanceof Uint8Array ? `${raw(`bytes(${detail.length}):`)}\n${paint("bytes", hexRows(detail))}` : raw(detail);
102
74
  return [`${LOG_LEVELS[level]} ${paint("key", tag)}`, body, typeof fhs === "number" ? `FHS: ${paint("number", String(fhs))}` : ""].filter(Boolean).join("\n");
@@ -0,0 +1,6 @@
1
+ export type YamlKind = "key" | "string" | "number" | "boolean" | "null" | "bytes";
2
+ export type YamlPaint = (kind: YamlKind, text: string) => string;
3
+ export declare const shortNumber: (value: number) => number;
4
+ export declare const formatYamlFlow: (value: unknown, paint?: YamlPaint) => string;
5
+ export declare const formatYamlBlock: (value: unknown, paint?: YamlPaint) => string;
6
+ export declare const yamlFlowToCbor: (text: string, binBase64?: boolean) => Uint8Array;
@@ -0,0 +1,294 @@
1
+ /* Вид CBOR в стиле YAML для xPOE-Debug: строка VALUE - поток (корневая карта без скобок), окно - блок с отступом 2; разбор поля Value - поток YAML или JSON */
2
+ import { base64ToBytes } from "./cbor/base64.js";
3
+ import { encodeCbor } from "./cbor/encoder.js";
4
+ import { bytesToHex, hexToBytes } from "./hex.js";
5
+ const plain = (_kind, text) => text;
6
+ /* float32 с провода - кратчайшая запись, дающая то же float32 (0.12, а не 0.12000000476837158); double и целые - как есть */
7
+ export const shortNumber = (value) => {
8
+ if (Number.isInteger(value) || !Number.isFinite(value) || Math.fround(value) !== value)
9
+ return value;
10
+ for (let digits = 1; digits <= 9; digits++) {
11
+ const short = Number(value.toPrecision(digits));
12
+ if (Math.fround(short) === value)
13
+ return short;
14
+ }
15
+ return value;
16
+ };
17
+ const NUMBER = /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/;
18
+ const SPECIAL = /^(?:null|Null|NULL|~|true|True|TRUE|false|False|FALSE|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$/;
19
+ /* Строка без кавычек только если читается обратно той же строкой: не похожа на число, true/false/null, не пустая, без «:,[]{}#», управляющих символов и крайних пробелов, не начинается с кавычки, h' или знака YAML */
20
+ const needsQuotes = (text) => !text ||
21
+ text !== text.trim() ||
22
+ /[:,[\]{}#\x00-\x1f\x7f]/.test(text) ||
23
+ /^(?:["'!&*|>%@`]|h'|- |\? )/.test(text) ||
24
+ /^[-+.]?\d/.test(text) ||
25
+ /^0[xX]/.test(text) ||
26
+ SPECIAL.test(text) ||
27
+ SPECIAL.test(text.toLowerCase());
28
+ const quote = (text) => (needsQuotes(text) ? JSON.stringify(text) : text);
29
+ const formatNumber = (value) => Number.isNaN(value) ? ".nan" : value === Infinity ? ".inf" : value === -Infinity ? "-.inf" : String(shortNumber(value));
30
+ const scalar = (value, paint) => {
31
+ if (value === null || value === undefined)
32
+ return paint("null", "null");
33
+ if (typeof value === "boolean")
34
+ return paint("boolean", String(value));
35
+ if (typeof value === "number")
36
+ return paint("number", formatNumber(value));
37
+ if (typeof value === "bigint")
38
+ return paint("number", String(value));
39
+ if (typeof value === "string")
40
+ return paint("string", quote(value));
41
+ if (value instanceof Uint8Array)
42
+ return paint("bytes", `h'${bytesToHex(value)}'`);
43
+ return null;
44
+ };
45
+ /* Пары карты: CBOR-карта приходит Map (ключи любого типа, порядок как на проводе) или объектом */
46
+ const entriesOf = (value) => {
47
+ if (value instanceof Map)
48
+ return [...value];
49
+ if (value && typeof value === "object" && !Array.isArray(value) && !(value instanceof Uint8Array))
50
+ return Object.entries(value);
51
+ return null;
52
+ };
53
+ const flow = (value, paint) => {
54
+ const simple = scalar(value, paint);
55
+ if (simple !== null)
56
+ return simple;
57
+ if (Array.isArray(value))
58
+ return `[${value.map((item) => flow(item, paint)).join(", ")}]`;
59
+ const entries = entriesOf(value) ?? [];
60
+ return `{${flowEntries(entries, paint)}}`;
61
+ };
62
+ /* Ключ-строка - по правилам кавычек («"1"» - строка), ключ-число и прочие - как значение («1» - число) */
63
+ const keyText = (key, paint) => paint("key", `${typeof key === "string" ? quote(key) : flow(key, plain)}:`);
64
+ const flowEntries = (entries, paint) => entries.map(([key, item]) => `${keyText(key, paint)} ${flow(item, paint)}`).join(", ");
65
+ /* Одна строка: корневая карта без внешних скобок («A: 1, B: [1, 2]»), пустая - {}; остальное - значение потока */
66
+ export const formatYamlFlow = (value, paint = plain) => {
67
+ const entries = Array.isArray(value) ? null : entriesOf(value);
68
+ return entries?.length ? flowEntries(entries, paint) : flow(value, paint);
69
+ };
70
+ /* Непустая карта или массив - блоком с новой строки */
71
+ const isBlock = (value) => (Array.isArray(value) ? value.length > 0 : !!entriesOf(value)?.length);
72
+ const blockLines = (value, paint, indent) => {
73
+ if (Array.isArray(value))
74
+ return value.map((item) => {
75
+ if (!isBlock(item))
76
+ return `${indent}- ${flow(item, paint)}`;
77
+ /* Вложенное - компактно: первая строка после «- », остальные с отступом +2 */
78
+ const [first, ...rest] = blockLines(item, paint, `${indent} `);
79
+ return [`${indent}- ${first.slice(indent.length + 2)}`, ...rest].join("\n");
80
+ });
81
+ return (entriesOf(value) ?? []).map(([key, item]) => {
82
+ const head = `${indent}${keyText(key, paint)}`;
83
+ return isBlock(item) ? [head, ...blockLines(item, paint, `${indent} `)].join("\n") : `${head} ${flow(item, paint)}`;
84
+ });
85
+ };
86
+ /* Несколько строк: блочный YAML с отступом 2; скаляр, пустые {} и [] - как в потоке */
87
+ export const formatYamlBlock = (value, paint = plain) => isBlock(value) ? blockLines(value, paint, "").join("\n") : flow(value, paint);
88
+ /* Разбор потока YAML (и JSON как его подмножества) в значение CBOR: h'..' - байтовая строка, корневая карта может быть без скобок */
89
+ class FlowParser {
90
+ text;
91
+ binBase64;
92
+ pos = 0;
93
+ constructor(text, binBase64) {
94
+ this.text = text;
95
+ this.binBase64 = binBase64;
96
+ }
97
+ fail(reason) {
98
+ throw new Error(`${reason} (позиция ${this.pos + 1})`);
99
+ }
100
+ skip() {
101
+ while (this.pos < this.text.length && /\s/.test(this.text[this.pos]))
102
+ this.pos++;
103
+ }
104
+ peek = () => this.text[this.pos];
105
+ root() {
106
+ this.skip();
107
+ const start = this.pos;
108
+ const first = this.peek();
109
+ /* Корень без скобок - карта, если начинается с «ключ: » */
110
+ if (first !== "{" && first !== "[" && this.tryKey(true) !== undefined) {
111
+ this.pos = start;
112
+ const map = this.entries(null);
113
+ return map;
114
+ }
115
+ this.pos = start;
116
+ const value = this.value();
117
+ this.skip();
118
+ if (this.pos < this.text.length)
119
+ this.fail(`лишний текст «${this.text.slice(this.pos, this.pos + 20)}»`);
120
+ return value;
121
+ }
122
+ /* Пары до закрывающей скобки или конца текста */
123
+ entries(close) {
124
+ const map = new Map();
125
+ for (;;) {
126
+ this.skip();
127
+ if (close && this.peek() === close)
128
+ break;
129
+ if (this.pos >= this.text.length) {
130
+ if (close)
131
+ this.fail(`ожидалась «${close}»`);
132
+ break;
133
+ }
134
+ const key = this.tryKey(!close);
135
+ if (key === undefined)
136
+ this.fail("ожидалась пара «ключ: значение»");
137
+ this.skip();
138
+ /* «ключ:» без значения - null */
139
+ const empty = this.pos >= this.text.length || this.peek() === "," || this.peek() === close;
140
+ const value = empty ? null : this.value();
141
+ /* JSON: строка под ключом на BIN (FileBin, DataBIN) - Base64 байтов */
142
+ map.set(key, this.binBase64 && typeof value === "string" && typeof key === "string" && /bin$/i.test(key) ? base64ToBytes(value) : value);
143
+ this.skip();
144
+ if (this.peek() === ",") {
145
+ this.pos++;
146
+ continue;
147
+ }
148
+ if (close ? this.peek() !== close : this.pos < this.text.length)
149
+ this.fail(close ? "ожидалась «,» или «}»" : "ожидалась «,»");
150
+ }
151
+ if (close)
152
+ this.pos++;
153
+ return map;
154
+ }
155
+ /* Ключ с двоеточием после него; нет - undefined (позиция не восстанавливается). В кавычках - строка, без - по виду («1» - число). В корне простой ключ требует пробел после «:» */
156
+ tryKey(atRoot) {
157
+ this.skip();
158
+ const char = this.peek();
159
+ let key;
160
+ if (char === '"' || char === "'") {
161
+ try {
162
+ key = this.quoted();
163
+ }
164
+ catch {
165
+ return undefined;
166
+ }
167
+ this.skip();
168
+ }
169
+ else {
170
+ const start = this.pos;
171
+ while (this.pos < this.text.length && !/[:,[\]{}]/.test(this.peek()))
172
+ this.pos++;
173
+ const token = this.text.slice(start, this.pos).trim();
174
+ if (!token || token.startsWith("h'"))
175
+ return undefined;
176
+ if (atRoot && this.peek() === ":" && this.pos + 1 < this.text.length && !/[\s,]/.test(this.text[this.pos + 1]))
177
+ return undefined;
178
+ key = resolvePlain(token);
179
+ }
180
+ if (this.peek() !== ":")
181
+ return undefined;
182
+ this.pos++;
183
+ return key;
184
+ }
185
+ value() {
186
+ this.skip();
187
+ const char = this.peek();
188
+ if (char === undefined)
189
+ this.fail("нет значения");
190
+ if (char === "{") {
191
+ this.pos++;
192
+ return this.entries("}");
193
+ }
194
+ if (char === "[") {
195
+ this.pos++;
196
+ const list = [];
197
+ for (;;) {
198
+ this.skip();
199
+ if (this.peek() === "]")
200
+ break;
201
+ list.push(this.value());
202
+ this.skip();
203
+ if (this.peek() === ",") {
204
+ this.pos++;
205
+ continue;
206
+ }
207
+ if (this.peek() !== "]")
208
+ this.fail("ожидалась «,» или «]»");
209
+ }
210
+ this.pos++;
211
+ return list;
212
+ }
213
+ if (char === '"' || char === "'")
214
+ return this.quoted();
215
+ if (char === "h" && this.text[this.pos + 1] === "'") {
216
+ const end = this.text.indexOf("'", this.pos + 2);
217
+ if (end < 0)
218
+ this.fail("не закрыта h'..'");
219
+ const bytes = hexToBytes(this.text.slice(this.pos + 2, end));
220
+ if (!bytes)
221
+ this.fail(`h'..': нужны HEX-цифры парами`);
222
+ this.pos = end + 1;
223
+ return bytes;
224
+ }
225
+ if (char === "}" || char === "]" || char === ",")
226
+ this.fail(`неожиданный «${char}»`);
227
+ return this.plainScalar();
228
+ }
229
+ /* "..." - экранирование как в JSON, '...' - кавычка удваивается */
230
+ quoted() {
231
+ const open = this.peek();
232
+ const start = this.pos;
233
+ this.pos++;
234
+ if (open === "'") {
235
+ let out = "";
236
+ for (;;) {
237
+ if (this.pos >= this.text.length)
238
+ this.fail("не закрыта строка в кавычках");
239
+ const char = this.text[this.pos++];
240
+ if (char !== "'")
241
+ out += char;
242
+ else if (this.peek() === "'") {
243
+ out += "'";
244
+ this.pos++;
245
+ }
246
+ else
247
+ return out;
248
+ }
249
+ }
250
+ while (this.pos < this.text.length && this.peek() !== '"')
251
+ this.pos += this.peek() === "\\" ? 2 : 1;
252
+ if (this.pos >= this.text.length) {
253
+ this.pos = start;
254
+ this.fail("не закрыта строка в кавычках");
255
+ }
256
+ this.pos++;
257
+ try {
258
+ return JSON.parse(this.text.slice(start, this.pos));
259
+ }
260
+ catch {
261
+ this.pos = start;
262
+ return this.fail("неверное экранирование в строке");
263
+ }
264
+ }
265
+ /* Простое значение до «,» или скобки */
266
+ plainScalar() {
267
+ const start = this.pos;
268
+ while (this.pos < this.text.length && !/[,[\]{}]/.test(this.peek()))
269
+ this.pos++;
270
+ return resolvePlain(this.text.slice(start, this.pos).trim());
271
+ }
272
+ }
273
+ /* Простое значение по виду: число, true/false, null, .inf/.nan, остальное - строка */
274
+ const resolvePlain = (token) => {
275
+ if (/^(?:null|Null|NULL|~)$/.test(token))
276
+ return null;
277
+ if (/^(?:true|True|TRUE)$/.test(token))
278
+ return true;
279
+ if (/^(?:false|False|FALSE)$/.test(token))
280
+ return false;
281
+ if (/^[-+]?\.(?:inf|Inf|INF)$/.test(token))
282
+ return token.startsWith("-") ? -Infinity : Infinity;
283
+ if (/^\.(?:nan|NaN|NAN)$/.test(token))
284
+ return NaN;
285
+ if (NUMBER.test(token)) {
286
+ /* Целое вне safe integer - bigint (uint64 устройства) */
287
+ if (/^[-+]?\d+$/.test(token) && !Number.isSafeInteger(Number(token)))
288
+ return BigInt(token);
289
+ return Number(token);
290
+ }
291
+ return token;
292
+ };
293
+ /* Поток YAML в байты CBOR; binBase64 - строки под ключами на BIN как Base64 байтов (так читается JSON); ошибка - с причиной и позицией */
294
+ export const yamlFlowToCbor = (text, binBase64 = false) => encodeCbor(new FlowParser(text, binBase64).root());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poe-svelte-ui-lib",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Oleg-Perevyshin/ElementsUI.git"
@@ -35,7 +35,7 @@
35
35
  "types": "./dist/protocols/index.d.ts",
36
36
  "default": "./dist/protocols/index.js"
37
37
  },
38
- "./protocols/dictionary.yaml": "./dist/protocols/dictionary.yaml",
38
+ "./dictionaries/*": "./dist/dictionaries/*",
39
39
  "./constructor": {
40
40
  "types": "./dist/constructor.d.ts",
41
41
  "svelte": "./dist/constructor.js"