@mirascript/mirascript 0.1.14 → 0.1.16

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 (216) hide show
  1. package/dist/{chunk-Q74RKZ7O.js → chunk-LU4ZKFF6.js} +1420 -607
  2. package/dist/chunk-LU4ZKFF6.js.map +6 -0
  3. package/dist/chunk-RIT53WVY.js +1 -0
  4. package/dist/chunk-RLWIIOH5.js +12 -0
  5. package/dist/chunk-RLWIIOH5.js.map +6 -0
  6. package/dist/{chunk-55FKP56O.js → chunk-YZGL3D7L.js} +741 -1361
  7. package/dist/chunk-YZGL3D7L.js.map +6 -0
  8. package/dist/cli/index.js +11 -67
  9. package/dist/cli/index.js.map +2 -2
  10. package/dist/compiler/compile-fast.d.ts +1 -1
  11. package/dist/compiler/compile-fast.d.ts.map +1 -1
  12. package/dist/compiler/create-script.d.ts +10 -1
  13. package/dist/compiler/create-script.d.ts.map +1 -1
  14. package/dist/compiler/diagnostic.d.ts +1 -1
  15. package/dist/compiler/diagnostic.d.ts.map +1 -1
  16. package/dist/compiler/emit/constants.d.ts +3 -0
  17. package/dist/compiler/emit/constants.d.ts.map +1 -0
  18. package/dist/compiler/emit/consts.d.ts +6 -0
  19. package/dist/compiler/emit/consts.d.ts.map +1 -0
  20. package/dist/compiler/emit/globals.d.ts +17 -0
  21. package/dist/compiler/emit/globals.d.ts.map +1 -0
  22. package/dist/compiler/emit/index.d.ts +58 -0
  23. package/dist/compiler/emit/index.d.ts.map +1 -0
  24. package/dist/compiler/emit/sourcemap.d.ts +6 -0
  25. package/dist/compiler/emit/sourcemap.d.ts.map +1 -0
  26. package/dist/compiler/index.d.ts +3 -2
  27. package/dist/compiler/index.d.ts.map +1 -1
  28. package/dist/compiler/worker.js +1 -1
  29. package/dist/helpers/constants.d.ts +15 -0
  30. package/dist/helpers/constants.d.ts.map +1 -1
  31. package/dist/helpers/convert.d.ts +12 -0
  32. package/dist/helpers/convert.d.ts.map +1 -0
  33. package/dist/{vm → helpers}/error.d.ts +1 -1
  34. package/dist/helpers/error.d.ts.map +1 -0
  35. package/dist/helpers/serialize.d.ts +14 -5
  36. package/dist/helpers/serialize.d.ts.map +1 -1
  37. package/dist/helpers/types.d.ts +54 -0
  38. package/dist/helpers/types.d.ts.map +1 -0
  39. package/dist/index.js +11 -17
  40. package/dist/subtle.d.ts +3 -2
  41. package/dist/subtle.d.ts.map +1 -1
  42. package/dist/subtle.js +21 -15
  43. package/dist/vm/checkpoint.d.ts +9 -0
  44. package/dist/vm/checkpoint.d.ts.map +1 -0
  45. package/dist/vm/helpers.d.ts +4 -10
  46. package/dist/vm/helpers.d.ts.map +1 -1
  47. package/dist/vm/index.d.ts +3 -3
  48. package/dist/vm/index.d.ts.map +1 -1
  49. package/dist/vm/lib/global/bit.d.ts +7 -7
  50. package/dist/vm/lib/global/bit.d.ts.map +1 -1
  51. package/dist/vm/lib/global/debug.d.ts +2 -2
  52. package/dist/vm/lib/global/debug.d.ts.map +1 -1
  53. package/dist/vm/lib/global/index.d.ts +0 -1
  54. package/dist/vm/lib/global/index.d.ts.map +1 -1
  55. package/dist/vm/lib/global/json.d.ts +2 -2
  56. package/dist/vm/lib/global/json.d.ts.map +1 -1
  57. package/dist/vm/lib/global/math-additional.d.ts +1 -1
  58. package/dist/vm/lib/global/math-additional.d.ts.map +1 -1
  59. package/dist/vm/lib/global/math-arr.d.ts +5 -5
  60. package/dist/vm/lib/global/math-arr.d.ts.map +1 -1
  61. package/dist/vm/lib/global/math-unary.d.ts +26 -26
  62. package/dist/vm/lib/global/math-unary.d.ts.map +1 -1
  63. package/dist/vm/lib/global/math.d.ts +3 -3
  64. package/dist/vm/lib/global/math.d.ts.map +1 -1
  65. package/dist/vm/lib/global/sequence/all-any.d.ts +2 -2
  66. package/dist/vm/lib/global/sequence/all-any.d.ts.map +1 -1
  67. package/dist/vm/lib/global/sequence/entries.d.ts +5 -5
  68. package/dist/vm/lib/global/sequence/entries.d.ts.map +1 -1
  69. package/dist/vm/lib/global/sequence/find.d.ts +3 -3
  70. package/dist/vm/lib/global/sequence/find.d.ts.map +1 -1
  71. package/dist/vm/lib/global/sequence/flatten.d.ts +1 -1
  72. package/dist/vm/lib/global/sequence/flatten.d.ts.map +1 -1
  73. package/dist/vm/lib/global/sequence/len.d.ts +1 -1
  74. package/dist/vm/lib/global/sequence/len.d.ts.map +1 -1
  75. package/dist/vm/lib/global/sequence/map-filter.d.ts +3 -3
  76. package/dist/vm/lib/global/sequence/map-filter.d.ts.map +1 -1
  77. package/dist/vm/lib/global/sequence/repeat.d.ts +1 -1
  78. package/dist/vm/lib/global/sequence/repeat.d.ts.map +1 -1
  79. package/dist/vm/lib/global/sequence/reverse.d.ts +1 -1
  80. package/dist/vm/lib/global/sequence/reverse.d.ts.map +1 -1
  81. package/dist/vm/lib/global/sequence/sort.d.ts +2 -2
  82. package/dist/vm/lib/global/sequence/sort.d.ts.map +1 -1
  83. package/dist/vm/lib/global/sequence/with.d.ts +2 -2
  84. package/dist/vm/lib/global/sequence/with.d.ts.map +1 -1
  85. package/dist/vm/lib/global/sequence/zip.d.ts +1 -1
  86. package/dist/vm/lib/global/sequence/zip.d.ts.map +1 -1
  87. package/dist/vm/lib/global/string.d.ts +10 -10
  88. package/dist/vm/lib/global/string.d.ts.map +1 -1
  89. package/dist/vm/lib/global/time.d.ts +3 -13
  90. package/dist/vm/lib/global/time.d.ts.map +1 -1
  91. package/dist/vm/lib/global/to-primitive.d.ts +4 -4
  92. package/dist/vm/lib/global/to-primitive.d.ts.map +1 -1
  93. package/dist/vm/lib/helpers.d.ts +53 -0
  94. package/dist/vm/lib/helpers.d.ts.map +1 -0
  95. package/dist/vm/lib/index.d.ts +4 -0
  96. package/dist/vm/lib/index.d.ts.map +1 -0
  97. package/dist/vm/lib/{_loader.d.ts → loader.d.ts} +5 -5
  98. package/dist/vm/lib/loader.d.ts.map +1 -0
  99. package/dist/vm/lib/mod/index.d.ts +2 -0
  100. package/dist/vm/lib/mod/index.d.ts.map +1 -0
  101. package/dist/vm/lib/mod/matrix.d.ts +15 -0
  102. package/dist/vm/lib/mod/matrix.d.ts.map +1 -0
  103. package/dist/vm/operations.d.ts +4 -6
  104. package/dist/vm/operations.d.ts.map +1 -1
  105. package/dist/vm/types/boundary.d.ts +1 -1
  106. package/dist/vm/types/boundary.d.ts.map +1 -1
  107. package/dist/vm/types/context.d.ts +18 -12
  108. package/dist/vm/types/context.d.ts.map +1 -1
  109. package/dist/vm/types/extern.d.ts +1 -3
  110. package/dist/vm/types/extern.d.ts.map +1 -1
  111. package/dist/vm/types/function.d.ts +1 -6
  112. package/dist/vm/types/function.d.ts.map +1 -1
  113. package/dist/vm/types/index.d.ts +31 -17
  114. package/dist/vm/types/index.d.ts.map +1 -1
  115. package/dist/vm/types/module.d.ts +2 -4
  116. package/dist/vm/types/module.d.ts.map +1 -1
  117. package/dist/vm/types/wrapper.d.ts +0 -2
  118. package/dist/vm/types/wrapper.d.ts.map +1 -1
  119. package/package.json +7 -3
  120. package/src/cli/index.ts +1 -1
  121. package/src/compiler/compile-fast.ts +1 -2
  122. package/src/compiler/create-script.ts +12 -2
  123. package/src/compiler/diagnostic.ts +17 -8
  124. package/src/compiler/emit/constants.ts +2 -0
  125. package/src/compiler/emit/consts.ts +47 -0
  126. package/src/compiler/emit/globals.ts +39 -0
  127. package/src/compiler/{emit.ts → emit/index.ts} +18 -202
  128. package/src/compiler/emit/sourcemap.ts +163 -0
  129. package/src/compiler/index.ts +9 -9
  130. package/src/compiler/worker.ts +1 -1
  131. package/src/helpers/constants.ts +18 -1
  132. package/src/helpers/convert.ts +128 -0
  133. package/src/{vm → helpers}/error.ts +1 -1
  134. package/src/helpers/serialize.ts +72 -25
  135. package/src/helpers/types.ts +267 -0
  136. package/src/subtle.ts +3 -1
  137. package/src/vm/checkpoint.ts +42 -0
  138. package/src/vm/helpers.ts +9 -53
  139. package/src/vm/index.ts +3 -3
  140. package/src/vm/lib/global/bit.ts +8 -9
  141. package/src/vm/lib/global/debug.ts +5 -4
  142. package/src/vm/lib/global/index.ts +0 -1
  143. package/src/vm/lib/global/json.ts +2 -2
  144. package/src/vm/lib/global/math-additional.ts +2 -4
  145. package/src/vm/lib/global/math-arr.ts +1 -1
  146. package/src/vm/lib/global/math-unary.ts +2 -4
  147. package/src/vm/lib/global/math.ts +3 -4
  148. package/src/vm/lib/global/sequence/all-any.ts +11 -6
  149. package/src/vm/lib/global/sequence/entries.ts +3 -3
  150. package/src/vm/lib/global/sequence/find.ts +8 -7
  151. package/src/vm/lib/global/sequence/flatten.ts +2 -3
  152. package/src/vm/lib/global/sequence/len.ts +1 -1
  153. package/src/vm/lib/global/sequence/map-filter.ts +7 -6
  154. package/src/vm/lib/global/sequence/repeat.ts +2 -4
  155. package/src/vm/lib/global/sequence/reverse.ts +1 -1
  156. package/src/vm/lib/global/sequence/sort.ts +6 -5
  157. package/src/vm/lib/global/sequence/with.ts +22 -21
  158. package/src/vm/lib/global/sequence/zip.ts +4 -4
  159. package/src/vm/lib/global/string.ts +16 -27
  160. package/src/vm/lib/global/time.ts +59 -30
  161. package/src/vm/lib/global/to-primitive.ts +27 -18
  162. package/src/vm/lib/{_helpers.ts → helpers.ts} +129 -41
  163. package/src/vm/lib/index.ts +16 -0
  164. package/src/vm/lib/{_loader.ts → loader.ts} +3 -11
  165. package/src/vm/lib/mod/index.ts +1 -0
  166. package/src/vm/lib/{global/mod → mod}/matrix.ts +9 -7
  167. package/src/vm/operations.ts +33 -128
  168. package/src/vm/types/boundary.ts +10 -13
  169. package/src/vm/types/context.ts +36 -28
  170. package/src/vm/types/extern.ts +8 -15
  171. package/src/vm/types/function.ts +4 -19
  172. package/src/vm/types/index.ts +47 -25
  173. package/src/vm/types/module.ts +3 -7
  174. package/src/vm/types/wrapper.ts +1 -5
  175. package/dist/chunk-35JGBXRE.js +0 -1
  176. package/dist/chunk-55FKP56O.js.map +0 -6
  177. package/dist/chunk-Q74RKZ7O.js.map +0 -6
  178. package/dist/compiler/emit.d.ts +0 -5
  179. package/dist/compiler/emit.d.ts.map +0 -1
  180. package/dist/vm/error.d.ts.map +0 -1
  181. package/dist/vm/lib/_helpers.d.ts +0 -35
  182. package/dist/vm/lib/_helpers.d.ts.map +0 -1
  183. package/dist/vm/lib/_loader.d.ts.map +0 -1
  184. package/dist/vm/lib/global/mod/index.d.ts +0 -3
  185. package/dist/vm/lib/global/mod/index.d.ts.map +0 -1
  186. package/dist/vm/lib/global/mod/matrix.d.ts +0 -15
  187. package/dist/vm/lib/global/mod/matrix.d.ts.map +0 -1
  188. package/dist/vm/types/any.d.ts +0 -10
  189. package/dist/vm/types/any.d.ts.map +0 -1
  190. package/dist/vm/types/array.d.ts +0 -12
  191. package/dist/vm/types/array.d.ts.map +0 -1
  192. package/dist/vm/types/callable.d.ts +0 -5
  193. package/dist/vm/types/callable.d.ts.map +0 -1
  194. package/dist/vm/types/const.d.ts +0 -15
  195. package/dist/vm/types/const.d.ts.map +0 -1
  196. package/dist/vm/types/immutable.d.ts +0 -15
  197. package/dist/vm/types/immutable.d.ts.map +0 -1
  198. package/dist/vm/types/primitive.d.ts +0 -7
  199. package/dist/vm/types/primitive.d.ts.map +0 -1
  200. package/dist/vm/types/record.d.ts +0 -20
  201. package/dist/vm/types/record.d.ts.map +0 -1
  202. package/dist/vm/types/script.d.ts +0 -14
  203. package/dist/vm/types/script.d.ts.map +0 -1
  204. package/dist/vm/types/value.d.ts +0 -14
  205. package/dist/vm/types/value.d.ts.map +0 -1
  206. package/src/vm/lib/global/mod/index.ts +0 -4
  207. package/src/vm/types/any.ts +0 -33
  208. package/src/vm/types/array.ts +0 -19
  209. package/src/vm/types/callable.ts +0 -10
  210. package/src/vm/types/const.ts +0 -109
  211. package/src/vm/types/immutable.ts +0 -22
  212. package/src/vm/types/primitive.ts +0 -14
  213. package/src/vm/types/record.ts +0 -53
  214. package/src/vm/types/script.ts +0 -18
  215. package/src/vm/types/value.ts +0 -22
  216. /package/dist/{chunk-35JGBXRE.js.map → chunk-RIT53WVY.js.map} +0 -0
@@ -1,42 +1,31 @@
1
1
  import {
2
- $Add,
3
- $Call,
4
- $Div,
5
- $Format,
6
- $Mul,
7
- $Same,
8
- $Sub,
9
- $ToBoolean,
10
- $ToNumber,
11
- $ToString,
12
- $Type,
13
- Cp,
14
2
  DiagnosticCode,
15
- Element,
16
- GlobalFallback,
17
3
  VM_ARRAY_MAX_LENGTH,
4
+ VM_FUNCTION_ANONYMOUS_NAME,
5
+ VM_SCRIPT_NAME,
18
6
  VmError,
19
- VmFunction,
20
- VmModule,
21
- VmSharedContext,
22
7
  __export,
8
+ apply,
23
9
  create,
24
10
  defineProperty,
11
+ display,
25
12
  emit,
26
13
  entries,
27
- formatDiagnostic,
14
+ formatDiagnostics,
28
15
  fromEntries,
29
16
  generateBytecode,
30
17
  generateBytecodeSync,
18
+ getPrototypeOf,
31
19
  hasOwn,
32
- helpers_exports,
20
+ hasOwnEnumerable,
21
+ innerToString,
33
22
  isArray,
34
23
  isFinite,
35
24
  isInteger,
36
25
  isNaN,
37
26
  isSafeInteger,
27
+ isVmAny,
38
28
  isVmArray,
39
- isVmArrayLikeRecordByEntires,
40
29
  isVmCallable,
41
30
  isVmConst,
42
31
  isVmExtern,
@@ -44,30 +33,1163 @@ import {
44
33
  isVmModule,
45
34
  isVmPrimitive,
46
35
  isVmRecord,
36
+ isVmWrapper,
37
+ kVmContext,
38
+ kVmExtern,
39
+ kVmFunction,
40
+ kVmFunctionProxy,
41
+ kVmModule,
42
+ kVmScript,
43
+ kVmWrapper,
47
44
  keys,
48
- operations_exports,
49
45
  parseDiagnostics,
46
+ toBoolean,
47
+ toFormat,
48
+ toNumber,
49
+ toString,
50
50
  values
51
- } from "./chunk-55FKP56O.js";
51
+ } from "./chunk-YZGL3D7L.js";
52
52
 
53
- // src/subtle.ts
54
- import { getModule } from "@mirascript/bindings";
53
+ // src/vm/operations.ts
54
+ var operations_exports = {};
55
+ __export(operations_exports, {
56
+ $Add: () => $Add,
57
+ $Aeq: () => $Aeq,
58
+ $And: () => $And,
59
+ $ArraySpread: () => $ArraySpread,
60
+ $AssertInit: () => $AssertInit,
61
+ $AssertNonNil: () => $AssertNonNil,
62
+ $Call: () => $Call,
63
+ $Concat: () => $Concat,
64
+ $Div: () => $Div,
65
+ $Eq: () => $Eq,
66
+ $Format: () => $Format,
67
+ $Get: () => $Get,
68
+ $Gt: () => $Gt,
69
+ $Gte: () => $Gte,
70
+ $Has: () => $Has,
71
+ $In: () => $In,
72
+ $IsArray: () => $IsArray,
73
+ $IsBoolean: () => $IsBoolean,
74
+ $IsNumber: () => $IsNumber,
75
+ $IsRecord: () => $IsRecord,
76
+ $IsString: () => $IsString,
77
+ $Iterable: () => $Iterable,
78
+ $Length: () => $Length,
79
+ $Lt: () => $Lt,
80
+ $Lte: () => $Lte,
81
+ $Mod: () => $Mod,
82
+ $Mul: () => $Mul,
83
+ $Naeq: () => $Naeq,
84
+ $Neg: () => $Neg,
85
+ $Neq: () => $Neq,
86
+ $Not: () => $Not,
87
+ $Nsame: () => $Nsame,
88
+ $Omit: () => $Omit,
89
+ $Or: () => $Or,
90
+ $Pick: () => $Pick,
91
+ $Pos: () => $Pos,
92
+ $Pow: () => $Pow,
93
+ $RecordSpread: () => $RecordSpread,
94
+ $Same: () => $Same,
95
+ $Set: () => $Set,
96
+ $Slice: () => $Slice,
97
+ $SliceExclusive: () => $SliceExclusive,
98
+ $Sub: () => $Sub,
99
+ $ToBoolean: () => $ToBoolean,
100
+ $ToNumber: () => $ToNumber,
101
+ $ToString: () => $ToString,
102
+ $Type: () => $Type
103
+ });
104
+ var { abs, min, trunc, ceil } = Math;
105
+ var { slice, at } = Array.prototype;
106
+ var isSame = (a, b) => {
107
+ if (typeof a == "number" && typeof b == "number") return a === b || isNaN(a) && isNaN(b);
108
+ if (a === b) return true;
109
+ if (a == null || typeof a != "object" || b == null || typeof b != "object") return false;
110
+ if (isVmWrapper(a)) return a.same(b);
111
+ if (isVmWrapper(b)) return b.same(a);
112
+ if (isVmArray(a) && isVmArray(b)) {
113
+ const len2 = a.length;
114
+ if (len2 !== b.length) {
115
+ return false;
116
+ }
117
+ for (let i = 0; i < len2; i++) {
118
+ if (!isSame(a[i] ?? null, b[i] ?? null)) {
119
+ return false;
120
+ }
121
+ }
122
+ return true;
123
+ }
124
+ if (!isVmArray(a) && !isVmArray(b)) {
125
+ const aKeys = keys(a);
126
+ const bKeys = keys(b);
127
+ if (aKeys.length !== bKeys.length) {
128
+ return false;
129
+ }
130
+ for (const key of aKeys) {
131
+ if (!hasOwnEnumerable(b, key)) {
132
+ return false;
133
+ }
134
+ const av = a[key] ?? null;
135
+ const bv = b[key] ?? null;
136
+ if (!isSame(av, bv)) {
137
+ return false;
138
+ }
139
+ }
140
+ return true;
141
+ }
142
+ return false;
143
+ };
144
+ var overloadNumberString = (a, b) => {
145
+ if (typeof a == "number" || typeof b == "number") return true;
146
+ if (typeof a == "string" || typeof b == "string") return false;
147
+ return true;
148
+ };
149
+ var $Add = (a, b) => {
150
+ return $ToNumber(a) + $ToNumber(b);
151
+ };
152
+ var $Sub = (a, b) => {
153
+ return $ToNumber(a) - $ToNumber(b);
154
+ };
155
+ var $Mul = (a, b) => {
156
+ return $ToNumber(a) * $ToNumber(b);
157
+ };
158
+ var $Div = (a, b) => {
159
+ return $ToNumber(a) / $ToNumber(b);
160
+ };
161
+ var $Mod = (a, b) => {
162
+ return $ToNumber(a) % $ToNumber(b);
163
+ };
164
+ var $Pow = (a, b) => {
165
+ return $ToNumber(a) ** $ToNumber(b);
166
+ };
167
+ var $And = (a, b) => {
168
+ return $ToBoolean(a) && $ToBoolean(b);
169
+ };
170
+ var $Or = (a, b) => {
171
+ return $ToBoolean(a) || $ToBoolean(b);
172
+ };
173
+ var $Gt = (a, b) => {
174
+ if (overloadNumberString(a, b)) {
175
+ return $ToNumber(a) > $ToNumber(b);
176
+ } else {
177
+ return $ToString(a) > $ToString(b);
178
+ }
179
+ };
180
+ var $Gte = (a, b) => {
181
+ if (overloadNumberString(a, b)) {
182
+ return $ToNumber(a) >= $ToNumber(b);
183
+ } else {
184
+ return $ToString(a) >= $ToString(b);
185
+ }
186
+ };
187
+ var $Lt = (a, b) => {
188
+ if (overloadNumberString(a, b)) {
189
+ return $ToNumber(a) < $ToNumber(b);
190
+ } else {
191
+ return $ToString(a) < $ToString(b);
192
+ }
193
+ };
194
+ var $Lte = (a, b) => {
195
+ if (overloadNumberString(a, b)) {
196
+ return $ToNumber(a) <= $ToNumber(b);
197
+ } else {
198
+ return $ToString(a) <= $ToString(b);
199
+ }
200
+ };
201
+ var $Eq = (a, b) => {
202
+ $AssertInit(a);
203
+ $AssertInit(b);
204
+ if (typeof a == "number" && typeof b == "number") return a === b;
205
+ return isSame(a, b);
206
+ };
207
+ var $Neq = (a, b) => {
208
+ return !$Eq(a, b);
209
+ };
210
+ var $Aeq = (a, b) => {
211
+ if (overloadNumberString(a, b)) {
212
+ const an = $ToNumber(a);
213
+ const bn = $ToNumber(b);
214
+ const EPS = 1e-15;
215
+ if (isNaN(an) || isNaN(bn)) return false;
216
+ if (an === bn) return true;
217
+ const absoluteDifference = abs(an - bn);
218
+ if (absoluteDifference < EPS) return true;
219
+ const base = min(abs(an), abs(bn));
220
+ return absoluteDifference < base * EPS;
221
+ } else {
222
+ const as = $ToString(a);
223
+ const bs = $ToString(b);
224
+ if (as === bs) return true;
225
+ const ai = as.toLowerCase();
226
+ const bi = bs.toLowerCase();
227
+ if (ai === bi) return true;
228
+ const an = ai.normalize("NFC");
229
+ const bn = bi.normalize("NFC");
230
+ return an === bn;
231
+ }
232
+ };
233
+ var $Naeq = (a, b) => {
234
+ return !$Aeq(a, b);
235
+ };
236
+ var $Same = (a, b) => {
237
+ $AssertInit(a);
238
+ $AssertInit(b);
239
+ return isSame(a, b);
240
+ };
241
+ var $Nsame = (a, b) => {
242
+ return !$Same(a, b);
243
+ };
244
+ var $In = (value, iterable) => {
245
+ $AssertInit(value);
246
+ $AssertInit(iterable);
247
+ if (iterable == null) return false;
248
+ if (typeof iterable != "object") return false;
249
+ if (isVmArray(iterable)) {
250
+ if (value == null) {
251
+ for (const item of iterable) if (item == null) return true;
252
+ return false;
253
+ }
254
+ if (isVmPrimitive(value)) return iterable.includes(value);
255
+ return iterable.some((item = null) => isSame(item, value));
256
+ }
257
+ const key = toString(value, void 0);
258
+ if (isVmWrapper(iterable)) return iterable.has(key);
259
+ return hasOwnEnumerable(iterable, key);
260
+ };
261
+ var $Concat = (...args) => {
262
+ return args.map((a) => toFormat(a, null)).join("");
263
+ };
264
+ var $Pos = (a) => {
265
+ return $ToNumber(a);
266
+ };
267
+ var $Neg = (a) => {
268
+ return -$ToNumber(a);
269
+ };
270
+ var $Not = (a) => {
271
+ return !$ToBoolean(a);
272
+ };
273
+ var $Length = (value) => {
274
+ $AssertInit(value);
275
+ if (isVmArray(value)) return value.length;
276
+ if (isVmRecord(value)) return keys(value).length;
277
+ if (isVmWrapper(value)) {
278
+ return value.keys().length;
279
+ }
280
+ return Number.NaN;
281
+ };
282
+ var $Omit = (value, omitted) => {
283
+ $AssertInit(value);
284
+ if (value == null || !isVmRecord(value)) return {};
285
+ const result = {};
286
+ const valueKeys = keys(value);
287
+ const omittedSet = new Set(omitted.map($ToString));
288
+ for (const key of valueKeys) {
289
+ if (!omittedSet.has(key)) {
290
+ result[key] = value[key] ?? null;
291
+ }
292
+ }
293
+ return result;
294
+ };
295
+ var $Pick = (value, picked) => {
296
+ $AssertInit(value);
297
+ if (value == null || !isVmRecord(value)) return {};
298
+ const result = {};
299
+ for (const key of picked) {
300
+ const k = $ToString(key);
301
+ if (hasOwnEnumerable(value, k)) {
302
+ result[k] = value[k] ?? null;
303
+ }
304
+ }
305
+ return result;
306
+ };
307
+ var sliceCore = (value, start, end, exclusive) => {
308
+ const { length } = value;
309
+ if (isNaN(start)) start = 0;
310
+ else if (start < 0) start = length + start;
311
+ if (isNaN(end)) end = exclusive ? length : length - 1;
312
+ else if (end < 0) end = length + end;
313
+ start = ceil(start);
314
+ if (exclusive || !isSafeInteger(end)) {
315
+ end = ceil(end);
316
+ } else {
317
+ end = end + 1;
318
+ }
319
+ return slice.call(value, start, end);
320
+ };
321
+ var $Slice = (value, start, end) => {
322
+ $AssertInit(value);
323
+ if (!isVmArray(value)) throw new VmError(`Expected array, got ${$Type(value)}`, []);
324
+ const s = start != null ? $ToNumber(start) : 0;
325
+ const e = end != null ? $ToNumber(end) : value.length - 1;
326
+ return sliceCore(value, s, e, false);
327
+ };
328
+ var $SliceExclusive = (value, start, end) => {
329
+ $AssertInit(value);
330
+ if (!isVmArray(value)) throw new VmError(`Expected array, got ${$Type(value)}`, []);
331
+ const s = start != null ? $ToNumber(start) : 0;
332
+ const e = end != null ? $ToNumber(end) : value.length;
333
+ return sliceCore(value, s, e, true);
334
+ };
335
+ var $AssertInit = (value) => {
336
+ if (value === void 0) throw new VmError(`Uninitialized value`, null);
337
+ };
338
+ var $Call = (func, args) => {
339
+ for (const a of args) {
340
+ $AssertInit(a);
341
+ }
342
+ if (isVmExtern(func)) {
343
+ return func.call(args) ?? null;
344
+ }
345
+ if (isVmFunction(func)) {
346
+ return func(...args) ?? null;
347
+ }
348
+ throw new VmError(`Value is not callable: ${display(func)}`, null);
349
+ };
350
+ var $Type = (value) => {
351
+ if (value == null) return "nil";
352
+ if (isVmWrapper(value)) return value.type;
353
+ if (isVmArray(value)) return "array";
354
+ if (typeof value == "object") return "record";
355
+ return typeof value;
356
+ };
357
+ var $ToBoolean = (value) => {
358
+ if (typeof value == "boolean") return value;
359
+ $AssertInit(value);
360
+ return toBoolean(value, void 0);
361
+ };
362
+ var $ToString = (value) => {
363
+ if (typeof value == "string") return value;
364
+ $AssertInit(value);
365
+ return toString(value, void 0);
366
+ };
367
+ var $ToNumber = (value) => {
368
+ if (typeof value == "number") return value;
369
+ $AssertInit(value);
370
+ return toNumber(value, void 0);
371
+ };
372
+ var $IsBoolean = (value) => {
373
+ $AssertInit(value);
374
+ return typeof value == "boolean";
375
+ };
376
+ var $IsNumber = (value) => {
377
+ $AssertInit(value);
378
+ return typeof value == "number";
379
+ };
380
+ var $IsString = (value) => {
381
+ $AssertInit(value);
382
+ return typeof value == "string";
383
+ };
384
+ var $IsRecord = (value) => {
385
+ $AssertInit(value);
386
+ return isVmRecord(value);
387
+ };
388
+ var $IsArray = (value) => {
389
+ $AssertInit(value);
390
+ return isVmArray(value);
391
+ };
392
+ var $AssertNonNil = (value) => {
393
+ $AssertInit(value);
394
+ if (value !== null) return;
395
+ throw new VmError("Expected non-nil value", null);
396
+ };
397
+ var $Has = (obj, key) => {
398
+ $AssertInit(obj);
399
+ const pk = $ToString(key);
400
+ if (obj == null || typeof obj != "object") return false;
401
+ if (isVmWrapper(obj)) return obj.has(pk);
402
+ return hasOwnEnumerable(obj, pk);
403
+ };
404
+ var $Get = (obj, key) => {
405
+ $AssertInit(obj);
406
+ if (isVmArray(obj)) {
407
+ const index = $ToNumber(key);
408
+ if (isNaN(index)) return null;
409
+ return at.call(obj, trunc(index)) ?? null;
410
+ }
411
+ const pk = $ToString(key);
412
+ if (obj == null || typeof obj != "object") return null;
413
+ if (isVmWrapper(obj)) return obj.get(pk) ?? null;
414
+ if (!hasOwnEnumerable(obj, pk)) return null;
415
+ return obj[pk] ?? null;
416
+ };
417
+ var $Set = (obj, key, value) => {
418
+ $AssertInit(obj);
419
+ $AssertInit(value);
420
+ const pk = $ToString(key);
421
+ if (obj == null) return;
422
+ if (!isVmExtern(obj)) throw new VmError(`Expected extern, got ${$Type(obj)}`, void 0);
423
+ obj.set(pk, value);
424
+ };
425
+ var $Iterable = (value) => {
426
+ $AssertInit(value);
427
+ if (isVmWrapper(value)) return value.keys();
428
+ if (isVmArray(value)) return value;
429
+ if (value != null && typeof value == "object") return keys(value);
430
+ throw new VmError(`Value is not iterable`, isVmFunction(value) ? [] : [value]);
431
+ };
432
+ var $RecordSpread = (record) => {
433
+ $AssertInit(record);
434
+ if (record == null || isVmRecord(record)) return record;
435
+ if (isVmArray(record)) {
436
+ const result = {};
437
+ const len2 = record.length;
438
+ for (let i = 0; i < len2; i++) {
439
+ const item = record[i];
440
+ result[i] = item ?? null;
441
+ }
442
+ return result;
443
+ }
444
+ if (isVmExtern(record)) {
445
+ const result = create(null);
446
+ for (const key of record.keys()) {
447
+ const value = record.get(key) ?? null;
448
+ if (isVmPrimitive(value)) {
449
+ result[key] = value;
450
+ }
451
+ }
452
+ return result;
453
+ }
454
+ throw new VmError(`Expected record, array, extern or nil, got ${$Type(record)}`, null);
455
+ };
456
+ var $ArraySpread = (array) => {
457
+ $AssertInit(array);
458
+ if (array == null) return [];
459
+ if (isVmArray(array)) return array;
460
+ if (isVmExtern(array) && typeof array.value[Symbol.iterator] == "function") {
461
+ const result = [];
462
+ for (const item of array.value) {
463
+ if (isVmPrimitive(item)) {
464
+ result.push(item);
465
+ } else {
466
+ result.push(null);
467
+ }
468
+ }
469
+ return result;
470
+ }
471
+ throw new VmError(`Expected array, iterable extern or nil, got ${$Type(array)}`, []);
472
+ };
473
+ var $Format = (value, format2) => {
474
+ $AssertInit(value);
475
+ const f = format2 == null ? "" : $ToString(format2);
476
+ return toFormat(value, f);
477
+ };
478
+
479
+ // src/vm/types/wrapper.ts
480
+ var VmWrapper = class {
481
+ constructor(value) {
482
+ this.value = value;
483
+ }
484
+ /** Convert the object to JSON */
485
+ toJSON() {
486
+ return void 0;
487
+ }
488
+ /** 转为字符串 */
489
+ toString(useBraces) {
490
+ const { type, describe } = this;
491
+ if (!describe) return `<${type}>`;
492
+ return `<${type} ${describe}>`;
493
+ }
494
+ };
495
+ Object.defineProperty(VmWrapper.prototype, kVmWrapper, { value: true });
496
+
497
+ // src/vm/types/boundary.ts
498
+ function toVmFunctionProxy(fn) {
499
+ const cached = fn[kVmFunctionProxy];
500
+ if (cached != null) return cached;
501
+ const proxy = (...args) => {
502
+ const ret = $Call(
503
+ fn,
504
+ // 作为函数参数传入的值一定丢失了它的 this
505
+ args.map((v) => wrapToVmValue(v, null))
506
+ );
507
+ return unwrapFromVmValue(ret);
508
+ };
509
+ defineProperty(fn, kVmFunctionProxy, { value: proxy });
510
+ defineProperty(proxy, kVmFunctionProxy, { value: fn });
511
+ defineProperty(proxy, "name", {
512
+ value: fn.name,
513
+ configurable: true
514
+ });
515
+ return proxy;
516
+ }
517
+ function fromVmFunctionProxy(fn) {
518
+ if (isVmFunction(fn)) return fn;
519
+ const original = fn[kVmFunctionProxy];
520
+ if (original && isVmFunction(original)) return original;
521
+ return void 0;
522
+ }
523
+ function wrapToVmValue(value, thisArg = null, assumeVmValue) {
524
+ if (value == null) return null;
525
+ switch (typeof value) {
526
+ case "function": {
527
+ const unwrapped = fromVmFunctionProxy(value);
528
+ if (unwrapped) return unwrapped;
529
+ return new VmExtern(value, thisArg);
530
+ }
531
+ case "object": {
532
+ if (isVmWrapper(value)) return value;
533
+ if (value instanceof Date) return value.valueOf();
534
+ if (assumeVmValue?.(value)) return value;
535
+ return new VmExtern(value);
536
+ }
537
+ case "string":
538
+ case "number":
539
+ case "boolean":
540
+ return value;
541
+ case "bigint":
542
+ return Number(value);
543
+ case "symbol":
544
+ case "undefined":
545
+ default:
546
+ return null;
547
+ }
548
+ }
549
+ function unwrapFromVmValue(value) {
550
+ if (isVmFunction(value)) {
551
+ return toVmFunctionProxy(value);
552
+ }
553
+ if (value == null || typeof value != "object") return value;
554
+ if (!isVmExtern(value)) return value;
555
+ if (value.thisArg == null || typeof value.value != "function") {
556
+ return value.value;
557
+ }
558
+ const f = value;
559
+ const caller = f.thisArg.value;
560
+ return new Proxy(f.value, {
561
+ apply(target, thisArg, args) {
562
+ return apply(target, caller, args);
563
+ }
564
+ });
565
+ }
566
+
567
+ // src/vm/types/extern.ts
568
+ var ObjectPrototype = Object.prototype;
569
+ var ObjectToString = ObjectPrototype.toString;
570
+ var FunctionToString = Function.prototype.toString;
571
+ var ArrayToString = Array.prototype.toString;
572
+ var ArrayMap = Array.prototype.map;
573
+ var VmExtern = class extends VmWrapper {
574
+ constructor(value, thisArg = null) {
575
+ super(value);
576
+ this.thisArg = thisArg;
577
+ }
578
+ /** Check if the object has a property */
579
+ access(key, read) {
580
+ if (key.startsWith("_")) return false;
581
+ if (typeof this.value == "function" && (key === "prototype" || key === "arguments" || key === "caller"))
582
+ return false;
583
+ if (hasOwn(this.value, key)) return true;
584
+ if (!read) return true;
585
+ if (!(key in this.value)) return false;
586
+ if (key === "constructor") return false;
587
+ const prop = this.value[key];
588
+ if (key in Function.prototype && prop === Function.prototype[key]) return false;
589
+ if (key in Array.prototype && prop === Array.prototype[key]) return false;
590
+ if (key in Object.prototype && prop === Object.prototype[key]) return false;
591
+ return true;
592
+ }
593
+ /** 决定是否对属性进行包装 */
594
+ assumeVmValue(value, key) {
595
+ return false;
596
+ }
597
+ /** @inheritdoc */
598
+ has(key) {
599
+ return this.access(key, true);
600
+ }
601
+ /** @inheritdoc */
602
+ get(key) {
603
+ if (!this.has(key)) return void 0;
604
+ const prop = this.value[key];
605
+ return wrapToVmValue(prop, this, (v) => this.assumeVmValue(v, key));
606
+ }
607
+ /** Set a property on the object */
608
+ set(key, value) {
609
+ if (!this.access(key, false)) return false;
610
+ const prop = unwrapFromVmValue(value);
611
+ this.value[key] = prop;
612
+ return true;
613
+ }
614
+ /** Call extern value */
615
+ call(args) {
616
+ const { value } = this;
617
+ if (typeof value != "function") {
618
+ throw VmError.from(`Not a callable extern`, null, null);
619
+ }
620
+ const caller = this.thisArg?.value ?? null;
621
+ const unwrappedArgs = args.map(unwrapFromVmValue);
622
+ let ret;
623
+ try {
624
+ ret = apply(value, caller, unwrappedArgs);
625
+ } catch (ex) {
626
+ throw VmError.from(`Callable extern`, ex, null);
627
+ }
628
+ return wrapToVmValue(ret, null, (obj) => this.assumeVmValue(obj, void 0));
629
+ }
630
+ /** @inheritdoc */
631
+ keys() {
632
+ const keys4 = [];
633
+ for (const key in this.value) {
634
+ if (this.has(key)) keys4.push(key);
635
+ }
636
+ return keys4;
637
+ }
638
+ /** @inheritdoc */
639
+ same(other) {
640
+ if (!isVmExtern(other)) return false;
641
+ return this.value === other.value && this.thisArg === other.thisArg;
642
+ }
643
+ /** @inheritdoc */
644
+ toString(useBraces) {
645
+ const { toString: toString2 } = this.value;
646
+ if (typeof toString2 != "function" || toString2 === ObjectToString || toString2 === FunctionToString) {
647
+ return super.toString(useBraces);
648
+ }
649
+ if (toString2 === ArrayToString && isArray(this.value)) {
650
+ const mapped = ArrayMap.call(this.value, (item) => {
651
+ if (item === void 0) return "";
652
+ return innerToString(wrapToVmValue(item ?? null, null), true);
653
+ });
654
+ const str = mapped.join(", ");
655
+ if (useBraces) return `[${str}]`;
656
+ return str;
657
+ }
658
+ return String(this.value);
659
+ }
660
+ /** @inheritdoc */
661
+ get type() {
662
+ return "extern";
663
+ }
664
+ /** @inheritdoc */
665
+ get describe() {
666
+ const tag = ObjectToString.call(this.value).slice(8, -1);
667
+ if (isArray(this.value)) {
668
+ return `${tag}(${this.value.length})`;
669
+ } else if (tag === "Object") {
670
+ const proto = getPrototypeOf(this.value);
671
+ if (proto === ObjectPrototype) {
672
+ return "Object";
673
+ }
674
+ if (proto == null) {
675
+ return "Object: null prototype";
676
+ }
677
+ if (typeof proto.constructor === "function" && proto.constructor.name) {
678
+ return proto.constructor.name;
679
+ }
680
+ } else if (tag === "Function" && "prototype" in this.value && typeof this.value.prototype == "object") {
681
+ const { name } = this.value;
682
+ return `class ${name || "<anonymous>"}`;
683
+ } else if (tag === "Function") {
684
+ const { name } = this.value;
685
+ return `function ${name || "<anonymous>"}()`;
686
+ } else if (tag === "AsyncFunction") {
687
+ const { name } = this.value;
688
+ return `async function ${name || "<anonymous>"}()`;
689
+ } else if (tag === "GeneratorFunction") {
690
+ const { name } = this.value;
691
+ return `function* ${name || "<anonymous>"}()`;
692
+ } else if (tag === "AsyncGeneratorFunction") {
693
+ const { name } = this.value;
694
+ return `async function* ${name || "<anonymous>"}()`;
695
+ }
696
+ return tag;
697
+ }
698
+ };
699
+ Object.defineProperty(VmExtern.prototype, kVmExtern, { value: true });
55
700
 
56
- // src/helpers/constants.ts
57
- var constants_exports = {};
58
- __export(constants_exports, {
59
- REG_IDENTIFIER: () => REG_IDENTIFIER,
60
- REG_ORDINAL: () => REG_ORDINAL
701
+ // src/vm/checkpoint.ts
702
+ var MAX_DEPTH = 128;
703
+ var cpDepth = 0;
704
+ var cp = Number.NaN;
705
+ var cpTimeout = 100;
706
+ function Cp() {
707
+ if (!cp) {
708
+ cp = Date.now();
709
+ } else if (Date.now() - cp > cpTimeout) {
710
+ throw new RangeError("Execution timeout");
711
+ }
712
+ }
713
+ function CpEnter() {
714
+ cpDepth++;
715
+ if (cpDepth <= 1) {
716
+ cp = Date.now();
717
+ cpDepth = 1;
718
+ } else if (cpDepth > MAX_DEPTH) {
719
+ throw new RangeError("Maximum call depth exceeded");
720
+ } else {
721
+ Cp();
722
+ }
723
+ }
724
+ function CpExit() {
725
+ cpDepth--;
726
+ if (cpDepth < 1) {
727
+ cp = Number.NaN;
728
+ cpDepth = 0;
729
+ } else {
730
+ Cp();
731
+ }
732
+ }
733
+ function configCheckpoint(timeout = 100) {
734
+ if (typeof timeout !== "number" || timeout <= 0 || Number.isNaN(timeout)) {
735
+ throw new RangeError("Invalid timeout value");
736
+ }
737
+ cpTimeout = timeout;
738
+ }
739
+
740
+ // src/vm/types/function.ts
741
+ function VmFunction(fn, option = {}) {
742
+ if (typeof fn != "function") {
743
+ throw new TypeError("Invalid function");
744
+ }
745
+ const exists = fromVmFunctionProxy(fn);
746
+ if (exists) return exists;
747
+ const info = {
748
+ fullName: option.fullName ?? (fn.name === VM_FUNCTION_ANONYMOUS_NAME ? "" : fn.name),
749
+ isLib: option.isLib ?? false,
750
+ summary: option.summary || void 0,
751
+ params: option.params,
752
+ paramsType: option.paramsType,
753
+ returns: option.returns || void 0,
754
+ returnsType: option.returnsType || void 0,
755
+ examples: option.examples?.length ? option.examples : void 0
756
+ };
757
+ if (option.injectCp) {
758
+ const original = fn;
759
+ info.original = original;
760
+ fn = ((...args) => {
761
+ try {
762
+ CpEnter();
763
+ const ret = original(...args);
764
+ return ret;
765
+ } finally {
766
+ CpExit();
767
+ }
768
+ });
769
+ defineProperty(fn, "name", { value: original.name });
770
+ }
771
+ defineProperty(fn, kVmFunction, {
772
+ value: Object.freeze(info)
773
+ });
774
+ return fn;
775
+ }
776
+
777
+ // src/vm/types/context.ts
778
+ var VmSharedContext = create(null);
779
+ var VmSharedContextKeys = null;
780
+ function globalVarNotFound(name) {
781
+ throw new VmError(`Global variable '${name}' is not defined.`, null);
782
+ }
783
+ function defineVmContextValue(name, value, override = false) {
784
+ if (!override && name in VmSharedContext) throw new Error(`Global variable '${name}' is already defined.`);
785
+ let v;
786
+ if (typeof value == "function") {
787
+ v = VmFunction(value, {
788
+ isLib: true,
789
+ fullName: `global.${name}`
790
+ });
791
+ } else {
792
+ v = value;
793
+ }
794
+ VmSharedContext[name] = v ?? null;
795
+ VmSharedContextKeys = null;
796
+ }
797
+ var DefaultVmContext = Object.freeze({
798
+ [kVmContext]: true,
799
+ /** @inheritdoc */
800
+ keys() {
801
+ VmSharedContextKeys ??= Object.freeze(keys(VmSharedContext));
802
+ return VmSharedContextKeys;
803
+ },
804
+ /** @inheritdoc */
805
+ get(key) {
806
+ const val = VmSharedContext[key];
807
+ if (val === void 0) globalVarNotFound(key);
808
+ return val;
809
+ },
810
+ /** @inheritdoc */
811
+ has(key) {
812
+ return key in VmSharedContext;
813
+ }
61
814
  });
62
- var REG_IDENTIFIER = /(?:_+|@+|\$+|\p{XID_Start})\p{XID_Continue}*/u;
63
- var REG_ORDINAL = /(?:0|[1-9]\d{0,8}|1\d{9}|20\d{8}|21[0-3]\d{7}|214[0-6]\d{6}|2147[0-3]\d{5}|21474[0-7]\d{4}|214748[0-2]\d{3}|2147483[0-5]\d{2}|21474836[0-3]\d|214748364[0-7])/;
815
+ var _a;
816
+ _a = kVmContext;
817
+ var ValueVmContext = class {
818
+ constructor(env, describe) {
819
+ this.env = env;
820
+ this.describe = describe;
821
+ this[_a] = true;
822
+ this.cachedKeys = null;
823
+ }
824
+ /** @inheritdoc */
825
+ keys() {
826
+ this.cachedKeys ??= keys(this.env);
827
+ return [...this.cachedKeys, ...DefaultVmContext.keys()];
828
+ }
829
+ /** @inheritdoc */
830
+ get(key) {
831
+ const val = this.env[key];
832
+ if (val === void 0) globalVarNotFound(key);
833
+ return val;
834
+ }
835
+ /** @inheritdoc */
836
+ has(key) {
837
+ return key in this.env;
838
+ }
839
+ };
840
+ var _a2;
841
+ _a2 = kVmContext;
842
+ var FactoryVmContext = class {
843
+ constructor(getter, enumerator, describe) {
844
+ this.getter = getter;
845
+ this.enumerator = enumerator;
846
+ this.describe = describe;
847
+ this[_a2] = true;
848
+ }
849
+ /** @inheritdoc */
850
+ keys() {
851
+ if (!this.enumerator) return DefaultVmContext.keys();
852
+ return [...this.enumerator(), ...DefaultVmContext.keys()];
853
+ }
854
+ /** @inheritdoc */
855
+ get(key) {
856
+ const value = this.getter(key);
857
+ if (value !== void 0) return value;
858
+ return DefaultVmContext.get(key);
859
+ }
860
+ /** @inheritdoc */
861
+ has(key) {
862
+ return this.getter(key) !== void 0 || DefaultVmContext.has(key);
863
+ }
864
+ };
865
+ function createVmContext(...args) {
866
+ if (args[0] == null && args[1] == null) {
867
+ return { ...DefaultVmContext };
868
+ }
869
+ if (typeof args[0] == "function") {
870
+ const [getter, enumerator, describer2] = args;
871
+ return new FactoryVmContext(getter, enumerator ?? void 0, describer2 ?? void 0);
872
+ }
873
+ const [vmValues, externValues, describer] = args;
874
+ const env = create(VmSharedContext);
875
+ if (vmValues) {
876
+ for (const [key, value] of entries(vmValues)) {
877
+ if (!isVmAny(value, false)) continue;
878
+ env[key] = value ?? null;
879
+ }
880
+ }
881
+ if (externValues) {
882
+ for (const [key, value] of entries(externValues)) {
883
+ env[key] = value == null ? null : wrapToVmValue(value, null);
884
+ }
885
+ }
886
+ return new ValueVmContext(env, describer ?? void 0);
887
+ }
888
+
889
+ // src/compiler/index.ts
890
+ import { loadModule } from "@mirascript/bindings";
891
+
892
+ // src/vm/helpers.ts
893
+ var helpers_exports = {};
894
+ __export(helpers_exports, {
895
+ ArrayRange: () => ArrayRange,
896
+ ArrayRangeExclusive: () => ArrayRangeExclusive,
897
+ Cp: () => Cp,
898
+ CpEnter: () => CpEnter,
899
+ CpExit: () => CpExit,
900
+ Element: () => Element,
901
+ ElementOpt: () => ElementOpt,
902
+ Function: () => Function2,
903
+ GlobalFallback: () => GlobalFallback,
904
+ Upvalue: () => Upvalue,
905
+ Vargs: () => Vargs
906
+ });
907
+ var Vargs = (varags) => {
908
+ for (let i = 0, l = varags.length; i < l; i++) {
909
+ const el = varags[i];
910
+ if (!isVmConst(el)) {
911
+ varags[i] = null;
912
+ }
913
+ }
914
+ return varags;
915
+ };
916
+ var Element = (value) => {
917
+ $AssertInit(value);
918
+ if (!isVmConst(value)) return null;
919
+ return value;
920
+ };
921
+ var ElementOpt = (key, value) => {
922
+ $AssertInit(value);
923
+ if (value == null || !isVmConst(value)) return {};
924
+ return { [key]: value };
925
+ };
926
+ var Function2 = (fn, name = VM_FUNCTION_ANONYMOUS_NAME) => {
927
+ defineProperty(fn, "name", { value: name });
928
+ return VmFunction(fn, { isLib: false, injectCp: false });
929
+ };
930
+ var Upvalue = (value) => {
931
+ $AssertInit(value);
932
+ return value;
933
+ };
934
+ var assertArrayLength = (start, end) => {
935
+ if (end - start > VM_ARRAY_MAX_LENGTH) {
936
+ throw new RangeError(`Array length exceeds maximum limit of ${VM_ARRAY_MAX_LENGTH}`);
937
+ }
938
+ };
939
+ var isEmptyRange = (start, end) => {
940
+ return !isFinite(start) || !isFinite(end) || start > end;
941
+ };
942
+ var ArrayRange = (start, end) => {
943
+ const s = $ToNumber(start);
944
+ const e = $ToNumber(end);
945
+ if (isEmptyRange(s, e)) return [];
946
+ assertArrayLength(s, e);
947
+ const arr = [];
948
+ for (let i = s; i <= e; i++) {
949
+ arr.push(i);
950
+ }
951
+ return arr;
952
+ };
953
+ var ArrayRangeExclusive = (start, end) => {
954
+ const s = $ToNumber(start);
955
+ const e = $ToNumber(end);
956
+ if (isEmptyRange(s, e)) return [];
957
+ assertArrayLength(s, e);
958
+ const arr = [];
959
+ for (let i = s; i < e; i++) {
960
+ arr.push(i);
961
+ }
962
+ return arr;
963
+ };
964
+ function GlobalFallback() {
965
+ return DefaultVmContext;
966
+ }
967
+
968
+ // src/vm/env.ts
969
+ var keys2 = [];
970
+ var values2 = [];
971
+ for (const [key, value] of entries(operations_exports)) {
972
+ keys2.push(key);
973
+ values2.push(value);
974
+ }
975
+ for (const [key, value] of entries(helpers_exports)) {
976
+ keys2.push(key);
977
+ values2.push(value);
978
+ }
979
+
980
+ // src/compiler/create-script.ts
981
+ function wrapScript(source, script) {
982
+ if (kVmScript in script) {
983
+ return script;
984
+ }
985
+ defineProperty(script, "name", { value: VM_SCRIPT_NAME });
986
+ defineProperty(script, kVmScript, { value: true });
987
+ if (typeof source === "string") {
988
+ defineProperty(script, "source", { value: source, configurable: true });
989
+ } else if (source instanceof Uint8Array) {
990
+ defineProperty(script, "source", { value: "<buffer>", configurable: true });
991
+ }
992
+ return script;
993
+ }
994
+ function createScript(source, code) {
995
+ let script;
996
+ try {
997
+ script = new Function(...keys2, code)(...values2);
998
+ } catch (error) {
999
+ throw new Error(`Failed to create script`, { cause: error });
1000
+ }
1001
+ return wrapScript(source, script);
1002
+ }
1003
+
1004
+ // src/compiler/compile-fast.ts
1005
+ var REG_NUMBER_FULL = /^\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
1006
+ var REG_IDENTIFIER_FAST = /^(?:\$+|@+)[a-zA-Z0-9_]*$/;
1007
+ var FAST_SCRIPT_MAX_LEN = 32;
1008
+ function compileScriptFast(code, options) {
1009
+ if (code.length > FAST_SCRIPT_MAX_LEN) return void 0;
1010
+ const trimmedCode = code.trim();
1011
+ if (!trimmedCode) {
1012
+ return wrapScript(code, () => null);
1013
+ }
1014
+ switch (trimmedCode) {
1015
+ case "nil":
1016
+ return wrapScript(code, () => null);
1017
+ case "true":
1018
+ return wrapScript(code, () => true);
1019
+ case "false":
1020
+ return wrapScript(code, () => false);
1021
+ case "nan":
1022
+ return wrapScript(code, () => 0 / 0);
1023
+ case "inf":
1024
+ case "+inf":
1025
+ return wrapScript(code, () => 1 / 0);
1026
+ case "-inf":
1027
+ return wrapScript(code, () => -1 / 0);
1028
+ }
1029
+ if (REG_IDENTIFIER_FAST.test(trimmedCode)) {
1030
+ const id = trimmedCode;
1031
+ return wrapScript(code, (global = GlobalFallback()) => global.get(id));
1032
+ }
1033
+ if (REG_NUMBER_FULL.test(trimmedCode)) {
1034
+ const num2 = Number(trimmedCode);
1035
+ if (!isFinite(num2)) return void 0;
1036
+ return wrapScript(code, () => num2);
1037
+ }
1038
+ return void 0;
1039
+ }
1040
+ var FAST_TEMPLATE_MAX_LEN = 1024;
1041
+ function compileTemplateFast(code, options) {
1042
+ if (code.length > FAST_TEMPLATE_MAX_LEN) return void 0;
1043
+ if (!code.includes("$")) {
1044
+ return wrapScript(code, () => code);
1045
+ }
1046
+ return void 0;
1047
+ }
1048
+ function compileFast(code, options) {
1049
+ if (options.sourceMap) return void 0;
1050
+ return (options.input_mode === "Template" ? compileTemplateFast : compileScriptFast)(code, options);
1051
+ }
1052
+
1053
+ // src/compiler/worker-manager.ts
1054
+ var worker;
1055
+ async function getWorker() {
1056
+ if (worker) return worker;
1057
+ worker = new Promise((resolve, reject) => {
1058
+ const w = new Worker(new URL("#compiler/worker", import.meta.url), {
1059
+ type: "module",
1060
+ name: "@mirascript/compiler"
1061
+ });
1062
+ const onError = (e) => {
1063
+ cleanUp();
1064
+ reject(new Error(`Worker failed to start: ${e.message}`));
1065
+ };
1066
+ const onMessage = (e) => {
1067
+ if (e.data === "ready") {
1068
+ cleanUp();
1069
+ resolve(w);
1070
+ } else if (e.data instanceof Error) {
1071
+ cleanUp();
1072
+ reject(e.data);
1073
+ }
1074
+ };
1075
+ w.addEventListener("error", onError);
1076
+ w.addEventListener("message", onMessage);
1077
+ const cleanUp = () => {
1078
+ w.removeEventListener("error", onError);
1079
+ w.removeEventListener("message", onMessage);
1080
+ };
1081
+ setTimeout(() => {
1082
+ onError(new ErrorEvent("error", { message: "Worker did not respond in time" }));
1083
+ }, 3e4);
1084
+ });
1085
+ return worker;
1086
+ }
1087
+ async function compileWorker(...args) {
1088
+ const worker2 = await getWorker();
1089
+ const seq = Math.random();
1090
+ worker2.postMessage([seq, ...args]);
1091
+ return await new Promise((resolve, reject) => {
1092
+ const callback = (ev) => {
1093
+ const data = ev.data;
1094
+ if (!Array.isArray(data)) return;
1095
+ const [retSeq, ...rest] = data;
1096
+ if (seq !== retSeq) return;
1097
+ worker2.removeEventListener("message", callback);
1098
+ if (rest.length === 2) {
1099
+ resolve(rest);
1100
+ } else {
1101
+ reject(rest[0]);
1102
+ }
1103
+ };
1104
+ worker2.addEventListener("message", callback);
1105
+ });
1106
+ }
1107
+
1108
+ // src/compiler/index.ts
1109
+ await loadModule();
1110
+ var WORKER_MIN_LEN = typeof Worker != "function" ? Number.MAX_VALUE : 1024;
1111
+ function reportDiagnostic(source, diagnostics, fileName) {
1112
+ const parsed = parseDiagnostics(source, diagnostics);
1113
+ const messages = formatDiagnostics(parsed.errors, source, fileName);
1114
+ throw new Error(`Failed to compile:
1115
+ ${messages.join("\n")}`);
1116
+ }
1117
+ function emitScript(source, [code, diagnostics], options) {
1118
+ if (!code) {
1119
+ reportDiagnostic(source, diagnostics, options.fileName);
1120
+ }
1121
+ const sourcemaps = options.sourceMap ? parseDiagnostics(source, diagnostics, (c) => c === DiagnosticCode.SourceMap).sourcemaps : [];
1122
+ const target = emit(source, code, sourcemaps, options);
1123
+ return createScript(source, target);
1124
+ }
1125
+ async function compile(source, options = {}) {
1126
+ if (options.sourceMap) {
1127
+ options.diagnostic_sourcemap = true;
1128
+ options.diagnostic_position_encoding ??= "Utf16";
1129
+ }
1130
+ if (typeof source == "string") {
1131
+ const result = compileFast(source, options);
1132
+ if (result) return result;
1133
+ }
1134
+ if (source.length < WORKER_MIN_LEN) {
1135
+ const bc = await generateBytecode(source, options);
1136
+ return emitScript(source, bc, options);
1137
+ }
1138
+ const [target, diagnostics] = await compileWorker(source, options);
1139
+ if (target == null) {
1140
+ reportDiagnostic(source, diagnostics, options.fileName);
1141
+ }
1142
+ return createScript(source, target);
1143
+ }
1144
+ function compileSync(source, options = {}) {
1145
+ if (typeof source == "string") {
1146
+ const result = compileFast(source, options);
1147
+ if (result) return result;
1148
+ }
1149
+ const bc = generateBytecodeSync(source, options);
1150
+ return emitScript(source, bc, options);
1151
+ }
1152
+
1153
+ // src/vm/types/module.ts
1154
+ var VmModule = class extends VmWrapper {
1155
+ constructor(name, value) {
1156
+ super(value);
1157
+ this.name = name;
1158
+ }
1159
+ /** @inheritdoc */
1160
+ has(key) {
1161
+ return hasOwnEnumerable(this.value, key);
1162
+ }
1163
+ /** @inheritdoc */
1164
+ get(key) {
1165
+ if (!this.has(key)) return void 0;
1166
+ return this.value[key] ?? null;
1167
+ }
1168
+ /** @inheritdoc */
1169
+ keys() {
1170
+ return keys(this.value);
1171
+ }
1172
+ /** @inheritdoc */
1173
+ same(other) {
1174
+ return this === other;
1175
+ }
1176
+ /** @inheritdoc */
1177
+ get type() {
1178
+ return "module";
1179
+ }
1180
+ /** @inheritdoc */
1181
+ get describe() {
1182
+ return this.name;
1183
+ }
1184
+ };
1185
+ Object.defineProperty(VmModule.prototype, kVmModule, { value: true });
64
1186
 
65
1187
  // src/vm/lib/global/index.ts
66
1188
  var global_exports = {};
67
1189
  __export(global_exports, {
68
1190
  "@e": () => E,
69
1191
  "@pi": () => PI,
70
- abs: () => abs,
1192
+ abs: () => abs2,
71
1193
  acos: () => acos,
72
1194
  acosh: () => acosh,
73
1195
  all: () => all,
@@ -82,7 +1204,7 @@ __export(global_exports, {
82
1204
  b_or: () => b_or,
83
1205
  b_xor: () => b_xor,
84
1206
  cbrt: () => cbrt,
85
- ceil: () => ceil,
1207
+ ceil: () => ceil2,
86
1208
  chars: () => chars,
87
1209
  contains: () => contains,
88
1210
  cos: () => cos,
@@ -102,16 +1224,15 @@ __export(global_exports, {
102
1224
  from_json: () => from_json,
103
1225
  hypot: () => hypot,
104
1226
  join: () => join,
105
- keys: () => keys2,
1227
+ keys: () => keys3,
106
1228
  len: () => len,
107
1229
  log: () => log,
108
1230
  log10: () => log10,
109
1231
  log1p: () => log1p,
110
1232
  log2: () => log2,
111
1233
  map: () => map2,
112
- matrix: () => matrix,
113
1234
  max: () => max,
114
- min: () => min,
1235
+ min: () => min2,
115
1236
  panic: () => panic,
116
1237
  pow: () => pow2,
117
1238
  product: () => product,
@@ -144,22 +1265,31 @@ __export(global_exports, {
144
1265
  trim: () => trim,
145
1266
  trim_end: () => trim_end,
146
1267
  trim_start: () => trim_start,
147
- trunc: () => trunc,
148
- values: () => values2,
1268
+ trunc: () => trunc2,
1269
+ values: () => values3,
149
1270
  with: () => _with,
150
1271
  zip: () => zip
151
1272
  });
152
1273
 
153
- // src/vm/lib/_helpers.ts
1274
+ // src/vm/lib/helpers.ts
154
1275
  function throwError(message, recovered) {
155
1276
  const recoveredValue = typeof recovered === "function" && !isVmFunction(recovered) ? recovered() : recovered;
156
1277
  throw new VmError(message, recoveredValue);
157
1278
  }
1279
+ function describeParam(name) {
1280
+ if (name == null) return "Value";
1281
+ if (typeof name == "string") {
1282
+ if (!name) return "Argument";
1283
+ return `Argument '${name}'`;
1284
+ }
1285
+ const pos = name <= 0 ? "first" : name <= 1 ? "second" : `${name + 1}th`;
1286
+ return `Argument at the ${pos} position`;
1287
+ }
158
1288
  function throwUnexpectedTypeError(name, expected, value, recovered) {
159
- const actual = $Type(value);
160
- if (typeof name == "string") throwError(`Expected ${expected} for parameter '${name}', got ${actual}`, recovered);
161
- const pos = name <= 0 ? "first" : name <= 1 ? "second" : name + 1 + "th";
162
- throwError(`Expected ${expected} at the ${pos} position, got ${actual}`, recovered);
1289
+ throwError(`${describeParam(name)} is not ${expected}: ${display(value)}`, recovered);
1290
+ }
1291
+ function throwUnconvertedTypeError(name, expected, value, recovered) {
1292
+ throwError(`${describeParam(name)} cannot be converted to ${expected}: ${display(value)}`, recovered);
163
1293
  }
164
1294
  function rethrowError(prefix, error, recovered) {
165
1295
  const recoveredValue = typeof recovered === "function" && !isVmFunction(recovered) ? recovered() : recovered;
@@ -167,11 +1297,50 @@ function rethrowError(prefix, error, recovered) {
167
1297
  }
168
1298
  function required(name, value, recovered) {
169
1299
  if (value === void 0) {
170
- if (typeof name == "string") throwError(`Missing required parameter '${name}'`, recovered);
171
- const pos = name <= 0 ? "first" : name <= 1 ? "second" : name + 1 + "th";
172
- throwError(`Missing required parameter at the ${pos} position`, recovered);
1300
+ throwError(`${describeParam(name)} is required`, recovered);
173
1301
  }
174
1302
  }
1303
+ function expectNumber(name, value) {
1304
+ required(name, value, Number.NaN);
1305
+ const v = toNumber(value, null);
1306
+ if (v == null) {
1307
+ throwUnconvertedTypeError(name, "number", value, Number.NaN);
1308
+ }
1309
+ return v;
1310
+ }
1311
+ function expectNumberRange(name, value, min3, max2) {
1312
+ const v = expectNumber(name, value);
1313
+ if (!isFinite(v)) {
1314
+ throwError(`${describeParam(name)} is not a finite number: ${display(value)}`, Number.NaN);
1315
+ }
1316
+ if (v < min3) {
1317
+ throwError(`${describeParam(name)} is less than minimum value ${min3}: ${display(value)}`, min3);
1318
+ }
1319
+ if (v > max2) {
1320
+ throwError(`${describeParam(name)} is greater than maximum value ${max2}: ${display(value)}`, max2);
1321
+ }
1322
+ return v;
1323
+ }
1324
+ function expectInteger(name, value) {
1325
+ required(name, value, 0);
1326
+ const v = toNumber(value, null);
1327
+ if (v == null) {
1328
+ throwUnconvertedTypeError(name, "integer", value, 0);
1329
+ }
1330
+ const i = Math.trunc(v);
1331
+ if (!isSafeInteger(i)) {
1332
+ throwUnconvertedTypeError(name, "integer", value, 0);
1333
+ }
1334
+ return i;
1335
+ }
1336
+ function expectString(name, value) {
1337
+ required(name, value, "");
1338
+ const v = toString(value, null);
1339
+ if (v == null) {
1340
+ throwUnconvertedTypeError(name, "string", value, "");
1341
+ }
1342
+ return v;
1343
+ }
175
1344
  function expectArray(name, value, recovered) {
176
1345
  required(name, value, recovered);
177
1346
  if (!isVmArray(value)) {
@@ -204,18 +1373,25 @@ function expectCallable(name, value, recovered) {
204
1373
  }
205
1374
  function getNumbers(args) {
206
1375
  if (args.length === 0) return [];
207
- if (args.length === 1 && isVmArray(args[0])) args = args[0];
1376
+ let useFirst = false;
1377
+ if (args.length === 1 && isVmArray(args[0])) {
1378
+ args = args[0];
1379
+ useFirst = true;
1380
+ }
208
1381
  const numbers = [];
209
- for (const arg of args) {
210
- if (arg == null) continue;
211
- numbers.push($ToNumber(arg));
1382
+ for (let len2 = args.length, i = 0; i < len2; i++) {
1383
+ numbers.push(expectNumber(useFirst ? null : i, args[i]));
212
1384
  }
213
1385
  return numbers;
214
1386
  }
215
1387
  function arrayLen(len2) {
216
- if (len2 == null || isNaN(len2) || len2 <= 0) return 0;
1388
+ if (len2 == null || isNaN(len2) || len2 <= -1) {
1389
+ throwError("Array length must be a non-negative integer", null);
1390
+ }
217
1391
  len2 = Math.trunc(len2);
218
- if (len2 > VM_ARRAY_MAX_LENGTH) throwError(`Array length exceeds maximum limit of ${VM_ARRAY_MAX_LENGTH}`, null);
1392
+ if (len2 > VM_ARRAY_MAX_LENGTH) {
1393
+ throwError(`Array length exceeds maximum limit of ${VM_ARRAY_MAX_LENGTH}`, null);
1394
+ }
219
1395
  return len2;
220
1396
  }
221
1397
  function map(data, mapper) {
@@ -271,7 +1447,7 @@ var max = VmLib(build(Math.max), {
271
1447
  returnsType: "number",
272
1448
  examples: ["max(3, 7, 2) // 7"]
273
1449
  });
274
- var min = VmLib(build(Math.min), {
1450
+ var min2 = VmLib(build(Math.min), {
275
1451
  summary: "返回一组数中的最小值",
276
1452
  params: { "..values": "要比较的数值" },
277
1453
  paramsType: { "..values": "number[]" },
@@ -318,11 +1494,10 @@ var { PI, E } = Math;
318
1494
  // src/vm/lib/global/math-unary.ts
319
1495
  function build2(f) {
320
1496
  return (x) => {
321
- required("x", x, Number.NaN);
322
- return f($ToNumber(x));
1497
+ return f(expectNumber("x", x));
323
1498
  };
324
1499
  }
325
- var trunc = VmLib(build2(Math.trunc), {
1500
+ var trunc2 = VmLib(build2(Math.trunc), {
326
1501
  summary: "返回数值的整数部分(去除小数)",
327
1502
  params: { x: "要取整数部分的数" },
328
1503
  paramsType: { x: "number" },
@@ -334,7 +1509,7 @@ var floor = VmLib(build2(Math.floor), {
334
1509
  paramsType: { x: "number" },
335
1510
  returnsType: "number"
336
1511
  });
337
- var ceil = VmLib(build2(Math.ceil), {
1512
+ var ceil2 = VmLib(build2(Math.ceil), {
338
1513
  summary: "返回大于等于给定数的最小整数",
339
1514
  params: { x: "要向上取整的数" },
340
1515
  paramsType: { x: "number" },
@@ -363,7 +1538,7 @@ var sign = VmLib(build2(Math.sign), {
363
1538
  paramsType: { x: "number" },
364
1539
  returnsType: "number"
365
1540
  });
366
- var abs = VmLib(build2(Math.abs), {
1541
+ var abs2 = VmLib(build2(Math.abs), {
367
1542
  summary: "返回数值的绝对值",
368
1543
  params: { x: "要取绝对值的数" },
369
1544
  paramsType: { x: "number" },
@@ -513,8 +1688,7 @@ var GAMMA_P = [
513
1688
  var SQRT_2_PI = sqrt2(2 * Math.PI);
514
1689
  var factorial = VmLib(
515
1690
  (x) => {
516
- required("x", x, Number.NaN);
517
- let n = $ToNumber(x);
1691
+ let n = expectNumber("x", x);
518
1692
  if (isNaN(n) || n < 0) return Number.NaN;
519
1693
  if (n >= 171) return Number.POSITIVE_INFINITY;
520
1694
  if (isInteger(n)) {
@@ -551,13 +1725,13 @@ var factorial = VmLib(
551
1725
 
552
1726
  // src/vm/lib/global/math.ts
553
1727
  var { atan2: _atan2, pow: _pow } = Math;
554
- var atan2 = VmLib((x, y) => _atan2($ToNumber(x), $ToNumber(y)), {
1728
+ var atan2 = VmLib((x, y) => _atan2(expectNumber(0, x), expectNumber(1, y)), {
555
1729
  summary: "返回从原点到点 (x, y) 的角度(弧度)",
556
1730
  params: { x: "x 坐标", y: "y 坐标" },
557
1731
  paramsType: { x: "number", y: "number" },
558
1732
  returnsType: "number"
559
1733
  });
560
- var pow2 = VmLib((x, y) => _pow($ToNumber(x), $ToNumber(y)), {
1734
+ var pow2 = VmLib((x, y) => _pow(expectNumber(0, x), expectNumber(1, y)), {
561
1735
  summary: "返回 x 的 y 次幂",
562
1736
  params: { x: "底数", y: "指数" },
563
1737
  paramsType: { x: "number", y: "number" },
@@ -573,7 +1747,7 @@ var random = VmLib(Math.random, {
573
1747
  // src/vm/lib/global/bit.ts
574
1748
  var b_and = VmLib(
575
1749
  (x, y) => {
576
- return $ToNumber(x) & $ToNumber(y);
1750
+ return expectNumber(0, x) & expectNumber(1, y);
577
1751
  },
578
1752
  {
579
1753
  summary: "返回两个数的按位与",
@@ -585,7 +1759,7 @@ var b_and = VmLib(
585
1759
  );
586
1760
  var b_or = VmLib(
587
1761
  (x, y) => {
588
- return $ToNumber(x) | $ToNumber(y);
1762
+ return expectNumber(0, x) | expectNumber(1, y);
589
1763
  },
590
1764
  {
591
1765
  summary: "返回两个数的按位或",
@@ -597,7 +1771,7 @@ var b_or = VmLib(
597
1771
  );
598
1772
  var b_not = VmLib(
599
1773
  (x) => {
600
- return ~$ToNumber(x);
1774
+ return ~expectNumber("x", x);
601
1775
  },
602
1776
  {
603
1777
  summary: "返回一个数的按位取反",
@@ -609,7 +1783,7 @@ var b_not = VmLib(
609
1783
  );
610
1784
  var b_xor = VmLib(
611
1785
  (x, y) => {
612
- return $ToNumber(x) ^ $ToNumber(y);
1786
+ return expectNumber(0, x) ^ expectNumber(1, y);
613
1787
  },
614
1788
  {
615
1789
  summary: "返回两个数的按位异或",
@@ -621,7 +1795,7 @@ var b_xor = VmLib(
621
1795
  );
622
1796
  var shl = VmLib(
623
1797
  (x, y) => {
624
- return $ToNumber(x) << $ToNumber(y);
1798
+ return expectNumber(0, x) << expectNumber(1, y);
625
1799
  },
626
1800
  {
627
1801
  summary: "返回第一个操作数左移指定的位数",
@@ -633,7 +1807,7 @@ var shl = VmLib(
633
1807
  );
634
1808
  var sar = VmLib(
635
1809
  (x, y) => {
636
- return $ToNumber(x) >> $ToNumber(y);
1810
+ return expectNumber(0, x) >> expectNumber(1, y);
637
1811
  },
638
1812
  {
639
1813
  summary: "返回第一个操作数右移指定的位数",
@@ -645,7 +1819,7 @@ var sar = VmLib(
645
1819
  );
646
1820
  var shr = VmLib(
647
1821
  (x, y) => {
648
- return $ToNumber(x) >>> $ToNumber(y);
1822
+ return expectNumber(0, x) >>> expectNumber(1, y);
649
1823
  },
650
1824
  {
651
1825
  summary: "返回第一个操作数无符号右移指定的位数",
@@ -658,12 +1832,19 @@ var shr = VmLib(
658
1832
 
659
1833
  // src/vm/lib/global/sequence/with.ts
660
1834
  var arrIndex = (index) => {
661
- const idx = Math.trunc($ToNumber(index));
662
- if (!isSafeInteger(idx) || idx < 0 || idx >= VM_ARRAY_MAX_LENGTH) {
663
- return -1;
1835
+ const idx = Math.trunc(toNumber(index, Number.NaN));
1836
+ if (isNaN(idx) || idx < 0) {
1837
+ throwError("Array index must be a non-negative integer", index);
1838
+ }
1839
+ if (idx >= VM_ARRAY_MAX_LENGTH) {
1840
+ throwError(`Array index exceeds maximum limit of ${VM_ARRAY_MAX_LENGTH}`, index);
664
1841
  }
665
1842
  return idx;
666
1843
  };
1844
+ var isArrIndex = (key) => {
1845
+ if (typeof key != "number") return false;
1846
+ return isInteger(key) && key >= 0 && key < VM_ARRAY_MAX_LENGTH;
1847
+ };
667
1848
  var withInner = (obj, key, keyIndex, value) => {
668
1849
  if (keyIndex >= key.length) {
669
1850
  return value;
@@ -674,7 +1855,7 @@ var withInner = (obj, key, keyIndex, value) => {
674
1855
  result = [...obj];
675
1856
  } else if (isVmRecord(obj)) {
676
1857
  result = { ...obj };
677
- } else if (arrIndex(k) === k) {
1858
+ } else if (isArrIndex(k)) {
678
1859
  result = [];
679
1860
  } else {
680
1861
  result = {};
@@ -686,7 +1867,7 @@ var withInner = (obj, key, keyIndex, value) => {
686
1867
  }
687
1868
  result[index] = withInner(result[index], key, keyIndex + 1, value);
688
1869
  } else {
689
- const prop = $ToString(k);
1870
+ const prop = toString(k, void 0);
690
1871
  result[prop] = withInner(result[prop], key, keyIndex + 1, value);
691
1872
  }
692
1873
  return result;
@@ -728,11 +1909,9 @@ var _with = VmLib(
728
1909
  let val;
729
1910
  if (isVmArray(key)) {
730
1911
  index = arrIndex(key[0]);
731
- if (index < 0) continue;
732
1912
  val = withInner(result[index], key, 1, value);
733
1913
  } else {
734
1914
  index = arrIndex(key);
735
- if (index < 0) continue;
736
1915
  val = value;
737
1916
  }
738
1917
  while (index > result.length) {
@@ -748,10 +1927,10 @@ var _with = VmLib(
748
1927
  let val;
749
1928
  if (isVmArray(key)) {
750
1929
  const firstKey = key[0];
751
- prop = $ToString(firstKey);
1930
+ prop = toString(firstKey, void 0);
752
1931
  val = withInner(result[prop], key, 1, value);
753
1932
  } else {
754
- prop = $ToString(key);
1933
+ prop = toString(key, void 0);
755
1934
  val = value;
756
1935
  }
757
1936
  result[prop] = val;
@@ -767,7 +1946,7 @@ var _with = VmLib(
767
1946
  },
768
1947
  paramsType: {
769
1948
  data: "array | record",
770
- "..entries": `[..[string | number | (string | number)[], any][]]`
1949
+ "..entries": `[..[number | string | (number | string)[], any][]]`
771
1950
  },
772
1951
  returnsType: "type(data)",
773
1952
  examples: [
@@ -778,7 +1957,7 @@ var _with = VmLib(
778
1957
  );
779
1958
 
780
1959
  // src/vm/lib/global/sequence/entries.ts
781
- var keys2 = VmLib(
1960
+ var keys3 = VmLib(
782
1961
  (data) => {
783
1962
  expectCompound("data", data, []);
784
1963
  if (isVmArray(data)) {
@@ -798,11 +1977,11 @@ var keys2 = VmLib(
798
1977
  summary: "返回数组、记录、外部对象或模块的键列表",
799
1978
  params: { data: "要获取键的数组、记录、外部对象或模块" },
800
1979
  paramsType: { data: "array | record | extern | module" },
801
- returnsType: "(string | number)[]",
1980
+ returnsType: "number[] | string[]",
802
1981
  examples: ["keys([10, 20]) // [0, 1]", 'keys((10, 20)) // ["0", "1"]']
803
1982
  }
804
1983
  );
805
- var values2 = VmLib(
1984
+ var values3 = VmLib(
806
1985
  (data) => {
807
1986
  expectArrayOrRecord("data", data, []);
808
1987
  if (isVmArray(data)) {
@@ -835,7 +2014,7 @@ var entries2 = VmLib(
835
2014
  summary: "返回数组或记录的键值对列表",
836
2015
  params: { data: "要获取键值对的数组或记录" },
837
2016
  paramsType: { data: "array | record" },
838
- returnsType: "(string | number, any)[]",
2017
+ returnsType: "(number, any)[] | (string, any)[]",
839
2018
  examples: ["entries([1]) // [(0, 1)]", 'entries((a: 1)) // [("a", 1)]']
840
2019
  }
841
2020
  );
@@ -875,7 +2054,7 @@ var map2 = VmLib(
875
2054
  },
876
2055
  paramsType: {
877
2056
  data: "array | record",
878
- f: "fn(value: any, key: number | string | nil, input: type(data)) -> any"
2057
+ f: "fn(value: any, key: number | string, input: type(data)) -> any"
879
2058
  },
880
2059
  returnsType: "type(data)",
881
2060
  examples: ["map([1, 2, 3], fn (v) { v * v }) // [1, 4, 9]"]
@@ -884,7 +2063,7 @@ var map2 = VmLib(
884
2063
  var filter = VmLib(
885
2064
  (data, predicate) => mapImplWrapped(data, "predicate", predicate, (fn, value, key, data2) => {
886
2065
  const ret = $Call(fn, [value, key, data2]);
887
- return $ToBoolean(ret) ? value : void 0;
2066
+ return toBoolean(ret, void 0) ? value : void 0;
888
2067
  }),
889
2068
  {
890
2069
  summary: "过滤数组或记录中的元素,返回满足条件的元素",
@@ -894,7 +2073,7 @@ var filter = VmLib(
894
2073
  },
895
2074
  paramsType: {
896
2075
  data: "array | record",
897
- predicate: "fn(value: any, key: number | string | nil, input: type(data)) -> boolean"
2076
+ predicate: "fn(value: any, key: number | string, input: type(data)) -> boolean"
898
2077
  },
899
2078
  returnsType: "type(data)",
900
2079
  examples: ["filter([1, 2, 3, 4], fn (v) { v % 2 == 0 }) // [2, 4]"]
@@ -913,7 +2092,7 @@ var filter_map = VmLib(
913
2092
  },
914
2093
  paramsType: {
915
2094
  data: "array | record",
916
- f: "fn(value: any, key: number | string | nil, input: type(data)) -> any | nil"
2095
+ f: "fn(value: any, key: number | string, input: type(data)) -> any | nil"
917
2096
  },
918
2097
  returnsType: "type(data)",
919
2098
  examples: ["filter_map([1, 2, 3], fn (v) { if v % 2 == 0 { v * v } else { nil } }) // [4]"]
@@ -927,7 +2106,7 @@ var find = VmLib(
927
2106
  required("predicate", predicate, null);
928
2107
  const p = isVmCallable(predicate) ? (value, key, data2) => {
929
2108
  const ret = $Call(predicate, [value, key, data2]);
930
- return $ToBoolean(ret);
2109
+ return toBoolean(ret, void 0);
931
2110
  } : (value) => $Same(predicate, value);
932
2111
  if (isVmArray(data)) {
933
2112
  const { length } = data;
@@ -953,14 +2132,14 @@ var find = VmLib(
953
2132
  {
954
2133
  summary: "查找数组或记录中的键值对,返回第一个满足条件的键值对",
955
2134
  params: {
956
- data: "查的数组或记录",
2135
+ data: "要查找的数组或记录",
957
2136
  predicate: "用于测试每个键值对的函数,或要查找的值"
958
2137
  },
959
2138
  paramsType: {
960
2139
  data: "array | record",
961
- predicate: "(fn(value: any, key: number | string | nil, input: type(data)) -> boolean) | any"
2140
+ predicate: "(fn(value: any, key: number | string, input: type(data)) -> boolean) | any"
962
2141
  },
963
- returnsType: "(string | number, any) | nil",
2142
+ returnsType: "(number | string, any) | nil",
964
2143
  examples: ["find([3, 5, 8], fn (v) { v % 2 == 0 }) // (2, 8)", `find((x: 1, y: 2, z: 3), 2) // ('y', 2)`]
965
2144
  }
966
2145
  );
@@ -969,7 +2148,7 @@ var find = VmLib(
969
2148
  var flatten = VmLib(
970
2149
  (data, depth = 1) => {
971
2150
  expectArray("data", data, data);
972
- return data.flat($ToNumber(depth));
2151
+ return data.flat(expectNumber("depth", depth));
973
2152
  },
974
2153
  {
975
2154
  summary: "将数组扁平化",
@@ -1004,7 +2183,7 @@ var zip = VmLib(
1004
2183
  let len2 = 0;
1005
2184
  for (const { 0: key, 1: arr } of ets) {
1006
2185
  if (!isVmArray(arr)) {
1007
- throwError(`data[${serialize(key)}] is not an array`, null);
2186
+ throwError(`data[${display(key)}] is not an array: ${display(arr)}`, null);
1008
2187
  }
1009
2188
  len2 = Math.max(len2, arr.length);
1010
2189
  }
@@ -1043,7 +2222,7 @@ var all = VmLib(
1043
2222
  Cp();
1044
2223
  const value = data[i] ?? null;
1045
2224
  const ret = $Call(predicate, [value, i, data]);
1046
- if (!$ToBoolean(ret)) return false;
2225
+ if (!toBoolean(ret, void 0)) return false;
1047
2226
  }
1048
2227
  return true;
1049
2228
  } else {
@@ -1051,7 +2230,7 @@ var all = VmLib(
1051
2230
  Cp();
1052
2231
  const value = v ?? null;
1053
2232
  const ret = $Call(predicate, [value, key, data]);
1054
- if (!$ToBoolean(ret)) return false;
2233
+ if (!toBoolean(ret, void 0)) return false;
1055
2234
  }
1056
2235
  return true;
1057
2236
  }
@@ -1076,7 +2255,7 @@ var any = VmLib(
1076
2255
  Cp();
1077
2256
  const value = data[i] ?? null;
1078
2257
  const ret = $Call(predicate, [value, i, data]);
1079
- if ($ToBoolean(ret)) return true;
2258
+ if (toBoolean(ret, void 0)) return true;
1080
2259
  }
1081
2260
  return false;
1082
2261
  } else {
@@ -1084,7 +2263,7 @@ var any = VmLib(
1084
2263
  Cp();
1085
2264
  const value = v ?? null;
1086
2265
  const ret = $Call(predicate, [value, key, data]);
1087
- if ($ToBoolean(ret)) return true;
2266
+ if (toBoolean(ret, void 0)) return true;
1088
2267
  }
1089
2268
  return false;
1090
2269
  }
@@ -1111,8 +2290,8 @@ function defaultCompare(a = null, b = null) {
1111
2290
  if (a > b) return 1;
1112
2291
  return 0;
1113
2292
  }
1114
- const an = $ToNumber(a) || 0;
1115
- const bn = $ToNumber(b) || 0;
2293
+ const an = toNumber(a, 0) || 0;
2294
+ const bn = toNumber(b, 0) || 0;
1116
2295
  if (an < bn) return -1;
1117
2296
  if (an > bn) return 1;
1118
2297
  return 0;
@@ -1122,7 +2301,7 @@ function cmp(comparator, recovered) {
1122
2301
  expectCallable("comparator", comparator, recovered);
1123
2302
  return (a = null, b = null) => {
1124
2303
  const ret = $Call(comparator, [a, b]);
1125
- return $ToNumber(ret);
2304
+ return toNumber(ret, 0);
1126
2305
  };
1127
2306
  }
1128
2307
  var sort = VmLib(
@@ -1188,8 +2367,7 @@ var sort_by = VmLib(
1188
2367
  var repeat = VmLib(
1189
2368
  (data, times) => {
1190
2369
  expectConst("data", data, []);
1191
- required("times", times, []);
1192
- const n = arrayLen($ToNumber(times));
2370
+ const n = arrayLen(expectNumber("times", times));
1193
2371
  const result = [];
1194
2372
  result.length = n;
1195
2373
  result.fill(data);
@@ -1231,7 +2409,8 @@ var panic = VmLib(
1231
2409
  (message) => {
1232
2410
  if (message === void 0) console.error(...panic.prefix);
1233
2411
  else console.error(...panic.prefix, message);
1234
- const error = message == null ? "panic" : "panic: " + $ToString(message);
2412
+ const mgsStr = toString(message, null);
2413
+ const error = !mgsStr ? "panic" : "panic: " + mgsStr;
1235
2414
  throw new VmError(error, void 0);
1236
2415
  },
1237
2416
  {
@@ -1289,7 +2468,7 @@ var from_json = VmLib(
1289
2468
  try {
1290
2469
  return parse(json);
1291
2470
  } catch (ex) {
1292
- if (fallback != null) return fallback;
2471
+ if (fallback !== void 0) return fallback;
1293
2472
  rethrowError("Invalid JSON", ex, null);
1294
2473
  }
1295
2474
  },
@@ -1304,48 +2483,57 @@ var from_json = VmLib(
1304
2483
 
1305
2484
  // src/vm/lib/global/to-primitive.ts
1306
2485
  var to_string = VmLib(
1307
- (data) => {
2486
+ (data, fallback) => {
1308
2487
  required("data", data, "");
1309
- return $ToString(data);
2488
+ return toString(data, fallback);
1310
2489
  },
1311
2490
  {
1312
2491
  summary: "将数据转换为字符串",
1313
- params: { data: "要转换的数据" },
1314
- paramsType: { data: "any" },
1315
- returnsType: "string",
2492
+ params: {
2493
+ data: "要转换的数据",
2494
+ fallback: "转换失败时的返回值"
2495
+ },
2496
+ paramsType: { data: "any", fallback: "any" },
2497
+ returnsType: "string | type(fallback)",
1316
2498
  examples: ['to_string([1, 2]) // "1, 2"']
1317
2499
  }
1318
2500
  );
1319
2501
  var to_number = VmLib(
1320
- (data) => {
2502
+ (data, fallback) => {
1321
2503
  required("data", data, Number.NaN);
1322
- return $ToNumber(data);
2504
+ return toNumber(data, fallback);
1323
2505
  },
1324
2506
  {
1325
2507
  summary: "将数据转换为数字",
1326
- params: { data: "要转换的数据" },
1327
- paramsType: { data: "any" },
1328
- returnsType: "number",
2508
+ params: {
2509
+ data: "要转换的数据",
2510
+ fallback: "转换失败时的返回值"
2511
+ },
2512
+ paramsType: { data: "any", fallback: "any" },
2513
+ returnsType: "number | type(fallback)",
1329
2514
  examples: ['to_number("1.5") // 1.5']
1330
2515
  }
1331
2516
  );
1332
2517
  var to_boolean = VmLib(
1333
- (data) => {
2518
+ (data, fallback) => {
1334
2519
  required("data", data, false);
1335
- return $ToBoolean(data);
2520
+ return toBoolean(data, fallback);
1336
2521
  },
1337
2522
  {
1338
2523
  summary: "将数据转换为布尔值",
1339
- params: { data: "要转换的数据" },
1340
- paramsType: { data: "any" },
1341
- returnsType: "boolean",
2524
+ params: {
2525
+ data: "要转换的数据",
2526
+ fallback: "转换失败时的返回值"
2527
+ },
2528
+ paramsType: { data: "any", fallback: "any" },
2529
+ returnsType: "boolean | type(fallback)",
1342
2530
  examples: ["to_boolean(nil) // false"]
1343
2531
  }
1344
2532
  );
1345
2533
  var format = VmLib(
1346
2534
  (data, format2) => {
1347
2535
  required("data", data, "");
1348
- return $Format(data, format2);
2536
+ return toFormat(data, expectString("format", format2));
1349
2537
  },
1350
2538
  {
1351
2539
  summary: "将数据格式化为指定格式的字符串",
@@ -1359,8 +2547,7 @@ var format = VmLib(
1359
2547
  // src/vm/lib/global/string.ts
1360
2548
  var chars = VmLib(
1361
2549
  (str) => {
1362
- required("str", str, null);
1363
- return [...$ToString(str)];
2550
+ return [...expectString("str", str)];
1364
2551
  },
1365
2552
  {
1366
2553
  summary: "将字符串转换为字符数组",
@@ -1372,9 +2559,7 @@ var chars = VmLib(
1372
2559
  );
1373
2560
  var starts_with = VmLib(
1374
2561
  (str, search) => {
1375
- required("str", str, null);
1376
- required("search", search, null);
1377
- return $ToString(str).startsWith($ToString(search));
2562
+ return expectString("str", str).startsWith(expectString("search", search));
1378
2563
  },
1379
2564
  {
1380
2565
  summary: "检查字符串是否以指定子串开头",
@@ -1386,9 +2571,7 @@ var starts_with = VmLib(
1386
2571
  );
1387
2572
  var ends_with = VmLib(
1388
2573
  (str, search) => {
1389
- required("str", str, null);
1390
- required("search", search, null);
1391
- return $ToString(str).endsWith($ToString(search));
2574
+ return expectString("str", str).endsWith(expectString("search", search));
1392
2575
  },
1393
2576
  {
1394
2577
  summary: "检查字符串是否以指定子串结尾",
@@ -1400,9 +2583,7 @@ var ends_with = VmLib(
1400
2583
  );
1401
2584
  var contains = VmLib(
1402
2585
  (str, search) => {
1403
- required("str", str, null);
1404
- required("search", search, null);
1405
- return $ToString(str).includes($ToString(search));
2586
+ return expectString("str", str).includes(expectString("search", search));
1406
2587
  },
1407
2588
  {
1408
2589
  summary: "检查字符串是否包含指定子串",
@@ -1414,8 +2595,7 @@ var contains = VmLib(
1414
2595
  );
1415
2596
  var trim_start = VmLib(
1416
2597
  (str) => {
1417
- required("str", str, null);
1418
- return $ToString(str).trimStart();
2598
+ return expectString("str", str).trimStart();
1419
2599
  },
1420
2600
  {
1421
2601
  summary: "去除字符串开头的空白字符",
@@ -1427,8 +2607,7 @@ var trim_start = VmLib(
1427
2607
  );
1428
2608
  var trim_end = VmLib(
1429
2609
  (str) => {
1430
- required("str", str, null);
1431
- return $ToString(str).trimEnd();
2610
+ return expectString("str", str).trimEnd();
1432
2611
  },
1433
2612
  {
1434
2613
  summary: "去除字符串结尾的空白字符",
@@ -1440,8 +2619,7 @@ var trim_end = VmLib(
1440
2619
  );
1441
2620
  var trim = VmLib(
1442
2621
  (str) => {
1443
- required("str", str, null);
1444
- return $ToString(str).trim();
2622
+ return expectString("str", str).trim();
1445
2623
  },
1446
2624
  {
1447
2625
  summary: "去除字符串两端的空白字符",
@@ -1453,9 +2631,10 @@ var trim = VmLib(
1453
2631
  );
1454
2632
  var replace = VmLib(
1455
2633
  (str, search, replacement = "") => {
1456
- required("str", str, null);
1457
- required("search", search, str);
1458
- return $ToString(str).replaceAll($ToString(search), $ToString(replacement));
2634
+ return expectString("str", str).replaceAll(
2635
+ expectString("search", search),
2636
+ expectString("replacement", replacement)
2637
+ );
1459
2638
  },
1460
2639
  {
1461
2640
  summary: "替换字符串中的指定子串",
@@ -1467,9 +2646,8 @@ var replace = VmLib(
1467
2646
  );
1468
2647
  var split = VmLib(
1469
2648
  (str, separator = "") => {
1470
- required("str", str, null);
1471
- const s = $ToString(str);
1472
- const p = $ToString(separator);
2649
+ const s = expectString("str", str);
2650
+ const p = expectString("separator", separator);
1473
2651
  if (!p) return [...s];
1474
2652
  return s.split(p);
1475
2653
  },
@@ -1484,8 +2662,8 @@ var split = VmLib(
1484
2662
  var join = VmLib(
1485
2663
  (arr, separator = "") => {
1486
2664
  expectArray("arr", arr, null);
1487
- const s = $ToString(separator);
1488
- return arr.map((v) => $ToString(v)).join(s);
2665
+ const s = expectString("separator", separator);
2666
+ return arr.map((v) => expectString(null, v)).join(s);
1489
2667
  },
1490
2668
  {
1491
2669
  summary: "将字符串数组连接为单个字符串",
@@ -1497,33 +2675,54 @@ var join = VmLib(
1497
2675
  );
1498
2676
 
1499
2677
  // src/vm/lib/global/time.ts
2678
+ var fromNumber = (datetime, fallback) => {
2679
+ const n = new Date(datetime).getTime();
2680
+ if (isFinite(n)) return n;
2681
+ if (fallback) return null;
2682
+ throwError(`${describeParam("datetime")} is an invalid timestamp: ${display(datetime)}`, Number.NaN);
2683
+ };
2684
+ var getTimestamp = (datetime, fallback) => {
2685
+ if (datetime == null) {
2686
+ return Date.now();
2687
+ }
2688
+ if (typeof datetime == "number") {
2689
+ return fromNumber(datetime, fallback);
2690
+ }
2691
+ if (typeof datetime != "string") {
2692
+ if (fallback) return null;
2693
+ throwUnexpectedTypeError("datetime", "number | string", datetime, Number.NaN);
2694
+ }
2695
+ const num2 = toNumber(datetime, Number.NaN);
2696
+ if (!isNaN(num2)) {
2697
+ return fromNumber(num2, fallback);
2698
+ }
2699
+ const parsed = Date.parse(datetime);
2700
+ if (isFinite(parsed)) return parsed;
2701
+ if (fallback) return null;
2702
+ throwError(`${describeParam("datetime")} cannot be parsed as datetime: ${display(datetime)}`, Number.NaN);
2703
+ };
1500
2704
  var to_timestamp = VmLib(
1501
- (datetime) => {
1502
- if (datetime == null) {
1503
- return Date.now();
1504
- }
1505
- if (typeof datetime == "number") {
1506
- return new Date(datetime).getTime();
1507
- }
1508
- const str = $ToString(datetime);
1509
- if (!str) return Number.NaN;
1510
- const num2 = $ToNumber(str);
1511
- if (isFinite(num2)) return num2;
1512
- return Date.parse(str);
2705
+ (datetime, fallback) => {
2706
+ const timestamp = getTimestamp(datetime, fallback !== void 0);
2707
+ if (timestamp == null) return fallback;
2708
+ return timestamp;
1513
2709
  },
1514
2710
  {
1515
2711
  summary: "将数据转换为 Unix 毫秒时间戳",
1516
- params: { datetime: "要转换的数据,默认为当前时间" },
1517
- paramsType: { datetime: "string | number" },
1518
- returnsType: "number",
2712
+ params: {
2713
+ datetime: "要转换的数据,默认为当前时间",
2714
+ fallback: "转换失败时的返回值"
2715
+ },
2716
+ paramsType: { datetime: "number | string", fallback: "any" },
2717
+ returnsType: "number | type(fallback)",
1519
2718
  examples: ['to_timestamp("1970-01-01T00:00:00Z") // 0']
1520
2719
  }
1521
2720
  );
1522
2721
  var to_datetime = VmLib(
1523
- (datetime, offset) => {
1524
- const timestamp = to_timestamp(datetime);
1525
- if (!isFinite(timestamp)) return null;
1526
- const o = $ToNumber(offset ?? 0) || 0;
2722
+ (datetime, offset, fallback) => {
2723
+ const timestamp = getTimestamp(datetime, fallback !== void 0);
2724
+ if (timestamp == null) return fallback;
2725
+ const o = expectNumberRange("offset", offset ?? 0, -24, 24);
1527
2726
  const dateOffset = new Date(timestamp + o * 1e3 * 60 * 60);
1528
2727
  return {
1529
2728
  year: dateOffset.getUTCFullYear(),
@@ -1541,10 +2740,11 @@ var to_datetime = VmLib(
1541
2740
  summary: "将数据转换为 Date 记录",
1542
2741
  params: {
1543
2742
  datetime: "要转换的数据,默认为当前时间",
1544
- offset: "时区偏移量(单位:小时),默认为 0"
2743
+ offset: "时区偏移量(单位:小时),默认为 0",
2744
+ fallback: "转换失败时的返回值"
1545
2745
  },
1546
- paramsType: { datetime: "string | number", offset: "number" },
1547
- returnsType: "Date",
2746
+ paramsType: { datetime: "number | string", offset: "number", fallback: "any" },
2747
+ returnsType: "Date | type(fallback)",
1548
2748
  examples: [
1549
2749
  `
1550
2750
  to_datetime(0)
@@ -1558,21 +2758,30 @@ to_datetime(0)
1558
2758
  }
1559
2759
  );
1560
2760
  var to_iso8601 = VmLib(
1561
- (datetime) => {
1562
- const timestamp = to_timestamp(datetime);
1563
- if (!isFinite(timestamp)) return null;
2761
+ (datetime, fallback) => {
2762
+ const timestamp = getTimestamp(datetime, fallback !== void 0);
2763
+ if (timestamp == null) return fallback;
1564
2764
  return new Date(timestamp).toISOString();
1565
2765
  },
1566
2766
  {
1567
2767
  summary: "将数据转换为 ISO 8601 格式的字符串",
1568
- params: { datetime: "要转换的数据,默认为当前时间" },
1569
- paramsType: { datetime: "string | number" },
1570
- returnsType: "string",
2768
+ params: {
2769
+ datetime: "要转换的数据,默认为当前时间",
2770
+ fallback: "转换失败时的返回值"
2771
+ },
2772
+ paramsType: { datetime: "number | string", fallback: "any" },
2773
+ returnsType: "string | type(fallback)",
1571
2774
  examples: ['to_iso8601(0) // "1970-01-01T00:00:00.000Z"']
1572
2775
  }
1573
2776
  );
1574
2777
 
1575
- // src/vm/lib/global/mod/matrix.ts
2778
+ // src/vm/lib/mod/index.ts
2779
+ var mod_exports = {};
2780
+ __export(mod_exports, {
2781
+ matrix: () => matrix_exports
2782
+ });
2783
+
2784
+ // src/vm/lib/mod/matrix.ts
1576
2785
  var matrix_exports = {};
1577
2786
  __export(matrix_exports, {
1578
2787
  add: () => add,
@@ -1589,12 +2798,12 @@ __export(matrix_exports, {
1589
2798
  transpose: () => transpose,
1590
2799
  zeros: () => zeros
1591
2800
  });
1592
- function sizeImpl(matrix2) {
1593
- if (!isVmArray(matrix2)) return [];
1594
- if (matrix2.length === 0) return [0];
1595
- const numRows = matrix2.length;
2801
+ function sizeImpl(matrix) {
2802
+ if (!isVmArray(matrix)) return [];
2803
+ if (matrix.length === 0) return [0];
2804
+ const numRows = matrix.length;
1596
2805
  let numCols = 0;
1597
- for (const row of matrix2) {
2806
+ for (const row of matrix) {
1598
2807
  if (isVmArray(row)) {
1599
2808
  numCols = Math.max(numCols, row.length);
1600
2809
  } else {
@@ -1604,12 +2813,12 @@ function sizeImpl(matrix2) {
1604
2813
  return [numRows, numCols];
1605
2814
  }
1606
2815
  function num(v) {
1607
- return $ToNumber(v ?? null);
2816
+ return toNumber(v, void 0);
1608
2817
  }
1609
2818
  var size = VmLib(
1610
- (matrix2) => {
1611
- required("matrix", matrix2, []);
1612
- return sizeImpl(matrix2);
2819
+ (matrix) => {
2820
+ required("matrix", matrix, []);
2821
+ return sizeImpl(matrix);
1613
2822
  },
1614
2823
  {
1615
2824
  summary: "获取矩阵尺寸",
@@ -1620,16 +2829,16 @@ var size = VmLib(
1620
2829
  }
1621
2830
  );
1622
2831
  var transpose = VmLib(
1623
- (matrix2) => {
1624
- required("matrix", matrix2, []);
1625
- const [numRows, numCols] = sizeImpl(matrix2);
1626
- if (numRows == null || numCols == null) return matrix2;
2832
+ (matrix) => {
2833
+ required("matrix", matrix, []);
2834
+ const [numRows, numCols] = sizeImpl(matrix);
2835
+ if (numRows == null || numCols == null) return matrix;
1627
2836
  const transposed = [];
1628
2837
  for (let j = 0; j < numCols; j++) {
1629
2838
  Cp();
1630
2839
  const tj = [];
1631
2840
  for (let i = 0; i < numRows; i++) {
1632
- const row = matrix2[i] ?? null;
2841
+ const row = matrix[i] ?? null;
1633
2842
  const item = row?.[j] ?? null;
1634
2843
  tj[i] = item;
1635
2844
  }
@@ -2029,7 +3238,7 @@ var identity = VmLib(
2029
3238
  var diagonal = VmLib(
2030
3239
  (x, k = 0) => {
2031
3240
  expectArray("x", x, []);
2032
- const fk = Math.round($ToNumber(k) || 0);
3241
+ const fk = expectInteger("k", k);
2033
3242
  if (x.every((e) => isArray(e))) {
2034
3243
  const diag = [];
2035
3244
  for (let i = 0; i < x.length; i++) {
@@ -2070,13 +3279,7 @@ var diagonal = VmLib(
2070
3279
  }
2071
3280
  );
2072
3281
 
2073
- // src/vm/lib/global/mod/index.ts
2074
- var matrix = createModule("matrix", matrix_exports);
2075
-
2076
- // src/vm/lib/_loader.ts
2077
- for (const [name, value] of entries(global_exports)) {
2078
- VmSharedContext[name] = wrapEntry(name, value, "global");
2079
- }
3282
+ // src/vm/lib/loader.ts
2080
3283
  function wrapEntry(name, value, module) {
2081
3284
  if (typeof value == "function") {
2082
3285
  if (value.name !== name) {
@@ -2102,423 +3305,33 @@ function createModule(name, lib2) {
2102
3305
  }
2103
3306
  return new VmModule(name, mod);
2104
3307
  }
2105
- var lib = global_exports;
2106
-
2107
- // src/helpers/serialize.ts
2108
- var REG_IDENTIFIER_FULL = new RegExp(`^${REG_IDENTIFIER.source}$`, REG_IDENTIFIER.flags);
2109
- var REG_ORDINAL_FULL = new RegExp(`^${REG_ORDINAL.source}$`, REG_ORDINAL.flags);
2110
- var DEFAULT_OPTIONS = Object.freeze({
2111
- maxDepth: 128,
2112
- serializeNil,
2113
- serializeBoolean,
2114
- serializeNumber,
2115
- serializeString: serializeStringImpl,
2116
- serializeStringQuote: (value) => value,
2117
- serializeStringEscape: (value) => value,
2118
- serializeStringContent: (value) => value,
2119
- serializeArray,
2120
- serializeRecord,
2121
- serializePropName: String,
2122
- serializeFunction: serializeNil,
2123
- serializeModule: serializeNil,
2124
- serializeExtern: serializeNil
2125
- });
2126
- function isDefaultOptions(options) {
2127
- return options == null || options === DEFAULT_OPTIONS;
2128
- }
2129
- function getSerializeOptions(options) {
2130
- if (isDefaultOptions(options)) return DEFAULT_OPTIONS;
2131
- let opt = null;
2132
- for (const key in options) {
2133
- if (!hasOwn(options, key) || !hasOwn(DEFAULT_OPTIONS, key)) continue;
2134
- const el = options[key];
2135
- if (el == null) continue;
2136
- opt ??= { ...DEFAULT_OPTIONS };
2137
- opt[key] = el;
2138
- }
2139
- return opt ? Object.freeze(opt) : DEFAULT_OPTIONS;
2140
- }
2141
- function serializeStringImpl(value, options) {
2142
- if (!/[\p{C}'"`$\\]/u.test(value)) {
2143
- const oq = options.serializeStringQuote(`'`, true, options);
2144
- const cq = options.serializeStringQuote(`'`, false, options);
2145
- const c = options.serializeStringContent(value, options);
2146
- return oq + c + cq;
2147
- }
2148
- let ret = options.serializeStringQuote(`'`, true, options);
2149
- for (const char of value) {
2150
- if (char === "'") {
2151
- ret += options.serializeStringEscape(String.raw`\'`, options);
2152
- } else if (char === "\0") {
2153
- ret += options.serializeStringEscape(String.raw`\0`, options);
2154
- } else if (char === "\n") {
2155
- ret += options.serializeStringEscape(String.raw`\n`, options);
2156
- } else if (char === "\r") {
2157
- ret += options.serializeStringEscape(String.raw`\r`, options);
2158
- } else if (char === " ") {
2159
- ret += options.serializeStringEscape(String.raw`\t`, options);
2160
- } else if (char === "\b") {
2161
- ret += options.serializeStringEscape(String.raw`\b`, options);
2162
- } else if (char === "\f") {
2163
- ret += options.serializeStringEscape(String.raw`\f`, options);
2164
- } else if (char === "\v") {
2165
- ret += options.serializeStringEscape(String.raw`\v`, options);
2166
- } else if (char === "\\") {
2167
- ret += options.serializeStringEscape(String.raw`\\`, options);
2168
- } else if (char === "$") {
2169
- ret += options.serializeStringEscape(String.raw`\$`, options);
2170
- } else if (/\p{C}/u.test(char)) {
2171
- const code = char.codePointAt(0);
2172
- if (code <= 127) {
2173
- ret += options.serializeStringEscape(String.raw`\x${code.toString(16).padStart(2, "0")}`, options);
2174
- } else if (code >= 55296 && code <= 57343) {
2175
- ret += options.serializeStringContent("�", options);
2176
- } else {
2177
- ret += options.serializeStringEscape(String.raw`\u{${code.toString(16)}}`, options);
2178
- }
2179
- } else {
2180
- ret += options.serializeStringContent(char, options);
2181
- }
2182
- }
2183
- ret += options.serializeStringQuote(`'`, false, options);
2184
- return ret;
2185
- }
2186
- function serializeString(value, options) {
2187
- return serializeStringImpl(value, getSerializeOptions(options));
2188
- }
2189
- function serializeRecordKeyDefault(key) {
2190
- if (REG_ORDINAL_FULL.test(key) || REG_IDENTIFIER_FULL.test(key)) {
2191
- return key;
2192
- }
2193
- return serializeStringImpl(key, DEFAULT_OPTIONS);
2194
- }
2195
- function serializeRecordKeyOpt(value, options) {
2196
- if (isDefaultOptions(options)) {
2197
- return serializeRecordKeyDefault(value);
2198
- }
2199
- if (REG_ORDINAL_FULL.test(value)) {
2200
- return options.serializePropName(Number(value), options);
2201
- }
2202
- if (REG_IDENTIFIER_FULL.test(value)) {
2203
- return options.serializePropName(value, options);
2204
- }
2205
- return options.serializeString(value, options);
2206
- }
2207
- function serializeRecordKey(key, options) {
2208
- if (isDefaultOptions(options)) {
2209
- return serializeRecordKeyDefault(key);
2210
- }
2211
- return serializeRecordKeyOpt(key, getSerializeOptions(options));
2212
- }
2213
- function serializeNil() {
2214
- return "nil";
2215
- }
2216
- function serializeBoolean(value) {
2217
- return value ? "true" : "false";
2218
- }
2219
- function serializeNumber(value) {
2220
- if (isNaN(value)) return "nan";
2221
- if (!isFinite(value)) return value < 0 ? "-inf" : "inf";
2222
- if (value === 0) {
2223
- if (1 / value < 0) return "-0";
2224
- return "0";
2225
- }
2226
- return String(value);
2227
- }
2228
- function serializeArray(value, depth, options) {
2229
- if (depth > options.maxDepth) return `[]`;
2230
- if (value.length === 0) return "[]";
2231
- let str = "[";
2232
- for (let i = 0; i < value.length; i++) {
2233
- if (i > 0) str += ", ";
2234
- str += serializeImpl(value[i], depth, options);
2235
- }
2236
- str += "]";
2237
- return str;
2238
- }
2239
- var { valueOf } = Object.prototype;
2240
- function customValueOf(value) {
2241
- const thisValueOf = value.valueOf;
2242
- if (typeof thisValueOf != "function" || thisValueOf === valueOf) {
2243
- return void 0;
2244
- }
2245
- const customValue = thisValueOf.call(value);
2246
- if (customValue === value) return void 0;
2247
- return customValue;
2248
- }
2249
- function serializeRecord(value, depth, options) {
2250
- const customValue = customValueOf(value);
2251
- if (customValue !== void 0) {
2252
- return serializeImpl(customValue, depth - 1, options);
2253
- }
2254
- if (depth > options.maxDepth) return `()`;
2255
- const e = entries(value);
2256
- if (e.length === 0) return "()";
2257
- if (e.length === 1) {
2258
- const [k, v] = e[0];
2259
- if (k === "0") {
2260
- return `(${serializeImpl(v, depth, options)},)`;
2261
- }
2262
- return `(${serializeRecordKeyOpt(k, options)}: ${serializeImpl(v, depth, options)})`;
2263
- }
2264
- const omitKey = isVmArrayLikeRecordByEntires(e);
2265
- let str = "(";
2266
- for (const [key, val] of e) {
2267
- if (str.length > 1) str += ", ";
2268
- if (omitKey) {
2269
- str += serializeImpl(val, depth, options);
2270
- } else {
2271
- str += `${serializeRecordKeyOpt(key, options)}: ${serializeImpl(val, depth, options)}`;
2272
- }
2273
- }
2274
- str += ")";
2275
- return str;
2276
- }
2277
- function serializeImpl(value, depth, options) {
2278
- if (value == null) {
2279
- return options.serializeNil(options);
2280
- }
2281
- if (typeof value == "boolean") {
2282
- return options.serializeBoolean(value, options);
2283
- }
2284
- if (typeof value == "number") {
2285
- return options.serializeNumber(value, options);
2286
- }
2287
- if (typeof value == "string") {
2288
- return options.serializeString(value, options);
2289
- }
2290
- if (isVmFunction(value)) {
2291
- return options.serializeFunction(value, options);
2292
- }
2293
- if (isVmModule(value)) {
2294
- return options.serializeModule(value, depth + 1, options);
2295
- }
2296
- if (isVmExtern(value)) {
2297
- return options.serializeExtern(value, depth + 1, options);
2298
- }
2299
- if (isVmArray(value)) {
2300
- return options.serializeArray(value, depth + 1, options);
2301
- }
2302
- if (isVmRecord(value)) {
2303
- return options.serializeRecord(value, depth + 1, options);
2304
- }
2305
- value;
2306
- return options.serializeNil(options);
2307
- }
2308
- function serialize(value, options) {
2309
- return serializeImpl(value, 0, getSerializeOptions(options));
2310
- }
2311
-
2312
- // src/compiler/index.ts
2313
- import { loadModule } from "@mirascript/bindings";
2314
-
2315
- // src/vm/env.ts
2316
- var keys3 = [];
2317
- var values3 = [];
2318
- for (const [key, value] of entries(operations_exports)) {
2319
- keys3.push(key);
2320
- values3.push(value);
2321
- }
2322
- for (const [key, value] of entries(helpers_exports)) {
2323
- keys3.push(key);
2324
- values3.push(value);
2325
- }
2326
-
2327
- // src/compiler/create-script.ts
2328
- var kVmScript = Symbol.for("mirascript.vm.script");
2329
- function wrapScript(source, script) {
2330
- if (kVmScript in script) {
2331
- return script;
2332
- }
2333
- defineProperty(script, kVmScript, { value: true });
2334
- if (typeof source === "string") {
2335
- defineProperty(script, "source", { value: source, configurable: true });
2336
- } else if (source instanceof Uint8Array) {
2337
- defineProperty(script, "source", { value: "<buffer>", configurable: true });
2338
- }
2339
- return script;
2340
- }
2341
- function createScript(source, code) {
2342
- let script;
2343
- try {
2344
- script = new Function(...keys3, code)(...values3);
2345
- } catch (error) {
2346
- throw new Error(`Failed to create script`, { cause: error });
2347
- }
2348
- return wrapScript(source, script);
2349
- }
2350
-
2351
- // src/compiler/compile-fast.ts
2352
- var REG_NUMBER_FULL = /^\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
2353
- var REG_IDENTIFIER_FAST = /^(?:\$+|@+)[a-zA-Z0-9_]*$/;
2354
- var FAST_SCRIPT_MAX_LEN = 32;
2355
- function compileScriptFast(code, options) {
2356
- if (code.length > FAST_SCRIPT_MAX_LEN) return void 0;
2357
- const trimmedCode = code.trim();
2358
- if (!trimmedCode) {
2359
- return wrapScript(code, () => null);
2360
- }
2361
- switch (trimmedCode) {
2362
- case "nil":
2363
- return wrapScript(code, () => null);
2364
- case "true":
2365
- return wrapScript(code, () => true);
2366
- case "false":
2367
- return wrapScript(code, () => false);
2368
- case "nan":
2369
- return wrapScript(code, () => 0 / 0);
2370
- case "inf":
2371
- case "+inf":
2372
- return wrapScript(code, () => 1 / 0);
2373
- case "-inf":
2374
- return wrapScript(code, () => -1 / 0);
2375
- }
2376
- if (REG_IDENTIFIER_FAST.test(trimmedCode)) {
2377
- const id = trimmedCode;
2378
- return wrapScript(code, (global = GlobalFallback()) => global.get(id));
2379
- }
2380
- if (REG_NUMBER_FULL.test(trimmedCode)) {
2381
- const num2 = Number(trimmedCode);
2382
- if (!isFinite(num2)) return void 0;
2383
- return wrapScript(code, () => num2);
2384
- }
2385
- return void 0;
2386
- }
2387
- var FAST_TEMPLATE_MAX_LEN = 1024;
2388
- function compileTemplateFast(code, options) {
2389
- if (code.length > FAST_TEMPLATE_MAX_LEN) return void 0;
2390
- if (!code.includes("$")) {
2391
- return wrapScript(code, () => code);
2392
- }
2393
- return void 0;
2394
- }
2395
- function compileFast(code, options) {
2396
- if (options.sourceMap) return void 0;
2397
- return (options.input_mode === "Template" ? compileTemplateFast : compileScriptFast)(code, options);
2398
- }
2399
-
2400
- // src/compiler/worker-manager.ts
2401
- var worker;
2402
- async function getWorker() {
2403
- if (worker) return worker;
2404
- worker = new Promise((resolve, reject) => {
2405
- const w = new Worker(new URL("#compiler/worker", import.meta.url), {
2406
- type: "module",
2407
- name: "@mirascript/compiler"
2408
- });
2409
- const onError = (e) => {
2410
- cleanUp();
2411
- reject(new Error(`Worker failed to start: ${e.message}`));
2412
- };
2413
- const onMessage = (e) => {
2414
- if (e.data === "ready") {
2415
- cleanUp();
2416
- resolve(w);
2417
- } else if (e.data instanceof Error) {
2418
- cleanUp();
2419
- reject(e.data);
2420
- }
2421
- };
2422
- w.addEventListener("error", onError);
2423
- w.addEventListener("message", onMessage);
2424
- const cleanUp = () => {
2425
- w.removeEventListener("error", onError);
2426
- w.removeEventListener("message", onMessage);
2427
- };
2428
- setTimeout(() => {
2429
- onError(new ErrorEvent("error", { message: "Worker did not respond in time" }));
2430
- }, 3e4);
2431
- });
2432
- return worker;
2433
- }
2434
- async function compileWorker(...args) {
2435
- const worker2 = await getWorker();
2436
- const seq = Math.random();
2437
- worker2.postMessage([seq, ...args]);
2438
- return await new Promise((resolve, reject) => {
2439
- const callback = (ev) => {
2440
- const data = ev.data;
2441
- if (!Array.isArray(data)) return;
2442
- const [retSeq, ...rest] = data;
2443
- if (seq !== retSeq) return;
2444
- worker2.removeEventListener("message", callback);
2445
- if (rest.length === 2) {
2446
- resolve(rest);
2447
- } else {
2448
- reject(rest[0]);
2449
- }
2450
- };
2451
- worker2.addEventListener("message", callback);
2452
- });
2453
- }
2454
3308
 
2455
- // src/compiler/index.ts
2456
- await loadModule();
2457
- var WORKER_MIN_LEN = typeof Worker != "function" ? Number.MAX_VALUE : 1024;
2458
- function reportDiagnostic(source, diagnostics) {
2459
- const parsed = parseDiagnostics(source, diagnostics);
2460
- const messages = parsed.errors.map(formatDiagnostic);
2461
- throw new Error(`Failed to compile:
2462
- ${messages.join("\n")}`);
2463
- }
2464
- function emitScript(source, [code, diagnostics], options) {
2465
- if (!code) {
2466
- reportDiagnostic(source, diagnostics);
2467
- }
2468
- const sourcemaps = options.sourceMap ? parseDiagnostics(source, diagnostics, (c) => c === DiagnosticCode.SourceMap).sourcemaps : [];
2469
- const target = emit(source, code, sourcemaps, options);
2470
- return createScript(source, target);
2471
- }
2472
- async function compile(source, options = {}) {
2473
- if (options.sourceMap) {
2474
- options.diagnostic_sourcemap = true;
2475
- options.diagnostic_position_encoding ??= "Utf16";
2476
- }
2477
- if (typeof source == "string") {
2478
- const result = compileFast(source, options);
2479
- if (result) return result;
2480
- }
2481
- if (source.length < WORKER_MIN_LEN) {
2482
- const bc = await generateBytecode(source, options);
2483
- return emitScript(source, bc, options);
2484
- }
2485
- const [target, diagnostics] = await compileWorker(source, options);
2486
- if (target == null) {
2487
- reportDiagnostic(source, diagnostics);
2488
- }
2489
- return createScript(source, target);
3309
+ // src/vm/lib/index.ts
3310
+ for (const [name, value] of entries(global_exports)) {
3311
+ VmSharedContext[name] = wrapEntry(name, value, "global");
2490
3312
  }
2491
- function compileSync(source, options = {}) {
2492
- if (typeof source == "string") {
2493
- const result = compileFast(source, options);
2494
- if (result) return result;
2495
- }
2496
- const bc = generateBytecodeSync(source, options);
2497
- return emitScript(source, bc, options);
3313
+ for (const [name, value] of entries(mod_exports)) {
3314
+ const mod = createModule(name, value);
3315
+ VmSharedContext[name] = wrapEntry(name, mod, "global");
2498
3316
  }
2499
-
2500
- // src/subtle.ts
2501
- var keywords = () => {
2502
- const kw = Object.freeze(getModule().keywords());
2503
- keywords = () => kw;
2504
- return kw;
2505
- };
3317
+ var lib = Object.freeze(Object.assign(create(null), global_exports, mod_exports));
2506
3318
 
2507
3319
  export {
2508
- constants_exports,
3320
+ operations_exports,
3321
+ VmExtern,
3322
+ wrapToVmValue,
3323
+ unwrapFromVmValue,
3324
+ configCheckpoint,
3325
+ VmFunction,
3326
+ VmSharedContext,
3327
+ defineVmContextValue,
3328
+ DefaultVmContext,
3329
+ createVmContext,
2509
3330
  emitScript,
2510
3331
  compile,
2511
3332
  compileSync,
2512
- keywords,
3333
+ VmModule,
2513
3334
  debug_print,
2514
- lib,
2515
- serializeString,
2516
- serializeRecordKey,
2517
- serializeNil,
2518
- serializeBoolean,
2519
- serializeNumber,
2520
- serializeArray,
2521
- serializeRecord,
2522
- serialize
2523
- };
2524
- //# sourceMappingURL=chunk-Q74RKZ7O.js.map
3335
+ lib
3336
+ };
3337
+ //# sourceMappingURL=chunk-LU4ZKFF6.js.map