@kidecms/core 0.1.10 → 0.13.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.
- package/LICENSE +21 -0
- package/admin/components/AssetsGrid.tsx +366 -173
- package/admin/components/BlockEditor.tsx +260 -679
- package/admin/components/CheckboxField.tsx +2 -2
- package/admin/components/CollaborationReviewBar.tsx +384 -0
- package/admin/components/ColorField.tsx +87 -0
- package/admin/components/CommandPalette.tsx +169 -0
- package/admin/components/ContentEditor.tsx +687 -0
- package/admin/components/DocumentActions.tsx +4 -2
- package/admin/components/DocumentsDataTable.tsx +91 -10
- package/admin/components/FieldControl.astro +151 -26
- package/admin/components/FocalPointSelector.tsx +27 -1
- package/admin/components/InternalLinkPicker.tsx +4 -3
- package/admin/components/LinkField.tsx +126 -0
- package/admin/components/RelationField.tsx +105 -26
- package/admin/components/RepeaterInput.tsx +46 -0
- package/admin/components/RichTextEditor.tsx +44 -9
- package/admin/components/SharedSectionBlockField.tsx +93 -0
- package/admin/components/SidebarUserMenu.tsx +1 -1
- package/admin/components/Toast.astro +1 -1
- package/admin/components/TreeItemsEditor.tsx +20 -19
- package/admin/components/TreeSelect.tsx +2 -2
- package/admin/components/YoutubeField.tsx +48 -0
- package/admin/components/block-fields.tsx +777 -0
- package/admin/components/content-block-spec.ts +114 -0
- package/admin/components/slash-command.tsx +242 -0
- package/admin/components/tree-utils.ts +14 -2
- package/admin/components/ui/badge.tsx +2 -3
- package/admin/components/ui/button.tsx +5 -4
- package/admin/components/ui/checkbox.tsx +1 -1
- package/admin/components/ui/input.tsx +1 -1
- package/admin/components/ui/select.tsx +1 -1
- package/admin/components/ui/table.tsx +1 -1
- package/admin/components/ui/textarea.tsx +1 -1
- package/admin/layouts/AdminLayout.astro +323 -123
- package/admin/lib/access.ts +54 -0
- package/admin/lib/collaboration.ts +178 -0
- package/admin/lib/edit-data.ts +448 -0
- package/admin/views/AccessDeniedView.astro +8 -0
- package/admin/views/EditView.astro +706 -0
- package/admin/views/ListView.astro +202 -0
- package/admin/views/RecentView.astro +76 -0
- package/admin/views/SinglesView.astro +65 -0
- package/admin/views/edit/EditScripts.astro +145 -0
- package/admin/views/edit/ReverseReferencesList.astro +68 -0
- package/core/admin.ts +193 -0
- package/core/ai.ts +87 -0
- package/core/api.ts +1392 -0
- package/core/assets.ts +336 -0
- package/core/audit.ts +84 -0
- package/core/auth-config.ts +44 -0
- package/core/auth.ts +303 -0
- package/core/collaboration.ts +276 -0
- package/core/content.ts +27 -0
- package/core/create-admin.ts +28 -0
- package/core/define.ts +625 -0
- package/core/field-model.ts +172 -0
- package/core/generator.ts +519 -0
- package/core/http.ts +42 -0
- package/core/image.ts +219 -0
- package/core/index.ts +211 -0
- package/core/locks.ts +52 -0
- package/core/log.ts +37 -0
- package/core/migrate.ts +278 -0
- package/core/rate-limit.ts +110 -0
- package/core/request-scope.ts +33 -0
- package/core/richtext.ts +1 -0
- package/core/runtime.ts +63 -0
- package/core/schema.ts +32 -0
- package/core/search.ts +489 -0
- package/core/seed.ts +101 -0
- package/core/shared-sections.ts +96 -0
- package/core/tasks.ts +176 -0
- package/core/values.ts +433 -0
- package/core/webhooks.ts +85 -0
- package/core/youtube.ts +39 -0
- package/internals/cli.mjs +34 -0
- package/internals/context.ts +67 -0
- package/internals/create-admin.ts +40 -0
- package/internals/describe.ts +25 -0
- package/internals/eject.ts +144 -0
- package/internals/generator.ts +11 -0
- package/internals/integration.ts +481 -0
- package/internals/mcp.ts +397 -0
- package/internals/project.ts +26 -0
- package/internals/push.ts +160 -0
- package/internals/reindex.ts +11 -0
- package/internals/restore.ts +257 -0
- package/internals/seed.data.ts +7 -0
- package/internals/seed.ts +11 -0
- package/internals/upgrade.ts +776 -0
- package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
- package/middleware/auth.ts +130 -17
- package/middleware/push.ts +121 -0
- package/package.json +55 -67
- package/platform/cloudflare/cf-env.ts +60 -0
- package/platform/cloudflare/database.ts +28 -0
- package/platform/cloudflare/globals.d.ts +5 -0
- package/platform/cloudflare/storage.ts +33 -0
- package/platform/cloudflare/uploads-route.ts +37 -0
- package/platform/node/database.ts +39 -0
- package/platform/node/storage.ts +52 -0
- package/routes/admin/[...path].astro +71 -0
- package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
- package/routes/admin/assets/index.astro +90 -0
- package/routes/admin/forgot-password.astro +60 -0
- package/routes/{pages/admin → admin}/invite.astro +7 -6
- package/routes/admin/login.astro +103 -0
- package/routes/admin/reset-password.astro +73 -0
- package/routes/{pages/admin → admin}/setup.astro +32 -8
- package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
- package/routes/api/admin/search.ts +89 -0
- package/routes/api/{cms/assets → assets}/[id].ts +24 -14
- package/routes/api/{cms/assets → assets}/index.ts +4 -2
- package/routes/api/assets/upload.ts +147 -0
- package/routes/api/auth/forgot-password.ts +77 -0
- package/routes/api/{cms/auth → auth}/invite.ts +41 -9
- package/routes/api/auth/login.ts +167 -0
- package/routes/api/{cms/auth → auth}/logout.ts +11 -2
- package/routes/api/auth/reset-password.ts +85 -0
- package/routes/api/auth/setup.ts +110 -0
- package/routes/api/auth/sso/[provider]/start.ts +34 -0
- package/routes/api/collaboration/index.ts +106 -0
- package/routes/api/cron/_authorize.ts +25 -0
- package/routes/api/{cms/cron → cron}/publish.ts +3 -9
- package/routes/api/cron/tasks.ts +33 -0
- package/routes/api/forms/submit/[slug].ts +143 -0
- package/routes/api/img/[...path].ts +65 -0
- package/routes/api/{cms/preview → preview}/render.ts +8 -3
- package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
- package/routes/api/webhooks/[provider].ts +54 -0
- package/README.md +0 -28
- package/dist/admin.d.ts +0 -33
- package/dist/admin.js +0 -92
- package/dist/ai.d.ts +0 -15
- package/dist/ai.js +0 -70
- package/dist/api.d.ts +0 -14
- package/dist/api.js +0 -833
- package/dist/assets.d.ts +0 -51
- package/dist/assets.js +0 -163
- package/dist/auth.d.ts +0 -30
- package/dist/auth.js +0 -132
- package/dist/content.d.ts +0 -3
- package/dist/content.js +0 -29
- package/dist/create-admin.d.ts +0 -5
- package/dist/create-admin.js +0 -23
- package/dist/define.d.ts +0 -254
- package/dist/define.js +0 -36
- package/dist/generator.d.ts +0 -9
- package/dist/generator.js +0 -370
- package/dist/image.d.ts +0 -9
- package/dist/image.js +0 -69
- package/dist/index.d.ts +0 -28
- package/dist/index.js +0 -16
- package/dist/integration.d.ts +0 -14
- package/dist/integration.js +0 -327
- package/dist/locks.d.ts +0 -7
- package/dist/locks.js +0 -37
- package/dist/richtext.d.ts +0 -1
- package/dist/richtext.js +0 -1
- package/dist/runtime.d.ts +0 -24
- package/dist/runtime.js +0 -26
- package/dist/schema.d.ts +0 -17
- package/dist/schema.js +0 -13
- package/dist/seed.d.ts +0 -2
- package/dist/seed.js +0 -84
- package/dist/values.d.ts +0 -8
- package/dist/values.js +0 -102
- package/dist/webhooks.d.ts +0 -2
- package/dist/webhooks.js +0 -73
- package/routes/api/cms/assets/upload.ts +0 -112
- package/routes/api/cms/auth/login.ts +0 -124
- package/routes/api/cms/auth/setup.ts +0 -77
- package/routes/api/cms/img/[...path].ts +0 -24
- package/routes/pages/admin/[...path].astro +0 -1107
- package/routes/pages/admin/assets/index.astro +0 -63
- package/routes/pages/admin/login.astro +0 -57
- /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
- /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
- /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
- /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
- /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
package/core/migrate.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Migration toolkit: validate documents against the collection schema BEFORE
|
|
3
|
+
* writing (so shape mismatches surface in a report, not by opening the admin and
|
|
4
|
+
* finding raw JSON), load a batch with a dry-run mode, and render the
|
|
5
|
+
* machine-readable model into `MODEL.md`. Pairs with `kide describe`
|
|
6
|
+
* (internals/describe.ts) and `createCmsContext` (internals/context.ts).
|
|
7
|
+
*/
|
|
8
|
+
import type { CMSConfig, CollectionConfig, FieldConfig } from "./define";
|
|
9
|
+
import { describeModel, FIELD_MODEL, CONTENT_AST_SCHEMA } from "./field-model";
|
|
10
|
+
|
|
11
|
+
export type ValidationIssue = { field: string; message: string };
|
|
12
|
+
export type ValidationResult = { ok: boolean; errors: ValidationIssue[]; warnings: ValidationIssue[] };
|
|
13
|
+
|
|
14
|
+
const isEmpty = (v: unknown) => v === undefined || v === null || v === "" || (Array.isArray(v) && v.length === 0);
|
|
15
|
+
const isRoot = (v: unknown) => !!v && typeof v === "object" && (v as { type?: string }).type === "root";
|
|
16
|
+
|
|
17
|
+
const validateField = (
|
|
18
|
+
name: string,
|
|
19
|
+
field: FieldConfig,
|
|
20
|
+
value: unknown,
|
|
21
|
+
errors: ValidationIssue[],
|
|
22
|
+
warnings: ValidationIssue[],
|
|
23
|
+
) => {
|
|
24
|
+
if (field.required && isEmpty(value) && field.defaultValue === undefined) {
|
|
25
|
+
errors.push({ field: name, message: "required but empty" });
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (isEmpty(value)) return;
|
|
29
|
+
|
|
30
|
+
switch (field.type) {
|
|
31
|
+
case "number":
|
|
32
|
+
if (typeof value !== "number" && Number.isNaN(Number(value)))
|
|
33
|
+
errors.push({ field: name, message: `expected number, got ${typeof value}` });
|
|
34
|
+
break;
|
|
35
|
+
case "boolean":
|
|
36
|
+
if (typeof value !== "boolean") warnings.push({ field: name, message: "expected boolean" });
|
|
37
|
+
break;
|
|
38
|
+
case "select":
|
|
39
|
+
if (!field.options.includes(String(value)))
|
|
40
|
+
errors.push({ field: name, message: `'${value}' is not one of [${field.options.join(", ")}]` });
|
|
41
|
+
break;
|
|
42
|
+
case "relation":
|
|
43
|
+
if (field.hasMany && !Array.isArray(value))
|
|
44
|
+
errors.push({ field: name, message: "hasMany relation expects an array of ids" });
|
|
45
|
+
if (!field.hasMany && typeof value !== "string")
|
|
46
|
+
errors.push({ field: name, message: "relation expects an id string" });
|
|
47
|
+
break;
|
|
48
|
+
case "image":
|
|
49
|
+
if (typeof value !== "string") errors.push({ field: name, message: "image expects a storagePath string" });
|
|
50
|
+
else if (!value.startsWith("/")) warnings.push({ field: name, message: "image src is not a '/uploads/…' path" });
|
|
51
|
+
break;
|
|
52
|
+
case "array":
|
|
53
|
+
if (!Array.isArray(value)) errors.push({ field: name, message: "expected an array" });
|
|
54
|
+
break;
|
|
55
|
+
case "richText":
|
|
56
|
+
if (!isRoot(value)) errors.push({ field: name, message: "richText expects { type:'root', children:[…] }" });
|
|
57
|
+
break;
|
|
58
|
+
case "content":
|
|
59
|
+
validateContent(name, field, value, errors, warnings);
|
|
60
|
+
break;
|
|
61
|
+
case "date":
|
|
62
|
+
if (Number.isNaN(Date.parse(String(value)))) warnings.push({ field: name, message: "date is not parseable" });
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const validateContent = (
|
|
68
|
+
name: string,
|
|
69
|
+
field: Extract<FieldConfig, { type: "content" }>,
|
|
70
|
+
value: unknown,
|
|
71
|
+
errors: ValidationIssue[],
|
|
72
|
+
warnings: ValidationIssue[],
|
|
73
|
+
) => {
|
|
74
|
+
if (!isRoot(value)) {
|
|
75
|
+
errors.push({ field: name, message: "content expects { type:'root', children:[…] }" });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const declared = new Set(Object.keys(field.blocks ?? {}));
|
|
79
|
+
for (const node of (value as { children?: Array<{ type?: string; blockType?: string }> }).children ?? []) {
|
|
80
|
+
if (node?.type === "block" && node.blockType && !declared.has(node.blockType)) {
|
|
81
|
+
warnings.push({
|
|
82
|
+
field: name,
|
|
83
|
+
message: `inline block '${node.blockType}' is not declared in this field's blocks`,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/** Validate a document's fields against its collection schema. */
|
|
90
|
+
export const validateDocument = (collection: CollectionConfig, data: Record<string, unknown>): ValidationResult => {
|
|
91
|
+
const errors: ValidationIssue[] = [];
|
|
92
|
+
const warnings: ValidationIssue[] = [];
|
|
93
|
+
for (const [name, field] of Object.entries(collection.fields)) {
|
|
94
|
+
validateField(name, field, data[name], errors, warnings);
|
|
95
|
+
}
|
|
96
|
+
for (const key of Object.keys(data)) {
|
|
97
|
+
if (key.startsWith("_")) continue;
|
|
98
|
+
if (!(key in collection.fields)) warnings.push({ field: key, message: "not a declared field (will be ignored)" });
|
|
99
|
+
}
|
|
100
|
+
return { ok: errors.length === 0, errors, warnings };
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// Batch loader (import IR → CMS) with dry-run + validation report.
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
export type ImportItem = {
|
|
108
|
+
collection: string;
|
|
109
|
+
/** Base-locale fields. Pass `_id` for deterministic, re-runnable imports. */
|
|
110
|
+
data: Record<string, unknown>;
|
|
111
|
+
/** Optional per-locale translatable-field overlays. */
|
|
112
|
+
translations?: Record<string, Record<string, unknown>>;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
export type ImportReport = {
|
|
116
|
+
dryRun: boolean;
|
|
117
|
+
total: number;
|
|
118
|
+
created: number;
|
|
119
|
+
translated: number;
|
|
120
|
+
failed: number;
|
|
121
|
+
invalid: Array<{ collection: string; id: unknown; errors: ValidationIssue[] }>;
|
|
122
|
+
warnings: Array<{ collection: string; id: unknown; warnings: ValidationIssue[] }>;
|
|
123
|
+
errors: Array<{ collection: string; id: unknown; message: string }>;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
type AnyCms = Record<string, any>;
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Validate then (unless dryRun) create every item via the typed API. Use
|
|
130
|
+
* `{ _system: true, _skipSearch: true }` context for bulk imports and call
|
|
131
|
+
* `reindex()` once afterwards.
|
|
132
|
+
*/
|
|
133
|
+
export const importDocuments = async (
|
|
134
|
+
cms: AnyCms,
|
|
135
|
+
config: CMSConfig,
|
|
136
|
+
items: ImportItem[],
|
|
137
|
+
options: { dryRun?: boolean; context?: Record<string, unknown> } = {},
|
|
138
|
+
): Promise<ImportReport> => {
|
|
139
|
+
const dryRun = options.dryRun ?? false;
|
|
140
|
+
const context = options.context ?? { _system: true, _skipSearch: true };
|
|
141
|
+
const collectionMap = Object.fromEntries(config.collections.map((c) => [c.slug, c]));
|
|
142
|
+
const report: ImportReport = {
|
|
143
|
+
dryRun,
|
|
144
|
+
total: items.length,
|
|
145
|
+
created: 0,
|
|
146
|
+
translated: 0,
|
|
147
|
+
failed: 0,
|
|
148
|
+
invalid: [],
|
|
149
|
+
warnings: [],
|
|
150
|
+
errors: [],
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
for (const item of items) {
|
|
154
|
+
const collection = collectionMap[item.collection];
|
|
155
|
+
const id = item.data._id;
|
|
156
|
+
if (!collection) {
|
|
157
|
+
report.errors.push({ collection: item.collection, id, message: "unknown collection" });
|
|
158
|
+
report.failed++;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const result = validateDocument(collection, item.data);
|
|
162
|
+
if (result.warnings.length) report.warnings.push({ collection: item.collection, id, warnings: result.warnings });
|
|
163
|
+
if (!result.ok) {
|
|
164
|
+
report.invalid.push({ collection: item.collection, id, errors: result.errors });
|
|
165
|
+
report.failed++;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (dryRun) continue;
|
|
169
|
+
try {
|
|
170
|
+
const created = await cms[item.collection].create(item.data, context);
|
|
171
|
+
report.created++;
|
|
172
|
+
for (const [locale, overlay] of Object.entries(item.translations ?? {})) {
|
|
173
|
+
await cms[item.collection].upsertTranslation(created._id, locale, overlay, context);
|
|
174
|
+
report.translated++;
|
|
175
|
+
}
|
|
176
|
+
} catch (e) {
|
|
177
|
+
report.errors.push({ collection: item.collection, id, message: (e as Error).message });
|
|
178
|
+
report.failed++;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return report;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
185
|
+
// MODEL.md renderer
|
|
186
|
+
// ---------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
const table = (headers: string[], rows: string[][]) =>
|
|
189
|
+
[
|
|
190
|
+
`| ${headers.join(" | ")} |`,
|
|
191
|
+
`| ${headers.map(() => "---").join(" | ")} |`,
|
|
192
|
+
...rows.map((r) => `| ${r.map((c) => c.replace(/\|/g, "\\|")).join(" | ")} |`),
|
|
193
|
+
].join("\n");
|
|
194
|
+
|
|
195
|
+
const fieldRow = (f: Record<string, unknown>): string[] => {
|
|
196
|
+
const extra: string[] = [];
|
|
197
|
+
if (f.options) extra.push(`options: ${(f.options as string[]).join(", ")}`);
|
|
198
|
+
if (f.collection) extra.push(`→ ${f.collection}${f.hasMany ? "[]" : ""}`);
|
|
199
|
+
if (f.itemFields) extra.push(`rows: ${Object.keys(f.itemFields as object).join(", ")}`);
|
|
200
|
+
if (f.blockTypes) extra.push(`blocks: ${Object.keys(f.blockTypes as object).join(", ")}`);
|
|
201
|
+
return [
|
|
202
|
+
`\`${f.name}\``,
|
|
203
|
+
String(f.type),
|
|
204
|
+
String(f.control),
|
|
205
|
+
f.required ? "yes" : "",
|
|
206
|
+
f.translatable ? "yes" : "",
|
|
207
|
+
`\`${f.valueShape}\`${extra.length ? " — " + extra.join("; ") : ""}`,
|
|
208
|
+
];
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
/** Render the model manifest as human/agent-readable Markdown (MODEL.md). */
|
|
212
|
+
export const renderModelMarkdown = (config: CMSConfig): string => {
|
|
213
|
+
const model = describeModel(config);
|
|
214
|
+
const out: string[] = [];
|
|
215
|
+
out.push("# Kide content model");
|
|
216
|
+
out.push("");
|
|
217
|
+
out.push("> Generated by `pnpm cms:describe`. The authoritative map of every collection, field, its");
|
|
218
|
+
out.push("> admin control and the exact value shape an importer must write. Do not edit by hand.");
|
|
219
|
+
out.push("");
|
|
220
|
+
out.push(`**Locales:** default \`${model.locales.default}\`, supported \`${model.locales.supported.join(", ")}\``);
|
|
221
|
+
out.push("");
|
|
222
|
+
|
|
223
|
+
out.push("## Field types");
|
|
224
|
+
out.push("");
|
|
225
|
+
out.push(
|
|
226
|
+
table(
|
|
227
|
+
["type", "storage", "admin control", "value shape"],
|
|
228
|
+
Object.entries(FIELD_MODEL).map(([t, m]) => [`\`${t}\``, m.storage, m.control, `\`${m.valueShape}\``]),
|
|
229
|
+
),
|
|
230
|
+
);
|
|
231
|
+
out.push("");
|
|
232
|
+
|
|
233
|
+
out.push("## Content / rich-text AST");
|
|
234
|
+
out.push("");
|
|
235
|
+
out.push("```");
|
|
236
|
+
out.push(`root: ${CONTENT_AST_SCHEMA.root}`);
|
|
237
|
+
for (const [k, v] of Object.entries(CONTENT_AST_SCHEMA.nodes)) out.push(` ${k}: ${v}`);
|
|
238
|
+
out.push("```");
|
|
239
|
+
out.push("> A `content` field stores any `{type:'root'}` doc as-is — inline block `fields` are not");
|
|
240
|
+
out.push("> validated. Build prose with `htmlToRichText(html)`; declare `blocks` for the editor.");
|
|
241
|
+
out.push("");
|
|
242
|
+
|
|
243
|
+
for (const collection of model.collections) {
|
|
244
|
+
out.push(`## Collection: \`${collection.slug}\` — ${collection.labels.plural}`);
|
|
245
|
+
out.push("");
|
|
246
|
+
const flags = [
|
|
247
|
+
collection.drafts ? "drafts" : null,
|
|
248
|
+
collection.versions ? "versioned" : null,
|
|
249
|
+
collection.searchable ? "searchable" : null,
|
|
250
|
+
].filter(Boolean);
|
|
251
|
+
out.push(
|
|
252
|
+
`Table \`${collection.table}\` · label field \`${collection.labelField}\`${flags.length ? " · " + flags.join(", ") : ""}`,
|
|
253
|
+
);
|
|
254
|
+
out.push("");
|
|
255
|
+
out.push(
|
|
256
|
+
table(
|
|
257
|
+
["field", "type", "control", "req", "i18n", "value shape"],
|
|
258
|
+
Object.values(collection.fields).map((f) => fieldRow(f as Record<string, unknown>)),
|
|
259
|
+
),
|
|
260
|
+
);
|
|
261
|
+
out.push("");
|
|
262
|
+
|
|
263
|
+
// Inline / block registries
|
|
264
|
+
for (const f of Object.values(collection.fields) as Array<Record<string, unknown>>) {
|
|
265
|
+
if (!f.blockTypes) continue;
|
|
266
|
+
out.push(`### \`${f.name}\` block types`);
|
|
267
|
+
out.push("");
|
|
268
|
+
for (const [blockType, fieldMap] of Object.entries(f.blockTypes as Record<string, Record<string, unknown>>)) {
|
|
269
|
+
const sub = Object.values(fieldMap).map(
|
|
270
|
+
(sf) => `${(sf as { name: string }).name}: ${(sf as { type: string }).type}`,
|
|
271
|
+
);
|
|
272
|
+
out.push(`- **${blockType}** — ${sub.join(", ")}`);
|
|
273
|
+
}
|
|
274
|
+
out.push("");
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return out.join("\n");
|
|
278
|
+
};
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { eq, lt, sql } from "drizzle-orm";
|
|
2
|
+
|
|
3
|
+
import { getDb } from "./runtime";
|
|
4
|
+
import { getSchema } from "./schema";
|
|
5
|
+
|
|
6
|
+
export type RateLimitResult = { ok: boolean; retryAfterMs: number };
|
|
7
|
+
export type RateLimitOptions = {
|
|
8
|
+
max: number;
|
|
9
|
+
windowMs: number;
|
|
10
|
+
/** On a DB error, reject (true) or allow (false). Reject for auth-critical endpoints. */
|
|
11
|
+
failClosed?: boolean;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
// Bound the stored key: callers pass IPs/emails/token-hashes, so hash+truncate to a fixed
|
|
15
|
+
// length rather than storing raw (unbounded) identifiers as primary keys.
|
|
16
|
+
const keyId = async (bucket: string, key: string): Promise<string> => {
|
|
17
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${bucket}:${key}`));
|
|
18
|
+
return [...new Uint8Array(digest)]
|
|
19
|
+
.slice(0, 16)
|
|
20
|
+
.map((b) => b.toString(16).padStart(2, "0"))
|
|
21
|
+
.join("");
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** Read-only: is this key already at/over its limit? Does NOT increment. */
|
|
25
|
+
export const peekRateLimit = async (bucket: string, key: string, opts: RateLimitOptions): Promise<RateLimitResult> => {
|
|
26
|
+
const { max, windowMs, failClosed = false } = opts;
|
|
27
|
+
const now = Date.now();
|
|
28
|
+
try {
|
|
29
|
+
const db = await getDb();
|
|
30
|
+
const t = getSchema().cmsRateLimits;
|
|
31
|
+
const rows = await db
|
|
32
|
+
.select()
|
|
33
|
+
.from(t)
|
|
34
|
+
.where(eq(t._id, await keyId(bucket, key)))
|
|
35
|
+
.limit(1);
|
|
36
|
+
const row = rows[0];
|
|
37
|
+
if (!row) return { ok: true, retryAfterMs: 0 };
|
|
38
|
+
const windowStart = Number(row.windowStart);
|
|
39
|
+
if (windowStart + windowMs <= now) return { ok: true, retryAfterMs: 0 }; // window elapsed
|
|
40
|
+
if (Number(row.count) >= max) return { ok: false, retryAfterMs: Math.max(0, windowStart + windowMs - now) };
|
|
41
|
+
return { ok: true, retryAfterMs: 0 };
|
|
42
|
+
} catch {
|
|
43
|
+
return { ok: !failClosed, retryAfterMs: failClosed ? windowMs : 0 };
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// Shared atomic upsert: one statement both increments and resets an elapsed window, so a
|
|
48
|
+
// lapsed window can't leave a stale high count. RETURNING avoids driver result-shape deps.
|
|
49
|
+
const bump = async (bucket: string, key: string, windowMs: number, now: number) => {
|
|
50
|
+
const db = await getDb();
|
|
51
|
+
const t = getSchema().cmsRateLimits;
|
|
52
|
+
const expired = sql`${t.windowStart} + ${windowMs} <= ${now}`;
|
|
53
|
+
const rows = await db
|
|
54
|
+
.insert(t)
|
|
55
|
+
.values({ _id: await keyId(bucket, key), windowStart: now, count: 1, expiresAt: now + windowMs })
|
|
56
|
+
.onConflictDoUpdate({
|
|
57
|
+
target: t._id,
|
|
58
|
+
set: {
|
|
59
|
+
windowStart: sql`CASE WHEN ${expired} THEN ${now} ELSE ${t.windowStart} END`,
|
|
60
|
+
count: sql`CASE WHEN ${expired} THEN 1 ELSE ${t.count} + 1 END`,
|
|
61
|
+
expiresAt: sql`CASE WHEN ${expired} THEN ${now + windowMs} ELSE ${t.expiresAt} END`,
|
|
62
|
+
},
|
|
63
|
+
})
|
|
64
|
+
.returning({ count: t.count, windowStart: t.windowStart });
|
|
65
|
+
return { count: Number(rows[0]?.count ?? 1), windowStart: Number(rows[0]?.windowStart ?? now) };
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** Increment the counter for one occurrence (e.g. a failed login). Best-effort. */
|
|
69
|
+
export const recordRateLimit = async (bucket: string, key: string, opts: RateLimitOptions): Promise<void> => {
|
|
70
|
+
try {
|
|
71
|
+
await bump(bucket, key, opts.windowMs, Date.now());
|
|
72
|
+
} catch {
|
|
73
|
+
// best-effort — a failed limiter write must not break the request path
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** Increment-and-check for endpoints where every request counts (forgot/reset/setup/invite). */
|
|
78
|
+
export const hitRateLimit = async (bucket: string, key: string, opts: RateLimitOptions): Promise<RateLimitResult> => {
|
|
79
|
+
const { max, windowMs, failClosed = false } = opts;
|
|
80
|
+
const now = Date.now();
|
|
81
|
+
try {
|
|
82
|
+
const { count, windowStart } = await bump(bucket, key, windowMs, now);
|
|
83
|
+
if (count > max) return { ok: false, retryAfterMs: Math.max(0, windowStart + windowMs - now) };
|
|
84
|
+
return { ok: true, retryAfterMs: 0 };
|
|
85
|
+
} catch {
|
|
86
|
+
return { ok: !failClosed, retryAfterMs: failClosed ? windowMs : 0 };
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/** Reset a key's counter — e.g. an account's failed-login budget after a success. */
|
|
91
|
+
export const clearRateLimit = async (bucket: string, key: string): Promise<void> => {
|
|
92
|
+
try {
|
|
93
|
+
const db = await getDb();
|
|
94
|
+
const t = getSchema().cmsRateLimits;
|
|
95
|
+
await db.delete(t).where(eq(t._id, await keyId(bucket, key)));
|
|
96
|
+
} catch {
|
|
97
|
+
// best-effort
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** Remove expired windows. Called from the cron tick — no in-process timers on Workers. */
|
|
102
|
+
export const pruneRateLimits = async (now = Date.now()): Promise<void> => {
|
|
103
|
+
try {
|
|
104
|
+
const db = await getDb();
|
|
105
|
+
const t = getSchema().cmsRateLimits;
|
|
106
|
+
await db.delete(t).where(lt(t.expiresAt, now));
|
|
107
|
+
} catch {
|
|
108
|
+
// best-effort
|
|
109
|
+
}
|
|
110
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
|
|
3
|
+
export type RequestScope = {
|
|
4
|
+
/** Keep background work alive until the response is flushed (Cloudflare waitUntil / Node no-op). */
|
|
5
|
+
defer: (task: Promise<unknown>) => void;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
const storage = new AsyncLocalStorage<RequestScope>();
|
|
9
|
+
|
|
10
|
+
/** Run `fn` inside a request scope so deferred work routes to this request only. */
|
|
11
|
+
export const runWithRequestScope = <T>(scope: RequestScope, fn: () => T): T => storage.run(scope, fn);
|
|
12
|
+
|
|
13
|
+
// Fallback outside a request (scripts) — drained by flushTasks(), never crosses requests.
|
|
14
|
+
const scriptTasks = new Set<Promise<unknown>>();
|
|
15
|
+
|
|
16
|
+
/** Defer fire-and-forget work: to the active request scope, or scriptTasks outside one. */
|
|
17
|
+
export const trackTask = <T>(task: Promise<T>): Promise<T> => {
|
|
18
|
+
const scope = storage.getStore();
|
|
19
|
+
if (scope) {
|
|
20
|
+
scope.defer(task.catch(() => {}));
|
|
21
|
+
} else {
|
|
22
|
+
scriptTasks.add(task);
|
|
23
|
+
void task.catch(() => {}).finally(() => scriptTasks.delete(task));
|
|
24
|
+
}
|
|
25
|
+
return task;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** Await all script-level deferred tasks (used by createCmsContext before dispose). */
|
|
29
|
+
export const flushTasks = async (): Promise<void> => {
|
|
30
|
+
while (scriptTasks.size) {
|
|
31
|
+
await Promise.allSettled([...scriptTasks]);
|
|
32
|
+
}
|
|
33
|
+
};
|
package/core/richtext.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createRichTextFromPlainText, htmlToRichText, renderRichText, richTextToPlainText } from "./values";
|
package/core/runtime.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export type CmsStorageAdapter = {
|
|
2
|
+
putFile: (storagePath: string, data: ArrayBuffer | Uint8Array) => Promise<void>;
|
|
3
|
+
getFile: (storagePath: string) => Promise<ArrayBuffer | null>;
|
|
4
|
+
deleteFile: (storagePath: string) => Promise<void>;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export type CmsEmailAdapter = {
|
|
8
|
+
sendInviteEmail: (to: string, inviteUrl: string) => Promise<boolean>;
|
|
9
|
+
sendPasswordResetEmail?: (to: string, resetUrl: string) => Promise<boolean>;
|
|
10
|
+
isEmailConfigured: () => boolean;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type CmsRuntimeConfig = {
|
|
14
|
+
getDb: () => Promise<any>;
|
|
15
|
+
closeDb?: () => void | Promise<void>;
|
|
16
|
+
storage: CmsStorageAdapter;
|
|
17
|
+
email?: CmsEmailAdapter;
|
|
18
|
+
env?: (key: string) => string | undefined;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
let runtime: CmsRuntimeConfig | null = null;
|
|
22
|
+
|
|
23
|
+
const runtimeError = () =>
|
|
24
|
+
new Error(
|
|
25
|
+
"../core runtime not initialized. Call configureCmsRuntime(...) and initSchema(...) from your app before using runtime APIs.",
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
export const configureCmsRuntime = (config: CmsRuntimeConfig) => {
|
|
29
|
+
runtime = config;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const resetCmsRuntime = () => {
|
|
33
|
+
runtime = null;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export const getCmsRuntime = (): CmsRuntimeConfig => {
|
|
37
|
+
if (!runtime) throw runtimeError();
|
|
38
|
+
return runtime;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export const getDb = () => getCmsRuntime().getDb();
|
|
42
|
+
|
|
43
|
+
// Returns the adapter's result so `await closeDb()` waits for teardown
|
|
44
|
+
// (on Cloudflare this disposes the local platform proxy used by Node scripts).
|
|
45
|
+
export const closeDb = (): void | Promise<void> => getCmsRuntime().closeDb?.();
|
|
46
|
+
|
|
47
|
+
export const getStorage = (): CmsStorageAdapter => getCmsRuntime().storage;
|
|
48
|
+
|
|
49
|
+
export const getEmail = (): CmsEmailAdapter => {
|
|
50
|
+
const email = getCmsRuntime().email;
|
|
51
|
+
return (
|
|
52
|
+
email ?? {
|
|
53
|
+
sendInviteEmail: async () => false,
|
|
54
|
+
isEmailConfigured: () => false,
|
|
55
|
+
}
|
|
56
|
+
);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export const readEnv = (key: string): string | undefined => getCmsRuntime().env?.(key) ?? process.env[key];
|
|
60
|
+
|
|
61
|
+
// Background work is request-scoped (see request-scope.ts); re-exported here for existing imports.
|
|
62
|
+
export { trackTask, flushTasks, runWithRequestScope } from "./request-scope";
|
|
63
|
+
export type { RequestScope } from "./request-scope";
|
package/core/schema.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
type SchemaModule = {
|
|
2
|
+
cmsTables: Record<string, { main: any; translations?: any; versions?: any }>;
|
|
3
|
+
cmsAssets: any;
|
|
4
|
+
cmsAssetFolders: any;
|
|
5
|
+
cmsSessions: any;
|
|
6
|
+
cmsLocks: any;
|
|
7
|
+
cmsInvites: any;
|
|
8
|
+
cmsRateLimits: any;
|
|
9
|
+
cmsAuditLog: any;
|
|
10
|
+
cmsOutbox: any;
|
|
11
|
+
cmsCollaboration: any;
|
|
12
|
+
cmsComments: any;
|
|
13
|
+
[key: string]: any;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
let schema: SchemaModule | null = null;
|
|
17
|
+
|
|
18
|
+
export const initSchema = (nextSchema: SchemaModule) => {
|
|
19
|
+
schema = nextSchema;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const resetSchema = () => {
|
|
23
|
+
schema = null;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export const getSchema = (): SchemaModule => {
|
|
27
|
+
if (!schema) {
|
|
28
|
+
throw new Error("../core schema not initialized. Call initSchema(...) from your app before using runtime APIs.");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return schema;
|
|
32
|
+
};
|