-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhermes-globals.js
More file actions
203 lines (188 loc) · 5.96 KB
/
Copy pathhermes-globals.js
File metadata and controls
203 lines (188 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Hermes globals to provide Node.js-like environment
// Helper function to format console arguments
function formatConsoleArgs(...args) {
return args
.map((arg) => {
if (arg === null) return "null";
if (arg === undefined) return "undefined";
if (typeof arg === "string") return arg;
if (typeof arg === "number" || typeof arg === "boolean")
return String(arg);
if (typeof arg === "function")
return `[Function: ${arg.name || "anonymous"}]`;
if (typeof arg === "object") {
try {
// Handle circular references and format objects nicely
return JSON.stringify(arg, null, 2);
} catch (e) {
// Fallback for circular references
return "[object Object]";
}
}
return String(arg);
})
.join(" ");
}
globalThis.console = {
log: function (...args) {
print(formatConsoleArgs(...args));
},
error: function (...args) {
print("ERROR: " + formatConsoleArgs(...args));
},
warn: function (...args) {
print("WARN: " + formatConsoleArgs(...args));
},
time: function (label) {
if (!globalThis._timers) {
globalThis._timers = new Map();
}
globalThis._timers.set(label || "default", Date.now());
},
timeEnd: function (label) {
if (!globalThis._timers) {
globalThis._timers = new Map();
}
const key = label || "default";
const startTime = globalThis._timers.get(key);
if (startTime !== undefined) {
const duration = Date.now() - startTime;
print(`${key}: ${duration}ms`);
globalThis._timers.delete(key);
} else {
print(`Timer '${key}' does not exist`);
}
},
timeLog: function (label, ...data) {
if (!globalThis._timers) {
globalThis._timers = new Map();
}
const key = label || "default";
const startTime = globalThis._timers.get(key);
if (startTime !== undefined) {
const duration = Date.now() - startTime;
const message = data.length > 0 ? ` ${data.join(" ")}` : "";
print(`${key}: ${duration}ms${message}`);
} else {
print(`Timer '${key}' does not exist`);
}
},
};
// Basic process object
globalThis.process = {
argv: ["hermes", "script.js"], // Will be updated by the runner
env: {},
exit: function (code) {
throw new Error("Process exit: " + (code || 0));
},
};
// Polyfill for setInterval using setTimeout
globalThis._intervals = new Map();
globalThis._intervalId = 1;
globalThis.setInterval = function (callback, delay, ...args) {
const id = globalThis._intervalId++;
let active = true;
function repeat() {
if (active) {
try {
callback(...args);
} catch (error) {
console.error("Error in setInterval callback:", error);
}
// Schedule next execution
if (active) {
setTimeout(repeat, delay);
}
}
}
// Store the active flag so we can stop it
globalThis._intervals.set(id, {
stop: () => {
active = false;
},
});
// Start the first execution
setTimeout(repeat, delay);
return id;
};
globalThis.clearInterval = function (id) {
if (globalThis._intervals.has(id)) {
const interval = globalThis._intervals.get(id);
interval.stop();
globalThis._intervals.delete(id);
}
};
// Performance measurement utilities for Hermes
// Since performance.now() is not available, we use Date.now() as fallback
// WARNING: This provides millisecond precision only, not the microsecond precision of native performance.now()
globalThis.performance = {
// Native performance.now() returns milliseconds with microsecond precision (e.g., 1234.567890)
// Date.now() only provides whole millisecond precision (e.g., 1234)
// We return Date.now() as-is since we cannot add precision we don't have
now: function () {
// Note: This returns whole milliseconds, not fractional like native performance.now()
// Libraries expecting sub-millisecond precision may not work correctly
return Date.now();
},
mark: function (name) {
if (!globalThis._performanceMarks) {
globalThis._performanceMarks = new Map();
}
globalThis._performanceMarks.set(name, Date.now());
},
measure: function (name, startMark, endMark) {
if (!globalThis._performanceMarks) {
globalThis._performanceMarks = new Map();
}
const start = globalThis._performanceMarks.get(startMark);
const end = globalThis._performanceMarks.get(endMark);
if (start !== undefined && end !== undefined) {
const duration = end - start;
console.log(`${name}: ${duration}ms`);
// Return object compatible with PerformanceMeasure interface
return {
name: name,
duration: duration, // milliseconds as number
startTime: start,
entryType: "measure",
detail: null,
};
} else {
console.error(
`Performance marks '${startMark}' or '${endMark}' not found`
);
return null;
}
},
// Add getEntries method for compatibility with performance API
getEntries: function () {
return []; // Simple implementation - could be enhanced
},
getEntriesByType: function (type) {
return []; // Simple implementation - could be enhanced
},
getEntriesByName: function (name) {
return []; // Simple implementation - could be enhanced
},
};
// Simple benchmark utility function
globalThis.benchmark = function (name, fn, iterations = 1) {
const results = [];
for (let i = 0; i < iterations; i++) {
const start = Date.now();
fn();
const end = Date.now();
results.push(end - start);
}
const total = results.reduce((sum, time) => sum + time, 0);
const average = total / iterations;
const min = Math.min(...results);
const max = Math.max(...results);
console.log(`Benchmark: ${name}`);
console.log(` Iterations: ${iterations}`);
console.log(` Total: ${total}ms`);
console.log(` Average: ${average.toFixed(2)}ms`);
console.log(` Min: ${min}ms`);
console.log(` Max: ${max}ms`);
return { name, iterations, total, average, min, max, results };
};