uncial-cms 5.0.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 (70) hide show
  1. package/README.md +62 -17
  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/local/vite.d.ts +2 -0
  47. package/dist/local/vite.js +1 -1
  48. package/dist/media-source.d.ts +45 -0
  49. package/dist/media-source.js +113 -0
  50. package/dist/mount.d.ts +1 -0
  51. package/dist/mount.js +2 -0
  52. package/dist/server/handlers.d.ts +1 -1
  53. package/dist/server/handlers.js +32 -5
  54. package/dist/server/index.d.ts +2 -1
  55. package/dist/server/index.js +2 -1
  56. package/dist/server/media.d.ts +1 -10
  57. package/dist/server/media.js +7 -11
  58. package/dist/server/postgres-store.d.ts +5 -0
  59. package/dist/server/postgres-store.js +50 -5
  60. package/dist/server-forge/adapter.d.ts +1 -0
  61. package/dist/server-forge/adapter.js +7 -4
  62. package/dist/server-forge/protocol.d.ts +3 -1
  63. package/dist/server-forge/protocol.js +2 -1
  64. package/dist/svelte/MediaLibrary.svelte +109 -53
  65. package/dist/svelte/MediaLibrary.svelte.d.ts +10 -2
  66. package/dist/svelte/index.d.ts +1 -4
  67. package/dist/svelte/index.js +1 -4
  68. package/dist/sveltekit/index.d.ts +2 -1
  69. package/dist/sveltekit/index.js +7 -2
  70. package/package.json +12 -3
@@ -0,0 +1,29 @@
1
+ export const PAGE_SIZE = 50;
2
+ const firstSegment = (pagePath) => pagePath.split('/')[0];
3
+ const sorted = (values) => [...new Set(values)].sort();
4
+ export function kindOptions(pages) {
5
+ return sorted(pages.flatMap((page) => page.kind ?? []));
6
+ }
7
+ export function folderOptions(pages) {
8
+ return sorted(pages.filter((page) => page.pagePath.includes('/')).map((page) => firstSegment(page.pagePath)));
9
+ }
10
+ /** `draft` and `published` match as the store's `list({ status })` does: a record with both matches both. */
11
+ function matchesStatus(page, status) {
12
+ if (!status)
13
+ return true;
14
+ return page.status !== (status === 'draft' ? 'published' : 'draft');
15
+ }
16
+ export function filterPages(pages, query) {
17
+ const needle = query.q?.trim().toLowerCase();
18
+ return pages.filter((page) => (!needle ||
19
+ [page.title, `/${page.pagePath}/`].some((text) => text?.toLowerCase().includes(needle))) &&
20
+ (!query.kind || page.kind === query.kind) &&
21
+ (!query.folder || firstSegment(page.pagePath) === query.folder) &&
22
+ matchesStatus(page, query.status));
23
+ }
24
+ export function pageWindow(total, page = 1) {
25
+ const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE));
26
+ const current = Math.min(Math.max(1, page), pageCount);
27
+ const start = (current - 1) * PAGE_SIZE;
28
+ return { page: current, pageCount, start, end: Math.min(start + PAGE_SIZE, total) };
29
+ }
@@ -0,0 +1,25 @@
1
+ export type DashboardSection = 'pages' | 'media' | 'globals';
2
+ export interface PagesQuery {
3
+ q?: string;
4
+ kind?: string;
5
+ folder?: string;
6
+ status?: 'draft' | 'published';
7
+ page?: number;
8
+ }
9
+ export type DashboardRoute = {
10
+ section: 'pages';
11
+ query?: PagesQuery;
12
+ } | {
13
+ section: 'edit';
14
+ pagePath: string;
15
+ } | {
16
+ section: 'media';
17
+ } | {
18
+ section: 'globals';
19
+ name?: string;
20
+ } | {
21
+ section: 'app';
22
+ id: string;
23
+ };
24
+ export declare function routeFromHash(hash: string): DashboardRoute;
25
+ export declare function hashForRoute(route: DashboardRoute): string;
@@ -0,0 +1,81 @@
1
+ import { GLOBAL_NAME, isGlobalsPath } from '../globals.js';
2
+ const PAGES = { section: 'pages' };
3
+ function editRoute(path) {
4
+ try {
5
+ const pagePath = decodeURIComponent(path);
6
+ if (isGlobalsPath(pagePath) || pagePath.split('/').some((part) => part === '.' || part === '..')) {
7
+ return PAGES;
8
+ }
9
+ return { section: 'edit', pagePath };
10
+ }
11
+ catch {
12
+ return PAGES;
13
+ }
14
+ }
15
+ function pagesRoute(search) {
16
+ const params = new URLSearchParams(search);
17
+ const query = {};
18
+ for (const key of ['q', 'kind', 'folder']) {
19
+ const value = params.get(key);
20
+ if (value)
21
+ query[key] = value;
22
+ }
23
+ const status = params.get('status');
24
+ if (status === 'draft' || status === 'published')
25
+ query.status = status;
26
+ const page = Number(params.get('page'));
27
+ if (Number.isInteger(page) && page > 1)
28
+ query.page = page;
29
+ return { section: 'pages', query };
30
+ }
31
+ export function routeFromHash(hash) {
32
+ if (!hash.startsWith('#/'))
33
+ return PAGES;
34
+ const rest = hash.slice(2);
35
+ if (rest === 'pages' || rest.startsWith('pages?'))
36
+ return pagesRoute(rest.slice('pages'.length));
37
+ if (rest === 'media')
38
+ return { section: 'media' };
39
+ if (rest === 'globals')
40
+ return { section: 'globals' };
41
+ if (rest.startsWith('edit/'))
42
+ return editRoute(rest.slice('edit/'.length).replace(/\/+$/, ''));
43
+ const [head, name, ...more] = rest.split('/');
44
+ if (head === 'globals' && name && more.length === 0 && GLOBAL_NAME.test(name)) {
45
+ return { section: 'globals', name };
46
+ }
47
+ if (head === 'app' && name && more.length === 0) {
48
+ try {
49
+ return { section: 'app', id: decodeURIComponent(name) };
50
+ }
51
+ catch {
52
+ return PAGES;
53
+ }
54
+ }
55
+ if (rest === '' || rest.endsWith('/'))
56
+ return editRoute(rest.replace(/\/+$/, ''));
57
+ return PAGES;
58
+ }
59
+ export function hashForRoute(route) {
60
+ switch (route.section) {
61
+ case 'edit':
62
+ return `#/edit/${route.pagePath.split('/').map(encodeURIComponent).join('/')}`;
63
+ case 'globals':
64
+ return route.name ? `#/globals/${route.name}` : '#/globals';
65
+ case 'app':
66
+ return `#/app/${encodeURIComponent(route.id)}`;
67
+ case 'pages': {
68
+ const { page, ...filters } = route.query ?? {};
69
+ const search = new URLSearchParams();
70
+ for (const [key, value] of Object.entries(filters))
71
+ if (value)
72
+ search.set(key, value);
73
+ if (page && page > 1)
74
+ search.set('page', String(page));
75
+ const query = search.toString();
76
+ return query ? `#/pages?${query}` : '#/pages';
77
+ }
78
+ default:
79
+ return `#/${route.section}`;
80
+ }
81
+ }
@@ -0,0 +1,32 @@
1
+ import type { ContentSchema } from 'uncial/core';
2
+ import type { Site } from '../define-site.js';
3
+ import type { Action } from '../server-forge/protocol.js';
4
+ import type { SessionProvider, UncialCmsSiteConfig } from '../types.js';
5
+ import type { DashboardSection } from './routes.js';
6
+ export type DashboardAction = Action;
7
+ export interface DashboardOptions {
8
+ config: UncialCmsSiteConfig | Site;
9
+ blocks: unknown;
10
+ schema: unknown;
11
+ globals?: Record<string, ContentSchema>;
12
+ editorHref?: (pagePath: string) => string;
13
+ can?: (action: DashboardAction, subject?: unknown) => boolean;
14
+ appSections?: Array<{
15
+ id: string;
16
+ label: string;
17
+ href?: string;
18
+ }>;
19
+ signOutHref?: string;
20
+ basePath?: string;
21
+ theme?: 'light' | 'dark' | 'system';
22
+ sessionProvider?: SessionProvider;
23
+ /** Site-relative page path → source path. Must match the one baked into the Editor variants. */
24
+ mapPathToSource?: (path: string) => string;
25
+ mapSourceToPath?: (source: string) => string;
26
+ editorStylesheets?: string[];
27
+ /** Repo-root-relative dir the build serves at the site root, as `cmsImageSource` takes it. Default 'static'. */
28
+ staticDir?: string;
29
+ }
30
+ export type DashboardProps = DashboardOptions & {
31
+ sections?: DashboardSection[];
32
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -3,13 +3,15 @@
3
3
  * build: the local forge while developing, the declared GitHub forge in a
4
4
  * production build, and a local-only site when no GitHub half is declared.
5
5
  */
6
+ import type { ContentSchema } from 'uncial/core';
6
7
  import { type DeployStatusTimings } from './deploy-status.js';
7
8
  import type { GitHubSiteConfig, LocalSiteConfig, ServerSiteConfig, UncialCmsSiteConfig } from './types.js';
8
9
  /** The auth worker this project operates for sites using the canonical GitHub App. */
9
10
  export declare const DEFAULT_AUTH_WORKER_URL = "https://uncial-cms-auth.dflood.workers.dev";
10
11
  /** The canonical GitHub App a site installs on its repository. */
11
12
  export declare const DEFAULT_APP_SLUG = "uncial-cms";
12
- export interface SiteOptions {
13
+ export type Globals = Record<string, ContentSchema>;
14
+ export interface SiteOptions<G extends Globals = Globals> {
13
15
  /** Repo-root-relative content directory, as the forge APIs address it. */
14
16
  contentDir: string;
15
17
  /** FS path of that directory at build time; defaults to `contentDir`. */
@@ -31,24 +33,27 @@ export interface SiteOptions {
31
33
  * ends on "status unknown". Each field falls back to its default.
32
34
  */
33
35
  deployStatus?: Partial<DeployStatusTimings>;
36
+ globals?: G;
34
37
  }
35
- export interface Site<Config extends UncialCmsSiteConfig = UncialCmsSiteConfig> {
38
+ export interface Site<Config extends UncialCmsSiteConfig = UncialCmsSiteConfig, G extends Globals = Globals> {
36
39
  config: Config;
37
40
  /** No GitHub half was declared, so this site is only editable in development. */
38
41
  localOnly: boolean;
39
42
  autosaveMs: number | undefined;
40
43
  localContentDir: string;
41
44
  deployStatusTimings: DeployStatusTimings;
45
+ globals: G;
42
46
  }
43
- export declare function defineSite(options: SiteOptions, env?: {
47
+ export declare function defineSite<G extends Globals = {}>(options: SiteOptions<G>, env?: {
44
48
  dev: boolean;
45
- }): Site<GitHubSiteConfig | LocalSiteConfig>;
46
- export interface ServerSiteOptions {
49
+ }): Site<GitHubSiteConfig | LocalSiteConfig, G>;
50
+ export interface ServerSiteOptions<G extends Globals = Globals> {
47
51
  /** The host endpoint serving `createServerContentHandlers`, e.g. '/dashboard/api/content'. */
48
52
  apiBase: string;
49
53
  mediaApiBase?: string;
50
54
  /** Autosave writes only the Draft, so a server site may autosave. */
51
55
  autosaveMs?: number;
56
+ globals?: G;
52
57
  }
53
58
  /** A site whose content lives behind the host's own endpoints, in every build. */
54
- export declare function defineServerSite(options: ServerSiteOptions): Site<ServerSiteConfig>;
59
+ export declare function defineServerSite<G extends Globals = {}>(options: ServerSiteOptions<G>): Site<ServerSiteConfig, G>;
@@ -1,8 +1,3 @@
1
- /**
2
- * One declaration of a site's CMS configuration, resolved for the current
3
- * build: the local forge while developing, the declared GitHub forge in a
4
- * production build, and a local-only site when no GitHub half is declared.
5
- */
6
1
  import { DEFAULT_DEPLOY_STATUS_TIMINGS } from './deploy-status.js';
7
2
  /** The auth worker this project operates for sites using the canonical GitHub App. */
8
3
  export const DEFAULT_AUTH_WORKER_URL = 'https://uncial-cms-auth.dflood.workers.dev';
@@ -33,7 +28,8 @@ export function defineSite(options, env = { dev: import.meta.env.DEV }) {
33
28
  localOnly,
34
29
  autosaveMs: config.forge === 'local' ? options.autosaveMs : undefined,
35
30
  localContentDir: options.localContentDir ?? options.contentDir,
36
- deployStatusTimings: resolveDeployStatusTimings(options.deployStatus)
31
+ deployStatusTimings: resolveDeployStatusTimings(options.deployStatus),
32
+ globals: options.globals ?? {}
37
33
  };
38
34
  }
39
35
  /** A site whose content lives behind the host's own endpoints, in every build. */
@@ -43,6 +39,7 @@ export function defineServerSite(options) {
43
39
  localOnly: false,
44
40
  autosaveMs: options.autosaveMs,
45
41
  localContentDir: '',
46
- deployStatusTimings: resolveDeployStatusTimings()
42
+ deployStatusTimings: resolveDeployStatusTimings(),
43
+ globals: options.globals ?? {}
47
44
  };
48
45
  }
@@ -40,6 +40,7 @@ export interface EditorPageUi {
40
40
  record?(state: RecordState): void;
41
41
  /** The record moved to a new path; this controller no longer addresses it. */
42
42
  moved?(path: string): void;
43
+ failed?(error: unknown): void;
43
44
  }
44
45
  export interface EditorControllerOptions {
45
46
  config: UncialCmsSiteConfig;
@@ -43,6 +43,7 @@ export function createEditorController(opts) {
43
43
  showRecord({ draft: view.draft !== null, published: view.published !== null, allowed: view.allowed });
44
44
  };
45
45
  const showFailure = (error, fallback) => {
46
+ ui.failed?.(error);
46
47
  if (error instanceof ConflictError) {
47
48
  // Do NOT touch content or dirty state: the unsaved edit must survive.
48
49
  ui.conflictVisible(true);
@@ -65,4 +65,9 @@ export interface CreateEditorSessionOptions {
65
65
  }
66
66
  export declare function forgeAdapter(config: UncialCmsSiteConfig): ForgeAdapter;
67
67
  export declare function defaultSessionProvider(config: UncialCmsSiteConfig): SessionProvider;
68
+ export declare function triggerDownload(payload: {
69
+ filename: string;
70
+ content: string;
71
+ mimeType: string;
72
+ }): void;
68
73
  export declare function createEditorSession(opts: CreateEditorSessionOptions): EditorController;
@@ -42,7 +42,7 @@ export function defaultSessionProvider(config) {
42
42
  return serverSessionProvider;
43
43
  return popupSessionProvider;
44
44
  }
45
- function triggerDownload(payload) {
45
+ export function triggerDownload(payload) {
46
46
  const blob = new Blob([payload.content], { type: payload.mimeType });
47
47
  const url = URL.createObjectURL(blob);
48
48
  const anchor = document.createElement('a');
package/dist/errors.d.ts CHANGED
@@ -6,3 +6,16 @@ export declare class ConflictError extends Error {
6
6
  export declare class NotFoundError extends Error {
7
7
  constructor(message?: string);
8
8
  }
9
+ export declare class MediaInUseError extends Error {
10
+ readonly usage: {
11
+ count: number;
12
+ paths: string[];
13
+ };
14
+ constructor(usage: {
15
+ count: number;
16
+ paths: string[];
17
+ });
18
+ }
19
+ export declare class SignedOutError extends Error {
20
+ constructor(message?: string);
21
+ }
package/dist/errors.js CHANGED
@@ -12,3 +12,17 @@ export class NotFoundError extends Error {
12
12
  this.name = 'NotFoundError';
13
13
  }
14
14
  }
15
+ export class MediaInUseError extends Error {
16
+ usage;
17
+ constructor(usage) {
18
+ super(`This Media item is used by ${usage.count} Content document${usage.count === 1 ? '' : 's'}: ${usage.paths.join(', ')}.`);
19
+ this.usage = usage;
20
+ this.name = 'MediaInUseError';
21
+ }
22
+ }
23
+ export class SignedOutError extends Error {
24
+ constructor(message = 'You are signed out. Sign in again to keep editing.') {
25
+ super(message);
26
+ this.name = 'SignedOutError';
27
+ }
28
+ }
@@ -0,0 +1,12 @@
1
+ import type { ContentDocument, ContentSchema } from 'uncial/core';
2
+ import type { Site } from './define-site.js';
3
+ export declare const GLOBALS_DIR = "_globals";
4
+ export declare const GLOBAL_KIND = "global";
5
+ export type GlobalValue<S extends Site, N extends keyof S['globals']> = S['globals'][N] extends ContentSchema<infer Meta> ? Meta : never;
6
+ export declare const GLOBAL_NAME: RegExp;
7
+ export declare function globalSourcePath(contentDir: string, name: string): string;
8
+ export declare function globalRecordPath(name: string): string;
9
+ export declare function isGlobalsPath(path: string): boolean;
10
+ export declare function assertPagePath(path: string): void;
11
+ export declare function globalTitle(schema: ContentSchema): string | undefined;
12
+ export declare function globalDocument(value: Record<string, unknown>): ContentDocument;
@@ -0,0 +1,29 @@
1
+ export const GLOBALS_DIR = '_globals';
2
+ export const GLOBAL_KIND = 'global';
3
+ export const GLOBAL_NAME = /^[A-Za-z0-9_-]+$/;
4
+ function checkName(name) {
5
+ if (!GLOBAL_NAME.test(name)) {
6
+ throw new Error(`"${name}" is not a Global name: use letters, digits, "-" and "_".`);
7
+ }
8
+ return name;
9
+ }
10
+ export function globalSourcePath(contentDir, name) {
11
+ return `${contentDir}/${GLOBALS_DIR}/${checkName(name)}.json`;
12
+ }
13
+ export function globalRecordPath(name) {
14
+ return `/${GLOBALS_DIR}/${checkName(name)}/`;
15
+ }
16
+ export function isGlobalsPath(path) {
17
+ return path.replace(/^\/+/, '').split('/')[0] === GLOBALS_DIR;
18
+ }
19
+ export function assertPagePath(path) {
20
+ if (isGlobalsPath(path))
21
+ throw new Error('The _globals namespace is reserved for Globals.');
22
+ }
23
+ export function globalTitle(schema) {
24
+ const title = schema.title;
25
+ return typeof title === 'string' && title !== '' ? title : undefined;
26
+ }
27
+ export function globalDocument(value) {
28
+ return { type: 'doc', content: [], meta: value };
29
+ }
@@ -1,15 +1,5 @@
1
1
  import type { ImageSource } from 'uncial/editor';
2
2
  import type { UncialCmsSiteConfig } from './types.js';
3
- /**
4
- * The editor's image source for a CMS site: an upload is fitted under the
5
- * forge limit, committed under the media dir through the active editor
6
- * session, and stored as its base-less served URL; browse lists the media
7
- * dir's images the same way. `base` and `staticDir` are the site's build-time
8
- * values, which the config does not carry. A site with a rendition pipeline
9
- * replaces the listing with `list` (served paths) and the tile URL with
10
- * `thumbnail`. On a `server` forge, upload and browse go to the Media
11
- * library at `mediaApiBase` instead.
12
- */
13
3
  export declare function cmsImageSource(config: UncialCmsSiteConfig, options?: {
14
4
  base?: string;
15
5
  staticDir?: string;
@@ -1,52 +1,23 @@
1
1
  import { resolveImageSrc } from 'uncial/render';
2
- import { resolveMediaDir, uploadImageAsset } from './index-actions.js';
3
- import { servedUrl } from './served-url.js';
4
- import { listMedia, uploadMedia } from './server-forge/media.js';
5
- import { configMediaDir, getActiveForge } from './upload-context.js';
6
- const IMAGE_EXTENSION = /\.(png|jpe?g|gif|webp|avif|svg)$/i;
7
- /**
8
- * The editor's image source for a CMS site: an upload is fitted under the
9
- * forge limit, committed under the media dir through the active editor
10
- * session, and stored as its base-less served URL; browse lists the media
11
- * dir's images the same way. `base` and `staticDir` are the site's build-time
12
- * values, which the config does not carry. A site with a rendition pipeline
13
- * replaces the listing with `list` (served paths) and the tile URL with
14
- * `thumbnail`. On a `server` forge, upload and browse go to the Media
15
- * library at `mediaApiBase` instead.
16
- */
2
+ import { mediaSourceFor } from './media-source.js';
3
+ import { getActiveForge } from './upload-context.js';
17
4
  export function cmsImageSource(config, options = {}) {
18
5
  const { base = '', staticDir = 'static', list } = options;
19
6
  const thumbnail = options.thumbnail ?? ((src) => resolveImageSrc(src, base));
20
- if (config.forge === 'server') {
21
- const { mediaApiBase } = config;
22
- if (!mediaApiBase)
23
- return { thumbnail };
24
- return {
25
- upload: async (file) => (await uploadMedia(mediaApiBase, file)).url,
26
- browse: list ??
27
- (async () => (await listMedia(mediaApiBase, { contentType: 'image/*' })).items.map((item) => item.url)),
28
- thumbnail
29
- };
30
- }
7
+ if (config.forge === 'server' && !config.mediaApiBase)
8
+ return { thumbnail };
9
+ const source = () => {
10
+ if (config.forge === 'server')
11
+ return mediaSourceFor(config);
12
+ const forge = getActiveForge();
13
+ if (!forge) {
14
+ throw new Error('No active editor session — open a page in the editor and sign in before choosing or uploading an image.');
15
+ }
16
+ return mediaSourceFor(config, forge, { staticDir });
17
+ };
31
18
  return {
32
- upload: async (file) => {
33
- const result = await uploadImageAsset(file, { fit: true, mediaDir: configMediaDir(config) });
34
- return servedUrl({ config }, result.path, staticDir);
35
- },
36
- browse: list ?? (async () => {
37
- const forge = getActiveForge();
38
- if (!forge) {
39
- throw new Error('No active editor session — open a page in the editor and sign in before choosing an image.');
40
- }
41
- // The same resolution `uploadImageAsset` commits under, so browse lists what upload wrote.
42
- const mediaDir = resolveMediaDir(configMediaDir(config), configMediaDir(forge.config));
43
- const entries = await forge.adapter.listDir(mediaDir);
44
- return entries
45
- .filter((entry) => entry.type === 'file' && IMAGE_EXTENSION.test(entry.path))
46
- .map((entry) => entry.path)
47
- .sort()
48
- .map((path) => servedUrl({ config }, path, staticDir));
49
- }),
19
+ upload: async (file) => (await source().upload(file)).url,
20
+ browse: list ?? (async () => (await source().list({ contentType: 'image/*' })).map((item) => item.url)),
50
21
  thumbnail
51
22
  };
52
23
  }
@@ -1,6 +1,7 @@
1
+ import type { ContentSchema } from 'uncial/core';
1
2
  import type { Site } from './define-site.js';
2
3
  import { type FitOptions, type ImageEncoder } from './fit-image.js';
3
- import type { ForgeAdapter } from './types.js';
4
+ import type { ForgeAdapter, UncialCmsSiteConfig } from './types.js';
4
5
  export interface CreatePageDeps {
5
6
  adapter: ForgeAdapter;
6
7
  blocks: unknown;
@@ -21,6 +22,33 @@ export declare function createPage(deps: CreatePageDeps, { pagePath, sourcePath
21
22
  }>;
22
23
  /** Delete `sourcePath` at its current sha. */
23
24
  export declare function deletePage(adapter: ForgeAdapter, { pagePath, sourcePath }: PageRef): Promise<void>;
25
+ export declare function readStoredGlobal(deps: {
26
+ adapter: ForgeAdapter;
27
+ config: UncialCmsSiteConfig;
28
+ }, global: {
29
+ name: string;
30
+ schema: ContentSchema;
31
+ }): Promise<{
32
+ value: Record<string, unknown>;
33
+ sha?: string;
34
+ }>;
35
+ export interface SaveGlobalDeps {
36
+ adapter: ForgeAdapter;
37
+ config: UncialCmsSiteConfig;
38
+ author: {
39
+ name: string;
40
+ email: string;
41
+ };
42
+ }
43
+ export declare function saveGlobal(deps: SaveGlobalDeps, global: {
44
+ name: string;
45
+ schema: ContentSchema;
46
+ value: Record<string, unknown>;
47
+ sha?: string;
48
+ }): Promise<{
49
+ sha: string;
50
+ commitSha: string;
51
+ }>;
24
52
  export interface UploadAssetFile {
25
53
  bytes: Uint8Array;
26
54
  filename: string;
@@ -72,5 +100,4 @@ export interface UploadImageAssetOptions {
72
100
  * dynamically from a block so the reader bundle stays free of CMS runtime.
73
101
  */
74
102
  export declare function uploadImageAsset(file: UploadAssetFile | File, opts?: UploadImageAssetOptions): Promise<UploadAssetResult>;
75
- /** Recursively list the content dir's JSON sources, sorted by page path. */
76
103
  export declare function listPages(adapter: ForgeAdapter, contentDir: string, mapSourceToPath?: (source: string) => string): Promise<PageRef[]>;
@@ -5,9 +5,10 @@
5
5
  */
6
6
  import { normalizeDocument } from 'uncial/core';
7
7
  import { MAX_CONTENT_BYTES } from './constants.js';
8
- import { serializeDocument } from './document.js';
8
+ import { parseDocument, serializeDocument } from './document.js';
9
9
  import { NotFoundError } from './errors.js';
10
10
  import { fitImage } from './fit-image.js';
11
+ import { globalDocument, globalRecordPath, globalSourcePath, GLOBALS_DIR } from './globals.js';
11
12
  import { defaultMapSourceToPath } from './paths/index.js';
12
13
  import { configMediaDir, getActiveForge } from './upload-context.js';
13
14
  /** Seed `sourcePath` with a normalized empty document (create-mode commit). */
@@ -37,6 +38,35 @@ export async function deletePage(adapter, { pagePath, sourcePath }) {
37
38
  const { sha } = await adapter.readFile(sourcePath);
38
39
  await adapter.deleteFile(sourcePath, { message: `uncial-cms: delete ${pagePath}`, sha });
39
40
  }
41
+ export async function readStoredGlobal(deps, global) {
42
+ const { config } = deps;
43
+ const path = config.forge === 'server'
44
+ ? globalRecordPath(global.name)
45
+ : globalSourcePath(config.contentDir, global.name);
46
+ try {
47
+ const file = await deps.adapter.readFile(path);
48
+ return { value: parseDocument(file.content, [], global.schema).meta ?? {}, sha: file.sha };
49
+ }
50
+ catch (error) {
51
+ if (!(error instanceof NotFoundError))
52
+ throw error;
53
+ return { value: normalizeDocument(null, [], global.schema).meta ?? {} };
54
+ }
55
+ }
56
+ export async function saveGlobal(deps, global) {
57
+ const { name, schema, value, sha } = global;
58
+ const content = serializeDocument(globalDocument(value), [], schema);
59
+ if (deps.config.forge === 'server') {
60
+ const adapter = deps.adapter;
61
+ const record = await adapter.saveGlobal(name, JSON.parse(content), sha);
62
+ return { sha: record.etag, commitSha: '' };
63
+ }
64
+ return deps.adapter.writeFile(globalSourcePath(deps.config.contentDir, name), content, {
65
+ message: `uncial-cms: save global ${name}`,
66
+ sha,
67
+ author: deps.author
68
+ });
69
+ }
40
70
  const EXTENSION_FROM_CONTENT_TYPE = {
41
71
  'image/jpeg': 'jpg',
42
72
  'image/svg+xml': 'svg'
@@ -129,13 +159,15 @@ export async function uploadImageAsset(file, opts = {}) {
129
159
  : file;
130
160
  return uploadAsset({ adapter: forge.adapter }, asset, { mediaDir, author: forge.author });
131
161
  }
132
- /** Recursively list the content dir's JSON sources, sorted by page path. */
133
162
  export async function listPages(adapter, contentDir, mapSourceToPath = (source) => defaultMapSourceToPath(source, contentDir)) {
134
163
  const sources = [];
164
+ const globalsDir = `${contentDir}/${GLOBALS_DIR}`;
135
165
  const walk = async (dir) => {
136
166
  for (const entry of await adapter.listDir(dir)) {
137
- if (entry.type === 'dir')
138
- await walk(entry.path);
167
+ if (entry.type === 'dir') {
168
+ if (entry.path !== globalsDir)
169
+ await walk(entry.path);
170
+ }
139
171
  else if (entry.path.endsWith('.json'))
140
172
  sources.push(entry.path);
141
173
  }
@@ -1,4 +1,5 @@
1
1
  import type { SessionProvider, UncialCmsSiteConfig } from './types.js';
2
+ /** @deprecated Render `<uncial-dashboard>`, which takes these options as properties. */
2
3
  export interface MountIndexPageOptions {
3
4
  config: UncialCmsSiteConfig;
4
5
  blocks: unknown;
@@ -16,6 +17,7 @@ export interface MountIndexPageOptions {
16
17
  /** Open pages in the host's own editing view instead of the Fallback editor. */
17
18
  editorHref?: (pagePath: string) => string;
18
19
  }
20
+ /** @deprecated Render `<uncial-dashboard>`; this mounts it showing only Pages. */
19
21
  export declare function mountIndexPage(target: HTMLElement, opts: MountIndexPageOptions): {
20
22
  destroy(): void;
21
23
  };