@lvce-editor/text-search-worker 1.1.0 → 1.2.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.
@@ -62,398 +62,436 @@ const getProtocol = uri => {
62
62
  return '';
63
63
  };
64
64
 
65
- const textSearch$5 = async (scheme, root, query) => {
66
- string(scheme);
67
- string(query);
68
- throw new Error('not implemented');
65
+ const state$3 = {
66
+ /**
67
+ * @type {any}
68
+ */
69
+ ipc: undefined
69
70
  };
70
-
71
- const assetDir = '';
72
-
73
- const splitLines$2 = lines => {
74
- return lines.split('\n');
71
+ const get$1 = () => {
72
+ return state$3.ipc;
73
+ };
74
+ const set$1 = ipc => {
75
+ state$3.ipc = ipc;
75
76
  };
76
77
 
77
- const File$1 = 1;
78
- const Match = 2;
79
-
80
- const textSearchInFile$1 = (file, content, query) => {
81
- const results = [];
82
- const lines = splitLines$2(content);
83
- for (let i = 0; i < lines.length; i++) {
84
- const line = lines[i];
85
- const index = line.indexOf(query);
86
- if (index !== -1) {
87
- results.push({
88
- type: Match,
89
- text: line,
90
- start: index,
91
- end: index + query.length,
92
- lineNumber: i
93
- });
94
- }
78
+ const Two = '2.0';
79
+ class AssertionError extends Error {
80
+ constructor(message) {
81
+ super(message);
82
+ this.name = 'AssertionError';
95
83
  }
96
- if (results.length > 0) {
97
- results.unshift({
98
- type: File$1,
99
- text: file,
100
- start: 0,
101
- end: 0,
102
- lineNumber: 0
103
- });
84
+ }
85
+ const getType$1 = value => {
86
+ switch (typeof value) {
87
+ case 'number':
88
+ return 'number';
89
+ case 'function':
90
+ return 'function';
91
+ case 'string':
92
+ return 'string';
93
+ case 'object':
94
+ if (value === null) {
95
+ return 'null';
96
+ }
97
+ if (Array.isArray(value)) {
98
+ return 'array';
99
+ }
100
+ return 'object';
101
+ case 'boolean':
102
+ return 'boolean';
103
+ default:
104
+ return 'unknown';
104
105
  }
105
- return results;
106
106
  };
107
- const textSearch$4 = async (scheme, root, query, options) => {
108
- string(scheme);
109
- string(root);
110
- string(query);
111
- const fetchUri = `${assetDir}/config/fileMap.json`;
112
- const fileList = await execute('Ajax.getJson', fetchUri);
113
- const allResults = [];
114
- const relativeRoot = root.slice('fetch://'.length);
115
- for (const uri of fileList) {
116
- const fetchUri = `${assetDir}${uri}`;
117
- const content = await execute('Ajax.getText', fetchUri);
118
- const relativeUri = uri.slice(relativeRoot.length + 1);
119
- const results = textSearchInFile$1(relativeUri, content, query);
120
- allResults.push(...results);
107
+ const number = value => {
108
+ const type = getType$1(value);
109
+ if (type !== 'number') {
110
+ throw new AssertionError('expected value to be of type number');
121
111
  }
122
- return allResults;
123
112
  };
124
-
125
- // based on https://github.com/microsoft/vscode/blob/c0769274fa136b45799edeccc0d0a2f645b75caf/src/vs/base/common/arrays.ts#L625 (License MIT)
126
-
127
- const insertInto = (array, start, newItems) => {
128
- const originalLength = array.length;
129
- const newItemsLength = newItems.length;
130
- array.length = originalLength + newItemsLength;
131
- // Move the items after the start index, start from the end so that we don't overwrite any value.
132
- for (let i = originalLength - 1; i >= start; i--) {
133
- array[i + newItemsLength] = array[i];
134
- }
135
- for (let i = 0; i < newItemsLength; i++) {
136
- array[i + start] = newItems[i];
137
- }
113
+ const state$1 = {
114
+ callbacks: Object.create(null)
138
115
  };
139
- const push = (array, newItems) => {
140
- insertInto(array, array.length, newItems);
116
+ const set = (id, fn) => {
117
+ state$1.callbacks[id] = fn;
141
118
  };
142
-
143
- const NotReadableError = 'NotReadableError';
144
-
145
- const isNotReadableError = error => {
146
- return error && error.name === NotReadableError;
119
+ const get = id => {
120
+ return state$1.callbacks[id];
147
121
  };
148
-
149
- const Directory = 'directory';
150
- const File = 'file';
151
-
152
- /**
153
- *
154
- * @param {FileSystemFileHandle} handle
155
- * @returns
156
- */
157
- const getFile = handle => {
158
- return handle.getFile();
122
+ const remove = id => {
123
+ delete state$1.callbacks[id];
159
124
  };
160
-
161
- const dirname = (pathSeparator, path) => {
162
- const index = path.lastIndexOf(pathSeparator);
163
- if (index === -1) {
164
- return path;
165
- }
166
- return path.slice(0, index);
125
+ const state$2 = {
126
+ id: 0
167
127
  };
168
-
169
- const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c);
170
- let idbProxyableTypes;
171
- let cursorAdvanceMethods;
172
- // This is a function to prevent it throwing up in node environments.
173
- function getIdbProxyableTypes() {
174
- return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]);
175
- }
176
- // This is a function to prevent it throwing up in node environments.
177
- function getCursorAdvanceMethods() {
178
- return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]);
179
- }
180
- const transactionDoneMap = new WeakMap();
181
- const transformCache = new WeakMap();
182
- const reverseTransformCache = new WeakMap();
183
- function promisifyRequest(request) {
184
- const promise = new Promise((resolve, reject) => {
185
- const unlisten = () => {
186
- request.removeEventListener('success', success);
187
- request.removeEventListener('error', error);
188
- };
189
- const success = () => {
190
- resolve(wrap(request.result));
191
- unlisten();
192
- };
193
- const error = () => {
194
- reject(request.error);
195
- unlisten();
196
- };
197
- request.addEventListener('success', success);
198
- request.addEventListener('error', error);
199
- });
200
- // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
201
- // is because we create many promises from a single IDBRequest.
202
- reverseTransformCache.set(promise, request);
203
- return promise;
204
- }
205
- function cacheDonePromiseForTransaction(tx) {
206
- // Early bail if we've already created a done promise for this transaction.
207
- if (transactionDoneMap.has(tx)) return;
208
- const done = new Promise((resolve, reject) => {
209
- const unlisten = () => {
210
- tx.removeEventListener('complete', complete);
211
- tx.removeEventListener('error', error);
212
- tx.removeEventListener('abort', error);
213
- };
214
- const complete = () => {
215
- resolve();
216
- unlisten();
217
- };
218
- const error = () => {
219
- reject(tx.error || new DOMException('AbortError', 'AbortError'));
220
- unlisten();
221
- };
222
- tx.addEventListener('complete', complete);
223
- tx.addEventListener('error', error);
224
- tx.addEventListener('abort', error);
128
+ const create$3 = () => {
129
+ return ++state$2.id;
130
+ };
131
+ const warn = (...args) => {
132
+ console.warn(...args);
133
+ };
134
+ const withResolvers$1 = () => {
135
+ /**
136
+ * @type {any}
137
+ */
138
+ let _resolve;
139
+ const promise = new Promise(resolve => {
140
+ _resolve = resolve;
225
141
  });
226
- // Cache it for later retrieval.
227
- transactionDoneMap.set(tx, done);
228
- }
229
- let idbProxyTraps = {
230
- get(target, prop, receiver) {
231
- if (target instanceof IDBTransaction) {
232
- // Special handling for transaction.done.
233
- if (prop === 'done') return transactionDoneMap.get(target);
234
- // Make tx.store return the only store in the transaction, or undefined if there are many.
235
- if (prop === 'store') {
236
- return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]);
237
- }
238
- }
239
- // Else transform whatever we get back.
240
- return wrap(target[prop]);
241
- },
242
- set(target, prop, value) {
243
- target[prop] = value;
244
- return true;
245
- },
246
- has(target, prop) {
247
- if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) {
248
- return true;
249
- }
250
- return prop in target;
142
+ return {
143
+ resolve: _resolve,
144
+ promise
145
+ };
146
+ };
147
+ const registerPromise = () => {
148
+ const id = create$3();
149
+ const {
150
+ resolve,
151
+ promise
152
+ } = withResolvers$1();
153
+ set(id, resolve);
154
+ return {
155
+ id,
156
+ promise
157
+ };
158
+ };
159
+ const resolve = (id, args) => {
160
+ number(id);
161
+ const fn = get(id);
162
+ if (!fn) {
163
+ console.log(args);
164
+ warn(`callback ${id} may already be disposed`);
165
+ return;
251
166
  }
167
+ fn(args);
168
+ remove(id);
252
169
  };
253
- function replaceTraps(callback) {
254
- idbProxyTraps = callback(idbProxyTraps);
255
- }
256
- function wrapFunction(func) {
257
- // Due to expected object equality (which is enforced by the caching in `wrap`), we
258
- // only create one new func per func.
259
- // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
260
- // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
261
- // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
262
- // with real promises, so each advance methods returns a new promise for the cursor object, or
263
- // undefined if the end of the cursor has been reached.
264
- if (getCursorAdvanceMethods().includes(func)) {
265
- return function (...args) {
266
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
267
- // the original object.
268
- func.apply(unwrap(this), args);
269
- return wrap(this.request);
270
- };
271
- }
272
- return function (...args) {
273
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
274
- // the original object.
275
- return wrap(func.apply(unwrap(this), args));
170
+ const create$2 = (method, params) => {
171
+ const {
172
+ id,
173
+ promise
174
+ } = registerPromise();
175
+ const message = {
176
+ jsonrpc: Two,
177
+ method,
178
+ params,
179
+ id
276
180
  };
277
- }
278
- function transformCachableValue(value) {
279
- if (typeof value === 'function') return wrapFunction(value);
280
- // This doesn't return, it just creates a 'done' promise for the transaction,
281
- // which is later returned for transaction.done (see idbObjectHandler).
282
- if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value);
283
- if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps);
284
- // Return the same value back if we're not going to transform it.
285
- return value;
286
- }
287
- function wrap(value) {
288
- // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
289
- // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
290
- if (value instanceof IDBRequest) return promisifyRequest(value);
291
- // If we've already transformed this value before, reuse the transformed value.
292
- // This is faster, but it also provides object equality.
293
- if (transformCache.has(value)) return transformCache.get(value);
294
- const newValue = transformCachableValue(value);
295
- // Not all types are transformed.
296
- // These may be primitive types, so they can't be WeakMap keys.
297
- if (newValue !== value) {
298
- transformCache.set(value, newValue);
299
- reverseTransformCache.set(newValue, value);
300
- }
301
- return newValue;
302
- }
303
- const unwrap = value => reverseTransformCache.get(value);
304
-
305
- /**
306
- * Open a database.
307
- *
308
- * @param name Name of the database.
309
- * @param version Schema version.
310
- * @param callbacks Additional callbacks.
311
- */
312
- function openDB(name, version, {
313
- blocked,
314
- upgrade,
315
- blocking,
316
- terminated
317
- } = {}) {
318
- const request = indexedDB.open(name, version);
319
- const openPromise = wrap(request);
320
- if (upgrade) {
321
- request.addEventListener('upgradeneeded', event => {
322
- upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
323
- });
324
- }
325
- if (blocked) {
326
- request.addEventListener('blocked', event => blocked(
327
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
328
- event.oldVersion, event.newVersion, event));
329
- }
330
- openPromise.then(db => {
331
- if (terminated) db.addEventListener('close', () => terminated());
332
- if (blocking) {
333
- db.addEventListener('versionchange', event => blocking(event.oldVersion, event.newVersion, event));
334
- }
335
- }).catch(() => {});
336
- return openPromise;
337
- }
338
- const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
339
- const writeMethods = ['put', 'add', 'delete', 'clear'];
340
- const cachedMethods = new Map();
341
- function getMethod(target, prop) {
342
- if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) {
343
- return;
344
- }
345
- if (cachedMethods.get(prop)) return cachedMethods.get(prop);
346
- const targetFuncName = prop.replace(/FromIndex$/, '');
347
- const useIndex = prop !== targetFuncName;
348
- const isWrite = writeMethods.includes(targetFuncName);
349
- if (
350
- // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
351
- !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) {
352
- return;
353
- }
354
- const method = async function (storeName, ...args) {
355
- // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
356
- const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
357
- let target = tx.store;
358
- if (useIndex) target = target.index(args.shift());
359
- // Must reject if op rejects.
360
- // If it's a write operation, must reject if tx.done rejects.
361
- // Must reject with op rejection first.
362
- // Must resolve with op value.
363
- // Must handle both promises (no unhandled rejections)
364
- return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0];
181
+ return {
182
+ message,
183
+ promise
365
184
  };
366
- cachedMethods.set(prop, method);
367
- return method;
368
- }
369
- replaceTraps(oldTraps => ({
370
- ...oldTraps,
371
- get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
372
- has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop)
373
- }));
374
- const advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];
375
- const methodMap = {};
376
- const advanceResults = new WeakMap();
377
- const ittrProxiedCursorToOriginalProxy = new WeakMap();
378
- const cursorIteratorTraps = {
379
- get(target, prop) {
380
- if (!advanceMethodProps.includes(prop)) return target[prop];
381
- let cachedFunc = methodMap[prop];
382
- if (!cachedFunc) {
383
- cachedFunc = methodMap[prop] = function (...args) {
384
- advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));
385
- };
386
- }
387
- return cachedFunc;
388
- }
389
185
  };
390
- async function* iterate(...args) {
391
- // tslint:disable-next-line:no-this-assignment
392
- let cursor = this;
393
- if (!(cursor instanceof IDBCursor)) {
394
- cursor = await cursor.openCursor(...args);
395
- }
396
- if (!cursor) return;
397
- cursor = cursor;
398
- const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);
399
- ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);
400
- // Map this double-proxy back to the original, so other cursor methods work.
401
- reverseTransformCache.set(proxiedCursor, unwrap(cursor));
402
- while (cursor) {
403
- yield proxiedCursor;
404
- // If one of the advancing methods was not called, call continue().
405
- cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());
406
- advanceResults.delete(proxiedCursor);
186
+ class JsonRpcError extends Error {
187
+ constructor(message) {
188
+ super(message);
189
+ this.name = 'JsonRpcError';
407
190
  }
408
191
  }
409
- function isIteratorProp(target, prop) {
410
- return prop === Symbol.asyncIterator && instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor]) || prop === 'iterate' && instanceOfAny(target, [IDBIndex, IDBObjectStore]);
411
- }
412
- replaceTraps(oldTraps => ({
413
- ...oldTraps,
414
- get(target, prop, receiver) {
415
- if (isIteratorProp(target, prop)) return iterate;
416
- return oldTraps.get(target, prop, receiver);
417
- },
418
- has(target, prop) {
419
- return isIteratorProp(target, prop) || oldTraps.has(target, prop);
192
+ const NewLine$3 = '\n';
193
+ const DomException = 'DOMException';
194
+ const ReferenceError$1 = 'ReferenceError';
195
+ const SyntaxError$1 = 'SyntaxError';
196
+ const TypeError$1 = 'TypeError';
197
+ const getErrorConstructor = (message, type) => {
198
+ if (type) {
199
+ switch (type) {
200
+ case DomException:
201
+ return DOMException;
202
+ case TypeError$1:
203
+ return TypeError;
204
+ case SyntaxError$1:
205
+ return SyntaxError;
206
+ case ReferenceError$1:
207
+ return ReferenceError;
208
+ default:
209
+ return Error;
210
+ }
420
211
  }
421
- }));
422
-
423
- const normalizeLine$1 = line => {
424
- if (line.startsWith('Error: ')) {
425
- return line.slice(`Error: `.length);
212
+ if (message.startsWith('TypeError: ')) {
213
+ return TypeError;
426
214
  }
427
- if (line.startsWith('VError: ')) {
428
- return line.slice(`VError: `.length);
215
+ if (message.startsWith('SyntaxError: ')) {
216
+ return SyntaxError;
429
217
  }
430
- return line;
218
+ if (message.startsWith('ReferenceError: ')) {
219
+ return ReferenceError;
220
+ }
221
+ return Error;
431
222
  };
432
- const getCombinedMessage$1 = (error, message) => {
433
- const stringifiedError = normalizeLine$1(`${error}`);
434
- if (message) {
435
- return `${message}: ${stringifiedError}`;
223
+ const constructError = (message, type, name) => {
224
+ const ErrorConstructor = getErrorConstructor(message, type);
225
+ if (ErrorConstructor === DOMException && name) {
226
+ return new ErrorConstructor(message, name);
436
227
  }
437
- return stringifiedError;
228
+ if (ErrorConstructor === Error) {
229
+ const error = new Error(message);
230
+ if (name && name !== 'VError') {
231
+ error.name = name;
232
+ }
233
+ return error;
234
+ }
235
+ return new ErrorConstructor(message);
438
236
  };
439
- const NewLine$3 = '\n';
440
237
  const getNewLineIndex$2 = (string, startIndex = undefined) => {
441
238
  return string.indexOf(NewLine$3, startIndex);
442
239
  };
443
- const mergeStacks$1 = (parent, child) => {
444
- if (!child) {
445
- return parent;
240
+ const getParentStack = error => {
241
+ let parentStack = error.stack || error.data || error.message || '';
242
+ if (parentStack.startsWith(' at')) {
243
+ parentStack = error.message + NewLine$3 + parentStack;
446
244
  }
447
- const parentNewLineIndex = getNewLineIndex$2(parent);
448
- const childNewLineIndex = getNewLineIndex$2(child);
449
- if (childNewLineIndex === -1) {
450
- return parent;
245
+ return parentStack;
246
+ };
247
+ const joinLines$1 = lines => {
248
+ return lines.join(NewLine$3);
249
+ };
250
+ const MethodNotFound = -32601;
251
+ const Custom = -32001;
252
+ const splitLines$2 = lines => {
253
+ return lines.split(NewLine$3);
254
+ };
255
+ const restoreJsonRpcError = error => {
256
+ if (error && error instanceof Error) {
257
+ return error;
451
258
  }
452
- const parentFirstLine = parent.slice(0, parentNewLineIndex);
453
- const childRest = child.slice(childNewLineIndex);
454
- const childFirstLine = normalizeLine$1(child.slice(0, childNewLineIndex));
455
- if (parentFirstLine.includes(childFirstLine)) {
456
- return parentFirstLine + childRest;
259
+ const currentStack = joinLines$1(splitLines$2(new Error().stack || '').slice(1));
260
+ if (error && error.code && error.code === MethodNotFound) {
261
+ const restoredError = new JsonRpcError(error.message);
262
+ const parentStack = getParentStack(error);
263
+ restoredError.stack = parentStack + NewLine$3 + currentStack;
264
+ return restoredError;
265
+ }
266
+ if (error && error.message) {
267
+ const restoredError = constructError(error.message, error.type, error.name);
268
+ if (error.data) {
269
+ if (error.data.stack && error.data.type && error.message) {
270
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine$3 + error.data.stack + NewLine$3 + currentStack;
271
+ } else if (error.data.stack) {
272
+ restoredError.stack = error.data.stack;
273
+ }
274
+ if (error.data.codeFrame) {
275
+ // @ts-ignore
276
+ restoredError.codeFrame = error.data.codeFrame;
277
+ }
278
+ if (error.data.code) {
279
+ // @ts-ignore
280
+ restoredError.code = error.data.code;
281
+ }
282
+ if (error.data.type) {
283
+ // @ts-ignore
284
+ restoredError.name = error.data.type;
285
+ }
286
+ } else {
287
+ if (error.stack) {
288
+ const lowerStack = restoredError.stack || '';
289
+ // @ts-ignore
290
+ const indexNewLine = getNewLineIndex$2(lowerStack);
291
+ const parentStack = getParentStack(error);
292
+ // @ts-ignore
293
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
294
+ }
295
+ if (error.codeFrame) {
296
+ // @ts-ignore
297
+ restoredError.codeFrame = error.codeFrame;
298
+ }
299
+ }
300
+ return restoredError;
301
+ }
302
+ if (typeof error === 'string') {
303
+ return new Error(`JsonRpc Error: ${error}`);
304
+ }
305
+ return new Error(`JsonRpc Error: ${error}`);
306
+ };
307
+ const unwrapJsonRpcResult = responseMessage => {
308
+ if ('error' in responseMessage) {
309
+ const restoredError = restoreJsonRpcError(responseMessage.error);
310
+ throw restoredError;
311
+ }
312
+ if ('result' in responseMessage) {
313
+ return responseMessage.result;
314
+ }
315
+ throw new JsonRpcError('unexpected response message');
316
+ };
317
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
318
+ const getType = prettyError => {
319
+ if (prettyError && prettyError.type) {
320
+ return prettyError.type;
321
+ }
322
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
323
+ return prettyError.constructor.name;
324
+ }
325
+ return undefined;
326
+ };
327
+ const getErrorProperty = (error, prettyError) => {
328
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
329
+ return {
330
+ code: MethodNotFound,
331
+ message: error.message,
332
+ data: error.stack
333
+ };
334
+ }
335
+ return {
336
+ code: Custom,
337
+ message: prettyError.message,
338
+ data: {
339
+ stack: prettyError.stack,
340
+ codeFrame: prettyError.codeFrame,
341
+ type: getType(prettyError),
342
+ code: prettyError.code,
343
+ name: prettyError.name
344
+ }
345
+ };
346
+ };
347
+ const create$1 = (message, error) => {
348
+ return {
349
+ jsonrpc: Two,
350
+ id: message.id,
351
+ error
352
+ };
353
+ };
354
+ const getErrorResponse = (message, error, preparePrettyError, logError) => {
355
+ const prettyError = preparePrettyError(error);
356
+ logError(error, prettyError);
357
+ const errorProperty = getErrorProperty(error, prettyError);
358
+ return create$1(message, errorProperty);
359
+ };
360
+ const create = (message, result) => {
361
+ return {
362
+ jsonrpc: Two,
363
+ id: message.id,
364
+ result: result ?? null
365
+ };
366
+ };
367
+ const getSuccessResponse = (message, result) => {
368
+ const resultProperty = result ?? null;
369
+ return create(message, resultProperty);
370
+ };
371
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
372
+ try {
373
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
374
+ return getSuccessResponse(message, result);
375
+ } catch (error) {
376
+ return getErrorResponse(message, error, preparePrettyError, logError);
377
+ }
378
+ };
379
+ const defaultPreparePrettyError = error => {
380
+ return error;
381
+ };
382
+ const defaultLogError = () => {
383
+ // ignore
384
+ };
385
+ const defaultRequiresSocket = () => {
386
+ return false;
387
+ };
388
+ const defaultResolve = resolve;
389
+ const handleJsonRpcMessage = async (...args) => {
390
+ let message;
391
+ let ipc;
392
+ let execute;
393
+ let preparePrettyError;
394
+ let logError;
395
+ let resolve;
396
+ let requiresSocket;
397
+ if (args.length === 1) {
398
+ const arg = args[0];
399
+ message = arg.message;
400
+ ipc = arg.ipc;
401
+ execute = arg.execute;
402
+ preparePrettyError = arg.preparePrettyError || defaultPreparePrettyError;
403
+ logError = arg.logError || defaultLogError;
404
+ requiresSocket = arg.requiresSocket || defaultRequiresSocket;
405
+ resolve = arg.resolve || defaultResolve;
406
+ } else {
407
+ ipc = args[0];
408
+ message = args[1];
409
+ execute = args[2];
410
+ resolve = args[3];
411
+ preparePrettyError = args[4];
412
+ logError = args[5];
413
+ requiresSocket = args[6];
414
+ }
415
+ if ('id' in message) {
416
+ if ('method' in message) {
417
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
418
+ try {
419
+ ipc.send(response);
420
+ } catch (error) {
421
+ const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
422
+ ipc.send(errorResponse);
423
+ }
424
+ return;
425
+ }
426
+ resolve(message.id, message);
427
+ return;
428
+ }
429
+ if ('method' in message) {
430
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
431
+ return;
432
+ }
433
+ throw new JsonRpcError('unexpected message');
434
+ };
435
+ const invoke$2 = async (ipc, method, ...params) => {
436
+ const {
437
+ message,
438
+ promise
439
+ } = create$2(method, params);
440
+ ipc.send(message);
441
+ const responseMessage = await promise;
442
+ const result = unwrapJsonRpcResult(responseMessage);
443
+ return result;
444
+ };
445
+
446
+ const invoke$1 = (method, ...params) => {
447
+ const ipc = get$1();
448
+ return invoke$2(ipc, method, ...params);
449
+ };
450
+ const listen$2 = ipc => {
451
+ set$1(ipc);
452
+ };
453
+
454
+ const textSearch$5 = async (scheme, root, query) => {
455
+ string(scheme);
456
+ string(query);
457
+ const result = await invoke$1('ExtensionHostTextSearch.executeTextSearchProvider', scheme, query);
458
+ return result;
459
+ };
460
+
461
+ const normalizeLine$1 = line => {
462
+ if (line.startsWith('Error: ')) {
463
+ return line.slice(`Error: `.length);
464
+ }
465
+ if (line.startsWith('VError: ')) {
466
+ return line.slice(`VError: `.length);
467
+ }
468
+ return line;
469
+ };
470
+ const getCombinedMessage$1 = (error, message) => {
471
+ const stringifiedError = normalizeLine$1(`${error}`);
472
+ if (message) {
473
+ return `${message}: ${stringifiedError}`;
474
+ }
475
+ return stringifiedError;
476
+ };
477
+ const NewLine$2 = '\n';
478
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
479
+ return string.indexOf(NewLine$2, startIndex);
480
+ };
481
+ const mergeStacks$1 = (parent, child) => {
482
+ if (!child) {
483
+ return parent;
484
+ }
485
+ const parentNewLineIndex = getNewLineIndex$1(parent);
486
+ const childNewLineIndex = getNewLineIndex$1(child);
487
+ if (childNewLineIndex === -1) {
488
+ return parent;
489
+ }
490
+ const parentFirstLine = parent.slice(0, parentNewLineIndex);
491
+ const childRest = child.slice(childNewLineIndex);
492
+ const childFirstLine = normalizeLine$1(child.slice(0, childNewLineIndex));
493
+ if (parentFirstLine.includes(childFirstLine)) {
494
+ return parentFirstLine + childRest;
457
495
  }
458
496
  return child;
459
497
  };
@@ -476,58 +514,42 @@ let VError$1 = class VError extends Error {
476
514
  }
477
515
  };
478
516
 
479
- const state$3 = {
480
- databases: Object.create(null),
481
- eventId: 0,
482
- dbVersion: 1,
483
- cachedDb: undefined
517
+ const getJson = async url => {
518
+ try {
519
+ const response = await fetch(url);
520
+ if (!response.ok) {
521
+ throw new Error(response.statusText);
522
+ }
523
+ const json = await response.json();
524
+ return json;
525
+ } catch (error) {
526
+ throw new VError$1(error, `Failed to get json`);
527
+ }
484
528
  };
485
529
 
486
- // TODO high memory usage in idb because of transactionDoneMap
487
-
488
- const getHandleDb = async () => {
489
- // @ts-ignore
490
- const db = await openDB('handle', state$3.dbVersion, {
491
- async upgrade(db, oldVersion) {
492
- if (!db.objectStoreNames.contains('file-handles-store')) {
493
- // @ts-ignore
494
- await db.createObjectStore('file-handles-store', {});
495
- }
530
+ const getText = async url => {
531
+ try {
532
+ const response = await fetch(url);
533
+ if (!response.ok) {
534
+ throw new Error(response.statusText);
496
535
  }
497
- });
498
- return db;
536
+ const text = await response.text();
537
+ return text;
538
+ } catch (error) {
539
+ throw new VError$1(error, `Failed to get text`);
540
+ }
499
541
  };
500
- const getHandle$1 = async uri => {
501
- const handleDb = await getHandleDb();
502
- const handle = await handleDb.get('file-handles-store', uri);
503
- return handle;
542
+
543
+ const splitLines$1 = lines => {
544
+ return lines.split('\n');
504
545
  };
505
546
 
506
- const getHandle = async uri => {
507
- try {
508
- // TODO retrieve handle from state or from indexeddb
509
- // TODO if not found, throw error
510
- const handle = await getHandle$1(uri);
511
- return handle;
512
- } catch (error) {
513
- throw new VError$1(error, 'Failed to get handle');
514
- }
515
- };
547
+ const File$1 = 1;
548
+ const Match = 2;
516
549
 
517
- const getDirectoryHandle = async uri => {
518
- const handle = await getHandle(uri);
519
- if (handle) {
520
- return handle;
521
- }
522
- const dirname$1 = dirname('/', uri);
523
- if (uri === dirname$1) {
524
- return undefined;
525
- }
526
- return getDirectoryHandle(dirname$1);
527
- };
528
- const textSearchInText = (file, content, query) => {
550
+ const textSearchInFile$1 = (file, content, query) => {
529
551
  const results = [];
530
- const lines = splitLines$2(content);
552
+ const lines = splitLines$1(content);
531
553
  for (let i = 0; i < lines.length; i++) {
532
554
  const line = lines[i];
533
555
  const index = line.indexOf(query);
@@ -552,464 +574,467 @@ const textSearchInText = (file, content, query) => {
552
574
  }
553
575
  return results;
554
576
  };
555
- const textSearchInFile = async (all, handle, absolutePath, query) => {
556
- try {
557
- const file = await getFile(handle);
558
- const content = await file.text();
559
- const results = textSearchInText(absolutePath, content, query);
560
- push(all, results);
561
- } catch (error) {
562
- if (isNotReadableError(error)) {
563
- // ignore
564
- return;
565
- }
566
- throw error;
567
- }
568
- };
569
- const textSearchRecursively = async (all, parent, handle, query) => {
570
- const childHandles = [];
571
- // TODO
572
- // await FileSystemHtml.getChildHandles(handle)
573
- const promises = [];
574
- for (const childHandle of childHandles) {
575
- const absolutePath = parent + '/' + childHandle.name;
576
- switch (childHandle.kind) {
577
- case Directory:
578
- promises.push(textSearchRecursively(all, absolutePath, childHandle, query));
579
- break;
580
- case File:
581
- promises.push(textSearchInFile(all, childHandle, absolutePath, query));
582
- break;
583
- }
584
- }
585
- await Promise.all(promises);
586
- };
587
- const textSearch$3 = async (scheme, root, query) => {
577
+ const textSearch$4 = async (scheme, root, query, options, assetDir) => {
588
578
  string(scheme);
589
579
  string(root);
590
580
  string(query);
591
- const relativeRoot = root.slice('html://'.length);
592
- const handle = await getDirectoryHandle(relativeRoot);
593
- if (!handle) {
594
- // @ts-ignore
595
- throw new VError$1(`Folder not found ${relativeRoot}`);
581
+ const fetchUri = `${assetDir}/config/fileMap.json`;
582
+ const fileList = await getJson(fetchUri);
583
+ const allResults = [];
584
+ const relativeRoot = root.slice('fetch://'.length);
585
+ for (const uri of fileList) {
586
+ const fetchUri = `${assetDir}${uri}`;
587
+ const content = await getText(fetchUri);
588
+ const relativeUri = uri.slice(relativeRoot.length + 1);
589
+ const results = textSearchInFile$1(relativeUri, content, query);
590
+ allResults.push(...results);
596
591
  }
597
- const all = [];
598
- await textSearchRecursively(all, '', handle, query);
599
- return all;
592
+ return allResults;
600
593
  };
601
594
 
602
- const getRipGrepArgs = ({
603
- threads,
604
- isCaseSensitive,
605
- searchString,
606
- useRegularExpression
607
- }) => {
608
- const ripGrepArgs = ['--hidden', '--no-require-git', '--smart-case', '--stats', '--json'];
609
- ripGrepArgs.push('--threads', `${threads}`);
610
- if (isCaseSensitive) {
611
- ripGrepArgs.push('--case-sensitive');
612
- } else {
613
- ripGrepArgs.push('--ignore-case');
595
+ // based on https://github.com/microsoft/vscode/blob/c0769274fa136b45799edeccc0d0a2f645b75caf/src/vs/base/common/arrays.ts#L625 (License MIT)
596
+
597
+ const insertInto = (array, start, newItems) => {
598
+ const originalLength = array.length;
599
+ const newItemsLength = newItems.length;
600
+ array.length = originalLength + newItemsLength;
601
+ // Move the items after the start index, start from the end so that we don't overwrite any value.
602
+ for (let i = originalLength - 1; i >= start; i--) {
603
+ array[i + newItemsLength] = array[i];
614
604
  }
615
- if (useRegularExpression) {
616
- ripGrepArgs.push('--regexp', searchString);
617
- } else {
618
- ripGrepArgs.push('--fixed-strings');
619
- ripGrepArgs.push('--');
620
- ripGrepArgs.push(searchString);
605
+ for (let i = 0; i < newItemsLength; i++) {
606
+ array[i + start] = newItems[i];
621
607
  }
622
- ripGrepArgs.push('.');
623
- return ripGrepArgs;
624
608
  };
625
-
626
- const state$2 = {
627
- /**
628
- * @type {any}
629
- */
630
- ipc: undefined
609
+ const push = (array, newItems) => {
610
+ insertInto(array, array.length, newItems);
631
611
  };
632
- const get$1 = () => {
633
- return state$2.ipc;
612
+
613
+ const NotReadableError = 'NotReadableError';
614
+
615
+ const isNotReadableError = error => {
616
+ return error && error.name === NotReadableError;
634
617
  };
635
- const set$1 = ipc => {
636
- state$2.ipc = ipc;
618
+
619
+ const Directory = 'directory';
620
+ const File = 'file';
621
+
622
+ /**
623
+ *
624
+ * @param {FileSystemFileHandle} handle
625
+ * @returns
626
+ */
627
+ const getFile = handle => {
628
+ return handle.getFile();
637
629
  };
638
630
 
639
- const Two = '2.0';
640
- class AssertionError extends Error {
641
- constructor(message) {
642
- super(message);
643
- this.name = 'AssertionError';
631
+ const dirname = (pathSeparator, path) => {
632
+ const index = path.lastIndexOf(pathSeparator);
633
+ if (index === -1) {
634
+ return path;
644
635
  }
636
+ return path.slice(0, index);
637
+ };
638
+
639
+ const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c);
640
+ let idbProxyableTypes;
641
+ let cursorAdvanceMethods;
642
+ // This is a function to prevent it throwing up in node environments.
643
+ function getIdbProxyableTypes() {
644
+ return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]);
645
645
  }
646
- const getType$1 = value => {
647
- switch (typeof value) {
648
- case 'number':
649
- return 'number';
650
- case 'function':
651
- return 'function';
652
- case 'string':
653
- return 'string';
654
- case 'object':
655
- if (value === null) {
656
- return 'null';
657
- }
658
- if (Array.isArray(value)) {
659
- return 'array';
646
+ // This is a function to prevent it throwing up in node environments.
647
+ function getCursorAdvanceMethods() {
648
+ return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]);
649
+ }
650
+ const transactionDoneMap = new WeakMap();
651
+ const transformCache = new WeakMap();
652
+ const reverseTransformCache = new WeakMap();
653
+ function promisifyRequest(request) {
654
+ const promise = new Promise((resolve, reject) => {
655
+ const unlisten = () => {
656
+ request.removeEventListener('success', success);
657
+ request.removeEventListener('error', error);
658
+ };
659
+ const success = () => {
660
+ resolve(wrap(request.result));
661
+ unlisten();
662
+ };
663
+ const error = () => {
664
+ reject(request.error);
665
+ unlisten();
666
+ };
667
+ request.addEventListener('success', success);
668
+ request.addEventListener('error', error);
669
+ });
670
+ // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
671
+ // is because we create many promises from a single IDBRequest.
672
+ reverseTransformCache.set(promise, request);
673
+ return promise;
674
+ }
675
+ function cacheDonePromiseForTransaction(tx) {
676
+ // Early bail if we've already created a done promise for this transaction.
677
+ if (transactionDoneMap.has(tx)) return;
678
+ const done = new Promise((resolve, reject) => {
679
+ const unlisten = () => {
680
+ tx.removeEventListener('complete', complete);
681
+ tx.removeEventListener('error', error);
682
+ tx.removeEventListener('abort', error);
683
+ };
684
+ const complete = () => {
685
+ resolve();
686
+ unlisten();
687
+ };
688
+ const error = () => {
689
+ reject(tx.error || new DOMException('AbortError', 'AbortError'));
690
+ unlisten();
691
+ };
692
+ tx.addEventListener('complete', complete);
693
+ tx.addEventListener('error', error);
694
+ tx.addEventListener('abort', error);
695
+ });
696
+ // Cache it for later retrieval.
697
+ transactionDoneMap.set(tx, done);
698
+ }
699
+ let idbProxyTraps = {
700
+ get(target, prop, receiver) {
701
+ if (target instanceof IDBTransaction) {
702
+ // Special handling for transaction.done.
703
+ if (prop === 'done') return transactionDoneMap.get(target);
704
+ // Make tx.store return the only store in the transaction, or undefined if there are many.
705
+ if (prop === 'store') {
706
+ return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]);
660
707
  }
661
- return 'object';
662
- case 'boolean':
663
- return 'boolean';
664
- default:
665
- return 'unknown';
666
- }
667
- };
668
- const number = value => {
669
- const type = getType$1(value);
670
- if (type !== 'number') {
671
- throw new AssertionError('expected value to be of type number');
708
+ }
709
+ // Else transform whatever we get back.
710
+ return wrap(target[prop]);
711
+ },
712
+ set(target, prop, value) {
713
+ target[prop] = value;
714
+ return true;
715
+ },
716
+ has(target, prop) {
717
+ if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) {
718
+ return true;
719
+ }
720
+ return prop in target;
672
721
  }
673
722
  };
674
- const state$1 = {
675
- callbacks: Object.create(null)
676
- };
677
- const set = (id, fn) => {
678
- state$1.callbacks[id] = fn;
679
- };
680
- const get = id => {
681
- return state$1.callbacks[id];
682
- };
683
- const remove = id => {
684
- delete state$1.callbacks[id];
685
- };
686
- const state = {
687
- id: 0
688
- };
689
- const create$3 = () => {
690
- return ++state.id;
691
- };
692
- const warn = (...args) => {
693
- console.warn(...args);
694
- };
695
- const withResolvers$1 = () => {
696
- /**
697
- * @type {any}
698
- */
699
- let _resolve;
700
- const promise = new Promise(resolve => {
701
- _resolve = resolve;
702
- });
703
- return {
704
- resolve: _resolve,
705
- promise
706
- };
707
- };
708
- const registerPromise = () => {
709
- const id = create$3();
710
- const {
711
- resolve,
712
- promise
713
- } = withResolvers$1();
714
- set(id, resolve);
715
- return {
716
- id,
717
- promise
718
- };
719
- };
720
- const resolve = (id, args) => {
721
- number(id);
722
- const fn = get(id);
723
- if (!fn) {
724
- console.log(args);
725
- warn(`callback ${id} may already be disposed`);
726
- return;
723
+ function replaceTraps(callback) {
724
+ idbProxyTraps = callback(idbProxyTraps);
725
+ }
726
+ function wrapFunction(func) {
727
+ // Due to expected object equality (which is enforced by the caching in `wrap`), we
728
+ // only create one new func per func.
729
+ // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
730
+ // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
731
+ // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
732
+ // with real promises, so each advance methods returns a new promise for the cursor object, or
733
+ // undefined if the end of the cursor has been reached.
734
+ if (getCursorAdvanceMethods().includes(func)) {
735
+ return function (...args) {
736
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
737
+ // the original object.
738
+ func.apply(unwrap(this), args);
739
+ return wrap(this.request);
740
+ };
727
741
  }
728
- fn(args);
729
- remove(id);
730
- };
731
- const create$2 = (method, params) => {
732
- const {
733
- id,
734
- promise
735
- } = registerPromise();
736
- const message = {
737
- jsonrpc: Two,
738
- method,
739
- params,
740
- id
741
- };
742
- return {
743
- message,
744
- promise
742
+ return function (...args) {
743
+ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
744
+ // the original object.
745
+ return wrap(func.apply(unwrap(this), args));
745
746
  };
746
- };
747
- class JsonRpcError extends Error {
748
- constructor(message) {
749
- super(message);
750
- this.name = 'JsonRpcError';
751
- }
752
747
  }
753
- const NewLine$2 = '\n';
754
- const DomException = 'DOMException';
755
- const ReferenceError$1 = 'ReferenceError';
756
- const SyntaxError$1 = 'SyntaxError';
757
- const TypeError$1 = 'TypeError';
758
- const getErrorConstructor = (message, type) => {
759
- if (type) {
760
- switch (type) {
761
- case DomException:
762
- return DOMException;
763
- case TypeError$1:
764
- return TypeError;
765
- case SyntaxError$1:
766
- return SyntaxError;
767
- case ReferenceError$1:
768
- return ReferenceError;
769
- default:
770
- return Error;
771
- }
748
+ function transformCachableValue(value) {
749
+ if (typeof value === 'function') return wrapFunction(value);
750
+ // This doesn't return, it just creates a 'done' promise for the transaction,
751
+ // which is later returned for transaction.done (see idbObjectHandler).
752
+ if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value);
753
+ if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps);
754
+ // Return the same value back if we're not going to transform it.
755
+ return value;
756
+ }
757
+ function wrap(value) {
758
+ // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
759
+ // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
760
+ if (value instanceof IDBRequest) return promisifyRequest(value);
761
+ // If we've already transformed this value before, reuse the transformed value.
762
+ // This is faster, but it also provides object equality.
763
+ if (transformCache.has(value)) return transformCache.get(value);
764
+ const newValue = transformCachableValue(value);
765
+ // Not all types are transformed.
766
+ // These may be primitive types, so they can't be WeakMap keys.
767
+ if (newValue !== value) {
768
+ transformCache.set(value, newValue);
769
+ reverseTransformCache.set(newValue, value);
772
770
  }
773
- if (message.startsWith('TypeError: ')) {
774
- return TypeError;
771
+ return newValue;
772
+ }
773
+ const unwrap = value => reverseTransformCache.get(value);
774
+
775
+ /**
776
+ * Open a database.
777
+ *
778
+ * @param name Name of the database.
779
+ * @param version Schema version.
780
+ * @param callbacks Additional callbacks.
781
+ */
782
+ function openDB(name, version, {
783
+ blocked,
784
+ upgrade,
785
+ blocking,
786
+ terminated
787
+ } = {}) {
788
+ const request = indexedDB.open(name, version);
789
+ const openPromise = wrap(request);
790
+ if (upgrade) {
791
+ request.addEventListener('upgradeneeded', event => {
792
+ upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
793
+ });
775
794
  }
776
- if (message.startsWith('SyntaxError: ')) {
777
- return SyntaxError;
795
+ if (blocked) {
796
+ request.addEventListener('blocked', event => blocked(
797
+ // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
798
+ event.oldVersion, event.newVersion, event));
778
799
  }
779
- if (message.startsWith('ReferenceError: ')) {
780
- return ReferenceError;
800
+ openPromise.then(db => {
801
+ if (terminated) db.addEventListener('close', () => terminated());
802
+ if (blocking) {
803
+ db.addEventListener('versionchange', event => blocking(event.oldVersion, event.newVersion, event));
804
+ }
805
+ }).catch(() => {});
806
+ return openPromise;
807
+ }
808
+ const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
809
+ const writeMethods = ['put', 'add', 'delete', 'clear'];
810
+ const cachedMethods = new Map();
811
+ function getMethod(target, prop) {
812
+ if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) {
813
+ return;
781
814
  }
782
- return Error;
783
- };
784
- const constructError = (message, type, name) => {
785
- const ErrorConstructor = getErrorConstructor(message, type);
786
- if (ErrorConstructor === DOMException && name) {
787
- return new ErrorConstructor(message, name);
815
+ if (cachedMethods.get(prop)) return cachedMethods.get(prop);
816
+ const targetFuncName = prop.replace(/FromIndex$/, '');
817
+ const useIndex = prop !== targetFuncName;
818
+ const isWrite = writeMethods.includes(targetFuncName);
819
+ if (
820
+ // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
821
+ !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) {
822
+ return;
788
823
  }
789
- if (ErrorConstructor === Error) {
790
- const error = new Error(message);
791
- if (name && name !== 'VError') {
792
- error.name = name;
824
+ const method = async function (storeName, ...args) {
825
+ // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
826
+ const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
827
+ let target = tx.store;
828
+ if (useIndex) target = target.index(args.shift());
829
+ // Must reject if op rejects.
830
+ // If it's a write operation, must reject if tx.done rejects.
831
+ // Must reject with op rejection first.
832
+ // Must resolve with op value.
833
+ // Must handle both promises (no unhandled rejections)
834
+ return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0];
835
+ };
836
+ cachedMethods.set(prop, method);
837
+ return method;
838
+ }
839
+ replaceTraps(oldTraps => ({
840
+ ...oldTraps,
841
+ get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
842
+ has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop)
843
+ }));
844
+ const advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];
845
+ const methodMap = {};
846
+ const advanceResults = new WeakMap();
847
+ const ittrProxiedCursorToOriginalProxy = new WeakMap();
848
+ const cursorIteratorTraps = {
849
+ get(target, prop) {
850
+ if (!advanceMethodProps.includes(prop)) return target[prop];
851
+ let cachedFunc = methodMap[prop];
852
+ if (!cachedFunc) {
853
+ cachedFunc = methodMap[prop] = function (...args) {
854
+ advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));
855
+ };
793
856
  }
794
- return error;
857
+ return cachedFunc;
795
858
  }
796
- return new ErrorConstructor(message);
797
859
  };
798
- const getNewLineIndex$1 = (string, startIndex = undefined) => {
799
- return string.indexOf(NewLine$2, startIndex);
800
- };
801
- const getParentStack = error => {
802
- let parentStack = error.stack || error.data || error.message || '';
803
- if (parentStack.startsWith(' at')) {
804
- parentStack = error.message + NewLine$2 + parentStack;
860
+ async function* iterate(...args) {
861
+ // tslint:disable-next-line:no-this-assignment
862
+ let cursor = this;
863
+ if (!(cursor instanceof IDBCursor)) {
864
+ cursor = await cursor.openCursor(...args);
805
865
  }
806
- return parentStack;
807
- };
808
- const joinLines$1 = lines => {
809
- return lines.join(NewLine$2);
810
- };
811
- const MethodNotFound = -32601;
812
- const Custom = -32001;
813
- const splitLines$1 = lines => {
814
- return lines.split(NewLine$2);
815
- };
816
- const restoreJsonRpcError = error => {
817
- if (error && error instanceof Error) {
818
- return error;
866
+ if (!cursor) return;
867
+ cursor = cursor;
868
+ const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);
869
+ ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);
870
+ // Map this double-proxy back to the original, so other cursor methods work.
871
+ reverseTransformCache.set(proxiedCursor, unwrap(cursor));
872
+ while (cursor) {
873
+ yield proxiedCursor;
874
+ // If one of the advancing methods was not called, call continue().
875
+ cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());
876
+ advanceResults.delete(proxiedCursor);
819
877
  }
820
- const currentStack = joinLines$1(splitLines$1(new Error().stack || '').slice(1));
821
- if (error && error.code && error.code === MethodNotFound) {
822
- const restoredError = new JsonRpcError(error.message);
823
- const parentStack = getParentStack(error);
824
- restoredError.stack = parentStack + NewLine$2 + currentStack;
825
- return restoredError;
878
+ }
879
+ function isIteratorProp(target, prop) {
880
+ return prop === Symbol.asyncIterator && instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor]) || prop === 'iterate' && instanceOfAny(target, [IDBIndex, IDBObjectStore]);
881
+ }
882
+ replaceTraps(oldTraps => ({
883
+ ...oldTraps,
884
+ get(target, prop, receiver) {
885
+ if (isIteratorProp(target, prop)) return iterate;
886
+ return oldTraps.get(target, prop, receiver);
887
+ },
888
+ has(target, prop) {
889
+ return isIteratorProp(target, prop) || oldTraps.has(target, prop);
826
890
  }
827
- if (error && error.message) {
828
- const restoredError = constructError(error.message, error.type, error.name);
829
- if (error.data) {
830
- if (error.data.stack && error.data.type && error.message) {
831
- restoredError.stack = error.data.type + ': ' + error.message + NewLine$2 + error.data.stack + NewLine$2 + currentStack;
832
- } else if (error.data.stack) {
833
- restoredError.stack = error.data.stack;
834
- }
835
- if (error.data.codeFrame) {
836
- // @ts-ignore
837
- restoredError.codeFrame = error.data.codeFrame;
838
- }
839
- if (error.data.code) {
840
- // @ts-ignore
841
- restoredError.code = error.data.code;
842
- }
843
- if (error.data.type) {
844
- // @ts-ignore
845
- restoredError.name = error.data.type;
846
- }
847
- } else {
848
- if (error.stack) {
849
- const lowerStack = restoredError.stack || '';
850
- // @ts-ignore
851
- const indexNewLine = getNewLineIndex$1(lowerStack);
852
- const parentStack = getParentStack(error);
853
- // @ts-ignore
854
- restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
855
- }
856
- if (error.codeFrame) {
891
+ }));
892
+
893
+ const state = {
894
+ databases: Object.create(null),
895
+ eventId: 0,
896
+ dbVersion: 1,
897
+ cachedDb: undefined
898
+ };
899
+
900
+ // TODO high memory usage in idb because of transactionDoneMap
901
+
902
+ const getHandleDb = async () => {
903
+ // @ts-ignore
904
+ const db = await openDB('handle', state.dbVersion, {
905
+ async upgrade(db, oldVersion) {
906
+ if (!db.objectStoreNames.contains('file-handles-store')) {
857
907
  // @ts-ignore
858
- restoredError.codeFrame = error.codeFrame;
908
+ await db.createObjectStore('file-handles-store', {});
859
909
  }
860
910
  }
861
- return restoredError;
862
- }
863
- if (typeof error === 'string') {
864
- return new Error(`JsonRpc Error: ${error}`);
865
- }
866
- return new Error(`JsonRpc Error: ${error}`);
911
+ });
912
+ return db;
867
913
  };
868
- const unwrapJsonRpcResult = responseMessage => {
869
- if ('error' in responseMessage) {
870
- const restoredError = restoreJsonRpcError(responseMessage.error);
871
- throw restoredError;
872
- }
873
- if ('result' in responseMessage) {
874
- return responseMessage.result;
914
+ const getHandle$1 = async uri => {
915
+ const handleDb = await getHandleDb();
916
+ const handle = await handleDb.get('file-handles-store', uri);
917
+ return handle;
918
+ };
919
+
920
+ const getHandle = async uri => {
921
+ try {
922
+ // TODO retrieve handle from state or from indexeddb
923
+ // TODO if not found, throw error
924
+ const handle = await getHandle$1(uri);
925
+ return handle;
926
+ } catch (error) {
927
+ throw new VError$1(error, 'Failed to get handle');
875
928
  }
876
- throw new JsonRpcError('unexpected response message');
877
929
  };
878
- const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
879
- const getType = prettyError => {
880
- if (prettyError && prettyError.type) {
881
- return prettyError.type;
930
+
931
+ const getDirectoryHandle = async uri => {
932
+ const handle = await getHandle(uri);
933
+ if (handle) {
934
+ return handle;
882
935
  }
883
- if (prettyError && prettyError.constructor && prettyError.constructor.name) {
884
- return prettyError.constructor.name;
936
+ const dirname$1 = dirname('/', uri);
937
+ if (uri === dirname$1) {
938
+ return undefined;
885
939
  }
886
- return undefined;
940
+ return getDirectoryHandle(dirname$1);
887
941
  };
888
- const getErrorProperty = (error, prettyError) => {
889
- if (error && error.code === E_COMMAND_NOT_FOUND) {
890
- return {
891
- code: MethodNotFound,
892
- message: error.message,
893
- data: error.stack
894
- };
895
- }
896
- return {
897
- code: Custom,
898
- message: prettyError.message,
899
- data: {
900
- stack: prettyError.stack,
901
- codeFrame: prettyError.codeFrame,
902
- type: getType(prettyError),
903
- code: prettyError.code,
904
- name: prettyError.name
942
+ const textSearchInText = (file, content, query) => {
943
+ const results = [];
944
+ const lines = splitLines$1(content);
945
+ for (let i = 0; i < lines.length; i++) {
946
+ const line = lines[i];
947
+ const index = line.indexOf(query);
948
+ if (index !== -1) {
949
+ results.push({
950
+ type: Match,
951
+ text: line,
952
+ start: index,
953
+ end: index + query.length,
954
+ lineNumber: i
955
+ });
905
956
  }
906
- };
907
- };
908
- const create$1 = (message, error) => {
909
- return {
910
- jsonrpc: Two,
911
- id: message.id,
912
- error
913
- };
914
- };
915
- const getErrorResponse = (message, error, preparePrettyError, logError) => {
916
- const prettyError = preparePrettyError(error);
917
- logError(error, prettyError);
918
- const errorProperty = getErrorProperty(error, prettyError);
919
- return create$1(message, errorProperty);
920
- };
921
- const create = (message, result) => {
922
- return {
923
- jsonrpc: Two,
924
- id: message.id,
925
- result: result ?? null
926
- };
927
- };
928
- const getSuccessResponse = (message, result) => {
929
- const resultProperty = result ?? null;
930
- return create(message, resultProperty);
957
+ }
958
+ if (results.length > 0) {
959
+ results.unshift({
960
+ type: File$1,
961
+ text: file,
962
+ start: 0,
963
+ end: 0,
964
+ lineNumber: 0
965
+ });
966
+ }
967
+ return results;
931
968
  };
932
- const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
969
+ const textSearchInFile = async (all, handle, absolutePath, query) => {
933
970
  try {
934
- const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
935
- return getSuccessResponse(message, result);
971
+ const file = await getFile(handle);
972
+ const content = await file.text();
973
+ const results = textSearchInText(absolutePath, content, query);
974
+ push(all, results);
936
975
  } catch (error) {
937
- return getErrorResponse(message, error, preparePrettyError, logError);
938
- }
939
- };
940
- const defaultPreparePrettyError = error => {
941
- return error;
942
- };
943
- const defaultLogError = () => {
944
- // ignore
945
- };
946
- const defaultRequiresSocket = () => {
947
- return false;
948
- };
949
- const defaultResolve = resolve;
950
- const handleJsonRpcMessage = async (...args) => {
951
- let message;
952
- let ipc;
953
- let execute;
954
- let preparePrettyError;
955
- let logError;
956
- let resolve;
957
- let requiresSocket;
958
- if (args.length === 1) {
959
- const arg = args[0];
960
- message = arg.message;
961
- ipc = arg.ipc;
962
- execute = arg.execute;
963
- preparePrettyError = arg.preparePrettyError || defaultPreparePrettyError;
964
- logError = arg.logError || defaultLogError;
965
- requiresSocket = arg.requiresSocket || defaultRequiresSocket;
966
- resolve = arg.resolve || defaultResolve;
967
- } else {
968
- ipc = args[0];
969
- message = args[1];
970
- execute = args[2];
971
- resolve = args[3];
972
- preparePrettyError = args[4];
973
- logError = args[5];
974
- requiresSocket = args[6];
975
- }
976
- if ('id' in message) {
977
- if ('method' in message) {
978
- const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
979
- try {
980
- ipc.send(response);
981
- } catch (error) {
982
- const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
983
- ipc.send(errorResponse);
984
- }
976
+ if (isNotReadableError(error)) {
977
+ // ignore
985
978
  return;
986
979
  }
987
- resolve(message.id, message);
988
- return;
980
+ throw error;
989
981
  }
990
- if ('method' in message) {
991
- await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
992
- return;
982
+ };
983
+ const textSearchRecursively = async (all, parent, handle, query) => {
984
+ const childHandles = [];
985
+ // TODO
986
+ // await FileSystemHtml.getChildHandles(handle)
987
+ const promises = [];
988
+ for (const childHandle of childHandles) {
989
+ const absolutePath = parent + '/' + childHandle.name;
990
+ switch (childHandle.kind) {
991
+ case Directory:
992
+ promises.push(textSearchRecursively(all, absolutePath, childHandle, query));
993
+ break;
994
+ case File:
995
+ promises.push(textSearchInFile(all, childHandle, absolutePath, query));
996
+ break;
997
+ }
993
998
  }
994
- throw new JsonRpcError('unexpected message');
999
+ await Promise.all(promises);
995
1000
  };
996
- const invoke$2 = async (ipc, method, ...params) => {
997
- const {
998
- message,
999
- promise
1000
- } = create$2(method, params);
1001
- ipc.send(message);
1002
- const responseMessage = await promise;
1003
- const result = unwrapJsonRpcResult(responseMessage);
1004
- return result;
1001
+ const textSearch$3 = async (scheme, root, query) => {
1002
+ string(scheme);
1003
+ string(root);
1004
+ string(query);
1005
+ const relativeRoot = root.slice('html://'.length);
1006
+ const handle = await getDirectoryHandle(relativeRoot);
1007
+ if (!handle) {
1008
+ // @ts-ignore
1009
+ throw new VError$1(`Folder not found ${relativeRoot}`);
1010
+ }
1011
+ const all = [];
1012
+ await textSearchRecursively(all, '', handle, query);
1013
+ return all;
1005
1014
  };
1006
1015
 
1007
- const invoke$1 = (method, ...params) => {
1008
- const ipc = get$1();
1009
- return invoke$2(ipc, method, ...params);
1010
- };
1011
- const listen$2 = ipc => {
1012
- set$1(ipc);
1016
+ const getRipGrepArgs = ({
1017
+ threads,
1018
+ isCaseSensitive,
1019
+ searchString,
1020
+ useRegularExpression
1021
+ }) => {
1022
+ const ripGrepArgs = ['--hidden', '--no-require-git', '--smart-case', '--stats', '--json'];
1023
+ ripGrepArgs.push('--threads', `${threads}`);
1024
+ if (isCaseSensitive) {
1025
+ ripGrepArgs.push('--case-sensitive');
1026
+ } else {
1027
+ ripGrepArgs.push('--ignore-case');
1028
+ }
1029
+ if (useRegularExpression) {
1030
+ ripGrepArgs.push('--regexp', searchString);
1031
+ } else {
1032
+ ripGrepArgs.push('--fixed-strings');
1033
+ ripGrepArgs.push('--');
1034
+ ripGrepArgs.push(searchString);
1035
+ }
1036
+ ripGrepArgs.push('.');
1037
+ return ripGrepArgs;
1013
1038
  };
1014
1039
 
1015
1040
  const invoke = (method, ...params) => {
@@ -1061,12 +1086,12 @@ const getProvider = scheme => {
1061
1086
  }
1062
1087
  };
1063
1088
 
1064
- const textSearch = async (root, query, options) => {
1089
+ const textSearch = async (root, query, options, assetDir) => {
1065
1090
  string(root);
1066
1091
  string(query);
1067
1092
  const scheme = getProtocol(root);
1068
1093
  const provider = getProvider(scheme);
1069
- const results = await provider(scheme, root, query, options);
1094
+ const results = await provider(scheme, root, query, options, assetDir);
1070
1095
  return results;
1071
1096
  };
1072
1097