sandcms 0.6.1 → 0.6.2

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 (41) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/doctor.js +2 -2
  3. package/dist/cli/files.js +11 -6
  4. package/dist/cli/index.js +1 -1
  5. package/dist/cli/upgrade.js +2 -1
  6. package/dist/env.d.ts +80 -0
  7. package/dist/env.js +103 -0
  8. package/dist/server/admin-load.d.ts +46 -76
  9. package/dist/server/admin-load.js +98 -24
  10. package/dist/server/api-pagination.d.ts +2 -0
  11. package/dist/server/api-pagination.js +51 -7
  12. package/dist/server/cms.d.ts +17 -2
  13. package/dist/server/cms.js +3 -1
  14. package/dist/server/content.d.ts +15 -2
  15. package/dist/server/content.js +72 -30
  16. package/dist/server/db/migration-data.js +8 -0
  17. package/dist/server/db/migrations/0007_content_and_job_indexes.sql +2 -0
  18. package/dist/server/db/migrations/0008_search_text_cache.sql +45 -0
  19. package/dist/server/db/migrations/meta/0007_snapshot.json +1643 -0
  20. package/dist/server/db/migrations/meta/0008_snapshot.json +1711 -0
  21. package/dist/server/db/migrations/meta/_journal.json +14 -0
  22. package/dist/server/db/schema.d.ts +83 -0
  23. package/dist/server/db/schema.js +23 -5
  24. package/dist/server/email/index.d.ts +5 -1
  25. package/dist/server/email/index.js +12 -11
  26. package/dist/server/media/runner.js +217 -191
  27. package/dist/server/media/service.d.ts +6 -0
  28. package/dist/server/media/service.js +36 -3
  29. package/dist/server/search.d.ts +2 -0
  30. package/dist/server/search.js +7 -0
  31. package/dist/worker/index.js +129 -76
  32. package/docs/cloudflare.md +1 -1
  33. package/docs/deployment.md +15 -1
  34. package/docs/email.md +5 -5
  35. package/docs/media.md +2 -2
  36. package/docs/package.md +4 -4
  37. package/docs/releases.md +10 -0
  38. package/docs/upgrades.md +31 -1
  39. package/package.json +5 -1
  40. package/templates/env.ts +8 -0
  41. package/templates/integration.ts +5 -5
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # SandCMS
2
2
 
3
- **0.6.1** renames the media Worker secrets to the `SANDCMS_` prefix and adds opt-in automatic migration on website start with `SANDCMS_AUTO_MIGRATE=true`. Set the renamed Worker secrets before deploying the updated Worker; there is no new database migration, and stored data and project-owned YAML are preserved. See the [0.6.1 release notes](docs/releases.md#061), [upgrade workflow](docs/upgrades.md#061-upgrade-checklist) and [agent instructions](AGENTS.md).
3
+ **0.6.2** speeds up media processing with batched variant encoding and the protocol-6 Worker, speeds up admin search and dashboard queries, and validates SandCMS environment variables on website start. Deploy the updated Worker first and apply retained migrations `0007` and `0008`; stored data and project-owned YAML are preserved. See the [0.6.2 release notes](docs/releases.md#062), [upgrade workflow](docs/upgrades.md#062-upgrade-checklist) and [agent instructions](AGENTS.md).
4
4
 
5
5
  SandCMS embeds a content workspace into a SvelteKit website. Developers own YAML blueprints and public routes; editors manage drafts, publication, images, and form submissions at `/admin`.
6
6
 
@@ -49,9 +49,9 @@ export async function doctor(root, database) {
49
49
  workerUrl: process.env.SANDCMS_WORKER_URL
50
50
  });
51
51
  try {
52
- if ((await cms.media.health()).protocol !== 5)
52
+ if ((await cms.media.health()).protocol !== 6)
53
53
  throw new Error('Worker protocol is incompatible');
54
- console.log('OK: Worker protocol 5 is reachable');
54
+ console.log('OK: Worker protocol 6 is reachable');
55
55
  }
56
56
  finally {
57
57
  cms.close();
package/dist/cli/files.js CHANGED
@@ -33,13 +33,15 @@ export function planFiles(root, name = 'My website') {
33
33
  'src/routes/(sandcms)/admin/[...path]/+page.svelte': 'routes/admin/+page.svelte',
34
34
  'src/routes/(sandcms)/api/cms/[...path]/+server.ts': 'routes/api/+server.ts',
35
35
  'src/lib/server/sandcms/index.ts': 'integration.ts',
36
- 'src/hooks.server.ts': 'hooks.server.ts'
36
+ 'src/hooks.server.ts': 'hooks.server.ts',
37
+ 'src/env.ts': 'env.ts'
37
38
  };
38
- if (existsSync(join(root, 'src/hooks.server.js')) &&
39
- !existsSync(join(root, 'src/hooks.server.ts'))) {
40
- delete templates['src/hooks.server.ts'];
41
- templates['src/hooks.server.js'] = 'hooks.server.ts';
42
- }
39
+ // Both templates are also valid JavaScript; keep a JavaScript project's existing file.
40
+ for (const file of ['src/hooks.server', 'src/env'])
41
+ if (existsSync(join(root, file + '.js')) && !existsSync(join(root, file + '.ts'))) {
42
+ templates[file + '.js'] = templates[file + '.ts'];
43
+ delete templates[file + '.ts'];
44
+ }
43
45
  for (const file of walk(join(templateRoot, 'sandcms')))
44
46
  templates['sandcms/' + relative(join(templateRoot, 'sandcms'), file)] =
45
47
  'sandcms/' + relative(join(templateRoot, 'sandcms'), file);
@@ -110,5 +112,8 @@ export function migrationReport(plan, notes = []) {
110
112
  '\n\n' +
111
113
  (plan.some((p) => /src\/hooks\.server\.[jt]s$/.test(p.path) && p.status === 'conflict')
112
114
  ? `## Compose the existing server hook\n\nPreserve the current handle, rename its export to siteHandle, and annotate it with Handle from @sveltejs/kit/hooks (use JSDoc in JavaScript). Then add:\n\n\`\`\`ts\nimport { sequence } from '@sveltejs/kit/hooks';\nimport { building } from '$app/env';\nimport { cmsHandle } from '${PACKAGE_NAME}/server';\nimport { getCMS } from '#lib/server/sandcms/index.js';\nexport const handle = sequence(cmsHandle(getCMS, building), siteHandle);\n\`\`\`\n`
115
+ : '') +
116
+ (plan.some((p) => /^src\/env\.[jt]s$/.test(p.path) && p.status === 'conflict')
117
+ ? `## Declare SandCMS environment variables\n\nThe generated integration reads validated values from \`$app/env/private\`. Keep your existing declarations and spread the SandCMS ones into \`defineEnvVars\`:\n\n\`\`\`ts\nimport { building } from '$app/env';\nimport { sandcmsEnvVars } from '${PACKAGE_NAME}/env';\nexport const variables = defineEnvVars({\n ...sandcmsEnvVars({ building }),\n // existing variables\n});\n\`\`\`\n`
113
118
  : ''));
114
119
  }
package/dist/cli/index.js CHANGED
@@ -105,7 +105,7 @@ async function main() {
105
105
  try {
106
106
  cms.media.rebuild();
107
107
  while (cms.media.list().some((a) => a.status === 'processing')) {
108
- await cms.media.tick();
108
+ await cms.media.drain();
109
109
  await Bun.sleep(1000);
110
110
  console.log(cms.media
111
111
  .list()
@@ -12,9 +12,10 @@ export async function upgrade(root, check = false, database) {
12
12
  const notes = [
13
13
  'SvelteKit 3 is required. Migrate developer-owned Vite configuration, package imports, and tsconfig before applying generated integrations; see docs/upgrades.md#sveltekit-3.',
14
14
  `Installed integration: ${manifest.version}. Blueprints are valid.`,
15
+ 'The website now validates SandCMS environment variables on start through src/env.ts. Ensure SANDCMS_ORIGIN and a 32-character SANDCMS_SECRET are set in every environment. See docs/upgrades.md#validated-environment-variables.',
15
16
  'Include @better-auth/core in ssr.noExternal in your Vite configuration, then rebuild and restart the website to fix concurrent image preview failures. Developer-owned configuration is preserved. See docs/deployment.md#server-build-configuration.',
16
17
  'From 0.5.0, database changes use incremental migrations. Back up with the installed package before updating, then run sandcms migrate. Changed pre-0.5.0 baselines still require a fresh database. See docs/upgrades.md.',
17
- 'Worker compatibility range: protocol 5 (Worker also accepts protocols 3 and 4 for existing website processes). Deploy with sandcms worker update before upgrading website processes; expect temporary media downtime. Configure Worker R2 signing credentials, bucket CORS and staging lifecycle rules for direct uploads; run the incremental database migration; metadata inspection and encoding use remote transformations; verify both in staging. Purge old /media/* caches and keep R2 public access disabled. See docs/media.md.'
18
+ 'Worker compatibility range: protocol 6 (Worker also accepts protocols 3, 4 and 5 for existing website processes). Deploy with sandcms worker update before upgrading website processes; expect temporary media downtime. Configure Worker R2 signing credentials, bucket CORS and staging lifecycle rules for direct uploads; run the incremental database migration; metadata inspection and encoding use remote transformations; verify both in staging. Purge old /media/* caches and keep R2 public access disabled. See docs/media.md.'
18
19
  ];
19
20
  if (database)
20
21
  notes.push('Pending DB migrations: ' +
package/dist/env.d.ts ADDED
@@ -0,0 +1,80 @@
1
+ export interface SandcmsEnvOptions {
2
+ /** Pass `building` from `$app/env`: required runtime values are not checked during builds. */
3
+ building?: boolean;
4
+ }
5
+ declare function boolean(value: string | undefined): "true" | "false" | undefined;
6
+ /**
7
+ * SandCMS environment variable declarations for `src/env.ts`. The app fails to start when a
8
+ * required value is missing or invalid, so a deployment with a broken environment never
9
+ * becomes healthy.
10
+ *
11
+ * ```ts
12
+ * import { building } from '$app/env';
13
+ * import { defineEnvVars } from '@sveltejs/kit/env';
14
+ * import { sandcmsEnvVars } from 'sandcms/env';
15
+ * export const variables = defineEnvVars({ ...sandcmsEnvVars({ building }) });
16
+ * ```
17
+ */
18
+ export declare function sandcmsEnvVars({ building }?: SandcmsEnvOptions): {
19
+ SANDCMS_DATABASE: {
20
+ description: string;
21
+ schema: (value: string | undefined) => string;
22
+ };
23
+ SANDCMS_ORIGIN: {
24
+ description: string;
25
+ schema: (value: string | undefined) => string;
26
+ };
27
+ SANDCMS_SECRET: {
28
+ description: string;
29
+ schema: (value: string | undefined) => string;
30
+ };
31
+ SANDCMS_WORKER_TOKEN: {
32
+ description: string;
33
+ schema: (value: string | undefined) => string | undefined;
34
+ };
35
+ SANDCMS_WORKER_URL: {
36
+ description: string;
37
+ schema: (value: string | undefined) => string | undefined;
38
+ };
39
+ SANDCMS_TRUSTED_PROXY_HEADER: {
40
+ description: string;
41
+ schema: (value: string | undefined) => string | undefined;
42
+ };
43
+ SANDCMS_AUTO_MIGRATE: {
44
+ description: string;
45
+ schema: (value: string | undefined) => boolean;
46
+ };
47
+ SANDCMS_EMAIL_FROM: {
48
+ description: string;
49
+ schema: (value: string | undefined) => string | undefined;
50
+ };
51
+ SANDCMS_EMAIL_REPLY_TO: {
52
+ description: string;
53
+ schema: (value: string | undefined) => string | undefined;
54
+ };
55
+ SANDCMS_SMTP_HOST: {
56
+ description: string;
57
+ schema: (value: string | undefined) => string | undefined;
58
+ };
59
+ SANDCMS_SMTP_PORT: {
60
+ description: string;
61
+ schema: (value: string | undefined) => string | undefined;
62
+ };
63
+ SANDCMS_SMTP_SECURE: {
64
+ description: string;
65
+ schema: typeof boolean;
66
+ };
67
+ SANDCMS_SMTP_USER: {
68
+ description: string;
69
+ schema: (value: string | undefined) => string | undefined;
70
+ };
71
+ SANDCMS_SMTP_PASSWORD: {
72
+ description: string;
73
+ schema: (value: string | undefined) => string | undefined;
74
+ };
75
+ SANDCMS_SMTP_ALLOW_INSECURE_LOCAL: {
76
+ description: string;
77
+ schema: typeof boolean;
78
+ };
79
+ };
80
+ export {};
package/dist/env.js ADDED
@@ -0,0 +1,103 @@
1
+ /** Empty values mean "unset", matching how the integration has always read the environment. */
2
+ const optional = (value) => (value?.trim() ? value : undefined);
3
+ function boolean(value) {
4
+ if (!optional(value))
5
+ return undefined;
6
+ if (value !== 'true' && value !== 'false')
7
+ throw new Error('Must be true or false');
8
+ return value;
9
+ }
10
+ function url(value) {
11
+ let parsed;
12
+ try {
13
+ parsed = new URL(value);
14
+ }
15
+ catch {
16
+ throw new Error(`Must be an absolute URL, e.g. https://example.com (received "${value}")`);
17
+ }
18
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
19
+ throw new Error('Must use http: or https:');
20
+ return value;
21
+ }
22
+ /**
23
+ * SandCMS environment variable declarations for `src/env.ts`. The app fails to start when a
24
+ * required value is missing or invalid, so a deployment with a broken environment never
25
+ * becomes healthy.
26
+ *
27
+ * ```ts
28
+ * import { building } from '$app/env';
29
+ * import { defineEnvVars } from '@sveltejs/kit/env';
30
+ * import { sandcmsEnvVars } from 'sandcms/env';
31
+ * export const variables = defineEnvVars({ ...sandcmsEnvVars({ building }) });
32
+ * ```
33
+ */
34
+ export function sandcmsEnvVars({ building = false } = {}) {
35
+ const required = (check) => (value) => {
36
+ if (building)
37
+ return value ?? '';
38
+ if (!optional(value))
39
+ throw new Error('Value is missing');
40
+ return check(value);
41
+ };
42
+ return {
43
+ SANDCMS_DATABASE: {
44
+ description: 'SQLite database path.',
45
+ schema: (value) => optional(value) ?? './data/sandcms.sqlite'
46
+ },
47
+ SANDCMS_ORIGIN: {
48
+ description: 'Public website origin, e.g. https://example.com.',
49
+ schema: required(url)
50
+ },
51
+ SANDCMS_SECRET: {
52
+ description: 'Stable random secret of at least 32 characters (openssl rand -hex 32).',
53
+ schema: required((value) => {
54
+ if (value.length < 32)
55
+ throw new Error('Must be at least 32 characters');
56
+ return value;
57
+ })
58
+ },
59
+ SANDCMS_WORKER_TOKEN: {
60
+ description: 'Media Worker token.',
61
+ schema: optional
62
+ },
63
+ SANDCMS_WORKER_URL: {
64
+ description: 'Overrides config media.workerUrl for this environment.',
65
+ schema: (value) => (optional(value) ? url(value) : undefined)
66
+ },
67
+ SANDCMS_TRUSTED_PROXY_HEADER: {
68
+ description: 'Client IP header set by a trusted reverse proxy; see docs/deployment.md.',
69
+ schema: (value) => {
70
+ const header = value?.trim();
71
+ if (!header)
72
+ return undefined;
73
+ if (!/^[!#$%&'*+.^_`|~0-9a-z-]+$/i.test(header))
74
+ throw new Error('Must be a single HTTP header name');
75
+ return header;
76
+ }
77
+ },
78
+ SANDCMS_AUTO_MIGRATE: {
79
+ description: 'Back up the database and apply pending migrations on start.',
80
+ schema: (value) => boolean(value) === 'true'
81
+ },
82
+ SANDCMS_EMAIL_FROM: { description: 'Transactional email sender.', schema: optional },
83
+ SANDCMS_EMAIL_REPLY_TO: { description: 'Default reply-to address.', schema: optional },
84
+ SANDCMS_SMTP_HOST: { description: 'SMTP host.', schema: optional },
85
+ SANDCMS_SMTP_PORT: {
86
+ description: 'SMTP port.',
87
+ schema: (value) => {
88
+ if (!optional(value))
89
+ return undefined;
90
+ if (!/^\d+$/.test(value) || !Number(value) || Number(value) > 65535)
91
+ throw new Error('Must be a port number');
92
+ return value;
93
+ }
94
+ },
95
+ SANDCMS_SMTP_SECURE: { description: 'Use implicit TLS.', schema: boolean },
96
+ SANDCMS_SMTP_USER: { description: 'SMTP user.', schema: optional },
97
+ SANDCMS_SMTP_PASSWORD: { description: 'SMTP password.', schema: optional },
98
+ SANDCMS_SMTP_ALLOW_INSECURE_LOCAL: {
99
+ description: 'Allow plaintext SMTP to a local mail catcher.',
100
+ schema: boolean
101
+ }
102
+ };
103
+ }
@@ -1,5 +1,43 @@
1
1
  import { type RequestEvent } from '@sveltejs/kit';
2
2
  import type { CMS } from './cms.js';
3
+ type Relations = Record<string, {
4
+ id: string;
5
+ label: string;
6
+ }[]>;
7
+ type Usages = Record<string, {
8
+ documentId: string;
9
+ snapshot: string;
10
+ blueprint: string;
11
+ }[]>;
12
+ /** Label options for every non-form blueprint, newest first. Empty blueprints map to []. */
13
+ export declare function relationLabels(cms: CMS): Relations;
14
+ /** Content references grouped by media id; every requested asset id gets an array. */
15
+ export declare function mediaUsages(cms: CMS, assetIds: string[]): Usages;
16
+ /** Dashboard entries (8 most recent) and counts, computed in SQL. */
17
+ export declare function dashboardData(cms: CMS, mediaCount: number): {
18
+ entries: ({
19
+ id: string;
20
+ createdAt: number;
21
+ updatedAt: number;
22
+ blueprint: string;
23
+ singleton: string | null;
24
+ draft: import("../index.ts").Payload;
25
+ published: import("../index.ts").Payload | null;
26
+ draftSlug: string | null;
27
+ publishedSlug: string | null;
28
+ version: number;
29
+ publishedAt: number | null;
30
+ searchText: string | null;
31
+ } & {
32
+ label: string | undefined;
33
+ })[];
34
+ stats: {
35
+ entries: number;
36
+ published: number;
37
+ media: number;
38
+ unread: number;
39
+ };
40
+ };
3
41
  export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
4
42
  screen: string;
5
43
  user: {
@@ -60,6 +98,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
60
98
  publishedAt: number | null;
61
99
  updatedAt: number;
62
100
  createdAt: number;
101
+ searchText: string | null;
63
102
  } | null | undefined;
64
103
  entries: {
65
104
  id: string;
@@ -73,6 +112,7 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
73
112
  publishedAt: number | null;
74
113
  updatedAt: number;
75
114
  createdAt: number;
115
+ searchText: string | null;
76
116
  }[];
77
117
  editing: boolean;
78
118
  assets: {
@@ -89,13 +129,9 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
89
129
  variants: import("./db/schema.js").Variant[];
90
130
  error: string | null;
91
131
  createdAt: number;
132
+ searchText: string | null;
92
133
  }[];
93
- relations: {
94
- [k: string]: {
95
- id: string;
96
- label: string;
97
- }[];
98
- };
134
+ relations: Relations;
99
135
  screen: string;
100
136
  user: {
101
137
  id: string;
@@ -147,22 +183,12 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
147
183
  variants: import("./db/schema.js").Variant[];
148
184
  error: string | null;
149
185
  createdAt: number;
186
+ searchText: string | null;
150
187
  }[];
151
- relations: {
152
- [k: string]: {
153
- id: string;
154
- label: string;
155
- }[];
156
- };
188
+ relations: Relations;
157
189
  photographerCollection: string | undefined;
158
190
  uploadLimit: number;
159
- usages: {
160
- [k: string]: {
161
- documentId: string;
162
- snapshot: "draft" | "published";
163
- blueprint: string;
164
- }[];
165
- };
191
+ usages: Usages;
166
192
  screen: string;
167
193
  user: {
168
194
  id: string;
@@ -309,61 +335,5 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
309
335
  fileBlueprints: import("../index.ts").FileBlueprint[];
310
336
  defaultFileBlueprint: string;
311
337
  next?: undefined;
312
- } | {
313
- entries: {
314
- label: string;
315
- id: string;
316
- blueprint: string;
317
- singleton: string | null;
318
- draft: import("../index.ts").Payload;
319
- published: import("../index.ts").Payload | null;
320
- draftSlug: string | null;
321
- publishedSlug: string | null;
322
- version: number;
323
- publishedAt: number | null;
324
- updatedAt: number;
325
- createdAt: number;
326
- }[];
327
- stats: {
328
- entries: number;
329
- published: number;
330
- media: number;
331
- unread: number;
332
- };
333
- screen: string;
334
- user: {
335
- id: string;
336
- createdAt: Date;
337
- updatedAt: Date;
338
- email: string;
339
- emailVerified: boolean;
340
- name: string;
341
- image?: string | null | undefined | undefined;
342
- role: string;
343
- mustChangePassword: boolean;
344
- twoFactorEnabled: boolean | null | undefined;
345
- };
346
- site: string;
347
- blueprints: {
348
- navigationIcon: import("@lucide/svelte").LucideIconData;
349
- id: string;
350
- label: string;
351
- kind: "page" | "site" | "collection" | "form";
352
- icon?: string;
353
- navigation?: {
354
- group: string | false;
355
- };
356
- description?: string;
357
- preview?: string;
358
- fields: Record<string, import("../index.ts").Field>;
359
- tabs?: Record<string, import("../index.ts").BlueprintTab>;
360
- columns?: string[];
361
- export?: string[];
362
- }[];
363
- emailEnabled: boolean;
364
- workerUrl: string;
365
- mediaVersion: string;
366
- fileBlueprints: import("../index.ts").FileBlueprint[];
367
- defaultFileBlueprint: string;
368
- next?: undefined;
369
338
  }>;
339
+ export {};
@@ -1,8 +1,102 @@
1
1
  import { fileBlueprints, getFileBlueprint } from '../blueprints/files.js';
2
2
  import { redirect, error } from '@sveltejs/kit';
3
+ import { and, asc, count, desc, eq, inArray, sql } from 'drizzle-orm';
3
4
  import { requireUser } from './auth.js';
4
- import { user } from './db/schema.js';
5
+ import { documents, references, submissions, user } from './db/schema.js';
5
6
  import { blueprintIcon } from './blueprint-icons.js';
7
+ const entryBlueprintIds = (cms) => cms.definition.blueprints.filter((b) => b.kind !== 'form').map((b) => b.id);
8
+ const formBlueprintIds = (cms) => cms.definition.blueprints.filter((b) => b.kind === 'form').map((b) => b.id);
9
+ // Matches String(draft.title ?? id) without parsing every draft in JS.
10
+ function titleLabel(row) {
11
+ if (row.titleType === null || row.titleType === 'null')
12
+ return row.id;
13
+ if (row.titleType === 'true' || row.titleType === 'false')
14
+ return row.titleType;
15
+ if (row.titleType === 'object' || row.titleType === 'array')
16
+ return String(JSON.parse(String(row.title)));
17
+ return String(row.title);
18
+ }
19
+ /** Label options for every non-form blueprint, newest first. Empty blueprints map to []. */
20
+ export function relationLabels(cms) {
21
+ const ids = entryBlueprintIds(cms);
22
+ const relations = Object.fromEntries(ids.map((id) => [id, []]));
23
+ if (!ids.length)
24
+ return relations;
25
+ const rows = cms.store.db
26
+ .select({
27
+ id: documents.id,
28
+ blueprint: documents.blueprint,
29
+ title: sql `json_extract(${documents.draft}, '$.title')`,
30
+ titleType: sql `json_type(${documents.draft}, '$.title')`
31
+ })
32
+ .from(documents)
33
+ .where(inArray(documents.blueprint, ids))
34
+ .orderBy(desc(documents.updatedAt), asc(documents.id))
35
+ .all();
36
+ for (const row of rows)
37
+ relations[row.blueprint].push({ id: row.id, label: titleLabel(row) });
38
+ return relations;
39
+ }
40
+ /** Content references grouped by media id; every requested asset id gets an array. */
41
+ export function mediaUsages(cms, assetIds) {
42
+ const usages = Object.fromEntries(assetIds.map((id) => [id, []]));
43
+ if (!assetIds.length)
44
+ return usages;
45
+ const rows = cms.store.db
46
+ .select({
47
+ targetId: references.targetId,
48
+ documentId: references.documentId,
49
+ snapshot: references.snapshot,
50
+ blueprint: documents.blueprint
51
+ })
52
+ .from(references)
53
+ .innerJoin(documents, eq(documents.id, references.documentId))
54
+ .where(eq(references.kind, 'media'))
55
+ .all();
56
+ for (const row of rows)
57
+ if (Object.hasOwn(usages, row.targetId))
58
+ usages[row.targetId].push({
59
+ documentId: row.documentId,
60
+ snapshot: row.snapshot,
61
+ blueprint: row.blueprint
62
+ });
63
+ return usages;
64
+ }
65
+ /** Dashboard entries (8 most recent) and counts, computed in SQL. */
66
+ export function dashboardData(cms, mediaCount) {
67
+ const entryIds = entryBlueprintIds(cms);
68
+ const formIds = formBlueprintIds(cms);
69
+ const labels = new Map(cms.definition.blueprints.map((b) => [b.id, b.label]));
70
+ let entries = [];
71
+ let totals = { entries: 0, published: 0 };
72
+ let unread = 0;
73
+ if (entryIds.length) {
74
+ const scope = inArray(documents.blueprint, entryIds);
75
+ totals = cms.store.db
76
+ .select({ entries: count(), published: count(documents.published) })
77
+ .from(documents)
78
+ .where(scope)
79
+ .get();
80
+ entries = cms.store.db
81
+ .select()
82
+ .from(documents)
83
+ .where(scope)
84
+ .orderBy(desc(documents.updatedAt))
85
+ .limit(8)
86
+ .all()
87
+ .map((e) => ({ ...e, label: labels.get(e.blueprint) }));
88
+ }
89
+ if (formIds.length)
90
+ unread = cms.store.db
91
+ .select({ n: count() })
92
+ .from(submissions)
93
+ .where(and(inArray(submissions.formId, formIds), eq(submissions.read, false)))
94
+ .get().n;
95
+ return {
96
+ entries,
97
+ stats: { entries: totals.entries, published: totals.published, media: mediaCount, unread }
98
+ };
99
+ }
6
100
  export async function adminLoad(cms, event) {
7
101
  const session = await cms.auth.api.getSession({ headers: event.request.headers }), path = event.params.path ?? '';
8
102
  // Preserve notification links through sign-in, accepting only local form paths.
@@ -45,12 +139,7 @@ export async function adminLoad(cms, event) {
45
139
  requireUser(session.user);
46
140
  const assets = cms.media
47
141
  .list()
48
- .map((asset) => ({ ...asset, expectedVersion: cms.media.versionForAsset(asset) })), relations = Object.fromEntries(cms.definition.blueprints
49
- .filter((b) => b.kind !== 'form')
50
- .map((b) => [
51
- b.id,
52
- cms.content.list(b.id).map((d) => ({ id: d.id, label: String(d.draft.title ?? d.id) }))
53
- ]));
142
+ .map((asset) => ({ ...asset, expectedVersion: cms.media.versionForAsset(asset) })), relations = relationLabels(cms);
54
143
  if (screen === 'content') {
55
144
  const blueprint = cms.content.blueprint(key);
56
145
  const entry = blueprint.kind === 'collection'
@@ -77,7 +166,7 @@ export async function adminLoad(cms, event) {
77
166
  relations,
78
167
  photographerCollection: cms.definition.config.media.photographerCollection,
79
168
  uploadLimit: cms.definition.config.media.uploadLimit,
80
- usages: Object.fromEntries(assets.map((a) => [a.id, cms.content.usages(a.id)]))
169
+ usages: mediaUsages(cms, assets.map((a) => a.id))
81
170
  };
82
171
  if (screen === 'forms') {
83
172
  const blueprint = cms.definition.blueprints.find((b) => b.id === key && b.kind === 'form');
@@ -118,20 +207,5 @@ export async function adminLoad(cms, event) {
118
207
  }
119
208
  if (screen && screen !== 'dashboard')
120
209
  error(404, 'Page not found');
121
- const entries = cms.definition.blueprints
122
- .filter((b) => b.kind !== 'form')
123
- .flatMap((b) => cms.content.list(b.id).map((e) => ({ ...e, label: b.label })));
124
- return {
125
- ...base,
126
- entries: entries.sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 8),
127
- stats: {
128
- entries: entries.length,
129
- published: entries.filter((e) => e.published).length,
130
- media: assets.length,
131
- unread: cms.definition.blueprints
132
- .filter((b) => b.kind === 'form')
133
- .flatMap((b) => cms.forms.list(b.id))
134
- .filter((s) => !s.read).length
135
- }
136
- };
210
+ return { ...base, ...dashboardData(cms, assets.length) };
137
211
  }
@@ -12,6 +12,7 @@ export declare function contentPage(cms: CMS, params: URLSearchParams): {
12
12
  publishedAt: number | null;
13
13
  updatedAt: number;
14
14
  createdAt: number;
15
+ searchText: string | null;
15
16
  }[];
16
17
  nextCursor: string | null;
17
18
  };
@@ -29,6 +30,7 @@ export declare function mediaPage(cms: CMS, params: URLSearchParams): {
29
30
  variants: import("./db/schema.js").Variant[];
30
31
  error: string | null;
31
32
  createdAt: number;
33
+ searchText: string | null;
32
34
  }[];
33
35
  nextCursor: string | null;
34
36
  };