@kidecms/core 0.29.2 → 0.30.1

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/core/api.ts CHANGED
@@ -29,9 +29,11 @@ export type FindOptions = {
29
29
  * With `locale`: `"fallback"` (default) returns every document, overlaying the
30
30
  * translation when one exists; `"exact"` returns only documents that exist in
31
31
  * that locale — their source locale, or a translation row. Use `"exact"` for
32
- * listings and `"fallback"` for single-document routes.
32
+ * listings and `"fallback"` for single-document routes. `"missing"` is the
33
+ * complement of `"exact"`: documents that don't exist in that locale yet
34
+ * (e.g. a translation to-do list).
33
35
  */
34
- availability?: "fallback" | "exact";
36
+ availability?: "fallback" | "exact" | "missing";
35
37
  search?: string;
36
38
  };
37
39
 
@@ -473,11 +475,17 @@ export const createCms = (config: CMSConfig) => {
473
475
  if (!supportedLocales.includes(locale)) throw new Error(`Locale "${locale}" is not in locales.supported.`);
474
476
  return locale;
475
477
  };
476
- /** `availability: "exact"` — the document must exist in the requested locale. */
478
+ /**
479
+ * `availability: "exact"` — the document must exist in the requested locale;
480
+ * `"missing"` — it must not (neither its source locale nor a translation).
481
+ */
477
482
  const availabilityCondition = (tables: any, options: { locale?: string; availability?: string }) => {
478
- if (!options.locale || options.availability !== "exact" || !tables.translations || !config.locales) return null;
483
+ const { availability } = options;
484
+ if (!options.locale || (availability !== "exact" && availability !== "missing")) return null;
485
+ if (!tables.translations || !config.locales) return null;
479
486
  const tr = tables.translations;
480
- return sql`(${tables.main._sourceLocale} = ${options.locale} OR EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale}))`;
487
+ const exists = sql`(${tables.main._sourceLocale} = ${options.locale} OR EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale}))`;
488
+ return availability === "exact" ? exists : sql`NOT ${exists}`;
481
489
  };
482
490
 
483
491
  const overlayLocale = (
@@ -4,6 +4,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, watch,
4
4
  import { createRequire } from "node:module";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
+ import { analyzeSharedDeps, formatConflicts } from "./shared-deps";
7
8
 
8
9
  // All runtime files resolve relative to this module, never the project root, so
9
10
  // the integration works identically embedded (workspace package in the project
@@ -113,9 +114,17 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
113
114
  return {
114
115
  name: "kide-cms",
115
116
  hooks: {
116
- "astro:config:setup": ({ command, updateConfig, injectRoute, injectScript, addMiddleware }) => {
117
+ "astro:config:setup": ({ command, updateConfig, injectRoute, injectScript, addMiddleware, logger }) => {
117
118
  const root = process.cwd();
118
119
 
120
+ // One copy per library the admin shares with the project — see shared-deps.ts.
121
+ const sharedDeps = analyzeSharedDeps({
122
+ projectRoot: root,
123
+ packageFile: packagePath("package.json"),
124
+ dependencies: JSON.parse(readFileSync(packagePath("package.json"), "utf8")).dependencies ?? {},
125
+ });
126
+ if (sharedDeps.conflicts.length > 0) logger.warn(formatConflicts(sharedDeps.conflicts));
127
+
119
128
  // Generate a wrapper CSS: Tailwind sources + the core admin chrome +
120
129
  // the project's theme file. Chrome (layers, focus, editor styles,
121
130
  // variants) is core-owned and updates with the package; the project
@@ -180,8 +189,9 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
180
189
  "virtual:kide/admin-css": wrapperCss,
181
190
  "virtual:kide/custom-fields": customFieldsBarrel,
182
191
  },
183
- // Two React copies (project + package) break hooks/context identity.
184
- dedupe: ["react", "react-dom"],
192
+ // Two React copies (project + package) break hooks/context identity, and two
193
+ // copies of any admin UI library break Vite's pre-bundling (shared-deps.ts).
194
+ dedupe: ["react", "react-dom", ...sharedDeps.dedupe],
185
195
  },
186
196
  // The package ships TypeScript/Astro source — Vite must compile it
187
197
  // rather than treat it as an external Node dependency in SSR.
package/internals/mcp.ts CHANGED
@@ -199,7 +199,7 @@ server.registerTool(
199
199
  {
200
200
  title: "List documents",
201
201
  description:
202
- "List documents in a collection with optional filters, search, sort, locale, status, limit, and offset. With locale, availability 'exact' lists only documents that exist in that locale (their _sourceLocale or a translation); the default 'fallback' lists every document.",
202
+ "List documents in a collection with optional filters, search, sort, locale, status, limit, and offset. With locale, availability 'exact' lists only documents that exist in that locale (their _sourceLocale or a translation), 'missing' only those that don't; the default 'fallback' lists every document.",
203
203
  inputSchema: {
204
204
  collection: z.string().min(1),
205
205
  where: jsonObjectSchema.optional(),
@@ -209,7 +209,7 @@ server.registerTool(
209
209
  offset: z.number().int().min(0).default(0),
210
210
  status: statusSchema.optional(),
211
211
  locale: z.string().min(1).optional(),
212
- availability: z.enum(["fallback", "exact"]).optional(),
212
+ availability: z.enum(["fallback", "exact", "missing"]).optional(),
213
213
  },
214
214
  },
215
215
  async (args) => toResult(await workerCall("listDocuments", args)),
@@ -226,7 +226,7 @@ server.registerTool(
226
226
  search: z.string().optional(),
227
227
  status: statusSchema.optional(),
228
228
  locale: z.string().min(1).optional(),
229
- availability: z.enum(["fallback", "exact"]).optional(),
229
+ availability: z.enum(["fallback", "exact", "missing"]).optional(),
230
230
  },
231
231
  },
232
232
  async (args) => toResult(await workerCall("countDocuments", args)),
@@ -0,0 +1,126 @@
1
+ // Libraries the admin shares with the host project.
2
+ //
3
+ // The admin's React islands import the package's own UI dependencies
4
+ // (@base-ui/react, lucide-react, TipTap, …). When the project installs its own
5
+ // copy of one of them — typically by adding shadcn/ui components for the public
6
+ // site — the browser graph contains two copies under one bare specifier. Vite
7
+ // pre-bundles each specifier once, so the two copies keep invalidating each
8
+ // other's bundle: requests 504 with "Outdated Optimize Dep", admin islands fail
9
+ // to hydrate, and every rich field renders empty (the data itself is fine).
10
+ //
11
+ // Resolution: when the project's copy satisfies the range this package declares,
12
+ // dedupe to it (one copy, and the admin runs on a version it supports). When it
13
+ // doesn't, deduping could break the admin, so warn with the exact fix instead.
14
+
15
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
16
+ import path from "node:path";
17
+
18
+ /** Package dependencies that never reach the browser — no hydration risk. */
19
+ const SERVER_ONLY = new Set([
20
+ "ai",
21
+ "@ai-sdk/openai",
22
+ "@modelcontextprotocol/sdk",
23
+ "drizzle-kit",
24
+ "tsx",
25
+ "tw-animate-css",
26
+ ]);
27
+
28
+ type Version = [number, number, number];
29
+
30
+ const parseVersion = (value: string): Version | null => {
31
+ const match = value.trim().match(/^v?(\d+)\.(\d+)\.(\d+)/);
32
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
33
+ };
34
+
35
+ const compare = (a: Version, b: Version) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
36
+
37
+ /**
38
+ * Whether `version` falls inside `range`. Supports the forms package manifests
39
+ * actually use here: `^x.y.z`, `~x.y.z` and exact `x.y.z`. Returns null for
40
+ * anything else, so callers can stay silent instead of guessing.
41
+ */
42
+ export const satisfiesRange = (version: string, range: string): boolean | null => {
43
+ const v = parseVersion(version);
44
+ const operator = range.trim().match(/^[\^~]/)?.[0] ?? "";
45
+ const base = parseVersion(range.trim().slice(operator.length));
46
+ if (!v || !base) return null;
47
+ if (!/^[\^~]?v?\d+\.\d+\.\d+$/.test(range.trim())) return null;
48
+ if (operator === "") return compare(v, base) === 0;
49
+ if (compare(v, base) < 0) return false;
50
+ if (operator === "~") return v[0] === base[0] && v[1] === base[1];
51
+ // Caret: the left-most non-zero component is fixed.
52
+ if (base[0] > 0) return v[0] === base[0];
53
+ if (base[1] > 0) return v[0] === 0 && v[1] === base[1];
54
+ return v[0] === 0 && v[1] === 0 && v[2] === base[2];
55
+ };
56
+
57
+ export type SharedDepConflict = { name: string; range: string; projectVersion: string };
58
+
59
+ export type SharedDepReport = {
60
+ /** Deduped to the project's copy (compatible with this package's range). */
61
+ dedupe: string[];
62
+ /** Project copies outside this package's range — the admin keeps its own. */
63
+ conflicts: SharedDepConflict[];
64
+ };
65
+
66
+ /**
67
+ * Directory of the copy of `name` that `fromFile` resolves through its own
68
+ * node_modules chain. Deliberately not `require.resolve.paths()`: that appends
69
+ * NODE_PATH, which `pnpm dev`/`pnpm exec` point at pnpm's hoisted store, so every
70
+ * package would appear to have a project copy.
71
+ */
72
+ const locatePackage = (name: string, fromFile: string): string | null => {
73
+ let dir = path.dirname(path.resolve(fromFile));
74
+ for (;;) {
75
+ const manifest = path.join(dir, "node_modules", name, "package.json");
76
+ if (existsSync(manifest)) return realpathSync(path.dirname(manifest));
77
+ const parent = path.dirname(dir);
78
+ if (parent === dir) return null;
79
+ dir = parent;
80
+ }
81
+ };
82
+
83
+ const readVersion = (dir: string) => {
84
+ try {
85
+ return String(JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")).version ?? "");
86
+ } catch {
87
+ return "";
88
+ }
89
+ };
90
+
91
+ /**
92
+ * Compare this package's browser dependencies with the copies the project
93
+ * resolves from its root. Only packages the project actually has a separate copy
94
+ * of are reported.
95
+ */
96
+ export const analyzeSharedDeps = (options: {
97
+ projectRoot: string;
98
+ /** A file inside this package, used as the resolution origin for its own deps. */
99
+ packageFile: string;
100
+ dependencies: Record<string, string>;
101
+ }): SharedDepReport => {
102
+ const projectFile = path.join(options.projectRoot, "package.json");
103
+ const report: SharedDepReport = { dedupe: [], conflicts: [] };
104
+
105
+ for (const [name, range] of Object.entries(options.dependencies)) {
106
+ if (SERVER_ONLY.has(name)) continue;
107
+ const projectDir = locatePackage(name, projectFile);
108
+ const packageDir = locatePackage(name, options.packageFile);
109
+ if (!projectDir || !packageDir || projectDir === packageDir) continue;
110
+
111
+ const projectVersion = readVersion(projectDir);
112
+ const compatible = satisfiesRange(projectVersion, range);
113
+ if (compatible === true) report.dedupe.push(name);
114
+ else if (compatible === false) report.conflicts.push({ name, range, projectVersion });
115
+ }
116
+ return report;
117
+ };
118
+
119
+ export const formatConflicts = (conflicts: SharedDepConflict[]) =>
120
+ [
121
+ "This project installs its own copy of libraries the admin uses, at versions the admin doesn't support:",
122
+ ...conflicts.map((c) => ` ${c.name} ${c.projectVersion} (admin requires ${c.range})`),
123
+ ' Two copies make Vite re-bundle dependencies in a loop (504 "Outdated Optimize Dep"), so admin',
124
+ " editors fail to load and fields look empty. Align the project's versions, then run `pnpm dev:clean`:",
125
+ ` pnpm add ${conflicts.map((c) => `${c.name}@"${c.range}"`).join(" ")}`,
126
+ ].join("\n");
@@ -271,6 +271,9 @@ const changedFilesJson = (repoDir: string, fromCommit: string, toCommit: string)
271
271
  const isManagedRuntimePath = (file: string, corePath: string) => {
272
272
  // Legacy seed-data file may carry user customizations — careful review, not auto-apply.
273
273
  if (file === `${corePath}/internals/seed.data.ts`) return false;
274
+ // The @kidecms/core manifest carries the managed runtime's own dependencies; without it
275
+ // an upgrade ships code that imports packages the project never installs.
276
+ if (file === `${corePath}/package.json`) return true;
274
277
 
275
278
  const managedPrefixes = [
276
279
  `${corePath}/admin`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.29.2",
3
+ "version": "0.30.1",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",
@@ -51,33 +51,33 @@
51
51
  "access": "public"
52
52
  },
53
53
  "dependencies": {
54
- "@ai-sdk/openai": "^3.0.41",
55
- "@base-ui/react": "^1.3.0",
54
+ "@ai-sdk/openai": "^3.0.114",
55
+ "@base-ui/react": "^1.8.0",
56
56
  "@dnd-kit/core": "^6.3.1",
57
57
  "@dnd-kit/sortable": "^10.0.0",
58
58
  "@dnd-kit/utilities": "^3.2.2",
59
- "@modelcontextprotocol/sdk": "^1.29.0",
60
- "@radix-ui/react-dropdown-menu": "^2.1.16",
61
- "@radix-ui/react-popover": "^1.1.15",
59
+ "@modelcontextprotocol/sdk": "^1.30.0",
60
+ "@radix-ui/react-dropdown-menu": "^2.1.24",
61
+ "@radix-ui/react-popover": "^1.1.23",
62
62
  "@tanstack/react-table": "^8.21.3",
63
- "@tiptap/core": "3.22.4",
64
- "@tiptap/extension-image": "3.22.4",
65
- "@tiptap/extension-link": "3.22.4",
66
- "@tiptap/extension-placeholder": "3.22.4",
67
- "@tiptap/markdown": "3.22.4",
68
- "@tiptap/pm": "3.22.4",
69
- "@tiptap/react": "3.22.4",
70
- "@tiptap/starter-kit": "3.22.4",
71
- "@tiptap/suggestion": "3.22.4",
72
- "ai": "^6.0.116",
63
+ "@tiptap/core": "3.31.3",
64
+ "@tiptap/extension-image": "3.31.3",
65
+ "@tiptap/extension-link": "3.31.3",
66
+ "@tiptap/extension-placeholder": "3.31.3",
67
+ "@tiptap/markdown": "3.31.3",
68
+ "@tiptap/pm": "3.31.3",
69
+ "@tiptap/react": "3.31.3",
70
+ "@tiptap/starter-kit": "3.31.3",
71
+ "@tiptap/suggestion": "3.31.3",
72
+ "ai": "^6.0.286",
73
73
  "class-variance-authority": "^0.7.1",
74
74
  "clsx": "^2.1.1",
75
75
  "cmdk": "^1.1.1",
76
- "drizzle-kit": "^0.31.9",
77
- "lucide-react": "^0.577.0",
76
+ "drizzle-kit": "^0.31.10",
77
+ "lucide-react": "^1.47.0",
78
78
  "nanoid": "^6.0.1",
79
- "tailwind-merge": "^3.5.0",
80
- "tsx": "^4.21.0",
79
+ "tailwind-merge": "^3.7.0",
80
+ "tsx": "^4.23.13",
81
81
  "tw-animate-css": "^1.4.0"
82
82
  },
83
83
  "peerDependencies": {
@@ -13,11 +13,13 @@ const RATE_MAX = 10; // submissions per IP per window
13
13
  const RATE_WINDOW_MS = 10 * 60 * 1000;
14
14
 
15
15
  type FormFieldConfig = {
16
- type: "text" | "email" | "textarea" | "select" | "checkbox";
16
+ type: "text" | "email" | "tel" | "number" | "textarea" | "select" | "radio" | "checkbox";
17
17
  name: string;
18
18
  label: string;
19
19
  required?: boolean;
20
20
  maxLength?: number;
21
+ min?: number;
22
+ max?: number;
21
23
  options?: string[];
22
24
  };
23
25
 
@@ -89,11 +91,34 @@ export const POST: APIRoute = async ({ request, params, redirect, clientAddress
89
91
  continue;
90
92
  }
91
93
 
92
- if (field.type === "select" && value && Array.isArray(field.options) && !field.options.includes(String(value))) {
94
+ // A choice field only ever accepts one of its declared options — the browser
95
+ // constrains the visible control, the server is what makes it true.
96
+ if (
97
+ (field.type === "select" || field.type === "radio") &&
98
+ value &&
99
+ Array.isArray(field.options) &&
100
+ !field.options.includes(String(value))
101
+ ) {
93
102
  errors.push(`${field.label} has an invalid value`);
94
103
  continue;
95
104
  }
96
105
 
106
+ if (field.type === "number" && value !== "") {
107
+ const parsed = Number(value);
108
+ if (!Number.isFinite(parsed)) {
109
+ errors.push(`${field.label} must be a number`);
110
+ continue;
111
+ }
112
+ if (field.min !== undefined && parsed < field.min) {
113
+ errors.push(`${field.label} must be ${field.min} or more`);
114
+ continue;
115
+ }
116
+ if (field.max !== undefined && parsed > field.max) {
117
+ errors.push(`${field.label} must be ${field.max} or less`);
118
+ continue;
119
+ }
120
+ }
121
+
97
122
  data[field.name] = value;
98
123
  }
99
124