@epekta/armarius-astro 0.0.0-stage → 0.1.1
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 +275 -2
- package/bin/armarius-astro.js +4 -0
- package/components/EditionBoot.astro +62 -0
- package/components/Image.astro +20 -0
- package/components/Text.astro +23 -0
- package/dist/api.d.ts +18 -0
- package/dist/api.js +43 -0
- package/dist/check.d.ts +25 -0
- package/dist/check.js +87 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +13 -0
- package/dist/hash.d.ts +5 -0
- package/dist/hash.js +8 -0
- package/dist/images.d.ts +18 -0
- package/dist/images.js +35 -0
- package/dist/import/command.d.ts +7 -0
- package/dist/import/command.js +255 -0
- package/dist/import/format.d.ts +53 -0
- package/dist/import/format.js +94 -0
- package/dist/import/webservice.d.ts +47 -0
- package/dist/import/webservice.js +218 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +2 -0
- package/dist/integration.d.ts +7 -0
- package/dist/integration.js +75 -0
- package/dist/options.d.ts +39 -0
- package/dist/options.js +44 -0
- package/dist/readers.d.ts +69 -0
- package/dist/readers.js +106 -0
- package/dist/render.d.ts +17 -0
- package/dist/render.js +26 -0
- package/dist/routes.d.ts +36 -0
- package/dist/routes.js +71 -0
- package/dist/runtime.d.ts +46 -0
- package/dist/runtime.js +132 -0
- package/dist/state.d.ts +38 -0
- package/dist/state.js +35 -0
- package/dist/sync.d.ts +59 -0
- package/dist/sync.js +73 -0
- package/package.json +57 -5
package/README.md
CHANGED
|
@@ -1,3 +1,276 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @epekta/armarius-astro
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Le kit d'un site Astro statique reconstruit par Armarius : textes, images, pages, fiches, menus et
|
|
4
|
+
réglages lus dans l'API d'Armarius au build, corps de synchro écrits pour la CI du site, et amorce
|
|
5
|
+
de la couche d'édition sur place (`@epekta/armarius-edition`) dans l'aperçu de l'écran
|
|
6
|
+
`/admin/editing`.
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
Node 22.23.4 au moins (l'exigence d'Astro 7), Astro 7.4.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @epekta/armarius-astro
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Le kit installe `@epekta/armarius-edition`, dont il copie la couche dans la sortie du build.
|
|
17
|
+
|
|
18
|
+
Armarius doit servir l'empreinte du code de chaque texte (`code_hash`, `code_intact`) dans
|
|
19
|
+
`GET /api/nuxt/contents` : sans elle, le texte d'Armarius l'emporte toujours et `check` ne trouve
|
|
20
|
+
aucun conflit.
|
|
21
|
+
|
|
22
|
+
## Configuration
|
|
23
|
+
|
|
24
|
+
```js
|
|
25
|
+
// astro.config.mjs
|
|
26
|
+
import { defineConfig } from 'astro/config';
|
|
27
|
+
import { armarius } from '@epekta/armarius-astro';
|
|
28
|
+
|
|
29
|
+
export default defineConfig({
|
|
30
|
+
output: 'static',
|
|
31
|
+
integrations: [
|
|
32
|
+
armarius({
|
|
33
|
+
apiUrl: 'https://app.example.com',
|
|
34
|
+
locale: 'fr',
|
|
35
|
+
pages: [
|
|
36
|
+
{ route_name: 'accueil', slug: '/', title: 'Accueil', view: 'home' },
|
|
37
|
+
{ route_name: 'projets', slug: 'projets', title: 'Projets', view: 'projects', crud: 'projets' },
|
|
38
|
+
],
|
|
39
|
+
}),
|
|
40
|
+
],
|
|
41
|
+
});
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
| Option | Rôle |
|
|
45
|
+
| --- | --- |
|
|
46
|
+
| `apiUrl` | L'origine de l'API d'Armarius ; un chemin y est ignoré. |
|
|
47
|
+
| `locale` | La langue du build et de la synchro : un build par langue. |
|
|
48
|
+
| `pages` | Les pages du code : `route_name` (nom stable, aussi le gabarit), `slug` par défaut, `title`, `view` (valeur libre que lit la route du site), `crud` (une page par fiche sous celle-ci). 100 au plus. |
|
|
49
|
+
| `screenOrigin` | L'origine de l'écran d'administration, si ce n'est pas celle de l'API. |
|
|
50
|
+
| `timeoutMs`, `retries` | Délai d'une requête (10 000 ms) et reprises (2) ; l'API muette, le build échoue. |
|
|
51
|
+
|
|
52
|
+
Armarius crée chaque page à la première synchro, puis possède son slug, son titre et son SEO : un
|
|
53
|
+
slug renommé dans l'administration change l'adresse au build suivant.
|
|
54
|
+
|
|
55
|
+
## Routes
|
|
56
|
+
|
|
57
|
+
Une seule route, `src/pages/[...path].astro`, rend toutes les pages :
|
|
58
|
+
|
|
59
|
+
```astro
|
|
60
|
+
---
|
|
61
|
+
import { armariusPaths } from '@epekta/armarius-astro';
|
|
62
|
+
|
|
63
|
+
export const getStaticPaths = armariusPaths;
|
|
64
|
+
const { routeName, view, record } = Astro.props;
|
|
65
|
+
---
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`armariusPaths` rend les chemins de la table d'Armarius, ceux des pages du code qu'il ne connaît pas
|
|
69
|
+
encore et, sous une page qui a un `crud`, un chemin par fiche (`<page>/<permalink>`). `record` vaut la
|
|
70
|
+
fiche sur sa page, `null` ailleurs. Deux pages sur un même chemin font échouer le build.
|
|
71
|
+
|
|
72
|
+
## Composants
|
|
73
|
+
|
|
74
|
+
```astro
|
|
75
|
+
---
|
|
76
|
+
import EditionBoot from '@epekta/armarius-astro/components/EditionBoot.astro';
|
|
77
|
+
import Image from '@epekta/armarius-astro/components/Image.astro';
|
|
78
|
+
import Text from '@epekta/armarius-astro/components/Text.astro';
|
|
79
|
+
---
|
|
80
|
+
<head><EditionBoot /></head>
|
|
81
|
+
|
|
82
|
+
<Text id="home-title" as="h1">Un atelier d'<em>architecture</em></Text>
|
|
83
|
+
<Text id="home-cta" routeName="contact">Parlons de votre projet</Text>
|
|
84
|
+
<Text id="contact-mail" href="mailto:atelier@example.com">atelier@example.com</Text>
|
|
85
|
+
<Image id="home-photo" src="/images/atelier.webp" alt="L'atelier" glide={{ fm: 'webp', q: 80, w: 1600 }} />
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
- `Text` : le contenu du composant est la valeur du code. Armarius la rend tant que l'administration
|
|
89
|
+
ne l'a pas modifiée ; une valeur du code changée remplace un texte que personne n'a touché
|
|
90
|
+
(option `NUXT_SYNC_REPLACE_UNTOUCHED_CONTENT` d'Armarius).
|
|
91
|
+
`as` : `span` par défaut, une balise de texte (`p`, `h1` à `h6`, `li`, `div`…). `href` ou
|
|
92
|
+
`routeName` (une page du code) en font un lien, dont la destination se modifie dans l'administration.
|
|
93
|
+
`href` : un chemin, une ancre, une adresse `http(s):`, `mailto:` ou `tel:` ; un lien vide ou d'un
|
|
94
|
+
autre schéma fait échouer le build.
|
|
95
|
+
- `Image` : `src` est un fichier du site (`public/`), rendu jusqu'à la première synchro, où Armarius
|
|
96
|
+
télécharge l'image depuis le site en ligne (la synchro suit donc le déploiement) ; ensuite, la
|
|
97
|
+
variante Glide d'Armarius, dans une des six formes de requête que le serveur sert en fichier statique
|
|
98
|
+
(`q,w`, `fit,q,w`, `fm,q,w`, `q`, `fit,fm,q,w`, `fit,fm,h,q,w`) ; `q=80&w=1600` par défaut. Une autre
|
|
99
|
+
forme fait échouer le build. Un `src` changé ensuite dans le code ne remplace pas l'image d'Armarius :
|
|
100
|
+
la remplacer dans l'administration, ou changer d'`id`.
|
|
101
|
+
- `EditionBoot`, dans le `<head>` de chaque page : langue et page pour la couche, `preconnect` vers
|
|
102
|
+
l'API, et l'amorce. Hors d'une iframe ouverte par l'écran avec `?preview=true`, la couche ne se
|
|
103
|
+
charge pas ; dans l'aperçu, les pages suivantes la gardent (`sessionStorage`). Les choix d'un champ
|
|
104
|
+
marqué `data-edition-field="<crud>/<champ>"` sont lus au chargement, sans rebuild.
|
|
105
|
+
|
|
106
|
+
Un identifiant (`id`) est littéral et propre à son texte : jamais construit dans une boucle. Le même
|
|
107
|
+
identifiant avec deux valeurs fait échouer le build.
|
|
108
|
+
|
|
109
|
+
Les styles scopés d'Astro marquent les éléments du contenu d'un `Text` (`data-astro-cid-…`) ; le kit
|
|
110
|
+
retire ces marques de la valeur du code, synchronisée et hachée sans elles.
|
|
111
|
+
|
|
112
|
+
## Lecteurs
|
|
113
|
+
|
|
114
|
+
| Fonction | Rend |
|
|
115
|
+
| --- | --- |
|
|
116
|
+
| `getRecords(crud)` | Les fiches d'un CRUD dans la langue du build (500 au plus, `slym.api.list_limit`). |
|
|
117
|
+
| `getSetting(key)` | Un réglage, `undefined` s'il est inconnu. |
|
|
118
|
+
| `getMenu(slug)` | Un menu actif et ses entrées, `undefined` s'il est inconnu ; un lien d'entrée vers un schéma exécutable (`javascript:`…) vaut `null`. |
|
|
119
|
+
| `getPageSeo(routeName)` | Titre, description et image SEO de la page ; le titre du code avant sa synchro. |
|
|
120
|
+
|
|
121
|
+
Chaque ressource est lue une fois par build. Pour la couche, une fiche se marque
|
|
122
|
+
`data-armarius-record="<id>"`, une entrée de menu `data-armarius-menu-item="<id>"`, un réglage
|
|
123
|
+
`data-armarius-setting="<clé>"` (README d'`@epekta/armarius-edition`).
|
|
124
|
+
|
|
125
|
+
## Synchro
|
|
126
|
+
|
|
127
|
+
Le build écrit, dans le dossier du site :
|
|
128
|
+
|
|
129
|
+
- `.armarius/sync/pages.json`, `contents.json`, `page-contents.json` : les corps que la CI du site
|
|
130
|
+
poste, dans cet ordre, à `POST /api/nuxt/pages`, `/api/nuxt/contents` et `/api/nuxt/page-contents` ;
|
|
131
|
+
- `.armarius/manifest.json` : l'empreinte et la valeur de chaque texte du code, que lit `check`.
|
|
132
|
+
|
|
133
|
+
Le kit ne signe rien : le modèle de CI du site signe chaque envoi sous la forme horodatée,
|
|
134
|
+
`X-Signature: <ts>.<hex>`, un HMAC-SHA256 (clé `API_NUXT_SECRET` d'Armarius) qui lie l'horodatage, la
|
|
135
|
+
route, la query et le corps, accepté à 300 s au plus de l'horloge de l'API. L'ancienne forme, le
|
|
136
|
+
HMAC du corps brut seul, reste acceptée pour les sites Nuxt ; un site statique ne l'envoie pas. Le
|
|
137
|
+
message signé et ses cas : ADR 0026 (`docs/decisions/0026-signed-writes-are-timestamped.md` du dépôt
|
|
138
|
+
Armarius) et `packages/core/resources/fixtures/nuxt-sync/signature-cases.json`.
|
|
139
|
+
|
|
140
|
+
`.armarius/` se régénère à chaque build : l'ajouter au `.gitignore` du site. Le build copie aussi
|
|
141
|
+
la couche d'édition dans `dist/_armarius/layer.js`.
|
|
142
|
+
|
|
143
|
+
## `armarius-astro check`
|
|
144
|
+
|
|
145
|
+
```sh
|
|
146
|
+
npx armarius-astro check
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
En lecture seule, depuis le manifeste du dernier build : nomme les textes changés à la fois dans le
|
|
150
|
+
code et dans l'administration, dont la synchro garde la valeur de l'administration. Sous chacun, une
|
|
151
|
+
ligne par valeur, ramenée sur une ligne et coupée au milieu au-delà de 72 caractères : celle de
|
|
152
|
+
l'administration (`admin (kept)`), puis celle du code (`code (discarded)`). Un manifeste écrit par
|
|
153
|
+
la version 0.1.0 n'a que l'empreinte : la valeur du code y manque jusqu'au build suivant. Le build
|
|
154
|
+
imprime le même rapport. Rend toujours 0 ; ce qu'il ne peut pas lire (pas de manifeste, API injoignable,
|
|
155
|
+
`src/` plus récent que le build), il le dit.
|
|
156
|
+
|
|
157
|
+
## Import
|
|
158
|
+
|
|
159
|
+
```sh
|
|
160
|
+
export ARMARIUS_API_URL=https://app.example.com
|
|
161
|
+
npx armarius-astro import import/projets.json --dry-run
|
|
162
|
+
read -rs ARMARIUS_API_KEY && export ARMARIUS_API_KEY # saisie masquée, hors de l'historique du shell
|
|
163
|
+
npx armarius-astro import import/projets.json
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Crée dans un CRUD d'Armarius les fiches d'un fichier `armarius-import/v1`, par le webservice. Il ne
|
|
167
|
+
modifie ni ne supprime jamais une fiche : une fiche dont la clé existe déjà est sautée.
|
|
168
|
+
|
|
169
|
+
```json
|
|
170
|
+
{
|
|
171
|
+
"format": "armarius-import/v1",
|
|
172
|
+
"crud": "projets",
|
|
173
|
+
"key": "name",
|
|
174
|
+
"records": [
|
|
175
|
+
{
|
|
176
|
+
"name": "Villa Marage",
|
|
177
|
+
"place": { "crud": "lieux", "name": "Côte d'Azur" },
|
|
178
|
+
"mainPicture": { "file": "../img/marage-1.jpg" },
|
|
179
|
+
"pictures": [{ "file": "../img/marage-2.jpg" }, { "file": "../img/marage-3.jpg" }],
|
|
180
|
+
"inHome": false
|
|
181
|
+
}
|
|
182
|
+
]
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
| Valeur | Forme |
|
|
187
|
+
| --- | --- |
|
|
188
|
+
| Texte, nombre, booléen | Tel quel ; un champ traduisible accepte aussi `{ "fr": "…", "en": "…" }`. |
|
|
189
|
+
| Relation | `{ "crud": "<slug>", "name": "<valeur>" }` : la fiche du CRUD cible dont la colonne affichée par la relation vaut `name`. Une relation multiple, ou vers un modèle qui n'est pas un CRUD, est refusée. |
|
|
190
|
+
| Fichier | `{ "file": "<chemin relatif au fichier d'entrée>" }` ; une liste de ces objets pour un champ à fichiers multiples (`FILEPCKR` seulement). Extensions envoyées : `.jpg`, `.jpeg`, `.png`, `.webp`, `.gif`, `.svg`, `.pdf`, `.mp4`. |
|
|
191
|
+
|
|
192
|
+
`key` nomme le champ qui identifie une fiche : texte, nombre, e-mail, téléphone ou URL, ni privé
|
|
193
|
+
ni traduisible (la liste publique doit le rendre tel qu'il a été envoyé). Clés et noms de relation
|
|
194
|
+
se comparent sans casse, sans espaces en bord, espaces intérieurs réduits à un, en Unicode NFC.
|
|
195
|
+
|
|
196
|
+
| Variable | Rôle |
|
|
197
|
+
| --- | --- |
|
|
198
|
+
| `ARMARIUS_API_URL` | L'origine d'Armarius, en `https` hors d'une machine locale (`localhost`, `127.0.0.1`, `*.test`). Le webservice y est attendu sous `/webservice` : sans `WEBSERVICE_DOMAIN` côté Armarius. |
|
|
199
|
+
| `ARMARIUS_API_KEY` | La clé du webservice, inutile avec `--dry-run`. À passer par l'environnement, jamais par un fichier du dépôt ; elle n'apparaît dans aucune sortie. |
|
|
200
|
+
|
|
201
|
+
Avant toute écriture, la commande lit la description du CRUD
|
|
202
|
+
(`GET /webservice/resources/<crud>/details`), ses fiches et celles des CRUD cibles des relations
|
|
203
|
+
par la route publique (`GET /api/cruds/from-slug/<crud>/items`, droit « Voir les entrées » de
|
|
204
|
+
l'invité), et vérifie chaque fiche : champ inconnu, champ requis absent, clé vide ou en double,
|
|
205
|
+
relation introuvable ou ambiguë, fichier absent, chemin absolu ou extension non envoyée.
|
|
206
|
+
|
|
207
|
+
- `--dry-run` : lecture seule ; une ligne par fiche (`create`, `exists`, `error` et sa raison) ; code
|
|
208
|
+
1 s'il y a une erreur, 0 sinon.
|
|
209
|
+
- Sans `--dry-run` : sur une erreur de vérification, les mêmes lignes et rien n'est écrit (code 1).
|
|
210
|
+
Sinon, un jeton pour le passage (refusé, rien n'est créé), puis, par fiche à créer : envoi de ses
|
|
211
|
+
fichiers et création ; une ligne `created`, `skipped` (la clé existe) ou `failed` (envoi ou
|
|
212
|
+
création refusés : la fiche n'est pas créée, la suivante continue), puis le bilan. Code 1 s'il y a
|
|
213
|
+
un échec, 0 sinon.
|
|
214
|
+
- Un fichier unique se traite après la création, sur un worker de la file `default` d'Armarius :
|
|
215
|
+
la création le rend `pending`, attendu. Une fiche dont un fichier unique est refusé est créée
|
|
216
|
+
quand même (Armarius rend 201) : la ligne `failed` donne son numéro, à corriger dans
|
|
217
|
+
l'administration.
|
|
218
|
+
- Une requête refusée par 429 est reprise après son `Retry-After` ; une écriture n'est jamais reprise
|
|
219
|
+
sur une erreur 5xx ni sans réponse, ni redirigée. Une création restée sans réponse a pu se faire :
|
|
220
|
+
sa ligne `failed` le dit. Après un échec, relancer : les fiches créées sont sautées.
|
|
221
|
+
|
|
222
|
+
La relance ne retrouve que les fiches que l'invité voit : sur un CRUD dont une fiche peut être hors
|
|
223
|
+
ligne (date ou drapeau de publication), une fiche importée hors ligne serait recréée.
|
|
224
|
+
|
|
225
|
+
La clé est dédiée à l'import et appartient à un utilisateur dont le rôle n'a que le droit de créer
|
|
226
|
+
dans ce CRUD (`formResponse@<id>.create`) ; un nouveau jeton de la clé révoque les précédents.
|
|
227
|
+
|
|
228
|
+
## Content-Security-Policy
|
|
229
|
+
|
|
230
|
+
L'amorce est un script inline, différent d'une page à l'autre (l'identifiant de la page y est écrit) :
|
|
231
|
+
une CSP doit l'autoriser par l'empreinte du script de chaque page, calculée sur le HTML construit
|
|
232
|
+
(`security.csp` d'Astro ne hache pas les scripts `is:inline`) ; `script-src 'unsafe-inline'` l'autorise
|
|
233
|
+
aussi, mais ôte à la CSP sa garde sur le HTML des textes rendus. Bloquée, l'amorce laisse la page hors
|
|
234
|
+
d'édition et les champs gardent les choix du build. Le reste : `script-src 'self'` (la couche),
|
|
235
|
+
`connect-src` et `img-src` vers l'API, et `frame-ancestors` vers l'écran d'administration, qui ouvre
|
|
236
|
+
le site dans une iframe ; `frame-ancestors` s'envoie en en-tête HTTP, une balise `<meta>` l'ignore.
|
|
237
|
+
|
|
238
|
+
## `astro dev`
|
|
239
|
+
|
|
240
|
+
Les réponses de l'API sont gardées toute la vie du serveur de dev : une modification faite dans
|
|
241
|
+
l'administration paraît après son redémarrage. Une requête échouée est reposée à la page suivante.
|
|
242
|
+
Le doublon d'identifiant n'échoue qu'au build.
|
|
243
|
+
|
|
244
|
+
## Site d'exemple
|
|
245
|
+
|
|
246
|
+
`example/` : pages d'accueil, de projets (une page par fiche du CRUD `projets`) et de contact, textes,
|
|
247
|
+
liens, image et amorce. Il attend d'Armarius le CRUD `projets` (champs `name` et `permalink`) ; le menu
|
|
248
|
+
`main` et le réglage `contact_email` sont facultatifs.
|
|
249
|
+
|
|
250
|
+
```sh
|
|
251
|
+
(cd ../edition && npm ci && npm run build)
|
|
252
|
+
npm ci && npm run build
|
|
253
|
+
ARMARIUS_API_URL=http://127.0.0.1:8065 npm run example:build
|
|
254
|
+
npm run example:preview -- --port 4065
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
Dans un back-office local dont `FRONTEND_URL` vaut `http://127.0.0.1:4065` (assets construits avec
|
|
258
|
+
`VITE_FRONTEND_URL` à la même valeur), ouvrir `/admin/editing`.
|
|
259
|
+
`ARMARIUS_SCREEN_ORIGIN` donne l'origine de l'écran quand elle diffère de l'API.
|
|
260
|
+
|
|
261
|
+
## Développement
|
|
262
|
+
|
|
263
|
+
```sh
|
|
264
|
+
(cd ../edition && npm ci && npm run build) # la couche, liée par file:../edition
|
|
265
|
+
npm ci
|
|
266
|
+
npm test # build du kit, puis vitest (dont un build du site de test contre une API simulée)
|
|
267
|
+
npm run typecheck
|
|
268
|
+
npm run lint
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
## Publication
|
|
272
|
+
|
|
273
|
+
Par une étiquette protégée `js-astro-v<x.y.z>` sur le dépôt d'Armarius, dont la version est celle de
|
|
274
|
+
`package.json` : `pack:js-astro` vérifie que la version d'`@epekta/armarius-edition` dont dépend le kit
|
|
275
|
+
est publiée, construit la couche, installe, teste et empaquette sans aucun identifiant npm ;
|
|
276
|
+
`publish:js-astro` publie l'archive.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
---
|
|
2
|
+
// Goes in the page's <head>. The choices of form fields are read at load, so that changing them in the
|
|
3
|
+
// admin needs no rebuild.
|
|
4
|
+
import { editionBoot } from '../dist/runtime.js';
|
|
5
|
+
|
|
6
|
+
const boot = await editionBoot(Astro.url.pathname);
|
|
7
|
+
---
|
|
8
|
+
<meta name="armarius:locale" content={boot.locale} />
|
|
9
|
+
{boot.pageId !== null && <meta name="armarius:page" content={String(boot.pageId)} />}
|
|
10
|
+
<link rel="preconnect" href={boot.apiOrigin} />
|
|
11
|
+
<script is:inline define:vars={{ boot }}>
|
|
12
|
+
const previewFlag = 'armarius:preview';
|
|
13
|
+
|
|
14
|
+
function inPreview() {
|
|
15
|
+
if (window.parent === window) return false;
|
|
16
|
+
try {
|
|
17
|
+
// The screen opens the first page with ?preview=true; the pages reached from it keep the layer.
|
|
18
|
+
if (new URLSearchParams(location.search).get('preview') === 'true') sessionStorage.setItem(previewFlag, '1');
|
|
19
|
+
return sessionStorage.getItem(previewFlag) === '1';
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// A sandboxed frame may refuse the storage: the page then stays out of edition.
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function loadFieldChoices(holder) {
|
|
28
|
+
const [crud, field] = (holder.getAttribute('data-edition-field') || '').split('/');
|
|
29
|
+
const selects = holder.matches('select') ? [holder] : [...holder.querySelectorAll('select')];
|
|
30
|
+
if (!crud || !field || selects.length === 0) return;
|
|
31
|
+
|
|
32
|
+
const url = new URL(`/api/nuxt/cruds/${encodeURIComponent(crud)}/form-fields/${encodeURIComponent(field)}/options`, boot.apiOrigin);
|
|
33
|
+
// The locale goes in the query: a Locale header would cost a preflight.
|
|
34
|
+
url.searchParams.set('locale', boot.locale);
|
|
35
|
+
fetch(url, { credentials: 'omit' })
|
|
36
|
+
.then(response => (response.ok ? response.json() : null))
|
|
37
|
+
.then((body) => {
|
|
38
|
+
const choices = Array.isArray(body) ? body : body && body.data;
|
|
39
|
+
if (!Array.isArray(choices)) return;
|
|
40
|
+
for (const select of selects) {
|
|
41
|
+
const chosen = select.value;
|
|
42
|
+
const placeholders = [...select.options].filter(option => option.value === '');
|
|
43
|
+
select.replaceChildren(...placeholders, ...choices.map(choice => new Option(choice.label, String(choice.id))));
|
|
44
|
+
select.value = chosen;
|
|
45
|
+
}
|
|
46
|
+
})
|
|
47
|
+
// The field keeps the choices of the build.
|
|
48
|
+
.catch(() => {});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function start() {
|
|
52
|
+
if (inPreview()) {
|
|
53
|
+
import(boot.layerUrl).then(({ createDomAdapter, startLayer }) => {
|
|
54
|
+
startLayer(createDomAdapter({ apiUrl: boot.apiOrigin }), { screenOrigin: boot.screenOrigin });
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
document.querySelectorAll('[data-edition-field]').forEach(loadFieldChoices);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
|
|
61
|
+
else start();
|
|
62
|
+
</script>
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
---
|
|
2
|
+
// An image of Armarius: the site's own file until an image is chosen in Armarius, then its Glide variant.
|
|
3
|
+
import type { GlideParams } from '../dist/images.js';
|
|
4
|
+
import { renderImage } from '../dist/runtime.js';
|
|
5
|
+
|
|
6
|
+
interface Props {
|
|
7
|
+
/** Identifier of the image in Armarius: literal, unique to this image, never built in a loop. */
|
|
8
|
+
id: string;
|
|
9
|
+
/** The image of the code, a path of the site (`public/`); Armarius copies it at the first sync. */
|
|
10
|
+
src: string;
|
|
11
|
+
alt?: string;
|
|
12
|
+
/** The variant, in one of the six static query shapes; `q=80&w=1600` by default. */
|
|
13
|
+
glide?: GlideParams;
|
|
14
|
+
[attribute: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const { id, src, alt = '', glide = { q: 80, w: 1600 }, ...attributes } = Astro.props;
|
|
18
|
+
const image = await renderImage({ name: id, src, alt, glide, pathname: Astro.url.pathname });
|
|
19
|
+
---
|
|
20
|
+
<img data-content-id={id} src={image.src} alt={image.alt} {...attributes} />
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
---
|
|
2
|
+
// A text of Armarius: the slot is the value of the code, rendered until Armarius holds another one.
|
|
3
|
+
import { renderText } from '../dist/runtime.js';
|
|
4
|
+
|
|
5
|
+
interface Props {
|
|
6
|
+
/** Identifier of the text in Armarius: literal, unique to this text, never built in a loop. */
|
|
7
|
+
id: string;
|
|
8
|
+
/** The element rendered, `span` by default; a link is always an `a`. */
|
|
9
|
+
as?: string;
|
|
10
|
+
class?: string;
|
|
11
|
+
/** A link to a path or an address. */
|
|
12
|
+
href?: string;
|
|
13
|
+
/** A link to a page of the code, by its `route_name`. */
|
|
14
|
+
routeName?: string;
|
|
15
|
+
[attribute: string]: unknown;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const { id, as = 'span', class: className, href, routeName, ...attributes } = Astro.props;
|
|
19
|
+
const value = Astro.slots.has('default') ? await Astro.slots.render('default') : '';
|
|
20
|
+
const text = await renderText({ name: id, value, tag: as, pathname: Astro.url.pathname, class: className, href, routeName });
|
|
21
|
+
const Tag = text.tag;
|
|
22
|
+
---
|
|
23
|
+
<Tag data-content-id={id} tag-type={text.isLink ? 'a' : undefined} href={text.href} class={className} {...attributes} set:html={text.html} />
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface ApiSettings {
|
|
2
|
+
apiOrigin: string;
|
|
3
|
+
locale: string;
|
|
4
|
+
timeoutMs: number;
|
|
5
|
+
retries: number;
|
|
6
|
+
}
|
|
7
|
+
export interface ApiRequest {
|
|
8
|
+
method?: 'GET' | 'POST';
|
|
9
|
+
query?: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
export declare class ArmariusApiError extends Error {
|
|
12
|
+
name: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* One request to the Armarius API, in the build's locale: retried when the API does not answer, answers
|
|
16
|
+
* 429 or 5xx; any other refusal, or the last failure, throws and so fails the build.
|
|
17
|
+
*/
|
|
18
|
+
export declare function requestJson<T>(settings: ApiSettings, path: string, { method, query }?: ApiRequest): Promise<T>;
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export class ArmariusApiError extends Error {
|
|
2
|
+
name = 'ArmariusApiError';
|
|
3
|
+
}
|
|
4
|
+
const RETRY_DELAY_MS = 500;
|
|
5
|
+
function isRetryable(status) {
|
|
6
|
+
return status === 429 || status >= 500;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* One request to the Armarius API, in the build's locale: retried when the API does not answer, answers
|
|
10
|
+
* 429 or 5xx; any other refusal, or the last failure, throws and so fails the build.
|
|
11
|
+
*/
|
|
12
|
+
export async function requestJson(settings, path, { method = 'GET', query = {} } = {}) {
|
|
13
|
+
const url = new URL(path, settings.apiOrigin);
|
|
14
|
+
url.searchParams.set('locale', settings.locale);
|
|
15
|
+
for (const [key, value] of Object.entries(query))
|
|
16
|
+
url.searchParams.set(key, value);
|
|
17
|
+
const label = `${method} ${url.pathname}`;
|
|
18
|
+
let lastFailure = '';
|
|
19
|
+
for (let attempt = 0; attempt <= settings.retries; attempt++) {
|
|
20
|
+
if (attempt > 0)
|
|
21
|
+
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY_MS * attempt));
|
|
22
|
+
let response;
|
|
23
|
+
try {
|
|
24
|
+
response = await fetch(url, {
|
|
25
|
+
method,
|
|
26
|
+
headers: { Accept: 'application/json', Locale: settings.locale },
|
|
27
|
+
signal: AbortSignal.timeout(settings.timeoutMs),
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
lastFailure = error instanceof Error && error.name === 'TimeoutError'
|
|
32
|
+
? `no answer within ${settings.timeoutMs} ms`
|
|
33
|
+
: String(error instanceof Error ? error.message : error);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (response.ok)
|
|
37
|
+
return await response.json();
|
|
38
|
+
lastFailure = `HTTP ${response.status}`;
|
|
39
|
+
if (!isRetryable(response.status))
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
throw new ArmariusApiError(`armarius-astro: ${label} on ${settings.apiOrigin} failed (${lastFailure}).`);
|
|
43
|
+
}
|
package/dist/check.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type StoredText } from './render.js';
|
|
2
|
+
import type { BuildManifest } from './sync.js';
|
|
3
|
+
export declare const MANIFEST_PATH = ".armarius/manifest.json";
|
|
4
|
+
/** Characters a value keeps on its line of the report, cut in the middle beyond. */
|
|
5
|
+
export declare const REPORT_VALUE_WIDTH = 72;
|
|
6
|
+
export interface TextConflict {
|
|
7
|
+
name: string;
|
|
8
|
+
/** What the admin holds, and the sync keeps. */
|
|
9
|
+
adminValue: string;
|
|
10
|
+
/** What the code holds, and the sync discards; null from a manifest of 0.1.0, which kept only its hash. */
|
|
11
|
+
codeValue: string | null;
|
|
12
|
+
}
|
|
13
|
+
/** Texts changed in the code since the last sync, and in the admin too: the sync will keep the admin's. */
|
|
14
|
+
export declare function conflicts(manifest: Pick<BuildManifest, 'texts' | 'codeValues'>, stored: Record<string, StoredText>): TextConflict[];
|
|
15
|
+
/**
|
|
16
|
+
* A value on one line: its whitespace runs as one space, its control and bidirectional characters dropped (an
|
|
17
|
+
* admin's text must not repaint the terminal nor the CI log), and its middle cut out beyond `width` characters.
|
|
18
|
+
*/
|
|
19
|
+
export declare function oneLine(value: string, width?: number): string;
|
|
20
|
+
export declare function conflictReport(found: TextConflict[]): string[];
|
|
21
|
+
/**
|
|
22
|
+
* `armarius-astro check`, read only: from the manifest of the last build, asks Armarius for the texts and
|
|
23
|
+
* prints the conflicts. Always ends with code 0; what it cannot read, it says.
|
|
24
|
+
*/
|
|
25
|
+
export declare function runCheck(root: string, print: (line: string) => void): Promise<void>;
|
package/dist/check.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { requestJson } from './api.js';
|
|
4
|
+
import { keyed } from './readers.js';
|
|
5
|
+
import { isConflict } from './render.js';
|
|
6
|
+
export const MANIFEST_PATH = '.armarius/manifest.json';
|
|
7
|
+
/** Conflicts are rare and the check informs: one attempt more than none is enough. */
|
|
8
|
+
const CHECK_RETRIES = 1;
|
|
9
|
+
const CHECK_TIMEOUT_MS = 10_000;
|
|
10
|
+
/** Characters a value keeps on its line of the report, cut in the middle beyond. */
|
|
11
|
+
export const REPORT_VALUE_WIDTH = 72;
|
|
12
|
+
/** Texts changed in the code since the last sync, and in the admin too: the sync will keep the admin's. */
|
|
13
|
+
export function conflicts(manifest, stored) {
|
|
14
|
+
return Object.keys(manifest.texts)
|
|
15
|
+
.filter(name => isConflict(manifest.texts[name], stored[name]))
|
|
16
|
+
.sort()
|
|
17
|
+
.map(name => ({
|
|
18
|
+
name,
|
|
19
|
+
adminValue: stored[name]?.content ?? '',
|
|
20
|
+
codeValue: manifest.codeValues?.[name] ?? null,
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A value on one line: its whitespace runs as one space, its control and bidirectional characters dropped (an
|
|
25
|
+
* admin's text must not repaint the terminal nor the CI log), and its middle cut out beyond `width` characters.
|
|
26
|
+
*/
|
|
27
|
+
export function oneLine(value, width = REPORT_VALUE_WIDTH) {
|
|
28
|
+
const characters = Array.from(value.replace(/\s+/g, ' ').replace(/[\p{Cc}\u202A-\u202E\u2066-\u2069]/gu, '').trim());
|
|
29
|
+
if (characters.length <= width)
|
|
30
|
+
return characters.join('');
|
|
31
|
+
const kept = width - 1;
|
|
32
|
+
const head = Math.ceil(kept / 2);
|
|
33
|
+
return `${characters.slice(0, head).join('')}…${characters.slice(characters.length - (kept - head)).join('')}`;
|
|
34
|
+
}
|
|
35
|
+
export function conflictReport(found) {
|
|
36
|
+
if (found.length === 0)
|
|
37
|
+
return ['armarius-astro check: no text changed both in the code and in the admin.'];
|
|
38
|
+
return [
|
|
39
|
+
`armarius-astro check: ${found.length} text(s) changed both in the code and in the admin; the sync keeps the admin's value:`,
|
|
40
|
+
...found.flatMap(conflict => [
|
|
41
|
+
` - ${conflict.name}`,
|
|
42
|
+
` admin (kept): ${oneLine(conflict.adminValue)}`,
|
|
43
|
+
` code (discarded): ${conflict.codeValue === null ? '(not in this manifest; build again to see it)' : oneLine(conflict.codeValue)}`,
|
|
44
|
+
]),
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
async function newestModification(directory) {
|
|
48
|
+
let newest = 0;
|
|
49
|
+
for (const entry of await readdir(directory, { withFileTypes: true, recursive: true })) {
|
|
50
|
+
if (!entry.isFile())
|
|
51
|
+
continue;
|
|
52
|
+
newest = Math.max(newest, (await stat(join(entry.parentPath, entry.name))).mtimeMs);
|
|
53
|
+
}
|
|
54
|
+
return newest;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* `armarius-astro check`, read only: from the manifest of the last build, asks Armarius for the texts and
|
|
58
|
+
* prints the conflicts. Always ends with code 0; what it cannot read, it says.
|
|
59
|
+
*/
|
|
60
|
+
export async function runCheck(root, print) {
|
|
61
|
+
let manifest;
|
|
62
|
+
try {
|
|
63
|
+
manifest = JSON.parse(await readFile(join(root, MANIFEST_PATH), 'utf8'));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
print(`armarius-astro check: no ${MANIFEST_PATH} here; run the site's build first.`);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
if (await newestModification(join(root, 'src')) > Date.parse(manifest.builtAt)) {
|
|
71
|
+
print('armarius-astro check: src/ changed after the last build; build again to check the current texts.');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// A site without src/ has nothing newer than its manifest.
|
|
76
|
+
}
|
|
77
|
+
let body;
|
|
78
|
+
try {
|
|
79
|
+
body = await requestJson({ apiOrigin: manifest.apiOrigin, locale: manifest.locale, timeoutMs: CHECK_TIMEOUT_MS, retries: CHECK_RETRIES }, '/api/nuxt/contents');
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
print(`armarius-astro check: ${error instanceof Error ? error.message : String(error)}`);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
for (const line of conflictReport(conflicts(manifest, keyed(body.data))))
|
|
86
|
+
print(line);
|
|
87
|
+
}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runCli(args: string[], root: string, print?: (line: string) => void): Promise<number>;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { runCheck } from './check.js';
|
|
2
|
+
import { IMPORT_SYNOPSIS, runImport } from './import/command.js';
|
|
3
|
+
const USAGE = `Usage: armarius-astro check | ${IMPORT_SYNOPSIS}`;
|
|
4
|
+
export async function runCli(args, root, print = console.log) {
|
|
5
|
+
if (args[0] === 'import')
|
|
6
|
+
return runImport(args.slice(1), root, print);
|
|
7
|
+
if (args[0] !== 'check') {
|
|
8
|
+
print(USAGE);
|
|
9
|
+
return 1;
|
|
10
|
+
}
|
|
11
|
+
await runCheck(root, print);
|
|
12
|
+
return 0;
|
|
13
|
+
}
|
package/dist/hash.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hash Armarius keeps of a text's code value (ADR 0024): SHA-256, lowercase hex, of the UTF-8
|
|
3
|
+
* bytes of the value as sent, without any normalization; a null value hashes as the empty string.
|
|
4
|
+
*/
|
|
5
|
+
export declare function codeHash(value: string | null): string;
|
package/dist/hash.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* The hash Armarius keeps of a text's code value (ADR 0024): SHA-256, lowercase hex, of the UTF-8
|
|
4
|
+
* bytes of the value as sent, without any normalization; a null value hashes as the empty string.
|
|
5
|
+
*/
|
|
6
|
+
export function codeHash(value) {
|
|
7
|
+
return createHash('sha256').update(value ?? '', 'utf8').digest('hex');
|
|
8
|
+
}
|
package/dist/images.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** The query keys of a Glide variant, as the image transformer of Armarius reads them. */
|
|
2
|
+
export interface GlideParams {
|
|
3
|
+
fit?: string;
|
|
4
|
+
fm?: 'webp' | 'jpg' | 'png' | 'avif' | 'gif';
|
|
5
|
+
h?: number;
|
|
6
|
+
q?: number;
|
|
7
|
+
w?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare class ArmariusImageError extends Error {
|
|
10
|
+
name: string;
|
|
11
|
+
}
|
|
12
|
+
/** A media of Armarius, as `MediaResource` serves it. */
|
|
13
|
+
export interface StoredMedia {
|
|
14
|
+
id: number;
|
|
15
|
+
name: string;
|
|
16
|
+
}
|
|
17
|
+
/** `<apiOrigin>/img/<id>/<file name>?<sorted query>`, in one of the six static shapes, else an error. */
|
|
18
|
+
export declare function glideUrl(apiOrigin: string, media: StoredMedia, params: GlideParams): string;
|
package/dist/images.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The query shapes the web server serves as static files (`public/.htaccess` of the client app, ADR 0002),
|
|
3
|
+
* keys sorted: any other shape reaches PHP at each visit.
|
|
4
|
+
*/
|
|
5
|
+
const STATIC_SHAPES = ['q,w', 'fit,q,w', 'fm,q,w', 'q', 'fit,fm,q,w', 'fit,fm,h,q,w'];
|
|
6
|
+
const VALUE_RULES = {
|
|
7
|
+
fit: /^[a-z-]{1,12}$/,
|
|
8
|
+
fm: /^(webp|jpg|png|avif|gif)$/,
|
|
9
|
+
h: /^[0-9]{1,4}$/,
|
|
10
|
+
q: /^[0-9]{1,3}$/,
|
|
11
|
+
w: /^[0-9]{1,4}$/,
|
|
12
|
+
};
|
|
13
|
+
export class ArmariusImageError extends Error {
|
|
14
|
+
name = 'ArmariusImageError';
|
|
15
|
+
}
|
|
16
|
+
/** `<apiOrigin>/img/<id>/<file name>?<sorted query>`, in one of the six static shapes, else an error. */
|
|
17
|
+
export function glideUrl(apiOrigin, media, params) {
|
|
18
|
+
if (!Number.isInteger(media.id) || media.id <= 0) {
|
|
19
|
+
throw new ArmariusImageError(`armarius-astro: media id ${JSON.stringify(media.id)} is not a positive integer.`);
|
|
20
|
+
}
|
|
21
|
+
const entries = Object.entries(params)
|
|
22
|
+
.filter(([, value]) => value !== undefined)
|
|
23
|
+
.sort(([left], [right]) => left.localeCompare(right));
|
|
24
|
+
const shape = entries.map(([key]) => key).join(',');
|
|
25
|
+
if (!STATIC_SHAPES.includes(shape)) {
|
|
26
|
+
throw new ArmariusImageError(`armarius-astro: image query "${shape}" is not one of the static shapes (${STATIC_SHAPES.join(' | ')}).`);
|
|
27
|
+
}
|
|
28
|
+
for (const [key, value] of entries) {
|
|
29
|
+
if (!VALUE_RULES[key].test(String(value))) {
|
|
30
|
+
throw new ArmariusImageError(`armarius-astro: image query ${key}=${value} is outside the static rule.`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const query = entries.map(([key, value]) => `${key}=${value}`).join('&');
|
|
34
|
+
return `${apiOrigin}/img/${media.id}/${encodeURIComponent(media.name)}?${query}`;
|
|
35
|
+
}
|