@e-mc/watch 0.5.3 → 0.6.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 (3) hide show
  1. package/filegroup/index.js +36 -17
  2. package/index.js +446 -417
  3. package/package.json +4 -4
@@ -1,10 +1,13 @@
1
1
  "use strict";
2
- var _a, _b, _c, _d, _e;
2
+ var _a, _b, _c, _d, _e, _f;
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
+ const util = require("util");
5
+ const ws = require("ws");
4
6
  const types_1 = require("../../types");
5
7
  const core_1 = require("../../core");
6
- const kPaused = Symbol('paused');
7
8
  const kServer = Symbol('server');
9
+ const kStarted = Symbol('started');
10
+ const kPaused = Symbol('paused');
8
11
  const kAssets = Symbol('assets');
9
12
  const kSockets = Symbol('sockets');
10
13
  const kStartTime = Symbol('startTime');
@@ -24,21 +27,23 @@ class SocketRequest {
24
27
  }
25
28
  class FileGroup extends core_1.AbortComponent {
26
29
  static checkTimeout(client) {
27
- if (client.readyState === 1) {
28
- const lastTime = FileGroup.CLIENT_SESSION.get(client);
29
- if (!lastTime) {
30
- FileGroup.CLIENT_SESSION.set(client, Date.now());
31
- }
32
- else if (FileGroup.CONNECTION_TIMEOUT > 0 && lastTime + FileGroup.CONNECTION_TIMEOUT <= Date.now()) {
33
- client.terminate();
34
- return false;
35
- }
36
- return true;
30
+ if (client.readyState !== ws.OPEN) {
31
+ return false;
37
32
  }
38
- return false;
33
+ const session = this.CLIENT_SESSION;
34
+ const lastTime = session.get(client);
35
+ if (!lastTime) {
36
+ session.set(client, Date.now());
37
+ }
38
+ else if (lastTime + this.CONNECTION_TIMEOUT <= Date.now() && this.CONNECTION_TIMEOUT > 0) {
39
+ client.terminate();
40
+ return false;
41
+ }
42
+ return true;
39
43
  }
40
44
  static cloneAsset(file) {
41
- return (0, types_1.cloneObject)(file, (0, types_1.isPlainObject)(file.watch) && (0, types_1.isArray)(file.watch.assets) ? new WeakSet([file.watch.assets]) : true);
45
+ const watch = file.watch;
46
+ return (0, types_1.cloneObject)(file, (0, types_1.isPlainObject)(watch) && (0, types_1.isArray)(watch.assets) ? new WeakSet([watch.assets]) : true);
42
47
  }
43
48
  constructor(uri, assets, startTime, abortable) {
44
49
  super();
@@ -51,9 +56,10 @@ class FileGroup extends core_1.AbortComponent {
51
56
  this._abortable = false;
52
57
  this[_a] = null;
53
58
  this[_b] = false;
54
- this[_c] = '';
59
+ this[_c] = false;
55
60
  this[_d] = '';
56
- this[_e] = [];
61
+ this[_e] = '';
62
+ this[_f] = [];
57
63
  this[kUri] = uri;
58
64
  this[kAssets] = assets;
59
65
  if (typeof startTime === 'boolean') {
@@ -94,6 +100,16 @@ class FileGroup extends core_1.AbortComponent {
94
100
  if (server && (data.socketId = this.socketId)) {
95
101
  data.event = event;
96
102
  data.always ?? (data.always = this.always);
103
+ const value = data.value;
104
+ if (value && (util.types.isAnyArrayBuffer(value) || util.types.isArrayBufferView(value))) {
105
+ try {
106
+ data.value = Buffer.from(value).toString('base64');
107
+ data.encoding = 'base64';
108
+ }
109
+ catch {
110
+ delete data.value;
111
+ }
112
+ }
97
113
  const outgoing = JSON.stringify(data);
98
114
  server.clients.forEach(client => {
99
115
  if (FileGroup.checkTimeout(client)) {
@@ -126,6 +142,9 @@ class FileGroup extends core_1.AbortComponent {
126
142
  get startTime() {
127
143
  return this[kStartTime];
128
144
  }
145
+ get started() {
146
+ return this[kStarted] || (this[kStarted] = Date.now() >= this.startTime);
147
+ }
129
148
  get assets() {
130
149
  return this[kAssets];
131
150
  }
@@ -186,7 +205,7 @@ class FileGroup extends core_1.AbortComponent {
186
205
  return this._abortable;
187
206
  }
188
207
  }
189
- _a = kServer, _b = kPaused, _c = kEtag, _d = kLastModified, _e = kSockets;
208
+ _a = kServer, _b = kStarted, _c = kPaused, _d = kEtag, _e = kLastModified, _f = kSockets;
190
209
  FileGroup.CONNECTION_TIMEOUT = 10 * 60000 /* TIME.m */;
191
210
  FileGroup.CLIENT_SESSION = new Map();
192
211
  exports.default = FileGroup;
package/index.js CHANGED
@@ -37,12 +37,36 @@ function isConnectionTimeout(err) {
37
37
  }
38
38
  function abortTimeout(group) {
39
39
  group.timeout.aborted = true;
40
- if (group.watcher) {
41
- group.watcher.close();
40
+ const watcher = group.watcher;
41
+ if (watcher) {
42
+ watcher.close();
42
43
  group.watcher = null;
43
44
  }
44
45
  }
45
- const getInterval = ({ watch }) => Math.max((0, types_1.isObject)(watch) && watch.interval || 0, 0);
46
+ function getInterval({ watch }) {
47
+ let interval;
48
+ if ((0, types_1.isObject)(watch) && (interval = watch.interval)) {
49
+ if (typeof interval === 'string') {
50
+ interval = (0, types_1.parseTime)(interval);
51
+ }
52
+ if (interval > 0) {
53
+ return interval;
54
+ }
55
+ }
56
+ return 0;
57
+ }
58
+ function closeFileGroup(map) {
59
+ for (const uri in map) {
60
+ for (const group of map[uri].values()) {
61
+ abortTimeout(group);
62
+ }
63
+ }
64
+ }
65
+ function closeServer(map) {
66
+ for (const port in map) {
67
+ map[port].close(err => err && Watch.writeFail([`Unable to shutdown ${map === PORT_MAP ? 'WS' : 'WSS'} server`, 'port: ' + port], err));
68
+ }
69
+ }
46
70
  const formatDate = (value) => new Date(value).toLocaleString().replace(/\/20\d+, /, '@').replace(/:\d+ (AM|PM)$/, (...match) => match[1]);
47
71
  class Watch extends core_1.Client {
48
72
  static createServer(port, secure, active) {
@@ -91,39 +115,32 @@ class Watch extends core_1.Client {
91
115
  catch (err) {
92
116
  this.writeFail("Unknown" /* ERR_MESSAGE.UNKNOWN */, err);
93
117
  }
94
- if (wss) {
95
- wss.on('connection', function (socket) {
96
- socket.on('message', function () {
97
- filegroup_1.default.CLIENT_SESSION.delete(this);
98
- });
99
- socket.on('close', function () {
100
- filegroup_1.default.CLIENT_SESSION.delete(this);
101
- });
102
- this.clients.forEach(client => filegroup_1.default.checkTimeout(client));
103
- });
104
- wss.on('error', function (err) {
105
- const data = JSON.stringify({ event: types_1.WATCH_EVENT.ERROR, errors: [err.message] });
106
- this.clients.forEach(client => filegroup_1.default.checkTimeout(client) && client.send(data));
118
+ if (!wss) {
119
+ return null;
120
+ }
121
+ wss.on('connection', function (socket) {
122
+ socket.on('message', function () {
123
+ filegroup_1.default.CLIENT_SESSION.delete(this);
107
124
  });
108
- wss.on('close', function () {
109
- this.clients.forEach(client => client.terminate());
125
+ socket.on('close', function () {
126
+ filegroup_1.default.CLIENT_SESSION.delete(this);
110
127
  });
111
- return wss;
112
- }
128
+ this.clients.forEach(client => filegroup_1.default.checkTimeout(client));
129
+ });
130
+ wss.on('error', function (err) {
131
+ const data = JSON.stringify({ event: types_1.WATCH_EVENT.ERROR, errors: [err.message] });
132
+ this.clients.forEach(client => filegroup_1.default.checkTimeout(client) && client.send(data));
133
+ });
134
+ wss.on('close', function () {
135
+ this.clients.forEach(client => client.terminate());
136
+ });
137
+ return wss;
113
138
  }
114
139
  static shutdown() {
115
- for (const item of [HTTP_MAP, DISK_MAP]) {
116
- for (const uri in item) {
117
- for (const group of item[uri].values()) {
118
- abortTimeout(group);
119
- }
120
- }
121
- }
122
- for (const item of [PORT_MAP, SECURE_MAP]) {
123
- for (const port in item) {
124
- item[port].close(err => err && this.writeFail([`Unable to shutdown ${item === PORT_MAP ? 'WS' : 'WSS'} server`, 'port: ' + port], err));
125
- }
126
- }
140
+ closeFileGroup(HTTP_MAP);
141
+ closeFileGroup(DISK_MAP);
142
+ closeServer(PORT_MAP);
143
+ closeServer(SECURE_MAP);
127
144
  filegroup_1.default.CLIENT_SESSION.clear();
128
145
  HTTP_MAP = {};
129
146
  DISK_MAP = {};
@@ -158,7 +175,7 @@ class Watch extends core_1.Client {
158
175
  let interval;
159
176
  if ((0, types_1.isPlainObject)(data)) {
160
177
  let secure;
161
- ({ interval, port, secure } = data);
178
+ ({ interval, port, secure, extensions } = data);
162
179
  if (secure) {
163
180
  securePort = secure.port;
164
181
  if (secure.cert && secure.key) {
@@ -169,7 +186,7 @@ class Watch extends core_1.Client {
169
186
  this.interval = (0, util_1.asInt)(interval);
170
187
  this.port = (0, util_1.asInt)(port);
171
188
  this.securePort = (0, util_1.asInt)(securePort);
172
- if ((0, types_1.isArray)(extensions)) {
189
+ if (Array.isArray(extensions)) {
173
190
  this.module.extensions = extensions;
174
191
  }
175
192
  }
@@ -181,7 +198,6 @@ class Watch extends core_1.Client {
181
198
  if (permission) {
182
199
  this.permission = permission;
183
200
  }
184
- const startTime = Date.now();
185
201
  const username = this.host?.username;
186
202
  const destMap = Object.create(null);
187
203
  for (const item of assets) {
@@ -214,8 +230,8 @@ class Watch extends core_1.Client {
214
230
  const related = [];
215
231
  for (let i = 0, length = items.length; i < length; ++i) {
216
232
  const watch = items[i].watch;
217
- if ((0, types_1.isObject)(watch) && watch.assets) {
218
- watch.assets.forEach(other => {
233
+ if ((0, types_1.isObject)(watch)) {
234
+ watch.assets?.forEach(other => {
219
235
  if (items.includes(other)) {
220
236
  return;
221
237
  }
@@ -236,391 +252,403 @@ class Watch extends core_1.Client {
236
252
  }
237
253
  for (const item of items) {
238
254
  let { watch, sourceFiles } = item;
239
- if (watch) {
240
- const fatalError = (map, target, err) => {
241
- const uri = target.value.uri;
242
- delete map[uri];
243
- abortTimeout(target);
244
- this.writeFail(["Unable to watch file" /* ERR_MESSAGE.WATCH_FILE */, uri], err, 16 /* LOG_TYPE.WATCH */);
245
- };
246
- const watchExpired = (map, target, message = 'Expired') => {
247
- this.formatMessage(16 /* LOG_TYPE.WATCH */, 'WATCH', [message, target.startTime ? 'since ' + formatDate(target.startTime) : ''], target.uri, { titleColor: 'grey' });
248
- const data = map[target.uri];
249
- if (!data || data.size === 0) {
250
- delete map[target.uri];
251
- return true;
252
- }
253
- return false;
254
- };
255
- let expires = 0, status = 0, wss, main, id, socketId, port, secure, hot, always, watched, message, settings;
256
- if (watch === true && username && (settings = this.settings.users?.[username])) {
257
- const { uri, localUri, mimeType } = item;
258
- watch = false;
259
- if (uri && !(watch = settings[uri])) {
260
- for (const pattern in settings) {
261
- if ((0, types_1.hasGlob)(pattern) && pm.isMatch(uri, pattern, { matchBase: true }) && (watch = settings[pattern])) {
262
- break;
263
- }
264
- }
265
- }
266
- if (!watch && localUri && !(watch = settings[localUri])) {
267
- for (const pattern in settings) {
268
- if ((0, types_1.hasGlob)(pattern) && pm.isMatch(localUri, pattern, { nocase: PLATFORM_WIN32 }) && (watch = settings[pattern])) {
269
- break;
270
- }
255
+ if (!watch) {
256
+ continue;
257
+ }
258
+ const fatalError = (map, target, err) => {
259
+ const uri = target.value.uri;
260
+ delete map[uri];
261
+ abortTimeout(target);
262
+ this.writeFail(["Unable to watch file" /* ERR_MESSAGE.WATCH_FILE */, uri], err, 16 /* LOG_TYPE.WATCH */);
263
+ };
264
+ const watchExpired = (map, target, message = 'Expired') => {
265
+ this.formatMessage(16 /* LOG_TYPE.WATCH */, 'WATCH', [message, target.startTime ? 'since ' + formatDate(target.startTime) : ''], target.uri, { titleColor: 'grey' });
266
+ const data = map[target.uri];
267
+ if (!data || data.size === 0) {
268
+ delete map[target.uri];
269
+ return true;
270
+ }
271
+ return false;
272
+ };
273
+ let expires = 0, status = 0, wss = null, main, id, socketId, port, secure, hot, always, watched, message, settings;
274
+ if (watch === true && username && (settings = this.settings.users?.[username])) {
275
+ const { uri, localUri, mimeType } = item;
276
+ watch = false;
277
+ if (uri && !(watch = settings[uri])) {
278
+ for (const pattern in settings) {
279
+ if ((0, types_1.hasGlob)(pattern) && pm.isMatch(uri, pattern, { matchBase: true }) && (watch = settings[pattern])) {
280
+ break;
271
281
  }
272
282
  }
273
- if (!watch && mimeType && !(watch = settings[mimeType])) {
274
- for (const pattern in settings) {
275
- if (/^[^*/]+\/\*+$/.test(pattern) && pm.isMatch(mimeType, pattern) && (watch = settings[pattern])) {
276
- break;
277
- }
283
+ }
284
+ if (!watch && localUri && !(watch = settings[localUri])) {
285
+ for (const pattern in settings) {
286
+ if ((0, types_1.hasGlob)(pattern) && pm.isMatch(localUri, pattern, { nocase: PLATFORM_WIN32 }) && (watch = settings[pattern])) {
287
+ break;
278
288
  }
279
289
  }
280
290
  }
281
- if ((0, types_1.isPlainObject)(watch)) {
282
- const reload = watch.reload;
283
- id = watch.id;
284
- if (watch.main) {
285
- main = item;
286
- }
287
- if (watch.expires) {
288
- expires = (0, types_1.parseExpires)(watch.expires, startTime);
289
- }
290
- if (reload && (socketId = reload.socketId)) {
291
- ({ port, module: hot, always } = reload);
292
- if (reload.secure) {
293
- const key = this[kTlsKey];
294
- const cert = this[kTlsCert];
295
- if (key && cert) {
296
- wss = Watch.createServer(port || (port = this.securePort), { ca: this[kCa], key, cert, passphrase: this[kTlsPassphrase], version: this[kTlsVersion], config: this[kTlsConfig] });
297
- }
298
- secure = true;
299
- }
300
- else {
301
- wss = Watch.createServer(port || (port = this.port));
302
- }
303
- if (!wss) {
304
- this.writeFail('Unable to create WebSocket server', (0, types_1.errorMessage)(secure ? 'wss' : 'ws', "Invalid parameters" /* ERR_MESSAGE.PARAMETERS */, 'port: ' + (port || "Unknown" /* ERR_MESSAGE.UNKNOWN */)), 16 /* LOG_TYPE.WATCH */);
305
- socketId = undefined;
306
- port = undefined;
307
- secure = undefined;
308
- hot = undefined;
309
- always = undefined;
291
+ if (!watch && mimeType && !(watch = settings[mimeType])) {
292
+ for (const pattern in settings) {
293
+ if (/^[^*/]+\/\*+$/.test(pattern) && pm.isMatch(mimeType, pattern) && (watch = settings[pattern])) {
294
+ break;
310
295
  }
311
296
  }
312
- item.watch = watch;
313
297
  }
314
- const interval = getInterval(item) || watchInterval || this.interval;
315
- const watching = (uri, esm) => {
316
- const group = new filegroup_1.default(uri, main ? assets : items, startTime, this.willAbort("(watch)" /* ABORT_NAME.WATCH */));
317
- group.add(expires, socketId, id);
318
- if (main) {
319
- group.main = main;
320
- }
321
- else if (related.length) {
322
- group.related = related;
323
- }
324
- if (bundleMain) {
325
- group.bundleMain = bundleMain;
326
- }
327
- if (item.document) {
328
- group.document = item.document;
298
+ }
299
+ let startTime = Date.now();
300
+ if ((0, types_1.isPlainObject)(watch)) {
301
+ const { start, expires: expired, reload } = watch;
302
+ id = watch.id;
303
+ if (watch.main) {
304
+ main = item;
305
+ }
306
+ if (start) {
307
+ const offset = (0, types_1.parseTime)(start);
308
+ if (offset > 0) {
309
+ startTime += offset;
329
310
  }
330
- if (hot) {
331
- group.hot = true;
311
+ }
312
+ if (expired) {
313
+ expires = (0, types_1.parseExpires)(expired, startTime);
314
+ }
315
+ if (reload && (socketId = reload.socketId)) {
316
+ ({ port, module: hot, always } = reload);
317
+ if (reload.secure) {
318
+ const key = this[kTlsKey];
319
+ const cert = this[kTlsCert];
320
+ if (key && cert) {
321
+ wss = Watch.createServer(port || (port = this.securePort), { ca: this[kCa], key, cert, passphrase: this[kTlsPassphrase], version: this[kTlsVersion], config: this[kTlsConfig] });
322
+ }
323
+ secure = true;
332
324
  }
333
- if (always) {
334
- group.always = true;
325
+ else {
326
+ wss = Watch.createServer(port || (port = this.port));
335
327
  }
336
- if (sourceFiles) {
337
- group.sourceFiles = sourceFiles.filter(file => file !== uri);
328
+ if (!wss) {
329
+ this.writeFail('Unable to create WebSocket server', (0, types_1.errorMessage)(secure ? 'wss' : 'ws', "Invalid parameters" /* ERR_MESSAGE.PARAMETERS */, 'port: ' + (port || "Unknown" /* ERR_MESSAGE.UNKNOWN */)), 16 /* LOG_TYPE.WATCH */);
330
+ socketId = undefined;
331
+ port = undefined;
332
+ secure = undefined;
333
+ hot = undefined;
334
+ always = undefined;
338
335
  }
339
- if (wss) {
340
- group.connection(wss, port, secure);
336
+ }
337
+ item.watch = watch;
338
+ }
339
+ const interval = getInterval(item) || watchInterval || this.interval;
340
+ const watching = (uri, esm) => {
341
+ const group = new filegroup_1.default(uri, main ? assets : items, startTime, this.willAbort("(watch)" /* ABORT_NAME.WATCH */));
342
+ group.add(expires, socketId, id);
343
+ if (main) {
344
+ group.main = main;
345
+ }
346
+ else if (related.length) {
347
+ group.related = related;
348
+ }
349
+ if (bundleMain) {
350
+ group.bundleMain = bundleMain;
351
+ }
352
+ if (item.document) {
353
+ group.document = item.document;
354
+ }
355
+ if (hot) {
356
+ group.hot = true;
357
+ }
358
+ if (always) {
359
+ group.always = true;
360
+ }
361
+ if (sourceFiles) {
362
+ group.sourceFiles = sourceFiles.filter(file => file !== uri);
363
+ }
364
+ if (wss) {
365
+ group.connection(wss, port, secure);
366
+ }
367
+ const timeout = { interval, retries: 0, aborted: false };
368
+ const target = { value: group, timeout, watcher: null };
369
+ const isMap = (value) => value ? value.size > 0 : false;
370
+ const checkAborted = (result, current) => result?.aborted && current.abortable && current.abort();
371
+ const checkPreceding = (map) => {
372
+ const data = map[uri];
373
+ if (!data) {
374
+ return;
341
375
  }
342
- const timeout = { interval, retries: 0, aborted: false };
343
- const target = { value: group, timeout, watcher: null };
344
- const isMap = (value) => value ? value.size > 0 : false;
345
- const checkAborted = (result, current) => result?.aborted && current.abortable && current.abort();
346
- const checkPreceding = (map) => {
347
- const data = map[uri];
348
- if (!data) {
349
- return;
350
- }
351
- const current = data.get(dest)?.value;
352
- if (current && !current.expired) {
353
- let reset;
354
- if (id) {
355
- const sockets = current.sockets;
356
- for (let i = 0, active; i < sockets.length; ++i) {
357
- const socket = sockets[i];
358
- if (socket.id === id) {
359
- if (active) {
360
- sockets.splice(i, 1);
361
- }
362
- else {
363
- reset = true;
364
- }
365
- break;
376
+ const current = data.get(dest)?.value;
377
+ if (current && !current.expired) {
378
+ let reset;
379
+ if (id) {
380
+ const sockets = current.sockets;
381
+ for (let i = 0, active; i < sockets.length; ++i) {
382
+ const socket = sockets[i];
383
+ if (socket.id === id) {
384
+ if (active) {
385
+ sockets.splice(i, 1);
366
386
  }
367
- if (!socket.expired) {
368
- active = true;
387
+ else {
388
+ reset = true;
369
389
  }
390
+ break;
391
+ }
392
+ if (!socket.expired) {
393
+ active = true;
370
394
  }
371
395
  }
372
- if (!reset) {
373
- if (wss) {
374
- const server = current.server;
375
- if (!server) {
376
- current.connection(wss, port, secure);
377
- }
378
- else if (server !== wss) {
379
- if (wss.clients.size === 0 && !STATE_MAP.has(wss)) {
380
- if (secure) {
381
- delete SECURE_MAP[port];
382
- }
383
- else {
384
- delete PORT_MAP[port];
385
- }
386
- wss.close();
396
+ }
397
+ if (!reset) {
398
+ if (wss) {
399
+ const server = current.server;
400
+ if (!server) {
401
+ current.connection(wss, port, secure);
402
+ }
403
+ else if (server !== wss) {
404
+ if (wss.clients.size === 0 && !STATE_MAP.has(wss)) {
405
+ if (secure) {
406
+ delete SECURE_MAP[port];
407
+ }
408
+ else {
409
+ delete PORT_MAP[port];
387
410
  }
388
- message = 'Destination already watched @ ' + (current.secure ? 'wss' : 'ws') + '://hostname:' + current.port;
389
- return 3 /* ERR.SERVER */;
411
+ wss.close();
390
412
  }
413
+ message = 'Destination already watched @ ' + (current.secure ? 'wss' : 'ws') + '://hostname:' + current.port;
414
+ return 3 /* ERR.SERVER */;
391
415
  }
392
- const socket = socketId && current.find(socketId);
393
- if (socket) {
394
- socket.expires = expires;
395
- }
396
- else {
397
- current.add(expires, socketId, id);
398
- }
399
- return 0 /* ERR.NONE */;
400
416
  }
417
+ const socket = socketId && current.find(socketId);
418
+ if (socket) {
419
+ socket.expires = expires;
420
+ }
421
+ else {
422
+ current.add(expires, socketId, id);
423
+ }
424
+ return 0 /* ERR.NONE */;
401
425
  }
402
- data.set(dest, target);
403
- return 0 /* ERR.NONE */;
404
- };
405
- if (core_1.Client.isFile(uri, 'http/s')) {
406
- group.url = item.url;
407
- group.etag = item.etag;
408
- group.lastModified = item.lastModified;
409
- if (!group.etag && !group.lastModified) {
410
- return 1 /* ERR.ETAG */;
411
- }
412
- if ((status = checkPreceding(HTTP_MAP)) !== undefined) {
413
- return status;
414
- }
415
- const url = group.url || (group.url = new URL(uri));
416
- const request = this.host?.Request || new request_1.default();
417
- const agentTimeout = Math.max(timeout.interval * 10, this.connectTimeout);
418
- const opts = request.opts(url, { method: 'HEAD', httpVersion: 1, timeout: agentTimeout, agentTimeout });
419
- (function recurse() {
420
- let client = null;
421
- new Promise((resolve, reject) => {
422
- client = request.open(uri, opts)
423
- .on('response', res => {
424
- if (group.aborted) {
425
- return;
426
- }
427
- if (this.aborted) {
428
- reject((0, types_1.createAbortError)());
429
- return;
430
- }
431
- const statusCode = res.statusCode;
432
- const valid = statusCode >= 200 /* HTTP_STATUS.OK */ && statusCode < 300 /* HTTP_STATUS.MULTIPLE_CHOICES */;
433
- const map = HTTP_MAP[uri];
434
- const etag = res.headers.etag;
435
- const lastModified = res.headers['last-modified'];
436
- if (valid && map?.size && (etag || lastModified)) {
437
- for (const [destUrl, input] of map) {
438
- const value = input.value;
439
- if (value.paused) {
440
- continue;
426
+ }
427
+ data.set(dest, target);
428
+ return 0 /* ERR.NONE */;
429
+ };
430
+ if (core_1.Client.isFile(uri, 'http/s')) {
431
+ group.url = item.url;
432
+ group.etag = item.etag;
433
+ group.lastModified = item.lastModified;
434
+ if (!group.etag && !group.lastModified) {
435
+ return 1 /* ERR.ETAG */;
436
+ }
437
+ if ((status = checkPreceding(HTTP_MAP)) !== undefined) {
438
+ return status;
439
+ }
440
+ const url = group.url || (group.url = new URL(uri));
441
+ const request = this.host?.Request || new request_1.default();
442
+ const agentTimeout = Math.max(timeout.interval * 10, this.connectTimeout);
443
+ const opts = request.opts(url, { method: 'HEAD', httpVersion: 1, timeout: agentTimeout, agentTimeout });
444
+ (function recurse() {
445
+ let client = null;
446
+ new Promise((resolve, reject) => {
447
+ client = request.open(uri, opts)
448
+ .on('response', res => {
449
+ if (group.aborted) {
450
+ return;
451
+ }
452
+ if (this.aborted) {
453
+ reject((0, types_1.createAbortError)());
454
+ return;
455
+ }
456
+ const statusCode = res.statusCode;
457
+ const valid = statusCode >= 200 /* HTTP_STATUS.OK */ && statusCode < 300 /* HTTP_STATUS.MULTIPLE_CHOICES */;
458
+ const map = HTTP_MAP[uri];
459
+ const etag = res.headers.etag;
460
+ const lastModified = res.headers['last-modified'];
461
+ if (valid && map?.size && (etag || lastModified)) {
462
+ for (const [destUrl, input] of map) {
463
+ const value = input.value;
464
+ if (value.paused) {
465
+ continue;
466
+ }
467
+ let aborted = value.aborted;
468
+ if (!aborted) {
469
+ if (value.expired) {
470
+ aborted = true;
441
471
  }
442
- let aborted = value.aborted;
443
- if (!aborted) {
444
- if (value.expired) {
445
- aborted = true;
446
- }
447
- else if (value.etag) {
448
- if (etag) {
449
- if (etag !== value.etag) {
450
- value.etag = etag;
472
+ else if (value.etag) {
473
+ if (etag) {
474
+ if (etag !== value.etag) {
475
+ value.etag = etag;
476
+ if (value.started) {
451
477
  this.modified(value).then(result => checkAborted(result, value));
452
478
  }
453
479
  }
454
480
  }
455
- else if (value.lastModified && lastModified) {
456
- if (lastModified !== value.lastModified) {
457
- value.lastModified = lastModified;
481
+ }
482
+ else if (value.lastModified && lastModified) {
483
+ if (lastModified !== value.lastModified) {
484
+ value.lastModified = lastModified;
485
+ if (value.started) {
458
486
  this.modified(value).then(result => checkAborted(result, value));
459
487
  }
460
488
  }
461
489
  }
462
- if (aborted) {
463
- map.delete(destUrl);
464
- if (watchExpired(HTTP_MAP, value)) {
465
- abortTimeout(target);
466
- }
467
- }
468
490
  }
469
- }
470
- else {
471
- if (isMap(map)) {
472
- reject(valid ? (0, types_1.errorValue)('ETag not supported', uri) : (0, types_1.errorMessage)(statusCode, 'Invalid HTTP request', uri));
473
- return;
491
+ if (aborted) {
492
+ map.delete(destUrl);
493
+ if (watchExpired(HTTP_MAP, value)) {
494
+ abortTimeout(target);
495
+ }
474
496
  }
475
- watchExpired(HTTP_MAP, group);
476
- abortTimeout(target);
477
- }
478
- if (client) {
479
- client.destroy();
480
- }
481
- resolve();
482
- })
483
- .on('error', err => {
484
- if (!timeout.aborted && !(isConnectionTimeout(err) && ++timeout.retries <= 10 /* HTTP.TIMEOUT_LIMIT */)) {
485
- reject(err);
486
- return;
487
- }
488
- resolve();
489
- })
490
- .on('timeout', () => {
491
- if (!timeout.aborted && ++timeout.retries > 10 /* HTTP.TIMEOUT_LIMIT */) {
492
- reject((0, types_1.errorMessage)(408 /* HTTP_STATUS.REQUEST_TIMEOUT */, 'HTTP request timeout'));
493
- return;
494
497
  }
495
- resolve();
496
- });
497
- })
498
- .then(() => {
499
- if (!timeout.aborted) {
500
- const map = HTTP_MAP[uri];
498
+ }
499
+ else {
501
500
  if (isMap(map)) {
502
- let ms = Watch.MAX_TIMEOUT;
503
- for (const session of map.values()) {
504
- ms = Math.min(session.timeout.interval, ms);
505
- }
506
- setTimeout(recurse.bind(this), timeout.interval = ms);
507
- }
508
- else {
509
- delete HTTP_MAP[uri];
501
+ reject(valid ? (0, types_1.errorValue)('ETag not supported', uri) : (0, types_1.errorMessage)(statusCode, 'Invalid HTTP request', uri));
502
+ return;
510
503
  }
504
+ watchExpired(HTTP_MAP, group);
505
+ abortTimeout(target);
511
506
  }
512
- })
513
- .catch(err => {
514
- fatalError(HTTP_MAP, target, err);
515
507
  if (client) {
516
508
  client.destroy();
517
509
  }
510
+ resolve();
511
+ })
512
+ .on('error', err => {
513
+ if (!timeout.aborted && !(isConnectionTimeout(err) && ++timeout.retries <= 10 /* HTTP.TIMEOUT_LIMIT */)) {
514
+ reject(err);
515
+ return;
516
+ }
517
+ resolve();
518
+ })
519
+ .on('timeout', () => {
520
+ if (!timeout.aborted && ++timeout.retries > 10 /* HTTP.TIMEOUT_LIMIT */) {
521
+ reject((0, types_1.errorMessage)(408 /* HTTP_STATUS.REQUEST_TIMEOUT */, 'HTTP request timeout'));
522
+ return;
523
+ }
524
+ resolve();
518
525
  });
519
- }).call(this);
520
- HTTP_MAP[uri] = new Map([[dest, target]]);
526
+ })
527
+ .then(() => {
528
+ if (!timeout.aborted) {
529
+ const map = HTTP_MAP[uri];
530
+ if (isMap(map)) {
531
+ let ms = Watch.MAX_TIMEOUT;
532
+ for (const session of map.values()) {
533
+ ms = Math.min(session.timeout.interval, ms);
534
+ }
535
+ setTimeout(recurse.bind(this), timeout.interval = ms);
536
+ }
537
+ else {
538
+ delete HTTP_MAP[uri];
539
+ }
540
+ }
541
+ })
542
+ .catch(err => {
543
+ fatalError(HTTP_MAP, target, err);
544
+ if (client) {
545
+ client.destroy();
546
+ }
547
+ });
548
+ }).call(this);
549
+ HTTP_MAP[uri] = new Map([[dest, target]]);
550
+ }
551
+ else if (esm || path.isAbsolute(uri = core_1.Client.resolveFile(uri)) && this.canRead(uri, { hostPermissionOnly: !!this.host })) {
552
+ if ((status = checkPreceding(DISK_MAP)) !== undefined) {
553
+ return status;
521
554
  }
522
- else if (esm || path.isAbsolute(uri = core_1.Client.resolveFile(uri)) && this.canRead(uri, { hostPermissionOnly: !!this.host })) {
523
- if ((status = checkPreceding(DISK_MAP)) !== undefined) {
524
- return status;
555
+ let ptime = 0;
556
+ target.watcher = fs.watch(uri, (event, filename) => {
557
+ if (this.aborted || group.aborted) {
558
+ fatalError(DISK_MAP, target, (0, types_1.createAbortError)());
559
+ return;
525
560
  }
526
- let ptime = 0;
527
- target.watcher = fs.watch(uri, (event, filename) => {
528
- if (this.aborted || group.aborted) {
529
- fatalError(DISK_MAP, target, (0, types_1.createAbortError)());
530
- return;
531
- }
532
- const map = DISK_MAP[uri];
533
- switch (event) {
534
- case 'change': {
535
- if (isMap(map)) {
536
- try {
537
- const mtime = Math.floor(fs.statSync(uri).mtimeMs);
538
- if (mtime > ptime) {
539
- for (const [key, input] of map) {
540
- const value = input.value;
541
- if (value.expired) {
542
- map.delete(key);
543
- if (watchExpired(DISK_MAP, value)) {
544
- abortTimeout(target);
545
- }
546
- }
547
- else if (value.aborted) {
548
- map.delete(key);
549
- if (map.size === 0) {
550
- abortTimeout(target);
551
- }
561
+ const map = DISK_MAP[uri];
562
+ switch (event) {
563
+ case 'change': {
564
+ if (isMap(map)) {
565
+ try {
566
+ const mtime = Math.floor(fs.statSync(uri).mtimeMs);
567
+ if (mtime > ptime) {
568
+ for (const [key, input] of map) {
569
+ const value = input.value;
570
+ if (value.expired) {
571
+ map.delete(key);
572
+ if (watchExpired(DISK_MAP, value)) {
573
+ abortTimeout(target);
552
574
  }
553
- else {
554
- this.modified(value).then(result => checkAborted(result, value));
575
+ }
576
+ else if (value.aborted) {
577
+ map.delete(key);
578
+ if (map.size === 0) {
579
+ abortTimeout(target);
555
580
  }
556
581
  }
557
- ptime = mtime + types_1.THRESHOLD.WATCH_CHANGE;
582
+ else if (value.started) {
583
+ this.modified(value).then(result => checkAborted(result, value));
584
+ }
558
585
  }
559
- break;
560
- }
561
- catch (err) {
562
- this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(uri)], err, { type: 32 /* LOG_TYPE.FILE */, fatal: false });
586
+ ptime = mtime + types_1.THRESHOLD.WATCH_CHANGE;
563
587
  }
588
+ break;
564
589
  }
565
- }
566
- case 'rename':
567
- if (map) {
568
- map.clear();
590
+ catch (err) {
591
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(uri)], err, { type: 32 /* LOG_TYPE.FILE */, fatal: false });
569
592
  }
570
- watchExpired(DISK_MAP, group, event === 'rename' ? 'File renamed: ' + filename : undefined);
571
- abortTimeout(target);
572
- break;
593
+ }
573
594
  }
574
- });
575
- DISK_MAP[uri] = new Map([[dest, target]]);
576
- }
577
- else {
578
- return 2 /* ERR.LOCAL_ACCESS */;
579
- }
580
- return 0 /* ERR.NONE */;
581
- };
582
- if ((0, types_1.isArray)(sourceFiles) && sourceFiles.some(file => this.canRead(file, { hostPermissionOnly: !!this.host }))) {
583
- let index = 0;
584
- for (const file of new Set(sourceFiles)) {
585
- if (index++ > 0) {
586
- watching(file, true);
587
- }
588
- else if ((status = watching(watched = file, true)) > 0) {
589
- break;
595
+ case 'rename':
596
+ if (map) {
597
+ map.clear();
598
+ }
599
+ watchExpired(DISK_MAP, group, event === 'rename' ? 'File renamed: ' + filename : undefined);
600
+ abortTimeout(target);
601
+ break;
590
602
  }
591
- }
592
- }
593
- else if (watched = item.uri) {
594
- status = watching(watched, false);
603
+ });
604
+ DISK_MAP[uri] = new Map([[dest, target]]);
595
605
  }
596
606
  else {
597
- continue;
607
+ return 2 /* ERR.LOCAL_ACCESS */;
598
608
  }
599
- if (status > 0) {
600
- if (!message) {
601
- switch (status) {
602
- case 1 /* ERR.ETAG */:
603
- if ((0, types_1.existsFlag)(item.flags)) {
604
- continue;
605
- }
606
- message = 'ETag unavailable';
607
- break;
608
- case 2 /* ERR.LOCAL_ACCESS */:
609
- message = 'No read permission';
610
- break;
611
- case 3 /* ERR.SERVER */:
612
- message = 'Server already in use';
613
- break;
614
- default:
615
- message = "Unknown" /* ERR_MESSAGE.UNKNOWN */;
616
- break;
617
- }
609
+ return 0 /* ERR.NONE */;
610
+ };
611
+ if ((0, types_1.isArray)(sourceFiles) && sourceFiles.some(file => this.canRead(file, { hostPermissionOnly: !!this.host }))) {
612
+ let index = 0;
613
+ for (const file of new Set(sourceFiles)) {
614
+ if (index++ > 0) {
615
+ watching(file, true);
616
+ }
617
+ else if ((status = watching(watched = file, true)) > 0) {
618
+ break;
618
619
  }
619
- this.formatFail((16 /* LOG_TYPE.WATCH */ | (status === 2 /* ERR.LOCAL_ACCESS */ ? 8192 /* LOG_TYPE.PERMISSION */ : 0)), 'WATCH', ["Unable to watch file" /* ERR_MESSAGE.WATCH_FILE */, watched && path.basename(watched)], (0, types_1.errorValue)(message, watched));
620
620
  }
621
- else {
622
- this.formatMessage(16 /* LOG_TYPE.WATCH */, 'WATCH', ['Start', interval + 'ms ' + (expires ? formatDate(expires) : 'never')], watched, { titleColor: 'blue' });
621
+ }
622
+ else if (watched = item.uri) {
623
+ status = watching(watched, false);
624
+ }
625
+ else {
626
+ continue;
627
+ }
628
+ if (status > 0) {
629
+ if (!message) {
630
+ switch (status) {
631
+ case 1 /* ERR.ETAG */:
632
+ if ((0, types_1.existsFlag)(item.flags)) {
633
+ continue;
634
+ }
635
+ message = 'ETag unavailable';
636
+ break;
637
+ case 2 /* ERR.LOCAL_ACCESS */:
638
+ message = 'No read permission';
639
+ break;
640
+ case 3 /* ERR.SERVER */:
641
+ message = 'Server already in use';
642
+ break;
643
+ default:
644
+ message = "Unknown" /* ERR_MESSAGE.UNKNOWN */;
645
+ break;
646
+ }
623
647
  }
648
+ this.formatFail((16 /* LOG_TYPE.WATCH */ | (status === 2 /* ERR.LOCAL_ACCESS */ ? 8192 /* LOG_TYPE.PERMISSION */ : 0)), 'WATCH', ["Unable to watch file" /* ERR_MESSAGE.WATCH_FILE */, watched && path.basename(watched)], (0, types_1.errorValue)(message, watched));
649
+ }
650
+ else {
651
+ this.formatMessage(16 /* LOG_TYPE.WATCH */, 'WATCH', ['Start', interval + 'ms ' + (expires ? formatDate(expires) : 'never')], watched, { titleColor: 'blue' });
624
652
  }
625
653
  }
626
654
  }
@@ -676,72 +704,73 @@ class Watch extends core_1.Client {
676
704
  catch {
677
705
  }
678
706
  }
679
- if (manager) {
680
- if (host && watch.document) {
681
- for (const { instance } of host.Document) {
682
- if (host.hasDocument(instance, watch.document)) {
683
- const result = instance.watchInit?.(watch, items, sanitize);
684
- if (result) {
685
- if ((0, types_1.isArray)(result.using)) {
686
- manager.using(...result.using);
687
- }
688
- if (Array.isArray(result.dataSource)) {
689
- const document = manager.find(instance.moduleName);
690
- if (document) {
691
- document.dataSource = result.dataSource;
692
- }
693
- }
707
+ if (!manager) {
708
+ return;
709
+ }
710
+ if (host && watch.document) {
711
+ for (const { instance } of host.Document) {
712
+ if (host.hasDocument(instance, watch.document)) {
713
+ const result = instance.watchInit?.(watch, items, sanitize);
714
+ if (result) {
715
+ if ((0, types_1.isArray)(result.using)) {
716
+ manager.using(...result.using);
694
717
  }
695
- const listener = instance.watchModified?.(watch, items);
696
- if (typeof listener === 'function') {
697
- manager.on('end', listener);
718
+ if (Array.isArray(result.dataSource)) {
719
+ const document = manager.find(instance.moduleName);
720
+ if (document) {
721
+ document.dataSource = result.dataSource;
722
+ }
698
723
  }
699
724
  }
725
+ const listener = instance.watchModified?.(watch, items);
726
+ if (typeof listener === 'function') {
727
+ manager.on('end', listener);
728
+ }
700
729
  }
701
730
  }
702
- return await manager.start();
703
731
  }
732
+ return await manager.start();
704
733
  }
705
734
  catch (err) {
706
735
  this.writeFail(["Unknown" /* ERR_MESSAGE.UNKNOWN */, watch.url?.pathname || path.basename(watch.uri)], err);
707
736
  }
708
737
  }
709
738
  configureServer({ ca, key, cert, passphrase, version, config }) {
710
- if ((0, types_1.isString)(key) && (0, types_1.isString)(cert)) {
711
- if (ca) {
712
- this.setCA(ca);
713
- }
714
- if (request_1.default.isCert(key) || core_1.Client.isPath(key = path.resolve(key = key.trim())) && this.canRead(key, { ownPermissionOnly: true })) {
715
- this[kTlsKey] = key.trim();
716
- }
717
- if (request_1.default.isCert(cert) || core_1.Client.isPath(cert = path.resolve(cert = cert.trim())) && this.canRead(cert, { ownPermissionOnly: true })) {
718
- this[kTlsCert] = cert.trim();
719
- }
720
- if ((0, types_1.isString)(passphrase)) {
721
- this[kTlsPassphrase] = passphrase;
722
- }
723
- if (!(0, types_1.isPlainObject)(config)) {
724
- config = undefined;
725
- }
726
- else if (version || (version = config.minVersion)) {
727
- delete config.minVersion;
728
- delete config.secureProtocol;
729
- }
730
- switch (version) {
731
- case 'TLSv1':
732
- case 'TLSv1.1':
733
- case 'TLSv1.2':
734
- case 'TLSv1.3':
735
- break;
736
- default:
737
- version = undefined;
738
- break;
739
- }
740
- this[kTlsConfig] = config;
741
- this[kTlsVersion] = version;
742
- return this.hasSecureProtocol();
739
+ if (!(0, types_1.isString)(key) || !(0, types_1.isString)(cert)) {
740
+ return false;
743
741
  }
744
- return false;
742
+ if (ca) {
743
+ this.setCA(ca);
744
+ }
745
+ if (request_1.default.isCert(key) || core_1.Client.isPath(key = path.resolve(key = key.trim())) && this.canRead(key, { ownPermissionOnly: true })) {
746
+ this[kTlsKey] = key.trim();
747
+ }
748
+ if (request_1.default.isCert(cert) || core_1.Client.isPath(cert = path.resolve(cert = cert.trim())) && this.canRead(cert, { ownPermissionOnly: true })) {
749
+ this[kTlsCert] = cert.trim();
750
+ }
751
+ if ((0, types_1.isString)(passphrase)) {
752
+ this[kTlsPassphrase] = passphrase;
753
+ }
754
+ if (!(0, types_1.isPlainObject)(config)) {
755
+ config = undefined;
756
+ }
757
+ else if (version || (version = config.minVersion)) {
758
+ delete config.minVersion;
759
+ delete config.secureProtocol;
760
+ }
761
+ switch (version) {
762
+ case 'TLSv1':
763
+ case 'TLSv1.1':
764
+ case 'TLSv1.2':
765
+ case 'TLSv1.3':
766
+ break;
767
+ default:
768
+ version = undefined;
769
+ break;
770
+ }
771
+ this[kTlsConfig] = config;
772
+ this[kTlsVersion] = version;
773
+ return this.hasSecureProtocol();
745
774
  }
746
775
  setCA(value) {
747
776
  if ((0, types_1.isString)(value) && core_1.Client.isPath(value = path.resolve(value = value.trim())) && this.canRead(value, { ownPermissionOnly: true })) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e-mc/watch",
3
- "version": "0.5.3",
3
+ "version": "0.6.0",
4
4
  "description": "Watch constructor for E-mc.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -20,9 +20,9 @@
20
20
  "license": "BSD 3-Clause",
21
21
  "homepage": "https://github.com/anpham6/e-mc#readme",
22
22
  "dependencies": {
23
- "@e-mc/core": "0.5.3",
24
- "@e-mc/request": "0.5.3",
25
- "@e-mc/types": "0.5.3",
23
+ "@e-mc/core": "0.6.0",
24
+ "@e-mc/request": "0.6.0",
25
+ "@e-mc/types": "0.6.0",
26
26
  "picomatch": "^2.3.1",
27
27
  "ws": "^8.13.0"
28
28
  }