@epekta/armarius-astro 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,273 @@
1
- # Temporary Holding Version
1
+ # @epekta/armarius-astro
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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 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. Le build imprime
151
+ le même rapport. Rend toujours 0 ; ce qu'il ne peut pas lire (pas de manifeste, API injoignable,
152
+ `src/` plus récent que le build), il le dit.
153
+
154
+ ## Import
155
+
156
+ ```sh
157
+ export ARMARIUS_API_URL=https://app.example.com
158
+ npx armarius-astro import import/projets.json --dry-run
159
+ read -rs ARMARIUS_API_KEY && export ARMARIUS_API_KEY # saisie masquée, hors de l'historique du shell
160
+ npx armarius-astro import import/projets.json
161
+ ```
162
+
163
+ Crée dans un CRUD d'Armarius les fiches d'un fichier `armarius-import/v1`, par le webservice. Il ne
164
+ modifie ni ne supprime jamais une fiche : une fiche dont la clé existe déjà est sautée.
165
+
166
+ ```json
167
+ {
168
+ "format": "armarius-import/v1",
169
+ "crud": "projets",
170
+ "key": "name",
171
+ "records": [
172
+ {
173
+ "name": "Villa Marage",
174
+ "place": { "crud": "lieux", "name": "Côte d'Azur" },
175
+ "mainPicture": { "file": "../img/marage-1.jpg" },
176
+ "pictures": [{ "file": "../img/marage-2.jpg" }, { "file": "../img/marage-3.jpg" }],
177
+ "inHome": false
178
+ }
179
+ ]
180
+ }
181
+ ```
182
+
183
+ | Valeur | Forme |
184
+ | --- | --- |
185
+ | Texte, nombre, booléen | Tel quel ; un champ traduisible accepte aussi `{ "fr": "…", "en": "…" }`. |
186
+ | 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. |
187
+ | 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`. |
188
+
189
+ `key` nomme le champ qui identifie une fiche : texte, nombre, e-mail, téléphone ou URL, ni privé
190
+ ni traduisible (la liste publique doit le rendre tel qu'il a été envoyé). Clés et noms de relation
191
+ se comparent sans casse, sans espaces en bord, espaces intérieurs réduits à un, en Unicode NFC.
192
+
193
+ | Variable | Rôle |
194
+ | --- | --- |
195
+ | `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. |
196
+ | `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. |
197
+
198
+ Avant toute écriture, la commande lit la description du CRUD
199
+ (`GET /webservice/resources/<crud>/details`), ses fiches et celles des CRUD cibles des relations
200
+ par la route publique (`GET /api/cruds/from-slug/<crud>/items`, droit « Voir les entrées » de
201
+ l'invité), et vérifie chaque fiche : champ inconnu, champ requis absent, clé vide ou en double,
202
+ relation introuvable ou ambiguë, fichier absent, chemin absolu ou extension non envoyée.
203
+
204
+ - `--dry-run` : lecture seule ; une ligne par fiche (`create`, `exists`, `error` et sa raison) ; code
205
+ 1 s'il y a une erreur, 0 sinon.
206
+ - Sans `--dry-run` : sur une erreur de vérification, les mêmes lignes et rien n'est écrit (code 1).
207
+ Sinon, un jeton pour le passage (refusé, rien n'est créé), puis, par fiche à créer : envoi de ses
208
+ fichiers et création ; une ligne `created`, `skipped` (la clé existe) ou `failed` (envoi ou
209
+ création refusés : la fiche n'est pas créée, la suivante continue), puis le bilan. Code 1 s'il y a
210
+ un échec, 0 sinon.
211
+ - Un fichier unique se traite après la création, sur un worker de la file `default` d'Armarius :
212
+ la création le rend `pending`, attendu. Une fiche dont un fichier unique est refusé est créée
213
+ quand même (Armarius rend 201) : la ligne `failed` donne son numéro, à corriger dans
214
+ l'administration.
215
+ - Une requête refusée par 429 est reprise après son `Retry-After` ; une écriture n'est jamais reprise
216
+ sur une erreur 5xx ni sans réponse, ni redirigée. Une création restée sans réponse a pu se faire :
217
+ sa ligne `failed` le dit. Après un échec, relancer : les fiches créées sont sautées.
218
+
219
+ La relance ne retrouve que les fiches que l'invité voit : sur un CRUD dont une fiche peut être hors
220
+ ligne (date ou drapeau de publication), une fiche importée hors ligne serait recréée.
221
+
222
+ La clé est dédiée à l'import et appartient à un utilisateur dont le rôle n'a que le droit de créer
223
+ dans ce CRUD (`formResponse@<id>.create`) ; un nouveau jeton de la clé révoque les précédents.
224
+
225
+ ## Content-Security-Policy
226
+
227
+ L'amorce est un script inline, différent d'une page à l'autre (l'identifiant de la page y est écrit) :
228
+ une CSP doit l'autoriser par l'empreinte du script de chaque page, calculée sur le HTML construit
229
+ (`security.csp` d'Astro ne hache pas les scripts `is:inline`) ; `script-src 'unsafe-inline'` l'autorise
230
+ aussi, mais ôte à la CSP sa garde sur le HTML des textes rendus. Bloquée, l'amorce laisse la page hors
231
+ d'édition et les champs gardent les choix du build. Le reste : `script-src 'self'` (la couche),
232
+ `connect-src` et `img-src` vers l'API, et `frame-ancestors` vers l'écran d'administration, qui ouvre
233
+ le site dans une iframe ; `frame-ancestors` s'envoie en en-tête HTTP, une balise `<meta>` l'ignore.
234
+
235
+ ## `astro dev`
236
+
237
+ Les réponses de l'API sont gardées toute la vie du serveur de dev : une modification faite dans
238
+ l'administration paraît après son redémarrage. Une requête échouée est reposée à la page suivante.
239
+ Le doublon d'identifiant n'échoue qu'au build.
240
+
241
+ ## Site d'exemple
242
+
243
+ `example/` : pages d'accueil, de projets (une page par fiche du CRUD `projets`) et de contact, textes,
244
+ liens, image et amorce. Il attend d'Armarius le CRUD `projets` (champs `name` et `permalink`) ; le menu
245
+ `main` et le réglage `contact_email` sont facultatifs.
246
+
247
+ ```sh
248
+ (cd ../edition && npm ci && npm run build)
249
+ npm ci && npm run build
250
+ ARMARIUS_API_URL=http://127.0.0.1:8065 npm run example:build
251
+ npm run example:preview -- --port 4065
252
+ ```
253
+
254
+ Dans un back-office local dont `FRONTEND_URL` vaut `http://127.0.0.1:4065` (assets construits avec
255
+ `VITE_FRONTEND_URL` à la même valeur), ouvrir `/admin/editing`.
256
+ `ARMARIUS_SCREEN_ORIGIN` donne l'origine de l'écran quand elle diffère de l'API.
257
+
258
+ ## Développement
259
+
260
+ ```sh
261
+ (cd ../edition && npm ci && npm run build) # la couche, liée par file:../edition
262
+ npm ci
263
+ npm test # build du kit, puis vitest (dont un build du site de test contre une API simulée)
264
+ npm run typecheck
265
+ npm run lint
266
+ ```
267
+
268
+ ## Publication
269
+
270
+ 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
271
+ `package.json` : `pack:js-astro` vérifie que la version d'`@epekta/armarius-edition` dont dépend le kit
272
+ est publiée, construit la couche, installe, teste et empaquette sans aucun identifiant npm ;
273
+ `publish:js-astro` publie l'archive.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '../dist/cli.js';
3
+
4
+ process.exitCode = await runCli(process.argv.slice(2), process.cwd());
@@ -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
+ }
@@ -0,0 +1,11 @@
1
+ import { type StoredText } from './render.js';
2
+ import type { BuildManifest } from './sync.js';
3
+ export declare const MANIFEST_PATH = ".armarius/manifest.json";
4
+ /** Texts changed in the code since the last sync, and in the admin too: the sync will keep the admin's. */
5
+ export declare function conflicts(manifest: Pick<BuildManifest, 'texts'>, stored: Record<string, StoredText>): string[];
6
+ export declare function conflictReport(names: string[]): string[];
7
+ /**
8
+ * `armarius-astro check`, read only: from the manifest of the last build, asks Armarius for the texts and
9
+ * prints the conflicts. Always ends with code 0; what it cannot read, it says.
10
+ */
11
+ export declare function runCheck(root: string, print: (line: string) => void): Promise<void>;
package/dist/check.js ADDED
@@ -0,0 +1,64 @@
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
+ /** Texts changed in the code since the last sync, and in the admin too: the sync will keep the admin's. */
11
+ export function conflicts(manifest, stored) {
12
+ return Object.keys(manifest.texts)
13
+ .filter(name => isConflict(manifest.texts[name], stored[name]))
14
+ .sort();
15
+ }
16
+ export function conflictReport(names) {
17
+ if (names.length === 0)
18
+ return ['armarius-astro check: no text changed both in the code and in the admin.'];
19
+ return [
20
+ `armarius-astro check: ${names.length} text(s) changed both in the code and in the admin; the sync keeps the admin's value:`,
21
+ ...names.map(name => ` - ${name}`),
22
+ ];
23
+ }
24
+ async function newestModification(directory) {
25
+ let newest = 0;
26
+ for (const entry of await readdir(directory, { withFileTypes: true, recursive: true })) {
27
+ if (!entry.isFile())
28
+ continue;
29
+ newest = Math.max(newest, (await stat(join(entry.parentPath, entry.name))).mtimeMs);
30
+ }
31
+ return newest;
32
+ }
33
+ /**
34
+ * `armarius-astro check`, read only: from the manifest of the last build, asks Armarius for the texts and
35
+ * prints the conflicts. Always ends with code 0; what it cannot read, it says.
36
+ */
37
+ export async function runCheck(root, print) {
38
+ let manifest;
39
+ try {
40
+ manifest = JSON.parse(await readFile(join(root, MANIFEST_PATH), 'utf8'));
41
+ }
42
+ catch {
43
+ print(`armarius-astro check: no ${MANIFEST_PATH} here; run the site's build first.`);
44
+ return;
45
+ }
46
+ try {
47
+ if (await newestModification(join(root, 'src')) > Date.parse(manifest.builtAt)) {
48
+ print('armarius-astro check: src/ changed after the last build; build again to check the current texts.');
49
+ }
50
+ }
51
+ catch {
52
+ // A site without src/ has nothing newer than its manifest.
53
+ }
54
+ let body;
55
+ try {
56
+ body = await requestJson({ apiOrigin: manifest.apiOrigin, locale: manifest.locale, timeoutMs: CHECK_TIMEOUT_MS, retries: CHECK_RETRIES }, '/api/nuxt/contents');
57
+ }
58
+ catch (error) {
59
+ print(`armarius-astro check: ${error instanceof Error ? error.message : String(error)}`);
60
+ return;
61
+ }
62
+ for (const line of conflictReport(conflicts(manifest, keyed(body.data))))
63
+ print(line);
64
+ }
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
+ }
@@ -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
+ }
@@ -0,0 +1,7 @@
1
+ export declare const IMPORT_SYNOPSIS = "armarius-astro import <file> [--dry-run]";
2
+ /**
3
+ * `armarius-astro import <file> [--dry-run]`: creates the records of an `armarius-import/v1` file through
4
+ * the webservice of Armarius (`ARMARIUS_API_URL`, key in `ARMARIUS_API_KEY`). A record whose key exists is
5
+ * skipped, never updated. Ends with 1 on any error, 0 otherwise.
6
+ */
7
+ export declare function runImport(args: string[], root: string, print: (line: string) => void, env?: Record<string, string | undefined>): Promise<number>;