node-opcua-client-dynamic-extension-object 2.64.1 → 2.66.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 (32) hide show
  1. package/dist/convert_data_type_definition_to_structuretype_schema.d.ts +12 -12
  2. package/dist/convert_data_type_definition_to_structuretype_schema.js +331 -327
  3. package/dist/convert_data_type_definition_to_structuretype_schema.js.map +1 -1
  4. package/dist/extra_data_type_manager.d.ts +16 -16
  5. package/dist/extra_data_type_manager.js +75 -75
  6. package/dist/get_extension_object_constructor.d.ts +7 -7
  7. package/dist/get_extension_object_constructor.js +37 -37
  8. package/dist/get_extra_data_type_manager.d.ts +3 -3
  9. package/dist/get_extra_data_type_manager.js +51 -51
  10. package/dist/index.d.ts +11 -11
  11. package/dist/index.js +27 -23
  12. package/dist/index.js.map +1 -1
  13. package/dist/populate_data_type_manager.d.ts +3 -3
  14. package/dist/populate_data_type_manager.js +25 -25
  15. package/dist/private/find_encodings.d.ts +4 -4
  16. package/dist/private/find_encodings.js +55 -55
  17. package/dist/private/populate_data_type_manager_103.d.ts +9 -9
  18. package/dist/private/populate_data_type_manager_103.js +601 -601
  19. package/dist/private/populate_data_type_manager_104.d.ts +9 -9
  20. package/dist/private/populate_data_type_manager_104.js +145 -145
  21. package/dist/promote_opaque_structure.d.ts +6 -6
  22. package/dist/promote_opaque_structure.js +41 -41
  23. package/dist/resolve_dynamic_extension_object.d.ts +4 -4
  24. package/dist/resolve_dynamic_extension_object.js +105 -105
  25. package/package.json +19 -19
  26. package/source/convert_data_type_definition_to_structuretype_schema.ts +31 -14
  27. package/dist/client_dynamic_extension_object.d.ts +0 -25
  28. package/dist/client_dynamic_extension_object.js +0 -1058
  29. package/dist/client_dynamic_extension_object.js.map +0 -1
  30. package/dist/convert_data_type_definition_to_structure_type_schema.d.ts +0 -1
  31. package/dist/convert_data_type_definition_to_structure_type_schema.js +0 -3
  32. package/dist/convert_data_type_definition_to_structure_type_schema.js.map +0 -1
@@ -1,1058 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.getExtensionObjectConstructor = exports.extractNamespaceDataType = exports.convertDataTypeDefinitionToStructureTypeSchema = exports.getDataTypeDefinition = exports.populateDataTypeManager = void 0;
13
- // tslint:disable: no-console
14
- /**
15
- * @module node-opcua-client-dynamic-extension-object
16
- */
17
- const chalk = require("chalk");
18
- const PrettyError = require("pretty-error");
19
- const pe = new PrettyError();
20
- const node_opcua_assert_1 = require("node-opcua-assert");
21
- const node_opcua_data_model_1 = require("node-opcua-data-model");
22
- const node_opcua_debug_1 = require("node-opcua-debug");
23
- const node_opcua_factory_1 = require("node-opcua-factory");
24
- const node_opcua_nodeid_1 = require("node-opcua-nodeid");
25
- const node_opcua_pseudo_session_1 = require("node-opcua-pseudo-session");
26
- const node_opcua_schemas_1 = require("node-opcua-schemas");
27
- const node_opcua_service_browse_1 = require("node-opcua-service-browse");
28
- const node_opcua_service_translate_browse_path_1 = require("node-opcua-service-translate-browse-path");
29
- const node_opcua_status_code_1 = require("node-opcua-status-code");
30
- const node_opcua_types_1 = require("node-opcua-types");
31
- const extra_data_type_manager_1 = require("./extra_data_type_manager");
32
- const doDebug = node_opcua_debug_1.checkDebugFlag(__filename);
33
- const debugLog = node_opcua_debug_1.make_debugLog(__filename);
34
- function _readDeprecatedFlag(session, dataTypeDictionary) {
35
- return __awaiter(this, void 0, void 0, function* () {
36
- const browsePath = node_opcua_service_translate_browse_path_1.makeBrowsePath(dataTypeDictionary, ".Deprecated");
37
- const a = yield session.translateBrowsePath(browsePath);
38
- /* istanbul ignore next */
39
- if (!a.targets || a.targets.length === 0) {
40
- // the server is probably version < 1.04.
41
- debugLog("Cannot find Deprecated property for dataTypeDictionary " + dataTypeDictionary.toString());
42
- return false;
43
- }
44
- const deprecatedFlagNodeId = a.targets[0].targetId;
45
- const dataValue = yield session.read({ nodeId: deprecatedFlagNodeId, attributeId: node_opcua_data_model_1.AttributeIds.Value });
46
- return dataValue.value.value;
47
- });
48
- }
49
- function _readNamespaceUriProperty(session, dataTypeDictionary) {
50
- return __awaiter(this, void 0, void 0, function* () {
51
- const a = yield session.translateBrowsePath(node_opcua_service_translate_browse_path_1.makeBrowsePath(dataTypeDictionary, ".NamespaceUri"));
52
- /* istanbul ignore next */
53
- if (!a.targets || a.targets.length === 0) {
54
- return "??dataTypeDictionary doesn't expose NamespaceUri property??";
55
- }
56
- const namespaceUriProp = a.targets[0].targetId;
57
- const dataValue = yield session.read({ nodeId: namespaceUriProp, attributeId: node_opcua_data_model_1.AttributeIds.Value });
58
- return dataValue.value.value || "<not set>";
59
- });
60
- }
61
- function _getDataTypeDescriptions(session, dataTypeDictionaryNodeId) {
62
- return __awaiter(this, void 0, void 0, function* () {
63
- const nodeToBrowse2 = {
64
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
65
- includeSubtypes: false,
66
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("Variable"),
67
- nodeId: dataTypeDictionaryNodeId,
68
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasComponent"),
69
- // resultMask: makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
70
- resultMask: node_opcua_data_model_1.makeResultMask("NodeId | BrowseName")
71
- };
72
- const result2 = yield node_opcua_pseudo_session_1.browseAll(session, nodeToBrowse2);
73
- result2.references = result2.references || [];
74
- return result2.references.map((r) => ({ nodeId: r.nodeId, browseName: r.browseName }));
75
- });
76
- }
77
- function _enrichWithDescriptionOf(session, dataTypeDescriptions) {
78
- return __awaiter(this, void 0, void 0, function* () {
79
- const nodesToBrowse3 = [];
80
- for (const ref of dataTypeDescriptions) {
81
- ref.browseName.toString();
82
- nodesToBrowse3.push({
83
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
84
- includeSubtypes: false,
85
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("Object"),
86
- nodeId: ref.nodeId.toString(),
87
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasDescription"),
88
- // resultMask: makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
89
- resultMask: node_opcua_data_model_1.makeResultMask("NodeId")
90
- });
91
- }
92
- /* istanbul ignore next */
93
- if (nodesToBrowse3.length === 0) {
94
- return [];
95
- }
96
- const results3 = yield node_opcua_pseudo_session_1.browseAll(session, nodesToBrowse3);
97
- const binaryEncodings = [];
98
- const nodesToBrowseDataType = [];
99
- let i = 0;
100
- for (const result3 of results3) {
101
- const dataTypeDescription = dataTypeDescriptions[i++];
102
- result3.references = result3.references || [];
103
- node_opcua_assert_1.assert(result3.references.length === 1);
104
- for (const ref of result3.references) {
105
- const binaryEncodingNodeId = ref.nodeId;
106
- dataTypeDescription.encodings = dataTypeDescription.encodings || {
107
- binaryEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
108
- dataTypeNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
109
- jsonEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
110
- xmlEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId
111
- };
112
- dataTypeDescription.encodings.binaryEncodingNodeId = binaryEncodingNodeId;
113
- binaryEncodings.push(binaryEncodingNodeId);
114
- nodesToBrowseDataType.push({
115
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
116
- includeSubtypes: false,
117
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("DataType"),
118
- nodeId: ref.nodeId.toString(),
119
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasEncoding"),
120
- // resultMask: makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
121
- resultMask: node_opcua_data_model_1.makeResultMask("NodeId | BrowseName")
122
- });
123
- }
124
- }
125
- const dataTypeNodeIds = [];
126
- if (nodesToBrowseDataType.length > 0) {
127
- const results4 = yield node_opcua_pseudo_session_1.browseAll(session, nodesToBrowseDataType);
128
- i = 0;
129
- for (const result4 of results4) {
130
- result4.references = result4.references || [];
131
- /* istanbul ignore next */
132
- if (result4.references.length !== 1) {
133
- console.log("What's going on ?", result4.toString());
134
- }
135
- for (const ref of result4.references) {
136
- const dataTypeNodeId = ref.nodeId;
137
- dataTypeNodeIds.push(dataTypeNodeId);
138
- const dataTypeDescription = dataTypeDescriptions[i++];
139
- dataTypeDescription.encodings.dataTypeNodeId = dataTypeNodeId;
140
- }
141
- }
142
- }
143
- return dataTypeNodeIds;
144
- });
145
- }
146
- function _findEncodings(session, dataTypeNodeId) {
147
- return __awaiter(this, void 0, void 0, function* () {
148
- const nodeToBrowse = {
149
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
150
- includeSubtypes: true,
151
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("Object"),
152
- nodeId: dataTypeNodeId,
153
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasEncoding"),
154
- resultMask: node_opcua_data_model_1.makeResultMask("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition")
155
- };
156
- const result = yield node_opcua_pseudo_session_1.browseAll(session, nodeToBrowse);
157
- const references = result.references || [];
158
- if (references.length === 0) {
159
- // xx throw new Error("Cannot find encodings on type " + dataTypeNodeId.toString() + " statusCode " + result.statusCode.toString());
160
- }
161
- const encodings = {
162
- dataTypeNodeId,
163
- binaryEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
164
- jsonEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId,
165
- xmlEncodingNodeId: node_opcua_nodeid_1.NodeId.nullNodeId
166
- };
167
- for (const ref of references) {
168
- switch (ref.browseName.name) {
169
- case "Default Binary":
170
- encodings.binaryEncodingNodeId = ref.nodeId;
171
- break;
172
- case "Default XML":
173
- encodings.xmlEncodingNodeId = ref.nodeId;
174
- break;
175
- case "Default JSON":
176
- encodings.jsonEncodingNodeId = ref.nodeId;
177
- break;
178
- default:
179
- console.log(" ignoring encoding ", ref.browseName.toString());
180
- }
181
- }
182
- return encodings;
183
- });
184
- }
185
- function sortStructure(dataTypeDefinitions) {
186
- const dataTypeDefinitionsSorted = [];
187
- const _visited = {};
188
- const _map = {};
189
- for (const d of dataTypeDefinitions) {
190
- _map[d.dataTypeNodeId.toString()] = d;
191
- }
192
- function _visit(d) {
193
- const hash = d.dataTypeNodeId.toString();
194
- if (_visited[hash]) {
195
- return;
196
- }
197
- const bbb = _map[d.dataTypeDefinition.baseDataType.toString()];
198
- if (bbb) {
199
- _visit(bbb);
200
- }
201
- for (const f of d.dataTypeDefinition.fields || []) {
202
- const ddd = _map[f.dataType.toString()];
203
- if (!ddd) {
204
- continue;
205
- }
206
- _visit(ddd);
207
- }
208
- _visited[hash] = d;
209
- dataTypeDefinitionsSorted.push(d);
210
- }
211
- for (const d of dataTypeDefinitions) {
212
- _visit(d);
213
- }
214
- return dataTypeDefinitionsSorted;
215
- }
216
- function _extractDataTypeDictionaryFromDefinition(session, dataTypeDictionaryNodeId, dataTypeFactory) {
217
- return __awaiter(this, void 0, void 0, function* () {
218
- node_opcua_assert_1.assert(dataTypeFactory, "expecting a dataTypeFactory");
219
- const dataTypeDescriptions = yield _getDataTypeDescriptions(session, dataTypeDictionaryNodeId);
220
- const dataTypeNodeIds = yield _enrichWithDescriptionOf(session, dataTypeDescriptions);
221
- // now read DataTypeDefinition attributes of all the dataTypeNodeIds, this will only contains concrete structure
222
- const nodesToRead = dataTypeNodeIds.map((nodeId) => ({
223
- attributeId: node_opcua_data_model_1.AttributeIds.DataTypeDefinition,
224
- nodeId
225
- }));
226
- const cache = {};
227
- const dataValuesWithDataTypeDefinition = nodesToRead.length > 0 ? yield session.read(nodesToRead) : [];
228
- // in some circumstances like Euromap, this assert fails:
229
- // assert(dataValuesWithDataTypeDefinition.length === dataTypeDescriptions.length);
230
- const dataTypeDefinitions = [];
231
- let index = 0;
232
- for (const dataValue of dataValuesWithDataTypeDefinition) {
233
- const dataTypeNodeId = dataTypeNodeIds[index];
234
- const dataTypeDescription = dataTypeDescriptions[index];
235
- /* istanbul ignore else */
236
- if (dataValue.statusCode === node_opcua_status_code_1.StatusCodes.Good) {
237
- const dataTypeDefinition = dataValue.value.value;
238
- if (dataTypeDefinition && dataTypeDefinition instanceof node_opcua_types_1.StructureDefinition) {
239
- const className = dataTypeDescription.browseName.name;
240
- dataTypeDefinitions.push({ className, dataTypeNodeId, dataTypeDefinition });
241
- }
242
- }
243
- else {
244
- debugLog("dataTypeNodeId ", dataTypeNodeId.toString(), " has no DataTypeDescription attribute", dataValue.statusCode.toString());
245
- }
246
- index++;
247
- }
248
- // to do put in logical order
249
- const dataTypeDefinitionsSorted = sortStructure(dataTypeDefinitions);
250
- if (doDebug) {
251
- debugLog("order ", dataTypeDefinitionsSorted.map((a) => a.className + " " + a.dataTypeNodeId).join(" -> "));
252
- }
253
- for (const { className, dataTypeNodeId, dataTypeDefinition } of dataTypeDefinitionsSorted) {
254
- // istanbul ignore next
255
- if (doDebug) {
256
- debugLog(chalk.yellow("--------------------------------------- "), className, dataTypeNodeId.toString());
257
- }
258
- if (dataTypeFactory.hasStructuredType(className)) {
259
- continue; // this structure has already been seen
260
- }
261
- // now fill typeDictionary
262
- try {
263
- const schema = yield convertDataTypeDefinitionToStructureTypeSchema(session, dataTypeNodeId, className, dataTypeDefinition, dataTypeFactory, cache);
264
- // istanbul ignore next
265
- if (doDebug) {
266
- debugLog(chalk.red("Registering "), chalk.cyan(className.padEnd(30, " ")), schema.dataTypeNodeId.toString());
267
- }
268
- const Constructor = node_opcua_schemas_1.createDynamicObjectConstructor(schema, dataTypeFactory);
269
- node_opcua_assert_1.assert(Constructor.schema === schema);
270
- }
271
- catch (err) {
272
- console.log("Constructor verification err: ", err.message);
273
- console.log("For this reason class " + className + " has not been registered");
274
- console.log(err);
275
- }
276
- }
277
- });
278
- }
279
- function _extractNodeIds(session, dataTypeDictionaryNodeId) {
280
- return __awaiter(this, void 0, void 0, function* () {
281
- const map = {};
282
- const dataTypeDescriptions = yield _getDataTypeDescriptions(session, dataTypeDictionaryNodeId);
283
- /* const dataTypeNodeIds = */
284
- yield _enrichWithDescriptionOf(session, dataTypeDescriptions);
285
- for (const dataTypeDescription of dataTypeDescriptions) {
286
- map[dataTypeDescription.browseName.name.toString()] = dataTypeDescription.encodings;
287
- }
288
- return {
289
- getDataTypeAndEncodingId(key) {
290
- return map[key] || null;
291
- }
292
- };
293
- });
294
- }
295
- function _extractDataTypeDictionary(session, d, dataTypeManager) {
296
- return __awaiter(this, void 0, void 0, function* () {
297
- const dataTypeDictionaryNodeId = d.reference.nodeId;
298
- const isDictionaryDeprecated = d.isDictionaryDeprecated; // await _readDeprecatedFlag(session, dataTypeDictionaryNodeId);
299
- const rawSchema = d.rawSchema; // DataValue = await session.read({ nodeId: dataTypeDictionaryNodeId, attributeId: AttributeIds.Value });
300
- const name = yield session.read({ nodeId: dataTypeDictionaryNodeId, attributeId: node_opcua_data_model_1.AttributeIds.BrowseName });
301
- const namespace = yield _readNamespaceUriProperty(session, dataTypeDictionaryNodeId);
302
- if (isDictionaryDeprecated || rawSchema.length === 0) {
303
- debugLog("DataTypeDictionary is deprecated or BSD schema stored in dataValue is null !", chalk.cyan(name.value.value.toString()), "namespace =", namespace);
304
- debugLog("let's use the new way (1.04) and let's crawl all dataTypes exposed by this name space");
305
- // dataType definition in store directly in UADataType under the $definition property
306
- const dataTypeFactory2 = dataTypeManager.getDataTypeFactory(dataTypeDictionaryNodeId.namespace);
307
- if (!dataTypeFactory2) {
308
- throw new Error("cannot find dataTypeFactory for namespace " + dataTypeDictionaryNodeId.namespace);
309
- }
310
- yield _extractDataTypeDictionaryFromDefinition(session, dataTypeDictionaryNodeId, dataTypeFactory2);
311
- return;
312
- }
313
- else {
314
- debugLog(" ----- Using old method for extracting schema => with BSD files");
315
- // old method ( until 1.03 )
316
- // one need to read the schema file store in the dataTypeDictionary node and parse it !
317
- /* istanbul ignore next */
318
- if (doDebug) {
319
- debugLog("---------------------------------------------");
320
- debugLog(rawSchema.toString());
321
- debugLog("---------------------------------------------");
322
- }
323
- const idProvider = yield _extractNodeIds(session, dataTypeDictionaryNodeId);
324
- const dataTypeFactory1 = dataTypeManager.getDataTypeFactory(dataTypeDictionaryNodeId.namespace);
325
- yield node_opcua_schemas_1.parseBinaryXSDAsync(rawSchema, idProvider, dataTypeFactory1);
326
- }
327
- });
328
- }
329
- function _exploreDataTypeDefinition(session, dataTypeDictionaryTypeNode, dataTypeFactory, namespaces) {
330
- return __awaiter(this, void 0, void 0, function* () {
331
- const nodeToBrowse = {
332
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
333
- includeSubtypes: false,
334
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("Variable"),
335
- nodeId: dataTypeDictionaryTypeNode,
336
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasComponent"),
337
- resultMask: node_opcua_data_model_1.makeResultMask("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition")
338
- };
339
- const result = yield node_opcua_pseudo_session_1.browseAll(session, nodeToBrowse);
340
- const references = result.references || [];
341
- /* istanbul ignore next */
342
- if (references.length === 0) {
343
- return;
344
- }
345
- // request the Definition of each nodes
346
- const nodesToBrowse2 = references.map((ref) => {
347
- return {
348
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
349
- includeSubtypes: false,
350
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("Object | Variable"),
351
- nodeId: ref.nodeId,
352
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasDescription"),
353
- resultMask: node_opcua_data_model_1.makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
354
- };
355
- });
356
- const results2 = yield node_opcua_pseudo_session_1.browseAll(session, nodesToBrowse2);
357
- const binaryEncodingNodeIds = results2.map((br) => {
358
- const defaultBin = br.references.filter((r) => r.browseName.toString() === "Default Binary");
359
- /* istanbul ignore next */
360
- if (defaultBin.length < 1) {
361
- return node_opcua_nodeid_1.ExpandedNodeId;
362
- }
363
- return node_opcua_nodeid_1.ExpandedNodeId.fromNodeId(defaultBin[0].nodeId, namespaces[defaultBin[0].nodeId.namespace]);
364
- });
365
- // follow now Default Binary <= [Has Encoding] = [DataType]
366
- /* istanbul ignore next */
367
- if (doDebug) {
368
- console.log(chalk.bgWhite.red("testing new constructors"));
369
- for (let i = 0; i < references.length; i++) {
370
- const ref = references[i];
371
- const binaryEncoding = binaryEncodingNodeIds[i];
372
- const name = ref.browseName.name.toString();
373
- if (doDebug) {
374
- debugLog(" type ", name.padEnd(30, " "), binaryEncoding.toString());
375
- }
376
- // let's verify that constructor is operational
377
- try {
378
- const constructor = dataTypeFactory.getStructureTypeConstructor(name);
379
- // xx const constructor = getOrCreateConstructor(name, dataTypeFactory, defaultBinary);
380
- const testObject = new constructor();
381
- debugLog(testObject.toString());
382
- }
383
- catch (err) {
384
- debugLog(" Error cannot construct Extension Object " + name);
385
- debugLog(" " + err.message);
386
- }
387
- }
388
- }
389
- });
390
- }
391
- const regexTargetNamespaceAttribute = /TargetNamespace="([^\"]+)"|TargetNamespace='([^\"]+)'/;
392
- function extractTargetNamespaceAttribute(xmlElement) {
393
- // warning TargetNamespace could have ' or " , Wago PLC for instance uses simple quotes
394
- const c2 = xmlElement.match(regexTargetNamespaceAttribute);
395
- if (c2) {
396
- return c2[1] || c2[2];
397
- }
398
- return "";
399
- }
400
- const regexNamespaceRef = /xmlns:(.*)=(("([^"]+)")|('([^']+)'))/;
401
- function extraNamespaceRef(attribute) {
402
- const c = attribute.match(regexNamespaceRef);
403
- if (c) {
404
- const xmlns = c[1];
405
- const namespace = c[3] || c[4];
406
- return { xmlns, namespace };
407
- }
408
- return null;
409
- }
410
- /**
411
- * Extract all custom dataType
412
- * @param session
413
- * @param dataTypeManager
414
- * @async
415
- */
416
- function populateDataTypeManager(session, dataTypeManager) {
417
- var _a;
418
- return __awaiter(this, void 0, void 0, function* () {
419
- debugLog("in ... populateDataTypeManager");
420
- // read namespace array
421
- const dataValueNamespaceArray = yield session.read({
422
- attributeId: node_opcua_data_model_1.AttributeIds.Value,
423
- nodeId: node_opcua_nodeid_1.resolveNodeId("Server_NamespaceArray")
424
- });
425
- const namespaceArray = dataValueNamespaceArray.value.value;
426
- // istanbul ignore next
427
- if (!namespaceArray) {
428
- debugLog("session: cannot read Server_NamespaceArray");
429
- // throw new Error("Cannot get Server_NamespaceArray as a array of string");
430
- return;
431
- }
432
- // istanbul ignore next
433
- if (doDebug) {
434
- debugLog("namespaceArray ", namespaceArray.map((a, index) => " " + index.toString().padEnd(3) + ":" + a).join(" "));
435
- }
436
- if (dataValueNamespaceArray.statusCode === node_opcua_status_code_1.StatusCodes.Good && namespaceArray && namespaceArray.length > 0) {
437
- dataTypeManager.setNamespaceArray(namespaceArray);
438
- for (let namespaceIndex = 1; namespaceIndex < namespaceArray.length; namespaceIndex++) {
439
- if (!dataTypeManager.hasDataTypeFactory(namespaceIndex)) {
440
- const dataTypeFactory1 = new node_opcua_factory_1.DataTypeFactory([node_opcua_factory_1.getStandardDataTypeFactory()]);
441
- dataTypeManager.registerDataTypeFactory(namespaceIndex, dataTypeFactory1);
442
- }
443
- }
444
- }
445
- /// to do :: may be not useful
446
- if (!dataValueNamespaceArray.value.value && dataTypeManager.namespaceArray.length === 0) {
447
- dataTypeManager.setNamespaceArray([]);
448
- }
449
- const dataTypeDictionaryType = node_opcua_nodeid_1.resolveNodeId("DataTypeDictionaryType");
450
- // DataType/OPCBinary => i=93 [OPCBinarySchema_TypeSystem]
451
- // "OPC Binary"[DataSystemType]
452
- const opcBinaryNodeId = node_opcua_nodeid_1.resolveNodeId("OPCBinarySchema_TypeSystem");
453
- // let find all DataType dictionary node corresponding to a given namespace
454
- // (have DataTypeDictionaryType)
455
- const nodeToBrowse = {
456
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
457
- includeSubtypes: false,
458
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("Variable"),
459
- nodeId: opcBinaryNodeId,
460
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasComponent"),
461
- resultMask: node_opcua_data_model_1.makeResultMask("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition")
462
- };
463
- const result = yield node_opcua_pseudo_session_1.browseAll(session, nodeToBrowse);
464
- if (doDebug) {
465
- debugLog(result.statusCode.toString());
466
- debugLog((_a = result.references) === null || _a === void 0 ? void 0 : _a.map((r) => { var _a; return (_a = r.browseName) === null || _a === void 0 ? void 0 : _a.toString(); }).join(" "));
467
- }
468
- // filter nodes that have the expected namespace Index
469
- // ( more specifically we want to filter out DataStructure from namespace 0)
470
- // we also want to keep only object of type DataTypeDictionaryType
471
- const references = result.references.filter((e) => e.nodeId.namespace !== 0 && node_opcua_nodeid_1.sameNodeId(e.typeDefinition, dataTypeDictionaryType));
472
- debugLog(`found ${references.length} dictionary`);
473
- function putInCorrectOrder() {
474
- return __awaiter(this, void 0, void 0, function* () {
475
- const infos = [];
476
- const innerMap = {};
477
- for (const reference of references) {
478
- const dataTypeDictionaryNodeId = reference.nodeId;
479
- const isDictionaryDeprecated = yield _readDeprecatedFlag(session, dataTypeDictionaryNodeId);
480
- const rawSchemaDataValue = yield session.read({
481
- attributeId: node_opcua_data_model_1.AttributeIds.Value,
482
- nodeId: dataTypeDictionaryNodeId
483
- });
484
- const rawSchema = rawSchemaDataValue.value.value ? rawSchemaDataValue.value.value.toString() : "";
485
- const info = {
486
- dataTypeDictionaryNodeId,
487
- dependencies: {},
488
- isDictionaryDeprecated,
489
- rawSchema,
490
- reference,
491
- targetNamespace: ""
492
- };
493
- infos.push(info);
494
- if (!isDictionaryDeprecated && rawSchema.length > 0) {
495
- if (doDebug) {
496
- console.log("schema", rawSchema);
497
- }
498
- const matches = rawSchema.match(/<opc:TypeDictionary([^\>]+)>/);
499
- if (matches) {
500
- // extract xml:NS="namespace" from attribute list
501
- // for instance:
502
- // <opc:TypeDictionary
503
- // xmlns:opc="http://opcfoundation.org/BinarySchema/"
504
- // xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
505
- // xmlns:ua="http://opcfoundation.org/UA/"
506
- // xmlns:tns="urn:SomeName:Ua:Types:GlobalTypes"
507
- // DefaultByteOrder="LittleEndian"
508
- // TargetNamespace="urn:SomeName:Ua:Types:GlobalTypes">
509
- const typeDictionaryElementAttributes = matches[1];
510
- info.targetNamespace = extractTargetNamespaceAttribute(typeDictionaryElementAttributes);
511
- const nsKeyNamespace = {};
512
- for (const attribute of typeDictionaryElementAttributes.split(" ")) {
513
- const r = extraNamespaceRef(attribute);
514
- if (r) {
515
- const { xmlns, namespace } = r;
516
- nsKeyNamespace[xmlns] = namespace;
517
- debugLog("xxxx ns= ", xmlns, "=>", namespace);
518
- }
519
- }
520
- info.dependencies = nsKeyNamespace;
521
- debugLog("xxx targetNamespace = ", info.targetNamespace);
522
- innerMap[info.targetNamespace] = info;
523
- }
524
- }
525
- else {
526
- // may be 1.04 => the rawSchema is no more needed in new version
527
- info.targetNamespace = namespaceArray[dataTypeDictionaryNodeId.namespace];
528
- debugLog("xxx targetNamespace = ", info.targetNamespace);
529
- innerMap[info.targetNamespace] = info;
530
- }
531
- // assert(info.targetNamespace.length !== 0);
532
- }
533
- // ----------------------------------
534
- const orderedList = [];
535
- const visited = {};
536
- function explore(d) {
537
- if (visited[d.targetNamespace]) {
538
- return;
539
- }
540
- visited[d.targetNamespace] = 1;
541
- for (const [xmlns, namespace] of Object.entries(d.dependencies)) {
542
- if (!innerMap[namespace] || namespace === d.targetNamespace) {
543
- continue;
544
- }
545
- explore(innerMap[namespace]);
546
- }
547
- orderedList.push(d);
548
- }
549
- for (const d of infos) {
550
- explore(d);
551
- }
552
- debugLog(" Ordered List = ", orderedList.map((a) => a.targetNamespace).join(" "));
553
- return orderedList;
554
- });
555
- }
556
- const dataTypeDictionaryInfo = yield putInCorrectOrder();
557
- // setup dependencies
558
- const map = {};
559
- for (const d of dataTypeDictionaryInfo) {
560
- map[d.targetNamespace] = d;
561
- debugLog(" fixing based dataTypeFactory dependencies for ", d.targetNamespace, "index = ", d.dataTypeDictionaryNodeId.namespace);
562
- const baseDataFactories = [node_opcua_factory_1.getStandardDataTypeFactory()];
563
- for (const namespace of Object.values(d.dependencies)) {
564
- if (namespace === d.targetNamespace) {
565
- continue;
566
- }
567
- const baseDataFactory = map[namespace];
568
- if (!baseDataFactory) {
569
- // xx console.log("xxxxx baseDataFactory = ", namespace);
570
- continue;
571
- }
572
- const namespaceIndex = baseDataFactory.dataTypeDictionaryNodeId.namespace;
573
- if (dataTypeManager.hasDataTypeFactory(namespaceIndex)) {
574
- const dep = dataTypeManager.getDataTypeFactory(namespaceIndex);
575
- baseDataFactories.push(dep);
576
- debugLog(" considering , ", baseDataFactory.targetNamespace, "index = ", baseDataFactory.dataTypeDictionaryNodeId.namespace);
577
- }
578
- }
579
- const dataTypeFactory = dataTypeManager.getDataTypeFactory(d.dataTypeDictionaryNodeId.namespace);
580
- if (dataTypeFactory) {
581
- dataTypeFactory.repairBaseDataFactories(baseDataFactories);
582
- }
583
- }
584
- // --------------------
585
- // now investigate DataTypeDescriptionType
586
- function processReferenceOnDataTypeDictionaryType(d) {
587
- return __awaiter(this, void 0, void 0, function* () {
588
- debugLog(chalk.cyan("processReferenceOnDataTypeDictionaryType on "), d.targetNamespace);
589
- const ref = d.reference;
590
- const dataTypeDictionaryNodeId = d.reference.nodeId;
591
- yield _extractDataTypeDictionary(session, d, dataTypeManager);
592
- /* istanbul ignore next */
593
- if (doDebug) {
594
- debugLog(chalk.bgWhite(" => "), ref.browseName.toString(), ref.nodeId.toString());
595
- }
596
- const dataTypeFactory = dataTypeManager.getDataTypeFactoryForNamespace(dataTypeDictionaryNodeId.namespace);
597
- yield _exploreDataTypeDefinition(session, dataTypeDictionaryNodeId, dataTypeFactory, dataTypeManager.namespaceArray);
598
- });
599
- }
600
- // https://medium.com/swlh/dealing-with-multiple-promises-in-javascript-41d6c21f20ff
601
- for (const d of dataTypeDictionaryInfo) {
602
- try {
603
- yield processReferenceOnDataTypeDictionaryType(d).catch((e) => {
604
- console.log(e);
605
- debugLog("processReferenceOnDataTypeDictionaryType has failed ");
606
- debugLog("Error", e.message);
607
- debugLog(e);
608
- return e;
609
- });
610
- }
611
- catch (err) {
612
- debugLog(chalk.red("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx "), err);
613
- }
614
- }
615
- debugLog("out ... populateDataTypeManager");
616
- });
617
- }
618
- exports.populateDataTypeManager = populateDataTypeManager;
619
- function getHasEncodingDefaultBinary(session, dataTypeNodeId) {
620
- return __awaiter(this, void 0, void 0, function* () {
621
- const nodeToBrowse1 = {
622
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
623
- includeSubtypes: false,
624
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("Object"),
625
- nodeId: dataTypeNodeId,
626
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasEncoding"),
627
- resultMask: node_opcua_data_model_1.makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
628
- };
629
- const result1 = yield node_opcua_pseudo_session_1.browseAll(session, nodeToBrowse1);
630
- if (result1.references && result1.references.length > 1) {
631
- // we have more than one possible Encoding .... only keep "Default Binary"
632
- result1.references = result1.references.filter((r) => r.browseName.toString() === "Default Binary");
633
- }
634
- /* istanbul ignore next */
635
- if (!(result1.references && result1.references.length === 1)) {
636
- // may be dataTypeNodeId is not a dataType,
637
- // let's verify this.
638
- const nodeClass = yield session.read({
639
- attributeId: node_opcua_data_model_1.AttributeIds.NodeClass,
640
- nodeId: dataTypeNodeId
641
- });
642
- const browseName = yield session.read({
643
- attributeId: node_opcua_data_model_1.AttributeIds.BrowseName,
644
- nodeId: dataTypeNodeId
645
- });
646
- // tslint:disable:no-console
647
- console.log("node-id :", dataTypeNodeId ? dataTypeNodeId.toString() : null);
648
- console.log("nodeClass :", node_opcua_data_model_1.NodeClass[nodeClass.value.value]);
649
- console.log("browseName :", browseName.toString());
650
- console.log(result1.toString());
651
- throw new Error("getDataTypeDefinition invalid HasEncoding reference dataTypeNodeId must be NodeClass.DataType but was " +
652
- node_opcua_data_model_1.NodeClass[nodeClass.value.value]);
653
- }
654
- const encodingReference = result1.references[0];
655
- node_opcua_assert_1.assert(encodingReference.browseName.toString() === "Default Binary");
656
- /* istanbul ignore next */
657
- if (doDebug) {
658
- const browseName = yield session.read({
659
- attributeId: node_opcua_data_model_1.AttributeIds.BrowseName,
660
- nodeId: dataTypeNodeId
661
- });
662
- debugLog(browseName.value.value.toString(), "Has Encoding ", encodingReference.browseName.toString(), encodingReference.nodeId.toString());
663
- }
664
- return encodingReference.nodeId;
665
- });
666
- }
667
- function getDefinition(session, defaultBinaryEncodingNodeId) {
668
- return __awaiter(this, void 0, void 0, function* () {
669
- const nodeToBrowse2 = {
670
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Forward,
671
- includeSubtypes: false,
672
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("Variable"),
673
- nodeId: defaultBinaryEncodingNodeId,
674
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasDescription"),
675
- resultMask: node_opcua_data_model_1.makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
676
- };
677
- const result2 = yield node_opcua_pseudo_session_1.browseAll(session, nodeToBrowse2);
678
- node_opcua_assert_1.assert(result2.references && result2.references.length === 1);
679
- const definitionRef = result2.references[0];
680
- const nameDataValue = yield session.read({
681
- attributeId: node_opcua_data_model_1.AttributeIds.Value,
682
- nodeId: definitionRef.nodeId
683
- });
684
- if (nameDataValue.statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
685
- throw new Error("Cannot find ... " + definitionRef.nodeId.toString());
686
- }
687
- /*
688
- const name = nameDataValue.value.value as string;
689
- if (!name) {
690
- console.log(nameDataValue.toString());
691
- throw new Error("Cannot find ... " + name + " " + definitionRef.nodeId.toString());
692
- }
693
- */
694
- return definitionRef.nodeId;
695
- });
696
- }
697
- function getSchemaNode(session, definitionRefNodeId) {
698
- return __awaiter(this, void 0, void 0, function* () {
699
- // find parent node to access the xsd File
700
- const nodeToBrowse3 = {
701
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
702
- includeSubtypes: false,
703
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("Variable"),
704
- nodeId: definitionRefNodeId,
705
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasComponent"),
706
- resultMask: node_opcua_data_model_1.makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass | TypeDefinition")
707
- };
708
- const result3 = yield node_opcua_pseudo_session_1.browseAll(session, nodeToBrowse3);
709
- node_opcua_assert_1.assert(result3.references && result3.references.length === 1);
710
- const schemaNode = result3.references[0].nodeId;
711
- return schemaNode;
712
- });
713
- }
714
- function getDataTypeDefinition(session, dataTypeNodeId,
715
- // tslint:disable-next-line: no-shadowed-variable
716
- dataTypeManager) {
717
- return __awaiter(this, void 0, void 0, function* () {
718
- // DataType
719
- // | 1
720
- // | n
721
- // +- HasEncoding-> "Default Binary" (O)[DataTypeEncodingType]
722
- // |
723
- // +-- HasDescription -> "MyItemType" (V)[DataTypeDescriptionType]
724
- // |
725
- // +- ComponentOf -> Schema(V) []
726
- // |
727
- // +- ComponentOf -> OPC Binary(V)[DataTypeSystemType]
728
- //
729
- // Note that in 1.04 compliant server, DataType definition might be available
730
- // in a DataTypeDefinition attributes of the DataType object
731
- // However this is a brand new aspect of the specification and is not widely implemented
732
- // it is also optional
733
- // It will takes time for old opcua server to be refurbished and we may have to
734
- // keep the current method to access type definition from embedded xsd.
735
- //
736
- const defaultBinaryEncodingNodeId = yield getHasEncodingDefaultBinary(session, dataTypeNodeId);
737
- const definitionRefNodeId = yield getDefinition(session, defaultBinaryEncodingNodeId);
738
- const schemaNode = yield getSchemaNode(session, definitionRefNodeId);
739
- const dataTypeFactory = dataTypeManager.getDataTypeFactoryForNamespace(schemaNode.namespace);
740
- /* istanbul ignore next */
741
- if (!dataTypeFactory) {
742
- throw new Error(" cannot find typeDictionary for " + schemaNode.toString());
743
- }
744
- const nameDataValue = yield session.read({
745
- attributeId: node_opcua_data_model_1.AttributeIds.BrowseName,
746
- nodeId: dataTypeNodeId
747
- });
748
- const name = nameDataValue.value.value.name;
749
- const schema = dataTypeFactory.getStructuredTypeSchema(name);
750
- return schema;
751
- });
752
- }
753
- exports.getDataTypeDefinition = getDataTypeDefinition;
754
- function findSuperType(session, dataTypeNodeId) {
755
- return __awaiter(this, void 0, void 0, function* () {
756
- const nodeToBrowse3 = {
757
- browseDirection: node_opcua_service_browse_1.BrowseDirection.Inverse,
758
- includeSubtypes: false,
759
- nodeClassMask: node_opcua_data_model_1.makeNodeClassMask("DataType"),
760
- nodeId: dataTypeNodeId,
761
- referenceTypeId: node_opcua_nodeid_1.resolveNodeId("HasSubtype"),
762
- resultMask: node_opcua_data_model_1.makeResultMask("NodeId | ReferenceType | BrowseName | NodeClass")
763
- };
764
- const result3 = yield node_opcua_pseudo_session_1.browseAll(session, nodeToBrowse3);
765
- /* istanbul ignore next */
766
- if (result3.statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
767
- throw new Error("Cannot find superType for " + dataTypeNodeId.toString());
768
- }
769
- result3.references = result3.references || [];
770
- /* istanbul ignore next */
771
- if (result3.references.length !== 1) {
772
- console.log(result3.toString());
773
- throw new Error("Invalid dataType with more than one superType " + dataTypeNodeId.toString());
774
- }
775
- return result3.references[0].nodeId;
776
- });
777
- }
778
- function findDataTypeCategory(session, cache, dataTypeNodeId) {
779
- return __awaiter(this, void 0, void 0, function* () {
780
- const subTypeNodeId = yield findSuperType(session, dataTypeNodeId);
781
- debugLog("subTypeNodeId of ", dataTypeNodeId.toString(), " is ", subTypeNodeId.toString());
782
- const key = subTypeNodeId.toString();
783
- if (cache[key]) {
784
- return cache[key].category;
785
- }
786
- let category;
787
- if (subTypeNodeId.namespace === 0 && subTypeNodeId.value <= 29) {
788
- // well known node ID !
789
- switch (subTypeNodeId.value) {
790
- case 22 /* Structure */:
791
- category = node_opcua_factory_1.FieldCategory.complex;
792
- break;
793
- case 29 /* Enumeration */:
794
- category = node_opcua_factory_1.FieldCategory.enumeration;
795
- break;
796
- default:
797
- category = node_opcua_factory_1.FieldCategory.basic;
798
- break;
799
- }
800
- return category;
801
- }
802
- // must drill down ...
803
- return yield findDataTypeCategory(session, cache, subTypeNodeId);
804
- });
805
- }
806
- function findDataTypeBasicType(session, cache, dataTypeNodeId) {
807
- return __awaiter(this, void 0, void 0, function* () {
808
- const subTypeNodeId = yield findSuperType(session, dataTypeNodeId);
809
- debugLog("subTypeNodeId of ", dataTypeNodeId.toString(), " is ", subTypeNodeId.toString());
810
- const key = subTypeNodeId.toString();
811
- if (cache[key]) {
812
- return cache[key].schema;
813
- }
814
- if (subTypeNodeId.namespace === 0 && subTypeNodeId.value < 29) {
815
- switch (subTypeNodeId.value) {
816
- case 22: /* Structure */
817
- case 29 /* Enumeration */:
818
- throw new Error("Not expecting Structure or Enumeration");
819
- default:
820
- break;
821
- }
822
- const nameDataValue = yield session.read({
823
- attributeId: node_opcua_data_model_1.AttributeIds.BrowseName,
824
- nodeId: subTypeNodeId
825
- });
826
- const name = nameDataValue.value.value.name;
827
- return node_opcua_factory_1.getBuildInType(name);
828
- }
829
- // must drill down ...
830
- return yield findDataTypeBasicType(session, cache, subTypeNodeId);
831
- });
832
- }
833
- function readBrowseName(session, nodeId) {
834
- return __awaiter(this, void 0, void 0, function* () {
835
- const dataValue = yield session.read({ nodeId, attributeId: node_opcua_data_model_1.AttributeIds.BrowseName });
836
- if (dataValue.statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
837
- const message = "cannot extract BrowseName of nodeId = " + nodeId.toString() + " statusCode = " + dataValue.statusCode.toString();
838
- debugLog(message);
839
- throw new Error(message);
840
- }
841
- return dataValue.value.value.name;
842
- });
843
- }
844
- function resolveFieldType(session, dataTypeNodeId, dataTypeFactory, cache) {
845
- return __awaiter(this, void 0, void 0, function* () {
846
- if (dataTypeNodeId.namespace === 0 && dataTypeNodeId.value === 22) {
847
- return null;
848
- }
849
- const key = dataTypeNodeId.toString();
850
- const v = cache[key];
851
- if (v) {
852
- return v;
853
- }
854
- if (dataTypeNodeId.value === 0) {
855
- const v3 = {
856
- category: node_opcua_factory_1.FieldCategory.basic,
857
- fieldTypeName: "Variant",
858
- schema: dataTypeFactory.getSimpleType("Variant")
859
- };
860
- cache[key] = v3;
861
- return v3;
862
- }
863
- const fieldTypeName = yield readBrowseName(session, dataTypeNodeId);
864
- let schema;
865
- let category = node_opcua_factory_1.FieldCategory.enumeration;
866
- if (dataTypeFactory.hasStructuredType(fieldTypeName)) {
867
- schema = dataTypeFactory.getStructuredTypeSchema(fieldTypeName);
868
- category = node_opcua_factory_1.FieldCategory.complex;
869
- }
870
- else if (dataTypeFactory.hasSimpleType(fieldTypeName)) {
871
- category = node_opcua_factory_1.FieldCategory.basic;
872
- schema = dataTypeFactory.getSimpleType(fieldTypeName);
873
- }
874
- else if (dataTypeFactory.hasEnumeration(fieldTypeName)) {
875
- category = node_opcua_factory_1.FieldCategory.enumeration;
876
- schema = dataTypeFactory.getEnumeration(fieldTypeName);
877
- }
878
- else {
879
- debugLog(" type " + fieldTypeName + " has not been seen yet, let resolve it");
880
- category = yield findDataTypeCategory(session, cache, dataTypeNodeId);
881
- debugLog(" type " + fieldTypeName + " has not been seen yet, let resolve it => (category = ", category, " )");
882
- switch (category) {
883
- case node_opcua_factory_1.FieldCategory.basic:
884
- schema = yield findDataTypeBasicType(session, cache, dataTypeNodeId);
885
- /* istanbul ignore next */
886
- if (!schema) {
887
- console.log("Cannot find basic type " + fieldTypeName);
888
- }
889
- break;
890
- default:
891
- case node_opcua_factory_1.FieldCategory.enumeration:
892
- case node_opcua_factory_1.FieldCategory.complex:
893
- const dataTypeDefinitionDataValue = yield session.read({
894
- attributeId: node_opcua_data_model_1.AttributeIds.DataTypeDefinition,
895
- nodeId: dataTypeNodeId
896
- });
897
- /* istanbul ignore next */
898
- if (dataTypeDefinitionDataValue.statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
899
- throw new Error(" Cannot find dataType Definition ! with nodeId =" + dataTypeNodeId.toString());
900
- }
901
- const definition = dataTypeDefinitionDataValue.value.value;
902
- if (category === node_opcua_factory_1.FieldCategory.enumeration) {
903
- if (definition instanceof node_opcua_types_1.EnumDefinition) {
904
- const e = new node_opcua_factory_1.EnumerationDefinitionSchema({
905
- enumValues: definition.fields,
906
- name: fieldTypeName
907
- });
908
- dataTypeFactory.registerEnumeration(e);
909
- schema = e;
910
- }
911
- }
912
- else {
913
- schema = yield convertDataTypeDefinitionToStructureTypeSchema(session, dataTypeNodeId, fieldTypeName, definition, dataTypeFactory, cache);
914
- }
915
- // xx const schema1 = dataTypeFactory.getStructuredTypeSchema(fieldTypeName);
916
- break;
917
- }
918
- }
919
- /* istanbul ignore next */
920
- if (!schema) {
921
- throw new Error("expecting a schema here fieldTypeName=" + fieldTypeName + " " + dataTypeNodeId.toString() + " category = " + category);
922
- }
923
- const v2 = {
924
- category,
925
- fieldTypeName,
926
- schema
927
- };
928
- cache[key] = v2;
929
- return v2;
930
- });
931
- }
932
- function _setupEncodings(session, dataTypeNodeId, schema) {
933
- return __awaiter(this, void 0, void 0, function* () {
934
- // read abstract flag
935
- const isAbstractDV = yield session.read({ nodeId: dataTypeNodeId, attributeId: node_opcua_data_model_1.AttributeIds.IsAbstract });
936
- schema.dataTypeNodeId = dataTypeNodeId;
937
- schema.id = dataTypeNodeId;
938
- if (isAbstractDV.statusCode === node_opcua_status_code_1.StatusCodes.Good && isAbstractDV.value.value === false) {
939
- const encodings = yield _findEncodings(session, dataTypeNodeId);
940
- schema.encodingDefaultBinary = node_opcua_nodeid_1.makeExpandedNodeId(encodings.binaryEncodingNodeId);
941
- schema.encodingDefaultXml = node_opcua_nodeid_1.makeExpandedNodeId(encodings.xmlEncodingNodeId);
942
- schema.encodingDefaultJson = node_opcua_nodeid_1.makeExpandedNodeId(encodings.jsonEncodingNodeId);
943
- }
944
- return schema;
945
- });
946
- }
947
- function convertDataTypeDefinitionToStructureTypeSchema(session, dataTypeNodeId, name, definition, dataTypeFactory, cache) {
948
- return __awaiter(this, void 0, void 0, function* () {
949
- if (definition instanceof node_opcua_types_1.StructureDefinition) {
950
- const fields = [];
951
- const isUnion = definition.structureType === node_opcua_types_1.StructureType.Union;
952
- switch (definition.structureType) {
953
- case node_opcua_types_1.StructureType.Union:
954
- // xx console.log("Union Found : ", name);
955
- fields.push({
956
- fieldType: "UInt32",
957
- name: "SwitchField"
958
- });
959
- break;
960
- case node_opcua_types_1.StructureType.Structure:
961
- case node_opcua_types_1.StructureType.StructureWithOptionalFields:
962
- break;
963
- }
964
- let switchValue = 1;
965
- let switchBit = 0;
966
- const bitFields = isUnion ? undefined : [];
967
- for (const fieldD of definition.fields) {
968
- const rt = (yield resolveFieldType(session, fieldD.dataType, dataTypeFactory, cache));
969
- if (!rt) {
970
- console.log("convertDataTypeDefinitionToStructureTypeSchema cannot handle field", fieldD.name, "in", name);
971
- continue;
972
- }
973
- const { schema, category, fieldTypeName } = rt;
974
- const field = {
975
- fieldType: fieldTypeName,
976
- name: fieldD.name,
977
- schema
978
- };
979
- if (fieldD.isOptional) {
980
- field.switchBit = switchBit++;
981
- bitFields === null || bitFields === void 0 ? void 0 : bitFields.push({ name: fieldD.name + "Specified", length: 1 });
982
- }
983
- if (isUnion) {
984
- field.switchValue = switchValue;
985
- switchValue += 1;
986
- }
987
- node_opcua_assert_1.assert(fieldD.valueRank === -1 || fieldD.valueRank === 1 || fieldD.valueRank === 0);
988
- if (fieldD.valueRank === 1) {
989
- field.isArray = true;
990
- }
991
- else {
992
- field.isArray = false;
993
- }
994
- field.category = category;
995
- field.schema = schema;
996
- fields.push(field);
997
- }
998
- const a = yield resolveFieldType(session, definition.baseDataType, dataTypeFactory, cache);
999
- const baseType = a ? a.fieldTypeName : "ExtensionObject";
1000
- const os = new node_opcua_factory_1.StructuredTypeSchema({
1001
- baseType,
1002
- bitFields,
1003
- fields,
1004
- id: 0,
1005
- name
1006
- });
1007
- const structuredTypeSchema = yield _setupEncodings(session, dataTypeNodeId, os);
1008
- return structuredTypeSchema;
1009
- }
1010
- throw new Error("Not Implemented");
1011
- });
1012
- }
1013
- exports.convertDataTypeDefinitionToStructureTypeSchema = convertDataTypeDefinitionToStructureTypeSchema;
1014
- function extractNamespaceDataType(session) {
1015
- return __awaiter(this, void 0, void 0, function* () {
1016
- const sessionPriv = session;
1017
- if (!sessionPriv.$$extraDataTypeManager) {
1018
- const dataTypeManager = new extra_data_type_manager_1.ExtraDataTypeManager();
1019
- const namespaceArray = yield sessionPriv.readNamespaceArray();
1020
- debugLog("Namespace Array = ", namespaceArray.join("\n "));
1021
- sessionPriv.$$extraDataTypeManager = dataTypeManager;
1022
- dataTypeManager.setNamespaceArray(namespaceArray);
1023
- for (let namespaceIndex = 1; namespaceIndex < namespaceArray.length; namespaceIndex++) {
1024
- const dataTypeFactory1 = new node_opcua_factory_1.DataTypeFactory([node_opcua_factory_1.getStandardDataTypeFactory()]);
1025
- dataTypeManager.registerDataTypeFactory(namespaceIndex, dataTypeFactory1);
1026
- }
1027
- yield populateDataTypeManager(session, dataTypeManager);
1028
- }
1029
- return sessionPriv.$$extraDataTypeManager;
1030
- });
1031
- }
1032
- exports.extractNamespaceDataType = extractNamespaceDataType;
1033
- function getExtensionObjectConstructor(session, dataTypeNodeId) {
1034
- return __awaiter(this, void 0, void 0, function* () {
1035
- const sessionPriv = session;
1036
- if (!sessionPriv.dataTypeConstructor) {
1037
- sessionPriv.dataTypeConstructor = {};
1038
- }
1039
- const c = sessionPriv.dataTypeConstructor[dataTypeNodeId.toString()];
1040
- if (c) {
1041
- return c;
1042
- }
1043
- yield extractNamespaceDataType(session);
1044
- if (!sessionPriv.$$extraDataTypeManager) {
1045
- throw new Error("Make sure to call await session.extractNamespaceDataType(); ");
1046
- }
1047
- const extraDataTypeManager = sessionPriv.$$extraDataTypeManager;
1048
- // make sure schema has been extracted
1049
- const schema = yield getDataTypeDefinition(session, dataTypeNodeId, extraDataTypeManager);
1050
- // now resolve it
1051
- const constructor = extraDataTypeManager.getExtensionObjectConstructorFromDataType(dataTypeNodeId);
1052
- // put it in cache
1053
- sessionPriv.dataTypeConstructor[dataTypeNodeId.toString()] = constructor;
1054
- return constructor;
1055
- });
1056
- }
1057
- exports.getExtensionObjectConstructor = getExtensionObjectConstructor;
1058
- //# sourceMappingURL=client_dynamic_extension_object.js.map