iobroker.javascript 8.9.2 → 9.0.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 (119) hide show
  1. package/README.md +7 -3
  2. package/admin/assets/{createSvgIcon-BdRvDw53.js → createSvgIcon-BQT-7-GS.js} +1 -1
  3. package/admin/assets/{docs-6na4NFtj.js → docs-BrInh2Pn.js} +2 -2
  4. package/admin/assets/index-B0RKH_iG.js +1329 -0
  5. package/admin/assets/index-CfuHVX2B.js +193 -0
  6. package/admin/assets/index-CuCs5aLs.js +5 -0
  7. package/admin/assets/index-tExaxF69.js +930 -0
  8. package/admin/assets/inheritsLoose--KnFDOw1.js +36 -0
  9. package/admin/assets/{useTheme-Cl1QmYFL.js → useTheme-DF6qfrtI.js} +1 -1
  10. package/admin/custom/assets/{Components-ChpTW7sE.js → Components-D9kRsHNY.js} +1 -1
  11. package/admin/custom/assets/{DefaultPropsProvider-CHpMCMgA.js → DefaultPropsProvider-9qubdy-V.js} +2 -2
  12. package/admin/custom/assets/{FilledInput-CtcQVKyj.js → FilledInput-BpuM_GyB.js} +1 -1
  13. package/admin/custom/assets/Tabs-CvEv0KOT.js +138 -0
  14. package/admin/custom/assets/ThemeProvider-DZTpMR8n.js +29 -0
  15. package/admin/custom/assets/{createSvgIcon-C_vAELFU.js → createSvgIcon-BQThUM-f.js} +1 -1
  16. package/admin/custom/assets/hostInit-CrAs5YZS.js +1 -1
  17. package/admin/custom/assets/{index-DwsbskQy.js → index-DIWNdd4a.js} +1 -1
  18. package/admin/custom/assets/index-DZqbj5K4.js +55 -0
  19. package/admin/custom/assets/{index-D5apCzjJ.js → index-Dbe-II7_.js} +6 -6
  20. package/admin/custom/assets/index-az76fZMP.js +904 -0
  21. package/admin/custom/assets/index-sawv1cUe.js +1399 -0
  22. package/admin/custom/assets/{virtualExposes-BPncCdUy.js → virtualExposes-BMKIjWrE.js} +2 -2
  23. package/admin/custom/customComponents.js +2 -2
  24. package/admin/custom/i18n/de.json +29 -29
  25. package/admin/custom/i18n/es.json +29 -29
  26. package/admin/custom/i18n/fr.json +29 -29
  27. package/admin/custom/i18n/it.json +29 -29
  28. package/admin/custom/i18n/nl.json +29 -29
  29. package/admin/custom/i18n/pl.json +29 -29
  30. package/admin/custom/i18n/pt.json +29 -29
  31. package/admin/custom/i18n/ru.json +29 -29
  32. package/admin/custom/i18n/uk.json +29 -29
  33. package/admin/custom/i18n/zh-cn.json +29 -29
  34. package/admin/google-blockly/blockly_compressed.js +875 -887
  35. package/admin/google-blockly/blocks_compressed.js +38 -41
  36. package/admin/google-blockly/javascript_compressed.js +19 -54
  37. package/admin/google-blockly/media/delete-icon.svg +1 -0
  38. package/admin/google-blockly/media/foldout-icon.svg +1 -0
  39. package/admin/google-blockly/media/resize-handle.svg +3 -0
  40. package/admin/jsonConfig.json +2 -0
  41. package/admin/mf-manifest.json +1 -1
  42. package/admin/remoteEntry.js +2 -2
  43. package/admin/tab.html +4 -4
  44. package/admin/vsFont/README.md +1 -1
  45. package/admin/vsFont/createJson.js +1 -1
  46. package/build-backend/lib/consts.js +346 -0
  47. package/build-backend/lib/consts.js.map +1 -0
  48. package/build-backend/lib/convert.js +120 -0
  49. package/build-backend/lib/convert.js.map +1 -0
  50. package/build-backend/lib/debug.js +163 -0
  51. package/build-backend/lib/debug.js.map +1 -0
  52. package/{lib → build-backend/lib}/debugger.js +261 -232
  53. package/build-backend/lib/debugger.js.map +1 -0
  54. package/build-backend/lib/eventObj.js +177 -0
  55. package/build-backend/lib/eventObj.js.map +1 -0
  56. package/build-backend/lib/inspect.js +728 -0
  57. package/build-backend/lib/inspect.js.map +1 -0
  58. package/build-backend/lib/javascript.d.ts +1972 -0
  59. package/{lib → build-backend/lib}/mirror.js +185 -182
  60. package/build-backend/lib/mirror.js.map +1 -0
  61. package/build-backend/lib/nodeModulesManagement.js +25 -0
  62. package/build-backend/lib/nodeModulesManagement.js.map +1 -0
  63. package/build-backend/lib/patternCompareFunctions.js +321 -0
  64. package/build-backend/lib/patternCompareFunctions.js.map +1 -0
  65. package/build-backend/lib/protectFs.js +477 -0
  66. package/build-backend/lib/protectFs.js.map +1 -0
  67. package/build-backend/lib/request.js +89 -0
  68. package/build-backend/lib/request.js.map +1 -0
  69. package/{lib → build-backend/lib}/sandbox.js +2046 -1852
  70. package/build-backend/lib/sandbox.js.map +1 -0
  71. package/build-backend/lib/scheduler.js +553 -0
  72. package/build-backend/lib/scheduler.js.map +1 -0
  73. package/build-backend/lib/tools.js +183 -0
  74. package/build-backend/lib/tools.js.map +1 -0
  75. package/build-backend/lib/typescriptSettings.js +39 -0
  76. package/build-backend/lib/typescriptSettings.js.map +1 -0
  77. package/build-backend/lib/typescriptTools.js +435 -0
  78. package/build-backend/lib/typescriptTools.js.map +1 -0
  79. package/build-backend/lib/utils.js +66 -0
  80. package/build-backend/lib/utils.js.map +1 -0
  81. package/{lib → build-backend/lib}/words.js +23 -30
  82. package/build-backend/lib/words.js.map +1 -0
  83. package/build-backend/main.js +2671 -0
  84. package/build-backend/main.js.map +1 -0
  85. package/build-backend/types.d.ts +742 -0
  86. package/docs/de/README.md +1 -1
  87. package/docs/en/README.md +1 -1
  88. package/docs/en/javascript.md +10 -6
  89. package/docs/ru/README.md +1 -1
  90. package/install/installTypings.js +34 -47
  91. package/io-package.json +14 -14
  92. package/package.json +14 -14
  93. package/admin/assets/index-DCkkMRRa.js +0 -1335
  94. package/admin/assets/index-DJfSBoBB.js +0 -192
  95. package/admin/assets/index-DTiA4WdK.js +0 -930
  96. package/admin/assets/index-qABB1JVe.js +0 -5
  97. package/admin/assets/inheritsLoose-BW-3V39H.js +0 -36
  98. package/admin/custom/assets/Tabs-C1KOyWRi.js +0 -137
  99. package/admin/custom/assets/ThemeProvider-Buvx5nSd.js +0 -29
  100. package/admin/custom/assets/index-BGCRznKh.js +0 -904
  101. package/admin/custom/assets/index-DfBPYXqA.js +0 -55
  102. package/admin/custom/assets/index-jIr6kOLK.js +0 -1398
  103. package/lib/adapter-config.d.ts +0 -16
  104. package/lib/consts.js +0 -83
  105. package/lib/convert.js +0 -106
  106. package/lib/debug.js +0 -154
  107. package/lib/eventObj.js +0 -201
  108. package/lib/inspect.js +0 -688
  109. package/lib/javascript.d.ts +0 -1858
  110. package/lib/nodeModulesManagement.js +0 -26
  111. package/lib/patternCompareFunctions.js +0 -391
  112. package/lib/protectFs.js +0 -401
  113. package/lib/request.js +0 -72
  114. package/lib/scheduler.js +0 -447
  115. package/lib/tools.js +0 -192
  116. package/lib/typescriptSettings.js +0 -44
  117. package/lib/typescriptTools.js +0 -529
  118. package/lib/utils.js +0 -87
  119. package/main.js +0 -2653
@@ -0,0 +1,435 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveTypescriptLibs = resolveTypescriptLibs;
4
+ exports.resolveTypings = resolveTypings;
5
+ exports.transformScriptBeforeCompilation = transformScriptBeforeCompilation;
6
+ exports.transformGlobalDeclarations = transformGlobalDeclarations;
7
+ exports.scriptIdToTSFilename = scriptIdToTSFilename;
8
+ const node_fs_1 = require("node:fs");
9
+ const node_path_1 = require("node:path");
10
+ const typescript_1 = require("typescript");
11
+ const tools_1 = require("./tools");
12
+ /**
13
+ * Resolves all TypeScript lib files for the editor
14
+ *
15
+ * @param targetLib The lib to target (e.g., es2017)
16
+ */
17
+ function resolveTypescriptLibs(targetLib) {
18
+ const typescriptLibRoot = (0, node_path_1.dirname)(require.resolve(`typescript/lib/lib.d.ts`));
19
+ const ret = {};
20
+ const libReferenceRegex = /\/\/\/ <reference lib=["']([^"']+)["'] \/>/g;
21
+ const matchAllLibs = (str) => (0, tools_1.matchAll)(libReferenceRegex, str).map(groups => groups[0]);
22
+ const libQueue = [targetLib];
23
+ while (libQueue.length > 0) {
24
+ const libName = libQueue.shift();
25
+ const filename = `lib.${libName}.d.ts`;
26
+ // Read the file and remember it in the return dictionary
27
+ const fileContent = (0, node_fs_1.readFileSync)((0, node_path_1.join)(typescriptLibRoot, filename), 'utf8');
28
+ ret[filename] = fileContent;
29
+ // If this file references another lib file, we need to load that too.
30
+ // A reference looks like this: /// <reference lib="es2015.core" />
31
+ // Find all libs we have not loaded yet
32
+ matchAllLibs(fileContent)
33
+ .filter(lib => !(`lib.${lib}.d.ts` in ret))
34
+ .forEach(lib => libQueue.push(lib));
35
+ }
36
+ return ret;
37
+ }
38
+ function normalizeDTSImport(filename) {
39
+ // An import is either...
40
+ // a normal import
41
+ if (filename.endsWith('.d.ts')) {
42
+ return filename;
43
+ }
44
+ // an extensionless import
45
+ if ((0, node_fs_1.existsSync)(`${filename}.d.ts`)) {
46
+ return `${filename}.d.ts`;
47
+ }
48
+ // or a directory import
49
+ return (0, node_path_1.join)(filename, 'index.d.ts');
50
+ }
51
+ /**
52
+ * Resolves the type declarations of a 3rd party package for the editor
53
+ *
54
+ * @param pkg The package whose typings we're interested in
55
+ * @param adapterScopedPackageName the package name on the system
56
+ * @param wrapInDeclareModule Whether the root file should be wrapped in `declare module "<pkg>" { ... }`
57
+ * @returns The found declarations or undefined if none were found
58
+ */
59
+ function resolveTypings(pkg, adapterScopedPackageName, wrapInDeclareModule) {
60
+ let packageJsonPath;
61
+ let packageJson;
62
+ let rootTypings;
63
+ let pkgIncludesTypings = true;
64
+ function tryToLoadPackage(path) {
65
+ try {
66
+ packageJsonPath = require.resolve(path);
67
+ packageJson = require(packageJsonPath);
68
+ rootTypings =
69
+ typeof packageJson.types === 'string'
70
+ ? packageJson.types
71
+ : typeof packageJson.typings === 'string'
72
+ ? packageJson.typings
73
+ : undefined;
74
+ }
75
+ catch {
76
+ /* ignore */
77
+ }
78
+ }
79
+ // First, try to resolve the package itself in case it brings its own typings
80
+ tryToLoadPackage(`${adapterScopedPackageName}/package.json`);
81
+ if (!rootTypings) {
82
+ tryToLoadPackage(`${pkg}/package.json`);
83
+ }
84
+ // If that didn't work, try again with the @types version of the package
85
+ if (!rootTypings) {
86
+ tryToLoadPackage(`@types/${pkg}/package.json`);
87
+ pkgIncludesTypings = false;
88
+ }
89
+ // TODO: If that didn't work, download @types/<packagename> and retry the previous step
90
+ // Nothing to do here since we found no packages
91
+ if (!rootTypings) {
92
+ return undefined;
93
+ }
94
+ if (!packageJsonPath) {
95
+ return undefined;
96
+ }
97
+ const packageRoot = (0, node_path_1.dirname)(packageJsonPath);
98
+ const normalizeImportPath = (filename) => (0, node_path_1.normalize)(`node_modules/${pkgIncludesTypings ? adapterScopedPackageName : `@types/${pkg}`}/${(0, node_path_1.relative)(packageRoot, filename)}`).replace(/\\/g, '/');
99
+ const ret = {};
100
+ // We need to look at `import/export ... from 'modulename'` and `/// <reference path='...' />`
101
+ const importDtsRegex = /^\s*(?:import|export) .+ from ["'](\.+\/[^"']+)["']/g;
102
+ const pathReferenceRegex = /\/\/\/ <reference path=["']([^"']+)["'] \/>/g;
103
+ const matchAllImports = (str) => [...(0, tools_1.matchAll)(importDtsRegex, str), ...(0, tools_1.matchAll)(pathReferenceRegex, str)].map(groups => groups[0]);
104
+ // the paths are relative to the package.json - we need an absolute path to read the files
105
+ rootTypings = (0, node_path_1.join)(packageRoot, rootTypings);
106
+ // some @types packages specify `index` as their typings file instead of `index.d.ts`
107
+ rootTypings = normalizeDTSImport(rootTypings);
108
+ // include package.json in typings, so TypeScript can look up the correct entry point
109
+ const relativePath = `node_modules/${pkgIncludesTypings ? '' : '@types/'}${pkg}/package.json`.replace(/\\/g, '/');
110
+ ret[relativePath] = JSON.stringify(packageJson);
111
+ // Used to test whether a .d.ts file already uses "declare module" or not
112
+ const declareModuleRegex = /^\s*declare module/gm;
113
+ // recursively load all typings
114
+ const definitionQueue = [rootTypings];
115
+ while (definitionQueue.length > 0) {
116
+ const filename = definitionQueue.shift();
117
+ const dirName = (0, node_path_1.dirname)(filename);
118
+ // Read the file and remember it in the return dictionary
119
+ let fileContent;
120
+ try {
121
+ fileContent = (0, node_fs_1.readFileSync)(filename, 'utf8');
122
+ }
123
+ catch (e) {
124
+ // The typings are malformed
125
+ console.error(`Failed to load definitions for ${pkg}: ${e.toString()}`);
126
+ // Since we cannot use them, return undefined
127
+ return undefined;
128
+ }
129
+ // We need to store the filename relative to the base dir
130
+ const relativePath = normalizeImportPath(filename);
131
+ // If necessary, wrap the root typings (only those!)
132
+ ret[relativePath] =
133
+ wrapInDeclareModule && filename === rootTypings && !declareModuleRegex.test(fileContent)
134
+ ? `declare module "${pkg}" { ${fileContent} }`
135
+ : fileContent;
136
+ // If this file references another .d.ts file, we need to load that too
137
+ matchAllImports(fileContent)
138
+ // resolve the file relative to the current directory
139
+ .map(file => (0, node_path_1.join)(dirName, file))
140
+ // find out the correct path of the file we want to import
141
+ .map(normalizeDTSImport)
142
+ // Find all libs we have not loaded yet
143
+ .filter(file => !(normalizeImportPath(file) in ret))
144
+ .forEach(file => definitionQueue.push(file));
145
+ }
146
+ // Avoid returning empty declarations
147
+ if (Object.keys(ret).length === 0) {
148
+ return undefined;
149
+ }
150
+ return ret;
151
+ }
152
+ /**
153
+ * @param s Statement to check whether it must be hoisted to the top of the file
154
+ * @param isGlobal Whether this is a global script or a normal one
155
+ */
156
+ function mustBeHoisted(s, isGlobal) {
157
+ return !!(
158
+ // Import/export statements must be moved to the top
159
+ ((0, typescript_1.isImportDeclaration)(s) ||
160
+ (0, typescript_1.isImportEqualsDeclaration)(s) ||
161
+ (0, typescript_1.isExportDeclaration)(s) ||
162
+ (0, typescript_1.isExportAssignment)(s) ||
163
+ // as well as many declarations
164
+ (0, typescript_1.isTypeAliasDeclaration)(s) ||
165
+ (0, typescript_1.isInterfaceDeclaration)(s) ||
166
+ (0, typescript_1.isModuleDeclaration)(s) ||
167
+ (0, typescript_1.isEnumDeclaration)(s) ||
168
+ (isGlobal &&
169
+ // in global scripts we don't wrap classes and functions, so they can be accessed from non-global scripts
170
+ ((0, typescript_1.isClassDeclaration)(s) || (0, typescript_1.isFunctionDeclaration)(s))) ||
171
+ // and declare ... / export ... statements
172
+ s.modifiers?.some(s => s.kind === typescript_1.SyntaxKind.DeclareKeyword || s.kind === typescript_1.SyntaxKind.ExportKeyword)));
173
+ }
174
+ function canBeExported(s) {
175
+ return (
176
+ // const, let, var
177
+ (0, typescript_1.isVariableStatement)(s) ||
178
+ // type, interface, enum, class, function
179
+ (0, typescript_1.isTypeAliasDeclaration)(s) ||
180
+ (0, typescript_1.isInterfaceDeclaration)(s) ||
181
+ (0, typescript_1.isEnumDeclaration)(s) ||
182
+ (0, typescript_1.isClassDeclaration)(s) ||
183
+ (0, typescript_1.isFunctionDeclaration)(s));
184
+ }
185
+ function addExportModifier(s) {
186
+ let modifiers;
187
+ // Add export modifiers
188
+ if (!s.modifiers) {
189
+ modifiers = [typescript_1.factory.createModifier(typescript_1.SyntaxKind.ExportKeyword)];
190
+ }
191
+ else if (!s.modifiers.some(m => m.kind === typescript_1.SyntaxKind.ExportKeyword)) {
192
+ modifiers = [...s.modifiers, typescript_1.factory.createModifier(typescript_1.SyntaxKind.ExportKeyword)];
193
+ }
194
+ else {
195
+ return s;
196
+ }
197
+ if ((0, typescript_1.isVariableStatement)(s)) {
198
+ return typescript_1.factory.updateVariableStatement(s, modifiers, s.declarationList);
199
+ }
200
+ if ((0, typescript_1.isTypeAliasDeclaration)(s)) {
201
+ return typescript_1.factory.updateTypeAliasDeclaration(s, modifiers, s.name, s.typeParameters, s.type);
202
+ }
203
+ if ((0, typescript_1.isInterfaceDeclaration)(s)) {
204
+ return typescript_1.factory.updateInterfaceDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);
205
+ }
206
+ if ((0, typescript_1.isEnumDeclaration)(s)) {
207
+ return typescript_1.factory.updateEnumDeclaration(s, modifiers, s.name, s.members);
208
+ }
209
+ if ((0, typescript_1.isClassDeclaration)(s)) {
210
+ return typescript_1.factory.updateClassDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);
211
+ }
212
+ if ((0, typescript_1.isFunctionDeclaration)(s)) {
213
+ return typescript_1.factory.updateFunctionDeclaration(s, modifiers, s.asteriskToken, s.name, s.typeParameters, s.parameters, s.type, s.body);
214
+ }
215
+ return s;
216
+ }
217
+ function removeDeclareModifier(s) {
218
+ let modifiers;
219
+ // Remove declare modifiers
220
+ if (s.modifiers) {
221
+ modifiers = s.modifiers.filter(m => m.kind !== typescript_1.SyntaxKind.DeclareKeyword);
222
+ }
223
+ else {
224
+ return s;
225
+ }
226
+ if ((0, typescript_1.isVariableStatement)(s)) {
227
+ return typescript_1.factory.updateVariableStatement(s, modifiers, s.declarationList);
228
+ }
229
+ if ((0, typescript_1.isTypeAliasDeclaration)(s)) {
230
+ return typescript_1.factory.updateTypeAliasDeclaration(s, modifiers, s.name, s.typeParameters, s.type);
231
+ }
232
+ if ((0, typescript_1.isInterfaceDeclaration)(s)) {
233
+ return typescript_1.factory.updateInterfaceDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);
234
+ }
235
+ if ((0, typescript_1.isEnumDeclaration)(s)) {
236
+ return typescript_1.factory.updateEnumDeclaration(s, modifiers, s.name, s.members);
237
+ }
238
+ if ((0, typescript_1.isClassDeclaration)(s)) {
239
+ return typescript_1.factory.updateClassDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);
240
+ }
241
+ if ((0, typescript_1.isFunctionDeclaration)(s)) {
242
+ return typescript_1.factory.updateFunctionDeclaration(s, modifiers, s.asteriskToken, s.name, s.typeParameters, s.parameters, s.type, s.body);
243
+ }
244
+ return s;
245
+ }
246
+ // taken from node_modules\@types\node\globals.d.ts
247
+ // the globally available things must be wrapped in `declare global` if the user wants to augment them
248
+ const NodeJSGlobals = [
249
+ 'Array',
250
+ 'ArrayBuffer',
251
+ 'Boolean',
252
+ 'Buffer',
253
+ 'DataView',
254
+ 'Date',
255
+ 'Error',
256
+ 'EvalError',
257
+ 'Float32Array',
258
+ 'Float64Array',
259
+ 'Function',
260
+ 'GLOBAL',
261
+ 'Infinity',
262
+ 'Int16Array',
263
+ 'Int32Array',
264
+ 'Int8Array',
265
+ 'Intl',
266
+ 'JSON',
267
+ 'Map',
268
+ 'Math',
269
+ 'NaN',
270
+ 'Number',
271
+ 'Object',
272
+ 'Promise',
273
+ 'RangeError',
274
+ 'ReferenceError',
275
+ 'RegExp',
276
+ 'Set',
277
+ 'String',
278
+ 'Symbol',
279
+ 'SyntaxError',
280
+ 'TypeError',
281
+ 'URIError',
282
+ 'Uint16Array',
283
+ 'Uint32Array',
284
+ 'Uint8Array',
285
+ 'Uint8ClampedArray',
286
+ 'WeakMap',
287
+ 'WeakSet',
288
+ 'clearImmediate',
289
+ 'clearInterval',
290
+ 'clearTimeout',
291
+ 'console',
292
+ 'decodeURI',
293
+ 'decodeURIComponent',
294
+ 'encodeURI',
295
+ 'encodeURIComponent',
296
+ 'escape',
297
+ 'eval',
298
+ 'global',
299
+ 'isFinite',
300
+ 'isNaN',
301
+ 'parseFloat',
302
+ 'parseInt',
303
+ 'process',
304
+ 'root',
305
+ 'setImmediate',
306
+ 'setInterval',
307
+ 'setTimeout',
308
+ 'queueMicrotask',
309
+ 'undefined',
310
+ 'unescape',
311
+ 'gc',
312
+ 'v8debug',
313
+ ];
314
+ function isGlobalAugmentation(s) {
315
+ return !!(((0, typescript_1.isInterfaceDeclaration)(s) || (0, typescript_1.isClassDeclaration)(s) || (0, typescript_1.isFunctionDeclaration)(s)) &&
316
+ s.name &&
317
+ NodeJSGlobals.includes(s.name.text));
318
+ }
319
+ function wrapInDeclareGlobal(statements) {
320
+ return typescript_1.factory.createModuleDeclaration([typescript_1.factory.createModifier(typescript_1.SyntaxKind.DeclareKeyword)], typescript_1.factory.createIdentifier('global'), typescript_1.factory.createModuleBlock(statements), typescript_1.NodeFlags.GlobalAugmentation);
321
+ }
322
+ /**
323
+ * Takes a TypeScript script and does the necessary transformations, so it can be compiled properly
324
+ *
325
+ * @param source The original TypeScript source
326
+ * @param isGlobal Whether the transformed script is a global script or not
327
+ */
328
+ function transformScriptBeforeCompilation(source, isGlobal) {
329
+ const transformer = (_context) => {
330
+ return (sourceFile) => (0, typescript_1.visitNode)(sourceFile, (node) => {
331
+ if ((0, typescript_1.isSourceFile)(node)) {
332
+ // Wrap all declarations that augment global interfaces in `declare global`
333
+ const augmentations = node.statements.filter(s => isGlobalAugmentation(s));
334
+ const nonAugmentations = node.statements.filter(s => !isGlobalAugmentation(s));
335
+ // If there is no top level await, don't move all the statements around
336
+ const hasTLA = node.statements.some(s => (0, typescript_1.isExpressionStatement)(s) && s.expression.kind === typescript_1.SyntaxKind.AwaitExpression);
337
+ // Move all statements to the top of the file that cannot appear in a function body
338
+ let hoistedStatements = hasTLA
339
+ ? typescript_1.factory.createNodeArray(nonAugmentations.filter(s => mustBeHoisted(s, isGlobal)))
340
+ : typescript_1.factory.createNodeArray(nonAugmentations);
341
+ // The rest gets wrapped
342
+ const wrappedStatements = hasTLA ? nonAugmentations.filter(s => !mustBeHoisted(s, isGlobal)) : [];
343
+ // When transforming global scripts, we need to do a couple of things
344
+ if (isGlobal) {
345
+ // 1. We need to add an export modifier to everything at the top level that can be exported
346
+ hoistedStatements = (0, typescript_1.visitNodes)(hoistedStatements,
347
+ // @ts-expect-error s is definitely a Statement
348
+ s => (canBeExported(s) ? addExportModifier(s) : s));
349
+ // 3. We need to transform the generated declarations to use `declare global` (this will happen in transformGlobalDeclarations)
350
+ }
351
+ const needsEmptyExport =
352
+ // An empty export is necessary when there is no import declaration
353
+ !node.statements.some(s => (0, typescript_1.isImportDeclaration)(s) || (0, typescript_1.isImportEqualsDeclaration)(s)) &&
354
+ // And there is no statement in a global script which had an export modifier added
355
+ (!(isGlobal &&
356
+ hoistedStatements.some(
357
+ // @ts-expect-error s should have modifiers
358
+ s => s.modifiers?.some(m => m.kind === typescript_1.SyntaxKind.ExportKeyword))) ||
359
+ // Or if there is a `declare global` statement
360
+ !!augmentations);
361
+ return typescript_1.factory.updateSourceFile(node, [
362
+ // Put the hoisted statements at the top (or all of them if there's no top level await)
363
+ ...hoistedStatements,
364
+ // Then add everything that augments the global scope
365
+ ...(augmentations && augmentations.length ? [wrapInDeclareGlobal(augmentations)] : []),
366
+ ...(hasTLA
367
+ ? // If there is a top-level await, wrap all non-hoisted statements in (async () => { ... })();
368
+ [
369
+ typescript_1.factory.createExpressionStatement(typescript_1.factory.createCallExpression(typescript_1.factory.createArrowFunction([typescript_1.factory.createModifier(typescript_1.SyntaxKind.AsyncKeyword)], undefined, [], undefined, undefined, typescript_1.factory.createBlock(wrappedStatements)), undefined, undefined)),
370
+ ]
371
+ : []),
372
+ ...(needsEmptyExport
373
+ ? [
374
+ // Put an empty export {}; at the bottom to force TypeScript to treat the script as a module
375
+ typescript_1.factory.createExportDeclaration(undefined, // ModifierLike[] | undefined
376
+ false, // isTypeOnly
377
+ typescript_1.factory.createNamedExports([]), // NamedExportBindings | undefined
378
+ undefined, // moduleSpecifier
379
+ undefined),
380
+ ]
381
+ : []),
382
+ ]);
383
+ }
384
+ return node;
385
+ });
386
+ };
387
+ const sourceFile = (0, typescript_1.createSourceFile)('index.ts', source, typescript_1.ScriptTarget.ESNext, /* setParentNodes */ true);
388
+ const result = (0, typescript_1.transform)(sourceFile, [transformer]);
389
+ return (0, typescript_1.createPrinter)().printNode(typescript_1.EmitHint.Unspecified, result.transformed[0], sourceFile);
390
+ }
391
+ /**
392
+ * Takes the global declarations for a TypeScript and wraps export statements in `declare global`
393
+ *
394
+ * @param decl The untransformed global declarations
395
+ */
396
+ function transformGlobalDeclarations(decl) {
397
+ const transformer = (_context) => {
398
+ return (sourceFile) => (0, typescript_1.visitNode)(sourceFile, (node) => {
399
+ if ((0, typescript_1.isSourceFile)(node)) {
400
+ // All non-export-statements stay at the root level, the rest is wrapped in `declare global`
401
+ const exportStatements = node.statements.filter(
402
+ // @ts-expect-error s should have modifiers
403
+ s => s.modifiers?.some(m => m.kind === typescript_1.SyntaxKind.ExportKeyword));
404
+ const otherStatements = node.statements.filter(s => !exportStatements.includes(s));
405
+ const hasExportStatements = exportStatements.length > 0;
406
+ const hasImport = otherStatements.some(s => (0, typescript_1.isImportDeclaration)(s) || (0, typescript_1.isImportEqualsDeclaration)(s));
407
+ return typescript_1.factory.updateSourceFile(node, [
408
+ ...otherStatements,
409
+ ...(hasExportStatements
410
+ ? [wrapInDeclareGlobal(exportStatements.map(s => removeDeclareModifier(s)))]
411
+ : []),
412
+ ...(hasImport
413
+ ? [] // If there is an import, the script is already treated as a module
414
+ : [
415
+ // Otherwise, put an empty export {}; at the bottom to force TypeScript to treat the script as a module
416
+ typescript_1.factory.createExportDeclaration(undefined, false, typescript_1.factory.createNamedExports([]), undefined, undefined),
417
+ ]),
418
+ ]);
419
+ }
420
+ return node;
421
+ });
422
+ };
423
+ const sourceFile = (0, typescript_1.createSourceFile)('index.d.ts', decl, typescript_1.ScriptTarget.ESNext, /* setParentNodes */ true);
424
+ const result = (0, typescript_1.transform)(sourceFile, [transformer]);
425
+ return (0, typescript_1.createPrinter)().printNode(typescript_1.EmitHint.Unspecified, result.transformed[0], sourceFile);
426
+ }
427
+ /**
428
+ * Translates a script ID to a filename for the compiler
429
+ *
430
+ * @param scriptID The ID of the script
431
+ */
432
+ function scriptIdToTSFilename(scriptID) {
433
+ return `${scriptID.replace(/^script.js./, '').replace(/\./g, '/')}.ts`;
434
+ }
435
+ //# sourceMappingURL=typescriptTools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typescriptTools.js","sourceRoot":"","sources":["../../src/lib/typescriptTools.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AA4Cb,sDAyBC;AAwBD,wCA+GC;AAsND,4EA2FC;AAOD,kEA2CC;AAOD,oDAEC;AAtjBD,qCAAmD;AACnD,yCAA+D;AAC/D,2CAgCoB;AACpB,mCAAmC;AAEnC;;;;GAIG;AACH,SAAgB,qBAAqB,CACjC,SAAqF;IAErF,MAAM,iBAAiB,GAAG,IAAA,mBAAO,EAAC,OAAO,CAAC,OAAO,CAAC,yBAAyB,CAAC,CAAC,CAAC;IAC9E,MAAM,GAAG,GAA2B,EAAE,CAAC;IAEvC,MAAM,iBAAiB,GAAG,6CAA6C,CAA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C,CAAC,CAAC;IACpD,OAAO,IAAA,0BAAa,GAAE,CAAC,SAAS,CAAC,qBAAQ,CAAC,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;AAC9F,CAAC;AAED;;;;GAIG;AACH,SAAgB,oBAAoB,CAAC,QAAgB;IACjD,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC;AAC3E,CAAC","sourcesContent":["'use strict';\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, normalize, relative } from 'node:path';\nimport {\n type Statement,\n isImportDeclaration,\n isImportEqualsDeclaration,\n isExportDeclaration,\n isExportAssignment,\n isTypeAliasDeclaration,\n isInterfaceDeclaration,\n isModuleDeclaration,\n isEnumDeclaration,\n isClassDeclaration,\n isFunctionDeclaration,\n isVariableStatement,\n isExpressionStatement,\n createSourceFile,\n createPrinter,\n transform,\n ScriptTarget,\n factory,\n SyntaxKind,\n type Modifier,\n NodeFlags,\n type ModuleDeclaration,\n visitNode,\n visitNodes,\n isSourceFile,\n EmitHint,\n type NodeArray,\n type TransformerFactory,\n type SourceFile,\n type TransformationContext,\n type Transformer,\n} from 'typescript';\nimport { matchAll } from './tools';\n\n/**\n * Resolves all TypeScript lib files for the editor\n *\n * @param targetLib The lib to target (e.g., es2017)\n */\nexport function resolveTypescriptLibs(\n targetLib: 'es2017' | 'es2018' | 'es2019' | 'es2020' | 'es2021' | 'es2022' | 'esnext',\n): Record<string, string> {\n const typescriptLibRoot = dirname(require.resolve(`typescript/lib/lib.d.ts`));\n const ret: Record<string, string> = {};\n\n const libReferenceRegex = /\\/\\/\\/ <reference lib=[\"']([^\"']+)[\"'] \\/>/g;\n const matchAllLibs = (str: string): string[] => matchAll(libReferenceRegex, str).map(groups => groups[0]);\n\n const libQueue: string[] = [targetLib];\n while (libQueue.length > 0) {\n const libName = libQueue.shift();\n const filename = `lib.${libName}.d.ts`;\n // Read the file and remember it in the return dictionary\n const fileContent = readFileSync(join(typescriptLibRoot, filename), 'utf8');\n ret[filename] = fileContent;\n // If this file references another lib file, we need to load that too.\n // A reference looks like this: /// <reference lib=\"es2015.core\" />\n // Find all libs we have not loaded yet\n matchAllLibs(fileContent)\n .filter(lib => !(`lib.${lib}.d.ts` in ret))\n .forEach(lib => libQueue.push(lib));\n }\n\n return ret;\n}\n\nfunction normalizeDTSImport(filename: string): string {\n // An import is either...\n // a normal import\n if (filename.endsWith('.d.ts')) {\n return filename;\n }\n // an extensionless import\n if (existsSync(`${filename}.d.ts`)) {\n return `${filename}.d.ts`;\n }\n // or a directory import\n return join(filename, 'index.d.ts');\n}\n\n/**\n * Resolves the type declarations of a 3rd party package for the editor\n *\n * @param pkg The package whose typings we're interested in\n * @param adapterScopedPackageName the package name on the system\n * @param wrapInDeclareModule Whether the root file should be wrapped in `declare module \"<pkg>\" { ... }`\n * @returns The found declarations or undefined if none were found\n */\nexport function resolveTypings(\n pkg: string,\n adapterScopedPackageName: string,\n wrapInDeclareModule?: boolean,\n): Record<string, string> | undefined {\n let packageJsonPath: string | undefined;\n let packageJson: Record<string, any> | undefined;\n let rootTypings: string | undefined;\n let pkgIncludesTypings = true;\n\n function tryToLoadPackage(path: string): void {\n try {\n packageJsonPath = require.resolve(path);\n packageJson = require(packageJsonPath);\n rootTypings =\n typeof (packageJson as Record<string, any>).types === 'string'\n ? (packageJson as Record<string, any>).types\n : typeof (packageJson as Record<string, any>).typings === 'string'\n ? (packageJson as Record<string, any>).typings\n : undefined;\n } catch {\n /* ignore */\n }\n }\n\n // First, try to resolve the package itself in case it brings its own typings\n tryToLoadPackage(`${adapterScopedPackageName}/package.json`);\n\n if (!rootTypings) {\n tryToLoadPackage(`${pkg}/package.json`);\n }\n // If that didn't work, try again with the @types version of the package\n if (!rootTypings) {\n tryToLoadPackage(`@types/${pkg}/package.json`);\n pkgIncludesTypings = false;\n }\n\n // TODO: If that didn't work, download @types/<packagename> and retry the previous step\n\n // Nothing to do here since we found no packages\n if (!rootTypings) {\n return undefined;\n }\n\n if (!packageJsonPath) {\n return undefined;\n }\n\n const packageRoot: string = dirname(packageJsonPath);\n const normalizeImportPath = (filename: string): string =>\n normalize(\n `node_modules/${pkgIncludesTypings ? adapterScopedPackageName : `@types/${pkg}`}/${relative(packageRoot, filename)}`,\n ).replace(/\\\\/g, '/');\n\n const ret: Record<string, string> = {};\n\n // We need to look at `import/export ... from 'modulename'` and `/// <reference path='...' />`\n const importDtsRegex = /^\\s*(?:import|export) .+ from [\"'](\\.+\\/[^\"']+)[\"']/g;\n const pathReferenceRegex = /\\/\\/\\/ <reference path=[\"']([^\"']+)[\"'] \\/>/g;\n const matchAllImports = (str: string): string[] =>\n [...matchAll(importDtsRegex, str), ...matchAll(pathReferenceRegex, str)].map(groups => groups[0]);\n\n // the paths are relative to the package.json - we need an absolute path to read the files\n rootTypings = join(packageRoot, rootTypings);\n // some @types packages specify `index` as their typings file instead of `index.d.ts`\n rootTypings = normalizeDTSImport(rootTypings);\n\n // include package.json in typings, so TypeScript can look up the correct entry point\n const relativePath = `node_modules/${pkgIncludesTypings ? '' : '@types/'}${pkg}/package.json`.replace(/\\\\/g, '/');\n ret[relativePath] = JSON.stringify(packageJson);\n\n // Used to test whether a .d.ts file already uses \"declare module\" or not\n const declareModuleRegex = /^\\s*declare module/gm;\n\n // recursively load all typings\n const definitionQueue = [rootTypings];\n while (definitionQueue.length > 0) {\n const filename: string = definitionQueue.shift() as string;\n const dirName = dirname(filename);\n // Read the file and remember it in the return dictionary\n let fileContent: string;\n try {\n fileContent = readFileSync(filename, 'utf8');\n } catch (e: any) {\n // The typings are malformed\n console.error(`Failed to load definitions for ${pkg}: ${e.toString()}`);\n // Since we cannot use them, return undefined\n return undefined;\n }\n // We need to store the filename relative to the base dir\n const relativePath = normalizeImportPath(filename);\n // If necessary, wrap the root typings (only those!)\n ret[relativePath] =\n wrapInDeclareModule && filename === rootTypings && !declareModuleRegex.test(fileContent)\n ? `declare module \"${pkg}\" { ${fileContent} }`\n : fileContent;\n // If this file references another .d.ts file, we need to load that too\n matchAllImports(fileContent)\n // resolve the file relative to the current directory\n .map(file => join(dirName, file))\n // find out the correct path of the file we want to import\n .map(normalizeDTSImport)\n // Find all libs we have not loaded yet\n .filter(file => !(normalizeImportPath(file) in ret))\n .forEach(file => definitionQueue.push(file));\n }\n // Avoid returning empty declarations\n if (Object.keys(ret).length === 0) {\n return undefined;\n }\n return ret;\n}\n\n/**\n * @param s Statement to check whether it must be hoisted to the top of the file\n * @param isGlobal Whether this is a global script or a normal one\n */\nfunction mustBeHoisted(s: Statement & { modifiers?: Modifier[] }, isGlobal?: boolean): boolean {\n return !!(\n // Import/export statements must be moved to the top\n (\n isImportDeclaration(s) ||\n isImportEqualsDeclaration(s) ||\n isExportDeclaration(s) ||\n isExportAssignment(s) ||\n // as well as many declarations\n isTypeAliasDeclaration(s) ||\n isInterfaceDeclaration(s) ||\n isModuleDeclaration(s) ||\n isEnumDeclaration(s) ||\n (isGlobal &&\n // in global scripts we don't wrap classes and functions, so they can be accessed from non-global scripts\n (isClassDeclaration(s) || isFunctionDeclaration(s))) ||\n // and declare ... / export ... statements\n s.modifiers?.some(s => s.kind === SyntaxKind.DeclareKeyword || s.kind === SyntaxKind.ExportKeyword)\n )\n );\n}\n\nfunction canBeExported(s: Statement): boolean {\n return (\n // const, let, var\n isVariableStatement(s) ||\n // type, interface, enum, class, function\n isTypeAliasDeclaration(s) ||\n isInterfaceDeclaration(s) ||\n isEnumDeclaration(s) ||\n isClassDeclaration(s) ||\n isFunctionDeclaration(s)\n );\n}\n\nfunction addExportModifier(s: Statement & { modifiers?: Modifier[] }): Statement {\n let modifiers: Modifier[] | undefined;\n // Add export modifiers\n if (!s.modifiers) {\n modifiers = [factory.createModifier(SyntaxKind.ExportKeyword)];\n } else if (!s.modifiers.some(m => m.kind === SyntaxKind.ExportKeyword)) {\n modifiers = [...s.modifiers, factory.createModifier(SyntaxKind.ExportKeyword)];\n } else {\n return s;\n }\n\n if (isVariableStatement(s)) {\n return factory.updateVariableStatement(s, modifiers, s.declarationList);\n }\n if (isTypeAliasDeclaration(s)) {\n return factory.updateTypeAliasDeclaration(s, modifiers, s.name, s.typeParameters, s.type);\n }\n if (isInterfaceDeclaration(s)) {\n return factory.updateInterfaceDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isEnumDeclaration(s)) {\n return factory.updateEnumDeclaration(s, modifiers, s.name, s.members);\n }\n if (isClassDeclaration(s)) {\n return factory.updateClassDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isFunctionDeclaration(s)) {\n return factory.updateFunctionDeclaration(\n s,\n modifiers,\n s.asteriskToken,\n s.name,\n s.typeParameters,\n s.parameters,\n s.type,\n s.body,\n );\n }\n return s;\n}\n\nfunction removeDeclareModifier(s: Statement & { modifiers?: Modifier[] }): Statement {\n let modifiers: Modifier[] | undefined;\n // Remove declare modifiers\n if (s.modifiers) {\n modifiers = s.modifiers.filter(m => m.kind !== SyntaxKind.DeclareKeyword);\n } else {\n return s;\n }\n\n if (isVariableStatement(s)) {\n return factory.updateVariableStatement(s, modifiers, s.declarationList);\n }\n if (isTypeAliasDeclaration(s)) {\n return factory.updateTypeAliasDeclaration(s, modifiers, s.name, s.typeParameters, s.type);\n }\n if (isInterfaceDeclaration(s)) {\n return factory.updateInterfaceDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isEnumDeclaration(s)) {\n return factory.updateEnumDeclaration(s, modifiers, s.name, s.members);\n }\n if (isClassDeclaration(s)) {\n return factory.updateClassDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isFunctionDeclaration(s)) {\n return factory.updateFunctionDeclaration(\n s,\n modifiers,\n s.asteriskToken,\n s.name,\n s.typeParameters,\n s.parameters,\n s.type,\n s.body,\n );\n }\n\n return s;\n}\n\n// taken from node_modules\\@types\\node\\globals.d.ts\n// the globally available things must be wrapped in `declare global` if the user wants to augment them\nconst NodeJSGlobals = [\n 'Array',\n 'ArrayBuffer',\n 'Boolean',\n 'Buffer',\n 'DataView',\n 'Date',\n 'Error',\n 'EvalError',\n 'Float32Array',\n 'Float64Array',\n 'Function',\n 'GLOBAL',\n 'Infinity',\n 'Int16Array',\n 'Int32Array',\n 'Int8Array',\n 'Intl',\n 'JSON',\n 'Map',\n 'Math',\n 'NaN',\n 'Number',\n 'Object',\n 'Promise',\n 'RangeError',\n 'ReferenceError',\n 'RegExp',\n 'Set',\n 'String',\n 'Symbol',\n 'SyntaxError',\n 'TypeError',\n 'URIError',\n 'Uint16Array',\n 'Uint32Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'WeakMap',\n 'WeakSet',\n 'clearImmediate',\n 'clearInterval',\n 'clearTimeout',\n 'console',\n 'decodeURI',\n 'decodeURIComponent',\n 'encodeURI',\n 'encodeURIComponent',\n 'escape',\n 'eval',\n 'global',\n 'isFinite',\n 'isNaN',\n 'parseFloat',\n 'parseInt',\n 'process',\n 'root',\n 'setImmediate',\n 'setInterval',\n 'setTimeout',\n 'queueMicrotask',\n 'undefined',\n 'unescape',\n 'gc',\n 'v8debug',\n];\n\nfunction isGlobalAugmentation(s: Statement): boolean {\n return !!(\n (isInterfaceDeclaration(s) || isClassDeclaration(s) || isFunctionDeclaration(s)) &&\n s.name &&\n NodeJSGlobals.includes(s.name.text)\n );\n}\n\nfunction wrapInDeclareGlobal(statements: Statement[]): ModuleDeclaration {\n return factory.createModuleDeclaration(\n [factory.createModifier(SyntaxKind.DeclareKeyword)],\n factory.createIdentifier('global'),\n factory.createModuleBlock(statements),\n NodeFlags.GlobalAugmentation,\n );\n}\n\n/**\n * Takes a TypeScript script and does the necessary transformations, so it can be compiled properly\n *\n * @param source The original TypeScript source\n * @param isGlobal Whether the transformed script is a global script or not\n */\nexport function transformScriptBeforeCompilation(source: string, isGlobal?: boolean): string {\n const transformer: TransformerFactory<SourceFile> = (_context: TransformationContext): Transformer<SourceFile> => {\n return (sourceFile: SourceFile) =>\n visitNode(sourceFile, (node: SourceFile): any => {\n if (isSourceFile(node)) {\n // Wrap all declarations that augment global interfaces in `declare global`\n const augmentations = node.statements.filter(s => isGlobalAugmentation(s));\n const nonAugmentations = node.statements.filter(s => !isGlobalAugmentation(s));\n\n // If there is no top level await, don't move all the statements around\n const hasTLA = node.statements.some(\n s => isExpressionStatement(s) && s.expression.kind === SyntaxKind.AwaitExpression,\n );\n // Move all statements to the top of the file that cannot appear in a function body\n let hoistedStatements = hasTLA\n ? factory.createNodeArray(nonAugmentations.filter(s => mustBeHoisted(s, isGlobal)))\n : factory.createNodeArray(nonAugmentations);\n\n // The rest gets wrapped\n const wrappedStatements = hasTLA ? nonAugmentations.filter(s => !mustBeHoisted(s, isGlobal)) : [];\n\n // When transforming global scripts, we need to do a couple of things\n if (isGlobal) {\n // 1. We need to add an export modifier to everything at the top level that can be exported\n hoistedStatements = visitNodes(\n hoistedStatements,\n // @ts-expect-error s is definitely a Statement\n s => (canBeExported(s) ? addExportModifier(s) : s),\n ) as NodeArray<Statement>;\n // 3. We need to transform the generated declarations to use `declare global` (this will happen in transformGlobalDeclarations)\n }\n const needsEmptyExport =\n // An empty export is necessary when there is no import declaration\n !node.statements.some(s => isImportDeclaration(s) || isImportEqualsDeclaration(s)) &&\n // And there is no statement in a global script which had an export modifier added\n (!(\n isGlobal &&\n hoistedStatements.some(\n // @ts-expect-error s should have modifiers\n s => s.modifiers?.some(m => m.kind === SyntaxKind.ExportKeyword),\n )\n ) ||\n // Or if there is a `declare global` statement\n !!augmentations);\n\n return factory.updateSourceFile(node, [\n // Put the hoisted statements at the top (or all of them if there's no top level await)\n ...hoistedStatements,\n // Then add everything that augments the global scope\n ...(augmentations && augmentations.length ? [wrapInDeclareGlobal(augmentations)] : []),\n ...(hasTLA\n ? // If there is a top-level await, wrap all non-hoisted statements in (async () => { ... })();\n [\n factory.createExpressionStatement(\n factory.createCallExpression(\n factory.createArrowFunction(\n [factory.createModifier(SyntaxKind.AsyncKeyword)],\n undefined,\n [],\n undefined,\n undefined,\n factory.createBlock(wrappedStatements),\n ),\n undefined,\n undefined,\n ),\n ),\n ]\n : []),\n ...(needsEmptyExport\n ? [\n // Put an empty export {}; at the bottom to force TypeScript to treat the script as a module\n factory.createExportDeclaration(\n undefined, // ModifierLike[] | undefined\n false, // isTypeOnly\n factory.createNamedExports([]), // NamedExportBindings | undefined\n undefined, // moduleSpecifier\n undefined, // attributes\n ),\n ]\n : []),\n ]);\n }\n return node;\n });\n };\n\n const sourceFile = createSourceFile('index.ts', source, ScriptTarget.ESNext, /* setParentNodes */ true);\n\n const result = transform(sourceFile, [transformer]);\n return createPrinter().printNode(EmitHint.Unspecified, result.transformed[0], sourceFile);\n}\n\n/**\n * Takes the global declarations for a TypeScript and wraps export statements in `declare global`\n *\n * @param decl The untransformed global declarations\n */\nexport function transformGlobalDeclarations(decl: string): string {\n const transformer: TransformerFactory<SourceFile> = (_context: TransformationContext): any => {\n return (sourceFile: SourceFile) =>\n visitNode(sourceFile, (node: SourceFile): SourceFile => {\n if (isSourceFile(node)) {\n // All non-export-statements stay at the root level, the rest is wrapped in `declare global`\n const exportStatements = node.statements.filter(\n // @ts-expect-error s should have modifiers\n s => s.modifiers?.some(m => m.kind === SyntaxKind.ExportKeyword),\n );\n const otherStatements = node.statements.filter(s => !exportStatements.includes(s));\n\n const hasExportStatements = exportStatements.length > 0;\n const hasImport = otherStatements.some(s => isImportDeclaration(s) || isImportEqualsDeclaration(s));\n\n return factory.updateSourceFile(node, [\n ...otherStatements,\n ...(hasExportStatements\n ? [wrapInDeclareGlobal(exportStatements.map(s => removeDeclareModifier(s)))]\n : []),\n ...(hasImport\n ? [] // If there is an import, the script is already treated as a module\n : [\n // Otherwise, put an empty export {}; at the bottom to force TypeScript to treat the script as a module\n factory.createExportDeclaration(\n undefined,\n false,\n factory.createNamedExports([]),\n undefined,\n undefined,\n ),\n ]),\n ]);\n }\n\n return node;\n });\n };\n\n const sourceFile = createSourceFile('index.d.ts', decl, ScriptTarget.ESNext, /* setParentNodes */ true);\n\n const result = transform(sourceFile, [transformer]);\n return createPrinter().printNode(EmitHint.Unspecified, result.transformed[0], sourceFile);\n}\n\n/**\n * Translates a script ID to a filename for the compiler\n *\n * @param scriptID The ID of the script\n */\nexport function scriptIdToTSFilename(scriptID: string): string {\n return `${scriptID.replace(/^script.js./, '').replace(/\\./g, '/')}.ts`;\n}\n"]}
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Adapter = exports.controllerDir = exports.appName = void 0;
4
+ exports.getConfig = getConfig;
5
+ const node_fs_1 = require("node:fs");
6
+ const node_path_1 = require("node:path");
7
+ const EXIT_CODES = {
8
+ NO_ERROR: 0,
9
+ CANNOT_FIND_ADAPTER_DIR: 10,
10
+ };
11
+ /**
12
+ * Returns the application name
13
+ * The name of the application can be different, and this function finds it out.
14
+ */
15
+ function getAppName() {
16
+ const parts = __dirname.replace(/\\/g, '/').split('/');
17
+ return parts[parts.length - 2].split('.')[0];
18
+ }
19
+ /**
20
+ * looks for js-controller home folder
21
+ */
22
+ function getControllerDir(isInstall) {
23
+ // Find the js-controller location
24
+ const possibilities = ['iobroker.js-controller', 'ioBroker.js-controller'];
25
+ let controllerPath;
26
+ for (const pkg of possibilities) {
27
+ try {
28
+ const possiblePath = require.resolve(pkg);
29
+ if ((0, node_fs_1.existsSync)(possiblePath)) {
30
+ controllerPath = possiblePath;
31
+ break;
32
+ }
33
+ }
34
+ catch {
35
+ /* not found */
36
+ }
37
+ }
38
+ if (!controllerPath) {
39
+ if (!isInstall) {
40
+ console.log('Cannot find js-controller');
41
+ process.exit(EXIT_CODES.CANNOT_FIND_ADAPTER_DIR);
42
+ }
43
+ else {
44
+ process.exit(EXIT_CODES.NO_ERROR);
45
+ }
46
+ }
47
+ // we found the controller
48
+ return (0, node_path_1.dirname)(controllerPath);
49
+ }
50
+ exports.appName = getAppName();
51
+ exports.controllerDir = getControllerDir(typeof process !== 'undefined' && process.argv && process.argv.includes('--install'));
52
+ /**
53
+ * Reads controller base settings
54
+ */
55
+ function getConfig() {
56
+ let configPath;
57
+ if ((0, node_fs_1.existsSync)((configPath = (0, node_path_1.join)(exports.controllerDir, 'conf', `${exports.appName}.json`)))) {
58
+ return JSON.parse((0, node_fs_1.readFileSync)(configPath, 'utf8'));
59
+ }
60
+ if ((0, node_fs_1.existsSync)((configPath = (0, node_path_1.join)(exports.controllerDir, 'conf', `${+exports.appName.toLowerCase()}.json`)))) {
61
+ return JSON.parse((0, node_fs_1.readFileSync)(configPath, 'utf8'));
62
+ }
63
+ throw new Error(`Cannot find ${exports.controllerDir}/conf/${exports.appName}.json`);
64
+ }
65
+ exports.Adapter = require((0, node_path_1.join)(exports.controllerDir, 'lib/adapter.js'));
66
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/lib/utils.ts"],"names":[],"mappings":";;;AAyDA,8BASC;AAlED,qCAAmD;AACnD,yCAA0C;AAG1C,MAAM,UAAU,GAAG;IACf,QAAQ,EAAE,CAAC;IACX,uBAAuB,EAAE,EAAE;CAC9B,CAAC;AAEF;;;GAGG;AACH,SAAS,UAAU;IACf,MAAM,KAAK,GAAG,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACvD,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACjD,CAAC;AAED;;GAEG;AACH,SAAS,gBAAgB,CAAC,SAAmB;IACzC,kCAAkC;IAClC,MAAM,aAAa,GAAG,CAAC,wBAAwB,EAAE,wBAAwB,CAAC,CAAC;IAC3E,IAAI,cAAkC,CAAC;IACvC,KAAK,MA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Aa,EAAE,MAAM,EAAE,GAAG,CAAC,eAAO,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3F,OAAO,IAAI,CAAC,KAAK,CAAC,IAAA,sBAAY,EAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;IACxD,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,eAAe,qBAAa,SAAS,eAAO,OAAO,CAAC,CAAC;AACzE,CAAC;AAEY,QAAA,OAAO,GAAG,OAAO,CAAC,IAAA,gBAAI,EAAC,qBAAa,EAAE,gBAAgB,CAAC,CAAC,CAAC","sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { IoBJson } from '@iobroker/types/build/config';\n\nconst EXIT_CODES = {\n NO_ERROR: 0,\n CANNOT_FIND_ADAPTER_DIR: 10,\n};\n\n/**\n * Returns the application name\n * The name of the application can be different, and this function finds it out.\n */\nfunction getAppName(): string {\n const parts = __dirname.replace(/\\\\/g, '/').split('/');\n return parts[parts.length - 2].split('.')[0];\n}\n\n/**\n * looks for js-controller home folder\n */\nfunction getControllerDir(isInstall?: boolean): string {\n // Find the js-controller location\n const possibilities = ['iobroker.js-controller', 'ioBroker.js-controller'];\n let controllerPath: string | undefined;\n for (const pkg of possibilities) {\n try {\n const possiblePath = require.resolve(pkg);\n if (existsSync(possiblePath)) {\n controllerPath = possiblePath;\n break;\n }\n } catch {\n /* not found */\n }\n }\n if (!controllerPath) {\n if (!isInstall) {\n console.log('Cannot find js-controller');\n process.exit(EXIT_CODES.CANNOT_FIND_ADAPTER_DIR);\n } else {\n process.exit(EXIT_CODES.NO_ERROR);\n }\n }\n\n // we found the controller\n return dirname(controllerPath);\n}\n\nexport const appName = getAppName();\nexport const controllerDir = getControllerDir(\n typeof process !== 'undefined' && process.argv && process.argv.includes('--install'),\n);\n\n/**\n * Reads controller base settings\n */\nexport function getConfig(): IoBJson {\n let configPath: string;\n if (existsSync((configPath = join(controllerDir, 'conf', `${appName}.json`)))) {\n return JSON.parse(readFileSync(configPath, 'utf8'));\n }\n if (existsSync((configPath = join(controllerDir, 'conf', `${+appName.toLowerCase()}.json`)))) {\n return JSON.parse(readFileSync(configPath, 'utf8'));\n }\n throw new Error(`Cannot find ${controllerDir}/conf/${appName}.json`);\n}\n\nexport const Adapter = require(join(controllerDir, 'lib/adapter.js'));\n"]}