@pirateandfox/pagestack 0.1.0-beta.7 → 0.1.0-beta.8

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.
Files changed (46) hide show
  1. package/README.md +39 -12
  2. package/index.mjs +18 -6
  3. package/package.json +1 -1
  4. package/src/client/auth.ts +5 -5
  5. package/src/client/collection.ts +6 -6
  6. package/src/client/editor.ts +105 -105
  7. package/src/client/form.ts +26 -26
  8. package/src/client/global.ts +4 -4
  9. package/src/client/inline.ts +4 -4
  10. package/src/client/inserter.ts +11 -11
  11. package/src/client/invite.ts +4 -4
  12. package/src/client/item.ts +202 -54
  13. package/src/client/live.ts +92 -0
  14. package/src/client/media.ts +12 -12
  15. package/src/client/pages.ts +14 -14
  16. package/src/client/picker.ts +30 -30
  17. package/src/client/preview.css +58 -58
  18. package/src/client/rich.ts +14 -14
  19. package/src/client/shell.css +281 -272
  20. package/src/client/state.ts +2 -2
  21. package/src/client/tomarkdown.ts +4 -2
  22. package/src/client/tree.ts +11 -11
  23. package/src/client/ui.ts +13 -13
  24. package/src/client/users.ts +6 -6
  25. package/src/core/auth.ts +1 -1
  26. package/src/core/markdown.ts +54 -5
  27. package/src/core/pages.ts +6 -2
  28. package/src/core/storage-github.ts +51 -5
  29. package/src/core/storage.ts +14 -0
  30. package/src/routes/Nav.astro +5 -3
  31. package/src/routes/api/collection.ts +30 -8
  32. package/src/routes/api/live.ts +27 -0
  33. package/src/routes/edit-collection.astro +14 -14
  34. package/src/routes/edit-global.astro +8 -8
  35. package/src/routes/edit-index.astro +18 -18
  36. package/src/routes/edit-item.astro +25 -23
  37. package/src/routes/edit-media.astro +9 -9
  38. package/src/routes/edit-page.astro +32 -30
  39. package/src/routes/edit-users.astro +9 -9
  40. package/src/routes/enroll.astro +6 -6
  41. package/src/routes/login.astro +6 -6
  42. package/src/routes/preview-item.astro +1 -1
  43. package/src/routes/preview.astro +1 -1
  44. package/src/runtime.ts +3 -3
  45. package/src/server/context.ts +3 -3
  46. package/src/server/middleware.ts +19 -4
package/README.md CHANGED
@@ -4,8 +4,8 @@ A visual editor for Astro sites where pages are a stack of sections. Git-only: s
4
4
  the public site stays static, and nothing lives outside the repo.
5
5
 
6
6
  - The public site stays **fully static**. `astro build` is unchanged.
7
- - The editor (`/edit/*`, `/api/editor/*`) is on-demand rendered and only exists in `astro dev`
8
- or in a build made with `EDITOR=1` (which adds `@astrojs/node`).
7
+ - The editor (`/edit/*`, `/api/editor/*`) is on-demand rendered and only exists when asked for:
8
+ `EDITOR=dev astro dev`, or a build made with `EDITOR=1` (which adds `@astrojs/node` unless the site has an adapter).
9
9
  - Pages are JSON documents in the repo (`src/content/pages/<slug>.json`). Saving writes a file
10
10
  (dev) or makes **one commit** through the GitHub API (production). Nothing is stored anywhere else.
11
11
  - Login is **passkeys** (WebAuthn). Users' public keys live in a committed `editor-users.json`;
@@ -58,7 +58,8 @@ export default defineConfig({
58
58
  ```
59
59
 
60
60
  ```bash
61
- npm run dev # editor at http://localhost:4321/edit, saves to the working tree
61
+ EDITOR=dev astro dev # editor at http://localhost:4321/edit, saves to the working tree
62
+ astro dev # the site alone: no editor, nothing can write content
62
63
  EDITOR=1 astro build # dist/server (node) + dist/client — the editor for a host
63
64
  astro build # plain static site, no editor code
64
65
  ```
@@ -216,10 +217,16 @@ export const globals = {
216
217
  #### Editing a collection item on its own page
217
218
 
218
219
  Give a collection a layout in `previews` (an option on the integration) and its items open on that
219
- page in the editor: click the title, a paragraph or a heading and type; click an image to pick
220
- another; lists, tables and code open the Markdown with that block selected. **Page** and **Markdown**
221
- switch views, and Preview ↗ shows the unsaved item in a tab. An edited paragraph is turned back into
222
- Markdown and replaces only its own lines, so the rest of the file stays byte-for-byte as it was.
220
+ page in the editor: click the title, a paragraph, a heading, a list or a quote and type; click an
221
+ image to pick another; tables, code and nested lists open the Markdown with that block selected. The
222
+ **+** beside a block, or `/` in an empty one, adds a paragraph, heading, list, quote, image or table
223
+ there. **Page** and **Markdown** switch views, and Preview ↗ shows the unsaved item in a tab. An
224
+ edited block is turned back into Markdown and replaces only its own lines, so the rest of the file
225
+ stays byte-for-byte as it was.
226
+
227
+ The ⋮ menu has **Change URL** (moves the file; with the collection's `url` and a redirects file, the
228
+ old address redirects in the same commit), **Revisions** (the file's git history; Restore loads one
229
+ as unsaved changes, covering the body and the fields the editor shows) and **Delete**.
223
230
 
224
231
  ```js
225
232
  pagestack({ /* … */ previews: { blog: './src/editor/PostPreview.astro' } })
@@ -229,7 +236,7 @@ The layout gets `{ item: { id, collection, data, body, html, headings }, editing
229
236
  sanitised body (render it with `set:html`), blocks already marked; `data` is the frontmatter as
230
237
  written, so apply the defaults and date parsing your content schema would. Mark the item's own
231
238
  fields with `itemField(editing, 'title')` from the runtime, or write the same two attributes
232
- (`data-ase-field`, `data-ase-field-type`) yourself. Sharing one component between the real page
239
+ (`data-ps-field`, `data-ps-field-type`) yourself. Sharing one component between the real page
233
240
  and the preview keeps them identical:
234
241
 
235
242
  ```astro
@@ -246,7 +253,11 @@ const { item, editing } = Astro.props;
246
253
  The preview renders on the editor's server (a Worker on Cloudflare), so whatever the layout imports
247
254
  must run there: no `node:fs` reads of the project, no native modules (sharp, resvg), and no import of
248
255
  `content.config.ts` (its loaders only run in a build). `getCollection` works. The page's own scripts
249
- don't run in the editor's frame.
256
+ are left out of the editor's frame.
257
+
258
+ In the block editor's preview the site's own scripts do run (tabs, accordions), but scripts from
259
+ other origins are refused, so analytics, captchas and chat widgets stay out of the editor.
260
+ `previewScripts: 'all'` lifts that for a site whose preview needs an outside script.
250
261
 
251
262
  An image field stored as a bare URL can name its alt-text field, `{ type: 'image', asUrl: true,
252
263
  altField: 'imageAlt' }`, and the picker fills it in.
@@ -275,6 +286,21 @@ than setting a hard limit. Passkeys are what actually stops guessing.
275
286
  | `local` (dev default) | working tree | writes the JSON file (you commit) | written to `public/images/uploads/` |
276
287
  | `github` (build default) | Contents API on `github.branch` | one commit via the Git Data API: blobs → tree → commit → ref; with `pullRequest: true` a new `site-editor/<timestamp>-<sha>` branch + PR instead | wait on a `pagestack-uploads` branch until the next save brings them along; the editor serves them, and anything committed since it was built, to signed-in editors |
277
288
 
289
+ ### Staging and Go live
290
+
291
+ With `github.live`, saves stay on `github.branch` (staging) and the public site builds from `live`.
292
+ Every screen gets a **Go live** button counting the saved changes the live site doesn't have yet;
293
+ it lists them, links to `github.stagingUrl` if you give one, and puts them all on `live` in one step.
294
+ That is a fast-forward when nobody committed to `live` directly. When someone did, it makes a merge
295
+ commit and moves staging to it; when their change conflicts, it refuses and says so, and a person
296
+ merges in GitHub. A burst of saves becomes one production build.
297
+
298
+ ```js
299
+ github: { repo: 'acme/site', branch: 'develop', live: 'main', stagingUrl: 'https://develop.acme.pages.dev/' }
300
+ ```
301
+
302
+ Point the host's production deploy at `live` and its preview deploys at the staging branch.
303
+
278
304
  The GitHub token (`GITHUB_TOKEN` or `EDITOR_GITHUB_TOKEN`) is read from the environment on the
279
305
  server only. A fine-grained token with *Contents: write* (and *Pull requests: write* for PR mode)
280
306
  on the one repo is enough. The host that runs the editor rebuilds and deploys from the commit
@@ -287,7 +313,7 @@ like any other push.
287
313
  - `editor-users.json` (committed, path configurable with `usersFile`) holds users and the
288
314
  **public keys** of their passkeys. Nothing in it is secret.
289
315
  - `EDITOR_SECRET` (≥ 16 chars, environment only) signs three kinds of short-lived tokens:
290
- WebAuthn challenges (5 min), the session cookie (`ase_session`, HttpOnly, SameSite=Lax, 12 h) and
316
+ WebAuthn challenges (5 min), the session cookie (`ps_session`, HttpOnly, SameSite=Lax, 12 h) and
291
317
  invite links (3 days). Tokens are `base64url(json).base64url(hmac-sha256)` with the expiry inside,
292
318
  so there is no server state.
293
319
  - **Invites** are single-use: the invite id is recorded on the credential it created. Make the first
@@ -340,8 +366,9 @@ editor response is `noindex` and `no-store`.
340
366
  | `usersFile` | `editor-users.json` | |
341
367
  | `auth` | `passkey` | `passkey` \| `none-behind-proxy` \| `none` |
342
368
  | `storage` | `local` in dev, `github` in build | |
343
- | `github` | — | `{ repo, branch, pullRequest }` |
344
- | `enabled` | dev, or `EDITOR=1` | |
369
+ | `github` | — | `{ repo, branch, live?, stagingUrl?, pullRequest? }`: see Staging and Go live |
370
+ | `previewScripts` | `'site'` | block-editor preview runs the site's own scripts only; `'all'` allows other origins too |
371
+ | `enabled` | `EDITOR=dev` (dev) or `EDITOR=1` | Off otherwise, so plain `astro dev` never writes content |
345
372
  | `siteName`, `secretEnv` | `Site editor`, `EDITOR_SECRET` | |
346
373
  | `reservedSlugs` | `[]` | URLs Add page must refuse, on top of the editor's own and `src/pages` |
347
374
  | `redirectsFile` | `public/_redirects` | Change URL appends here, only if the file exists |
package/index.mjs CHANGED
@@ -4,8 +4,8 @@
4
4
  // integrations: [sectionEditor({ renderer: './src/components/SectionPage.astro', sections: './src/sections/index.ts' })]
5
5
  //
6
6
  // The public site stays fully static. The editor (/edit/*, /api/editor/*) is on-demand rendered
7
- // and only exists when the integration is enabled: always in `astro dev`, and in `astro build`
8
- // when EDITOR=1 (which produces a Node server build with @astrojs/node).
7
+ // and only exists when the integration is enabled: `EDITOR=dev astro dev` (or EDITOR=1) locally, and
8
+ // `EDITOR=1 astro build` for a server build. Plain `astro dev` / `astro build` leave it out.
9
9
  import node from '@astrojs/node';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import fs from 'node:fs';
@@ -32,8 +32,12 @@ const route = (file) => new URL(`./src/routes/${file}`, import.meta.url);
32
32
  * @property {string} [usersFile='editor-users.json'] Passkey users (public keys only).
33
33
  * @property {'none'|'passkey'|'none-behind-proxy'} [auth='passkey']
34
34
  * @property {'local'|'github'} [storage] Defaults: local in dev, github in a build.
35
- * @property {{repo: string, branch?: string, pullRequest?: boolean}} [github]
36
- * @property {boolean} [enabled] Default: dev, or EDITOR=1.
35
+ * @property {{repo: string, branch?: string, pullRequest?: boolean, live?: string, stagingUrl?: string}} [github]
36
+ * `branch` is where saves go. With `live` (the branch the public site builds from), saves stay on
37
+ * `branch` as staging and a Go live button puts them on `live` in one step; `stagingUrl` links to
38
+ * a preview of the staging branch. `pullRequest` opens a PR per save instead.
39
+ * @property {'site'|'all'} [previewScripts='site'] Scripts in the block editor's preview: 'site' runs the site's own and blocks other origins (analytics, captchas, widgets); 'all' allows everything.
40
+ * @property {boolean} [enabled] Default: EDITOR=dev or EDITOR=1 (exact values: $EDITOR is also the shell's text editor). Off otherwise, in dev too.
37
41
  * @property {string} [siteName] Shown in the editor chrome.
38
42
  * @property {string} [interactiveSelector='summary'] Elements in the preview that keep their own click
39
43
  * behaviour (accordion summaries, tab titles, load-map buttons…). Everything else is
@@ -85,8 +89,9 @@ export default function sectionEditor(userOptions) {
85
89
  ...forwarded,
86
90
  'astro:config:setup': async (params) => {
87
91
  const { config, command, injectRoute, updateConfig, addMiddleware, logger } = params;
88
- const enabled = userOptions.enabled ?? (command === 'dev' || process.env.EDITOR === '1');
89
- if (!enabled) { logger.info('disabled (static build). Set EDITOR=1 to build the editor.'); return; }
92
+ const flag = process.env.EDITOR;
93
+ const enabled = userOptions.enabled ?? (flag === '1' || (command === 'dev' && flag === 'dev'));
94
+ if (!enabled) { logger.info(command === 'dev' ? 'off. Run with EDITOR=dev to edit at /edit.' : 'off (static build). Set EDITOR=1 to build the editor.'); return; }
90
95
  const isBuild = command === 'build';
91
96
  const options = {
92
97
  pagesDir: 'src/content/pages',
@@ -110,6 +115,12 @@ export default function sectionEditor(userOptions) {
110
115
  if (options.storage === 'github' && !options.github?.repo) {
111
116
  throw new Error('pagestack: storage "github" needs github.repo ("owner/name")');
112
117
  }
118
+ if (options.github?.live && options.github.live === (options.github.branch ?? 'main')) {
119
+ throw new Error('pagestack: github.live must differ from github.branch (saves go to branch, Go live moves them to live)');
120
+ }
121
+ if (options.github?.live && options.github.pullRequest) {
122
+ throw new Error('pagestack: use github.live or github.pullRequest, not both');
123
+ }
113
124
  const root = fileURLToPath(config.root);
114
125
  const abs = (p) => path.isAbsolute(p) ? p : path.resolve(root, p);
115
126
  const reservedSlugs = [...new Set([...(options.reservedSlugs ?? []), ...staticRoutes(fileURLToPath(config.srcDir))])];
@@ -170,6 +181,7 @@ export default function sectionEditor(userOptions) {
170
181
  injectRoute({ pattern: '/api/editor/images', entrypoint: route('api/images.ts'), prerender: false });
171
182
  injectRoute({ pattern: '/api/editor/collection/[id]/[...slug]', entrypoint: route('api/collection.ts'), prerender: false });
172
183
  injectRoute({ pattern: '/api/editor/users', entrypoint: route('api/users.ts'), prerender: false });
184
+ injectRoute({ pattern: '/api/editor/live', entrypoint: route('api/live.ts'), prerender: false });
173
185
  injectRoute({ pattern: '/api/editor/asset/[...path]', entrypoint: route('api/asset.ts'), prerender: false });
174
186
  injectRoute({ pattern: '/api/editor/auth/[action]', entrypoint: route('api/auth.ts'), prerender: false });
175
187
  // Uploads saved after this editor was built aren't static files in it; serve them from the repo.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pirateandfox/pagestack",
3
- "version": "0.1.0-beta.7",
3
+ "version": "0.1.0-beta.8",
4
4
  "description": "PageStack: visual section editor for Astro sites. Git-only, static public site, passkey login, saves are commits.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,9 +1,9 @@
1
1
  // Browser side of passkey login / enrolment (login.astro, enroll.astro).
2
2
  import { browserSupportsWebAuthn, startAuthentication, startRegistration } from '@simplewebauthn/browser';
3
3
 
4
- const root = document.querySelector<HTMLElement>('[data-ase-auth]')!;
5
- const go = document.getElementById('ase-auth-go') as HTMLButtonElement | null;
6
- const errEl = document.getElementById('ase-auth-error')!;
4
+ const root = document.querySelector<HTMLElement>('[data-ps-auth]')!;
5
+ const go = document.getElementById('ps-auth-go') as HTMLButtonElement | null;
6
+ const errEl = document.getElementById('ps-auth-error')!;
7
7
  const fail = (msg: string) => { errEl.textContent = msg; errEl.hidden = false; if (go) go.disabled = false; };
8
8
  const post = async (action: string, body: unknown) => {
9
9
  const res = await fetch(`/api/editor/auth/${action}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
@@ -16,7 +16,7 @@ if (!browserSupportsWebAuthn()) fail('This browser does not support passkeys.');
16
16
  else if (go) go.addEventListener('click', async () => {
17
17
  go.disabled = true; errEl.hidden = true;
18
18
  try {
19
- if (root.dataset.aseAuth === 'login') {
19
+ if (root.dataset.psAuth === 'login') {
20
20
  const { options, token } = await post('login-options', {});
21
21
  const response = await startAuthentication({ optionsJSON: options });
22
22
  const { next } = await post('login-verify', { token, response, next: root.dataset.next });
@@ -24,7 +24,7 @@ else if (go) go.addEventListener('click', async () => {
24
24
  } else {
25
25
  const { options, token } = await post('register-options', { invite: root.dataset.invite });
26
26
  const response = await startRegistration({ optionsJSON: options });
27
- const label = (document.getElementById('ase-auth-label') as HTMLInputElement | null)?.value;
27
+ const label = (document.getElementById('ps-auth-label') as HTMLInputElement | null)?.value;
28
28
  await post('register-verify', { token, response, label });
29
29
  location.assign('/edit');
30
30
  }
@@ -2,10 +2,10 @@
2
2
  import { slugify, uniqueSlug } from '../core/pages';
3
3
  import { confirmDialog, promptDialog, toast } from './ui';
4
4
 
5
- const boot = (window as any).__ASE_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[] };
5
+ const boot = (window as any).__PS_COLLECTION__ as { id: string; singular: string; slugs: string[]; reserved: string[] };
6
6
  const api = `/api/editor/collection/${boot.id}`;
7
7
 
8
- document.getElementById('ase-add-item')?.addEventListener('click', async () => {
8
+ document.getElementById('ps-add-item')?.addEventListener('click', async () => {
9
9
  const title = await promptDialog({ title: `Add ${boot.singular}`, label: 'Title', submit: `Add ${boot.singular}` });
10
10
  if (!title) return;
11
11
  const slug = uniqueSlug(slugify(title) || boot.singular, [...boot.slugs, ...boot.reserved]);
@@ -15,7 +15,7 @@ document.getElementById('ase-add-item')?.addEventListener('click', async () => {
15
15
  location.href = `/edit/collection/${boot.id}/${data.slug}`;
16
16
  });
17
17
 
18
- document.getElementById('ase-pagelist')!.addEventListener('click', async (e) => {
18
+ document.getElementById('ps-pagelist')!.addEventListener('click', async (e) => {
19
19
  const b = (e.target as HTMLElement).closest<HTMLElement>('[data-delete]');
20
20
  if (!b) return;
21
21
  const row = b.closest('li')!;
@@ -28,10 +28,10 @@ document.getElementById('ase-pagelist')!.addEventListener('click', async (e) =>
28
28
  toast(`Deleted ${name}.`, 'ok');
29
29
  });
30
30
 
31
- const search = document.getElementById('ase-page-search') as HTMLInputElement;
31
+ const search = document.getElementById('ps-page-search') as HTMLInputElement;
32
32
  search.addEventListener('input', () => {
33
33
  const q = search.value.trim().toLowerCase();
34
34
  let shown = 0;
35
- document.querySelectorAll<HTMLElement>('#ase-pagelist > li').forEach((li) => { const on = li.dataset.search!.includes(q); li.hidden = !on; if (on) shown++; });
36
- document.getElementById('ase-no-match')!.hidden = shown > 0;
35
+ document.querySelectorAll<HTMLElement>('#ps-pagelist > li').forEach((li) => { const on = li.dataset.search!.includes(q); li.hidden = !on; if (on) shown++; });
36
+ document.getElementById('ps-no-match')!.hidden = shown > 0;
37
37
  });