vite-react-ssg 0.3.3 → 0.5.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.
- package/README.md +13 -0
- package/dist/index.d.cts +24 -0
- package/dist/index.d.mts +24 -0
- package/dist/index.d.ts +2 -2
- package/dist/node/cli.cjs +18 -4
- package/dist/node/cli.d.cts +2 -0
- package/dist/node/cli.d.mts +2 -0
- package/dist/node/cli.d.ts +1 -1
- package/dist/node/cli.mjs +16 -2
- package/dist/node.cjs +29153 -20
- package/dist/node.d.cts +11 -0
- package/dist/node.d.mts +11 -0
- package/dist/node.d.ts +1 -1
- package/dist/node.mjs +29132 -15
- package/dist/{types-3aee4b6b.d.ts → shared/vite-react-ssg.d5f23f74.d.cts} +1 -1
- package/dist/shared/vite-react-ssg.d5f23f74.d.mts +178 -0
- package/dist/shared/vite-react-ssg.d5f23f74.d.ts +178 -0
- package/dist/style-collectors/styled-components.d.cts +9 -0
- package/dist/style-collectors/styled-components.d.mts +9 -0
- package/package.json +20 -20
- package/dist/shared/vite-react-ssg.69de2462.cjs +0 -1541
- package/dist/shared/vite-react-ssg.f8eacfb1.mjs +0 -1532
|
@@ -1,1532 +0,0 @@
|
|
|
1
|
-
import { join, isAbsolute, parse, dirname } from 'node:path';
|
|
2
|
-
import { createRequire } from 'node:module';
|
|
3
|
-
import { gray, yellow, blue, dim, cyan, red, green, bold, reset, bgLightCyan } from 'kolorist';
|
|
4
|
-
import fs from 'fs-extra';
|
|
5
|
-
import { resolveConfig, build as build$1, mergeConfig, createServer, version as version$1 } from 'vite';
|
|
6
|
-
import { JSDOM } from 'jsdom';
|
|
7
|
-
import { S as SiteMetadataDefaults, s as serializeState } from './vite-react-ssg.9d005d5e.mjs';
|
|
8
|
-
import express from 'express';
|
|
9
|
-
import { readFileSync } from 'node:fs';
|
|
10
|
-
import React from 'react';
|
|
11
|
-
import { HelmetProvider } from 'react-helmet-async';
|
|
12
|
-
import { createStaticHandler, createStaticRouter, StaticRouterProvider } from 'react-router-dom/server.js';
|
|
13
|
-
import { Writable } from 'node:stream';
|
|
14
|
-
import { renderToPipeableStream } from 'react-dom/server';
|
|
15
|
-
|
|
16
|
-
function getDefaultExportFromCjs (x) {
|
|
17
|
-
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
var eventemitter3 = {exports: {}};
|
|
21
|
-
|
|
22
|
-
(function (module) {
|
|
23
|
-
|
|
24
|
-
var has = Object.prototype.hasOwnProperty
|
|
25
|
-
, prefix = '~';
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Constructor to create a storage for our `EE` objects.
|
|
29
|
-
* An `Events` instance is a plain object whose properties are event names.
|
|
30
|
-
*
|
|
31
|
-
* @constructor
|
|
32
|
-
* @private
|
|
33
|
-
*/
|
|
34
|
-
function Events() {}
|
|
35
|
-
|
|
36
|
-
//
|
|
37
|
-
// We try to not inherit from `Object.prototype`. In some engines creating an
|
|
38
|
-
// instance in this way is faster than calling `Object.create(null)` directly.
|
|
39
|
-
// If `Object.create(null)` is not supported we prefix the event names with a
|
|
40
|
-
// character to make sure that the built-in object properties are not
|
|
41
|
-
// overridden or used as an attack vector.
|
|
42
|
-
//
|
|
43
|
-
if (Object.create) {
|
|
44
|
-
Events.prototype = Object.create(null);
|
|
45
|
-
|
|
46
|
-
//
|
|
47
|
-
// This hack is needed because the `__proto__` property is still inherited in
|
|
48
|
-
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
|
|
49
|
-
//
|
|
50
|
-
if (!new Events().__proto__) prefix = false;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Representation of a single event listener.
|
|
55
|
-
*
|
|
56
|
-
* @param {Function} fn The listener function.
|
|
57
|
-
* @param {*} context The context to invoke the listener with.
|
|
58
|
-
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
|
|
59
|
-
* @constructor
|
|
60
|
-
* @private
|
|
61
|
-
*/
|
|
62
|
-
function EE(fn, context, once) {
|
|
63
|
-
this.fn = fn;
|
|
64
|
-
this.context = context;
|
|
65
|
-
this.once = once || false;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Add a listener for a given event.
|
|
70
|
-
*
|
|
71
|
-
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
|
|
72
|
-
* @param {(String|Symbol)} event The event name.
|
|
73
|
-
* @param {Function} fn The listener function.
|
|
74
|
-
* @param {*} context The context to invoke the listener with.
|
|
75
|
-
* @param {Boolean} once Specify if the listener is a one-time listener.
|
|
76
|
-
* @returns {EventEmitter}
|
|
77
|
-
* @private
|
|
78
|
-
*/
|
|
79
|
-
function addListener(emitter, event, fn, context, once) {
|
|
80
|
-
if (typeof fn !== 'function') {
|
|
81
|
-
throw new TypeError('The listener must be a function');
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
var listener = new EE(fn, context || emitter, once)
|
|
85
|
-
, evt = prefix ? prefix + event : event;
|
|
86
|
-
|
|
87
|
-
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
|
|
88
|
-
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
|
|
89
|
-
else emitter._events[evt] = [emitter._events[evt], listener];
|
|
90
|
-
|
|
91
|
-
return emitter;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* Clear event by name.
|
|
96
|
-
*
|
|
97
|
-
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
|
|
98
|
-
* @param {(String|Symbol)} evt The Event name.
|
|
99
|
-
* @private
|
|
100
|
-
*/
|
|
101
|
-
function clearEvent(emitter, evt) {
|
|
102
|
-
if (--emitter._eventsCount === 0) emitter._events = new Events();
|
|
103
|
-
else delete emitter._events[evt];
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Minimal `EventEmitter` interface that is molded against the Node.js
|
|
108
|
-
* `EventEmitter` interface.
|
|
109
|
-
*
|
|
110
|
-
* @constructor
|
|
111
|
-
* @public
|
|
112
|
-
*/
|
|
113
|
-
function EventEmitter() {
|
|
114
|
-
this._events = new Events();
|
|
115
|
-
this._eventsCount = 0;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Return an array listing the events for which the emitter has registered
|
|
120
|
-
* listeners.
|
|
121
|
-
*
|
|
122
|
-
* @returns {Array}
|
|
123
|
-
* @public
|
|
124
|
-
*/
|
|
125
|
-
EventEmitter.prototype.eventNames = function eventNames() {
|
|
126
|
-
var names = []
|
|
127
|
-
, events
|
|
128
|
-
, name;
|
|
129
|
-
|
|
130
|
-
if (this._eventsCount === 0) return names;
|
|
131
|
-
|
|
132
|
-
for (name in (events = this._events)) {
|
|
133
|
-
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
if (Object.getOwnPropertySymbols) {
|
|
137
|
-
return names.concat(Object.getOwnPropertySymbols(events));
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
return names;
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* Return the listeners registered for a given event.
|
|
145
|
-
*
|
|
146
|
-
* @param {(String|Symbol)} event The event name.
|
|
147
|
-
* @returns {Array} The registered listeners.
|
|
148
|
-
* @public
|
|
149
|
-
*/
|
|
150
|
-
EventEmitter.prototype.listeners = function listeners(event) {
|
|
151
|
-
var evt = prefix ? prefix + event : event
|
|
152
|
-
, handlers = this._events[evt];
|
|
153
|
-
|
|
154
|
-
if (!handlers) return [];
|
|
155
|
-
if (handlers.fn) return [handlers.fn];
|
|
156
|
-
|
|
157
|
-
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
|
|
158
|
-
ee[i] = handlers[i].fn;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
return ee;
|
|
162
|
-
};
|
|
163
|
-
|
|
164
|
-
/**
|
|
165
|
-
* Return the number of listeners listening to a given event.
|
|
166
|
-
*
|
|
167
|
-
* @param {(String|Symbol)} event The event name.
|
|
168
|
-
* @returns {Number} The number of listeners.
|
|
169
|
-
* @public
|
|
170
|
-
*/
|
|
171
|
-
EventEmitter.prototype.listenerCount = function listenerCount(event) {
|
|
172
|
-
var evt = prefix ? prefix + event : event
|
|
173
|
-
, listeners = this._events[evt];
|
|
174
|
-
|
|
175
|
-
if (!listeners) return 0;
|
|
176
|
-
if (listeners.fn) return 1;
|
|
177
|
-
return listeners.length;
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Calls each of the listeners registered for a given event.
|
|
182
|
-
*
|
|
183
|
-
* @param {(String|Symbol)} event The event name.
|
|
184
|
-
* @returns {Boolean} `true` if the event had listeners, else `false`.
|
|
185
|
-
* @public
|
|
186
|
-
*/
|
|
187
|
-
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
|
|
188
|
-
var evt = prefix ? prefix + event : event;
|
|
189
|
-
|
|
190
|
-
if (!this._events[evt]) return false;
|
|
191
|
-
|
|
192
|
-
var listeners = this._events[evt]
|
|
193
|
-
, len = arguments.length
|
|
194
|
-
, args
|
|
195
|
-
, i;
|
|
196
|
-
|
|
197
|
-
if (listeners.fn) {
|
|
198
|
-
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
|
|
199
|
-
|
|
200
|
-
switch (len) {
|
|
201
|
-
case 1: return listeners.fn.call(listeners.context), true;
|
|
202
|
-
case 2: return listeners.fn.call(listeners.context, a1), true;
|
|
203
|
-
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
|
|
204
|
-
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
|
|
205
|
-
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
|
|
206
|
-
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
for (i = 1, args = new Array(len -1); i < len; i++) {
|
|
210
|
-
args[i - 1] = arguments[i];
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
listeners.fn.apply(listeners.context, args);
|
|
214
|
-
} else {
|
|
215
|
-
var length = listeners.length
|
|
216
|
-
, j;
|
|
217
|
-
|
|
218
|
-
for (i = 0; i < length; i++) {
|
|
219
|
-
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
|
|
220
|
-
|
|
221
|
-
switch (len) {
|
|
222
|
-
case 1: listeners[i].fn.call(listeners[i].context); break;
|
|
223
|
-
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
|
|
224
|
-
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
|
|
225
|
-
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
|
|
226
|
-
default:
|
|
227
|
-
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
|
|
228
|
-
args[j - 1] = arguments[j];
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
listeners[i].fn.apply(listeners[i].context, args);
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
return true;
|
|
237
|
-
};
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* Add a listener for a given event.
|
|
241
|
-
*
|
|
242
|
-
* @param {(String|Symbol)} event The event name.
|
|
243
|
-
* @param {Function} fn The listener function.
|
|
244
|
-
* @param {*} [context=this] The context to invoke the listener with.
|
|
245
|
-
* @returns {EventEmitter} `this`.
|
|
246
|
-
* @public
|
|
247
|
-
*/
|
|
248
|
-
EventEmitter.prototype.on = function on(event, fn, context) {
|
|
249
|
-
return addListener(this, event, fn, context, false);
|
|
250
|
-
};
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* Add a one-time listener for a given event.
|
|
254
|
-
*
|
|
255
|
-
* @param {(String|Symbol)} event The event name.
|
|
256
|
-
* @param {Function} fn The listener function.
|
|
257
|
-
* @param {*} [context=this] The context to invoke the listener with.
|
|
258
|
-
* @returns {EventEmitter} `this`.
|
|
259
|
-
* @public
|
|
260
|
-
*/
|
|
261
|
-
EventEmitter.prototype.once = function once(event, fn, context) {
|
|
262
|
-
return addListener(this, event, fn, context, true);
|
|
263
|
-
};
|
|
264
|
-
|
|
265
|
-
/**
|
|
266
|
-
* Remove the listeners of a given event.
|
|
267
|
-
*
|
|
268
|
-
* @param {(String|Symbol)} event The event name.
|
|
269
|
-
* @param {Function} fn Only remove the listeners that match this function.
|
|
270
|
-
* @param {*} context Only remove the listeners that have this context.
|
|
271
|
-
* @param {Boolean} once Only remove one-time listeners.
|
|
272
|
-
* @returns {EventEmitter} `this`.
|
|
273
|
-
* @public
|
|
274
|
-
*/
|
|
275
|
-
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
|
|
276
|
-
var evt = prefix ? prefix + event : event;
|
|
277
|
-
|
|
278
|
-
if (!this._events[evt]) return this;
|
|
279
|
-
if (!fn) {
|
|
280
|
-
clearEvent(this, evt);
|
|
281
|
-
return this;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
var listeners = this._events[evt];
|
|
285
|
-
|
|
286
|
-
if (listeners.fn) {
|
|
287
|
-
if (
|
|
288
|
-
listeners.fn === fn &&
|
|
289
|
-
(!once || listeners.once) &&
|
|
290
|
-
(!context || listeners.context === context)
|
|
291
|
-
) {
|
|
292
|
-
clearEvent(this, evt);
|
|
293
|
-
}
|
|
294
|
-
} else {
|
|
295
|
-
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
|
|
296
|
-
if (
|
|
297
|
-
listeners[i].fn !== fn ||
|
|
298
|
-
(once && !listeners[i].once) ||
|
|
299
|
-
(context && listeners[i].context !== context)
|
|
300
|
-
) {
|
|
301
|
-
events.push(listeners[i]);
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
//
|
|
306
|
-
// Reset the array, or remove it completely if we have no more listeners.
|
|
307
|
-
//
|
|
308
|
-
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
|
|
309
|
-
else clearEvent(this, evt);
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
return this;
|
|
313
|
-
};
|
|
314
|
-
|
|
315
|
-
/**
|
|
316
|
-
* Remove all listeners, or those of the specified event.
|
|
317
|
-
*
|
|
318
|
-
* @param {(String|Symbol)} [event] The event name.
|
|
319
|
-
* @returns {EventEmitter} `this`.
|
|
320
|
-
* @public
|
|
321
|
-
*/
|
|
322
|
-
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
|
|
323
|
-
var evt;
|
|
324
|
-
|
|
325
|
-
if (event) {
|
|
326
|
-
evt = prefix ? prefix + event : event;
|
|
327
|
-
if (this._events[evt]) clearEvent(this, evt);
|
|
328
|
-
} else {
|
|
329
|
-
this._events = new Events();
|
|
330
|
-
this._eventsCount = 0;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
return this;
|
|
334
|
-
};
|
|
335
|
-
|
|
336
|
-
//
|
|
337
|
-
// Alias methods names because people roll like that.
|
|
338
|
-
//
|
|
339
|
-
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
|
|
340
|
-
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
|
|
341
|
-
|
|
342
|
-
//
|
|
343
|
-
// Expose the prefix.
|
|
344
|
-
//
|
|
345
|
-
EventEmitter.prefixed = prefix;
|
|
346
|
-
|
|
347
|
-
//
|
|
348
|
-
// Allow `EventEmitter` to be imported as module namespace.
|
|
349
|
-
//
|
|
350
|
-
EventEmitter.EventEmitter = EventEmitter;
|
|
351
|
-
|
|
352
|
-
//
|
|
353
|
-
// Expose the module.
|
|
354
|
-
//
|
|
355
|
-
{
|
|
356
|
-
module.exports = EventEmitter;
|
|
357
|
-
}
|
|
358
|
-
} (eventemitter3));
|
|
359
|
-
|
|
360
|
-
var eventemitter3Exports = eventemitter3.exports;
|
|
361
|
-
const EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
|
|
362
|
-
|
|
363
|
-
class TimeoutError extends Error {
|
|
364
|
-
constructor(message) {
|
|
365
|
-
super(message);
|
|
366
|
-
this.name = 'TimeoutError';
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
/**
|
|
371
|
-
An error to be thrown when the request is aborted by AbortController.
|
|
372
|
-
DOMException is thrown instead of this Error when DOMException is available.
|
|
373
|
-
*/
|
|
374
|
-
let AbortError$1 = class AbortError extends Error {
|
|
375
|
-
constructor(message) {
|
|
376
|
-
super();
|
|
377
|
-
this.name = 'AbortError';
|
|
378
|
-
this.message = message;
|
|
379
|
-
}
|
|
380
|
-
};
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
TODO: Remove AbortError and just throw DOMException when targeting Node 18.
|
|
384
|
-
*/
|
|
385
|
-
const getDOMException = errorMessage => globalThis.DOMException === undefined ?
|
|
386
|
-
new AbortError$1(errorMessage) :
|
|
387
|
-
new DOMException(errorMessage);
|
|
388
|
-
|
|
389
|
-
/**
|
|
390
|
-
TODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.
|
|
391
|
-
*/
|
|
392
|
-
const getAbortedReason = signal => {
|
|
393
|
-
const reason = signal.reason === undefined ?
|
|
394
|
-
getDOMException('This operation was aborted.') :
|
|
395
|
-
signal.reason;
|
|
396
|
-
|
|
397
|
-
return reason instanceof Error ? reason : getDOMException(reason);
|
|
398
|
-
};
|
|
399
|
-
|
|
400
|
-
function pTimeout(promise, milliseconds, fallback, options) {
|
|
401
|
-
let timer;
|
|
402
|
-
|
|
403
|
-
const cancelablePromise = new Promise((resolve, reject) => {
|
|
404
|
-
if (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {
|
|
405
|
-
throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
if (milliseconds === Number.POSITIVE_INFINITY) {
|
|
409
|
-
resolve(promise);
|
|
410
|
-
return;
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
options = {
|
|
414
|
-
customTimers: {setTimeout, clearTimeout},
|
|
415
|
-
...options
|
|
416
|
-
};
|
|
417
|
-
|
|
418
|
-
if (options.signal) {
|
|
419
|
-
const {signal} = options;
|
|
420
|
-
if (signal.aborted) {
|
|
421
|
-
reject(getAbortedReason(signal));
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
signal.addEventListener('abort', () => {
|
|
425
|
-
reject(getAbortedReason(signal));
|
|
426
|
-
});
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
timer = options.customTimers.setTimeout.call(undefined, () => {
|
|
430
|
-
if (typeof fallback === 'function') {
|
|
431
|
-
try {
|
|
432
|
-
resolve(fallback());
|
|
433
|
-
} catch (error) {
|
|
434
|
-
reject(error);
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
return;
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
|
|
441
|
-
const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);
|
|
442
|
-
|
|
443
|
-
if (typeof promise.cancel === 'function') {
|
|
444
|
-
promise.cancel();
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
reject(timeoutError);
|
|
448
|
-
}, milliseconds);
|
|
449
|
-
|
|
450
|
-
(async () => {
|
|
451
|
-
try {
|
|
452
|
-
resolve(await promise);
|
|
453
|
-
} catch (error) {
|
|
454
|
-
reject(error);
|
|
455
|
-
} finally {
|
|
456
|
-
options.customTimers.clearTimeout.call(undefined, timer);
|
|
457
|
-
}
|
|
458
|
-
})();
|
|
459
|
-
});
|
|
460
|
-
|
|
461
|
-
cancelablePromise.clear = () => {
|
|
462
|
-
clearTimeout(timer);
|
|
463
|
-
timer = undefined;
|
|
464
|
-
};
|
|
465
|
-
|
|
466
|
-
return cancelablePromise;
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound
|
|
470
|
-
// Used to compute insertion index to keep queue sorted after insertion
|
|
471
|
-
function lowerBound(array, value, comparator) {
|
|
472
|
-
let first = 0;
|
|
473
|
-
let count = array.length;
|
|
474
|
-
while (count > 0) {
|
|
475
|
-
const step = Math.trunc(count / 2);
|
|
476
|
-
let it = first + step;
|
|
477
|
-
if (comparator(array[it], value) <= 0) {
|
|
478
|
-
first = ++it;
|
|
479
|
-
count -= step + 1;
|
|
480
|
-
}
|
|
481
|
-
else {
|
|
482
|
-
count = step;
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
return first;
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
var __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
489
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
490
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
491
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
492
|
-
};
|
|
493
|
-
var _PriorityQueue_queue;
|
|
494
|
-
class PriorityQueue {
|
|
495
|
-
constructor() {
|
|
496
|
-
_PriorityQueue_queue.set(this, []);
|
|
497
|
-
}
|
|
498
|
-
enqueue(run, options) {
|
|
499
|
-
options = {
|
|
500
|
-
priority: 0,
|
|
501
|
-
...options,
|
|
502
|
-
};
|
|
503
|
-
const element = {
|
|
504
|
-
priority: options.priority,
|
|
505
|
-
run,
|
|
506
|
-
};
|
|
507
|
-
if (this.size && __classPrivateFieldGet$1(this, _PriorityQueue_queue, "f")[this.size - 1].priority >= options.priority) {
|
|
508
|
-
__classPrivateFieldGet$1(this, _PriorityQueue_queue, "f").push(element);
|
|
509
|
-
return;
|
|
510
|
-
}
|
|
511
|
-
const index = lowerBound(__classPrivateFieldGet$1(this, _PriorityQueue_queue, "f"), element, (a, b) => b.priority - a.priority);
|
|
512
|
-
__classPrivateFieldGet$1(this, _PriorityQueue_queue, "f").splice(index, 0, element);
|
|
513
|
-
}
|
|
514
|
-
dequeue() {
|
|
515
|
-
const item = __classPrivateFieldGet$1(this, _PriorityQueue_queue, "f").shift();
|
|
516
|
-
return item === null || item === void 0 ? void 0 : item.run;
|
|
517
|
-
}
|
|
518
|
-
filter(options) {
|
|
519
|
-
return __classPrivateFieldGet$1(this, _PriorityQueue_queue, "f").filter((element) => element.priority === options.priority).map((element) => element.run);
|
|
520
|
-
}
|
|
521
|
-
get size() {
|
|
522
|
-
return __classPrivateFieldGet$1(this, _PriorityQueue_queue, "f").length;
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
_PriorityQueue_queue = new WeakMap();
|
|
526
|
-
|
|
527
|
-
var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
528
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
529
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
530
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
531
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
532
|
-
};
|
|
533
|
-
var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
534
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
535
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
536
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
537
|
-
};
|
|
538
|
-
var _PQueue_instances, _PQueue_carryoverConcurrencyCount, _PQueue_isIntervalIgnored, _PQueue_intervalCount, _PQueue_intervalCap, _PQueue_interval, _PQueue_intervalEnd, _PQueue_intervalId, _PQueue_timeoutId, _PQueue_queue, _PQueue_queueClass, _PQueue_pending, _PQueue_concurrency, _PQueue_isPaused, _PQueue_throwOnTimeout, _PQueue_doesIntervalAllowAnother_get, _PQueue_doesConcurrentAllowAnother_get, _PQueue_next, _PQueue_onResumeInterval, _PQueue_isIntervalPaused_get, _PQueue_tryToStartAnother, _PQueue_initializeIntervalIfNeeded, _PQueue_onInterval, _PQueue_processQueue, _PQueue_throwOnAbort, _PQueue_onEvent;
|
|
539
|
-
/**
|
|
540
|
-
The error thrown by `queue.add()` when a job is aborted before it is run. See `signal`.
|
|
541
|
-
*/
|
|
542
|
-
class AbortError extends Error {
|
|
543
|
-
}
|
|
544
|
-
/**
|
|
545
|
-
Promise queue with concurrency control.
|
|
546
|
-
*/
|
|
547
|
-
class PQueue extends EventEmitter {
|
|
548
|
-
// TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`
|
|
549
|
-
constructor(options) {
|
|
550
|
-
var _a, _b, _c, _d;
|
|
551
|
-
super();
|
|
552
|
-
_PQueue_instances.add(this);
|
|
553
|
-
_PQueue_carryoverConcurrencyCount.set(this, void 0);
|
|
554
|
-
_PQueue_isIntervalIgnored.set(this, void 0);
|
|
555
|
-
_PQueue_intervalCount.set(this, 0);
|
|
556
|
-
_PQueue_intervalCap.set(this, void 0);
|
|
557
|
-
_PQueue_interval.set(this, void 0);
|
|
558
|
-
_PQueue_intervalEnd.set(this, 0);
|
|
559
|
-
_PQueue_intervalId.set(this, void 0);
|
|
560
|
-
_PQueue_timeoutId.set(this, void 0);
|
|
561
|
-
_PQueue_queue.set(this, void 0);
|
|
562
|
-
_PQueue_queueClass.set(this, void 0);
|
|
563
|
-
_PQueue_pending.set(this, 0);
|
|
564
|
-
// The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
|
|
565
|
-
_PQueue_concurrency.set(this, void 0);
|
|
566
|
-
_PQueue_isPaused.set(this, void 0);
|
|
567
|
-
_PQueue_throwOnTimeout.set(this, void 0);
|
|
568
|
-
/**
|
|
569
|
-
Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.
|
|
570
|
-
|
|
571
|
-
Applies to each future operation.
|
|
572
|
-
*/
|
|
573
|
-
Object.defineProperty(this, "timeout", {
|
|
574
|
-
enumerable: true,
|
|
575
|
-
configurable: true,
|
|
576
|
-
writable: true,
|
|
577
|
-
value: void 0
|
|
578
|
-
});
|
|
579
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
580
|
-
options = {
|
|
581
|
-
carryoverConcurrencyCount: false,
|
|
582
|
-
intervalCap: Number.POSITIVE_INFINITY,
|
|
583
|
-
interval: 0,
|
|
584
|
-
concurrency: Number.POSITIVE_INFINITY,
|
|
585
|
-
autoStart: true,
|
|
586
|
-
queueClass: PriorityQueue,
|
|
587
|
-
...options,
|
|
588
|
-
};
|
|
589
|
-
if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {
|
|
590
|
-
throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`);
|
|
591
|
-
}
|
|
592
|
-
if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {
|
|
593
|
-
throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`);
|
|
594
|
-
}
|
|
595
|
-
__classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, "f");
|
|
596
|
-
__classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, "f");
|
|
597
|
-
__classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, "f");
|
|
598
|
-
__classPrivateFieldSet(this, _PQueue_interval, options.interval, "f");
|
|
599
|
-
__classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), "f");
|
|
600
|
-
__classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, "f");
|
|
601
|
-
this.concurrency = options.concurrency;
|
|
602
|
-
this.timeout = options.timeout;
|
|
603
|
-
__classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, "f");
|
|
604
|
-
__classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, "f");
|
|
605
|
-
}
|
|
606
|
-
get concurrency() {
|
|
607
|
-
return __classPrivateFieldGet(this, _PQueue_concurrency, "f");
|
|
608
|
-
}
|
|
609
|
-
set concurrency(newConcurrency) {
|
|
610
|
-
if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {
|
|
611
|
-
throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
|
|
612
|
-
}
|
|
613
|
-
__classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, "f");
|
|
614
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_processQueue).call(this);
|
|
615
|
-
}
|
|
616
|
-
async add(function_, options = {}) {
|
|
617
|
-
options = {
|
|
618
|
-
timeout: this.timeout,
|
|
619
|
-
throwOnTimeout: __classPrivateFieldGet(this, _PQueue_throwOnTimeout, "f"),
|
|
620
|
-
...options,
|
|
621
|
-
};
|
|
622
|
-
return new Promise((resolve, reject) => {
|
|
623
|
-
__classPrivateFieldGet(this, _PQueue_queue, "f").enqueue(async () => {
|
|
624
|
-
var _a;
|
|
625
|
-
var _b, _c;
|
|
626
|
-
__classPrivateFieldSet(this, _PQueue_pending, (_b = __classPrivateFieldGet(this, _PQueue_pending, "f"), _b++, _b), "f");
|
|
627
|
-
__classPrivateFieldSet(this, _PQueue_intervalCount, (_c = __classPrivateFieldGet(this, _PQueue_intervalCount, "f"), _c++, _c), "f");
|
|
628
|
-
try {
|
|
629
|
-
// TODO: Use options.signal?.throwIfAborted() when targeting Node.js 18
|
|
630
|
-
if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
|
|
631
|
-
// TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)
|
|
632
|
-
throw new AbortError('The task was aborted.');
|
|
633
|
-
}
|
|
634
|
-
let operation = function_({ signal: options.signal });
|
|
635
|
-
if (options.timeout) {
|
|
636
|
-
operation = pTimeout(Promise.resolve(operation), options.timeout);
|
|
637
|
-
}
|
|
638
|
-
if (options.signal) {
|
|
639
|
-
operation = Promise.race([operation, __classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_throwOnAbort).call(this, options.signal)]);
|
|
640
|
-
}
|
|
641
|
-
const result = await operation;
|
|
642
|
-
resolve(result);
|
|
643
|
-
this.emit('completed', result);
|
|
644
|
-
}
|
|
645
|
-
catch (error) {
|
|
646
|
-
if (error instanceof TimeoutError && !options.throwOnTimeout) {
|
|
647
|
-
resolve();
|
|
648
|
-
return;
|
|
649
|
-
}
|
|
650
|
-
reject(error);
|
|
651
|
-
this.emit('error', error);
|
|
652
|
-
}
|
|
653
|
-
finally {
|
|
654
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_next).call(this);
|
|
655
|
-
}
|
|
656
|
-
}, options);
|
|
657
|
-
this.emit('add');
|
|
658
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_tryToStartAnother).call(this);
|
|
659
|
-
});
|
|
660
|
-
}
|
|
661
|
-
async addAll(functions, options) {
|
|
662
|
-
return Promise.all(functions.map(async (function_) => this.add(function_, options)));
|
|
663
|
-
}
|
|
664
|
-
/**
|
|
665
|
-
Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
|
|
666
|
-
*/
|
|
667
|
-
start() {
|
|
668
|
-
if (!__classPrivateFieldGet(this, _PQueue_isPaused, "f")) {
|
|
669
|
-
return this;
|
|
670
|
-
}
|
|
671
|
-
__classPrivateFieldSet(this, _PQueue_isPaused, false, "f");
|
|
672
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_processQueue).call(this);
|
|
673
|
-
return this;
|
|
674
|
-
}
|
|
675
|
-
/**
|
|
676
|
-
Put queue execution on hold.
|
|
677
|
-
*/
|
|
678
|
-
pause() {
|
|
679
|
-
__classPrivateFieldSet(this, _PQueue_isPaused, true, "f");
|
|
680
|
-
}
|
|
681
|
-
/**
|
|
682
|
-
Clear the queue.
|
|
683
|
-
*/
|
|
684
|
-
clear() {
|
|
685
|
-
__classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet(this, _PQueue_queueClass, "f"))(), "f");
|
|
686
|
-
}
|
|
687
|
-
/**
|
|
688
|
-
Can be called multiple times. Useful if you for example add additional items at a later time.
|
|
689
|
-
|
|
690
|
-
@returns A promise that settles when the queue becomes empty.
|
|
691
|
-
*/
|
|
692
|
-
async onEmpty() {
|
|
693
|
-
// Instantly resolve if the queue is empty
|
|
694
|
-
if (__classPrivateFieldGet(this, _PQueue_queue, "f").size === 0) {
|
|
695
|
-
return;
|
|
696
|
-
}
|
|
697
|
-
await __classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_onEvent).call(this, 'empty');
|
|
698
|
-
}
|
|
699
|
-
/**
|
|
700
|
-
@returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.
|
|
701
|
-
|
|
702
|
-
If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.
|
|
703
|
-
|
|
704
|
-
Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.
|
|
705
|
-
*/
|
|
706
|
-
async onSizeLessThan(limit) {
|
|
707
|
-
// Instantly resolve if the queue is empty.
|
|
708
|
-
if (__classPrivateFieldGet(this, _PQueue_queue, "f").size < limit) {
|
|
709
|
-
return;
|
|
710
|
-
}
|
|
711
|
-
await __classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_onEvent).call(this, 'next', () => __classPrivateFieldGet(this, _PQueue_queue, "f").size < limit);
|
|
712
|
-
}
|
|
713
|
-
/**
|
|
714
|
-
The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
|
|
715
|
-
|
|
716
|
-
@returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
|
|
717
|
-
*/
|
|
718
|
-
async onIdle() {
|
|
719
|
-
// Instantly resolve if none pending and if nothing else is queued
|
|
720
|
-
if (__classPrivateFieldGet(this, _PQueue_pending, "f") === 0 && __classPrivateFieldGet(this, _PQueue_queue, "f").size === 0) {
|
|
721
|
-
return;
|
|
722
|
-
}
|
|
723
|
-
await __classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_onEvent).call(this, 'idle');
|
|
724
|
-
}
|
|
725
|
-
/**
|
|
726
|
-
Size of the queue, the number of queued items waiting to run.
|
|
727
|
-
*/
|
|
728
|
-
get size() {
|
|
729
|
-
return __classPrivateFieldGet(this, _PQueue_queue, "f").size;
|
|
730
|
-
}
|
|
731
|
-
/**
|
|
732
|
-
Size of the queue, filtered by the given options.
|
|
733
|
-
|
|
734
|
-
For example, this can be used to find the number of items remaining in the queue with a specific priority level.
|
|
735
|
-
*/
|
|
736
|
-
sizeBy(options) {
|
|
737
|
-
// eslint-disable-next-line unicorn/no-array-callback-reference
|
|
738
|
-
return __classPrivateFieldGet(this, _PQueue_queue, "f").filter(options).length;
|
|
739
|
-
}
|
|
740
|
-
/**
|
|
741
|
-
Number of running items (no longer in the queue).
|
|
742
|
-
*/
|
|
743
|
-
get pending() {
|
|
744
|
-
return __classPrivateFieldGet(this, _PQueue_pending, "f");
|
|
745
|
-
}
|
|
746
|
-
/**
|
|
747
|
-
Whether the queue is currently paused.
|
|
748
|
-
*/
|
|
749
|
-
get isPaused() {
|
|
750
|
-
return __classPrivateFieldGet(this, _PQueue_isPaused, "f");
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
_PQueue_carryoverConcurrencyCount = new WeakMap(), _PQueue_isIntervalIgnored = new WeakMap(), _PQueue_intervalCount = new WeakMap(), _PQueue_intervalCap = new WeakMap(), _PQueue_interval = new WeakMap(), _PQueue_intervalEnd = new WeakMap(), _PQueue_intervalId = new WeakMap(), _PQueue_timeoutId = new WeakMap(), _PQueue_queue = new WeakMap(), _PQueue_queueClass = new WeakMap(), _PQueue_pending = new WeakMap(), _PQueue_concurrency = new WeakMap(), _PQueue_isPaused = new WeakMap(), _PQueue_throwOnTimeout = new WeakMap(), _PQueue_instances = new WeakSet(), _PQueue_doesIntervalAllowAnother_get = function _PQueue_doesIntervalAllowAnother_get() {
|
|
754
|
-
return __classPrivateFieldGet(this, _PQueue_isIntervalIgnored, "f") || __classPrivateFieldGet(this, _PQueue_intervalCount, "f") < __classPrivateFieldGet(this, _PQueue_intervalCap, "f");
|
|
755
|
-
}, _PQueue_doesConcurrentAllowAnother_get = function _PQueue_doesConcurrentAllowAnother_get() {
|
|
756
|
-
return __classPrivateFieldGet(this, _PQueue_pending, "f") < __classPrivateFieldGet(this, _PQueue_concurrency, "f");
|
|
757
|
-
}, _PQueue_next = function _PQueue_next() {
|
|
758
|
-
var _a;
|
|
759
|
-
__classPrivateFieldSet(this, _PQueue_pending, (_a = __classPrivateFieldGet(this, _PQueue_pending, "f"), _a--, _a), "f");
|
|
760
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_tryToStartAnother).call(this);
|
|
761
|
-
this.emit('next');
|
|
762
|
-
}, _PQueue_onResumeInterval = function _PQueue_onResumeInterval() {
|
|
763
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_onInterval).call(this);
|
|
764
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_initializeIntervalIfNeeded).call(this);
|
|
765
|
-
__classPrivateFieldSet(this, _PQueue_timeoutId, undefined, "f");
|
|
766
|
-
}, _PQueue_isIntervalPaused_get = function _PQueue_isIntervalPaused_get() {
|
|
767
|
-
const now = Date.now();
|
|
768
|
-
if (__classPrivateFieldGet(this, _PQueue_intervalId, "f") === undefined) {
|
|
769
|
-
const delay = __classPrivateFieldGet(this, _PQueue_intervalEnd, "f") - now;
|
|
770
|
-
if (delay < 0) {
|
|
771
|
-
// Act as the interval was done
|
|
772
|
-
// We don't need to resume it here because it will be resumed on line 160
|
|
773
|
-
__classPrivateFieldSet(this, _PQueue_intervalCount, (__classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, "f")) ? __classPrivateFieldGet(this, _PQueue_pending, "f") : 0, "f");
|
|
774
|
-
}
|
|
775
|
-
else {
|
|
776
|
-
// Act as the interval is pending
|
|
777
|
-
if (__classPrivateFieldGet(this, _PQueue_timeoutId, "f") === undefined) {
|
|
778
|
-
__classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => {
|
|
779
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_onResumeInterval).call(this);
|
|
780
|
-
}, delay), "f");
|
|
781
|
-
}
|
|
782
|
-
return true;
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
return false;
|
|
786
|
-
}, _PQueue_tryToStartAnother = function _PQueue_tryToStartAnother() {
|
|
787
|
-
if (__classPrivateFieldGet(this, _PQueue_queue, "f").size === 0) {
|
|
788
|
-
// We can clear the interval ("pause")
|
|
789
|
-
// Because we can redo it later ("resume")
|
|
790
|
-
if (__classPrivateFieldGet(this, _PQueue_intervalId, "f")) {
|
|
791
|
-
clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, "f"));
|
|
792
|
-
}
|
|
793
|
-
__classPrivateFieldSet(this, _PQueue_intervalId, undefined, "f");
|
|
794
|
-
this.emit('empty');
|
|
795
|
-
if (__classPrivateFieldGet(this, _PQueue_pending, "f") === 0) {
|
|
796
|
-
this.emit('idle');
|
|
797
|
-
}
|
|
798
|
-
return false;
|
|
799
|
-
}
|
|
800
|
-
if (!__classPrivateFieldGet(this, _PQueue_isPaused, "f")) {
|
|
801
|
-
const canInitializeInterval = !__classPrivateFieldGet(this, _PQueue_instances, "a", _PQueue_isIntervalPaused_get);
|
|
802
|
-
if (__classPrivateFieldGet(this, _PQueue_instances, "a", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet(this, _PQueue_instances, "a", _PQueue_doesConcurrentAllowAnother_get)) {
|
|
803
|
-
const job = __classPrivateFieldGet(this, _PQueue_queue, "f").dequeue();
|
|
804
|
-
if (!job) {
|
|
805
|
-
return false;
|
|
806
|
-
}
|
|
807
|
-
this.emit('active');
|
|
808
|
-
job();
|
|
809
|
-
if (canInitializeInterval) {
|
|
810
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_initializeIntervalIfNeeded).call(this);
|
|
811
|
-
}
|
|
812
|
-
return true;
|
|
813
|
-
}
|
|
814
|
-
}
|
|
815
|
-
return false;
|
|
816
|
-
}, _PQueue_initializeIntervalIfNeeded = function _PQueue_initializeIntervalIfNeeded() {
|
|
817
|
-
if (__classPrivateFieldGet(this, _PQueue_isIntervalIgnored, "f") || __classPrivateFieldGet(this, _PQueue_intervalId, "f") !== undefined) {
|
|
818
|
-
return;
|
|
819
|
-
}
|
|
820
|
-
__classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => {
|
|
821
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_onInterval).call(this);
|
|
822
|
-
}, __classPrivateFieldGet(this, _PQueue_interval, "f")), "f");
|
|
823
|
-
__classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet(this, _PQueue_interval, "f"), "f");
|
|
824
|
-
}, _PQueue_onInterval = function _PQueue_onInterval() {
|
|
825
|
-
if (__classPrivateFieldGet(this, _PQueue_intervalCount, "f") === 0 && __classPrivateFieldGet(this, _PQueue_pending, "f") === 0 && __classPrivateFieldGet(this, _PQueue_intervalId, "f")) {
|
|
826
|
-
clearInterval(__classPrivateFieldGet(this, _PQueue_intervalId, "f"));
|
|
827
|
-
__classPrivateFieldSet(this, _PQueue_intervalId, undefined, "f");
|
|
828
|
-
}
|
|
829
|
-
__classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet(this, _PQueue_carryoverConcurrencyCount, "f") ? __classPrivateFieldGet(this, _PQueue_pending, "f") : 0, "f");
|
|
830
|
-
__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_processQueue).call(this);
|
|
831
|
-
}, _PQueue_processQueue = function _PQueue_processQueue() {
|
|
832
|
-
// eslint-disable-next-line no-empty
|
|
833
|
-
while (__classPrivateFieldGet(this, _PQueue_instances, "m", _PQueue_tryToStartAnother).call(this)) { }
|
|
834
|
-
}, _PQueue_throwOnAbort = async function _PQueue_throwOnAbort(signal) {
|
|
835
|
-
return new Promise((_resolve, reject) => {
|
|
836
|
-
signal.addEventListener('abort', () => {
|
|
837
|
-
// TODO: Reject with signal.throwIfAborted() when targeting Node.js 18
|
|
838
|
-
// TODO: Use ABORT_ERR code when targeting Node.js 16 (https://nodejs.org/docs/latest-v16.x/api/errors.html#abort_err)
|
|
839
|
-
reject(new AbortError('The task was aborted.'));
|
|
840
|
-
}, { once: true });
|
|
841
|
-
});
|
|
842
|
-
}, _PQueue_onEvent = async function _PQueue_onEvent(event, filter) {
|
|
843
|
-
return new Promise(resolve => {
|
|
844
|
-
const listener = () => {
|
|
845
|
-
if (filter && !filter()) {
|
|
846
|
-
return;
|
|
847
|
-
}
|
|
848
|
-
this.off(event, listener);
|
|
849
|
-
resolve();
|
|
850
|
-
};
|
|
851
|
-
this.on(event, listener);
|
|
852
|
-
});
|
|
853
|
-
};
|
|
854
|
-
|
|
855
|
-
function buildLog(text, count) {
|
|
856
|
-
console.log(`
|
|
857
|
-
${gray("[vite-react-ssg]")} ${yellow(text)}${count ? blue(` (${count})`) : ""}`);
|
|
858
|
-
}
|
|
859
|
-
function getSize(str) {
|
|
860
|
-
return `${(str.length / 1024).toFixed(2)} KiB`;
|
|
861
|
-
}
|
|
862
|
-
async function routesToPaths(routes) {
|
|
863
|
-
const pathToEntry = {};
|
|
864
|
-
function addEntry(path, entry) {
|
|
865
|
-
if (!entry)
|
|
866
|
-
return;
|
|
867
|
-
if (entry[0] === "/")
|
|
868
|
-
entry = entry.slice(1);
|
|
869
|
-
if (pathToEntry[path])
|
|
870
|
-
pathToEntry[path].add(entry);
|
|
871
|
-
else
|
|
872
|
-
pathToEntry[path] = /* @__PURE__ */ new Set([entry]);
|
|
873
|
-
}
|
|
874
|
-
if (!routes)
|
|
875
|
-
return { paths: ["/"], pathToEntry };
|
|
876
|
-
const paths = /* @__PURE__ */ new Set();
|
|
877
|
-
const lazyPaths = /* @__PURE__ */ new Set();
|
|
878
|
-
const getPaths = async (routes2, prefix = "") => {
|
|
879
|
-
prefix = prefix.replace(/\/$/g, "");
|
|
880
|
-
for (const route of routes2) {
|
|
881
|
-
let path = route.path;
|
|
882
|
-
path = handlePath(path, prefix, route.entry);
|
|
883
|
-
if (route.getStaticPaths && path?.includes(":")) {
|
|
884
|
-
const staticPaths = await route.getStaticPaths();
|
|
885
|
-
for (let staticPath of staticPaths) {
|
|
886
|
-
staticPath = handlePath(staticPath, prefix, route.entry);
|
|
887
|
-
if (Array.isArray(route.children))
|
|
888
|
-
await getPaths(route.children, staticPath);
|
|
889
|
-
}
|
|
890
|
-
}
|
|
891
|
-
if (route.lazy)
|
|
892
|
-
lazyPaths.add(route.index ? prefix : path ?? "");
|
|
893
|
-
if (route.index)
|
|
894
|
-
addEntry(prefix, route.entry);
|
|
895
|
-
if (Array.isArray(route.children))
|
|
896
|
-
await getPaths(route.children, path);
|
|
897
|
-
}
|
|
898
|
-
};
|
|
899
|
-
await getPaths(routes);
|
|
900
|
-
return { paths: Array.from(paths), pathToEntry, lazyPaths: Array.from(lazyPaths) };
|
|
901
|
-
function handlePath(path, prefix, entry) {
|
|
902
|
-
if (path != null) {
|
|
903
|
-
path = prefix && !path.startsWith("/") ? `${prefix}${path ? `/${path}` : ""}` : path;
|
|
904
|
-
paths.add(path);
|
|
905
|
-
addEntry(path, entry);
|
|
906
|
-
if (pathToEntry[prefix]) {
|
|
907
|
-
const pathCopy = path;
|
|
908
|
-
pathToEntry[prefix].forEach((entry2) => addEntry(pathCopy, entry2));
|
|
909
|
-
}
|
|
910
|
-
}
|
|
911
|
-
return path;
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
function createFetchRequest(req) {
|
|
915
|
-
const origin = `${req.protocol}://${req.get("host")}`;
|
|
916
|
-
const url = new URL(req.originalUrl || req.url, origin);
|
|
917
|
-
const controller = new AbortController();
|
|
918
|
-
req.on("close", () => controller.abort());
|
|
919
|
-
const headers = new Headers();
|
|
920
|
-
for (const [key, values] of Object.entries(req.headers)) {
|
|
921
|
-
if (values) {
|
|
922
|
-
if (Array.isArray(values)) {
|
|
923
|
-
for (const value of values)
|
|
924
|
-
headers.append(key, value);
|
|
925
|
-
} else {
|
|
926
|
-
headers.set(key, values);
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
}
|
|
930
|
-
const init = {
|
|
931
|
-
method: req.method,
|
|
932
|
-
headers,
|
|
933
|
-
signal: controller.signal
|
|
934
|
-
};
|
|
935
|
-
if (req.method !== "GET" && req.method !== "HEAD")
|
|
936
|
-
init.body = req.body;
|
|
937
|
-
return new Request(url.href, init);
|
|
938
|
-
}
|
|
939
|
-
async function resolveAlias(config, entry) {
|
|
940
|
-
const resolver = config.createResolver();
|
|
941
|
-
const result = await resolver(entry, config.root);
|
|
942
|
-
return result || join(config.root, entry);
|
|
943
|
-
}
|
|
944
|
-
const { version } = JSON.parse(
|
|
945
|
-
readFileSync(new URL("../../package.json", import.meta.url)).toString()
|
|
946
|
-
);
|
|
947
|
-
function createRequest(path) {
|
|
948
|
-
const url = new URL(path, "http://vite-react-ssg.com");
|
|
949
|
-
url.search = "";
|
|
950
|
-
url.hash = "";
|
|
951
|
-
url.pathname = path;
|
|
952
|
-
return new Request(url.href);
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
async function getCritters(outDir, options = {}) {
|
|
956
|
-
try {
|
|
957
|
-
const CrittersClass = (await import('critters')).default;
|
|
958
|
-
return new CrittersClass({
|
|
959
|
-
path: outDir,
|
|
960
|
-
logLevel: "warn",
|
|
961
|
-
external: true,
|
|
962
|
-
inlineFonts: true,
|
|
963
|
-
preloadFonts: true,
|
|
964
|
-
...options
|
|
965
|
-
});
|
|
966
|
-
} catch (e) {
|
|
967
|
-
return void 0;
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
async function renderStaticApp(app) {
|
|
972
|
-
const writableStream = new WritableAsPromise();
|
|
973
|
-
const { pipe } = renderToPipeableStream(app, {
|
|
974
|
-
onError(error) {
|
|
975
|
-
writableStream.destroy(error);
|
|
976
|
-
},
|
|
977
|
-
onAllReady() {
|
|
978
|
-
pipe(writableStream);
|
|
979
|
-
}
|
|
980
|
-
});
|
|
981
|
-
return writableStream.getPromise();
|
|
982
|
-
}
|
|
983
|
-
class WritableAsPromise extends Writable {
|
|
984
|
-
constructor() {
|
|
985
|
-
super();
|
|
986
|
-
this._output = "";
|
|
987
|
-
this._deferred = {
|
|
988
|
-
promise: null,
|
|
989
|
-
resolve: () => null,
|
|
990
|
-
reject: () => null
|
|
991
|
-
};
|
|
992
|
-
this._deferred.promise = new Promise((resolve, reject) => {
|
|
993
|
-
this._deferred.resolve = resolve;
|
|
994
|
-
this._deferred.reject = reject;
|
|
995
|
-
});
|
|
996
|
-
}
|
|
997
|
-
_write(chunk, _enc, next) {
|
|
998
|
-
this._output += chunk.toString();
|
|
999
|
-
next();
|
|
1000
|
-
}
|
|
1001
|
-
_destroy(error, next) {
|
|
1002
|
-
if (error instanceof Error)
|
|
1003
|
-
this._deferred.reject(error);
|
|
1004
|
-
else
|
|
1005
|
-
next();
|
|
1006
|
-
}
|
|
1007
|
-
end() {
|
|
1008
|
-
this._deferred.resolve(this._output);
|
|
1009
|
-
return this.destroy();
|
|
1010
|
-
}
|
|
1011
|
-
getPromise() {
|
|
1012
|
-
return this._deferred.promise;
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
|
|
1016
|
-
async function render(routes, request, styleCollector) {
|
|
1017
|
-
const { dataRoutes, query } = createStaticHandler(routes);
|
|
1018
|
-
const context = await query(request);
|
|
1019
|
-
const helmetContext = {};
|
|
1020
|
-
if (context instanceof Response)
|
|
1021
|
-
throw context;
|
|
1022
|
-
const router = createStaticRouter(dataRoutes, context);
|
|
1023
|
-
let app = /* @__PURE__ */ React.createElement(HelmetProvider, { context: helmetContext }, /* @__PURE__ */ React.createElement(SiteMetadataDefaults, null), /* @__PURE__ */ React.createElement(StaticRouterProvider, { router, context }));
|
|
1024
|
-
if (styleCollector)
|
|
1025
|
-
app = styleCollector.collect(app);
|
|
1026
|
-
const appHTML = await renderStaticApp(app);
|
|
1027
|
-
const { helmet } = helmetContext;
|
|
1028
|
-
const htmlAttributes = helmet.htmlAttributes.toString();
|
|
1029
|
-
const bodyAttributes = helmet.bodyAttributes.toString();
|
|
1030
|
-
const metaStrings = [
|
|
1031
|
-
helmet.title.toString(),
|
|
1032
|
-
helmet.meta.toString(),
|
|
1033
|
-
helmet.link.toString(),
|
|
1034
|
-
helmet.script.toString()
|
|
1035
|
-
];
|
|
1036
|
-
const styleTag = styleCollector?.toString?.(appHTML) ?? "";
|
|
1037
|
-
const metaAttributes = metaStrings.filter(Boolean);
|
|
1038
|
-
return { appHTML, htmlAttributes, bodyAttributes, metaAttributes, styleTag, routerContext: context };
|
|
1039
|
-
}
|
|
1040
|
-
async function preLoad(routes, paths) {
|
|
1041
|
-
if (!paths || paths.length === 0)
|
|
1042
|
-
return routes;
|
|
1043
|
-
const { dataRoutes, query } = createStaticHandler(routes);
|
|
1044
|
-
await Promise.all(paths.map(async (path) => {
|
|
1045
|
-
const request = createRequest(path);
|
|
1046
|
-
return query(request);
|
|
1047
|
-
}));
|
|
1048
|
-
return dataRoutes;
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
function renderPreloadLinks(document, modules, ssrManifest) {
|
|
1052
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1053
|
-
const preloadLinks = [];
|
|
1054
|
-
Array.from(modules).forEach((id) => {
|
|
1055
|
-
const files = ssrManifest[id] || [];
|
|
1056
|
-
files.forEach((file) => {
|
|
1057
|
-
if (!preloadLinks.includes(file))
|
|
1058
|
-
preloadLinks.push(file);
|
|
1059
|
-
});
|
|
1060
|
-
});
|
|
1061
|
-
if (preloadLinks) {
|
|
1062
|
-
preloadLinks.forEach((file) => {
|
|
1063
|
-
if (!seen.has(file)) {
|
|
1064
|
-
seen.add(file);
|
|
1065
|
-
renderPreloadLink(document, file);
|
|
1066
|
-
}
|
|
1067
|
-
});
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
function renderPreloadLink(document, file) {
|
|
1071
|
-
if (file.endsWith(".js")) {
|
|
1072
|
-
appendLink(document, {
|
|
1073
|
-
rel: "modulepreload",
|
|
1074
|
-
crossOrigin: "",
|
|
1075
|
-
href: file
|
|
1076
|
-
});
|
|
1077
|
-
} else if (file.endsWith(".css")) {
|
|
1078
|
-
appendLink(document, {
|
|
1079
|
-
rel: "stylesheet",
|
|
1080
|
-
href: file
|
|
1081
|
-
});
|
|
1082
|
-
}
|
|
1083
|
-
}
|
|
1084
|
-
function createLink$1(document) {
|
|
1085
|
-
return document.createElement("link");
|
|
1086
|
-
}
|
|
1087
|
-
function setAttrs(el, attrs) {
|
|
1088
|
-
const keys = Object.keys(attrs);
|
|
1089
|
-
for (const key of keys)
|
|
1090
|
-
el.setAttribute(key, attrs[key]);
|
|
1091
|
-
}
|
|
1092
|
-
function appendLink(document, attrs) {
|
|
1093
|
-
const exits = document.head.querySelector(`link[href='${attrs.file}']`);
|
|
1094
|
-
if (exits)
|
|
1095
|
-
return;
|
|
1096
|
-
const link = createLink$1(document);
|
|
1097
|
-
setAttrs(link, attrs);
|
|
1098
|
-
document.head.appendChild(link);
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
async function renderHTML({
|
|
1102
|
-
rootContainerId,
|
|
1103
|
-
indexHTML,
|
|
1104
|
-
appHTML,
|
|
1105
|
-
metaAttributes,
|
|
1106
|
-
bodyAttributes,
|
|
1107
|
-
htmlAttributes,
|
|
1108
|
-
initialState
|
|
1109
|
-
}) {
|
|
1110
|
-
const stateScript = initialState ? `
|
|
1111
|
-
<script>window.__INITIAL_STATE__=${initialState}<\/script>` : "";
|
|
1112
|
-
const headStartTag = "<head>";
|
|
1113
|
-
const metaTags = metaAttributes.join("");
|
|
1114
|
-
indexHTML = indexHTML.replace(headStartTag, headStartTag + metaTags);
|
|
1115
|
-
const bodyStartTag = "<body";
|
|
1116
|
-
indexHTML = indexHTML.replace(bodyStartTag, `${bodyStartTag} ${bodyAttributes}`);
|
|
1117
|
-
const htmlStartTag = "<html";
|
|
1118
|
-
indexHTML = indexHTML.replace(htmlStartTag, `${htmlStartTag} ${htmlAttributes}`);
|
|
1119
|
-
const container = `<div id="${rootContainerId}"></div>`;
|
|
1120
|
-
if (indexHTML.includes(container)) {
|
|
1121
|
-
return indexHTML.replace(
|
|
1122
|
-
container,
|
|
1123
|
-
`<div id="${rootContainerId}" data-server-rendered="true">${appHTML}</div>${stateScript}`
|
|
1124
|
-
);
|
|
1125
|
-
}
|
|
1126
|
-
const html5Parser = await import('html5parser');
|
|
1127
|
-
const ast = html5Parser.parse(indexHTML);
|
|
1128
|
-
let renderedOutput;
|
|
1129
|
-
html5Parser.walk(ast, {
|
|
1130
|
-
enter: (node) => {
|
|
1131
|
-
if (!renderedOutput && node?.type === html5Parser.SyntaxKind.Tag && Array.isArray(node.attributes) && node.attributes.length > 0 && node.attributes.some((attr) => attr.name.value === "id" && attr.value?.value === rootContainerId)) {
|
|
1132
|
-
const attributesStringified = [...node.attributes.map(({ name: { value: name }, value }) => `${name}="${value.value}"`)].join(" ");
|
|
1133
|
-
const indexHTMLBefore = indexHTML.slice(0, node.start);
|
|
1134
|
-
const indexHTMLAfter = indexHTML.slice(node.end);
|
|
1135
|
-
renderedOutput = `${indexHTMLBefore}<${node.name} ${attributesStringified} data-server-rendered="true">${appHTML}</${node.name}>${stateScript}${indexHTMLAfter}`;
|
|
1136
|
-
}
|
|
1137
|
-
}
|
|
1138
|
-
});
|
|
1139
|
-
if (!renderedOutput)
|
|
1140
|
-
throw new Error(`Could not find a tag with id="${rootContainerId}" to replace it with server-side rendered HTML`);
|
|
1141
|
-
return renderedOutput;
|
|
1142
|
-
}
|
|
1143
|
-
async function detectEntry(root) {
|
|
1144
|
-
const scriptSrcReg = /<script(?:.*?)src=["'](.+?)["'](?!<)(?:.*)\>(?:[\n\r\s]*?)(?:<\/script>)/img;
|
|
1145
|
-
const html = await fs.readFile(join(root, "index.html"), "utf-8");
|
|
1146
|
-
const scripts = [...html.matchAll(scriptSrcReg)];
|
|
1147
|
-
const [, entry] = scripts.find((matchResult) => {
|
|
1148
|
-
const [script] = matchResult;
|
|
1149
|
-
const [, scriptType] = script.match(/.*\stype=(?:'|")?([^>'"\s]+)/i) || [];
|
|
1150
|
-
return scriptType === "module";
|
|
1151
|
-
}) || [];
|
|
1152
|
-
return entry || "src/main.ts";
|
|
1153
|
-
}
|
|
1154
|
-
function createLink(href) {
|
|
1155
|
-
return `<link rel="stylesheet" href="${href}">`;
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
function DefaultIncludedRoutes(paths, _routes) {
|
|
1159
|
-
return paths.filter((i) => !i.includes(":") && !i.includes("*"));
|
|
1160
|
-
}
|
|
1161
|
-
async function build(ssgOptions = {}, viteConfig = {}) {
|
|
1162
|
-
const mode = process.env.MODE || process.env.NODE_ENV || ssgOptions.mode || "production";
|
|
1163
|
-
const config = await resolveConfig(viteConfig, "build", mode, mode);
|
|
1164
|
-
const cwd = process.cwd();
|
|
1165
|
-
const root = config.root || cwd;
|
|
1166
|
-
const ssgOut = join(root, ".vite-react-ssg-temp", Math.random().toString(36).substring(2, 12));
|
|
1167
|
-
const outDir = config.build.outDir || "dist";
|
|
1168
|
-
const out = isAbsolute(outDir) ? outDir : join(root, outDir);
|
|
1169
|
-
const {
|
|
1170
|
-
script = "sync",
|
|
1171
|
-
mock = false,
|
|
1172
|
-
entry = await detectEntry(root),
|
|
1173
|
-
formatting = "none",
|
|
1174
|
-
crittersOptions = {},
|
|
1175
|
-
includedRoutes: configIncludedRoutes = DefaultIncludedRoutes,
|
|
1176
|
-
onBeforePageRender,
|
|
1177
|
-
onPageRendered,
|
|
1178
|
-
onFinished,
|
|
1179
|
-
dirStyle = "flat",
|
|
1180
|
-
includeAllRoutes = false,
|
|
1181
|
-
format = "esm",
|
|
1182
|
-
concurrency = 20,
|
|
1183
|
-
rootContainerId = "root"
|
|
1184
|
-
} = Object.assign({}, config.ssgOptions || {}, ssgOptions);
|
|
1185
|
-
if (fs.existsSync(ssgOut))
|
|
1186
|
-
await fs.remove(ssgOut);
|
|
1187
|
-
buildLog("Build for client...");
|
|
1188
|
-
await build$1(mergeConfig(viteConfig, {
|
|
1189
|
-
build: {
|
|
1190
|
-
manifest: true,
|
|
1191
|
-
ssrManifest: true,
|
|
1192
|
-
rollupOptions: {
|
|
1193
|
-
input: {
|
|
1194
|
-
app: join(root, "./index.html")
|
|
1195
|
-
}
|
|
1196
|
-
}
|
|
1197
|
-
},
|
|
1198
|
-
mode: config.mode
|
|
1199
|
-
}));
|
|
1200
|
-
if (mock) {
|
|
1201
|
-
const { jsdomGlobal } = await import('../chunks/jsdomGlobal.mjs');
|
|
1202
|
-
jsdomGlobal();
|
|
1203
|
-
}
|
|
1204
|
-
buildLog("Build for server...");
|
|
1205
|
-
process.env.VITE_SSG = "true";
|
|
1206
|
-
const ssrEntry = await resolveAlias(config, entry);
|
|
1207
|
-
await build$1(mergeConfig(viteConfig, {
|
|
1208
|
-
build: {
|
|
1209
|
-
ssr: ssrEntry,
|
|
1210
|
-
outDir: ssgOut,
|
|
1211
|
-
minify: false,
|
|
1212
|
-
cssCodeSplit: false,
|
|
1213
|
-
rollupOptions: {
|
|
1214
|
-
output: format === "esm" ? {
|
|
1215
|
-
entryFileNames: "[name].mjs",
|
|
1216
|
-
format: "esm"
|
|
1217
|
-
} : {
|
|
1218
|
-
entryFileNames: "[name].cjs",
|
|
1219
|
-
format: "cjs"
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
},
|
|
1223
|
-
mode: config.mode
|
|
1224
|
-
}));
|
|
1225
|
-
const prefix = format === "esm" && process.platform === "win32" ? "file://" : "";
|
|
1226
|
-
const ext = format === "esm" ? ".mjs" : ".cjs";
|
|
1227
|
-
const serverEntry = join(prefix, ssgOut, parse(ssrEntry).name + ext);
|
|
1228
|
-
const _require = createRequire(import.meta.url);
|
|
1229
|
-
const { createRoot, includedRoutes: serverEntryIncludedRoutes } = format === "esm" ? await import(serverEntry) : _require(serverEntry);
|
|
1230
|
-
const includedRoutes = serverEntryIncludedRoutes || configIncludedRoutes;
|
|
1231
|
-
const { routes } = await createRoot(false);
|
|
1232
|
-
const { lazyPaths } = await routesToPaths(routes);
|
|
1233
|
-
const dataRoutes = await preLoad([...routes], lazyPaths);
|
|
1234
|
-
const { paths, pathToEntry } = await routesToPaths(dataRoutes);
|
|
1235
|
-
let routesPaths = includeAllRoutes ? paths : await includedRoutes(paths, routes || []);
|
|
1236
|
-
routesPaths = DefaultIncludedRoutes(routesPaths);
|
|
1237
|
-
routesPaths = Array.from(new Set(routesPaths));
|
|
1238
|
-
buildLog("Rendering Pages...", routesPaths.length);
|
|
1239
|
-
const critters = crittersOptions !== false ? await getCritters(outDir, crittersOptions) : void 0;
|
|
1240
|
-
if (critters)
|
|
1241
|
-
console.log(`${gray("[vite-react-ssg]")} ${blue("Critical CSS generation enabled via `critters`")}`);
|
|
1242
|
-
const ssrManifest = JSON.parse(await fs.readFile(join(out, "ssr-manifest.json"), "utf-8"));
|
|
1243
|
-
const manifest = JSON.parse(await fs.readFile(join(out, "manifest.json"), "utf-8"));
|
|
1244
|
-
let indexHTML = await fs.readFile(join(out, "index.html"), "utf-8");
|
|
1245
|
-
indexHTML = rewriteScripts(indexHTML, script);
|
|
1246
|
-
const queue = new PQueue({ concurrency });
|
|
1247
|
-
const crittersQueue = new PQueue({ concurrency: 1 });
|
|
1248
|
-
for (const path of routesPaths) {
|
|
1249
|
-
queue.add(async () => {
|
|
1250
|
-
try {
|
|
1251
|
-
const appCtx = await createRoot(false, path);
|
|
1252
|
-
const { initialState, routes: routes2, triggerOnSSRAppRendered, transformState = serializeState, getStyleCollector } = appCtx;
|
|
1253
|
-
const styleCollector = getStyleCollector ? await getStyleCollector() : null;
|
|
1254
|
-
const transformedIndexHTML = await onBeforePageRender?.(path, indexHTML, appCtx) || indexHTML;
|
|
1255
|
-
const request = createRequest(path);
|
|
1256
|
-
const { appHTML, bodyAttributes, htmlAttributes, metaAttributes, styleTag } = await render([...routes2], request, styleCollector);
|
|
1257
|
-
await triggerOnSSRAppRendered?.(path, appHTML, appCtx);
|
|
1258
|
-
const renderedHTML = await renderHTML({
|
|
1259
|
-
rootContainerId,
|
|
1260
|
-
appHTML,
|
|
1261
|
-
indexHTML: transformedIndexHTML,
|
|
1262
|
-
metaAttributes,
|
|
1263
|
-
bodyAttributes,
|
|
1264
|
-
htmlAttributes,
|
|
1265
|
-
initialState: null
|
|
1266
|
-
});
|
|
1267
|
-
const jsdom = new JSDOM(renderedHTML);
|
|
1268
|
-
const modules = collectModulesForEntrys(manifest, pathToEntry?.[path]);
|
|
1269
|
-
renderPreloadLinks(jsdom.window.document, modules, ssrManifest);
|
|
1270
|
-
const html = jsdom.serialize();
|
|
1271
|
-
let transformed = await onPageRendered?.(path, html, appCtx) || html;
|
|
1272
|
-
if (critters)
|
|
1273
|
-
transformed = await crittersQueue.add(() => critters.process(transformed));
|
|
1274
|
-
if (styleTag)
|
|
1275
|
-
transformed = transformed.replace("<head>", `<head>${styleTag}`);
|
|
1276
|
-
const formatted = await formatHtml(transformed, formatting);
|
|
1277
|
-
const relativeRouteFile = `${(path.endsWith("/") ? `${path}index` : path).replace(/^\//g, "")}.html`;
|
|
1278
|
-
const filename = dirStyle === "nested" ? join(path.replace(/^\//g, ""), "index.html") : relativeRouteFile;
|
|
1279
|
-
await fs.ensureDir(join(out, dirname(filename)));
|
|
1280
|
-
await fs.writeFile(join(out, filename), formatted, "utf-8");
|
|
1281
|
-
config.logger.info(
|
|
1282
|
-
`${dim(`${outDir}/`)}${cyan(filename.padEnd(15, " "))} ${dim(getSize(formatted))}`
|
|
1283
|
-
);
|
|
1284
|
-
} catch (err) {
|
|
1285
|
-
throw new Error(`${gray("[vite-react-ssg]")} ${red(`Error on page: ${cyan(path)}`)}
|
|
1286
|
-
${err.stack}`);
|
|
1287
|
-
}
|
|
1288
|
-
});
|
|
1289
|
-
}
|
|
1290
|
-
await queue.start().onIdle();
|
|
1291
|
-
await fs.remove(join(root, ".vite-react-ssg-temp"));
|
|
1292
|
-
const pwaPlugin = config.plugins.find((i) => i.name === "vite-plugin-pwa")?.api;
|
|
1293
|
-
if (pwaPlugin && !pwaPlugin.disabled && pwaPlugin.generateSW) {
|
|
1294
|
-
buildLog("Regenerate PWA...");
|
|
1295
|
-
await pwaPlugin.generateSW();
|
|
1296
|
-
}
|
|
1297
|
-
console.log(`
|
|
1298
|
-
${gray("[vite-react-ssg]")} ${green("Build finished.")}`);
|
|
1299
|
-
await onFinished?.();
|
|
1300
|
-
const waitInSeconds = 15;
|
|
1301
|
-
const timeout = setTimeout(() => {
|
|
1302
|
-
console.log(`${gray("[vite-react-ssg]")} ${yellow(`Build process still running after ${waitInSeconds}s`)}. There might be something misconfigured in your setup. Force exit.`);
|
|
1303
|
-
process.exit(0);
|
|
1304
|
-
}, waitInSeconds * 1e3);
|
|
1305
|
-
timeout.unref();
|
|
1306
|
-
}
|
|
1307
|
-
function rewriteScripts(indexHTML, mode) {
|
|
1308
|
-
if (!mode || mode === "sync")
|
|
1309
|
-
return indexHTML;
|
|
1310
|
-
return indexHTML.replace(/<script type="module" /g, `<script type="module" ${mode} `);
|
|
1311
|
-
}
|
|
1312
|
-
async function formatHtml(html, formatting) {
|
|
1313
|
-
if (formatting === "minify") {
|
|
1314
|
-
const htmlMinifier = await import('html-minifier');
|
|
1315
|
-
return htmlMinifier.minify(html, {
|
|
1316
|
-
collapseWhitespace: true,
|
|
1317
|
-
caseSensitive: true,
|
|
1318
|
-
collapseInlineTagWhitespace: false,
|
|
1319
|
-
minifyJS: true,
|
|
1320
|
-
minifyCSS: true
|
|
1321
|
-
});
|
|
1322
|
-
} else if (formatting === "prettify") {
|
|
1323
|
-
const prettier = (await import('prettier/esm/standalone.mjs')).default;
|
|
1324
|
-
const parserHTML = (await import('prettier/esm/parser-html.mjs')).default;
|
|
1325
|
-
return prettier.format(html, { semi: false, parser: "html", plugins: [parserHTML] });
|
|
1326
|
-
}
|
|
1327
|
-
return html;
|
|
1328
|
-
}
|
|
1329
|
-
function collectModulesForEntrys(manifest, entrys) {
|
|
1330
|
-
const mods = /* @__PURE__ */ new Set();
|
|
1331
|
-
if (!entrys)
|
|
1332
|
-
return mods;
|
|
1333
|
-
for (const entry of entrys)
|
|
1334
|
-
collectModules(manifest, entry, mods);
|
|
1335
|
-
return mods;
|
|
1336
|
-
}
|
|
1337
|
-
function collectModules(manifest, entry, mods = /* @__PURE__ */ new Set()) {
|
|
1338
|
-
if (!entry)
|
|
1339
|
-
return mods;
|
|
1340
|
-
mods.add(entry);
|
|
1341
|
-
manifest[entry]?.dynamicImports?.forEach((item) => {
|
|
1342
|
-
collectModules(manifest, item, mods);
|
|
1343
|
-
});
|
|
1344
|
-
return mods;
|
|
1345
|
-
}
|
|
1346
|
-
|
|
1347
|
-
const SHORTCUTS = [
|
|
1348
|
-
{
|
|
1349
|
-
key: "u",
|
|
1350
|
-
description: "show server url",
|
|
1351
|
-
action(vite, _) {
|
|
1352
|
-
vite.config.logger.info("");
|
|
1353
|
-
printServerInfo(vite, true);
|
|
1354
|
-
}
|
|
1355
|
-
},
|
|
1356
|
-
{
|
|
1357
|
-
key: "c",
|
|
1358
|
-
description: "clear console",
|
|
1359
|
-
action(vite, _) {
|
|
1360
|
-
vite.config.logger.clearScreen("error");
|
|
1361
|
-
}
|
|
1362
|
-
},
|
|
1363
|
-
{
|
|
1364
|
-
key: "q",
|
|
1365
|
-
description: "quit",
|
|
1366
|
-
action(_, server) {
|
|
1367
|
-
server.close(() => process.exit());
|
|
1368
|
-
}
|
|
1369
|
-
}
|
|
1370
|
-
];
|
|
1371
|
-
function bindShortcuts(viteServer, server) {
|
|
1372
|
-
if (!process.stdin.isTTY || process.env.CI)
|
|
1373
|
-
return;
|
|
1374
|
-
viteServer.config.logger.info(
|
|
1375
|
-
dim(green(" \u279C")) + dim(" press ") + bold("h") + dim(" to show help")
|
|
1376
|
-
);
|
|
1377
|
-
const shortcuts = SHORTCUTS;
|
|
1378
|
-
let actionRunning = false;
|
|
1379
|
-
const onInput = async (input) => {
|
|
1380
|
-
if (input === "" || input === "") {
|
|
1381
|
-
try {
|
|
1382
|
-
await server.close();
|
|
1383
|
-
} finally {
|
|
1384
|
-
process.exit(1);
|
|
1385
|
-
}
|
|
1386
|
-
return;
|
|
1387
|
-
}
|
|
1388
|
-
if (actionRunning)
|
|
1389
|
-
return;
|
|
1390
|
-
if (input === "h") {
|
|
1391
|
-
viteServer.config.logger.info(
|
|
1392
|
-
[
|
|
1393
|
-
"",
|
|
1394
|
-
bold(" Shortcuts"),
|
|
1395
|
-
...shortcuts.map(
|
|
1396
|
-
(shortcut2) => dim(" press ") + bold(shortcut2.key) + dim(` to ${shortcut2.description}`)
|
|
1397
|
-
)
|
|
1398
|
-
].join("\n")
|
|
1399
|
-
);
|
|
1400
|
-
}
|
|
1401
|
-
const shortcut = shortcuts.find((shortcut2) => shortcut2.key === input);
|
|
1402
|
-
if (!shortcut)
|
|
1403
|
-
return;
|
|
1404
|
-
actionRunning = true;
|
|
1405
|
-
await shortcut.action(viteServer, server);
|
|
1406
|
-
actionRunning = false;
|
|
1407
|
-
};
|
|
1408
|
-
process.stdin.setRawMode(true);
|
|
1409
|
-
process.stdin.on("data", onInput).setEncoding("utf8").resume();
|
|
1410
|
-
server.on("close", () => {
|
|
1411
|
-
process.stdin.off("data", onInput).pause();
|
|
1412
|
-
});
|
|
1413
|
-
}
|
|
1414
|
-
|
|
1415
|
-
async function dev(ssgOptions = {}, viteConfig = {}) {
|
|
1416
|
-
const mode = process.env.MODE || process.env.NODE_ENV || ssgOptions.mode || "development";
|
|
1417
|
-
const config = await resolveConfig(viteConfig, "serve", mode, mode);
|
|
1418
|
-
const cwd = process.cwd();
|
|
1419
|
-
const root = config.root || cwd;
|
|
1420
|
-
const {
|
|
1421
|
-
entry = await detectEntry(root),
|
|
1422
|
-
onBeforePageRender,
|
|
1423
|
-
onPageRendered,
|
|
1424
|
-
rootContainerId = "root"
|
|
1425
|
-
} = Object.assign({}, config.ssgOptions || {}, ssgOptions);
|
|
1426
|
-
const ssrEntry = await resolveAlias(config, entry);
|
|
1427
|
-
const template = await fs.readFile(join(root, "index.html"), "utf-8");
|
|
1428
|
-
let viteServer;
|
|
1429
|
-
globalThis.__ssr_start_time = performance.now();
|
|
1430
|
-
createServer$1().then((app) => {
|
|
1431
|
-
const port = viteServer.config.server.port || 5173;
|
|
1432
|
-
const server = app.listen(port, () => {
|
|
1433
|
-
printServerInfo(viteServer);
|
|
1434
|
-
bindShortcuts(viteServer, server);
|
|
1435
|
-
});
|
|
1436
|
-
});
|
|
1437
|
-
async function createServer$1() {
|
|
1438
|
-
process.env.__DEV_MODE_SSR = "true";
|
|
1439
|
-
const app = express();
|
|
1440
|
-
viteServer = await createServer({
|
|
1441
|
-
// ...options,
|
|
1442
|
-
server: { middlewareMode: true },
|
|
1443
|
-
appType: "custom"
|
|
1444
|
-
});
|
|
1445
|
-
app.use(viteServer.middlewares);
|
|
1446
|
-
app.use("*", async (req, res) => {
|
|
1447
|
-
try {
|
|
1448
|
-
const url = req.originalUrl;
|
|
1449
|
-
const indexHTML = await viteServer.transformIndexHtml(url, template);
|
|
1450
|
-
const createRoot = await viteServer.ssrLoadModule(ssrEntry).then((m) => m.createRoot);
|
|
1451
|
-
const appCtx = await createRoot(false, url);
|
|
1452
|
-
const { routes, getStyleCollector } = appCtx;
|
|
1453
|
-
const transformedIndexHTML = await onBeforePageRender?.(url, indexHTML, appCtx) || indexHTML;
|
|
1454
|
-
const styleCollector = getStyleCollector ? await getStyleCollector() : null;
|
|
1455
|
-
const { appHTML, bodyAttributes, htmlAttributes, metaAttributes, styleTag, routerContext } = await render([...routes], createFetchRequest(req), styleCollector);
|
|
1456
|
-
metaAttributes.push(styleTag);
|
|
1457
|
-
const matchesEntries = routerContext.matches.map((match) => match.route.entry).filter((entry2) => !!entry2).map((entry2) => entry2[0] === "/" ? entry2 : `/${entry2}`);
|
|
1458
|
-
const mods = await Promise.all(
|
|
1459
|
-
[entry, ...matchesEntries].map(async (entry2) => await viteServer.moduleGraph.getModuleByUrl(entry2))
|
|
1460
|
-
);
|
|
1461
|
-
const assetsUrls = /* @__PURE__ */ new Set();
|
|
1462
|
-
const collectAssets = async (mod) => {
|
|
1463
|
-
if (!mod || !mod?.ssrTransformResult)
|
|
1464
|
-
return;
|
|
1465
|
-
const { deps = [], dynamicDeps = [] } = mod?.ssrTransformResult;
|
|
1466
|
-
const allDeps = [...deps, ...dynamicDeps];
|
|
1467
|
-
for (const dep of allDeps) {
|
|
1468
|
-
if (dep.endsWith(".css")) {
|
|
1469
|
-
assetsUrls.add(dep);
|
|
1470
|
-
} else if (dep.endsWith(".ts") || dep.endsWith(".tsx")) {
|
|
1471
|
-
const depModule = await viteServer.moduleGraph.getModuleByUrl(dep);
|
|
1472
|
-
depModule && await collectAssets(depModule);
|
|
1473
|
-
}
|
|
1474
|
-
}
|
|
1475
|
-
};
|
|
1476
|
-
await Promise.all(mods.map(async (mod) => collectAssets(mod)));
|
|
1477
|
-
const preloadLink = [...assetsUrls].map((item) => createLink(item));
|
|
1478
|
-
metaAttributes.push(...preloadLink);
|
|
1479
|
-
const renderedHTML = await renderHTML({
|
|
1480
|
-
rootContainerId,
|
|
1481
|
-
appHTML,
|
|
1482
|
-
indexHTML: transformedIndexHTML,
|
|
1483
|
-
metaAttributes,
|
|
1484
|
-
bodyAttributes,
|
|
1485
|
-
htmlAttributes,
|
|
1486
|
-
initialState: null
|
|
1487
|
-
});
|
|
1488
|
-
const transformed = await onPageRendered?.(url, renderedHTML, appCtx) || renderedHTML;
|
|
1489
|
-
res.status(200).set({ "Content-Type": "text/html" }).end(transformed);
|
|
1490
|
-
} catch (e) {
|
|
1491
|
-
viteServer.ssrFixStacktrace(e);
|
|
1492
|
-
console.error(`[vite-react-ssg] error: ${e.stack}`);
|
|
1493
|
-
res.status(500).end(e.stack);
|
|
1494
|
-
}
|
|
1495
|
-
});
|
|
1496
|
-
return app;
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
async function printServerInfo(server, onlyUrl = false) {
|
|
1500
|
-
const info = server.config.logger.info;
|
|
1501
|
-
const port = server.config.server.port || 5173;
|
|
1502
|
-
const url = `http://localhost:${port}/`;
|
|
1503
|
-
if (!onlyUrl) {
|
|
1504
|
-
let ssrReadyMessage = " -- SSR";
|
|
1505
|
-
if (globalThis.__ssr_start_time) {
|
|
1506
|
-
ssrReadyMessage += ` ready in ${reset(bold(`${Math.round(
|
|
1507
|
-
// @ts-expect-error global var
|
|
1508
|
-
performance.now() - globalThis.__ssr_start_time
|
|
1509
|
-
)}ms`))}`;
|
|
1510
|
-
}
|
|
1511
|
-
info(
|
|
1512
|
-
`
|
|
1513
|
-
${bgLightCyan(` VITE-REACT-SSG v${version} `)}`,
|
|
1514
|
-
{ clear: !server.config.logger.hasWarned }
|
|
1515
|
-
);
|
|
1516
|
-
info(
|
|
1517
|
-
`${cyan(`
|
|
1518
|
-
VITE v${version$1}`) + dim(ssrReadyMessage)}
|
|
1519
|
-
`
|
|
1520
|
-
);
|
|
1521
|
-
}
|
|
1522
|
-
info(
|
|
1523
|
-
green(" dev server running at:")
|
|
1524
|
-
);
|
|
1525
|
-
printUrls(url, info);
|
|
1526
|
-
}
|
|
1527
|
-
function printUrls(url, info) {
|
|
1528
|
-
const colorUrl = (url2) => cyan(url2.replace(/:(\d+)\//, (_, port) => `:${bold(port)}/`));
|
|
1529
|
-
info(` ${green("\u279C")} ${bold("Local")}: ${colorUrl(url)}`);
|
|
1530
|
-
}
|
|
1531
|
-
|
|
1532
|
-
export { build as b, dev as d };
|