@junoscript/juno 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/Modules/async.ts +81 -0
  2. package/Modules/juno-node-fs.ts +105 -0
  3. package/Modules/juno-test.jn +156 -0
  4. package/dist/CLI/build-juno.d.ts +5 -0
  5. package/dist/CLI/build-juno.js +58 -0
  6. package/dist/CLI/generate-juno-types.d.ts +1 -0
  7. package/dist/CLI/generate-juno-types.js +51 -0
  8. package/dist/CLI/junode.d.ts +2 -0
  9. package/dist/CLI/junode.js +32 -0
  10. package/dist/Lexer/lexer.d.ts +42 -0
  11. package/dist/Lexer/lexer.js +300 -0
  12. package/dist/Lexer/parser.d.ts +395 -0
  13. package/dist/Lexer/parser.js +1881 -0
  14. package/dist/Modules/async.d.ts +33 -0
  15. package/dist/Modules/async.js +76 -0
  16. package/dist/Modules/index.d.ts +195 -0
  17. package/dist/Modules/index.js +31 -0
  18. package/dist/Modules/juno-node-fs.d.ts +52 -0
  19. package/dist/Modules/juno-node-fs.js +129 -0
  20. package/dist/Modules/juno-node.d.ts +74 -0
  21. package/dist/Modules/juno-node.js +56 -0
  22. package/dist/Modules/juno-test.d.ts +141 -0
  23. package/dist/Modules/juno-test.js +134 -0
  24. package/dist/Modules/juno-types.d.ts +35 -0
  25. package/dist/Modules/juno-types.js +2 -0
  26. package/dist/Modules/juno.d.ts +21 -0
  27. package/dist/Modules/juno.js +76 -0
  28. package/dist/Modules/types.d.ts +56 -0
  29. package/dist/Modules/types.js +87 -0
  30. package/dist/Runtime/interpreter.d.ts +64 -0
  31. package/dist/Runtime/interpreter.js +2533 -0
  32. package/dist/Runtime/resolve-import.d.ts +2 -0
  33. package/dist/Runtime/resolve-import.js +30 -0
  34. package/dist/vscode-junoscript/src/language.d.ts +86 -0
  35. package/dist/vscode-junoscript/src/language.js +4206 -0
  36. package/package.json +19 -4
  37. package/types/array.jn +158 -0
  38. package/types/boolean.jn +18 -0
  39. package/types/error.jn +28 -0
  40. package/types/error.ts +9 -0
  41. package/types/index.jn +11 -0
  42. package/types/iterable.jn +211 -0
  43. package/types/map.jn +44 -0
  44. package/types/map.ts +132 -0
  45. package/types/number.ts +52 -0
  46. package/types/object.jn +94 -0
  47. package/types/object.ts +49 -0
  48. package/types/queue.jn +46 -0
  49. package/types/random.jn +25 -0
  50. package/types/random.ts +1 -0
  51. package/types/range.jn +27 -0
  52. package/types/set.jn +139 -0
  53. package/types/set.ts +209 -0
  54. package/types/string.jn +33 -0
  55. package/types/string.ts +1 -0
  56. package/types/tuple.jn +11 -0
  57. package/README.md +0 -3
@@ -0,0 +1,2533 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Interpreter = void 0;
4
+ exports.runFile = runFile;
5
+ exports.runBuiltModule = runBuiltModule;
6
+ const node_fs_1 = require("node:fs");
7
+ const node_path_1 = require("node:path");
8
+ const parser_1 = require("../Lexer/parser");
9
+ const Modules_1 = require("../Modules");
10
+ const language_js_1 = require("../vscode-junoscript/src/language.js");
11
+ const resolve_import_1 = require("./resolve-import");
12
+ class ReturnValue {
13
+ value;
14
+ constructor(value) {
15
+ this.value = value;
16
+ }
17
+ }
18
+ class BreakSignal {
19
+ }
20
+ function expressionContainsAwait(expression) {
21
+ switch (expression.kind) {
22
+ case 'Unary': return expression.operator === 'await' || expressionContainsAwait(expression.operand);
23
+ case 'Template': return expression.parts.some(part => typeof part !== 'string' && expressionContainsAwait(part));
24
+ case 'Assignment': return expressionContainsAwait(expression.value);
25
+ case 'MemberAssignment': return expressionContainsAwait(expression.object) || Boolean(expression.index && expressionContainsAwait(expression.index)) || expressionContainsAwait(expression.value);
26
+ case 'Array': return expression.elements.some(expressionContainsAwait);
27
+ case 'Spread': return expressionContainsAwait(expression.value);
28
+ case 'Object': return expression.properties.some(property => property.value.kind !== 'Function' && expressionContainsAwait(property.value));
29
+ case 'Binary': return expressionContainsAwait(expression.left) || expressionContainsAwait(expression.right);
30
+ case 'Conditional': return expressionContainsAwait(expression.condition) || expressionContainsAwait(expression.consequent) || expressionContainsAwait(expression.alternate);
31
+ case 'Match': return expressionContainsAwait(expression.value) || expression.cases.some(item => Boolean(item.guard && expressionContainsAwait(item.guard)) || statementsContainAwait(item.body));
32
+ case 'Try': return Boolean(expression.value && expressionContainsAwait(expression.value)) || Boolean(expression.body && statementsContainAwait(expression.body)) || expression.catches.some(item => statementsContainAwait(item.body)) || Boolean(expression.finallyBody && statementsContainAwait(expression.finallyBody));
33
+ case 'Is': return expressionContainsAwait(expression.value);
34
+ case 'Member': return expressionContainsAwait(expression.object);
35
+ case 'Index': return expressionContainsAwait(expression.object) || expressionContainsAwait(expression.index);
36
+ case 'Call': return expressionContainsAwait(expression.callee) || expression.args.some(expressionContainsAwait);
37
+ case 'Function': return false;
38
+ default: return false;
39
+ }
40
+ }
41
+ function statementContainsAwait(statement) {
42
+ switch (statement.kind) {
43
+ case 'Variable': return Boolean(statement.initializer && expressionContainsAwait(statement.initializer));
44
+ case 'Destructure':
45
+ case 'ArrayDestructure': return expressionContainsAwait(statement.initializer);
46
+ case 'Return': return Boolean(statement.value && expressionContainsAwait(statement.value));
47
+ case 'ExpressionStatement': return expressionContainsAwait(statement.expression);
48
+ case 'If': return expressionContainsAwait(statement.condition) || statementsContainAwait(statement.consequent) || Boolean(statement.alternate && statementsContainAwait(statement.alternate));
49
+ case 'While': return expressionContainsAwait(statement.condition) || statementsContainAwait(statement.body);
50
+ case 'ForOf': return expressionContainsAwait(statement.iterable) || statementsContainAwait(statement.body);
51
+ case 'Export': return statementContainsAwait(statement.declaration);
52
+ default: return false;
53
+ }
54
+ }
55
+ function statementsContainAwait(statements) {
56
+ return statements.some(statementContainsAwait);
57
+ }
58
+ class Interpreter {
59
+ globals = { bindings: new Map(), types: new Map() };
60
+ currentDirectory = process.cwd();
61
+ currentFile;
62
+ sourceFiles = new WeakMap();
63
+ errorTraces = new WeakMap();
64
+ callStack = [];
65
+ constructor() {
66
+ ;
67
+ globalThis[Symbol.for('junoscript.captureStackTrace')] = () => this.captureStackTrace();
68
+ this.globals.bindings.set('isType', { value: (value, type) => matchesType(value, type), mutable: false });
69
+ this.globals.bindings.set('RegEx', {
70
+ value: (pattern, flags) => new RegExp(pattern, flags),
71
+ mutable: false,
72
+ declaredType: { kind: 'FunctionType', params: [{ kind: 'NamedType', name: 'string' }, { kind: 'NamedType', name: 'string' }], result: { kind: 'NamedType', name: 'RegEx' } }
73
+ });
74
+ }
75
+ run(source, filePath) {
76
+ this.currentFile = filePath;
77
+ if (filePath)
78
+ this.sourceFiles.set(this.globals, filePath);
79
+ else
80
+ this.sourceFiles.delete(this.globals);
81
+ const statements = (0, parser_1.parse)(source, { filePath });
82
+ for (const statement of statements) {
83
+ if (statement.kind === 'TypeDeclaration') {
84
+ this.globals.types.set(statement.name, { value: statement.value, generics: statement.generics, genericDefaults: statement.genericDefaults });
85
+ this.registerTypeDeclarations(statement.value, this.globals);
86
+ }
87
+ else if (statement.kind === 'Export' && statement.declaration.kind === 'TypeDeclaration') {
88
+ this.globals.types.set(statement.declaration.name, { value: statement.declaration.value, generics: statement.declaration.generics, genericDefaults: statement.declaration.genericDefaults });
89
+ this.registerTypeDeclarations(statement.declaration.value, this.globals);
90
+ }
91
+ }
92
+ this.executeStatements(statements, this.globals);
93
+ }
94
+ runModule(source, filePath) {
95
+ const previousDirectory = this.currentDirectory;
96
+ const previousFile = this.currentFile;
97
+ this.currentDirectory = (0, node_path_1.resolve)(filePath, '..');
98
+ this.currentFile = filePath;
99
+ const env = { bindings: new Map(), types: new Map(), parent: this.globals };
100
+ this.sourceFiles.set(env, filePath);
101
+ const exported = {};
102
+ const statements = (0, parser_1.parse)(source, { filePath });
103
+ try {
104
+ for (const statement of statements) {
105
+ const declaration = statement.kind === 'Export' ? statement.declaration : statement;
106
+ if (declaration.kind === 'TypeDeclaration') {
107
+ env.types.set(declaration.name, { value: declaration.value, generics: declaration.generics, genericDefaults: declaration.genericDefaults });
108
+ this.registerTypeDeclarations(declaration.value, env);
109
+ }
110
+ }
111
+ for (const statement of statements) {
112
+ if (statement.kind !== 'Export') {
113
+ this.execute(statement, env);
114
+ continue;
115
+ }
116
+ this.execute(statement.declaration, env);
117
+ const declaration = statement.declaration;
118
+ if (declaration.kind === 'Import') {
119
+ if (declaration.defaultImport) {
120
+ const binding = this.lookup(env, declaration.defaultImport);
121
+ if (binding)
122
+ exported[statement.default ? 'default' : declaration.defaultImport] = this.toNativeExport(binding.value);
123
+ }
124
+ for (const name of declaration.namedImports) {
125
+ const binding = this.lookup(env, name);
126
+ if (binding)
127
+ exported[name] = this.toNativeExport(binding.value);
128
+ }
129
+ continue;
130
+ }
131
+ if (declaration.kind === 'Destructure') {
132
+ for (const binding of declaration.bindings) {
133
+ const value = this.lookup(env, binding.name);
134
+ if (value)
135
+ exported[binding.name] = this.toNativeExport(value.value);
136
+ }
137
+ continue;
138
+ }
139
+ if (declaration.kind !== 'Variable' && declaration.kind !== 'FunctionDeclaration' && declaration.kind !== 'TypeDeclaration' && declaration.kind !== 'ConstructorDeclaration')
140
+ continue;
141
+ const binding = this.lookup(env, declaration.name);
142
+ if (binding)
143
+ exported[statement.default ? 'default' : declaration.name] = this.toNativeExport(binding.value);
144
+ }
145
+ return exported;
146
+ }
147
+ finally {
148
+ this.currentDirectory = previousDirectory;
149
+ this.currentFile = previousFile;
150
+ }
151
+ }
152
+ executeStatements(statements, env) {
153
+ for (const statement of statements)
154
+ this.execute(statement, env);
155
+ return null;
156
+ }
157
+ execute(statement, env) {
158
+ switch (statement.kind) {
159
+ case 'Import': {
160
+ const module = ['juno', 'juno:node', 'juno:types', 'juno:async', 'juno:node:fs', 'juno:test', 'types'].includes(statement.module)
161
+ ? (0, Modules_1.resolveModule)(statement.module)
162
+ : this.loadLocalModule(statement.module, env);
163
+ if ((statement.module === 'juno:async' || statement.module === 'juno:node:fs') && !module.__junoTypes) {
164
+ const filename = statement.module === 'juno:async' ? 'async.ts' : 'juno-node-fs.ts';
165
+ const source = (0, node_fs_1.readFileSync)((0, node_path_1.resolve)(__dirname, '../../Modules', filename), 'utf8');
166
+ const runtimeTypes = {};
167
+ for (const [name, symbol] of (0, language_js_1.hostDeclarations)(source))
168
+ if (symbol.kind === 'type') {
169
+ runtimeTypes[name] = { value: symbol.value, generics: symbol.generics, genericDefaults: symbol.genericDefaults };
170
+ }
171
+ Object.defineProperty(module, '__junoTypes', { value: runtimeTypes, configurable: true });
172
+ }
173
+ const adaptedModule = this.adaptModule(module, env);
174
+ if (statement.defaultImport)
175
+ this.declare(env, statement.defaultImport, adaptedModule, false);
176
+ for (const name of statement.namedImports) {
177
+ const localTypeModule = {
178
+ Iterable: 'iterable', Range: 'range', Array: 'array', Set: 'set', ValueSet: 'set', Map: 'map', ValueMap: 'map', Queue: 'queue', Object: 'object', Boolean: 'boolean', Number: 'number',
179
+ String: 'string', Tuple: 'tuple', Random: 'random', Error: 'error', Result: 'error', ok: 'error'
180
+ }[name];
181
+ if ((statement.module === 'juno' || statement.module === 'juno:types') && localTypeModule) {
182
+ const constructorModule = this.loadLocalModule(`juno:types/${localTypeModule}`, env);
183
+ if (!(name in constructorModule))
184
+ throw new Error(`Module 'juno' has no export '${name}'`);
185
+ const alias = constructorModule.__junoTypes?.[name];
186
+ if (alias) {
187
+ ;
188
+ (statement.importedTypes ??= {})[name] = alias.value;
189
+ env.types.set(name, alias);
190
+ }
191
+ this.declare(env, name, constructorModule[name], false);
192
+ continue;
193
+ }
194
+ if (!(name in module) && !module.__junoTypes?.[name])
195
+ throw new Error(`Module '${statement.module}' has no export '${name}'`);
196
+ if (!(name in module) && module.__junoTypes?.[name]) {
197
+ const alias = module.__junoTypes[name];
198
+ (statement.importedTypes ??= {})[name] = alias.value;
199
+ env.types.set(name, alias);
200
+ this.declare(env, name, { __junoTypeConstructor: true, typeName: name, typeNode: alias.value, generics: alias.generics }, false);
201
+ continue;
202
+ }
203
+ const importedValue = name === 'console' ? this.adaptConsole(module[name]) : this.adaptNativeValue(module[name]);
204
+ if (importedValue && typeof importedValue === 'object')
205
+ this.installDefaultHas(importedValue);
206
+ this.declare(env, name, importedValue, false);
207
+ const exportedType = module.__junoTypes?.[name];
208
+ if (exportedType) {
209
+ env.types.set(name, exportedType);
210
+ (statement.importedTypes ??= {})[name] = exportedType.value;
211
+ }
212
+ }
213
+ return;
214
+ }
215
+ case 'Export':
216
+ this.execute(statement.declaration, env);
217
+ return;
218
+ case 'Variable': {
219
+ if (statement.type)
220
+ this.registerTypeDeclarations(statement.type, env);
221
+ let value = statement.initializer ? this.evaluate(statement.initializer, env) : null;
222
+ if (statement.type && value && typeof value === 'object' && !Array.isArray(value))
223
+ value = this.applyTypeDefaults(value, statement.type, env);
224
+ const declaredType = statement.type ?? (statement.initializer ? this.inferValueType(statement.initializer, env) : undefined);
225
+ this.declare(env, statement.name, value, statement.mutable, declaredType);
226
+ return;
227
+ }
228
+ case 'Destructure': {
229
+ const value = this.evaluate(statement.initializer, env);
230
+ if (value === null || typeof value !== 'object')
231
+ throw new TypeError('Object destructuring requires an object');
232
+ for (const binding of statement.bindings)
233
+ this.declare(env, binding.name, value[binding.name], statement.mutable);
234
+ return;
235
+ }
236
+ case 'ArrayDestructure': {
237
+ const source = this.evaluate(statement.initializer, env);
238
+ let values;
239
+ if (Array.isArray(source))
240
+ values = [...source];
241
+ else if (source?.toArray?.__junoFunction)
242
+ values = this.callFunction(source.toArray, [], source);
243
+ else if (typeof source?.toArray === 'function')
244
+ values = source.toArray();
245
+ else
246
+ throw new TypeError('Array destructuring requires an array, tuple, or value with toArray()');
247
+ for (const binding of statement.bindings) {
248
+ if (!binding.name || binding.name === '_')
249
+ continue;
250
+ this.declare(env, binding.name, binding.rest ? values.slice(binding.index) : values[binding.index] ?? null, statement.mutable);
251
+ }
252
+ return;
253
+ }
254
+ case 'TypeDeclaration': {
255
+ env.types.set(statement.name, { value: statement.value, generics: statement.generics, genericDefaults: statement.genericDefaults });
256
+ this.registerTypeDeclarations(statement.value, env);
257
+ this.declare(env, statement.name, { __junoTypeConstructor: true, typeName: statement.name, typeNode: statement.value, generics: statement.generics }, false);
258
+ return;
259
+ }
260
+ case 'FunctionDeclaration':
261
+ this.declare(env, statement.name, { __junoFunction: true, params: statement.params, body: statement.body, closure: env, name: statement.name, file: this.currentFile, loc: statement.loc }, false);
262
+ return;
263
+ case 'ConstructorDeclaration': {
264
+ if (!statement.overloads.length)
265
+ throw new TypeError(`Constructor '${statement.name}' needs at least one anonymous function`);
266
+ this.registerTypeDeclarations(statement.inheritedType, env);
267
+ const overloads = statement.overloads.map(overload => ({ __junoFunction: true, params: overload.params, body: overload.body, closure: env, name: statement.name, file: this.currentFile, loc: statement.loc }));
268
+ const constructor = { __junoConstructor: true, typeName: statement.name, inheritedType: statement.inheritedType, overloads };
269
+ for (const method of statement.methods)
270
+ constructor[method.name] = { __junoFunction: true, params: method.params, body: method.body, closure: env, name: `${statement.name}.${method.name}`, file: this.currentFile, loc: method.loc };
271
+ this.declare(env, statement.name, constructor, false);
272
+ return;
273
+ }
274
+ case 'Return': throw new ReturnValue(statement.value ? this.evaluate(statement.value, env) : null);
275
+ case 'Break': throw new BreakSignal();
276
+ case 'ExpressionStatement':
277
+ this.evaluate(statement.expression, env);
278
+ return;
279
+ case 'If':
280
+ this.executeStatements(this.requireCondition(this.evaluate(statement.condition, env)) ? statement.consequent : (statement.alternate ?? []), this.childEnvironment(env));
281
+ return;
282
+ case 'While': {
283
+ while (this.requireCondition(this.evaluate(statement.condition, env))) {
284
+ try {
285
+ this.executeStatements(statement.body, this.childEnvironment(env));
286
+ }
287
+ catch (error) {
288
+ if (error instanceof BreakSignal)
289
+ break;
290
+ throw error;
291
+ }
292
+ }
293
+ return;
294
+ }
295
+ case 'ForOf': {
296
+ const iterable = this.evaluate(statement.iterable, env);
297
+ const values = Array.isArray(iterable) || iterable?.[Symbol.iterator]
298
+ ? iterable
299
+ : iterable?.toArray?.__junoFunction
300
+ ? this.callFunction(iterable.toArray, [], iterable)
301
+ : iterable && typeof iterable.toArray === 'function'
302
+ ? iterable.toArray()
303
+ : iterable;
304
+ for (const value of values) {
305
+ const local = this.childEnvironment(env);
306
+ this.declare(local, statement.binding, value, statement.mutable);
307
+ try {
308
+ this.executeStatements(statement.body, local);
309
+ }
310
+ catch (error) {
311
+ if (error instanceof BreakSignal)
312
+ break;
313
+ throw error;
314
+ }
315
+ }
316
+ return;
317
+ }
318
+ }
319
+ }
320
+ registerTypeDeclarations(type, env, seen = new Set()) {
321
+ if (seen.has(type))
322
+ return;
323
+ seen.add(type);
324
+ if (type.kind === 'NamedType') {
325
+ if (type.name === 'Iterable') {
326
+ const declarations = (0, parser_1.parse)((0, node_fs_1.readFileSync)((0, node_path_1.resolve)(__dirname, '../../types/iterable.jn'), 'utf8'));
327
+ for (const declaration of declarations)
328
+ if (declaration.kind === 'Export' && declaration.declaration.kind === 'TypeDeclaration') {
329
+ const alias = { value: declaration.declaration.value, generics: declaration.declaration.generics, genericDefaults: declaration.declaration.genericDefaults };
330
+ env.types.set(declaration.declaration.name, alias);
331
+ if (!env.bindings.has(declaration.declaration.name)) {
332
+ this.declare(env, declaration.declaration.name, { __junoTypeConstructor: true, typeName: declaration.declaration.name, typeNode: alias.value, generics: alias.generics }, false);
333
+ }
334
+ }
335
+ }
336
+ return;
337
+ }
338
+ if (type.kind === 'GenericType') {
339
+ if (type.name === 'Iterable')
340
+ this.registerTypeDeclarations({ kind: 'NamedType', name: 'Iterable' }, env, seen);
341
+ type.args.forEach(argument => this.registerTypeDeclarations(argument, env, seen));
342
+ }
343
+ else if (type.kind === 'UnionType' || type.kind === 'IntersectionType')
344
+ type.types.forEach(part => this.registerTypeDeclarations(part, env, seen));
345
+ else if (type.kind === 'ObjectType')
346
+ type.members.forEach(member => this.registerTypeDeclarations(member.type, env, seen));
347
+ else if (type.kind === 'ArrayType')
348
+ this.registerTypeDeclarations(type.element, env, seen);
349
+ else if (type.kind === 'IndexedAccessType') {
350
+ this.registerTypeDeclarations(type.object, env, seen);
351
+ this.registerTypeDeclarations(type.index, env, seen);
352
+ }
353
+ }
354
+ loadLocalModule(specifier, env) {
355
+ const junoTypeModule = specifier === 'juno:types' ? 'index' : /^juno:types\/(.+)$/.exec(specifier)?.[1];
356
+ const target = junoTypeModule ? (0, node_path_1.resolve)(__dirname, '../../types', junoTypeModule) : specifier;
357
+ const file = (0, resolve_import_1.resolveImport)(target, this.currentFile ?? (0, node_path_1.resolve)(this.currentDirectory, 'index.jn'));
358
+ if (!file)
359
+ throw new Error(`Cannot find module '${specifier}'`);
360
+ const source = (0, node_fs_1.readFileSync)(file, 'utf8');
361
+ if (!/\.jn$/i.test(file)) {
362
+ const loaded = require(file);
363
+ const nativeModule = loaded && (typeof loaded === 'object' || typeof loaded === 'function') ? loaded : { default: loaded };
364
+ const module = { ...nativeModule };
365
+ const declarationFile = (0, resolve_import_1.siblingDeclaration)(file);
366
+ const declarations = (0, language_js_1.hostDeclarations)(declarationFile ? (0, node_fs_1.readFileSync)(declarationFile, 'utf8') : source);
367
+ const runtimeTypes = {};
368
+ for (const [name, symbol] of declarations)
369
+ if (symbol.kind === 'type') {
370
+ runtimeTypes[name] = { value: symbol.value, generics: symbol.generics, genericDefaults: symbol.genericDefaults };
371
+ }
372
+ const aliases = { ...nativeModule.__junoTypes, ...runtimeTypes };
373
+ if (Object.keys(aliases).length)
374
+ Object.defineProperty(module, '__junoTypes', { value: aliases, configurable: true });
375
+ return module;
376
+ }
377
+ const previousDirectory = this.currentDirectory;
378
+ const previousFile = this.currentFile;
379
+ this.currentDirectory = (0, node_path_1.dirname)(file);
380
+ this.currentFile = file;
381
+ const moduleEnv = { bindings: new Map(), types: new Map(), parent: env };
382
+ this.sourceFiles.set(moduleEnv, file);
383
+ const exported = {};
384
+ const statements = (0, parser_1.parse)(source);
385
+ for (const statement of statements) {
386
+ if (statement.kind === 'Export') {
387
+ this.execute(statement.declaration, moduleEnv);
388
+ const declaration = statement.declaration;
389
+ if (declaration.kind === 'Import') {
390
+ if (declaration.defaultImport) {
391
+ const binding = this.lookup(moduleEnv, declaration.defaultImport);
392
+ if (binding)
393
+ exported[statement.default ? 'default' : declaration.defaultImport] = binding.value;
394
+ }
395
+ for (const name of declaration.namedImports) {
396
+ const binding = this.lookup(moduleEnv, name);
397
+ if (binding)
398
+ exported[name] = binding.value;
399
+ const alias = moduleEnv.types.get(name);
400
+ if (alias)
401
+ exported.__types ??= {}, exported.__types[name] = alias;
402
+ }
403
+ continue;
404
+ }
405
+ if (declaration.kind === 'Destructure') {
406
+ for (const binding of declaration.bindings) {
407
+ const value = this.lookup(moduleEnv, binding.name);
408
+ if (value)
409
+ exported[binding.name] = value.value;
410
+ }
411
+ continue;
412
+ }
413
+ if (declaration.kind !== 'Variable' && declaration.kind !== 'FunctionDeclaration' && declaration.kind !== 'TypeDeclaration' && declaration.kind !== 'ConstructorDeclaration')
414
+ continue;
415
+ const binding = this.lookup(moduleEnv, declaration.name);
416
+ if (binding)
417
+ exported[statement.default ? 'default' : declaration.name] = binding.value;
418
+ if (declaration.kind === 'TypeDeclaration') {
419
+ const alias = moduleEnv.types.get(declaration.name);
420
+ if (alias)
421
+ exported.__types ??= {}, exported.__types[declaration.name] = alias;
422
+ }
423
+ }
424
+ else
425
+ this.execute(statement, moduleEnv);
426
+ }
427
+ Object.defineProperty(exported, '__junoTypes', { value: exported.__types ?? {}, enumerable: false });
428
+ this.currentDirectory = previousDirectory;
429
+ this.currentFile = previousFile;
430
+ return exported;
431
+ }
432
+ evaluateSpread(expression, env) {
433
+ const value = this.evaluate(expression, env);
434
+ let result;
435
+ if (Array.isArray(value))
436
+ result = [...value];
437
+ else if (value && typeof value === 'object') {
438
+ const indices = Object.keys(value).filter(key => /^\d+$/.test(key)).map(Number).sort((a, b) => a - b);
439
+ if (indices.length > 0 || 'copy' in value && 'push' in value)
440
+ result = indices.map(index => value[index]);
441
+ else {
442
+ const toArray = this.readMember(value, 'toArray', false, expression, env);
443
+ if (toArray?.__junoFunction)
444
+ result = this.callFunction(toArray, [], value);
445
+ else if (typeof toArray === 'function')
446
+ result = toArray.call(value);
447
+ else
448
+ throw new TypeError('Spread requires a callable toArray() method');
449
+ }
450
+ }
451
+ else {
452
+ const toArray = this.readMember(value, 'toArray', false, expression, env);
453
+ if (toArray?.__junoFunction)
454
+ result = this.callFunction(toArray, [], value);
455
+ else if (typeof toArray === 'function')
456
+ result = toArray.call(value);
457
+ else
458
+ throw new TypeError('Spread requires a callable toArray() method');
459
+ }
460
+ if (!Array.isArray(result))
461
+ throw new TypeError('Spread toArray() must return an array');
462
+ return result;
463
+ }
464
+ addExpressionFrame(error, expression, env) {
465
+ if (!(error instanceof Error))
466
+ return;
467
+ const trace = this.errorTraces.get(error);
468
+ if (trace && expression.kind !== 'Call')
469
+ return;
470
+ let site = expression;
471
+ while (site.kind === 'Call')
472
+ site = site.callee;
473
+ const loc = site.loc;
474
+ if (!loc)
475
+ return;
476
+ let scope = env;
477
+ let file;
478
+ while (scope && !file) {
479
+ file = this.sourceFiles.get(scope);
480
+ scope = scope.parent;
481
+ }
482
+ if (!file)
483
+ return;
484
+ const entry = trace ?? { stack: error.stack ?? error.toString(), frames: [] };
485
+ const frame = ` at ${file}:${loc.line}:${loc.column}`;
486
+ if (entry.frames.at(-1) === frame)
487
+ return;
488
+ entry.frames.push(frame);
489
+ this.errorTraces.set(error, entry);
490
+ const hostStart = entry.stack.indexOf('\n at ');
491
+ const split = hostStart < 0 ? entry.stack.length : hostStart;
492
+ error.stack = entry.stack.slice(0, split) + '\n' + entry.frames.join('\n') + entry.stack.slice(split);
493
+ }
494
+ evaluate(expression, env) {
495
+ try {
496
+ return this.evaluateExpression(expression, env);
497
+ }
498
+ catch (error) {
499
+ this.addExpressionFrame(error, expression, env);
500
+ throw error;
501
+ }
502
+ }
503
+ evaluateExpression(expression, env) {
504
+ switch (expression.kind) {
505
+ case 'Literal': return expression.value;
506
+ case 'RegEx': return new RegExp(expression.source, expression.flags);
507
+ case 'Template': return expression.parts.map(part => typeof part === 'string' ? part : this.toJunoString(this.evaluate(part, env))).join('');
508
+ case 'Identifier':
509
+ if (expression.name === 'this')
510
+ return this.lookup(env, 'this')?.value ?? null;
511
+ const binding = this.lookup(env, expression.name);
512
+ if (!binding)
513
+ throw new ReferenceError(`${expression.name} is not defined`);
514
+ return binding.value;
515
+ case 'Assignment': {
516
+ const binding = this.lookup(env, expression.name);
517
+ if (!binding)
518
+ throw new ReferenceError(`${expression.name} is not defined`);
519
+ if (!binding.mutable)
520
+ throw new TypeError(`Cannot assign to constant '${expression.name}'`);
521
+ const right = this.evaluate(expression.value, env);
522
+ binding.value = expression.operator && expression.operator !== '='
523
+ ? this.applyCompoundOperator(expression.operator, binding.value, right)
524
+ : right;
525
+ return binding.value;
526
+ }
527
+ case 'MemberAssignment': {
528
+ const object = this.evaluate(expression.object, env);
529
+ if (object === null || object === undefined)
530
+ throw new TypeError(`Cannot set property '${expression.property}' of null`);
531
+ const key = expression.index ? this.evaluate(expression.index, env) : expression.property;
532
+ if (object.__junoSealed?.has(String(key)))
533
+ throw new TypeError(`Cannot override sealed member '${String(key)}'`);
534
+ const right = this.evaluate(expression.value, env);
535
+ const current = expression.operator && expression.operator !== '=' ? object[key] : undefined;
536
+ const value = expression.operator && expression.operator !== '=' ? this.applyCompoundOperator(expression.operator, current, right) : right;
537
+ object[key] = value;
538
+ return value;
539
+ }
540
+ case 'Array': {
541
+ const array = [];
542
+ for (const item of expression.elements) {
543
+ if (item.kind === 'Spread')
544
+ array.push(...this.evaluateSpread(item.value, env));
545
+ else
546
+ array.push(this.evaluate(item, env));
547
+ }
548
+ Object.defineProperty(array, 'toString', { enumerable: false, value: function () { return stringifyJunoObject(this); } });
549
+ this.installDefaultHas(array);
550
+ return array;
551
+ }
552
+ case 'Spread':
553
+ throw new SyntaxError('Spread is only valid in arrays and call arguments');
554
+ case 'Object': {
555
+ const object = {};
556
+ const accessors = new Map();
557
+ const readonly = new Set();
558
+ const sealed = new Set();
559
+ Object.defineProperty(object, 'keys', {
560
+ enumerable: false,
561
+ configurable: true,
562
+ writable: true,
563
+ value: function () { return Object.keys(this); }
564
+ });
565
+ object.toString = this.defaultToString();
566
+ this.installDefaultHas(object);
567
+ for (const property of expression.properties) {
568
+ if (property.typeOnly)
569
+ continue;
570
+ if (property.spread) {
571
+ let source = this.evaluate(property.value, env);
572
+ if (source?.__junoTypeConstructor)
573
+ source = this.applyTypeDefaults({}, { kind: 'NamedType', name: source.typeName }, env);
574
+ if (!source || typeof source !== 'object')
575
+ throw new TypeError('Object spread requires an object');
576
+ for (const key of Object.keys(source)) {
577
+ if (sealed.has(key))
578
+ throw new TypeError(`Cannot override sealed member '${key}'`);
579
+ object[key] = source[key];
580
+ }
581
+ for (const key of source.__junoSealed ?? [])
582
+ sealed.add(key);
583
+ continue;
584
+ }
585
+ if (sealed.has(property.key))
586
+ throw new TypeError(`Cannot override sealed member '${property.key}'`);
587
+ if (property.accessor && property.value.kind === 'Function') {
588
+ const previous = accessors.get(property.key) ?? Object.getOwnPropertyDescriptor(object, property.key) ?? { enumerable: true, configurable: true };
589
+ const fn = property.value;
590
+ const runtimeFn = { __junoFunction: true, params: fn.params, body: fn.expressionBody ? [{ kind: 'Return', value: fn.expressionBody }] : fn.body, closure: env, thisValue: object };
591
+ delete previous.value;
592
+ delete previous.writable;
593
+ if (property.accessor === 'get')
594
+ previous.get = () => this.callFunction(runtimeFn, [], object);
595
+ else
596
+ previous.set = (value) => { this.callFunction(runtimeFn, [value], object); };
597
+ previous.enumerable = true;
598
+ previous.configurable = true;
599
+ accessors.set(property.key, previous);
600
+ if (property.sealed)
601
+ sealed.add(property.key);
602
+ continue;
603
+ }
604
+ if (property.value.kind === 'Function') {
605
+ const fn = property.value;
606
+ const runtimeFn = { __junoFunction: true, params: fn.params, body: fn.expressionBody ? [{ kind: 'Return', value: fn.expressionBody }] : fn.body, closure: env, thisValue: object };
607
+ if (property.key === '')
608
+ Object.defineProperty(object, '__junoCall', { enumerable: false, configurable: true, writable: true, value: runtimeFn });
609
+ else
610
+ object[property.key] = runtimeFn;
611
+ }
612
+ else
613
+ object[property.key] = this.evaluate(property.value, env);
614
+ if (property.readonly)
615
+ readonly.add(property.key);
616
+ if (property.sealed)
617
+ sealed.add(property.key);
618
+ }
619
+ for (const [key, descriptor] of accessors)
620
+ Object.defineProperty(object, key, descriptor);
621
+ for (const key of readonly)
622
+ Object.defineProperty(object, key, { ...Object.getOwnPropertyDescriptor(object, key), writable: false, enumerable: true, configurable: false });
623
+ Object.defineProperty(object, '__junoSealed', { enumerable: false, configurable: false, value: sealed });
624
+ this.installCallableMethods(object);
625
+ return object;
626
+ }
627
+ case 'Unary': {
628
+ if (expression.operator.endsWith('++') || expression.operator.endsWith('--')) {
629
+ const oldValue = this.evaluate(expression.operand, env);
630
+ const amount = typeof oldValue === 'bigint' ? 1n : typeof oldValue === 'number' ? 1 : null;
631
+ if (amount === null)
632
+ throw new TypeError(`Cannot apply '${expression.operator}' to a value of type ${typeof oldValue}; expected number or BigInt`);
633
+ const updated = expression.operator.endsWith('++') ? oldValue + amount : oldValue - amount;
634
+ this.writeTarget(expression.operand, updated, env);
635
+ return expression.operator.startsWith('prefix') ? updated : oldValue;
636
+ }
637
+ const value = this.evaluate(expression.operand, env);
638
+ if (expression.operator === 'postfix!') {
639
+ if (value == null)
640
+ throw new TypeError('Non-null assertion failed: value is null');
641
+ return value;
642
+ }
643
+ if (value == null)
644
+ throw new TypeError(`Cannot apply '${expression.operator}' to null`);
645
+ return expression.operator === '-' ? -value : !this.toBoolean(value);
646
+ }
647
+ case 'Binary': {
648
+ const left = this.evaluate(expression.left, env);
649
+ if (expression.operator === '??')
650
+ return left ?? this.evaluate(expression.right, env);
651
+ const right = this.evaluate(expression.right, env);
652
+ if ((left == null || right == null) && expression.operator !== '==' && expression.operator !== '!=') {
653
+ throw new TypeError(`Cannot apply '${expression.operator}' to null; use ! or ?? to handle null`);
654
+ }
655
+ const bothNumbers = typeof left === 'number' && typeof right === 'number';
656
+ const bothBigInts = typeof left === 'bigint' && typeof right === 'bigint';
657
+ const bothStrings = typeof left === 'string' && typeof right === 'string';
658
+ const typeName = (value) => value === null ? 'null' : typeof value;
659
+ switch (expression.operator) {
660
+ case '+':
661
+ if (bothNumbers || bothBigInts || bothStrings)
662
+ return left + right;
663
+ throw new TypeError(`Invalid operands for '+': ${typeName(left)} and ${typeName(right)}`);
664
+ case '-':
665
+ if (bothNumbers || bothBigInts)
666
+ return left - right;
667
+ throw new TypeError(`Invalid operands for '-': ${typeof left} and ${typeof right}`);
668
+ case '*':
669
+ if (bothNumbers || bothBigInts)
670
+ return left * right;
671
+ throw new TypeError(`Invalid operands for '*': ${typeof left} and ${typeof right}`);
672
+ case '/':
673
+ if (bothNumbers || bothBigInts)
674
+ return left / right;
675
+ throw new TypeError(`Invalid operands for '/': ${typeof left} and ${typeof right}`);
676
+ case '%':
677
+ if (bothNumbers || bothBigInts)
678
+ return left % right;
679
+ throw new TypeError(`Invalid operands for '%': ${typeof left} and ${typeof right}`);
680
+ case '==':
681
+ return deepEqual(left, right);
682
+ case '!=':
683
+ return !deepEqual(left, right);
684
+ case '<':
685
+ if (bothNumbers || bothBigInts)
686
+ return left < right;
687
+ throw new TypeError(`Invalid operands for '<': ${typeof left} and ${typeof right}`);
688
+ case '<=':
689
+ if (bothNumbers || bothBigInts)
690
+ return left <= right;
691
+ throw new TypeError(`Invalid operands for '<=': ${typeof left} and ${typeof right}`);
692
+ case '>':
693
+ if (bothNumbers || bothBigInts)
694
+ return left > right;
695
+ throw new TypeError(`Invalid operands for '>': ${typeof left} and ${typeof right}`);
696
+ case '>=':
697
+ if (bothNumbers || bothBigInts)
698
+ return left >= right;
699
+ throw new TypeError(`Invalid operands for '>=': ${typeof left} and ${typeof right}`);
700
+ case '|':
701
+ return this.toBoolean(left) || this.toBoolean(right);
702
+ case '&':
703
+ return this.toBoolean(left) && this.toBoolean(right);
704
+ default:
705
+ throw new Error(`Unsupported operator '${expression.operator}'`);
706
+ }
707
+ }
708
+ case 'Conditional':
709
+ return this.requireCondition(this.evaluate(expression.condition, env))
710
+ ? this.evaluate(expression.consequent, env)
711
+ : this.evaluate(expression.alternate, env);
712
+ case 'Match': {
713
+ const value = this.evaluate(expression.value, env);
714
+ for (const item of expression.cases) {
715
+ const bindings = new Map();
716
+ if (item.pattern && !this.matchesPattern(value, item.pattern, env, bindings))
717
+ continue;
718
+ const local = this.childEnvironment(env);
719
+ if (item.pattern && expression.value.kind === 'Identifier') {
720
+ const narrowedType = this.patternTypeNode(item.pattern, env);
721
+ if (narrowedType)
722
+ this.declare(local, expression.value.name, value, false, narrowedType);
723
+ }
724
+ for (const [name, binding] of bindings)
725
+ this.declare(local, name, binding, false);
726
+ if (item.guard && !this.requireCondition(this.evaluate(item.guard, local)))
727
+ continue;
728
+ try {
729
+ this.executeStatements(item.body, local);
730
+ return null;
731
+ }
732
+ catch (error) {
733
+ if (error instanceof ReturnValue)
734
+ return error.value;
735
+ throw error;
736
+ }
737
+ }
738
+ return null;
739
+ }
740
+ case 'Try': {
741
+ let result;
742
+ try {
743
+ let attempted;
744
+ if (expression.body) {
745
+ try {
746
+ this.executeStatements(expression.body, this.childEnvironment(env));
747
+ attempted = null;
748
+ }
749
+ catch (error) {
750
+ if (error instanceof ReturnValue)
751
+ attempted = error.value;
752
+ else
753
+ throw error;
754
+ }
755
+ }
756
+ else
757
+ attempted = this.evaluate(expression.value, env);
758
+ if (!attempted || typeof attempted !== 'object' || typeof attempted.ok !== 'boolean') {
759
+ throw new TypeError('try expects a Result value');
760
+ }
761
+ if (attempted.ok)
762
+ result = attempted.value;
763
+ else {
764
+ let handled = false;
765
+ for (const clause of expression.catches) {
766
+ const taggedMatch = clause.type?.kind === 'NamedType'
767
+ && attempted.error !== null && typeof attempted.error === 'object'
768
+ && attempted.error.type === clause.type.name;
769
+ if (clause.type && !taggedMatch && !this.matchesTypeNode(attempted.error, clause.type, env))
770
+ continue;
771
+ const local = this.childEnvironment(env);
772
+ if (clause.binding)
773
+ this.declare(local, clause.binding, attempted.error, false);
774
+ try {
775
+ this.executeStatements(clause.body, local);
776
+ result = null;
777
+ }
778
+ catch (error) {
779
+ if (error instanceof ReturnValue)
780
+ result = error.value;
781
+ else
782
+ throw error;
783
+ }
784
+ handled = true;
785
+ break;
786
+ }
787
+ if (!handled)
788
+ throw attempted.error;
789
+ }
790
+ }
791
+ finally {
792
+ if (expression.finallyBody) {
793
+ try {
794
+ this.executeStatements(expression.finallyBody, this.childEnvironment(env));
795
+ }
796
+ catch (error) {
797
+ if (!(error instanceof ReturnValue))
798
+ throw error;
799
+ }
800
+ }
801
+ }
802
+ return result;
803
+ }
804
+ case 'Is':
805
+ return this.matchesTypeNode(this.evaluate(expression.value, env), expression.type, env);
806
+ case 'Member': {
807
+ const object = this.evaluate(expression.object, env);
808
+ const member = this.readMember(object, expression.property, expression.optional, expression.object, env);
809
+ return typeof member === 'function' ? member.bind(object) : member;
810
+ }
811
+ case 'Index': {
812
+ const object = this.evaluate(expression.object, env);
813
+ const index = this.evaluate(expression.index, env);
814
+ if (object == null)
815
+ throw new TypeError('Cannot index null');
816
+ if (Array.isArray(object)) {
817
+ if (typeof index === 'number' && (!Number.isInteger(index) || index < 0 || index >= object.length)) {
818
+ throw new TypeError(`Array index must be an integer in [0, ${object.length}); received ${String(index)}`);
819
+ }
820
+ if (typeof index !== 'number' && typeof index !== 'string') {
821
+ throw new TypeError(`Array index must be a number or an array member name; received ${typeof index}`);
822
+ }
823
+ }
824
+ else if (typeof object === 'object' || typeof object === 'function') {
825
+ if (typeof index !== 'string' && typeof index !== 'number') {
826
+ throw new TypeError(`Object index must be a string or number; received ${typeof index}`);
827
+ }
828
+ }
829
+ else {
830
+ throw new TypeError(`Cannot index value of type ${typeof object}`);
831
+ }
832
+ return object[index] ?? null;
833
+ }
834
+ case 'Call': {
835
+ if (expression.callee.kind === 'Identifier' && expression.callee.name === 'Items' && expression.typeArguments?.length) {
836
+ const values = [];
837
+ const collect = (type) => {
838
+ if (type.kind === 'UnionType')
839
+ return type.types.forEach(collect);
840
+ if (type.kind === 'LiteralType' && (typeof type.value === 'string' || typeof type.value === 'number')) {
841
+ values.push(type.value);
842
+ return;
843
+ }
844
+ throw new TypeError(`Items<> only accepts string or number literal types; received '${typeName(type)}'`);
845
+ };
846
+ expression.typeArguments.forEach(type => collect(this.resolveAliasType(type, env)));
847
+ return values;
848
+ }
849
+ if (expression.callee.kind === 'Member' && expression.callee.property === 'as' && expression.typeArguments?.length) {
850
+ const value = this.evaluate(expression.callee.object, env);
851
+ if (value === null || value === undefined)
852
+ throw new TypeError('Cannot cast null with as<T>()');
853
+ const targetType = expression.typeArguments[0];
854
+ if (!this.matchesTypeNode(value, targetType, env)) {
855
+ throw new TypeError(`Value does not match type '${typeName(targetType)}'`);
856
+ }
857
+ return value;
858
+ }
859
+ const staticCalleeType = this.typeOf(expression.callee, env) ?? this.inferValueType(expression.callee, env);
860
+ if (staticCalleeType.kind === 'UnionType') {
861
+ const nonCallable = staticCalleeType.types.find(part => !this.isCallableType(part));
862
+ if (nonCallable)
863
+ throw new TypeError(`This expression is not callable. Type '${typeName(nonCallable)}' has no call signatures.`);
864
+ }
865
+ if (expression.callee.kind === 'Member' && expression.callee.property === 'isType' && expression.typeArguments?.length) {
866
+ return this.matchesTypeNode(this.evaluate(expression.callee.object, env), expression.typeArguments[0], env);
867
+ }
868
+ if (expression.callee.kind === 'Identifier' && expression.callee.name === 'isType' && expression.typeArguments?.length) {
869
+ const value = expression.args[0] ? this.evaluate(expression.args[0], env) : null;
870
+ return this.matchesTypeNode(value, expression.typeArguments[0], env);
871
+ }
872
+ if (expression.callee.kind === 'Identifier' && expression.callee.name === 'isType' && expression.args.length >= 2) {
873
+ const value = this.evaluate(expression.args[0], env);
874
+ const target = this.evaluate(expression.args[1], env);
875
+ const targetType = target?.typeNode;
876
+ if (targetType)
877
+ return this.matchesTypeNode(value, targetType, env);
878
+ return matchesType(value, target);
879
+ }
880
+ let thisValue;
881
+ let callee;
882
+ if (expression.callee.kind === 'Member') {
883
+ thisValue = this.evaluate(expression.callee.object, env);
884
+ if (thisValue == null && expression.callee.optional)
885
+ return null;
886
+ callee = this.readMember(thisValue, expression.callee.property, expression.callee.optional, expression.callee.object, env);
887
+ }
888
+ else
889
+ callee = this.evaluate(expression.callee, env);
890
+ const args = [];
891
+ for (const argument of expression.args) {
892
+ if (argument.kind === 'Spread')
893
+ args.push(...this.evaluateSpread(argument.value, env));
894
+ else
895
+ args.push(this.evaluate(argument, env));
896
+ }
897
+ const passesRuntimeType = expression.callee.kind === 'Identifier' && expression.callee.name === 'isType'
898
+ || expression.callee.kind === 'Member' && (expression.callee.property === 'isType' || expression.callee.property === 'as');
899
+ if (passesRuntimeType && expression.typeArguments?.length)
900
+ args.push(expression.typeArguments[0].kind === 'NamedType' ? expression.typeArguments[0].name : 'object');
901
+ if (typeof callee === 'function') {
902
+ const nativeArgs = args.map(argument => this.toNativeValue(argument));
903
+ return this.adaptNativeValue(callee.apply(thisValue, nativeArgs)) ?? null;
904
+ }
905
+ if (callee?.__junoConstructor) {
906
+ const constructor = callee;
907
+ if (!constructor.overloads.length)
908
+ throw new TypeError('A constructor needs at least one anonymous function');
909
+ const overload = constructor.overloads.find(candidate => {
910
+ const nullable = (type) => Boolean(type && (type.kind === 'NamedType' && type.name === 'null' ||
911
+ type.kind === 'UnionType' && type.types.some(part => nullable(part))));
912
+ const required = candidate.params.filter(param => !param.rest && param.defaultValue === undefined && !nullable(param.type)).length;
913
+ const maximum = candidate.params.some(param => param.rest) ? Number.POSITIVE_INFINITY : candidate.params.length;
914
+ return args.length >= required && args.length <= maximum;
915
+ });
916
+ if (!overload)
917
+ throw new TypeError(`No constructor overload accepts ${args.length} argument(s)`);
918
+ const value = this.callFunction(overload, args);
919
+ if (!value || typeof value !== 'object')
920
+ throw new TypeError('A constructor must return an object');
921
+ const result = this.applyTypeDefaults(value, constructor.inheritedType, overload.closure);
922
+ return constructor.typeName === 'Tuple' ? Object.freeze(result) : result;
923
+ }
924
+ if (callee?.__junoTypeConstructor) {
925
+ const input = args[0] ?? {};
926
+ if (!input || typeof input !== 'object' || Array.isArray(input))
927
+ throw new TypeError(`Constructor '${callee.typeName}' expects an object`);
928
+ const targetType = expression.typeArguments?.length
929
+ ? { kind: 'GenericType', name: callee.typeName, args: expression.typeArguments }
930
+ : { kind: 'NamedType', name: callee.typeName };
931
+ return this.applyTypeDefaults(input, targetType, env);
932
+ }
933
+ if (callee?.__junoCall?.__junoFunction)
934
+ return this.callFunction(callee.__junoCall, args, callee);
935
+ if (callee?.__junoFunction)
936
+ return this.callFunction(callee, args, thisValue ?? callee.thisValue);
937
+ throw new TypeError('Value is not callable');
938
+ }
939
+ case 'Function': {
940
+ const body = expression.expressionBody
941
+ ? [{ kind: 'Return', value: expression.expressionBody }]
942
+ : expression.body;
943
+ return { __junoFunction: true, params: expression.params, body, closure: env };
944
+ }
945
+ }
946
+ }
947
+ callFunction(fn, args, thisValue) {
948
+ if (statementsContainAwait(fn.body))
949
+ return this.callFunctionAsync(fn, args, thisValue);
950
+ this.callStack.push({ name: fn.name ?? '<anonymous>', file: fn.file, loc: fn.loc });
951
+ const local = this.childEnvironment(fn.closure);
952
+ if (thisValue !== undefined)
953
+ local.bindings.set('this', { value: thisValue, mutable: false });
954
+ let argumentIndex = 0;
955
+ for (const param of fn.params) {
956
+ if (param.rest) {
957
+ if (param.name !== '_')
958
+ this.declare(local, param.name, args.slice(argumentIndex), true);
959
+ argumentIndex = args.length;
960
+ }
961
+ else {
962
+ const value = argumentIndex < args.length ? args[argumentIndex] : param.defaultValue ? this.evaluate(param.defaultValue, local) : null;
963
+ argumentIndex++;
964
+ if (param.name !== '_')
965
+ this.declare(local, param.name, value, true, param.type);
966
+ }
967
+ }
968
+ try {
969
+ this.executeStatements(fn.body, local);
970
+ return null;
971
+ }
972
+ catch (error) {
973
+ if (error instanceof ReturnValue)
974
+ return error.value;
975
+ if (error instanceof BreakSignal)
976
+ throw new SyntaxError("'break' cannot cross a function boundary");
977
+ throw error;
978
+ }
979
+ finally {
980
+ this.callStack.pop();
981
+ }
982
+ }
983
+ async callFunctionAsync(fn, args, thisValue) {
984
+ this.callStack.push({ name: fn.name ?? '<anonymous>', file: fn.file, loc: fn.loc });
985
+ const local = this.childEnvironment(fn.closure);
986
+ if (thisValue !== undefined)
987
+ local.bindings.set('this', { value: thisValue, mutable: false });
988
+ let argumentIndex = 0;
989
+ for (const param of fn.params) {
990
+ if (param.rest) {
991
+ if (param.name !== '_')
992
+ this.declare(local, param.name, args.slice(argumentIndex), true);
993
+ argumentIndex = args.length;
994
+ }
995
+ else {
996
+ const value = argumentIndex < args.length ? args[argumentIndex] : param.defaultValue ? this.evaluate(param.defaultValue, local) : null;
997
+ argumentIndex++;
998
+ if (param.name !== '_')
999
+ this.declare(local, param.name, value, true, param.type);
1000
+ }
1001
+ }
1002
+ try {
1003
+ await this.executeStatementsAsync(fn.body, local);
1004
+ return null;
1005
+ }
1006
+ catch (error) {
1007
+ if (error instanceof ReturnValue)
1008
+ return error.value;
1009
+ if (error instanceof BreakSignal)
1010
+ throw new SyntaxError("'break' cannot cross a function boundary");
1011
+ throw error;
1012
+ }
1013
+ finally {
1014
+ this.callStack.pop();
1015
+ }
1016
+ }
1017
+ async executeStatementsAsync(statements, env) {
1018
+ for (const statement of statements)
1019
+ await this.executeAsync(statement, env);
1020
+ }
1021
+ async executeAsync(statement, env) {
1022
+ if (!statementContainsAwait(statement)) {
1023
+ this.execute(statement, env);
1024
+ return;
1025
+ }
1026
+ switch (statement.kind) {
1027
+ case 'Variable': {
1028
+ if (statement.type)
1029
+ this.registerTypeDeclarations(statement.type, env);
1030
+ let value = statement.initializer ? await this.evaluateAsync(statement.initializer, env) : null;
1031
+ if (statement.type && value && typeof value === 'object' && !Array.isArray(value))
1032
+ value = this.applyTypeDefaults(value, statement.type, env);
1033
+ this.declare(env, statement.name, value, statement.mutable, statement.type ?? this.inferRuntimeValueType(value));
1034
+ return;
1035
+ }
1036
+ case 'Destructure': {
1037
+ const value = await this.evaluateAsync(statement.initializer, env);
1038
+ if (value === null || typeof value !== 'object')
1039
+ throw new TypeError('Object destructuring requires an object');
1040
+ for (const binding of statement.bindings)
1041
+ this.declare(env, binding.name, value[binding.name], statement.mutable);
1042
+ return;
1043
+ }
1044
+ case 'ArrayDestructure': {
1045
+ const source = await this.evaluateAsync(statement.initializer, env);
1046
+ const values = Array.isArray(source) ? [...source] : typeof source?.toArray === 'function' ? await source.toArray() : null;
1047
+ if (!values)
1048
+ throw new TypeError('Array destructuring requires an array, tuple, or value with toArray()');
1049
+ for (const binding of statement.bindings)
1050
+ if (binding.name && binding.name !== '_')
1051
+ this.declare(env, binding.name, binding.rest ? values.slice(binding.index) : values[binding.index] ?? null, statement.mutable);
1052
+ return;
1053
+ }
1054
+ case 'Return': throw new ReturnValue(statement.value ? await this.evaluateAsync(statement.value, env) : null);
1055
+ case 'ExpressionStatement':
1056
+ await this.evaluateAsync(statement.expression, env);
1057
+ return;
1058
+ case 'If': {
1059
+ const body = this.requireCondition(await this.evaluateAsync(statement.condition, env)) ? statement.consequent : (statement.alternate ?? []);
1060
+ await this.executeStatementsAsync(body, this.childEnvironment(env));
1061
+ return;
1062
+ }
1063
+ case 'While': {
1064
+ while (this.requireCondition(await this.evaluateAsync(statement.condition, env))) {
1065
+ try {
1066
+ await this.executeStatementsAsync(statement.body, this.childEnvironment(env));
1067
+ }
1068
+ catch (error) {
1069
+ if (error instanceof BreakSignal)
1070
+ break;
1071
+ throw error;
1072
+ }
1073
+ }
1074
+ return;
1075
+ }
1076
+ case 'ForOf': {
1077
+ const iterable = await this.evaluateAsync(statement.iterable, env);
1078
+ const values = Array.isArray(iterable) || iterable?.[Symbol.iterator] ? iterable : typeof iterable?.toArray === 'function' ? await iterable.toArray() : iterable;
1079
+ for (const value of values) {
1080
+ const local = this.childEnvironment(env);
1081
+ this.declare(local, statement.binding, value, statement.mutable);
1082
+ try {
1083
+ await this.executeStatementsAsync(statement.body, local);
1084
+ }
1085
+ catch (error) {
1086
+ if (error instanceof BreakSignal)
1087
+ break;
1088
+ throw error;
1089
+ }
1090
+ }
1091
+ return;
1092
+ }
1093
+ case 'Export':
1094
+ await this.executeAsync(statement.declaration, env);
1095
+ return;
1096
+ default: this.execute(statement, env);
1097
+ }
1098
+ }
1099
+ async evaluateAsync(expression, env) {
1100
+ try {
1101
+ return await this.evaluateExpressionAsync(expression, env);
1102
+ }
1103
+ catch (error) {
1104
+ this.addExpressionFrame(error, expression, env);
1105
+ throw error;
1106
+ }
1107
+ }
1108
+ async evaluateExpressionAsync(expression, env) {
1109
+ if (expression.kind === 'Unary' && expression.operator === 'await')
1110
+ return (await this.evaluateAsync(expression.operand, env)) ?? null;
1111
+ if (expression.kind === 'Conditional') {
1112
+ return this.requireCondition(await this.evaluateAsync(expression.condition, env))
1113
+ ? this.evaluateAsync(expression.consequent, env)
1114
+ : this.evaluateAsync(expression.alternate, env);
1115
+ }
1116
+ if (expression.kind === 'Match') {
1117
+ const value = await this.evaluateAsync(expression.value, env);
1118
+ for (const item of expression.cases) {
1119
+ const bindings = new Map();
1120
+ if (item.pattern && !this.matchesPattern(value, item.pattern, env, bindings))
1121
+ continue;
1122
+ const local = this.childEnvironment(env);
1123
+ if (item.pattern && expression.value.kind === 'Identifier') {
1124
+ const narrowedType = this.patternTypeNode(item.pattern, env);
1125
+ if (narrowedType)
1126
+ this.declare(local, expression.value.name, value, false, narrowedType);
1127
+ }
1128
+ for (const [name, binding] of bindings)
1129
+ this.declare(local, name, binding, false);
1130
+ if (item.guard && !this.requireCondition(await this.evaluateAsync(item.guard, local)))
1131
+ continue;
1132
+ try {
1133
+ await this.executeStatementsAsync(item.body, local);
1134
+ return null;
1135
+ }
1136
+ catch (error) {
1137
+ if (error instanceof ReturnValue)
1138
+ return error.value;
1139
+ throw error;
1140
+ }
1141
+ }
1142
+ return null;
1143
+ }
1144
+ if (expression.kind === 'Try') {
1145
+ let result;
1146
+ try {
1147
+ let attempted;
1148
+ if (expression.body) {
1149
+ try {
1150
+ await this.executeStatementsAsync(expression.body, this.childEnvironment(env));
1151
+ attempted = null;
1152
+ }
1153
+ catch (error) {
1154
+ if (error instanceof ReturnValue)
1155
+ attempted = error.value;
1156
+ else
1157
+ throw error;
1158
+ }
1159
+ }
1160
+ else
1161
+ attempted = await this.evaluateAsync(expression.value, env);
1162
+ if (!attempted || typeof attempted !== 'object' || typeof attempted.ok !== 'boolean')
1163
+ throw new TypeError('try expects a Result value');
1164
+ if (attempted.ok)
1165
+ result = attempted.value;
1166
+ else {
1167
+ let handled = false;
1168
+ for (const clause of expression.catches) {
1169
+ const taggedMatch = clause.type?.kind === 'NamedType' && attempted.error !== null && typeof attempted.error === 'object' && attempted.error.type === clause.type.name;
1170
+ if (clause.type && !taggedMatch && !this.matchesTypeNode(attempted.error, clause.type, env))
1171
+ continue;
1172
+ const local = this.childEnvironment(env);
1173
+ if (clause.binding)
1174
+ this.declare(local, clause.binding, attempted.error, false);
1175
+ try {
1176
+ await this.executeStatementsAsync(clause.body, local);
1177
+ result = null;
1178
+ }
1179
+ catch (error) {
1180
+ if (error instanceof ReturnValue)
1181
+ result = error.value;
1182
+ else
1183
+ throw error;
1184
+ }
1185
+ handled = true;
1186
+ break;
1187
+ }
1188
+ if (!handled)
1189
+ throw attempted.error;
1190
+ }
1191
+ }
1192
+ finally {
1193
+ if (expression.finallyBody) {
1194
+ try {
1195
+ await this.executeStatementsAsync(expression.finallyBody, this.childEnvironment(env));
1196
+ }
1197
+ catch (error) {
1198
+ if (!(error instanceof ReturnValue))
1199
+ throw error;
1200
+ }
1201
+ }
1202
+ }
1203
+ return result;
1204
+ }
1205
+ const resolved = await this.resolveAwaitExpressions(expression, env);
1206
+ return this.evaluate(resolved, env);
1207
+ }
1208
+ async resolveAwaitList(expressions, env) {
1209
+ const resolved = [];
1210
+ for (const expression of expressions)
1211
+ resolved.push(await this.resolveAwaitExpressions(expression, env));
1212
+ return resolved;
1213
+ }
1214
+ async resolveAwaitExpressions(expression, env) {
1215
+ if (expression.kind === 'Unary' && expression.operator === 'await')
1216
+ return { kind: 'Literal', value: (await this.evaluateAsync(expression.operand, env)) ?? null };
1217
+ switch (expression.kind) {
1218
+ case 'Template': {
1219
+ const parts = [];
1220
+ for (const part of expression.parts)
1221
+ parts.push(typeof part === 'string' ? part : await this.resolveAwaitExpressions(part, env));
1222
+ return { ...expression, parts };
1223
+ }
1224
+ case 'Assignment': return { ...expression, value: await this.resolveAwaitExpressions(expression.value, env) };
1225
+ case 'MemberAssignment': return { ...expression, object: await this.resolveAwaitExpressions(expression.object, env), index: expression.index ? await this.resolveAwaitExpressions(expression.index, env) : undefined, value: await this.resolveAwaitExpressions(expression.value, env) };
1226
+ case 'Array': return { ...expression, elements: await this.resolveAwaitList(expression.elements, env) };
1227
+ case 'Spread': return { ...expression, value: await this.resolveAwaitExpressions(expression.value, env) };
1228
+ case 'Object': {
1229
+ const properties = [];
1230
+ for (const property of expression.properties)
1231
+ properties.push({ ...property, value: property.value.kind === 'Function' ? property.value : await this.resolveAwaitExpressions(property.value, env) });
1232
+ return { ...expression, properties };
1233
+ }
1234
+ case 'Unary': return { ...expression, operand: await this.resolveAwaitExpressions(expression.operand, env) };
1235
+ case 'Binary': return { ...expression, left: await this.resolveAwaitExpressions(expression.left, env), right: await this.resolveAwaitExpressions(expression.right, env) };
1236
+ case 'Is': return { ...expression, value: await this.resolveAwaitExpressions(expression.value, env) };
1237
+ case 'Member': return { ...expression, object: await this.resolveAwaitExpressions(expression.object, env) };
1238
+ case 'Index': return { ...expression, object: await this.resolveAwaitExpressions(expression.object, env), index: await this.resolveAwaitExpressions(expression.index, env) };
1239
+ case 'Call': return { ...expression, callee: await this.resolveAwaitExpressions(expression.callee, env), args: await this.resolveAwaitList(expression.args, env) };
1240
+ case 'Conditional': return { kind: 'Literal', value: await this.evaluateAsync(expression, env) };
1241
+ case 'Function': return expression;
1242
+ default: return expression;
1243
+ }
1244
+ }
1245
+ patternBindings(pattern) {
1246
+ if (pattern.kind === 'PatternObject')
1247
+ return new Set(pattern.properties.map(property => property.name));
1248
+ if (pattern.kind === 'PatternUnion')
1249
+ return new Set(pattern.patterns.flatMap(part => [...this.patternBindings(part)]));
1250
+ return new Set();
1251
+ }
1252
+ patternTypeNode(pattern, env) {
1253
+ if (pattern.kind === 'PatternLiteral') {
1254
+ if (typeof pattern.value === 'bigint')
1255
+ return { kind: 'NamedType', name: 'bigint' };
1256
+ return pattern.value === null ? { kind: 'NamedType', name: 'null' } : { kind: 'LiteralType', value: pattern.value };
1257
+ }
1258
+ if (pattern.kind === 'PatternUnion') {
1259
+ const types = pattern.patterns.flatMap(part => this.patternTypeNode(part, env) ?? []);
1260
+ return types.length ? { kind: 'UnionType', types } : undefined;
1261
+ }
1262
+ if (pattern.kind === 'PatternObject')
1263
+ return { kind: 'ObjectType', members: pattern.properties.map(property => ({
1264
+ name: property.name, type: property.pattern ? this.patternTypeNode(property.pattern, env) ?? { kind: 'NamedType', name: 'any' } : { kind: 'NamedType', name: 'any' },
1265
+ optional: false, readonly: true, constant: false
1266
+ })) };
1267
+ if (pattern.name === '_')
1268
+ return undefined;
1269
+ const binding = this.lookup(env, pattern.name)?.value;
1270
+ const isType = binding?.__junoConstructor || binding?.__junoTypeConstructor || env.types.has(pattern.name)
1271
+ || ['string', 'number', 'boolean', 'bigint', 'symbol', 'object', 'unknown', 'any', 'null'].includes(pattern.name);
1272
+ if (!isType)
1273
+ return undefined;
1274
+ const base = { kind: 'NamedType', name: pattern.name };
1275
+ return pattern.nullable ? { kind: 'UnionType', types: [base, { kind: 'NamedType', name: 'null' }] } : base;
1276
+ }
1277
+ matchesPattern(value, pattern, env, bindings) {
1278
+ if (pattern.kind === 'PatternLiteral')
1279
+ return deepEqual(value, pattern.value);
1280
+ if (pattern.kind === 'PatternUnion') {
1281
+ const names = this.patternBindings(pattern);
1282
+ for (const part of pattern.patterns) {
1283
+ const candidate = new Map([...names].map(name => [name, null]));
1284
+ if (this.matchesPattern(value, part, env, candidate)) {
1285
+ for (const [name, binding] of candidate)
1286
+ bindings.set(name, binding);
1287
+ return true;
1288
+ }
1289
+ }
1290
+ return false;
1291
+ }
1292
+ if (pattern.kind === 'PatternObject') {
1293
+ if (value === null || typeof value !== 'object')
1294
+ return false;
1295
+ const candidate = new Map(bindings);
1296
+ for (const property of pattern.properties) {
1297
+ const member = property.name in value ? value[property.name] : null;
1298
+ if (property.pattern && !this.matchesPattern(member, property.pattern, env, candidate))
1299
+ return false;
1300
+ candidate.set(property.name, member);
1301
+ }
1302
+ for (const [name, binding] of candidate)
1303
+ bindings.set(name, binding);
1304
+ return true;
1305
+ }
1306
+ if (pattern.name === '_')
1307
+ return true;
1308
+ const binding = this.lookup(env, pattern.name)?.value;
1309
+ let matches;
1310
+ if (binding?.__junoConstructor)
1311
+ matches = this.matchesTypeNode(value, binding.inheritedType, env);
1312
+ else if (binding?.__junoTypeConstructor || env.types.has(pattern.name) || ['string', 'number', 'boolean', 'bigint', 'symbol', 'object', 'unknown', 'any', 'null'].includes(pattern.name)) {
1313
+ matches = this.matchesTypeNode(value, { kind: 'NamedType', name: pattern.name }, env);
1314
+ }
1315
+ else if (binding !== undefined)
1316
+ matches = deepEqual(value, binding);
1317
+ else
1318
+ matches = false;
1319
+ return matches || Boolean(pattern.nullable && value === null);
1320
+ }
1321
+ captureStackTrace() {
1322
+ return [...this.callStack].reverse().map(frame => {
1323
+ const position = frame.file
1324
+ ? `${frame.file}${frame.loc ? `:${frame.loc.line}:${frame.loc.column}` : ''}`
1325
+ : frame.loc ? `${frame.loc.line}:${frame.loc.column}` : '<unknown>';
1326
+ return `at ${frame.name} (${position})`;
1327
+ });
1328
+ }
1329
+ toNativeValue(value) {
1330
+ if (value?.__junoFunction) {
1331
+ return (...args) => this.toNativeValue(this.callFunction(value, args));
1332
+ }
1333
+ if (value === null || typeof value !== 'object')
1334
+ return value;
1335
+ const target = value;
1336
+ const hasJunoMethod = Reflect.ownKeys(target).some(property => target[property]?.__junoFunction);
1337
+ const hasToArray = typeof target.toArray === 'function' || target.toArray?.__junoFunction;
1338
+ if (!hasJunoMethod && !hasToArray)
1339
+ return value;
1340
+ const thisInterpreter = this;
1341
+ const wrappers = new Map();
1342
+ return new Proxy(target, {
1343
+ get: (object, property, receiver) => {
1344
+ if (property === Symbol.iterator && hasToArray)
1345
+ return function () {
1346
+ const method = object.toArray;
1347
+ const items = method?.__junoFunction
1348
+ ? thisInterpreter.callFunction(method, [], object)
1349
+ : method.call(object);
1350
+ if (!items || typeof items[Symbol.iterator] !== 'function')
1351
+ throw new TypeError('toArray() must return an iterable value');
1352
+ return items[Symbol.iterator]();
1353
+ };
1354
+ const member = Reflect.get(object, property, receiver);
1355
+ if (!member?.__junoFunction)
1356
+ return member;
1357
+ const cached = wrappers.get(property);
1358
+ if (cached && cached.method === member)
1359
+ return cached.callable;
1360
+ const callable = (...args) => this.callFunction(member, args, object);
1361
+ wrappers.set(property, { method: member, callable });
1362
+ return callable;
1363
+ }
1364
+ });
1365
+ }
1366
+ callRuntimeConstructor(constructor, args) {
1367
+ const overload = constructor.overloads.find(candidate => {
1368
+ const nullable = (type) => Boolean(type && (type.kind === 'NamedType' && type.name === 'null' ||
1369
+ type.kind === 'UnionType' && type.types.some(part => nullable(part))));
1370
+ const required = candidate.params.filter(param => !param.rest && param.defaultValue === undefined && !nullable(param.type)).length;
1371
+ const maximum = candidate.params.some(param => param.rest) ? Number.POSITIVE_INFINITY : candidate.params.length;
1372
+ return args.length >= required && args.length <= maximum;
1373
+ });
1374
+ if (!overload)
1375
+ throw new TypeError(`No constructor overload accepts ${args.length} argument(s)`);
1376
+ const value = this.callFunction(overload, args);
1377
+ if (!value || typeof value !== 'object')
1378
+ throw new TypeError('A constructor must return an object');
1379
+ const result = this.applyTypeDefaults(value, constructor.inheritedType, overload.closure);
1380
+ return this.toNativeValue(constructor.typeName === 'Tuple' ? Object.freeze(result) : result);
1381
+ }
1382
+ toNativeExport(value) {
1383
+ if (value?.__junoConstructor) {
1384
+ const constructor = value;
1385
+ const callable = (...args) => this.callRuntimeConstructor(constructor, args.map(argument => this.adaptNativeValue(argument)));
1386
+ for (const key of Object.keys(constructor)) {
1387
+ if (key.startsWith('__') || key === 'overloads' || key === 'inheritedType' || key === 'typeName')
1388
+ continue;
1389
+ const member = constructor[key];
1390
+ callable[key] = member?.__junoFunction
1391
+ ? (...args) => this.toNativeValue(this.callFunction(member, args.map(argument => this.adaptNativeValue(argument))))
1392
+ : this.toNativeValue(member);
1393
+ }
1394
+ Object.defineProperty(callable, '__junoConstructor', { value: true });
1395
+ return callable;
1396
+ }
1397
+ if (value?.__junoTypeConstructor) {
1398
+ return (input = {}) => this.toNativeValue(this.applyTypeDefaults(input, value.typeNode, this.globals));
1399
+ }
1400
+ return this.toNativeValue(value);
1401
+ }
1402
+ adaptNativeValue(value) {
1403
+ if (typeof value === 'function') {
1404
+ const source = Function.prototype.toString.call(value);
1405
+ if (/^class\s/.test(source)) {
1406
+ const NativeClass = value;
1407
+ return new Proxy(NativeClass, {
1408
+ apply: (_target, _thisArg, args) => this.adaptNativeValue(Reflect.construct(NativeClass, args.map(argument => this.toNativeValue(argument))))
1409
+ });
1410
+ }
1411
+ return value;
1412
+ }
1413
+ if (value === null || value === undefined || typeof value !== 'object')
1414
+ return value;
1415
+ if (typeof value.iterator === 'function' || typeof value[Symbol.iterator] !== 'function')
1416
+ return value;
1417
+ const iterator = function () {
1418
+ const native = value[Symbol.iterator].call(value);
1419
+ return () => {
1420
+ const next = native.next();
1421
+ return next.done ? null : { value: next.value };
1422
+ };
1423
+ };
1424
+ if (Object.isExtensible(value)) {
1425
+ Object.defineProperty(value, 'iterator', { enumerable: false, configurable: true, value: iterator });
1426
+ return value;
1427
+ }
1428
+ return new Proxy(value, {
1429
+ has: (target, property) => property === 'iterator' || Reflect.has(target, property),
1430
+ get: (target, property, receiver) => property === 'iterator' ? iterator : Reflect.get(target, property, receiver)
1431
+ });
1432
+ }
1433
+ declare(env, name, value, mutable, declaredType) {
1434
+ if (env.bindings.has(name))
1435
+ throw new SyntaxError(`Duplicate declaration '${name}' in the same scope`);
1436
+ env.bindings.set(name, { value, mutable, declaredType });
1437
+ }
1438
+ childEnvironment(parent) { return { bindings: new Map(), types: new Map(), parent }; }
1439
+ adaptModule(module, env) {
1440
+ const adapted = 'console' in module ? { ...module, console: this.adaptConsole(module.console) } : { ...module };
1441
+ for (const key of Reflect.ownKeys(adapted))
1442
+ if (key !== 'console')
1443
+ adapted[key] = this.adaptNativeValue(adapted[key]);
1444
+ this.installDefaultHas(adapted);
1445
+ return adapted;
1446
+ }
1447
+ adaptConsole(consoleObject) {
1448
+ const convert = (args) => args.map(value => value !== null && (typeof value === 'object' || typeof value === 'function') ? this.toJunoString(value) : value);
1449
+ const adapted = {
1450
+ ...consoleObject,
1451
+ log: (...args) => consoleObject.log(...convert(args)),
1452
+ error: (...args) => consoleObject.error(...convert(args)),
1453
+ warn: (...args) => consoleObject.warn(...convert(args))
1454
+ };
1455
+ this.installDefaultHas(adapted);
1456
+ return adapted;
1457
+ }
1458
+ toJunoString(value) {
1459
+ if (value === null || value === undefined)
1460
+ return String(value);
1461
+ if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
1462
+ const method = value.toString;
1463
+ if (typeof method === 'function')
1464
+ return String(method.call(value));
1465
+ if (method?.__junoFunction)
1466
+ return String(this.callFunction(method, [], value));
1467
+ }
1468
+ return String(value);
1469
+ }
1470
+ defaultToString() {
1471
+ const method = function () { return stringifyJunoObject(this); };
1472
+ Object.defineProperty(method, '__junoDefaultToString', { value: true });
1473
+ return method;
1474
+ }
1475
+ installDefaultHas(value) {
1476
+ const interpreter = this;
1477
+ if (!('has' in value))
1478
+ Object.defineProperty(value, 'has', {
1479
+ enumerable: false,
1480
+ configurable: true,
1481
+ writable: true,
1482
+ value: function (key) { return key in this; }
1483
+ });
1484
+ const installResult = (result) => {
1485
+ if (result && typeof result === 'object') {
1486
+ if (!Array.isArray(result) && !Object.prototype.hasOwnProperty.call(result, 'toString'))
1487
+ result.toString = this.defaultToString();
1488
+ this.installDefaultHas(result);
1489
+ }
1490
+ return result;
1491
+ };
1492
+ if (!('asReadonly' in value))
1493
+ Object.defineProperty(value, 'asReadonly', {
1494
+ enumerable: false,
1495
+ configurable: true,
1496
+ writable: true,
1497
+ value: function () {
1498
+ const copy = Array.isArray(this) ? [...this] : { ...this };
1499
+ interpreter.installDefaultHas(copy);
1500
+ return Object.freeze(copy);
1501
+ }
1502
+ });
1503
+ if (!('asMutable' in value))
1504
+ Object.defineProperty(value, 'asMutable', {
1505
+ enumerable: false,
1506
+ configurable: true,
1507
+ writable: true,
1508
+ value: function () {
1509
+ const copy = Array.isArray(this) ? [...this] : { ...this };
1510
+ interpreter.installDefaultHas(copy);
1511
+ return copy;
1512
+ }
1513
+ });
1514
+ if (!('deepClone' in value))
1515
+ Object.defineProperty(value, 'deepClone', {
1516
+ enumerable: false,
1517
+ configurable: true,
1518
+ writable: true,
1519
+ value: function () {
1520
+ const clone = deepCloneValue(this);
1521
+ interpreter.installDefaultHas(clone);
1522
+ return clone;
1523
+ }
1524
+ });
1525
+ if (!('deepFreeze' in value))
1526
+ Object.defineProperty(value, 'deepFreeze', {
1527
+ enumerable: false,
1528
+ configurable: true,
1529
+ writable: true,
1530
+ value: function () { return deepFreezeValue(this); }
1531
+ });
1532
+ if (!('toDeepFreezed' in value))
1533
+ Object.defineProperty(value, 'toDeepFreezed', {
1534
+ enumerable: false,
1535
+ configurable: true,
1536
+ writable: true,
1537
+ value: function () {
1538
+ const clone = deepCloneValue(this);
1539
+ interpreter.installDefaultHas(clone);
1540
+ return deepFreezeValue(clone);
1541
+ }
1542
+ });
1543
+ if (!('pick' in value))
1544
+ Object.defineProperty(value, 'pick', {
1545
+ enumerable: false,
1546
+ configurable: true,
1547
+ writable: true,
1548
+ value: function (...keys) {
1549
+ if (Array.isArray(this) && keys.every(key => typeof key === 'number'))
1550
+ return installResult(keys.map(key => this[key]));
1551
+ const result = {};
1552
+ for (const key of keys)
1553
+ if (key in this)
1554
+ result[String(key)] = this[key];
1555
+ return installResult(result);
1556
+ }
1557
+ });
1558
+ if (!('omit' in value))
1559
+ Object.defineProperty(value, 'omit', {
1560
+ enumerable: false,
1561
+ configurable: true,
1562
+ writable: true,
1563
+ value: function (...keys) {
1564
+ if (Array.isArray(this) && keys.every(key => typeof key === 'number')) {
1565
+ const removed = new Set(keys);
1566
+ return installResult(this.filter((_item, index) => !removed.has(index)));
1567
+ }
1568
+ const removed = new Set(keys.map(String));
1569
+ const result = {};
1570
+ for (const key of Object.keys(this))
1571
+ if (!removed.has(key))
1572
+ result[key] = this[key];
1573
+ return installResult(result);
1574
+ }
1575
+ });
1576
+ }
1577
+ installCallableMethods(value) {
1578
+ if (!value.__junoCall?.__junoFunction)
1579
+ return;
1580
+ const define = (name, method) => {
1581
+ if (name in value)
1582
+ return;
1583
+ Object.defineProperty(value, name, { enumerable: false, configurable: true, writable: true, value: method });
1584
+ };
1585
+ define('call', (thisArg, ...args) => this.callFunction(value.__junoCall, args, thisArg));
1586
+ define('apply', (thisArg, args) => {
1587
+ if (!Array.isArray(args))
1588
+ throw new TypeError('Callable object apply() expects an array as its second argument');
1589
+ return this.callFunction(value.__junoCall, args, thisArg);
1590
+ });
1591
+ define('bind', (thisArg, ...boundArgs) => (...args) => this.callFunction(value.__junoCall, [...boundArgs, ...args], thisArg));
1592
+ }
1593
+ writeTarget(target, value, env) {
1594
+ if (target.kind === 'Identifier') {
1595
+ const binding = this.lookup(env, target.name);
1596
+ if (!binding)
1597
+ throw new ReferenceError(`${target.name} is not defined`);
1598
+ if (!binding.mutable)
1599
+ throw new TypeError(`Cannot assign to constant '${target.name}'`);
1600
+ binding.value = value;
1601
+ return;
1602
+ }
1603
+ if (target.kind === 'Member') {
1604
+ const object = this.evaluate(target.object, env);
1605
+ if (object === null || object === undefined)
1606
+ throw new TypeError(`Cannot set property '${target.property}' of null`);
1607
+ if (object.__junoSealed?.has(target.property))
1608
+ throw new TypeError(`Cannot override sealed member '${target.property}'`);
1609
+ object[target.property] = value;
1610
+ return;
1611
+ }
1612
+ if (target.kind === 'Index') {
1613
+ const object = this.evaluate(target.object, env);
1614
+ if (object === null || object === undefined)
1615
+ throw new TypeError('Cannot set an index on null');
1616
+ const index = this.evaluate(target.index, env);
1617
+ if (object.__junoSealed?.has(String(index)))
1618
+ throw new TypeError(`Cannot override sealed member '${String(index)}'`);
1619
+ object[index] = value;
1620
+ return;
1621
+ }
1622
+ throw new TypeError('Increment and decrement require an assignable target');
1623
+ }
1624
+ applyCompoundOperator(operator, left, right) {
1625
+ const type = typeof left;
1626
+ const bothNumbers = type === 'number' && typeof right === 'number';
1627
+ const bothBigInts = type === 'bigint' && typeof right === 'bigint';
1628
+ if (operator === '+=') {
1629
+ if (bothNumbers || bothBigInts || type === 'string' && typeof right === 'string')
1630
+ return left + right;
1631
+ }
1632
+ else if (operator === '-=') {
1633
+ if (bothNumbers || bothBigInts)
1634
+ return left - right;
1635
+ }
1636
+ else if (operator === '*=') {
1637
+ if (bothNumbers || bothBigInts)
1638
+ return left * right;
1639
+ }
1640
+ else if (operator === '/=') {
1641
+ if (bothNumbers || bothBigInts)
1642
+ return left / right;
1643
+ }
1644
+ else if (operator === '%=') {
1645
+ if (bothNumbers || bothBigInts)
1646
+ return left % right;
1647
+ }
1648
+ else if (operator === '&=')
1649
+ return this.toBoolean(left) && this.toBoolean(right);
1650
+ else if (operator === '|=')
1651
+ return this.toBoolean(left) || this.toBoolean(right);
1652
+ throw new TypeError(`Invalid operands for '${operator}': ${type} and ${typeof right}`);
1653
+ }
1654
+ requireCondition(value) {
1655
+ if (value == null)
1656
+ throw new TypeError('Cannot use null as a condition; use ! or ?? to handle null');
1657
+ return this.toBoolean(value);
1658
+ }
1659
+ toBoolean(value) {
1660
+ if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
1661
+ const method = value.toBoolean;
1662
+ if (method === undefined)
1663
+ return true;
1664
+ const result = method?.__junoFunction
1665
+ ? this.callFunction(method, [], value)
1666
+ : typeof method === 'function'
1667
+ ? method.call(value)
1668
+ : (() => { throw new TypeError("Property 'toBoolean' must be a function"); })();
1669
+ if (typeof result !== 'boolean')
1670
+ throw new TypeError("Method 'toBoolean' must return boolean");
1671
+ return result;
1672
+ }
1673
+ return Boolean(value);
1674
+ }
1675
+ lookup(env, name) {
1676
+ for (let current = env; current; current = current.parent) {
1677
+ const binding = current.bindings.get(name);
1678
+ if (binding)
1679
+ return binding;
1680
+ }
1681
+ return undefined;
1682
+ }
1683
+ typeOf(expression, env) {
1684
+ if (expression.kind === 'Identifier')
1685
+ return this.lookup(env, expression.name)?.declaredType ?? null;
1686
+ if (expression.kind === 'Member') {
1687
+ const parentType = this.typeOf(expression.object, env);
1688
+ const lookupType = parentType && expression.optional ? this.nonNullableType(parentType) : parentType;
1689
+ return lookupType ? this.findTypeMember(lookupType, expression.property, env)?.type ?? null : null;
1690
+ }
1691
+ if (expression.kind === 'Index') {
1692
+ const parentType = this.typeOf(expression.object, env) ?? this.inferValueType(expression.object, env);
1693
+ const keyType = expression.index.kind === 'Literal' && (typeof expression.index.value === 'string' || typeof expression.index.value === 'number')
1694
+ ? { kind: 'LiteralType', value: expression.index.value }
1695
+ : this.typeOf(expression.index, env) ?? this.inferValueType(expression.index, env);
1696
+ return this.indexedType(parentType, keyType, env);
1697
+ }
1698
+ return null;
1699
+ }
1700
+ indexedType(objectType, keyType, env) {
1701
+ const object = this.resolveAliasType(objectType, env);
1702
+ const key = this.resolveAliasType(keyType, env);
1703
+ const keys = key.kind === 'UnionType' ? key.types : [key];
1704
+ const results = [];
1705
+ for (const part of keys) {
1706
+ if ((object.kind === 'ArrayType' || object.kind === 'GenericType' && (object.name === 'Array' || object.name === 'ReadonlyArray')) && (part.kind === 'NamedType' && part.name === 'number' || part.kind === 'LiteralType' && typeof part.value === 'number')) {
1707
+ results.push(object.kind === 'ArrayType' ? object.element : object.args[0] ?? { kind: 'NamedType', name: 'any' });
1708
+ continue;
1709
+ }
1710
+ if (part.kind !== 'LiteralType' || typeof part.value !== 'string' && typeof part.value !== 'number')
1711
+ return null;
1712
+ const member = this.findTypeMember(object, String(part.value), env);
1713
+ if (member)
1714
+ results.push(member.type);
1715
+ else if (object.kind === 'ObjectType') {
1716
+ const signature = object.members.find(item => item.indexType && this.matchesTypeNode(part.value, item.indexType, env));
1717
+ if (!signature)
1718
+ return null;
1719
+ results.push(signature.type);
1720
+ }
1721
+ else
1722
+ return null;
1723
+ }
1724
+ return results.length === 1 ? results[0] : results.length ? { kind: 'UnionType', types: results } : null;
1725
+ }
1726
+ nonNullableType(type) {
1727
+ if (type.kind !== 'UnionType')
1728
+ return type;
1729
+ const types = type.types.filter(part => !(part.kind === 'NamedType' && part.name === 'null'
1730
+ || part.kind === 'LiteralType' && part.value === null));
1731
+ return types.length === 1 ? types[0] : { ...type, types };
1732
+ }
1733
+ inferValueType(expression, env) {
1734
+ switch (expression.kind) {
1735
+ case 'RegEx': return { kind: 'NamedType', name: 'RegEx' };
1736
+ case 'Literal':
1737
+ return { kind: 'NamedType', name: expression.value === null ? 'null' : typeof expression.value === 'bigint' ? 'BigInt' : typeof expression.value };
1738
+ case 'Template': return { kind: 'NamedType', name: 'string' };
1739
+ case 'Identifier': return this.lookup(env, expression.name)?.declaredType ?? { kind: 'NamedType', name: 'any' };
1740
+ case 'Array': {
1741
+ const elements = expression.elements.map(item => {
1742
+ if (item.kind !== 'Spread')
1743
+ return this.inferValueType(item, env);
1744
+ const spread = this.inferValueType(item.value, env);
1745
+ return spread.kind === 'ArrayType' ? spread.element : { kind: 'NamedType', name: 'any' };
1746
+ });
1747
+ const flattened = elements.flatMap(type => type.kind === 'UnionType' ? type.types : [type]);
1748
+ return { kind: 'ArrayType', element: flattened.length === 0 ? { kind: 'NamedType', name: 'any' } : flattened.length === 1 ? flattened[0] : { kind: 'UnionType', types: flattened } };
1749
+ }
1750
+ case 'Spread': {
1751
+ const spread = this.inferValueType(expression.value, env);
1752
+ return spread.kind === 'ArrayType' ? spread.element : { kind: 'NamedType', name: 'any' };
1753
+ }
1754
+ case 'Object':
1755
+ return { kind: 'ObjectType', members: expression.properties.flatMap(property => property.accessor === 'set' ? [] : [{
1756
+ name: property.key,
1757
+ type: property.accessor === 'get' && property.value.kind === 'Function'
1758
+ ? property.value.returnType ?? { kind: 'NamedType', name: 'any' }
1759
+ : this.inferValueType(property.value, env),
1760
+ optional: false,
1761
+ readonly: false,
1762
+ constant: false,
1763
+ method: property.value.kind === 'Function' && !property.accessor,
1764
+ params: property.value.kind === 'Function' ? property.value.params : undefined
1765
+ }]) };
1766
+ case 'Function':
1767
+ return {
1768
+ kind: 'FunctionType',
1769
+ params: expression.params.map(param => param.type ?? { kind: 'NamedType', name: 'any' }),
1770
+ result: expression.returnType ?? { kind: 'NamedType', name: 'any' }
1771
+ };
1772
+ case 'Index': return this.typeOf(expression, env) ?? { kind: 'NamedType', name: 'any' };
1773
+ case 'Unary':
1774
+ if (expression.operator.endsWith('++') || expression.operator.endsWith('--'))
1775
+ return this.inferValueType(expression.operand, env);
1776
+ return expression.operator === '-' ? { kind: 'NamedType', name: 'number' } : { kind: 'NamedType', name: 'boolean' };
1777
+ case 'Call':
1778
+ if (expression.callee.kind === 'Member' && expression.callee.property === 'as' && expression.typeArguments?.length)
1779
+ return expression.typeArguments[0];
1780
+ if (expression.callee.kind === 'Identifier' && this.lookup(env, expression.callee.name)?.value?.__junoConstructor) {
1781
+ return { kind: 'NamedType', name: 'any' };
1782
+ }
1783
+ if (expression.callee.kind === 'Identifier' && this.lookup(env, expression.callee.name)?.value?.__junoTypeConstructor) {
1784
+ return expression.typeArguments?.length
1785
+ ? { kind: 'GenericType', name: expression.callee.name, args: expression.typeArguments }
1786
+ : { kind: 'NamedType', name: expression.callee.name };
1787
+ }
1788
+ return { kind: 'NamedType', name: 'any' };
1789
+ default: return { kind: 'NamedType', name: 'any' };
1790
+ }
1791
+ }
1792
+ inferRuntimeValueType(value) {
1793
+ if (value === null || value === undefined)
1794
+ return { kind: 'NamedType', name: 'null' };
1795
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
1796
+ return { kind: 'LiteralType', value };
1797
+ if (typeof value === 'bigint')
1798
+ return { kind: 'NamedType', name: 'BigInt' };
1799
+ if (typeof value === 'function' || value?.__junoFunction)
1800
+ return { kind: 'NamedType', name: 'Function' };
1801
+ if (Array.isArray(value)) {
1802
+ const elements = value.map(item => this.inferRuntimeValueType(item));
1803
+ const unique = elements.filter((item, index) => elements.findIndex(other => typeName(other) === typeName(item)) === index);
1804
+ return { kind: 'ArrayType', element: unique.length === 1 ? unique[0] : unique.length ? { kind: 'UnionType', types: unique } : { kind: 'NamedType', name: 'any' } };
1805
+ }
1806
+ const members = Object.entries(value)
1807
+ .filter(([name, member]) => !name.startsWith('__') && typeof member !== 'function' && !member?.__junoFunction)
1808
+ .map(([name, member]) => ({ name, type: this.inferRuntimeValueType(member), optional: false, readonly: false, constant: false }));
1809
+ return { kind: 'ObjectType', members };
1810
+ }
1811
+ resolveAliasType(type, env, resolving = new Set()) {
1812
+ if (type.kind === 'NamedType') {
1813
+ if (resolving.has(type.name))
1814
+ return type;
1815
+ for (let current = env; current; current = current.parent) {
1816
+ const alias = current.types.get(type.name);
1817
+ if (alias && alias.generics.every((_name, index) => alias.genericDefaults?.[index]))
1818
+ return this.resolveAliasType(this.instantiateAlias(alias, []), env, new Set([...resolving, type.name]));
1819
+ }
1820
+ return type;
1821
+ }
1822
+ if (type.kind === 'GenericType') {
1823
+ for (let current = env; current; current = current.parent) {
1824
+ const alias = current.types.get(type.name);
1825
+ if (alias)
1826
+ return this.resolveAliasType(this.instantiateAlias(alias, type.args), env, resolving);
1827
+ }
1828
+ const utility = this.instantiateUtilityType(type, env);
1829
+ return utility ?? type;
1830
+ }
1831
+ if (type.kind === 'UnionType' || type.kind === 'IntersectionType') {
1832
+ const parts = type.types.map(part => this.resolveAliasType(part, env, resolving));
1833
+ if (type.kind === 'IntersectionType' && parts.every(part => part.kind === 'ObjectType'))
1834
+ return { kind: 'ObjectType', members: parts.reverse().flatMap(part => part.kind === 'ObjectType' ? part.members : []) };
1835
+ return { ...type, types: parts };
1836
+ }
1837
+ if (type.kind === 'ArrayType')
1838
+ return { ...type, element: this.resolveAliasType(type.element, env, resolving) };
1839
+ if (type.kind === 'TypeOfType') {
1840
+ const dependsOnUnresolvedType = type.expression.kind === 'Index'
1841
+ && type.expression.index.kind === 'Identifier'
1842
+ && resolving.has(type.expression.index.name);
1843
+ if (dependsOnUnresolvedType)
1844
+ return type;
1845
+ return this.resolveAliasType(this.inferRuntimeValueType(this.evaluate(type.expression, env)), env, resolving);
1846
+ }
1847
+ if (type.kind === 'ConditionalType') {
1848
+ const check = this.resolveAliasType(type.check, env, resolving);
1849
+ const target = this.resolveAliasType(type.target, env, resolving);
1850
+ const assignable = (source, destination) => {
1851
+ if (source.kind === 'UnionType')
1852
+ return source.types.every(part => assignable(part, destination));
1853
+ if (destination.kind === 'UnionType')
1854
+ return destination.types.some(part => assignable(source, part));
1855
+ if (destination.kind === 'NamedType' && (destination.name === 'any' || destination.name === 'unknown'))
1856
+ return true;
1857
+ if (source.kind === 'LiteralType' && destination.kind === 'NamedType')
1858
+ return typeof source.value === destination.name;
1859
+ if (source.kind === 'LiteralType' && destination.kind === 'LiteralType')
1860
+ return source.value === destination.value;
1861
+ if (source.kind === 'NamedType' && destination.kind === 'NamedType')
1862
+ return source.name === destination.name;
1863
+ if (source.kind === 'ArrayType' && destination.kind === 'ArrayType')
1864
+ return assignable(source.element, destination.element);
1865
+ return false;
1866
+ };
1867
+ return this.resolveAliasType(assignable(check, target) ? type.consequent : type.alternate, env, resolving);
1868
+ }
1869
+ if (type.kind === 'IndexedAccessType')
1870
+ return this.indexedType(type.object, type.index, env) ?? { kind: 'NamedType', name: 'any' };
1871
+ if (type.kind === 'ObjectType')
1872
+ return { ...type, members: type.members.map(member => ({
1873
+ ...member,
1874
+ type: this.resolveAliasType(member.type, env, new Set([...resolving, ...(member.generics ?? []), ...(member.indexType ? [member.name] : [])])),
1875
+ indexType: member.indexType ? this.resolveAliasType(member.indexType, env, resolving) : undefined,
1876
+ params: member.params?.map(param => ({ ...param, type: param.type ? this.resolveAliasType(param.type, env, new Set([...resolving, ...(member.generics ?? [])])) : undefined }))
1877
+ })) };
1878
+ if (type.kind === 'FunctionType')
1879
+ return { ...type, params: type.params.map(param => this.resolveAliasType(param, env, resolving)), result: this.resolveAliasType(type.result, env, resolving) };
1880
+ return type;
1881
+ }
1882
+ instantiateAlias(alias, args) {
1883
+ const substitutions = new Map(alias.generics.map((name, index) => [name, args[index] ?? alias.genericDefaults?.[index] ?? { kind: 'NamedType', name }]));
1884
+ const replace = (node) => {
1885
+ if (node.kind === 'NamedType' && substitutions.has(node.name))
1886
+ return substitutions.get(node.name);
1887
+ if (node.kind === 'GenericType')
1888
+ return { ...node, args: node.args.map(replace) };
1889
+ if (node.kind === 'UnionType' || node.kind === 'IntersectionType')
1890
+ return { ...node, types: node.types.map(replace) };
1891
+ if (node.kind === 'ArrayType')
1892
+ return { ...node, element: replace(node.element) };
1893
+ if (node.kind === 'IndexedAccessType')
1894
+ return { ...node, object: replace(node.object), index: replace(node.index) };
1895
+ if (node.kind === 'ConditionalType')
1896
+ return { ...node, check: replace(node.check), target: replace(node.target), consequent: replace(node.consequent), alternate: replace(node.alternate) };
1897
+ if (node.kind === 'FunctionType')
1898
+ return { ...node, params: node.params.map(replace), result: replace(node.result) };
1899
+ if (node.kind === 'ObjectType')
1900
+ return { ...node, members: node.members.map(member => ({ ...member, type: replace(member.type), indexType: member.indexType ? replace(member.indexType) : undefined })) };
1901
+ return node;
1902
+ };
1903
+ return replace(alias.value);
1904
+ }
1905
+ isCallableType(type) {
1906
+ return type.kind === 'FunctionType' || (type.kind === 'NamedType' && type.name === 'any')
1907
+ || type.kind === 'ObjectType' && type.members.some(member => member.name === '' && member.method);
1908
+ }
1909
+ instantiateUtilityType(type, env) {
1910
+ if (!['Partial', 'Required', 'Readonly', 'Pick', 'Omit', 'KeyOf', 'Exclude'].includes(type.name) || !type.args[0])
1911
+ return null;
1912
+ if (type.name === 'Exclude') {
1913
+ const source = this.resolveAliasType(type.args[0], env);
1914
+ const excluded = type.args[1] ? this.resolveAliasType(type.args[1], env) : { kind: 'NamedType', name: 'never' };
1915
+ const parts = source.kind === 'UnionType' ? source.types : [source];
1916
+ const remaining = parts.filter(part => typeName(part) !== typeName(excluded) && !(excluded.kind === 'UnionType' && excluded.types.some(item => typeName(item) === typeName(part))));
1917
+ return remaining.length === 1 ? remaining[0] : remaining.length ? { kind: 'UnionType', types: remaining } : { kind: 'NamedType', name: 'never' };
1918
+ }
1919
+ const source = this.resolveAliasType(type.args[0], env);
1920
+ if (type.name === 'KeyOf') {
1921
+ if (source.kind === 'ArrayType' || source.kind === 'GenericType' && (source.name === 'Array' || source.name === 'ReadonlyArray')) {
1922
+ const names = ['length', 'indices', 'has', 'pick', 'omit', 'deepClone', 'deepFreeze', 'toDeepFreezed', 'at', 'concat', 'copy', 'copyWithin', 'entries', 'enumerate', 'every', 'fill', 'filter', 'find', 'findIndex', 'findLast', 'findLastIndex', 'flat', 'flatMap', 'forEach', 'includes', 'indexOf', 'iterator', 'join', 'lastIndexOf', 'map', 'pop', 'push', 'reduce', 'reduceRight', 'reverse', 'shift', 'slice', 'some', 'sort', 'splice', 'toArray', 'toReversed', 'toSorted', 'toSpliced', 'toString', 'unshift', 'with'];
1923
+ return { kind: 'UnionType', types: [{ kind: 'NamedType', name: 'number' }, ...names.map(name => ({ kind: 'LiteralType', value: name }))] };
1924
+ }
1925
+ if (source.kind !== 'ObjectType')
1926
+ return null;
1927
+ const keys = source.members.flatMap(member => {
1928
+ if (member.indexType)
1929
+ return [member.indexType];
1930
+ const numeric = Number(member.name);
1931
+ return [{ kind: 'LiteralType', value: member.name !== '' && Number.isFinite(numeric) && String(numeric) === member.name ? numeric : member.name }];
1932
+ });
1933
+ return keys.length === 1 ? keys[0] : { kind: 'UnionType', types: keys };
1934
+ }
1935
+ if (source.kind === 'UnionType' || source.kind === 'IntersectionType') {
1936
+ return { ...source, types: source.types.map(part => this.instantiateUtilityType({ ...type, args: [part, ...type.args.slice(1)] }, env) ?? part) };
1937
+ }
1938
+ if (source.kind !== 'ObjectType')
1939
+ return null;
1940
+ let members = source.members;
1941
+ if (type.name === 'Partial')
1942
+ members = members.map(member => ({ ...member, optional: true }));
1943
+ else if (type.name === 'Required')
1944
+ members = members.map(member => ({ ...member, optional: false }));
1945
+ else if (type.name === 'Readonly')
1946
+ members = members.map(member => ({ ...member, readonly: true }));
1947
+ else if (type.name === 'Pick' || type.name === 'Omit') {
1948
+ const keyArgument = type.args[1];
1949
+ const keys = keyArgument?.kind === 'ArrayType'
1950
+ ? this.literalKeys(keyArgument.element)
1951
+ : this.literalKeys(keyArgument);
1952
+ if (!keys)
1953
+ return null;
1954
+ members = members.filter(member => type.name === 'Pick' ? keys.has(member.name) : !keys.has(member.name));
1955
+ }
1956
+ return { ...source, members };
1957
+ }
1958
+ literalKeys(type) {
1959
+ if (!type)
1960
+ return null;
1961
+ if (type.kind === 'LiteralType' && typeof type.value === 'string')
1962
+ return new Set([type.value]);
1963
+ if (type.kind === 'UnionType') {
1964
+ const keys = new Set();
1965
+ for (const part of type.types) {
1966
+ const values = this.literalKeys(part);
1967
+ if (!values)
1968
+ return null;
1969
+ for (const value of values)
1970
+ keys.add(value);
1971
+ }
1972
+ return keys;
1973
+ }
1974
+ if (type.kind === 'ArrayType')
1975
+ return this.literalKeys(type.element);
1976
+ return null;
1977
+ }
1978
+ matchesTypeNode(value, type, env, resolving = new Set()) {
1979
+ if (type.kind === 'TypeOfType' || type.kind === 'IndexedAccessType' || type.kind === 'ConditionalType') {
1980
+ const resolved = this.resolveAliasType(type, env, resolving);
1981
+ return this.matchesTypeNode(value, resolved, env, resolving);
1982
+ }
1983
+ if (type.kind === 'NamedType') {
1984
+ if (type.name === 'any' || type.name === 'unknown')
1985
+ return true;
1986
+ if (type.name === 'null')
1987
+ return value === null;
1988
+ if (type.name === 'Array' || type.name === 'ReadonlyArray')
1989
+ return Array.isArray(value);
1990
+ for (let current = env; current; current = current.parent) {
1991
+ const alias = current.types.get(type.name);
1992
+ if (alias && alias.generics.every((_name, index) => alias.genericDefaults?.[index])) {
1993
+ if (resolving.has(type.name))
1994
+ return false;
1995
+ return this.matchesTypeNode(value, this.instantiateAlias(alias, []), env, new Set([...resolving, type.name]));
1996
+ }
1997
+ }
1998
+ switch (type.name) {
1999
+ case 'string': return typeof value === 'string';
2000
+ case 'number': return typeof value === 'number';
2001
+ case 'boolean': return typeof value === 'boolean';
2002
+ case 'BigInt': return typeof value === 'bigint';
2003
+ case 'RegEx': return value instanceof RegExp;
2004
+ case 'object': return value !== null && typeof value === 'object';
2005
+ case 'Function': return typeof value === 'function' || Boolean(value?.__junoFunction);
2006
+ default: return false;
2007
+ }
2008
+ }
2009
+ if (type.kind === 'LiteralType')
2010
+ return value === type.value;
2011
+ if (type.kind === 'ArrayType')
2012
+ return Array.isArray(value) && value.every(item => this.matchesTypeNode(item, type.element, env, resolving));
2013
+ if (type.kind === 'GenericType') {
2014
+ if ((type.name === 'Array' || type.name === 'ReadonlyArray') && type.args[0]) {
2015
+ return Array.isArray(value) && value.every(item => this.matchesTypeNode(item, type.args[0], env, resolving));
2016
+ }
2017
+ const resolved = this.resolveAliasType(type, env);
2018
+ if (resolved !== type)
2019
+ return this.matchesTypeNode(value, resolved, env, resolving);
2020
+ return this.matchesTypeNode(value, { kind: 'NamedType', name: type.name }, env, resolving);
2021
+ }
2022
+ if (type.kind === 'UnionType')
2023
+ return type.types.some(part => this.matchesTypeNode(value, part, env, resolving));
2024
+ if (type.kind === 'IntersectionType')
2025
+ return type.types.every(part => this.matchesTypeNode(value, part, env, resolving));
2026
+ if (type.kind === 'FunctionType')
2027
+ return typeof value === 'function' || Boolean(value?.__junoFunction || value?.__junoCall?.__junoFunction);
2028
+ if (type.kind === 'ObjectType') {
2029
+ if (value === null || typeof value !== 'object')
2030
+ return false;
2031
+ const object = value;
2032
+ for (const signature of type.members.filter(member => member.indexType)) {
2033
+ for (const [key, memberValue] of Object.entries(object)) {
2034
+ if (key.startsWith('__') || typeof memberValue === 'function' || memberValue?.__junoFunction)
2035
+ continue;
2036
+ const numeric = Number(key);
2037
+ const runtimeKey = Number.isFinite(numeric) && String(numeric) === key ? numeric : key;
2038
+ if (this.matchesTypeNode(runtimeKey, signature.indexType, env, resolving) && !this.matchesTypeNode(memberValue, signature.type, env, resolving))
2039
+ return false;
2040
+ }
2041
+ }
2042
+ return type.members.filter(member => !member.indexType).every(member => {
2043
+ if (member.name === '' && member.method)
2044
+ return Boolean(object.__junoCall?.__junoFunction);
2045
+ if (!Object.prototype.hasOwnProperty.call(object, member.name))
2046
+ return member.optional || member.defaultValue !== undefined;
2047
+ const memberValue = object[member.name];
2048
+ if (member.accessor === 'set')
2049
+ return typeof Object.getOwnPropertyDescriptor(object, member.name)?.set === 'function';
2050
+ if (member.accessor === 'get')
2051
+ return this.matchesTypeNode(memberValue, member.type, env, resolving);
2052
+ if (member.method)
2053
+ return typeof memberValue === 'function' || Boolean(memberValue?.__junoFunction);
2054
+ return this.matchesTypeNode(memberValue, member.type, env, resolving);
2055
+ });
2056
+ }
2057
+ return false;
2058
+ }
2059
+ applyTypeDefaults(value, type, env, resolving = new Set()) {
2060
+ if (type.kind === 'GenericType') {
2061
+ const resolved = this.resolveAliasType(type, env);
2062
+ if (resolved !== type)
2063
+ return this.applyTypeDefaults(value, resolved, env, resolving);
2064
+ return value;
2065
+ }
2066
+ if (type.kind === 'NamedType') {
2067
+ if (resolving.has(type.name))
2068
+ return value;
2069
+ for (let current = env; current; current = current.parent) {
2070
+ const alias = current.types.get(type.name);
2071
+ if (alias && alias.generics.every((_name, index) => alias.genericDefaults?.[index]))
2072
+ return this.applyTypeDefaults(value, this.instantiateAlias(alias, []), env, new Set([...resolving, type.name]));
2073
+ }
2074
+ return value;
2075
+ }
2076
+ if (type.kind === 'IntersectionType') {
2077
+ for (const part of [...type.types].reverse())
2078
+ this.applyTypeDefaults(value, part, env, resolving);
2079
+ return value;
2080
+ }
2081
+ if (type.kind === 'UnionType') {
2082
+ for (const part of type.types) {
2083
+ if (part.kind === 'NamedType' && part.name === 'null')
2084
+ continue;
2085
+ this.applyTypeDefaults(value, part, env, resolving);
2086
+ }
2087
+ return value;
2088
+ }
2089
+ // A frozen value is already finalized. Applying defaults must not
2090
+ // mutate it or replace it with a mutable copy.
2091
+ if (type.kind !== 'ObjectType' || Object.isFrozen(value))
2092
+ return value;
2093
+ const runtimeValue = value;
2094
+ const resolvedType = this.resolveAliasType(type, env);
2095
+ if (resolvedType.kind === 'ObjectType')
2096
+ type = resolvedType;
2097
+ this.installDefaultHas(runtimeValue);
2098
+ const sealedMembers = runtimeValue.__junoSealed ?? new Set();
2099
+ if (!runtimeValue.__junoSealed)
2100
+ Object.defineProperty(runtimeValue, '__junoSealed', { enumerable: false, configurable: false, value: sealedMembers });
2101
+ if (typeof runtimeValue.toString !== 'function' && !runtimeValue.toString?.__junoFunction) {
2102
+ runtimeValue.toString = this.defaultToString();
2103
+ }
2104
+ for (const member of type.members) {
2105
+ if (member.indexType)
2106
+ continue;
2107
+ if (member.accessor && member.body) {
2108
+ const previous = Object.getOwnPropertyDescriptor(runtimeValue, member.name) ?? { enumerable: true, configurable: true };
2109
+ const runtimeFn = { __junoFunction: true, params: member.params ?? [], body: member.body, closure: env, thisValue: value };
2110
+ delete previous.value;
2111
+ delete previous.writable;
2112
+ if (member.accessor === 'get')
2113
+ previous.get = () => this.callFunction(runtimeFn, [], value);
2114
+ else
2115
+ previous.set = (input) => { this.callFunction(runtimeFn, [input], value); };
2116
+ previous.enumerable = true;
2117
+ previous.configurable = true;
2118
+ Object.defineProperty(runtimeValue, member.name, previous);
2119
+ if (member.sealed)
2120
+ sealedMembers.add(member.name);
2121
+ continue;
2122
+ }
2123
+ if (member.method) {
2124
+ if (member.name === '') {
2125
+ if (member.body && !runtimeValue.__junoCall?.__junoFunction) {
2126
+ Object.defineProperty(runtimeValue, '__junoCall', {
2127
+ enumerable: false,
2128
+ configurable: true,
2129
+ writable: true,
2130
+ value: { __junoFunction: true, params: member.params ?? [], body: member.body, closure: env, thisValue: value }
2131
+ });
2132
+ }
2133
+ continue;
2134
+ }
2135
+ const isDefaultToString = member.name === 'toString' && runtimeValue[member.name]?.__junoDefaultToString;
2136
+ if (member.body && (isDefaultToString || (typeof runtimeValue[member.name] !== 'function' && !runtimeValue[member.name]?.__junoFunction))) {
2137
+ ;
2138
+ value[member.name] = { __junoFunction: true, params: member.params ?? [], body: member.body, closure: env, thisValue: value };
2139
+ }
2140
+ if (member.sealed)
2141
+ sealedMembers.add(member.name);
2142
+ continue;
2143
+ }
2144
+ const nullableMember = member.type.kind === 'NamedType' && member.type.name === 'null'
2145
+ || member.type.kind === 'UnionType' && member.type.types.some(part => part.kind === 'NamedType' && part.name === 'null');
2146
+ if (!Object.prototype.hasOwnProperty.call(value, member.name) && (member.optional || nullableMember) && member.defaultValue === undefined) {
2147
+ Object.defineProperty(runtimeValue, member.name, {
2148
+ value: null,
2149
+ enumerable: false,
2150
+ writable: !member.readonly,
2151
+ configurable: !member.readonly
2152
+ });
2153
+ }
2154
+ if (!Object.prototype.hasOwnProperty.call(value, member.name) && member.defaultValue) {
2155
+ ;
2156
+ value[member.name] = this.evaluate(member.defaultValue, env);
2157
+ }
2158
+ const fieldValue = value[member.name];
2159
+ if (fieldValue && typeof fieldValue === 'object' && !Array.isArray(fieldValue)) {
2160
+ this.applyTypeDefaults(fieldValue, member.type, env, resolving);
2161
+ }
2162
+ if (member.sealed)
2163
+ sealedMembers.add(member.name);
2164
+ }
2165
+ this.installCallableMethods(runtimeValue);
2166
+ return value;
2167
+ }
2168
+ findTypeMember(type, name, env, resolving = new Set()) {
2169
+ if ((name === 'asReadonly' || name === 'asMutable' || name === 'deepClone' || name === 'deepFreeze' || name === 'toDeepFreezed') && !(type.kind === 'LiteralType' && type.value === null) && !(type.kind === 'NamedType' && type.name === 'null')) {
2170
+ return { type: { kind: 'FunctionType', params: [], result: type }, optional: false };
2171
+ }
2172
+ if (type.kind === 'NamedType') {
2173
+ if (resolving.has(type.name))
2174
+ return null;
2175
+ for (let current = env; current; current = current.parent) {
2176
+ const alias = current.types.get(type.name);
2177
+ if (alias && alias.generics.every((_generic, index) => alias.genericDefaults?.[index]))
2178
+ return this.findTypeMember(this.instantiateAlias(alias, []), name, env, new Set([...resolving, type.name]));
2179
+ }
2180
+ if (type.name === 'string') {
2181
+ const string = { kind: 'NamedType', name: 'string' };
2182
+ const number = { kind: 'NamedType', name: 'number' };
2183
+ const boolean = { kind: 'NamedType', name: 'boolean' };
2184
+ const regex = { kind: 'NamedType', name: 'RegEx' };
2185
+ const matcher = { kind: 'UnionType', types: [string, regex] };
2186
+ const callable = (params, result) => ({ type: { kind: 'FunctionType', params, result }, optional: false });
2187
+ if (name === 'length')
2188
+ return { type: number, optional: false };
2189
+ if (name === 'indices')
2190
+ return { type: { kind: 'NamedType', name: 'Range' }, optional: false };
2191
+ if (['find', 'findLast'].includes(name))
2192
+ return callable([matcher], { kind: 'UnionType', types: [string, { kind: 'NamedType', name: 'null' }] });
2193
+ if (['findIndex', 'findLastIndex', 'indexOf', 'lastIndexOf', 'search', 'charCodeAt', 'codePointAt', 'localeCompare'].includes(name))
2194
+ return callable([matcher], number);
2195
+ if (['includes', 'startsWith', 'endsWith', 'test'].includes(name))
2196
+ return callable([matcher], boolean);
2197
+ if (name === 'exec')
2198
+ return callable([matcher], { kind: 'UnionType', types: [{ kind: 'ArrayType', element: string }, { kind: 'NamedType', name: 'null' }] });
2199
+ if (name === 'join')
2200
+ return callable([string], string);
2201
+ if (['split', 'match', 'matchAll', 'toArray'].includes(name))
2202
+ return callable(name === 'toArray' ? [] : [matcher], { kind: 'ArrayType', element: string });
2203
+ if (name === 'iterator')
2204
+ return callable([], { kind: 'FunctionType', params: [], result: { kind: 'NamedType', name: 'any' } });
2205
+ if (['at', 'charAt', 'concat', 'normalize', 'padEnd', 'padStart', 'repeat', 'replace', 'replaceAll', 'slice', 'substring', 'substr', 'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimEnd', 'trimStart', 'valueOf'].includes(name))
2206
+ return callable([], string);
2207
+ }
2208
+ if (type.name === 'RegEx') {
2209
+ const string = { kind: 'NamedType', name: 'string' };
2210
+ const boolean = { kind: 'NamedType', name: 'boolean' };
2211
+ const number = { kind: 'NamedType', name: 'number' };
2212
+ if (['source', 'flags'].includes(name))
2213
+ return { type: string, optional: false };
2214
+ if (['global', 'ignoreCase', 'multiline', 'dotAll', 'sticky', 'unicode', 'hasIndices', 'unicodeSets'].includes(name))
2215
+ return { type: boolean, optional: false };
2216
+ if (name === 'lastIndex')
2217
+ return { type: number, optional: false };
2218
+ const input = { kind: 'UnionType', types: [string, { kind: 'NamedType', name: 'RegEx' }] };
2219
+ if (name === 'test')
2220
+ return { type: { kind: 'FunctionType', params: [input], result: boolean }, optional: false };
2221
+ if (name === 'exec')
2222
+ return { type: { kind: 'FunctionType', params: [input], result: { kind: 'UnionType', types: [{ kind: 'ArrayType', element: string }, { kind: 'NamedType', name: 'null' }] } }, optional: false };
2223
+ if (name === 'compile')
2224
+ return { type: { kind: 'FunctionType', params: [input, string], result: { kind: 'NamedType', name: 'RegEx' } }, optional: false };
2225
+ }
2226
+ if (type.name === 'number' && name === 'valueOf') {
2227
+ return { type: { kind: 'FunctionType', params: [], result: { kind: 'NamedType', name: 'number' } }, optional: false };
2228
+ }
2229
+ if (name === 'toString' && type.name !== 'null')
2230
+ return { type: { kind: 'NamedType', name: 'string' }, optional: false };
2231
+ return null;
2232
+ }
2233
+ if (type.kind === 'IntersectionType') {
2234
+ for (const part of type.types) {
2235
+ const member = this.findTypeMember(part, name, env, resolving);
2236
+ if (member)
2237
+ return member;
2238
+ }
2239
+ return null;
2240
+ }
2241
+ if (type.kind === 'UnionType') {
2242
+ let commonMember = null;
2243
+ for (const part of type.types) {
2244
+ const member = this.findTypeMember(part, name, env, resolving);
2245
+ if (!member)
2246
+ return null;
2247
+ if (!commonMember)
2248
+ commonMember = member;
2249
+ else
2250
+ commonMember.optional ||= member.optional;
2251
+ }
2252
+ return commonMember;
2253
+ }
2254
+ if (type.kind === 'GenericType') {
2255
+ for (let current = env; current; current = current.parent) {
2256
+ const alias = current.types.get(type.name);
2257
+ if (alias)
2258
+ return this.findTypeMember(this.instantiateAlias(alias, type.args), name, env, resolving);
2259
+ }
2260
+ }
2261
+ if (type.kind === 'ObjectType') {
2262
+ const member = type.members.find(item => !item.indexType && item.name === name && item.accessor === 'get')
2263
+ ?? type.members.find(item => !item.indexType && item.name === name);
2264
+ if (member)
2265
+ return { type: member.type, optional: member.optional };
2266
+ const indexMember = type.members.find(item => item.indexType && this.matchesTypeNode(name, item.indexType, env));
2267
+ if (indexMember)
2268
+ return { type: indexMember.type, optional: indexMember.optional };
2269
+ const call = type.members.find(item => item.name === '' && item.method);
2270
+ if (call) {
2271
+ const any = { kind: 'NamedType', name: 'any' };
2272
+ const signature = { kind: 'FunctionType', params: (call.params ?? []).map(param => param.type ?? any), result: call.type };
2273
+ if (name === 'call')
2274
+ return { type: { kind: 'FunctionType', params: [any, ...(call.params ?? []).map(param => param.type ?? any)], result: call.type }, optional: false };
2275
+ if (name === 'apply')
2276
+ return { type: { kind: 'FunctionType', params: [any, { kind: 'ArrayType', element: any }], result: call.type }, optional: false };
2277
+ if (name === 'bind')
2278
+ return { type: { kind: 'FunctionType', params: [any], result: signature }, optional: false };
2279
+ }
2280
+ if (name === 'has')
2281
+ return { type: { kind: 'FunctionType', params: [{ kind: 'NamedType', name: 'string' }], result: { kind: 'NamedType', name: 'boolean' } }, optional: false };
2282
+ if (name === 'pick' || name === 'omit')
2283
+ return { type: { kind: 'FunctionType', params: [{ kind: 'ArrayType', element: { kind: 'NamedType', name: 'any' } }], result: type }, optional: false };
2284
+ }
2285
+ if ((name === 'pick' || name === 'omit') && (type.kind === 'ArrayType' || type.kind === 'GenericType' && (type.name === 'Array' || type.name === 'ReadonlyArray'))) {
2286
+ return { type: { kind: 'FunctionType', params: [{ kind: 'ArrayType', element: { kind: 'NamedType', name: 'number' } }], result: type }, optional: false };
2287
+ }
2288
+ if (name === 'has' && (type.kind === 'ArrayType' || type.kind === 'GenericType' && (type.name === 'Array' || type.name === 'ReadonlyArray'))) {
2289
+ return { type: { kind: 'FunctionType', params: [{ kind: 'NamedType', name: 'string' }], result: { kind: 'NamedType', name: 'boolean' } }, optional: false };
2290
+ }
2291
+ if (name === 'length' && (type.kind === 'ArrayType' || type.kind === 'GenericType' && (type.name === 'Array' || type.name === 'ReadonlyArray'))) {
2292
+ return { type: { kind: 'NamedType', name: 'number' }, optional: false };
2293
+ }
2294
+ if (name === 'indices' && (type.kind === 'ArrayType' || type.kind === 'GenericType' && (type.name === 'Array' || type.name === 'ReadonlyArray'))) {
2295
+ return { type: { kind: 'NamedType', name: 'Range' }, optional: false };
2296
+ }
2297
+ if (name === 'push' && (type.kind === 'ArrayType' || type.kind === 'GenericType' && (type.name === 'Array' || type.name === 'ReadonlyArray'))) {
2298
+ const element = type.kind === 'ArrayType' ? type.element : type.args[0] ?? { kind: 'NamedType', name: 'any' };
2299
+ return { type: { kind: 'FunctionType', params: [element], result: { kind: 'NamedType', name: 'number' } }, optional: false };
2300
+ }
2301
+ if (name === 'includes' && (type.kind === 'ArrayType' || type.kind === 'GenericType' && (type.name === 'Array' || type.name === 'ReadonlyArray'))) {
2302
+ const element = type.kind === 'ArrayType' ? type.element : type.args[0] ?? { kind: 'NamedType', name: 'any' };
2303
+ return { type: { kind: 'FunctionType', params: [element], result: { kind: 'NamedType', name: 'boolean' } }, optional: false };
2304
+ }
2305
+ if (name === 'toString' && !(type.kind === 'LiteralType' && type.value === null)) {
2306
+ return { type: { kind: 'NamedType', name: 'string' }, optional: false };
2307
+ }
2308
+ return null;
2309
+ }
2310
+ readMember(object, property, optional, owner, env) {
2311
+ if (object === null || object === undefined) {
2312
+ if (optional)
2313
+ return null;
2314
+ throw new TypeError(`Cannot read property '${property}' of null`);
2315
+ }
2316
+ if (object instanceof Promise && property === 'then')
2317
+ return (...callbacks) => {
2318
+ if (callbacks.length !== 1 || typeof callbacks[0] !== 'function')
2319
+ throw new TypeError('Promise.then() accepts exactly one fulfilled callback');
2320
+ return object.then(callbacks[0]);
2321
+ };
2322
+ if (property === 'indices' && (typeof object === 'string' || Array.isArray(object))) {
2323
+ return (0, Modules_1.resolveModule)('juno').Range(object.length);
2324
+ }
2325
+ if (Array.isArray(object) && property === 'includes') {
2326
+ return (value, fromIndex = 0) => {
2327
+ let start = Math.trunc(fromIndex);
2328
+ if (start < 0)
2329
+ start = Math.max(object.length + start, 0);
2330
+ for (let index = start; index < object.length; index++) {
2331
+ if (deepEqual(object[index], value))
2332
+ return true;
2333
+ }
2334
+ return false;
2335
+ };
2336
+ }
2337
+ if (Array.isArray(object) && (property === 'copy' || property === 'toArray'))
2338
+ return () => [...object];
2339
+ if (object && typeof object === 'object' && object.__junoFunction && property === 'call') {
2340
+ return (thisArg, ...args) => this.callFunction(object, args, thisArg);
2341
+ }
2342
+ if (typeof object === 'string') {
2343
+ const findMatch = (search, last) => {
2344
+ if (typeof search === 'string') {
2345
+ const index = last ? object.lastIndexOf(search) : object.indexOf(search);
2346
+ return index < 0 ? null : { value: search, index };
2347
+ }
2348
+ const flags = search.flags.includes('g') ? search.flags : `${search.flags}g`;
2349
+ const regexp = new RegExp(search.source, flags);
2350
+ let found = null;
2351
+ for (let match = regexp.exec(object); match; match = regexp.exec(object)) {
2352
+ found = match;
2353
+ if (!last)
2354
+ break;
2355
+ if (match[0] === '')
2356
+ regexp.lastIndex++;
2357
+ }
2358
+ return found ? { value: found[0], index: found.index } : null;
2359
+ };
2360
+ if (property === 'find')
2361
+ return (search) => findMatch(search, false)?.value ?? null;
2362
+ if (property === 'findLast')
2363
+ return (search) => findMatch(search, true)?.value ?? null;
2364
+ if (property === 'findIndex')
2365
+ return (search) => findMatch(search, false)?.index ?? -1;
2366
+ if (property === 'findLastIndex')
2367
+ return (search) => findMatch(search, true)?.index ?? -1;
2368
+ if (property === 'includes')
2369
+ return (search, position = 0) => typeof search === 'string' ? object.includes(search, position) : findMatch(search, false) !== null;
2370
+ if (property === 'test')
2371
+ return (pattern) => new RegExp(pattern).test(object);
2372
+ if (property === 'exec')
2373
+ return (pattern) => new RegExp(pattern).exec(object);
2374
+ if (property === 'join')
2375
+ return (separator = ',') => object.split('').join(separator);
2376
+ if (property === 'toArray')
2377
+ return () => object.split('');
2378
+ if (property === 'iterator')
2379
+ return () => {
2380
+ const iterator = object[Symbol.iterator]();
2381
+ return () => {
2382
+ const next = iterator.next();
2383
+ return next.done ? null : { value: next.value };
2384
+ };
2385
+ };
2386
+ }
2387
+ const hasProperty = property in Object(object);
2388
+ if (!hasProperty && (typeof object === 'object' || typeof object === 'function'))
2389
+ return null;
2390
+ const declaredType = this.typeOf(owner, env);
2391
+ const memberLookupType = declaredType && optional ? this.nonNullableType(declaredType) : declaredType;
2392
+ const declaredMember = memberLookupType ? this.findTypeMember(memberLookupType, property, env) : null;
2393
+ if (declaredType && !(declaredType.kind === 'NamedType' && declaredType.name === 'any') && !declaredMember) {
2394
+ throw new TypeError(`Property '${property}' does not exist on declared type`);
2395
+ }
2396
+ if (!hasProperty) {
2397
+ if (optional || declaredMember?.optional)
2398
+ return null;
2399
+ throw new TypeError(`Property '${property}' does not exist on value`);
2400
+ }
2401
+ const value = object[property];
2402
+ return value === undefined ? null : value;
2403
+ }
2404
+ }
2405
+ exports.Interpreter = Interpreter;
2406
+ function deepEqual(a, b, seen = new WeakMap()) {
2407
+ if (a === b || typeof a === 'number' && typeof b === 'number' && Number.isNaN(a) && Number.isNaN(b))
2408
+ return true;
2409
+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object')
2410
+ return false;
2411
+ if (Array.isArray(a) !== Array.isArray(b))
2412
+ return false;
2413
+ let compared = seen.get(a);
2414
+ if (compared?.has(b))
2415
+ return true;
2416
+ if (!compared) {
2417
+ compared = new WeakSet();
2418
+ seen.set(a, compared);
2419
+ }
2420
+ compared.add(b);
2421
+ const structuralKeys = (value) => Object.keys(value).filter(key => !(key === 'toString' && typeof value[key] === 'function' && value[key].__junoDefaultToString));
2422
+ const keysA = structuralKeys(a), keysB = structuralKeys(b);
2423
+ return keysA.length === keysB.length && keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key], seen));
2424
+ }
2425
+ function isRuntimeCallable(value) {
2426
+ return Boolean(value && typeof value === 'object' && (value.__junoFunction || value.__junoConstructor));
2427
+ }
2428
+ function deepCloneValue(value, seen = new WeakMap()) {
2429
+ if (value === null || typeof value !== 'object' || isRuntimeCallable(value))
2430
+ return value;
2431
+ const existing = seen.get(value);
2432
+ if (existing)
2433
+ return existing;
2434
+ if (value instanceof Set) {
2435
+ const clone = new Set();
2436
+ seen.set(value, clone);
2437
+ for (const item of value)
2438
+ clone.add(deepCloneValue(item, seen));
2439
+ return clone;
2440
+ }
2441
+ if (value instanceof Map) {
2442
+ const clone = new Map();
2443
+ seen.set(value, clone);
2444
+ for (const [key, item] of value)
2445
+ clone.set(deepCloneValue(key, seen), deepCloneValue(item, seen));
2446
+ return clone;
2447
+ }
2448
+ const clone = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
2449
+ seen.set(value, clone);
2450
+ for (const key of Reflect.ownKeys(value)) {
2451
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
2452
+ if (!descriptor)
2453
+ continue;
2454
+ if ('value' in descriptor)
2455
+ descriptor.value = deepCloneValue(descriptor.value, seen);
2456
+ Object.defineProperty(clone, key, descriptor);
2457
+ }
2458
+ return clone;
2459
+ }
2460
+ function deepFreezeValue(value, seen = new WeakSet()) {
2461
+ if (value === null || typeof value !== 'object' || isRuntimeCallable(value) || seen.has(value))
2462
+ return value;
2463
+ seen.add(value);
2464
+ for (const key of Reflect.ownKeys(value)) {
2465
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
2466
+ if (descriptor && 'value' in descriptor)
2467
+ deepFreezeValue(descriptor.value, seen);
2468
+ }
2469
+ return Object.freeze(value);
2470
+ }
2471
+ function stringifyJunoObject(value) {
2472
+ return JSON.stringify(value, (_key, item) => {
2473
+ if (item && typeof item === 'object' && item.__junoFunction)
2474
+ return undefined;
2475
+ if (typeof item === 'bigint')
2476
+ return String(item);
2477
+ return item;
2478
+ }) ?? 'null';
2479
+ }
2480
+ function matchesType(value, type) {
2481
+ if (typeof type !== 'string')
2482
+ return false;
2483
+ switch (type) {
2484
+ case 'string': return typeof value === 'string';
2485
+ case 'number': return typeof value === 'number';
2486
+ case 'boolean': return typeof value === 'boolean';
2487
+ case 'RegEx': return value instanceof RegExp;
2488
+ case 'null': return value === null;
2489
+ case 'Array': return Array.isArray(value);
2490
+ case 'object': return value !== null && typeof value === 'object';
2491
+ default: return false;
2492
+ }
2493
+ }
2494
+ function typeName(type) {
2495
+ switch (type.kind) {
2496
+ case 'NamedType': return type.name;
2497
+ case 'LiteralType': return String(type.value);
2498
+ case 'GenericType': return `${type.name}<${type.args.map(typeName).join(', ')}>`;
2499
+ case 'ArrayType': return `${typeName(type.element)}[]`;
2500
+ case 'IndexedAccessType': return `${typeName(type.object)}[${typeName(type.index)}]`;
2501
+ case 'TypeOfType': return 'typeof<…>';
2502
+ case 'ConditionalType': return `${typeName(type.check)} is ${typeName(type.target)} ? ${typeName(type.consequent)} : ${typeName(type.alternate)}`;
2503
+ case 'UnionType': return type.types.map(typeName).join(' | ');
2504
+ case 'IntersectionType': return type.types.map(typeName).join(' & ');
2505
+ case 'FunctionType': return 'function';
2506
+ case 'ObjectType': return 'object';
2507
+ }
2508
+ }
2509
+ function runFile(file) {
2510
+ const path = (0, node_path_1.resolve)(file);
2511
+ const source = (0, node_fs_1.readFileSync)(path, 'utf8');
2512
+ const diagnostics = (0, language_js_1.analyze)(source, path)?.diagnostics ?? [];
2513
+ if (diagnostics.length) {
2514
+ const details = diagnostics
2515
+ .map(diagnostic => `${path}:${diagnostic.line}:${diagnostic.column} - ${diagnostic.message}`)
2516
+ .join('\n');
2517
+ throw new Error(`JunoScript diagnostics prevented execution:\n${details}`);
2518
+ }
2519
+ const interpreter = new Interpreter();
2520
+ interpreter.currentDirectory = (0, node_path_1.resolve)(path, '..');
2521
+ interpreter.run(source, path);
2522
+ }
2523
+ function runBuiltModule(source, file) {
2524
+ const path = (0, node_path_1.resolve)(file);
2525
+ const diagnostics = (0, language_js_1.analyze)(source, path)?.diagnostics ?? [];
2526
+ if (diagnostics.length) {
2527
+ const details = diagnostics
2528
+ .map(diagnostic => `${path}:${diagnostic.line}:${diagnostic.column} - ${diagnostic.message}`)
2529
+ .join('\n');
2530
+ throw new Error(`JunoScript diagnostics prevented module initialization:\n${details}`);
2531
+ }
2532
+ return new Interpreter().runModule(source, path);
2533
+ }