uncial-cms 5.1.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +61 -16
  2. package/dist/astro/index.d.ts +2 -1
  3. package/dist/astro/index.js +7 -2
  4. package/dist/content-sources.d.ts +10 -0
  5. package/dist/content-sources.js +25 -1
  6. package/dist/dashboard/ConfirmDialog.svelte +76 -0
  7. package/dist/dashboard/ConfirmDialog.svelte.d.ts +10 -0
  8. package/dist/dashboard/Dashboard.svelte +639 -0
  9. package/dist/dashboard/Dashboard.svelte.d.ts +4 -0
  10. package/dist/dashboard/FallbackEditor.svelte +42 -0
  11. package/dist/dashboard/FallbackEditor.svelte.d.ts +14 -0
  12. package/dist/dashboard/GlobalForm.svelte +405 -0
  13. package/dist/dashboard/GlobalForm.svelte.d.ts +17 -0
  14. package/dist/dashboard/GlobalsList.svelte +62 -0
  15. package/dist/dashboard/GlobalsList.svelte.d.ts +7 -0
  16. package/dist/dashboard/MediaSection.svelte +221 -0
  17. package/dist/dashboard/MediaSection.svelte.d.ts +16 -0
  18. package/dist/dashboard/PagesSection.svelte +477 -0
  19. package/dist/dashboard/PagesSection.svelte.d.ts +23 -0
  20. package/dist/dashboard/element.d.ts +39 -0
  21. package/dist/dashboard/element.js +107 -0
  22. package/dist/dashboard/pages-list.d.ts +18 -0
  23. package/dist/dashboard/pages-list.js +29 -0
  24. package/dist/dashboard/routes.d.ts +25 -0
  25. package/dist/dashboard/routes.js +81 -0
  26. package/dist/dashboard/types.d.ts +32 -0
  27. package/dist/dashboard/types.js +1 -0
  28. package/dist/define-site.d.ts +11 -6
  29. package/dist/define-site.js +4 -7
  30. package/dist/editor-controller.d.ts +1 -0
  31. package/dist/editor-controller.js +1 -0
  32. package/dist/editor-session.d.ts +5 -0
  33. package/dist/editor-session.js +1 -1
  34. package/dist/errors.d.ts +13 -0
  35. package/dist/errors.js +14 -0
  36. package/dist/globals.d.ts +12 -0
  37. package/dist/globals.js +29 -0
  38. package/dist/image-source.d.ts +0 -10
  39. package/dist/image-source.js +15 -44
  40. package/dist/index-actions.d.ts +29 -2
  41. package/dist/index-actions.js +36 -4
  42. package/dist/index-page.d.ts +2 -0
  43. package/dist/index-page.js +6 -256
  44. package/dist/index.d.ts +5 -2
  45. package/dist/index.js +3 -2
  46. package/dist/media-source.d.ts +45 -0
  47. package/dist/media-source.js +113 -0
  48. package/dist/mount.d.ts +1 -0
  49. package/dist/mount.js +2 -0
  50. package/dist/server/handlers.d.ts +1 -1
  51. package/dist/server/handlers.js +32 -5
  52. package/dist/server/index.d.ts +2 -1
  53. package/dist/server/index.js +2 -1
  54. package/dist/server/media.d.ts +1 -10
  55. package/dist/server/media.js +7 -11
  56. package/dist/server/postgres-store.d.ts +5 -0
  57. package/dist/server/postgres-store.js +50 -5
  58. package/dist/server-forge/adapter.d.ts +1 -0
  59. package/dist/server-forge/adapter.js +7 -4
  60. package/dist/server-forge/protocol.d.ts +3 -1
  61. package/dist/server-forge/protocol.js +2 -1
  62. package/dist/svelte/MediaLibrary.svelte +109 -53
  63. package/dist/svelte/MediaLibrary.svelte.d.ts +10 -2
  64. package/dist/svelte/index.d.ts +1 -4
  65. package/dist/svelte/index.js +1 -4
  66. package/dist/sveltekit/index.d.ts +2 -1
  67. package/dist/sveltekit/index.js +7 -2
  68. package/package.json +12 -3
@@ -1,258 +1,8 @@
1
- /**
2
- * `/uncial/` site-index runtime (PRD §6.6, D2): list/create/delete pages and
3
- * the hash-routed fallback editor (`#/<path>/`). Framework-agnostic plain DOM,
4
- * same style as mountEditorPage — the SvelteKit index route is just a shell
5
- * that calls this.
6
- */
7
- import { createPage, deletePage, listPages } from './index-actions.js';
8
- import { mountEditorPage } from './mount.js';
9
- import { defaultMapPathToSource, hashForPagePath, pagePathFromHash, validatePagePath } from './paths/index.js';
10
- import { defaultSessionProvider, forgeAdapter } from './editor-session.js';
11
- import { describeContentStatus } from './server-forge/protocol.js';
12
- import { UNCIAL_CMS_RUNTIME_SENTINEL } from './sentinel.js';
1
+ import { UncialDashboardElement } from './dashboard/element.js';
2
+ /** @deprecated Render `<uncial-dashboard>`; this mounts it showing only Pages. */
13
3
  export function mountIndexPage(target, opts) {
14
- const { config, basePath = '' } = opts;
15
- const sessionProvider = opts.sessionProvider ?? defaultSessionProvider(config);
16
- const branchLabel = config.forge === 'github'
17
- ? config.branch
18
- : config.forge === 'server'
19
- ? 'the server'
20
- : 'the local checkout';
21
- const locationLabel = config.forge === 'github' ? `${config.repo}@${config.branch}` : branchLabel;
22
- // A server record's path is the site path with its surrounding slashes ('/' = site root).
23
- const mapPathToSource = opts.mapPathToSource ??
24
- (config.forge === 'server'
25
- ? (path) => (path === '' ? '/' : `/${path}/`)
26
- : (path) => defaultMapPathToSource(path, config.contentDir));
27
- const editHref = opts.editorHref ?? hashForPagePath;
28
- const root = document.createElement('div');
29
- root.className = 'uncial-cms-index';
30
- root.dataset.uncialCmsRuntime = UNCIAL_CMS_RUNTIME_SENTINEL;
31
- const status = document.createElement('p');
32
- status.className = 'uncial-cms-status';
33
- status.setAttribute('role', 'status');
34
- const listView = document.createElement('section');
35
- listView.className = 'uncial-cms-index-list';
36
- const editorView = document.createElement('section');
37
- editorView.className = 'uncial-cms-fallback-editor';
38
- editorView.hidden = true;
39
- const signInButton = document.createElement('button');
40
- signInButton.type = 'button';
41
- signInButton.className = 'uncial-cms-sign-in';
42
- signInButton.textContent = 'Sign in';
43
- signInButton.hidden = true;
44
- root.append(status, signInButton, listView, editorView);
45
- target.append(root);
46
- let destroyed = false;
47
- let adapter = null;
48
- let session = null;
49
- let editorHandle = null;
50
- let currentHash = location.hash;
51
- let revertingHash = false;
52
- const setStatus = (text) => {
53
- status.textContent = text;
54
- };
55
- const livePageUrl = (pagePath) => `${basePath}/${pagePath === '' ? '' : `${pagePath}/`}`;
56
- const renderList = (pages) => {
57
- listView.replaceChildren();
58
- const heading = document.createElement('h2');
59
- heading.textContent = 'Pages';
60
- const list = document.createElement('ul');
61
- for (const page of pages) {
62
- const item = document.createElement('li');
63
- const live = document.createElement('a');
64
- live.href = livePageUrl(page.pagePath);
65
- live.textContent = page.pagePath === '' ? '(site root)' : `/${page.pagePath}/`;
66
- // Always link the fallback editor — it works whether or not the page's
67
- // static variant has deployed yet.
68
- const edit = document.createElement('a');
69
- edit.href = editHref(page.pagePath);
70
- edit.textContent = 'Edit';
71
- const del = document.createElement('button');
72
- del.type = 'button';
73
- del.textContent = 'Delete';
74
- del.addEventListener('click', () => void onDelete(page));
75
- item.append(live, ' ');
76
- if (page.status) {
77
- const status = document.createElement('span');
78
- status.className = 'uncial-cms-index-status';
79
- status.textContent = page.status;
80
- item.append(status, ' ');
81
- }
82
- item.append(edit, ' ', del);
83
- list.append(item);
84
- }
85
- const form = document.createElement('form');
86
- form.className = 'uncial-cms-create';
87
- const label = document.createElement('label');
88
- label.textContent = 'New page path ';
89
- const input = document.createElement('input');
90
- input.name = 'path';
91
- input.placeholder = 'team/new-page';
92
- label.append(input);
93
- const submit = document.createElement('button');
94
- submit.type = 'submit';
95
- submit.textContent = 'Create page';
96
- const message = document.createElement('p');
97
- message.className = 'uncial-cms-create-message';
98
- message.setAttribute('role', 'alert');
99
- message.hidden = true;
100
- form.append(label, ' ', submit, message);
101
- form.addEventListener('submit', (event) => {
102
- event.preventDefault();
103
- void onCreate(input.value, message, submit);
104
- });
105
- listView.append(heading, list, form);
106
- };
107
- const refreshList = async () => {
108
- if (!adapter)
109
- return;
110
- setStatus('Loading pages…');
111
- const pages = config.forge === 'server'
112
- ? (await adapter.list()).map((record) => ({
113
- pagePath: opts.mapSourceToPath?.(record.path) ?? record.path.replace(/^\/+|\/+$/g, ''),
114
- sourcePath: record.path,
115
- status: describeContentStatus(record.status)
116
- }))
117
- : await listPages(adapter, config.contentDir, opts.mapSourceToPath);
118
- if (destroyed)
119
- return;
120
- renderList(pages);
121
- setStatus(`Editing ${locationLabel} as ${session.user.login}`);
122
- };
123
- const onCreate = async (raw, message, submit) => {
124
- const result = validatePagePath(raw);
125
- if (!result.ok) {
126
- message.hidden = false;
127
- message.textContent = result.message;
128
- return;
129
- }
130
- if (!adapter || !session)
131
- return;
132
- message.hidden = true;
133
- submit.disabled = true;
134
- try {
135
- await createPage({ adapter, blocks: opts.blocks, schema: opts.schema, author: session.user }, { pagePath: result.path, sourcePath: mapPathToSource(result.path) });
136
- // Open the fallback editor immediately — the static variant only
137
- // appears after the next deploy.
138
- if (opts.editorHref)
139
- location.assign(opts.editorHref(result.path));
140
- else
141
- location.hash = hashForPagePath(result.path);
142
- }
143
- catch (error) {
144
- message.hidden = false;
145
- message.textContent = error instanceof Error ? error.message : 'Create failed.';
146
- }
147
- finally {
148
- submit.disabled = false;
149
- }
150
- };
151
- const onDelete = async (page) => {
152
- if (!adapter)
153
- return;
154
- const confirmed = window.confirm(`Delete ${page.sourcePath} from ${branchLabel}? ` +
155
- (config.forge === 'server' ? 'This cannot be undone.' : 'This commits the deletion immediately.'));
156
- if (!confirmed)
157
- return;
158
- try {
159
- await deletePage(adapter, page);
160
- await refreshList();
161
- }
162
- catch (error) {
163
- setStatus(error instanceof Error ? error.message : 'Delete failed.');
164
- }
165
- };
166
- const closeEditor = () => {
167
- editorHandle?.destroy();
168
- editorHandle = null;
169
- editorView.replaceChildren();
170
- editorView.hidden = true;
171
- listView.hidden = false;
172
- };
173
- const openEditor = (pagePath) => {
174
- closeEditor();
175
- listView.hidden = true;
176
- editorView.hidden = false;
177
- const back = document.createElement('a');
178
- back.href = '#';
179
- back.textContent = '← Back to index';
180
- const heading = document.createElement('h2');
181
- heading.textContent = pagePath === '' ? 'Editing site root' : `Editing /${pagePath}/`;
182
- const mountTarget = document.createElement('div');
183
- editorView.append(back, heading, mountTarget);
184
- editorHandle = mountEditorPage(mountTarget, {
185
- config,
186
- sourcePath: mapPathToSource(pagePath),
187
- pagePath,
188
- blocks: opts.blocks,
189
- schema: opts.schema,
190
- sessionProvider,
191
- editorStylesheets: opts.editorStylesheets
192
- });
193
- };
194
- const applyHash = () => {
195
- const pagePath = pagePathFromHash(location.hash);
196
- if (pagePath === null) {
197
- closeEditor();
198
- void refreshList().catch((error) => {
199
- setStatus(error instanceof Error ? error.message : 'Failed to list pages.');
200
- });
201
- }
202
- else {
203
- openEditor(pagePath);
204
- }
205
- currentHash = location.hash;
206
- };
207
- const onHashChange = () => {
208
- if (revertingHash) {
209
- revertingHash = false;
210
- return;
211
- }
212
- if (editorHandle?.isDirty() && !window.confirm('Discard unsaved changes?')) {
213
- revertingHash = true;
214
- location.hash = currentHash;
215
- return;
216
- }
217
- applyHash();
218
- };
219
- const onBeforeUnload = (event) => {
220
- if (editorHandle?.isDirty())
221
- event.preventDefault();
222
- };
223
- window.addEventListener('hashchange', onHashChange);
224
- window.addEventListener('beforeunload', onBeforeUnload);
225
- const load = async () => {
226
- setStatus('Signing in…');
227
- adapter = forgeAdapter(config);
228
- session = await adapter.authenticate(config, sessionProvider);
229
- if (destroyed)
230
- return;
231
- applyHash();
232
- };
233
- // The first attempt runs outside a click, where browsers block the sign-in
234
- // popup, so a failed sign-in is retried from a button.
235
- const signIn = async () => {
236
- signInButton.hidden = true;
237
- try {
238
- await load();
239
- }
240
- catch (error) {
241
- if (destroyed)
242
- return;
243
- setStatus(error instanceof Error ? error.message : 'Failed to load the site index.');
244
- signInButton.hidden = false;
245
- }
246
- };
247
- signInButton.addEventListener('click', () => void signIn());
248
- void signIn();
249
- return {
250
- destroy() {
251
- destroyed = true;
252
- window.removeEventListener('hashchange', onHashChange);
253
- window.removeEventListener('beforeunload', onBeforeUnload);
254
- editorHandle?.destroy();
255
- root.remove();
256
- }
257
- };
4
+ const element = new UncialDashboardElement();
5
+ Object.assign(element, opts, { sections: ['pages'] });
6
+ target.append(element);
7
+ return { destroy: () => element.remove() };
258
8
  }
package/dist/index.d.ts CHANGED
@@ -1,15 +1,18 @@
1
1
  export type { ForgeAdapter, ForgeSession, GitHubSiteConfig, ServerSiteConfig, SessionProvider, UncialCmsSiteConfig } from './types.js';
2
2
  export { defineServerSite, defineSite, DEFAULT_APP_SLUG, DEFAULT_AUTH_WORKER_URL, type ServerSiteOptions, type Site, type SiteOptions } from './define-site.js';
3
- export { ConflictError, NotFoundError } from './errors.js';
3
+ export { ConflictError, MediaInUseError, NotFoundError } from './errors.js';
4
4
  export { UNCIAL_CMS_RUNTIME_SENTINEL } from './sentinel.js';
5
5
  export { mountEditorPage, type MountEditorPageOptions } from './mount.js';
6
6
  export { createEditorSession, defaultSessionProvider, forgeAdapter, type CreateEditorSessionOptions } from './editor-session.js';
7
7
  export { createEditorController, conflictDownloadFilename, type DownloadPayload, type EditorController, type EditorControllerOptions, type EditorPageUi, type RecordState, type StatusView } from './editor-controller.js';
8
8
  export { mountIndexPage, type MountIndexPageOptions } from './index-page.js';
9
- export { createPage, deletePage, listPages, uploadAsset, uploadImageAsset, type PageRef, type UploadAssetFile, type UploadAssetOptions, type UploadAssetResult, type UploadImageAssetOptions } from './index-actions.js';
9
+ export type { UncialDashboardElement } from './dashboard/element.js';
10
+ export type { DashboardAction, DashboardOptions } from './dashboard/types.js';
11
+ export { createPage, deletePage, listPages, saveGlobal, uploadAsset, uploadImageAsset, type PageRef, type SaveGlobalDeps, type UploadAssetFile, type UploadAssetOptions, type UploadAssetResult, type UploadImageAssetOptions } from './index-actions.js';
10
12
  export { fitImage, type FitOptions, type FittedImage, type ImageEncoder, type EncodableImage } from './fit-image.js';
11
13
  export { servedUrl } from './served-url.js';
12
14
  export { cmsImageSource } from './image-source.js';
15
+ export { mediaSourceFor, type MediaItem, type MediaSource } from './media-source.js';
13
16
  export { MAX_CONTENT_BYTES } from './constants.js';
14
17
  export { hashForPagePath, pagePathFromHash, validatePagePath } from './paths/index.js';
15
18
  export { parseDocument, serializeDocument, type Blocks } from './document.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { defineServerSite, defineSite, DEFAULT_APP_SLUG, DEFAULT_AUTH_WORKER_URL } from './define-site.js';
2
- export { ConflictError, NotFoundError } from './errors.js';
2
+ export { ConflictError, MediaInUseError, NotFoundError } from './errors.js';
3
3
  export { UNCIAL_CMS_RUNTIME_SENTINEL } from './sentinel.js';
4
4
  export { mountEditorPage } from './mount.js';
5
5
  /*
@@ -12,10 +12,11 @@ export { mountEditorPage } from './mount.js';
12
12
  export { createEditorSession, defaultSessionProvider, forgeAdapter } from './editor-session.js';
13
13
  export { createEditorController, conflictDownloadFilename } from './editor-controller.js';
14
14
  export { mountIndexPage } from './index-page.js';
15
- export { createPage, deletePage, listPages, uploadAsset, uploadImageAsset } from './index-actions.js';
15
+ export { createPage, deletePage, listPages, saveGlobal, uploadAsset, uploadImageAsset } from './index-actions.js';
16
16
  export { fitImage } from './fit-image.js';
17
17
  export { servedUrl } from './served-url.js';
18
18
  export { cmsImageSource } from './image-source.js';
19
+ export { mediaSourceFor } from './media-source.js';
19
20
  export { MAX_CONTENT_BYTES } from './constants.js';
20
21
  export { hashForPagePath, pagePathFromHash, validatePagePath } from './paths/index.js';
21
22
  export { parseDocument, serializeDocument } from './document.js';
@@ -0,0 +1,45 @@
1
+ import type { Action } from './server-forge/protocol.js';
2
+ import type { ForgeAdapter, UncialCmsSiteConfig } from './types.js';
3
+ export interface MediaSource {
4
+ capabilities: {
5
+ metadata: boolean;
6
+ usage: boolean;
7
+ delete: boolean;
8
+ search: boolean;
9
+ };
10
+ list(query?: {
11
+ search?: string;
12
+ contentType?: string;
13
+ }): Promise<MediaItem[]>;
14
+ upload(file: File, opts?: {
15
+ title?: string;
16
+ }): Promise<MediaItem>;
17
+ delete(item: MediaItem): Promise<void>;
18
+ }
19
+ export interface MediaItem {
20
+ id: string;
21
+ /** What a Content document stores as `src`: base-less on git forges. */
22
+ url: string;
23
+ filename: string;
24
+ contentType: string;
25
+ size?: number;
26
+ width?: number;
27
+ height?: number;
28
+ title?: string;
29
+ uploadedAt?: string;
30
+ uploadedBy?: string;
31
+ usage?: Array<{
32
+ path: string;
33
+ title?: string;
34
+ }>;
35
+ }
36
+ export declare function serverMediaSource(apiBase: string, onAllowed?: (allowed: Action[]) => void): MediaSource;
37
+ export declare function mediaSourceFor(config: UncialCmsSiteConfig, session?: {
38
+ adapter: ForgeAdapter;
39
+ author: {
40
+ name: string;
41
+ email: string;
42
+ };
43
+ }, opts?: {
44
+ staticDir?: string;
45
+ }): MediaSource;
@@ -0,0 +1,113 @@
1
+ import { fitImage } from './fit-image.js';
2
+ import { uploadAsset } from './index-actions.js';
3
+ import { servedUrl } from './served-url.js';
4
+ import { deleteMedia, listMedia, uploadMedia } from './server-forge/media.js';
5
+ import { configMediaDir } from './upload-context.js';
6
+ const CONTENT_TYPES = {
7
+ png: 'image/png',
8
+ jpg: 'image/jpeg',
9
+ jpeg: 'image/jpeg',
10
+ gif: 'image/gif',
11
+ webp: 'image/webp',
12
+ avif: 'image/avif',
13
+ svg: 'image/svg+xml'
14
+ };
15
+ function matchesType(contentType, pattern) {
16
+ if (!pattern)
17
+ return true;
18
+ return pattern.endsWith('/*')
19
+ ? contentType.startsWith(pattern.slice(0, -1))
20
+ : contentType === pattern;
21
+ }
22
+ function gitMediaSource(opts) {
23
+ const { adapter, author, config, mediaDir, staticDir } = opts;
24
+ const item = (path) => {
25
+ const filename = path.slice(path.lastIndexOf('/') + 1);
26
+ const extension = filename.slice(filename.lastIndexOf('.') + 1).toLowerCase();
27
+ return {
28
+ id: path,
29
+ url: servedUrl({ config }, path, staticDir),
30
+ filename,
31
+ contentType: CONTENT_TYPES[extension] ?? 'application/octet-stream'
32
+ };
33
+ };
34
+ return {
35
+ capabilities: { metadata: false, usage: false, delete: true, search: false },
36
+ async list({ contentType } = {}) {
37
+ const entries = await adapter.listDir(mediaDir);
38
+ return entries
39
+ .filter((entry) => entry.type === 'file')
40
+ .map((entry) => entry.path)
41
+ .sort()
42
+ .map(item)
43
+ .filter((media) => matchesType(media.contentType, contentType));
44
+ },
45
+ async upload(file) {
46
+ const raster = file.type.startsWith('image/') && file.type !== 'image/svg+xml';
47
+ const asset = raster
48
+ ? await fitImage(file)
49
+ : {
50
+ bytes: new Uint8Array(await file.arrayBuffer()),
51
+ filename: file.name,
52
+ contentType: file.type || 'application/octet-stream'
53
+ };
54
+ const { path } = await uploadAsset({ adapter }, asset, { mediaDir, author });
55
+ return item(path);
56
+ },
57
+ async delete(media) {
58
+ // The forge deletes at a blob sha, which a listing does not carry.
59
+ const { sha } = await adapter.readFile(media.id);
60
+ await adapter.deleteFile(media.id, { message: `uncial-cms: delete ${media.id}`, sha });
61
+ }
62
+ };
63
+ }
64
+ function fromView(item) {
65
+ return {
66
+ id: item.id,
67
+ url: item.url,
68
+ filename: item.filename,
69
+ contentType: item.contentType,
70
+ size: item.size,
71
+ width: item.width ?? undefined,
72
+ height: item.height ?? undefined,
73
+ title: item.title,
74
+ uploadedAt: item.uploadedAt,
75
+ uploadedBy: item.uploadedBy
76
+ };
77
+ }
78
+ export function serverMediaSource(apiBase, onAllowed) {
79
+ return {
80
+ capabilities: { metadata: true, usage: true, delete: true, search: true },
81
+ async list(query) {
82
+ const view = await listMedia(apiBase, query);
83
+ onAllowed?.(view.allowed);
84
+ return view.items.map((item) => ({
85
+ ...fromView(item),
86
+ usage: item.usagePaths.map((path) => ({ path }))
87
+ }));
88
+ },
89
+ upload: async (file, opts) => fromView(await uploadMedia(apiBase, file, opts)),
90
+ delete: (item) => deleteMedia(apiBase, item.id)
91
+ };
92
+ }
93
+ export function mediaSourceFor(config, session, opts = {}) {
94
+ if (config.forge === 'server') {
95
+ if (!config.mediaApiBase) {
96
+ throw new Error('This server site sets no `mediaApiBase`, so it has no Media library.');
97
+ }
98
+ return serverMediaSource(config.mediaApiBase);
99
+ }
100
+ if (!session) {
101
+ throw new Error('A git forge reaches its media through a signed-in editing session.');
102
+ }
103
+ const mediaDir = configMediaDir(config);
104
+ if (!mediaDir)
105
+ throw new Error('No media directory: set `mediaDir` in the site config.');
106
+ return gitMediaSource({
107
+ adapter: session.adapter,
108
+ author: session.author,
109
+ config,
110
+ mediaDir,
111
+ staticDir: opts.staticDir ?? 'static'
112
+ });
113
+ }
package/dist/mount.d.ts CHANGED
@@ -38,6 +38,7 @@ export interface MountEditorPageOptions {
38
38
  editorStylesheets?: string[];
39
39
  /** Where `input: 'image'` fields get images; defaults to `cmsImageSource(config)`. */
40
40
  imageSource?: UncialEditorElement['imageSource'];
41
+ onerror?: (error: unknown) => void;
41
42
  }
42
43
  export declare function mountEditorPage(target: HTMLElement, opts: MountEditorPageOptions): {
43
44
  destroy(): void;
package/dist/mount.js CHANGED
@@ -86,6 +86,7 @@ export function mountEditorPage(target, opts) {
86
86
  target.append(root);
87
87
  let destroyed = false;
88
88
  const ui = {
89
+ failed: opts.onerror,
89
90
  status(view) {
90
91
  status.replaceChildren(document.createTextNode(view.text));
91
92
  status.dataset.tone = view.tone;
@@ -136,6 +137,7 @@ export function mountEditorPage(target, opts) {
136
137
  void controller.load().catch((error) => {
137
138
  if (destroyed)
138
139
  return;
140
+ opts.onerror?.(error);
139
141
  ui.status({
140
142
  tone: 'error',
141
143
  text: error instanceof Error ? error.message : 'Failed to load the document.'
@@ -1,5 +1,5 @@
1
1
  import { type Action, type ServerUser } from '../server-forge/protocol.js';
2
- import { type MediaLibrary } from './media.js';
2
+ import type { MediaLibrary } from './media.js';
3
3
  import type { ContentRecord, ContentStore } from './postgres-store.js';
4
4
  export type { Action, ServerUser };
5
5
  export type Authorize = (user: ServerUser | null, action: Action, record: ContentRecord | null) => boolean | Promise<boolean>;
@@ -1,6 +1,6 @@
1
- import { ConflictError, NotFoundError } from '../errors.js';
1
+ import { ConflictError, MediaInUseError, NotFoundError } from '../errors.js';
2
+ import { assertPagePath, GLOBAL_KIND, GLOBAL_NAME, globalRecordPath } from '../globals.js';
2
3
  import { ACTIONS, contentStatus } from '../server-forge/protocol.js';
3
- import { MediaInUseError } from './media.js';
4
4
  class HttpError extends Error {
5
5
  status;
6
6
  constructor(status, message) {
@@ -31,9 +31,20 @@ function text(value, name) {
31
31
  throw new HttpError(400, `Expected a string "${name}".`);
32
32
  return value;
33
33
  }
34
+ function pagePath(path) {
35
+ try {
36
+ assertPagePath(path);
37
+ return path;
38
+ }
39
+ catch (error) {
40
+ throw new HttpError(400, error.message);
41
+ }
42
+ }
34
43
  function summary(record) {
44
+ const { meta } = (record.draft ?? record.published ?? {});
35
45
  return {
36
46
  path: record.path,
47
+ title: typeof meta?.title === 'string' ? meta.title : undefined,
37
48
  kind: record.kind,
38
49
  status: contentStatus(record.draft !== null, record.published !== null),
39
50
  publishedAt: record.publishedAt?.toISOString() ?? null,
@@ -109,10 +120,24 @@ export function createServerContentHandlers(opts) {
109
120
  }),
110
121
  POST: handle(async ({ request }, user) => {
111
122
  const input = await body(request);
112
- const path = text(input.path, 'path');
123
+ if (input.action === 'global-edit') {
124
+ const name = text(input.name, 'name');
125
+ if (!GLOBAL_NAME.test(name))
126
+ throw new HttpError(400, `"${name}" is not a Global name.`);
127
+ await guard(user, 'global-edit', await store.get(globalRecordPath(name)));
128
+ const etag = input.etag === undefined ? undefined : text(input.etag, 'etag');
129
+ const record = await store.publishGlobal(name, input.document, {
130
+ etag,
131
+ author: user.email
132
+ });
133
+ return view(user, record, etag === undefined ? 201 : 200);
134
+ }
135
+ const path = pagePath(text(input.path, 'path'));
113
136
  if (input.action === 'create') {
114
137
  await guard(user, 'create', null);
115
138
  const kind = input.kind === undefined ? 'page' : text(input.kind, 'kind');
139
+ if (kind === GLOBAL_KIND)
140
+ throw new HttpError(400, 'Globals are saved with global-edit.');
116
141
  return view(user, await store.create(path, kind, input.draft, { author: user.email }), 201);
117
142
  }
118
143
  if (input.action === 'publish' || input.action === 'unpublish') {
@@ -139,6 +164,7 @@ export function createServerContentHandlers(opts) {
139
164
  const to = opts.normalizePath ? opts.normalizePath(requested) : requested;
140
165
  if (to === null)
141
166
  throw new HttpError(400, `${requested} is not a path content can live at.`);
167
+ pagePath(to);
142
168
  if (opts.derivePath?.(record.kind, record.draft ?? record.published)) {
143
169
  throw new HttpError(400, `The path of ${path} follows its metadata; edit that instead.`);
144
170
  }
@@ -150,15 +176,16 @@ export function createServerContentHandlers(opts) {
150
176
  const write = { etag: text(input.etag, 'etag'), author: user.email };
151
177
  return view(user, await store.move(path, to, write));
152
178
  }
153
- throw new HttpError(400, 'Expected "action" to be create, publish, unpublish, restore or move.');
179
+ throw new HttpError(400, 'Expected "action" to be create, publish, unpublish, restore, move or global-edit.');
154
180
  }),
155
181
  PUT: handle(async ({ request }, user) => {
156
182
  const input = await body(request);
157
- const path = text(input.path, 'path');
183
+ const path = pagePath(text(input.path, 'path'));
158
184
  const record = await existing(path);
159
185
  await guard(user, 'save-draft', record);
160
186
  const etag = text(input.etag, 'etag');
161
187
  const target = opts.derivePath?.(record.kind, input.draft) ?? path;
188
+ pagePath(target);
162
189
  if (target !== path) {
163
190
  await guard(user, 'move', record);
164
191
  if (await store.get(target)) {
@@ -1,5 +1,6 @@
1
1
  export { createPostgresContentStore } from './postgres-store.js';
2
2
  export type { ContentRecord, ContentStore, OnMove, RetentionPolicy, VersionSummary } from './postgres-store.js';
3
3
  export { contentStoreMigrations, mediaLibraryMigrations } from './migrations.js';
4
- export { createMediaLibrary, MediaInUseError, type MediaItem, type MediaLibrary, type MediaLibraryOptions } from './media.js';
4
+ export { MediaInUseError } from '../errors.js';
5
+ export { createMediaLibrary, type MediaItem, type MediaLibrary, type MediaLibraryOptions } from './media.js';
5
6
  export { createServerContentHandlers, createServerMediaHandlers, type Action, type Authorize, type ServerContentHandlerOptions, type ServerMediaHandlerOptions, type ServerUser } from './handlers.js';
@@ -1,4 +1,5 @@
1
1
  export { createPostgresContentStore } from './postgres-store.js';
2
2
  export { contentStoreMigrations, mediaLibraryMigrations } from './migrations.js';
3
- export { createMediaLibrary, MediaInUseError } from './media.js';
3
+ export { MediaInUseError } from '../errors.js';
4
+ export { createMediaLibrary } from './media.js';
4
5
  export { createServerContentHandlers, createServerMediaHandlers } from './handlers.js';
@@ -33,6 +33,7 @@ export interface MediaLibrary {
33
33
  contentType?: string;
34
34
  }): Promise<Array<MediaItem & {
35
35
  usage: number;
36
+ usagePaths: string[];
36
37
  }>>;
37
38
  upload(bytes: Uint8Array, meta: {
38
39
  filename: string;
@@ -46,16 +47,6 @@ export interface MediaLibrary {
46
47
  }>;
47
48
  delete(id: string): Promise<void>;
48
49
  }
49
- export declare class MediaInUseError extends Error {
50
- readonly usage: {
51
- count: number;
52
- paths: string[];
53
- };
54
- constructor(usage: {
55
- count: number;
56
- paths: string[];
57
- });
58
- }
59
50
  /** Reads width and height from a PNG, GIF, WebP or JPEG header; null for anything else. */
60
51
  export declare function imageSize(bytes: Uint8Array): {
61
52
  width: number;
@@ -1,13 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { NotFoundError } from '../errors.js';
3
- export class MediaInUseError extends Error {
4
- usage;
5
- constructor(usage) {
6
- super(`This Media item is used by ${usage.count} Content document${usage.count === 1 ? '' : 's'}: ${usage.paths.join(', ')}.`);
7
- this.usage = usage;
8
- this.name = 'MediaInUseError';
9
- }
10
- }
2
+ import { MediaInUseError, NotFoundError } from '../errors.js';
3
+ import { GLOBAL_KIND } from '../globals.js';
11
4
  const EXTENSIONS = {
12
5
  'image/webp': 'webp',
13
6
  'image/png': 'png',
@@ -100,7 +93,7 @@ export function createMediaLibrary(opts) {
100
93
  })
101
94
  })));
102
95
  async function referencing(urls) {
103
- const records = await store.list();
96
+ const records = (await Promise.all([store.list(), store.list({ kind: GLOBAL_KIND })])).flat();
104
97
  const paths = new Map(urls.map((url) => [url, []]));
105
98
  for (const record of records) {
106
99
  const docs = [record.draft, record.published]
@@ -136,7 +129,10 @@ export function createMediaLibrary(opts) {
136
129
  `;
137
130
  const items = rows.map((row) => toItem(row, publicBaseUrl));
138
131
  const paths = await referencing(items.map((item) => item.url));
139
- return items.map((item) => ({ ...item, usage: paths.get(item.url).length }));
132
+ return items.map((item) => {
133
+ const usagePaths = paths.get(item.url);
134
+ return { ...item, usage: usagePaths.length, usagePaths };
135
+ });
140
136
  },
141
137
  async upload(bytes, { filename, title, contentType, uploadedBy }) {
142
138
  const id = createHash('sha256').update(bytes).digest('hex');