@zappdev/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/README.md +55 -0
  2. package/dist/zapp-cli.js +9471 -0
  3. package/native/src/app/app.zc +490 -0
  4. package/native/src/event/event.zc +24 -0
  5. package/native/src/event/events.zc +70 -0
  6. package/native/src/platform/darwin/backend.zc +923 -0
  7. package/native/src/platform/darwin/backend_bootstrap.zc +9 -0
  8. package/native/src/platform/darwin/bootstrap.zc +9 -0
  9. package/native/src/platform/darwin/engine_jsc.zc +86 -0
  10. package/native/src/platform/darwin/engine_qjs.zc +92 -0
  11. package/native/src/platform/darwin/platform.zc +156 -0
  12. package/native/src/platform/darwin/webview.zc +550 -0
  13. package/native/src/platform/darwin/webview_bootstrap.zc +9 -0
  14. package/native/src/platform/darwin/window.zc +1223 -0
  15. package/native/src/platform/darwin/worker/common.zc +223 -0
  16. package/native/src/platform/darwin/worker/core/base64_core.zc +29 -0
  17. package/native/src/platform/darwin/worker/core/crypto_core.zc +19 -0
  18. package/native/src/platform/darwin/worker/core/encoding_core.zc +32 -0
  19. package/native/src/platform/darwin/worker/core/fetch_core.zc +145 -0
  20. package/native/src/platform/darwin/worker/core/url_core.zc +69 -0
  21. package/native/src/platform/darwin/worker/core/websocket_core.zc +179 -0
  22. package/native/src/platform/darwin/worker/dispatch.zc +55 -0
  23. package/native/src/platform/darwin/worker/jsc/base64_jsc.zc +39 -0
  24. package/native/src/platform/darwin/worker/jsc/crypto_jsc.zc +49 -0
  25. package/native/src/platform/darwin/worker/jsc/encoding_jsc.zc +86 -0
  26. package/native/src/platform/darwin/worker/jsc/fetch_jsc.zc +149 -0
  27. package/native/src/platform/darwin/worker/jsc/url_jsc.zc +54 -0
  28. package/native/src/platform/darwin/worker/jsc/websocket_jsc.zc +127 -0
  29. package/native/src/platform/darwin/worker/jsc.zc +670 -0
  30. package/native/src/platform/darwin/worker/mod.zc +30 -0
  31. package/native/src/platform/darwin/worker/qjs/fetch_qjs.zc +233 -0
  32. package/native/src/platform/darwin/worker/qjs/qjs_macros.zc +23 -0
  33. package/native/src/platform/darwin/worker/qjs/websocket_qjs.zc +223 -0
  34. package/native/src/platform/darwin/worker/qjs.zc +1053 -0
  35. package/native/src/platform/darwin/worker/timers.zc +149 -0
  36. package/native/src/platform/darwin/worker/timers_qjs.zc +209 -0
  37. package/native/src/platform/platform.zc +64 -0
  38. package/native/src/platform/shared/log.zc +156 -0
  39. package/native/src/platform/shared/worker/qjs/base64_qjs.zc +38 -0
  40. package/native/src/platform/shared/worker/qjs/crypto_qjs.zc +44 -0
  41. package/native/src/platform/shared/worker/qjs/encoding_qjs.zc +95 -0
  42. package/native/src/platform/shared/worker/qjs/url_qjs.zc +65 -0
  43. package/native/src/platform/shared/worker_registry.zc +206 -0
  44. package/native/src/platform/window.zc +446 -0
  45. package/native/src/platform/windows/backend.zc +452 -0
  46. package/native/src/platform/windows/backend_bootstrap.zc +9 -0
  47. package/native/src/platform/windows/bootstrap.zc +9 -0
  48. package/native/src/platform/windows/engine_qjs.zc +60 -0
  49. package/native/src/platform/windows/platform.zc +387 -0
  50. package/native/src/platform/windows/webview.zc +1175 -0
  51. package/native/src/platform/windows/webview_bootstrap.zc +9 -0
  52. package/native/src/platform/windows/window.zc +1271 -0
  53. package/native/src/platform/windows/worker/common.zc +409 -0
  54. package/native/src/platform/windows/worker/core/base64_core.zc +52 -0
  55. package/native/src/platform/windows/worker/core/crypto_core.zc +34 -0
  56. package/native/src/platform/windows/worker/core/encoding_core.zc +60 -0
  57. package/native/src/platform/windows/worker/core/fetch_core.zc +274 -0
  58. package/native/src/platform/windows/worker/core/url_core.zc +216 -0
  59. package/native/src/platform/windows/worker/core/websocket_core.zc +343 -0
  60. package/native/src/platform/windows/worker/dispatch.zc +34 -0
  61. package/native/src/platform/windows/worker/mod.zc +46 -0
  62. package/native/src/platform/windows/worker/qjs/fetch_qjs.zc +255 -0
  63. package/native/src/platform/windows/worker/qjs/websocket_qjs.zc +263 -0
  64. package/native/src/platform/windows/worker/qjs.zc +1049 -0
  65. package/native/src/platform/windows/worker/timers_qjs.zc +288 -0
  66. package/native/src/platform/worker.zc +8 -0
  67. package/native/src/service/service.zc +228 -0
  68. package/native/vendor/quickjs-ng/.gitattributes +4 -0
  69. package/native/vendor/quickjs-ng/.github/dependabot.yml +7 -0
  70. package/native/vendor/quickjs-ng/.github/workflows/ci.yml +812 -0
  71. package/native/vendor/quickjs-ng/.github/workflows/docs.yml +49 -0
  72. package/native/vendor/quickjs-ng/.github/workflows/release.yml +162 -0
  73. package/native/vendor/quickjs-ng/.github/workflows/test-docs.yml +23 -0
  74. package/native/vendor/quickjs-ng/.github/workflows/tsan.yml +32 -0
  75. package/native/vendor/quickjs-ng/.github/workflows/valgrind.yml +33 -0
  76. package/native/vendor/quickjs-ng/.gitmodules +5 -0
  77. package/native/vendor/quickjs-ng/CMakeLists.txt +553 -0
  78. package/native/vendor/quickjs-ng/LICENSE +24 -0
  79. package/native/vendor/quickjs-ng/Makefile +149 -0
  80. package/native/vendor/quickjs-ng/amalgam.js +53 -0
  81. package/native/vendor/quickjs-ng/api-test.c +927 -0
  82. package/native/vendor/quickjs-ng/builtin-array-fromasync.h +119 -0
  83. package/native/vendor/quickjs-ng/builtin-array-fromasync.js +36 -0
  84. package/native/vendor/quickjs-ng/builtin-iterator-zip-keyed.h +332 -0
  85. package/native/vendor/quickjs-ng/builtin-iterator-zip-keyed.js +194 -0
  86. package/native/vendor/quickjs-ng/builtin-iterator-zip.h +337 -0
  87. package/native/vendor/quickjs-ng/builtin-iterator-zip.js +210 -0
  88. package/native/vendor/quickjs-ng/ctest.c +17 -0
  89. package/native/vendor/quickjs-ng/cutils.h +2013 -0
  90. package/native/vendor/quickjs-ng/cxxtest.cc +2 -0
  91. package/native/vendor/quickjs-ng/dtoa.c +1619 -0
  92. package/native/vendor/quickjs-ng/dtoa.h +87 -0
  93. package/native/vendor/quickjs-ng/examples/fib.c +67 -0
  94. package/native/vendor/quickjs-ng/examples/fib_module.js +10 -0
  95. package/native/vendor/quickjs-ng/examples/hello.js +1 -0
  96. package/native/vendor/quickjs-ng/examples/hello_module.js +6 -0
  97. package/native/vendor/quickjs-ng/examples/meson.build +17 -0
  98. package/native/vendor/quickjs-ng/examples/pi_bigint.js +118 -0
  99. package/native/vendor/quickjs-ng/examples/point.c +154 -0
  100. package/native/vendor/quickjs-ng/examples/test_fib.js +8 -0
  101. package/native/vendor/quickjs-ng/examples/test_point.js +43 -0
  102. package/native/vendor/quickjs-ng/fuzz.c +51 -0
  103. package/native/vendor/quickjs-ng/gen/function_source.c +81 -0
  104. package/native/vendor/quickjs-ng/gen/hello.c +53 -0
  105. package/native/vendor/quickjs-ng/gen/hello_module.c +106 -0
  106. package/native/vendor/quickjs-ng/gen/repl.c +3053 -0
  107. package/native/vendor/quickjs-ng/gen/standalone.c +324 -0
  108. package/native/vendor/quickjs-ng/gen/test_fib.c +81 -0
  109. package/native/vendor/quickjs-ng/libregexp-opcode.h +58 -0
  110. package/native/vendor/quickjs-ng/libregexp.c +2687 -0
  111. package/native/vendor/quickjs-ng/libregexp.h +98 -0
  112. package/native/vendor/quickjs-ng/libunicode-table.h +4707 -0
  113. package/native/vendor/quickjs-ng/libunicode.c +1746 -0
  114. package/native/vendor/quickjs-ng/libunicode.h +126 -0
  115. package/native/vendor/quickjs-ng/list.h +107 -0
  116. package/native/vendor/quickjs-ng/lre-test.c +73 -0
  117. package/native/vendor/quickjs-ng/meson.build +684 -0
  118. package/native/vendor/quickjs-ng/meson_options.txt +6 -0
  119. package/native/vendor/quickjs-ng/qjs-wasi-reactor.c +208 -0
  120. package/native/vendor/quickjs-ng/qjs.c +748 -0
  121. package/native/vendor/quickjs-ng/qjsc.c +673 -0
  122. package/native/vendor/quickjs-ng/quickjs-atom.h +267 -0
  123. package/native/vendor/quickjs-ng/quickjs-c-atomics.h +54 -0
  124. package/native/vendor/quickjs-ng/quickjs-libc.c +4986 -0
  125. package/native/vendor/quickjs-ng/quickjs-libc.h +79 -0
  126. package/native/vendor/quickjs-ng/quickjs-opcode.h +369 -0
  127. package/native/vendor/quickjs-ng/quickjs.c +60259 -0
  128. package/native/vendor/quickjs-ng/quickjs.h +1419 -0
  129. package/native/vendor/quickjs-ng/repl.js +1927 -0
  130. package/native/vendor/quickjs-ng/run-test262.c +2417 -0
  131. package/native/vendor/quickjs-ng/standalone.js +129 -0
  132. package/native/vendor/quickjs-ng/tests/assert.js +49 -0
  133. package/native/vendor/quickjs-ng/tests/bug1221.js +16 -0
  134. package/native/vendor/quickjs-ng/tests/bug1296.js +12 -0
  135. package/native/vendor/quickjs-ng/tests/bug1297.js +22 -0
  136. package/native/vendor/quickjs-ng/tests/bug1301.js +21 -0
  137. package/native/vendor/quickjs-ng/tests/bug1302.js +24 -0
  138. package/native/vendor/quickjs-ng/tests/bug1305.js +26 -0
  139. package/native/vendor/quickjs-ng/tests/bug1318.js +54 -0
  140. package/native/vendor/quickjs-ng/tests/bug1352.js +8 -0
  141. package/native/vendor/quickjs-ng/tests/bug1354.js +6 -0
  142. package/native/vendor/quickjs-ng/tests/bug1355.js +58 -0
  143. package/native/vendor/quickjs-ng/tests/bug1368.js +9 -0
  144. package/native/vendor/quickjs-ng/tests/bug39/1.js +6 -0
  145. package/native/vendor/quickjs-ng/tests/bug39/2.js +6 -0
  146. package/native/vendor/quickjs-ng/tests/bug39/3.js +7 -0
  147. package/native/vendor/quickjs-ng/tests/bug488-upstream.js +7 -0
  148. package/native/vendor/quickjs-ng/tests/bug633/0.js +7 -0
  149. package/native/vendor/quickjs-ng/tests/bug633/1.js +4 -0
  150. package/native/vendor/quickjs-ng/tests/bug633/2.js +4 -0
  151. package/native/vendor/quickjs-ng/tests/bug633/3.js +4 -0
  152. package/native/vendor/quickjs-ng/tests/bug645/0.js +4 -0
  153. package/native/vendor/quickjs-ng/tests/bug645/1.js +9 -0
  154. package/native/vendor/quickjs-ng/tests/bug645/2.js +7 -0
  155. package/native/vendor/quickjs-ng/tests/bug648.js +13 -0
  156. package/native/vendor/quickjs-ng/tests/bug652.js +4 -0
  157. package/native/vendor/quickjs-ng/tests/bug741.js +19 -0
  158. package/native/vendor/quickjs-ng/tests/bug775.js +7 -0
  159. package/native/vendor/quickjs-ng/tests/bug776.js +7 -0
  160. package/native/vendor/quickjs-ng/tests/bug832.js +2 -0
  161. package/native/vendor/quickjs-ng/tests/bug858.js +26 -0
  162. package/native/vendor/quickjs-ng/tests/bug904.js +6 -0
  163. package/native/vendor/quickjs-ng/tests/bug988.js +7 -0
  164. package/native/vendor/quickjs-ng/tests/bug999.js +3 -0
  165. package/native/vendor/quickjs-ng/tests/destructured-export.js +8 -0
  166. package/native/vendor/quickjs-ng/tests/detect_module/0.js +1 -0
  167. package/native/vendor/quickjs-ng/tests/detect_module/1.js +2 -0
  168. package/native/vendor/quickjs-ng/tests/detect_module/2.js +1 -0
  169. package/native/vendor/quickjs-ng/tests/detect_module/3.js +8 -0
  170. package/native/vendor/quickjs-ng/tests/detect_module/4.js +3 -0
  171. package/native/vendor/quickjs-ng/tests/empty.js +0 -0
  172. package/native/vendor/quickjs-ng/tests/fixture_cyclic_import.js +2 -0
  173. package/native/vendor/quickjs-ng/tests/fixture_string_exports.js +12 -0
  174. package/native/vendor/quickjs-ng/tests/function_source.js +14 -0
  175. package/native/vendor/quickjs-ng/tests/microbench.js +1267 -0
  176. package/native/vendor/quickjs-ng/tests/null_or_undefined.js +38 -0
  177. package/native/vendor/quickjs-ng/tests/str-pad-leak.js +5 -0
  178. package/native/vendor/quickjs-ng/tests/test_bigint.js +107 -0
  179. package/native/vendor/quickjs-ng/tests/test_bjson.js +366 -0
  180. package/native/vendor/quickjs-ng/tests/test_builtin.js +1314 -0
  181. package/native/vendor/quickjs-ng/tests/test_closure.js +220 -0
  182. package/native/vendor/quickjs-ng/tests/test_cyclic_import.js +12 -0
  183. package/native/vendor/quickjs-ng/tests/test_domexception.js +35 -0
  184. package/native/vendor/quickjs-ng/tests/test_language.js +755 -0
  185. package/native/vendor/quickjs-ng/tests/test_loop.js +367 -0
  186. package/native/vendor/quickjs-ng/tests/test_queue_microtask.js +39 -0
  187. package/native/vendor/quickjs-ng/tests/test_std.js +340 -0
  188. package/native/vendor/quickjs-ng/tests/test_string_exports.js +25 -0
  189. package/native/vendor/quickjs-ng/tests/test_worker.js +43 -0
  190. package/native/vendor/quickjs-ng/tests/test_worker_module.js +30 -0
  191. package/native/vendor/quickjs-ng/tests.conf +14 -0
  192. package/native/vendor/quickjs-ng/unicode_download.sh +19 -0
  193. package/native/vendor/quickjs-ng/unicode_gen.c +3108 -0
  194. package/native/vendor/quickjs-ng/unicode_gen_def.h +310 -0
  195. package/native/vendor/quickjs-ng/update-version.sh +32 -0
  196. package/native/vendor/webview2/include/WebView2.h +60636 -0
  197. package/native/vendor/webview2/include/WebView2EnvironmentOptions.h +406 -0
  198. package/package.json +33 -0
  199. package/src/backend.ts +139 -0
  200. package/src/build-config.ts +87 -0
  201. package/src/build.ts +276 -0
  202. package/src/common.ts +195 -0
  203. package/src/config.ts +89 -0
  204. package/src/dev.ts +164 -0
  205. package/src/generate.ts +200 -0
  206. package/src/icons.ts +116 -0
  207. package/src/init.ts +190 -0
  208. package/src/package.ts +150 -0
  209. package/src/zapp-cli.ts +263 -0
@@ -0,0 +1,1927 @@
1
+ /*
2
+ * QuickJS Read Eval Print Loop
3
+ *
4
+ * Copyright (c) 2017-2020 Fabrice Bellard
5
+ * Copyright (c) 2017-2020 Charlie Gordon
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ * of this software and associated documentation files (the "Software"), to deal
9
+ * in the Software without restriction, including without limitation the rights
10
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the Software, and to permit persons to whom the Software is
12
+ * furnished to do so, subject to the following conditions:
13
+ *
14
+ * The above copyright notice and this permission notice shall be included in
15
+ * all copies or substantial portions of the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ * THE SOFTWARE.
24
+ */
25
+ import * as std from "qjs:std";
26
+ import * as os from "qjs:os";
27
+ import * as bjson from "qjs:bjson";
28
+
29
+ (function(g) {
30
+ /* add 'bjson', 'os' and 'std' bindings */
31
+ g.bjson = bjson;
32
+ g.os = os;
33
+ g.std = std;
34
+
35
+ /* close global objects */
36
+ var Object = g.Object;
37
+ var String = g.String;
38
+ var Number = g.Number;
39
+ var Boolean = g.Boolean;
40
+ var BigInt = g.BigInt;
41
+ var Uint8Array = g.Uint8Array;
42
+ var Array = g.Array;
43
+ var Date = g.Date;
44
+ var RegExp = g.RegExp;
45
+ var Error = g.Error;
46
+ var Symbol = g.Symbol;
47
+ var Math = g.Math;
48
+ var JSON = g.JSON;
49
+ var isFinite = g.isFinite;
50
+ var isNaN = g.isNaN;
51
+ var Infinity = g.Infinity;
52
+ var console = g.console;
53
+
54
+ // auto-completion keywords
55
+ var keywords = [
56
+ "await ", "catch (", "class ", "const ", "else ", "export ", "for ",
57
+ "function ", "if (", "import ", "instanceof ", "let ", "new ",
58
+ "return", "super ", "this", "try {", "typeof ", "var ", "while (",
59
+ "yield ",
60
+ ];
61
+
62
+ var colors = {
63
+ none: "\x1b[0m",
64
+ black: "\x1b[30m",
65
+ red: "\x1b[31m",
66
+ green: "\x1b[32m",
67
+ yellow: "\x1b[33m",
68
+ blue: "\x1b[34m",
69
+ magenta: "\x1b[35m",
70
+ cyan: "\x1b[36m",
71
+ white: "\x1b[37m",
72
+ gray: "\x1b[30;1m",
73
+ grey: "\x1b[30;1m",
74
+ bright_red: "\x1b[31;1m",
75
+ bright_green: "\x1b[32;1m",
76
+ bright_yellow: "\x1b[33;1m",
77
+ bright_blue: "\x1b[34;1m",
78
+ bright_magenta: "\x1b[35;1m",
79
+ bright_cyan: "\x1b[36;1m",
80
+ bright_white: "\x1b[37;1m",
81
+ };
82
+
83
+ var themes = {
84
+ dark: {
85
+ 'annotation': 'cyan',
86
+ 'boolean': 'bright_white',
87
+ 'comment': 'white',
88
+ 'date': 'magenta',
89
+ 'default': 'bright_green',
90
+ 'error': 'bright_red',
91
+ 'function': 'bright_yellow',
92
+ 'identifier': 'bright_green',
93
+ 'keyword': 'bright_white',
94
+ 'null': 'bright_white',
95
+ 'number': 'green',
96
+ 'other': 'white',
97
+ 'propname': 'white',
98
+ 'regexp': 'cyan',
99
+ 'string': 'bright_cyan',
100
+ 'symbol': 'bright_white',
101
+ 'type': 'bright_magenta',
102
+ 'undefined': 'bright_white',
103
+ },
104
+ light: {
105
+ 'annotation': 'cyan',
106
+ 'boolean': 'bright_magenta',
107
+ 'comment': 'grey',
108
+ 'date': 'magenta',
109
+ 'default': 'black',
110
+ 'error': 'red',
111
+ 'function': 'bright_yellow',
112
+ 'identifier': 'black',
113
+ 'keyword': 'bright_magenta',
114
+ 'null': 'bright_magenta',
115
+ 'number': 'green',
116
+ 'other': 'black',
117
+ 'propname': 'black',
118
+ 'regexp': 'cyan',
119
+ 'string': 'bright_cyan',
120
+ 'symbol': 'grey',
121
+ 'type': 'bright_magenta',
122
+ 'undefined': 'bright_magenta',
123
+ },
124
+ };
125
+ var styles = themes.dark;
126
+ var utf8 = true;
127
+ var show_time = false;
128
+ var show_colors = true;
129
+ var show_hidden = false;
130
+ var show_depth = 2;
131
+ var hex_mode = false;
132
+ var use_strict = false;
133
+
134
+ var history = [];
135
+ var history_index;
136
+ var clip_board = "";
137
+ var pstate = "";
138
+ var prompt = "";
139
+ var plen = 0;
140
+ var ps1 = "qjs > ";
141
+ var ps2 = " ... ";
142
+ var eval_start_time;
143
+ var eval_time = 0;
144
+ var mexpr = "";
145
+ var level = 0;
146
+ var cmd = "";
147
+ var cursor_pos = 0;
148
+ var last_cmd = "";
149
+ var last_cursor_pos = 0;
150
+ var this_fun, last_fun;
151
+ var quote_flag = false;
152
+
153
+ var utf8_state = 0;
154
+ var utf8_val = 0;
155
+
156
+ var term_fd;
157
+ var term_read_buf;
158
+ var term_width;
159
+ /* current X position of the cursor in the terminal */
160
+ var term_cursor_x = 0;
161
+
162
+ function termInit() {
163
+ var tab;
164
+ term_fd = std.in.fileno();
165
+
166
+ /* get the terminal size */
167
+ term_width = 80;
168
+ if (os.isatty(term_fd)) {
169
+ if (os.ttyGetWinSize) {
170
+ tab = os.ttyGetWinSize(term_fd);
171
+ if (tab)
172
+ term_width = tab[0];
173
+ }
174
+ if (os.ttySetRaw) {
175
+ /* set the TTY to raw mode */
176
+ os.ttySetRaw(term_fd);
177
+ }
178
+ }
179
+
180
+ /* install a Ctrl-C signal handler */
181
+ os.signal(os.SIGINT, sigint_handler);
182
+
183
+ /* install a handler to read stdin */
184
+ term_read_buf = new Uint8Array(64);
185
+ os.setReadHandler(term_fd, term_read_handler);
186
+ }
187
+
188
+ function sigint_handler() {
189
+ /* send Ctrl-C to readline */
190
+ handle_byte(3);
191
+ }
192
+
193
+ function term_read_handler() {
194
+ var l, i;
195
+ l = os.read(term_fd, term_read_buf.buffer, 0, term_read_buf.length);
196
+ for(i = 0; i < l; i++)
197
+ handle_byte(term_read_buf[i]);
198
+ }
199
+
200
+ function handle_byte(c) {
201
+ if (!utf8) {
202
+ handle_char(c);
203
+ } else if (utf8_state !== 0 && (c >= 0x80 && c < 0xc0)) {
204
+ utf8_val = (utf8_val << 6) | (c & 0x3F);
205
+ utf8_state--;
206
+ if (utf8_state === 0) {
207
+ handle_char(utf8_val);
208
+ }
209
+ } else if (c >= 0xc0 && c < 0xf8) {
210
+ utf8_state = 1 + (c >= 0xe0) + (c >= 0xf0);
211
+ utf8_val = c & ((1 << (6 - utf8_state)) - 1);
212
+ } else {
213
+ utf8_state = 0;
214
+ handle_char(c);
215
+ }
216
+ }
217
+
218
+ function is_alpha(c) {
219
+ return typeof c === "string" &&
220
+ ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
221
+ }
222
+
223
+ function is_digit(c) {
224
+ return typeof c === "string" && (c >= '0' && c <= '9');
225
+ }
226
+
227
+ function is_word(c) {
228
+ return typeof c === "string" &&
229
+ (is_alpha(c) || is_digit(c) || c == '_' || c == '$');
230
+ }
231
+
232
+ function is_blank(c) {
233
+ return typeof c === "string" && "\t\r\n\f\v".includes(c[0])
234
+ }
235
+
236
+ function ucs_length(str) {
237
+ var len, c, i, str_len = str.length;
238
+ len = 0;
239
+ /* we never count the trailing surrogate to have the
240
+ following property: ucs_length(str) =
241
+ ucs_length(str.substring(0, a)) + ucs_length(str.substring(a,
242
+ str.length)) for 0 <= a <= str.length */
243
+ for(i = 0; i < str_len; i++) {
244
+ c = str.charCodeAt(i);
245
+ if (c < 0xdc00 || c >= 0xe000)
246
+ len++;
247
+ }
248
+ return len;
249
+ }
250
+
251
+ function is_trailing_surrogate(c) {
252
+ var d;
253
+ if (typeof c !== "string")
254
+ return false;
255
+ d = c.codePointAt(0); /* can be NaN if empty string */
256
+ return d >= 0xdc00 && d < 0xe000;
257
+ }
258
+
259
+ function is_balanced(a, b) {
260
+ switch (a + b) {
261
+ case "()":
262
+ case "[]":
263
+ case "{}":
264
+ return true;
265
+ }
266
+ return false;
267
+ }
268
+
269
+ function print_color_text(str, start, style_names) {
270
+ var i, j;
271
+ for (j = start; j < str.length;) {
272
+ var style = style_names[i = j];
273
+ while (++j < str.length && style_names[j] == style)
274
+ continue;
275
+ std.puts(colors[styles[style] || 'none']);
276
+ std.puts(str.substring(i, j));
277
+ std.puts(colors['none']);
278
+ }
279
+ }
280
+
281
+ function print_csi(n, code) {
282
+ std.puts("\x1b[" + ((n != 1) ? n : "") + code);
283
+ }
284
+
285
+ /* XXX: handle double-width characters */
286
+ function move_cursor(delta) {
287
+ var i, l;
288
+ if (delta > 0) {
289
+ while (delta != 0) {
290
+ if (term_cursor_x == (term_width - 1)) {
291
+ std.puts("\n"); /* translated to CRLF */
292
+ term_cursor_x = 0;
293
+ delta--;
294
+ } else {
295
+ l = Math.min(term_width - 1 - term_cursor_x, delta);
296
+ print_csi(l, "C"); /* right */
297
+ delta -= l;
298
+ term_cursor_x += l;
299
+ }
300
+ }
301
+ } else {
302
+ delta = -delta;
303
+ while (delta != 0) {
304
+ if (term_cursor_x == 0) {
305
+ print_csi(1, "A"); /* up */
306
+ print_csi(term_width - 1, "C"); /* right */
307
+ delta--;
308
+ term_cursor_x = term_width - 1;
309
+ } else {
310
+ l = Math.min(delta, term_cursor_x);
311
+ print_csi(l, "D"); /* left */
312
+ delta -= l;
313
+ term_cursor_x -= l;
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ function update() {
320
+ var i, cmd_len;
321
+ /* cursor_pos is the position in 16 bit characters inside the
322
+ UTF-16 string 'cmd' */
323
+ if (cmd != last_cmd) {
324
+ if (!show_colors && last_cmd.substring(0, last_cursor_pos) == cmd.substring(0, last_cursor_pos)) {
325
+ /* optimize common case */
326
+ std.puts(cmd.substring(last_cursor_pos));
327
+ } else {
328
+ /* goto the start of the line */
329
+ move_cursor(-ucs_length(last_cmd.substring(0, last_cursor_pos)));
330
+ if (show_colors) {
331
+ var str = mexpr ? mexpr + '\n' + cmd : cmd;
332
+ var start = str.length - cmd.length;
333
+ var colorstate = colorize_js(str);
334
+ print_color_text(str, start, colorstate[2]);
335
+ } else {
336
+ std.puts(cmd);
337
+ }
338
+ }
339
+ term_cursor_x = (term_cursor_x + ucs_length(cmd)) % term_width;
340
+ if (term_cursor_x == 0) {
341
+ /* show the cursor on the next line */
342
+ std.puts(" \x08");
343
+ }
344
+ /* remove the trailing characters */
345
+ std.puts("\x1b[J");
346
+ last_cmd = cmd;
347
+ last_cursor_pos = cmd.length;
348
+ }
349
+ if (cursor_pos > last_cursor_pos) {
350
+ move_cursor(ucs_length(cmd.substring(last_cursor_pos, cursor_pos)));
351
+ } else if (cursor_pos < last_cursor_pos) {
352
+ move_cursor(-ucs_length(cmd.substring(cursor_pos, last_cursor_pos)));
353
+ }
354
+ last_cursor_pos = cursor_pos;
355
+ std.out.flush();
356
+ }
357
+
358
+ /* editing commands */
359
+ function insert(str) {
360
+ if (str) {
361
+ cmd = cmd.substring(0, cursor_pos) + str + cmd.substring(cursor_pos);
362
+ cursor_pos += str.length;
363
+ }
364
+ }
365
+
366
+ function quoted_insert() {
367
+ quote_flag = true;
368
+ }
369
+
370
+ function abort() {
371
+ cmd = "";
372
+ cursor_pos = 0;
373
+ return -2;
374
+ }
375
+
376
+ function alert() {
377
+ }
378
+
379
+ function beginning_of_line() {
380
+ cursor_pos = 0;
381
+ }
382
+
383
+ function end_of_line() {
384
+ cursor_pos = cmd.length;
385
+ }
386
+
387
+ function forward_char() {
388
+ if (cursor_pos < cmd.length) {
389
+ cursor_pos++;
390
+ while (is_trailing_surrogate(cmd.charAt(cursor_pos)))
391
+ cursor_pos++;
392
+ }
393
+ }
394
+
395
+ function backward_char() {
396
+ if (cursor_pos > 0) {
397
+ cursor_pos--;
398
+ while (is_trailing_surrogate(cmd.charAt(cursor_pos)))
399
+ cursor_pos--;
400
+ }
401
+ }
402
+
403
+ function skip_word_forward(pos) {
404
+ while (pos < cmd.length && !is_word(cmd.charAt(pos)))
405
+ pos++;
406
+ while (pos < cmd.length && is_word(cmd.charAt(pos)))
407
+ pos++;
408
+ return pos;
409
+ }
410
+
411
+ function skip_word_backward(pos) {
412
+ while (pos > 0 && !is_word(cmd.charAt(pos - 1)))
413
+ pos--;
414
+ while (pos > 0 && is_word(cmd.charAt(pos - 1)))
415
+ pos--;
416
+ return pos;
417
+ }
418
+
419
+ function forward_word() {
420
+ cursor_pos = skip_word_forward(cursor_pos);
421
+ }
422
+
423
+ function backward_word() {
424
+ cursor_pos = skip_word_backward(cursor_pos);
425
+ }
426
+
427
+ function clear_screen() {
428
+ directives["clear"]();
429
+ return -2;
430
+ }
431
+
432
+ function accept_line() {
433
+ std.puts("\n");
434
+ history_add(cmd);
435
+ return -1;
436
+ }
437
+
438
+ function history_add(str) {
439
+ str = str.trimRight();
440
+ if (str) {
441
+ while (history.length && !history[history.length - 1])
442
+ history.length--;
443
+ history.push(str);
444
+ }
445
+ history_index = history.length;
446
+ }
447
+
448
+ function previous_history() {
449
+ if (history_index > 0) {
450
+ if (history_index == history.length) {
451
+ history.push(cmd);
452
+ }
453
+ history_index--;
454
+ cmd = history[history_index];
455
+ cursor_pos = cmd.length;
456
+ }
457
+ }
458
+
459
+ function next_history() {
460
+ if (history_index < history.length - 1) {
461
+ history_index++;
462
+ cmd = history[history_index];
463
+ cursor_pos = cmd.length;
464
+ }
465
+ }
466
+
467
+ function history_search(dir) {
468
+ var pos = cursor_pos;
469
+ for (var i = 1; i <= history.length; i++) {
470
+ var index = (history.length + i * dir + history_index) % history.length;
471
+ if (history[index].substring(0, pos) == cmd.substring(0, pos)) {
472
+ history_index = index;
473
+ cmd = history[index];
474
+ return;
475
+ }
476
+ }
477
+ }
478
+
479
+ function history_search_backward() {
480
+ return history_search(-1);
481
+ }
482
+
483
+ function history_search_forward() {
484
+ return history_search(1);
485
+ }
486
+
487
+ function delete_char_dir(dir) {
488
+ var start, end;
489
+
490
+ start = cursor_pos;
491
+ if (dir < 0) {
492
+ start--;
493
+ while (is_trailing_surrogate(cmd.charAt(start)))
494
+ start--;
495
+ }
496
+ end = start + 1;
497
+ while (is_trailing_surrogate(cmd.charAt(end)))
498
+ end++;
499
+
500
+ if (start >= 0 && start < cmd.length) {
501
+ if (last_fun === kill_region) {
502
+ kill_region(start, end, dir);
503
+ } else {
504
+ cmd = cmd.substring(0, start) + cmd.substring(end);
505
+ cursor_pos = start;
506
+ }
507
+ }
508
+ }
509
+
510
+ function delete_char() {
511
+ delete_char_dir(1);
512
+ }
513
+
514
+ function control_d() {
515
+ if (cmd.length == 0) {
516
+ std.puts("\n");
517
+ return -3; /* exit read eval print loop */
518
+ } else {
519
+ delete_char_dir(1);
520
+ }
521
+ }
522
+
523
+ function backward_delete_char() {
524
+ delete_char_dir(-1);
525
+ }
526
+
527
+ function transpose_chars() {
528
+ var pos = cursor_pos;
529
+ if (cmd.length > 1 && pos > 0) {
530
+ if (pos == cmd.length)
531
+ pos--;
532
+ cmd = cmd.substring(0, pos - 1) + cmd.substring(pos, pos + 1) +
533
+ cmd.substring(pos - 1, pos) + cmd.substring(pos + 1);
534
+ cursor_pos = pos + 1;
535
+ }
536
+ }
537
+
538
+ function transpose_words() {
539
+ var p1 = skip_word_backward(cursor_pos);
540
+ var p2 = skip_word_forward(p1);
541
+ var p4 = skip_word_forward(cursor_pos);
542
+ var p3 = skip_word_backward(p4);
543
+
544
+ if (p1 < p2 && p2 <= cursor_pos && cursor_pos <= p3 && p3 < p4) {
545
+ cmd = cmd.substring(0, p1) + cmd.substring(p3, p4) +
546
+ cmd.substring(p2, p3) + cmd.substring(p1, p2);
547
+ cursor_pos = p4;
548
+ }
549
+ }
550
+
551
+ function upcase_word() {
552
+ var end = skip_word_forward(cursor_pos);
553
+ cmd = cmd.substring(0, cursor_pos) +
554
+ cmd.substring(cursor_pos, end).toUpperCase() +
555
+ cmd.substring(end);
556
+ }
557
+
558
+ function downcase_word() {
559
+ var end = skip_word_forward(cursor_pos);
560
+ cmd = cmd.substring(0, cursor_pos) +
561
+ cmd.substring(cursor_pos, end).toLowerCase() +
562
+ cmd.substring(end);
563
+ }
564
+
565
+ function kill_region(start, end, dir) {
566
+ var s = cmd.substring(start, end);
567
+ if (last_fun !== kill_region)
568
+ clip_board = s;
569
+ else if (dir < 0)
570
+ clip_board = s + clip_board;
571
+ else
572
+ clip_board = clip_board + s;
573
+
574
+ cmd = cmd.substring(0, start) + cmd.substring(end);
575
+ if (cursor_pos > end)
576
+ cursor_pos -= end - start;
577
+ else if (cursor_pos > start)
578
+ cursor_pos = start;
579
+ this_fun = kill_region;
580
+ }
581
+
582
+ function kill_line() {
583
+ kill_region(cursor_pos, cmd.length, 1);
584
+ }
585
+
586
+ function backward_kill_line() {
587
+ kill_region(0, cursor_pos, -1);
588
+ }
589
+
590
+ function kill_word() {
591
+ kill_region(cursor_pos, skip_word_forward(cursor_pos), 1);
592
+ }
593
+
594
+ function backward_kill_word() {
595
+ kill_region(skip_word_backward(cursor_pos), cursor_pos, -1);
596
+ }
597
+
598
+ function yank() {
599
+ insert(clip_board);
600
+ }
601
+
602
+ function control_c() {
603
+ if (last_fun === control_c) {
604
+ std.puts("\n");
605
+ exit(0);
606
+ } else {
607
+ std.puts("\n(Press Ctrl-C again to quit)\n");
608
+ readline_print_prompt();
609
+ }
610
+ }
611
+
612
+ function reset() {
613
+ cmd = "";
614
+ cursor_pos = 0;
615
+ }
616
+
617
+ // returns true if |line| looks something like "object.prop"
618
+ function is_named_property(line, end) {
619
+ var pos = end;
620
+ while (pos > 0 && is_word(line[pos - 1]))
621
+ pos--;
622
+ while (pos > 0 && is_blank(line[pos - 1]))
623
+ pos--;
624
+ return pos > 0 && line[pos - 1] === ".";
625
+ }
626
+
627
+ function get_context_word(line, end) {
628
+ var pos = end;
629
+ while (pos > 0 && is_word(line[pos - 1]))
630
+ pos--;
631
+ return line.slice(pos, end);
632
+ }
633
+
634
+ function get_context_object(line, pos) {
635
+ if (pos <= 0)
636
+ return g;
637
+ var c = line[pos - 1];
638
+ if (pos === 1 && (c === '\\' || c === '.'))
639
+ return directives;
640
+ if ("'\"`@#)]}\\".indexOf(c) >= 0)
641
+ return void 0;
642
+ if (c === ".") {
643
+ pos--;
644
+ switch (c = line[pos - 1]) {
645
+ case '\'':
646
+ case '\"':
647
+ case '`':
648
+ return "a";
649
+ case ']':
650
+ return []; // incorrect for a[b].<TAB>
651
+ case '/':
652
+ return / /;
653
+ default:
654
+ if (is_word(c)) {
655
+ var base = get_context_word(line, pos);
656
+ var base_pos = pos - base.length;
657
+ if (base === 'true' || base === 'false')
658
+ return true;
659
+ if (base === 'null')
660
+ return null;
661
+ if (base === 'this')
662
+ return g;
663
+ if (!isNaN(+base)) // number literal, incorrect for 1.<TAB>
664
+ return 0;
665
+ var obj = get_context_object(line, base_pos);
666
+ if (obj === null || obj === void 0)
667
+ return obj;
668
+ if (typeof obj[base] !== 'undefined')
669
+ return obj[base];
670
+ // Check if `base` is a set of regexp flags
671
+ // TODO(chqrlie): this is incorrect for a/i<TAB>...
672
+ // Should use colorizer to determine the token type
673
+ if (base_pos >= 3 && line[base_pos - 1] === '/' && base.match(/^[dgimsuvy]+$/))
674
+ return RegExp();
675
+ // base is a local identifier, complete as generic object
676
+ }
677
+ break;
678
+ }
679
+ return {};
680
+ }
681
+ return g;
682
+ }
683
+
684
+ function get_completions(line, pos) {
685
+ var s, obj, ctx_obj, r, i, j, paren;
686
+
687
+ s = get_context_word(line, pos);
688
+ ctx_obj = get_context_object(line, pos - s.length);
689
+ r = [];
690
+ if (!is_named_property(line, pos)) {
691
+ for (const kw of keywords) {
692
+ if (kw.startsWith(s))
693
+ r.push(kw);
694
+ }
695
+ }
696
+ /* enumerate properties from object and its prototype chain,
697
+ add non-numeric regular properties with s as e prefix
698
+ */
699
+ for (i = 0, obj = ctx_obj; i < 10 && obj !== null && obj !== void 0; i++) {
700
+ var props = Object.getOwnPropertyNames(obj);
701
+ /* add non-numeric regular properties */
702
+ for (j = 0; j < props.length; j++) {
703
+ var prop = props[j];
704
+ if (typeof prop == "string" && ""+(+prop) != prop && prop.startsWith(s))
705
+ r.push(prop);
706
+ }
707
+ obj = Object.getPrototypeOf(obj);
708
+ }
709
+ if (r.length > 1) {
710
+ /* sort list with internal names last and remove duplicates */
711
+ function symcmp(a, b) {
712
+ if (a[0] != b[0]) {
713
+ if (a[0] == '_')
714
+ return 1;
715
+ if (b[0] == '_')
716
+ return -1;
717
+ }
718
+ if (a < b)
719
+ return -1;
720
+ if (a > b)
721
+ return +1;
722
+ return 0;
723
+ }
724
+ r.sort(symcmp);
725
+ for(i = j = 1; i < r.length; i++) {
726
+ if (r[i] != r[i - 1])
727
+ r[j++] = r[i];
728
+ }
729
+ r.length = j;
730
+ }
731
+ /* 'tab' = list of completions, 'pos' = cursor position inside
732
+ the completions */
733
+ return { tab: r, pos: s.length, ctx: ctx_obj };
734
+ }
735
+
736
+ function completion() {
737
+ var tab, res, s, i, j, len, t, max_width, col, n_cols, row, n_rows;
738
+ res = get_completions(cmd, cursor_pos);
739
+ tab = res.tab;
740
+ if (tab.length === 0)
741
+ return;
742
+ s = tab[0];
743
+ len = s.length;
744
+ /* add the chars which are identical in all the completions */
745
+ for(i = 1; i < tab.length; i++) {
746
+ t = tab[i];
747
+ for(j = 0; j < len; j++) {
748
+ if (t[j] !== s[j]) {
749
+ len = j;
750
+ break;
751
+ }
752
+ }
753
+ }
754
+ for(i = res.pos; i < len; i++) {
755
+ insert(s[i]);
756
+ }
757
+ if (last_fun === completion && tab.length == 1) {
758
+ /* append parentheses to function names */
759
+ s = tab[0];
760
+ var m = res.ctx[s];
761
+ if (typeof m == "function") {
762
+ insert('(');
763
+ if (m.length == 0)
764
+ insert(')');
765
+ } else if (typeof m == "object" ||
766
+ typeof m == "undefined" && s == "this") {
767
+ insert('.');
768
+ }
769
+ }
770
+ /* show the possible completions */
771
+ if (last_fun === completion && tab.length >= 2) {
772
+ max_width = 0;
773
+ for(i = 0; i < tab.length; i++)
774
+ max_width = Math.max(max_width, tab[i].length);
775
+ max_width += 2;
776
+ n_cols = Math.max(1, Math.floor((term_width + 1) / max_width));
777
+ n_rows = Math.ceil(tab.length / n_cols);
778
+ std.puts("\n");
779
+ /* display the sorted list column-wise */
780
+ for (row = 0; row < n_rows; row++) {
781
+ for (col = 0; col < n_cols; col++) {
782
+ i = col * n_rows + row;
783
+ if (i >= tab.length)
784
+ break;
785
+ s = tab[i];
786
+ if (col != n_cols - 1)
787
+ s = s.padEnd(max_width);
788
+ std.puts(s);
789
+ }
790
+ std.puts("\n");
791
+ }
792
+ /* show a new prompt */
793
+ readline_print_prompt();
794
+ }
795
+ }
796
+
797
+ var commands = { /* command table */
798
+ "\x01": beginning_of_line, /* ^A - bol */
799
+ "\x02": backward_char, /* ^B - backward-char */
800
+ "\x03": control_c, /* ^C - abort */
801
+ "\x04": control_d, /* ^D - delete-char or exit */
802
+ "\x05": end_of_line, /* ^E - eol */
803
+ "\x06": forward_char, /* ^F - forward-char */
804
+ "\x07": abort, /* ^G - bell */
805
+ "\x08": backward_delete_char, /* ^H - backspace */
806
+ "\x09": completion, /* ^I - history-search-backward */
807
+ "\x0a": accept_line, /* ^J - newline */
808
+ "\x0b": kill_line, /* ^K - delete to end of line */
809
+ "\x0c": clear_screen, /* ^L - clear screen */
810
+ "\x0d": accept_line, /* ^M - enter */
811
+ "\x0e": next_history, /* ^N - down */
812
+ "\x10": previous_history, /* ^P - up */
813
+ "\x11": quoted_insert, /* ^Q - quoted-insert */
814
+ "\x12": alert, /* ^R - reverse-search */
815
+ "\x13": alert, /* ^S - search */
816
+ "\x14": transpose_chars, /* ^T - transpose */
817
+ "\x17": backward_kill_word, /* ^W - backward_kill_word */
818
+ "\x18": reset, /* ^X - cancel */
819
+ "\x19": yank, /* ^Y - yank */
820
+ "\x1bOA": previous_history, /* ^[OA - up */
821
+ "\x1bOB": next_history, /* ^[OB - down */
822
+ "\x1bOC": forward_char, /* ^[OC - right */
823
+ "\x1bOD": backward_char, /* ^[OD - left */
824
+ "\x1bOF": forward_word, /* ^[OF - ctrl-right */
825
+ "\x1bOH": backward_word, /* ^[OH - ctrl-left */
826
+ "\x1b[1;5C": forward_word, /* ^[[1;5C - ctrl-right */
827
+ "\x1b[1;5D": backward_word, /* ^[[1;5D - ctrl-left */
828
+ "\x1b[1~": beginning_of_line, /* ^[[1~ - bol */
829
+ "\x1b[3~": delete_char, /* ^[[3~ - delete */
830
+ "\x1b[4~": end_of_line, /* ^[[4~ - eol */
831
+ "\x1b[5~": history_search_backward,/* ^[[5~ - page up */
832
+ "\x1b[6~": history_search_forward, /* ^[[5~ - page down */
833
+ "\x1b[A": previous_history, /* ^[[A - up */
834
+ "\x1b[B": next_history, /* ^[[B - down */
835
+ "\x1b[C": forward_char, /* ^[[C - right */
836
+ "\x1b[D": backward_char, /* ^[[D - left */
837
+ "\x1b[F": end_of_line, /* ^[[F - end */
838
+ "\x1b[H": beginning_of_line, /* ^[[H - home */
839
+ "\x1b\x7f": backward_kill_word, /* M-C-? - backward_kill_word */
840
+ "\x1bb": backward_word, /* M-b - backward_word */
841
+ "\x1bd": kill_word, /* M-d - kill_word */
842
+ "\x1bf": forward_word, /* M-f - backward_word */
843
+ "\x1bk": backward_kill_line, /* M-k - backward_kill_line */
844
+ "\x1bl": downcase_word, /* M-l - downcase_word */
845
+ "\x1bt": transpose_words, /* M-t - transpose_words */
846
+ "\x1bu": upcase_word, /* M-u - upcase_word */
847
+ "\x7f": backward_delete_char, /* ^? - delete */
848
+ };
849
+
850
+ function dupstr(str, count) {
851
+ var res = "";
852
+ while (count-- > 0)
853
+ res += str;
854
+ return res;
855
+ }
856
+
857
+ var readline_keys;
858
+ var readline_state;
859
+ var readline_cb;
860
+
861
+ function readline_print_prompt()
862
+ {
863
+ std.puts(prompt);
864
+ term_cursor_x = ucs_length(prompt) % term_width;
865
+ last_cmd = "";
866
+ last_cursor_pos = 0;
867
+ }
868
+
869
+ function readline_start(defstr, cb) {
870
+ cmd = defstr || "";
871
+ cursor_pos = cmd.length;
872
+ history_index = history.length;
873
+ readline_cb = cb;
874
+
875
+ prompt = pstate;
876
+
877
+ if (mexpr) {
878
+ prompt += dupstr(" ", plen - prompt.length);
879
+ prompt += ps2;
880
+ } else {
881
+ if (show_time) {
882
+ var t = eval_time / 1000;
883
+ prompt += t.toFixed(6) + " ";
884
+ }
885
+ plen = prompt.length;
886
+ prompt += ps1;
887
+ }
888
+ readline_print_prompt();
889
+ update();
890
+ readline_state = 0;
891
+ }
892
+
893
+ function handle_char(c1) {
894
+ var c;
895
+ c = String.fromCodePoint(c1);
896
+ switch(readline_state) {
897
+ case 0:
898
+ if (c == '\x1b') { /* '^[' - ESC */
899
+ readline_keys = c;
900
+ readline_state = 1;
901
+ } else {
902
+ handle_key(c);
903
+ }
904
+ break;
905
+ case 1: /* '^[ */
906
+ readline_keys += c;
907
+ if (c == '[') {
908
+ readline_state = 2;
909
+ } else if (c == 'O') {
910
+ readline_state = 3;
911
+ } else {
912
+ handle_key(readline_keys);
913
+ readline_state = 0;
914
+ }
915
+ break;
916
+ case 2: /* '^[[' - CSI */
917
+ readline_keys += c;
918
+ if (!(c == ';' || (c >= '0' && c <= '9'))) {
919
+ handle_key(readline_keys);
920
+ readline_state = 0;
921
+ }
922
+ break;
923
+ case 3: /* '^[O' - ESC2 */
924
+ readline_keys += c;
925
+ handle_key(readline_keys);
926
+ readline_state = 0;
927
+ break;
928
+ }
929
+ }
930
+
931
+ function handle_key(keys) {
932
+ var fun;
933
+
934
+ if (quote_flag) {
935
+ if (ucs_length(keys) === 1)
936
+ insert(keys);
937
+ quote_flag = false;
938
+ } else if (fun = commands[keys]) {
939
+ this_fun = fun;
940
+ switch (fun(keys)) {
941
+ case -1:
942
+ readline_cb(cmd);
943
+ return;
944
+ case -2:
945
+ readline_cb(null);
946
+ return;
947
+ case -3:
948
+ /* uninstall a Ctrl-C signal handler */
949
+ os.signal(os.SIGINT, null);
950
+ /* uninstall the stdin read handler */
951
+ os.setReadHandler(term_fd, null);
952
+ save_history();
953
+ return;
954
+ }
955
+ last_fun = this_fun;
956
+ } else if (ucs_length(keys) === 1 && keys >= ' ') {
957
+ insert(keys);
958
+ last_fun = insert;
959
+ } else {
960
+ alert(); /* beep! */
961
+ }
962
+
963
+ cursor_pos = (cursor_pos < 0) ? 0 :
964
+ (cursor_pos > cmd.length) ? cmd.length : cursor_pos;
965
+ update();
966
+ }
967
+
968
+ function number_to_string(a, radix) {
969
+ var s;
970
+ if (!isFinite(a)) {
971
+ /* NaN, Infinite */
972
+ return a.toString();
973
+ } else {
974
+ if (a == 0) {
975
+ if (1 / a < 0)
976
+ s = "-0";
977
+ else
978
+ s = "0";
979
+ } else {
980
+ if (radix == 16 && a === Math.floor(a)) {
981
+ var s;
982
+ if (a < 0) {
983
+ a = -a;
984
+ s = "-";
985
+ } else {
986
+ s = "";
987
+ }
988
+ s += "0x" + a.toString(16);
989
+ } else {
990
+ s = a.toString();
991
+ }
992
+ }
993
+ return s;
994
+ }
995
+ }
996
+
997
+ function bigint_to_string(a, radix) {
998
+ var s;
999
+ if (radix == 16) {
1000
+ var s;
1001
+ if (a < 0) {
1002
+ a = -a;
1003
+ s = "-";
1004
+ } else {
1005
+ s = "";
1006
+ }
1007
+ s += "0x" + a.toString(16);
1008
+ } else {
1009
+ s = a.toString();
1010
+ }
1011
+ return s + "n";
1012
+ }
1013
+
1014
+ var util = {};
1015
+ util.inspect = function(val, show_hidden, max_depth, use_colors) {
1016
+ var options = {};
1017
+ if (typeof show_hidden === 'object' && show_hidden !== null) {
1018
+ options = show_hidden;
1019
+ show_hidden = options.showHidden;
1020
+ max_depth = options.depth;
1021
+ use_colors = options.colors;
1022
+ }
1023
+ function set(opt, def) {
1024
+ return (typeof opt === 'undefined') ? def : (opt === null) ? Infinity : opt;
1025
+ }
1026
+ if (typeof show_hidden !== 'boolean')
1027
+ show_hidden = false;
1028
+ max_depth = set(max_depth, 2);
1029
+ use_colors = set(use_colors, true);
1030
+ var breakLength = set(options.breakLength, Math.min(term_width, 80));
1031
+ var maxArrayLength = set(options.maxArrayLength, 100);
1032
+ var maxObjectLength = set(options.maxObjectLength, maxArrayLength + 10);
1033
+ var maxStringLength = set(options.maxStringLength, 78);
1034
+ var refs = [{}]; /* list of circular references */
1035
+ var stack = []; /* stack of pending objects */
1036
+ var tokens = []; /* list of generated tokens */
1037
+ var output = []; /* list of output fragments */
1038
+ var last_style = 'none';
1039
+
1040
+ function quote_str(s) {
1041
+ if (s.includes("'"))
1042
+ return JSON.stringify(s);
1043
+ s = JSON.stringify(s).slice(1, -1).replaceAll('\\"', '"');
1044
+ return `'${s}'`;
1045
+ }
1046
+ function push_token(s) {
1047
+ tokens.push("" + s);
1048
+ }
1049
+ function append_token(s) {
1050
+ tokens[tokens.length - 1] += s;
1051
+ }
1052
+ function class_tag(o) {
1053
+ // get the class id of an object
1054
+ // works for boxed objects, Math, JSON, globalThis...
1055
+ return Object.prototype.toString.call(o).slice(8, -1);
1056
+ }
1057
+
1058
+ function print_rec(a, level) {
1059
+ var n, n0, i, k, keys, key, type, isarray, noindex, nokeys, brace, sep;
1060
+
1061
+ switch (type = typeof(a)) {
1062
+ case "undefined":
1063
+ case "boolean":
1064
+ push_token(a);
1065
+ break;
1066
+ case "number":
1067
+ push_token(number_to_string(a, hex_mode ? 16 : 10));
1068
+ break;
1069
+ case "bigint":
1070
+ push_token(bigint_to_string(a, hex_mode ? 16 : 10));
1071
+ break;
1072
+ case "string":
1073
+ if (a.length > maxStringLength)
1074
+ a = a.substring(0, maxStringLength) + "...";
1075
+ push_token(quote_str(a));
1076
+ break;
1077
+ case "symbol":
1078
+ push_token(String(a));
1079
+ break;
1080
+ case "object":
1081
+ case "function":
1082
+ if (a === null) {
1083
+ push_token(a);
1084
+ break;
1085
+ }
1086
+ if ((n = refs.indexOf(a)) >= 0) {
1087
+ push_token(`[Circular *${n}]`);
1088
+ break;
1089
+ }
1090
+ if ((n = stack.indexOf(a)) >= 0) {
1091
+ push_token(`[Circular *${refs.length}]`);
1092
+ refs.push(stack[n]);
1093
+ break;
1094
+ }
1095
+ var obj_index = tokens.length;
1096
+ var tag = class_tag(a);
1097
+ stack.push(a);
1098
+ // XXX: should have Proxy instances
1099
+ if (a instanceof Date) {
1100
+ push_token(`Date ${JSON.stringify(a.toGMTString())}`);
1101
+ } else if (a instanceof RegExp) {
1102
+ push_token(a.toString());
1103
+ } else if (a instanceof Boolean || a instanceof Number || a instanceof BigInt) {
1104
+ push_token(`[${tag}: ${a}]`);
1105
+ } else if (a instanceof String) {
1106
+ push_token(`[${tag}: ${quote_str(a)}]`);
1107
+ len = a.length;
1108
+ noindex = 1;
1109
+ } else if (Array.isArray(a)) {
1110
+ push_token("[");
1111
+ isarray = 1;
1112
+ } else if (tag.includes('Array') && a instanceof Uint8Array.__proto__) {
1113
+ push_token(`${tag}(${a.length}) [`);
1114
+ isarray = 1;
1115
+ } else if (type === 'function') {
1116
+ if (a.name)
1117
+ push_token(`[Function: ${a.name}]`);
1118
+ else
1119
+ push_token(`[Function (anonymous)]`);
1120
+ } else {
1121
+ var cons = (a.constructor && a.constructor.name) || 'Object';
1122
+ if (tag !== 'Object') {
1123
+ push_token(`${cons} [${tag}] {`);
1124
+ } else if (a.__proto__ === null) {
1125
+ push_token(`[${cons}: null prototype] {`);
1126
+ } else if (cons !== 'Object') {
1127
+ push_token(`${cons} {`);
1128
+ } else {
1129
+ push_token("{");
1130
+ }
1131
+ brace = "}";
1132
+ }
1133
+ keys = null;
1134
+ n = 0;
1135
+ n0 = 0;
1136
+ k = 0;
1137
+ if (isarray) {
1138
+ brace = "]";
1139
+ var len = a.length;
1140
+ if (level > max_depth && len) {
1141
+ push_token("...");
1142
+ push_token(brace);
1143
+ return;
1144
+ }
1145
+ for (i = 0; i < len; i++) {
1146
+ k++;
1147
+ if (i in a) {
1148
+ print_rec(a[i], level + 1);
1149
+ } else {
1150
+ var start = i;
1151
+ while (i + 1 < len && !((i + 1) in a))
1152
+ i++;
1153
+ if (i > start)
1154
+ push_token(`<${i - start + 1} empty items>`);
1155
+ else
1156
+ push_token("<empty>");
1157
+ }
1158
+ if (k >= maxArrayLength && len - k > 5) {
1159
+ push_token(`... ${len - k} more items`);
1160
+ break;
1161
+ }
1162
+ }
1163
+ noindex = 1;
1164
+ /* avoid using Object.keys for large arrays */
1165
+ if (i !== len && len > 1000)
1166
+ nokeys = 1;
1167
+ }
1168
+ if (!nokeys) {
1169
+ keys = show_hidden ? Object.getOwnPropertyNames(a) : Object.keys(a);
1170
+ n = keys.length;
1171
+ }
1172
+ if (noindex) {
1173
+ /* skip all index properties */
1174
+ for (; n0 < n; n0++) {
1175
+ i = +keys[n0];
1176
+ if (i !== (i >>> 0) || i >= len)
1177
+ break;
1178
+ }
1179
+ }
1180
+ if (n0 < n) {
1181
+ if (!brace) {
1182
+ append_token(" {");
1183
+ brace = "}";
1184
+ }
1185
+ if (level > max_depth && n0 < n) {
1186
+ push_token("...");
1187
+ push_token(brace);
1188
+ return;
1189
+ }
1190
+ for(i = n0; i < n; i++) {
1191
+ var key = keys[i];
1192
+ var desc = Object.getOwnPropertyDescriptor(a, key);
1193
+ if (!desc)
1194
+ continue;
1195
+ if (!desc.enumerable)
1196
+ push_token(`[${String(key)}]`);
1197
+ else
1198
+ if (+key === (key >>> 0) || key.match(/^[a-zA-Z_$][0-9a-zA-Z_$]*/))
1199
+ push_token(key);
1200
+ else
1201
+ push_token(quote_str(key));
1202
+ push_token(":");
1203
+ if ('value' in desc) {
1204
+ print_rec(desc.value, level + 1);
1205
+ } else {
1206
+ var fields = [];
1207
+ if (desc.get)
1208
+ fields.push("Getter");
1209
+ if (desc.set)
1210
+ fields.push("Setter");
1211
+ push_token(`[${fields.join('/')}]`);
1212
+ }
1213
+ k++;
1214
+ if (k > maxObjectLength && n - k > 5) {
1215
+ push_token(`... ${n - k} more properties`);
1216
+ break;
1217
+ }
1218
+ }
1219
+ }
1220
+ if (brace)
1221
+ push_token(brace);
1222
+ stack.pop(a);
1223
+ if ((i = refs.indexOf(a)) > 0)
1224
+ tokens[obj_index] = `<ref *${i}> ${tokens[obj_index]}`;
1225
+ break;
1226
+ default:
1227
+ push_token(String(a));
1228
+ break;
1229
+ }
1230
+ };
1231
+ function output_str(s, style) {
1232
+ if (use_colors) {
1233
+ if (last_style !== style) {
1234
+ output.push(colors.none);
1235
+ last_style = style;
1236
+ }
1237
+ if (style) {
1238
+ var color = colors[styles[style]];
1239
+ if (color)
1240
+ output.push(color);
1241
+ }
1242
+ }
1243
+ output.push(s);
1244
+ }
1245
+ function output_propname(s) {
1246
+ if (s[0] >= '0' && s[0] <= '9')
1247
+ output_str(s, 'number');
1248
+ else
1249
+ output_str(s, 'propname');
1250
+ output_str(": ");
1251
+ }
1252
+ function output_pretty(s) {
1253
+ if (!use_colors) {
1254
+ output_str(s);
1255
+ return;
1256
+ }
1257
+ while (s.length > 0) {
1258
+ var style = 'none';
1259
+ var chunk = s;
1260
+ var len = 0;
1261
+ var m = null;
1262
+ switch (s[0]) {
1263
+ case '"':
1264
+ style = 'string';
1265
+ m = s.match(/^"([^\\"]|\\.)*"/);
1266
+ break;
1267
+ case '\'':
1268
+ style = 'string';
1269
+ m = s.match(/^'([^\\']|\\.)*'/);
1270
+ break;
1271
+ case '/':
1272
+ style = 'regexp';
1273
+ break;
1274
+ case '<':
1275
+ m = s.match(/^\<[^\>]+\>/);
1276
+ if (m)
1277
+ style = 'annotation';
1278
+ break;
1279
+ case '[':
1280
+ m = s.match(/^\[[^\]]+\]/);
1281
+ if (m) {
1282
+ style = 'annotation';
1283
+ break;
1284
+ }
1285
+ /* fall thru */
1286
+ case ']':
1287
+ case '}':
1288
+ case ',':
1289
+ case ' ':
1290
+ style = 'other';
1291
+ len = 1;
1292
+ break;
1293
+ case '.':
1294
+ style = 'annotation';
1295
+ break;
1296
+ case '0': case '1': case '2': case '3': case '4':
1297
+ case '5': case '6': case '7': case '8': case '9':
1298
+ style = 'number';
1299
+ m = s.match(/^[0-9a-z_]+[.]?[0-9a-z_]*[eEpP]?[+-]?[0-9]*/);
1300
+ break;
1301
+ case '-':
1302
+ len = 1;
1303
+ break;
1304
+ default:
1305
+ if (is_block(s))
1306
+ len = s.length - 1;
1307
+ if (s.startsWith('Date'))
1308
+ style = 'date';
1309
+ else if (s.startsWith('Symbol'))
1310
+ style = 'symbol';
1311
+ else if (s === 'Infinity' || s === 'NaN')
1312
+ style = 'keyword';
1313
+ else if (s === 'true' || s === 'false')
1314
+ style = 'boolean';
1315
+ else if (s === 'null')
1316
+ style = 'null';
1317
+ else if (s === 'undefined')
1318
+ style = 'undefined';
1319
+ break;
1320
+ }
1321
+ if (m)
1322
+ len = m[0].length;
1323
+ if (len > 0)
1324
+ chunk = s.slice(0, len);
1325
+ output_str(chunk, style);
1326
+ s = s.slice(chunk.length);
1327
+ }
1328
+ }
1329
+ function is_block(s) {
1330
+ var c = s[s.length - 1];
1331
+ return c === '[' || c === '{';
1332
+ }
1333
+ function block_width(i) {
1334
+ var w = tokens[i].length;
1335
+ if (tokens[i + 1] === ":") {
1336
+ i += 2;
1337
+ w += 2 + tokens[i].length;
1338
+ }
1339
+ var width = w;
1340
+ if (is_block(tokens[i])) {
1341
+ var seplen = 1;
1342
+ while (++i < tokens.length) {
1343
+ width += seplen;
1344
+ var s = tokens[i];
1345
+ if (s === ']' || s === '}')
1346
+ break;
1347
+ [ i, w ] = block_width(i);
1348
+ width += w;
1349
+ seplen = 2;
1350
+ }
1351
+ }
1352
+ return [ i, width ];
1353
+ }
1354
+ function output_single(i, last) {
1355
+ var sep = "";
1356
+ while (i <= last) {
1357
+ var s = tokens[i++];
1358
+ if (s === ']' || s === '}') {
1359
+ if (sep.length > 1)
1360
+ output_str(" ");
1361
+ } else {
1362
+ output_str(sep);
1363
+ if (tokens[i] === ":") {
1364
+ output_propname(s);
1365
+ i++;
1366
+ s = tokens[i++];
1367
+ }
1368
+ }
1369
+ output_pretty(s);
1370
+ sep = is_block(s) ? " " : ", ";
1371
+ }
1372
+ }
1373
+ function output_spaces(s, count) {
1374
+ if (count > 0)
1375
+ s += " ".repeat(count);
1376
+ output_str(s);
1377
+ }
1378
+ function output_indent(indent, from) {
1379
+ var avail_width = breakLength - indent - 2;
1380
+ var [ last, width ] = block_width(from);
1381
+ if (width <= avail_width) {
1382
+ output_single(from, last);
1383
+ return [ last, width ];
1384
+ }
1385
+ if (tokens[from + 1] === ":") {
1386
+ output_propname(tokens[from]);
1387
+ from += 2;
1388
+ }
1389
+ output_pretty(tokens[from]);
1390
+ if (!is_block(tokens[from])) {
1391
+ return [ from, width ];
1392
+ }
1393
+ indent += 2;
1394
+ avail_width -= 2;
1395
+ var sep = "";
1396
+ var first = from + 1;
1397
+ var i, w;
1398
+ if (tokens[from].endsWith('[')) {
1399
+ /* array: try multiple columns for indexed values */
1400
+ var k = 0, col, cols;
1401
+ var tab = [];
1402
+ for (i = first; i < last; i++) {
1403
+ if (tokens[i][0] === '.' || tokens[i + 1] === ':')
1404
+ break;
1405
+ [ i, w ] = block_width(i);
1406
+ tab[k++] = w;
1407
+ }
1408
+ var colwidth;
1409
+ for (cols = Math.min(avail_width / 3, tab.length, 16); cols > 1; cols--) {
1410
+ colwidth = [];
1411
+ col = 0;
1412
+ for (k = 0; k < tab.length; k++) {
1413
+ colwidth[col] = Math.max(colwidth[col] || 0, tab[k] + 2);
1414
+ col = (col + 1) % cols;
1415
+ }
1416
+ w = 0;
1417
+ for (col = 0; col < cols; col++) {
1418
+ w += colwidth[col];
1419
+ }
1420
+ if (w <= avail_width)
1421
+ break;
1422
+ }
1423
+ if (cols > 1) {
1424
+ w = 0;
1425
+ col = cols - 1;
1426
+ for (i = first; i < last; i++) {
1427
+ if (tokens[i][0] === '.' || tokens[i + 1] === ':')
1428
+ break;
1429
+ w += sep.length;
1430
+ output_str(sep);
1431
+ sep = ",";
1432
+ if (col === cols - 1) {
1433
+ output_spaces("\n", indent);
1434
+ col = 0;
1435
+ } else {
1436
+ output_spaces("", colwidth[col++] - w);
1437
+ }
1438
+ [i, w] = output_indent(indent, i);
1439
+ }
1440
+ first = i;
1441
+ }
1442
+ }
1443
+ for (i = first; i < last; i++) {
1444
+ output_str(sep);
1445
+ sep = ",";
1446
+ output_spaces("\n", indent);
1447
+ [i, w] = output_indent(indent, i);
1448
+ }
1449
+ output_spaces("\n", indent -= 2);
1450
+ output_pretty(tokens[last]);
1451
+ return [last, breakLength];
1452
+ }
1453
+ print_rec(val, 0);
1454
+ output_indent(0, 0);
1455
+ output_str("");
1456
+ return output.join("");
1457
+ };
1458
+
1459
+ function print(val) {
1460
+ std.puts(util.inspect(val, { depth: show_depth, colors: show_colors, showHidden: show_hidden }));
1461
+ std.puts("\n");
1462
+ }
1463
+
1464
+ /* return true if the string was a directive */
1465
+ function handle_directive(a) {
1466
+ if (a === "?") {
1467
+ help();
1468
+ return true;
1469
+ }
1470
+ if (a[0] !== '\\' && a[0] !== '.')
1471
+ return false;
1472
+ var pos = 1;
1473
+ while (pos < a.length && a[pos] !== ' ') {
1474
+ pos++;
1475
+ }
1476
+ var cmd = a.substring(1, pos);
1477
+ var partial = 0;
1478
+ var fun;
1479
+ for (var p in directives) {
1480
+ if (p.startsWith(cmd)) {
1481
+ fun = directives[p];
1482
+ partial++;
1483
+ if (p === cmd) {
1484
+ partial = 0;
1485
+ break;
1486
+ }
1487
+ }
1488
+ }
1489
+ if (fun && partial < 2) {
1490
+ fun(a.substring(pos).trim());
1491
+ } else {
1492
+ std.puts(`Unknown directive: ${cmd}\n`);
1493
+ }
1494
+ return true;
1495
+ }
1496
+
1497
+ function help() {
1498
+ var sel = (n) => n ? "*": " ";
1499
+ std.puts(".help print this help\n" +
1500
+ ".x " + sel(hex_mode) + "hexadecimal number display\n" +
1501
+ ".dec " + sel(!hex_mode) + "decimal number display\n" +
1502
+ ".time " + sel(show_time) + "toggle timing display\n" +
1503
+ ".strict " + sel(use_strict) + "toggle strict mode evaluation\n" +
1504
+ `.depth set object depth (current: ${show_depth})\n` +
1505
+ ".hidden " + sel(show_hidden) + "toggle hidden properties display\n" +
1506
+ ".color " + sel(show_colors) + "toggle colored output\n" +
1507
+ ".dark " + sel(styles == themes.dark) + "select dark color theme\n" +
1508
+ ".light " + sel(styles == themes.light) + "select light color theme\n" +
1509
+ ".clear clear the terminal\n" +
1510
+ ".load load source code from a file\n" +
1511
+ ".quit exit\n");
1512
+ }
1513
+
1514
+ function load(s) {
1515
+ if (s.lastIndexOf(".") <= s.lastIndexOf("/"))
1516
+ s += ".js";
1517
+ try {
1518
+ std.loadScript(s);
1519
+ } catch (e) {
1520
+ std.puts(`${e}\n`);
1521
+ }
1522
+ }
1523
+
1524
+ function exit(e) {
1525
+ save_history();
1526
+ std.exit(e);
1527
+ }
1528
+
1529
+ function to_bool(s, def) {
1530
+ return s ? "1 true yes Yes".includes(s) : def;
1531
+ }
1532
+
1533
+ var directives = Object.setPrototypeOf({
1534
+ "help": help,
1535
+ "load": load,
1536
+ "x": (s) => { hex_mode = to_bool(s, true); },
1537
+ "dec": (s) => { hex_mode = !to_bool(s, true); },
1538
+ "time": (s) => { show_time = to_bool(s, !show_time); },
1539
+ "strict": (s) => { use_strict = to_bool(s, !use_strict); },
1540
+ "depth": (s) => { show_depth = +s || 2; },
1541
+ "hidden": (s) => { show_hidden = to_bool(s, !show_hidden); },
1542
+ "color": (s) => { show_colors = to_bool(s, !show_colors); },
1543
+ "dark": () => { styles = themes.dark; },
1544
+ "light": () => { styles = themes.light; },
1545
+ "clear": () => { std.puts("\x1b[H\x1b[J") },
1546
+ "quit": () => { exit(0); },
1547
+ }, null);
1548
+
1549
+ function cmd_start() {
1550
+ std.puts('QuickJS-ng - Type ".help" for help\n');
1551
+ cmd_readline_start();
1552
+ }
1553
+
1554
+ function cmd_readline_start() {
1555
+ readline_start(dupstr(" ", level), readline_handle_cmd);
1556
+ }
1557
+
1558
+ function readline_handle_cmd(expr) {
1559
+ if (!handle_cmd(expr)) {
1560
+ cmd_readline_start();
1561
+ }
1562
+ }
1563
+
1564
+ /* return true if async termination */
1565
+ function handle_cmd(expr) {
1566
+ if (!expr)
1567
+ return false;
1568
+ if (mexpr) {
1569
+ expr = mexpr + '\n' + expr;
1570
+ } else {
1571
+ if (handle_directive(expr))
1572
+ return false;
1573
+ }
1574
+ var colorstate = colorize_js(expr);
1575
+ pstate = colorstate[0];
1576
+ level = colorstate[1];
1577
+ if (pstate) {
1578
+ mexpr = expr;
1579
+ return false;
1580
+ }
1581
+ mexpr = "";
1582
+
1583
+ eval_and_print(expr);
1584
+
1585
+ return true;
1586
+ }
1587
+
1588
+ function eval_and_print(expr) {
1589
+ var result;
1590
+
1591
+ if (use_strict)
1592
+ expr = '"use strict"; void 0;' + expr;
1593
+ eval_start_time = os.now();
1594
+ /* eval as a script */
1595
+ result = Promise.try(std.evalScript, expr, { backtrace_barrier: true, async: true });
1596
+ result.then(print_eval_result, print_eval_error);
1597
+ }
1598
+
1599
+ function print_eval_result(result) {
1600
+ result = result.value;
1601
+ eval_time = os.now() - eval_start_time;
1602
+ print(result);
1603
+ /* set the last result */
1604
+ g._ = result;
1605
+
1606
+ handle_cmd_end();
1607
+ }
1608
+
1609
+ function print_eval_error(error) {
1610
+ if (show_colors) {
1611
+ std.puts(colors[styles.error]);
1612
+ }
1613
+ if (error instanceof Error) {
1614
+ std.puts(error);
1615
+ std.puts('\n');
1616
+ if (error.stack) {
1617
+ std.puts(error.stack);
1618
+ }
1619
+ } else {
1620
+ std.puts("Throw: ");
1621
+ std.puts(error);
1622
+ std.puts('\n');
1623
+ }
1624
+
1625
+ if (show_colors) {
1626
+ std.puts(colors.none);
1627
+ }
1628
+
1629
+ handle_cmd_end();
1630
+ }
1631
+
1632
+ function handle_cmd_end() {
1633
+ level = 0;
1634
+
1635
+ /* run the garbage collector after each command */
1636
+ std.gc();
1637
+
1638
+ cmd_readline_start();
1639
+ }
1640
+
1641
+ function colorize_js(str) {
1642
+ var i, c, start, n = str.length;
1643
+ var style, state = "", level = 0;
1644
+ var primary, can_regex = 1;
1645
+ var r = [];
1646
+
1647
+ function push_state(c) { state += c; }
1648
+ function last_state(c) { return state.substring(state.length - 1); }
1649
+ function pop_state(c) {
1650
+ var c = last_state();
1651
+ state = state.substring(0, state.length - 1);
1652
+ return c;
1653
+ }
1654
+
1655
+ function parse_block_comment() {
1656
+ style = 'comment';
1657
+ push_state('/');
1658
+ for (i++; i < n - 1; i++) {
1659
+ if (str[i] == '*' && str[i + 1] == '/') {
1660
+ i += 2;
1661
+ pop_state('/');
1662
+ break;
1663
+ }
1664
+ }
1665
+ }
1666
+
1667
+ function parse_line_comment() {
1668
+ style = 'comment';
1669
+ for (i++; i < n; i++) {
1670
+ if (str[i] == '\n') {
1671
+ break;
1672
+ }
1673
+ }
1674
+ }
1675
+
1676
+ function parse_string(delim) {
1677
+ style = 'string';
1678
+ push_state(delim);
1679
+ while (i < n) {
1680
+ c = str[i++];
1681
+ if (c == '\n') {
1682
+ style = 'error';
1683
+ continue;
1684
+ }
1685
+ if (c == '\\') {
1686
+ if (i >= n)
1687
+ break;
1688
+ i++;
1689
+ } else
1690
+ if (c == delim) {
1691
+ pop_state();
1692
+ break;
1693
+ }
1694
+ }
1695
+ }
1696
+
1697
+ function parse_regex() {
1698
+ style = 'regexp';
1699
+ push_state('/');
1700
+ while (i < n) {
1701
+ c = str[i++];
1702
+ if (c == '\n') {
1703
+ style = 'error';
1704
+ continue;
1705
+ }
1706
+ if (c == '\\') {
1707
+ if (i < n) {
1708
+ i++;
1709
+ }
1710
+ continue;
1711
+ }
1712
+ if (last_state() == '[') {
1713
+ if (c == ']') {
1714
+ pop_state()
1715
+ }
1716
+ // ECMA 5: ignore '/' inside char classes
1717
+ continue;
1718
+ }
1719
+ if (c == '[') {
1720
+ push_state('[');
1721
+ if (str[i] == '[' || str[i] == ']')
1722
+ i++;
1723
+ continue;
1724
+ }
1725
+ if (c == '/') {
1726
+ pop_state();
1727
+ while (i < n && is_word(str[i]))
1728
+ i++;
1729
+ break;
1730
+ }
1731
+ }
1732
+ }
1733
+
1734
+ function parse_number() {
1735
+ style = 'number';
1736
+ // TODO(chqrlie) parse partial number syntax
1737
+ // TODO(chqrlie) special case bignum
1738
+ while (i < n && (is_word(str[i]) || (str[i] == '.' && (i == n - 1 || str[i + 1] != '.')))) {
1739
+ i++;
1740
+ }
1741
+ }
1742
+
1743
+ var js_keywords = "|" +
1744
+ "break|case|catch|continue|debugger|default|delete|do|" +
1745
+ "else|finally|for|function|if|in|instanceof|new|" +
1746
+ "return|switch|this|throw|try|typeof|while|with|" +
1747
+ "class|const|enum|import|export|extends|super|" +
1748
+ "implements|interface|let|package|private|protected|" +
1749
+ "public|static|yield|" +
1750
+ "undefined|null|true|false|Infinity|NaN|" +
1751
+ "eval|arguments|" +
1752
+ "await|";
1753
+
1754
+ var js_no_regex = "|this|super|undefined|null|true|false|Infinity|NaN|arguments|";
1755
+ var js_types = "|void|var|";
1756
+
1757
+ function parse_identifier() {
1758
+ can_regex = 1;
1759
+
1760
+ while (i < n && is_word(str[i]))
1761
+ i++;
1762
+
1763
+ var s = str.substring(start, i);
1764
+ var w = '|' + s + '|';
1765
+
1766
+ if (js_keywords.indexOf(w) >= 0) {
1767
+ style = 'keyword';
1768
+ if (s === 'true' || s === 'false')
1769
+ style = 'boolean';
1770
+ else if (s === 'true' || s === 'false')
1771
+ style = 'boolean';
1772
+ else if (s === 'null')
1773
+ style = 'null';
1774
+ else if (s === 'undefined')
1775
+ style = 'undefined';
1776
+ if (js_no_regex.indexOf(w) >= 0)
1777
+ can_regex = 0;
1778
+ return;
1779
+ }
1780
+
1781
+ var i1 = i;
1782
+ while (i1 < n && str[i1] == ' ')
1783
+ i1++;
1784
+
1785
+ if (i1 < n && str[i1] == '(') {
1786
+ style = 'function';
1787
+ return;
1788
+ }
1789
+
1790
+ if (js_types.indexOf(w) >= 0) {
1791
+ style = 'type';
1792
+ return;
1793
+ }
1794
+
1795
+ style = 'identifier';
1796
+ can_regex = 0;
1797
+ }
1798
+
1799
+ function set_style(from, to) {
1800
+ while (r.length < from)
1801
+ r.push('default');
1802
+ while (r.length < to)
1803
+ r.push(style);
1804
+ }
1805
+
1806
+ for (i = 0; i < n;) {
1807
+ style = null;
1808
+ start = i;
1809
+ switch (c = str[i++]) {
1810
+ case ' ':
1811
+ case '\t':
1812
+ case '\r':
1813
+ case '\n':
1814
+ continue;
1815
+ case '+':
1816
+ case '-':
1817
+ if (i < n && str[i] == c) {
1818
+ i++;
1819
+ continue;
1820
+ }
1821
+ can_regex = 1;
1822
+ continue;
1823
+ case '/':
1824
+ if (i < n && str[i] == '*') { // block comment
1825
+ parse_block_comment();
1826
+ break;
1827
+ }
1828
+ if (i < n && str[i] == '/') { // line comment
1829
+ parse_line_comment();
1830
+ break;
1831
+ }
1832
+ if (can_regex) {
1833
+ parse_regex();
1834
+ can_regex = 0;
1835
+ break;
1836
+ }
1837
+ can_regex = 1;
1838
+ continue;
1839
+ case '\'':
1840
+ case '\"':
1841
+ case '`':
1842
+ parse_string(c);
1843
+ can_regex = 0;
1844
+ break;
1845
+ case '(':
1846
+ case '[':
1847
+ case '{':
1848
+ can_regex = 1;
1849
+ level++;
1850
+ push_state(c);
1851
+ continue;
1852
+ case ')':
1853
+ case ']':
1854
+ case '}':
1855
+ can_regex = 0;
1856
+ if (level > 0 && is_balanced(last_state(), c)) {
1857
+ level--;
1858
+ pop_state();
1859
+ continue;
1860
+ }
1861
+ style = 'error';
1862
+ break;
1863
+ default:
1864
+ if (is_digit(c)) {
1865
+ parse_number();
1866
+ can_regex = 0;
1867
+ break;
1868
+ }
1869
+ if (is_word(c)) {
1870
+ parse_identifier();
1871
+ break;
1872
+ }
1873
+ can_regex = 1;
1874
+ continue;
1875
+ }
1876
+ if (style)
1877
+ set_style(start, i);
1878
+ }
1879
+ set_style(n, n);
1880
+ return [ state, level, r ];
1881
+ }
1882
+
1883
+ function config_file(s) {
1884
+ var xdg_state_home = std.getenv("XDG_STATE_HOME");
1885
+ if (xdg_state_home && xdg_state_home[0] === "/") return xdg_state_home + "/" + s;
1886
+ var home = std.getenv("HOME");
1887
+ if (os.platform === "linux" && home) xdg_state_home = home + "/.local/state";
1888
+ if (os.stat(xdg_state_home + "/")[1] === 0) return xdg_state_home + "/" + s;
1889
+ return (home || std.getenv("USERPROFILE") || ".") + "/." + s;
1890
+ }
1891
+ function save_history() {
1892
+ var s = history.slice(-1000).join('\n').trim();
1893
+ if (s) {
1894
+ try {
1895
+ var f = std.open(config_file("qjs_history"), "w");
1896
+ f.puts(s + '\n');
1897
+ f.close();
1898
+ } catch (e) {
1899
+ }
1900
+ }
1901
+ }
1902
+ function load_history() {
1903
+ var a = std.loadFile(config_file("qjs_history"));
1904
+ if (a) {
1905
+ history = a.trim().split('\n');
1906
+ history_index = history.length;
1907
+ }
1908
+ }
1909
+ function load_config() {
1910
+ var m, s = std.getenv("COLORFGBG");
1911
+ if (s && (m = s.match(/(\d+);(\d+)/))) {
1912
+ if (+m[2] !== 0) { // light background
1913
+ styles = themes.light;
1914
+ }
1915
+ }
1916
+ s = std.getenv("NO_COLOR"); // https://no-color.org/
1917
+ if (s && +s[0] !== 0) {
1918
+ show_colors = false;
1919
+ }
1920
+ }
1921
+
1922
+ load_config();
1923
+ load_history();
1924
+ termInit();
1925
+ cmd_start();
1926
+
1927
+ })(globalThis);