1. 1// MIT License
2. 1//
3. 1// Copyright (c) 2021 Kai Zhu
4. 1//
5. 1// Permission is hereby granted, free of charge, to any person obtaining a copy
6. 1// of this software and associated documentation files (the "Software"), to deal
7. 1// in the Software without restriction, including without limitation the rights
8. 1// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9. 1// copies of the Software, and to permit persons to whom the Software is
10. 1// furnished to do so, subject to the following conditions:
11. 1//
12. 1// The above copyright notice and this permission notice shall be included in
13. 1// all copies or substantial portions of the Software.
14. 1//
15. 1// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16. 1// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17. 1// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18. 1// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19. 1// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20. 1// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21. 1// SOFTWARE.
22. 1
23. 1
24. 1/*jslint beta, bitwise, name, node*/
25. 1/*global FinalizationRegistry*/
26. 1"use strict";
27. 1
28. 1const JSBATON_ARGC = 8;
29. 1const JSBATON_OFFSET_ALL = 256;
30. 1const JSBATON_OFFSET_ARGV = 128;
31. 1const JSBATON_OFFSET_BUFV = 192;
32. 1// const JSBATON_OFFSET_ERRMSG = 48;
33. 1const JSBATON_OFFSET_FUNCNAME = 8;
34. 1const JS_MAX_SAFE_INTEGER = 0x1f_ffff_ffff_ffff;
35. 1const JS_MIN_SAFE_INTEGER = -0x1f_ffff_ffff_ffff;
36. 1const SIZEOF_BLOB_MAX = 1_000_000_000;
37. 1// const SIZEOF_ERRMSG = 80;
38. 1const SIZEOF_FUNCNAME = 16;
39. 1const SQLITE_DATATYPE_BLOB = 0x04;
40. 1const SQLITE_DATATYPE_EXTERNALBUFFER = 0x71;
41. 1const SQLITE_DATATYPE_FLOAT = 0x02;
42. 1const SQLITE_DATATYPE_INTEGER = 0x01;
43. 1const SQLITE_DATATYPE_INTEGER_0 = 0x00;
44. 1const SQLITE_DATATYPE_INTEGER_1 = 0x21;
45. 1const SQLITE_DATATYPE_NULL = 0x05;
46. 1const SQLITE_DATATYPE_TEXT = 0x03;
47. 1const SQLITE_DATATYPE_TEXT_0 = 0x13;
48. 1const SQLITE_RESPONSETYPE_LASTBLOB = 1;
49. 1const SQLITE_RESPONSETYPE_LASTVALUE = 2;
50. 1
51. 1const FILENAME_DBTMP = "/tmp/__dbtmp1"; //jslint-ignore-line
52. 1
53. 1const LGBM_DTYPE_FLOAT32 = 0; /* float32 (single precision float)*/
54. 1const LGBM_DTYPE_FLOAT64 = 1; /* float64 (double precision float)*/
55. 1const LGBM_DTYPE_INT32 = 2; /* int32*/
56. 1const LGBM_DTYPE_INT64 = 3; /* int64*/
57. 1const LGBM_FEATURE_IMPORTANCE_GAIN = 1; /* Gain type of feature importance*/
58. 1const LGBM_FEATURE_IMPORTANCE_SPLIT = 0;/* Split type of feature importance*/
59. 1const LGBM_MATRIX_TYPE_CSC = 1; /* CSC sparse matrix type*/
60. 1const LGBM_MATRIX_TYPE_CSR = 0; /* CSR sparse matrix type*/
61. 1const LGBM_PREDICT_CONTRIB = 3; /* Predict feature contributions (SHAP values)*/
62. 1const LGBM_PREDICT_LEAF_INDEX = 2; /* Predict leaf index*/
63. 1const LGBM_PREDICT_NORMAL = 0; /* Normal prediction w/ transform (if needed)*/
64. 1const LGBM_PREDICT_RAW_SCORE = 1; /* Predict raw score*/
65. 1const SQLITE_OPEN_AUTOPROXY = 0x00000020; /* VFS only */
66. 1const SQLITE_OPEN_CREATE = 0x00000004; /* Ok for sqlite3_open_v2() */
67. 1const SQLITE_OPEN_DELETEONCLOSE = 0x00000008; /* VFS only */
68. 1const SQLITE_OPEN_EXCLUSIVE = 0x00000010; /* VFS only */
69. 1const SQLITE_OPEN_FULLMUTEX = 0x00010000; /* Ok for sqlite3_open_v2() */
70. 1const SQLITE_OPEN_MAIN_DB = 0x00000100; /* VFS only */
71. 1const SQLITE_OPEN_MAIN_JOURNAL = 0x00000800; /* VFS only */
72. 1const SQLITE_OPEN_MEMORY = 0x00000080; /* Ok for sqlite3_open_v2() */
73. 1const SQLITE_OPEN_NOFOLLOW = 0x01000000; /* Ok for sqlite3_open_v2() */
74. 1const SQLITE_OPEN_NOMUTEX = 0x00008000; /* Ok for sqlite3_open_v2() */
75. 1const SQLITE_OPEN_PRIVATECACHE = 0x00040000; /* Ok for sqlite3_open_v2() */
76. 1const SQLITE_OPEN_READONLY = 0x00000001; /* Ok for sqlite3_open_v2() */
77. 1const SQLITE_OPEN_READWRITE = 0x00000002; /* Ok for sqlite3_open_v2() */
78. 1const SQLITE_OPEN_SHAREDCACHE = 0x00020000; /* Ok for sqlite3_open_v2() */
79. 1const SQLITE_OPEN_SUBJOURNAL = 0x00002000; /* VFS only */
80. 1const SQLITE_OPEN_SUPER_JOURNAL = 0x00004000; /* VFS only */
81. 1const SQLITE_OPEN_TEMP_DB = 0x00000200; /* VFS only */
82. 1const SQLITE_OPEN_TEMP_JOURNAL = 0x00001000; /* VFS only */
83. 1const SQLITE_OPEN_TRANSIENT_DB = 0x00000400; /* VFS only */
84. 1const SQLITE_OPEN_URI = 0x00000040; /* Ok for sqlite3_open_v2() */
85. 1const SQLITE_OPEN_WAL = 0x00080000; /* VFS only */
86. 1
87. 1let IS_BROWSER;
88. 1let cModule;
89. 1let cModulePath;
90. 1let consoleError = console.error;
91. 1let dbFinalizationRegistry;
92. 1// init debugInline
93. 1let debugInline = (function () {
94. 3 let __consoleError = function () {
95. 3 return;
96. 3 };
97. 1 function debug(...argv) {
98. 1
99. 1// This function will print <argv> to stderr and then return <argv>[0].
100. 1
101. 1 __consoleError("\n\ndebugInline");
102. 1 __consoleError(...argv);
103. 1 __consoleError("\n");
104. 1 return argv[0];
105. 1 }
106. 1 debug(); // Coverage-hack.
107. 1 __consoleError = console.error; //jslint-ignore-line
108. 1 return debug;
109. 1}());
110. 1let moduleChildProcess;
111. 1let moduleChildProcessSpawn;
112. 1let moduleCrypto;
113. 1let moduleFs;
114. 1let moduleFsInitResolveList;
115. 1let modulePath;
116. 1let moduleUrl;
117. 1let {
118. 1 npm_config_mode_debug,
119. 1 npm_config_mode_setup,
120. 1 npm_config_mode_test
121. 1} = typeof process === "object" && process?.env;
122. 1let sqlMessageDict = {}; // dict of web-worker-callbacks
123. 1let sqlMessageId = 0;
124. 1let sqlWorker;
125. 1let version = "v2025.6.28";
126. 1
127. 88async function assertErrorThrownAsync(asyncFunc, regexp) {
128. 88
129. 88// This function will assert calling <asyncFunc> throws an error.
130. 88
131. 88 let err;
132. 88 try {
133. 1 await asyncFunc();
134. 87 } catch (errCaught) {
135. 87 err = errCaught;
136. 87 }
137. 88 assertOrThrow(err, "No error thrown.");
138. 88 assertOrThrow(
139. 85 !regexp || new RegExp(regexp).test(err.message),
140. 88 err
141. 88 );
142. 88}
143. 1
144. 14300function assertInt64(val) {
145. 14300 // This function will assert <val> is within range of c99-signed-long-long.
146. 14300 val = BigInt(val);
147. 14300 if (!(
148. 14293 -9_223_372_036_854_775_808n <= val && val <= 9_223_372_036_854_775_807n
149. 14 )) {
150. 14 throw new Error(
151. 14 `integer ${val} outside signed-64-bit inclusive-range`
152. 14 + " -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807"
153. 14 );
154. 14 }
155. 14300}
156. 1
157. 4929function assertJsonEqual(aa, bb, message) {
158. 4929
159. 4929// This function will assert JSON.stringify(<aa>) === JSON.stringify(<bb>).
160. 4929
161. 4929 aa = JSON.stringify(objectDeepCopyWithKeysSorted(aa), undefined, 1);
162. 4929 bb = JSON.stringify(objectDeepCopyWithKeysSorted(bb), undefined, 1);
163. 3 if (aa !== bb) {
164. 3 throw new Error(
165. 3 "\n" + aa + "\n!==\n" + bb
166. 3 + (
167. 3 typeof message === "string"
168. 3 ? " - " + message
169. 3 : message
170. 3 ? " - " + JSON.stringify(message)
171. 3 : ""
172. 3 )
173. 3 );
174. 3 }
175. 4929}
176. 1
177. 4function assertNumericalEqual(aa, bb, message) {
178. 4
179. 4// This function will assert aa - bb <= Number.EPSILON.
180. 4
181. 4 assertOrThrow(aa, "value cannot be 0 or falsy");
182. 2 if (!(Math.abs((aa - bb) / Math.max(aa, bb)) <= 256 * Number.EPSILON)) {
183. 2 throw new Error(
184. 2 JSON.stringify(aa) + " != " + JSON.stringify(bb) + (
185. 2 message
186. 2 ? " - " + message
187. 2 : ""
188. 2 )
189. 2 );
190. 2 }
191. 4}
192. 1
193. 48101function assertOrThrow(condition, message) {
194. 48101
195. 48101// This function will throw <message> if <condition> is falsy.
196. 48101
197. 72 if (!condition) {
198. 72 throw (
199. 72 (!message || typeof message === "string")
200. 72 ? new Error(String(message).slice(0, 2048))
201. 72 : message
202. 72 );
203. 72 }
204. 48101}
205. 1
206. 15async function childProcessSpawn2(command, args, option) {
207. 15
208. 15// This function will run child_process.spawn as a promise.
209. 15
210. 15 return await new Promise(function (resolve, reject) {
211. 15 let bufList = [[], [], []];
212. 15 let child;
213. 15 let {
214. 15 modeCapture,
215. 15 modeDebug,
216. 15 stdio
217. 15 } = option;
218. 1 if (modeDebug) {
219. 1 consoleError(
220. 1 `childProcessSpawn2 - ${command} ${JSON.stringify(args)}`
221. 1 );
222. 1 }
223. 15 child = moduleChildProcessSpawn(
224. 15 command,
225. 15 args,
226. 15 Object.assign({}, option, {
227. 15 stdio: [
228. 15 "ignore",
229. 15 (
230. 15 modeCapture
231. 1 ? "pipe"
232. 14 : stdio[1]
233. 15 ),
234. 15 (
235. 15 modeCapture
236. 1 ? "pipe"
237. 14 : stdio[2]
238. 15 )
239. 15 ]
240. 15 })
241. 15 );
242. 1 if (modeCapture) {
243. 1 [
244. 1 child.stdin, child.stdout, child.stderr
245. 3 ].forEach(function (pipe, ii) {
246. 1 if (ii === 0) {
247. 1 return;
248. 2 }
249. 2 pipe.on("data", function (chunk) {
250. 2 bufList[ii].push(chunk);
251. 2 if (stdio[ii] !== "ignore") {
252. 2 switch (ii) {
253. 2 case 1:
254. 2 process.stdout.write(chunk);
255. 2 break;
256. 2 case 2:
257. 2 process.stderr.write(chunk);
258. 2 break;
259. 2 }
260. 2 }
261. 2 });
262. 2 });
263. 1 }
264. 15 child.on("exit", function (exitCode) {
265. 15 let resolve0 = resolve;
266. 15 let stderr;
267. 15 let stdout;
268. 15 // coverage-hack
269. 15 if (exitCode || npm_config_mode_test) {
270. 15 resolve = reject;
271. 15 }
272. 15 // coverage-hack
273. 15 if (npm_config_mode_test) {
274. 15 resolve = resolve0;
275. 15 }
276. 30 [stdout, stderr] = bufList.slice(1).map(function (buf) {
277. 30 return (
278. 30 typeof modeCapture === "string"
279. 2 ? Buffer.concat(buf).toString(modeCapture)
280. 28 : Buffer.concat(buf)
281. 30 );
282. 30 });
283. 15 resolve({exitCode, stderr, stdout});
284. 15 });
285. 15 });
286. 15
287. 15}
288. 1
289. 7async function ciBuildExt({
290. 7 modeSkip,
291. 7 process
292. 7}) {
293. 7
294. 7// This function will build sqlmath from c.
295. 7
296. 7 let option;
297. 7 option = {
298. 7 binNodegyp: modulePath.resolve(
299. 7 modulePath.dirname(process.execPath || ""),
300. 7 "node_modules/npm/node_modules/node-gyp/bin/node-gyp.js"
301. 7 ).replace("/bin/node_modules/", "/lib/node_modules/"),
302. 7 isWin32: process.platform === "win32",
303. 7 modeDebug: npm_config_mode_debug,
304. 7 modeSkip,
305. 7 process
306. 7 };
307. 7 await ciBuildExt2NodejsBuild(option);
308. 7}
309. 1
310. 7async function ciBuildExt1NodejsConfigure({
311. 7 binNodegyp,
312. 7 modeDebug
313. 7}) {
314. 7
315. 7// This function will setup posix/win32 env for building c-extension.
316. 7
317. 7 let cflagWallList = [];
318. 7 let cflagWnoList = [];
319. 7 String(
320. 7 await fsReadFileUnlessTest(".ci.sh", "utf8", (`
321. 7SQLMATH_CFLAG_WALL_LIST=" \\
322. 7"
323. 7SQLMATH_CFLAG_WNO_LIST=" \\
324. 7"
325. 7 `))
326. 7 ).replace((
327. 7 /(SQLMATH_CFLAG_WALL_LIST|SQLMATH_CFLAG_WNO_LIST)=" \\([\S\s]*?)"/g
328. 14 ), function (ignore, cflagType, cflagList) {
329. 14 cflagList = cflagList.split(/[\s\\]/).filter(noop);
330. 14 switch (cflagType) {
331. 7 case "SQLMATH_CFLAG_WALL_LIST":
332. 7 cflagWallList = cflagList;
333. 7 break;
334. 7 case "SQLMATH_CFLAG_WNO_LIST":
335. 7 cflagWnoList = cflagList;
336. 7 break;
337. 14 }
338. 14 return "";
339. 14 });
340. 7 consoleError(`ciBuildExt1Nodejs - configure binding.gyp`);
341. 7 await fsWriteFileUnlessTest("binding.gyp", JSON.stringify({
342. 7 "target_defaults": {
343. 7 "cflags": cflagWnoList,
344. 7// https://github.com/nodejs/node-gyp/blob/v9.3.1/gyp/pylib/gyp/MSVSSettings.py
345. 7 "msvs_settings": {
346. 7 "VCCLCompilerTool": {
347. 7 "WarnAsError": 1,
348. 7 "WarningLevel": 2
349. 7 }
350. 7 },
351. 7 "xcode_settings": {
352. 7 "OTHER_CFLAGS": cflagWnoList
353. 7 }
354. 7 },
355. 7 "targets": [
356. 7 {
357. 7 "defines": [
358. 7 "SRC_SQLITE_BASE_C2",
359. 7 "SRC_ZLIB_C2"
360. 7 ],
361. 7 "sources": [
362. 7 "sqlmath_external_sqlite.c",
363. 7 "sqlmath_external_zlib.c"
364. 7 ],
365. 7 "target_name": "SRC_SQLITE_BASE",
366. 7 "type": "static_library"
367. 7 },
368. 7 {
369. 7 "cflags": cflagWallList,
370. 7 "defines": [
371. 7 "SRC_SQLMATH_BASE_C2",
372. 7 "SRC_SQLMATH_CUSTOM_C2"
373. 7 ],
374. 7 "msvs_settings": {
375. 7 "VCCLCompilerTool": {
376. 7 "WarnAsError": 1,
377. 7 "WarningLevel": 4
378. 7 }
379. 7 },
380. 7 "sources": [
381. 7 "sqlmath_base.c",
382. 7 "sqlmath_custom.c"
383. 7 ],
384. 7 "target_name": "SRC_SQLMATH_CUSTOM",
385. 7 "type": "static_library",
386. 7 "xcode_settings": {
387. 7 "OTHER_CFLAGS": cflagWallList
388. 7 }
389. 7 },
390. 7 {
391. 7 "cflags": cflagWallList,
392. 7 "defines": [
393. 7 "SRC_SQLMATH_NODEJS_C2"
394. 7 ],
395. 7 "dependencies": [
396. 7 "SRC_SQLITE_BASE",
397. 7 "SRC_SQLMATH_CUSTOM"
398. 7 ],
399. 7 "msvs_settings": {
400. 7 "VCCLCompilerTool": {
401. 7 "WarnAsError": 1,
402. 7 "WarningLevel": 4
403. 7 }
404. 7 },
405. 7 "sources": [
406. 7 "sqlmath_base.c"
407. 7 ],
408. 7 "target_name": "binding",
409. 7 "xcode_settings": {
410. 7 "OTHER_CFLAGS": cflagWallList
411. 7 }
412. 7 },
413. 7 {
414. 7 "defines": [
415. 7 "SRC_SQLITE_SHELL_C2"
416. 7 ],
417. 7 "dependencies": [
418. 7 "SRC_SQLITE_BASE",
419. 7 "SRC_SQLMATH_CUSTOM"
420. 7 ],
421. 7 "sources": [
422. 7 "sqlmath_external_sqlite.c"
423. 7 ],
424. 7 "target_name": "shell",
425. 7 "type": "executable"
426. 7 }
427. 7 ]
428. 7 }, undefined, 4) + "\n");
429. 7 await childProcessSpawn2(
430. 7 "sh",
431. 7 [
432. 7 "-c",
433. 7 (`
434. 7(set -e
435. 7 # node "${binNodegyp}" clean
436. 7 node "${binNodegyp}" configure
437. 7)
438. 7 `)
439. 7 ],
440. 7 {modeDebug, stdio: ["ignore", 1, 2]}
441. 7 );
442. 7}
443. 1
444. 7async function ciBuildExt2NodejsBuild({
445. 7 binNodegyp,
446. 7 modeDebug
447. 7}) {
448. 7
449. 7// This function will archive <fileObj> into <fileLib>
450. 7
451. 7 if (!noop(
452. 7 await fsExistsUnlessTest(cModulePath)
453. 7 )) {
454. 7 await ciBuildExt1NodejsConfigure({
455. 7 binNodegyp,
456. 7 modeDebug
457. 7 });
458. 7 }
459. 7 consoleError(
460. 7 `ciBuildExt2Nodejs - linking lib ${modulePath.resolve(cModulePath)}`
461. 7 );
462. 7 await childProcessSpawn2(
463. 7 "sh",
464. 7 [
465. 7 "-c",
466. 7 (`
467. 7(set -e
468. 7 # rebuild binding
469. 7 rm -rf build/Release/obj/SRC_SQLMATH_CUSTOM/
470. 7 node "${binNodegyp}" build --release
471. 7 mv build/Release/binding.node "${cModulePath}"
472. 7 if [ "${process.platform}" = "win32" ]
473. 7 then
474. 7 mv build/Release/shell \
475. 7 "_sqlmath.shell_${process.platform}_${process.arch}.exe"
476. 7 else
477. 7 mv build/Release/shell \
478. 7 "_sqlmath.shell_${process.platform}_${process.arch}"
479. 7 fi
480. 7)
481. 7 `)
482. 7 ],
483. 7 {modeDebug, stdio: ["ignore", 1, 2]}
484. 7 );
485. 7}
486. 1
487. 3980async function dbCallAsync(baton, argList, mode) {
488. 3980
489. 3980// This function will call c-function dbXxx() with given <funcname>
490. 3980// and return [<baton>, ...argList].
491. 3980
492. 3980 let db;
493. 3980 let errStack;
494. 3980 let funcname;
495. 3980 let id;
496. 3980 let result;
497. 3980 let timeElapsed;
498. 3980 // If argList contains <db>, then mark it as busy.
499. 1931 if (mode === "modeDb") {
500. 1931 // init db
501. 1931 db = argList[0];
502. 1931 assertOrThrow(
503. 1931 db.busy >= 0,
504. 1931 `dbCallAsync - invalid db.busy = ${db.busy}`
505. 1931 );
506. 1931 db.ii = (db.ii + 1) % db.connPool.length;
507. 1931 db.ptr = db.connPool[db.ii][0];
508. 1931 // increment db.busy
509. 1931 db.busy += 1;
510. 1931 try {
511. 1931 return await dbCallAsync(baton, [db.ptr, ...argList.slice(1)]);
512. 1931 } finally {
513. 1931 // decrement db.busy
514. 1931 db.busy -= 1;
515. 1931 assertOrThrow(
516. 1931 db.busy >= 0,
517. 1931 `dbCallAsync - invalid db.busy = ${db.busy}`
518. 1931 );
519. 1931 }
520. 2049 }
521. 2049 // copy argList to avoid side-effect
522. 2049 argList = [...argList];
523. 2049 assertOrThrow(
524. 2049 argList.length <= JSBATON_ARGC,
525. 2049 `dbCallAsync - argList.length must be less than than ${JSBATON_ARGC}`
526. 2049 );
527. 2049 // pad argList to length JSBATON_ARGC
528. 6382 while (argList.length < JSBATON_ARGC) {
529. 6382 argList.push(0n);
530. 6382 }
531. 2049 // serialize js-value to c-value
532. 16254 argList = argList.map(function (val, argi) {
533. 16253 if (val === null || val === undefined) {
534. 2049 val = 0;
535. 2049 }
536. 16254 switch (typeof val) {
537. 8240 case "bigint":
538. 10159 case "boolean":
539. 14268 case "number":
540. 14268 // check for min/max safe-integer
541. 14268 assertOrThrow(
542. 14268 (
543. 14268 (JS_MIN_SAFE_INTEGER <= val && val <= JS_MAX_SAFE_INTEGER)
544. 14268 || typeof val === "bigint"
545. 14268 ),
546. 14268 (
547. 14268 "dbCallAsync - "
548. 14268 + "non-bigint-integer must be within inclusive-range"
549. 14268 + ` ${JS_MIN_SAFE_INTEGER} to ${JS_MAX_SAFE_INTEGER}`
550. 14268 )
551. 14268 );
552. 14268 val = BigInt(val);
553. 14268 assertInt64(val);
554. 14268 baton.setBigInt64(JSBATON_OFFSET_ARGV + argi * 8, val, true);
555. 14268 return val;
556. 16254 // case "object":
557. 16254 // break;
558. 2049 case "string":
559. 2049 baton = jsbatonSetValue(baton, argi, (
560. 2049 val.endsWith("\u0000")
561. 2049 ? val
562. 2049 // append null-terminator to string
563. 2049 : val + "\u0000"
564. 2049 ));
565. 2049 return;
566. 2049 }
567. 2049 assertOrThrow(
568. 2049 !ArrayBuffer.isView(val) || val.byteOffset === 0,
569. 16254 (
570. 16254 "dbCallAsync - argList cannot contain arraybuffer-views"
571. 16254 + " with non-zero byteOffset"
572. 16254 )
573. 16254 );
574. 2049 if (isExternalBuffer(val)) {
575. 2049 return val;
576. 2049 }
577. 2049 throw new Error(`dbCallAsync - invalid arg-type "${typeof val}"`);
578. 2049 });
579. 2049 // assert byteOffset === 0
580. 18234 [baton, ...argList].forEach(function (arg) {
581. 2049 assertOrThrow(!ArrayBuffer.isView(arg) || arg.byteOffset === 0, arg);
582. 18234 });
583. 2049 // extract funcname
584. 2049 funcname = new TextDecoder().decode(
585. 2049 new DataView(baton.buffer, JSBATON_OFFSET_FUNCNAME, SIZEOF_FUNCNAME)
586. 2049 ).replace((/\u0000/g), "");
587. 2049 // preserve stack-trace
588. 2049 errStack = new Error().stack.replace((/.*$/m), "");
589. 2049 try {
590. 2049
591. 2049// Dispatch to nodejs-napi.
592. 2049
593. 2049 if (!IS_BROWSER) {
594. 2024 await cModule._jspromiseCreate(baton.buffer, argList, funcname);
595. 2024 // prepend baton to argList
596. 2024 return [baton, ...argList];
597. 2024 }
598. 2
599. 2// Dispatch to web-worker.
600. 2
601. 2 // increment sqlMessageId
602. 2 sqlMessageId += 1;
603. 2 id = sqlMessageId;
604. 2 // postMessage to web-worker
605. 2 sqlWorker.postMessage(
606. 2 {
607. 2 FILENAME_DBTMP,
608. 2 JSBATON_OFFSET_ALL,
609. 2 JSBATON_OFFSET_BUFV,
610. 2 argList,
611. 2 baton,
612. 2 funcname,
613. 2 id
614. 2 },
615. 2 // transfer arraybuffer without copying
616. 2 [baton.buffer, ...argList.filter(isExternalBuffer)]
617. 2 );
618. 2 // init timeElapsed
619. 2 timeElapsed = Date.now();
620. 2 // await result from web-worker
621. 2 result = await new Promise(function (resolve) {
622. 2 sqlMessageDict[id] = resolve;
623. 2 });
624. 2 // cleanup sqlMessageDict
625. 2 delete sqlMessageDict[id];
626. 2 // debug slow postMessage
627. 2 timeElapsed = Date.now() - timeElapsed;
628. 2 if (timeElapsed > 500 || funcname === "testTimeElapsed") {
629. 1 consoleError(
630. 1 "sqlMessagePost - "
631. 1 + JSON.stringify({funcname, timeElapsed})
632. 1 + errStack
633. 1 );
634. 2 }
635. 2 assertOrThrow(!result.errmsg, result.errmsg);
636. 2 // prepend baton to argList
637. 2 return [result.baton, ...result.argList];
638. 55 } catch (err) {
639. 55 err.stack += errStack;
640. 55 assertOrThrow(undefined, err);
641. 55 }
642. 3980}
643. 1
644. 3async function dbCloseAsync(db) {
645. 3
646. 3// This function will close sqlite-database-connection <db>.
647. 3
648. 3 // prevent segfault - do not close db if actions are pending
649. 3 assertOrThrow(
650. 3 db.busy === 0,
651. 3 `dbCloseAsync - cannot close db with ${db.busy} actions pending`
652. 3 );
653. 3 // cleanup connPool
654. 1 await Promise.all(db.connPool.map(async function (ptr) {
655. 1 let val = ptr[0];
656. 1 ptr[0] = 0n;
657. 1 await dbCallAsync(jsbatonCreate("_dbClose"), [val, db.filename]);
658. 1 }));
659. 1}
660. 1
661. 58function dbExecAndReturnLastBlob({
662. 58 bindList = [],
663. 58 db,
664. 58 sql
665. 58}) {
666. 58
667. 58// This function will exec <sql> in <db>,
668. 58// and return last-value retrieved from execution as raw blob/buffer.
669. 58
670. 58 return dbExecAsync({
671. 58 bindList,
672. 58 db,
673. 58 responseType: "lastblob",
674. 58 sql
675. 58 });
676. 58}
677. 1
678. 115async function dbExecAndReturnLastRow({
679. 115 bindList = [],
680. 115 db,
681. 115 sql
682. 115}) {
683. 115
684. 115// This function will exec <sql> in <db>,
685. 115// and return last-row or empty-object.
686. 115
687. 101 let result = await dbExecAsync({bindList, db, sql});
688. 101 result = result[result.length - 1] || [];
689. 1 result = result[result.length - 1] || {};
690. 115 return result;
691. 115}
692. 1
693. 65async function dbExecAndReturnLastTable({
694. 65 bindList = [],
695. 65 db,
696. 65 sql
697. 65}) {
698. 65
699. 65// This function will exec <sql> in <db>,
700. 65// and return last-table or empty-list.
701. 65
702. 65 let result = await dbExecAsync({bindList, db, sql});
703. 1 result = result[result.length - 1] || [];
704. 65 return result;
705. 65}
706. 1
707. 1184function dbExecAndReturnLastValue({
708. 1184 bindList = [],
709. 1184 db,
710. 1184 sql
711. 1184}) {
712. 1184
713. 1184// This function will exec <sql> in <db>,
714. 1184// and return last-json-value.
715. 1184
716. 1184 return dbExecAsync({
717. 1184 bindList,
718. 1184 db,
719. 1184 responseType: "lastvalue",
720. 1184 sql
721. 1184 });
722. 1184}
723. 1
724. 1929async function dbExecAsync({
725. 1929 bindList = [],
726. 1929 db,
727. 1929 modeNoop,
728. 1929 responseType,
729. 1929 sql
730. 1929}) {
731. 1929
732. 1929// This function will exec <sql> in <db> and return <result>.
733. 1929
734. 1929 let baton = jsbatonCreate("_dbExec");
735. 1929 let bindByKey = !Array.isArray(bindList);
736. 1929 let bufi = [0];
737. 1929 let referenceList = [];
738. 1929 let result;
739. 1 if (modeNoop) {
740. 1 return;
741. 1928 }
742. 1928 if (bindByKey) {
743. 1347 Object.entries(bindList).forEach(function ([key, val]) {
744. 1347 baton = jsbatonSetValue(baton, undefined, `:${key}\u0000`);
745. 1347 baton = jsbatonSetValue(
746. 1347 baton,
747. 1347 undefined,
748. 1347 val,
749. 1347 bufi,
750. 1347 referenceList
751. 1347 );
752. 1347 });
753. 1235 } else {
754. 693 bindList.forEach(function (val) {
755. 693 baton = jsbatonSetValue(
756. 693 baton,
757. 693 undefined,
758. 693 val,
759. 693 bufi,
760. 693 referenceList
761. 693 );
762. 693 });
763. 1916 }
764. 1916 [baton, ...result] = await dbCallAsync(
765. 1916 baton,
766. 1916 [
767. 1916 // 0. db
768. 1916 db,
769. 1916 // 1. sql
770. 1916 String(sql) + "\n;\nPRAGMA noop",
771. 1916 // 2. bindList.length
772. 1916 (
773. 1916 bindByKey
774. 1916 ? Object.keys(bindList).length
775. 681 : bindList.length
776. 1929 ),
777. 1929 // 3. bindByKey
778. 1929 bindByKey,
779. 1929 // 4. responseType
780. 1929 (
781. 1929 responseType === "lastblob"
782. 56 ? SQLITE_RESPONSETYPE_LASTBLOB
783. 1860 : responseType === "lastvalue"
784. 1860 ? SQLITE_RESPONSETYPE_LASTVALUE
785. 1860 : 0
786. 1929 )
787. 1929 ],
788. 1929 "modeDb"
789. 1861 );
790. 1861 result = result[0];
791. 1861 if (!IS_BROWSER) {
792. 1861 result = cModule._jsbatonStealCbuffer(
793. 1861 baton.buffer,
794. 1861 0,
795. 1861 Number(
796. 1861 responseType !== "arraybuffer" && responseType !== "lastblob"
797. 1861 )
798. 1861 );
799. 1861 }
800. 1861 switch (responseType) {
801. 1861 case "arraybuffer":
802. 110 case "lastblob":
803. 110 return result;
804. 1236 case "lastvalue":
805. 1403 case "list":
806. 1403 return jsonParseArraybuffer(result);
807. 348 default:
808. 374 return jsonParseArraybuffer(result).map(function (table) {
809. 374 let colList = table.shift();
810. 13942 return table.map(function (row) {
811. 13942 let dict = {};
812. 40235 colList.forEach(function (key, ii) {
813. 40235 dict[key] = row[ii];
814. 40235 });
815. 13942 return dict;
816. 13942 });
817. 374 });
818. 1929 }
819. 1929}
820. 1
821. 18async function dbFileLoadAsync({
822. 18 db,
823. 18 dbData,
824. 18 filename,
825. 18 modeNoop,
826. 18 modeSave = 0
827. 18}) {
828. 18
829. 18// This function will load <filename> to <db>.
830. 18
831. 18 let filename2;
832. 15 async function _dbFileLoad() {
833. 15 dbData = await dbCallAsync(
834. 15 jsbatonCreate("_dbFileLoad"),
835. 15 [
836. 15 // 0. sqlite3 * pInMemory
837. 15 db,
838. 15 // 1. char *zFilename
839. 15 filename,
840. 15 // 2. const int isSave
841. 15 modeSave,
842. 15 // 3. undefined
843. 15 undefined,
844. 15 // 4. dbData - same position as dbOpenAsync
845. 15 dbData
846. 15 ],
847. 15 "modeDb"
848. 15 );
849. 15 }
850. 1 if (modeNoop) {
851. 1 return;
852. 17 }
853. 17 if (IS_BROWSER) {
854. 1 filename = FILENAME_DBTMP;
855. 17 }
856. 17 assertOrThrow(
857. 17 typeof filename === "string" && filename,
858. 18 `invalid filename ${filename}`
859. 18 );
860. 18 // Save to tmpfile and then atomically-rename to actual-filename.
861. 15 if (moduleFs && modeSave) {
862. 13 filename2 = filename;
863. 13 filename = modulePath.join(
864. 13 modulePath.dirname(filename),
865. 13 `.dbFileSaveAsync.${moduleCrypto.randomUUID()}`
866. 13 );
867. 13 try {
868. 13 await _dbFileLoad();
869. 13 await moduleFs.promises.rename(filename, filename2);
870. 13 } finally {
871. 13 await moduleFs.promises.unlink(filename).catch(noop);
872. 13 }
873. 13 } else {
874. 2 await _dbFileLoad();
875. 15 }
876. 15 return dbData[1 + 0];
877. 15}
878. 1
879. 14async function dbFileSaveAsync({
880. 14 db,
881. 14 dbData,
882. 14 filename,
883. 14 modeNoop
884. 14}) {
885. 14
886. 14// This function will save <db> to <filename>.
887. 14
888. 14 return await dbFileLoadAsync({
889. 14 db,
890. 14 dbData,
891. 14 filename,
892. 14 modeNoop,
893. 14 modeSave: 1
894. 14 });
895. 14}
896. 1
897. 56async function dbNoopAsync(...argList) {
898. 56
899. 56// This function will do nothing except return <argList>.
900. 56
901. 56 return await dbCallAsync(jsbatonCreate("_dbNoop"), argList);
902. 56}
903. 1
904. 32async function dbOpenAsync({
905. 32 afterFinalization,
906. 32 dbData,
907. 32 filename,
908. 32 flags,
909. 32 threadCount = 1
910. 32}) {
911. 32
912. 32// This function will open and return sqlite-database-connection <db>.
913. 32
914. 32// int sqlite3_open_v2(
915. 32// const char *filename, /* Database filename (UTF-8) */
916. 32// sqlite3 **ppDb, /* OUT: SQLite db handle */
917. 32// int flags, /* Flags */
918. 32// const char *zVfs /* Name of VFS module to use */
919. 32// );
920. 32 let connPool;
921. 32 let db = {busy: 0, filename, ii: 0};
922. 32 let fileLgbm;
923. 32 assertOrThrow(typeof filename === "string", `invalid filename ${filename}`);
924. 32 assertOrThrow(
925. 1 !dbData || isExternalBuffer(dbData),
926. 32 "dbData must be ArrayBuffer"
927. 32 );
928. 32 connPool = await Promise.all(Array.from(new Array(
929. 32 threadCount
930. 31 ), async function () {
931. 31 let [ptr] = await dbCallAsync(
932. 31 jsbatonCreate("_dbOpen"),
933. 31 [
934. 31 // 0. const char *filename, Database filename (UTF-8)
935. 31 filename,
936. 31 // 1. sqlite3 **ppDb, OUT: SQLite db handle
937. 31 undefined,
938. 31 // 2. int flags, Flags
939. 31 flags ?? (
940. 31 SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI
941. 31 ),
942. 31 // 3. const char *zVfs Name of VFS module to use
943. 31 undefined,
944. 31 // 4. wasm-only - arraybuffer of raw sqlite-database
945. 31 dbData
946. 31 ]
947. 31 );
948. 31 ptr = [ptr.getBigInt64(JSBATON_OFFSET_ARGV + 0, true)];
949. 31 dbFinalizationRegistry.register(db, {afterFinalization, ptr});
950. 31 return ptr;
951. 31 }));
952. 31 db.connPool = connPool;
953. 31 // init lightgbm
954. 31 if (!IS_BROWSER) {
955. 31 fileLgbm = process.platform;
956. 31 fileLgbm = fileLgbm.replace("darwin", "lib_lightgbm.dylib");
957. 31 fileLgbm = fileLgbm.replace("win32", "lib_lightgbm.dll");
958. 31 fileLgbm = fileLgbm.replace(process.platform, "lib_lightgbm.so");
959. 31 fileLgbm = `${import.meta.dirname}/sqlmath/${fileLgbm}`;
960. 31 await moduleFs.promises.access(fileLgbm).then(async function () {
961. 31 await dbExecAsync({
962. 31 db,
963. 31 sql: `SELECT lgbm_dlopen('${fileLgbm}');`
964. 31 });
965. 31 }).catch(noop);
966. 31 }
967. 31 return db;
968. 31}
969. 1
970. 47async function dbTableImportAsync({
971. 47 db,
972. 47 filename,
973. 47 headerMissing,
974. 47 mode,
975. 47 tableName,
976. 47 textData
977. 47}) {
978. 47// this function will create table from imported csv/json <textData>
979. 47 let colList;
980. 47 let rowList;
981. 47 let rowidList;
982. 47 let tmp;
983. 42 if (filename) {
984. 42 textData = await moduleFs.promises.readFile(filename, "utf8");
985. 42 }
986. 47 switch (mode) {
987. 2 case "csv":
988. 2 rowList = jsonRowListFromCsv({
989. 2 csv: textData
990. 2 });
991. 2 break;
992. 43 case "tsv":
993. 43 rowList = [];
994. 99001 textData.trimEnd().replace((/.+/g), function (line) {
995. 99001 rowList.push(line.split("\t"));
996. 99001 });
997. 43 break;
998. 47 // case "json":
999. 2 default:
1000. 2 rowList = JSON.parse(textData);
1001. 47 }
1002. 1 if (!(typeof rowList === "object" && rowList)) {
1003. 1 rowList = [];
1004. 1 }
1005. 47 // normalize rowList to list
1006. 1 if (!Array.isArray(rowList)) {
1007. 1 rowidList = [];
1008. 2 rowList = Object.entries(rowList).map(function ([
1009. 2 key, val
1010. 2 ]) {
1011. 2 rowidList.push(key);
1012. 2 return val;
1013. 2 });
1014. 1 }
1015. 47 // headerMissing
1016. 42 if (headerMissing && (rowList.length > 0 && Array.isArray(rowList[0]))) {
1017. 714 rowList.unshift(Array.from(rowList[0]).map(function (ignore, ii) {
1018. 714 return String(ii + 1);
1019. 714 }));
1020. 42 }
1021. 47 // normalize rowList[ii] to list
1022. 1 if (rowList.length === 0) {
1023. 1 rowList.push([
1024. 1 "undefined"
1025. 1 ]);
1026. 1 }
1027. 1 if (!Array.isArray(rowList[0])) {
1028. 1 colList = Array.from(
1029. 1 new Set(
1030. 2 rowList.map(function (obj) {
1031. 2 return Object.keys(obj);
1032. 2 }).flat()
1033. 1 )
1034. 1 );
1035. 2 rowList = rowList.map(function (obj) {
1036. 4 return colList.map(function (key) {
1037. 4 return obj[key];
1038. 4 });
1039. 2 });
1040. 1 rowList.unshift(colList);
1041. 1 }
1042. 47 // init colList
1043. 47 colList = rowList.shift();
1044. 47 // preserve rowid
1045. 1 if (rowidList) {
1046. 1 colList.unshift("rowid");
1047. 2 rowList.forEach(function (row, ii) {
1048. 2 row.unshift(rowidList[ii]);
1049. 2 });
1050. 1 }
1051. 47 // normalize colList
1052. 47 tmp = new Set();
1053. 723 colList = colList.map(function (colName) {
1054. 723 let colName2;
1055. 723 let duplicate = 0;
1056. 723 colName = colName.trim();
1057. 723 colName = colName.replace((/\W/g), "_");
1058. 723 colName = colName.replace((/^[^A-Z_a-z]|^$/gm), "_$&");
1059. 724 while (true) {
1060. 724 duplicate += 1;
1061. 724 colName2 = (
1062. 724 duplicate === 1
1063. 724 ? colName
1064. 724 : colName + "_" + duplicate
1065. 724 );
1066. 724 if (!tmp.has(colName2)) {
1067. 724 tmp.add(colName2);
1068. 724 return colName2;
1069. 724 }
1070. 724 }
1071. 723 });
1072. 47 // create dbtable from rowList
1073. 47 await dbExecAsync({
1074. 47 bindList: {
1075. 47 rowList: JSON.stringify(rowList)
1076. 47 },
1077. 47 db,
1078. 47 sql: (
1079. 47 rowList.length === 0
1080. 3 ? `CREATE TABLE ${tableName} (${colList.join(",")});`
1081. 44 : (
1082. 44 `CREATE TABLE ${tableName} AS SELECT `
1083. 719 + colList.map(function (colName, ii) {
1084. 719 return "value->>" + ii + " AS " + colName;
1085. 719 }).join(",")
1086. 44 + " FROM JSON_EACH($rowList);"
1087. 44 )
1088. 47 )
1089. 47 });
1090. 47}
1091. 1
1092. 2async function fsCopyFileUnlessTest(file1, file2, mode) {
1093. 2
1094. 2// This function will copy <file1> to <file2> unless <npm_config_mode_test> = 1.
1095. 2
1096. 1 if (npm_config_mode_test && mode !== "force") {
1097. 1 return;
1098. 1 }
1099. 1 await moduleFs.promises.copyFile(file1, file2, mode | 0);
1100. 1}
1101. 1
1102. 10async function fsExistsUnlessTest(file, mode) {
1103. 10
1104. 10// This function will test if <file> exists unless <npm_config_mode_test> = 1.
1105. 10
1106. 8 if (npm_config_mode_test && mode !== "force") {
1107. 8 return false;
1108. 8 }
1109. 2 try {
1110. 2 await moduleFs.promises.access(file);
1111. 1 return true;
1112. 1 } catch (ignore) {
1113. 1 return false;
1114. 1 }
1115. 10}
1116. 1
1117. 22async function fsReadFileUnlessTest(file, mode, defaultData) {
1118. 22
1119. 22// This function will read <data> from <file> unless <npm_config_mode_test> = 1.
1120. 22
1121. 8 if (npm_config_mode_test && mode !== "force") {
1122. 8 return defaultData;
1123. 14 }
1124. 14 return await moduleFs.promises.readFile(
1125. 14 file,
1126. 14 mode && mode.replace("force", "utf8")
1127. 22 );
1128. 22}
1129. 1
1130. 10async function fsWriteFileUnlessTest(file, data, mode) {
1131. 10
1132. 10// This function will write <data> to <file> unless <npm_config_mode_test> = 1.
1133. 10
1134. 9 if (npm_config_mode_test && mode !== "force") {
1135. 9 return;
1136. 9 }
1137. 1 await moduleFs.promises.writeFile(file, data);
1138. 1}
1139. 1
1140. 31function isExternalBuffer(buf) {
1141. 31
1142. 31// This function will check if <buf> is ArrayBuffer.
1143. 31
1144. 17 return buf && buf.constructor === ArrayBuffer;
1145. 31}
1146. 1
1147. 2062function jsbatonCreate(funcname) {
1148. 2062
1149. 2062// This function will create buffer <baton>.
1150. 2062
1151. 2062 let baton = new DataView(new ArrayBuffer(JSBATON_OFFSET_ALL));
1152. 2062 // init nallc, nused
1153. 2062 baton.setInt32(4, JSBATON_OFFSET_ALL, true);
1154. 2062 // copy funcname into baton
1155. 2062 new Uint8Array(
1156. 2062 baton.buffer,
1157. 2062 baton.byteOffset + JSBATON_OFFSET_FUNCNAME,
1158. 2062 SIZEOF_FUNCNAME - 1
1159. 2062 ).set(new TextEncoder().encode(funcname));
1160. 2062 return baton;
1161. 2062}
1162. 1
1163. 24function jsbatonGetInt64(baton, argi) {
1164. 24
1165. 24// This function will return int64-value from <baton> at <argi>.
1166. 24
1167. 24 return baton.getBigInt64(JSBATON_OFFSET_ARGV + argi * 8, true);
1168. 24}
1169. 1
1170. 9function jsbatonGetString(baton, argi) {
1171. 9
1172. 9// This function will return string-value from <baton> at <argi>.
1173. 9
1174. 9 let offset = baton.getInt32(JSBATON_OFFSET_ARGV + argi * 8, true);
1175. 9 return new TextDecoder().decode(new Uint8Array(
1176. 9 baton.buffer,
1177. 9 baton.byteOffset + offset + 1 + 4,
1178. 9 // remove null-terminator from string
1179. 9 baton.getInt32(offset + 1, true) - 1
1180. 9 ));
1181. 9}
1182. 1
1183. 5182function jsbatonSetValue(baton, argi, val, bufi, referenceList) {
1184. 5182
1185. 5182// This function will set <val> to buffer <baton>.
1186. 5182
1187. 5182 let nn;
1188. 5182 let nused;
1189. 5182 let tmp;
1190. 5182 let vsize;
1191. 5182 let vtype;
1192. 5182/*
1193. 5182#define SQLITE_DATATYPE_BLOB 0x04
1194. 5182#define SQLITE_DATATYPE_EXTERNALBUFFER 0x71
1195. 5182#define SQLITE_DATATYPE_FLOAT 0x02
1196. 5182#define SQLITE_DATATYPE_INTEGER 0x01
1197. 5182#define SQLITE_DATATYPE_INTEGER_0 0x00
1198. 5182#define SQLITE_DATATYPE_INTEGER_1 0x21
1199. 5182#define SQLITE_DATATYPE_NULL 0x05
1200. 5182#define SQLITE_DATATYPE_TEXT 0x03
1201. 5182#define SQLITE_DATATYPE_TEXT_0 0x13
1202. 5182 // 1. 0.bigint
1203. 5182 // 2. 0.boolean
1204. 5182 // 3. 0.function
1205. 5182 // 4. 0.number
1206. 5182 // 5. 0.object
1207. 5182 // 6. 0.string
1208. 5182 // 7. 0.symbol
1209. 5182 // 8. 0.undefined
1210. 5182 // 9. 1.bigint
1211. 5182 // 10. 1.boolean
1212. 5182 // 11. 1.function
1213. 5182 // 12. 1.number
1214. 5182 // 13. 1.object
1215. 5182 // 14. 1.string
1216. 5182 // 15. 1.symbol
1217. 5182 // 16. 1.undefined
1218. 5182 // 17. 1.buffer
1219. 5182 // 18. 1.externalbuffer
1220. 5182*/
1221. 5182 // 10. 1.boolean
1222. 5158 if (val === 1 || val === 1n) {
1223. 30 val = true;
1224. 30 }
1225. 5182 switch (
1226. 5182 val
1227. 4801 ? "1." + typeof(val)
1228. 381 : "0." + typeof(val)
1229. 5182 ) {
1230. 5182 // 1. 0.bigint
1231. 24 case "0.bigint":
1232. 5182 // 2. 0.boolean
1233. 30 case "0.boolean":
1234. 5182 // 4. 0.number
1235. 250 case "0.number":
1236. 250 if (Number.isNaN(val)) {
1237. 250 vtype = SQLITE_DATATYPE_NULL;
1238. 250 vsize = 0;
1239. 250 break;
1240. 250 }
1241. 250 vtype = SQLITE_DATATYPE_INTEGER_0;
1242. 250 vsize = 0;
1243. 250 break;
1244. 5182 // 3. 0.function
1245. 5182 // case "0.function":
1246. 5182 // 5. 0.object
1247. 98 case "0.object":
1248. 5182 // 7. 0.symbol
1249. 98 case "0.symbol":
1250. 5182 // 8. 0.undefined
1251. 105 case "0.undefined":
1252. 5182 // 11. 1.function
1253. 119 case "1.function":
1254. 5182 // 15. 1.symbol
1255. 125 case "1.symbol":
1256. 125 // 16. 1.undefined
1257. 125 // case "1.undefined":
1258. 125 vtype = SQLITE_DATATYPE_NULL;
1259. 125 vsize = 0;
1260. 125 break;
1261. 5182 // 6. 0.string
1262. 26 case "0.string":
1263. 26 vtype = SQLITE_DATATYPE_TEXT_0;
1264. 26 vsize = 0;
1265. 26 break;
1266. 5182 // 9. 1.bigint
1267. 42 case "1.bigint":
1268. 42 vtype = SQLITE_DATATYPE_INTEGER;
1269. 42 vsize = 8;
1270. 42 break;
1271. 5182 // 10. 1.boolean
1272. 36 case "1.boolean":
1273. 36 vtype = SQLITE_DATATYPE_INTEGER_1;
1274. 36 vsize = 0;
1275. 36 break;
1276. 5182 // 12. 1.number
1277. 561 case "1.number":
1278. 561 vtype = SQLITE_DATATYPE_FLOAT;
1279. 561 vsize = 8;
1280. 561 break;
1281. 5182 // 14. 1.string
1282. 4060 case "1.string":
1283. 4060 val = new TextEncoder().encode(val);
1284. 4060 vtype = SQLITE_DATATYPE_TEXT;
1285. 4060 vsize = 4 + val.byteLength;
1286. 4060 break;
1287. 5182 // 13. 1.object
1288. 82 default:
1289. 82 // 18. 1.externalbuffer
1290. 82 if (val.constructor === ArrayBuffer) {
1291. 82 assertOrThrow(
1292. 82 !IS_BROWSER,
1293. 82 "external ArrayBuffer cannot be passed directly to wasm"
1294. 82 );
1295. 82 vtype = SQLITE_DATATYPE_EXTERNALBUFFER;
1296. 82 vsize = 4;
1297. 82 break;
1298. 82 }
1299. 82 // 17. 1.buffer
1300. 82 if (ArrayBuffer.isView(val)) {
1301. 82 if (val.byteLength === 0) {
1302. 82 vtype = SQLITE_DATATYPE_NULL;
1303. 82 vsize = 0;
1304. 82 break;
1305. 82 }
1306. 82 vtype = SQLITE_DATATYPE_BLOB;
1307. 82 vsize = 4 + val.byteLength;
1308. 82 break;
1309. 82 }
1310. 82 // 13. 1.object
1311. 82 val = new TextEncoder().encode(
1312. 82 typeof val.toJSON === "function"
1313. 82 ? val.toJSON()
1314. 82 : JSON.stringify(val)
1315. 82 );
1316. 82 vtype = SQLITE_DATATYPE_TEXT;
1317. 82 vsize = 4 + val.byteLength;
1318. 5182 }
1319. 5182 nused = baton.getInt32(4, true);
1320. 5182 nn = nused + 1 + vsize;
1321. 5182 assertOrThrow(
1322. 5182 nn <= 0xffff_ffff,
1323. 5182 "jsbaton cannot exceed 0x7fff_ffff / 2,147,483,647 bytes"
1324. 5182 );
1325. 5182 // exponentially grow baton as needed
1326. 2164 if (baton.byteLength < nn) {
1327. 2164 tmp = baton;
1328. 2164 baton = new DataView(new ArrayBuffer(
1329. 2164 Math.min(2 ** Math.ceil(Math.log2(nn)), 0x7fff_ffff)
1330. 2164 ));
1331. 2164 // update nallc
1332. 2164 baton.setInt32(0, baton.byteLength, true);
1333. 2164 // copy old-baton into new-baton
1334. 2164 new Uint8Array(baton.buffer, baton.byteOffset, nused).set(
1335. 2164 new Uint8Array(tmp.buffer, tmp.byteOffset, nused)
1336. 2164 );
1337. 2164 }
1338. 5182 // push vtype - 1-byte
1339. 5182 baton.setUint8(nused, vtype);
1340. 5182 // update nused
1341. 5182 baton.setInt32(4, nused + 1 + vsize, true);
1342. 5182 // handle blob-value
1343. 5182 switch (vtype) {
1344. 30 case SQLITE_DATATYPE_BLOB:
1345. 4118 case SQLITE_DATATYPE_TEXT:
1346. 4118 // set argv[ii] to blob/text location
1347. 4118 if (argi !== undefined) {
1348. 4118 baton.setInt32(JSBATON_OFFSET_ARGV + argi * 8, nused, true);
1349. 4118 }
1350. 4118 vsize -= 4;
1351. 4118 assertOrThrow(
1352. 4118 0 <= vsize && vsize <= SIZEOF_BLOB_MAX,
1353. 4118 (
1354. 4118 "sqlite-blob byte-length must be within inclusive-range"
1355. 4118 + ` 0 to ${SIZEOF_BLOB_MAX}`
1356. 4118 )
1357. 4118 );
1358. 4118 // push vsize - 4-byte
1359. 4118 baton.setInt32(nused + 1, vsize, true);
1360. 4118 // push SQLITE-BLOB/TEXT - vsize-byte
1361. 4118 new Uint8Array(
1362. 4118 baton.buffer,
1363. 4118 baton.byteOffset + nused + 1 + 4,
1364. 4118 vsize
1365. 4118 ).set(new Uint8Array(val.buffer, val.byteOffset, vsize));
1366. 4118 break;
1367. 12 case SQLITE_DATATYPE_EXTERNALBUFFER:
1368. 12 vsize = val.byteLength;
1369. 12 assertOrThrow(
1370. 12 0 <= vsize && vsize <= SIZEOF_BLOB_MAX,
1371. 12 (
1372. 12 "sqlite-blob byte-length must be within inclusive-range"
1373. 12 + ` 0 to ${SIZEOF_BLOB_MAX}`
1374. 12 )
1375. 12 );
1376. 12 assertOrThrow(
1377. 12 bufi[0] < JSBATON_ARGC,
1378. 12 `cannot pass more than ${JSBATON_ARGC} arraybuffers`
1379. 12 );
1380. 12 // push externalbuffer - 4-byte
1381. 12 baton.setInt32(nused + 1, bufi[0], true);
1382. 12 // set buffer
1383. 12 cModule._jsbatonSetArraybuffer(baton.buffer, bufi[0], val);
1384. 12 // increment bufi
1385. 12 bufi[0] += 1;
1386. 12 // add buffer to reference_list to prevent gc during db_call.
1387. 12 referenceList.push(val);
1388. 12 break;
1389. 561 case SQLITE_DATATYPE_FLOAT:
1390. 561 // push SQLITE-REAL - 8-byte
1391. 561 baton.setFloat64(nused + 1, val, true);
1392. 561 break;
1393. 42 case SQLITE_DATATYPE_INTEGER:
1394. 42 assertInt64(val);
1395. 42 // push SQLITE-INTEGER - 8-byte
1396. 42 baton.setBigInt64(nused + 1, val, true);
1397. 42 break;
1398. 5170 }
1399. 5170 return baton;
1400. 5170}
1401. 1
1402. 1752function jsonParseArraybuffer(buf) {
1403. 1752
1404. 1752// This function will JSON.parse arraybuffer <buf>.
1405. 1752
1406. 1752 return JSON.parse(
1407. 1752 (
1408. 1752 IS_BROWSER
1409. 1 ? new TextDecoder().decode(buf)
1410. 1751 : buf
1411. 1752 )
1412. 1 || "null"
1413. 1752 );
1414. 1752}
1415. 1
1416. 2function jsonRowListFromCsv({
1417. 2 csv
1418. 2}) {
1419. 2// this function will convert <csv>-text to json list-of-list
1420. 2//
1421. 2// https://tools.ietf.org/html/rfc4180#section-2
1422. 2// Definition of the CSV Format
1423. 2// While there are various specifications and implementations for the
1424. 2// CSV format (for ex. [4], [5], [6] and [7]), there is no formal
1425. 2// specification in existence, which allows for a wide variety of
1426. 2// interpretations of CSV files. This section documents the format that
1427. 2// seems to be followed by most implementations:
1428. 2//
1429. 2// 1. Each record is located on a separate line, delimited by a line
1430. 2// break (CRLF). For example:
1431. 2// aaa,bbb,ccc CRLF
1432. 2// zzz,yyy,xxx CRLF
1433. 2//
1434. 2// 2. The last record in the file may or may not have an ending line
1435. 2// break. For example:
1436. 2// aaa,bbb,ccc CRLF
1437. 2// zzz,yyy,xxx
1438. 2//
1439. 2// 3. There maybe an optional header line appearing as the first line
1440. 2// of the file with the same format as normal record lines. This
1441. 2// header will contain names corresponding to the fields in the file
1442. 2// and should contain the same number of fields as the records in
1443. 2// the rest of the file (the presence or absence of the header line
1444. 2// should be indicated via the optional "header" parameter of this
1445. 2// MIME type). For example:
1446. 2// field_name,field_name,field_name CRLF
1447. 2// aaa,bbb,ccc CRLF
1448. 2// zzz,yyy,xxx CRLF
1449. 2//
1450. 2// 4. Within the header and each record, there may be one or more
1451. 2// fields, separated by commas. Each line should contain the same
1452. 2// number of fields throughout the file. Spaces are considered part
1453. 2// of a field and should not be ignored. The last field in the
1454. 2// record must not be followed by a comma. For example:
1455. 2// aaa,bbb,ccc
1456. 2//
1457. 2// 5. Each field may or may not be enclosed in double quotes (however
1458. 2// some programs, such as Microsoft Excel, do not use double quotes
1459. 2// at all). If fields are not enclosed with double quotes, then
1460. 2// double quotes may not appear inside the fields. For example:
1461. 2// "aaa","bbb","ccc" CRLF
1462. 2// zzz,yyy,xxx
1463. 2//
1464. 2// 6. Fields containing line breaks (CRLF), double quotes, and commas
1465. 2// should be enclosed in double-quotes. For example:
1466. 2// "aaa","b CRLF
1467. 2// bb","ccc" CRLF
1468. 2// zzz,yyy,xxx
1469. 2//
1470. 2// 7. If double-quotes are used to enclose fields, then a double-quote
1471. 2// appearing inside a field must be escaped by preceding it with
1472. 2// another double quote. For example:
1473. 2// "aaa","b""bb","ccc"
1474. 2 let match;
1475. 2 let quote;
1476. 2 let rgx;
1477. 2 let row;
1478. 2 let rowList;
1479. 2 let val;
1480. 2 // normalize "\r\n" to "\n"
1481. 2 csv = csv.trimEnd().replace((
1482. 2 /\r\n?/gu
1483. 2 ), "\n") + "\n";
1484. 2 rgx = (
1485. 2 /(.*?)(""|"|,|\n)/gu
1486. 2 );
1487. 2 rowList = [];
1488. 2 // reset row
1489. 2 row = [];
1490. 2 val = "";
1491. 28 while (true) {
1492. 28 match = rgx.exec(csv);
1493. 28 if (!match) {
1494. 28// 2. The last record in the file may or may not have an ending line
1495. 28// break. For example:
1496. 28// aaa,bbb,ccc CRLF
1497. 28// zzz,yyy,xxx
1498. 28 if (!row.length) {
1499. 28 break;
1500. 28 }
1501. 28 // // if eof missing crlf, then mock it
1502. 28 // rgx.lastIndex = csv.length;
1503. 28 // match = [
1504. 28 // "\n", "", "\n"
1505. 28 // ];
1506. 28 }
1507. 28 // build val
1508. 28 val += match[1];
1509. 28 if (match[2] === "\"") {
1510. 28// 5. Each field may or may not be enclosed in double quotes (however
1511. 28// some programs, such as Microsoft Excel, do not use double quotes
1512. 28// at all). If fields are not enclosed with double quotes, then
1513. 28// double quotes may not appear inside the fields. For example:
1514. 28// "aaa","bbb","ccc" CRLF
1515. 28// zzz,yyy,xxx
1516. 28 quote = !quote;
1517. 28 } else if (quote) {
1518. 28// 7. If double-quotes are used to enclose fields, then a double-quote
1519. 28// appearing inside a field must be escaped by preceding it with
1520. 28// another double quote. For example:
1521. 28// "aaa","b""bb","ccc"
1522. 28 if (match[2] === "\"\"") {
1523. 28 val += "\"";
1524. 28// 6. Fields containing line breaks (CRLF), double quotes, and commas
1525. 28// should be enclosed in double-quotes. For example:
1526. 28// "aaa","b CRLF
1527. 28// bb","ccc" CRLF
1528. 28// zzz,yyy,xxx
1529. 28 } else {
1530. 28 val += match[2];
1531. 28 }
1532. 28 } else if (match[2] === ",") {
1533. 28// 4. Within the header and each record, there may be one or more
1534. 28// fields, separated by commas. Each line should contain the same
1535. 28// number of fields throughout the file. Spaces are considered part
1536. 28// of a field and should not be ignored. The last field in the
1537. 28// record must not be followed by a comma. For example:
1538. 28// aaa,bbb,ccc
1539. 28 // delimit val
1540. 28 row.push(val);
1541. 28 val = "";
1542. 28 } else if (match[2] === "\n") {
1543. 28// 1. Each record is located on a separate line, delimited by a line
1544. 28// break (CRLF). For example:
1545. 28// aaa,bbb,ccc CRLF
1546. 28// zzz,yyy,xxx CRLF
1547. 28 // delimit val
1548. 28 row.push(val);
1549. 28 val = "";
1550. 28 // append row
1551. 28 rowList.push(row);
1552. 28 // reset row
1553. 28 row = [];
1554. 28 }
1555. 28 }
1556. 2 // // append val
1557. 2 // if (val) {
1558. 2 // row.push(val);
1559. 2 // }
1560. 2 // // append row
1561. 2 // if (row.length) {
1562. 2 // rowList.push(row);
1563. 2 // }
1564. 2 return rowList;
1565. 2}
1566. 1
1567. 1function listOrEmptyList(list) {
1568. 1
1569. 1// This function will return <list> or empty-list if falsy.
1570. 1
1571. 1 return list || [];
1572. 1}
1573. 1
1574. 8async function moduleFsInit() {
1575. 8
1576. 8// This function will import nodejs builtin-modules if they have not yet been
1577. 8// imported.
1578. 8
1579. 8// State 3 - Modules already imported.
1580. 8
1581. 6 if (moduleFs !== undefined) {
1582. 6 return;
1583. 6 }
1584. 2
1585. 2// State 2 - Wait while modules are importing.
1586. 2
1587. 2 if (moduleFsInitResolveList !== undefined) {
1588. 1 return new Promise(function (resolve) {
1589. 1 moduleFsInitResolveList.push(resolve);
1590. 1 });
1591. 1 }
1592. 1
1593. 1// State 1 - Start importing modules.
1594. 1
1595. 1 moduleFsInitResolveList = [];
1596. 1 [
1597. 1 moduleChildProcess,
1598. 1 moduleCrypto,
1599. 1 moduleFs,
1600. 1 modulePath,
1601. 1 moduleUrl
1602. 1 ] = await Promise.all([
1603. 1 import("child_process"),
1604. 1 import("crypto"),
1605. 1 import("fs"),
1606. 1 import("path"),
1607. 1 import("url")
1608. 1 ]);
1609. 1 while (moduleFsInitResolveList.length > 0) {
1610. 1 moduleFsInitResolveList.shift()();
1611. 1 }
1612. 8}
1613. 1
1614. 264function noop(val) {
1615. 264
1616. 264// This function will do nothing except return <val>.
1617. 264
1618. 264 return val;
1619. 264}
1620. 1
1621. 42580function objectDeepCopyWithKeysSorted(obj) {
1622. 42580
1623. 42580// This function will recursively deep-copy <obj> with keys sorted.
1624. 42580
1625. 42580 let sorted;
1626. 28132 if (typeof obj !== "object" || !obj) {
1627. 28132 return obj;
1628. 28132 }
1629. 14448
1630. 14448// Recursively deep-copy list with child-keys sorted.
1631. 14448
1632. 14448 if (Array.isArray(obj)) {
1633. 2202 return obj.map(objectDeepCopyWithKeysSorted);
1634. 12246 }
1635. 12246
1636. 12246// Recursively deep-copy obj with keys sorted.
1637. 12246
1638. 12246 sorted = Object.create(null);
1639. 13522 Object.keys(obj).sort().forEach(function (key) {
1640. 13522 sorted[key] = objectDeepCopyWithKeysSorted(obj[key]);
1641. 13522 });
1642. 12246 return sorted;
1643. 12246}
1644. 1
1645. 3async function sqlmathInit() {
1646. 3
1647. 3// This function will init sqlmath.
1648. 3
1649. 3 let moduleModule;
1650. 3 dbFinalizationRegistry = (
1651. 3 dbFinalizationRegistry
1652. 29 ) || new FinalizationRegistry(function ({afterFinalization, ptr}) {
1653. 29
1654. 29// This function will auto-close any open sqlite3-db-pointer,
1655. 29// after its js-wrapper has been garbage-collected.
1656. 29
1657. 29 dbCallAsync(jsbatonCreate("_dbClose"), [ptr[0]]);
1658. 1 if (afterFinalization) {
1659. 1 afterFinalization();
1660. 1 }
1661. 29 });
1662. 3
1663. 3// Feature-detect nodejs.
1664. 3
1665. 3 if (
1666. 3 typeof process !== "object"
1667. 3 || typeof process?.versions?.node !== "string"
1668. 3 || cModule
1669. 1 ) {
1670. 1 return;
1671. 2 }
1672. 2
1673. 2// Init moduleFs.
1674. 2
1675. 2 await moduleFsInit();
1676. 2 moduleFsInit(); // coverage-hack
1677. 2 moduleChildProcessSpawn = moduleChildProcess.spawn;
1678. 2
1679. 2// Init moduleFs.
1680. 2
1681. 2 await moduleFsInit();
1682. 2 moduleFsInit(); // coverage-hack
1683. 2 moduleChildProcessSpawn = moduleChildProcess.spawn;
1684. 2 cModulePath = moduleUrl.fileURLToPath(import.meta.url).replace(
1685. 2 (/\bsqlmath\.mjs$/),
1686. 2 `_sqlmath.napi6_${process.platform}_${process.arch}.node`
1687. 2 );
1688. 2
1689. 2// Import napi c-addon.
1690. 2
1691. 2 if (!npm_config_mode_setup) {
1692. 2 moduleModule = await import("module");
1693. 2 if (!cModule) {
1694. 2 cModule = moduleModule.createRequire(cModulePath);
1695. 2 cModule = cModule(cModulePath);
1696. 2 }
1697. 2 }
1698. 2 if (npm_config_mode_test) {
1699. 2
1700. 2// Mock consoleError.
1701. 2
1702. 2 consoleError = noop;
1703. 2
1704. 2// Mock moduleChildProcessSpawn.
1705. 2
1706. 15 moduleChildProcessSpawn = function () {
1707. 15 let child = {
1708. 15 end: noop,
1709. 17 on: function (onType, resolve) {
1710. 17 switch (onType) {
1711. 2 case "data":
1712. 2 resolve(Buffer.alloc(0));
1713. 2 return;
1714. 15 default:
1715. 15 resolve(0);
1716. 17 }
1717. 17 },
1718. 15 setEncoding: noop,
1719. 15 write: noop
1720. 15 };
1721. 15 child.stderr = child;
1722. 15 child.stdin = child;
1723. 15 child.stdout = child;
1724. 15 return child;
1725. 15 };
1726. 2 }
1727. 3}
1728. 1
1729. 1function sqlmathWebworkerInit({
1730. 1 db,
1731. 1 modeTest
1732. 1}) {
1733. 1
1734. 1// This function will init sqlmath web-worker.
1735. 1
1736. 1// Feature-detect browser.
1737. 1
1738. 1 let Worker = globalThis.Worker;
1739. 1 IS_BROWSER = true;
1740. 1 if (modeTest) {
1741. 1 Worker = function () {
1742. 1 return;
1743. 1 };
1744. 1 }
1745. 1 sqlWorker = new Worker("sqlmath_wasm.js");
1746. 2 sqlWorker.onmessage = function ({
1747. 2 data
1748. 2 }) {
1749. 2 sqlMessageDict[data.id](data);
1750. 2 };
1751. 1 if (modeTest) {
1752. 2 sqlWorker.postMessage = function (data) {
1753. 2 setTimeout(function () {
1754. 2 sqlWorker.onmessage({data});
1755. 2 });
1756. 2 };
1757. 1 // test dbCallAsync handling-behavior
1758. 1 dbCallAsync(jsbatonCreate("testTimeElapsed"), [true]);
1759. 1 // test dbFileLoadAsync handling-behavior
1760. 1 dbFileLoadAsync({db, filename: "aa", modeTest});
1761. 1 // test jsonParseArraybuffer handling-behavior
1762. 1 jsonParseArraybuffer(new TextEncoder().encode("0"));
1763. 1 // revert IS_BROWSER
1764. 1 IS_BROWSER = undefined;
1765. 1 }
1766. 1}
1767. 1
1768. 1function waitAsync(timeout) {
1769. 1
1770. 1// This function will wait <timeout> ms.
1771. 1
1772. 1 return new Promise(function (resolve) {
1773. 1 setTimeout(resolve, timeout * !npm_config_mode_test);
1774. 1 });
1775. 1}
1776. 1
1777. 1sqlmathInit(); // coverage-hack
1778. 1await sqlmathInit();
1779. 1sqlmathInit(); // coverage-hack
1780. 1
1781. 1export {
1782. 1 LGBM_DTYPE_FLOAT32,
1783. 1 LGBM_DTYPE_FLOAT64,
1784. 1 LGBM_DTYPE_INT32,
1785. 1 LGBM_DTYPE_INT64,
1786. 1 LGBM_FEATURE_IMPORTANCE_GAIN,
1787. 1 LGBM_FEATURE_IMPORTANCE_SPLIT,
1788. 1 LGBM_MATRIX_TYPE_CSC,
1789. 1 LGBM_MATRIX_TYPE_CSR,
1790. 1 LGBM_PREDICT_CONTRIB,
1791. 1 LGBM_PREDICT_LEAF_INDEX,
1792. 1 LGBM_PREDICT_NORMAL,
1793. 1 LGBM_PREDICT_RAW_SCORE,
1794. 1 SQLITE_OPEN_AUTOPROXY,
1795. 1 SQLITE_OPEN_CREATE,
1796. 1 SQLITE_OPEN_DELETEONCLOSE,
1797. 1 SQLITE_OPEN_EXCLUSIVE,
1798. 1 SQLITE_OPEN_FULLMUTEX,
1799. 1 SQLITE_OPEN_MAIN_DB,
1800. 1 SQLITE_OPEN_MAIN_JOURNAL,
1801. 1 SQLITE_OPEN_MEMORY,
1802. 1 SQLITE_OPEN_NOFOLLOW,
1803. 1 SQLITE_OPEN_NOMUTEX,
1804. 1 SQLITE_OPEN_PRIVATECACHE,
1805. 1 SQLITE_OPEN_READONLY,
1806. 1 SQLITE_OPEN_READWRITE,
1807. 1 SQLITE_OPEN_SHAREDCACHE,
1808. 1 SQLITE_OPEN_SUBJOURNAL,
1809. 1 SQLITE_OPEN_SUPER_JOURNAL,
1810. 1 SQLITE_OPEN_TEMP_DB,
1811. 1 SQLITE_OPEN_TEMP_JOURNAL,
1812. 1 SQLITE_OPEN_TRANSIENT_DB,
1813. 1 SQLITE_OPEN_URI,
1814. 1 SQLITE_OPEN_WAL,
1815. 1 assertErrorThrownAsync,
1816. 1 assertInt64,
1817. 1 assertJsonEqual,
1818. 1 assertNumericalEqual,
1819. 1 assertOrThrow,
1820. 1 childProcessSpawn2,
1821. 1 ciBuildExt,
1822. 1 dbCloseAsync,
1823. 1 dbExecAndReturnLastBlob,
1824. 1 dbExecAndReturnLastRow,
1825. 1 dbExecAndReturnLastTable,
1826. 1 dbExecAndReturnLastValue,
1827. 1 dbExecAsync,
1828. 1 dbFileLoadAsync,
1829. 1 dbFileSaveAsync,
1830. 1 dbNoopAsync,
1831. 1 dbOpenAsync,
1832. 1 dbTableImportAsync,
1833. 1 debugInline,
1834. 1 fsCopyFileUnlessTest,
1835. 1 fsExistsUnlessTest,
1836. 1 fsReadFileUnlessTest,
1837. 1 fsWriteFileUnlessTest,
1838. 1 jsbatonGetInt64,
1839. 1 jsbatonGetString,
1840. 1 listOrEmptyList,
1841. 1 noop,
1842. 1 objectDeepCopyWithKeysSorted,
1843. 1 sqlmathWebworkerInit,
1844. 1 version,
1845. 1 waitAsync
1846. 1};
1847. 1