@parcel/workers 2.0.0-beta.3 → 2.0.0-dev.1510

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.
package/lib/backend.js CHANGED
@@ -5,31 +5,29 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.detectBackend = detectBackend;
7
7
  exports.getWorkerBackend = getWorkerBackend;
8
-
9
8
  function detectBackend() {
9
+ // $FlowFixMe
10
+ if (process.browser) return 'web';
10
11
  switch (process.env.PARCEL_WORKER_BACKEND) {
11
12
  case 'threads':
12
13
  case 'process':
13
14
  return process.env.PARCEL_WORKER_BACKEND;
14
15
  }
15
-
16
16
  try {
17
17
  require('worker_threads');
18
-
19
18
  return 'threads';
20
19
  } catch (err) {
21
20
  return 'process';
22
21
  }
23
22
  }
24
-
25
23
  function getWorkerBackend(backend) {
26
24
  switch (backend) {
27
25
  case 'threads':
28
26
  return require('./threads/ThreadsWorker').default;
29
-
30
27
  case 'process':
31
28
  return require('./process/ProcessWorker').default;
32
-
29
+ case 'web':
30
+ return require('./web/WebWorker').default;
33
31
  default:
34
32
  throw new Error(`Invalid backend: ${backend}`);
35
33
  }
package/lib/bus.js CHANGED
@@ -4,46 +4,28 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
-
8
7
  function _events() {
9
8
  const data = _interopRequireDefault(require("events"));
10
-
11
9
  _events = function () {
12
10
  return data;
13
11
  };
14
-
15
- return data;
16
- }
17
-
18
- function _childState() {
19
- const data = require("./childState");
20
-
21
- _childState = function () {
22
- return data;
23
- };
24
-
25
12
  return data;
26
13
  }
27
-
14
+ var _childState = require("./childState");
28
15
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29
-
30
16
  class Bus extends _events().default {
31
17
  emit(event, ...args) {
32
- if (_childState().child) {
33
- _childState().child.workerApi.callMaster({
34
- location: __filename,
18
+ if (_childState.child) {
19
+ _childState.child.workerApi.callMaster({
20
+ // $FlowFixMe
21
+ location: process.browser ? '@parcel/workers/src/bus.js' : __filename,
35
22
  method: 'emit',
36
23
  args: [event, ...args]
37
24
  }, false);
38
-
39
25
  return true;
40
26
  } else {
41
27
  return super.emit(event, ...args);
42
28
  }
43
29
  }
44
-
45
30
  }
46
-
47
- var _default = new Bus();
48
-
49
- exports.default = _default;
31
+ var _default = exports.default = new Bus();
package/lib/child.js CHANGED
@@ -4,145 +4,89 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Child = void 0;
7
-
7
+ var coreWorker = _interopRequireWildcard(require("./core-worker"));
8
8
  function _assert() {
9
9
  const data = _interopRequireDefault(require("assert"));
10
-
11
10
  _assert = function () {
12
11
  return data;
13
12
  };
14
-
15
13
  return data;
16
14
  }
17
-
18
15
  function _nullthrows() {
19
16
  const data = _interopRequireDefault(require("nullthrows"));
20
-
21
17
  _nullthrows = function () {
22
18
  return data;
23
19
  };
24
-
25
20
  return data;
26
21
  }
27
-
28
22
  function _logger() {
29
23
  const data = _interopRequireWildcard(require("@parcel/logger"));
30
-
31
24
  _logger = function () {
32
25
  return data;
33
26
  };
34
-
35
27
  return data;
36
28
  }
37
-
38
29
  function _diagnostic() {
39
30
  const data = _interopRequireWildcard(require("@parcel/diagnostic"));
40
-
41
31
  _diagnostic = function () {
42
32
  return data;
43
33
  };
44
-
45
34
  return data;
46
35
  }
47
-
48
36
  function _core() {
49
37
  const data = require("@parcel/core");
50
-
51
38
  _core = function () {
52
39
  return data;
53
40
  };
54
-
55
- return data;
56
- }
57
-
58
- function _bus() {
59
- const data = _interopRequireDefault(require("./bus"));
60
-
61
- _bus = function () {
62
- return data;
63
- };
64
-
65
- return data;
66
- }
67
-
68
- function _Profiler() {
69
- const data = _interopRequireDefault(require("./Profiler"));
70
-
71
- _Profiler = function () {
72
- return data;
73
- };
74
-
75
41
  return data;
76
42
  }
77
-
78
- function _Handle2() {
79
- const data = _interopRequireDefault(require("./Handle"));
80
-
81
- _Handle2 = function () {
43
+ var _bus = _interopRequireDefault(require("./bus"));
44
+ function _profiler() {
45
+ const data = require("@parcel/profiler");
46
+ _profiler = function () {
82
47
  return data;
83
48
  };
84
-
85
49
  return data;
86
50
  }
87
-
88
- function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
89
-
90
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
91
-
51
+ var _Handle2 = _interopRequireDefault(require("./Handle"));
92
52
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
93
-
94
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
95
-
53
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
54
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
96
55
  // The import of './Handle' should really be imported eagerly (with @babel/plugin-transform-modules-commonjs's lazy mode).
97
- const Handle = _Handle2().default;
98
-
56
+ const Handle = _Handle2.default;
99
57
  class Child {
58
+ callQueue = [];
59
+ maxConcurrentCalls = 10;
60
+ responseId = 0;
61
+ responseQueue = new Map();
62
+ handles = new Map();
63
+ sharedReferences = new Map();
64
+ sharedReferencesByValue = new Map();
100
65
  constructor(ChildBackend) {
101
- _defineProperty(this, "callQueue", []);
102
-
103
- _defineProperty(this, "childId", void 0);
104
-
105
- _defineProperty(this, "maxConcurrentCalls", 10);
106
-
107
- _defineProperty(this, "module", void 0);
108
-
109
- _defineProperty(this, "responseId", 0);
110
-
111
- _defineProperty(this, "responseQueue", new Map());
112
-
113
- _defineProperty(this, "loggerDisposable", void 0);
114
-
115
- _defineProperty(this, "child", void 0);
116
-
117
- _defineProperty(this, "profiler", void 0);
66
+ this.child = new ChildBackend(m => {
67
+ this.messageListener(m);
68
+ }, () => this.handleEnd());
118
69
 
119
- _defineProperty(this, "workerApi", void 0);
120
-
121
- _defineProperty(this, "handles", new Map());
122
-
123
- _defineProperty(this, "sharedReferences", new Map());
124
-
125
- _defineProperty(this, "sharedReferencesByValue", new Map());
126
-
127
- _defineProperty(this, "workerApi", {
128
- callMaster: (request, awaitResponse = true) => this.addCall(request, awaitResponse),
129
- createReverseHandle: fn => this.createReverseHandle(fn),
130
- runHandle: (handle, args) => this.workerApi.callMaster({
131
- handle: handle.id,
132
- args
133
- }, true),
134
- getSharedReference: ref => this.sharedReferences.get(ref),
135
- resolveSharedReference: value => this.sharedReferencesByValue.get(value)
136
- });
137
-
138
- this.child = new ChildBackend(this.messageListener.bind(this), this.handleEnd.bind(this)); // Monitior all logging events inside this child process and forward to
70
+ // Monitior all logging events inside this child process and forward to
139
71
  // the main process via the bus.
140
-
141
72
  this.loggerDisposable = _logger().default.onLog(event => {
142
- _bus().default.emit('logEvent', event);
73
+ _bus.default.emit('logEvent', event);
74
+ });
75
+ // .. and do the same for trace events
76
+ this.tracerDisposable = _profiler().tracer.onTrace(event => {
77
+ _bus.default.emit('traceEvent', event);
143
78
  });
144
79
  }
145
-
80
+ workerApi = {
81
+ callMaster: (request, awaitResponse = true) => this.addCall(request, awaitResponse),
82
+ createReverseHandle: fn => this.createReverseHandle(fn),
83
+ runHandle: (handle, args) => this.workerApi.callMaster({
84
+ handle: handle.id,
85
+ args
86
+ }, true),
87
+ getSharedReference: ref => this.sharedReferences.get(ref),
88
+ resolveSharedReference: value => this.sharedReferencesByValue.get(value)
89
+ };
146
90
  messageListener(message) {
147
91
  if (message.type === 'response') {
148
92
  return this.handleResponse(message);
@@ -150,17 +94,26 @@ class Child {
150
94
  return this.handleRequest(message);
151
95
  }
152
96
  }
153
-
154
97
  send(data) {
155
98
  this.child.send(data);
156
99
  }
157
-
158
- childInit(module, childId) {
159
- // $FlowFixMe this must be dynamic
160
- this.module = require(module);
100
+ async childInit(module, childId) {
101
+ // $FlowFixMe
102
+ if (process.browser) {
103
+ if (module === '@parcel/core/src/worker.js') {
104
+ this.module = coreWorker;
105
+ } else {
106
+ throw new Error('No dynamic require possible: ' + module);
107
+ }
108
+ } else {
109
+ // $FlowFixMe this must be dynamic
110
+ this.module = require(module);
111
+ }
161
112
  this.childId = childId;
113
+ if (this.module.childInit != null) {
114
+ await this.module.childInit();
115
+ }
162
116
  }
163
-
164
117
  async handleRequest(data) {
165
118
  let {
166
119
  idx,
@@ -169,7 +122,6 @@ class Child {
169
122
  handle: handleId
170
123
  } = data;
171
124
  let child = (0, _nullthrows().default)(data.child);
172
-
173
125
  const responseFromContent = content => ({
174
126
  idx,
175
127
  child,
@@ -177,7 +129,6 @@ class Child {
177
129
  contentType: 'data',
178
130
  content
179
131
  });
180
-
181
132
  const errorResponseFromError = e => ({
182
133
  idx,
183
134
  child,
@@ -185,13 +136,10 @@ class Child {
185
136
  contentType: 'error',
186
137
  content: (0, _diagnostic().anyToDiagnostic)(e)
187
138
  });
188
-
189
139
  let result;
190
-
191
140
  if (handleId != null) {
192
141
  try {
193
142
  var _this$handles$get;
194
-
195
143
  let fn = (0, _nullthrows().default)((_this$handles$get = this.handles.get(handleId)) === null || _this$handles$get === void 0 ? void 0 : _this$handles$get.fn);
196
144
  result = responseFromContent(fn(...args));
197
145
  } catch (e) {
@@ -200,20 +148,20 @@ class Child {
200
148
  } else if (method === 'childInit') {
201
149
  try {
202
150
  let [moduleName, childOptions] = args;
203
-
204
151
  if (childOptions.shouldPatchConsole) {
205
152
  (0, _logger().patchConsole)();
206
153
  } else {
207
154
  (0, _logger().unpatchConsole)();
208
155
  }
209
-
210
- result = responseFromContent(this.childInit(moduleName, child));
156
+ if (childOptions.shouldTrace) {
157
+ _profiler().tracer.enable();
158
+ }
159
+ result = responseFromContent(await this.childInit(moduleName, child));
211
160
  } catch (e) {
212
161
  result = errorResponseFromError(e);
213
162
  }
214
163
  } else if (method === 'startProfile') {
215
- this.profiler = new (_Profiler().default)();
216
-
164
+ this.profiler = new (_profiler().SamplingProfiler)();
217
165
  try {
218
166
  result = responseFromContent(await this.profiler.startProfiling());
219
167
  } catch (e) {
@@ -229,15 +177,14 @@ class Child {
229
177
  } else if (method === 'takeHeapSnapshot') {
230
178
  try {
231
179
  let v8 = require('v8');
232
-
233
- result = responseFromContent( // $FlowFixMe
234
- v8.writeHeapSnapshot('heap-' + args[0] + '-' + (this.childId ? 'worker' + this.childId : 'main') + '.heapsnapshot'));
180
+ result = responseFromContent(v8.writeHeapSnapshot('heap-' + args[0] + '-' + (this.childId ? 'worker' + this.childId : 'main') + '.heapsnapshot'));
235
181
  } catch (e) {
236
182
  result = errorResponseFromError(e);
237
183
  }
238
184
  } else if (method === 'createSharedReference') {
239
185
  let [ref, _value] = args;
240
- let value = _value instanceof ArrayBuffer ? // In the case the value is pre-serialized as a buffer,
186
+ let value = _value instanceof ArrayBuffer ?
187
+ // In the case the value is pre-serialized as a buffer,
241
188
  // deserialize it.
242
189
  (0, _core().deserialize)(Buffer.from(_value)) : _value;
243
190
  this.sharedReferences.set(ref, value);
@@ -251,26 +198,24 @@ class Child {
251
198
  result = responseFromContent(null);
252
199
  } else {
253
200
  try {
254
- result = responseFromContent( // $FlowFixMe
201
+ result = responseFromContent(
202
+ // $FlowFixMe
255
203
  await this.module[method](this.workerApi, ...args));
256
204
  } catch (e) {
257
205
  result = errorResponseFromError(e);
258
206
  }
259
207
  }
260
-
261
208
  try {
262
209
  this.send(result);
263
210
  } catch (e) {
264
211
  result = this.send(errorResponseFromError(e));
265
212
  }
266
213
  }
267
-
268
214
  handleResponse(data) {
269
215
  let idx = (0, _nullthrows().default)(data.idx);
270
216
  let contentType = data.contentType;
271
217
  let content = data.content;
272
218
  let call = (0, _nullthrows().default)(this.responseQueue.get(idx));
273
-
274
219
  if (contentType === 'error') {
275
220
  (0, _assert().default)(typeof content !== 'string');
276
221
  call.reject(new (_diagnostic().default)({
@@ -279,18 +224,18 @@ class Child {
279
224
  } else {
280
225
  call.resolve(content);
281
226
  }
227
+ this.responseQueue.delete(idx);
282
228
 
283
- this.responseQueue.delete(idx); // Process the next call
284
-
229
+ // Process the next call
285
230
  this.processQueue();
286
- } // Keep in mind to make sure responses to these calls are JSON.Stringify safe
287
-
231
+ }
288
232
 
233
+ // Keep in mind to make sure responses to these calls are JSON.Stringify safe
289
234
  addCall(request, awaitResponse = true) {
290
235
  var _promise;
291
-
292
236
  // $FlowFixMe
293
- let call = { ...request,
237
+ let call = {
238
+ ...request,
294
239
  type: 'request',
295
240
  child: this.childId,
296
241
  // $FlowFixMe Added in Flow 0.121.0 upgrade in #4381
@@ -299,27 +244,22 @@ class Child {
299
244
  reject: () => {}
300
245
  };
301
246
  let promise;
302
-
303
247
  if (awaitResponse) {
304
248
  promise = new Promise((resolve, reject) => {
305
249
  call.resolve = resolve;
306
250
  call.reject = reject;
307
251
  });
308
252
  }
309
-
310
253
  this.callQueue.push(call);
311
254
  this.processQueue();
312
255
  return (_promise = promise) !== null && _promise !== void 0 ? _promise : Promise.resolve();
313
256
  }
314
-
315
257
  sendRequest(call) {
316
258
  let idx;
317
-
318
259
  if (call.awaitResponse) {
319
260
  idx = this.responseId++;
320
261
  this.responseQueue.set(idx, call);
321
262
  }
322
-
323
263
  this.send({
324
264
  idx,
325
265
  child: call.child,
@@ -331,21 +271,18 @@ class Child {
331
271
  awaitResponse: call.awaitResponse
332
272
  });
333
273
  }
334
-
335
274
  processQueue() {
336
275
  if (!this.callQueue.length) {
337
276
  return;
338
277
  }
339
-
340
278
  if (this.responseQueue.size < this.maxConcurrentCalls) {
341
279
  this.sendRequest(this.callQueue.shift());
342
280
  }
343
281
  }
344
-
345
282
  handleEnd() {
346
283
  this.loggerDisposable.dispose();
284
+ this.tracerDisposable.dispose();
347
285
  }
348
-
349
286
  createReverseHandle(fn) {
350
287
  let handle = new Handle({
351
288
  fn,
@@ -354,7 +291,5 @@ class Child {
354
291
  this.handles.set(handle.id, handle);
355
292
  return handle;
356
293
  }
357
-
358
294
  }
359
-
360
295
  exports.Child = Child;
package/lib/childState.js CHANGED
@@ -3,14 +3,12 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.setChild = setChild;
7
6
  exports.child = void 0;
7
+ exports.setChild = setChild;
8
8
  // This file is imported by both the WorkerFarm and child implementation.
9
9
  // When a worker is inited, it sets the state in this file.
10
10
  // This way, WorkerFarm can access the state without directly importing the child code.
11
- let child = null;
12
- exports.child = child;
13
-
11
+ let child = exports.child = null;
14
12
  function setChild(c) {
15
13
  exports.child = child = c;
16
14
  }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+
3
+ // eslint-disable-next-line monorepo/no-internal-import
4
+ module.exports = require('@parcel/core/src/worker.js');
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+
3
+ // This is used only in browser builds
4
+ module.exports = {};
package/lib/cpuCount.js CHANGED
@@ -3,31 +3,23 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.detectRealCores = detectRealCores;
7
6
  exports.default = getCores;
8
-
7
+ exports.detectRealCores = detectRealCores;
9
8
  function _os() {
10
9
  const data = _interopRequireDefault(require("os"));
11
-
12
10
  _os = function () {
13
11
  return data;
14
12
  };
15
-
16
13
  return data;
17
14
  }
18
-
19
15
  function _child_process() {
20
16
  const data = require("child_process");
21
-
22
17
  _child_process = function () {
23
18
  return data;
24
19
  };
25
-
26
20
  return data;
27
21
  }
28
-
29
22
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30
-
31
23
  const exec = command => {
32
24
  try {
33
25
  let stdout = (0, _child_process().execSync)(command, {
@@ -40,50 +32,48 @@ const exec = command => {
40
32
  return '';
41
33
  }
42
34
  };
43
-
44
35
  function detectRealCores() {
45
36
  let platform = _os().default.platform();
46
-
47
37
  let amount = 0;
48
-
49
38
  if (platform === 'linux') {
50
39
  amount = parseInt(exec('lscpu -p | egrep -v "^#" | sort -u -t, -k 2,4 | wc -l'), 10);
51
40
  } else if (platform === 'darwin') {
52
41
  amount = parseInt(exec('sysctl -n hw.physicalcpu_max'), 10);
53
42
  } else if (platform === 'win32') {
54
43
  const str = exec('wmic cpu get NumberOfCores').match(/\d+/g);
55
-
56
44
  if (str !== null) {
57
45
  amount = parseInt(str.filter(n => n !== '')[0], 10);
58
46
  }
59
47
  }
60
-
61
48
  if (!amount || amount <= 0) {
62
49
  throw new Error('Could not detect cpu count!');
63
50
  }
64
-
65
51
  return amount;
66
52
  }
67
-
68
53
  let cores;
69
-
70
54
  function getCores(bypassCache = false) {
71
55
  // Do not re-run commands if we already have the count...
72
56
  if (cores && !bypassCache) {
73
57
  return cores;
74
58
  }
75
59
 
76
- try {
77
- cores = detectRealCores();
78
- } catch (e) {
79
- // Guess the amount of real cores
80
- cores = _os().default.cpus().filter((cpu, index) => !cpu.model.includes('Intel') || index % 2 === 1).length;
81
- } // Another fallback
82
-
60
+ // $FlowFixMe
61
+ if (process.browser) {
62
+ // eslint-disable-next-line no-undef
63
+ cores = navigator.hardwareConcurrency / 2;
64
+ }
65
+ if (!cores) {
66
+ try {
67
+ cores = detectRealCores();
68
+ } catch (e) {
69
+ // Guess the amount of real cores
70
+ cores = _os().default.cpus().filter((cpu, index) => !cpu.model.includes('Intel') || index % 2 === 1).length;
71
+ }
72
+ }
83
73
 
74
+ // Another fallback
84
75
  if (!cores) {
85
76
  cores = 1;
86
77
  }
87
-
88
78
  return cores;
89
79
  }