@conloca/content-api 0.1.15 → 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 (281) 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 +164 -0
  10. package/dist/asset-operations.d.ts.map +1 -0
  11. package/dist/asset-operations.js +784 -0
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +72 -0
  14. package/dist/asset-types.d.ts.map +1 -0
  15. package/dist/asset-types.js +13 -0
  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 +63 -0
  22. package/dist/base-content-index.d.ts.map +1 -0
  23. package/dist/base-content-index.js +200 -0
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.d.ts +31 -0
  26. package/dist/cf-access.d.ts.map +1 -0
  27. package/dist/cf-access.js +67 -0
  28. package/dist/cf-access.js.map +1 -0
  29. package/dist/component-registry.d.ts +50 -0
  30. package/dist/component-registry.d.ts.map +1 -0
  31. package/dist/component-registry.js +121 -0
  32. package/dist/component-registry.js.map +1 -0
  33. package/dist/component-registry.types.d.ts +11 -0
  34. package/dist/component-registry.types.d.ts.map +1 -0
  35. package/dist/component-registry.types.js +2 -0
  36. package/dist/component-registry.types.js.map +1 -0
  37. package/dist/component-vocabulary.d.ts +33 -0
  38. package/dist/component-vocabulary.d.ts.map +1 -0
  39. package/dist/component-vocabulary.js +105 -0
  40. package/dist/component-vocabulary.js.map +1 -0
  41. package/dist/content-api.interface.d.ts +64 -0
  42. package/dist/content-api.interface.d.ts.map +1 -0
  43. package/dist/content-api.interface.js +2 -0
  44. package/dist/content-api.interface.js.map +1 -0
  45. package/dist/content-filters.d.ts +31 -0
  46. package/dist/content-filters.d.ts.map +1 -0
  47. package/dist/content-filters.js +247 -0
  48. package/dist/content-filters.js.map +1 -0
  49. package/dist/content-index.d.ts +184 -0
  50. package/dist/content-index.d.ts.map +1 -0
  51. package/dist/content-index.js +546 -0
  52. package/dist/content-index.js.map +1 -0
  53. package/dist/content-operations.d.ts +157 -0
  54. package/dist/content-operations.d.ts.map +1 -0
  55. package/dist/content-operations.js +359 -0
  56. package/dist/content-operations.js.map +1 -0
  57. package/dist/content-path.d.ts +59 -0
  58. package/dist/content-path.d.ts.map +1 -0
  59. package/dist/content-path.js +88 -0
  60. package/dist/content-path.js.map +1 -0
  61. package/dist/content-reader.d.ts +10 -0
  62. package/dist/content-reader.d.ts.map +1 -0
  63. package/dist/content-reader.js +14 -0
  64. package/dist/content-reader.js.map +1 -0
  65. package/dist/content-utils.d.ts +175 -0
  66. package/dist/content-utils.d.ts.map +1 -0
  67. package/dist/content-utils.js +421 -0
  68. package/dist/content-utils.js.map +1 -0
  69. package/dist/content-watcher.d.ts +43 -0
  70. package/dist/content-watcher.d.ts.map +1 -0
  71. package/dist/content-watcher.js +86 -0
  72. package/dist/content-watcher.js.map +1 -0
  73. package/dist/data-index.d.ts +8 -0
  74. package/dist/data-index.d.ts.map +1 -0
  75. package/dist/data-index.js +8 -0
  76. package/dist/data-index.js.map +1 -0
  77. package/dist/data.d.ts +35 -0
  78. package/dist/data.d.ts.map +1 -0
  79. package/dist/data.js +104 -0
  80. package/dist/data.js.map +1 -0
  81. package/dist/editor-data-bindings.d.ts +10 -0
  82. package/dist/editor-data-bindings.d.ts.map +1 -0
  83. package/dist/editor-data-bindings.js +67 -0
  84. package/dist/editor-data-bindings.js.map +1 -0
  85. package/dist/etag-utils.d.ts +77 -0
  86. package/dist/etag-utils.d.ts.map +1 -0
  87. package/dist/etag-utils.js +161 -0
  88. package/dist/etag-utils.js.map +1 -0
  89. package/dist/filesystem-content-api.d.ts +162 -0
  90. package/dist/filesystem-content-api.d.ts.map +1 -0
  91. package/dist/filesystem-content-api.js +2307 -0
  92. package/dist/filesystem-content-api.js.map +1 -0
  93. package/dist/filesystem-reader-backend.d.ts +46 -0
  94. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  95. package/dist/filesystem-reader-backend.js +119 -0
  96. package/dist/filesystem-reader-backend.js.map +1 -0
  97. package/dist/fragment-index.d.ts +8 -0
  98. package/dist/fragment-index.d.ts.map +1 -0
  99. package/dist/fragment-index.js +8 -0
  100. package/dist/fragment-index.js.map +1 -0
  101. package/dist/fragments.d.ts +16 -0
  102. package/dist/fragments.d.ts.map +1 -0
  103. package/dist/fragments.js +104 -0
  104. package/dist/fragments.js.map +1 -0
  105. package/dist/git-operations.d.ts +49 -0
  106. package/dist/git-operations.d.ts.map +1 -0
  107. package/dist/git-operations.js +256 -0
  108. package/dist/git-operations.js.map +1 -0
  109. package/dist/header-parser.d.ts +37 -0
  110. package/dist/header-parser.d.ts.map +1 -0
  111. package/dist/header-parser.js +233 -0
  112. package/dist/header-parser.js.map +1 -0
  113. package/dist/in-memory-content-api.d.ts +35 -0
  114. package/dist/in-memory-content-api.d.ts.map +1 -0
  115. package/dist/in-memory-content-api.js +609 -0
  116. package/dist/in-memory-content-api.js.map +1 -0
  117. package/dist/index.d.ts +26 -0
  118. package/dist/index.d.ts.map +1 -0
  119. package/dist/index.js +28 -0
  120. package/dist/index.js.map +1 -0
  121. package/dist/indexing.d.ts +5 -0
  122. package/dist/indexing.d.ts.map +1 -0
  123. package/dist/indexing.js +8 -0
  124. package/dist/indexing.js.map +1 -0
  125. package/dist/json-whitespace-view.d.ts +32 -0
  126. package/dist/json-whitespace-view.d.ts.map +1 -0
  127. package/dist/json-whitespace-view.js +153 -0
  128. package/dist/json-whitespace-view.js.map +1 -0
  129. package/dist/middleware.d.ts +20 -0
  130. package/dist/middleware.d.ts.map +1 -0
  131. package/dist/middleware.js +1082 -0
  132. package/dist/middleware.js.map +1 -0
  133. package/dist/node.d.ts +32 -0
  134. package/dist/node.d.ts.map +1 -0
  135. package/dist/node.js +27 -0
  136. package/dist/node.js.map +1 -0
  137. package/dist/page-references.d.ts +21 -0
  138. package/dist/page-references.d.ts.map +1 -0
  139. package/dist/page-references.js +50 -0
  140. package/dist/page-references.js.map +1 -0
  141. package/dist/read-date.d.ts +3 -0
  142. package/dist/read-date.d.ts.map +1 -0
  143. package/dist/read-date.js +9 -0
  144. package/dist/read-date.js.map +1 -0
  145. package/dist/reader-backend.d.ts +54 -0
  146. package/dist/reader-backend.d.ts.map +1 -0
  147. package/dist/reader-backend.js +2 -0
  148. package/dist/reader-backend.js.map +1 -0
  149. package/dist/reader.d.ts +15 -0
  150. package/dist/reader.d.ts.map +1 -0
  151. package/dist/reader.js +14 -0
  152. package/dist/reader.js.map +1 -0
  153. package/dist/schemas/index.d.ts +102 -0
  154. package/dist/schemas/index.d.ts.map +1 -0
  155. package/dist/schemas/index.js +88 -0
  156. package/dist/schemas/index.js.map +1 -0
  157. package/dist/site-index.d.ts +60 -0
  158. package/dist/site-index.d.ts.map +1 -0
  159. package/dist/site-index.js +291 -0
  160. package/dist/site-index.js.map +1 -0
  161. package/dist/site.d.ts +23 -0
  162. package/dist/site.d.ts.map +1 -0
  163. package/dist/site.js +180 -0
  164. package/dist/site.js.map +1 -0
  165. package/dist/types.d.ts +641 -0
  166. package/dist/types.d.ts.map +1 -0
  167. package/dist/types.js +45 -0
  168. package/dist/types.js.map +1 -0
  169. package/dist/url-safe-base64.d.ts +12 -0
  170. package/dist/url-safe-base64.d.ts.map +1 -0
  171. package/dist/url-safe-base64.js +41 -0
  172. package/dist/url-safe-base64.js.map +1 -0
  173. package/dist/url-validation.d.ts +28 -0
  174. package/dist/url-validation.d.ts.map +1 -0
  175. package/dist/url-validation.js +123 -0
  176. package/dist/url-validation.js.map +1 -0
  177. package/dist/utils/atomic-write.d.ts +6 -0
  178. package/dist/utils/atomic-write.d.ts.map +1 -0
  179. package/dist/utils/atomic-write.js +21 -0
  180. package/dist/utils/atomic-write.js.map +1 -0
  181. package/dist/utils.d.ts +46 -0
  182. package/dist/utils.d.ts.map +1 -0
  183. package/dist/utils.js +71 -0
  184. package/dist/utils.js.map +1 -0
  185. package/dist/vite-plugin.d.ts +12 -0
  186. package/dist/vite-plugin.d.ts.map +1 -0
  187. package/dist/vite-plugin.js +30 -0
  188. package/dist/vite-plugin.js.map +1 -0
  189. package/dist/vxjson-serialize.d.ts +13 -0
  190. package/dist/vxjson-serialize.d.ts.map +1 -0
  191. package/dist/vxjson-serialize.js +53 -0
  192. package/dist/vxjson-serialize.js.map +1 -0
  193. package/dist/vxjson.d.ts +113 -0
  194. package/dist/vxjson.d.ts.map +1 -0
  195. package/dist/vxjson.js +381 -0
  196. package/dist/vxjson.js.map +1 -0
  197. package/dist/xxhash.d.ts +10 -0
  198. package/dist/xxhash.d.ts.map +1 -0
  199. package/dist/xxhash.js +35 -0
  200. package/dist/xxhash.js.map +1 -0
  201. package/package.json +132 -34
  202. package/src/asset-constraints.ts +33 -0
  203. package/src/asset-metadata-store.ts +401 -0
  204. package/src/asset-operations.ts +914 -0
  205. package/src/asset-types.ts +74 -0
  206. package/src/asset-usage.ts +47 -0
  207. package/src/base-content-index.ts +227 -0
  208. package/src/cf-access.ts +85 -0
  209. package/src/component-registry.ts +145 -0
  210. package/src/component-registry.types.ts +12 -0
  211. package/src/component-vocabulary.ts +87 -0
  212. package/src/content-api.interface.ts +94 -0
  213. package/src/content-filters.ts +278 -0
  214. package/src/content-index.ts +642 -0
  215. package/src/content-operations.ts +497 -0
  216. package/src/content-path.ts +113 -0
  217. package/src/content-reader.ts +18 -0
  218. package/src/content-utils.ts +474 -0
  219. package/src/content-watcher.ts +122 -0
  220. package/src/data-index.ts +7 -0
  221. package/src/data.ts +134 -0
  222. package/src/editor-data-bindings.ts +66 -0
  223. package/src/etag-utils.ts +204 -0
  224. package/src/filesystem-content-api.ts +2685 -0
  225. package/src/filesystem-reader-backend.ts +135 -0
  226. package/src/fragment-index.ts +7 -0
  227. package/src/fragments.ts +113 -0
  228. package/src/git-operations.ts +340 -0
  229. package/src/header-parser.ts +272 -0
  230. package/src/in-memory-content-api.ts +760 -0
  231. package/src/index.ts +45 -0
  232. package/src/indexing.ts +8 -0
  233. package/src/json-whitespace-view.ts +155 -0
  234. package/src/middleware.ts +1341 -0
  235. package/src/node.ts +40 -0
  236. package/src/page-references.ts +76 -0
  237. package/src/read-date.ts +7 -0
  238. package/src/reader-backend.ts +54 -0
  239. package/src/reader.ts +15 -0
  240. package/src/schemas/index.ts +113 -0
  241. package/src/site-index.ts +330 -0
  242. package/src/site.ts +198 -0
  243. package/src/types.ts +759 -0
  244. package/src/url-safe-base64.ts +38 -0
  245. package/src/url-validation.ts +121 -0
  246. package/src/utils/atomic-write.ts +20 -0
  247. package/src/utils.ts +84 -0
  248. package/src/vite-plugin.ts +45 -0
  249. package/src/vxjson-serialize.ts +66 -0
  250. package/src/vxjson.ts +442 -0
  251. package/src/xxhash.ts +43 -0
  252. package/dist/component-registry.types-CBGONnYn.d.mts +0 -71
  253. package/dist/component-registry.types-CBGONnYn.d.mts.map +0 -1
  254. package/dist/content-operations-Dv67amz3.d.mts +0 -852
  255. package/dist/content-operations-Dv67amz3.d.mts.map +0 -1
  256. package/dist/data-Db1Iv9T0.mjs +0 -60
  257. package/dist/data-Db1Iv9T0.mjs.map +0 -1
  258. package/dist/filesystem-content-api-C1TM0GLo.d.mts +0 -119
  259. package/dist/filesystem-content-api-C1TM0GLo.d.mts.map +0 -1
  260. package/dist/filesystem-content-api-kxKY5IUw.mjs +0 -2678
  261. package/dist/filesystem-content-api-kxKY5IUw.mjs.map +0 -1
  262. package/dist/index.d.mts +0 -79
  263. package/dist/index.d.mts.map +0 -1
  264. package/dist/index.mjs +0 -47
  265. package/dist/index.mjs.map +0 -1
  266. package/dist/node.d.mts +0 -378
  267. package/dist/node.d.mts.map +0 -1
  268. package/dist/node.mjs +0 -2618
  269. package/dist/node.mjs.map +0 -1
  270. package/dist/reader.d.mts +0 -18
  271. package/dist/reader.d.mts.map +0 -1
  272. package/dist/reader.mjs +0 -22
  273. package/dist/reader.mjs.map +0 -1
  274. package/dist/schemas/index.d.mts +0 -90
  275. package/dist/schemas/index.d.mts.map +0 -1
  276. package/dist/schemas/index.mjs +0 -70
  277. package/dist/schemas/index.mjs.map +0 -1
  278. package/dist/site-vNtJ5jCh.mjs +0 -538
  279. package/dist/site-vNtJ5jCh.mjs.map +0 -1
  280. package/dist/types-DWt912tu.mjs +0 -33
  281. package/dist/types-DWt912tu.mjs.map +0 -1
@@ -0,0 +1,135 @@
1
+ import { type FileHandle, open, readFile } from 'node:fs/promises';
2
+ import { resolve, sep } from 'node:path';
3
+ import fg from 'fast-glob';
4
+ import type { BackendReadResult, ContentReaderBackend } from './reader-backend.js';
5
+
6
+ const DEFAULT_GLOB = '**/*.{vxjson,mdx,json}';
7
+ const DEFAULT_HEADER_BYTES = 4096;
8
+ const DEFAULT_BATCH_SIZE = 1000;
9
+
10
+ export interface FileSystemReaderBackendOptions {
11
+ /** Filesystem root for content. Relative paths are resolved against cwd. */
12
+ contentRoot: string;
13
+ /** Glob applied during listing when the caller doesn't override; defaults to '**\/*.{vxjson,mdx,json}'. */
14
+ defaultGlob?: string;
15
+ /** Upper bound on the buffer pool size (one reusable Uint8Array per slot). */
16
+ batchSize?: number;
17
+ }
18
+
19
+ function errorReasonFromCode(error: unknown): 'not-found' | 'permission-denied' | 'io-error' {
20
+ if (error && typeof error === 'object' && 'code' in error) {
21
+ const code = (error as { code: unknown }).code;
22
+ if (code === 'ENOENT') return 'not-found';
23
+ if (code === 'EACCES' || code === 'EPERM') return 'permission-denied';
24
+ }
25
+ return 'io-error';
26
+ }
27
+
28
+ function toForwardSlash(path: string): string {
29
+ return sep === '/' ? path : path.split(sep).join('/');
30
+ }
31
+
32
+ /**
33
+ * `FileSystemReaderBackend` — the filesystem implementation of `ContentReaderBackend`.
34
+ *
35
+ * Hot-loop optimisations preserved from the legacy `FileSystemContentAPI` scanner:
36
+ * - fast-glob is used for the path scan (matches the existing dependency surface).
37
+ * - A small buffer pool (`min(files.length, batchSize)` slots) is reused across
38
+ * parallel reads to keep allocator pressure low on large content trees.
39
+ * - Per-file reads run via `fs/promises.open` + `read(buffer, 0, headerBytes, 0)`
40
+ * to avoid loading the full blob when only the manifest header is needed.
41
+ *
42
+ * By contract, the yielded `header` is **always a copy** of the bytes written
43
+ * into the pooled buffer. The pool will be overwritten by subsequent reads;
44
+ * yielding a slice would alias and corrupt earlier consumers.
45
+ *
46
+ * Per-file FS failures are surfaced as `{ ok: false, reason, message, path }`
47
+ * items — never thrown — so a single corrupt file doesn't abort the stream.
48
+ */
49
+ export class FileSystemReaderBackend implements ContentReaderBackend {
50
+ private readonly absoluteContentRoot: string;
51
+ private readonly defaultGlob: string;
52
+ private readonly batchSize: number;
53
+
54
+ constructor(options: FileSystemReaderBackendOptions) {
55
+ this.absoluteContentRoot = resolve(options.contentRoot);
56
+ this.defaultGlob = options.defaultGlob ?? DEFAULT_GLOB;
57
+ this.batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
58
+ }
59
+
60
+ /**
61
+ * Stream content paths matching the glob, with up to `headerBytes` of each
62
+ * file's bytes attached. Errors are surfaced as `{ ok: false }` items.
63
+ */
64
+ async *listContentPaths(opts?: { glob?: string; headerBytes?: number }): AsyncIterable<BackendReadResult> {
65
+ const glob = opts?.glob ?? this.defaultGlob;
66
+ const headerBytes = opts?.headerBytes ?? DEFAULT_HEADER_BYTES;
67
+
68
+ const matches = await fg(glob, {
69
+ cwd: this.absoluteContentRoot,
70
+ onlyFiles: true,
71
+ followSymbolicLinks: false,
72
+ dot: false,
73
+ });
74
+
75
+ if (matches.length === 0) return;
76
+
77
+ const poolSize = Math.max(1, Math.min(matches.length, this.batchSize));
78
+ const pool: Uint8Array[] = Array.from({ length: poolSize }, () => new Uint8Array(headerBytes));
79
+
80
+ for (let i = 0; i < matches.length; i++) {
81
+ const relativePath = toForwardSlash(matches[i]);
82
+ const absolutePath = resolve(this.absoluteContentRoot, matches[i]);
83
+ const buffer = pool[i % pool.length];
84
+
85
+ let handle: FileHandle | undefined;
86
+ try {
87
+ handle = await open(absolutePath, 'r');
88
+ const stat = await handle.stat();
89
+ const readLen = Math.min(headerBytes, stat.size);
90
+ const targetBuffer = buffer.byteLength >= readLen ? buffer : new Uint8Array(readLen);
91
+ const { bytesRead } = readLen > 0 ? await handle.read(targetBuffer, 0, readLen, 0) : { bytesRead: 0 };
92
+ // Always yield a copy. Slicing a `Uint8Array` allocates a fresh view
93
+ // backed by a new buffer in V8, so the next read into `targetBuffer`
94
+ // can't poison the bytes we just handed out.
95
+ const header = targetBuffer.slice(0, bytesRead);
96
+
97
+ yield {
98
+ ok: true,
99
+ path: relativePath,
100
+ size: stat.size,
101
+ header,
102
+ complete: bytesRead === stat.size,
103
+ };
104
+ } catch (error) {
105
+ yield {
106
+ ok: false,
107
+ path: relativePath,
108
+ reason: errorReasonFromCode(error),
109
+ message: error instanceof Error ? error.message : String(error),
110
+ };
111
+ } finally {
112
+ await handle?.close().catch(() => {
113
+ // Closing a never-opened handle throws — but we set it to undefined
114
+ // in that case, so this catch only swallows already-closed errors.
115
+ });
116
+ }
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Read the full bytes of a content path. Returns null if the path no longer
122
+ * exists (race against deletion is acceptable).
123
+ */
124
+ async readPath(path: string): Promise<Uint8Array | null> {
125
+ try {
126
+ const absolutePath = resolve(this.absoluteContentRoot, path);
127
+ const bytes = await readFile(absolutePath);
128
+ // readFile returns a Buffer (a Uint8Array subclass), which satisfies the
129
+ // contract. Returning it directly avoids a copy.
130
+ return bytes as Uint8Array;
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+ }
@@ -0,0 +1,7 @@
1
+ import { BaseContentIndex } from './base-content-index.js';
2
+
3
+ /**
4
+ * V8-optimized index for fragments
5
+ * Maintains collection->name->locale lookups
6
+ */
7
+ export class FragmentIndex extends BaseContentIndex {}
@@ -0,0 +1,113 @@
1
+ import type { ContentAPI } from './content-api.interface.js';
2
+ import type { FragmentIndex } from './fragment-index.js';
3
+ import type { ContentManifest, CreateFragmentInput, CreateResult, FragmentFilters } from './types.js';
4
+
5
+ export class Fragments {
6
+ constructor(
7
+ private api: ContentAPI,
8
+ private fragmentIndex: FragmentIndex,
9
+ ) {}
10
+
11
+ // Content discovery
12
+ *listContent(filters?: FragmentFilters): Generator<ContentManifest> {
13
+ // Choose the most efficient method based on filters
14
+ if (filters?.collection) {
15
+ if (filters.locales && filters.locales.length > 0) {
16
+ // Filter by locales after getting collection entries
17
+ for (const manifest of this.fragmentIndex.getManifestsByCollection(filters.collection)) {
18
+ if (filters.locales.some((locale) => manifest.locales[locale])) {
19
+ yield manifest;
20
+ }
21
+ }
22
+ } else {
23
+ yield* this.fragmentIndex.getManifestsByCollection(filters.collection);
24
+ }
25
+ } else if (filters?.locales && filters.locales.length > 0) {
26
+ // For multiple locales, we need to check each
27
+ for (const manifest of this.fragmentIndex.getAllManifests()) {
28
+ if (filters.locales.some((locale) => manifest.locales[locale])) {
29
+ yield manifest;
30
+ }
31
+ }
32
+ } else {
33
+ yield* this.fragmentIndex.getAllManifests();
34
+ }
35
+ }
36
+
37
+ // Get all fragment collections
38
+ get collections(): Set<string> {
39
+ return this.fragmentIndex.collections;
40
+ }
41
+
42
+ // Fragment operations (returns null if not found)
43
+ getByName(collection: string, name: string, locale?: string): ContentManifest | null {
44
+ return this.fragmentIndex.getByName(collection, name, locale);
45
+ }
46
+
47
+ // Check if fragment name is available, in any letter case as getNameConflict checks it
48
+ isNameAvailable(collection: string, name: string, excludeId?: string): boolean {
49
+ return this.getNameConflict(collection, name, excludeId) === null;
50
+ }
51
+
52
+ // Get the ID of content that conflicts with a fragment name
53
+ getNameConflict(collection: string, name: string, excludeId?: string): string | null {
54
+ // In any letter case: those names share one file on a case-insensitive disk.
55
+ for (const existing of this.fragmentIndex.getAllByNameInAnyCase(collection, name)) {
56
+ if (existing.id !== excludeId) return existing.id;
57
+ }
58
+ return null;
59
+ }
60
+
61
+ // Check if fragment name is valid
62
+ isFragmentNameValid(fragmentName: string): boolean {
63
+ // Fragment names must not be empty
64
+ if (!fragmentName || fragmentName.trim() === '') {
65
+ return false;
66
+ }
67
+
68
+ // Fragment names must not contain dots (would interfere with locale suffixes)
69
+ if (fragmentName.includes('.')) {
70
+ return false;
71
+ }
72
+
73
+ // Fragment names must not contain path separators
74
+ if (fragmentName.includes('/') || fragmentName.includes('\\')) {
75
+ return false;
76
+ }
77
+
78
+ // Fragment names should only contain alphanumeric, hyphens, underscores
79
+ return /^[a-zA-Z0-9_-]+$/.test(fragmentName);
80
+ }
81
+
82
+ // Create fragment with name validation
83
+ async create(data: CreateFragmentInput): Promise<CreateResult> {
84
+ // Validate fragment name
85
+ if (!this.isFragmentNameValid(data.name)) {
86
+ return {
87
+ success: false,
88
+ reason: 'invalid_name',
89
+ error: new Error(`Invalid fragment name: ${data.name}`),
90
+ };
91
+ }
92
+
93
+ // Check if name is already taken in any locale
94
+ const existing = this.getByName(data.collection, data.name);
95
+ if (existing) {
96
+ return {
97
+ success: false,
98
+ reason: 'name_taken',
99
+ error: new Error(`Fragment name ${data.name} already exists in collection ${data.collection}`),
100
+ };
101
+ }
102
+
103
+ // Create the content
104
+ return this.api.createContent({
105
+ kind: 'fragment',
106
+ collection: data.collection,
107
+ type: 'mdx',
108
+ name: data.name,
109
+ meta: data.meta,
110
+ locales: data.locales,
111
+ });
112
+ }
113
+ }
@@ -0,0 +1,340 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { access, readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
4
+
5
+ export interface GitStatus {
6
+ isRepo: boolean;
7
+ hasChanges: boolean;
8
+ changedFiles: number;
9
+ ahead: number;
10
+ behind: number;
11
+ branch: string;
12
+ remoteConfigured?: boolean;
13
+ }
14
+
15
+ export interface GitCommitResult {
16
+ success: boolean;
17
+ commit?: string;
18
+ summary?: string;
19
+ error?: string;
20
+ }
21
+
22
+ export interface GitPushResult {
23
+ success: boolean;
24
+ error?: string;
25
+ }
26
+
27
+ export interface GitPullResult {
28
+ success: boolean;
29
+ summary?: string;
30
+ error?: string;
31
+ }
32
+
33
+ export interface GitAuthor {
34
+ name: string;
35
+ email: string;
36
+ }
37
+
38
+ export interface GitOperations {
39
+ getStatus(): Promise<GitStatus>;
40
+ commitAll(message: string, author?: GitAuthor): Promise<GitCommitResult>;
41
+ pushOrigin(): Promise<GitPushResult>;
42
+ pull(): Promise<GitPullResult>;
43
+ }
44
+
45
+ export interface GitConfig {
46
+ contentPath: string;
47
+ branch?: string;
48
+ }
49
+
50
+ interface GitCommandResult {
51
+ exitCode: number;
52
+ stdout: string;
53
+ stderr: string;
54
+ }
55
+
56
+ function runGitCommand(cwd: string, args: string[]): Promise<GitCommandResult> {
57
+ return new Promise((resolveCommand, reject) => {
58
+ const process = spawn('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
59
+ let stdout = '';
60
+ let stderr = '';
61
+
62
+ process.stdout.on('data', (data: Buffer) => {
63
+ stdout += data.toString();
64
+ });
65
+
66
+ process.stderr.on('data', (data: Buffer) => {
67
+ stderr += data.toString();
68
+ });
69
+
70
+ process.on('error', reject);
71
+
72
+ process.on('close', (exitCode) => {
73
+ resolveCommand({
74
+ exitCode: exitCode ?? 1,
75
+ stdout: stdout.trim(),
76
+ stderr: stderr.trim(),
77
+ });
78
+ });
79
+ });
80
+ }
81
+
82
+ /**
83
+ * Resolve the git repository root from a content path.
84
+ * Uses `git rev-parse --show-toplevel` starting from the parent of the content directory.
85
+ */
86
+ async function resolveRepoRoot(contentPath: string): Promise<string | null> {
87
+ const contentRoot = resolve(contentPath);
88
+ const startDir = dirname(contentRoot);
89
+ const result = await runGitCommand(startDir, ['rev-parse', '--show-toplevel']);
90
+ if (result.exitCode !== 0) {
91
+ return null;
92
+ }
93
+ return result.stdout;
94
+ }
95
+
96
+ /**
97
+ * Create git operations using local git CLI commands.
98
+ * Requires git binary available on PATH and CONTENT_PATH inside a git repository.
99
+ */
100
+ export function createGitOperations(config: GitConfig): GitOperations {
101
+ // Git commands run with the repo root as cwd, so a project-relative contentPath
102
+ // (`./content`) would match nothing there when the repo root is a parent of the site.
103
+ const contentPath = resolve(config.contentPath);
104
+ const { branch } = config;
105
+
106
+ let cachedRepoRoot: string | null | undefined;
107
+
108
+ async function getCachedRepoRoot(): Promise<string | null> {
109
+ if (cachedRepoRoot === undefined) {
110
+ cachedRepoRoot = await resolveRepoRoot(contentPath);
111
+ }
112
+ return cachedRepoRoot;
113
+ }
114
+
115
+ return {
116
+ async getStatus(): Promise<GitStatus> {
117
+ try {
118
+ const repoRoot = await getCachedRepoRoot();
119
+ if (!repoRoot) {
120
+ return { isRepo: false, hasChanges: false, changedFiles: 0, ahead: 0, behind: 0, branch: 'unknown' };
121
+ }
122
+
123
+ // Get current branch
124
+ const branchResult = await runGitCommand(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);
125
+ const currentBranch = branchResult.exitCode === 0 ? branchResult.stdout : 'unknown';
126
+
127
+ // Get changed files count
128
+ const statusResult = await runGitCommand(repoRoot, ['status', '--porcelain', '--', contentPath]);
129
+ const changedLines = statusResult.stdout ? statusResult.stdout.split('\n').filter((l) => l.trim()) : [];
130
+ const changedFiles = changedLines.length;
131
+ const hasChanges = changedFiles > 0;
132
+
133
+ // Check if remote origin is configured
134
+ const remoteResult = await runGitCommand(repoRoot, ['remote', 'get-url', 'origin']);
135
+ const remoteConfigured = remoteResult.exitCode === 0;
136
+
137
+ // Get ahead/behind counts
138
+ let ahead = 0;
139
+ let behind = 0;
140
+ if (remoteConfigured) {
141
+ const trackingBranch = branch || currentBranch;
142
+ const revListResult = await runGitCommand(repoRoot, [
143
+ 'rev-list',
144
+ '--left-right',
145
+ '--count',
146
+ `HEAD...origin/${trackingBranch}`,
147
+ ]);
148
+ if (revListResult.exitCode === 0 && revListResult.stdout) {
149
+ const [a, b] = revListResult.stdout.split('\t').map(Number);
150
+ ahead = a || 0;
151
+ behind = b || 0;
152
+ }
153
+ }
154
+
155
+ return { isRepo: true, hasChanges, changedFiles, ahead, behind, branch: currentBranch, remoteConfigured };
156
+ } catch {
157
+ return { isRepo: false, hasChanges: false, changedFiles: 0, ahead: 0, behind: 0, branch: 'unknown' };
158
+ }
159
+ },
160
+
161
+ async commitAll(message: string, author?: GitAuthor): Promise<GitCommitResult> {
162
+ try {
163
+ const repoRoot = await getCachedRepoRoot();
164
+ if (!repoRoot) {
165
+ return { success: false, error: 'Not a git repository' };
166
+ }
167
+
168
+ // Stage all changes
169
+ const addResult = await runGitCommand(repoRoot, ['add', '-A', '--', contentPath]);
170
+ if (addResult.exitCode !== 0) {
171
+ return { success: false, error: addResult.stderr || 'Failed to stage changes' };
172
+ }
173
+
174
+ // Check if there's anything to commit after staging
175
+ const diffResult = await runGitCommand(repoRoot, ['diff', '--cached', '--quiet', '--', contentPath]);
176
+ if (diffResult.exitCode === 0) {
177
+ return { success: false, error: 'No changes to commit' };
178
+ }
179
+
180
+ // Count staged files for summary
181
+ const diffStatResult = await runGitCommand(repoRoot, ['diff', '--cached', '--numstat', '--', contentPath]);
182
+ const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split('\n').filter((l) => l.trim()).length : 0;
183
+
184
+ // Build commit command
185
+ const commitArgs = ['commit', '-m', message];
186
+ if (author) {
187
+ commitArgs.push('--author', `${author.name} <${author.email}>`);
188
+ }
189
+
190
+ const commitResult = await runGitCommand(repoRoot, commitArgs);
191
+ if (commitResult.exitCode !== 0) {
192
+ return { success: false, error: commitResult.stderr || 'Commit failed' };
193
+ }
194
+
195
+ // Get the commit SHA
196
+ const shaResult = await runGitCommand(repoRoot, ['rev-parse', 'HEAD']);
197
+ const commitSha = shaResult.stdout || undefined;
198
+
199
+ return {
200
+ success: true,
201
+ commit: commitSha,
202
+ summary: `${fileCount} files committed`,
203
+ };
204
+ } catch (error) {
205
+ return {
206
+ success: false,
207
+ error: error instanceof Error ? error.message : 'Commit failed',
208
+ };
209
+ }
210
+ },
211
+
212
+ async pushOrigin(): Promise<GitPushResult> {
213
+ try {
214
+ const repoRoot = await getCachedRepoRoot();
215
+ if (!repoRoot) {
216
+ return { success: false, error: 'Not a git repository' };
217
+ }
218
+
219
+ // Pre-check: verify remote is configured
220
+ const remoteResult = await runGitCommand(repoRoot, ['remote', 'get-url', 'origin']);
221
+ if (remoteResult.exitCode !== 0) {
222
+ return {
223
+ success: false,
224
+ error: 'No git remote "origin" configured. Please configure a remote to enable push.',
225
+ };
226
+ }
227
+
228
+ // Determine branch to push
229
+ let targetBranch = branch;
230
+ if (!targetBranch) {
231
+ const branchResult = await runGitCommand(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);
232
+ targetBranch = branchResult.stdout;
233
+ }
234
+
235
+ const pushResult = await runGitCommand(repoRoot, ['push', 'origin', targetBranch]);
236
+ if (pushResult.exitCode !== 0) {
237
+ const stderr = pushResult.stderr || '';
238
+ if (stderr.includes('non-fast-forward') || stderr.includes('rejected')) {
239
+ return {
240
+ success: false,
241
+ error: 'Push rejected: remote has changes. Pull first, then try pushing again.',
242
+ };
243
+ }
244
+ if (stderr.includes('Could not resolve host')) {
245
+ return {
246
+ success: false,
247
+ error: 'Cannot reach git remote. Check your network connection.',
248
+ };
249
+ }
250
+ if (stderr.includes('Permission denied') || stderr.includes('Authentication failed')) {
251
+ return {
252
+ success: false,
253
+ error: 'Git remote authentication failed. Check server SSH key or credential configuration.',
254
+ };
255
+ }
256
+ return { success: false, error: stderr || 'Push failed' };
257
+ }
258
+
259
+ return { success: true };
260
+ } catch (error) {
261
+ return {
262
+ success: false,
263
+ error: error instanceof Error ? error.message : 'Push failed',
264
+ };
265
+ }
266
+ },
267
+
268
+ async pull(): Promise<GitPullResult> {
269
+ try {
270
+ const repoRoot = await getCachedRepoRoot();
271
+ if (!repoRoot) {
272
+ return { success: false, error: 'Not a git repository' };
273
+ }
274
+
275
+ // Determine branch for pull
276
+ let targetBranch = branch;
277
+ if (!targetBranch) {
278
+ const branchResult = await runGitCommand(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);
279
+ targetBranch = branchResult.stdout;
280
+ }
281
+
282
+ const pullResult = await runGitCommand(repoRoot, ['pull', '--autostash', '--rebase', 'origin', targetBranch]);
283
+
284
+ if (pullResult.exitCode !== 0) {
285
+ return {
286
+ success: false,
287
+ error: pullResult.stderr || pullResult.stdout || 'Pull failed',
288
+ };
289
+ }
290
+
291
+ return {
292
+ success: true,
293
+ summary: pullResult.stdout || `Pulled latest changes from origin/${targetBranch}`,
294
+ };
295
+ } catch (error) {
296
+ return {
297
+ success: false,
298
+ error: error instanceof Error ? error.message : 'Pull failed',
299
+ };
300
+ }
301
+ },
302
+ };
303
+ }
304
+
305
+ const LFS_PATTERNS = [
306
+ '*.jpg filter=lfs diff=lfs merge=lfs -text',
307
+ '*.jpeg filter=lfs diff=lfs merge=lfs -text',
308
+ '*.png filter=lfs diff=lfs merge=lfs -text',
309
+ '*.gif filter=lfs diff=lfs merge=lfs -text',
310
+ '*.svg filter=lfs diff=lfs merge=lfs -text',
311
+ '*.webp filter=lfs diff=lfs merge=lfs -text',
312
+ '*.avif filter=lfs diff=lfs merge=lfs -text',
313
+ '*.ico filter=lfs diff=lfs merge=lfs -text',
314
+ ];
315
+
316
+ /**
317
+ * Ensure .gitattributes exists at contentRoot with LFS tracking patterns for web image extensions.
318
+ * Creates the file if missing, or appends missing patterns if file exists.
319
+ */
320
+ export async function setupGitLfsAttributes(contentRoot: string): Promise<void> {
321
+ const gitattributesPath = join(contentRoot, '.gitattributes');
322
+ let existing = '';
323
+
324
+ try {
325
+ await access(gitattributesPath);
326
+ existing = await readFile(gitattributesPath, 'utf-8');
327
+ } catch {
328
+ // File doesn't exist — will create fresh
329
+ }
330
+
331
+ const missingPatterns = LFS_PATTERNS.filter((pattern) => !existing.includes(pattern));
332
+
333
+ if (missingPatterns.length === 0) return;
334
+
335
+ const newContent = existing
336
+ ? `${existing.trimEnd()}\n${missingPatterns.join('\n')}\n`
337
+ : `${missingPatterns.join('\n')}\n`;
338
+
339
+ await writeFile(gitattributesPath, newContent, 'utf-8');
340
+ }