deno.land / x / deno@v1.28.2 / core / 01_core.js

نووسراو ببینە
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license."use strict";
((window) => { const { Error, RangeError, ReferenceError, SyntaxError, TypeError, URIError, Map, Array, ArrayPrototypeFill, ArrayPrototypePush, ArrayPrototypeMap, ErrorCaptureStackTrace, Promise, ObjectFromEntries, MapPrototypeGet, MapPrototypeHas, MapPrototypeDelete, MapPrototypeSet, PromisePrototypeThen, PromisePrototypeFinally, StringPrototypeSlice, ObjectAssign, SymbolFor, setQueueMicrotask, } = window.__bootstrap.primordials; const { ops } = window.Deno.core;
const errorMap = {}; // Builtin v8 / JS errors registerErrorClass("Error", Error); registerErrorClass("RangeError", RangeError); registerErrorClass("ReferenceError", ReferenceError); registerErrorClass("SyntaxError", SyntaxError); registerErrorClass("TypeError", TypeError); registerErrorClass("URIError", URIError);
let nextPromiseId = 1; const promiseMap = new Map(); const RING_SIZE = 4 * 1024; const NO_PROMISE = null; // Alias to null is faster than plain nulls const promiseRing = ArrayPrototypeFill(new Array(RING_SIZE), NO_PROMISE); // TODO(bartlomieju): it future use `v8::Private` so it's not visible // to users. Currently missing bindings. const promiseIdSymbol = SymbolFor("Deno.core.internalPromiseId");
let opCallTracingEnabled = false; const opCallTraces = new Map();
function enableOpCallTracing() { opCallTracingEnabled = true; }
function isOpCallTracingEnabled() { return opCallTracingEnabled; }
function setPromise(promiseId) { const idx = promiseId % RING_SIZE; // Move old promise from ring to map const oldPromise = promiseRing[idx]; if (oldPromise !== NO_PROMISE) { const oldPromiseId = promiseId - RING_SIZE; MapPrototypeSet(promiseMap, oldPromiseId, oldPromise); } // Set new promise return promiseRing[idx] = newPromise(); }
function getPromise(promiseId) { // Check if out of ring bounds, fallback to map const outOfBounds = promiseId < nextPromiseId - RING_SIZE; if (outOfBounds) { const promise = MapPrototypeGet(promiseMap, promiseId); MapPrototypeDelete(promiseMap, promiseId); return promise; } // Otherwise take from ring const idx = promiseId % RING_SIZE; const promise = promiseRing[idx]; promiseRing[idx] = NO_PROMISE; return promise; }
function newPromise() { let resolve, reject; const promise = new Promise((resolve_, reject_) => { resolve = resolve_; reject = reject_; }); promise.resolve = resolve; promise.reject = reject; return promise; }
function hasPromise(promiseId) { // Check if out of ring bounds, fallback to map const outOfBounds = promiseId < nextPromiseId - RING_SIZE; if (outOfBounds) { return MapPrototypeHas(promiseMap, promiseId); } // Otherwise check it in ring const idx = promiseId % RING_SIZE; return promiseRing[idx] != NO_PROMISE; }
function opresolve() { for (let i = 0; i < arguments.length; i += 2) { const promiseId = arguments[i]; const res = arguments[i + 1]; const promise = getPromise(promiseId); promise.resolve(res); } }
function registerErrorClass(className, errorClass) { registerErrorBuilder(className, (msg) => new errorClass(msg)); }
function registerErrorBuilder(className, errorBuilder) { if (typeof errorMap[className] !== "undefined") { throw new TypeError(`Error class for "${className}" already registered`); } errorMap[className] = errorBuilder; }
function buildCustomError(className, message, code) { const error = errorMap[className]?.(message); // Strip buildCustomError() calls from stack trace if (typeof error == "object") { ErrorCaptureStackTrace(error, buildCustomError); if (code) { error.code = code; } } return error; }
function unwrapOpResult(res) { // .$err_class_name is a special key that should only exist on errors if (res?.$err_class_name) { const className = res.$err_class_name; const errorBuilder = errorMap[className]; const err = errorBuilder ? errorBuilder(res.message) : new Error( `Unregistered error class: "${className}"\n ${res.message}\n Classes of errors returned from ops should be registered via Deno.core.registerErrorClass().`, ); // Set .code if error was a known OS error, see error_codes.rs if (res.code) { err.code = res.code; } // Strip unwrapOpResult() and errorBuilder() calls from stack trace ErrorCaptureStackTrace(err, unwrapOpResult); throw err; } return res; }
function rollPromiseId() { return nextPromiseId++; }
// Generate async op wrappers. See core/bindings.rs function initializeAsyncOps() { function genAsyncOp(op, name, args) { return new Function( "setPromise", "getPromise", "promiseIdSymbol", "rollPromiseId", "handleOpCallTracing", "op", "unwrapOpResult", "PromisePrototypeThen", ` return function ${name}(${args}) { const id = rollPromiseId(); let promise = PromisePrototypeThen(setPromise(id), unwrapOpResult); try { op(id, ${args}); } catch (err) { // Cleanup the just-created promise getPromise(id); // Rethrow the error throw err; } handleOpCallTracing("${name}", id, promise); promise[promiseIdSymbol] = id; return promise; } `, )( setPromise, getPromise, promiseIdSymbol, rollPromiseId, handleOpCallTracing, op, unwrapOpResult, PromisePrototypeThen, ); }
// { <name>: <argc>, ... } for (const ele of Object.entries(ops.asyncOpsInfo())) { if (!ele) continue; const [name, argc] = ele; const op = ops[name]; const args = Array.from({ length: argc }, (_, i) => `arg${i}`).join(", "); ops[name] = genAsyncOp(op, name, args); } }
function handleOpCallTracing(opName, promiseId, p) { if (opCallTracingEnabled) { const stack = StringPrototypeSlice(new Error().stack, 6); MapPrototypeSet(opCallTraces, promiseId, { opName, stack }); p = PromisePrototypeFinally( p, () => MapPrototypeDelete(opCallTraces, promiseId), ); } }
function opAsync(opName, ...args) { return ops[opName](...args); }
function refOp(promiseId) { if (!hasPromise(promiseId)) { return; } ops.op_ref_op(promiseId); }
function unrefOp(promiseId) { if (!hasPromise(promiseId)) { return; } ops.op_unref_op(promiseId); }
function resources() { return ObjectFromEntries(ops.op_resources()); }
function metrics() { const [aggregate, perOps] = ops.op_metrics(); aggregate.ops = ObjectFromEntries(ArrayPrototypeMap( ops.op_op_names(), (opName, opId) => [opName, perOps[opId]], )); return aggregate; }
let reportExceptionCallback = undefined;
// Used to report errors thrown from functions passed to `queueMicrotask()`. // The callback will be passed the thrown error. For example, you can use this // to dispatch an error event to the global scope. // In other words, set the implementation for // https://html.spec.whatwg.org/multipage/webappapis.html#report-the-exception function setReportExceptionCallback(cb) { if (typeof cb != "function") { throw new TypeError("expected a function"); } reportExceptionCallback = cb; }
function queueMicrotask(cb) { if (typeof cb != "function") { throw new TypeError("expected a function"); } return ops.op_queue_microtask(() => { try { cb(); } catch (error) { if (reportExceptionCallback) { reportExceptionCallback(error); } else { throw error; } } }); }
// Some "extensions" rely on "BadResource" and "Interrupted" errors in the // JS code (eg. "deno_net") so they are provided in "Deno.core" but later // reexported on "Deno.errors" class BadResource extends Error { constructor(msg) { super(msg); this.name = "BadResource"; } } const BadResourcePrototype = BadResource.prototype;
class Interrupted extends Error { constructor(msg) { super(msg); this.name = "Interrupted"; } } const InterruptedPrototype = Interrupted.prototype;
const promiseHooks = { init: [], before: [], after: [], resolve: [], hasBeenSet: false, };
function setPromiseHooks(init, before, after, resolve) { if (init) ArrayPrototypePush(promiseHooks.init, init); if (before) ArrayPrototypePush(promiseHooks.before, before); if (after) ArrayPrototypePush(promiseHooks.after, after); if (resolve) ArrayPrototypePush(promiseHooks.resolve, resolve);
if (!promiseHooks.hasBeenSet) { promiseHooks.hasBeenSet = true;
ops.op_set_promise_hooks((promise, parentPromise) => { for (let i = 0; i < promiseHooks.init.length; ++i) { promiseHooks.init[i](promise, parentPromise); } }, (promise) => { for (let i = 0; i < promiseHooks.before.length; ++i) { promiseHooks.before[i](promise); } }, (promise) => { for (let i = 0; i < promiseHooks.after.length; ++i) { promiseHooks.after[i](promise); } }, (promise) => { for (let i = 0; i < promiseHooks.resolve.length; ++i) { promiseHooks.resolve[i](promise); } }); } }
// Extra Deno.core.* exports const core = ObjectAssign(globalThis.Deno.core, { opAsync, initializeAsyncOps, resources, metrics, registerErrorBuilder, registerErrorClass, buildCustomError, opresolve, BadResource, BadResourcePrototype, Interrupted, InterruptedPrototype, enableOpCallTracing, isOpCallTracingEnabled, opCallTraces, refOp, unrefOp, setReportExceptionCallback, setPromiseHooks, close: (rid) => ops.op_close(rid), tryClose: (rid) => ops.op_try_close(rid), read: (rid, buffer) => ops.op_read(rid, buffer), readAll: (rid) => ops.op_read_all(rid), write: (rid, buffer) => ops.op_write(rid, buffer), writeAll: (rid, buffer) => ops.op_write_all(rid, buffer), shutdown: (rid) => ops.op_shutdown(rid), print: (msg, isErr) => ops.op_print(msg, isErr), setMacrotaskCallback: (fn) => ops.op_set_macrotask_callback(fn), setNextTickCallback: (fn) => ops.op_set_next_tick_callback(fn), runMicrotasks: () => ops.op_run_microtasks(), hasTickScheduled: () => ops.op_has_tick_scheduled(), setHasTickScheduled: (bool) => ops.op_set_has_tick_scheduled(bool), evalContext: ( source, specifier, ) => ops.op_eval_context(source, specifier), createHostObject: () => ops.op_create_host_object(), encode: (text) => ops.op_encode(text), decode: (buffer) => ops.op_decode(buffer), serialize: ( value, options, errorCallback, ) => ops.op_serialize(value, options, errorCallback), deserialize: (buffer, options) => ops.op_deserialize(buffer, options), getPromiseDetails: (promise) => ops.op_get_promise_details(promise), getProxyDetails: (proxy) => ops.op_get_proxy_details(proxy), isProxy: (value) => ops.op_is_proxy(value), memoryUsage: () => ops.op_memory_usage(), setWasmStreamingCallback: (fn) => ops.op_set_wasm_streaming_callback(fn), abortWasmStreaming: ( rid, error, ) => ops.op_abort_wasm_streaming(rid, error), destructureError: (error) => ops.op_destructure_error(error), opNames: () => ops.op_op_names(), eventLoopHasMoreWork: () => ops.op_event_loop_has_more_work(), setPromiseRejectCallback: (fn) => ops.op_set_promise_reject_callback(fn), byteLength: (str) => ops.op_str_byte_length(str), });
ObjectAssign(globalThis.__bootstrap, { core }); ObjectAssign(globalThis.Deno, { core });
// Direct bindings on `globalThis` ObjectAssign(globalThis, { queueMicrotask }); setQueueMicrotask(queueMicrotask);})(globalThis);
deno

Version Info

Tagged at
a year ago