-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
ViteService.php
executable file
·658 lines (601 loc) · 22 KB
/
ViteService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
<?php
/**
* Vite plugin for Craft CMS 3.x
*
* Allows the use of the Vite.js next generation frontend tooling with Craft CMS
*
* @link https://nystudio107.com
* @copyright Copyright (c) 2021 nystudio107
*/
namespace nystudio107\pluginvite\services;
use Craft;
use craft\base\Component;
use craft\helpers\Html as HtmlHelper;
use craft\helpers\Json as JsonHelper;
use craft\web\View;
use nystudio107\pluginvite\helpers\FileHelper;
use nystudio107\pluginvite\helpers\ManifestHelper;
use Throwable;
use yii\base\InvalidConfigException;
use yii\caching\TagDependency;
/**
* @author nystudio107
* @package Vite
* @since 1.0.0
*/
class ViteService extends Component
{
// Constants
// =========================================================================
const VITE_CLIENT = '@vite/client';
const VITE_DEVSERVER_PING = '__vite_ping';
const LEGACY_POLYFILLS = 'vite/legacy-polyfills';
// Public Properties
// =========================================================================
/**
* @var bool Should the dev server be used for?
*/
public $useDevServer;
/**
* @var string File system path (or URL) to the Vite-built manifest.json
*/
public $manifestPath;
/**
* @var string The public URL to the dev server (what appears in `<script src="">` tags
*/
public $devServerPublic;
/**
* @var string The public URL to use when not using the dev server
*/
public $serverPublic;
/**
* @var string The JavaScript entry from the manifest.json to inject on Twig error pages
* This can be a string or an array of strings
*/
public $errorEntry = '';
/**
* @var string String to be appended to the cache key
*/
public $cacheKeySuffix = '';
/**
* @var string The internal URL to the dev server, when accessed from the environment in which PHP is executing
* This can be the same as `$devServerPublic`, but may be different in containerized or VM setups.
* ONLY used if $checkDevServer = true
*/
public $devServerInternal;
/**
* @var bool Should we check for the presence of the dev server by pinging $devServerInternal to make sure it's running?
*/
public $checkDevServer = false;
/**
* @var bool Whether the react-refresh-shim should be included
*/
public $includeReactRefreshShim = false;
/**
* @var bool Whether the modulepreload-polyfill shim should be included
*/
public $includeModulePreloadShim = true;
/**
* @var bool Whether an onload handler should be added to <script> tags to fire a custom event when the script has loaded
*/
public $includeScriptOnloadHandler = true;
// Protected Properties
// =========================================================================
/**
* @var bool Whether the manifest shims has been included yet or not
*/
protected $manifestShimsIncluded = false;
/**
* @var bool Whether the dev server shims has been included yet or not
*/
protected $devServerShimsIncluded = false;
/**
* @var null|bool Cached status of whether the devServer is running or not
*/
protected $devServerRunningCached = null;
// Public Methods
// =========================================================================
/**
* @inheritDoc
*/
public function init()
{
parent::init();
// Do nothing for console requests
$request = Craft::$app->getRequest();
if ($request->getIsConsoleRequest()) {
return;
}
// Our component is lazily loaded, so the View will be instantiated by now
if ($this->devServerRunning() && Craft::$app->getConfig()->getGeneral()->devMode) {
Craft::$app->getView()->on(View::EVENT_END_BODY, [$this, 'injectErrorEntry']);
}
}
/**
* Register the appropriate tags to the Craft View to load the Vite script, either via the dev server or
* extracting it from the manifest.json file
*
* @param string $path
* @param bool $asyncCss
* @param array $scriptTagAttrs
* @param array $cssTagAttrs
*
* @return void
* @throws InvalidConfigException
*/
public function register(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
{
// Filter out empty attributes, but preserve boolean values
$preserveBools = function($value) {
return is_bool($value) || !empty($value);
};
$scriptTagAttrs = array_filter($scriptTagAttrs, $preserveBools);
$cssTagAttrs = array_filter($cssTagAttrs, $preserveBools);
if ($this->devServerRunning()) {
$this->devServerRegister($path, $scriptTagAttrs);
return;
}
$this->manifestRegister($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
}
/**
* Determine whether the Vite dev server is running
*
* @return bool
*/
public function devServerRunning(): bool
{
if ($this->devServerRunningCached !== null) {
return $this->devServerRunningCached;
}
// If the dev server is turned off via config, say it's not running
if (!$this->useDevServer) {
return false;
}
// If we're not supposed to check that the dev server is actually running, just assume it is
if (!$this->checkDevServer) {
return true;
}
// Check to see if the dev server is actually running by pinging it
$url = FileHelper::createUrl($this->devServerInternal, self::VITE_DEVSERVER_PING);
$response = FileHelper::fetchResponse($url);
$this->devServerRunningCached = false;
// Status code of 200 or 404 means the dev server is running
if ($response) {
$statusCode = $response->getStatusCode();
$this->devServerRunningCached = $statusCode === 200 || $statusCode === 404;
}
return $this->devServerRunningCached;
}
/**
* Return the contents of a local file (via path) or remote file (via URL),
* or null if the file doesn't exist or couldn't be fetched
* Yii2 aliases and/or environment variables may be used
*
* @param string $pathOrUrl
* @param callable|null $callback
*
* @return string|array|null
*/
public function fetch(string $pathOrUrl, callable $callback = null)
{
// If the devServer is running, and this is a URL, swap in the devServerInternal URL
if ($this->devServerRunning()) {
if (!filter_var($pathOrUrl, FILTER_VALIDATE_URL) === false) {
$devServerInternalUrl = str_replace($this->devServerPublic, '', $pathOrUrl);
$devServerInternalUrl = FileHelper::createUrl($this->devServerInternal, $devServerInternalUrl);
// If we get a result from the $devServerInternalUrl, return it
if ($devServerInternalResult = FileHelper::fetch($devServerInternalUrl, $callback, $this->cacheKeySuffix)) {
return $devServerInternalResult;
}
}
}
return FileHelper::fetch($pathOrUrl, $callback, $this->cacheKeySuffix);
}
/**
* Register the script tag to the Craft View to load the script from the Vite dev server
*
* @param string $path
* @param array $scriptTagAttrs
*
* @return void
* @throws InvalidConfigException
*/
public function devServerRegister(string $path, array $scriptTagAttrs = [])
{
$view = Craft::$app->getView();
// Include any dev server shims
if (!$this->devServerShimsIncluded) {
// Include the react-refresh-shim
if ($this->includeReactRefreshShim) {
$script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
// Replace the hard-coded dev server URL with whatever they have theirs set to
$script = str_replace(
'http://localhost:3000/',
rtrim($this->devServerPublic, '/') . '/',
$script
);
$view->registerScript(
$script,
$view::POS_HEAD,
[
'type' => 'module',
],
'REACT_REFRESH_SHIM'
);
}
$this->devServerShimsIncluded = true;
}
// Include the entry script
$url = FileHelper::createUrl($this->devServerPublic, $path);
$view->registerJsFile(
$url,
array_merge(['type' => 'module'], $scriptTagAttrs),
md5($url . JsonHelper::encode($scriptTagAttrs))
);
}
/**
* Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file
*
* @param string $path
* @param bool $asyncCss
* @param array $scriptTagAttrs
* @param array $cssTagAttrs
*
* @return void
* @throws InvalidConfigException
*/
public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
{
$view = Craft::$app->getView();
ManifestHelper::fetchManifest($this->manifestPath);
$tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
$legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
// Include any manifest shims
if (!$this->manifestShimsIncluded) {
// Handle the modulepreload-polyfill shim
if ($this->includeModulePreloadShim) {
$view->registerScript(
FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
$view::POS_HEAD,
['type' => 'module'],
'MODULEPRELOAD_POLYFILL'
);
}
// Handle any legacy polyfills
if (!empty($legacyTags)) {
$view->registerScript(
FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
$view::POS_HEAD,
[],
'SAFARI_NOMODULE_FIX'
);
$legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
$tags = array_merge($legacyPolyfillTags, $tags);
}
$this->manifestShimsIncluded = true;
}
$this->manifestRegisterTags($tags, $legacyTags);
}
/**
* Return the URL for the given entry
*
* @param string $path
*
* @return string
*/
public function entry(string $path): string
{
ManifestHelper::fetchManifest($this->manifestPath);
$entry = ManifestHelper::extractEntry($path);
return FileHelper::createUrl($this->serverPublic, $entry);
}
/**
* Return the integrity hash (or an empty string if not present) for the given entry
*
* @param string $path
*
* @return string
*/
public function integrity(string $path): string
{
ManifestHelper::fetchManifest($this->manifestPath);
return ManifestHelper::extractIntegrity($path);
}
/**
* Return the URL for the given asset
*
* @param string $path
*
* @return string
*/
public function asset(string $path, bool $public = false): string
{
if ($this->devServerRunning()) {
return $this->devServerAsset($path);
}
if ($public) {
return $this->publicAsset($path);
}
return $this->manifestAsset($path);
}
/**
* Return the URL for the asset from the Vite dev server
*
* @param string $path
*
* @return string
*/
public function devServerAsset(string $path): string
{
// Return a URL to the given asset
return FileHelper::createUrl($this->devServerPublic, $path);
}
/**
* Return the URL for the asset from the public Vite folder
*
* @param string $path
*
* @return string
*/
public function publicAsset(string $path): string
{
// Return a URL to the given asset
return FileHelper::createUrl($this->serverPublic, $path);
}
/**
* Return the URL for the asset from the manifest.json file
*
* @param string $path
*
* @return string
*/
public function manifestAsset(string $path): string
{
ManifestHelper::fetchManifest($this->manifestPath);
$assets = ManifestHelper::extractAssetFiles();
// Get just the file name
$assetKeyParts = explode('/', $path);
$assetKey = end($assetKeyParts);
foreach ($assets as $key => $value) {
if ($key === $assetKey) {
return FileHelper::createUrl($this->serverPublic, $value);
}
}
// With Vite 3.x or later, the assets are also included as top-level entries in the
// manifest, so check there, too
$entry = ManifestHelper::extractEntry($path);
return $entry === '' ? '' : FileHelper::createUrl($this->serverPublic, $entry);
}
/**
* Invalidate all of the Vite caches
*/
public function invalidateCaches()
{
$cache = Craft::$app->getCache();
TagDependency::invalidate($cache, FileHelper::CACHE_TAG . $this->cacheKeySuffix);
Craft::info('All Vite caches cleared', __METHOD__);
}
/**
* Return the appropriate tags to load the Vite script, either via the dev server or
* extracting it from the manifest.json file
*
* @param string $path
* @param bool $asyncCss
* @param array $scriptTagAttrs
* @param array $cssTagAttrs
*
* @return string
*/
public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
{
// Filter out empty attributes, but preserve boolean values
$preserveBools = function($value) {
return is_bool($value) || !empty($value);
};
$scriptTagAttrs = array_filter($scriptTagAttrs, $preserveBools);
$cssTagAttrs = array_filter($cssTagAttrs, $preserveBools);
if ($this->devServerRunning()) {
return $this->devServerScript($path, $scriptTagAttrs);
}
return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
}
/**
* Return the script tag to load the script from the Vite dev server
*
* @param string $path
* @param array $scriptTagAttrs
*
* @return string
*/
public function devServerScript(string $path, array $scriptTagAttrs = []): string
{
$lines = [];
// Include any dev server shims
if (!$this->devServerShimsIncluded) {
// Include the react-refresh-shim
if ($this->includeReactRefreshShim) {
$script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
// Replace the hard-coded dev server URL with whatever they have theirs set to
$script = str_replace(
'http://localhost:3000/',
rtrim($this->devServerPublic, '/') . '/',
$script
);
$lines[] = HtmlHelper::script(
$script,
[
'type' => 'module',
]
);
}
$this->devServerShimsIncluded = true;
}
// Include the entry script
$url = FileHelper::createUrl($this->devServerPublic, $path);
$lines[] = HtmlHelper::jsFile($url, array_merge([
'type' => 'module',
], $scriptTagAttrs));
return implode("\r\n", $lines);
}
/**
* Return the script, module link, and CSS link tags for the script from the manifest.json file
*
* @param string $path
* @param bool $asyncCss
* @param array $scriptTagAttrs
* @param array $cssTagAttrs
*
* @return string
*/
public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
{
$lines = [];
ManifestHelper::fetchManifest($this->manifestPath);
$tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
$legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
// Include any manifest shims
if (!$this->manifestShimsIncluded) {
// Handle the modulepreload-polyfill shim
if ($this->includeModulePreloadShim) {
$lines[] = HtmlHelper::script(
FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
['type' => 'module']
);
}
// Handle any legacy polyfills
if (!empty($legacyTags)) {
$lines[] = HtmlHelper::script(
FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
[]
);
$legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
$tags = array_merge($legacyPolyfillTags, $tags);
}
$this->manifestShimsIncluded = true;
}
$lines = array_merge($lines, $this->manifestScriptTags($tags, $legacyTags));
return implode("\r\n", $lines);
}
// Protected Methods
// =========================================================================
/**
* Iterate through all the tags, and register them
*
* @param array $tags
* @param array $legacyTags
* @throws InvalidConfigException
*/
protected function manifestRegisterTags(array $tags, array $legacyTags)
{
$view = Craft::$app->getView();
foreach (array_merge($tags, $legacyTags) as $tag) {
if (!empty($tag)) {
$url = FileHelper::createUrl($this->serverPublic, $tag['url']);
switch ($tag['type']) {
case 'file':
if (!$this->includeScriptOnloadHandler) {
unset($tag['options']['onload']);
}
$view->registerJsFile(
$url,
$tag['options'],
md5($url . JsonHelper::encode($tag['options']))
);
break;
case 'css':
$view->registerCssFile(
$url,
$tag['options']
);
break;
case 'import':
$view->registerLinkTag(
array_filter([
'crossorigin' => $tag['crossorigin'],
'href' => $url,
'rel' => 'modulepreload',
'integrity' => $tag['integrity'] ?? '',
]),
md5($url)
);
break;
default:
break;
}
}
}
}
/**
* Inject the error entry point JavaScript for auto-reloading of Twig error
* pages
*/
protected function injectErrorEntry()
{
// If there's no error entry provided, return
if (empty($this->errorEntry)) {
return;
}
// If it's not a server error or a client error, return
$response = Craft::$app->getResponse();
if (!($response->isServerError || $response->isClientError)) {
return;
}
// If the dev server isn't running, return
if (!$this->devServerRunning()) {
return;
}
// Inject the errorEntry script tags to enable HMR on this page
try {
$errorEntry = $this->errorEntry;
if (is_string($errorEntry)) {
$errorEntry = [$errorEntry];
}
foreach ($errorEntry as $entry) {
$tag = $this->script($entry);
if ($tag !== null) {
echo $tag;
}
}
} catch (Throwable $e) {
// That's okay, Vite will have already logged the error
}
}
/**
* Iterate through all the tags, and return them
*
* @param array $tags
* @param array $legacyTags
* @return array
*/
protected function manifestScriptTags(array $tags, array $legacyTags): array
{
$lines = [];
foreach (array_merge($tags, $legacyTags) as $tag) {
if (!empty($tag)) {
$url = FileHelper::createUrl($this->serverPublic, $tag['url']);
switch ($tag['type']) {
case 'file':
if (!$this->includeScriptOnloadHandler) {
unset($tag['options']['onload']);
}
$lines[] = HtmlHelper::jsFile($url, $tag['options']);
break;
case 'css':
$lines[] = HtmlHelper::cssFile($url, $tag['options']);
break;
case 'import':
$lines[] = HtmlHelper::tag('link', '', array_filter([
'crossorigin' => $tag['crossorigin'],
'href' => $url,
'rel' => 'modulepreload',
'integrity' => $tag['integrity'] ?? '',
]));
break;
default:
break;
}
}
}
return $lines;
}
}