vector-index 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 (46) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1456 -2
  3. package/build-browser.js +67 -0
  4. package/index.js +39 -0
  5. package/package.json +72 -4
  6. package/src/async.js +458 -0
  7. package/src/clustering.js +226 -0
  8. package/src/embeddings/als.js +211 -0
  9. package/src/embeddings/bpr.js +149 -0
  10. package/src/embeddings/embeddings.js +222 -0
  11. package/src/embeddings/evaluate.js +193 -0
  12. package/src/embeddings/graph.js +376 -0
  13. package/src/embeddings/idmap.js +120 -0
  14. package/src/embeddings/interactions.js +123 -0
  15. package/src/embeddings/memory.js +52 -0
  16. package/src/embeddings/node2vec.js +142 -0
  17. package/src/embeddings/sgns.js +191 -0
  18. package/src/embeddings/skipgram.js +128 -0
  19. package/src/embeddings/trainer.js +147 -0
  20. package/src/embeddings/walker.js +208 -0
  21. package/src/errors.js +41 -0
  22. package/src/heap.js +82 -0
  23. package/src/index/block-codec.js +191 -0
  24. package/src/index/diskann-block-engine.js +891 -0
  25. package/src/index/diskann.js +331 -0
  26. package/src/index/engine-common.js +159 -0
  27. package/src/index/flat.js +49 -0
  28. package/src/index/hnsw.js +282 -0
  29. package/src/index/ivf.js +232 -0
  30. package/src/index/prune.js +70 -0
  31. package/src/index/vector-index.js +391 -0
  32. package/src/lru.js +32 -0
  33. package/src/math.js +666 -0
  34. package/src/metric.js +62 -0
  35. package/src/quant/bq.js +172 -0
  36. package/src/quant/pq.js +418 -0
  37. package/src/quant/scan.js +52 -0
  38. package/src/quant/sq.js +274 -0
  39. package/src/quant/turboquant.js +527 -0
  40. package/src/reduce/pca.js +253 -0
  41. package/src/results.js +86 -0
  42. package/src/search.js +52 -0
  43. package/src/sparse/sparse-index.js +349 -0
  44. package/src/store.js +476 -0
  45. package/src/typed.js +23 -0
  46. package/src/validate.js +130 -0
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * build-browser.js — bundle the ESM library into a single browser file.
4
+ *
5
+ * Prereq: npm install -D esbuild
6
+ *
7
+ * Run: node build-browser.js
8
+ *
9
+ * Output: dist/vector-index.browser.js (IIFE, sets window.VectorIndex)
10
+ * dist/vector-index.browser.min.js (minified)
11
+ *
12
+ * In the page:
13
+ * <script src="dist/vector-index.browser.min.js"></script>
14
+ * const { createVectorIndex, createNode2Vec } = window.VectorIndex;
15
+ *
16
+ * Modern bundlers (Vite, webpack, esbuild) don't need this file: they import
17
+ * index.js directly and drop whatever you don't use.
18
+ *
19
+ * The library has no dependencies and uses no Node builtins, so nothing is
20
+ * external.
21
+ */
22
+ import * as esbuild from 'esbuild';
23
+ import path from 'node:path';
24
+ import fs from 'node:fs';
25
+ import { fileURLToPath } from 'node:url';
26
+
27
+ const ROOT = path.dirname(fileURLToPath(import.meta.url));
28
+ const OUT = path.join(ROOT, 'dist');
29
+ if (!fs.existsSync(OUT)) fs.mkdirSync(OUT, { recursive: true });
30
+
31
+ // A tiny generated entry: import every export and expose them as one global.
32
+ const entry = {
33
+ contents:
34
+ "import * as VectorIndex from './index.js';\n" +
35
+ "if (typeof window !== 'undefined') window.VectorIndex = VectorIndex;\n" +
36
+ "export default VectorIndex;\n",
37
+ resolveDir: ROOT,
38
+ loader: 'js',
39
+ };
40
+
41
+ const common = {
42
+ stdin: entry,
43
+ bundle: true,
44
+ format: 'iife',
45
+ globalName: 'VectorIndexModule', // namespace; the entry also sets window.VectorIndex
46
+ platform: 'browser',
47
+ target: ['es2020'],
48
+ legalComments: 'none',
49
+ };
50
+
51
+ await esbuild.build({
52
+ ...common,
53
+ outfile: path.join(OUT, 'vector-index.browser.js'),
54
+ });
55
+ await esbuild.build({
56
+ ...common,
57
+ minify: true,
58
+ outfile: path.join(OUT, 'vector-index.browser.min.js'),
59
+ });
60
+
61
+ for (const f of ['vector-index.browser.js', 'vector-index.browser.min.js']) {
62
+ const p = path.join(OUT, f);
63
+ const kb = (fs.statSync(p).size / 1024).toFixed(1);
64
+ const ok = fs.readFileSync(p, 'utf8').includes('window.VectorIndex');
65
+ console.log(`${ok ? '✓' : '✗'} ${path.relative(ROOT, p)} (${kb} kB)`);
66
+ if (!ok) process.exitCode = 1;
67
+ }
package/index.js ADDED
@@ -0,0 +1,39 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // search: indexes (flat, hnsw, ivf, diskann, diskann-blocks)
6
+ export { createVectorIndex } from './src/index/vector-index.js';
7
+ // low-level engine for advanced use cases where the main factory doesn't
8
+ // fit — e.g. custom composition with other indexes. Same callback contract.
9
+ export { createDiskANNBlockEngine } from './src/index/diskann-block-engine.js';
10
+
11
+ // search: sparse vectors (keywords, BM25, SPLADE) — an inverted index
12
+ export { createSparseIndex } from './src/sparse/sparse-index.js';
13
+
14
+ // combining result lists: hybrid search (RRF) and shards
15
+ export { fuseResults, mergeResults } from './src/results.js';
16
+
17
+ // compression: quantizers
18
+ export { createPQ } from './src/quant/pq.js';
19
+ export { createSQ } from './src/quant/sq.js';
20
+ export { createBQ } from './src/quant/bq.js';
21
+ export { createTurboQuant, createTurboQuantProd } from './src/quant/turboquant.js';
22
+
23
+ // dimensionality reduction
24
+ export { createPCA } from './src/reduce/pca.js';
25
+
26
+ // embeddings: vectors from relationships (node2vec, DeepWalk, item2vec)
27
+ export { createGraph } from './src/embeddings/graph.js';
28
+ export { createWalker } from './src/embeddings/walker.js';
29
+ export { createNode2Vec } from './src/embeddings/node2vec.js';
30
+ export { createSkipGram } from './src/embeddings/skipgram.js';
31
+ // embeddings: users and items from interactions (matrix factorization)
32
+ export { createALS } from './src/embeddings/als.js';
33
+ export { createBPR } from './src/embeddings/bpr.js';
34
+ export { loadEmbeddings, loadEmbeddingsSync } from './src/embeddings/embeddings.js';
35
+ export { splitEdges, splitEdgesSync, evaluateLinkPrediction, evaluateLinkPredictionSync } from './src/embeddings/evaluate.js';
36
+ export { estimateMemory } from './src/embeddings/memory.js';
37
+
38
+ // stable error codes: compare err.code against these
39
+ export { ERR } from './src/errors.js';
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "vector-index",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Vector search, compression and embeddings in plain JavaScript for Node.js & Browsers. HNSW, IVF, DiskANN, PQ/SQ/BQ/TurboQuant quantizers, and node2vec / DeepWalk / item2vec embeddings. Zero dependencies, time-sliced, never blocks the event loop.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js"
9
+ },
10
+ "files": [
11
+ "index.js",
12
+ "README.md",
13
+ "LICENSE",
14
+ "build-browser.js",
15
+ "src/",
16
+ "dist/"
17
+ ],
18
+ "scripts": {
19
+ "build": "node build-browser.js"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/colocohen/vector-index.git"
24
+ },
25
+ "keywords": [
26
+ "vector",
27
+ "vector-search",
28
+ "vector-index",
29
+ "vector-database",
30
+ "ann",
31
+ "nearest-neighbor",
32
+ "similarity-search",
33
+ "hnsw",
34
+ "ivf",
35
+ "diskann",
36
+ "quantization",
37
+ "product-quantization",
38
+ "turboquant",
39
+ "embeddings",
40
+ "node2vec",
41
+ "deepwalk",
42
+ "item2vec",
43
+ "graph-embeddings",
44
+ "recommendations",
45
+ "k-means",
46
+ "pca",
47
+ "dimensionality-reduction",
48
+ "als",
49
+ "bpr",
50
+ "matrix-factorization",
51
+ "e-means",
52
+ "browser",
53
+ "nodejs"
54
+ ],
55
+ "author": "colocohen",
56
+ "license": "Apache-2.0",
57
+ "bugs": {
58
+ "url": "https://github.com/colocohen/vector-index/issues"
59
+ },
60
+ "homepage": "https://github.com/colocohen/vector-index#readme",
61
+ "funding": [
62
+ {
63
+ "type": "github",
64
+ "url": "https://github.com/sponsors/colocohen"
65
+ },
66
+ {
67
+ "type": "opencollective",
68
+ "url": "https://opencollective.com/colocohen"
69
+ }
70
+ ],
71
+ "devDependencies": {
72
+ "esbuild": "^0.28.2"
73
+ }
74
+ }
package/src/async.js ADDED
@@ -0,0 +1,458 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // async plumbing: deferring, callbacks, sync/async pairs, time-slicing, the
7
+ // write queue and the event emitter.
8
+ //
9
+ // this file also defines the CALLBACK CONTRACT every public function follows:
10
+ //
11
+ // 1. the callback is the last argument and is required. a missing or
12
+ // non-function callback is a programmer error: it throws a TypeError
13
+ // synchronously (same as Node core). everything else is reported
14
+ // through the callback.
15
+ // 2. the callback is ALWAYS invoked asynchronously, never in the same tick
16
+ // as the call — even when the result is already known.
17
+ // 3. the callback is invoked EXACTLY once, as cb(err) or cb(null, result).
18
+ // 4. an exception thrown by the caller's callback is never caught by the
19
+ // library: it surfaces as an uncaught exception, like in Node core.
20
+ // (catching it would either hide the bug or call the callback twice.)
21
+ // 5. every error the library creates carries a stable `err.code`.
22
+ // ===========================
23
+
24
+ import { ERR, createError, isLibraryError } from './errors.js';
25
+
26
+ // ===========================
27
+ // defer(fn) — run fn on a later macrotask
28
+ //
29
+ // setImmediate on Node; MessageChannel in browsers (no 4ms setTimeout clamp);
30
+ // setTimeout as the last resort.
31
+ // ===========================
32
+ const defer = (() => {
33
+ if (typeof setImmediate === 'function') return (fn) => setImmediate(fn);
34
+ if (typeof MessageChannel === 'function') {
35
+ let queue = [];
36
+ let head = 0;
37
+ const channel = new MessageChannel();
38
+ channel.port1.onmessage = () => {
39
+ const fn = queue[head];
40
+ queue[head++] = undefined;
41
+ if (head === queue.length) { queue = []; head = 0; }
42
+ fn();
43
+ };
44
+ return (fn) => {
45
+ queue.push(fn);
46
+ channel.port2.postMessage(0);
47
+ };
48
+ }
49
+ return (fn) => setTimeout(fn, 0);
50
+ })();
51
+
52
+ // ===========================
53
+ // callback helpers
54
+ // ===========================
55
+
56
+ // throws (synchronously) when cb isn't a function — rule 1
57
+ function requireCallback(cb, fnName) {
58
+ if (typeof cb !== 'function') {
59
+ const err = new TypeError(fnName + ': callback must be a function, got ' + typeof cb);
60
+ err.code = ERR.INVALID_ARGUMENT;
61
+ throw err;
62
+ }
63
+ }
64
+
65
+ // wraps a user callback so it is delivered async and at most once — rules 2–4.
66
+ // a second invocation is a library bug; it is ignored rather than surfacing
67
+ // a duplicate result to the caller.
68
+ function onceAsync(cb) {
69
+ let called = false;
70
+ return function done(err, result) {
71
+ if (called) return;
72
+ called = true;
73
+ defer(() => {
74
+ if (err) cb(err);
75
+ else cb(null, result);
76
+ });
77
+ };
78
+ }
79
+
80
+ // run a synchronous function and deliver its return value / exception
81
+ // through the callback — the standard way to expose an xSync() function
82
+ // as x(cb). the work runs now; only the delivery is deferred, so call order
83
+ // equals execution order.
84
+ function callAsync(fnName, cb, fn) {
85
+ requireCallback(cb, fnName);
86
+ let result;
87
+ let error = null;
88
+ try {
89
+ result = fn();
90
+ } catch (err) {
91
+ error = err;
92
+ }
93
+ defer(() => {
94
+ if (error) cb(error);
95
+ else cb(null, result);
96
+ });
97
+ }
98
+
99
+ // ===========================
100
+ // event emitter — one implementation for the whole package
101
+ //
102
+ // on(event, fn) add a listener
103
+ // off(event, fn) remove that listener; off(event) removes all of them
104
+ // emit(event, data) notify every listener (progress, root:change, ...)
105
+ // request(event, ...args, cb)
106
+ // call the ONE handler registered for a request event
107
+ // (block:read / block:write / block:delete). cb is
108
+ // guarded: a handler that calls back twice, or throws
109
+ // after calling back, can't call into the library twice.
110
+ //
111
+ // request events accept a single handler: registering a second one throws,
112
+ // since it's ambiguous which storage the data would go to.
113
+ // ===========================
114
+ function createEmitter(requestEvents) {
115
+ const singles = new Set(requestEvents || []);
116
+ const listeners = new Map();
117
+
118
+ function on(event, fn) {
119
+ if (typeof event !== 'string') {
120
+ throw createError(ERR.INVALID_ARGUMENT, 'on: event name must be a string');
121
+ }
122
+ if (typeof fn !== 'function') {
123
+ throw createError(ERR.INVALID_ARGUMENT, 'on: listener must be a function');
124
+ }
125
+ const arr = listeners.get(event) || [];
126
+ if (singles.has(event) && arr.length > 0) {
127
+ throw createError(ERR.INVALID_ARGUMENT,
128
+ 'on: "' + event + '" already has a handler — call off("' + event + '") first');
129
+ }
130
+ arr.push(fn);
131
+ listeners.set(event, arr);
132
+ }
133
+
134
+ function off(event, fn) {
135
+ if (fn === undefined) {
136
+ listeners.delete(event);
137
+ return;
138
+ }
139
+ const arr = listeners.get(event);
140
+ if (!arr) return;
141
+ const next = arr.filter(f => f !== fn);
142
+ if (next.length) listeners.set(event, next);
143
+ else listeners.delete(event);
144
+ }
145
+
146
+ function emit(event, data) {
147
+ const arr = listeners.get(event);
148
+ if (!arr) return;
149
+ for (const fn of arr.slice()) fn(data);
150
+ }
151
+
152
+ function request(event, ...args) {
153
+ const cb = args.pop();
154
+ let called = false;
155
+ const guarded = (err, result) => {
156
+ if (called) return;
157
+ called = true;
158
+ if (err) {
159
+ // errors from the caller's storage (e.g. Node's ENOENT) are wrapped so
160
+ // err.code is always one of ours; the original stays on err.cause
161
+ cb(isLibraryError(err) ? err
162
+ : createError(ERR.STORAGE, event + ' handler failed: ' + (err && err.message || err), err));
163
+ } else {
164
+ cb(null, result);
165
+ }
166
+ };
167
+
168
+ const arr = listeners.get(event);
169
+ if (!arr || arr.length === 0) {
170
+ return guarded(createError(ERR.STORAGE, 'no handler registered for "' + event + '"'));
171
+ }
172
+ try {
173
+ arr[0](...args, guarded);
174
+ } catch (err) {
175
+ guarded(err);
176
+ }
177
+ }
178
+
179
+ function has(event) {
180
+ return (listeners.get(event) || []).length > 0;
181
+ }
182
+
183
+ return { on, off, emit, request, has };
184
+ }
185
+
186
+ // ===========================
187
+ // pairedApi(fns, opts) → { name(...args, cb), nameSync(...args) }
188
+ //
189
+ // the callback is always the LAST argument, so optional arguments work
190
+ // (addEdge(a, b, cb) and addEdge(a, b, 2.5, cb) are both valid).
191
+ //
192
+ // opts.queue — when given, the async form runs through this task queue
193
+ // (writes are serialized), and the Sync form throws BUSY if
194
+ // anything is pending in the queue.
195
+ // opts.guard — function () → error|null checked before the Sync form runs.
196
+ // opts.reads — names that never wait in the queue (cheap reads).
197
+ //
198
+ // a GENERATOR function is a long job: Sync runs it to completion, async runs
199
+ // it time-sliced. a plain function runs immediately; only delivery is deferred.
200
+ // ===========================
201
+ function pairedApi(fns, opts) {
202
+ const queue = opts && opts.queue;
203
+ const reads = new Set((opts && opts.reads) || []);
204
+ const out = {};
205
+ for (const name of Object.keys(fns)) {
206
+ const fn = fns[name];
207
+ const isJob = isGeneratorFunction(fn);
208
+ const queued = queue && !reads.has(name);
209
+
210
+ out[name + 'Sync'] = function () {
211
+ if (queued && !queue.idle()) {
212
+ throw createError(ERR.BUSY, name + 'Sync: an async operation is still running on this object; ' +
213
+ 'use ' + name + '(..., cb) or wait for it to finish');
214
+ }
215
+ const r = fn.apply(null, arguments);
216
+ return isJob ? runJobSync(r) : r;
217
+ };
218
+
219
+ out[name] = function () {
220
+ const n = arguments.length;
221
+ const cb = n > 0 ? arguments[n - 1] : undefined;
222
+ requireCallback(cb, name);
223
+ const args = Array.prototype.slice.call(arguments, 0, n - 1);
224
+ const run = (finish) => {
225
+ if (isJob) {
226
+ runJobSliced(() => fn.apply(null, args), finish);
227
+ } else {
228
+ let result, error = null;
229
+ try { result = fn.apply(null, args); } catch (err) { error = err; }
230
+ finish(error, result);
231
+ }
232
+ };
233
+ if (!queued) {
234
+ const done = onceAsync(cb);
235
+ run(done);
236
+ return;
237
+ }
238
+ queue.push((next) => {
239
+ run((err, result) => {
240
+ // deliver first, then start the next task: callbacks arrive in queue order
241
+ defer(() => { if (err) cb(err); else cb(null, result); });
242
+ next();
243
+ });
244
+ });
245
+ };
246
+ }
247
+ return out;
248
+ }
249
+
250
+ function isGeneratorFunction(fn) {
251
+ return Object.prototype.toString.call(fn) === '[object GeneratorFunction]';
252
+ }
253
+
254
+ // ===========================
255
+ // TIME-SLICING
256
+ //
257
+ // a long operation is written once, as a generator that `yield`s at natural
258
+ // unit boundaries (one vector, one k-means iteration, one graph node).
259
+ // the same generator can then be run:
260
+ //
261
+ // runJobSync(iter) to completion, blocking — for the xSync API
262
+ // runJobSliced(make, cb) in slices of ~SLICE_MS, handing the thread back
263
+ // to the event loop between slices
264
+ //
265
+ // the generator's return value is the job's result. a `yield` costs tens of
266
+ // nanoseconds, so yielding often is cheap; what matters is that no single
267
+ // step between two yields takes long.
268
+ //
269
+ // `yield true` marks a HEAVY step (a work budget used up, a row of a dense
270
+ // matrix): the clock is read right after it, whatever the stride. without
271
+ // it, a job that goes from tiny steps (stride grown into the thousands) to
272
+ // heavy ones would run thousands of heavy steps before the next check.
273
+ // ===========================
274
+
275
+ const SLICE_MS = 8; // ≈ half a 60fps frame
276
+
277
+ const now = (typeof performance !== 'undefined' && typeof performance.now === 'function')
278
+ ? () => performance.now()
279
+ : () => Date.now();
280
+
281
+ function runJobSync(iter) {
282
+ let r = iter.next();
283
+ while (!r.done) r = iter.next();
284
+ return r.value;
285
+ }
286
+
287
+ // makeIter() is called inside the first slice, so an exception thrown while
288
+ // validating the arguments is delivered through cb like any other error.
289
+ // cb follows the callback contract (async, exactly once).
290
+ //
291
+ // reading the clock costs ~50ns; when a step is ~1µs (one vector against a
292
+ // small codebook) checking after every step would cost more than the work.
293
+ // so the clock is read every `stride` steps, and stride adapts so that a
294
+ // check happens roughly every CHECK_MS, whatever the step size.
295
+ //
296
+ // stride is capped at MAX_STRIDE: when a job moves from tiny steps to bigger
297
+ // ones, the first window still runs `stride` of the bigger steps before the
298
+ // clock notices. uncapped, a stride grown on 50ns steps (65536) times 2µs
299
+ // steps was a 130ms freeze; capped, a clock read every 1024 steps costs at
300
+ // most ~0.1% even on the tiniest steps.
301
+ const CHECK_MS = 0.25;
302
+ const MAX_STRIDE = 1024;
303
+
304
+ function runJobSliced(makeIter, cb) {
305
+ const done = onceAsync(cb);
306
+ let iter = null;
307
+ let stride = 1;
308
+
309
+ function slice() {
310
+ const start = now();
311
+ const deadline = start + SLICE_MS;
312
+ let lastCheck = start;
313
+ let sinceCheck = 0;
314
+ try {
315
+ if (!iter) iter = makeIter();
316
+ while (true) {
317
+ const r = iter.next();
318
+ if (r.done) return done(null, r.value);
319
+ if (++sinceCheck < stride && r.value !== true) continue;
320
+
321
+ const t = now();
322
+ if (t >= deadline) break;
323
+ const elapsed = t - lastCheck;
324
+ if (elapsed < CHECK_MS / 2 && stride < MAX_STRIDE) stride *= 2;
325
+ else if (elapsed > CHECK_MS * 2 && stride > 1) stride = Math.max(1, Math.floor(stride * CHECK_MS / elapsed));
326
+ lastCheck = t;
327
+ sinceCheck = 0;
328
+ }
329
+ } catch (err) {
330
+ return done(err);
331
+ }
332
+ defer(slice);
333
+ }
334
+
335
+ slice();
336
+ }
337
+
338
+ // ===========================
339
+ // task queue — serializes everything that mutates an index
340
+ //
341
+ // push(task) where task(next) does its work and calls next() exactly once
342
+ // when finished (synchronously or later). tasks run strictly in FIFO order,
343
+ // one at a time.
344
+ //
345
+ // - when the queue is idle, a pushed task starts immediately, inside push():
346
+ // a lone add() runs right away, exactly as without a queue.
347
+ // - while a long task (a sliced compact, an async storage write...) is
348
+ // running, new tasks wait their turn.
349
+ // - draining a backlog of quick tasks is itself time-sliced, so 100k adds
350
+ // that piled up during a compact don't block the event loop either.
351
+ // ===========================
352
+ function createTaskQueue() {
353
+ // FIFO with a head index: Array#shift is O(n) on large arrays, which made
354
+ // draining a big backlog quadratic
355
+ let tasks = [];
356
+ let head = 0;
357
+ let running = false; // a task has started and not called next() yet
358
+ let pumping = false; // the drain loop below is on the stack
359
+
360
+ function push(task) {
361
+ tasks.push(task);
362
+ pump();
363
+ }
364
+
365
+ function pump() {
366
+ if (running || pumping) return;
367
+ pumping = true;
368
+ const deadline = now() + SLICE_MS;
369
+ try {
370
+ while (head < tasks.length && !running) {
371
+ if (now() >= deadline) {
372
+ defer(pump);
373
+ return;
374
+ }
375
+ const task = tasks[head];
376
+ tasks[head++] = undefined;
377
+ if (head === tasks.length) {
378
+ tasks = [];
379
+ head = 0;
380
+ } else if (head > 4096 && head * 2 > tasks.length) {
381
+ tasks = tasks.slice(head);
382
+ head = 0;
383
+ }
384
+ running = true;
385
+ let inCall = true;
386
+ let finished = false;
387
+ const next = () => {
388
+ if (finished) return;
389
+ finished = true;
390
+ running = false;
391
+ // finished later (async task): resume draining from here
392
+ if (!inCall) pump();
393
+ };
394
+ try {
395
+ task(next);
396
+ } catch (err) {
397
+ // tasks catch their own errors; reaching this is an engine bug.
398
+ // keep the queue alive, then let the bug surface.
399
+ inCall = false;
400
+ next();
401
+ throw err;
402
+ }
403
+ inCall = false;
404
+ }
405
+ } finally {
406
+ pumping = false;
407
+ }
408
+ }
409
+
410
+ return {
411
+ push,
412
+ idle: () => !running && head === tasks.length,
413
+ size: () => tasks.length - head + (running ? 1 : 0)
414
+ };
415
+ }
416
+
417
+ // a quick synchronous write through the queue: fn() runs when its turn
418
+ // comes; its result or exception reaches cb (async, exactly once)
419
+ function queuedCall(queue, cb, fn) {
420
+ const done = onceAsync(cb);
421
+ queue.push((next) => {
422
+ let result;
423
+ let error = null;
424
+ try {
425
+ result = fn();
426
+ } catch (err) {
427
+ error = err;
428
+ }
429
+ done(error, result);
430
+ next();
431
+ });
432
+ }
433
+
434
+ // a long write through the queue, time-sliced: makeIter() returns the generator
435
+ function queuedJob(queue, cb, makeIter) {
436
+ const done = onceAsync(cb);
437
+ queue.push((next) => {
438
+ runJobSliced(makeIter, (err, result) => {
439
+ done(err, result);
440
+ next();
441
+ });
442
+ });
443
+ }
444
+
445
+ export {
446
+ defer,
447
+ now,
448
+ requireCallback,
449
+ onceAsync,
450
+ callAsync,
451
+ pairedApi,
452
+ runJobSync,
453
+ runJobSliced,
454
+ createTaskQueue,
455
+ queuedCall,
456
+ queuedJob,
457
+ createEmitter
458
+ };