beresta 0.0.0-stage → 2.1.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -2
  3. package/examples/demo.mts +49 -0
  4. package/lib/errors.js +59 -0
  5. package/lib/factory.js +50 -0
  6. package/lib/flags.js +49 -0
  7. package/lib/index.d.ts +228 -0
  8. package/lib/index.js +38 -0
  9. package/lib/internal/bytes.js +35 -0
  10. package/lib/internal/keys.js +24 -0
  11. package/lib/internal/mixin.js +30 -0
  12. package/lib/internal/native.js +83 -0
  13. package/lib/internal/release.js +44 -0
  14. package/lib/languages.js +70 -0
  15. package/lib/nodes/document.js +57 -0
  16. package/lib/nodes/document_content.js +48 -0
  17. package/lib/nodes/element.js +55 -0
  18. package/lib/nodes/element_attributes.js +38 -0
  19. package/lib/nodes/node.js +25 -0
  20. package/lib/nodes/node_base.js +58 -0
  21. package/lib/nodes/node_children.js +49 -0
  22. package/lib/nodes/node_content.js +47 -0
  23. package/lib/nodes/node_editing.js +48 -0
  24. package/lib/nodes/node_navigation.js +46 -0
  25. package/lib/nodes/node_structure.js +51 -0
  26. package/lib/nodes/registry.js +121 -0
  27. package/lib/nodes/wrapping.js +55 -0
  28. package/lib/schema/diagnostics.js +50 -0
  29. package/lib/schema/schema.js +66 -0
  30. package/lib/schema/schema_lifecycle.js +35 -0
  31. package/lib/schema/schema_streaming.js +45 -0
  32. package/lib/xpath/xpath.js +68 -0
  33. package/lib/xpath/xpath_context.js +33 -0
  34. package/lib/xpath/xpath_evaluation.js +69 -0
  35. package/lib/xpath/xpath_scalars.js +34 -0
  36. package/native/linux-aarch64/beresta.node +0 -0
  37. package/native/linux-x86_64/beresta.node +0 -0
  38. package/native/macos-aarch64/beresta.node +0 -0
  39. package/native/macos-x86_64/beresta.node +0 -0
  40. package/native/windows-aarch64/beresta.node +0 -0
  41. package/native/windows-x86_64/beresta.node +0 -0
  42. package/package.json +37 -4
@@ -0,0 +1,83 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Поиск и загрузка нативного аддона «Берёсты» (beresta.node).
5
+ * Порядок поиска (первый найденный файл побеждает):
6
+ * 1. переменная окружения BERESTA_NODE_ADDON — явный путь к файлу;
7
+ * 2. папка пакета native/<os>-<arch>/ — туда бинарник кладут
8
+ * CMake (-DBERESTA_BUILD_NODE=ON) и Makefile (make NODE=1).
9
+ * Имена ОС и архитектуры совпадают с CMake, Makefile и остальными обёртками:
10
+ * windows / linux / macos и x86_64 / aarch64 / x86.
11
+ * Модуль загружается один раз (кэш require — паттерн Singleton).
12
+ *
13
+ * Finding and loading the Beresta native addon (beresta.node).
14
+ * Lookup order (the first file found wins):
15
+ * 1. the BERESTA_NODE_ADDON environment variable — an explicit file path;
16
+ * 2. the package folder native/<os>-<arch>/ — the binary is put there by
17
+ * CMake (-DBERESTA_BUILD_NODE=ON) and the Makefile (make NODE=1).
18
+ * The OS and architecture names match CMake, the Makefile and the other bindings:
19
+ * windows / linux / macos and x86_64 / aarch64 / x86.
20
+ * The module is loaded once (the require cache — the Singleton pattern).
21
+ */
22
+
23
+ const fs = require('node:fs');
24
+ const path = require('node:path');
25
+ const { BerestaError, BerestaLoadError } = require('../errors.js');
26
+
27
+ // Имена ОС Node.js -> имена папок / Node.js OS names -> folder names
28
+ const OS_NAMES = Object.freeze({ win32: 'windows', linux: 'linux', darwin: 'macos' });
29
+
30
+ // Имена архитектур Node.js -> имена папок / Node.js architecture names -> folder names
31
+ const ARCH_NAMES = Object.freeze({ x64: 'x86_64', arm64: 'aarch64', ia32: 'x86' });
32
+
33
+ // Имя платформы вида windows-x86_64 (имя папки в native/)
34
+ // The platform name like windows-x86_64 (the folder name in native/)
35
+ function platformName()
36
+ {
37
+ const os = OS_NAMES[process.platform] || process.platform;
38
+ const arch = ARCH_NAMES[process.arch] || process.arch;
39
+
40
+ return os + '-' + arch;
41
+ }
42
+
43
+ // Кандидаты в порядке приоритета / Candidates in priority order
44
+ function candidates()
45
+ {
46
+ const result = [];
47
+
48
+ if (process.env.BERESTA_NODE_ADDON)
49
+ result.push(path.resolve(process.env.BERESTA_NODE_ADDON));
50
+ result.push(path.join(__dirname, '..', '..', 'native', platformName(), 'beresta.node'));
51
+ return result;
52
+ }
53
+
54
+ /*
55
+ * Загрузка аддона и передача ему класса ошибки: дальше аддон бросает
56
+ * BerestaError сам. Аддон без функции init значит, что файл — не
57
+ * аддон «Берёсты» или Node-API в процессе недоступен.
58
+ *
59
+ * Loads the addon and passes the error class to it: from then on the addon
60
+ * throws BerestaError itself. An addon without the init function means that
61
+ * the file is not a Beresta addon or Node-API is unavailable in the process.
62
+ */
63
+ function loadNative()
64
+ {
65
+ const tried = candidates();
66
+
67
+ for (const file of tried)
68
+ {
69
+ if (!fs.existsSync(file))
70
+ continue;
71
+ const native = require(file);
72
+ if (typeof native.init !== 'function')
73
+ throw new BerestaLoadError('Аддон не зарегистрировал функции Node-API / '
74
+ + 'The addon did not register its Node-API functions: ' + file);
75
+ native.init(BerestaError);
76
+ return native;
77
+ }
78
+ throw new BerestaLoadError('Нативный аддон «Берёсты» для ' + platformName() + ' не найден / '
79
+ + 'The Beresta native addon for ' + platformName() + ' was not found: ' + tried.join(', ')
80
+ + '. Соберите его / Build it: make NODE=1 или / or cmake -DBERESTA_BUILD_NODE=ON');
81
+ }
82
+
83
+ module.exports = { native: loadNative(), platformName };
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Освобождение нативных объектов (документ, XPath-выражение, схема).
5
+ * Основной путь — явный close() или `using` (Symbol.dispose). Страховка —
6
+ * FinalizationRegistry: если объект забыли закрыть, нативная память всё
7
+ * равно освободится, когда сборщик мусора удалит обёртку. В реестре хранится
8
+ * только имя функции и дескриптор, а не сама обёртка: иначе она никогда
9
+ * не стала бы недостижимой. После close() запись снимается — двойного
10
+ * освобождения не бывает.
11
+ *
12
+ * Releasing native objects (a document, an XPath expression, a schema).
13
+ * The main path is an explicit close() or `using` (Symbol.dispose). The safety
14
+ * net is FinalizationRegistry: if an object was not closed, the native memory
15
+ * is still freed when the garbage collector removes the wrapper. The registry
16
+ * keeps only the function name and the handle, not the wrapper itself:
17
+ * otherwise it would never become unreachable. After close() the entry is
18
+ * removed — a double free never happens.
19
+ */
20
+
21
+ const { native } = require('./native.js');
22
+
23
+ // Освобождение по записи реестра / Releasing by a registry entry
24
+ function releaseHandle(held)
25
+ {
26
+ native[held.free](held.handle);
27
+ }
28
+
29
+ const registry = new FinalizationRegistry(releaseHandle);
30
+
31
+ // Владелец будет освобождён функцией free при сборке мусора / The owner will be freed by free on garbage collection
32
+ function track(owner, free, handle)
33
+ {
34
+ registry.register(owner, { free, handle }, owner);
35
+ }
36
+
37
+ // Явное освобождение: запись снимается, затем вызывается free / An explicit release: the entry is removed, then free is called
38
+ function release(owner, free, handle)
39
+ {
40
+ registry.unregister(owner);
41
+ native[free](handle);
42
+ }
43
+
44
+ module.exports = { track, release };
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Языки сообщений. Язык общий для всего процесса: его смена сразу меняет
5
+ * тексты ошибок ядра и сообщения самой обёртки. Коды ошибок (PARSE_ERROR...)
6
+ * от языка не зависят.
7
+ *
8
+ * Message languages. The language is shared by the whole process: changing it
9
+ * changes the core error texts and the messages of the binding itself at once.
10
+ * Error codes (PARSE_ERROR...) do not depend on the language.
11
+ */
12
+
13
+ const { native } = require('./internal/native.js');
14
+
15
+ // Номера сообщений обёрток (beresta_message) / Binding message numbers (beresta_message)
16
+ const Messages = Object.freeze({
17
+ DOCUMENT_CLOSED: 1,
18
+ XPATH_CLOSED: 2,
19
+ SCHEMA_CLOSED: 3,
20
+ NATIVE_CALL_FAILED: 4,
21
+ UNKNOWN_NODE_TYPE: 5,
22
+ INVALID_ARGUMENT: 6,
23
+ NO_FILE_SYSTEM: 7
24
+ });
25
+
26
+ // Смена языка; неизвестный код — BerestaError(INVALID_ARGUMENT) / Switches the language; an unknown code is BerestaError(INVALID_ARGUMENT)
27
+ function setLanguage(code)
28
+ {
29
+ native.set_language(code);
30
+ }
31
+
32
+ // Код текущего языка, например "ru" / The current language code, for example "ru"
33
+ function language()
34
+ {
35
+ return native.language();
36
+ }
37
+
38
+ // Все языки библиотеки: ["ru", "en", ...] / All languages of the library: ["ru", "en", ...]
39
+ function languages()
40
+ {
41
+ return native.languages().split(',');
42
+ }
43
+
44
+ /*
45
+ * Сообщение обёртки на текущем языке; метки {0}, {1}... заменяются
46
+ * аргументами по номеру (метка без аргумента остаётся видна как есть).
47
+ *
48
+ * A binding message in the current language; the {0}, {1}... placeholders are
49
+ * replaced with the arguments by number (a placeholder without an argument stays visible as is).
50
+ */
51
+ function messageText(message, ...values)
52
+ {
53
+ const template = native.message_text(message);
54
+ let result = '';
55
+ let position = 0;
56
+
57
+ for (const match of template.matchAll(/\{(\d+)\}/g))
58
+ {
59
+ const index = Number(match[1]);
60
+ result += template.slice(position, match.index);
61
+ if (index < values.length)
62
+ result += String(values[index]);
63
+ else
64
+ result += match[0];
65
+ position = match.index + match[0].length;
66
+ }
67
+ return result + template.slice(position);
68
+ }
69
+
70
+ module.exports = { Messages, setLanguage, language, languages, messageText };
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+
3
+ const { applyMixins } = require('../internal/mixin.js');
4
+ const { HANDLE, OWNER, REGISTRY } = require('../internal/keys.js');
5
+ const { track, release } = require('../internal/release.js');
6
+ const { XmlNode } = require('./node.js');
7
+ const { DocumentContent } = require('./document_content.js');
8
+ const { NodeRegistry } = require('./registry.js');
9
+
10
+ /**
11
+ * XML-документ — владелец всего дерева узлов в нативной памяти. Документ
12
+ * сам является узлом (к нему можно добавлять детей). Память освобождается
13
+ * детерминированно — close() или `using` — либо, если про это забыли,
14
+ * при сборке мусора (FinalizationRegistry, см. release.js).
15
+ *
16
+ * An XML document — the owner of the whole node tree in native memory. The
17
+ * document is itself a node (children can be appended to it). The memory is
18
+ * freed deterministically — close() or `using` — or, if that was forgotten,
19
+ * on garbage collection (FinalizationRegistry, see release.js).
20
+ */
21
+ class XmlDocument extends XmlNode
22
+ {
23
+ /** Создаётся фабриками parse / parseFile / createDocument. / Created by the parse / parseFile / createDocument factories. */
24
+ constructor(handle)
25
+ {
26
+ super(null, handle);
27
+ this[OWNER] = this;
28
+ this[REGISTRY] = new NodeRegistry();
29
+ track(this, 'document_free', handle);
30
+ }
31
+
32
+ /** true после close(): память документа уже освобождена. / true after close(): the document memory is already freed. */
33
+ get closed()
34
+ {
35
+ return this[HANDLE] === null;
36
+ }
37
+
38
+ /** Освобождение нативной памяти; повторный вызов безопасен. / Releases the native memory; calling it again is safe. */
39
+ close()
40
+ {
41
+ if (this[HANDLE] === null)
42
+ return;
43
+ const handle = this[HANDLE];
44
+ this[HANDLE] = null;
45
+ release(this, 'document_free', handle);
46
+ }
47
+
48
+ /** Поддержка `using document = beresta.parse(...)`. / Support for `using document = beresta.parse(...)`. */
49
+ [Symbol.dispose]()
50
+ {
51
+ this.close();
52
+ }
53
+ }
54
+
55
+ applyMixins(XmlDocument, DocumentContent);
56
+
57
+ module.exports = { XmlDocument };
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ const { native } = require('../internal/native.js');
4
+ const { WriteFlags } = require('../flags.js');
5
+ const { wrap } = require('./wrapping.js');
6
+
7
+ /**
8
+ * Примесь документа: корень, поиск по ID, копия, запись в файл.
9
+ * A document mixin: the root, lookup by ID, a copy, writing to a file.
10
+ */
11
+ class DocumentContent
12
+ {
13
+ /** Корневой элемент или null. / The root element or null. */
14
+ get root()
15
+ {
16
+ return wrap(this, native.document_root(this.handle));
17
+ }
18
+
19
+ /** Элемент с атрибутом типа ID (по DTD) или xml:id; null, если не найден.
20
+ * An element with an ID-typed attribute (by DTD) or xml:id; null if not found. */
21
+ elementById(id)
22
+ {
23
+ return wrap(this, native.document_element_by_id(this.handle, id));
24
+ }
25
+
26
+ /** Независимая глубокая копия; её тоже нужно закрыть. / An independent deep copy; it must be closed too. */
27
+ clone()
28
+ {
29
+ return new this.constructor(native.document_clone(this.handle));
30
+ }
31
+
32
+ /**
33
+ * Запись в файл. options.flags — WriteFlags, options.encoding — имя
34
+ * кодировки (по умолчанию UTF-8), например "windows-1251".
35
+ *
36
+ * Writes to a file. options.flags are WriteFlags, options.encoding is an
37
+ * encoding name (UTF-8 by default), for example "windows-1251".
38
+ */
39
+ save(path, options = {})
40
+ {
41
+ const flags = options.flags ?? WriteFlags.DEFAULT;
42
+ const encoding = options.encoding ?? null;
43
+
44
+ native.document_save(this.handle, String(path), flags, encoding);
45
+ }
46
+ }
47
+
48
+ module.exports = { DocumentContent };
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ const { native } = require('../internal/native.js');
4
+ const { applyMixins } = require('../internal/mixin.js');
5
+ const { XmlNode } = require('./node.js');
6
+ const { ElementAttributes } = require('./element_attributes.js');
7
+ const { registerNodeClasses } = require('./wrapping.js');
8
+
9
+ /**
10
+ * Элемент XML: узел с именем, атрибутами и пространством имён.
11
+ * An XML element: a node with a name, attributes and a namespace.
12
+ */
13
+ class XmlElement extends XmlNode
14
+ {
15
+ /** Имя без префикса: у <s:item> — "item". / The name without a prefix: "item" for <s:item>. */
16
+ get localName()
17
+ {
18
+ return native.element_local_name(this.handle);
19
+ }
20
+
21
+ /** URI пространства имён или null, если элемент вне пространств имён.
22
+ * The namespace URI or null if the element is in no namespace. */
23
+ get namespaceUri()
24
+ {
25
+ return native.element_namespace_uri(this.handle);
26
+ }
27
+
28
+ /**
29
+ * Снимок всех атрибутов { имя: значение } в порядке документа. Свойства
30
+ * задаются через defineProperty: имя вроде "__proto__" не изменит прототип.
31
+ *
32
+ * A snapshot of all attributes { name: value } in document order. The properties
33
+ * are set through defineProperty: a name like "__proto__" will not change the prototype.
34
+ */
35
+ get attributes()
36
+ {
37
+ const handle = this.handle;
38
+ const count = native.element_attribute_count(handle);
39
+ const result = {};
40
+
41
+ for (let index = 0; index < count; ++index)
42
+ {
43
+ Object.defineProperty(result, native.element_attribute_name(handle, index), {
44
+ value: native.element_attribute_value(handle, index),
45
+ enumerable: true, writable: true, configurable: true
46
+ });
47
+ }
48
+ return result;
49
+ }
50
+ }
51
+
52
+ applyMixins(XmlElement, ElementAttributes);
53
+ registerNodeClasses(XmlNode, XmlElement);
54
+
55
+ module.exports = { XmlElement };
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ const { native } = require('../internal/native.js');
4
+
5
+ /**
6
+ * Примесь элемента: чтение и запись атрибутов по имени.
7
+ * An element mixin: reading and writing attributes by name.
8
+ */
9
+ class ElementAttributes
10
+ {
11
+ /** Значение атрибута или null, если атрибута нет. / The attribute value or null if there is no such attribute. */
12
+ getAttribute(name)
13
+ {
14
+ return native.element_get_attribute(this.handle, name);
15
+ }
16
+
17
+ /** Установка или замена значения; недопустимое имя — BerestaError(INVALID_NAME).
18
+ * Sets or replaces the value; an invalid name is BerestaError(INVALID_NAME). */
19
+ setAttribute(name, value)
20
+ {
21
+ native.element_set_attribute(this.handle, name, String(value));
22
+ return this;
23
+ }
24
+
25
+ /** Есть ли атрибут с таким именем. / Whether there is an attribute with this name. */
26
+ hasAttribute(name)
27
+ {
28
+ return native.element_has_attribute(this.handle, name);
29
+ }
30
+
31
+ /** true — атрибут был и удалён, false — его не было. / true means it existed and was removed, false means it did not exist. */
32
+ removeAttribute(name)
33
+ {
34
+ return native.element_remove_attribute(this.handle, name);
35
+ }
36
+ }
37
+
38
+ module.exports = { ElementAttributes };
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+
3
+ const { applyMixins } = require('../internal/mixin.js');
4
+ const { NodeBase } = require('./node_base.js');
5
+ const { NodeContent } = require('./node_content.js');
6
+ const { NodeNavigation } = require('./node_navigation.js');
7
+ const { NodeChildren } = require('./node_children.js');
8
+ const { NodeEditing } = require('./node_editing.js');
9
+ const { NodeStructure } = require('./node_structure.js');
10
+
11
+ /**
12
+ * Узел дерева документа. Класс лишь собирает части: основу (дескриптор и
13
+ * документ) и примеси содержимого, навигации, детей, изменения и структуры.
14
+ *
15
+ * A node of the document tree. The class only combines the parts: the base
16
+ * (the handle and the document) and the mixins of content, navigation,
17
+ * children, editing and structure.
18
+ */
19
+ class XmlNode extends NodeBase
20
+ {
21
+ }
22
+
23
+ applyMixins(XmlNode, NodeContent, NodeNavigation, NodeChildren, NodeEditing, NodeStructure);
24
+
25
+ module.exports = { XmlNode };
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+
3
+ const { HANDLE, OWNER } = require('../internal/keys.js');
4
+ const { BerestaClosedError } = require('../errors.js');
5
+ const { messageText, Messages } = require('../languages.js');
6
+
7
+ /**
8
+ * Основа узла: нативный дескриптор и документ-владелец. Ссылка на
9
+ * документ решает две задачи: пока жив узел, документ не соберёт сборщик
10
+ * мусора, а после document.close() обращение к узлу даёт понятную ошибку
11
+ * вместо падения процесса.
12
+ *
13
+ * The base of a node: the native handle and the owner document. The reference
14
+ * to the document solves two problems: while the node is alive, the document is
15
+ * not garbage-collected, and after document.close() any access to the node gives
16
+ * a clear error instead of a process crash.
17
+ */
18
+ class NodeBase
19
+ {
20
+ constructor(document, handle)
21
+ {
22
+ this[OWNER] = document;
23
+ this[HANDLE] = handle;
24
+ }
25
+
26
+ /** Дескриптор для вызова аддона; бросает BerestaClosedError, если документ закрыт.
27
+ * The handle for addon calls; throws BerestaClosedError if the document is closed. */
28
+ get handle()
29
+ {
30
+ if (this[OWNER].closed)
31
+ throw new BerestaClosedError(messageText(Messages.DOCUMENT_CLOSED));
32
+ return this[HANDLE];
33
+ }
34
+
35
+ /** Документ, которому принадлежит узел. / The document the node belongs to. */
36
+ get document()
37
+ {
38
+ return this[OWNER];
39
+ }
40
+
41
+ /** Указывают ли две обёртки на один и тот же узел (как isSameNode в DOM).
42
+ * Whether two wrappers point to the same node (like isSameNode in DOM). */
43
+ isSameNode(other)
44
+ {
45
+ return other instanceof NodeBase && other[HANDLE] === this[HANDLE] && other[HANDLE] !== null;
46
+ }
47
+
48
+ /** Короткое представление для console.log и util.inspect: «XmlElement <item>».
49
+ * A short representation for console.log and util.inspect: "XmlElement <item>". */
50
+ [Symbol.for('nodejs.util.inspect.custom')]()
51
+ {
52
+ if (this[OWNER].closed)
53
+ return this.constructor.name + ' (closed)';
54
+ return this.constructor.name + ' <' + this.name + '>';
55
+ }
56
+ }
57
+
58
+ module.exports = { NodeBase };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ const { native } = require('../internal/native.js');
4
+ const { wrap } = require('./wrapping.js');
5
+
6
+ /**
7
+ * Примесь: доступ к детям — по индексу, массивом и перебором for...of.
8
+ * Mixin: access to children — by index, as an array and with for...of.
9
+ */
10
+ class NodeChildren
11
+ {
12
+ /** Число детей (0 у листовых узлов). / The number of children (0 for leaf nodes). */
13
+ get childCount()
14
+ {
15
+ return native.node_child_count(this.handle);
16
+ }
17
+
18
+ /** Ребёнок по индексу; отрицательный индекс — с конца, как у Array.prototype.at.
19
+ * A child by index; a negative index counts from the end, as in Array.prototype.at. */
20
+ child(index)
21
+ {
22
+ let position = Math.trunc(index);
23
+
24
+ if (position < 0)
25
+ position += this.childCount;
26
+ return wrap(this.document, native.node_child(this.handle, position));
27
+ }
28
+
29
+ /** Снимок списка детей: последующие изменения дерева в нём не видны.
30
+ * A snapshot of the child list: later tree changes are not visible in it. */
31
+ get children()
32
+ {
33
+ return Array.from(this);
34
+ }
35
+
36
+ /** Перебор детей через соседей — O(1) на шаг. / Iterates children through siblings — O(1) per step. */
37
+ *[Symbol.iterator]()
38
+ {
39
+ let current = this.firstChild;
40
+
41
+ while (current !== null)
42
+ {
43
+ yield current;
44
+ current = current.nextSibling;
45
+ }
46
+ }
47
+ }
48
+
49
+ module.exports = { NodeChildren };
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+
3
+ const { native } = require('../internal/native.js');
4
+ const { WriteFlags } = require('../flags.js');
5
+
6
+ /**
7
+ * Примесь: тип, имя, текст и сериализация узла.
8
+ * Mixin: the node type, name, text and serialization.
9
+ */
10
+ class NodeContent
11
+ {
12
+ /** Тип узла (значение NodeType). / The node type (a NodeType value). */
13
+ get type()
14
+ {
15
+ return native.node_type(this.handle);
16
+ }
17
+
18
+ /** Имя по соглашению DOM: тег, цель PI, "#text", "#comment"...
19
+ * The name by the DOM convention: a tag, a PI target, "#text", "#comment"... */
20
+ get name()
21
+ {
22
+ return native.node_name(this.handle);
23
+ }
24
+
25
+ /** Текстовое содержимое (у элемента — весь текст потомков).
26
+ * The text content (for an element — all text of its descendants). */
27
+ get text()
28
+ {
29
+ return native.node_text(this.handle);
30
+ }
31
+
32
+ /** У элемента все дети заменяются одним текстовым узлом.
33
+ * For an element all children are replaced with one text node. */
34
+ set text(value)
35
+ {
36
+ native.node_set_text(this.handle, String(value));
37
+ }
38
+
39
+ /** Сериализация узла с потомками; по умолчанию — без единого лишнего пробела.
40
+ * Serializes the node with its descendants; by default — without a single extra space. */
41
+ toXml(flags = WriteFlags.DEFAULT)
42
+ {
43
+ return native.node_to_string(this.handle, flags);
44
+ }
45
+ }
46
+
47
+ module.exports = { NodeContent };
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ const { native } = require('../internal/native.js');
4
+ const { wrap } = require('./wrapping.js');
5
+
6
+ /**
7
+ * Примесь: добавление новых узлов в конец детей. Каждый метод возвращает
8
+ * созданный узел — удобно строить дерево цепочкой:
9
+ * root.appendElement('item').appendText('Чай').
10
+ *
11
+ * Mixin: appending new nodes to the end of the children. Each method returns
12
+ * the created node — convenient for building a tree in a chain:
13
+ * root.appendElement('item').appendText('Чай').
14
+ */
15
+ class NodeEditing
16
+ {
17
+ /** Новый элемент; у пустого документа он становится корнем. / A new element; in an empty document it becomes the root. */
18
+ appendElement(name)
19
+ {
20
+ return wrap(this.document, native.node_append_element(this.handle, name));
21
+ }
22
+
23
+ /** Текстовый узел (спецсимволы экранируются при выводе). / A text node (special characters are escaped on output). */
24
+ appendText(text)
25
+ {
26
+ return wrap(this.document, native.node_append_text(this.handle, text));
27
+ }
28
+
29
+ /** Комментарий <!--text-->. / A comment <!--text-->. */
30
+ appendComment(text)
31
+ {
32
+ return wrap(this.document, native.node_append_comment(this.handle, text));
33
+ }
34
+
35
+ /** Секция <![CDATA[text]]>. / A <![CDATA[text]]> section. */
36
+ appendCData(text)
37
+ {
38
+ return wrap(this.document, native.node_append_cdata(this.handle, text));
39
+ }
40
+
41
+ /** Инструкция обработки <?target data?>; data необязательна. / A processing instruction <?target data?>; data is optional. */
42
+ appendProcessingInstruction(target, data = null)
43
+ {
44
+ return wrap(this.document, native.node_append_pi(this.handle, target, data));
45
+ }
46
+ }
47
+
48
+ module.exports = { NodeEditing };
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ const { native } = require('../internal/native.js');
4
+ const { wrap } = require('./wrapping.js');
5
+
6
+ /**
7
+ * Примесь: навигация по дереву. Соседи и родитель находятся за O(1):
8
+ * ядро хранит индекс узла у родителя. Отсутствующий сосед — null.
9
+ *
10
+ * Mixin: tree navigation. Siblings and the parent are found in O(1):
11
+ * the core stores the node index in its parent. A missing sibling is null.
12
+ */
13
+ class NodeNavigation
14
+ {
15
+ /** Родитель (у корня — документ, у документа — null). / The parent (the document for the root, null for the document). */
16
+ get parent()
17
+ {
18
+ return wrap(this.document, native.node_parent(this.handle));
19
+ }
20
+
21
+ /** Первый ребёнок или null. / The first child or null. */
22
+ get firstChild()
23
+ {
24
+ return wrap(this.document, native.node_first_child(this.handle));
25
+ }
26
+
27
+ /** Последний ребёнок или null. / The last child or null. */
28
+ get lastChild()
29
+ {
30
+ return wrap(this.document, native.node_last_child(this.handle));
31
+ }
32
+
33
+ /** Следующий сосед или null. / The next sibling or null. */
34
+ get nextSibling()
35
+ {
36
+ return wrap(this.document, native.node_next_sibling(this.handle));
37
+ }
38
+
39
+ /** Предыдущий сосед или null. / The previous sibling or null. */
40
+ get previousSibling()
41
+ {
42
+ return wrap(this.document, native.node_previous_sibling(this.handle));
43
+ }
44
+ }
45
+
46
+ module.exports = { NodeNavigation };