node-opcua-convert-nodeset-to-javascript 2.64.1 → 2.65.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.
@@ -1,885 +1,885 @@
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.convertTypeToTypescript = exports._convertTypeToTypescript = exports._exportDataTypeToTypescript = exports.findUsedImport = exports.extractClassMemberDef = exports.checkIfShouldExposeInnerDefinition = exports.findClassMember = exports.extractClassDefinition = exports.makeTypeName2 = exports.convertDataTypeToTypescript = void 0;
13
- const chalk = require("chalk");
14
- const wrap = require("wordwrap");
15
- const node_opcua_data_model_1 = require("node-opcua-data-model");
16
- const node_opcua_types_1 = require("node-opcua-types");
17
- const node_opcua_utils_1 = require("node-opcua-utils");
18
- const node_opcua_variant_1 = require("node-opcua-variant");
19
- const node_opcua_assert_1 = require("node-opcua-assert");
20
- const node_opcua_debug_1 = require("node-opcua-debug");
21
- const utils_1 = require("./private/utils");
22
- const cache_1 = require("./private/cache");
23
- const to_filename_1 = require("./private/to_filename");
24
- const warningLog = (0, node_opcua_debug_1.make_warningLog)("typescript");
25
- const doDebug = false;
26
- const wrapText = wrap(0, 50);
27
- const f2 = (str) => str.padEnd(50, "-");
28
- const f1 = (str) => str.padEnd(50, " ");
29
- const baseExtension = "_Base";
30
- function convertDataTypeToTypescript(session, dataTypeId) {
31
- return __awaiter(this, void 0, void 0, function* () {
32
- const definition = yield (0, utils_1.getDefinition)(session, dataTypeId);
33
- const browseName = yield (0, utils_1.getBrowseName)(session, dataTypeId);
34
- const dataTypeTypescriptName = `UA${browseName.name.toString()}`;
35
- const f = new node_opcua_utils_1.LineFile();
36
- if (definition && definition instanceof node_opcua_types_1.StructureDefinition) {
37
- f.write(`interface ${dataTypeTypescriptName} {`);
38
- for (const field of definition.fields || []) {
39
- /** */
40
- }
41
- f.write(`}`);
42
- }
43
- });
44
- }
45
- exports.convertDataTypeToTypescript = convertDataTypeToTypescript;
46
- // to avoid clashes
47
- function toJavascritPropertyName(childName, { ignoreConflictingName }) {
48
- childName = (0, node_opcua_utils_1.lowerFirstLetter)(childName);
49
- if (ignoreConflictingName) {
50
- if (childName === "namespaceUri") {
51
- childName = "$namespaceUri";
52
- }
53
- if (childName === "rolePermissions") {
54
- childName = "$rolePermissions";
55
- }
56
- if (childName === "displayName") {
57
- childName = "$displayName";
58
- }
59
- if (childName === "eventNotifier") {
60
- childName = "$eventNotifier";
61
- }
62
- if (childName === "description") {
63
- childName = "$description";
64
- }
65
- }
66
- return childName.replace(/</g, "$").replace(/>/g, "$").replace(/ |\./g, "_").replace(/#/g, "_");
67
- }
68
- function quotifyIfNecessary(s) {
69
- if (s.match(/(^[^a-zA-Z])|([^a-zA-Z_0-9])/)) {
70
- return `"${s}"`;
71
- }
72
- if (s === "nodeClass") {
73
- return `["$nodeClass"]`;
74
- }
75
- return s;
76
- }
77
- function getCorrepondingJavascriptType2(session, nodeId, dataTypeNodeId, cache, importCollect) {
78
- return __awaiter(this, void 0, void 0, function* () {
79
- const q = yield getCorrepondingJavascriptType(session, dataTypeNodeId, cache, importCollect);
80
- const valueRank = yield (0, utils_1.getValueRank)(session, nodeId);
81
- return { dataType: q.dataType, jtype: q.jtype + (valueRank >= 1 ? "[]" : "") };
82
- });
83
- }
84
- // eslint-disable-next-line complexity
85
- function getCorrepondingJavascriptType(session, dataTypeNodeId, cache, importCollect) {
86
- return __awaiter(this, void 0, void 0, function* () {
87
- const dataType = yield (0, utils_1.convertNodeIdToDataTypeAsync)(session, dataTypeNodeId);
88
- const referenceBasicType = (name) => {
89
- const t = { name, namespace: -1, module: "BasicType" };
90
- importCollect && importCollect(t);
91
- cache.ensureImported(t);
92
- return t.name;
93
- };
94
- if (dataType === node_opcua_variant_1.DataType.ExtensionObject) {
95
- const jtypeImport = yield (0, cache_1.referenceExtensionObject)(session, dataTypeNodeId);
96
- const jtype = jtypeImport.name;
97
- importCollect && importCollect(jtypeImport);
98
- return { dataType, jtype: jtype };
99
- }
100
- switch (dataType) {
101
- case node_opcua_variant_1.DataType.Null:
102
- return { dataType, jtype: "undefined" };
103
- case node_opcua_variant_1.DataType.Boolean:
104
- return { dataType, jtype: "boolean" };
105
- case node_opcua_variant_1.DataType.Byte:
106
- return { dataType, jtype: referenceBasicType("Byte") };
107
- case node_opcua_variant_1.DataType.ByteString:
108
- return { dataType, jtype: "Buffer" };
109
- case node_opcua_variant_1.DataType.DataValue:
110
- return { dataType, jtype: referenceBasicType("DataValue") };
111
- case node_opcua_variant_1.DataType.DateTime:
112
- return { dataType, jtype: "Date" };
113
- case node_opcua_variant_1.DataType.DiagnosticInfo:
114
- return { dataType, jtype: referenceBasicType("DiagnosticInfo") };
115
- case node_opcua_variant_1.DataType.Double:
116
- return { dataType, jtype: "number" };
117
- case node_opcua_variant_1.DataType.Float:
118
- return { dataType, jtype: "number" };
119
- case node_opcua_variant_1.DataType.Guid:
120
- return { dataType, jtype: referenceBasicType("Guid") };
121
- case node_opcua_variant_1.DataType.Int16:
122
- return { dataType, jtype: referenceBasicType("Int16") };
123
- case node_opcua_variant_1.DataType.Int32:
124
- return { dataType, jtype: referenceBasicType("Int32") };
125
- case node_opcua_variant_1.DataType.UInt16:
126
- return { dataType, jtype: referenceBasicType("UInt16") };
127
- case node_opcua_variant_1.DataType.UInt32:
128
- return { dataType, jtype: referenceBasicType("UInt32") };
129
- case node_opcua_variant_1.DataType.UInt64:
130
- return { dataType, jtype: referenceBasicType("UInt64") };
131
- case node_opcua_variant_1.DataType.Int64:
132
- return { dataType, jtype: referenceBasicType("Int64") };
133
- case node_opcua_variant_1.DataType.LocalizedText:
134
- return { dataType, jtype: referenceBasicType("LocalizedText") };
135
- case node_opcua_variant_1.DataType.NodeId:
136
- return { dataType, jtype: referenceBasicType("NodeId") };
137
- case node_opcua_variant_1.DataType.ExpandedNodeId:
138
- return { dataType, jtype: referenceBasicType("ExpandedNodeId") };
139
- case node_opcua_variant_1.DataType.QualifiedName:
140
- return { dataType, jtype: referenceBasicType("QualifiedName") };
141
- case node_opcua_variant_1.DataType.SByte:
142
- return { dataType, jtype: referenceBasicType("SByte") };
143
- case node_opcua_variant_1.DataType.StatusCode:
144
- return { dataType, jtype: referenceBasicType("StatusCode") };
145
- case node_opcua_variant_1.DataType.String:
146
- return { dataType, jtype: referenceBasicType("UAString") };
147
- case node_opcua_variant_1.DataType.Variant:
148
- return { dataType, jtype: referenceBasicType("Variant") };
149
- case node_opcua_variant_1.DataType.XmlElement:
150
- return { dataType, jtype: referenceBasicType("UAString") };
151
- default:
152
- throw new Error("Unsupported " + dataType + " " + node_opcua_variant_1.DataType[dataType]);
153
- }
154
- });
155
- }
156
- function makeTypeName2(nodeClass, browseName, suffix) {
157
- (0, node_opcua_assert_1.default)(browseName);
158
- if (nodeClass === node_opcua_data_model_1.NodeClass.Method) {
159
- return { name: "UAMethod", namespace: 0, module: "UAMethod" };
160
- }
161
- return (0, cache_1.makeTypeNameNew)(nodeClass, null, browseName, suffix);
162
- }
163
- exports.makeTypeName2 = makeTypeName2;
164
- function extractClassDefinition(session, nodeId, cache) {
165
- return __awaiter(this, void 0, void 0, function* () {
166
- const extraImports = [];
167
- const _c = cache.classDefCache || {};
168
- cache.classDefCache = _c;
169
- let classDef = _c[nodeId.toString()];
170
- if (classDef) {
171
- return classDef;
172
- }
173
- const nodeClass = yield (0, utils_1.getNodeClass)(session, nodeId);
174
- if (nodeClass !== node_opcua_data_model_1.NodeClass.VariableType && nodeClass !== node_opcua_data_model_1.NodeClass.ObjectType) {
175
- throw new Error("Invalid nodeClass " + node_opcua_data_model_1.NodeClass[nodeClass] + " nodeId " + nodeId.toString());
176
- }
177
- const browseName = yield (0, utils_1.getBrowseName)(session, nodeId);
178
- const isAbstract = yield (0, utils_1.getIsAbstract)(session, nodeId);
179
- const superType = (yield (0, utils_1.getSubtypeNodeIdIfAny)(session, nodeId)) || undefined;
180
- const dataTypeNodeId = yield (0, utils_1.getDataTypeNodeId)(session, nodeId);
181
- let dataTypeName = "";
182
- let dataType = node_opcua_variant_1.DataType.Null;
183
- let dataTypeImport = undefined;
184
- if (nodeClass === node_opcua_data_model_1.NodeClass.VariableType) {
185
- dataType = yield (0, utils_1.extractBasicDataType)(session, dataTypeNodeId);
186
- const importCollector = (i) => {
187
- extraImports.push(i);
188
- cache.ensureImported(i);
189
- };
190
- const { jtype } = yield getCorrepondingJavascriptType2(session, nodeId, dataTypeNodeId, cache, importCollector);
191
- dataTypeName = jtype; // with decoration
192
- if (!(dataTypeNodeId === null || dataTypeNodeId === void 0 ? void 0 : dataTypeNodeId.isEmpty())) {
193
- // "DT" + (await getBrowseName(session, dataTypeNodeId!))?.name! || "";
194
- // const bn = await getBrowseName(session, dataTypeNodeId!);
195
- dataTypeImport = extraImports; // makeTypeName2(NodeClass.DataType, bn);
196
- }
197
- }
198
- const baseClassDef = !superType ? null : yield extractClassDefinition(session, superType.nodeId, cache);
199
- const description = yield (0, utils_1.getDescription)(session, nodeId);
200
- // const definition = await getDefinition(session, nodeId);
201
- const interfaceName = makeTypeName2(nodeClass, browseName);
202
- const baseInterfaceName = !superType ? null : makeTypeName2(nodeClass, superType.browseName);
203
- // extract member
204
- const children = yield (0, utils_1.getChildrenOrFolderElements)(session, nodeId);
205
- const members = [];
206
- classDef = {
207
- nodeClass,
208
- browseName,
209
- isAbstract,
210
- dataType,
211
- dataTypeNodeId,
212
- dataTypeName,
213
- dataTypeImport,
214
- superType,
215
- baseClassDef,
216
- description,
217
- // definition,
218
- children,
219
- members,
220
- interfaceName,
221
- baseInterfaceName
222
- };
223
- _c[nodeId.toString()] = classDef;
224
- for (const child of children) {
225
- const c = yield extractClassMemberDef(session, child.nodeId, classDef, cache);
226
- classDef.members.push(c);
227
- }
228
- return classDef;
229
- });
230
- }
231
- exports.extractClassDefinition = extractClassDefinition;
232
- function classify(session, refs) {
233
- return __awaiter(this, void 0, void 0, function* () {
234
- const r = {
235
- Mandatory: [],
236
- Optional: [],
237
- MandatoryPlaceholder: [],
238
- OptionalPlaceholder: [],
239
- ExposesItsArray: []
240
- };
241
- for (const mm of refs) {
242
- const modellingRule = yield (0, utils_1.getModellingRule)(session, mm.nodeId);
243
- if (modellingRule) {
244
- r[modellingRule] = r[modellingRule] || [];
245
- r[modellingRule].push(mm);
246
- }
247
- }
248
- return r;
249
- });
250
- }
251
- function extractAllMembers(session, classDef, cache) {
252
- return __awaiter(this, void 0, void 0, function* () {
253
- const m = [...classDef.children];
254
- let s = classDef;
255
- while (s.baseClassDef) {
256
- s = s.baseClassDef;
257
- // start from top most class
258
- // do not overwrite most top member definition, so we get mandatory stuff
259
- for (const mm of s.children) {
260
- const found = m.findIndex((r) => r.browseName.toString() === mm.browseName.toString());
261
- if (found < 0) {
262
- m.push(mm);
263
- }
264
- }
265
- }
266
- // now separate mandatory and optionals
267
- const members = yield classify(session, m);
268
- return members;
269
- });
270
- }
271
- function findClassMember(session, browseName, baseParentDef, cache) {
272
- return __awaiter(this, void 0, void 0, function* () {
273
- const str = browseName.toString();
274
- const r = baseParentDef.children.find((a) => a.browseName.toString() === str);
275
- if (r) {
276
- const d = yield extractClassMemberDef(session, r.nodeId, baseParentDef, cache);
277
- return d;
278
- }
279
- const baseBaseParentDef = baseParentDef.superType && (yield extractClassDefinition(session, baseParentDef.superType.nodeId, cache));
280
- if (!baseBaseParentDef) {
281
- return null;
282
- }
283
- return yield findClassMember(session, browseName, baseBaseParentDef, cache);
284
- });
285
- }
286
- exports.findClassMember = findClassMember;
287
- function hasNewMaterial(referenceMembers, instanceMembers) {
288
- const ref = referenceMembers.map((x) => x.browseName.toString()).sort();
289
- const instance = instanceMembers.map((x) => x.browseName.toString()).sort();
290
- for (const n of instance) {
291
- if (ref.findIndex((x) => x === n) < 0) {
292
- return true;
293
- }
294
- }
295
- return false;
296
- }
297
- // we should expose an inner definition if
298
- // - at least one mandatory in instnace doesn't exist in main.Mandatory
299
- // - at least one optional in instnace doesn't exist in main.Mandatory
300
- function checkIfShouldExposeInnerDefinition(main, instance) {
301
- const hasNewStuff = hasNewMaterial(main.Mandatory, instance.Mandatory) || hasNewMaterial(main.Optional, instance.Optional);
302
- return hasNewStuff;
303
- }
304
- exports.checkIfShouldExposeInnerDefinition = checkIfShouldExposeInnerDefinition;
305
- function dump1(a) {
306
- console.log("Mandatory = ", a.Mandatory.map((x) => x.browseName.toString())
307
- .sort()
308
- .join(" "));
309
- console.log("Optional = ", a.Optional.map((x) => x.browseName.toString())
310
- .sort()
311
- .join(" "));
312
- }
313
- function _extractLocalMembers(session, classMember, cache) {
314
- var _a;
315
- return __awaiter(this, void 0, void 0, function* () {
316
- const children2 = [];
317
- for (const child of classMember.children) {
318
- const nodeId = child.nodeId;
319
- const browseName = yield (0, utils_1.getBrowseName)(session, nodeId);
320
- const name = toJavascritPropertyName(browseName.name, { ignoreConflictingName: true });
321
- const description = yield (0, utils_1.getDescription)(session, nodeId);
322
- const modellingRule = yield (0, utils_1.getModellingRule)(session, nodeId);
323
- const isOptional = modellingRule === "Optional";
324
- const typeDefinition = yield (0, utils_1.getTypeDefOrBaseType)(session, nodeId);
325
- const childInBase = (_a = classMember.classDef) === null || _a === void 0 ? void 0 : _a.members.find((a) => a.browseName.toString() === browseName.toString());
326
- let childType;
327
- if (childInBase) {
328
- childType = childInBase.childType;
329
- }
330
- else {
331
- const d = typeDefinition.nodeId.isEmpty() ? null : yield extractClassDefinition(session, typeDefinition.nodeId, cache);
332
- childType = (d === null || d === void 0 ? void 0 : d.interfaceName) || { name: "UAMethod", module: "BasicType", namespace: -1 };
333
- }
334
- // may be childType is already
335
- const { suffix, suffixInstantiate, typeToReference, chevrons } = yield extractVariableExtra(session, child.nodeId, cache, classMember);
336
- const c = {
337
- childType,
338
- description,
339
- isOptional,
340
- modellingRule,
341
- name,
342
- suffix,
343
- suffixInstantiate,
344
- typeToReference,
345
- chevrons
346
- };
347
- children2.push(c);
348
- }
349
- return children2;
350
- });
351
- }
352
- function isUnspecifiedDataType(dataType) {
353
- return dataType === node_opcua_variant_1.DataType.Null || dataType === node_opcua_variant_1.DataType.Variant;
354
- }
355
- function extractVariableExtra(session, nodeId, cache, classMember) {
356
- var _a;
357
- return __awaiter(this, void 0, void 0, function* () {
358
- const typeToReference = [];
359
- const importCollector = (i) => {
360
- typeToReference.push(i);
361
- cache.ensureImported(i);
362
- };
363
- const nodeClass = yield (0, utils_1.getNodeClass)(session, nodeId);
364
- if (nodeClass === node_opcua_data_model_1.NodeClass.Variable) {
365
- const dataTypeNodeId = yield (0, utils_1.getDataTypeNodeId)(session, nodeId);
366
- const { dataType, jtype } = yield getCorrepondingJavascriptType2(session, nodeId, dataTypeNodeId, cache, importCollector);
367
- cache && cache.referenceBasicType("DataType");
368
- importCollector({ name: "DataType", namespace: -1, module: "BasicType" });
369
- const t = isUnspecifiedDataType((_a = classMember.classDef) === null || _a === void 0 ? void 0 : _a.dataType);
370
- const suffix = jtype === "undefined" || isUnspecifiedDataType(dataType)
371
- ? `<any, any>`
372
- : `<${jtype}${t ? `, /*c*/DataType.${node_opcua_variant_1.DataType[dataType]}` : ""}>`;
373
- // const suffix2 = `<T${t ? `, /*a*/DT extends DataType` : ""}>`;
374
- const suffix3 = `<T${t ? `, /*b*/DT` : ""}>`;
375
- const typeDef = yield (0, utils_1.getTypeDefOrBaseType)(session, nodeId);
376
- const typeDefCD = yield extractClassDefinition(session, typeDef.nodeId, cache);
377
- const chevrons = calculateChevrons(typeDefCD, { dataType });
378
- const suffix2 = chevrons.chevronsDef;
379
- /** Suffix for instantiation
380
- * if typeDef.dataType is not null, then we need to add a type argument
381
- */
382
- let suffixInstantiate = "";
383
- if (isUnspecifiedDataType(dataType)) {
384
- if (!isUnspecifiedDataType(typeDefCD.dataType)) {
385
- suffixInstantiate = "<any>";
386
- }
387
- else {
388
- suffixInstantiate = "<any, any>";
389
- }
390
- }
391
- else {
392
- if (!isUnspecifiedDataType(typeDefCD.dataType)) {
393
- suffixInstantiate = `<${jtype}>`;
394
- }
395
- else {
396
- suffixInstantiate = `<${jtype}, /*z*/DataType.${node_opcua_variant_1.DataType[dataType]}>`;
397
- }
398
- }
399
- return { suffixInstantiate, suffix, suffix2, suffix3, dataTypeNodeId, dataType, jtype, typeToReference, chevrons };
400
- }
401
- return { suffix: "", typeToReference };
402
- });
403
- }
404
- // eslint-disable-next-line max-statements
405
- function extractClassMemberDef(session, nodeId, parentDef, cache) {
406
- return __awaiter(this, void 0, void 0, function* () {
407
- const nodeClass = yield (0, utils_1.getNodeClass)(session, nodeId);
408
- const browseName = yield (0, utils_1.getBrowseName)(session, nodeId);
409
- const name = toJavascritPropertyName(browseName.name, { ignoreConflictingName: true });
410
- if (nodeClass !== node_opcua_data_model_1.NodeClass.Method && nodeClass !== node_opcua_data_model_1.NodeClass.Object && nodeClass !== node_opcua_data_model_1.NodeClass.Variable) {
411
- throw new Error("Invalid property " + node_opcua_data_model_1.NodeClass[nodeClass] + " " + (browseName === null || browseName === void 0 ? void 0 : browseName.toString()) + " " + nodeId.toString());
412
- }
413
- const description = yield (0, utils_1.getDescription)(session, nodeId);
414
- const children = yield (0, utils_1.getChildrenOrFolderElements)(session, nodeId);
415
- const modellingRule = yield (0, utils_1.getModellingRule)(session, nodeId);
416
- const isOptional = modellingRule === "Optional";
417
- const typeDefinition = yield (0, utils_1.getTypeDefOrBaseType)(session, nodeId);
418
- if (nodeClass !== node_opcua_data_model_1.NodeClass.Method && (!typeDefinition.browseName || !typeDefinition.browseName.name)) {
419
- warningLog(typeDefinition.toString());
420
- warningLog("cannot find typeDefinition for ", browseName.toString(), "( is the namespace loaded ?)");
421
- }
422
- let childType = makeTypeName2(nodeClass, typeDefinition.browseName);
423
- const classDef = typeDefinition.nodeId.isEmpty() ? null : yield extractClassDefinition(session, typeDefinition.nodeId, cache);
424
- let innerClass = null;
425
- let childBase = null;
426
- let shouldExposeInnerDefinition = false;
427
- // find member exposed by type definition
428
- const baseParentDef = parentDef.superType && (yield extractClassDefinition(session, parentDef.superType.nodeId, cache));
429
- if (classDef && baseParentDef) {
430
- const chevrons1 = calculateChevrons(classDef, baseParentDef);
431
- (0, node_opcua_assert_1.default)(!innerClass);
432
- // let's extract the member that are theorically defined in the member
433
- const membersReference = yield extractAllMembers(session, classDef, cache);
434
- // find member exposed by this member
435
- const membersInstance = yield classify(session, children);
436
- // if (name==="powerup") {
437
- // dump1(membersReference);
438
- // dump1(membersInstance);
439
- // await extractAllMembers(session, classDef, cache);
440
- // }
441
- shouldExposeInnerDefinition = checkIfShouldExposeInnerDefinition(membersReference, membersInstance);
442
- const sameMemberInBaseClass = baseParentDef && (yield findClassMember(session, browseName, baseParentDef, cache));
443
- if (shouldExposeInnerDefinition) {
444
- if (sameMemberInBaseClass) {
445
- innerClass = {
446
- module: parentDef.interfaceName.module,
447
- name: parentDef.interfaceName.name + "_" + name,
448
- namespace: nodeId.namespace
449
- };
450
- childBase = sameMemberInBaseClass.childType;
451
- childType = innerClass;
452
- }
453
- else {
454
- innerClass = {
455
- module: parentDef.interfaceName.module,
456
- name: parentDef.interfaceName.name + "_" + name,
457
- namespace: nodeId.namespace
458
- };
459
- childBase = childType;
460
- childType = innerClass;
461
- }
462
- (0, node_opcua_assert_1.default)(innerClass);
463
- (0, node_opcua_assert_1.default)(childBase);
464
- }
465
- else {
466
- // may not expose definition but we may want to used the augment typescript class defined in the definition
467
- // we don't need to create an inner class ...
468
- childType = sameMemberInBaseClass ? sameMemberInBaseClass === null || sameMemberInBaseClass === void 0 ? void 0 : sameMemberInBaseClass.childType : childType;
469
- (0, node_opcua_assert_1.default)(!innerClass);
470
- (0, node_opcua_assert_1.default)(!childBase);
471
- }
472
- }
473
- else {
474
- // the lass member has no HasTypeDefinition reference
475
- // may be is a method
476
- (0, node_opcua_assert_1.default)(!innerClass);
477
- (0, node_opcua_assert_1.default)(!childBase);
478
- }
479
- let classMember = {
480
- name,
481
- nodeClass,
482
- browseName,
483
- modellingRule,
484
- isOptional,
485
- classDef,
486
- description,
487
- typeDefinition,
488
- childType,
489
- suffix2: "",
490
- suffix: "",
491
- suffix3: "",
492
- suffixInstantiate: "",
493
- children,
494
- children2: [],
495
- typeToReference: [],
496
- //
497
- innerClass,
498
- childBase,
499
- chevrons: null
500
- };
501
- classMember.children2 = yield _extractLocalMembers(session, classMember, cache);
502
- if (nodeClass === node_opcua_data_model_1.NodeClass.Variable) {
503
- const extra = yield extractVariableExtra(session, nodeId, cache, classMember);
504
- classMember = Object.assign(Object.assign({}, classMember), extra);
505
- }
506
- return classMember;
507
- });
508
- }
509
- exports.extractClassMemberDef = extractClassMemberDef;
510
- function preDumpChildren(session, padding, classDef, f, cache) {
511
- return __awaiter(this, void 0, void 0, function* () {
512
- f = f || new node_opcua_utils_1.LineFile();
513
- for (const memberDef of classDef.members) {
514
- const { innerClass, suffix2, suffix3, nodeClass, childBase, chevrons } = memberDef;
515
- if (!innerClass || !childBase) {
516
- continue; // no need to expose inner class
517
- }
518
- cache.ensureImported(childBase);
519
- if (innerClass.name === "UAPubSubDiagnostics_counters" || innerClass.name === "UAProgramStateMachine_currentState") {
520
- // debugger;
521
- }
522
- const baseStuff = getBaseClassWithOmit2(memberDef);
523
- //f.write(`export interface ${innerClass.name}${suffix2} extends ${childBase.name}${suffix3} { // ${NodeClass[nodeClass]}`);
524
- f.write(`export interface ${innerClass.name}${suffix2} extends ${baseStuff} { // ${node_opcua_data_model_1.NodeClass[nodeClass]}`);
525
- yield dumpChildren(session, padding + " ", memberDef.children2, f, cache);
526
- f.write("}");
527
- }
528
- });
529
- }
530
- function dumpChildren(session, padding, children, f, cache) {
531
- f = f || new node_opcua_utils_1.LineFile();
532
- for (const def of children) {
533
- const { suffixInstantiate, name, childType, modellingRule, isOptional, description } = def;
534
- def.typeToReference.forEach((t) => cache.ensureImported(t));
535
- if (modellingRule === "MandatoryPlaceholder" || modellingRule === "OptionalPlaceholder")
536
- continue;
537
- cache.ensureImported(childType);
538
- const adjustedName = toJavascritPropertyName(name, { ignoreConflictingName: true });
539
- if (description.text) {
540
- f.write(`${padding}/**`);
541
- f.write(`${padding} * ${name || ""}`);
542
- f.write(toComment(`${padding} * `, description.text || ""));
543
- f.write(`${padding} */`);
544
- }
545
- f.write(`${padding}${quotifyIfNecessary(adjustedName)}${isOptional ? "?" : ""}: ${childType.name}${suffixInstantiate || ""};`);
546
- }
547
- }
548
- // now from other namespace
549
- const getSubSymbolList = (s) => {
550
- const subSymbolList = [];
551
- for (const [subSymbol, count] of Object.entries(s.subSymbols)) {
552
- subSymbolList.push(subSymbol);
553
- }
554
- return subSymbolList;
555
- };
556
- function findUsedImport(namespaceIndex, cache) {
557
- const usedImport = [];
558
- // from standard types
559
- for (const imp of Object.keys(cache.imports)) {
560
- const symbolToImport = Object.keys(cache.imports[imp]).filter((f) => Object.prototype.hasOwnProperty.call(cache.requestedBasicTypes, f));
561
- if (symbolToImport.length == 0) {
562
- continue;
563
- }
564
- usedImport.push(imp);
565
- }
566
- // from namespace
567
- for (let ns = 0; ns < cache.requestedSymbols.namespace.length; ns++) {
568
- if (ns === namespaceIndex) {
569
- continue; // avoid self reference
570
- }
571
- const module = cache.namespace[ns].module;
572
- if (cache.requestedSymbols.namespace[ns] && Object.values(cache.requestedSymbols.namespace[ns]).length > 0) {
573
- usedImport.push(module);
574
- }
575
- }
576
- return usedImport;
577
- }
578
- exports.findUsedImport = findUsedImport;
579
- function dumpUsedExport(currentType, namespaceIndex, cache, f) {
580
- f = f || new node_opcua_utils_1.LineFile();
581
- for (const imp of Object.keys(cache.imports)) {
582
- const symbolToImport = Object.keys(cache.imports[imp]).filter((f) => f !== currentType && Object.prototype.hasOwnProperty.call(cache.requestedBasicTypes, f));
583
- if (symbolToImport.length == 0) {
584
- continue;
585
- }
586
- f.write(`import { ${symbolToImport.join(", ")} } from "${imp}"`);
587
- }
588
- for (let ns = 0; ns < cache.requestedSymbols.namespace.length; ns++) {
589
- const n = cache.namespace[ns];
590
- const sourceFolder = n.sourceFolder;
591
- const module = n.module;
592
- if (ns === namespaceIndex) {
593
- // include individuals stuff
594
- for (const [symbol, s] of Object.entries(cache.requestedSymbols.namespace[ns].symbols).filter((a) => a[0] !== currentType)) {
595
- const filename = (0, to_filename_1.toFilename)(symbol);
596
- const subSymbolList = getSubSymbolList(s);
597
- f.write(`import { ${subSymbolList.join(", ")} } from "./${filename}"`);
598
- }
599
- }
600
- else {
601
- if (cache.requestedSymbols.namespace[ns]) {
602
- for (const [symbol, s] of Object.entries(cache.requestedSymbols.namespace[ns].symbols)) {
603
- const subSymbolList = getSubSymbolList(s);
604
- const filename = (0, to_filename_1.toFilename)(symbol);
605
- f.write(`import { ${subSymbolList.join(", ")} } from "${module}/source/${filename}"`);
606
- }
607
- }
608
- }
609
- }
610
- return f.toString();
611
- }
612
- function toComment(prefix, description) {
613
- const d = wrapText(description);
614
- return d
615
- .split("\n")
616
- .map((x) => prefix + x)
617
- .join("\n");
618
- }
619
- // eslint-disable-next-line max-statements
620
- function _exportDataTypeToTypescript(session, nodeId, cache, f) {
621
- return __awaiter(this, void 0, void 0, function* () {
622
- f = f || new node_opcua_utils_1.LineFile();
623
- const importCollector = (i) => {
624
- cache.ensureImported(i);
625
- };
626
- const nodeClass = node_opcua_data_model_1.NodeClass.DataType;
627
- const description = yield (0, utils_1.getDescription)(session, nodeId);
628
- const definition = yield (0, utils_1.getDefinition)(session, nodeId);
629
- const browseName = yield (0, utils_1.getBrowseName)(session, nodeId);
630
- const isAbstract = yield (0, utils_1.getIsAbstract)(session, nodeId);
631
- const interfaceImport = (0, cache_1.makeTypeNameNew)(nodeClass, definition, browseName);
632
- const interfaceName = interfaceImport.name;
633
- const superType = yield (0, utils_1.getSubtypeNodeId)(session, nodeId);
634
- const baseInterfaceImport = (0, cache_1.makeTypeNameNew)(nodeClass, definition, superType.browseName);
635
- cache.ensureImported(baseInterfaceImport);
636
- const baseInterfaceName = baseInterfaceImport.name;
637
- // f.write(superType.toString());
638
- f.write(`/**`);
639
- if (description.text) {
640
- f.write(toComment(" * ", description.text || ""));
641
- f.write(` *`);
642
- }
643
- f.write(` * | |${f1(" ")}|`);
644
- f.write(` * |-----------|${f2("-")}|`);
645
- f.write(` * | namespace |${f1(cache.namespace[nodeId.namespace].namespaceUri)}|`);
646
- f.write(` * | nodeClass |${f1(node_opcua_data_model_1.NodeClass[nodeClass])}|`);
647
- f.write(` * | name |${f1(browseName.toString())}|`);
648
- f.write(` * | isAbstract|${f1(isAbstract.toString())}|`);
649
- f.write(` */`);
650
- let type = "basic";
651
- if (definition instanceof node_opcua_types_1.EnumDefinition) {
652
- type = "enum";
653
- f.write(`export enum ${interfaceName} {`);
654
- for (const field of definition.fields) {
655
- if (field.description.text) {
656
- f.write(` /**`);
657
- f.write(toComment(" * ", field.description.text || ""));
658
- f.write(` */`);
659
- }
660
- f.write(` ${quotifyIfNecessary(field.name)} = ${field.value[1]},`);
661
- }
662
- f.write(`}`);
663
- }
664
- else if (definition instanceof node_opcua_types_1.StructureDefinition) {
665
- type = "structure";
666
- if (interfaceName === "DTStructure") {
667
- f.write(`export interface ${interfaceName} {`);
668
- }
669
- else {
670
- f.write(`export interface ${interfaceName} extends ${baseInterfaceName} {`);
671
- }
672
- for (const field of definition.fields) {
673
- const fieldName = toJavascritPropertyName(field.name, { ignoreConflictingName: false });
674
- // special case ! fieldName=
675
- if (field.description.text) {
676
- f.write(`/** ${field.description.text}*/`);
677
- }
678
- let ar = "";
679
- if (field.valueRank >= 1) {
680
- ar = "[]";
681
- }
682
- const { dataType, jtype } = yield getCorrepondingJavascriptType(session, field.dataType, cache, importCollector);
683
- f.write(` ${quotifyIfNecessary(fieldName)}: ${jtype}${ar}; // ${node_opcua_variant_1.DataType[dataType]} ${field.dataType.toString()}`);
684
- }
685
- f.write(`}`);
686
- }
687
- else {
688
- type = "basic";
689
- f.write(`// NO DEFINITION`);
690
- f.write(`export interface ${interfaceName} extends ${baseInterfaceName} {`);
691
- f.write(`}`);
692
- // throw new Error("Invalid " + definition?.constructor.name);
693
- }
694
- return { type, content: f.toString(), typeName: interfaceName };
695
- });
696
- }
697
- exports._exportDataTypeToTypescript = _exportDataTypeToTypescript;
698
- function calculateChevrons(classDef, classDefDerived) {
699
- const { nodeClass, dataType, dataTypeName } = classDef;
700
- let chevronsDef = "";
701
- let chevronsUse = "";
702
- let chevronsExtend = "";
703
- if (nodeClass !== node_opcua_data_model_1.NodeClass.VariableType) {
704
- return { chevronsDef, chevronsUse, chevronsExtend };
705
- }
706
- if (!isUnspecifiedDataType(dataType)) {
707
- chevronsDef = `<T extends ${dataTypeName}/*j*/>`;
708
- chevronsUse = "<T/*k*/>";
709
- if (classDefDerived) {
710
- if (isUnspecifiedDataType(classDefDerived.dataType)) {
711
- chevronsExtend = `<T, /*i*/DataType.${node_opcua_variant_1.DataType[dataType]}>`;
712
- }
713
- else {
714
- chevronsExtend = `<T/*h*/>`;
715
- }
716
- }
717
- }
718
- else {
719
- // classDef.dataType === DataType.Null
720
- chevronsDef = `<T, DT extends DataType>`;
721
- if (classDefDerived) {
722
- if (isUnspecifiedDataType(classDefDerived.dataType)) {
723
- chevronsUse = "<T, /*m*/DT>";
724
- chevronsExtend = `<T/*g*/, DT>`;
725
- }
726
- else {
727
- chevronsUse = `<T, /*n*/DataType.${node_opcua_variant_1.DataType[classDefDerived.dataType]}>`;
728
- chevronsExtend = `<T, /*e*/DataType.${node_opcua_variant_1.DataType[classDefDerived.dataType]}>`;
729
- }
730
- }
731
- }
732
- return { chevronsDef, chevronsUse, chevronsExtend };
733
- }
734
- // find the structure member that are already in base structure definition and that are replicated here
735
- // we will have to use the Omit<Base,"member1" |"member2"> typescript pattern to avoid issues
736
- function extractMembersRecursively(classDef) {
737
- if (!classDef) {
738
- return [];
739
- }
740
- const m = classDef.members.map((m) => m.name);
741
- if (classDef.baseClassDef) {
742
- const m2 = extractMembersRecursively(classDef.baseClassDef);
743
- return m.concat(m2);
744
- }
745
- return m;
746
- }
747
- function getBaseClassWithOmit(classDef) {
748
- const { baseInterfaceName, members } = classDef;
749
- const allMembers = extractMembersRecursively(classDef.baseClassDef);
750
- const conflictingMembers = members.filter((m) => allMembers.indexOf(m.name) !== -1);
751
- //console.log(allMembers.join(" "));
752
- if (conflictingMembers.length) {
753
- // console.log("conflictingMembers = ", conflictingMembers.map((a) => a.name).join(" "));
754
- }
755
- const chBase = calculateChevrons(classDef.baseClassDef, classDef);
756
- let baseStuff = `${baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name}${chBase.chevronsUse}`;
757
- if (conflictingMembers.length) {
758
- baseStuff = `Omit<${baseStuff}, ${conflictingMembers.map((a) => `"${a.name}"`).join("|")}>`;
759
- }
760
- return baseStuff;
761
- }
762
- function getBaseClassWithOmit2(classMember) {
763
- const members = classMember.children2;
764
- const allMembers = extractMembersRecursively(classMember.classDef);
765
- const conflictingMembers = members.filter((m) => allMembers.indexOf(m.name) !== -1);
766
- //console.log(allMembers.join(" "));
767
- if (conflictingMembers.length) {
768
- doDebug && console.log("conflictingMembers = ", conflictingMembers.map((a) => a.name).join(" "));
769
- }
770
- const childBase = classMember.childBase;
771
- let baseStuff = `${childBase === null || childBase === void 0 ? void 0 : childBase.name}${classMember.suffix3}`;
772
- if (conflictingMembers.length) {
773
- baseStuff = `Omit<${baseStuff}, ${conflictingMembers.map((a) => `"${a.name}"`).join("|")}>`;
774
- }
775
- return baseStuff;
776
- }
777
- /**
778
- * nodeId : a DataType, ReferenceType,AObjectType, VariableType node
779
- */
780
- // eslint-disable-next-line max-statements
781
- function _convertTypeToTypescript(session, nodeId, cache, f) {
782
- return __awaiter(this, void 0, void 0, function* () {
783
- f = f || new node_opcua_utils_1.LineFile();
784
- const nodeClass = yield (0, utils_1.getNodeClass)(session, nodeId);
785
- if (nodeClass === node_opcua_data_model_1.NodeClass.DataType) {
786
- return yield _exportDataTypeToTypescript(session, nodeId, cache, f);
787
- }
788
- const classDef = yield extractClassDefinition(session, nodeId, cache);
789
- // if (classDef.browseName.toString().match(/PubSubDiagnosticsWriterGroupType/)) {
790
- // debugger;
791
- // }
792
- const { dataTypeName, dataType, dataTypeNodeId, interfaceName, baseInterfaceName, browseName, description, isAbstract, members } = classDef;
793
- yield preDumpChildren(session, " ", classDef, f, cache);
794
- // f.write(superType.toString());
795
- f.write(`/**`);
796
- if (description.text) {
797
- f.write(toComment(" * ", description.text || ""));
798
- f.write(` *`);
799
- }
800
- f.write(` * | |${f1(" ")}|`);
801
- f.write(` * |----------------|${f2("-")}|`);
802
- f.write(` * |namespace |${f1(cache.namespace[nodeId.namespace].namespaceUri)}|`);
803
- f.write(` * |nodeClass |${f1(node_opcua_data_model_1.NodeClass[nodeClass])}|`);
804
- f.write(` * |typedDefinition |${f1(browseName.toString() + " " + nodeId.toString())}|`);
805
- if (nodeClass === node_opcua_data_model_1.NodeClass.VariableType) {
806
- f.write(` * |dataType |${f1(node_opcua_variant_1.DataType[dataType])}|`);
807
- f.write(` * |dataType Name |${f1(dataTypeName + " " + (dataTypeNodeId === null || dataTypeNodeId === void 0 ? void 0 : dataTypeNodeId.toString()))}|`);
808
- }
809
- f.write(` * |isAbstract |${f1(isAbstract.toString())}|`);
810
- f.write(` */`);
811
- // if (interfaceName.name === "UAOperationLimits") {
812
- // debugger;
813
- // }
814
- cache.ensureImported(baseInterfaceName);
815
- cache.ensureImported(Object.assign(Object.assign({}, baseInterfaceName), { name: baseInterfaceName.name + `${baseExtension}` }));
816
- const ch = calculateChevrons(classDef);
817
- if (nodeClass === node_opcua_data_model_1.NodeClass.VariableType) {
818
- if (classDef.dataTypeImport) {
819
- console.log(chalk.red(" ----------------> ", classDef.browseName));
820
- classDef.dataTypeImport.forEach((a) => {
821
- console.log(chalk.red(" ------------------------> ", a.module, a.name, a.namespace));
822
- });
823
- classDef.dataTypeImport.forEach(cache.ensureImported.bind(cache));
824
- }
825
- cache.referenceBasicType("DataType");
826
- const chevrons = calculateChevrons(classDef);
827
- const chevronsBase = calculateChevrons(classDef.baseClassDef, classDef);
828
- // Shall we cache.ensureImported({ ...baseInterfaceName!, module: dataTypeName, name: dataTypeName });
829
- const classBaseName = `${interfaceName.name}${baseExtension}${chevrons.chevronsDef}`;
830
- if ((baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name) === "UAVariableT") {
831
- f.write(`export interface ${classBaseName} {`);
832
- }
833
- else {
834
- const baseName = `${baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name}${baseExtension}${chevronsBase.chevronsExtend}`;
835
- f.write(`export interface ${classBaseName} extends ${baseName} {`);
836
- }
837
- }
838
- else {
839
- const classBaseName = `${interfaceName.name}${baseExtension}`;
840
- if ((baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name) === "UAObject") {
841
- f.write(`export interface ${classBaseName} {`);
842
- }
843
- else {
844
- const baseName = `${baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name}${baseExtension}`;
845
- f.write(`export interface ${classBaseName} extends ${baseName} {`);
846
- }
847
- }
848
- yield dumpChildren(session, " ", members, f, cache);
849
- f.write(`}`);
850
- const baseStuff = getBaseClassWithOmit(classDef);
851
- if (nodeClass === node_opcua_data_model_1.NodeClass.VariableType) {
852
- cache.referenceBasicType("DataType");
853
- // if dataType is a extension object we can simpligy by forcing DT
854
- const className = `${interfaceName.name}${ch.chevronsDef}`;
855
- const c = isUnspecifiedDataType(dataType) ? "<T, DT /*A*/>" : "<T /*B*/>";
856
- const classBaseName = `${interfaceName.name}${baseExtension}${c}`;
857
- f.write(`export interface ${className} extends ${baseStuff}, ${classBaseName} {`);
858
- }
859
- else {
860
- const className = `${interfaceName.name}`;
861
- const classBaseName = `${interfaceName.name}${baseExtension}`;
862
- f.write(`export interface ${className} extends ${baseStuff}, ${classBaseName} {`);
863
- }
864
- f.write(`}`);
865
- return { type: "ua", content: f.toString(), typeName: interfaceName.name };
866
- });
867
- }
868
- exports._convertTypeToTypescript = _convertTypeToTypescript;
869
- function convertTypeToTypescript(session, nodeId, options, cache, f) {
870
- return __awaiter(this, void 0, void 0, function* () {
871
- f = new node_opcua_utils_1.LineFile();
872
- cache = cache || (yield (0, cache_1.constructCache)(session, options));
873
- const { type, content, typeName } = yield _convertTypeToTypescript(session, nodeId, cache);
874
- f.write(`// ----- this file has been automatically generated - do not edit`);
875
- f.write(dumpUsedExport(typeName, nodeId.namespace, cache));
876
- f.write(content);
877
- const folder = cache.namespace[nodeId.namespace].sourceFolder;
878
- const module = cache.namespace[nodeId.namespace].module;
879
- const filename = (0, to_filename_1.toFilename)(typeName);
880
- const dependencies = findUsedImport(nodeId.namespace, cache);
881
- return { type, content: f.toString(), folder, module, filename, dependencies };
882
- });
883
- }
884
- exports.convertTypeToTypescript = convertTypeToTypescript;
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.convertTypeToTypescript = exports._convertTypeToTypescript = exports._exportDataTypeToTypescript = exports.findUsedImport = exports.extractClassMemberDef = exports.checkIfShouldExposeInnerDefinition = exports.findClassMember = exports.extractClassDefinition = exports.makeTypeName2 = exports.convertDataTypeToTypescript = void 0;
13
+ const chalk = require("chalk");
14
+ const wrap = require("wordwrap");
15
+ const node_opcua_data_model_1 = require("node-opcua-data-model");
16
+ const node_opcua_types_1 = require("node-opcua-types");
17
+ const node_opcua_utils_1 = require("node-opcua-utils");
18
+ const node_opcua_variant_1 = require("node-opcua-variant");
19
+ const node_opcua_assert_1 = require("node-opcua-assert");
20
+ const node_opcua_debug_1 = require("node-opcua-debug");
21
+ const utils_1 = require("./private/utils");
22
+ const cache_1 = require("./private/cache");
23
+ const to_filename_1 = require("./private/to_filename");
24
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)("typescript");
25
+ const doDebug = false;
26
+ const wrapText = wrap(0, 50);
27
+ const f2 = (str) => str.padEnd(50, "-");
28
+ const f1 = (str) => str.padEnd(50, " ");
29
+ const baseExtension = "_Base";
30
+ function convertDataTypeToTypescript(session, dataTypeId) {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ const definition = yield (0, utils_1.getDefinition)(session, dataTypeId);
33
+ const browseName = yield (0, utils_1.getBrowseName)(session, dataTypeId);
34
+ const dataTypeTypescriptName = `UA${browseName.name.toString()}`;
35
+ const f = new node_opcua_utils_1.LineFile();
36
+ if (definition && definition instanceof node_opcua_types_1.StructureDefinition) {
37
+ f.write(`interface ${dataTypeTypescriptName} {`);
38
+ for (const field of definition.fields || []) {
39
+ /** */
40
+ }
41
+ f.write(`}`);
42
+ }
43
+ });
44
+ }
45
+ exports.convertDataTypeToTypescript = convertDataTypeToTypescript;
46
+ // to avoid clashes
47
+ function toJavascritPropertyName(childName, { ignoreConflictingName }) {
48
+ childName = (0, node_opcua_utils_1.lowerFirstLetter)(childName);
49
+ if (ignoreConflictingName) {
50
+ if (childName === "namespaceUri") {
51
+ childName = "$namespaceUri";
52
+ }
53
+ if (childName === "rolePermissions") {
54
+ childName = "$rolePermissions";
55
+ }
56
+ if (childName === "displayName") {
57
+ childName = "$displayName";
58
+ }
59
+ if (childName === "eventNotifier") {
60
+ childName = "$eventNotifier";
61
+ }
62
+ if (childName === "description") {
63
+ childName = "$description";
64
+ }
65
+ }
66
+ return childName.replace(/</g, "$").replace(/>/g, "$").replace(/ |\./g, "_").replace(/#/g, "_");
67
+ }
68
+ function quotifyIfNecessary(s) {
69
+ if (s.match(/(^[^a-zA-Z])|([^a-zA-Z_0-9])/)) {
70
+ return `"${s}"`;
71
+ }
72
+ if (s === "nodeClass") {
73
+ return `["$nodeClass"]`;
74
+ }
75
+ return s;
76
+ }
77
+ function getCorrepondingJavascriptType2(session, nodeId, dataTypeNodeId, cache, importCollect) {
78
+ return __awaiter(this, void 0, void 0, function* () {
79
+ const q = yield getCorrepondingJavascriptType(session, dataTypeNodeId, cache, importCollect);
80
+ const valueRank = yield (0, utils_1.getValueRank)(session, nodeId);
81
+ return { dataType: q.dataType, jtype: q.jtype + (valueRank >= 1 ? "[]" : "") };
82
+ });
83
+ }
84
+ // eslint-disable-next-line complexity
85
+ function getCorrepondingJavascriptType(session, dataTypeNodeId, cache, importCollect) {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ const dataType = yield (0, utils_1.convertNodeIdToDataTypeAsync)(session, dataTypeNodeId);
88
+ const referenceBasicType = (name) => {
89
+ const t = { name, namespace: -1, module: "BasicType" };
90
+ importCollect && importCollect(t);
91
+ cache.ensureImported(t);
92
+ return t.name;
93
+ };
94
+ if (dataType === node_opcua_variant_1.DataType.ExtensionObject) {
95
+ const jtypeImport = yield (0, cache_1.referenceExtensionObject)(session, dataTypeNodeId);
96
+ const jtype = jtypeImport.name;
97
+ importCollect && importCollect(jtypeImport);
98
+ return { dataType, jtype: jtype };
99
+ }
100
+ switch (dataType) {
101
+ case node_opcua_variant_1.DataType.Null:
102
+ return { dataType, jtype: "undefined" };
103
+ case node_opcua_variant_1.DataType.Boolean:
104
+ return { dataType, jtype: "boolean" };
105
+ case node_opcua_variant_1.DataType.Byte:
106
+ return { dataType, jtype: referenceBasicType("Byte") };
107
+ case node_opcua_variant_1.DataType.ByteString:
108
+ return { dataType, jtype: "Buffer" };
109
+ case node_opcua_variant_1.DataType.DataValue:
110
+ return { dataType, jtype: referenceBasicType("DataValue") };
111
+ case node_opcua_variant_1.DataType.DateTime:
112
+ return { dataType, jtype: "Date" };
113
+ case node_opcua_variant_1.DataType.DiagnosticInfo:
114
+ return { dataType, jtype: referenceBasicType("DiagnosticInfo") };
115
+ case node_opcua_variant_1.DataType.Double:
116
+ return { dataType, jtype: "number" };
117
+ case node_opcua_variant_1.DataType.Float:
118
+ return { dataType, jtype: "number" };
119
+ case node_opcua_variant_1.DataType.Guid:
120
+ return { dataType, jtype: referenceBasicType("Guid") };
121
+ case node_opcua_variant_1.DataType.Int16:
122
+ return { dataType, jtype: referenceBasicType("Int16") };
123
+ case node_opcua_variant_1.DataType.Int32:
124
+ return { dataType, jtype: referenceBasicType("Int32") };
125
+ case node_opcua_variant_1.DataType.UInt16:
126
+ return { dataType, jtype: referenceBasicType("UInt16") };
127
+ case node_opcua_variant_1.DataType.UInt32:
128
+ return { dataType, jtype: referenceBasicType("UInt32") };
129
+ case node_opcua_variant_1.DataType.UInt64:
130
+ return { dataType, jtype: referenceBasicType("UInt64") };
131
+ case node_opcua_variant_1.DataType.Int64:
132
+ return { dataType, jtype: referenceBasicType("Int64") };
133
+ case node_opcua_variant_1.DataType.LocalizedText:
134
+ return { dataType, jtype: referenceBasicType("LocalizedText") };
135
+ case node_opcua_variant_1.DataType.NodeId:
136
+ return { dataType, jtype: referenceBasicType("NodeId") };
137
+ case node_opcua_variant_1.DataType.ExpandedNodeId:
138
+ return { dataType, jtype: referenceBasicType("ExpandedNodeId") };
139
+ case node_opcua_variant_1.DataType.QualifiedName:
140
+ return { dataType, jtype: referenceBasicType("QualifiedName") };
141
+ case node_opcua_variant_1.DataType.SByte:
142
+ return { dataType, jtype: referenceBasicType("SByte") };
143
+ case node_opcua_variant_1.DataType.StatusCode:
144
+ return { dataType, jtype: referenceBasicType("StatusCode") };
145
+ case node_opcua_variant_1.DataType.String:
146
+ return { dataType, jtype: referenceBasicType("UAString") };
147
+ case node_opcua_variant_1.DataType.Variant:
148
+ return { dataType, jtype: referenceBasicType("Variant") };
149
+ case node_opcua_variant_1.DataType.XmlElement:
150
+ return { dataType, jtype: referenceBasicType("UAString") };
151
+ default:
152
+ throw new Error("Unsupported " + dataType + " " + node_opcua_variant_1.DataType[dataType]);
153
+ }
154
+ });
155
+ }
156
+ function makeTypeName2(nodeClass, browseName, suffix) {
157
+ (0, node_opcua_assert_1.default)(browseName);
158
+ if (nodeClass === node_opcua_data_model_1.NodeClass.Method) {
159
+ return { name: "UAMethod", namespace: 0, module: "UAMethod" };
160
+ }
161
+ return (0, cache_1.makeTypeNameNew)(nodeClass, null, browseName, suffix);
162
+ }
163
+ exports.makeTypeName2 = makeTypeName2;
164
+ function extractClassDefinition(session, nodeId, cache) {
165
+ return __awaiter(this, void 0, void 0, function* () {
166
+ const extraImports = [];
167
+ const _c = cache.classDefCache || {};
168
+ cache.classDefCache = _c;
169
+ let classDef = _c[nodeId.toString()];
170
+ if (classDef) {
171
+ return classDef;
172
+ }
173
+ const nodeClass = yield (0, utils_1.getNodeClass)(session, nodeId);
174
+ if (nodeClass !== node_opcua_data_model_1.NodeClass.VariableType && nodeClass !== node_opcua_data_model_1.NodeClass.ObjectType) {
175
+ throw new Error("Invalid nodeClass " + node_opcua_data_model_1.NodeClass[nodeClass] + " nodeId " + nodeId.toString());
176
+ }
177
+ const browseName = yield (0, utils_1.getBrowseName)(session, nodeId);
178
+ const isAbstract = yield (0, utils_1.getIsAbstract)(session, nodeId);
179
+ const superType = (yield (0, utils_1.getSubtypeNodeIdIfAny)(session, nodeId)) || undefined;
180
+ const dataTypeNodeId = yield (0, utils_1.getDataTypeNodeId)(session, nodeId);
181
+ let dataTypeName = "";
182
+ let dataType = node_opcua_variant_1.DataType.Null;
183
+ let dataTypeImport = undefined;
184
+ if (nodeClass === node_opcua_data_model_1.NodeClass.VariableType) {
185
+ dataType = yield (0, utils_1.extractBasicDataType)(session, dataTypeNodeId);
186
+ const importCollector = (i) => {
187
+ extraImports.push(i);
188
+ cache.ensureImported(i);
189
+ };
190
+ const { jtype } = yield getCorrepondingJavascriptType2(session, nodeId, dataTypeNodeId, cache, importCollector);
191
+ dataTypeName = jtype; // with decoration
192
+ if (!(dataTypeNodeId === null || dataTypeNodeId === void 0 ? void 0 : dataTypeNodeId.isEmpty())) {
193
+ // "DT" + (await getBrowseName(session, dataTypeNodeId!))?.name! || "";
194
+ // const bn = await getBrowseName(session, dataTypeNodeId!);
195
+ dataTypeImport = extraImports; // makeTypeName2(NodeClass.DataType, bn);
196
+ }
197
+ }
198
+ const baseClassDef = !superType ? null : yield extractClassDefinition(session, superType.nodeId, cache);
199
+ const description = yield (0, utils_1.getDescription)(session, nodeId);
200
+ // const definition = await getDefinition(session, nodeId);
201
+ const interfaceName = makeTypeName2(nodeClass, browseName);
202
+ const baseInterfaceName = !superType ? null : makeTypeName2(nodeClass, superType.browseName);
203
+ // extract member
204
+ const children = yield (0, utils_1.getChildrenOrFolderElements)(session, nodeId);
205
+ const members = [];
206
+ classDef = {
207
+ nodeClass,
208
+ browseName,
209
+ isAbstract,
210
+ dataType,
211
+ dataTypeNodeId,
212
+ dataTypeName,
213
+ dataTypeImport,
214
+ superType,
215
+ baseClassDef,
216
+ description,
217
+ // definition,
218
+ children,
219
+ members,
220
+ interfaceName,
221
+ baseInterfaceName
222
+ };
223
+ _c[nodeId.toString()] = classDef;
224
+ for (const child of children) {
225
+ const c = yield extractClassMemberDef(session, child.nodeId, classDef, cache);
226
+ classDef.members.push(c);
227
+ }
228
+ return classDef;
229
+ });
230
+ }
231
+ exports.extractClassDefinition = extractClassDefinition;
232
+ function classify(session, refs) {
233
+ return __awaiter(this, void 0, void 0, function* () {
234
+ const r = {
235
+ Mandatory: [],
236
+ Optional: [],
237
+ MandatoryPlaceholder: [],
238
+ OptionalPlaceholder: [],
239
+ ExposesItsArray: []
240
+ };
241
+ for (const mm of refs) {
242
+ const modellingRule = yield (0, utils_1.getModellingRule)(session, mm.nodeId);
243
+ if (modellingRule) {
244
+ r[modellingRule] = r[modellingRule] || [];
245
+ r[modellingRule].push(mm);
246
+ }
247
+ }
248
+ return r;
249
+ });
250
+ }
251
+ function extractAllMembers(session, classDef, cache) {
252
+ return __awaiter(this, void 0, void 0, function* () {
253
+ const m = [...classDef.children];
254
+ let s = classDef;
255
+ while (s.baseClassDef) {
256
+ s = s.baseClassDef;
257
+ // start from top most class
258
+ // do not overwrite most top member definition, so we get mandatory stuff
259
+ for (const mm of s.children) {
260
+ const found = m.findIndex((r) => r.browseName.toString() === mm.browseName.toString());
261
+ if (found < 0) {
262
+ m.push(mm);
263
+ }
264
+ }
265
+ }
266
+ // now separate mandatory and optionals
267
+ const members = yield classify(session, m);
268
+ return members;
269
+ });
270
+ }
271
+ function findClassMember(session, browseName, baseParentDef, cache) {
272
+ return __awaiter(this, void 0, void 0, function* () {
273
+ const str = browseName.toString();
274
+ const r = baseParentDef.children.find((a) => a.browseName.toString() === str);
275
+ if (r) {
276
+ const d = yield extractClassMemberDef(session, r.nodeId, baseParentDef, cache);
277
+ return d;
278
+ }
279
+ const baseBaseParentDef = baseParentDef.superType && (yield extractClassDefinition(session, baseParentDef.superType.nodeId, cache));
280
+ if (!baseBaseParentDef) {
281
+ return null;
282
+ }
283
+ return yield findClassMember(session, browseName, baseBaseParentDef, cache);
284
+ });
285
+ }
286
+ exports.findClassMember = findClassMember;
287
+ function hasNewMaterial(referenceMembers, instanceMembers) {
288
+ const ref = referenceMembers.map((x) => x.browseName.toString()).sort();
289
+ const instance = instanceMembers.map((x) => x.browseName.toString()).sort();
290
+ for (const n of instance) {
291
+ if (ref.findIndex((x) => x === n) < 0) {
292
+ return true;
293
+ }
294
+ }
295
+ return false;
296
+ }
297
+ // we should expose an inner definition if
298
+ // - at least one mandatory in instnace doesn't exist in main.Mandatory
299
+ // - at least one optional in instnace doesn't exist in main.Mandatory
300
+ function checkIfShouldExposeInnerDefinition(main, instance) {
301
+ const hasNewStuff = hasNewMaterial(main.Mandatory, instance.Mandatory) || hasNewMaterial(main.Optional, instance.Optional);
302
+ return hasNewStuff;
303
+ }
304
+ exports.checkIfShouldExposeInnerDefinition = checkIfShouldExposeInnerDefinition;
305
+ function dump1(a) {
306
+ console.log("Mandatory = ", a.Mandatory.map((x) => x.browseName.toString())
307
+ .sort()
308
+ .join(" "));
309
+ console.log("Optional = ", a.Optional.map((x) => x.browseName.toString())
310
+ .sort()
311
+ .join(" "));
312
+ }
313
+ function _extractLocalMembers(session, classMember, cache) {
314
+ var _a;
315
+ return __awaiter(this, void 0, void 0, function* () {
316
+ const children2 = [];
317
+ for (const child of classMember.children) {
318
+ const nodeId = child.nodeId;
319
+ const browseName = yield (0, utils_1.getBrowseName)(session, nodeId);
320
+ const name = toJavascritPropertyName(browseName.name, { ignoreConflictingName: true });
321
+ const description = yield (0, utils_1.getDescription)(session, nodeId);
322
+ const modellingRule = yield (0, utils_1.getModellingRule)(session, nodeId);
323
+ const isOptional = modellingRule === "Optional";
324
+ const typeDefinition = yield (0, utils_1.getTypeDefOrBaseType)(session, nodeId);
325
+ const childInBase = (_a = classMember.classDef) === null || _a === void 0 ? void 0 : _a.members.find((a) => a.browseName.toString() === browseName.toString());
326
+ let childType;
327
+ if (childInBase) {
328
+ childType = childInBase.childType;
329
+ }
330
+ else {
331
+ const d = typeDefinition.nodeId.isEmpty() ? null : yield extractClassDefinition(session, typeDefinition.nodeId, cache);
332
+ childType = (d === null || d === void 0 ? void 0 : d.interfaceName) || { name: "UAMethod", module: "BasicType", namespace: -1 };
333
+ }
334
+ // may be childType is already
335
+ const { suffix, suffixInstantiate, typeToReference, chevrons } = yield extractVariableExtra(session, child.nodeId, cache, classMember);
336
+ const c = {
337
+ childType,
338
+ description,
339
+ isOptional,
340
+ modellingRule,
341
+ name,
342
+ suffix,
343
+ suffixInstantiate,
344
+ typeToReference,
345
+ chevrons
346
+ };
347
+ children2.push(c);
348
+ }
349
+ return children2;
350
+ });
351
+ }
352
+ function isUnspecifiedDataType(dataType) {
353
+ return dataType === node_opcua_variant_1.DataType.Null || dataType === node_opcua_variant_1.DataType.Variant;
354
+ }
355
+ function extractVariableExtra(session, nodeId, cache, classMember) {
356
+ var _a;
357
+ return __awaiter(this, void 0, void 0, function* () {
358
+ const typeToReference = [];
359
+ const importCollector = (i) => {
360
+ typeToReference.push(i);
361
+ cache.ensureImported(i);
362
+ };
363
+ const nodeClass = yield (0, utils_1.getNodeClass)(session, nodeId);
364
+ if (nodeClass === node_opcua_data_model_1.NodeClass.Variable) {
365
+ const dataTypeNodeId = yield (0, utils_1.getDataTypeNodeId)(session, nodeId);
366
+ const { dataType, jtype } = yield getCorrepondingJavascriptType2(session, nodeId, dataTypeNodeId, cache, importCollector);
367
+ cache && cache.referenceBasicType("DataType");
368
+ importCollector({ name: "DataType", namespace: -1, module: "BasicType" });
369
+ const t = isUnspecifiedDataType((_a = classMember.classDef) === null || _a === void 0 ? void 0 : _a.dataType);
370
+ const suffix = jtype === "undefined" || isUnspecifiedDataType(dataType)
371
+ ? `<any, any>`
372
+ : `<${jtype}${t ? `, /*c*/DataType.${node_opcua_variant_1.DataType[dataType]}` : ""}>`;
373
+ // const suffix2 = `<T${t ? `, /*a*/DT extends DataType` : ""}>`;
374
+ const suffix3 = `<T${t ? `, /*b*/DT` : ""}>`;
375
+ const typeDef = yield (0, utils_1.getTypeDefOrBaseType)(session, nodeId);
376
+ const typeDefCD = yield extractClassDefinition(session, typeDef.nodeId, cache);
377
+ const chevrons = calculateChevrons(typeDefCD, { dataType });
378
+ const suffix2 = chevrons.chevronsDef;
379
+ /** Suffix for instantiation
380
+ * if typeDef.dataType is not null, then we need to add a type argument
381
+ */
382
+ let suffixInstantiate = "";
383
+ if (isUnspecifiedDataType(dataType)) {
384
+ if (!isUnspecifiedDataType(typeDefCD.dataType)) {
385
+ suffixInstantiate = "<any>";
386
+ }
387
+ else {
388
+ suffixInstantiate = "<any, any>";
389
+ }
390
+ }
391
+ else {
392
+ if (!isUnspecifiedDataType(typeDefCD.dataType)) {
393
+ suffixInstantiate = `<${jtype}>`;
394
+ }
395
+ else {
396
+ suffixInstantiate = `<${jtype}, /*z*/DataType.${node_opcua_variant_1.DataType[dataType]}>`;
397
+ }
398
+ }
399
+ return { suffixInstantiate, suffix, suffix2, suffix3, dataTypeNodeId, dataType, jtype, typeToReference, chevrons };
400
+ }
401
+ return { suffix: "", typeToReference };
402
+ });
403
+ }
404
+ // eslint-disable-next-line max-statements
405
+ function extractClassMemberDef(session, nodeId, parentDef, cache) {
406
+ return __awaiter(this, void 0, void 0, function* () {
407
+ const nodeClass = yield (0, utils_1.getNodeClass)(session, nodeId);
408
+ const browseName = yield (0, utils_1.getBrowseName)(session, nodeId);
409
+ const name = toJavascritPropertyName(browseName.name, { ignoreConflictingName: true });
410
+ if (nodeClass !== node_opcua_data_model_1.NodeClass.Method && nodeClass !== node_opcua_data_model_1.NodeClass.Object && nodeClass !== node_opcua_data_model_1.NodeClass.Variable) {
411
+ throw new Error("Invalid property " + node_opcua_data_model_1.NodeClass[nodeClass] + " " + (browseName === null || browseName === void 0 ? void 0 : browseName.toString()) + " " + nodeId.toString());
412
+ }
413
+ const description = yield (0, utils_1.getDescription)(session, nodeId);
414
+ const children = yield (0, utils_1.getChildrenOrFolderElements)(session, nodeId);
415
+ const modellingRule = yield (0, utils_1.getModellingRule)(session, nodeId);
416
+ const isOptional = modellingRule === "Optional";
417
+ const typeDefinition = yield (0, utils_1.getTypeDefOrBaseType)(session, nodeId);
418
+ if (nodeClass !== node_opcua_data_model_1.NodeClass.Method && (!typeDefinition.browseName || !typeDefinition.browseName.name)) {
419
+ warningLog(typeDefinition.toString());
420
+ warningLog("cannot find typeDefinition for ", browseName.toString(), "( is the namespace loaded ?)");
421
+ }
422
+ let childType = makeTypeName2(nodeClass, typeDefinition.browseName);
423
+ const classDef = typeDefinition.nodeId.isEmpty() ? null : yield extractClassDefinition(session, typeDefinition.nodeId, cache);
424
+ let innerClass = null;
425
+ let childBase = null;
426
+ let shouldExposeInnerDefinition = false;
427
+ // find member exposed by type definition
428
+ const baseParentDef = parentDef.superType && (yield extractClassDefinition(session, parentDef.superType.nodeId, cache));
429
+ if (classDef && baseParentDef) {
430
+ const chevrons1 = calculateChevrons(classDef, baseParentDef);
431
+ (0, node_opcua_assert_1.default)(!innerClass);
432
+ // let's extract the member that are theorically defined in the member
433
+ const membersReference = yield extractAllMembers(session, classDef, cache);
434
+ // find member exposed by this member
435
+ const membersInstance = yield classify(session, children);
436
+ // if (name==="powerup") {
437
+ // dump1(membersReference);
438
+ // dump1(membersInstance);
439
+ // await extractAllMembers(session, classDef, cache);
440
+ // }
441
+ shouldExposeInnerDefinition = checkIfShouldExposeInnerDefinition(membersReference, membersInstance);
442
+ const sameMemberInBaseClass = baseParentDef && (yield findClassMember(session, browseName, baseParentDef, cache));
443
+ if (shouldExposeInnerDefinition) {
444
+ if (sameMemberInBaseClass) {
445
+ innerClass = {
446
+ module: parentDef.interfaceName.module,
447
+ name: parentDef.interfaceName.name + "_" + name,
448
+ namespace: nodeId.namespace
449
+ };
450
+ childBase = sameMemberInBaseClass.childType;
451
+ childType = innerClass;
452
+ }
453
+ else {
454
+ innerClass = {
455
+ module: parentDef.interfaceName.module,
456
+ name: parentDef.interfaceName.name + "_" + name,
457
+ namespace: nodeId.namespace
458
+ };
459
+ childBase = childType;
460
+ childType = innerClass;
461
+ }
462
+ (0, node_opcua_assert_1.default)(innerClass);
463
+ (0, node_opcua_assert_1.default)(childBase);
464
+ }
465
+ else {
466
+ // may not expose definition but we may want to used the augment typescript class defined in the definition
467
+ // we don't need to create an inner class ...
468
+ childType = sameMemberInBaseClass ? sameMemberInBaseClass === null || sameMemberInBaseClass === void 0 ? void 0 : sameMemberInBaseClass.childType : childType;
469
+ (0, node_opcua_assert_1.default)(!innerClass);
470
+ (0, node_opcua_assert_1.default)(!childBase);
471
+ }
472
+ }
473
+ else {
474
+ // the lass member has no HasTypeDefinition reference
475
+ // may be is a method
476
+ (0, node_opcua_assert_1.default)(!innerClass);
477
+ (0, node_opcua_assert_1.default)(!childBase);
478
+ }
479
+ let classMember = {
480
+ name,
481
+ nodeClass,
482
+ browseName,
483
+ modellingRule,
484
+ isOptional,
485
+ classDef,
486
+ description,
487
+ typeDefinition,
488
+ childType,
489
+ suffix2: "",
490
+ suffix: "",
491
+ suffix3: "",
492
+ suffixInstantiate: "",
493
+ children,
494
+ children2: [],
495
+ typeToReference: [],
496
+ //
497
+ innerClass,
498
+ childBase,
499
+ chevrons: null
500
+ };
501
+ classMember.children2 = yield _extractLocalMembers(session, classMember, cache);
502
+ if (nodeClass === node_opcua_data_model_1.NodeClass.Variable) {
503
+ const extra = yield extractVariableExtra(session, nodeId, cache, classMember);
504
+ classMember = Object.assign(Object.assign({}, classMember), extra);
505
+ }
506
+ return classMember;
507
+ });
508
+ }
509
+ exports.extractClassMemberDef = extractClassMemberDef;
510
+ function preDumpChildren(session, padding, classDef, f, cache) {
511
+ return __awaiter(this, void 0, void 0, function* () {
512
+ f = f || new node_opcua_utils_1.LineFile();
513
+ for (const memberDef of classDef.members) {
514
+ const { innerClass, suffix2, suffix3, nodeClass, childBase, chevrons } = memberDef;
515
+ if (!innerClass || !childBase) {
516
+ continue; // no need to expose inner class
517
+ }
518
+ cache.ensureImported(childBase);
519
+ if (innerClass.name === "UAPubSubDiagnostics_counters" || innerClass.name === "UAProgramStateMachine_currentState") {
520
+ // debugger;
521
+ }
522
+ const baseStuff = getBaseClassWithOmit2(memberDef);
523
+ //f.write(`export interface ${innerClass.name}${suffix2} extends ${childBase.name}${suffix3} { // ${NodeClass[nodeClass]}`);
524
+ f.write(`export interface ${innerClass.name}${suffix2} extends ${baseStuff} { // ${node_opcua_data_model_1.NodeClass[nodeClass]}`);
525
+ yield dumpChildren(session, padding + " ", memberDef.children2, f, cache);
526
+ f.write("}");
527
+ }
528
+ });
529
+ }
530
+ function dumpChildren(session, padding, children, f, cache) {
531
+ f = f || new node_opcua_utils_1.LineFile();
532
+ for (const def of children) {
533
+ const { suffixInstantiate, name, childType, modellingRule, isOptional, description } = def;
534
+ def.typeToReference.forEach((t) => cache.ensureImported(t));
535
+ if (modellingRule === "MandatoryPlaceholder" || modellingRule === "OptionalPlaceholder")
536
+ continue;
537
+ cache.ensureImported(childType);
538
+ const adjustedName = toJavascritPropertyName(name, { ignoreConflictingName: true });
539
+ if (description.text) {
540
+ f.write(`${padding}/**`);
541
+ f.write(`${padding} * ${name || ""}`);
542
+ f.write(toComment(`${padding} * `, description.text || ""));
543
+ f.write(`${padding} */`);
544
+ }
545
+ f.write(`${padding}${quotifyIfNecessary(adjustedName)}${isOptional ? "?" : ""}: ${childType.name}${suffixInstantiate || ""};`);
546
+ }
547
+ }
548
+ // now from other namespace
549
+ const getSubSymbolList = (s) => {
550
+ const subSymbolList = [];
551
+ for (const [subSymbol, count] of Object.entries(s.subSymbols)) {
552
+ subSymbolList.push(subSymbol);
553
+ }
554
+ return subSymbolList;
555
+ };
556
+ function findUsedImport(namespaceIndex, cache) {
557
+ const usedImport = [];
558
+ // from standard types
559
+ for (const imp of Object.keys(cache.imports)) {
560
+ const symbolToImport = Object.keys(cache.imports[imp]).filter((f) => Object.prototype.hasOwnProperty.call(cache.requestedBasicTypes, f));
561
+ if (symbolToImport.length == 0) {
562
+ continue;
563
+ }
564
+ usedImport.push(imp);
565
+ }
566
+ // from namespace
567
+ for (let ns = 0; ns < cache.requestedSymbols.namespace.length; ns++) {
568
+ if (ns === namespaceIndex) {
569
+ continue; // avoid self reference
570
+ }
571
+ const module = cache.namespace[ns].module;
572
+ if (cache.requestedSymbols.namespace[ns] && Object.values(cache.requestedSymbols.namespace[ns]).length > 0) {
573
+ usedImport.push(module);
574
+ }
575
+ }
576
+ return usedImport;
577
+ }
578
+ exports.findUsedImport = findUsedImport;
579
+ function dumpUsedExport(currentType, namespaceIndex, cache, f) {
580
+ f = f || new node_opcua_utils_1.LineFile();
581
+ for (const imp of Object.keys(cache.imports)) {
582
+ const symbolToImport = Object.keys(cache.imports[imp]).filter((f) => f !== currentType && Object.prototype.hasOwnProperty.call(cache.requestedBasicTypes, f));
583
+ if (symbolToImport.length == 0) {
584
+ continue;
585
+ }
586
+ f.write(`import { ${symbolToImport.join(", ")} } from "${imp}"`);
587
+ }
588
+ for (let ns = 0; ns < cache.requestedSymbols.namespace.length; ns++) {
589
+ const n = cache.namespace[ns];
590
+ const sourceFolder = n.sourceFolder;
591
+ const module = n.module;
592
+ if (ns === namespaceIndex) {
593
+ // include individuals stuff
594
+ for (const [symbol, s] of Object.entries(cache.requestedSymbols.namespace[ns].symbols).filter((a) => a[0] !== currentType)) {
595
+ const filename = (0, to_filename_1.toFilename)(symbol);
596
+ const subSymbolList = getSubSymbolList(s);
597
+ f.write(`import { ${subSymbolList.join(", ")} } from "./${filename}"`);
598
+ }
599
+ }
600
+ else {
601
+ if (cache.requestedSymbols.namespace[ns]) {
602
+ for (const [symbol, s] of Object.entries(cache.requestedSymbols.namespace[ns].symbols)) {
603
+ const subSymbolList = getSubSymbolList(s);
604
+ const filename = (0, to_filename_1.toFilename)(symbol);
605
+ f.write(`import { ${subSymbolList.join(", ")} } from "${module}/source/${filename}"`);
606
+ }
607
+ }
608
+ }
609
+ }
610
+ return f.toString();
611
+ }
612
+ function toComment(prefix, description) {
613
+ const d = wrapText(description);
614
+ return d
615
+ .split("\n")
616
+ .map((x) => prefix + x)
617
+ .join("\n");
618
+ }
619
+ // eslint-disable-next-line max-statements
620
+ function _exportDataTypeToTypescript(session, nodeId, cache, f) {
621
+ return __awaiter(this, void 0, void 0, function* () {
622
+ f = f || new node_opcua_utils_1.LineFile();
623
+ const importCollector = (i) => {
624
+ cache.ensureImported(i);
625
+ };
626
+ const nodeClass = node_opcua_data_model_1.NodeClass.DataType;
627
+ const description = yield (0, utils_1.getDescription)(session, nodeId);
628
+ const definition = yield (0, utils_1.getDefinition)(session, nodeId);
629
+ const browseName = yield (0, utils_1.getBrowseName)(session, nodeId);
630
+ const isAbstract = yield (0, utils_1.getIsAbstract)(session, nodeId);
631
+ const interfaceImport = (0, cache_1.makeTypeNameNew)(nodeClass, definition, browseName);
632
+ const interfaceName = interfaceImport.name;
633
+ const superType = yield (0, utils_1.getSubtypeNodeId)(session, nodeId);
634
+ const baseInterfaceImport = (0, cache_1.makeTypeNameNew)(nodeClass, definition, superType.browseName);
635
+ cache.ensureImported(baseInterfaceImport);
636
+ const baseInterfaceName = baseInterfaceImport.name;
637
+ // f.write(superType.toString());
638
+ f.write(`/**`);
639
+ if (description.text) {
640
+ f.write(toComment(" * ", description.text || ""));
641
+ f.write(` *`);
642
+ }
643
+ f.write(` * | |${f1(" ")}|`);
644
+ f.write(` * |-----------|${f2("-")}|`);
645
+ f.write(` * | namespace |${f1(cache.namespace[nodeId.namespace].namespaceUri)}|`);
646
+ f.write(` * | nodeClass |${f1(node_opcua_data_model_1.NodeClass[nodeClass])}|`);
647
+ f.write(` * | name |${f1(browseName.toString())}|`);
648
+ f.write(` * | isAbstract|${f1(isAbstract.toString())}|`);
649
+ f.write(` */`);
650
+ let type = "basic";
651
+ if (definition instanceof node_opcua_types_1.EnumDefinition) {
652
+ type = "enum";
653
+ f.write(`export enum ${interfaceName} {`);
654
+ for (const field of definition.fields) {
655
+ if (field.description.text) {
656
+ f.write(` /**`);
657
+ f.write(toComment(" * ", field.description.text || ""));
658
+ f.write(` */`);
659
+ }
660
+ f.write(` ${quotifyIfNecessary(field.name)} = ${field.value[1]},`);
661
+ }
662
+ f.write(`}`);
663
+ }
664
+ else if (definition instanceof node_opcua_types_1.StructureDefinition) {
665
+ type = "structure";
666
+ if (interfaceName === "DTStructure") {
667
+ f.write(`export interface ${interfaceName} {`);
668
+ }
669
+ else {
670
+ f.write(`export interface ${interfaceName} extends ${baseInterfaceName} {`);
671
+ }
672
+ for (const field of definition.fields) {
673
+ const fieldName = toJavascritPropertyName(field.name, { ignoreConflictingName: false });
674
+ // special case ! fieldName=
675
+ if (field.description.text) {
676
+ f.write(`/** ${field.description.text}*/`);
677
+ }
678
+ let ar = "";
679
+ if (field.valueRank >= 1) {
680
+ ar = "[]";
681
+ }
682
+ const { dataType, jtype } = yield getCorrepondingJavascriptType(session, field.dataType, cache, importCollector);
683
+ f.write(` ${quotifyIfNecessary(fieldName)}: ${jtype}${ar}; // ${node_opcua_variant_1.DataType[dataType]} ${field.dataType.toString()}`);
684
+ }
685
+ f.write(`}`);
686
+ }
687
+ else {
688
+ type = "basic";
689
+ f.write(`// NO DEFINITION`);
690
+ f.write(`export interface ${interfaceName} extends ${baseInterfaceName} {`);
691
+ f.write(`}`);
692
+ // throw new Error("Invalid " + definition?.constructor.name);
693
+ }
694
+ return { type, content: f.toString(), typeName: interfaceName };
695
+ });
696
+ }
697
+ exports._exportDataTypeToTypescript = _exportDataTypeToTypescript;
698
+ function calculateChevrons(classDef, classDefDerived) {
699
+ const { nodeClass, dataType, dataTypeName } = classDef;
700
+ let chevronsDef = "";
701
+ let chevronsUse = "";
702
+ let chevronsExtend = "";
703
+ if (nodeClass !== node_opcua_data_model_1.NodeClass.VariableType) {
704
+ return { chevronsDef, chevronsUse, chevronsExtend };
705
+ }
706
+ if (!isUnspecifiedDataType(dataType)) {
707
+ chevronsDef = `<T extends ${dataTypeName}/*j*/>`;
708
+ chevronsUse = "<T/*k*/>";
709
+ if (classDefDerived) {
710
+ if (isUnspecifiedDataType(classDefDerived.dataType)) {
711
+ chevronsExtend = `<T, /*i*/DataType.${node_opcua_variant_1.DataType[dataType]}>`;
712
+ }
713
+ else {
714
+ chevronsExtend = `<T/*h*/>`;
715
+ }
716
+ }
717
+ }
718
+ else {
719
+ // classDef.dataType === DataType.Null
720
+ chevronsDef = `<T, DT extends DataType>`;
721
+ if (classDefDerived) {
722
+ if (isUnspecifiedDataType(classDefDerived.dataType)) {
723
+ chevronsUse = "<T, /*m*/DT>";
724
+ chevronsExtend = `<T/*g*/, DT>`;
725
+ }
726
+ else {
727
+ chevronsUse = `<T, /*n*/DataType.${node_opcua_variant_1.DataType[classDefDerived.dataType]}>`;
728
+ chevronsExtend = `<T, /*e*/DataType.${node_opcua_variant_1.DataType[classDefDerived.dataType]}>`;
729
+ }
730
+ }
731
+ }
732
+ return { chevronsDef, chevronsUse, chevronsExtend };
733
+ }
734
+ // find the structure member that are already in base structure definition and that are replicated here
735
+ // we will have to use the Omit<Base,"member1" |"member2"> typescript pattern to avoid issues
736
+ function extractMembersRecursively(classDef) {
737
+ if (!classDef) {
738
+ return [];
739
+ }
740
+ const m = classDef.members.map((m) => m.name);
741
+ if (classDef.baseClassDef) {
742
+ const m2 = extractMembersRecursively(classDef.baseClassDef);
743
+ return m.concat(m2);
744
+ }
745
+ return m;
746
+ }
747
+ function getBaseClassWithOmit(classDef) {
748
+ const { baseInterfaceName, members } = classDef;
749
+ const allMembers = extractMembersRecursively(classDef.baseClassDef);
750
+ const conflictingMembers = members.filter((m) => allMembers.indexOf(m.name) !== -1);
751
+ //console.log(allMembers.join(" "));
752
+ if (conflictingMembers.length) {
753
+ // console.log("conflictingMembers = ", conflictingMembers.map((a) => a.name).join(" "));
754
+ }
755
+ const chBase = calculateChevrons(classDef.baseClassDef, classDef);
756
+ let baseStuff = `${baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name}${chBase.chevronsUse}`;
757
+ if (conflictingMembers.length) {
758
+ baseStuff = `Omit<${baseStuff}, ${conflictingMembers.map((a) => `"${a.name}"`).join("|")}>`;
759
+ }
760
+ return baseStuff;
761
+ }
762
+ function getBaseClassWithOmit2(classMember) {
763
+ const members = classMember.children2;
764
+ const allMembers = extractMembersRecursively(classMember.classDef);
765
+ const conflictingMembers = members.filter((m) => allMembers.indexOf(m.name) !== -1);
766
+ //console.log(allMembers.join(" "));
767
+ if (conflictingMembers.length) {
768
+ doDebug && console.log("conflictingMembers = ", conflictingMembers.map((a) => a.name).join(" "));
769
+ }
770
+ const childBase = classMember.childBase;
771
+ let baseStuff = `${childBase === null || childBase === void 0 ? void 0 : childBase.name}${classMember.suffix3}`;
772
+ if (conflictingMembers.length) {
773
+ baseStuff = `Omit<${baseStuff}, ${conflictingMembers.map((a) => `"${a.name}"`).join("|")}>`;
774
+ }
775
+ return baseStuff;
776
+ }
777
+ /**
778
+ * nodeId : a DataType, ReferenceType,AObjectType, VariableType node
779
+ */
780
+ // eslint-disable-next-line max-statements
781
+ function _convertTypeToTypescript(session, nodeId, cache, f) {
782
+ return __awaiter(this, void 0, void 0, function* () {
783
+ f = f || new node_opcua_utils_1.LineFile();
784
+ const nodeClass = yield (0, utils_1.getNodeClass)(session, nodeId);
785
+ if (nodeClass === node_opcua_data_model_1.NodeClass.DataType) {
786
+ return yield _exportDataTypeToTypescript(session, nodeId, cache, f);
787
+ }
788
+ const classDef = yield extractClassDefinition(session, nodeId, cache);
789
+ // if (classDef.browseName.toString().match(/PubSubDiagnosticsWriterGroupType/)) {
790
+ // debugger;
791
+ // }
792
+ const { dataTypeName, dataType, dataTypeNodeId, interfaceName, baseInterfaceName, browseName, description, isAbstract, members } = classDef;
793
+ yield preDumpChildren(session, " ", classDef, f, cache);
794
+ // f.write(superType.toString());
795
+ f.write(`/**`);
796
+ if (description.text) {
797
+ f.write(toComment(" * ", description.text || ""));
798
+ f.write(` *`);
799
+ }
800
+ f.write(` * | |${f1(" ")}|`);
801
+ f.write(` * |----------------|${f2("-")}|`);
802
+ f.write(` * |namespace |${f1(cache.namespace[nodeId.namespace].namespaceUri)}|`);
803
+ f.write(` * |nodeClass |${f1(node_opcua_data_model_1.NodeClass[nodeClass])}|`);
804
+ f.write(` * |typedDefinition |${f1(browseName.toString() + " " + nodeId.toString())}|`);
805
+ if (nodeClass === node_opcua_data_model_1.NodeClass.VariableType) {
806
+ f.write(` * |dataType |${f1(node_opcua_variant_1.DataType[dataType])}|`);
807
+ f.write(` * |dataType Name |${f1(dataTypeName + " " + (dataTypeNodeId === null || dataTypeNodeId === void 0 ? void 0 : dataTypeNodeId.toString()))}|`);
808
+ }
809
+ f.write(` * |isAbstract |${f1(isAbstract.toString())}|`);
810
+ f.write(` */`);
811
+ // if (interfaceName.name === "UAOperationLimits") {
812
+ // debugger;
813
+ // }
814
+ cache.ensureImported(baseInterfaceName);
815
+ cache.ensureImported(Object.assign(Object.assign({}, baseInterfaceName), { name: baseInterfaceName.name + `${baseExtension}` }));
816
+ const ch = calculateChevrons(classDef);
817
+ if (nodeClass === node_opcua_data_model_1.NodeClass.VariableType) {
818
+ if (classDef.dataTypeImport) {
819
+ console.log(chalk.red(" ----------------> ", classDef.browseName));
820
+ classDef.dataTypeImport.forEach((a) => {
821
+ console.log(chalk.red(" ------------------------> ", a.module, a.name, a.namespace));
822
+ });
823
+ classDef.dataTypeImport.forEach(cache.ensureImported.bind(cache));
824
+ }
825
+ cache.referenceBasicType("DataType");
826
+ const chevrons = calculateChevrons(classDef);
827
+ const chevronsBase = calculateChevrons(classDef.baseClassDef, classDef);
828
+ // Shall we cache.ensureImported({ ...baseInterfaceName!, module: dataTypeName, name: dataTypeName });
829
+ const classBaseName = `${interfaceName.name}${baseExtension}${chevrons.chevronsDef}`;
830
+ if ((baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name) === "UAVariableT") {
831
+ f.write(`export interface ${classBaseName} {`);
832
+ }
833
+ else {
834
+ const baseName = `${baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name}${baseExtension}${chevronsBase.chevronsExtend}`;
835
+ f.write(`export interface ${classBaseName} extends ${baseName} {`);
836
+ }
837
+ }
838
+ else {
839
+ const classBaseName = `${interfaceName.name}${baseExtension}`;
840
+ if ((baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name) === "UAObject") {
841
+ f.write(`export interface ${classBaseName} {`);
842
+ }
843
+ else {
844
+ const baseName = `${baseInterfaceName === null || baseInterfaceName === void 0 ? void 0 : baseInterfaceName.name}${baseExtension}`;
845
+ f.write(`export interface ${classBaseName} extends ${baseName} {`);
846
+ }
847
+ }
848
+ yield dumpChildren(session, " ", members, f, cache);
849
+ f.write(`}`);
850
+ const baseStuff = getBaseClassWithOmit(classDef);
851
+ if (nodeClass === node_opcua_data_model_1.NodeClass.VariableType) {
852
+ cache.referenceBasicType("DataType");
853
+ // if dataType is a extension object we can simpligy by forcing DT
854
+ const className = `${interfaceName.name}${ch.chevronsDef}`;
855
+ const c = isUnspecifiedDataType(dataType) ? "<T, DT /*A*/>" : "<T /*B*/>";
856
+ const classBaseName = `${interfaceName.name}${baseExtension}${c}`;
857
+ f.write(`export interface ${className} extends ${baseStuff}, ${classBaseName} {`);
858
+ }
859
+ else {
860
+ const className = `${interfaceName.name}`;
861
+ const classBaseName = `${interfaceName.name}${baseExtension}`;
862
+ f.write(`export interface ${className} extends ${baseStuff}, ${classBaseName} {`);
863
+ }
864
+ f.write(`}`);
865
+ return { type: "ua", content: f.toString(), typeName: interfaceName.name };
866
+ });
867
+ }
868
+ exports._convertTypeToTypescript = _convertTypeToTypescript;
869
+ function convertTypeToTypescript(session, nodeId, options, cache, f) {
870
+ return __awaiter(this, void 0, void 0, function* () {
871
+ f = new node_opcua_utils_1.LineFile();
872
+ cache = cache || (yield (0, cache_1.constructCache)(session, options));
873
+ const { type, content, typeName } = yield _convertTypeToTypescript(session, nodeId, cache);
874
+ f.write(`// ----- this file has been automatically generated - do not edit`);
875
+ f.write(dumpUsedExport(typeName, nodeId.namespace, cache));
876
+ f.write(content);
877
+ const folder = cache.namespace[nodeId.namespace].sourceFolder;
878
+ const module = cache.namespace[nodeId.namespace].module;
879
+ const filename = (0, to_filename_1.toFilename)(typeName);
880
+ const dependencies = findUsedImport(nodeId.namespace, cache);
881
+ return { type, content: f.toString(), folder, module, filename, dependencies };
882
+ });
883
+ }
884
+ exports.convertTypeToTypescript = convertTypeToTypescript;
885
885
  //# sourceMappingURL=convert_to_typescript.js.map