vite-plugin-php 3.0.0-beta.3 → 3.0.0-beta.5

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/dist/index.mjs CHANGED
@@ -4,14 +4,14 @@ import { resolve, dirname, relative } from 'node:path';
4
4
  import require$$1 from 'net';
5
5
  import require$$0 from 'util';
6
6
  import require$$0$1 from 'tty';
7
+ import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
8
+ import { normalizePath } from 'vite';
9
+ import http from 'node:http';
7
10
  import require$$0$2 from 'os';
8
11
  import require$$0$3 from 'path';
9
12
  import require$$0$4 from 'stream';
10
13
  import require$$0$6 from 'events';
11
14
  import require$$0$5 from 'fs';
12
- import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
13
- import { normalizePath } from 'vite';
14
- import http from 'node:http';
15
15
 
16
16
  const EPHPError = {
17
17
  ERROR: 1,
@@ -40,7 +40,8 @@ const shared = {
40
40
  cleanup: true,
41
41
  errorLevels: EPHPError.ALL | EPHPError.STRICT
42
42
  },
43
- entries: [],
43
+ entryPatterns: ["index.php"],
44
+ entries: ["index.php"],
44
45
  tempDir: ".php-tmp"
45
46
  };
46
47
 
@@ -164,7 +165,7 @@ var picocolorsExports = /*@__PURE__*/ requirePicocolors();
164
165
  const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
165
166
 
166
167
  function hasViteConfig(input) {
167
- if (!input) {
168
+ if (!input || typeof input !== "object" || ["logger", "server"].some((key) => !(key in input))) {
168
169
  throw new Error("Vite config not initialized!");
169
170
  }
170
171
  }
@@ -3322,205 +3323,531 @@ function stop(callBack) {
3322
3323
  }
3323
3324
  }
3324
3325
 
3325
- var tasks = {};
3326
-
3327
- var utils$3 = {};
3328
-
3329
- var array = {};
3330
-
3331
- var hasRequiredArray;
3332
-
3333
- function requireArray () {
3334
- if (hasRequiredArray) return array;
3335
- hasRequiredArray = 1;
3336
- Object.defineProperty(array, "__esModule", { value: true });
3337
- array.splitWhen = array.flatten = void 0;
3338
- function flatten(items) {
3339
- return items.reduce((collection, item) => [].concat(collection, item), []);
3340
- }
3341
- array.flatten = flatten;
3342
- function splitWhen(items, predicate) {
3343
- const result = [[]];
3344
- let groupIndex = 0;
3345
- for (const item of items) {
3346
- if (predicate(item)) {
3347
- groupIndex++;
3348
- result[groupIndex] = [];
3349
- }
3350
- else {
3351
- result[groupIndex].push(item);
3352
- }
3353
- }
3354
- return result;
3355
- }
3356
- array.splitWhen = splitWhen;
3357
- return array;
3326
+ function readFile(file) {
3327
+ return readFileSync(file, "utf-8").toString();
3358
3328
  }
3359
-
3360
- var errno = {};
3361
-
3362
- var hasRequiredErrno;
3363
-
3364
- function requireErrno () {
3365
- if (hasRequiredErrno) return errno;
3366
- hasRequiredErrno = 1;
3367
- Object.defineProperty(errno, "__esModule", { value: true });
3368
- errno.isEnoentCodeError = void 0;
3369
- function isEnoentCodeError(error) {
3370
- return error.code === 'ENOENT';
3371
- }
3372
- errno.isEnoentCodeError = isEnoentCodeError;
3373
- return errno;
3329
+ function writeFile(file, data) {
3330
+ mkdirSync(dirname(file), { recursive: true });
3331
+ writeFileSync(file, data);
3374
3332
  }
3375
-
3376
- var fs$3 = {};
3377
-
3378
- var hasRequiredFs$3;
3379
-
3380
- function requireFs$3 () {
3381
- if (hasRequiredFs$3) return fs$3;
3382
- hasRequiredFs$3 = 1;
3383
- Object.defineProperty(fs$3, "__esModule", { value: true });
3384
- fs$3.createDirentFromStats = void 0;
3385
- class DirentFromStats {
3386
- constructor(name, stats) {
3387
- this.name = name;
3388
- this.isBlockDevice = stats.isBlockDevice.bind(stats);
3389
- this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
3390
- this.isDirectory = stats.isDirectory.bind(stats);
3391
- this.isFIFO = stats.isFIFO.bind(stats);
3392
- this.isFile = stats.isFile.bind(stats);
3393
- this.isSocket = stats.isSocket.bind(stats);
3394
- this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
3395
- }
3396
- }
3397
- function createDirentFromStats(name, stats) {
3398
- return new DirentFromStats(name, stats);
3399
- }
3400
- fs$3.createDirentFromStats = createDirentFromStats;
3401
- return fs$3;
3333
+ function tempName(entry) {
3334
+ return `${shared.tempDir}/${entry}`;
3402
3335
  }
3403
3336
 
3404
- var path = {};
3405
-
3406
- var hasRequiredPath;
3407
-
3408
- function requirePath () {
3409
- if (hasRequiredPath) return path;
3410
- hasRequiredPath = 1;
3411
- Object.defineProperty(path, "__esModule", { value: true });
3412
- path.convertPosixPathToPattern = path.convertWindowsPathToPattern = path.convertPathToPattern = path.escapePosixPath = path.escapeWindowsPath = path.escape = path.removeLeadingDotSegment = path.makeAbsolute = path.unixify = void 0;
3413
- const os = require$$0$2;
3414
- const path$1 = require$$0$3;
3415
- const IS_WINDOWS_PLATFORM = os.platform() === 'win32';
3416
- const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
3417
- /**
3418
- * All non-escaped special characters.
3419
- * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters.
3420
- * Windows: (){}[], !+@ before (, ! at the beginning.
3421
- */
3422
- const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
3423
- const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g;
3424
- /**
3425
- * The device path (\\.\ or \\?\).
3426
- * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths
3427
- */
3428
- const DOS_DEVICE_PATH_RE = /^\\\\([.?])/;
3429
- /**
3430
- * All backslashes except those escaping special characters.
3431
- * Windows: !()+@{}
3432
- * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
3433
- */
3434
- const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g;
3435
- /**
3436
- * Designed to work only with simple paths: `dir\\file`.
3437
- */
3438
- function unixify(filepath) {
3439
- return filepath.replace(/\\/g, '/');
3440
- }
3441
- path.unixify = unixify;
3442
- function makeAbsolute(cwd, filepath) {
3443
- return path$1.resolve(cwd, filepath);
3444
- }
3445
- path.makeAbsolute = makeAbsolute;
3446
- function removeLeadingDotSegment(entry) {
3447
- // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
3448
- // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
3449
- if (entry.charAt(0) === '.') {
3450
- const secondCharactery = entry.charAt(1);
3451
- if (secondCharactery === '/' || secondCharactery === '\\') {
3452
- return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
3453
- }
3454
- }
3455
- return entry;
3456
- }
3457
- path.removeLeadingDotSegment = removeLeadingDotSegment;
3458
- path.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath;
3459
- function escapeWindowsPath(pattern) {
3460
- return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
3461
- }
3462
- path.escapeWindowsPath = escapeWindowsPath;
3463
- function escapePosixPath(pattern) {
3464
- return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
3465
- }
3466
- path.escapePosixPath = escapePosixPath;
3467
- path.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern;
3468
- function convertWindowsPathToPattern(filepath) {
3469
- return escapeWindowsPath(filepath)
3470
- .replace(DOS_DEVICE_PATH_RE, '//$1')
3471
- .replace(WINDOWS_BACKSLASHES_RE, '/');
3472
- }
3473
- path.convertWindowsPathToPattern = convertWindowsPathToPattern;
3474
- function convertPosixPathToPattern(filepath) {
3475
- return escapePosixPath(filepath);
3476
- }
3477
- path.convertPosixPathToPattern = convertPosixPathToPattern;
3478
- return path;
3337
+ function makeID() {
3338
+ return Date.now().toString(36) + Math.random() * 100;
3479
3339
  }
3480
3340
 
3481
- var pattern = {};
3482
-
3483
- /*!
3484
- * is-extglob <https://github.com/jonschlinkert/is-extglob>
3485
- *
3486
- * Copyright (c) 2014-2016, Jon Schlinkert.
3487
- * Licensed under the MIT License.
3488
- */
3489
-
3490
- var isExtglob;
3491
- var hasRequiredIsExtglob;
3492
-
3493
- function requireIsExtglob () {
3494
- if (hasRequiredIsExtglob) return isExtglob;
3495
- hasRequiredIsExtglob = 1;
3496
- isExtglob = function isExtglob(str) {
3497
- if (typeof str !== 'string' || str === '') {
3498
- return false;
3499
- }
3500
-
3501
- var match;
3502
- while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
3503
- if (match[2]) return true;
3504
- str = str.slice(match.index + match[0].length);
3505
- }
3506
-
3507
- return false;
3508
- };
3509
- return isExtglob;
3341
+ function resolveEnvPrefix({ envPrefix = "VITE_" }) {
3342
+ envPrefix = Array.isArray(envPrefix) ? envPrefix : [envPrefix];
3343
+ if (envPrefix.includes("")) {
3344
+ throw new Error(
3345
+ `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
3346
+ );
3347
+ }
3348
+ return envPrefix;
3349
+ }
3350
+ const envPattern = /%(\S+?)%/g;
3351
+ function initReplaceEnv() {
3352
+ hasViteConfig(shared.viteConfig);
3353
+ const { env, define, root, logger } = shared.viteConfig;
3354
+ const envPrefix = resolveEnvPrefix({
3355
+ envPrefix: shared.viteConfig.envPrefix
3356
+ });
3357
+ for (const key in define) {
3358
+ if (key.startsWith(`import.meta.env.`)) {
3359
+ const val = define[key];
3360
+ if (typeof val === "string") {
3361
+ try {
3362
+ const parsed = JSON.parse(val);
3363
+ env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
3364
+ } catch {
3365
+ env[key.slice(16)] = val;
3366
+ }
3367
+ } else {
3368
+ env[key.slice(16)] = JSON.stringify(val);
3369
+ }
3370
+ }
3371
+ }
3372
+ return function replaceEnv(content, filename) {
3373
+ const relativeHtml = normalizePath(relative(root, filename));
3374
+ return content.replace(envPattern, (text, key) => {
3375
+ if (key in env) {
3376
+ return env[key];
3377
+ } else {
3378
+ if (envPrefix.some((prefix) => key.startsWith(prefix))) {
3379
+ logger.warn(
3380
+ colors.yellow(
3381
+ colors.bold(
3382
+ `(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
3383
+ )
3384
+ )
3385
+ );
3386
+ }
3387
+ return text;
3388
+ }
3389
+ });
3390
+ };
3510
3391
  }
3511
3392
 
3512
- /*!
3513
- * is-glob <https://github.com/jonschlinkert/is-glob>
3514
- *
3515
- * Copyright (c) 2014-2017, Jon Schlinkert.
3516
- * Released under the MIT License.
3517
- */
3518
-
3519
- var isGlob;
3520
- var hasRequiredIsGlob;
3521
-
3522
- function requireIsGlob () {
3523
- if (hasRequiredIsGlob) return isGlob;
3393
+ const phpStartPattern = `<\\?(?:php|)`;
3394
+ const phpEndPattern = `\\?>`;
3395
+ const phpTagRegex = new RegExp(
3396
+ `${phpStartPattern}.+?(${phpEndPattern}|$)`,
3397
+ "gis"
3398
+ );
3399
+ class PHP_Code {
3400
+ file = "!!__VIRTUAL__!!.php";
3401
+ code;
3402
+ mapping = {};
3403
+ static fromFile(file) {
3404
+ const inst = new this(readFile(file));
3405
+ inst.file = file;
3406
+ return inst;
3407
+ }
3408
+ constructor(code) {
3409
+ this.code = code;
3410
+ return this;
3411
+ }
3412
+ applyEnv() {
3413
+ const replaceEnv = initReplaceEnv();
3414
+ this.code = replaceEnv(this.code, this.file || "");
3415
+ return this;
3416
+ }
3417
+ escape() {
3418
+ const isJS = this.file.includes(".js") || this.file.includes(".ts");
3419
+ const isML = this.file.includes(".php") || this.file.includes(".htm");
3420
+ this.code = this.code.replace(phpTagRegex, (match) => {
3421
+ let token = makeID();
3422
+ if (isJS) {
3423
+ token = `/*${token}*/`;
3424
+ } else if (isML) {
3425
+ token = `\u2400\u2400${token}\u2400\u2400`;
3426
+ }
3427
+ this.mapping[token] = match;
3428
+ return token;
3429
+ });
3430
+ return this;
3431
+ }
3432
+ write(file, mapping = false) {
3433
+ writeFile(file, this.code);
3434
+ mapping && writeFile(file + ".json", JSON.stringify(this.mapping));
3435
+ }
3436
+ static unescape(code, mapping) {
3437
+ let out = code;
3438
+ Object.entries(mapping).forEach(([token, code2]) => {
3439
+ out = out.replace(token, code2);
3440
+ });
3441
+ return out;
3442
+ }
3443
+ }
3444
+
3445
+ const exitSignals = [
3446
+ "exit",
3447
+ "SIGINT",
3448
+ "SIGUSR1",
3449
+ "SIGUSR2",
3450
+ "uncaughtException",
3451
+ "SIGTERM"
3452
+ ];
3453
+ function exitHandler(signal) {
3454
+ if (signal === "SIGINT") {
3455
+ console.log();
3456
+ }
3457
+ const tempDir = resolve(shared.tempDir);
3458
+ if (shared.devConfig.cleanup && existsSync(tempDir)) {
3459
+ log("Removing temporary files");
3460
+ rmSync(tempDir, {
3461
+ recursive: true,
3462
+ force: true
3463
+ });
3464
+ }
3465
+ if (PHP_Server.process && shared.viteConfig?.command === "serve") {
3466
+ PHP_Server.stop(() => {
3467
+ process.exit();
3468
+ });
3469
+ } else {
3470
+ process.exit();
3471
+ }
3472
+ }
3473
+ const listeners = /* @__PURE__ */ new Map();
3474
+ const handleExit = {
3475
+ register() {
3476
+ exitSignals.forEach((eventType) => {
3477
+ new Promise((resolve2) => {
3478
+ listeners.set(eventType, resolve2);
3479
+ process.on(eventType, resolve2);
3480
+ }).then(exitHandler);
3481
+ });
3482
+ },
3483
+ unregister() {
3484
+ exitSignals.forEach((eventType) => {
3485
+ const listener = listeners.get(eventType);
3486
+ if (listener) {
3487
+ process.off(eventType, listener);
3488
+ listeners.delete(eventType);
3489
+ }
3490
+ });
3491
+ }
3492
+ };
3493
+
3494
+ const assetsPattern = new RegExp(
3495
+ `^(.+?)(${phpStartPattern}\\s+namespace\\s\\S+?(?:\\s*;|\\s*{).+)$`,
3496
+ "si"
3497
+ );
3498
+ const viteClientInjection = '<script type="module" src="/@vite/client"><\/script>\n';
3499
+ const viteClientInjectionPattern = new RegExp(
3500
+ '<script[^>]+?src="/@vite/client".+?<\/script>(\r\n|\n|\r)*',
3501
+ "si"
3502
+ );
3503
+ const lastTagPattern = new RegExp(`^(.+(?:</.+?>|<.+?/>))(.+|)$`, "si");
3504
+ const closingPattern = new RegExp(`^(.+)(${phpStartPattern}.+)$`, "si");
3505
+ function fixAssetsInjection(input) {
3506
+ let out = input;
3507
+ let assets = "";
3508
+ out = out.replace(assetsPattern, (match, p1, p2) => {
3509
+ assets = p1.trim();
3510
+ return p2;
3511
+ });
3512
+ const injectAssets = (_, part1, part2) => {
3513
+ let a = assets;
3514
+ if (!(part1.endsWith("\n") || part1.endsWith("\r"))) {
3515
+ a = "\r\n" + a;
3516
+ }
3517
+ if (!(part2.startsWith("\n") || part2.startsWith("\r"))) {
3518
+ a += "\r\n";
3519
+ }
3520
+ assets = "";
3521
+ return `${part1}${a}${part2}`;
3522
+ };
3523
+ if (assets) {
3524
+ out = out.replace(lastTagPattern, injectAssets);
3525
+ }
3526
+ if (assets) {
3527
+ out = out.replace(closingPattern, injectAssets);
3528
+ }
3529
+ if (assets) {
3530
+ out += assets;
3531
+ }
3532
+ return out;
3533
+ }
3534
+
3535
+ const phpProxy = async (req, res, next) => {
3536
+ try {
3537
+ if (req.url && !["/@vite", "/@fs", "/@id/__x00__", "/node_modules"].some(
3538
+ (path) => req.url.startsWith(path)
3539
+ )) {
3540
+ req.on("error", (error) => {
3541
+ throw error;
3542
+ });
3543
+ let url = new URL(req.url, "http://localhost");
3544
+ if (shared.viteConfig?.server.port) {
3545
+ url.port = shared.viteConfig.server.port.toString();
3546
+ }
3547
+ const requestUrl = new URL(url);
3548
+ if (url.pathname.endsWith("/")) {
3549
+ url.pathname += "index.php";
3550
+ }
3551
+ const routedUrl = serve.rewriteUrl(url);
3552
+ if (routedUrl) {
3553
+ if (routedUrl.origin !== requestUrl.origin) {
3554
+ res.writeHead(307, {
3555
+ location: routedUrl.toString()
3556
+ }).end();
3557
+ return;
3558
+ }
3559
+ url = routedUrl;
3560
+ }
3561
+ const entryPathname = url.pathname.substring(1);
3562
+ const entry = shared.entries.find((file) => {
3563
+ return file === entryPathname || file.substring(0, file.lastIndexOf(".")) === entryPathname;
3564
+ });
3565
+ if (entry) {
3566
+ const tempFile = tempName(entry);
3567
+ if (existsSync(resolve(tempFile))) {
3568
+ url.pathname = tempFile;
3569
+ url.host = PHP_Server.host;
3570
+ url.port = PHP_Server.port.toString();
3571
+ url.searchParams.set(
3572
+ internalParam,
3573
+ new URLSearchParams({
3574
+ $REQUEST_URI: requestUrl.pathname,
3575
+ $PHP_SELF: "/" + entry,
3576
+ temp_dir: shared.tempDir,
3577
+ error_levels: shared.devConfig.errorLevels.toString()
3578
+ }).toString()
3579
+ );
3580
+ const body = await new Promise(
3581
+ (resolve2, reject) => {
3582
+ let data = [];
3583
+ req.on("data", (chunk) => {
3584
+ data.push(chunk);
3585
+ }).on("end", () => {
3586
+ resolve2(Buffer.concat(data));
3587
+ });
3588
+ }
3589
+ );
3590
+ const phpResult = await new Promise(async (resolve2, reject) => {
3591
+ const chunks = [];
3592
+ let statusCode;
3593
+ let incomingHeaders = {};
3594
+ const request = http.request(
3595
+ url.toString(),
3596
+ {
3597
+ method: req.method,
3598
+ headers: {
3599
+ ...req.headers,
3600
+ "content-length": Buffer.byteLength(body)
3601
+ }
3602
+ },
3603
+ (msg) => {
3604
+ statusCode = msg.statusCode;
3605
+ incomingHeaders = msg.headers;
3606
+ msg.on("data", (data) => {
3607
+ chunks.push(data);
3608
+ });
3609
+ }
3610
+ ).on("error", (error) => {
3611
+ reject(error);
3612
+ }).on("close", () => {
3613
+ let content = Buffer.concat(chunks).toString("utf8");
3614
+ if (incomingHeaders["content-type"]?.includes(
3615
+ "text/html"
3616
+ ) && content.includes("</head>") && !viteClientInjectionPattern.test(content)) {
3617
+ content = content.replace(
3618
+ "</head>",
3619
+ `${viteClientInjection}</head>`
3620
+ );
3621
+ if (incomingHeaders["content-length"]) {
3622
+ incomingHeaders["content-length"] = `${content.length}`;
3623
+ }
3624
+ }
3625
+ resolve2({
3626
+ statusCode,
3627
+ headers: incomingHeaders,
3628
+ content
3629
+ });
3630
+ });
3631
+ request.write(body, (error) => {
3632
+ if (error) {
3633
+ reject(error);
3634
+ }
3635
+ });
3636
+ request.end();
3637
+ });
3638
+ res.writeHead(
3639
+ phpResult.statusCode || 200,
3640
+ phpResult.headers
3641
+ ).end(phpResult.content);
3642
+ return;
3643
+ }
3644
+ }
3645
+ }
3646
+ } catch (error) {
3647
+ console.error("Vite-PHP Error: " + error);
3648
+ }
3649
+ next();
3650
+ };
3651
+
3652
+ var tasks = {};
3653
+
3654
+ var utils$3 = {};
3655
+
3656
+ var array = {};
3657
+
3658
+ var hasRequiredArray;
3659
+
3660
+ function requireArray () {
3661
+ if (hasRequiredArray) return array;
3662
+ hasRequiredArray = 1;
3663
+ Object.defineProperty(array, "__esModule", { value: true });
3664
+ array.splitWhen = array.flatten = void 0;
3665
+ function flatten(items) {
3666
+ return items.reduce((collection, item) => [].concat(collection, item), []);
3667
+ }
3668
+ array.flatten = flatten;
3669
+ function splitWhen(items, predicate) {
3670
+ const result = [[]];
3671
+ let groupIndex = 0;
3672
+ for (const item of items) {
3673
+ if (predicate(item)) {
3674
+ groupIndex++;
3675
+ result[groupIndex] = [];
3676
+ }
3677
+ else {
3678
+ result[groupIndex].push(item);
3679
+ }
3680
+ }
3681
+ return result;
3682
+ }
3683
+ array.splitWhen = splitWhen;
3684
+ return array;
3685
+ }
3686
+
3687
+ var errno = {};
3688
+
3689
+ var hasRequiredErrno;
3690
+
3691
+ function requireErrno () {
3692
+ if (hasRequiredErrno) return errno;
3693
+ hasRequiredErrno = 1;
3694
+ Object.defineProperty(errno, "__esModule", { value: true });
3695
+ errno.isEnoentCodeError = void 0;
3696
+ function isEnoentCodeError(error) {
3697
+ return error.code === 'ENOENT';
3698
+ }
3699
+ errno.isEnoentCodeError = isEnoentCodeError;
3700
+ return errno;
3701
+ }
3702
+
3703
+ var fs$3 = {};
3704
+
3705
+ var hasRequiredFs$3;
3706
+
3707
+ function requireFs$3 () {
3708
+ if (hasRequiredFs$3) return fs$3;
3709
+ hasRequiredFs$3 = 1;
3710
+ Object.defineProperty(fs$3, "__esModule", { value: true });
3711
+ fs$3.createDirentFromStats = void 0;
3712
+ class DirentFromStats {
3713
+ constructor(name, stats) {
3714
+ this.name = name;
3715
+ this.isBlockDevice = stats.isBlockDevice.bind(stats);
3716
+ this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
3717
+ this.isDirectory = stats.isDirectory.bind(stats);
3718
+ this.isFIFO = stats.isFIFO.bind(stats);
3719
+ this.isFile = stats.isFile.bind(stats);
3720
+ this.isSocket = stats.isSocket.bind(stats);
3721
+ this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
3722
+ }
3723
+ }
3724
+ function createDirentFromStats(name, stats) {
3725
+ return new DirentFromStats(name, stats);
3726
+ }
3727
+ fs$3.createDirentFromStats = createDirentFromStats;
3728
+ return fs$3;
3729
+ }
3730
+
3731
+ var path = {};
3732
+
3733
+ var hasRequiredPath;
3734
+
3735
+ function requirePath () {
3736
+ if (hasRequiredPath) return path;
3737
+ hasRequiredPath = 1;
3738
+ Object.defineProperty(path, "__esModule", { value: true });
3739
+ path.convertPosixPathToPattern = path.convertWindowsPathToPattern = path.convertPathToPattern = path.escapePosixPath = path.escapeWindowsPath = path.escape = path.removeLeadingDotSegment = path.makeAbsolute = path.unixify = void 0;
3740
+ const os = require$$0$2;
3741
+ const path$1 = require$$0$3;
3742
+ const IS_WINDOWS_PLATFORM = os.platform() === 'win32';
3743
+ const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
3744
+ /**
3745
+ * All non-escaped special characters.
3746
+ * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters.
3747
+ * Windows: (){}[], !+@ before (, ! at the beginning.
3748
+ */
3749
+ const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
3750
+ const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g;
3751
+ /**
3752
+ * The device path (\\.\ or \\?\).
3753
+ * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths
3754
+ */
3755
+ const DOS_DEVICE_PATH_RE = /^\\\\([.?])/;
3756
+ /**
3757
+ * All backslashes except those escaping special characters.
3758
+ * Windows: !()+@{}
3759
+ * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
3760
+ */
3761
+ const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g;
3762
+ /**
3763
+ * Designed to work only with simple paths: `dir\\file`.
3764
+ */
3765
+ function unixify(filepath) {
3766
+ return filepath.replace(/\\/g, '/');
3767
+ }
3768
+ path.unixify = unixify;
3769
+ function makeAbsolute(cwd, filepath) {
3770
+ return path$1.resolve(cwd, filepath);
3771
+ }
3772
+ path.makeAbsolute = makeAbsolute;
3773
+ function removeLeadingDotSegment(entry) {
3774
+ // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
3775
+ // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
3776
+ if (entry.charAt(0) === '.') {
3777
+ const secondCharactery = entry.charAt(1);
3778
+ if (secondCharactery === '/' || secondCharactery === '\\') {
3779
+ return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
3780
+ }
3781
+ }
3782
+ return entry;
3783
+ }
3784
+ path.removeLeadingDotSegment = removeLeadingDotSegment;
3785
+ path.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath;
3786
+ function escapeWindowsPath(pattern) {
3787
+ return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
3788
+ }
3789
+ path.escapeWindowsPath = escapeWindowsPath;
3790
+ function escapePosixPath(pattern) {
3791
+ return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
3792
+ }
3793
+ path.escapePosixPath = escapePosixPath;
3794
+ path.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern;
3795
+ function convertWindowsPathToPattern(filepath) {
3796
+ return escapeWindowsPath(filepath)
3797
+ .replace(DOS_DEVICE_PATH_RE, '//$1')
3798
+ .replace(WINDOWS_BACKSLASHES_RE, '/');
3799
+ }
3800
+ path.convertWindowsPathToPattern = convertWindowsPathToPattern;
3801
+ function convertPosixPathToPattern(filepath) {
3802
+ return escapePosixPath(filepath);
3803
+ }
3804
+ path.convertPosixPathToPattern = convertPosixPathToPattern;
3805
+ return path;
3806
+ }
3807
+
3808
+ var pattern = {};
3809
+
3810
+ /*!
3811
+ * is-extglob <https://github.com/jonschlinkert/is-extglob>
3812
+ *
3813
+ * Copyright (c) 2014-2016, Jon Schlinkert.
3814
+ * Licensed under the MIT License.
3815
+ */
3816
+
3817
+ var isExtglob;
3818
+ var hasRequiredIsExtglob;
3819
+
3820
+ function requireIsExtglob () {
3821
+ if (hasRequiredIsExtglob) return isExtglob;
3822
+ hasRequiredIsExtglob = 1;
3823
+ isExtglob = function isExtglob(str) {
3824
+ if (typeof str !== 'string' || str === '') {
3825
+ return false;
3826
+ }
3827
+
3828
+ var match;
3829
+ while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
3830
+ if (match[2]) return true;
3831
+ str = str.slice(match.index + match[0].length);
3832
+ }
3833
+
3834
+ return false;
3835
+ };
3836
+ return isExtglob;
3837
+ }
3838
+
3839
+ /*!
3840
+ * is-glob <https://github.com/jonschlinkert/is-glob>
3841
+ *
3842
+ * Copyright (c) 2014-2017, Jon Schlinkert.
3843
+ * Released under the MIT License.
3844
+ */
3845
+
3846
+ var isGlob;
3847
+ var hasRequiredIsGlob;
3848
+
3849
+ function requireIsGlob () {
3850
+ if (hasRequiredIsGlob) return isGlob;
3524
3851
  hasRequiredIsGlob = 1;
3525
3852
  var isExtglob = requireIsExtglob();
3526
3853
  var chars = { '{': '}', '(': ')', '[': ']'};
@@ -10607,377 +10934,80 @@ function requireOut () {
10607
10934
  (function (posix) {
10608
10935
  function escapePath(source) {
10609
10936
  assertPatternsInput(source);
10610
- return utils.path.escapePosixPath(source);
10611
- }
10612
- posix.escapePath = escapePath;
10613
- function convertPathToPattern(source) {
10614
- assertPatternsInput(source);
10615
- return utils.path.convertPosixPathToPattern(source);
10616
- }
10617
- posix.convertPathToPattern = convertPathToPattern;
10618
- })(FastGlob.posix || (FastGlob.posix = {}));
10619
- (function (win32) {
10620
- function escapePath(source) {
10621
- assertPatternsInput(source);
10622
- return utils.path.escapeWindowsPath(source);
10623
- }
10624
- win32.escapePath = escapePath;
10625
- function convertPathToPattern(source) {
10626
- assertPatternsInput(source);
10627
- return utils.path.convertWindowsPathToPattern(source);
10628
- }
10629
- win32.convertPathToPattern = convertPathToPattern;
10630
- })(FastGlob.win32 || (FastGlob.win32 = {}));
10631
- })(FastGlob || (FastGlob = {}));
10632
- function getWorks(source, _Provider, options) {
10633
- const patterns = [].concat(source);
10634
- const settings = new settings_1.default(options);
10635
- const tasks = taskManager.generate(patterns, settings);
10636
- const provider = new _Provider(settings);
10637
- return tasks.map(provider.read, provider);
10638
- }
10639
- function assertPatternsInput(input) {
10640
- const source = [].concat(input);
10641
- const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
10642
- if (!isValidSource) {
10643
- throw new TypeError('Patterns must be a string (non empty) or an array of strings');
10644
- }
10645
- }
10646
- out = FastGlob;
10647
- return out;
10648
- }
10649
-
10650
- var outExports = requireOut();
10651
- const fastGlob = /*@__PURE__*/getDefaultExportFromCjs(outExports);
10652
-
10653
- function readFile(file) {
10654
- return readFileSync(file, "utf-8").toString();
10655
- }
10656
- function writeFile(file, data) {
10657
- mkdirSync(dirname(file), { recursive: true });
10658
- writeFileSync(file, data);
10659
- }
10660
- function tempName(entry) {
10661
- return `${shared.tempDir}/${entry}`;
10662
- }
10663
-
10664
- function makeID() {
10665
- return Date.now().toString(36) + Math.random() * 100;
10666
- }
10667
-
10668
- function resolveEnvPrefix({ envPrefix = "VITE_" }) {
10669
- envPrefix = Array.isArray(envPrefix) ? envPrefix : [envPrefix];
10670
- if (envPrefix.includes("")) {
10671
- throw new Error(
10672
- `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
10673
- );
10674
- }
10675
- return envPrefix;
10676
- }
10677
- const envPattern = /%(\S+?)%/g;
10678
- function initReplaceEnv() {
10679
- hasViteConfig(shared.viteConfig);
10680
- const { env, define, root, logger } = shared.viteConfig;
10681
- const envPrefix = resolveEnvPrefix({
10682
- envPrefix: shared.viteConfig.envPrefix
10683
- });
10684
- for (const key in define) {
10685
- if (key.startsWith(`import.meta.env.`)) {
10686
- const val = define[key];
10687
- if (typeof val === "string") {
10688
- try {
10689
- const parsed = JSON.parse(val);
10690
- env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
10691
- } catch {
10692
- env[key.slice(16)] = val;
10693
- }
10694
- } else {
10695
- env[key.slice(16)] = JSON.stringify(val);
10696
- }
10697
- }
10698
- }
10699
- return function replaceEnv(content, filename) {
10700
- const relativeHtml = normalizePath(relative(root, filename));
10701
- return content.replace(envPattern, (text, key) => {
10702
- if (key in env) {
10703
- return env[key];
10704
- } else {
10705
- if (envPrefix.some((prefix) => key.startsWith(prefix))) {
10706
- logger.warn(
10707
- colors.yellow(
10708
- colors.bold(
10709
- `(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
10710
- )
10711
- )
10712
- );
10713
- }
10714
- return text;
10715
- }
10716
- });
10717
- };
10718
- }
10719
-
10720
- const phpStartPattern = `<\\?(?:php|)`;
10721
- const phpEndPattern = `\\?>`;
10722
- const phpTagRegex = new RegExp(
10723
- `${phpStartPattern}.+?(${phpEndPattern}|$)`,
10724
- "gis"
10725
- );
10726
- class PHP_Code {
10727
- file = "!!__VIRTUAL__!!.php";
10728
- code;
10729
- mapping = {};
10730
- static fromFile(file) {
10731
- const inst = new this(readFile(file));
10732
- inst.file = file;
10733
- return inst;
10734
- }
10735
- constructor(code) {
10736
- this.code = code;
10737
- return this;
10738
- }
10739
- applyEnv() {
10740
- const replaceEnv = initReplaceEnv();
10741
- this.code = replaceEnv(this.code, this.file || "");
10742
- return this;
10743
- }
10744
- escape() {
10745
- const isJS = this.file.includes(".js") || this.file.includes(".ts");
10746
- const isML = this.file.includes(".php") || this.file.includes(".htm");
10747
- this.code = this.code.replace(phpTagRegex, (match) => {
10748
- let token = makeID();
10749
- if (isJS) {
10750
- token = `/*${token}*/`;
10751
- } else if (isML) {
10752
- token = `\u2400\u2400${token}\u2400\u2400`;
10753
- }
10754
- this.mapping[token] = match;
10755
- return token;
10756
- });
10757
- return this;
10758
- }
10759
- write(file, mapping = false) {
10760
- writeFile(file, this.code);
10761
- mapping && writeFile(file + ".json", JSON.stringify(this.mapping));
10762
- }
10763
- static unescape(code, mapping) {
10764
- let out = code;
10765
- Object.entries(mapping).forEach(([token, code2]) => {
10766
- out = out.replace(token, code2);
10767
- });
10768
- return out;
10769
- }
10937
+ return utils.path.escapePosixPath(source);
10938
+ }
10939
+ posix.escapePath = escapePath;
10940
+ function convertPathToPattern(source) {
10941
+ assertPatternsInput(source);
10942
+ return utils.path.convertPosixPathToPattern(source);
10943
+ }
10944
+ posix.convertPathToPattern = convertPathToPattern;
10945
+ })(FastGlob.posix || (FastGlob.posix = {}));
10946
+ (function (win32) {
10947
+ function escapePath(source) {
10948
+ assertPatternsInput(source);
10949
+ return utils.path.escapeWindowsPath(source);
10950
+ }
10951
+ win32.escapePath = escapePath;
10952
+ function convertPathToPattern(source) {
10953
+ assertPatternsInput(source);
10954
+ return utils.path.convertWindowsPathToPattern(source);
10955
+ }
10956
+ win32.convertPathToPattern = convertPathToPattern;
10957
+ })(FastGlob.win32 || (FastGlob.win32 = {}));
10958
+ })(FastGlob || (FastGlob = {}));
10959
+ function getWorks(source, _Provider, options) {
10960
+ const patterns = [].concat(source);
10961
+ const settings = new settings_1.default(options);
10962
+ const tasks = taskManager.generate(patterns, settings);
10963
+ const provider = new _Provider(settings);
10964
+ return tasks.map(provider.read, provider);
10965
+ }
10966
+ function assertPatternsInput(input) {
10967
+ const source = [].concat(input);
10968
+ const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
10969
+ if (!isValidSource) {
10970
+ throw new TypeError('Patterns must be a string (non empty) or an array of strings');
10971
+ }
10972
+ }
10973
+ out = FastGlob;
10974
+ return out;
10770
10975
  }
10771
10976
 
10772
- const exitSignals = [
10773
- "exit",
10774
- "SIGINT",
10775
- "SIGUSR1",
10776
- "SIGUSR2",
10777
- "uncaughtException",
10778
- "SIGTERM"
10779
- ];
10780
- function exitHandler(signal) {
10781
- if (signal === "SIGINT") {
10782
- console.log();
10783
- }
10784
- const tempDir = resolve(shared.tempDir);
10785
- if (shared.devConfig.cleanup && existsSync(tempDir)) {
10786
- log("Removing temporary files");
10787
- rmSync(tempDir, {
10788
- recursive: true,
10789
- force: true
10790
- });
10791
- }
10792
- if (PHP_Server.process && shared.viteConfig?.command === "serve") {
10793
- PHP_Server.stop(() => {
10794
- process.exit();
10795
- });
10796
- } else {
10797
- process.exit();
10798
- }
10799
- }
10800
- const listeners = /* @__PURE__ */ new Map();
10801
- const handleExit = {
10802
- register() {
10803
- exitSignals.forEach((eventType) => {
10804
- new Promise((resolve2) => {
10805
- listeners.set(eventType, resolve2);
10806
- process.on(eventType, resolve2);
10807
- }).then(exitHandler);
10808
- });
10809
- },
10810
- unregister() {
10811
- exitSignals.forEach((eventType) => {
10812
- const listener = listeners.get(eventType);
10813
- if (listener) {
10814
- process.off(eventType, listener);
10815
- listeners.delete(eventType);
10816
- }
10817
- });
10818
- }
10819
- };
10977
+ var outExports = requireOut();
10978
+ const FastGlob = /*@__PURE__*/getDefaultExportFromCjs(outExports);
10820
10979
 
10821
- const assetsPattern = new RegExp(
10822
- `^(.+?)(${phpStartPattern}\\s+namespace\\s\\S+?(?:\\s*;|\\s*{).+)$`,
10823
- "si"
10824
- );
10825
- const viteClientInjection = '<script type="module" src="/@vite/client"><\/script>\n';
10826
- const viteClientInjectionPattern = new RegExp(
10827
- '<script.+?src="/@vite/client".+?<\/script>(\r\n|\n|\r)',
10828
- "si"
10829
- );
10830
- const lastTagPattern = new RegExp(`^(.+(?:</.+?>|<.+?/>))(.+|)$`, "si");
10831
- const closingPattern = new RegExp(`^(.+)(${phpStartPattern}.+)$`, "si");
10832
- function fixAssetsInjection(input) {
10833
- let out = input;
10834
- let assets = "";
10835
- out = out.replace(assetsPattern, (match, p1, p2) => {
10836
- assets = p1.trim();
10837
- return p2;
10838
- });
10839
- const injectAssets = (_, part1, part2) => {
10840
- let a = assets;
10841
- if (!(part1.endsWith("\n") || part1.endsWith("\r"))) {
10842
- a = "\r\n" + a;
10843
- }
10844
- if (!(part2.startsWith("\n") || part2.startsWith("\r"))) {
10845
- a += "\r\n";
10846
- }
10847
- assets = "";
10848
- return `${part1}${a}${part2}`;
10849
- };
10850
- if (assets) {
10851
- out = out.replace(lastTagPattern, injectAssets);
10852
- }
10853
- if (assets) {
10854
- out = out.replace(closingPattern, injectAssets);
10855
- }
10856
- if (assets) {
10857
- out += assets;
10858
- }
10859
- return out;
10980
+ function findFiles(pattern, root = process.cwd(), ignore) {
10981
+ return [
10982
+ ...new Set(
10983
+ pattern.flatMap(
10984
+ (entry) => FastGlob.globSync(entry, {
10985
+ cwd: root,
10986
+ dot: true,
10987
+ onlyFiles: true,
10988
+ unique: true,
10989
+ ignore
10990
+ })
10991
+ )
10992
+ )
10993
+ ];
10860
10994
  }
10861
10995
 
10862
- const phpProxy = async (req, res, next) => {
10863
- try {
10864
- if (req.url && !["/@vite", "/@fs", "/@id/__x00__", "/node_modules"].some(
10865
- (path) => req.url.startsWith(path)
10866
- )) {
10867
- req.on("error", (error) => {
10868
- throw error;
10869
- });
10870
- let url = new URL(req.url, "http://localhost");
10871
- if (shared.viteConfig?.server.port) {
10872
- url.port = shared.viteConfig.server.port.toString();
10873
- }
10874
- const requestUrl = new URL(url);
10875
- if (url.pathname.endsWith("/")) {
10876
- url.pathname += "index.php";
10877
- }
10878
- const routedUrl = serve.rewriteUrl(url);
10879
- if (routedUrl) {
10880
- if (routedUrl.origin !== requestUrl.origin) {
10881
- res.writeHead(307, {
10882
- location: routedUrl.toString()
10883
- }).end();
10884
- return;
10885
- }
10886
- url = routedUrl;
10887
- }
10888
- const entryPathname = url.pathname.substring(1);
10889
- const entry = shared.entries.find((file) => {
10890
- return file === entryPathname || file.substring(0, file.lastIndexOf(".")) === entryPathname;
10891
- });
10892
- if (entry) {
10893
- const tempFile = tempName(entry);
10894
- if (existsSync(resolve(tempFile))) {
10895
- url.pathname = tempFile;
10896
- url.host = PHP_Server.host;
10897
- url.port = PHP_Server.port.toString();
10898
- url.searchParams.set(
10899
- internalParam,
10900
- new URLSearchParams({
10901
- $REQUEST_URI: requestUrl.pathname,
10902
- $PHP_SELF: "/" + entry,
10903
- temp_dir: shared.tempDir,
10904
- error_levels: shared.devConfig.errorLevels.toString()
10905
- }).toString()
10906
- );
10907
- const body = await new Promise(
10908
- (resolve2, reject) => {
10909
- let data = [];
10910
- req.on("data", (chunk) => {
10911
- data.push(chunk);
10912
- }).on("end", () => {
10913
- resolve2(Buffer.concat(data));
10914
- });
10915
- }
10916
- );
10917
- const phpResult = await new Promise(async (resolve2, reject) => {
10918
- const chunks = [];
10919
- let statusCode;
10920
- let incomingHeaders = {};
10921
- const request = http.request(
10922
- url.toString(),
10923
- {
10924
- method: req.method,
10925
- headers: {
10926
- ...req.headers,
10927
- "content-length": Buffer.byteLength(body)
10928
- }
10929
- },
10930
- (msg) => {
10931
- statusCode = msg.statusCode;
10932
- incomingHeaders = msg.headers;
10933
- msg.on("data", (data) => {
10934
- chunks.push(data);
10935
- });
10936
- }
10937
- ).on("error", (error) => {
10938
- reject(error);
10939
- }).on("close", () => {
10940
- let content = Buffer.concat(chunks).toString("utf8");
10941
- if (incomingHeaders["content-type"]?.includes(
10942
- "text/html"
10943
- ) && !viteClientInjectionPattern.test(content)) {
10944
- content = viteClientInjection + content;
10945
- if (incomingHeaders["content-length"]) {
10946
- incomingHeaders["content-length"] = `${content.length}`;
10947
- }
10948
- }
10949
- resolve2({
10950
- statusCode,
10951
- headers: incomingHeaders,
10952
- content
10953
- });
10954
- });
10955
- request.write(body, (error) => {
10956
- if (error) {
10957
- reject(error);
10958
- }
10959
- });
10960
- request.end();
10961
- });
10962
- res.writeHead(
10963
- phpResult.statusCode || 200,
10964
- phpResult.headers
10965
- ).end(phpResult.content);
10966
- return;
10967
- }
10968
- }
10969
- }
10970
- } catch (error) {
10971
- console.error("Vite-PHP Error: " + error);
10972
- }
10973
- next();
10974
- };
10996
+ function escapeRegExp(str) {
10997
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10998
+ }
10975
10999
 
10976
11000
  const serve = {
10977
11001
  rewriteUrl: (url) => url
10978
11002
  };
10979
11003
  let devServer = void 0;
10980
11004
  let entryMatcher = new RegExp(``, "gs");
11005
+ function updateEntryMatcher() {
11006
+ entryMatcher = new RegExp(
11007
+ `(${shared.entries.map(escapeRegExp).join("|")}).html`,
11008
+ "gs"
11009
+ );
11010
+ }
10981
11011
  const codeMap$1 = /* @__PURE__ */ new Map();
10982
11012
  const servePlugin = [
10983
11013
  {
@@ -10990,10 +11020,7 @@ const servePlugin = [
10990
11020
  if (!existsSync(gitIgnoreFile)) {
10991
11021
  writeFile(gitIgnoreFile, "*\r\n**/*");
10992
11022
  }
10993
- entryMatcher = new RegExp(
10994
- `(${shared.entries.join("|")}).html`,
10995
- "gs"
10996
- );
11023
+ updateEntryMatcher();
10997
11024
  }
10998
11025
  },
10999
11026
  configureServer: {
@@ -11125,12 +11152,10 @@ const servePlugin = [
11125
11152
  php.code = PHP_Code.unescape(php.code, escapes);
11126
11153
  }
11127
11154
  php.code = fixAssetsInjection(php.code);
11128
- if (!php.code.includes("</head>")) {
11129
- php.code = php.code.replace(
11130
- new RegExp(viteClientInjectionPattern, "gsi"),
11131
- ""
11132
- );
11133
- }
11155
+ php.code = php.code.replace(
11156
+ new RegExp(viteClientInjectionPattern, "gsi"),
11157
+ ""
11158
+ );
11134
11159
  php.write(tempName(entry));
11135
11160
  return php.code;
11136
11161
  }
@@ -11141,23 +11166,53 @@ const servePlugin = [
11141
11166
  name: "php:serve-watch",
11142
11167
  apply: "serve",
11143
11168
  async watchChange(id, change) {
11169
+ const resolvedId = resolve(id);
11170
+ const root = devServer?.config.root || process.cwd();
11144
11171
  const entry = shared.entries.find(
11145
- (entryFile) => resolve(entryFile) === resolve(id)
11172
+ (entryFile) => resolve(root, entryFile) === resolvedId
11146
11173
  );
11147
- if (entry) {
11174
+ if (change.event === "delete" && entry) {
11148
11175
  try {
11149
- await this.load({
11150
- id: entry
11151
- });
11176
+ rmSync(resolve(shared.tempDir, entry));
11152
11177
  } catch (error) {
11153
11178
  }
11179
+ } else {
11180
+ const loadEntry = async (entry2) => {
11181
+ try {
11182
+ await this.load({
11183
+ id: entry2
11184
+ });
11185
+ } catch (error) {
11186
+ }
11187
+ };
11188
+ if (entry) {
11189
+ await loadEntry(entry);
11190
+ } else if (devServer && !resolvedId.startsWith(resolve(shared.tempDir)) && resolvedId.includes(".php")) {
11191
+ const priorEntries = shared.entries;
11192
+ shared.entries = findFiles(
11193
+ shared.entryPatterns,
11194
+ devServer.config.root,
11195
+ [
11196
+ shared.tempDir,
11197
+ devServer.config.build?.outDir || "dist"
11198
+ ]
11199
+ );
11200
+ updateEntryMatcher();
11201
+ const allEntries = shared.entries;
11202
+ const newEntries = allEntries.filter(
11203
+ (entry2) => !priorEntries.includes(entry2)
11204
+ );
11205
+ await Promise.allSettled(newEntries.map(loadEntry));
11206
+ }
11154
11207
  }
11155
11208
  },
11156
11209
  handleHotUpdate({ server, file }) {
11210
+ const resolvedFile = resolve(file);
11211
+ const root = devServer?.config.root || process.cwd();
11157
11212
  const entry = shared.entries.find(
11158
- (entryFile) => resolve(entryFile) === resolve(file)
11213
+ (entryFile) => resolve(root, entryFile) === resolvedFile
11159
11214
  );
11160
- if (entry || !file.startsWith(resolve(shared.tempDir)) && file.includes(".php")) {
11215
+ if (entry || !resolvedFile.startsWith(resolve(shared.tempDir)) && resolvedFile.includes(".php")) {
11161
11216
  server.ws.send({
11162
11217
  type: "full-reload"
11163
11218
  });
@@ -11270,11 +11325,11 @@ const buildPlugin = [
11270
11325
  ];
11271
11326
 
11272
11327
  function usePHP(cfg = {}) {
11273
- const { entry = "index.php" } = cfg;
11328
+ const { entry = shared.entryPatterns } = cfg;
11274
11329
  PHP_Server.binary = cfg.binary ?? PHP_Server.binary;
11275
11330
  PHP_Server.host = cfg.php?.host ?? PHP_Server.host;
11276
11331
  serve.rewriteUrl = cfg.rewriteUrl ?? serve.rewriteUrl;
11277
- shared.entries = Array.isArray(entry) ? entry : [entry];
11332
+ shared.entryPatterns = Array.isArray(entry) ? entry : [entry];
11278
11333
  shared.tempDir = cfg.tempDir ?? shared.tempDir;
11279
11334
  shared.devConfig = {
11280
11335
  cleanup: cfg.dev?.cleanup || shared.devConfig.cleanup,
@@ -11285,21 +11340,10 @@ function usePHP(cfg = {}) {
11285
11340
  name: "php:init",
11286
11341
  enforce: "post",
11287
11342
  config(config, env) {
11288
- shared.entries = [
11289
- ...new Set(
11290
- shared.entries.flatMap(
11291
- (entry2) => fastGlob.globSync(entry2, {
11292
- dot: true,
11293
- onlyFiles: true,
11294
- unique: true,
11295
- ignore: [
11296
- shared.tempDir,
11297
- config.build?.outDir || "dist"
11298
- ]
11299
- })
11300
- )
11301
- )
11302
- ];
11343
+ shared.entries = findFiles(shared.entryPatterns, config.root, [
11344
+ shared.tempDir,
11345
+ config.build?.outDir || "dist"
11346
+ ]);
11303
11347
  return {
11304
11348
  server: {
11305
11349
  watch: {