@poadio/starter-next 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.dockerignore +17 -8
- package/Dockerfile +26 -10
- package/Dockerfile.dockerignore +18 -0
- package/README.md +62 -6
- package/package.json +3 -1
- package/scripts/dev.mjs +33 -9
- package/scripts/env.mjs +34 -4
- package/scripts/env.test.mjs +24 -2
- package/src/app/layout.tsx +3 -2
- package/src/core/auth.tsx +3 -2
- package/src/core/env.server.ts +67 -11
- package/src/core/env.tsx +3 -1
package/.dockerignore
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
.
|
|
3
|
-
.
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
# Contexte de l'image : le front seul (docker build .) ou la racine d'un projet
|
|
2
|
+
# à plusieurs fronts (docker build -f apps/<nom>/Dockerfile --build-arg APP=apps/<nom> .).
|
|
3
|
+
# Docker lit ce fichier, placé à côté du Dockerfile, dans les deux cas.
|
|
4
|
+
**/node_modules
|
|
5
|
+
**/.next
|
|
6
|
+
**/.angular
|
|
7
|
+
**/dist
|
|
8
|
+
**/out
|
|
9
|
+
**/.git
|
|
10
|
+
**/public/env.json
|
|
11
|
+
**/.env
|
|
12
|
+
**/.env.*
|
|
13
|
+
!**/.env.example
|
|
9
14
|
poad/data
|
|
15
|
+
poad/backups
|
|
16
|
+
poad/secrets.toml
|
|
17
|
+
**/*.log
|
|
18
|
+
**/.DS_Store
|
package/Dockerfile
CHANGED
|
@@ -1,29 +1,45 @@
|
|
|
1
1
|
# Image du front : compilée une fois, configurée au démarrage.
|
|
2
|
+
#
|
|
3
|
+
# Front seul (son bun.lock à côté) :
|
|
2
4
|
# docker build -t mon-app .
|
|
3
|
-
#
|
|
5
|
+
# Front d'un projet à plusieurs fronts (apps/<nom>, bun.lock à la racine) :
|
|
6
|
+
# contexte = racine du projet, APP = dossier du front
|
|
7
|
+
# docker build -f apps/web/Dockerfile --build-arg APP=apps/web -t web .
|
|
8
|
+
#
|
|
9
|
+
# docker run -p 8080:3000 -e POAD_URL=https://... -e POAD_ANON_KEY=... mon-app
|
|
4
10
|
# Le serveur Next.js lit les variables PUBLIC_* et POAD_* à chaque requête et
|
|
5
|
-
# les passe au navigateur
|
|
11
|
+
# les passe au navigateur, avec les variables publiques du projet poad pour
|
|
12
|
+
# son application (poad.app du package.json, ou -e POAD_APP=…) : rien n'est
|
|
13
|
+
# compilé dans l'image (pas de NEXT_PUBLIC_* au build).
|
|
6
14
|
|
|
7
15
|
FROM node:22-alpine AS build
|
|
8
16
|
# bun installe les dépendances ; Node exécute Next.js
|
|
9
17
|
COPY --from=oven/bun:1.4.4-alpine /usr/local/bin/bun /usr/local/bin/bun
|
|
10
|
-
|
|
18
|
+
ARG APP=.
|
|
19
|
+
WORKDIR /src
|
|
11
20
|
ENV NEXT_TELEMETRY_DISABLED=1
|
|
12
|
-
|
|
13
|
-
|
|
21
|
+
# Tout le contexte (filtré par Dockerfile.dockerignore) : dans un espace de
|
|
22
|
+
# travail, le bun.lock et les package.json des autres fronts sont à la racine
|
|
14
23
|
COPY . .
|
|
24
|
+
WORKDIR /src/${APP}
|
|
25
|
+
RUN test -f package.json || { echo "APP=${APP}: no package.json there (build context = project root, APP = folder of the front-end)"; exit 1; }
|
|
26
|
+
RUN bun install --frozen-lockfile
|
|
15
27
|
RUN bun run build
|
|
28
|
+
# Serveur autonome à la même place quelle que soit la disposition : Next.js le
|
|
29
|
+
# range sous le chemin du front par rapport à la racine qu'il a retenue
|
|
30
|
+
RUN mkdir -p /out && cd .next/standalone \
|
|
31
|
+
&& if [ -f "./${APP}/server.js" ]; then dir="${APP}"; elif [ -f ./server.js ]; then dir=.; else echo "server.js not found in .next/standalone"; exit 1; fi \
|
|
32
|
+
&& cp -a . /out/ && echo "$dir" > /out/.app-dir \
|
|
33
|
+
&& mkdir -p "/out/$dir/.next" && cp -a /src/${APP}/.next/static "/out/$dir/.next/static" \
|
|
34
|
+
&& { [ ! -d /src/${APP}/public ] || cp -a /src/${APP}/public "/out/$dir/"; }
|
|
16
35
|
|
|
17
|
-
# Serveur autonome (output: 'standalone') : server.js et le strict nécessaire de node_modules
|
|
18
36
|
FROM node:22-alpine
|
|
19
37
|
WORKDIR /app
|
|
20
38
|
ENV NODE_ENV=production \
|
|
21
39
|
NEXT_TELEMETRY_DISABLED=1 \
|
|
22
40
|
HOSTNAME=0.0.0.0 \
|
|
23
41
|
PORT=3000
|
|
24
|
-
COPY --from=build --chown=node:node /
|
|
25
|
-
COPY --from=build --chown=node:node /app/.next/static ./.next/static
|
|
26
|
-
COPY --from=build --chown=node:node /app/public ./public
|
|
42
|
+
COPY --from=build --chown=node:node /out ./
|
|
27
43
|
USER node
|
|
28
44
|
EXPOSE 3000
|
|
29
|
-
CMD ["
|
|
45
|
+
CMD ["sh", "-c", "exec node \"$(cat /app/.app-dir)/server.js\""]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Contexte de l'image : le front seul (docker build .) ou la racine d'un projet
|
|
2
|
+
# à plusieurs fronts (docker build -f apps/<nom>/Dockerfile --build-arg APP=apps/<nom> .).
|
|
3
|
+
# Docker lit ce fichier, placé à côté du Dockerfile, dans les deux cas.
|
|
4
|
+
**/node_modules
|
|
5
|
+
**/.next
|
|
6
|
+
**/.angular
|
|
7
|
+
**/dist
|
|
8
|
+
**/out
|
|
9
|
+
**/.git
|
|
10
|
+
**/public/env.json
|
|
11
|
+
**/.env
|
|
12
|
+
**/.env.*
|
|
13
|
+
!**/.env.example
|
|
14
|
+
poad/data
|
|
15
|
+
poad/backups
|
|
16
|
+
poad/secrets.toml
|
|
17
|
+
**/*.log
|
|
18
|
+
**/.DS_Store
|
package/README.md
CHANGED
|
@@ -8,11 +8,13 @@ starter Angular (`@poadio/starter-angular`), page pour page.
|
|
|
8
8
|
## Démarrer
|
|
9
9
|
|
|
10
10
|
```sh
|
|
11
|
-
poad create mon-
|
|
12
|
-
cd mon-
|
|
11
|
+
poad create mon-projet --template next # poad/ (backend) et apps/web (ce front), dépendances, premier commit
|
|
12
|
+
cd mon-projet && bun start # projet poad, puis next dev
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
Dans un projet poad existant : `poad create web --template next` ajoute
|
|
16
|
+
`apps/web`. L'ancienne disposition (un seul front, `poad/` dedans) :
|
|
17
|
+
`poad create mon-app --template next --flat`.
|
|
16
18
|
|
|
17
19
|
Projet repris de git sur un autre poste : `git clone`, puis `bun start`, rien
|
|
18
20
|
d'autre. `bun start` installe les dépendances si elles manquent et lance le
|
|
@@ -30,8 +32,13 @@ l'environnement du processus (voir `.env.example`). Sans `POAD_URL` ni
|
|
|
30
32
|
|
|
31
33
|
Le serveur Next.js lit ces variables **à chaque requête** (`src/core/env.server.ts`,
|
|
32
34
|
appelé par `src/app/layout.tsx`) et ne passe au navigateur que `PUBLIC_*`,
|
|
33
|
-
`NEXT_PUBLIC_*` et `POAD_URL`, `POAD_ANON_KEY`, `POAD_MAIL_URL`. Rien
|
|
34
|
-
compilé dans le code : pas besoin de reconstruire pour changer de projet poad.
|
|
35
|
+
`NEXT_PUBLIC_*` et `POAD_URL`, `POAD_ANON_KEY`, `POAD_MAIL_URL`, `POAD_APP`. Rien
|
|
36
|
+
n'est compilé dans le code : pas besoin de reconstruire pour changer de projet poad.
|
|
37
|
+
|
|
38
|
+
Il y ajoute les variables publiques du projet poad (console, Variables) pour
|
|
39
|
+
cette application : `GET <POAD_URL>/env/v1?app=<POAD_APP>`, relu au plus toutes
|
|
40
|
+
les 2 secondes, ignoré si le backend ne répond pas. Une valeur de
|
|
41
|
+
l'environnement (`.env*`, `-e` du conteneur) l'emporte sur celle du projet.
|
|
35
42
|
|
|
36
43
|
```tsx
|
|
37
44
|
'use client';
|
|
@@ -41,16 +48,65 @@ const api = useEnv('PUBLIC_API_URL'); // dans un composant ; env('PUBLIC_API_U
|
|
|
41
48
|
|
|
42
49
|
`bun run env` affiche les noms des variables que verra le navigateur.
|
|
43
50
|
|
|
51
|
+
## Plusieurs fronts sur un même backend
|
|
52
|
+
|
|
53
|
+
Un projet poad peut avoir plusieurs fronts, chacun dans son dossier :
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
mon-projet/
|
|
57
|
+
poad/ backend (config, migrations, fonctions, flows)
|
|
58
|
+
apps/web/ Next.js (poad create web --template next)
|
|
59
|
+
apps/admin/ Angular (poad create admin --template angular)
|
|
60
|
+
package.json espace de travail bun (workspaces: ["apps/*"])
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
- `bun start` à la racine démarre poad une fois, puis tous les fronts en
|
|
64
|
+
parallèle, chacun sur son port (`poad.port` de son `package.json`, choisi
|
|
65
|
+
par `poad create` pour ne pas croiser les autres), sortie préfixée
|
|
66
|
+
(`[web]`, `[admin]`) ; Ctrl+C les arrête tous. `bun run start:web` : celui-là seul.
|
|
67
|
+
- `bun start` dans `apps/web` marche aussi : `poad/config.toml` et
|
|
68
|
+
`node_modules` sont cherchés dans les dossiers parents.
|
|
69
|
+
- **Variables publiques par front.** Le nom d'application est `poad.app` du
|
|
70
|
+
`package.json` (sinon son `name`, ou `POAD_APP` dans l'environnement). Le
|
|
71
|
+
serveur lit `/env/v1?app=<nom>` : les valeurs communes du projet, puis
|
|
72
|
+
celles de cette application par-dessus. `PUBLIC_TITLE` peut ainsi valoir
|
|
73
|
+
« Boutique » pour `web` et « Back-office » pour `admin`, sur le même backend
|
|
74
|
+
(console > Variables, colonne Application). Côté navigateur, `poad.env`
|
|
75
|
+
(`createClient(..., { app })`) suit les mêmes valeurs en direct.
|
|
76
|
+
- En production, chaque front a son image (voir « Image Docker » :
|
|
77
|
+
`docker build -f apps/web/Dockerfile --build-arg APP=apps/web .` depuis la
|
|
78
|
+
racine) ; le nom d'application est celui du `package.json` au moment du
|
|
79
|
+
build, ou `-e POAD_APP=web`.
|
|
80
|
+
|
|
44
81
|
## Image Docker
|
|
45
82
|
|
|
46
83
|
Compilée une fois, configurée au démarrage : serveur autonome de Next.js
|
|
47
84
|
(`output: 'standalone'`), qui lit les variables du conteneur à chaque requête.
|
|
48
85
|
|
|
86
|
+
Front seul (`poad create … --flat`, son `bun.lock` à côté), depuis son dossier :
|
|
87
|
+
|
|
49
88
|
```sh
|
|
50
89
|
docker build -t mon-app .
|
|
51
|
-
docker run -p 8080:3000 -e POAD_URL=https://mon-projet.example.com -e POAD_ANON_KEY=eyJ... -e PUBLIC_APP_ENV=prod mon-app
|
|
52
90
|
```
|
|
53
91
|
|
|
92
|
+
Front d'un projet à plusieurs fronts (`apps/web`, `bun.lock` à la racine),
|
|
93
|
+
depuis la racine du projet : le contexte est la racine, `APP` le dossier du front.
|
|
94
|
+
|
|
95
|
+
```sh
|
|
96
|
+
docker build -f apps/web/Dockerfile --build-arg APP=apps/web -t web .
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Puis, dans les deux cas :
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
docker run -p 8080:3000 -e POAD_URL=https://mon-projet.example.com -e POAD_ANON_KEY=eyJ... -e PUBLIC_APP_ENV=prod web
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Le nom d'application (variables publiques du projet, `/env/v1?app=`) est
|
|
106
|
+
`poad.app` du `package.json` au build ; `-e POAD_APP=…` le remplace.
|
|
107
|
+
`Dockerfile.dockerignore` (lu par Docker à côté du Dockerfile) écarte
|
|
108
|
+
`node_modules`, `.next`, les `.env*` et les secrets de `poad/` dans les deux cas.
|
|
109
|
+
|
|
54
110
|
## Routes
|
|
55
111
|
|
|
56
112
|
Celles de Next.js : un dossier de `src/app`, un `page.tsx`.
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@poadio/starter-next",
|
|
3
3
|
"title": "Mon application",
|
|
4
4
|
"description": "Application Next.js branchée sur poad : connexion, compte, cadre d’application (poad create --template next)",
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "0.2.0",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
"gitignore",
|
|
26
26
|
"Dockerfile",
|
|
27
27
|
".dockerignore",
|
|
28
|
+
"Dockerfile.dockerignore",
|
|
28
29
|
".env.example",
|
|
29
30
|
"next.config.ts",
|
|
30
31
|
"tsconfig.json",
|
|
@@ -49,6 +50,7 @@
|
|
|
49
50
|
"port": 3300,
|
|
50
51
|
"template": {
|
|
51
52
|
"framework": "next",
|
|
53
|
+
"appEnv": true,
|
|
52
54
|
"label": "Next.js + @poadio/ui-react",
|
|
53
55
|
"description": "Application Next.js branchée sur poad",
|
|
54
56
|
"port": 3300,
|
package/scripts/dev.mjs
CHANGED
|
@@ -6,32 +6,46 @@
|
|
|
6
6
|
// base, applique les migrations et le seed, remplace les ports déjà pris
|
|
7
7
|
// et lance les services du projet (Keycloak, Valkey…) ;
|
|
8
8
|
// 3. POAD_URL et POAD_ANON_KEY lus dans le projet poad, sauf s'ils sont déjà
|
|
9
|
-
// donnés (.env*, environnement),
|
|
9
|
+
// donnés (.env*, environnement), POAD_APP (nom d'application : poad.app
|
|
10
|
+
// du package.json), puis next dev sur un port libre.
|
|
11
|
+
// Le projet poad et les dépendances peuvent être dans un dossier parent
|
|
12
|
+
// (apps/<nom> d'un projet à plusieurs fronts).
|
|
10
13
|
// Les arguments sont passés à next dev : bun start --port 3300 (port fixe)
|
|
11
14
|
import { spawn, spawnSync } from 'node:child_process';
|
|
12
15
|
import { existsSync, readFileSync } from 'node:fs';
|
|
13
|
-
import { createServer } from 'node:net';
|
|
14
|
-
import { join } from 'node:path';
|
|
16
|
+
import { connect, createServer } from 'node:net';
|
|
17
|
+
import { dirname, join } from 'node:path';
|
|
15
18
|
|
|
16
19
|
const windows = process.platform === 'win32';
|
|
17
20
|
const { root, findPoadProject, poadDefaults } = await import('./env.mjs');
|
|
18
|
-
|
|
21
|
+
// node_modules du front, ou d'un dossier parent : dans un projet à plusieurs
|
|
22
|
+
// fronts (apps/<nom>, bun workspaces), les dépendances sont à la racine
|
|
23
|
+
const findBin = (name) => {
|
|
24
|
+
for (let dir = root; ; dir = dirname(dir)) {
|
|
25
|
+
const bin = join(dir, 'node_modules', '.bin', windows ? `${name}.cmd` : name);
|
|
26
|
+
if (existsSync(bin)) return bin;
|
|
27
|
+
if (dirname(dir) === dir) return null;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
let nextBin = findBin('next');
|
|
19
31
|
|
|
20
32
|
// 1. Dépendances : bun s'il est là, sinon npm
|
|
21
|
-
if (!
|
|
33
|
+
if (!nextBin) {
|
|
22
34
|
console.log('Dependencies are missing: installing them.');
|
|
23
35
|
const tried = ['bun', 'npm'].some((cmd) => {
|
|
24
36
|
const r = spawnSync(cmd, ['install'], { cwd: root, stdio: 'inherit', shell: windows });
|
|
25
37
|
return !r.error && r.status === 0;
|
|
26
38
|
});
|
|
27
|
-
|
|
39
|
+
nextBin = findBin('next');
|
|
40
|
+
if (!tried || !nextBin) {
|
|
28
41
|
console.error('Dependencies could not be installed: run "bun install" (or "npm install"), then "bun start" again.');
|
|
29
42
|
process.exit(1);
|
|
30
43
|
}
|
|
31
44
|
}
|
|
32
45
|
|
|
33
|
-
// 2. Projet poad local : démarré s'il ne tourne pas (sans effet sinon)
|
|
34
|
-
|
|
46
|
+
// 2. Projet poad local : démarré s'il ne tourne pas (sans effet sinon) ;
|
|
47
|
+
// POAD_SKIP_START : déjà fait par le bun start de la racine du projet
|
|
48
|
+
const project = process.env.POAD_URL || process.env.POAD_SKIP_START ? null : findPoadProject(root);
|
|
35
49
|
if (project) {
|
|
36
50
|
const r = spawnSync('poad', ['start', '--quiet'], { cwd: project, stdio: 'inherit', shell: windows });
|
|
37
51
|
if (r.error && r.error.code === 'ENOENT') console.warn('The poad CLI is not installed: the local backend was not started (npm install -g poad, then "poad start").');
|
|
@@ -44,11 +58,21 @@ const given = Object.keys(added);
|
|
|
44
58
|
console.log(`[env] ${given.length ? `from the poad project: ${given.join(', ')}` : 'POAD_* from .env* or the environment'}`);
|
|
45
59
|
|
|
46
60
|
/** Premier port libre à partir de start */
|
|
47
|
-
|
|
61
|
+
// Rien n'y répond (IPv4 ni IPv6 : un serveur sur [::1] seul n'empêche pas
|
|
62
|
+
// d'écouter sur 127.0.0.1, mais localhost peut y mener) et on peut y écouter
|
|
63
|
+
const answers = (port, host) =>
|
|
64
|
+
new Promise((ok) => {
|
|
65
|
+
const c = connect({ port, host });
|
|
66
|
+
c.setTimeout(500, () => c.destroy() && ok(false));
|
|
67
|
+
c.once('connect', () => c.destroy() && ok(true));
|
|
68
|
+
c.once('error', () => ok(false));
|
|
69
|
+
});
|
|
70
|
+
const bindable = (port) =>
|
|
48
71
|
new Promise((ok) => {
|
|
49
72
|
const s = createServer().once('error', () => ok(false)).once('listening', () => s.close(() => ok(true)));
|
|
50
73
|
s.listen(port, '127.0.0.1');
|
|
51
74
|
});
|
|
75
|
+
const free = async (port) => !(await answers(port, '127.0.0.1')) && !(await answers(port, '::1')) && (await bindable(port));
|
|
52
76
|
async function freePort(start) {
|
|
53
77
|
for (let port = start; port < start + 100; port++) if (await free(port)) return port;
|
|
54
78
|
return start;
|
package/scripts/env.mjs
CHANGED
|
@@ -10,7 +10,9 @@
|
|
|
10
10
|
//
|
|
11
11
|
// Les valeurs ne sont JAMAIS compilées dans le code : le serveur Next.js les
|
|
12
12
|
// lit à chaque requête (src/core/env.server.ts) et n'envoie au navigateur que
|
|
13
|
-
// les variables PUBLIC_*, NEXT_PUBLIC_* et POAD_URL, POAD_ANON_KEY, POAD_MAIL_URL
|
|
13
|
+
// les variables PUBLIC_*, NEXT_PUBLIC_* et POAD_URL, POAD_ANON_KEY, POAD_MAIL_URL,
|
|
14
|
+
// POAD_APP ; il y ajoute les variables publiques du projet poad pour cette
|
|
15
|
+
// application (/env/v1?app=<POAD_APP>), que les valeurs locales remplacent.
|
|
14
16
|
//
|
|
15
17
|
// node scripts/env.mjs [mode] affiche les variables que verra le navigateur (noms seulement)
|
|
16
18
|
import { existsSync, readFileSync } from 'node:fs';
|
|
@@ -19,7 +21,33 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
19
21
|
|
|
20
22
|
export const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
21
23
|
|
|
22
|
-
|
|
24
|
+
// POAD_APP : nom d'application du front (variables publiques par application,
|
|
25
|
+
// /env/v1?app=<nom>) ; un nom, rien de secret
|
|
26
|
+
const POAD_KEYS = ['POAD_URL', 'POAD_ANON_KEY', 'POAD_MAIL_URL', 'POAD_APP'];
|
|
27
|
+
const APP_RE = /^[a-z][a-z0-9-]{0,62}$/;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Nom d'application du front : POAD_APP, sinon poad.app du package.json, sinon
|
|
31
|
+
* le nom du paquet (sans scope) ; '' si aucun n'est un nom valide (valeurs
|
|
32
|
+
* communes seulement). Même règle que l'engine : a-z, 0-9, « - ».
|
|
33
|
+
*/
|
|
34
|
+
export function appName(dir = root, env = process.env) {
|
|
35
|
+
if (APP_RE.test(env.POAD_APP ?? '')) return env.POAD_APP;
|
|
36
|
+
let pkg = {};
|
|
37
|
+
try {
|
|
38
|
+
pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
|
|
39
|
+
} catch {
|
|
40
|
+
return '';
|
|
41
|
+
}
|
|
42
|
+
if (APP_RE.test(pkg.poad?.app ?? '')) return pkg.poad.app;
|
|
43
|
+
const name = String(pkg.name ?? '')
|
|
44
|
+
.replace(/^@[^/]+\//, '')
|
|
45
|
+
.toLowerCase()
|
|
46
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
47
|
+
.replace(/^[^a-z]+|-+$/g, '')
|
|
48
|
+
.slice(0, 63);
|
|
49
|
+
return APP_RE.test(name) ? name : '';
|
|
50
|
+
}
|
|
23
51
|
|
|
24
52
|
/** Même règle que src/core/env.server.ts */
|
|
25
53
|
export const isPublic = (key) => key.startsWith('PUBLIC_') || key.startsWith('NEXT_PUBLIC_') || POAD_KEYS.includes(key);
|
|
@@ -103,7 +131,8 @@ export function fromDotenvFiles(mode = 'development', dir = root) {
|
|
|
103
131
|
export function poadDefaults(mode = 'development', env = process.env, dir = root) {
|
|
104
132
|
const given = { ...fromDotenvFiles(mode, dir), ...env };
|
|
105
133
|
const out = {};
|
|
106
|
-
|
|
134
|
+
const app = appName(dir, {});
|
|
135
|
+
for (const [k, v] of Object.entries({ ...fromPoadProject(dir), ...(app ? { POAD_APP: app } : {}) })) {
|
|
107
136
|
if (given[k] === undefined || given[k] === '') out[k] = v;
|
|
108
137
|
}
|
|
109
138
|
return out;
|
|
@@ -111,7 +140,8 @@ export function poadDefaults(mode = 'development', env = process.env, dir = root
|
|
|
111
140
|
|
|
112
141
|
/** Variables qu'aura le navigateur (même règle que le serveur) */
|
|
113
142
|
export function publicEnv(mode = 'development', env = process.env, dir = root) {
|
|
114
|
-
const
|
|
143
|
+
const app = appName(dir, {});
|
|
144
|
+
const vars = { ...fromPoadProject(dir), ...(app ? { POAD_APP: app } : {}), ...fromDotenvFiles(mode, dir), ...env };
|
|
115
145
|
return Object.fromEntries(
|
|
116
146
|
Object.entries(vars)
|
|
117
147
|
.filter(([k, v]) => isPublic(k) && v !== undefined && v !== '')
|
package/scripts/env.test.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import assert from 'node:assert/strict';
|
|
|
4
4
|
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
5
|
import { tmpdir } from 'node:os';
|
|
6
6
|
import { join } from 'node:path';
|
|
7
|
-
import { fromPoadProject, isPublic, parseDotenv, poadDefaults, publicEnv, root } from './env.mjs';
|
|
7
|
+
import { appName, fromPoadProject, isPublic, parseDotenv, poadDefaults, publicEnv, root } from './env.mjs';
|
|
8
8
|
|
|
9
9
|
/** Projet poad factice : poad/config.toml, poad/secrets.toml (valeurs de test, pas de vrai secret) */
|
|
10
10
|
function fakeProject() {
|
|
@@ -51,6 +51,26 @@ test('poadDefaults : .env* et l’environnement l’emportent sur le projet poad
|
|
|
51
51
|
}
|
|
52
52
|
});
|
|
53
53
|
|
|
54
|
+
test('appName : POAD_APP, sinon poad.app, sinon le nom du paquet ; passé à next dev', () => {
|
|
55
|
+
const { dir, app } = fakeProject();
|
|
56
|
+
try {
|
|
57
|
+
assert.equal(appName(app, {}), '');
|
|
58
|
+
writeFileSync(join(app, 'package.json'), JSON.stringify({ name: '@acme/Site_Web' }));
|
|
59
|
+
assert.equal(appName(app, {}), 'site-web');
|
|
60
|
+
writeFileSync(join(app, 'package.json'), JSON.stringify({ name: 'web', poad: { app: 'admin' } }));
|
|
61
|
+
assert.equal(appName(app, {}), 'admin');
|
|
62
|
+
assert.equal(appName(app, { POAD_APP: 'shop' }), 'shop');
|
|
63
|
+
assert.equal(appName(app, { POAD_APP: 'Not Valid' }), 'admin');
|
|
64
|
+
// Projet à plusieurs fronts : POAD_APP ajouté pour next dev, sauf s'il est donné
|
|
65
|
+
assert.equal(poadDefaults('development', {}, app).POAD_APP, 'admin');
|
|
66
|
+
assert.equal(poadDefaults('development', { POAD_APP: 'shop' }, app).POAD_APP, undefined);
|
|
67
|
+
assert.equal(publicEnv('development', {}, app).POAD_APP, 'admin');
|
|
68
|
+
assert.ok(isPublic('POAD_APP'));
|
|
69
|
+
} finally {
|
|
70
|
+
rmSync(dir, { recursive: true, force: true });
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
|
|
54
74
|
test('package.json : contrat du modèle attendu par poad create', () => {
|
|
55
75
|
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
56
76
|
assert.equal(pkg.name, '@poadio/starter-next');
|
|
@@ -58,11 +78,13 @@ test('package.json : contrat du modèle attendu par poad create', () => {
|
|
|
58
78
|
assert.match(pkg.packageManager, /^bun@/);
|
|
59
79
|
const tpl = pkg.poad?.template;
|
|
60
80
|
assert.equal(tpl.framework, 'next');
|
|
81
|
+
// Lit les variables publiques de son application (/env/v1?app=) : poad create le sait
|
|
82
|
+
assert.equal(tpl.appEnv, true);
|
|
61
83
|
assert.ok(tpl.label && tpl.description && tpl.port);
|
|
62
84
|
assert.ok(Array.isArray(tpl.gitignore) && tpl.gitignore.includes('/.next/'));
|
|
63
85
|
// Port gardé après poad create (qui retire poad.template)
|
|
64
86
|
assert.equal(pkg.poad.port, tpl.port);
|
|
65
|
-
for (const f of ['src', 'public', '!public/env.json', 'scripts', 'gitignore']) assert.ok(pkg.files.includes(f), f);
|
|
87
|
+
for (const f of ['src', 'public', '!public/env.json', 'scripts', 'gitignore', 'Dockerfile', 'Dockerfile.dockerignore']) assert.ok(pkg.files.includes(f), f);
|
|
66
88
|
for (const f of ['node_modules', '.next', '.env.local', 'poad']) assert.ok(!pkg.files.includes(f), f);
|
|
67
89
|
});
|
|
68
90
|
|
package/src/app/layout.tsx
CHANGED
|
@@ -38,7 +38,8 @@ export const metadata: Metadata = {
|
|
|
38
38
|
/**
|
|
39
39
|
* Racine, rendue par le serveur À CHAQUE REQUÊTE (la langue lit les cookies) :
|
|
40
40
|
* les variables publiques (POAD_URL, POAD_ANON_KEY, PUBLIC_*) sont lues dans
|
|
41
|
-
* l'environnement du serveur
|
|
41
|
+
* l'environnement du serveur et dans le projet poad (variables de cette
|
|
42
|
+
* application) à ce moment-là, jamais compilées dans le code.
|
|
42
43
|
* L'image Docker est donc construite une fois et configurée au démarrage.
|
|
43
44
|
*/
|
|
44
45
|
export default async function RootLayout({ children }: { children: ReactNode }) {
|
|
@@ -49,7 +50,7 @@ export default async function RootLayout({ children }: { children: ReactNode })
|
|
|
49
50
|
<script dangerouslySetInnerHTML={{ __html: THEME_SCRIPT }} />
|
|
50
51
|
</head>
|
|
51
52
|
<body>
|
|
52
|
-
<Providers env={publicEnv()} locale={locale}>
|
|
53
|
+
<Providers env={await publicEnv()} locale={locale}>
|
|
53
54
|
{children}
|
|
54
55
|
</Providers>
|
|
55
56
|
</body>
|
package/src/core/auth.tsx
CHANGED
|
@@ -61,10 +61,11 @@ const AuthContext = createContext<AuthState | null>(null);
|
|
|
61
61
|
/** Un seul client par page, même si React monte deux fois le fournisseur (mode strict) */
|
|
62
62
|
let shared: { key: string; client: PoadClient } | null = null;
|
|
63
63
|
function clientFor(config: PoadConfig, locale: string): PoadClient {
|
|
64
|
-
const key = `${config.url}|${config.anonKey}`;
|
|
64
|
+
const key = `${config.url}|${config.anonKey}|${config.app}`;
|
|
65
65
|
if (!shared || shared.key !== key) {
|
|
66
66
|
shared?.client.auth.dispose();
|
|
67
|
-
|
|
67
|
+
// app : poad.env (variables publiques, en direct) lit celles de ce front
|
|
68
|
+
shared = { key, client: createClient(config.url, config.anonKey, { app: config.app, auth: { locale } }) };
|
|
68
69
|
}
|
|
69
70
|
return shared.client;
|
|
70
71
|
}
|
package/src/core/env.server.ts
CHANGED
|
@@ -1,27 +1,83 @@
|
|
|
1
|
+
import pkg from '../../package.json';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
|
-
* Variables publiques du front, lues
|
|
3
|
-
*
|
|
4
|
-
* déploie partout, seules les variables du conteneur changent.
|
|
4
|
+
* Variables publiques du front, lues À CHAQUE REQUÊTE (jamais compilées dans
|
|
5
|
+
* le code) : la même image Docker se déploie partout.
|
|
5
6
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
7
|
+
* Deux sources, la seconde l'emporte :
|
|
8
|
+
* 1. les variables publiques du projet poad pour cette application
|
|
9
|
+
* (GET <POAD_URL>/env/v1?app=<POAD_APP>, Projet > Variables) : elles
|
|
10
|
+
* changent sans redéployer, et chaque front d'un même backend a les siennes ;
|
|
11
|
+
* 2. l'environnement du serveur Next.js : en local, `bun start` les prend dans
|
|
12
|
+
* .env* ou, à défaut, dans le projet poad (poad/config.toml,
|
|
13
|
+
* poad/secrets.toml) ; dans l'image Docker, `docker run -e POAD_URL=… -e POAD_ANON_KEY=…`.
|
|
9
14
|
*
|
|
10
15
|
* Seules passent au navigateur PUBLIC_*, NEXT_PUBLIC_* et POAD_URL,
|
|
11
|
-
* POAD_ANON_KEY, POAD_MAIL_URL : le reste ne quitte pas le serveur.
|
|
16
|
+
* POAD_ANON_KEY, POAD_MAIL_URL, POAD_APP : le reste ne quitte pas le serveur.
|
|
12
17
|
*/
|
|
13
|
-
const POAD_KEYS = ['POAD_URL', 'POAD_ANON_KEY', 'POAD_MAIL_URL'];
|
|
18
|
+
const POAD_KEYS = ['POAD_URL', 'POAD_ANON_KEY', 'POAD_MAIL_URL', 'POAD_APP'];
|
|
19
|
+
const APP_RE = /^[a-z][a-z0-9-]{0,62}$/;
|
|
14
20
|
|
|
15
21
|
export const isPublic = (key: string): boolean =>
|
|
16
22
|
key.startsWith('PUBLIC_') || key.startsWith('NEXT_PUBLIC_') || POAD_KEYS.includes(key);
|
|
17
23
|
|
|
18
|
-
|
|
24
|
+
type Manifest = { name?: string; poad?: { app?: string } };
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Nom d'application du front : POAD_APP, sinon poad.app du package.json
|
|
28
|
+
* (écrit par poad create), sinon le nom du paquet ; '' : valeurs communes.
|
|
29
|
+
*/
|
|
30
|
+
export function appName(env: Record<string, string | undefined> = process.env, manifest: Manifest = pkg as Manifest): string {
|
|
31
|
+
if (APP_RE.test(env.POAD_APP ?? '')) return env.POAD_APP as string;
|
|
32
|
+
if (APP_RE.test(manifest.poad?.app ?? '')) return manifest.poad?.app as string;
|
|
33
|
+
const name = String(manifest.name ?? '')
|
|
34
|
+
.replace(/^@[^/]+\//, '')
|
|
35
|
+
.toLowerCase()
|
|
36
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
37
|
+
.replace(/^[^a-z]+|-+$/g, '')
|
|
38
|
+
.slice(0, 63);
|
|
39
|
+
return APP_RE.test(name) ? name : '';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Une lecture du backend par intervalle de 2 s au plus, par (URL, application)
|
|
43
|
+
const TTL = 2000;
|
|
44
|
+
const cache = new Map<string, { at: number; values: Record<string, string> }>();
|
|
45
|
+
|
|
46
|
+
/** Variables publiques du projet poad pour l'application ; {} si le backend ne répond pas */
|
|
47
|
+
export async function projectEnv(url: string, anonKey: string, app: string): Promise<Record<string, string>> {
|
|
48
|
+
const key = `${url}|${app}`;
|
|
49
|
+
const hit = cache.get(key);
|
|
50
|
+
if (hit && Date.now() - hit.at < TTL) return hit.values;
|
|
51
|
+
let values: Record<string, string> = {};
|
|
52
|
+
try {
|
|
53
|
+
const res = await fetch(`${url.replace(/\/+$/, '')}/env/v1${app ? `?app=${encodeURIComponent(app)}` : ''}`, {
|
|
54
|
+
headers: { apikey: anonKey, Authorization: `Bearer ${anonKey}` },
|
|
55
|
+
cache: 'no-store',
|
|
56
|
+
signal: AbortSignal.timeout(1500),
|
|
57
|
+
});
|
|
58
|
+
if (res.ok) {
|
|
59
|
+
const body = (await res.json()) as { variables?: Record<string, unknown> };
|
|
60
|
+
for (const [k, v] of Object.entries(body.variables ?? {})) if (k.startsWith('PUBLIC_') && typeof v === 'string') values[k] = v;
|
|
61
|
+
}
|
|
62
|
+
} catch {
|
|
63
|
+
// Backend arrêté ou injoignable : les valeurs locales seules
|
|
64
|
+
values = hit?.values ?? {};
|
|
65
|
+
}
|
|
66
|
+
cache.set(key, { at: Date.now(), values });
|
|
67
|
+
return values;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function publicEnv(): Promise<Record<string, string>> {
|
|
19
71
|
// Parcours dynamique de process.env : Next.js ne remplace rien à la compilation
|
|
20
72
|
const env = process.env as Record<string, string | undefined>;
|
|
21
|
-
|
|
73
|
+
const local = Object.fromEntries(
|
|
22
74
|
Object.keys(env)
|
|
23
75
|
.filter((k) => isPublic(k) && env[k])
|
|
24
|
-
.sort()
|
|
25
76
|
.map((k) => [k, env[k] as string]),
|
|
26
77
|
);
|
|
78
|
+
const app = appName(env);
|
|
79
|
+
if (app) local.POAD_APP = app;
|
|
80
|
+
const remote = local.POAD_URL && local.POAD_ANON_KEY ? await projectEnv(local.POAD_URL, local.POAD_ANON_KEY, app) : {};
|
|
81
|
+
const all = { ...remote, ...local };
|
|
82
|
+
return Object.fromEntries(Object.keys(all).sort().map((k) => [k, all[k]]));
|
|
27
83
|
}
|
package/src/core/env.tsx
CHANGED
|
@@ -37,10 +37,12 @@ export interface PoadConfig {
|
|
|
37
37
|
anonKey: string;
|
|
38
38
|
/** Interface web des e-mails du projet local, Mailpit (POAD_MAIL_URL) */
|
|
39
39
|
mail: string | null;
|
|
40
|
+
/** Nom d'application du front : ses variables publiques à lui (POAD_APP, poad.app du package.json) */
|
|
41
|
+
app: string;
|
|
40
42
|
}
|
|
41
43
|
|
|
42
44
|
export function configFrom(v: Record<string, string>): PoadConfig | null {
|
|
43
45
|
const url = v['POAD_URL'];
|
|
44
46
|
const anonKey = v['POAD_ANON_KEY'];
|
|
45
|
-
return url && anonKey ? { url, anonKey, mail: v['POAD_MAIL_URL'] ?? null } : null;
|
|
47
|
+
return url && anonKey ? { url, anonKey, mail: v['POAD_MAIL_URL'] ?? null, app: v['POAD_APP'] ?? '' } : null;
|
|
46
48
|
}
|