java-bridge 2.1.4 → 2.1.5

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,1487 +0,0 @@
1
- (function webpackUniversalModuleDefinition(root, factory) {
2
- if(typeof exports === 'object' && typeof module === 'object')
3
- module.exports = factory();
4
- else if(typeof define === 'function' && define.amd)
5
- define([], factory);
6
- else if(typeof exports === 'object')
7
- exports["java"] = factory();
8
- else
9
- root["java"] = factory();
10
- })(global, () => {
11
- return /******/ (() => { // webpackBootstrap
12
- /******/ var __webpack_modules__ = ({
13
-
14
- /***/ "./java.linux-x64-gnu.node":
15
- /*!*********************************!*\
16
- !*** ./java.linux-x64-gnu.node ***!
17
- \*********************************/
18
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
19
-
20
- /* module decorator */ module = __webpack_require__.nmd(module);
21
-
22
- try {
23
- process.dlopen(module, __dirname + (__webpack_require__(/*! path */ "path").sep) + __webpack_require__.p + "java.linux-x64-gnu.node");
24
- } catch (error) {
25
- throw new Error('node-loader:\n' + error);
26
- }
27
-
28
-
29
- /***/ }),
30
-
31
- /***/ "./native.js":
32
- /*!*******************!*\
33
- !*** ./native.js ***!
34
- \*******************/
35
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
36
-
37
- const { existsSync, readFileSync } = __webpack_require__(/*! fs */ "fs")
38
- const { join } = __webpack_require__(/*! path */ "path")
39
-
40
- const { platform, arch } = process
41
-
42
- let nativeBinding = null
43
- let localFileExisted = false
44
- let loadError = null
45
-
46
- function isMusl() {
47
- // For Node 10
48
- if (!process.report || typeof process.report.getReport !== 'function') {
49
- try {
50
- return readFileSync('/usr/bin/ldd', 'utf8').includes('musl')
51
- } catch (e) {
52
- return true
53
- }
54
- } else {
55
- const { glibcVersionRuntime } = process.report.getReport().header
56
- return !glibcVersionRuntime
57
- }
58
- }
59
-
60
- switch (platform) {
61
- case 'android':
62
- switch (arch) {
63
- case 'arm64':
64
- localFileExisted = existsSync(join(__dirname, 'java.android-arm64.node'))
65
- try {
66
- if (localFileExisted) {
67
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.android-arm64.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
68
- } else {
69
- nativeBinding = require('java-bridge-android-arm64')
70
- }
71
- } catch (e) {
72
- loadError = e
73
- }
74
- break
75
- case 'arm':
76
- localFileExisted = existsSync(join(__dirname, 'java.android-arm-eabi.node'))
77
- try {
78
- if (localFileExisted) {
79
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.android-arm-eabi.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
80
- } else {
81
- nativeBinding = require('java-bridge-android-arm-eabi')
82
- }
83
- } catch (e) {
84
- loadError = e
85
- }
86
- break
87
- default:
88
- throw new Error(`Unsupported architecture on Android ${arch}`)
89
- }
90
- break
91
- case 'win32':
92
- switch (arch) {
93
- case 'x64':
94
- localFileExisted = existsSync(
95
- join(__dirname, 'java.win32-x64-msvc.node')
96
- )
97
- try {
98
- if (localFileExisted) {
99
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.win32-x64-msvc.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
100
- } else {
101
- nativeBinding = require('java-bridge-win32-x64-msvc')
102
- }
103
- } catch (e) {
104
- loadError = e
105
- }
106
- break
107
- case 'ia32':
108
- localFileExisted = existsSync(
109
- join(__dirname, 'java.win32-ia32-msvc.node')
110
- )
111
- try {
112
- if (localFileExisted) {
113
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.win32-ia32-msvc.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
114
- } else {
115
- nativeBinding = require('java-bridge-win32-ia32-msvc')
116
- }
117
- } catch (e) {
118
- loadError = e
119
- }
120
- break
121
- case 'arm64':
122
- localFileExisted = existsSync(
123
- join(__dirname, 'java.win32-arm64-msvc.node')
124
- )
125
- try {
126
- if (localFileExisted) {
127
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.win32-arm64-msvc.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
128
- } else {
129
- nativeBinding = require('java-bridge-win32-arm64-msvc')
130
- }
131
- } catch (e) {
132
- loadError = e
133
- }
134
- break
135
- default:
136
- throw new Error(`Unsupported architecture on Windows: ${arch}`)
137
- }
138
- break
139
- case 'darwin':
140
- switch (arch) {
141
- case 'x64':
142
- localFileExisted = existsSync(join(__dirname, 'java.darwin-x64.node'))
143
- try {
144
- if (localFileExisted) {
145
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.darwin-x64.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
146
- } else {
147
- nativeBinding = require('java-bridge-darwin-x64')
148
- }
149
- } catch (e) {
150
- loadError = e
151
- }
152
- break
153
- case 'arm64':
154
- localFileExisted = existsSync(
155
- join(__dirname, 'java.darwin-arm64.node')
156
- )
157
- try {
158
- if (localFileExisted) {
159
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.darwin-arm64.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
160
- } else {
161
- nativeBinding = require('java-bridge-darwin-arm64')
162
- }
163
- } catch (e) {
164
- loadError = e
165
- }
166
- break
167
- default:
168
- throw new Error(`Unsupported architecture on macOS: ${arch}`)
169
- }
170
- break
171
- case 'freebsd':
172
- if (arch !== 'x64') {
173
- throw new Error(`Unsupported architecture on FreeBSD: ${arch}`)
174
- }
175
- localFileExisted = existsSync(join(__dirname, 'java.freebsd-x64.node'))
176
- try {
177
- if (localFileExisted) {
178
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.freebsd-x64.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
179
- } else {
180
- nativeBinding = require('java-bridge-freebsd-x64')
181
- }
182
- } catch (e) {
183
- loadError = e
184
- }
185
- break
186
- case 'linux':
187
- switch (arch) {
188
- case 'x64':
189
- if (isMusl()) {
190
- localFileExisted = existsSync(
191
- join(__dirname, 'java.linux-x64-musl.node')
192
- )
193
- try {
194
- if (localFileExisted) {
195
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.linux-x64-musl.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
196
- } else {
197
- nativeBinding = require('java-bridge-linux-x64-musl')
198
- }
199
- } catch (e) {
200
- loadError = e
201
- }
202
- } else {
203
- localFileExisted = existsSync(
204
- join(__dirname, 'java.linux-x64-gnu.node')
205
- )
206
- try {
207
- if (localFileExisted) {
208
- nativeBinding = __webpack_require__(/*! ./java.linux-x64-gnu.node */ "./java.linux-x64-gnu.node")
209
- } else {
210
- nativeBinding = require('java-bridge-linux-x64-gnu')
211
- }
212
- } catch (e) {
213
- loadError = e
214
- }
215
- }
216
- break
217
- case 'arm64':
218
- if (isMusl()) {
219
- localFileExisted = existsSync(
220
- join(__dirname, 'java.linux-arm64-musl.node')
221
- )
222
- try {
223
- if (localFileExisted) {
224
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.linux-arm64-musl.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
225
- } else {
226
- nativeBinding = require('java-bridge-linux-arm64-musl')
227
- }
228
- } catch (e) {
229
- loadError = e
230
- }
231
- } else {
232
- localFileExisted = existsSync(
233
- join(__dirname, 'java.linux-arm64-gnu.node')
234
- )
235
- try {
236
- if (localFileExisted) {
237
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.linux-arm64-gnu.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
238
- } else {
239
- nativeBinding = require('java-bridge-linux-arm64-gnu')
240
- }
241
- } catch (e) {
242
- loadError = e
243
- }
244
- }
245
- break
246
- case 'arm':
247
- localFileExisted = existsSync(
248
- join(__dirname, 'java.linux-arm-gnueabihf.node')
249
- )
250
- try {
251
- if (localFileExisted) {
252
- nativeBinding = __webpack_require__(Object(function webpackMissingModule() { var e = new Error("Cannot find module './java.linux-arm-gnueabihf.node'"); e.code = 'MODULE_NOT_FOUND'; throw e; }()))
253
- } else {
254
- nativeBinding = require('java-bridge-linux-arm-gnueabihf')
255
- }
256
- } catch (e) {
257
- loadError = e
258
- }
259
- break
260
- default:
261
- throw new Error(`Unsupported architecture on Linux: ${arch}`)
262
- }
263
- break
264
- default:
265
- throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`)
266
- }
267
-
268
- if (!nativeBinding) {
269
- if (loadError) {
270
- throw loadError
271
- }
272
- throw new Error(`Failed to load native binding`)
273
- }
274
-
275
- const { Java, getClassFields, getField, setField, getStaticField, setStaticField, JavaInterfaceProxy, StdoutRedirect, getJavaLibPath } = nativeBinding
276
-
277
- module.exports.Java = Java
278
- module.exports.getClassFields = getClassFields
279
- module.exports.getField = getField
280
- module.exports.setField = setField
281
- module.exports.getStaticField = getStaticField
282
- module.exports.setStaticField = setStaticField
283
- module.exports.JavaInterfaceProxy = JavaInterfaceProxy
284
- module.exports.StdoutRedirect = StdoutRedirect
285
- module.exports.getJavaLibPath = getJavaLibPath
286
-
287
-
288
- /***/ }),
289
-
290
- /***/ "./ts-src/TypescriptDefinitionGenerator.ts":
291
- /*!*************************************************!*\
292
- !*** ./ts-src/TypescriptDefinitionGenerator.ts ***!
293
- \*************************************************/
294
- /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
295
-
296
- "use strict";
297
-
298
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
299
- if (k2 === undefined) k2 = k;
300
- var desc = Object.getOwnPropertyDescriptor(m, k);
301
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
302
- desc = { enumerable: true, get: function() { return m[k]; } };
303
- }
304
- Object.defineProperty(o, k2, desc);
305
- }) : (function(o, m, k, k2) {
306
- if (k2 === undefined) k2 = k;
307
- o[k2] = m[k];
308
- }));
309
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
310
- Object.defineProperty(o, "default", { enumerable: true, value: v });
311
- }) : function(o, v) {
312
- o["default"] = v;
313
- });
314
- var __importStar = (this && this.__importStar) || function (mod) {
315
- if (mod && mod.__esModule) return mod;
316
- var result = {};
317
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
318
- __setModuleDefault(result, mod);
319
- return result;
320
- };
321
- var __importDefault = (this && this.__importDefault) || function (mod) {
322
- return (mod && mod.__esModule) ? mod : { "default": mod };
323
- };
324
- Object.defineProperty(exports, "__esModule", ({ value: true }));
325
- const typescript_1 = __importStar(__webpack_require__(/*! typescript */ "typescript"));
326
- const _1 = __webpack_require__(/*! ./. */ "./ts-src/index.ts");
327
- const fs_1 = __importDefault(__webpack_require__(/*! fs */ "fs"));
328
- const path_1 = __importDefault(__webpack_require__(/*! path */ "path"));
329
- const sourceFile = typescript_1.default.createSourceFile('source.ts', '', typescript_1.default.ScriptTarget.Latest, false, typescript_1.default.ScriptKind.TS);
330
- /**
331
- * A class to generate typescript definitions for java classes.
332
- * Converts the given class and all of its dependencies to typescript.
333
- *
334
- * ## Example
335
- * ```ts
336
- * import { TypescriptDefinitionGenerator } from 'java-bridge';
337
- *
338
- * const generator = new TypescriptDefinitionGenerator('java.lang.String');
339
- * // Generate the typescript definitions
340
- * const definitions = await generator.generate();
341
- *
342
- * // Save the definitions to a directory
343
- * await TypescriptDefinitionGenerator.save(definitions, './project');
344
- * ```
345
- */
346
- class TypescriptDefinitionGenerator {
347
- /**
348
- * Create a new `TypescriptDefinitionGenerator` instance
349
- *
350
- * @param classname the fully-qualified name of the class to generate a typescript definition for
351
- * @param progressCallback a callback method to be called every time a java class is
352
- * converted to typescript
353
- * @param resolvedImports a list of imports that have already been resolved.
354
- * This is used to prevent converting a class multiple times
355
- */
356
- constructor(classname, progressCallback = null, resolvedImports = []) {
357
- this.classname = classname;
358
- this.progressCallback = progressCallback;
359
- this.resolvedImports = resolvedImports;
360
- this.usesBasicOrJavaType = false;
361
- this.additionalImports = [];
362
- this.importsToResolve = [];
363
- }
364
- static async convertMethods(methods) {
365
- const Modifier = await (0, _1.importClassAsync)('java.lang.reflect.Modifier');
366
- const result = {};
367
- for (const method of methods) {
368
- const modifiers = await method.getModifiers();
369
- if (await Modifier.isPublic(modifiers)) {
370
- const name = await method.getName();
371
- const returnType = await method.getReturnType();
372
- const parameterTypes = await method.getParameterTypes();
373
- const data = {
374
- returnType: await returnType.getTypeName(),
375
- parameters: await Promise.all(parameterTypes.map((p) => p.getTypeName())),
376
- isStatic: await Modifier.isStatic(modifiers),
377
- };
378
- if (Object.hasOwn(result, name)) {
379
- result[name].push(data);
380
- }
381
- else {
382
- result[name] = [data];
383
- }
384
- }
385
- }
386
- return result;
387
- }
388
- async convertConstructors(constructors) {
389
- const Modifier = await (0, _1.importClassAsync)('java.lang.reflect.Modifier');
390
- const types = [];
391
- for (const constructor of constructors) {
392
- const modifiers = await constructor.getModifiers();
393
- if (await Modifier.isPublic(modifiers)) {
394
- const parameterTypes = await constructor.getParameterTypes();
395
- types.push(await Promise.all(parameterTypes.map((p) => p.getTypeName())));
396
- }
397
- }
398
- const tsConstructors = types.map((t, i) => {
399
- const params = t.map(this.convertParameter.bind(this));
400
- let declaration = typescript_1.default.factory.createConstructorDeclaration([typescript_1.default.factory.createModifier(typescript_1.default.SyntaxKind.PublicKeyword)], params, undefined);
401
- if (i === 0) {
402
- declaration = typescript_1.default.addSyntheticLeadingComment(declaration, typescript_1.default.SyntaxKind.SingleLineCommentTrivia, ` ================== Constructors ==================`, true);
403
- }
404
- if (t.length > 0) {
405
- declaration = typescript_1.default.addSyntheticLeadingComment(declaration, typescript_1.default.SyntaxKind.MultiLineCommentTrivia, '*\n' +
406
- t
407
- .map((p, i) => ` * @param var${i} original type: '${p}'\n`)
408
- .join('') +
409
- ' ', true);
410
- }
411
- return declaration;
412
- });
413
- const newInstanceMethods = types.map((t, i) => {
414
- return this.createMethod({
415
- returnType: this.classname,
416
- parameters: t,
417
- isStatic: true,
418
- }, 'newInstance', i, false);
419
- });
420
- return [...newInstanceMethods, ...tsConstructors];
421
- }
422
- javaTypeToTypescriptType(javaType, isParam) {
423
- switch (javaType) {
424
- case 'byte[]':
425
- case 'java.lang.Byte[]':
426
- return typescript_1.default.factory.createTypeReferenceNode('Buffer');
427
- }
428
- if (javaType.endsWith('[]')) {
429
- return typescript_1.default.factory.createArrayTypeNode(this.javaTypeToTypescriptType(javaType.substring(0, javaType.length - 2), isParam));
430
- }
431
- switch (javaType) {
432
- case 'int':
433
- case 'java.lang.Integer':
434
- case 'long':
435
- case 'java.lang.Long':
436
- case 'float':
437
- case 'java.lang.Float':
438
- case 'double':
439
- case 'java.lang.Double':
440
- case 'byte':
441
- case 'java.lang.Byte':
442
- case 'short':
443
- case 'java.lang.Short':
444
- return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.NumberKeyword);
445
- case 'char':
446
- case 'java.lang.Character':
447
- case 'java.lang.String':
448
- return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.StringKeyword);
449
- case 'boolean':
450
- case 'java.lang.Boolean':
451
- return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.BooleanKeyword);
452
- case 'void':
453
- case 'java.lang.Void':
454
- return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.VoidKeyword);
455
- case 'java.lang.Object':
456
- this.usesBasicOrJavaType = true;
457
- return typescript_1.default.factory.createTypeReferenceNode('BasicOrJavaType');
458
- default:
459
- if (!this.resolvedImports.includes(javaType)) {
460
- this.additionalImports.push(javaType);
461
- }
462
- this.importsToResolve.push(javaType);
463
- const isSelf = javaType === this.classname && isParam;
464
- return typescript_1.default.factory.createTypeReferenceNode(javaType === this.classname
465
- ? javaType.substring(javaType.lastIndexOf('.') + 1) +
466
- (isSelf ? 'Class' : '')
467
- : javaType.replaceAll('.', '_'));
468
- }
469
- }
470
- convertParameter(param, index) {
471
- const name = 'var' + index;
472
- const type = this.javaTypeToTypescriptType(param, true);
473
- return typescript_1.default.factory.createParameterDeclaration(undefined, undefined, name, undefined, type);
474
- }
475
- convertParameters(params) {
476
- return params.parameters.map(this.convertParameter.bind(this));
477
- }
478
- static createMethodComment(declaration) {
479
- return ('*\n' +
480
- declaration.parameters
481
- .map((p, i) => ` * @param var${i} original type: '${p}'\n`)
482
- .join('') +
483
- ` * @return original return type: '${declaration.returnType}'\n `);
484
- }
485
- createMethod(m, name, i, isSync) {
486
- const publicMod = typescript_1.default.factory.createModifier(typescript_1.default.SyntaxKind.PublicKeyword);
487
- const staticMod = typescript_1.default.factory.createModifier(typescript_1.default.SyntaxKind.StaticKeyword);
488
- const modifiers = [publicMod];
489
- if (m.isStatic) {
490
- modifiers.push(staticMod);
491
- }
492
- let returnType = this.javaTypeToTypescriptType(m.returnType, false);
493
- if (!isSync) {
494
- returnType = typescript_1.default.factory.createTypeReferenceNode(typescript_1.default.factory.createIdentifier('Promise'), [returnType]);
495
- }
496
- let declaration = typescript_1.default.factory.createMethodDeclaration(modifiers, undefined, name + (isSync ? 'Sync' : ''), undefined, undefined, this.convertParameters(m), returnType, undefined);
497
- if (i === 0) {
498
- declaration = typescript_1.default.addSyntheticLeadingComment(declaration, typescript_1.default.SyntaxKind.SingleLineCommentTrivia, ` ================== Method ${name} ==================`, true);
499
- }
500
- return typescript_1.default.addSyntheticLeadingComment(declaration, typescript_1.default.SyntaxKind.MultiLineCommentTrivia, TypescriptDefinitionGenerator.createMethodComment(m), true);
501
- }
502
- convertMethod(method, name) {
503
- const res = [];
504
- for (let i = 0; i < method.length; i++) {
505
- const m = method[i];
506
- res.push(this.createMethod(m, name, i, false), this.createMethod(m, name, i, true));
507
- }
508
- return res;
509
- }
510
- getAdditionalImports() {
511
- const getPath = (i) => {
512
- const thisSplit = this.classname.split('.');
513
- const importSplit = i.split('.');
514
- for (let j = 0; j < thisSplit.length; j++) {
515
- if (importSplit[j] === thisSplit[j]) {
516
- thisSplit[j] = null;
517
- importSplit[j] = null;
518
- }
519
- else {
520
- break;
521
- }
522
- }
523
- return ('./' +
524
- thisSplit
525
- .filter((e) => !!e)
526
- .map(() => '')
527
- .join('../') +
528
- importSplit.filter((e) => !!e).join('/'));
529
- };
530
- const unique = (value, index, self) => {
531
- return self.indexOf(value) === index;
532
- };
533
- return this.importsToResolve
534
- .filter((i) => i != this.classname)
535
- .filter(unique)
536
- .map((i) => typescript_1.default.factory.createImportDeclaration(undefined, typescript_1.default.factory.createImportClause(false, undefined, typescript_1.default.factory.createNamedImports([
537
- typescript_1.default.factory.createImportSpecifier(false, typescript_1.default.factory.createIdentifier(i.substring(i.lastIndexOf('.') + 1)), typescript_1.default.factory.createIdentifier(i.replaceAll('.', '_'))),
538
- ])), typescript_1.default.factory.createStringLiteral(getPath(i))));
539
- }
540
- getImports() {
541
- const importElements = [
542
- typescript_1.default.factory.createImportSpecifier(false, undefined, typescript_1.default.factory.createIdentifier('importClass')),
543
- typescript_1.default.factory.createImportSpecifier(false, undefined, typescript_1.default.factory.createIdentifier('JavaClass')),
544
- ];
545
- if (this.usesBasicOrJavaType) {
546
- importElements.push(typescript_1.default.factory.createImportSpecifier(false, undefined, typescript_1.default.factory.createIdentifier('BasicOrJavaType')));
547
- }
548
- const imports = typescript_1.default.factory.createNamedImports(importElements);
549
- return typescript_1.default.factory.createImportDeclaration(undefined, typescript_1.default.factory.createImportClause(false, undefined, imports), typescript_1.default.factory.createStringLiteral('java-bridge'));
550
- }
551
- getExportStatement(simpleName) {
552
- const statement = typescript_1.default.factory.createClassDeclaration([typescript_1.default.factory.createModifier(typescript_1.default.SyntaxKind.ExportKeyword)], simpleName, undefined, [
553
- typescript_1.default.factory.createHeritageClause(typescript_1.default.SyntaxKind.ExtendsKeyword, [
554
- typescript_1.default.factory.createExpressionWithTypeArguments(typescript_1.default.factory.createIdentifier(`importClass<typeof ${simpleName}Class>("${this.classname}")`), undefined),
555
- ]),
556
- ], []);
557
- return [
558
- typescript_1.default.addSyntheticLeadingComment(statement, typescript_1.SyntaxKind.MultiLineCommentTrivia, `*\n * Class ${this.classname}.\n *\n` +
559
- ' * This actually imports the java class for further use.\n' +
560
- ` * The class ${simpleName}Class only defines types, this is the class you should actually import.\n` +
561
- ' * Please note that this statement imports the underlying java class at runtime, which may take a while.\n' +
562
- ' * This was generated by java-bridge.\n * You should probably not edit this.\n ', true),
563
- typescript_1.default.factory.createExportDefault(typescript_1.default.factory.createIdentifier(simpleName)),
564
- ];
565
- }
566
- getText(nodes) {
567
- return nodes
568
- .map((n) => (n &&
569
- typescript_1.default
570
- .createPrinter({ newLine: typescript_1.default.NewLineKind.LineFeed })
571
- .printNode(typescript_1.default.EmitHint.Unspecified, n, sourceFile)) ||
572
- '')
573
- .join('\n');
574
- }
575
- /**
576
- * Generates the typescript definition for the given class.
577
- *
578
- * @returns the generated typescript definitions
579
- */
580
- async generate() {
581
- if (this.resolvedImports.includes(this.classname)) {
582
- return [];
583
- }
584
- this.resolvedImports.push(this.classname);
585
- if (this.progressCallback) {
586
- this.progressCallback(this.classname);
587
- }
588
- const Class = await (0, _1.importClassAsync)(this.classname);
589
- const cls = Class.class;
590
- const simpleName = this.classname.substring(this.classname.lastIndexOf('.') + 1);
591
- const methods = await cls.getDeclaredMethods();
592
- const classMembers = [];
593
- const convertedMethods = await TypescriptDefinitionGenerator.convertMethods(methods);
594
- for (const key of Object.keys(convertedMethods)) {
595
- const m = convertedMethods[key];
596
- classMembers.push(...this.convertMethod(m, key));
597
- }
598
- const constructors = await cls.getDeclaredConstructors();
599
- const convertedConstructors = await this.convertConstructors(constructors);
600
- classMembers.push(...convertedConstructors);
601
- let tsClass = typescript_1.default.factory.createClassDeclaration([
602
- typescript_1.default.factory.createModifier(typescript_1.default.SyntaxKind.ExportKeyword),
603
- typescript_1.default.factory.createModifier(typescript_1.default.SyntaxKind.DeclareKeyword),
604
- ], simpleName + 'Class', undefined, [
605
- typescript_1.default.factory.createHeritageClause(typescript_1.default.SyntaxKind.ExtendsKeyword, [
606
- typescript_1.default.factory.createExpressionWithTypeArguments(typescript_1.default.factory.createIdentifier('JavaClass'), undefined),
607
- ]),
608
- ], classMembers);
609
- tsClass = typescript_1.default.addSyntheticLeadingComment(tsClass, typescript_1.default.SyntaxKind.MultiLineCommentTrivia, `*\n * This class just defines types, you should import ${simpleName} instead of this.\n` +
610
- ' * This was generated by java-bridge.\n * You should probably not edit this.\n ', true);
611
- const sourceText = this.getText([
612
- this.getImports(),
613
- ...this.getAdditionalImports(),
614
- null,
615
- tsClass,
616
- null,
617
- ...this.getExportStatement(simpleName),
618
- ]);
619
- const res = [];
620
- for (const imported of this.additionalImports) {
621
- const generator = new TypescriptDefinitionGenerator(imported, this.progressCallback, this.resolvedImports);
622
- const generated = await generator.generate();
623
- res.push(...generated);
624
- }
625
- res.push({
626
- name: this.classname,
627
- contents: sourceText,
628
- });
629
- return res;
630
- }
631
- /**
632
- * Save the converted classes to the given directory.
633
- *
634
- * @param declarations the declarations to save
635
- * @param sourceDir the directory to save the files to
636
- */
637
- static async save(declarations, sourceDir) {
638
- for (const declaration of declarations) {
639
- const p = declaration.name.split('.');
640
- p[p.length - 1] = p[p.length - 1] + '.ts';
641
- const filePath = path_1.default.join(sourceDir, ...p);
642
- await fs_1.default.promises.mkdir(path_1.default.dirname(filePath), {
643
- recursive: true,
644
- });
645
- await fs_1.default.promises.writeFile(filePath, declaration.contents, {
646
- encoding: 'utf8',
647
- });
648
- }
649
- }
650
- }
651
- exports["default"] = TypescriptDefinitionGenerator;
652
-
653
-
654
- /***/ }),
655
-
656
- /***/ "./ts-src/definitions.ts":
657
- /*!*******************************!*\
658
- !*** ./ts-src/definitions.ts ***!
659
- \*******************************/
660
- /***/ ((__unused_webpack_module, exports) => {
661
-
662
- "use strict";
663
-
664
- Object.defineProperty(exports, "__esModule", ({ value: true }));
665
- exports.JavaObject = exports.JavaVersion = void 0;
666
- /**
667
- * The supported java versions.
668
- * Your list of supported versions
669
- * may differ if you use a different
670
- * version of the jvm shared library.
671
- */
672
- var JavaVersion;
673
- (function (JavaVersion) {
674
- /** Java version 1.1 */
675
- JavaVersion["VER_1_1"] = "1.1";
676
- /** Java version 1.2 */
677
- JavaVersion["VER_1_2"] = "1.2";
678
- /** Java version 1.4 */
679
- JavaVersion["VER_1_4"] = "1.4";
680
- /** Java version 1.6 */
681
- JavaVersion["VER_1_6"] = "1.6";
682
- /** Java version 1.8 */
683
- JavaVersion["VER_1_8"] = "1.8";
684
- /** Java version 9 */
685
- JavaVersion["VER_9"] = "9";
686
- /** Java version 10 */
687
- JavaVersion["VER_10"] = "10";
688
- })(JavaVersion = exports.JavaVersion || (exports.JavaVersion = {}));
689
- Object.freeze(JavaVersion);
690
- /**
691
- * A dummy java object class
692
- */
693
- class JavaObject {
694
- }
695
- exports.JavaObject = JavaObject;
696
-
697
-
698
- /***/ }),
699
-
700
- /***/ "./ts-src/index.ts":
701
- /*!*************************!*\
702
- !*** ./ts-src/index.ts ***!
703
- \*************************/
704
- /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
705
-
706
- "use strict";
707
-
708
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
709
- if (k2 === undefined) k2 = k;
710
- var desc = Object.getOwnPropertyDescriptor(m, k);
711
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
712
- desc = { enumerable: true, get: function() { return m[k]; } };
713
- }
714
- Object.defineProperty(o, k2, desc);
715
- }) : (function(o, m, k, k2) {
716
- if (k2 === undefined) k2 = k;
717
- o[k2] = m[k];
718
- }));
719
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
720
- Object.defineProperty(o, "default", { enumerable: true, value: v });
721
- }) : function(o, v) {
722
- o["default"] = v;
723
- });
724
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
725
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
726
- };
727
- var __importStar = (this && this.__importStar) || function (mod) {
728
- if (mod && mod.__esModule) return mod;
729
- var result = {};
730
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
731
- __setModuleDefault(result, mod);
732
- return result;
733
- };
734
- var __importDefault = (this && this.__importDefault) || function (mod) {
735
- return (mod && mod.__esModule) ? mod : { "default": mod };
736
- };
737
- Object.defineProperty(exports, "__esModule", ({ value: true }));
738
- exports.TypescriptDefinitionGenerator = exports.getJavaLibPath = exports.JavaClassConstructor = exports.JavaClass = exports.JavaClassProxy = exports.JavaClassInstance = exports.JavaObject = exports.JavaVersion = void 0;
739
- var definitions_1 = __webpack_require__(/*! ./definitions */ "./ts-src/definitions.ts");
740
- Object.defineProperty(exports, "JavaVersion", ({ enumerable: true, get: function () { return definitions_1.JavaVersion; } }));
741
- Object.defineProperty(exports, "JavaObject", ({ enumerable: true, get: function () { return definitions_1.JavaObject; } }));
742
- Object.defineProperty(exports, "JavaClassInstance", ({ enumerable: true, get: function () { return definitions_1.JavaClassInstance; } }));
743
- Object.defineProperty(exports, "JavaClassProxy", ({ enumerable: true, get: function () { return definitions_1.JavaClassProxy; } }));
744
- Object.defineProperty(exports, "JavaClass", ({ enumerable: true, get: function () { return definitions_1.JavaClass; } }));
745
- Object.defineProperty(exports, "JavaClassConstructor", ({ enumerable: true, get: function () { return definitions_1.JavaClassConstructor; } }));
746
- __exportStar(__webpack_require__(/*! ./java */ "./ts-src/java.ts"), exports);
747
- const java = __importStar(__webpack_require__(/*! ./java */ "./ts-src/java.ts"));
748
- exports["default"] = java;
749
- var native_1 = __webpack_require__(/*! ../native */ "./native.js");
750
- Object.defineProperty(exports, "getJavaLibPath", ({ enumerable: true, get: function () { return native_1.getJavaLibPath; } }));
751
- const TypescriptDefinitionGenerator_1 = __importDefault(__webpack_require__(/*! ./TypescriptDefinitionGenerator */ "./ts-src/TypescriptDefinitionGenerator.ts"));
752
- exports.TypescriptDefinitionGenerator = TypescriptDefinitionGenerator_1.default;
753
-
754
-
755
- /***/ }),
756
-
757
- /***/ "./ts-src/java.ts":
758
- /*!************************!*\
759
- !*** ./ts-src/java.ts ***!
760
- \************************/
761
- /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
762
-
763
- "use strict";
764
-
765
- Object.defineProperty(exports, "__esModule", ({ value: true }));
766
- exports.getJavaInstance = exports.newProxy = exports.stdout = exports.classpath = exports.isInstanceOf = exports.appendClasspath = exports.importClassAsync = exports.importClass = exports.ensureJvm = void 0;
767
- const native_1 = __webpack_require__(/*! ../native */ "./native.js");
768
- const nativeLib_1 = __webpack_require__(/*! ./nativeLib */ "./ts-src/nativeLib.ts");
769
- /**
770
- * The static java instance
771
- */
772
- let javaInstance = null;
773
- /**
774
- * Ensure the java vm is created.
775
- * If the jvm is already created, this does nothing.
776
- * If the vm is not created yet, the jvm will be created upon this call.
777
- * This method is also called every time with no arguments when any call
778
- * to the jvm is done in another method.
779
- *
780
- * ## Examples
781
- * Specify the path to jvm.(dylib|dll|so) manually,
782
- * specify the java version to use and set to use daemon threads.
783
- * ```ts
784
- * import { ensureJvm, JavaVersion } from 'java-bridge';
785
- *
786
- * ensureJvm({
787
- * libPath: 'path/to/jvm.dll',
788
- * version: JavaVersion.VER_9,
789
- * useDaemonThreads: true
790
- * });
791
- * ```
792
- *
793
- * Let the plugin find the jvm.(dylib|dll|so)
794
- * ```ts
795
- * ensureJvm({
796
- * JavaVersion.VER_9,
797
- * useDaemonThreads: true
798
- * });
799
- * ```
800
- *
801
- * Let the plugin find the jvm.(dylib|dll|so) and use the default options
802
- * ```ts
803
- * ensureJvm();
804
- * ```
805
- *
806
- * @param options the options to use when creating the jvm
807
- */
808
- function ensureJvm(options) {
809
- if (!javaInstance) {
810
- javaInstance = new native_1.Java(options?.libPath, options?.version, options?.opts, options, (0, nativeLib_1.getJavaLibPath)(), (0, nativeLib_1.getNativeLibPath)());
811
- }
812
- }
813
- exports.ensureJvm = ensureJvm;
814
- function defineFields(object, getStatic) {
815
- for (const field of (0, native_1.getClassFields)(object['class.proxy'], getStatic)) {
816
- const getter = () => getStatic
817
- ? (0, native_1.getStaticField)(object, field.name)
818
- : (0, native_1.getField)(object, field.name);
819
- if (field.isFinal) {
820
- Object.defineProperty(object, field.name, {
821
- get: getter,
822
- enumerable: true,
823
- });
824
- }
825
- else {
826
- Object.defineProperty(object, field.name, {
827
- get: getter,
828
- set: (value) => getStatic
829
- ? (0, native_1.setStaticField)(object, field.name, value)
830
- : (0, native_1.setField)(object, field.name, value),
831
- enumerable: true,
832
- });
833
- }
834
- }
835
- }
836
- /**
837
- * Import a class.
838
- * Returns the constructor of the class to be created.
839
- * For example, import "java.util.ArrayList" for a java Array List.
840
- *
841
- * Define a custom class type for the imported class and pass the
842
- * constructor type of the class as the template parameter to get
843
- * the proper type returned. You could also just cast the result.
844
- *
845
- * ## Examples
846
- * ### Import ``java.util.ArrayList`` and create a new instance of it
847
- * ```ts
848
- * import { importClass } from 'java-bridge';
849
- *
850
- * // Import java.util.ArrayList
851
- * const ArrayList = importClass('java.util.ArrayList');
852
- *
853
- * // Create a new instance of ArrayList
854
- * const list = new ArrayList();
855
- * ```
856
- *
857
- * ### Import ``java.util.ArrayList`` with types
858
- * ```ts
859
- * import { importClass, JavaClassInstance, JavaType } from 'java-bridge';
860
- *
861
- * // Definitions for class java.util.List
862
- * declare class List <T extends JavaType> extends JavaClassInstance {
863
- * size(): Promise<number>;
864
- * sizeSync(): number;
865
- * add(e: T): Promise<void>;
866
- * addSync(e: T): void;
867
- * get(index: number): Promise<T>;
868
- * getSync(index: number): T;
869
- * toArray(): Promise<T[]>;
870
- * toArraySync(): T[];
871
- * isEmpty(): Promise<boolean>;
872
- * isEmptySync(): boolean;
873
- * }
874
- *
875
- * // Definitions for class java.util.ArrayList
876
- * declare class ArrayListClass<T extends JavaType> extends List<T> {
877
- * public constructor(other: ArrayListClass<T>);
878
- * public constructor();
879
- * }
880
- *
881
- * // This causes the class to be import when the module is loaded.
882
- * class ArrayList<T> extends importClass<typeof ArrayListClass>('java.util.ArrayList')<T> {}
883
- *
884
- * // Create a new ArrayList instance
885
- * const list = new ArrayList<string>();
886
- *
887
- * // Add some contents to the list
888
- * list.add('Hello');
889
- * list.add('World');
890
- *
891
- * // Check the list contents
892
- * assert.equals(list.sizeSync(), 2);
893
- * assert.equals(list.getSync(0), 'Hello');
894
- * assert.equals(list.getSync(1), 'World');
895
- * ```
896
- *
897
- * @template T the type of the java class to import as a js type
898
- * @param classname the name of the class to resolve
899
- * @return the java class constructor
900
- */
901
- function importClass(classname) {
902
- ensureJvm();
903
- const constructor = javaInstance.importClass(classname);
904
- defineFields(constructor, true);
905
- constructor.constructor = function (...args) {
906
- const object = new constructor.prototype.constructor(...args);
907
- defineFields(object, false);
908
- return object;
909
- };
910
- return constructor;
911
- }
912
- exports.importClass = importClass;
913
- /**
914
- * @inheritDoc importClass
915
- */
916
- async function importClassAsync(classname) {
917
- ensureJvm();
918
- const constructor = (await javaInstance.importClassAsync(classname));
919
- defineFields(constructor, true);
920
- constructor.constructor = function (...args) {
921
- const object = new constructor.prototype.constructor(...args);
922
- defineFields(object, false);
923
- return object;
924
- };
925
- return constructor;
926
- }
927
- exports.importClassAsync = importClassAsync;
928
- /**
929
- * Append a single or multiple jars to the class path.
930
- *
931
- * Just replaces the old internal class loader with a new one containing the new jars.
932
- * This doesn't check if the jars are valid and/or even exist.
933
- * The new classpath will be available to all classes imported after this call.
934
- *
935
- * ## Example
936
- * ```ts
937
- * import { appendClasspath } from 'java-bridge';
938
- *
939
- * // Append a single jar to the class path
940
- * appendClasspath('/path/to/jar.jar');
941
- *
942
- * // Append multiple jars to the class path
943
- * appendClasspath(['/path/to/jar1.jar', '/path/to/jar2.jar']);
944
- * ```
945
- * or
946
- * ```ts
947
- * import { classpath } from 'java-bridge';
948
- *
949
- * // Append a single jar to the class path
950
- * classpath.append('/path/to/jar.jar');
951
- * ```
952
- *
953
- * @param path the path(s) to add
954
- */
955
- function appendClasspath(path) {
956
- ensureJvm();
957
- javaInstance.appendClasspath(path);
958
- }
959
- exports.appendClasspath = appendClasspath;
960
- /**
961
- * Check if `this_obj` is instance of `other`.
962
- * This uses the native java `instanceof` operator.
963
- * You may want to use this if {@link JavaClass.instanceOf}
964
- * is overridden, as that method itself does not override
965
- * any method defined in the specific java class named 'instanceOf'.
966
- *
967
- * ## Example
968
- * ```ts
969
- * import { instanceOf, importClass } from 'java-bridge';
970
- *
971
- * const ArrayList = importClass('java.util.ArrayList');
972
- * const list = new ArrayList();
973
- *
974
- * isInstanceOf(list, ArrayList); // true
975
- * isInstanceOf(list, 'java.util.ArrayList'); // true
976
- * isInstanceOf(list, 'java.util.List'); // true
977
- * isInstanceOf(list, 'java.util.Collection'); // true
978
- * isInstanceOf(list, 'java.lang.Object'); // true
979
- * isInstanceOf(list, 'java.lang.String'); // false
980
- *
981
- * // You can also use the instanceOf method (if not overridden)
982
- * list.instanceOf(ArrayList); // true
983
- * list.instanceOf('java.util.ArrayList'); // true
984
- * list.instanceOf('java.util.List'); // true
985
- * list.instanceOf('java.util.Collection'); // true
986
- * list.instanceOf('java.lang.Object'); // true
987
- * list.instanceOf('java.lang.String'); // false
988
- * ```
989
- *
990
- * @param this_obj the object to check
991
- * @param other the class or class name to check against
992
- * @return true if `this_obj` is an instance of `other`
993
- */
994
- function isInstanceOf(this_obj, other) {
995
- ensureJvm();
996
- return javaInstance.isInstanceOf(this_obj, other);
997
- }
998
- exports.isInstanceOf = isInstanceOf;
999
- /**
1000
- * Methods for altering and querying the class path.
1001
- * @example
1002
- * import { classpath } from 'java-bridge';
1003
- *
1004
- * // Append a jar to the class path
1005
- * classpath.append('/path/to/jar.jar');
1006
- *
1007
- * assert.equal(classpath.get().length, 1);
1008
- * assert.equal(classpath.get()[0], '/path/to/jar.jar');
1009
- */
1010
- var classpath;
1011
- (function (classpath) {
1012
- /**
1013
- * @inheritDoc appendClasspath
1014
- */
1015
- function append(path) {
1016
- appendClasspath(path);
1017
- }
1018
- classpath.append = append;
1019
- /**
1020
- * Get the loaded jars in the class path
1021
- *
1022
- * @returns a list of the loaded jars
1023
- */
1024
- function get() {
1025
- ensureJvm();
1026
- return javaInstance.loadedJars;
1027
- }
1028
- classpath.get = get;
1029
- })(classpath = exports.classpath || (exports.classpath = {}));
1030
- /**
1031
- * A namespace containing methods for redirecting the stdout/stderr of the java process.
1032
- *
1033
- * ## See also
1034
- * * {@link StdoutRedirectGuard}
1035
- * * {@link stdout.enableRedirect}
1036
- */
1037
- var stdout;
1038
- (function (stdout_1) {
1039
- /**
1040
- * Enable stdout/stderr redirection.
1041
- *
1042
- * Pass methods for the stdout and stderr output to be redirected to.
1043
- * These methods must accept an error as the first argument,
1044
- * although this will probably never be set and can be ignored.
1045
- * The second argument is the data that was redirected.
1046
- *
1047
- * Setting any method to ``null`` or ``undefined`` will disable the redirect for that method.
1048
- * This also allows you not set any handler which does not make any sense at all.
1049
- *
1050
- * ## Examples
1051
- * ### Redirect all data to the js console
1052
- * ```ts
1053
- * import { stdout } from 'java-bridge';
1054
- *
1055
- * const guard = stdout.enableRedirect((_, data) => {
1056
- * console.log('Stdout:', data);
1057
- * }, (_, data) => {
1058
- * console.error('Stderr:', data);
1059
- * });
1060
- * ```
1061
- *
1062
- * ### Redirect stdout to the js console
1063
- * ```ts
1064
- * const guard = stdout.enableRedirect((_, data) => {
1065
- * console.log('Stdout:', data);
1066
- * });
1067
- * ```
1068
- *
1069
- * ### Redirect stderr to the js console
1070
- * ```ts
1071
- * const guard = stdout.enableRedirect(null, (_, data) => {
1072
- * console.error('Stderr:', data);
1073
- * });
1074
- * ```
1075
- *
1076
- * ### Redirect nothing to the js console (y tho)
1077
- * This enables you to print nothing to nowhere.
1078
- * ```ts
1079
- * // Why would you do this?
1080
- * const guard = stdout.enableRedirect(null, null);
1081
- *
1082
- * // Or
1083
- * const guard = stdout.enableRedirect();
1084
- * ```
1085
- *
1086
- * @see StdoutRedirectGuard
1087
- * @see StdoutCallback
1088
- * @param stdout the callback to be called when stdout is received
1089
- * @param stderr the callback to be called when stderr is received
1090
- * @returns a <code>StdoutRedirectGuard</code> instance. Keep this instance in scope to not lose the redirect.
1091
- */
1092
- function enableRedirect(stdout, stderr) {
1093
- ensureJvm();
1094
- return javaInstance.setStdoutCallbacks(stdout, stderr);
1095
- }
1096
- stdout_1.enableRedirect = enableRedirect;
1097
- })(stdout = exports.stdout || (exports.stdout = {}));
1098
- /**
1099
- * Create a new java interface proxy.
1100
- * This allows you to implement java interfaces in javascript.
1101
- *
1102
- * Pass an object as the second argument with the names of the
1103
- * methods you want to implement as keys and the implementations
1104
- * as values in order to expose these methods to the java process.
1105
- * Any arguments will be converted to javascript values and
1106
- * return values will be converted to java values.
1107
- *
1108
- * When the java process tries to call any method which is
1109
- * not implemented by the proxy, an error will be thrown.
1110
- *
1111
- * ## Examples
1112
- * ### Implement ``java.lang.Runnable``
1113
- * ```ts
1114
- * import { newProxy, importClass } from 'java-bridge';
1115
- *
1116
- * // Define the interface
1117
- * const runnable = newProxy('java.lang.Runnable', {
1118
- * run: (): void => {
1119
- * console.log('Hello World!');
1120
- * }
1121
- * });
1122
- *
1123
- * // Note: You can't do something like this:
1124
- * // runnable.run();
1125
- *
1126
- * // Pass the proxy to a java method instead:
1127
- * const Thread = importClass('java.lang.Thread');
1128
- * const thread = new Thread(runnable); // <- Pass the proxy here
1129
- *
1130
- * // NOTE: You don't have to call this asynchronously
1131
- * // as this call instantly returns.
1132
- * thread.startSync();
1133
- * ```
1134
- *
1135
- * ### Implement ``java.util.function.Function`` to transform a string
1136
- * ```ts
1137
- * const func = newProxy('java.util.function.Function', {
1138
- * // Any parameters and return types will be automatically converted
1139
- * apply: (str: string): string => {
1140
- * return str.toUpperCase();
1141
- * }
1142
- * });
1143
- *
1144
- * // Import the string class
1145
- * const JString = java.importClass('java.lang.String');
1146
- * const str = new JString('hello');
1147
- *
1148
- * // Pass the proxy.
1149
- * // NOTE: You must call this method async otherwise your program will hang.
1150
- * // See notes for more info.
1151
- * const transformed = await str.transform(func);
1152
- *
1153
- * assert.assertEquals(transformed, 'HELLO');
1154
- * ```
1155
- *
1156
- * Which is equivalent to the following java code:
1157
- * ```java
1158
- * Function<String, String> func = new Function<>() {
1159
- * @Override
1160
- * public String apply(String str) {
1161
- * return str.toUpperCase();
1162
- * }
1163
- * };
1164
- *
1165
- * String str = "hello";
1166
- * String transformed = str.transform(func);
1167
- * assert.assertEquals(transformed, "HELLO");
1168
- * ```
1169
- *
1170
- * #### Throwing exceptions
1171
- * Any exceptions thrown by the proxy will be converted to java exceptions
1172
- * and then rethrown in the java process. This may cause the exception
1173
- * to again be rethrown in the javascript process.
1174
- * ```ts
1175
- * const func = newProxy('java.util.function.Function', {
1176
- * apply: (str: string): string => {
1177
- * throw new Error('Something went wrong');
1178
- * }
1179
- * });
1180
- *
1181
- * const JString = java.importClass('java.lang.String');
1182
- * const str = new JString('hello');
1183
- *
1184
- * // This will re-throw the above error
1185
- * const transformed: never = await str.transform(func);
1186
- * ```
1187
- *
1188
- * ## Notes
1189
- * * Keep this instance in scope to not destroy the interface proxy.
1190
- * * Call {@link JavaInterfaceProxy.reset} to instantly destroy this instance.
1191
- * * If any method is queried by the java process and not implemented in here,
1192
- * an exception will be thrown in the java process.
1193
- * * Any errors thrown in the javascript process will be rethrown in the java process.
1194
- * * **When calling a java method that uses an interface defined by this, you must call
1195
- * that method using the interface asynchronously as Node.js is single threaded and can't
1196
- * wait for the java method to return while calling the proxy method at the same time.**
1197
- *
1198
- * ## See also
1199
- * * {@link JavaInterfaceProxy}
1200
- *
1201
- * @param interfaceName the name of the java interface to implement
1202
- * @param methods the methods to implement.
1203
- * @returns a proxy class to pass back to the java process
1204
- */
1205
- function newProxy(interfaceName, methods) {
1206
- ensureJvm();
1207
- const proxyMethods = Object.create(null);
1208
- for (const [name, method] of Object.entries(methods)) {
1209
- proxyMethods[name] = (err, callback, ...args) => {
1210
- if (err) {
1211
- throw err;
1212
- }
1213
- try {
1214
- const res = method(...args);
1215
- callback(null, res);
1216
- }
1217
- catch (e) {
1218
- if (e instanceof Error) {
1219
- callback(e);
1220
- }
1221
- else {
1222
- callback(new Error(e.toString()));
1223
- }
1224
- }
1225
- };
1226
- }
1227
- return javaInstance.createInterfaceProxy(interfaceName, proxyMethods);
1228
- }
1229
- exports.newProxy = newProxy;
1230
- /**
1231
- * Get the static java instance.
1232
- * This has no real use, all important methods are exported explicitly.
1233
- */
1234
- function getJavaInstance() {
1235
- return javaInstance;
1236
- }
1237
- exports.getJavaInstance = getJavaInstance;
1238
-
1239
-
1240
- /***/ }),
1241
-
1242
- /***/ "./ts-src/nativeLib.ts":
1243
- /*!*****************************!*\
1244
- !*** ./ts-src/nativeLib.ts ***!
1245
- \*****************************/
1246
- /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
1247
-
1248
- "use strict";
1249
-
1250
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
1251
- if (k2 === undefined) k2 = k;
1252
- var desc = Object.getOwnPropertyDescriptor(m, k);
1253
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1254
- desc = { enumerable: true, get: function() { return m[k]; } };
1255
- }
1256
- Object.defineProperty(o, k2, desc);
1257
- }) : (function(o, m, k, k2) {
1258
- if (k2 === undefined) k2 = k;
1259
- o[k2] = m[k];
1260
- }));
1261
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
1262
- Object.defineProperty(o, "default", { enumerable: true, value: v });
1263
- }) : function(o, v) {
1264
- o["default"] = v;
1265
- });
1266
- var __importStar = (this && this.__importStar) || function (mod) {
1267
- if (mod && mod.__esModule) return mod;
1268
- var result = {};
1269
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
1270
- __setModuleDefault(result, mod);
1271
- return result;
1272
- };
1273
- var __importDefault = (this && this.__importDefault) || function (mod) {
1274
- return (mod && mod.__esModule) ? mod : { "default": mod };
1275
- };
1276
- Object.defineProperty(exports, "__esModule", ({ value: true }));
1277
- exports.getJavaLibPath = exports.getNativeLibPath = void 0;
1278
- const path_1 = __importDefault(__webpack_require__(/*! path */ "path"));
1279
- const fs_1 = __importStar(__webpack_require__(/*! fs */ "fs"));
1280
- const glob_1 = __importDefault(__webpack_require__(/*! glob */ "glob"));
1281
- const { platform, arch } = process;
1282
- function getModule(base) {
1283
- const local = path_1.default.join(__dirname, base + '.node');
1284
- if (fs_1.default.existsSync(local)) {
1285
- return local;
1286
- }
1287
- else {
1288
- const module = base.replaceAll('.', '-').replace('java', 'java-bridge');
1289
- // @ts-ignore
1290
- if (require && require.resolve) {
1291
- // @ts-ignore
1292
- return require.resolve(module);
1293
- }
1294
- else {
1295
- return /*require.resolve*/(__webpack_require__("./ts-src sync recursive").resolve(module));
1296
- }
1297
- }
1298
- }
1299
- function UnsupportedPlatform() {
1300
- return new Error(`Unsupported platform: ${platform} ${arch}`);
1301
- }
1302
- function isMusl() {
1303
- // For Node 10
1304
- if (!process.report || typeof process.report.getReport !== 'function') {
1305
- try {
1306
- return (0, fs_1.readFileSync)('/usr/bin/ldd', 'utf8').includes('musl');
1307
- }
1308
- catch (e) {
1309
- return true;
1310
- }
1311
- }
1312
- else {
1313
- const { glibcVersionRuntime } = process.report.getReport()
1314
- .header;
1315
- return !glibcVersionRuntime;
1316
- }
1317
- }
1318
- function getNativeLibPath() {
1319
- switch (platform) {
1320
- case 'android':
1321
- switch (arch) {
1322
- case 'arm64':
1323
- return getModule('java.android-arm64');
1324
- case 'arm':
1325
- return getModule('java.android-arm-eabi');
1326
- default:
1327
- throw UnsupportedPlatform();
1328
- }
1329
- case 'win32':
1330
- return getModule(`java.win32-${arch}-msvc`);
1331
- case 'darwin':
1332
- return getModule(`java.darwin-${arch}`);
1333
- case 'freebsd':
1334
- return getModule(`java.freebsd-${arch}`);
1335
- case 'linux':
1336
- switch (arch) {
1337
- case 'x64':
1338
- case 'arm64':
1339
- return getModule(`java.linux-${arch}-${isMusl() ? 'musl' : 'gnu'}`);
1340
- case 'arm':
1341
- return getModule('java.linux-arm-gnueabihf');
1342
- default:
1343
- throw UnsupportedPlatform();
1344
- }
1345
- default:
1346
- throw UnsupportedPlatform();
1347
- }
1348
- }
1349
- exports.getNativeLibPath = getNativeLibPath;
1350
- function getJavaLibPath() {
1351
- const dir = path_1.default.join(__dirname, '..', 'java-src', 'build', 'libs');
1352
- let files = glob_1.default.sync('*.jar', { cwd: dir });
1353
- if (files.length === 0) {
1354
- throw new Error(`No java lib found in ${dir}`);
1355
- }
1356
- else {
1357
- return path_1.default.join(dir, files[0]);
1358
- }
1359
- }
1360
- exports.getJavaLibPath = getJavaLibPath;
1361
-
1362
-
1363
- /***/ }),
1364
-
1365
- /***/ "./ts-src sync recursive":
1366
- /*!**********************!*\
1367
- !*** ./ts-src/ sync ***!
1368
- \**********************/
1369
- /***/ ((module) => {
1370
-
1371
- function webpackEmptyContext(req) {
1372
- var e = new Error("Cannot find module '" + req + "'");
1373
- e.code = 'MODULE_NOT_FOUND';
1374
- throw e;
1375
- }
1376
- webpackEmptyContext.keys = () => ([]);
1377
- webpackEmptyContext.resolve = webpackEmptyContext;
1378
- webpackEmptyContext.id = "./ts-src sync recursive";
1379
- module.exports = webpackEmptyContext;
1380
-
1381
- /***/ }),
1382
-
1383
- /***/ "glob":
1384
- /*!***********************!*\
1385
- !*** external "glob" ***!
1386
- \***********************/
1387
- /***/ ((module) => {
1388
-
1389
- "use strict";
1390
- module.exports = require("glob");
1391
-
1392
- /***/ }),
1393
-
1394
- /***/ "typescript":
1395
- /*!*****************************!*\
1396
- !*** external "typescript" ***!
1397
- \*****************************/
1398
- /***/ ((module) => {
1399
-
1400
- "use strict";
1401
- module.exports = require("typescript");
1402
-
1403
- /***/ }),
1404
-
1405
- /***/ "fs":
1406
- /*!*********************!*\
1407
- !*** external "fs" ***!
1408
- \*********************/
1409
- /***/ ((module) => {
1410
-
1411
- "use strict";
1412
- module.exports = require("fs");
1413
-
1414
- /***/ }),
1415
-
1416
- /***/ "path":
1417
- /*!***********************!*\
1418
- !*** external "path" ***!
1419
- \***********************/
1420
- /***/ ((module) => {
1421
-
1422
- "use strict";
1423
- module.exports = require("path");
1424
-
1425
- /***/ })
1426
-
1427
- /******/ });
1428
- /************************************************************************/
1429
- /******/ // The module cache
1430
- /******/ var __webpack_module_cache__ = {};
1431
- /******/
1432
- /******/ // The require function
1433
- /******/ function __webpack_require__(moduleId) {
1434
- /******/ // Check if module is in cache
1435
- /******/ var cachedModule = __webpack_module_cache__[moduleId];
1436
- /******/ if (cachedModule !== undefined) {
1437
- /******/ return cachedModule.exports;
1438
- /******/ }
1439
- /******/ // Create a new module (and put it into the cache)
1440
- /******/ var module = __webpack_module_cache__[moduleId] = {
1441
- /******/ id: moduleId,
1442
- /******/ loaded: false,
1443
- /******/ exports: {}
1444
- /******/ };
1445
- /******/
1446
- /******/ // Execute the module function
1447
- /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
1448
- /******/
1449
- /******/ // Flag the module as loaded
1450
- /******/ module.loaded = true;
1451
- /******/
1452
- /******/ // Return the exports of the module
1453
- /******/ return module.exports;
1454
- /******/ }
1455
- /******/
1456
- /************************************************************************/
1457
- /******/ /* webpack/runtime/hasOwnProperty shorthand */
1458
- /******/ (() => {
1459
- /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
1460
- /******/ })();
1461
- /******/
1462
- /******/ /* webpack/runtime/node module decorator */
1463
- /******/ (() => {
1464
- /******/ __webpack_require__.nmd = (module) => {
1465
- /******/ module.paths = [];
1466
- /******/ if (!module.children) module.children = [];
1467
- /******/ return module;
1468
- /******/ };
1469
- /******/ })();
1470
- /******/
1471
- /******/ /* webpack/runtime/publicPath */
1472
- /******/ (() => {
1473
- /******/ __webpack_require__.p = "";
1474
- /******/ })();
1475
- /******/
1476
- /************************************************************************/
1477
- /******/
1478
- /******/ // startup
1479
- /******/ // Load entry module and return exports
1480
- /******/ // This entry module is referenced by other modules so it can't be inlined
1481
- /******/ var __webpack_exports__ = __webpack_require__("./ts-src/index.ts");
1482
- /******/
1483
- /******/ return __webpack_exports__;
1484
- /******/ })()
1485
- ;
1486
- });
1487
- //# sourceMappingURL=index.dev.min.js.map