@conloca/content-api 0.1.14 → 0.1.16

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 (183) hide show
  1. package/dist/asset-manifest.d.ts +23 -0
  2. package/dist/asset-manifest.d.ts.map +1 -0
  3. package/dist/asset-manifest.js +73 -0
  4. package/dist/asset-operations.d.ts +159 -0
  5. package/dist/asset-operations.d.ts.map +1 -0
  6. package/dist/asset-operations.js +736 -0
  7. package/dist/asset-types.d.ts +56 -0
  8. package/dist/asset-types.d.ts.map +1 -0
  9. package/dist/asset-types.js +7 -0
  10. package/dist/base-content-index.d.ts +57 -0
  11. package/dist/base-content-index.d.ts.map +1 -0
  12. package/dist/base-content-index.js +179 -0
  13. package/dist/block-index.d.ts +9 -0
  14. package/dist/block-index.d.ts.map +1 -0
  15. package/dist/block-index.js +11 -0
  16. package/dist/blocks.d.ts +16 -0
  17. package/dist/blocks.d.ts.map +1 -0
  18. package/dist/blocks.js +103 -0
  19. package/dist/cf-access.d.ts +31 -0
  20. package/dist/cf-access.d.ts.map +1 -0
  21. package/dist/cf-access.js +66 -0
  22. package/dist/component-registry.d.ts +50 -0
  23. package/dist/component-registry.d.ts.map +1 -0
  24. package/dist/component-registry.js +120 -0
  25. package/dist/component-registry.types-C0ctF9nh.d.mts +71 -0
  26. package/dist/component-registry.types-C0ctF9nh.d.mts.map +1 -0
  27. package/dist/component-registry.types.d.ts +11 -0
  28. package/dist/component-registry.types.d.ts.map +1 -0
  29. package/dist/component-registry.types.js +1 -0
  30. package/dist/content-api.interface.d.ts +64 -0
  31. package/dist/content-api.interface.d.ts.map +1 -0
  32. package/dist/content-api.interface.js +1 -0
  33. package/dist/content-filters.d.ts +31 -0
  34. package/dist/content-filters.d.ts.map +1 -0
  35. package/dist/content-filters.js +246 -0
  36. package/dist/content-index-D092_vk1.mjs +629 -0
  37. package/dist/content-index-D092_vk1.mjs.map +1 -0
  38. package/dist/content-index-D6IVMmAB.d.mts +127 -0
  39. package/dist/content-index-D6IVMmAB.d.mts.map +1 -0
  40. package/dist/content-index.d.ts +126 -0
  41. package/dist/content-index.d.ts.map +1 -0
  42. package/dist/content-index.js +418 -0
  43. package/dist/content-operations-DIbsxG5A.d.mts +354 -0
  44. package/dist/content-operations-DIbsxG5A.d.mts.map +1 -0
  45. package/dist/content-operations.d.ts +93 -0
  46. package/dist/content-operations.d.ts.map +1 -0
  47. package/dist/content-operations.js +275 -0
  48. package/dist/content-reader.d.ts +10 -0
  49. package/dist/content-reader.d.ts.map +1 -0
  50. package/dist/content-reader.js +13 -0
  51. package/dist/content-utils-fWNHTrPy.mjs +280 -0
  52. package/dist/content-utils-fWNHTrPy.mjs.map +1 -0
  53. package/dist/content-utils.d.ts +132 -0
  54. package/dist/content-utils.d.ts.map +1 -0
  55. package/dist/content-utils.js +352 -0
  56. package/dist/content-watcher.d.ts +43 -0
  57. package/dist/content-watcher.d.ts.map +1 -0
  58. package/dist/content-watcher.js +83 -0
  59. package/dist/data-DquNIEnQ.mjs +62 -0
  60. package/dist/data-DquNIEnQ.mjs.map +1 -0
  61. package/dist/data-index.d.ts +8 -0
  62. package/dist/data-index.d.ts.map +1 -0
  63. package/dist/data-index.js +7 -0
  64. package/dist/data.d.ts +43 -0
  65. package/dist/data.d.ts.map +1 -0
  66. package/dist/data.js +103 -0
  67. package/dist/etag-utils.d.ts +77 -0
  68. package/dist/etag-utils.d.ts.map +1 -0
  69. package/dist/etag-utils.js +160 -0
  70. package/dist/filesystem-content-api-B1KIQJfk.mjs +2 -0
  71. package/dist/filesystem-content-api-C0HIhqZi.mjs +1620 -0
  72. package/dist/filesystem-content-api-C0HIhqZi.mjs.map +1 -0
  73. package/dist/filesystem-content-api-DCdNi-co.d.mts +134 -0
  74. package/dist/filesystem-content-api-DCdNi-co.d.mts.map +1 -0
  75. package/dist/filesystem-content-api.d.ts +135 -0
  76. package/dist/filesystem-content-api.d.ts.map +1 -0
  77. package/dist/filesystem-content-api.js +2181 -0
  78. package/dist/git-operations.d.ts +49 -0
  79. package/dist/git-operations.d.ts.map +1 -0
  80. package/dist/git-operations.js +252 -0
  81. package/dist/header-parser.d.ts +37 -0
  82. package/dist/header-parser.d.ts.map +1 -0
  83. package/dist/header-parser.js +286 -0
  84. package/dist/in-memory-content-api.d.ts +35 -0
  85. package/dist/in-memory-content-api.d.ts.map +1 -0
  86. package/dist/in-memory-content-api.js +591 -0
  87. package/dist/index-DxVTFK66.d.mts +105 -0
  88. package/dist/index-DxVTFK66.d.mts.map +1 -0
  89. package/dist/index.d.mts +6 -4
  90. package/dist/index.d.mts.map +1 -1
  91. package/dist/index.d.ts +19 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +16 -0
  94. package/dist/index.mjs +37 -5
  95. package/dist/index.mjs.map +1 -1
  96. package/dist/indexing.d.mts +152 -0
  97. package/dist/indexing.d.mts.map +1 -0
  98. package/dist/indexing.d.ts +5 -0
  99. package/dist/indexing.d.ts.map +1 -0
  100. package/dist/indexing.js +7 -0
  101. package/dist/indexing.mjs +255 -0
  102. package/dist/indexing.mjs.map +1 -0
  103. package/dist/json-whitespace-view.d.ts +32 -0
  104. package/dist/json-whitespace-view.d.ts.map +1 -0
  105. package/dist/json-whitespace-view.js +152 -0
  106. package/dist/middleware.d.ts +20 -0
  107. package/dist/middleware.d.ts.map +1 -0
  108. package/dist/middleware.js +1031 -0
  109. package/dist/node.d.mts +28 -126
  110. package/dist/node.d.mts.map +1 -1
  111. package/dist/node.d.ts +25 -0
  112. package/dist/node.d.ts.map +1 -0
  113. package/dist/node.js +24 -0
  114. package/dist/node.mjs +199 -2890
  115. package/dist/node.mjs.map +1 -1
  116. package/dist/reader.d.mts +15 -0
  117. package/dist/reader.d.mts.map +1 -0
  118. package/dist/reader.d.ts +15 -0
  119. package/dist/reader.d.ts.map +1 -0
  120. package/dist/reader.js +13 -0
  121. package/dist/reader.mjs +22 -0
  122. package/dist/reader.mjs.map +1 -0
  123. package/dist/schemas/index.d.mts +2 -90
  124. package/dist/schemas/index.d.ts +102 -0
  125. package/dist/schemas/index.d.ts.map +1 -0
  126. package/dist/schemas/index.js +87 -0
  127. package/dist/schemas/index.mjs +2 -70
  128. package/dist/schemas-CFRD0FIQ.mjs +84 -0
  129. package/dist/schemas-CFRD0FIQ.mjs.map +1 -0
  130. package/dist/{types-BUG0Cfkg.mjs → site-8oaj1Q60.mjs} +20 -222
  131. package/dist/site-8oaj1Q60.mjs.map +1 -0
  132. package/dist/site-index-B_254bCc.d.mts +136 -0
  133. package/dist/site-index-B_254bCc.d.mts.map +1 -0
  134. package/dist/site-index.d.ts +60 -0
  135. package/dist/site-index.d.ts.map +1 -0
  136. package/dist/site-index.js +287 -0
  137. package/dist/site.d.ts +21 -0
  138. package/dist/site.d.ts.map +1 -0
  139. package/dist/site.js +168 -0
  140. package/dist/types-DOdldbfD.mjs +34 -0
  141. package/dist/types-DOdldbfD.mjs.map +1 -0
  142. package/dist/types-DjfhS272.d.mts +456 -0
  143. package/dist/types-DjfhS272.d.mts.map +1 -0
  144. package/dist/types.d.ts +453 -0
  145. package/dist/types.d.ts.map +1 -0
  146. package/dist/types.js +36 -0
  147. package/dist/url-safe-base64.d.ts +12 -0
  148. package/dist/url-safe-base64.d.ts.map +1 -0
  149. package/dist/url-safe-base64.js +40 -0
  150. package/dist/url-validation.d.ts +14 -0
  151. package/dist/url-validation.d.ts.map +1 -0
  152. package/dist/url-validation.js +81 -0
  153. package/dist/utils/atomic-write.d.ts +6 -0
  154. package/dist/utils/atomic-write.d.ts.map +1 -0
  155. package/dist/utils/atomic-write.js +20 -0
  156. package/dist/utils.d.ts +46 -0
  157. package/dist/utils.d.ts.map +1 -0
  158. package/dist/utils.js +70 -0
  159. package/dist/vite-plugin.d.ts +12 -0
  160. package/dist/vite-plugin.d.ts.map +1 -0
  161. package/dist/vite-plugin.js +29 -0
  162. package/dist/vxjson-qHrgLGip.mjs +555 -0
  163. package/dist/vxjson-qHrgLGip.mjs.map +1 -0
  164. package/dist/vxjson-serialize-geF6qvpn.mjs +34 -0
  165. package/dist/vxjson-serialize-geF6qvpn.mjs.map +1 -0
  166. package/dist/vxjson-serialize.d.mts +17 -0
  167. package/dist/vxjson-serialize.d.mts.map +1 -0
  168. package/dist/vxjson-serialize.d.ts +14 -0
  169. package/dist/vxjson-serialize.d.ts.map +1 -0
  170. package/dist/vxjson-serialize.js +50 -0
  171. package/dist/vxjson-serialize.mjs +2 -0
  172. package/dist/vxjson.d.ts +112 -0
  173. package/dist/vxjson.d.ts.map +1 -0
  174. package/dist/vxjson.js +391 -0
  175. package/dist/xxhash.d.ts +10 -0
  176. package/dist/xxhash.d.ts.map +1 -0
  177. package/dist/xxhash.js +31 -0
  178. package/package.json +88 -17
  179. package/dist/content-operations-BZLfJWqT.d.mts +0 -916
  180. package/dist/content-operations-BZLfJWqT.d.mts.map +0 -1
  181. package/dist/schemas/index.d.mts.map +0 -1
  182. package/dist/schemas/index.mjs.map +0 -1
  183. package/dist/types-BUG0Cfkg.mjs.map +0 -1
@@ -0,0 +1,132 @@
1
+ import type { ContentMeta, LocaleVersion } from './types';
2
+ export declare function localesOf<T>(manifest: {
3
+ locales: Record<string, T | undefined>;
4
+ }): Generator<T>;
5
+ /**
6
+ * Pure utility functions for content operations
7
+ * These functions don't depend on any class state and can be shared
8
+ * between FileSystemContentAPI, InMemoryContentAPI, and other implementations
9
+ */
10
+ /**
11
+ * Check if content is published based on publishAt/unpublishAt dates
12
+ */
13
+ export declare function isContentPublished(localeVersion: Pick<LocaleVersion, 'publishAt' | 'unpublishAt'>, now?: Date): boolean;
14
+ /**
15
+ * Validate that metadata doesn't exceed 4KB when serialized
16
+ * This ensures efficient indexing as per the specification
17
+ */
18
+ export declare function isMetadataTooLarge(meta: ContentMeta): boolean;
19
+ /**
20
+ * Extract block name from various sources
21
+ * Used when displaying blocks in the UI
22
+ */
23
+ export declare function extractBlockName(source: string): string;
24
+ /**
25
+ * Validate block name according to the specification
26
+ * - Cannot contain dots (reserved for locale separator)
27
+ * - Cannot contain slashes (would create subdirectories)
28
+ * - Cannot contain spaces (for clean filenames)
29
+ * - Must have at least one character
30
+ */
31
+ export declare function isValidBlockName(name: string): boolean;
32
+ /**
33
+ * Format file size for display with human-readable units
34
+ * @example formatFileSize(1536) // "1.5 KB"
35
+ */
36
+ export declare function formatFileSize(bytes: number): string;
37
+ /**
38
+ * Calculate metadata size in bytes
39
+ */
40
+ export declare function getMetadataSize(meta: ContentMeta): number;
41
+ /**
42
+ * Check if a pathname is valid
43
+ * - Must start with /
44
+ * - Cannot contain spaces (should be URL-encoded)
45
+ * - Cannot contain special characters that would break URLs
46
+ */
47
+ export declare function isValidPathname(pathname: string): boolean;
48
+ /**
49
+ * Normalize a pathname to ensure consistency
50
+ * - Ensure it starts with /
51
+ * - Remove trailing slashes (except for root)
52
+ * - Collapse multiple slashes
53
+ */
54
+ export declare function normalizePathname(pathname: string): string;
55
+ /**
56
+ * Reasons a pathname can be rejected. Each maps to a specific user-facing
57
+ * error message so the UI can highlight the exact problem.
58
+ */
59
+ export type PathnameValidationReason = 'empty' | 'whitespace' | 'forbidden_char' | 'control_char' | 'uppercase' | 'non_ascii' | 'traversal_segment' | 'disallowed_char';
60
+ export interface PathnameValidationResult {
61
+ /** When valid: the normalized pathname. When invalid: the raw (trimmed) input. */
62
+ value: string;
63
+ valid: boolean;
64
+ reason?: PathnameValidationReason;
65
+ message?: string;
66
+ }
67
+ /**
68
+ * Validate the shape of a CMS pathname and normalize it for storage.
69
+ *
70
+ * Silently fixes harmless slips (missing leading slash, doubled slashes,
71
+ * trailing slash) and rejects malformed inputs with a specific reason so
72
+ * the UI can show a helpful error message.
73
+ *
74
+ * Accepted chars: a–z, 0–9, `-`, `_`, `/`. Mixed case, accents, spaces,
75
+ * `?`, `#`, `\`, and traversal segments (`.`, `..`) are rejected.
76
+ */
77
+ export declare function normalizeAndValidatePathname(input: string | undefined | null): PathnameValidationResult;
78
+ /**
79
+ * Generate a content ID in the standard format
80
+ * IDs are prefixed with "vx-" followed by 8 random characters
81
+ */
82
+ export declare function generateContentId(): string;
83
+ /**
84
+ * Get the current date/time in ISO format
85
+ * Used for timestamps in content files
86
+ */
87
+ export declare function getCurrentISODate(): string;
88
+ /**
89
+ * Parse a date string safely
90
+ * Returns null if invalid
91
+ */
92
+ export declare function parseDate(dateStr: string | undefined): Date | null;
93
+ /**
94
+ * Creates a V8-optimized object by mapping site names to values.
95
+ * Ensures all objects have the same hidden class by adding properties in consistent order.
96
+ *
97
+ * @param sitesConfig - Sites configuration containing site names
98
+ * @param factory - Function that creates the value for each site
99
+ * @returns Object with all sites initialized in alphabetical order
100
+ */
101
+ export declare function mapSiteNames<T>(sitesConfig: {
102
+ sites: Record<string, any>;
103
+ }, factory: (siteName: string) => T): Record<string, T>;
104
+ /**
105
+ * Creates a V8-optimized object by mapping locale names to values.
106
+ * Ensures all objects have the same hidden class by adding properties in consistent order.
107
+ *
108
+ * @param locales - Array of locale codes
109
+ * @param factory - Function that creates the value for each locale
110
+ * @returns Object with all locales initialized in array order
111
+ */
112
+ export declare function mapLocales<T>(locales: string[], factory: (locale: string) => T): Record<string, T>;
113
+ /**
114
+ * Resolves a publish date value to a valid string or undefined.
115
+ * Handles various input types including null, false, and empty strings.
116
+ *
117
+ * @param updateValue - The value being updated (string | null | false | undefined)
118
+ * @param currentValue - The current value to fall back to if updateValue is undefined
119
+ * @returns A valid date string or undefined
120
+ */
121
+ export declare function resolvePublishDate(updateValue: string | null | false | undefined, currentValue: string | undefined): string | undefined;
122
+ /**
123
+ * Serializes MDX content with frontmatter.
124
+ * This is used by both FileSystemContentAPI and InMemoryContentAPI to ensure
125
+ * consistent MDX output that includes frontmatter for variable access.
126
+ *
127
+ * @param frontmatterData - The frontmatter data to serialize
128
+ * @param mdxContent - The MDX content (without frontmatter)
129
+ * @returns Complete MDX file content with frontmatter
130
+ */
131
+ export declare function serializeMdxWithFrontmatter(frontmatterData: Record<string, any>, mdxContent: string): string;
132
+ //# sourceMappingURL=content-utils.d.ts.map
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Document, isScalar } from 'yaml';
3
+ // Pinned key order at the top of every .mdx frontmatter block. Anything not
4
+ // listed here is appended after, sorted alphabetically for determinism. Without
5
+ // this, the JS object insertion order in the update path leaks into the file
6
+ // and every save reshuffles the YAML keys, producing diff noise unrelated to
7
+ // the author's edit.
8
+ const FRONTMATTER_KEY_ORDER = [
9
+ 'title',
10
+ 'category',
11
+ 'description',
12
+ 'id',
13
+ 'created',
14
+ 'modified',
15
+ 'publishAt',
16
+ 'unpublishAt',
17
+ ];
18
+ // ISO 8601 timestamps were authored with single quotes in the canonical
19
+ // fixtures (e.g. `created: '2026-05-07T18:07:39.049Z'`). yaml.stringify defaults
20
+ // to a plain (unquoted) scalar for strings that aren't ambiguous, which strips
21
+ // the quotes on every round-trip. We re-apply the single-quote style for any
22
+ // scalar value that looks like an ISO 8601 timestamp.
23
+ const ISO_TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
24
+ export function* localesOf(manifest) {
25
+ for (const value of Object.values(manifest.locales)) {
26
+ if (value)
27
+ yield value;
28
+ }
29
+ }
30
+ /**
31
+ * Pure utility functions for content operations
32
+ * These functions don't depend on any class state and can be shared
33
+ * between FileSystemContentAPI, InMemoryContentAPI, and other implementations
34
+ */
35
+ /**
36
+ * Check if content is published based on publishAt/unpublishAt dates
37
+ */
38
+ export function isContentPublished(localeVersion, now = new Date()) {
39
+ if (localeVersion.publishAt) {
40
+ const publishDate = new Date(localeVersion.publishAt);
41
+ // Check for invalid dates (e.g., from empty strings or invalid values)
42
+ if (!isNaN(publishDate.getTime()) && publishDate > now)
43
+ return false;
44
+ }
45
+ if (localeVersion.unpublishAt) {
46
+ const unpublishDate = new Date(localeVersion.unpublishAt);
47
+ // Check for invalid dates (e.g., from empty strings or invalid values)
48
+ if (!isNaN(unpublishDate.getTime()) && unpublishDate < now)
49
+ return false;
50
+ }
51
+ return true;
52
+ }
53
+ /**
54
+ * Validate that metadata doesn't exceed 4KB when serialized
55
+ * This ensures efficient indexing as per the specification
56
+ */
57
+ export function isMetadataTooLarge(meta) {
58
+ const size = new TextEncoder().encode(JSON.stringify(meta)).length;
59
+ return size > 4096;
60
+ }
61
+ /**
62
+ * Extract block name from various sources
63
+ * Used when displaying blocks in the UI
64
+ */
65
+ export function extractBlockName(source) {
66
+ // If it's a collection/name path, extract the name part
67
+ if (source.includes('/') && !source.includes('.')) {
68
+ const parts = source.split('/');
69
+ return parts[parts.length - 1];
70
+ }
71
+ // If it's a filename, extract the base name
72
+ if (source.includes('.')) {
73
+ const match = source.match(/^(.+?)\.([a-z]{2})?\.(mdx|vxjson)$/);
74
+ if (match) {
75
+ return match[1];
76
+ }
77
+ // Fallback: remove any extension
78
+ return source.replace(/\.[^.]+$/, '');
79
+ }
80
+ // If it's an ID, create a simple name
81
+ if (source.startsWith('vx-')) {
82
+ return `block-${source.substring(3, 8)}`;
83
+ }
84
+ // Otherwise return as-is
85
+ return source;
86
+ }
87
+ /**
88
+ * Validate block name according to the specification
89
+ * - Cannot contain dots (reserved for locale separator)
90
+ * - Cannot contain slashes (would create subdirectories)
91
+ * - Cannot contain spaces (for clean filenames)
92
+ * - Must have at least one character
93
+ */
94
+ export function isValidBlockName(name) {
95
+ if (!name || name.length === 0)
96
+ return false;
97
+ if (name.includes('.'))
98
+ return false;
99
+ if (name.includes('/'))
100
+ return false;
101
+ if (name.includes(' '))
102
+ return false;
103
+ return true;
104
+ }
105
+ /**
106
+ * Format file size for display with human-readable units
107
+ * @example formatFileSize(1536) // "1.5 KB"
108
+ */
109
+ export function formatFileSize(bytes) {
110
+ if (bytes < 1024)
111
+ return `${bytes} B`;
112
+ if (bytes < 1024 * 1024)
113
+ return `${(bytes / 1024).toFixed(1)} KB`;
114
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
115
+ }
116
+ /**
117
+ * Calculate metadata size in bytes
118
+ */
119
+ export function getMetadataSize(meta) {
120
+ return new TextEncoder().encode(JSON.stringify(meta)).length;
121
+ }
122
+ /**
123
+ * Check if a pathname is valid
124
+ * - Must start with /
125
+ * - Cannot contain spaces (should be URL-encoded)
126
+ * - Cannot contain special characters that would break URLs
127
+ */
128
+ export function isValidPathname(pathname) {
129
+ if (!pathname || !pathname.startsWith('/'))
130
+ return false;
131
+ if (pathname.includes(' '))
132
+ return false;
133
+ if (pathname.includes('?') || pathname.includes('#'))
134
+ return false;
135
+ return true;
136
+ }
137
+ /**
138
+ * Normalize a pathname to ensure consistency
139
+ * - Ensure it starts with /
140
+ * - Remove trailing slashes (except for root)
141
+ * - Collapse multiple slashes
142
+ */
143
+ export function normalizePathname(pathname) {
144
+ if (!pathname)
145
+ return '/';
146
+ let normalized = pathname;
147
+ // Ensure it starts with /
148
+ if (!normalized.startsWith('/')) {
149
+ normalized = `/${normalized}`;
150
+ }
151
+ // Collapse multiple slashes
152
+ normalized = normalized.replace(/\/+/g, '/');
153
+ // Remove trailing slash unless it's the root
154
+ if (normalized !== '/' && normalized.endsWith('/')) {
155
+ normalized = normalized.slice(0, -1);
156
+ }
157
+ return normalized;
158
+ }
159
+ /**
160
+ * Validate the shape of a CMS pathname and normalize it for storage.
161
+ *
162
+ * Silently fixes harmless slips (missing leading slash, doubled slashes,
163
+ * trailing slash) and rejects malformed inputs with a specific reason so
164
+ * the UI can show a helpful error message.
165
+ *
166
+ * Accepted chars: a–z, 0–9, `-`, `_`, `/`. Mixed case, accents, spaces,
167
+ * `?`, `#`, `\`, and traversal segments (`.`, `..`) are rejected.
168
+ */
169
+ export function normalizeAndValidatePathname(input) {
170
+ const raw = (input ?? '').trim();
171
+ if (raw === '') {
172
+ return { value: '', valid: false, reason: 'empty', message: 'Path is required' };
173
+ }
174
+ // Pre-normalize character checks — run on the raw input so the error
175
+ // matches what the user actually typed.
176
+ if (/\s/.test(raw)) {
177
+ return { value: raw, valid: false, reason: 'whitespace', message: 'Path cannot contain spaces' };
178
+ }
179
+ if (/[?#\\]/.test(raw)) {
180
+ return { value: raw, valid: false, reason: 'forbidden_char', message: 'Path cannot contain `?`, `#`, or `\\`' };
181
+ }
182
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional control-char detection
183
+ if (/[\x00-\x1F\x7F]/.test(raw)) {
184
+ return { value: raw, valid: false, reason: 'control_char', message: 'Path cannot contain control characters' };
185
+ }
186
+ if (/[A-Z]/.test(raw)) {
187
+ return { value: raw, valid: false, reason: 'uppercase', message: 'Path must be lowercase' };
188
+ }
189
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: ASCII-only enforcement
190
+ if (/[^\x00-\x7F]/.test(raw)) {
191
+ return {
192
+ value: raw,
193
+ valid: false,
194
+ reason: 'non_ascii',
195
+ message: 'Path can only contain a–z, 0–9, `-`, `_`, `/`',
196
+ };
197
+ }
198
+ // Normalize: add leading slash, collapse //, strip trailing slash.
199
+ let value = raw;
200
+ if (!value.startsWith('/'))
201
+ value = '/' + value;
202
+ value = value.replace(/\/+/g, '/');
203
+ if (value !== '/' && value.endsWith('/'))
204
+ value = value.slice(0, -1);
205
+ // Segment-level check: `.` and `..` are never valid path segments.
206
+ // Run before the generic disallowed-char check so the user gets the
207
+ // more specific "traversal" message.
208
+ if (value !== '/') {
209
+ for (const seg of value.slice(1).split('/')) {
210
+ if (seg === '.' || seg === '..') {
211
+ return {
212
+ value,
213
+ valid: false,
214
+ reason: 'traversal_segment',
215
+ message: 'Path cannot contain `.` or `..` segments',
216
+ };
217
+ }
218
+ }
219
+ }
220
+ // Final allowed-chars check — catches stray dots and anything else.
221
+ if (!/^[a-z0-9\-_/]*$/.test(value)) {
222
+ return {
223
+ value,
224
+ valid: false,
225
+ reason: 'disallowed_char',
226
+ message: 'Path can only contain a–z, 0–9, `-`, `_`, `/`',
227
+ };
228
+ }
229
+ return { value, valid: true };
230
+ }
231
+ /**
232
+ * Generate a content ID in the standard format
233
+ * IDs are prefixed with "vx-" followed by 8 random characters
234
+ */
235
+ export function generateContentId() {
236
+ return `vx-${nanoid(8)}`;
237
+ }
238
+ /**
239
+ * Get the current date/time in ISO format
240
+ * Used for timestamps in content files
241
+ */
242
+ export function getCurrentISODate() {
243
+ return new Date().toISOString();
244
+ }
245
+ /**
246
+ * Parse a date string safely
247
+ * Returns null if invalid
248
+ */
249
+ export function parseDate(dateStr) {
250
+ if (!dateStr)
251
+ return null;
252
+ try {
253
+ const date = new Date(dateStr);
254
+ if (isNaN(date.getTime()))
255
+ return null;
256
+ return date;
257
+ }
258
+ catch {
259
+ return null;
260
+ }
261
+ }
262
+ /**
263
+ * Creates a V8-optimized object by mapping site names to values.
264
+ * Ensures all objects have the same hidden class by adding properties in consistent order.
265
+ *
266
+ * @param sitesConfig - Sites configuration containing site names
267
+ * @param factory - Function that creates the value for each site
268
+ * @returns Object with all sites initialized in alphabetical order
269
+ */
270
+ export function mapSiteNames(sitesConfig, factory) {
271
+ const obj = {};
272
+ // Object.keys returns keys in insertion order, which is stable for a given object
273
+ for (const siteName of Object.keys(sitesConfig.sites)) {
274
+ obj[siteName] = factory(siteName);
275
+ }
276
+ return obj;
277
+ }
278
+ /**
279
+ * Creates a V8-optimized object by mapping locale names to values.
280
+ * Ensures all objects have the same hidden class by adding properties in consistent order.
281
+ *
282
+ * @param locales - Array of locale codes
283
+ * @param factory - Function that creates the value for each locale
284
+ * @returns Object with all locales initialized in array order
285
+ */
286
+ export function mapLocales(locales, factory) {
287
+ const obj = {};
288
+ for (const locale of locales) {
289
+ obj[locale] = factory(locale);
290
+ }
291
+ return obj;
292
+ }
293
+ /**
294
+ * Resolves a publish date value to a valid string or undefined.
295
+ * Handles various input types including null, false, and empty strings.
296
+ *
297
+ * @param updateValue - The value being updated (string | null | false | undefined)
298
+ * @param currentValue - The current value to fall back to if updateValue is undefined
299
+ * @returns A valid date string or undefined
300
+ */
301
+ export function resolvePublishDate(updateValue, currentValue) {
302
+ // If updateValue is explicitly provided (including null/false), use it
303
+ if (updateValue !== undefined) {
304
+ // Only return string values, treat null/false/empty as undefined
305
+ return updateValue && typeof updateValue === 'string' ? updateValue : undefined;
306
+ }
307
+ // Otherwise keep the current value
308
+ return currentValue;
309
+ }
310
+ /**
311
+ * Serializes MDX content with frontmatter.
312
+ * This is used by both FileSystemContentAPI and InMemoryContentAPI to ensure
313
+ * consistent MDX output that includes frontmatter for variable access.
314
+ *
315
+ * @param frontmatterData - The frontmatter data to serialize
316
+ * @param mdxContent - The MDX content (without frontmatter)
317
+ * @returns Complete MDX file content with frontmatter
318
+ */
319
+ export function serializeMdxWithFrontmatter(frontmatterData, mdxContent) {
320
+ const ordered = {};
321
+ const normalize = (value) => {
322
+ // gray-matter's default js-yaml schema parses ISO timestamps into JS Date
323
+ // objects. Convert back to strings so the QUOTE_SINGLE visitor below can
324
+ // restore the canonical single-quoted form on write.
325
+ if (value instanceof Date)
326
+ return value.toISOString();
327
+ return value;
328
+ };
329
+ for (const key of FRONTMATTER_KEY_ORDER) {
330
+ if (key in frontmatterData)
331
+ ordered[key] = normalize(frontmatterData[key]);
332
+ }
333
+ for (const key of Object.keys(frontmatterData).sort()) {
334
+ if (!(key in ordered))
335
+ ordered[key] = normalize(frontmatterData[key]);
336
+ }
337
+ const doc = new Document(ordered);
338
+ yaml.visit(doc, {
339
+ Scalar(_key, node) {
340
+ if (isScalar(node) && typeof node.value === 'string' && ISO_TIMESTAMP_RE.test(node.value)) {
341
+ node.type = 'QUOTE_SINGLE';
342
+ }
343
+ },
344
+ });
345
+ // Strip any leading newlines from the body. The serializer always emits
346
+ // exactly one blank line between the closing `---` and the body, so a
347
+ // caller-side leading `\n` (gray-matter leaves one in the content slice when
348
+ // it strips frontmatter) would compound into multiple blank lines and drift
349
+ // the diff on every save.
350
+ const body = mdxContent.replace(/^\n+/, '');
351
+ return `---\n${doc.toString()}---\n\n${body}`;
352
+ }
@@ -0,0 +1,43 @@
1
+ import { FileSystemContentAPI } from './filesystem-content-api';
2
+ import type { ContentAPIOptions } from './types';
3
+ export type ContentWatcherOptions = ContentAPIOptions;
4
+ export interface WebSocketSender {
5
+ send(payload: {
6
+ type: string;
7
+ event: string;
8
+ data: any;
9
+ }): void;
10
+ }
11
+ export interface ContentWatchEvent {
12
+ file: string;
13
+ action: 'update' | 'create' | 'delete';
14
+ inMdxRoot: boolean;
15
+ inContentRoot: boolean;
16
+ }
17
+ interface ReindexResultLike {
18
+ updated: unknown[];
19
+ deleted?: {
20
+ id: string;
21
+ locale: string;
22
+ kind: 'page' | 'block' | 'data';
23
+ }[];
24
+ }
25
+ interface ReindexableContentAPI {
26
+ reindex(paths: string[], options?: {
27
+ handleDeletions?: boolean;
28
+ }): Promise<ReindexResultLike>;
29
+ }
30
+ /**
31
+ * Creates a content API instance for the given options
32
+ */
33
+ export declare function createContentAPI(options: ContentWatcherOptions): Promise<FileSystemContentAPI>;
34
+ /**
35
+ * Creates file change handlers for content watching
36
+ */
37
+ export declare function createContentWatchHandlers(contentApi: ReindexableContentAPI, options: ContentWatcherOptions, ws: WebSocketSender, onReindexed?: (event: ContentWatchEvent) => void | Promise<void>): {
38
+ onChange: (file: string) => Promise<void>;
39
+ onAdd: (file: string) => Promise<void>;
40
+ onUnlink: (file: string) => Promise<void>;
41
+ };
42
+ export {};
43
+ //# sourceMappingURL=content-watcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content-watcher.d.ts","sourceRoot":"","sources":["../src/content-watcher.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEjD,MAAM,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,GAAG,CAAA;KAAE,GAAG,IAAI,CAAC;CACjE;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,aAAa,EAAE,OAAO,CAAC;CACxB;AAED,UAAU,iBAAiB;IACzB,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB,OAAO,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAAA;KAAE,EAAE,CAAC;CAC7E;AAED,UAAU,qBAAqB;IAC7B,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;CAC/F;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAKpG;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CACxC,UAAU,EAAE,qBAAqB,EACjC,OAAO,EAAE,qBAAqB,EAC9B,EAAE,EAAE,eAAe,EACnB,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAwE9D,QAAQ,SAAS,MAAM;IACvB,KAAK,SAAS,MAAM;IACpB,QAAQ,SAAS,MAAM;EAE1B"}
@@ -0,0 +1,83 @@
1
+ import { normalize, resolve } from 'node:path';
2
+ import { FileSystemContentAPI } from './filesystem-content-api';
3
+ /**
4
+ * Creates a content API instance for the given options
5
+ */
6
+ export async function createContentAPI(options) {
7
+ return await FileSystemContentAPI.create({
8
+ ...options,
9
+ canvasDir: options.canvasDir || './canvas',
10
+ });
11
+ }
12
+ /**
13
+ * Creates file change handlers for content watching
14
+ */
15
+ export function createContentWatchHandlers(contentApi, options, ws, onReindexed) {
16
+ const handleFileChange = async (file, action) => {
17
+ // Only process content files (.mdx, .vxjson, and .json in data/ directory)
18
+ const isContentFile = file.endsWith('.mdx') || file.endsWith('.vxjson');
19
+ const isDataFile = file.endsWith('.json') && file.includes('/data/');
20
+ if (!isContentFile && !isDataFile) {
21
+ return;
22
+ }
23
+ // Normalize paths for consistent comparison
24
+ const normalizedFile = normalize(resolve(file));
25
+ const normalizedRoot = normalize(resolve(options.contentRoot));
26
+ const normalizedMdxRoot = options.mdxPagesRoot ? normalize(resolve(options.mdxPagesRoot)) : null;
27
+ // Trailing-slash guard avoids prefix collisions
28
+ // (e.g. `/foo/content-extra/...` matching root `/foo/content`).
29
+ const inContentRoot = normalizedFile === normalizedRoot || normalizedFile.startsWith(normalizedRoot + '/');
30
+ const inMdxRoot = !!normalizedMdxRoot &&
31
+ (normalizedFile === normalizedMdxRoot || normalizedFile.startsWith(normalizedMdxRoot + '/'));
32
+ if (inContentRoot || inMdxRoot) {
33
+ const matchedRoot = inContentRoot ? normalizedRoot : normalizedMdxRoot;
34
+ const relativePath = normalizedFile.replace(matchedRoot + '/', '');
35
+ console.log(`[Content] ${action}: ${relativePath}`);
36
+ try {
37
+ // Reindex the file
38
+ const reindexOptions = action === 'delete' ? { handleDeletions: true } : undefined;
39
+ const result = await contentApi.reindex([normalizedFile], reindexOptions);
40
+ // Send updates for each changed locale
41
+ for (const manifest of result.updated) {
42
+ const message = {
43
+ type: 'custom',
44
+ event: 'conloca:content-update',
45
+ data: {
46
+ action,
47
+ manifest,
48
+ },
49
+ };
50
+ ws.send(message);
51
+ }
52
+ // Send deletion updates
53
+ if (action === 'delete' && result.deleted) {
54
+ for (const deletion of result.deleted) {
55
+ ws.send({
56
+ type: 'custom',
57
+ event: 'conloca:content-update',
58
+ data: {
59
+ action: 'delete',
60
+ ...deletion,
61
+ },
62
+ });
63
+ }
64
+ }
65
+ }
66
+ catch (error) {
67
+ console.error('[Content Watcher] Reindex failed:', error);
68
+ return;
69
+ }
70
+ try {
71
+ await onReindexed?.({ file: normalizedFile, action, inMdxRoot, inContentRoot });
72
+ }
73
+ catch (error) {
74
+ console.error('[Content Watcher] onReindexed callback failed:', error);
75
+ }
76
+ }
77
+ };
78
+ return {
79
+ onChange: (file) => handleFileChange(file, 'update'),
80
+ onAdd: (file) => handleFileChange(file, 'create'),
81
+ onUnlink: (file) => handleFileChange(file, 'delete'),
82
+ };
83
+ }
@@ -0,0 +1,62 @@
1
+ //#region src/data.ts
2
+ var Data = class {
3
+ api;
4
+ dataIndex;
5
+ constructor(api, dataIndex) {
6
+ this.api = api;
7
+ this.dataIndex = dataIndex;
8
+ }
9
+ *listContent(filters) {
10
+ if (filters?.collection) if (filters.locales && filters.locales.length > 0) {
11
+ for (const manifest of this.dataIndex.getManifestsByCollection(filters.collection)) if (filters.locales.some((locale) => manifest.locales[locale])) yield manifest;
12
+ } else yield* this.dataIndex.getManifestsByCollection(filters.collection);
13
+ else if (filters?.locales && filters.locales.length > 0) {
14
+ for (const manifest of this.dataIndex.getAllManifests()) if (filters.locales.some((locale) => manifest.locales[locale])) yield manifest;
15
+ } else yield* this.dataIndex.getAllManifests();
16
+ }
17
+ get collections() {
18
+ return this.dataIndex.collections;
19
+ }
20
+ getByName(collection, name, locale) {
21
+ return this.dataIndex.getByName(collection, name, locale);
22
+ }
23
+ isNameAvailable(collection, name, excludeId) {
24
+ const existing = this.getByName(collection, name);
25
+ return !existing || existing.id === excludeId;
26
+ }
27
+ getNameConflict(collection, name, excludeId) {
28
+ const existing = this.getByName(collection, name);
29
+ if (existing && existing.id !== excludeId) return existing.id;
30
+ return null;
31
+ }
32
+ isDataNameValid(dataName) {
33
+ if (!dataName || dataName.trim() === "") return false;
34
+ if (dataName.includes(".")) return false;
35
+ if (dataName.includes("/") || dataName.includes("\\")) return false;
36
+ return /^[a-zA-Z0-9_-]+$/.test(dataName);
37
+ }
38
+ async create(input) {
39
+ if (!this.isDataNameValid(input.name)) return {
40
+ success: false,
41
+ reason: "invalid_name",
42
+ error: /* @__PURE__ */ new Error(`Invalid data name: ${input.name}`)
43
+ };
44
+ if (this.getByName(input.collection, input.name)) return {
45
+ success: false,
46
+ reason: "name_taken",
47
+ error: /* @__PURE__ */ new Error(`Data name ${input.name} already exists in collection ${input.collection}`)
48
+ };
49
+ return this.api.createContent({
50
+ kind: "data",
51
+ collection: input.collection,
52
+ type: "json",
53
+ name: input.name,
54
+ meta: input.meta,
55
+ locales: input.locales
56
+ });
57
+ }
58
+ };
59
+ //#endregion
60
+ export { Data as t };
61
+
62
+ //# sourceMappingURL=data-DquNIEnQ.mjs.map