@conloca/content-api 0.1.16 → 0.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 (299) hide show
  1. package/dist/asset-constraints.d.ts +16 -0
  2. package/dist/asset-constraints.d.ts.map +1 -0
  3. package/dist/asset-constraints.js +29 -0
  4. package/dist/asset-constraints.js.map +1 -0
  5. package/dist/asset-metadata-store.d.ts +60 -0
  6. package/dist/asset-metadata-store.d.ts.map +1 -0
  7. package/dist/asset-metadata-store.js +335 -0
  8. package/dist/asset-metadata-store.js.map +1 -0
  9. package/dist/asset-operations.d.ts +18 -13
  10. package/dist/asset-operations.d.ts.map +1 -1
  11. package/dist/asset-operations.js +302 -254
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +23 -7
  14. package/dist/asset-types.d.ts.map +1 -1
  15. package/dist/asset-types.js +8 -2
  16. package/dist/asset-types.js.map +1 -0
  17. package/dist/asset-usage.d.ts +10 -0
  18. package/dist/asset-usage.d.ts.map +1 -0
  19. package/dist/asset-usage.js +49 -0
  20. package/dist/asset-usage.js.map +1 -0
  21. package/dist/base-content-index.d.ts +8 -2
  22. package/dist/base-content-index.d.ts.map +1 -1
  23. package/dist/base-content-index.js +24 -3
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.js +1 -0
  26. package/dist/cf-access.js.map +1 -0
  27. package/dist/component-registry.d.ts +1 -1
  28. package/dist/component-registry.d.ts.map +1 -1
  29. package/dist/component-registry.js +2 -1
  30. package/dist/component-registry.js.map +1 -0
  31. package/dist/component-registry.types.js +1 -0
  32. package/dist/component-registry.types.js.map +1 -0
  33. package/dist/component-vocabulary.d.ts +33 -0
  34. package/dist/component-vocabulary.d.ts.map +1 -0
  35. package/dist/component-vocabulary.js +105 -0
  36. package/dist/component-vocabulary.js.map +1 -0
  37. package/dist/content-api.interface.d.ts +5 -5
  38. package/dist/content-api.interface.d.ts.map +1 -1
  39. package/dist/content-api.interface.js +1 -0
  40. package/dist/content-api.interface.js.map +1 -0
  41. package/dist/content-filters.d.ts +2 -2
  42. package/dist/content-filters.d.ts.map +1 -1
  43. package/dist/content-filters.js +9 -8
  44. package/dist/content-filters.js.map +1 -0
  45. package/dist/content-index.d.ts +74 -16
  46. package/dist/content-index.d.ts.map +1 -1
  47. package/dist/content-index.js +183 -55
  48. package/dist/content-index.js.map +1 -0
  49. package/dist/content-operations.d.ts +71 -7
  50. package/dist/content-operations.d.ts.map +1 -1
  51. package/dist/content-operations.js +166 -82
  52. package/dist/content-operations.js.map +1 -0
  53. package/dist/content-path.d.ts +59 -0
  54. package/dist/content-path.d.ts.map +1 -0
  55. package/dist/content-path.js +88 -0
  56. package/dist/content-path.js.map +1 -0
  57. package/dist/content-reader.d.ts +2 -2
  58. package/dist/content-reader.d.ts.map +1 -1
  59. package/dist/content-reader.js +2 -1
  60. package/dist/content-reader.js.map +1 -0
  61. package/dist/content-utils.d.ts +53 -10
  62. package/dist/content-utils.d.ts.map +1 -1
  63. package/dist/content-utils.js +103 -34
  64. package/dist/content-utils.js.map +1 -0
  65. package/dist/content-watcher.d.ts +3 -3
  66. package/dist/content-watcher.d.ts.map +1 -1
  67. package/dist/content-watcher.js +13 -10
  68. package/dist/content-watcher.js.map +1 -0
  69. package/dist/data-index.d.ts +1 -1
  70. package/dist/data-index.d.ts.map +1 -1
  71. package/dist/data-index.js +2 -1
  72. package/dist/data-index.js.map +1 -0
  73. package/dist/data.d.ts +5 -13
  74. package/dist/data.d.ts.map +1 -1
  75. package/dist/data.js +7 -6
  76. package/dist/data.js.map +1 -0
  77. package/dist/editor-data-bindings.d.ts +10 -0
  78. package/dist/editor-data-bindings.d.ts.map +1 -0
  79. package/dist/editor-data-bindings.js +67 -0
  80. package/dist/editor-data-bindings.js.map +1 -0
  81. package/dist/etag-utils.d.ts.map +1 -1
  82. package/dist/etag-utils.js +5 -4
  83. package/dist/etag-utils.js.map +1 -0
  84. package/dist/filesystem-content-api.d.ts +45 -18
  85. package/dist/filesystem-content-api.d.ts.map +1 -1
  86. package/dist/filesystem-content-api.js +407 -281
  87. package/dist/filesystem-content-api.js.map +1 -0
  88. package/dist/filesystem-reader-backend.d.ts +46 -0
  89. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  90. package/dist/filesystem-reader-backend.js +119 -0
  91. package/dist/filesystem-reader-backend.js.map +1 -0
  92. package/dist/fragment-index.d.ts +8 -0
  93. package/dist/fragment-index.d.ts.map +1 -0
  94. package/dist/fragment-index.js +8 -0
  95. package/dist/fragment-index.js.map +1 -0
  96. package/dist/fragments.d.ts +16 -0
  97. package/dist/fragments.d.ts.map +1 -0
  98. package/dist/fragments.js +104 -0
  99. package/dist/fragments.js.map +1 -0
  100. package/dist/git-operations.d.ts.map +1 -1
  101. package/dist/git-operations.js +5 -1
  102. package/dist/git-operations.js.map +1 -0
  103. package/dist/header-parser.d.ts +4 -4
  104. package/dist/header-parser.d.ts.map +1 -1
  105. package/dist/header-parser.js +8 -61
  106. package/dist/header-parser.js.map +1 -0
  107. package/dist/in-memory-content-api.d.ts +7 -7
  108. package/dist/in-memory-content-api.d.ts.map +1 -1
  109. package/dist/in-memory-content-api.js +74 -56
  110. package/dist/in-memory-content-api.js.map +1 -0
  111. package/dist/index.d.ts +19 -12
  112. package/dist/index.d.ts.map +1 -1
  113. package/dist/index.js +21 -9
  114. package/dist/index.js.map +1 -0
  115. package/dist/indexing.d.ts +4 -4
  116. package/dist/indexing.d.ts.map +1 -1
  117. package/dist/indexing.js +6 -5
  118. package/dist/indexing.js.map +1 -0
  119. package/dist/json-whitespace-view.js +1 -0
  120. package/dist/json-whitespace-view.js.map +1 -0
  121. package/dist/middleware.d.ts +6 -6
  122. package/dist/middleware.d.ts.map +1 -1
  123. package/dist/middleware.js +170 -119
  124. package/dist/middleware.js.map +1 -0
  125. package/dist/node.d.ts +24 -17
  126. package/dist/node.d.ts.map +1 -1
  127. package/dist/node.js +17 -14
  128. package/dist/node.js.map +1 -0
  129. package/dist/page-references.d.ts +21 -0
  130. package/dist/page-references.d.ts.map +1 -0
  131. package/dist/page-references.js +50 -0
  132. package/dist/page-references.js.map +1 -0
  133. package/dist/read-date.d.ts +3 -0
  134. package/dist/read-date.d.ts.map +1 -0
  135. package/dist/read-date.js +9 -0
  136. package/dist/read-date.js.map +1 -0
  137. package/dist/reader-backend.d.ts +54 -0
  138. package/dist/reader-backend.d.ts.map +1 -0
  139. package/dist/reader-backend.js +2 -0
  140. package/dist/reader-backend.js.map +1 -0
  141. package/dist/reader.d.ts +8 -8
  142. package/dist/reader.d.ts.map +1 -1
  143. package/dist/reader.js +8 -7
  144. package/dist/reader.js.map +1 -0
  145. package/dist/schemas/index.d.ts +6 -6
  146. package/dist/schemas/index.d.ts.map +1 -1
  147. package/dist/schemas/index.js +9 -8
  148. package/dist/schemas/index.js.map +1 -0
  149. package/dist/site-index.d.ts +3 -3
  150. package/dist/site-index.d.ts.map +1 -1
  151. package/dist/site-index.js +9 -5
  152. package/dist/site-index.js.map +1 -0
  153. package/dist/site.d.ts +5 -3
  154. package/dist/site.d.ts.map +1 -1
  155. package/dist/site.js +14 -2
  156. package/dist/site.js.map +1 -0
  157. package/dist/types.d.ts +203 -15
  158. package/dist/types.d.ts.map +1 -1
  159. package/dist/types.js +9 -0
  160. package/dist/types.js.map +1 -0
  161. package/dist/url-safe-base64.js +1 -0
  162. package/dist/url-safe-base64.js.map +1 -0
  163. package/dist/url-validation.d.ts +14 -0
  164. package/dist/url-validation.d.ts.map +1 -1
  165. package/dist/url-validation.js +56 -14
  166. package/dist/url-validation.js.map +1 -0
  167. package/dist/utils/atomic-write.js +1 -0
  168. package/dist/utils/atomic-write.js.map +1 -0
  169. package/dist/utils.d.ts +1 -1
  170. package/dist/utils.js +2 -1
  171. package/dist/utils.js.map +1 -0
  172. package/dist/vite-plugin.d.ts +2 -2
  173. package/dist/vite-plugin.js +5 -4
  174. package/dist/vite-plugin.js.map +1 -0
  175. package/dist/vxjson-serialize.d.ts +5 -6
  176. package/dist/vxjson-serialize.d.ts.map +1 -1
  177. package/dist/vxjson-serialize.js +13 -10
  178. package/dist/vxjson-serialize.js.map +1 -0
  179. package/dist/vxjson.d.ts +4 -3
  180. package/dist/vxjson.d.ts.map +1 -1
  181. package/dist/vxjson.js +10 -20
  182. package/dist/vxjson.js.map +1 -0
  183. package/dist/xxhash.d.ts.map +1 -1
  184. package/dist/xxhash.js +6 -2
  185. package/dist/xxhash.js.map +1 -0
  186. package/package.json +92 -56
  187. package/src/asset-constraints.ts +33 -0
  188. package/src/asset-metadata-store.ts +401 -0
  189. package/src/asset-operations.ts +914 -0
  190. package/src/asset-types.ts +74 -0
  191. package/src/asset-usage.ts +47 -0
  192. package/src/base-content-index.ts +227 -0
  193. package/src/cf-access.ts +85 -0
  194. package/src/component-registry.ts +145 -0
  195. package/src/component-registry.types.ts +12 -0
  196. package/src/component-vocabulary.ts +87 -0
  197. package/src/content-api.interface.ts +94 -0
  198. package/src/content-filters.ts +278 -0
  199. package/src/content-index.ts +642 -0
  200. package/src/content-operations.ts +497 -0
  201. package/src/content-path.ts +113 -0
  202. package/src/content-reader.ts +18 -0
  203. package/src/content-utils.ts +474 -0
  204. package/src/content-watcher.ts +122 -0
  205. package/src/data-index.ts +7 -0
  206. package/src/data.ts +134 -0
  207. package/src/editor-data-bindings.ts +66 -0
  208. package/src/etag-utils.ts +204 -0
  209. package/src/filesystem-content-api.ts +2685 -0
  210. package/src/filesystem-reader-backend.ts +135 -0
  211. package/src/fragment-index.ts +7 -0
  212. package/src/fragments.ts +113 -0
  213. package/src/git-operations.ts +340 -0
  214. package/src/header-parser.ts +272 -0
  215. package/src/in-memory-content-api.ts +760 -0
  216. package/src/index.ts +45 -0
  217. package/src/indexing.ts +8 -0
  218. package/src/json-whitespace-view.ts +155 -0
  219. package/src/middleware.ts +1341 -0
  220. package/src/node.ts +40 -0
  221. package/src/page-references.ts +76 -0
  222. package/src/read-date.ts +7 -0
  223. package/src/reader-backend.ts +54 -0
  224. package/src/reader.ts +15 -0
  225. package/src/schemas/index.ts +113 -0
  226. package/src/site-index.ts +330 -0
  227. package/src/site.ts +198 -0
  228. package/src/types.ts +759 -0
  229. package/src/url-safe-base64.ts +38 -0
  230. package/src/url-validation.ts +121 -0
  231. package/src/utils/atomic-write.ts +20 -0
  232. package/src/utils.ts +84 -0
  233. package/src/vite-plugin.ts +45 -0
  234. package/src/vxjson-serialize.ts +66 -0
  235. package/src/vxjson.ts +442 -0
  236. package/src/xxhash.ts +43 -0
  237. package/dist/asset-manifest.d.ts +0 -23
  238. package/dist/asset-manifest.d.ts.map +0 -1
  239. package/dist/asset-manifest.js +0 -73
  240. package/dist/block-index.d.ts +0 -9
  241. package/dist/block-index.d.ts.map +0 -1
  242. package/dist/block-index.js +0 -11
  243. package/dist/blocks.d.ts +0 -16
  244. package/dist/blocks.d.ts.map +0 -1
  245. package/dist/blocks.js +0 -103
  246. package/dist/component-registry.types-C0ctF9nh.d.mts +0 -71
  247. package/dist/component-registry.types-C0ctF9nh.d.mts.map +0 -1
  248. package/dist/content-index-D092_vk1.mjs +0 -629
  249. package/dist/content-index-D092_vk1.mjs.map +0 -1
  250. package/dist/content-index-D6IVMmAB.d.mts +0 -127
  251. package/dist/content-index-D6IVMmAB.d.mts.map +0 -1
  252. package/dist/content-operations-DIbsxG5A.d.mts +0 -354
  253. package/dist/content-operations-DIbsxG5A.d.mts.map +0 -1
  254. package/dist/content-utils-fWNHTrPy.mjs +0 -280
  255. package/dist/content-utils-fWNHTrPy.mjs.map +0 -1
  256. package/dist/data-DquNIEnQ.mjs +0 -62
  257. package/dist/data-DquNIEnQ.mjs.map +0 -1
  258. package/dist/filesystem-content-api-B1KIQJfk.mjs +0 -2
  259. package/dist/filesystem-content-api-C0HIhqZi.mjs +0 -1620
  260. package/dist/filesystem-content-api-C0HIhqZi.mjs.map +0 -1
  261. package/dist/filesystem-content-api-DCdNi-co.d.mts +0 -134
  262. package/dist/filesystem-content-api-DCdNi-co.d.mts.map +0 -1
  263. package/dist/index-DxVTFK66.d.mts +0 -105
  264. package/dist/index-DxVTFK66.d.mts.map +0 -1
  265. package/dist/index.d.mts +0 -80
  266. package/dist/index.d.mts.map +0 -1
  267. package/dist/index.mjs +0 -78
  268. package/dist/index.mjs.map +0 -1
  269. package/dist/indexing.d.mts +0 -152
  270. package/dist/indexing.d.mts.map +0 -1
  271. package/dist/indexing.mjs +0 -255
  272. package/dist/indexing.mjs.map +0 -1
  273. package/dist/node.d.mts +0 -373
  274. package/dist/node.d.mts.map +0 -1
  275. package/dist/node.mjs +0 -2572
  276. package/dist/node.mjs.map +0 -1
  277. package/dist/reader.d.mts +0 -15
  278. package/dist/reader.d.mts.map +0 -1
  279. package/dist/reader.mjs +0 -22
  280. package/dist/reader.mjs.map +0 -1
  281. package/dist/schemas/index.d.mts +0 -2
  282. package/dist/schemas/index.mjs +0 -2
  283. package/dist/schemas-CFRD0FIQ.mjs +0 -84
  284. package/dist/schemas-CFRD0FIQ.mjs.map +0 -1
  285. package/dist/site-8oaj1Q60.mjs +0 -366
  286. package/dist/site-8oaj1Q60.mjs.map +0 -1
  287. package/dist/site-index-B_254bCc.d.mts +0 -136
  288. package/dist/site-index-B_254bCc.d.mts.map +0 -1
  289. package/dist/types-DOdldbfD.mjs +0 -34
  290. package/dist/types-DOdldbfD.mjs.map +0 -1
  291. package/dist/types-DjfhS272.d.mts +0 -456
  292. package/dist/types-DjfhS272.d.mts.map +0 -1
  293. package/dist/vxjson-qHrgLGip.mjs +0 -555
  294. package/dist/vxjson-qHrgLGip.mjs.map +0 -1
  295. package/dist/vxjson-serialize-geF6qvpn.mjs +0 -34
  296. package/dist/vxjson-serialize-geF6qvpn.mjs.map +0 -1
  297. package/dist/vxjson-serialize.d.mts +0 -17
  298. package/dist/vxjson-serialize.d.mts.map +0 -1
  299. package/dist/vxjson-serialize.mjs +0 -2
@@ -0,0 +1,474 @@
1
+ import { nanoid } from 'nanoid';
2
+ import yaml, { Document, isScalar } from 'yaml';
3
+ import { parseLocaleFilename } from './content-path.js';
4
+ import { readDate } from './read-date.js';
5
+ import type { ContentMeta, ContentMetaPatch } from './types.js';
6
+
7
+ // Pinned key order at the top of every .mdx frontmatter block. Anything not
8
+ // listed here is appended after, sorted alphabetically for determinism. Without
9
+ // this, the JS object insertion order in the update path leaks into the file
10
+ // and every save reshuffles the YAML keys, producing diff noise unrelated to
11
+ // the author's edit.
12
+ const FRONTMATTER_KEY_ORDER = [
13
+ 'title',
14
+ 'category',
15
+ 'description',
16
+ 'id',
17
+ 'created',
18
+ 'modified',
19
+ 'publishAt',
20
+ 'unpublishAt',
21
+ ] as const;
22
+
23
+ // ISO 8601 timestamps were authored with single quotes in the canonical
24
+ // fixtures (e.g. `created: '2026-05-07T18:07:39.049Z'`). yaml.stringify defaults
25
+ // to a plain (unquoted) scalar for strings that aren't ambiguous, which strips
26
+ // the quotes on every round-trip. We re-apply the single-quote style for any
27
+ // scalar value that looks like an ISO 8601 timestamp.
28
+ const ISO_TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
29
+
30
+ export function* localesOf<T>(manifest: { locales: Record<string, T | undefined> }): Generator<T> {
31
+ for (const value of Object.values(manifest.locales)) {
32
+ if (value) yield value;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Pure utility functions for content operations
38
+ * These functions don't depend on any class state and can be shared
39
+ * between FileSystemContentAPI, InMemoryContentAPI, and other implementations
40
+ */
41
+
42
+ /**
43
+ * Whether content is published at `now`: from its publish time on, until the
44
+ * instant its unpublish time arrives. Empty or invalid dates count as not set.
45
+ * Serving a page, the page feed, the site index and the status the editor
46
+ * shows for a page all ask this, so the site and the editor agree at the
47
+ * unpublish instant.
48
+ * The `published` listing filter asks a different question: whether any
49
+ * locale is still before its unpublish time.
50
+ *
51
+ * The schedule takes a locale version or a page entry. A page entry from the
52
+ * Astro schema holds Date values and nulls, and `undefined` is spelled out
53
+ * rather than left to `?:` so a host compiling with exactOptionalPropertyTypes
54
+ * can pass the entry straight in: its schedule keys can be present with no
55
+ * value.
56
+ */
57
+ export function isContentPublished(
58
+ schedule: { publishAt?: string | Date | null | undefined; unpublishAt?: string | Date | null | undefined },
59
+ now = new Date(),
60
+ ): boolean {
61
+ const publishAt = readDate(schedule.publishAt);
62
+ if (publishAt && publishAt > now) return false;
63
+
64
+ const unpublishAt = readDate(schedule.unpublishAt);
65
+ if (unpublishAt && unpublishAt <= now) return false;
66
+
67
+ return true;
68
+ }
69
+
70
+ /**
71
+ * Apply a dialog's metadata patch: absent keys keep the stored value, null
72
+ * deletes the field. Every update path merges through here so "clear" cannot
73
+ * silently regress back into "keep" at one of the spread sites.
74
+ */
75
+ export function applyMetaPatch(current: ContentMeta, patch: ContentMetaPatch): Partial<ContentMeta> {
76
+ return applyNullClearPatch(current, patch);
77
+ }
78
+
79
+ /**
80
+ * The underlying merge: null deletes, absent or undefined keeps. Shared by
81
+ * content metadata and asset-manifest updates so "clear" means one thing
82
+ * everywhere a dialog saves a fixed set of fields.
83
+ */
84
+ export function applyNullClearPatch<T extends object>(current: T, patch: { [K in keyof T]?: T[K] | null }): Partial<T> {
85
+ // Interfaces carry no index signature, so the spread needs the widened view.
86
+ const merged: Record<string, unknown> = { ...(current as Record<string, unknown>) };
87
+ for (const [key, value] of Object.entries(patch)) {
88
+ if (value === null) {
89
+ delete merged[key];
90
+ } else if (value !== undefined) {
91
+ if (key === '__proto__') {
92
+ // JSON keys are data, including this legacy prototype setter name.
93
+ Object.defineProperty(merged, key, { value, enumerable: true, configurable: true, writable: true });
94
+ } else {
95
+ merged[key] = value;
96
+ }
97
+ }
98
+ }
99
+ return merged as Partial<T>;
100
+ }
101
+
102
+ /**
103
+ * A meta field read as a string, or undefined when it holds anything else.
104
+ *
105
+ * Fields outside ContentMeta's declared set are typed as JsonValue, because
106
+ * that is all the format guarantees. Content meta is also hand-editable in
107
+ * git, so a reader that wants a string genuinely cannot assume it has one —
108
+ * narrowing here stops a malformed value from posing as a real one, which a
109
+ * cast would wave through. Takes `unknown` so it also serves callers holding
110
+ * meta in a looser shape than ContentMeta.
111
+ */
112
+ export function metaString(value: unknown): string | undefined {
113
+ return typeof value === 'string' ? value : undefined;
114
+ }
115
+
116
+ /**
117
+ * Validate that metadata doesn't exceed 4KB when serialized
118
+ * This ensures efficient indexing as per the specification
119
+ */
120
+ export function isMetadataTooLarge(meta: ContentMeta): boolean {
121
+ const size = new TextEncoder().encode(JSON.stringify(meta)).length;
122
+ return size > 4096;
123
+ }
124
+
125
+ /**
126
+ * Extract fragment name from various sources
127
+ * Used when displaying fragments in the UI
128
+ */
129
+ export function extractFragmentName(source: string): string {
130
+ // If it's a collection/name path, extract the name part
131
+ if (source.includes('/') && !source.includes('.')) {
132
+ const parts = source.split('/');
133
+ return parts[parts.length - 1];
134
+ }
135
+
136
+ // If it's a filename, extract the base name
137
+ if (source.includes('.')) {
138
+ // Same locale grammar as every reader (content-path.ts), so 'hero.en-US.mdx'
139
+ // displays as 'hero' rather than 'hero.en-US'. The whole source is passed
140
+ // on purpose — the greedy base tolerates '/', so 'heroes/main.en.mdx'
141
+ // names as 'heroes/main'.
142
+ const suffix = parseLocaleFilename(source);
143
+ if (suffix) {
144
+ return suffix.base;
145
+ }
146
+ // Fallback: remove any extension
147
+ return source.replace(/\.[^.]+$/, '');
148
+ }
149
+
150
+ // If it's an ID, create a simple name
151
+ if (source.startsWith('vx-')) {
152
+ return `fragment-${source.substring(3, 8)}`;
153
+ }
154
+
155
+ // Otherwise return as-is
156
+ return source;
157
+ }
158
+
159
+ /**
160
+ * Validate fragment name according to the specification
161
+ * - Cannot contain dots (reserved for locale separator)
162
+ * - Cannot contain slashes (would create subdirectories)
163
+ * - Cannot contain spaces (for clean filenames)
164
+ * - Must have at least one character
165
+ */
166
+ export function isValidFragmentName(name: string): boolean {
167
+ if (!name || name.length === 0) return false;
168
+ if (name.includes('.')) return false;
169
+ if (name.includes('/')) return false;
170
+ if (name.includes(' ')) return false;
171
+ return true;
172
+ }
173
+
174
+ /**
175
+ * Format file size for display with human-readable units
176
+ * @example formatFileSize(1536) // "1.5 KB"
177
+ */
178
+ export function formatFileSize(bytes: number): string {
179
+ if (bytes < 1024) return `${bytes} B`;
180
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
181
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
182
+ }
183
+
184
+ /**
185
+ * Calculate metadata size in bytes
186
+ */
187
+ export function getMetadataSize(meta: ContentMeta): number {
188
+ return new TextEncoder().encode(JSON.stringify(meta)).length;
189
+ }
190
+
191
+ /**
192
+ * Check if a pathname is valid
193
+ * - Must start with /
194
+ * - Cannot contain spaces (should be URL-encoded)
195
+ * - Cannot contain special characters that would break URLs
196
+ */
197
+ export function isValidPathname(pathname: string): boolean {
198
+ if (!pathname?.startsWith('/')) return false;
199
+ if (pathname.includes(' ')) return false;
200
+ if (pathname.includes('?') || pathname.includes('#')) return false;
201
+ return true;
202
+ }
203
+
204
+ /**
205
+ * Normalize a pathname to ensure consistency
206
+ * - Ensure it starts with /
207
+ * - Remove trailing slashes (except for root)
208
+ * - Collapse multiple slashes
209
+ */
210
+ export function normalizePathname(pathname: string): string {
211
+ if (!pathname) return '/';
212
+
213
+ let normalizedPathname = pathname;
214
+
215
+ // Ensure it starts with /
216
+ if (!normalizedPathname.startsWith('/')) {
217
+ normalizedPathname = `/${normalizedPathname}`;
218
+ }
219
+
220
+ // Collapse multiple slashes
221
+ normalizedPathname = normalizedPathname.replace(/\/+/g, '/');
222
+
223
+ // Remove trailing slash unless it's the root
224
+ if (normalizedPathname !== '/' && normalizedPathname.endsWith('/')) {
225
+ normalizedPathname = normalizedPathname.slice(0, -1);
226
+ }
227
+
228
+ return normalizedPathname;
229
+ }
230
+
231
+ /**
232
+ * Reasons a pathname can be rejected. Each maps to a specific user-facing
233
+ * error message so the UI can highlight the exact problem.
234
+ */
235
+ export type PathnameValidationReason =
236
+ | 'empty'
237
+ | 'whitespace'
238
+ | 'forbidden_char'
239
+ | 'control_char'
240
+ | 'uppercase'
241
+ | 'non_ascii'
242
+ | 'traversal_segment'
243
+ | 'index_segment'
244
+ | 'disallowed_char';
245
+
246
+ export interface PathnameValidationResult {
247
+ /** When valid: the normalized pathname. When invalid: the raw (trimmed) input. */
248
+ value: string;
249
+ valid: boolean;
250
+ reason?: PathnameValidationReason;
251
+ message?: string;
252
+ }
253
+
254
+ /**
255
+ * Validate the shape of a CMS pathname and normalize it for storage.
256
+ *
257
+ * Silently fixes harmless slips (missing leading slash, doubled slashes,
258
+ * trailing slash) and rejects malformed inputs with a specific reason so
259
+ * the UI can show a helpful error message.
260
+ *
261
+ * Accepted chars: a–z, 0–9, `-`, `_`, `/`. Mixed case, accents, spaces,
262
+ * `?`, `#`, `\`, and traversal segments (`.`, `..`) are rejected, as is a
263
+ * last segment `index`: a page's file is named after its path, `/` is stored
264
+ * as `index`, and `blog/index` reads back as `/blog`, so `/index` would be the
265
+ * home page's file and `/blog/index` a second page at `/blog`.
266
+ */
267
+ export function normalizeAndValidatePathname(input: string | undefined | null): PathnameValidationResult {
268
+ const raw = (input ?? '').trim();
269
+
270
+ if (raw === '') {
271
+ return { value: '', valid: false, reason: 'empty', message: 'Path is required' };
272
+ }
273
+
274
+ // Pre-normalize character checks — run on the raw input so the error
275
+ // matches what the user actually typed.
276
+ if (/\s/.test(raw)) {
277
+ return { value: raw, valid: false, reason: 'whitespace', message: 'Path cannot contain spaces' };
278
+ }
279
+ if (/[?#\\]/.test(raw)) {
280
+ return { value: raw, valid: false, reason: 'forbidden_char', message: 'Path cannot contain `?`, `#`, or `\\`' };
281
+ }
282
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional control-char detection
283
+ if (/[\x00-\x1F\x7F]/.test(raw)) {
284
+ return { value: raw, valid: false, reason: 'control_char', message: 'Path cannot contain control characters' };
285
+ }
286
+ if (/[A-Z]/.test(raw)) {
287
+ return { value: raw, valid: false, reason: 'uppercase', message: 'Path must be lowercase' };
288
+ }
289
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: ASCII-only enforcement
290
+ if (/[^\x00-\x7F]/.test(raw)) {
291
+ return {
292
+ value: raw,
293
+ valid: false,
294
+ reason: 'non_ascii',
295
+ message: 'Path can only contain a–z, 0–9, `-`, `_`, `/`',
296
+ };
297
+ }
298
+
299
+ // Normalize: add leading slash, collapse //, strip trailing slash.
300
+ let value = raw;
301
+ if (!value.startsWith('/')) value = `/${value}`;
302
+ value = value.replace(/\/+/g, '/');
303
+ if (value !== '/' && value.endsWith('/')) value = value.slice(0, -1);
304
+
305
+ // Segment-level check: `.` and `..` are never valid path segments.
306
+ // Run before the generic disallowed-char check so the user gets the
307
+ // more specific "traversal" message.
308
+ if (value !== '/') {
309
+ for (const seg of value.slice(1).split('/')) {
310
+ if (seg === '.' || seg === '..') {
311
+ return {
312
+ value,
313
+ valid: false,
314
+ reason: 'traversal_segment',
315
+ message: 'Path cannot contain `.` or `..` segments',
316
+ };
317
+ }
318
+ }
319
+ }
320
+
321
+ if (value.endsWith('/index')) {
322
+ return {
323
+ value,
324
+ valid: false,
325
+ reason: 'index_segment',
326
+ message: 'Path cannot end in `/index`: `/index` is the home page and `/blog/index` is `/blog`',
327
+ };
328
+ }
329
+
330
+ // Final allowed-chars check — catches stray dots and anything else.
331
+ if (!/^[a-z0-9\-_/]*$/.test(value)) {
332
+ return {
333
+ value,
334
+ valid: false,
335
+ reason: 'disallowed_char',
336
+ message: 'Path can only contain a–z, 0–9, `-`, `_`, `/`',
337
+ };
338
+ }
339
+
340
+ return { value, valid: true };
341
+ }
342
+
343
+ /**
344
+ * Generate a content ID in the standard format
345
+ * IDs are prefixed with "vx-" followed by 8 random characters
346
+ */
347
+ export function generateContentId(): string {
348
+ return `vx-${nanoid(8)}`;
349
+ }
350
+
351
+ /**
352
+ * Get the current date/time in ISO format
353
+ * Used for timestamps in content files
354
+ */
355
+ export function getCurrentISODate(): string {
356
+ return new Date().toISOString();
357
+ }
358
+
359
+ /**
360
+ * Parse a date string safely
361
+ * Returns null if invalid
362
+ */
363
+ export function parseDate(dateStr: string | undefined): Date | null {
364
+ if (!dateStr) return null;
365
+
366
+ try {
367
+ const date = new Date(dateStr);
368
+ if (Number.isNaN(date.getTime())) return null;
369
+ return date;
370
+ } catch {
371
+ return null;
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Creates a V8-optimized object by mapping site names to values.
377
+ * Ensures all objects have the same hidden class by adding properties in consistent order.
378
+ *
379
+ * @param sitesConfig - Sites configuration containing site names
380
+ * @param factory - Function that creates the value for each site
381
+ * @returns Object with all sites initialized in alphabetical order
382
+ */
383
+ export function mapSiteNames<T>(
384
+ sitesConfig: { sites: Record<string, any> },
385
+ factory: (siteName: string) => T,
386
+ ): Record<string, T> {
387
+ const obj: Record<string, T> = {};
388
+ // Object.keys returns keys in insertion order, which is stable for a given object
389
+ for (const siteName of Object.keys(sitesConfig.sites)) {
390
+ obj[siteName] = factory(siteName);
391
+ }
392
+ return obj;
393
+ }
394
+
395
+ /**
396
+ * Creates a V8-optimized object by mapping locale names to values.
397
+ * Ensures all objects have the same hidden class by adding properties in consistent order.
398
+ *
399
+ * @param locales - Array of locale codes
400
+ * @param factory - Function that creates the value for each locale
401
+ * @returns Object with all locales initialized in array order
402
+ */
403
+ export function mapLocales<T>(locales: string[], factory: (locale: string) => T): Record<string, T> {
404
+ const obj: Record<string, T> = {};
405
+ for (const locale of locales) {
406
+ obj[locale] = factory(locale);
407
+ }
408
+ return obj;
409
+ }
410
+
411
+ /**
412
+ * Resolves a publish date value to a valid string or undefined.
413
+ * Handles various input types including null, false, and empty strings.
414
+ *
415
+ * @param updateValue - The value being updated (string | null | false | undefined)
416
+ * @param currentValue - The current value to fall back to if updateValue is undefined
417
+ * @returns A valid date string or undefined
418
+ */
419
+ export function resolvePublishDate(
420
+ updateValue: string | null | false | undefined,
421
+ currentValue: string | undefined,
422
+ ): string | undefined {
423
+ // If updateValue is explicitly provided (including null/false), use it
424
+ if (updateValue !== undefined) {
425
+ // Only return string values, treat null/false/empty as undefined
426
+ return updateValue && typeof updateValue === 'string' ? updateValue : undefined;
427
+ }
428
+ // Otherwise keep the current value
429
+ return currentValue;
430
+ }
431
+
432
+ /**
433
+ * Serializes MDX content with frontmatter.
434
+ * This is used by both FileSystemContentAPI and InMemoryContentAPI to ensure
435
+ * consistent MDX output that includes frontmatter for variable access.
436
+ *
437
+ * @param frontmatterData - The frontmatter data to serialize
438
+ * @param mdxContent - The MDX content (without frontmatter)
439
+ * @returns Complete MDX file content with frontmatter
440
+ */
441
+ export function serializeMdxWithFrontmatter(frontmatterData: Record<string, any>, mdxContent: string): string {
442
+ const ordered: Record<string, unknown> = {};
443
+ const normalize = (value: unknown): unknown => {
444
+ // gray-matter's default js-yaml schema parses ISO timestamps into JS Date
445
+ // objects. Convert back to strings so the QUOTE_SINGLE visitor below can
446
+ // restore the canonical single-quoted form on write.
447
+ if (value instanceof Date) return value.toISOString();
448
+ return value;
449
+ };
450
+ for (const key of FRONTMATTER_KEY_ORDER) {
451
+ if (key in frontmatterData) ordered[key] = normalize(frontmatterData[key]);
452
+ }
453
+ for (const key of Object.keys(frontmatterData).sort()) {
454
+ if (!(key in ordered)) ordered[key] = normalize(frontmatterData[key]);
455
+ }
456
+
457
+ const doc = new Document(ordered);
458
+ yaml.visit(doc, {
459
+ Scalar(_key, node) {
460
+ if (isScalar(node) && typeof node.value === 'string' && ISO_TIMESTAMP_RE.test(node.value)) {
461
+ node.type = 'QUOTE_SINGLE';
462
+ }
463
+ },
464
+ });
465
+
466
+ // Strip any leading newlines from the body. The serializer always emits
467
+ // exactly one blank line between the closing `---` and the body, so a
468
+ // caller-side leading `\n` (gray-matter leaves one in the content slice when
469
+ // it strips frontmatter) would compound into multiple blank lines and drift
470
+ // the diff on every save.
471
+ const body = mdxContent.replace(/^\n+/, '');
472
+
473
+ return `---\n${doc.toString()}---\n\n${body}`;
474
+ }
@@ -0,0 +1,122 @@
1
+ import { normalize, resolve } from 'node:path';
2
+ import { FileSystemContentAPI } from './filesystem-content-api.js';
3
+ import type { ContentAPIOptions } from './types.js';
4
+
5
+ export type ContentWatcherOptions = ContentAPIOptions;
6
+
7
+ export interface WebSocketSender {
8
+ send(payload: { type: string; event: string; data: any }): void;
9
+ }
10
+
11
+ export interface ContentWatchEvent {
12
+ file: string;
13
+ action: 'update' | 'create' | 'delete';
14
+ inMdxRoot: boolean;
15
+ inContentRoot: boolean;
16
+ }
17
+
18
+ interface ReindexResultLike {
19
+ updated: unknown[];
20
+ deleted?: { id: string; locale: string; kind: 'page' | 'fragment' | 'data' }[];
21
+ }
22
+
23
+ interface ReindexableContentAPI {
24
+ reindex(paths: string[], options?: { handleDeletions?: boolean }): Promise<ReindexResultLike>;
25
+ }
26
+
27
+ /**
28
+ * Creates a content API instance for the given options
29
+ */
30
+ export async function createContentAPI(options: ContentWatcherOptions): Promise<FileSystemContentAPI> {
31
+ return await FileSystemContentAPI.create({
32
+ ...options,
33
+ canvasDir: options.canvasDir || './canvas',
34
+ });
35
+ }
36
+
37
+ /**
38
+ * Creates file change handlers for content watching
39
+ */
40
+ export function createContentWatchHandlers(
41
+ contentApi: ReindexableContentAPI,
42
+ options: ContentWatcherOptions,
43
+ ws: WebSocketSender,
44
+ onReindexed?: (event: ContentWatchEvent) => void | Promise<void>,
45
+ ) {
46
+ const handleFileChange = async (file: string, action: 'update' | 'create' | 'delete') => {
47
+ // Normalize paths for consistent comparison
48
+ const normalizedFile = normalize(resolve(file));
49
+ const normalizedRoot = normalize(resolve(options.contentRoot));
50
+ const normalizedMdxRoot = options.mdxPagesRoot ? normalize(resolve(options.mdxPagesRoot)) : null;
51
+
52
+ // Only the files the content scanner indexes: .mdx and .vxjson, and .json
53
+ // only under the content root's data/ directory. Other .json files under
54
+ // the content root, such as asset metadata records, are not content.
55
+ const isContentFile = normalizedFile.endsWith('.mdx') || normalizedFile.endsWith('.vxjson');
56
+ const isDataFile = normalizedFile.endsWith('.json') && normalizedFile.startsWith(`${normalizedRoot}/data/`);
57
+ if (!isContentFile && !isDataFile) {
58
+ return;
59
+ }
60
+
61
+ // Trailing-slash guard avoids prefix collisions
62
+ // (e.g. `/foo/content-extra/...` matching root `/foo/content`).
63
+ const inContentRoot = normalizedFile === normalizedRoot || normalizedFile.startsWith(`${normalizedRoot}/`);
64
+ const inMdxRoot =
65
+ !!normalizedMdxRoot &&
66
+ (normalizedFile === normalizedMdxRoot || normalizedFile.startsWith(`${normalizedMdxRoot}/`));
67
+
68
+ if (inContentRoot || inMdxRoot) {
69
+ const matchedRoot = inContentRoot ? normalizedRoot : (normalizedMdxRoot as string);
70
+ const relativePath = normalizedFile.replace(`${matchedRoot}/`, '');
71
+ console.log(`[Content] ${action}: ${relativePath}`);
72
+
73
+ try {
74
+ // Reindex the file
75
+ const reindexOptions = action === 'delete' ? { handleDeletions: true } : undefined;
76
+ const result = await contentApi.reindex([normalizedFile], reindexOptions);
77
+
78
+ // Send updates for each changed locale
79
+ for (const manifest of result.updated) {
80
+ const message = {
81
+ type: 'custom',
82
+ event: 'conloca:content-update',
83
+ data: {
84
+ action,
85
+ manifest,
86
+ },
87
+ };
88
+ ws.send(message);
89
+ }
90
+
91
+ // Send deletion updates
92
+ if (action === 'delete' && result.deleted) {
93
+ for (const deletion of result.deleted) {
94
+ ws.send({
95
+ type: 'custom',
96
+ event: 'conloca:content-update',
97
+ data: {
98
+ action: 'delete',
99
+ ...deletion,
100
+ },
101
+ });
102
+ }
103
+ }
104
+ } catch (error) {
105
+ console.error('[Content Watcher] Reindex failed:', error);
106
+ return;
107
+ }
108
+
109
+ try {
110
+ await onReindexed?.({ file: normalizedFile, action, inMdxRoot, inContentRoot });
111
+ } catch (error) {
112
+ console.error('[Content Watcher] onReindexed callback failed:', error);
113
+ }
114
+ }
115
+ };
116
+
117
+ return {
118
+ onChange: (file: string) => handleFileChange(file, 'update'),
119
+ onAdd: (file: string) => handleFileChange(file, 'create'),
120
+ onUnlink: (file: string) => handleFileChange(file, 'delete'),
121
+ };
122
+ }
@@ -0,0 +1,7 @@
1
+ import { BaseContentIndex } from './base-content-index.js';
2
+
3
+ /**
4
+ * V8-optimized index for data collections
5
+ * Maintains collection->name->locale lookups
6
+ */
7
+ export class DataIndex extends BaseContentIndex {}