@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.
@@ -0,0 +1,132 @@
1
+ import { glideUrl } from './images.js';
2
+ import { resolvePaths, storedContents, storedPages, storedRoutes } from './readers.js';
3
+ import { textToRender } from './render.js';
4
+ import { isSafeLink, normalizePath, pagePath } from './routes.js';
5
+ import { kitState, LAYER_PATH, requireOptions } from './state.js';
6
+ /** Longest `content` the content sync accepts (`SaveArmaNuxtContentRequest`, `max:65535`, in characters). */
7
+ const MAX_CONTENT_LENGTH = 65535;
8
+ /**
9
+ * Elements a text renders as. The admin types into them: one that runs or hides its text (`script`, `style`,
10
+ * `textarea`, `title`) would turn an editor's text into code for every visitor.
11
+ */
12
+ const TEXT_TAGS = new Set([
13
+ 'span', 'p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'blockquote', 'button', 'strong', 'em', 'small',
14
+ 'label', 'figcaption', 'dt', 'dd',
15
+ ]);
16
+ /** The schemes a stored link may keep, as core's request rule for contents (`ContentSaveRequest`). */
17
+ const SAFE_HREF = /^(?:[/#?]|(?:https?|mailto|tel):)/i;
18
+ /** Scoped styles of the calling component mark the slot's elements; the mark is not part of the text. */
19
+ const SCOPE_ATTRIBUTE = /\sdata-astro-cid-[a-z0-9]+(?:="[^"]*")?/g;
20
+ export class ArmariusContentError extends Error {
21
+ name = 'ArmariusContentError';
22
+ }
23
+ /** The value of the code a text sends and hashes: the slot's HTML without the marks of scoped styles. */
24
+ export function codeValueOf(slotHtml) {
25
+ return slotHtml.replace(SCOPE_ATTRIBUTE, '');
26
+ }
27
+ /** The built path a rendered page is on; `null` for a path the kit did not build (404). */
28
+ async function pathEntryOf(pathname) {
29
+ await resolvePaths();
30
+ const { base, paths } = kitState();
31
+ const withoutBase = base !== '/' && pathname.startsWith(base) ? `/${pathname.slice(base.length)}` : pathname;
32
+ return paths.get(normalizePath(withoutBase)) ?? null;
33
+ }
34
+ function register(entry, routeName) {
35
+ const { contents, command } = kitState();
36
+ const known = contents.get(entry.name);
37
+ if (known === undefined) {
38
+ contents.set(entry.name, { ...entry, routeNames: new Set(routeName === null ? [] : [routeName]) });
39
+ return;
40
+ }
41
+ const sameContent = known.value === entry.value
42
+ && known.kind === entry.kind
43
+ && known.tag === entry.tag
44
+ && JSON.stringify(known.attrs) === JSON.stringify(entry.attrs);
45
+ if (command === 'build' && !sameContent) {
46
+ throw new ArmariusContentError(`armarius-astro: "${entry.name}" has two values in the code (${JSON.stringify(known.value)} and ${JSON.stringify(entry.value)}); give each its own identifier.`);
47
+ }
48
+ if (routeName !== null)
49
+ known.routeNames.add(routeName);
50
+ }
51
+ export async function renderText(input) {
52
+ const name = input.name.trim();
53
+ if (name === '')
54
+ throw new ArmariusContentError('armarius-astro: a Text has an empty id.');
55
+ const value = codeValueOf(input.value);
56
+ if ([...value].length > MAX_CONTENT_LENGTH) {
57
+ throw new ArmariusContentError(`armarius-astro: the text "${name}" is longer than ${MAX_CONTENT_LENGTH} characters.`);
58
+ }
59
+ const isLink = input.href !== undefined || input.routeName !== undefined;
60
+ // Armarius' saver of a link throws on a blank one once the sync has answered; a scheme a browser runs would reach every page.
61
+ if (input.href !== undefined && !isSafeLink(input.href)) {
62
+ throw new ArmariusContentError(`armarius-astro: the link "${name}" leads to ${JSON.stringify(input.href)}; give a path, an anchor, an http(s), mailto: or tel: address.`);
63
+ }
64
+ const tag = isLink ? 'a' : input.tag.toLowerCase();
65
+ if (!isLink && !TEXT_TAGS.has(tag)) {
66
+ throw new ArmariusContentError(`armarius-astro: the text "${name}" cannot render as <${tag}> (${[...TEXT_TAGS].join(', ')}).`);
67
+ }
68
+ const codeHref = isLink ? await codeHrefOf(input) : undefined;
69
+ const attrs = {};
70
+ if (input.class !== undefined && input.class !== '')
71
+ attrs.class = input.class;
72
+ if (input.href !== undefined)
73
+ attrs.to = input.href;
74
+ // Armarius' saver of a link requires `route-name`, and of a button `type`; `to` wins over `route-name`.
75
+ const linkTarget = input.routeName ?? input.href;
76
+ if (linkTarget !== undefined)
77
+ attrs['route-name'] = linkTarget;
78
+ if (tag === 'button')
79
+ attrs.type = 'button';
80
+ register({ name, kind: 'text', value, tag, attrs }, (await pathEntryOf(input.pathname))?.routeName ?? null);
81
+ const stored = (await storedContents())[name];
82
+ const storedHref = stored?.href?.trim() ?? '';
83
+ return {
84
+ html: textToRender(value, stored),
85
+ tag,
86
+ isLink,
87
+ href: isLink ? (SAFE_HREF.test(storedHref) ? storedHref : codeHref) : undefined,
88
+ };
89
+ }
90
+ async function codeHrefOf(input) {
91
+ if (input.href !== undefined)
92
+ return input.href;
93
+ const options = requireOptions();
94
+ const page = options.pages.find(candidate => candidate.route_name === input.routeName);
95
+ if (page === undefined) {
96
+ throw new ArmariusContentError(`armarius-astro: the link "${input.name}" names no page of the code ("${input.routeName}").`);
97
+ }
98
+ const path = pagePath(page, await storedRoutes(), options.locale);
99
+ const { base } = kitState();
100
+ return path === '/' ? base : `${base}${path.slice(1)}`;
101
+ }
102
+ export async function renderImage(input) {
103
+ const name = input.name.trim();
104
+ if (name === '')
105
+ throw new ArmariusContentError('armarius-astro: an Image has an empty id.');
106
+ const attrs = { src: input.src };
107
+ if (input.alt !== '')
108
+ attrs.alt = input.alt;
109
+ register({ name, kind: 'image', value: input.src, tag: 'img', attrs }, (await pathEntryOf(input.pathname))?.routeName ?? null);
110
+ const stored = (await storedContents())[name];
111
+ const picture = stored?.picture;
112
+ if (picture === null || picture === undefined)
113
+ return { src: input.src, alt: input.alt };
114
+ return {
115
+ src: glideUrl(requireOptions().apiOrigin, picture, input.glide),
116
+ alt: stored?.picture_alt ?? input.alt,
117
+ };
118
+ }
119
+ export async function editionBoot(pathname) {
120
+ const options = requireOptions();
121
+ const entry = await pathEntryOf(pathname);
122
+ // A record's page has no SEO of its own in the screen: only the page of the code does.
123
+ const storedId = entry === null || entry.recordId !== null ? null : (await storedPages())[entry.routeName]?.id;
124
+ const pageId = Number.isInteger(storedId) && storedId > 0 ? storedId : null;
125
+ return {
126
+ locale: options.locale,
127
+ pageId,
128
+ apiOrigin: options.apiOrigin,
129
+ screenOrigin: options.screenOrigin,
130
+ layerUrl: `${kitState().base}${LAYER_PATH}`,
131
+ };
132
+ }
@@ -0,0 +1,38 @@
1
+ import { type ResolvedOptions } from './options.js';
2
+ /** Where the site serves the edit layer, under its `base`. */
3
+ export declare const LAYER_PATH = "_armarius/layer.js";
4
+ /** A text or an image a component rendered during the build, with the value of the site's code. */
5
+ export interface RegisteredContent {
6
+ name: string;
7
+ kind: 'text' | 'image';
8
+ /** The value of the code: a text's HTML, or an image's `src` on the site. */
9
+ value: string;
10
+ tag: string;
11
+ attrs: Record<string, string>;
12
+ /** Pages (`route_name`) the content was rendered on. */
13
+ routeNames: Set<string>;
14
+ }
15
+ /** Where a built path comes from: the page of the code that renders it, and the record it shows, if any. */
16
+ export interface PathEntry {
17
+ routeName: string;
18
+ recordId: number | string | null;
19
+ }
20
+ export interface KitState {
21
+ options: ResolvedOptions | null;
22
+ /** `build` once `astro build` started: duplicate texts fail there, never in dev, where a value changes as it is typed. */
23
+ command: 'dev' | 'build' | 'preview' | 'sync' | null;
24
+ /** The site's `base`, ending with a slash. */
25
+ base: string;
26
+ contents: Map<string, RegisteredContent>;
27
+ paths: Map<string, PathEntry>;
28
+ requests: Map<string, Promise<unknown>>;
29
+ }
30
+ /**
31
+ * The kit's state, shared by the integration (loaded by Node from the site's config) and the components and
32
+ * readers (bundled into the build's own chunks): two module instances, one process, so the state lives on
33
+ * `globalThis`.
34
+ */
35
+ export declare function kitState(): KitState;
36
+ /** Forgets what a previous build read and rendered; the options stay. */
37
+ export declare function resetBuildState(): void;
38
+ export declare function requireOptions(): ResolvedOptions;
package/dist/state.js ADDED
@@ -0,0 +1,35 @@
1
+ import { ArmariusConfigError } from './options.js';
2
+ /** Where the site serves the edit layer, under its `base`. */
3
+ export const LAYER_PATH = '_armarius/layer.js';
4
+ const STATE_KEY = Symbol.for('@epekta/armarius-astro');
5
+ /**
6
+ * The kit's state, shared by the integration (loaded by Node from the site's config) and the components and
7
+ * readers (bundled into the build's own chunks): two module instances, one process, so the state lives on
8
+ * `globalThis`.
9
+ */
10
+ export function kitState() {
11
+ const holder = globalThis;
12
+ holder[STATE_KEY] ??= {
13
+ options: null,
14
+ command: null,
15
+ base: '/',
16
+ contents: new Map(),
17
+ paths: new Map(),
18
+ requests: new Map(),
19
+ };
20
+ return holder[STATE_KEY];
21
+ }
22
+ /** Forgets what a previous build read and rendered; the options stay. */
23
+ export function resetBuildState() {
24
+ const state = kitState();
25
+ state.contents.clear();
26
+ state.paths.clear();
27
+ state.requests.clear();
28
+ }
29
+ export function requireOptions() {
30
+ const { options } = kitState();
31
+ if (options === null) {
32
+ throw new ArmariusConfigError('armarius-astro: the armarius() integration is missing from the site\'s astro.config.');
33
+ }
34
+ return options;
35
+ }
package/dist/sync.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ import type { ArmariusPage, ResolvedOptions } from './options.js';
2
+ import type { RegisteredContent } from './state.js';
3
+ /**
4
+ * Cap of `SaveArmaNuxtPage` (`pages` max 100). The page contents body lists the same pages, under its own cap
5
+ * of 200 (`SaveArmaNuxtPageContentsRequest`).
6
+ */
7
+ export declare const MAX_SYNCED_PAGES = 100;
8
+ export interface PagePayload {
9
+ template: string;
10
+ route_name: string;
11
+ title: string;
12
+ slug: string;
13
+ requiresCrud?: boolean;
14
+ }
15
+ export interface ContentPayload {
16
+ content: string | null;
17
+ template?: string;
18
+ attrs: Record<string, string>;
19
+ }
20
+ export interface PageContentsPayload {
21
+ route_name: string;
22
+ items: {
23
+ type: 'content';
24
+ name: string;
25
+ }[];
26
+ }
27
+ export interface SyncBodies {
28
+ pages: {
29
+ pages: PagePayload[];
30
+ };
31
+ contents: {
32
+ contents: ContentPayload[];
33
+ };
34
+ pageContents: {
35
+ pages: PageContentsPayload[];
36
+ };
37
+ }
38
+ /**
39
+ * What `armarius-astro check` reads: where the build read, the hash of each text of the code and, since 0.1.1, its
40
+ * value. A manifest of 0.1.0 has no `codeValues`; `check` reads it all the same.
41
+ */
42
+ export interface BuildManifest {
43
+ version: 1;
44
+ apiOrigin: string;
45
+ locale: string;
46
+ builtAt: string;
47
+ texts: Record<string, string>;
48
+ codeValues?: Record<string, string>;
49
+ }
50
+ export declare class ArmariusSyncError extends Error {
51
+ name: string;
52
+ }
53
+ /**
54
+ * The three bodies the site's CI signs and posts after a build: pages of the code, texts and images with their
55
+ * value in the code, and which page shows which of them. Read from what the components recorded, not from the
56
+ * HTML, which no longer holds the code's value once the admin edited a text.
57
+ */
58
+ export declare function syncBodies(pages: ArmariusPage[], contents: Iterable<RegisteredContent>): SyncBodies;
59
+ export declare function buildManifest(options: ResolvedOptions, contents: Iterable<RegisteredContent>, builtAt: Date): BuildManifest;
package/dist/sync.js ADDED
@@ -0,0 +1,73 @@
1
+ import { codeHash } from './hash.js';
2
+ /**
3
+ * Cap of `SaveArmaNuxtPage` (`pages` max 100). The page contents body lists the same pages, under its own cap
4
+ * of 200 (`SaveArmaNuxtPageContentsRequest`).
5
+ */
6
+ export const MAX_SYNCED_PAGES = 100;
7
+ export class ArmariusSyncError extends Error {
8
+ name = 'ArmariusSyncError';
9
+ }
10
+ /**
11
+ * The three bodies the site's CI signs and posts after a build: pages of the code, texts and images with their
12
+ * value in the code, and which page shows which of them. Read from what the components recorded, not from the
13
+ * HTML, which no longer holds the code's value once the admin edited a text.
14
+ */
15
+ export function syncBodies(pages, contents) {
16
+ if (pages.length > MAX_SYNCED_PAGES) {
17
+ throw new ArmariusSyncError(`armarius-astro: ${pages.length} pages exceed the ${MAX_SYNCED_PAGES} the page sync accepts.`);
18
+ }
19
+ const sorted = [...contents];
20
+ // No content seen means the components did not share the integration's state: an empty page contents body
21
+ // would detach every content of every page. `SaveArmaNuxtContentRequest` refuses an empty list anyway.
22
+ if (sorted.length === 0) {
23
+ throw new ArmariusSyncError('armarius-astro: the build rendered no Text nor Image of the kit; no sync body is written.');
24
+ }
25
+ sorted.sort((left, right) => left.name.localeCompare(right.name));
26
+ const namesByPage = new Map(pages.map(page => [page.route_name, []]));
27
+ const contentPayloads = sorted.map((content) => {
28
+ for (const routeName of content.routeNames)
29
+ namesByPage.get(routeName)?.push(content.name);
30
+ const payload = {
31
+ content: content.kind === 'text' ? content.value : null,
32
+ attrs: {
33
+ 'data-content-id': content.name,
34
+ 'tag-type': content.tag,
35
+ 'component-type': content.kind,
36
+ ...content.attrs,
37
+ },
38
+ };
39
+ // A text shown on one page belongs to it; one shown on several stays shared.
40
+ if (content.routeNames.size === 1)
41
+ payload.template = [...content.routeNames][0];
42
+ return payload;
43
+ });
44
+ return {
45
+ pages: {
46
+ pages: pages.map(page => ({
47
+ template: page.route_name,
48
+ route_name: page.route_name,
49
+ title: page.title,
50
+ slug: page.slug,
51
+ ...(page.crud === undefined ? {} : { requiresCrud: true }),
52
+ })),
53
+ },
54
+ contents: { contents: contentPayloads },
55
+ pageContents: {
56
+ pages: pages.map(page => ({
57
+ route_name: page.route_name,
58
+ items: (namesByPage.get(page.route_name) ?? []).map(name => ({ type: 'content', name })),
59
+ })),
60
+ },
61
+ };
62
+ }
63
+ export function buildManifest(options, contents, builtAt) {
64
+ const texts = {};
65
+ const codeValues = {};
66
+ for (const content of [...contents].sort((left, right) => left.name.localeCompare(right.name))) {
67
+ if (content.kind !== 'text')
68
+ continue;
69
+ texts[content.name] = codeHash(content.value);
70
+ codeValues[content.name] = content.value;
71
+ }
72
+ return { version: 1, apiOrigin: options.apiOrigin, locale: options.locale, builtAt: builtAt.toISOString(), texts, codeValues };
73
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
- "name": "@epekta/armarius-astro",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@epekta/armarius-astro",
3
+ "version": "0.1.1",
4
+ "description": "Kit of a static Astro site rebuilt by Armarius: texts, images, pages and records read at build, sync bodies, in-place editing boot.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "keywords": [
8
+ "astro-component",
9
+ "armarius"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./components/*": "./components/*"
17
+ },
18
+ "bin": {
19
+ "armarius-astro": "bin/armarius-astro.js"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "components",
24
+ "bin"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "engines": {
30
+ "node": ">=22.23.4"
31
+ },
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.build.json",
34
+ "prepack": "npm run build",
35
+ "test": "npm run build && vitest run",
36
+ "typecheck": "tsc -p tsconfig.json",
37
+ "lint": "eslint .",
38
+ "example:build": "astro build --root example",
39
+ "example:preview": "astro preview --root example"
40
+ },
41
+ "peerDependencies": {
42
+ "astro": "^7.4.12"
43
+ },
44
+ "dependencies": {
45
+ "@epekta/armarius-edition": "^0.1.0"
46
+ },
47
+ "devDependencies": {
48
+ "@epekta/armarius-edition": "file:../edition",
49
+ "@eslint/js": "^10.0.1",
50
+ "@types/node": "^22.20.5",
51
+ "astro": "^7.4.13",
52
+ "eslint": "^10.15.0",
53
+ "globals": "^17.14.0",
54
+ "typescript": "~6.0.3",
55
+ "typescript-eslint": "^8.73.0",
56
+ "vitest": "^4.1.12"
57
+ }
58
+ }