Add ECMAScript 5.1 global imports like Math/JSON/Date/Number

This commit is contained in:
bigguy345 committed 2026-03-04 13:21:40 +02:00
1 parent 789c7f5317
commit 60fc7ec252
18 files changed
+1213 -18

No files matched your search

+1
View File
@@ -68,6 +68,7 @@ tasks.named("generateTypeScriptDefinitions").configure {
outputDirectory = "src/main/resources/assets/${project.property("modId")}/api"
apiPackages = ['noppes.npcs.api', 'net.minecraft'] as Set
cleanOutputFirst = true // Clean old generated files before regenerating
patchesDirectory = "dts-patches"
implementationPackages = [
'noppes.npcs.scripted',
'noppes.npcs.controllers.data',
+122
View File
@@ -0,0 +1,122 @@
/**
* ECMAScript 5.1 - Array type for working with ordered collections of elements.
* Supports static methods like Array.isArray() and instance methods like push(), map(), filter().
*
* ## How to Use
*
* ### Creating Arrays
* ```js
* var empty = []; // Empty array
* var nums = [1, 2, 3]; // Array with values
* var mixed = ["hello", 42, true]; // Mixed types
* var nested = [[1, 2], [3, 4]]; // Nested arrays
* ```
*
* ### Static Methods
* ```js
* Array.isArray([1, 2, 3]); // true
* Array.isArray("hello"); // false
* Array.isArray({length: 3}); // false
* ```
*
* ### Adding & Removing Elements
* ```js
* var arr = [1, 2, 3];
* arr.push(4); // [1, 2, 3, 4] — add to end
* arr.pop(); // [1, 2, 3] — remove from end
* arr.unshift(0); // [0, 1, 2, 3] — add to start
* arr.shift(); // [1, 2, 3] — remove from start
* arr.splice(1, 1, 99); // [1, 99, 3] — replace at index 1
* ```
*
* ### Searching & Iterating
* ```js
* var arr = [10, 20, 30, 20];
* arr.indexOf(20); // 1 (first match)
* arr.lastIndexOf(20); // 3 (last match)
* arr.forEach(function(val) { log(val); });
* var doubled = arr.map(function(v) { return v * 2; }); // [20, 40, 60, 40]
* var big = arr.filter(function(v) { return v > 15; }); // [20, 30, 20]
* ```
*
* ### Reducing & Testing
* ```js
* var sum = [1, 2, 3].reduce(function(acc, v) { return acc + v; }, 0); // 6
* var allPositive = [1, 2, 3].every(function(v) { return v > 0; }); // true
* var hasNeg = [1, -2, 3].some(function(v) { return v < 0; }); // true
* ```
*
* ### ❌ Common Mistakes
* ```js
* Array.push(1); // TypeError — push is an instance method
* var a = [3,1,2]; a.sort(); // Sorts as strings! Use compareFn for numbers
* a.sort(function(a, b) { return a - b; }); // Correct numeric sort: [1, 2, 3]
* ```
*/
export interface Array {
/** Returns true if the given object is an array, false otherwise */
isArray(arg: any): boolean;
/** The number of elements in the array */
length: number;
/** Combines two or more arrays and returns a new array without modifying the original */
concat(...items: any[]): any[];
/** Tests whether all elements in the array pass the provided test function */
every(callback: Java.java.util.function.Function<any, boolean>): boolean;
/** Creates a new array with all elements that pass the test implemented by the provided function */
filter(callback: Java.java.util.function.Function<any, boolean>): any[];
/** Executes a provided function once for each array element. Returns undefined */
forEach(callback: Java.java.util.function.Consumer<any>): void;
/** Returns the first index at which an element is found, or -1 if not present */
indexOf(searchElement: any, fromIndex: number): number;
/** Joins all elements of an array into a string separated by the given separator */
join(separator: string): string;
/** Returns the last index at which an element is found, or -1 if not present */
lastIndexOf(searchElement: any, fromIndex: number): number;
/** Creates a new array with the results of calling a function on every element */
map(callback: Java.java.util.function.Function<any, any>): any[];
/** Removes and returns the last element from the array, modifying the original array */
pop(): any;
/** Adds one or more elements to the end of an array and returns the new length */
push(...items: any[]): number;
/** Applies a function against an accumulator and each element to reduce the array to a single value */
reduce(callback: Java.java.util.function.BiFunction<any, any, any>, initialValue: any): any;
/** Same as reduce() but processes the array from right to left */
reduceRight(callback: Java.java.util.function.BiFunction<any, any, any>, initialValue: any): any;
/** Reverses an array in place. The first element becomes the last, and vice versa */
reverse(): any[];
/** Removes and returns the first element from the array, modifying the original array */
shift(): any;
/** Returns a shallow copy of a portion of an array as a new array object */
slice(start: number, end: number): any[];
/** Tests whether at least one element in the array passes the test implemented by the provided function */
some(callback: Java.java.util.function.Function<any, boolean>): boolean;
/** Sorts the elements of an array in place and returns the sorted array */
sort(compareFn: Java.java.util.function.BiFunction<any, any, number>): any[];
/** Changes the contents of an array by removing or replacing existing elements and/or adding new ones */
splice(start: number, deleteCount: number, ...items: any[]): any[];
/** Returns a string representation of the array */
toString(): string;
/** Adds one or more elements to the beginning of an array and returns the new length */
unshift(...items: any[]): number;
}
+36
View File
@@ -0,0 +1,36 @@
/**
* ECMAScript 5.1 - Boolean type for true/false values.
* Booleans are the result of comparison and logical operations.
*
* ## How to Use
*
* ### Creating Booleans
* ```js
* var yes = true; // Boolean literal
* var no = false; // Boolean literal
* var fromExpr = (5 > 3); // true (comparison result)
* ```
*
* ### Boolean Methods
* ```js
* var b = true;
* b.toString(); // "true"
* b.valueOf(); // true (primitive value)
* ```
*
* ### Truthy & Falsy Values
* ```js
* // These are FALSY (evaluate to false):
* // false, 0, "", null, undefined, NaN
*
* // These are TRUTHY (evaluate to true):
* // true, any non-zero number, any non-empty string, objects, arrays
*
*/
export interface Boolean {
/** Returns the string "true" or "false" */
toString(): string;
/** Returns the primitive boolean value */
valueOf(): boolean;
}
+168
View File
@@ -0,0 +1,168 @@
/**
* ECMAScript 5.1 - Date type for working with dates and times.
* Create with `new Date()` or use static methods like Date.now() to get current timestamp.
*
* ## How to Use
*
* ### Creating Dates
* ```js
* var now = new Date(); // Current date & time
* var epoch = new Date(0); // Jan 1, 1970
* var specific = new Date(2024, 0, 15); // Jan 15, 2024 (months are 0-based!)
* var full = new Date(2024, 5, 15, 10, 30, 0); // Jun 15, 2024 10:30:00
* var fromStr = new Date("2024-01-15"); // Parse from ISO string
* ```
*
* ### Static Methods (no `new` needed)
* ```js
* var timestamp = Date.now(); // Current time in milliseconds
* var parsed = Date.parse("2024-01-15"); // Parse string to timestamp
* var utc = Date.UTC(2024, 0, 15); // UTC timestamp for Jan 15, 2024
* ```
*
* ### Common Mistakes
* ```js
* Date.now; // Returns the function, not the timestamp!
* Date.getMinutes(); // TypeError — instance method, not static
* new Date(2024, 1, 1); // Feb 1, not Jan 1 — months are 0-based!
* ```
*/
export interface Date {
/** Returns the current time as the number of milliseconds since 1970-01-01 00:00:00 UTC */
now(): number;
/** Parses a date string and returns the number of milliseconds since 1970-01-01 00:00:00 UTC */
parse(s: string): number;
/** Returns the number of milliseconds since 1970-01-01 00:00:00 UTC for the given UTC date/time components */
UTC(year: number, month: number, date: number, hours: number, minutes: number, seconds: number, ms: number): number;
/** Returns the day of the month (1-31) in local time */
getDate(): number;
/** Returns the day of the week (0=Sunday, 6=Saturday) in local time */
getDay(): number;
/** Returns the year in local time */
getFullYear(): number;
/** Returns the hour (0-23) in local time */
getHours(): number;
/** Returns the milliseconds (0-999) in local time */
getMilliseconds(): number;
/** Returns the minutes (0-59) in local time */
getMinutes(): number;
/** Returns the month (0=January, 11=December) in local time */
getMonth(): number;
/** Returns the seconds (0-59) in local time */
getSeconds(): number;
/** Returns the number of milliseconds since 1970-01-01 00:00:00 UTC */
getTime(): number;
/** Returns the time zone offset in minutes between local time and UTC */
getTimezoneOffset(): number;
/** Returns the day of the month (1-31) in UTC */
getUTCDate(): number;
/** Returns the day of the week (0=Sunday, 6=Saturday) in UTC */
getUTCDay(): number;
/** Returns the year in UTC */
getUTCFullYear(): number;
/** Returns the hour (0-23) in UTC */
getUTCHours(): number;
/** Returns the milliseconds (0-999) in UTC */
getUTCMilliseconds(): number;
/** Returns the minutes (0-59) in UTC */
getUTCMinutes(): number;
/** Returns the month (0=January, 11=December) in UTC */
getUTCMonth(): number;
/** Returns the seconds (0-59) in UTC */
getUTCSeconds(): number;
/** Sets the day of the month and returns the new timestamp */
setDate(date: number): number;
/** Sets the year, and optionally month and date, then returns the new timestamp */
setFullYear(year: number, month: number, date: number): number;
/** Sets the hour, minutes, seconds, and milliseconds, then returns the new timestamp */
setHours(hour: number, min: number, sec: number, ms: number): number;
/** Sets the milliseconds and returns the new timestamp */
setMilliseconds(ms: number): number;
/** Sets the minutes, seconds, and milliseconds, then returns the new timestamp */
setMinutes(min: number, sec: number, ms: number): number;
/** Sets the month, and optionally date, then returns the new timestamp */
setMonth(month: number, date: number): number;
/** Sets the seconds and milliseconds, then returns the new timestamp */
setSeconds(sec: number, ms: number): number;
/** Sets the timestamp (milliseconds since epoch) and returns it */
setTime(time: number): number;
/** Sets the day of the month (UTC) and returns the new timestamp */
setUTCDate(date: number): number;
/** Sets the year, month, and date (UTC), then returns the new timestamp */
setUTCFullYear(year: number, month: number, date: number): number;
/** Sets the hour, minutes, seconds, and milliseconds (UTC), then returns the new timestamp */
setUTCHours(hour: number, min: number, sec: number, ms: number): number;
/** Sets the milliseconds (UTC) and returns the new timestamp */
setUTCMilliseconds(ms: number): number;
/** Sets the minutes, seconds, and milliseconds (UTC), then returns the new timestamp */
setUTCMinutes(min: number, sec: number, ms: number): number;
/** Sets the month and date (UTC), then returns the new timestamp */
setUTCMonth(month: number, date: number): number;
/** Sets the seconds and milliseconds (UTC), then returns the new timestamp */
setUTCSeconds(sec: number, ms: number): number;
/** Returns a string representation of the date portion in local time (e.g., "Mon Jan 01 2024") */
toDateString(): string;
/** Returns the date as an ISO 8601 string (e.g., "2024-01-01T00:00:00.000Z") */
toISOString(): string;
/** Returns a JSON representation of the date (typically an ISO 8601 string) */
toJSON(key: any): string;
/** Returns a localized string for the date portion (format depends on locale) */
toLocaleDateString(): string;
/** Returns a localized string for the entire date and time (format depends on locale) */
toLocaleString(): string;
/** Returns a localized string for the time portion (format depends on locale) */
toLocaleTimeString(): string;
/** Returns a string representation of the date and time in local time */
toString(): string;
/** Returns a string representation of the time portion in local time (e.g., "00:00:00 GMT+0000") */
toTimeString(): string;
/** Returns a string representation of the date and time in UTC (e.g., "Mon, 01 Jan 2024 00:00:00 GMT") */
toUTCString(): string;
/** Returns the primitive value of the date object (milliseconds since 1970-01-01 00:00:00 UTC) */
valueOf(): number;
}
+81
View File
@@ -0,0 +1,81 @@
/**
* ECMAScript 5.1 - Error base type for runtime errors.
* Throw Error objects to indicate failure conditions in your code.
*
* ## How to Use
*
* ### Creating & Throwing Errors
* ```js
* throw new Error("Something went wrong");
* throw new TypeError("Expected a string");
* throw new RangeError("Value out of range");
* ```
*
* ### Catching Errors
* ```js
* try {
* var result = riskyOperation();
* } catch (e) {
* log(e.name); // "Error", "TypeError", etc.
* log(e.message); // "Something went wrong"
* log(e.toString()); // "Error: Something went wrong"
* }
* ```
*
* ### Custom Error Messages
* ```js
* function divide(a, b) {
* if (b === 0) {
* throw new Error("Cannot divide by zero");
* }
* return a / b;
* }
* ```
*
* ### ❌ Common Mistakes
* ```js
* throw "Something went wrong"; // Works but no .name or .message properties
* Error("oops"); // Creates error but doesn't throw it!
* throw Error("oops"); // ✅ Works (with or without `new`)
* ```
*/
export interface Error {
/** The name of the error type (e.g., "Error", "TypeError", "RangeError") */
name: string;
/** A human-readable description of what went wrong */
message: string;
/** Returns a string representation of the error (typically "name: message") */
toString(): string;
}
/**
* EvalError - Thrown when eval() function is misused (rarely used in modern JavaScript)
*/
export interface EvalError extends Error {}
/**
* RangeError - Thrown when a numeric value is out of the acceptable range (e.g., array length < 0)
*/
export interface RangeError extends Error {}
/**
* ReferenceError - Thrown when trying to reference a variable that does not exist or is not in scope
*/
export interface ReferenceError extends Error {}
/**
* SyntaxError - Thrown when parsing invalid syntax (usually caught during compile/parse, not runtime)
*/
export interface SyntaxError extends Error {}
/**
* TypeError - Thrown when an operation is performed on a value of the wrong type (e.g., calling a non-function)
*/
export interface TypeError extends Error {}
/**
* URIError - Thrown by URI encoding/decoding functions when given invalid characters or sequences
*/
export interface URIError extends Error {}
+72
View File
@@ -0,0 +1,72 @@
/**
* ECMAScript 5.1 - Global functions available in the global scope.
* These are not on any specific object - call them directly (e.g., parseInt("42")).
*
* ## How to Use
*
* ### Parsing Numbers
* ```js
* parseInt("42"); // 42
* parseInt("42px"); // 42 (stops at non-digit)
* parseInt("0xFF", 16); // 255 (hexadecimal)
* parseInt("111", 2); // 7 (binary)
* parseFloat("3.14"); // 3.14
* parseFloat("3.14abc"); // 3.14 (stops at invalid char)
* ```
*
* ### Checking Special Values
* ```js
* isNaN(NaN); // true
* isNaN(42); // false
* isNaN("hello"); // true (cannot parse as number)
* isNaN("42"); // false (can parse as number)
* isFinite(42); // true
* isFinite(Infinity); // false
* isFinite(NaN); // false
* ```
*
* ### URI Encoding/Decoding
* ```js
* encodeURI("hello world"); // "hello%20world"
* decodeURI("hello%20world"); // "hello world"
* encodeURIComponent("a=1&b=2"); // "a%3D1%26b%3D2" (encodes & and =)
* decodeURIComponent("a%3D1%26b%3D2"); // "a=1&b=2"
* ```
*
* ### ❌ Common Mistakes
* ```js
* parseInt("08"); // Some engines treat as octal! Always specify radix
* parseInt("08", 10); // 8 ✅ — explicitly base-10
* parseInt(""); // NaN — empty string returns NaN, not 0
* parseFloat(""); // NaN
* isNaN(undefined); // true — coerces to NaN first
* ```
*/
export interface GlobalFunctions {
/** Evaluates JavaScript code in a string (use with caution - slow and potential security issues) */
eval(x: any): any;
/** Parses a string and returns an integer. Stops parsing at the first non-digit character */
parseInt(string: string, radix: number): number;
/** Parses a string and returns a floating-point number. Stops parsing at the first invalid character */
parseFloat(string: string): number;
/** Determines whether a value is NaN (not-a-number). Returns true for NaN, false for numbers and non-numeric values */
isNaN(number: number): boolean;
/** Determines whether a value is a finite number. Returns false for infinity, -infinity, and NaN */
isFinite(number: number): boolean;
/** Decodes a URI by replacing encoded sequences like %20 with their original characters */
decodeURI(encodedURI: string): string;
/** Decodes URI component by replacing ALL encoded sequences including those for reserved URI characters */
decodeURIComponent(encodedURIComponent: string): string;
/** Encodes a URI by replacing special characters with %HH sequences (but preserves reserved characters like / : ?) */
encodeURI(uri: string): string;
/** Encodes URI component by replacing ALL special characters including reserved ones with %HH sequences */
encodeURIComponent(uriComponent: string): string;
}
+100
View File
@@ -0,0 +1,100 @@
/**
* ECMAScript 5.1 - JSON built-in object for parsing and serializing JSON data.
*
* ## How to Use
*
* JSON is a **static object** — use its methods directly, never with `new`.
*
* ### Parsing JSON Strings to Objects
* ```js
* var obj = JSON.parse('{"name": "Steve", "level": 5}');
* log(obj.name); // "Steve"
* log(obj.level); // 5
*
* var arr = JSON.parse('[1, 2, 3]');
* log(arr[0]); // 1
* ```
*
* ### Converting Objects to JSON Strings
* ```js
* var data = { name: "Steve", hp: 100 };
* var json = JSON.stringify(data); // '{"name":"Steve","hp":100}'
*
* // Pretty-printed with 2-space indent:
* var pretty = JSON.stringify(data, null, 2);
* // '{
* // "name": "Steve",
* // "hp": 100
* // }'
* ```
*
* ### Storing & Loading Data
* ```js
* // Save to NPC stored data:
* var inventory = { sword: 1, potion: 5 };
* npc.getStoredData().put("inv", JSON.stringify(inventory));
*
* // Load from NPC stored data:
* var raw = npc.getStoredData().get("inv");
* var loaded = JSON.parse(raw);
* log(loaded.potion); // 5
* ```
*
* ### ❌ Common Mistakes
* ```js
* new JSON(); // TypeError — JSON is not a constructor
* JSON.parse('{name: "Steve"}'); // SyntaxError — keys must be quoted
* JSON.parse("{'name': 'Steve'}"); // SyntaxError — must use double quotes
* JSON.parse('{"name": "Steve"}'); // ✅ Correct — double-quoted keys & values
* ```
*/
export interface JSON {
/**
* Parses a JSON string and returns the parsed value (object, array, string, number, boolean, or null).
* @param text - A valid JSON string to parse
* @returns The parsed JavaScript value
*/
parse(text: string): any;
/**
* Parses a JSON string with a reviver function that transforms each parsed key-value pair.
* @param text - A valid JSON string to parse
* @param reviver - Function called for each key-value pair; receives the key and parsed value, returns the transformed value
* @returns The parsed JavaScript value after applying the reviver
*/
parse(text: string, reviver: Java.java.util.function.BiFunction<string, any, any>): any;
/**
* Converts a JavaScript value to a JSON string.
* @param value - The value to serialize (object, array, string, number, boolean, or null)
* @returns A JSON-formatted string representation of the value
*/
stringify(value: any): string;
/**
* Converts a JavaScript value to a JSON string, using a replacer function to filter or transform properties.
* @param value - The value to serialize
* @param replacer - Function called for each key-value pair; receives the key and value, returns the value to include (or undefined to omit)
* @param space - Optional indentation: a number of spaces (up to 10), or a string prefix per level
* @returns A JSON-formatted string representation of the value
*/
stringify(value: any, replacer: Java.java.util.function.BiFunction<string, any, any>, space?: any): string;
/**
* Converts a JavaScript value to a JSON string, including only the specified properties.
* @param value - The value to serialize
* @param replacer - Array of property names to include in the output
* @param space - Optional indentation: a number of spaces (up to 10), or a string prefix per level
* @returns A JSON-formatted string representation of the value
*/
stringify(value: any, replacer: string[], space?: any): string;
/**
* Converts a JavaScript value to a JSON string with optional pretty-printing.
* @param value - The value to serialize
* @param replacer - Pass null to include all properties
* @param space - Indentation: a number of spaces (up to 10), or a string prefix per level
* @returns A JSON-formatted string representation of the value
*/
stringify(value: any, replacer: null, space: any): string;
}
+128
View File
@@ -0,0 +1,128 @@
/**
* ECMAScript 5.1 - Math built-in object providing mathematical constants and functions.
* All methods are static and called as Math.methodName(). No constructor.
*
* ## How to Use
*
* Math is a **static object** — use its methods directly, never with `new`.
*
* ### Basic Math Operations
* ```js
* var rounded = Math.floor(3.7); // 3
* var ceiling = Math.ceil(3.2); // 4
* var nearest = Math.round(3.5); // 4
* var absolute = Math.abs(-42); // 42
* ```
*
* ### Powers, Roots & Logarithms
* ```js
* var squared = Math.pow(2, 3); // 8
* var root = Math.sqrt(16); // 4
* var natural = Math.log(Math.E); // 1
* ```
*
* ### Random Numbers
* ```js
* var rand = Math.random(); // 0.0 to 0.999...
* // Random integer between 1 and 10:
* var dice = Math.floor(Math.random() * 10) + 1;
* ```
*
* ### Finding Min/Max
* ```js
* var biggest = Math.max(5, 10, 3); // 10
* var smallest = Math.min(5, 10, 3); // 3
* ```
*
* ### Trigonometry
* ```js
* var sine = Math.sin(Math.PI / 2); // 1
* var cosine = Math.cos(0); // 1
* var angle = Math.atan2(1, 1); // 0.785... (PI/4)
* ```
*
* ### ❌ Common Mistakes
* ```js
* new Math() // TypeError — Math is not a constructor
* Math() // TypeError — Math is not a function
* ```
*/
export interface Math {
/** Euler's number (~2.718), the base of natural logarithms */
E: number;
/** Natural logarithm of 2 (~0.693) */
LN2: number;
/** Natural logarithm of 10 (~2.303) */
LN10: number;
/** Base-2 logarithm of e (~1.443) */
LOG2E: number;
/** Base-10 logarithm of e (~0.434) */
LOG10E: number;
/** Ratio of a circle's circumference to its diameter (~3.14159) */
PI: number;
/** Square root of 0.5 (~0.707) */
SQRT1_2: number;
/** Square root of 2 (~1.414) */
SQRT2: number;
/** Returns the absolute value of a number */
abs(x: number): number;
/** Returns the arccosine (in radians) of a number */
acos(x: number): number;
/** Returns the arcsine (in radians) of a number */
asin(x: number): number;
/** Returns the arctangent (in radians) of a number */
atan(x: number): number;
/** Returns the arctangent of two numbers (y/x), with proper quadrant handling */
atan2(y: number, x: number): number;
/** Returns the smallest integer greater than or equal to a number */
ceil(x: number): number;
/** Returns the cosine (in radians) of a number */
cos(x: number): number;
/** Returns e raised to the power of a number */
exp(x: number): number;
/** Returns the largest integer less than or equal to a number */
floor(x: number): number;
/** Returns the natural logarithm (base e) of a number */
log(x: number): number;
/** Returns the largest of zero or more numbers */
max(...values: number[]): number;
/** Returns the smallest of zero or more numbers */
min(...values: number[]): number;
/** Returns base raised to the power of exponent */
pow(x: number, y: number): number;
/** Returns a random number between 0 (inclusive) and 1 (exclusive) */
random(): number;
/** Returns the value of a number rounded to the nearest integer */
round(x: number): number;
/** Returns the sine (in radians) of a number */
sin(x: number): number;
/** Returns the square root of a number */
sqrt(x: number): number;
/** Returns the tangent (in radians) of a number */
tan(x: number): number;
}
+74
View File
@@ -0,0 +1,74 @@
/**
* ECMAScript 5.1 - Number type for working with numeric values and constants.
* Access static constants like Number.MAX_VALUE or format numbers with instance methods.
*
* ## How to Use
*
* ### Number Constants
* ```js
* Number.MAX_VALUE; // ~1.79e+308 (largest representable number)
* Number.MIN_VALUE; // ~5e-324 (smallest positive number)
* Number.NaN; // NaN
* Number.POSITIVE_INFINITY; // Infinity
* Number.NEGATIVE_INFINITY; // -Infinity
* ```
*
* ### Formatting Numbers
* ```js
* var n = 3.14159;
* n.toFixed(2); // "3.14" (fixed decimal places)
* n.toFixed(0); // "3"
* n.toPrecision(4); // "3.142" (significant digits)
* n.toExponential(2); // "3.14e+0" (scientific notation)
* ```
*
* ### Converting to String
* ```js
* var n = 255;
* n.toString(); // "255" (base 10, default)
* n.toString(16); // "ff" (hexadecimal)
* n.toString(2); // "11111111" (binary)
* n.toString(8); // "377" (octal)
* ```
*
* ### ❌ Common Mistakes
* ```js
* Number.toFixed(2); // TypeError — instance method, not static
* (3).toFixed(2); // "3.00" ✅ — wrap literal in parentheses
* 3.toFixed(2); // SyntaxError — parser reads 3. as float
* ```
*/
export interface Number {
/** The largest representable number (~1.79e+308) */
MAX_VALUE: number;
/** The smallest representable positive number (~5e-324) */
MIN_VALUE: number;
/** Represents "Not a Number" (NaN) - the result of undefined or invalid arithmetic operations */
NaN: number;
/** Represents negative infinity, the result of overflow or division by zero */
NEGATIVE_INFINITY: number;
/** Represents positive infinity, the result of overflow or division by zero */
POSITIVE_INFINITY: number;
/** Formats the number using exponential notation with optional fractional digits */
toExponential(fractionDigits: number): string;
/** Formats the number as a fixed-point string with the specified number of fractional digits (0-20) */
toFixed(fractionDigits: number): string;
/** Returns a localized string representation of the number (format depends on locale) */
toLocaleString(): string;
/** Formats the number as a string with the specified number of significant digits (1-21) */
toPrecision(precision: number): string;
/** Converts the number to a string in the specified radix (base 2-36, default 10) */
toString(radix: number): string;
/** Returns the primitive numeric value of this Number object */
valueOf(): number;
}
+110
View File
@@ -0,0 +1,110 @@
/**
* ECMAScript 5.1 - Object type, the base type for all JavaScript objects.
* Use static methods like Object.keys() and Object.create() to manipulate object structure.
*
* ## How to Use
*
* ### Creating Objects
* ```js
* var obj = {}; // Empty object literal
* var person = { name: "Steve", age: 20 }; // Object with properties
* var child = Object.create(person); // Create with prototype
* ```
*
* ### Inspecting Objects
* ```js
* var obj = { a: 1, b: 2, c: 3 };
* Object.keys(obj); // ["a", "b", "c"]
* Object.getOwnPropertyNames(obj); // ["a", "b", "c"] (includes non-enumerable)
* obj.hasOwnProperty("a"); // true
* obj.hasOwnProperty("toString"); // false (inherited, not own)
* ```
*
* ### Freezing & Sealing
* ```js
* var config = { debug: false };
* Object.freeze(config); // Cannot modify, add, or delete properties
* config.debug = true; // Silently fails (or throws in strict mode)
* Object.isFrozen(config); // true
*
* var settings = { volume: 50 };
* Object.seal(settings); // Can modify values, but cannot add/delete
* settings.volume = 75; // ✅ Works
* settings.newProp = true; // Silently fails
* ```
*
* ### Property Descriptors
* ```js
* var obj = {};
* Object.defineProperty(obj, "id", {
* value: 42,
* writable: false, // Cannot be changed
* enumerable: true // Shows up in for-in / Object.keys
* });
* ```
*
* ### ❌ Common Mistakes
* ```js
* Object.keys(); // TypeError — needs an argument
* obj.keys(); // TypeError — keys is a static method
* Object.hasOwnProperty("a"); // Wrong — instance method on the object
* ```
*/
export interface Object {
/** Creates a new object with the specified prototype and optional property descriptors */
create(proto: any, propertiesObject: any): any;
/** Defines or modifies multiple properties on an object and returns the modified object */
defineProperties(obj: any, props: any): any;
/** Defines a new property on an object or modifies an existing property and returns the object */
defineProperty(obj: any, prop: string, descriptor: any): any;
/** Prevents all modifications to an object (cannot add, modify, or delete properties) */
freeze(obj: any): any;
/** Returns a property descriptor for a named property on an object, or undefined if not found */
getOwnPropertyDescriptor(obj: any, prop: string): any;
/** Returns an array of all property names (both enumerable and non-enumerable) on an object */
getOwnPropertyNames(obj: any): string[];
/** Returns the prototype object of the specified object */
getPrototypeOf(obj: any): any;
/** Determines whether an object is extensible (can have new properties added to it) */
isExtensible(obj: any): boolean;
/** Determines whether an object has been frozen (is immutable) */
isFrozen(obj: any): boolean;
/** Determines whether an object is sealed (cannot add or delete properties) */
isSealed(obj: any): boolean;
/** Returns an array of all enumerable property names on an object */
keys(obj: any): string[];
/** Prevents new properties from being added to an object but allows modification of existing ones */
preventExtensions(obj: any): any;
/** Prevents all modifications to an object except for reading and writing property values */
seal(obj: any): any;
/** Determines whether an object has a property with the specified name (direct property, not inherited) */
hasOwnProperty(prop: string): boolean;
/** Determines whether an object is in the prototype chain of another object */
isPrototypeOf(obj: any): boolean;
/** Determines whether an object property is enumerable (would be included in a for-in loop) */
propertyIsEnumerable(prop: string): boolean;
/** Returns a localized string representation of the object (format depends on locale) */
toLocaleString(): string;
/** Returns a string representation of the object, usually "[object Object]" unless overridden */
toString(): string;
/** Returns the primitive value of the object (usually the object itself unless overridden) */
valueOf(): any;
}
+94
View File
@@ -0,0 +1,94 @@
/**
* ECMAScript 5.1 - RegExp type for pattern matching and string manipulation.
* Create with the RegExp constructor or literal syntax: /pattern/flags
*
* ## How to Use
*
* ### Creating Regular Expressions
* ```js
* // Method 1: Regex literal (preferred)
* var re = /hello/;
* var reFlags = /hello/gi; // g=global, i=ignore case, m=multiline
*
* // Method 2: Constructor (useful for dynamic patterns)
* var re2 = new RegExp("hello");
* var re3 = new RegExp("hello", "gi");
* var dynamic = new RegExp(playerName); // Build pattern from variable
* ```
*
* ### Testing for Matches
* ```js
* /\d+/.test("abc123"); // true — contains digits
* /^\d+$/.test("abc123"); // false — not ALL digits
* /^\d+$/.test("12345"); // true — all digits
* /hello/i.test("Hello World"); // true — case insensitive
* ```
*
* ### Extracting Matches
* ```js
* var match = /\d+/.exec("abc123def"); // ["123"]
* var noMatch = /\d+/.exec("no digits"); // null
*
* // With capturing groups
* var result = /(\w+)@(\w+)/.exec("user@domain");
* // result[0] = "user@domain" (full match)
* // result[1] = "user" (first group)
* // result[2] = "domain" (second group)
* ```
*
* ### Using with String Methods
* ```js
* "abc123".match(/\d+/); // ["123"]
* "abc123".search(/\d/); // 3 (index of first digit)
* "abc123".replace(/\d+/, "NUM"); // "abcNUMdef"
* "a,b,,c".split(/,+/); // ["a", "b", "c"]
* ```
*
* ### RegExp Properties
* ```js
* var re = /hello/gi;
* re.source; // "hello"
* re.global; // true
* re.ignoreCase; // true
* re.multiline; // false
* re.lastIndex; // 0 (changes with global exec/test)
* ```
*
* ### ❌ Common Mistakes
* ```js
* RegExp.test("string"); // TypeError — test is an INSTANCE method!
* new RegExp.test("string"); // TypeError — incorrect syntax
* // ✅ CORRECT:
* /pattern/.test("string"); // Use on a regex instance
* new RegExp("pattern").test("string"); // Or create instance first
*
* // Double-escape backslashes in constructor strings:
* new RegExp("\d+"); // Wrong — \d becomes just d
* new RegExp("\\d+"); // ✅ Correct — \\d becomes \d
* ```
*/
export interface RegExp {
/** The pattern string that was used to create this regular expression */
source: string;
/** True if the 'g' (global) flag is set, affecting match behavior in exec() and test() */
global: boolean;
/** True if the 'i' (ignore case) flag is set, making pattern matching case-insensitive */
ignoreCase: boolean;
/** True if the 'm' (multiline) flag is set, affecting ^ and $ anchor behavior */
multiline: boolean;
/** The index at which to start searching in the string (used with 'g' flag in exec() loops) */
lastIndex: number;
/** Searches the string for a match and returns an array of matches or null if no match found */
exec(string: string): any[];
/** Tests whether the pattern matches the string, returning true or false */
test(string: string): boolean;
/** Returns a string representation of the regular expression (e.g., "/pattern/flags") */
toString(): string;
}
+123
View File
@@ -0,0 +1,123 @@
/**
* ECMAScript 5.1 - String type for working with text. Strings are immutable sequences of characters.
* Use String.fromCharCode() to create a string from character codes.
*
* ## How to Use
*
* ### Creating Strings
* ```js
* var greeting = "Hello, world!"; // String literal (double quotes)
* var name = 'Steve'; // String literal (single quotes)
* var fromCode = String.fromCharCode(65); // "A" (from char code)
* ```
*
* ### Searching & Checking
* ```js
* var str = "Hello, world!";
* str.indexOf("world"); // 7
* str.indexOf("missing"); // -1 (not found)
* str.lastIndexOf("l"); // 10
* str.search(/world/); // 7 (regex search)
* str.charAt(0); // "H"
* str.charCodeAt(0); // 72
* str.length; // 13
* ```
*
* ### Extracting & Transforming
* ```js
* var str = "Hello, world!";
* str.slice(7, 12); // "world"
* str.substring(0, 5); // "Hello"
* str.toUpperCase(); // "HELLO, WORLD!"
* str.toLowerCase(); // "hello, world!"
* str.trim(); // Removes leading/trailing whitespace
* str.replace("world", "NPC"); // "Hello, NPC!"
* str.replace(/l/g, "L"); // "HeLLo, worLd!" (regex with global flag)
* ```
*
* ### Splitting & Joining
* ```js
* "a,b,c".split(","); // ["a", "b", "c"]
* "hello".split(""); // ["h", "e", "l", "l", "o"]
* ["a", "b", "c"].join("-"); // "a-b-c" (Array.join, but related)
* "one two three".split(" ", 2); // ["one", "two"] (limit results)
* ```
*
* ### Pattern Matching
* ```js
* "abc123".match(/\d+/); // ["123"]
* "no numbers".match(/\d+/); // null
* "hello".concat(" ", "world"); // "hello world"
* ```
*
* ### ❌ Common Mistakes
* ```js
* str.replace("l", "L"); // Only replaces FIRST "l" — use /l/g for all
* String.charAt(0); // TypeError — instance method, not static
* "abc"[0]; // May not work in all engines — use charAt()
* ```
*/
export interface String {
/** Creates a string from one or more Unicode character codes (e.g., String.fromCharCode(65, 66, 67) returns "ABC") */
fromCharCode(...codes: number[]): string;
/** The number of characters in the string */
length: number;
/** Returns the character at the specified index, or an empty string if the index is out of range */
charAt(pos: number): string;
/** Returns the Unicode code point (0-65535) of the character at the specified index */
charCodeAt(pos: number): number;
/** Combines this string with other strings and returns a new combined string */
concat(...strings: string[]): string;
/** Returns the index of the first occurrence of the search string, or -1 if not found */
indexOf(searchString: string, position: number): number;
/** Returns the index of the last occurrence of the search string, or -1 if not found */
lastIndexOf(searchString: string, position: number): number;
/** Compares this string to another string and returns a number indicating sort order (-1, 0, or 1) */
localeCompare(that: string): number;
/** Tests the string against a regular expression and returns an array of matches or null if no match */
match(regexp: any): any[];
/** Replaces the first occurrence of a pattern (string or regex) with a replacement string or the result of a function */
replace(searchValue: any, replaceValue: any): string;
/** Returns the index of the first character that matches a regular expression, or -1 if not found */
search(regexp: any): number;
/** Returns a new string containing the characters from the start index up to (but not including) the end index */
slice(start: number, end: number): string;
/** Splits the string into an array of substrings using the separator, optionally limiting the number of splits */
split(separator: any, limit: number): string[];
/** Returns a new string containing characters from the start index up to (but not including) the end index */
substring(start: number, end: number): string;
/** Returns a new string with all uppercase characters converted to lowercase */
toLowerCase(): string;
/** Returns a new string with all uppercase characters converted to lowercase according to locale rules */
toLocaleLowerCase(): string;
/** Returns a new string with all lowercase characters converted to uppercase */
toUpperCase(): string;
/** Returns a new string with all lowercase characters converted to uppercase according to locale rules */
toLocaleUpperCase(): string;
/** Returns a new string with whitespace (spaces, tabs, newlines, etc.) removed from both ends */
trim(): string;
/** Returns the string itself */
toString(): string;
/** Returns the primitive value of the string object */
valueOf(): string;
}
@@ -217,6 +217,14 @@ public class JSAutocompleteProvider extends JavaAutocompleteProvider {
items.add(AutocompleteItem.fromField(fieldInfo));
}
// Add global imports in JSTypeRegistry.globalEngineImports
for (String importName : registry.getGlobalEngineImports().keySet()) {
TypeInfo jsTypeInfo = document.resolveType(registry.getGlobalImportType(importName));
if (jsTypeInfo != null) {
items.add(AutocompleteItem.fromType(jsTypeInfo));
}
}
}
protected UsageTracker getUsageTracker() {
@@ -7134,13 +7134,22 @@ public class ScriptDocument {
continue;
// For JavaScript, first check synthetic types (Nashorn built-ins like Java, print, etc.)
if (isJavaScript() && typeResolver.isSyntheticType(className)) {
SyntheticType syntheticType = typeResolver.getSyntheticType(className);
// Mark as IMPORTED_CLASS since it's a type reference
// Pass the TypeInfo (which the hover system can display)
marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.IMPORTED_CLASS,
syntheticType.getTypeInfo()));
continue;
if (isJavaScript()) {
if (typeResolver.isSyntheticType(className)) {
SyntheticType syntheticType = typeResolver.getSyntheticType(className);
// Mark as IMPORTED_CLASS since it's a type reference
// Pass the TypeInfo (which the hover system can display)
marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.IMPORTED_CLASS,
syntheticType.getTypeInfo()));
continue;
}
JSTypeRegistry jsRegistry = JSTypeRegistry.getInstance();
if (jsRegistry.isGlobalImport(className)) {
// Mark as IMPORTED_CLASS since it's a type reference
TypeInfo globalType = typeResolver.resolveJSType(jsRegistry.getGlobalImportType(className));
marks.add(new ScriptLine.Mark(m.start(1), m.end(1), TokenType.INTERFACE_DECL, globalType));
continue;
}
}
// Try to resolve the class
@@ -52,6 +52,8 @@ public class JSTypeRegistry {
// Global object instances: name -> type (e.g., "API" -> "AbstractNpcAPI")
// These are treated as instance objects, not static classes
private final Map<String, String> globalEngineObjects = new LinkedHashMap<>();
// Math / Number / Json / etc. built-in globals from ECMAScript 5.1
private final Map<String, String> globalEngineImports = new LinkedHashMap<>();
// Primitive types
private static final Set<String> PRIMITIVES = new HashSet<>(Arrays.asList(
@@ -119,6 +121,7 @@ public class JSTypeRegistry {
resolveInheritance();
registerEngineGlobalObjects();
registerES5Builtins();
initialized = true;
System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks from resources");
@@ -449,6 +452,13 @@ public class JSTypeRegistry {
return getType(resolved, visited);
}
if (globalEngineImports.containsKey(baseName)){
String resolved = globalEngineImports.get(baseName);
if (types.containsKey(resolved)) {
return types.get(resolved);
}
}
// Try simple name lookup (for types like "IEntity" without namespace)
for (JSTypeInfo type : types.values()) {
if (type.getSimpleName().equals(baseName)) {
@@ -824,7 +834,64 @@ public class JSTypeRegistry {
// Default: return the original name
return concreteClassName;
}
/**
* Register ECMAScript 5.1 global built-in objects so that expressions like
* `Math.floor(Math.random())`, `new Date()`, `Array.isArray(...)`, etc.
* resolve properly with type checking and autocomplete.
*
* These globals are parsed from .d.ts patch files under `patches/ecmascript/`
* and provide both static methods (e.g., Math.floor, Array.isArray, Object.keys)
* and instance members (e.g., date.getTime(), array.length, string.charAt).
*/
private void registerES5Builtins() {
// Singleton/namespace globals (accessed directly, not constructed)
registerGlobalIfTypeExists("Math", "Math");
registerGlobalIfTypeExists("JSON", "JSON");
// Constructor globals (can be called with `new` or used for static methods)
registerGlobalIfTypeExists("Date", "Date");
registerGlobalIfTypeExists("Array", "Array");
registerGlobalIfTypeExists("Object", "Object");
registerGlobalIfTypeExists("String", "String");
registerGlobalIfTypeExists("Number", "Number");
registerGlobalIfTypeExists("Boolean", "Boolean");
registerGlobalIfTypeExists("RegExp", "RegExp");
registerGlobalIfTypeExists("Error", "Error");
}
/**
* Registers a global object only if the target type is present in the registry.
* Silently skips if the .d.ts patch hasn't been loaded yet (e.g. in unit tests).
*/
private void registerGlobalIfTypeExists(String globalName, String typeName) {
if (types.containsKey(typeName)) {
globalEngineImports.put(globalName, typeName);
}
}
/**
* Get the type name for a global object.
* @param name The global variable name
* @return The type name, or null if not a registered global object
*/
public String getGlobalImportType(String name) {
return globalEngineImports.get(name);
}
/**
* Check if a name is a registered global object instance.
*/
public boolean isGlobalImport(String name) {
return globalEngineImports.containsKey(name);
}
/**
* Get all registered global objects.
*/
public Map<String, String> getGlobalEngineImports() {
return Collections.unmodifiableMap(globalEngineImports);
}
/**
* Check if initialized.
*/
@@ -844,6 +911,7 @@ public class JSTypeRegistry {
hooks.clear();
contextHooks.clear();
globalEngineObjects.clear();
globalEngineImports.clear();
DtsJavaBridge.clearCache();
initialized = false;
initializationAttempted = false;
@@ -41,10 +41,10 @@ public class TypeScriptDefinitionParser {
"export\\s+type\\s+(\\w+)\\s*=\\s*([^;\\n]+);?");
private static final Pattern METHOD_PATTERN = Pattern.compile(
"(?m)^\\s*(\\w+)\\s*\\((.*)\\)\\s*:\\s*([^;]+);", Pattern.MULTILINE);
"(?m)^\\s*(\\w+)\\??\\s*\\((.*)\\)\\s*:\\s*([^;]+);", Pattern.MULTILINE);
private static final Pattern FIELD_PATTERN = Pattern.compile(
"^\\s*(readonly\\s+)?(\\w+)\\s*:\\s*([^;]+);", Pattern.MULTILINE);
"^\\s*(readonly\\s+)?(\\w+)\\??\\s*:\\s*([^;]+);", Pattern.MULTILINE);
private static final Pattern GLOBAL_FUNCTION_PATTERN = Pattern.compile(
"function\\s+(\\w+)\\s*\\((.*)\\)\\s*:\\s*([^;]+);");
@@ -413,6 +413,13 @@ public class TypeResolver {
SyntheticType syntheticType = getSyntheticType(baseName);
return syntheticType.getTypeInfo();
}
// Check JS type registry
// Before primitive mapping, to allow .d.ts types to override primitive names for ECMAScript 5.1 globals (e.g., "String" in JS is not the same as "String" in Java))
JSTypeInfo jsTypeInfo = getJSTypeRegistry().getType(baseName);
if (jsTypeInfo != null) {
return TypeInfo.fromJSTypeInfo(jsTypeInfo);
}
// Check primitives and common types
switch (baseName.toLowerCase()) {
@@ -433,12 +440,6 @@ public class TypeResolver {
return TypeInfo.ANY;
}
// Check JS type registry
JSTypeInfo jsTypeInfo = getJSTypeRegistry().getType(baseName);
if (jsTypeInfo != null) {
return TypeInfo.fromJSTypeInfo(jsTypeInfo);
}
// Fall back to Java type resolution
TypeInfo javaType = resolveFullName(baseName);
if (javaType != null && javaType.isResolved()) {
@@ -898,7 +899,7 @@ public class TypeResolver {
// Not a variable - check if it's a type name by trying to resolve as type
TypeInfo typeCheck = document.resolveType(identifier);
boolean isType = typeCheck != null && typeCheck.isResolved();
boolean isType = typeCheck != null && typeCheck.isResolved() && !typeCheck.isJSType(); // JS types aren't static access in this context
return isStaticAccess(typeCheck, isType);
}