@nodefony/frontend 10.0.0-beta.2 → 10.0.0-beta.3
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 +38 -50
- package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.153.0}/helpers/esm/decorate.js +1 -1
- package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.153.0}/helpers/esm/decorateMetadata.js +1 -1
- package/dist/index.js +2 -2
- package/dist/nodefony/config/config.js +3 -8
- package/dist/nodefony/service/FrontendService.js +73 -295
- package/dist/nodefony/service/ViteConfigGenerator.js +11 -30
- package/dist/nodefony/service/ViteProcessSupervisor.js +17 -12
- package/dist/nodefony/service/bootSummary.js +44 -0
- package/dist/nodefony/src/isolationGroups.js +27 -32
- package/dist/nodefony/src/template/TemplateHelper.js +52 -19
- package/dist/types/nodefony/config/config.d.ts +0 -8
- package/dist/types/nodefony/interfaces/IFrontBuilder.d.ts +0 -9
- package/dist/types/nodefony/interfaces/IFrontendService.d.ts +6 -10
- package/dist/types/nodefony/interfaces/IViteSupervisor.d.ts +11 -5
- package/dist/types/nodefony/service/FrontendService.d.ts +24 -118
- package/dist/types/nodefony/service/ViteConfigGenerator.d.ts +13 -21
- package/dist/types/nodefony/service/ViteProcessSupervisor.d.ts +13 -16
- package/dist/types/nodefony/service/bootSummary.d.ts +23 -0
- package/dist/types/nodefony/src/isolationGroups.d.ts +24 -23
- package/dist/types/nodefony/src/template/TemplateHelper.d.ts +23 -7
- package/docs/index.md +173 -145
- package/package.json +12 -12
- package/dist/nodefony/src/remoteDev.js +0 -216
- package/dist/types/nodefony/src/remoteDev.d.ts +0 -152
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import config from "../config/config.js";
|
|
2
2
|
import { FrontendNoEntriesError, FrontendSupervisorStartError } from "../src/errors/FrontendError.js";
|
|
3
3
|
import { ViteBuilder } from "../src/builders/ViteBuilder.js";
|
|
4
|
-
import { allowedHostPatternForTemplate, detectRemoteDev, isLoopbackHostname, isValidOriginTemplate, remoteDevListenAdvice, viteAllowedHostFromPattern } from "../src/remoteDev.js";
|
|
5
4
|
import { ViteProcessSupervisor } from "./ViteProcessSupervisor.js";
|
|
6
5
|
import { TemplateHelper } from "../src/template/TemplateHelper.js";
|
|
7
|
-
import {
|
|
8
|
-
import
|
|
9
|
-
import
|
|
6
|
+
import { devBasePath, familyPortPlan, isolationGroup } from "../src/isolationGroups.js";
|
|
7
|
+
import { summarizeFrontendBoot } from "./bootSummary.js";
|
|
8
|
+
import __decorateMetadata from "../../_virtual/_@oxc-project_runtime@0.153.0/helpers/esm/decorateMetadata.js";
|
|
9
|
+
import __decorate from "../../_virtual/_@oxc-project_runtime@0.153.0/helpers/esm/decorate.js";
|
|
10
10
|
import { FRONTEND_CHOICES, Module, Service, extend, injectable, stripTrailingSlashes } from "nodefony";
|
|
11
11
|
import path from "node:path";
|
|
12
12
|
import fs from "node:fs";
|
|
@@ -46,33 +46,6 @@ let FrontendService = class FrontendService extends Service {
|
|
|
46
46
|
entryFamily = /* @__PURE__ */ new Map();
|
|
47
47
|
/** Helper prod unique (lit les manifests) — `null` tant qu'on n'est pas en prod. */
|
|
48
48
|
prodHelper = null;
|
|
49
|
-
/**
|
|
50
|
-
* QUI a épinglé l'origine publique — la question n'est pas « est-elle
|
|
51
|
-
* épinglée » mais « par quoi », car les deux sources n'ont pas la même
|
|
52
|
-
* autorité :
|
|
53
|
-
*
|
|
54
|
-
* - `"config"` — `frontend.publicOrigin` : une décision ÉCRITE par l'auteur.
|
|
55
|
-
* Elle gagne sur tout, y compris sur le `Host` reçu : c'est le sens même
|
|
56
|
-
* d'un réglage explicite, et le seul moyen de servir derrière un frontal
|
|
57
|
-
* qui réécrit l'origine.
|
|
58
|
-
* - `"platform"` — Codespaces/Gitpod déduits de l'environnement : une
|
|
59
|
-
* DÉDUCTION, faite une fois au démarrage, sur une machine qui reçoit
|
|
60
|
-
* simultanément des clients arrivés par des chemins différents. Elle ne
|
|
61
|
-
* peut donc pas prévaloir sur un fait constaté à la requête — un client
|
|
62
|
-
* venu de la boucle locale se sert en local (cf `derivableHost`).
|
|
63
|
-
* - `null` — rien d'épinglé : chaque page annonce l'origine par laquelle son
|
|
64
|
-
* client est arrivé.
|
|
65
|
-
*/
|
|
66
|
-
originPinnedBy = null;
|
|
67
|
-
/**
|
|
68
|
-
* Ports que l'instance Vite de chaque famille PEUT prendre pour ce démarrage
|
|
69
|
-
* (bloc de la famille, port-retry compris) — `null` tant que `startDev` n'a
|
|
70
|
-
* pas établi le plan, et remis à `null` par `stopDev`.
|
|
71
|
-
*
|
|
72
|
-
* Alloué une fois par démarrage de développement, jamais en production
|
|
73
|
-
* (`startDev` n'y tourne pas) : aucun coût par requête.
|
|
74
|
-
*/
|
|
75
|
-
plannedPortBlocks = null;
|
|
76
49
|
constructor(module) {
|
|
77
50
|
const options = module.options;
|
|
78
51
|
const merged = extend(true, {}, config, options ?? {});
|
|
@@ -114,18 +87,10 @@ let FrontendService = class FrontendService extends Service {
|
|
|
114
87
|
} catch (e) {
|
|
115
88
|
this.log(e, "ERROR");
|
|
116
89
|
} finally {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
ready++;
|
|
122
|
-
const scheme = st.https ? "https" : "http";
|
|
123
|
-
const url = `${st.origin ?? `${scheme}://${st.host}:${st.port}`}/`;
|
|
124
|
-
for (const e of st.entries) {
|
|
125
|
-
const fw = e.type.replace(/[0-9]+$/, "");
|
|
126
|
-
this.kernel?.reportBootLine("Frontend (Vite)", `${e.entryName.padEnd(24)}${url}${fw ? ` ${fw}` : ""}`);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
90
|
+
const summary = summarizeFrontendBoot([...this.supervisors.values()].map((sup) => sup.status()));
|
|
91
|
+
const ready = summary.ready;
|
|
92
|
+
this.kernel?.setBootLines("Frontend (Vite)", summary.lines);
|
|
93
|
+
if (summary.notice) this.kernel?.reportBootNotice(summary.notice);
|
|
129
94
|
this.kernel?.fire("onFrontendReady", {
|
|
130
95
|
bundles: names.length,
|
|
131
96
|
names,
|
|
@@ -162,8 +127,7 @@ let FrontendService = class FrontendService extends Service {
|
|
|
162
127
|
root,
|
|
163
128
|
entryFile: relEntry,
|
|
164
129
|
outDir,
|
|
165
|
-
publicPath: normalizePublicPath(declaration.publicPath ?? `/_assets/${entryName}`)
|
|
166
|
-
apiProxyPaths: declaration.apiProxyPaths ?? []
|
|
130
|
+
publicPath: normalizePublicPath(declaration.publicPath ?? `/_assets/${entryName}`)
|
|
167
131
|
};
|
|
168
132
|
this.entries.push(entry);
|
|
169
133
|
this.log(`registered entry: ${entry.entryName} (${entry.type}) from "${entry.moduleName}"`, "INFO");
|
|
@@ -180,7 +144,7 @@ let FrontendService = class FrontendService extends Service {
|
|
|
180
144
|
origin: null,
|
|
181
145
|
port: null,
|
|
182
146
|
pid: null,
|
|
183
|
-
https:
|
|
147
|
+
https: false,
|
|
184
148
|
restartCount: 0,
|
|
185
149
|
healthFailures: 0,
|
|
186
150
|
portRetries: 0,
|
|
@@ -206,38 +170,21 @@ let FrontendService = class FrontendService extends Service {
|
|
|
206
170
|
async startDev() {
|
|
207
171
|
if (this.entries.length === 0) throw new FrontendNoEntriesError();
|
|
208
172
|
if (this.supervisors.size > 0 && [...this.supervisors.values()].some((s) => s.status().state === "ready")) return;
|
|
209
|
-
const backendOrigin = `${this.cfg.backendProtocol}://${this.cfg.backendHost}:${this.resolveBackendPort()}`;
|
|
210
|
-
const https = this.resolveHttps();
|
|
211
|
-
const pinned = this.resolvePublicOrigin();
|
|
212
|
-
const conseil = remoteDevListenAdvice(detectRemoteDev(process.env), this.cfg.devHost);
|
|
213
|
-
if (conseil) this.log(conseil, "WARNING");
|
|
214
|
-
const publicOriginTemplate = pinned?.template;
|
|
215
|
-
this.originPinnedBy = pinned?.source ?? null;
|
|
216
|
-
const allowedHosts = this.viteAllowedHosts(publicOriginTemplate);
|
|
217
173
|
const nodeEnv = this.kernel?.environment;
|
|
218
174
|
const extraEnv = this.cfg.viteEnv;
|
|
219
175
|
const groups = this.groupEntriesByFamily();
|
|
220
176
|
const portPlan = familyPortPlan(this.cfg.devPort, [...groups.keys()], this.cfg.resilience.portRetryAttempts);
|
|
221
177
|
const families = [...portPlan.keys()];
|
|
222
|
-
if (publicOriginTemplate && !publicOriginTemplate.includes("{port}") && families.length > 1) this.log(`publicOrigin figée (« ${publicOriginTemplate} ») avec ${families.length} familles Vite (${families.join(", ")}) — une origine ne peut en servir qu'UNE : utiliser {port} (ex. https://host:{port}) pour suivre chaque famille`, "WARNING");
|
|
223
|
-
this.plannedPortBlocks = familyPortBlocks(portPlan, this.cfg.resilience.portRetryAttempts);
|
|
224
178
|
this.#registerCsp();
|
|
225
|
-
this.fire("frontend:starting", {
|
|
226
|
-
backendOrigin,
|
|
227
|
-
entries: this.entries
|
|
228
|
-
});
|
|
179
|
+
this.fire("frontend:starting", { entries: this.entries });
|
|
229
180
|
const total = this.entries.length;
|
|
230
181
|
let done = 0;
|
|
231
182
|
(await Promise.allSettled([...portPlan].map(([family, port]) => {
|
|
232
183
|
const familyEntries = groups.get(family) ?? [];
|
|
233
184
|
const famSize = familyEntries.length;
|
|
234
185
|
return this.startFamily(family, familyEntries, port, {
|
|
235
|
-
backendOrigin,
|
|
236
|
-
https,
|
|
237
186
|
nodeEnv,
|
|
238
|
-
extraEnv
|
|
239
|
-
publicOriginTemplate,
|
|
240
|
-
allowedHosts
|
|
187
|
+
extraEnv
|
|
241
188
|
}).finally(() => {
|
|
242
189
|
done += famSize;
|
|
243
190
|
this.kernel?.fire("onFrontendProgress", {
|
|
@@ -257,114 +204,8 @@ let FrontendService = class FrontendService extends Service {
|
|
|
257
204
|
this.fire("frontend:error", err);
|
|
258
205
|
throw err;
|
|
259
206
|
}
|
|
260
|
-
this.#registerCsp();
|
|
261
207
|
this.fire("frontend:ready", this.status());
|
|
262
208
|
}
|
|
263
|
-
/**
|
|
264
|
-
* Port backend que Vite doit proxifier — le port RÉELLEMENT écouté, pas celui
|
|
265
|
-
* qu'on espérait.
|
|
266
|
-
*
|
|
267
|
-
* `config.backendPort` (5151) n'est qu'une intention : avec
|
|
268
|
-
* `servers.portPolicy: "auto"`, un port occupé fait glisser l'écoute du backend
|
|
269
|
-
* (5151 → 5153). Un proxy figé sur 5151 enverrait alors les appels API du front
|
|
270
|
-
* vers le serveur d'une AUTRE app — au mieux des 404, au pire les données du
|
|
271
|
-
* voisin. On lit donc le port sur le serveur lui-même.
|
|
272
|
-
*
|
|
273
|
-
* Résolution par NOM (`server-http`), jamais par import : `@nodefony/frontend`
|
|
274
|
-
* ne dépend pas de `@nodefony/http` (cycle via la config d'app).
|
|
275
|
-
*/
|
|
276
|
-
resolveBackendPort() {
|
|
277
|
-
const server = this.container?.get("server-http");
|
|
278
|
-
const real = server?.active && server.port ? server.port : 0;
|
|
279
|
-
if (real > 0 && real !== this.cfg.backendPort) this.log(`backend à l'écoute sur ${real} (et non ${this.cfg.backendPort}) — le proxy Vite suit le port réel`, "INFO");
|
|
280
|
-
return real > 0 ? real : this.cfg.backendPort;
|
|
281
|
-
}
|
|
282
|
-
/**
|
|
283
|
-
* Résout les certificats HTTPS partagés (service `certificates` de
|
|
284
|
-
* @nodefony/http) si `https: true`. Pas de duplication — mêmes PEM que
|
|
285
|
-
* `server-https` (5152). Retombe sur HTTP avec un warning si indisponible.
|
|
286
|
-
*/
|
|
287
|
-
resolveHttps() {
|
|
288
|
-
if (!this.cfg.https) return void 0;
|
|
289
|
-
const certs = this.container?.get("certificates");
|
|
290
|
-
if (!certs?.privateKeyPath || !certs.certPath) {
|
|
291
|
-
this.log("https: true requested but `certificates` service unavailable — falling back to HTTP", "WARNING");
|
|
292
|
-
return;
|
|
293
|
-
}
|
|
294
|
-
return {
|
|
295
|
-
keyPath: certs.privateKeyPath,
|
|
296
|
-
certPath: certs.certPath
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
/**
|
|
300
|
-
* Template d'origine publique Vite (P14.17), AVEC sa provenance. Priorité :
|
|
301
|
-
* `frontend.publicOrigin` (config, validée — invalide = ERROR + ignorée,
|
|
302
|
-
* jamais un boot cassé) puis détection de plateforme (Codespaces/Gitpod —
|
|
303
|
-
* variables documentées de la plateforme, qu'on lit sans les posséder).
|
|
304
|
-
* `null` = dérivation locale.
|
|
305
|
-
*
|
|
306
|
-
* La provenance est rendue avec le template parce qu'elle CHANGE la suite :
|
|
307
|
-
* une config écrite est un ordre, une plateforme déduite est une supposition
|
|
308
|
-
* qui cède devant le `Host` reçu quand celui-ci désigne la boucle locale
|
|
309
|
-
* (cf `originPinnedBy`). Les confondre servait l'origine publique à un client
|
|
310
|
-
* venu d'un tunnel local, qui n'a pas la session de la plateforme.
|
|
311
|
-
*
|
|
312
|
-
* Chaque adaptation est JOURNALISÉE : on doit pouvoir lire dans le boot
|
|
313
|
-
* pourquoi les `<script>` pointent où ils pointent.
|
|
314
|
-
*/
|
|
315
|
-
resolvePublicOrigin() {
|
|
316
|
-
const cfgOrigin = this.cfg.publicOrigin;
|
|
317
|
-
if (cfgOrigin) {
|
|
318
|
-
if (!isValidOriginTemplate(cfgOrigin)) {
|
|
319
|
-
this.log(`frontend.publicOrigin invalide (« ${cfgOrigin} ») — attendu scheme://host[:port|:{port}] sans chemin ; origine locale utilisée`, "ERROR");
|
|
320
|
-
return null;
|
|
321
|
-
}
|
|
322
|
-
this.log(`origine publique Vite (config) : ${cfgOrigin}`, "INFO");
|
|
323
|
-
return {
|
|
324
|
-
template: cfgOrigin,
|
|
325
|
-
source: "config"
|
|
326
|
-
};
|
|
327
|
-
}
|
|
328
|
-
const detected = detectRemoteDev(process.env);
|
|
329
|
-
if (detected) {
|
|
330
|
-
this.log(`dev déporté détecté (${detected.provider}) — origine publique Vite : ${detected.originTemplate} (un client arrivé par la boucle locale reste servi en local)`, "INFO");
|
|
331
|
-
return {
|
|
332
|
-
template: detected.originTemplate,
|
|
333
|
-
source: "platform"
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
return null;
|
|
337
|
-
}
|
|
338
|
-
/**
|
|
339
|
-
* `server.allowedHosts` pour Vite. Vite accepte d'office IP et `localhost` ;
|
|
340
|
-
* cette liste ne porte que les NOMS. Source des noms légitimes = la MÊME que
|
|
341
|
-
* la barrière Host de Nodefony (`kernel.domain` + `trustedHosts` http) — une
|
|
342
|
-
* seule liste à maintenir : autoriser un hôte dans `trustedHosts` ouvre à la
|
|
343
|
-
* fois la barrière 421 ET Vite. S'y ajoute l'hôte du template d'origine
|
|
344
|
-
* publique. `trustedHosts: true` (barrière déléguée au reverse-proxy) →
|
|
345
|
-
* `true` (même délégation). Un pattern non exprimable chez Vite est ANNONCÉ.
|
|
346
|
-
*/
|
|
347
|
-
viteAllowedHosts(publicOriginTemplate) {
|
|
348
|
-
const th = (this.container?.get("HttpKernel"))?.trustedHosts;
|
|
349
|
-
if (th === true) return true;
|
|
350
|
-
const hosts = /* @__PURE__ */ new Set();
|
|
351
|
-
if (this.kernel?.domain) {
|
|
352
|
-
const d = viteAllowedHostFromPattern(this.kernel.domain);
|
|
353
|
-
if (d) hosts.add(d);
|
|
354
|
-
}
|
|
355
|
-
const patterns = Array.isArray(th) ? th : th ? [th] : [];
|
|
356
|
-
for (const p of patterns) {
|
|
357
|
-
if (typeof p !== "string") continue;
|
|
358
|
-
const v = viteAllowedHostFromPattern(p);
|
|
359
|
-
if (v) hosts.add(v);
|
|
360
|
-
else this.log(`trustedHosts « ${p} » non exprimable en allowedHosts Vite — cet hôte passera la barrière Nodefony mais Vite le refusera`, "WARNING");
|
|
361
|
-
}
|
|
362
|
-
if (publicOriginTemplate) {
|
|
363
|
-
const v = allowedHostPatternForTemplate(publicOriginTemplate);
|
|
364
|
-
if (v) hosts.add(v);
|
|
365
|
-
}
|
|
366
|
-
return hosts.size > 0 ? [...hosts] : void 0;
|
|
367
|
-
}
|
|
368
209
|
/** Regroupe les entries par famille d'isolation + remplit l'index inverse. */
|
|
369
210
|
groupEntriesByFamily() {
|
|
370
211
|
const groups = /* @__PURE__ */ new Map();
|
|
@@ -387,16 +228,14 @@ let FrontendService = class FrontendService extends Service {
|
|
|
387
228
|
const [first] = entries;
|
|
388
229
|
if (first === void 0) throw new FrontendNoEntriesError();
|
|
389
230
|
const r = this.cfg.resilience;
|
|
231
|
+
const devBase = devBasePath(family);
|
|
390
232
|
const supervisor = new ViteProcessSupervisor({
|
|
391
233
|
devHost: this.cfg.devHost,
|
|
392
234
|
devPort: port,
|
|
393
|
-
|
|
394
|
-
allowedHosts: ctx.allowedHosts,
|
|
235
|
+
devBase,
|
|
395
236
|
startupTimeoutMs: this.cfg.startupTimeoutMs,
|
|
396
237
|
pipeLogs: this.cfg.pipeViteLogs,
|
|
397
238
|
cwd: first.root,
|
|
398
|
-
backendOrigin: ctx.backendOrigin,
|
|
399
|
-
https: ctx.https,
|
|
400
239
|
nodeEnv: ctx.nodeEnv,
|
|
401
240
|
extraEnv: ctx.extraEnv,
|
|
402
241
|
autoRestart: r.autoRestart,
|
|
@@ -414,12 +253,49 @@ let FrontendService = class FrontendService extends Service {
|
|
|
414
253
|
}
|
|
415
254
|
});
|
|
416
255
|
this.supervisors.set(family, supervisor);
|
|
417
|
-
|
|
256
|
+
const helper = new TemplateHelper(supervisor, "development");
|
|
257
|
+
this.templateHelpers.set(family, helper);
|
|
258
|
+
this.mountDevProxy(devBase, helper);
|
|
418
259
|
const cfg = await this.builder.buildViteConfig([...entries], "development");
|
|
419
260
|
await supervisor.start(entries, cfg);
|
|
420
261
|
this.log(`vite [${family}] ready on ${supervisor.status().host}:${supervisor.status().port}`, "INFO");
|
|
421
262
|
}
|
|
422
263
|
/**
|
|
264
|
+
* Monte `/_vite/<famille>/` sur le proxy inverse de `@nodefony/http` (#528).
|
|
265
|
+
*
|
|
266
|
+
* Tout ce que la page demande à Vite — modules, images importées, `url()`
|
|
267
|
+
* CSS, socket du rechargement à chaud — porte ce préfixe (`base` Vite) et
|
|
268
|
+
* reste donc sur l'ORIGINE DE LA PAGE : un certificat, aucun contenu mixte,
|
|
269
|
+
* et les API réservées aux contextes sécurisés (caméra, Service Workers,
|
|
270
|
+
* WebAuthn) disponibles depuis un téléphone, une IP de réseau local ou un
|
|
271
|
+
* navigateur en conteneur. Vite, lui, reste sur la boucle locale.
|
|
272
|
+
*
|
|
273
|
+
* GET/HEAD seulement (Vite ne sert que des lectures) ; `cookie` et
|
|
274
|
+
* `authorization` ne lui parviennent pas — un serveur de sources n'a pas à
|
|
275
|
+
* voir la session. Posé avant `start()` : tant que Vite n'est pas prêt, la
|
|
276
|
+
* cible est inconnue et le relais répond `503` — à la socket de sonde du
|
|
277
|
+
* client Vite comprise, AVANT tout `101` : la page ne recharge qu'une fois
|
|
278
|
+
* Vite revenu, jamais sur une page blanche (#577). No-op sans proxy
|
|
279
|
+
* (application sans serveur HTTP).
|
|
280
|
+
*
|
|
281
|
+
* @param devBase - chemin de base de la famille (`devBasePath`)
|
|
282
|
+
* @param helper - helper de la famille, qui connaît son superviseur
|
|
283
|
+
*/
|
|
284
|
+
mountDevProxy(devBase, helper) {
|
|
285
|
+
const proxy = this.container?.get("reverse-proxy");
|
|
286
|
+
if (!proxy) return;
|
|
287
|
+
if (typeof proxy.mount !== "function") {
|
|
288
|
+
this.log(`relais ${devBase} impossible : le service reverse-proxy ne sait pas monter un préfixe — le front ne se chargera pas en développement. Aligner @nodefony/http sur la version de @nodefony/frontend.`, "WARNING");
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
proxy.mount(devBase, {
|
|
292
|
+
target: () => helper.devTarget(),
|
|
293
|
+
websocket: true,
|
|
294
|
+
methods: ["GET", "HEAD"],
|
|
295
|
+
stripHeaders: ["cookie", "authorization"]
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
423
299
|
* Câblage prod (idempotent) : monte chaque `outDir` sur son `publicPath`
|
|
424
300
|
* auprès du serveur statique `server-static` (résolu par nom — pas d'import
|
|
425
301
|
* http) et crée le helper prod (lecture manifests). No-op si pas d'entrée.
|
|
@@ -464,10 +340,11 @@ let FrontendService = class FrontendService extends Service {
|
|
|
464
340
|
async stopDev() {
|
|
465
341
|
if (this.supervisors.size === 0) return;
|
|
466
342
|
await Promise.allSettled([...this.supervisors.values()].map((s) => s.stop()));
|
|
343
|
+
const proxy = this.container?.get("reverse-proxy");
|
|
344
|
+
for (const family of this.supervisors.keys()) proxy?.unmount?.(devBasePath(family));
|
|
467
345
|
this.supervisors.clear();
|
|
468
346
|
this.templateHelpers.clear();
|
|
469
347
|
this.entryFamily.clear();
|
|
470
|
-
this.plannedPortBlocks = null;
|
|
471
348
|
(this.container?.get("firewall"))?.unregisterCspOrigins?.("frontend");
|
|
472
349
|
this.fire("frontend:stopped");
|
|
473
350
|
}
|
|
@@ -582,46 +459,19 @@ let FrontendService = class FrontendService extends Service {
|
|
|
582
459
|
* Le controller renvoie : `this.render(svc.renderDocument("x", this.context.cspNonce))`.
|
|
583
460
|
* @param nonce nonce CSP de la requête (`Context.cspNonce`) — propagé aux `<script>`.
|
|
584
461
|
*/
|
|
585
|
-
renderDocument(entryName, nonce
|
|
462
|
+
renderDocument(entryName, nonce) {
|
|
586
463
|
if (this.prodHelper) return this.prodHelper.renderDocument(entryName, nonce);
|
|
587
464
|
const family = this.entryFamily.get(entryName);
|
|
588
465
|
const helper = family ? this.templateHelpers.get(family) : void 0;
|
|
589
466
|
if (!helper) return `<!-- @nodefony/frontend: helper not initialized for "${entryName}" -->`;
|
|
590
|
-
return helper.renderDocument(entryName, nonce
|
|
467
|
+
return helper.renderDocument(entryName, nonce);
|
|
591
468
|
}
|
|
592
|
-
renderTags(entryName, nonce
|
|
469
|
+
renderTags(entryName, nonce) {
|
|
593
470
|
if (this.prodHelper) return this.prodHelper.renderTags(entryName, nonce);
|
|
594
471
|
const family = this.entryFamily.get(entryName);
|
|
595
472
|
const helper = family ? this.templateHelpers.get(family) : void 0;
|
|
596
473
|
if (!helper) return `<!-- @nodefony/frontend: helper not initialized for "${entryName}" -->`;
|
|
597
|
-
return helper.renderTags(entryName, nonce
|
|
598
|
-
}
|
|
599
|
-
/**
|
|
600
|
-
* Le `Host` de la requête peut-il servir à dériver l'origine des assets ?
|
|
601
|
-
*
|
|
602
|
-
* Trois conditions, dans cet ordre — chacune protège un cas RÉEL :
|
|
603
|
-
* 1. **origine non épinglée** : un `frontend.publicOrigin` explicite (ou une
|
|
604
|
-
* plateforme de dev déporté détectée) est une décision de l'auteur, elle
|
|
605
|
-
* gagne toujours sur une déduction ;
|
|
606
|
-
* 2. **barrière `trustedHosts` franchie** : le `Host` est une donnée
|
|
607
|
-
* CLIENTE. Sans ce filtre, un `Host` forgé ferait émettre des
|
|
608
|
-
* `<script src="https://attaquant:5173/…">` dans une page de dev ;
|
|
609
|
-
* 3. **barrière non déléguée** (`trustedHosts !== true`) : le bypass total
|
|
610
|
-
* ne dit plus rien de la légitimité d'un nom, et surtout le CSP émis par
|
|
611
|
-
* le firewall (`#viteCspFragment`) ne couvre alors QUE loopback +
|
|
612
|
-
* domaine canonique — dériver ailleurs produirait une page dont les
|
|
613
|
-
* scripts sont bloqués. Les deux listes doivent rester la même liste.
|
|
614
|
-
*
|
|
615
|
-
* @returns le nom d'hôte à employer, ou `undefined` pour garder l'origine
|
|
616
|
-
* résolue au démarrage (comportement d'avant la dérivation).
|
|
617
|
-
*/
|
|
618
|
-
derivableHost(requestHost) {
|
|
619
|
-
if (!requestHost) return void 0;
|
|
620
|
-
if (this.originPinnedBy === "config") return void 0;
|
|
621
|
-
if (this.originPinnedBy === "platform" && !isLoopbackHostname(requestHost)) return;
|
|
622
|
-
const httpKernel = this.container?.get("HttpKernel");
|
|
623
|
-
if (!httpKernel || httpKernel.trustedHosts === true) return void 0;
|
|
624
|
-
return httpKernel.isTrustedHostname?.(requestHost) === true ? requestHost : void 0;
|
|
474
|
+
return helper.renderTags(entryName, nonce);
|
|
625
475
|
}
|
|
626
476
|
/**
|
|
627
477
|
* Déclare les origines Vite dev au firewall `@nodefony/security` (résolution PAR
|
|
@@ -633,51 +483,22 @@ let FrontendService = class FrontendService extends Service {
|
|
|
633
483
|
(this.container?.get("firewall"))?.registerCspOrigins?.("frontend", this.#viteCspFragment());
|
|
634
484
|
}
|
|
635
485
|
/**
|
|
636
|
-
* Fragment CSP des besoins Vite DEV
|
|
486
|
+
* Fragment CSP des besoins Vite DEV — sans aucune origine : modules,
|
|
487
|
+
* styles, images et socket du rechargement à chaud passent tous par
|
|
488
|
+
* l'origine de la page (`/_vite/<famille>/`, #528). Deux exigences restent :
|
|
637
489
|
* 1. **`'self'` dans CHAQUE directive** : `connect-src`/`style-src`/`img-src`/
|
|
638
|
-
* `font-src` n'héritent PAS de `default-src
|
|
639
|
-
*
|
|
640
|
-
* 2.
|
|
641
|
-
*
|
|
642
|
-
*
|
|
643
|
-
*
|
|
644
|
-
*
|
|
645
|
-
* script : le preamble inline est NONCÉ. Mergé par le firewall (jamais en prod :
|
|
646
|
-
* `startDev` ne tourne pas en production → CSP strict same-origin).
|
|
490
|
+
* `font-src` n'héritent PAS de `default-src`. `'self'` couvre aussi le
|
|
491
|
+
* socket `ws(s):` de même hôte et port (CSP niveau 3).
|
|
492
|
+
* 2. Tokens : `'unsafe-eval'` (React Fast Refresh — le nonce ne couvre PAS
|
|
493
|
+
* l'eval) et `'unsafe-inline'` style (styles injectés par Vite). PAS de
|
|
494
|
+
* `'unsafe-inline'` script : le preamble inline est NONCÉ.
|
|
495
|
+
* Mergé par le firewall (jamais en prod : `startDev` ne tourne pas en
|
|
496
|
+
* production → CSP strict same-origin).
|
|
647
497
|
*/
|
|
648
498
|
#viteCspFragment() {
|
|
649
|
-
const scheme = this.cfg.https ? "https" : "http";
|
|
650
|
-
const wsScheme = this.cfg.https ? "wss" : "ws";
|
|
651
|
-
const ports = this.cspPorts();
|
|
652
|
-
const hosts = /* @__PURE__ */ new Set(["127.0.0.1", "localhost"]);
|
|
653
|
-
if (this.kernel?.domain) hosts.add(this.kernel.domain);
|
|
654
|
-
const th = (this.container?.get("HttpKernel"))?.trustedHosts;
|
|
655
|
-
if (typeof th === "string") hosts.add(th);
|
|
656
|
-
else if (Array.isArray(th)) for (const h of th) hosts.add(h);
|
|
657
|
-
const httpSrc = [];
|
|
658
|
-
const wsSrc = [];
|
|
659
|
-
for (const h of hosts) for (const p of ports) {
|
|
660
|
-
httpSrc.push(`${scheme}://${h}:${p}`);
|
|
661
|
-
wsSrc.push(`${wsScheme}://${h}:${p}`);
|
|
662
|
-
}
|
|
663
|
-
for (const s of this.supervisors.values()) {
|
|
664
|
-
const o = s.status().origin;
|
|
665
|
-
if (!o) continue;
|
|
666
|
-
if (!httpSrc.includes(o)) httpSrc.push(o);
|
|
667
|
-
const w = o.replace(/^http/, "ws");
|
|
668
|
-
if (!wsSrc.includes(w)) wsSrc.push(w);
|
|
669
|
-
}
|
|
670
499
|
return {
|
|
671
|
-
"script-src": [
|
|
672
|
-
|
|
673
|
-
"'unsafe-eval'",
|
|
674
|
-
...httpSrc
|
|
675
|
-
],
|
|
676
|
-
"style-src": [
|
|
677
|
-
"'self'",
|
|
678
|
-
"'unsafe-inline'",
|
|
679
|
-
...httpSrc
|
|
680
|
-
],
|
|
500
|
+
"script-src": ["'self'", "'unsafe-eval'"],
|
|
501
|
+
"style-src": ["'self'", "'unsafe-inline'"],
|
|
681
502
|
"worker-src": ["'self'", "blob:"],
|
|
682
503
|
"img-src": [
|
|
683
504
|
"'self'",
|
|
@@ -685,59 +506,16 @@ let FrontendService = class FrontendService extends Service {
|
|
|
685
506
|
"blob:",
|
|
686
507
|
"https://www.gravatar.com",
|
|
687
508
|
"https://*.googleusercontent.com",
|
|
688
|
-
"https://avatars.githubusercontent.com"
|
|
689
|
-
...httpSrc
|
|
690
|
-
],
|
|
691
|
-
"font-src": [
|
|
692
|
-
"'self'",
|
|
693
|
-
"data:",
|
|
694
|
-
...httpSrc
|
|
509
|
+
"https://avatars.githubusercontent.com"
|
|
695
510
|
],
|
|
511
|
+
"font-src": ["'self'", "data:"],
|
|
696
512
|
"connect-src": [
|
|
697
513
|
"'self'",
|
|
698
514
|
"blob:",
|
|
699
|
-
"data:"
|
|
700
|
-
...httpSrc,
|
|
701
|
-
...wsSrc
|
|
515
|
+
"data:"
|
|
702
516
|
]
|
|
703
517
|
};
|
|
704
518
|
}
|
|
705
|
-
/**
|
|
706
|
-
* Ports Vite à déclarer au CSP, famille par famille : le BLOC entier tant que
|
|
707
|
-
* l'instance ne sert pas, son port RÉEL dès qu'elle sert.
|
|
708
|
-
*
|
|
709
|
-
* Pourquoi le bloc avant : le CSP part AVEC la page et ne se renégocie jamais.
|
|
710
|
-
* Une page servie avant que Vite ait résolu son port doit déjà porter le port
|
|
711
|
-
* qu'il prendra, sinon son socket de rechargement à chaud est refusé pour
|
|
712
|
-
* toute la durée de la page.
|
|
713
|
-
*
|
|
714
|
-
* Pourquoi le port seul après : la plage est le prix d'une incertitude, elle
|
|
715
|
-
* ne doit pas lui survivre. Mesuré sur ce dépôt (3 familles × 4 hôtes de
|
|
716
|
-
* confiance), garder les blocs porte l'en-tête CSP à ~7,9 Ko sur CHAQUE
|
|
717
|
-
* réponse, contre ~2,3 Ko une fois les ports connus — au bord des 8 Ko que
|
|
718
|
-
* refusent beaucoup de relais.
|
|
719
|
-
*
|
|
720
|
-
* Développement seulement : `startDev` ne tourne pas en production. La
|
|
721
|
-
* garantie reste une liste d'origines nommées — jamais un `ws:` sans hôte,
|
|
722
|
-
* qui la supprimerait au lieu de corriger le symptôme.
|
|
723
|
-
*
|
|
724
|
-
* @returns ports en chaîne, dédupliqués ; repli `devPort` si rien n'est connu.
|
|
725
|
-
*/
|
|
726
|
-
cspPorts() {
|
|
727
|
-
const ports = /* @__PURE__ */ new Set();
|
|
728
|
-
for (const [family, block] of this.plannedPortBlocks ?? []) {
|
|
729
|
-
const st = this.supervisors.get(family)?.status();
|
|
730
|
-
if ((st?.state === "ready" || st?.state === "compiling") && st.port) ports.add(String(st.port));
|
|
731
|
-
else for (const p of block) ports.add(String(p));
|
|
732
|
-
}
|
|
733
|
-
for (const [family, sup] of this.supervisors) {
|
|
734
|
-
if (this.plannedPortBlocks?.has(family)) continue;
|
|
735
|
-
const st = sup.status();
|
|
736
|
-
if (st.port) ports.add(String(st.port));
|
|
737
|
-
}
|
|
738
|
-
if (ports.size === 0) ports.add(String(this.cfg.devPort));
|
|
739
|
-
return ports;
|
|
740
|
-
}
|
|
741
519
|
};
|
|
742
520
|
FrontendService = __decorate([injectable(), __decorateMetadata("design:paramtypes", [typeof Module === "undefined" ? Object : Module])], FrontendService);
|
|
743
521
|
var FrontendService_default = FrontendService;
|
|
@@ -16,11 +16,9 @@ var ViteConfigGenerator = class {
|
|
|
16
16
|
/**
|
|
17
17
|
* Construit le content `.mjs` à écrire à côté de `index.html` du module.
|
|
18
18
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* relatifs depuis l'app servie par Vite atterrissent sur Vite et reçoivent
|
|
23
|
-
* un SPA-fallback HTML (cause classique de `Unexpected token '<'`).
|
|
19
|
+
* Aucun `server.proxy` : la page est rendue par Nodefony et ses appels d'API
|
|
20
|
+
* partent sur sa propre origine ; Vite ne reçoit que ce que le relais
|
|
21
|
+
* `/_vite/<famille>/` lui transmet (#528).
|
|
24
22
|
*/
|
|
25
23
|
toMjs(entries, mode, opts = {}) {
|
|
26
24
|
const [first] = entries;
|
|
@@ -46,7 +44,7 @@ var ViteConfigGenerator = class {
|
|
|
46
44
|
imports.push(`import angular from "@analogjs/vite-plugin-angular";`);
|
|
47
45
|
if (!angularEntry) throw new Error("vite config: aucune entrée angular pour le type « angular »");
|
|
48
46
|
const tsconfigPath = toGeneratedPath(path.resolve(angularEntry.root, "tsconfig.app.json"));
|
|
49
|
-
pluginsExprs.push(`angular({ disableTypeChecking: false, tsconfig: ${JSON.stringify(tsconfigPath)} })`);
|
|
47
|
+
pluginsExprs.push(`angular({ disableTypeChecking: false, liveReload: true, tsconfig: ${JSON.stringify(tsconfigPath)} })`);
|
|
50
48
|
optimizeInclude.push("@angular/core", "@angular/common", "@angular/platform-browser");
|
|
51
49
|
break;
|
|
52
50
|
}
|
|
@@ -72,36 +70,19 @@ var ViteConfigGenerator = class {
|
|
|
72
70
|
const fsAllowLines = Array.from(fsAllowSet).map((p) => ` ${JSON.stringify(p)},`).join("\n");
|
|
73
71
|
const inputLines = Object.entries(input).map(([name, file]) => ` ${JSON.stringify(name)}: ${JSON.stringify(file)},`).join("\n");
|
|
74
72
|
const optimizeLines = optimizeInclude.map((d) => ` ${JSON.stringify(d)},`).join("\n");
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
}
|
|
80
|
-
const proxyLines = proxyPaths.size > 0 ? Array.from(proxyPaths).map((p) => ` ${JSON.stringify(p)}: { target: ${JSON.stringify(opts.backendOrigin)}, changeOrigin: false, secure: false, ws: true },`).join("\n") : "";
|
|
81
|
-
const useViteOrigin = mode === "development" && !!opts.viteOrigin;
|
|
82
|
-
const strictPort = useViteOrigin ? "true" : "false";
|
|
83
|
-
const httpsLines = mode === "development" && !!opts.https ? ` https: {
|
|
73
|
+
const devBase = mode === "development" && opts.devBase ? opts.devBase : void 0;
|
|
74
|
+
const serverBlock = ` server: {
|
|
75
|
+
strictPort: ${mode === "development" ? "true" : "false"},
|
|
76
|
+
${mode === "development" && !!opts.https ? ` https: {
|
|
84
77
|
key: fs.readFileSync(${JSON.stringify(toGeneratedPath(opts.https.keyPath))}),
|
|
85
78
|
cert: fs.readFileSync(${JSON.stringify(toGeneratedPath(opts.https.certPath))}),
|
|
86
|
-
},\n` : ""
|
|
87
|
-
const fsBlock = ` fs: {
|
|
79
|
+
},\n` : ""}${` fs: {
|
|
88
80
|
allow: [
|
|
89
81
|
${fsAllowLines}
|
|
90
82
|
],
|
|
91
83
|
},
|
|
92
|
-
|
|
93
|
-
const
|
|
94
|
-
const serverBlock = proxyPaths.size > 0 ? ` server: {
|
|
95
|
-
strictPort: ${strictPort},
|
|
96
|
-
cors: true,
|
|
97
|
-
${allowedHostsLine}${httpsLines}${fsBlock} proxy: {
|
|
98
|
-
${proxyLines}
|
|
99
|
-
},
|
|
100
|
-
},` : ` server: {
|
|
101
|
-
strictPort: ${strictPort},
|
|
102
|
-
cors: true,
|
|
103
|
-
${allowedHostsLine}${httpsLines}${fsBlock} },`;
|
|
104
|
-
const baseLine = useViteOrigin ? ` base: ${JSON.stringify(opts.viteOrigin + "/")},\n` : "";
|
|
84
|
+
`} },`;
|
|
85
|
+
const baseLine = devBase ? ` base: ${JSON.stringify(devBase)},\n` : "";
|
|
105
86
|
const dedupe = [];
|
|
106
87
|
if (usedTypes.has("react19")) dedupe.push("react", "react-dom");
|
|
107
88
|
if (usedTypes.has("vue3")) dedupe.push("vue");
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { FrontendSupervisorStartError } from "../src/errors/FrontendError.js";
|
|
2
2
|
import { ViteConfigGenerator } from "./ViteConfigGenerator.js";
|
|
3
|
-
import { browserReachableHost, resolveOriginTemplate } from "../src/remoteDev.js";
|
|
4
3
|
import { createRequire } from "node:module";
|
|
5
4
|
import { GENERATED_VITE_CONFIG_FILE, signalProcessGroup } from "nodefony";
|
|
6
5
|
import path from "node:path";
|
|
@@ -10,6 +9,18 @@ import http from "node:http";
|
|
|
10
9
|
import https from "node:https";
|
|
11
10
|
//#region nodefony/service/ViteProcessSupervisor.ts
|
|
12
11
|
/**
|
|
12
|
+
* Hôte JOIGNABLE pour une adresse d'écoute : `0.0.0.0`/`::` désignent toutes
|
|
13
|
+
* les interfaces, pas une destination — s'y connecter échoue sous Windows. Le
|
|
14
|
+
* superviseur, sa sonde et le proxy inverse joignent Vite depuis la machine
|
|
15
|
+
* qui le lance : la boucle locale est alors toujours juste.
|
|
16
|
+
*
|
|
17
|
+
* @param listenHost - adresse d'écoute (`devHost`)
|
|
18
|
+
* @returns l'hôte à joindre
|
|
19
|
+
*/
|
|
20
|
+
function browserReachableHost(listenHost) {
|
|
21
|
+
return listenHost === "0.0.0.0" || listenHost === "::" || listenHost === "[::]" || listenHost === "" ? "127.0.0.1" : listenHost;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
13
24
|
* Résout le binaire Vite **une seule fois** (mis en cache module-level).
|
|
14
25
|
*
|
|
15
26
|
* Lancer le VRAI `node vite.js` en direct — au lieu du shim `npx vite` — évite le
|
|
@@ -204,6 +215,7 @@ var ViteProcessSupervisor = class {
|
|
|
204
215
|
state: this.state,
|
|
205
216
|
host: this.opts.devHost,
|
|
206
217
|
origin: this.resolvedOrigin,
|
|
218
|
+
...this.opts.devBase ? { base: this.opts.devBase } : {},
|
|
207
219
|
port: this.resolvedPort,
|
|
208
220
|
pid: this.child?.pid ?? null,
|
|
209
221
|
lastError: this.lastError,
|
|
@@ -253,18 +265,11 @@ var ViteProcessSupervisor = class {
|
|
|
253
265
|
if (first === void 0) throw new FrontendSupervisorStartError("no entries");
|
|
254
266
|
const moduleRoot = first.root;
|
|
255
267
|
this.configFilePath = path.resolve(moduleRoot, GENERATED_VITE_CONFIG_FILE);
|
|
256
|
-
const
|
|
257
|
-
const tpl = this.opts.publicOriginTemplate;
|
|
258
|
-
const resolved = tpl ? resolveOriginTemplate(tpl, port) : null;
|
|
259
|
-
if (tpl && !resolved) this.opts.logger.error(`publicOrigin invalide (« ${tpl} ») — attendu scheme://host[:port|:{port}] ; origine locale dérivée utilisée à la place`);
|
|
260
|
-
if (resolved && tpl && !tpl.includes("{port}") && port !== this.opts.devPort) this.opts.logger.error(`publicOrigin figée (« ${tpl} ») mais Vite écoute sur ${port} (≠ ${this.opts.devPort}) — ajouter {port} au template ou libérer le port d'origine`);
|
|
261
|
-
const viteOrigin = resolved?.origin ?? `${scheme}://${browserReachableHost(this.opts.devHost)}:${port}`;
|
|
268
|
+
const viteOrigin = `${this.opts.https ? "https" : "http"}://${browserReachableHost(this.opts.devHost)}:${port}`;
|
|
262
269
|
this.resolvedOrigin = viteOrigin;
|
|
263
270
|
const content = this.generator.toMjs(this.entries, "development", {
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
https: this.opts.https,
|
|
267
|
-
allowedHosts: this.opts.allowedHosts
|
|
271
|
+
devBase: this.opts.devBase,
|
|
272
|
+
https: this.opts.https
|
|
268
273
|
});
|
|
269
274
|
writeFileSync(this.configFilePath, content, "utf8");
|
|
270
275
|
this.opts.logger.debug?.(`vite config written: ${this.configFilePath}`);
|
|
@@ -613,4 +618,4 @@ var ViteProcessSupervisor = class {
|
|
|
613
618
|
}
|
|
614
619
|
};
|
|
615
620
|
//#endregion
|
|
616
|
-
export { ViteProcessSupervisor, ViteProcessSupervisor as default, isPortInUseMessage, startupTimeoutMessage };
|
|
621
|
+
export { ViteProcessSupervisor, ViteProcessSupervisor as default, browserReachableHost, isPortInUseMessage, startupTimeoutMessage };
|