@conloca/astro-cms 0.1.15 → 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 (160) hide show
  1. package/README.md +65 -5
  2. package/dist/collections-Bd7EME4b.mjs +129 -0
  3. package/dist/collections-Bd7EME4b.mjs.map +1 -0
  4. package/dist/collections.d.mts +0 -1
  5. package/dist/collections.d.mts.map +1 -1
  6. package/dist/collections.mjs +1 -64
  7. package/dist/components.d.mts +2 -7
  8. package/dist/components.d.mts.map +1 -1
  9. package/dist/components.mjs +3 -6
  10. package/dist/components.mjs.map +1 -1
  11. package/dist/hydration.d.mts +2 -2
  12. package/dist/hydration.mjs +2 -3
  13. package/dist/index.d.mts +6 -37
  14. package/dist/index.d.mts.map +1 -1
  15. package/dist/index.mjs +7 -6
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/internal/cms-handler.d.mts +0 -1
  18. package/dist/internal/cms-handler.d.mts.map +1 -1
  19. package/dist/internal/cms-handler.mjs +55 -8
  20. package/dist/internal/cms-handler.mjs.map +1 -1
  21. package/dist/lib/hydration-script.d.mts +1 -2
  22. package/dist/lib/hydration-script.d.mts.map +1 -1
  23. package/dist/lib/hydration-script.mjs +1 -2
  24. package/dist/lib/hydration-script.mjs.map +1 -1
  25. package/dist/locales-helpers-BvYYqnJ5.d.mts +64 -0
  26. package/dist/locales-helpers-BvYYqnJ5.d.mts.map +1 -0
  27. package/dist/locales-helpers-qiwh7nxS.mjs +54 -0
  28. package/dist/locales-helpers-qiwh7nxS.mjs.map +1 -0
  29. package/dist/node/content.d.mts +0 -1
  30. package/dist/node/content.d.mts.map +1 -1
  31. package/dist/node/content.d.ts +3 -0
  32. package/dist/node/content.d.ts.map +1 -0
  33. package/dist/node/content.js +2 -0
  34. package/dist/node/content.mjs +2 -4
  35. package/dist/node/index.d.mts +151 -3
  36. package/dist/node/index.d.mts.map +1 -1
  37. package/dist/node/index.d.ts +4 -0
  38. package/dist/node/index.d.ts.map +1 -0
  39. package/dist/node/index.js +3 -0
  40. package/dist/node/index.mjs +1857 -97
  41. package/dist/node/index.mjs.map +1 -1
  42. package/dist/{serialize-props-Dhv_MnkY.mjs → serialize-props-BHoNpzH6.mjs} +2 -3
  43. package/dist/{serialize-props-Dhv_MnkY.mjs.map → serialize-props-BHoNpzH6.mjs.map} +1 -1
  44. package/dist/src/cms-handler.d.ts +19 -0
  45. package/dist/src/cms-handler.d.ts.map +1 -0
  46. package/dist/src/cms-handler.js +366 -0
  47. package/dist/src/collections.d.ts +32 -0
  48. package/dist/src/collections.d.ts.map +1 -0
  49. package/dist/src/collections.js +50 -0
  50. package/dist/src/components/HydrationWrapper.d.ts +18 -0
  51. package/dist/src/components/HydrationWrapper.d.ts.map +1 -0
  52. package/dist/src/components/HydrationWrapper.js +21 -0
  53. package/dist/src/components/RenderWithBlocks.d.ts +23 -0
  54. package/dist/src/components/RenderWithBlocks.d.ts.map +1 -0
  55. package/dist/src/components/RenderWithBlocks.js +129 -0
  56. package/dist/src/components/RenderWithHydration.d.ts +17 -0
  57. package/dist/src/components/RenderWithHydration.d.ts.map +1 -0
  58. package/dist/src/components/RenderWithHydration.js +36 -0
  59. package/dist/src/components.d.ts +4 -0
  60. package/dist/src/components.d.ts.map +1 -0
  61. package/dist/src/components.js +3 -0
  62. package/dist/src/discovery/astro-frontmatter.d.ts +18 -0
  63. package/dist/src/discovery/astro-frontmatter.d.ts.map +1 -0
  64. package/dist/src/discovery/astro-frontmatter.js +24 -0
  65. package/dist/src/discovery/extract-props-ts.d.ts +41 -0
  66. package/dist/src/discovery/extract-props-ts.d.ts.map +1 -0
  67. package/dist/src/discovery/extract-props-ts.js +231 -0
  68. package/dist/src/discovery/merge-registry.d.ts +58 -0
  69. package/dist/src/discovery/merge-registry.d.ts.map +1 -0
  70. package/dist/src/discovery/merge-registry.js +332 -0
  71. package/dist/src/discovery/registry-endpoint.d.ts +42 -0
  72. package/dist/src/discovery/registry-endpoint.d.ts.map +1 -0
  73. package/dist/src/discovery/registry-endpoint.js +81 -0
  74. package/dist/src/discovery/scan-components.d.ts +98 -0
  75. package/dist/src/discovery/scan-components.d.ts.map +1 -0
  76. package/dist/src/discovery/scan-components.js +399 -0
  77. package/dist/src/discovery/scan-mdx.d.ts +63 -0
  78. package/dist/src/discovery/scan-mdx.d.ts.map +1 -0
  79. package/dist/src/discovery/scan-mdx.js +112 -0
  80. package/dist/src/discovery/scan-overrides.d.ts +71 -0
  81. package/dist/src/discovery/scan-overrides.d.ts.map +1 -0
  82. package/dist/src/discovery/scan-overrides.js +33 -0
  83. package/dist/src/hydration.d.ts +4 -0
  84. package/dist/src/hydration.d.ts.map +1 -0
  85. package/dist/src/hydration.js +4 -0
  86. package/dist/src/index.d.ts +11 -0
  87. package/dist/src/index.d.ts.map +1 -0
  88. package/dist/src/index.js +25 -0
  89. package/dist/src/lib/hydration-scanner.d.ts +47 -0
  90. package/dist/src/lib/hydration-scanner.d.ts.map +1 -0
  91. package/dist/src/lib/hydration-scanner.js +135 -0
  92. package/dist/src/lib/hydration-script.d.ts +28 -0
  93. package/dist/src/lib/hydration-script.d.ts.map +1 -0
  94. package/dist/src/lib/hydration-script.js +88 -0
  95. package/dist/src/lib/hydration-utils.d.ts +51 -0
  96. package/dist/src/lib/hydration-utils.d.ts.map +1 -0
  97. package/dist/src/lib/hydration-utils.js +83 -0
  98. package/dist/src/lib/page-api.d.ts +77 -0
  99. package/dist/src/lib/page-api.d.ts.map +1 -0
  100. package/dist/src/lib/page-api.js +121 -0
  101. package/dist/src/lib/route-utils.d.ts +41 -0
  102. package/dist/src/lib/route-utils.d.ts.map +1 -0
  103. package/dist/src/lib/route-utils.js +78 -0
  104. package/dist/src/lib/routing-config.d.ts +32 -0
  105. package/dist/src/lib/routing-config.d.ts.map +1 -0
  106. package/dist/src/lib/routing-config.js +93 -0
  107. package/dist/src/lib/serialize-props.d.ts +6 -0
  108. package/dist/src/lib/serialize-props.d.ts.map +1 -0
  109. package/dist/src/lib/serialize-props.js +7 -0
  110. package/dist/src/lib/virtual-module-generators.d.ts +57 -0
  111. package/dist/src/lib/virtual-module-generators.d.ts.map +1 -0
  112. package/dist/src/lib/virtual-module-generators.js +263 -0
  113. package/dist/src/lib/withHydration.d.ts +51 -0
  114. package/dist/src/lib/withHydration.d.ts.map +1 -0
  115. package/dist/src/lib/withHydration.js +49 -0
  116. package/dist/src/loader.d.ts +14 -0
  117. package/dist/src/loader.d.ts.map +1 -0
  118. package/dist/src/loader.js +89 -0
  119. package/dist/src/locales-helpers.d.ts +61 -0
  120. package/dist/src/locales-helpers.d.ts.map +1 -0
  121. package/dist/src/locales-helpers.js +49 -0
  122. package/dist/src/mime-types.d.ts +3 -0
  123. package/dist/src/mime-types.d.ts.map +1 -0
  124. package/dist/src/mime-types.js +19 -0
  125. package/dist/src/path-validation.d.ts +8 -0
  126. package/dist/src/path-validation.d.ts.map +1 -0
  127. package/dist/src/path-validation.js +12 -0
  128. package/dist/src/plugin-spa.d.ts +164 -0
  129. package/dist/src/plugin-spa.d.ts.map +1 -0
  130. package/dist/src/plugin-spa.js +972 -0
  131. package/dist/src/safe-json-stringify.d.ts +13 -0
  132. package/dist/src/safe-json-stringify.d.ts.map +1 -0
  133. package/dist/src/safe-json-stringify.js +6 -0
  134. package/dist/src/site-styles/content-wrapper-endpoint.d.ts +76 -0
  135. package/dist/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -0
  136. package/dist/src/site-styles/content-wrapper-endpoint.js +227 -0
  137. package/dist/src/site-styles/render-endpoint.d.ts +55 -0
  138. package/dist/src/site-styles/render-endpoint.d.ts.map +1 -0
  139. package/dist/src/site-styles/render-endpoint.js +263 -0
  140. package/dist/src/site-styles/styles-endpoint.d.ts +61 -0
  141. package/dist/src/site-styles/styles-endpoint.d.ts.map +1 -0
  142. package/dist/src/site-styles/styles-endpoint.js +158 -0
  143. package/dist/src/types.d.ts +627 -0
  144. package/dist/src/types.d.ts.map +1 -0
  145. package/dist/src/types.js +1 -0
  146. package/dist/{types-CVQNmPxF.d.mts → types-CS9neadI.d.mts} +193 -3
  147. package/dist/types-CS9neadI.d.mts.map +1 -0
  148. package/dist/virtual-modules.d.ts +155 -0
  149. package/dist/{withHydration-EzyzBQ-Y.mjs → withHydration-C256ox_6.mjs} +2 -2
  150. package/dist/{withHydration-EzyzBQ-Y.mjs.map → withHydration-C256ox_6.mjs.map} +1 -1
  151. package/dist/{withHydration-HIvO9ysY.d.mts → withHydration-DkKpkmzJ.d.mts} +1 -2
  152. package/dist/withHydration-DkKpkmzJ.d.mts.map +1 -0
  153. package/package.json +82 -26
  154. package/dist/collections.mjs.map +0 -1
  155. package/dist/hydration-scanner-B0NjYkZ_.mjs +0 -109
  156. package/dist/hydration-scanner-B0NjYkZ_.mjs.map +0 -1
  157. package/dist/loader-By-AQWHc.mjs +0 -68
  158. package/dist/loader-By-AQWHc.mjs.map +0 -1
  159. package/dist/types-CVQNmPxF.d.mts.map +0 -1
  160. package/dist/withHydration-HIvO9ysY.d.mts.map +0 -1
@@ -0,0 +1,399 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import { basename, dirname, extname, relative, resolve } from 'node:path';
5
+ import fg from 'fast-glob';
6
+ import { extractAstroFrontmatter } from './astro-frontmatter.js';
7
+ import { createScanProject, extractPropsViaTs } from './extract-props-ts.js';
8
+ /**
9
+ * Scan every `.astro` / `.tsx` file under each configured folder.
10
+ * Folder globs are resolved relative to `projectRoot`.
11
+ */
12
+ export async function scanLocalComponents(folders, projectRoot) {
13
+ if (folders.length === 0)
14
+ return [];
15
+ // Source files (`.astro` for Astro, `.tsx` for React) first; `.d.ts`
16
+ // declaration files only if no matching source file exists. Same
17
+ // priority rationale as `scanExternalComponents` — host source is
18
+ // ground truth, declarations are last-resort schema.
19
+ const sourcePatterns = folders.map((f) => `${f.replace(/\/+$/, '')}/**/*.{astro,tsx}`);
20
+ const dtsPatterns = folders.map((f) => `${f.replace(/\/+$/, '')}/**/*.d.ts`);
21
+ const sourceFiles = await fg(sourcePatterns, { cwd: projectRoot, absolute: true, dot: false });
22
+ const dtsFiles = await fg(dtsPatterns, { cwd: projectRoot, absolute: true, dot: false });
23
+ const seen = new Set();
24
+ const allFiles = [];
25
+ for (const file of sourceFiles) {
26
+ const name = componentNameFromPath(file);
27
+ if (seen.has(name))
28
+ continue;
29
+ seen.add(name);
30
+ allFiles.push(file);
31
+ }
32
+ for (const file of dtsFiles) {
33
+ const name = componentNameFromPath(file);
34
+ if (seen.has(name))
35
+ continue;
36
+ seen.add(name);
37
+ allFiles.push(file);
38
+ }
39
+ // One ts-morph Project per scan run, shared across every file
40
+ // we extract from. Building the Project loads `lib.dom.d.ts` etc.
41
+ // (the dominant cost ~500ms-2s); sharing across files amortises
42
+ // it. Fed the host's tsconfig when present so cross-file `typeof`
43
+ // refs and path mappings (`@/foo`) resolve as authored.
44
+ const tsConfigFilePath = findTsConfig(projectRoot);
45
+ const project = createScanProject(tsConfigFilePath);
46
+ const results = [];
47
+ for (const file of allFiles) {
48
+ try {
49
+ const r = await scanFile(file, projectRoot, project);
50
+ if (r)
51
+ results.push(r);
52
+ }
53
+ catch (err) {
54
+ console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);
55
+ }
56
+ }
57
+ return results;
58
+ }
59
+ async function scanFile(filepath, projectRoot, project) {
60
+ const content = await readFile(filepath, 'utf8');
61
+ const name = componentNameFromPath(filepath);
62
+ // Components typically start with a capital. Lowercase-named files
63
+ // are usually utilities, not authorable components — skip them so
64
+ // we don't pollute the registry with `helpers.ts` and friends.
65
+ if (!/^[A-Z]/.test(name))
66
+ return null;
67
+ const props = extractPropsForFile(project, filepath, content, name);
68
+ const importSpecifier = `/${relative(projectRoot, filepath).replace(/\\/g, '/')}`;
69
+ return {
70
+ filepath,
71
+ name,
72
+ source: filepath,
73
+ importSpecifier,
74
+ kind: 'flow',
75
+ props,
76
+ };
77
+ }
78
+ /**
79
+ * Bridge between the file-level scanner and the ts-morph extractor.
80
+ * Handles the three file types we accept:
81
+ * - `.astro` — extract the `---`-fenced frontmatter, feed it as
82
+ * a virtual `.ts` source.
83
+ * - `.tsx` / `.d.ts` — feed the whole file content directly.
84
+ *
85
+ * The virtual source path is the real filepath suffixed with
86
+ * `.virtual.ts` for `.astro` files, so ts-morph's diagnostics still
87
+ * point back at the right author file. For `.tsx` / `.d.ts` we use
88
+ * the real path verbatim — ts-morph parses TS extensions natively.
89
+ */
90
+ function extractPropsForFile(project, filepath, content, componentName) {
91
+ if (filepath.endsWith('.astro')) {
92
+ const frontmatter = extractAstroFrontmatter(content);
93
+ if (!frontmatter)
94
+ return [];
95
+ return extractPropsViaTs(project, `${filepath}.virtual.ts`, frontmatter, componentName);
96
+ }
97
+ return extractPropsViaTs(project, filepath, content, componentName);
98
+ }
99
+ /**
100
+ * Locate the host's `tsconfig.json` so the ts-morph Project can
101
+ * resolve cross-file `typeof` refs, path aliases, and node_modules
102
+ * declarations the same way the author's IDE does. Walks up from
103
+ * `projectRoot` looking for the closest tsconfig; returns `undefined`
104
+ * if none found (the Project then uses permissive defaults).
105
+ */
106
+ function findTsConfig(projectRoot) {
107
+ const candidate = resolve(projectRoot, 'tsconfig.json');
108
+ return existsSync(candidate) ? candidate : undefined;
109
+ }
110
+ /**
111
+ * Derive the canonical component name from a file path.
112
+ *
113
+ * Two extension shapes:
114
+ * - Single (`.astro`, `.tsx`) → strip with `extname`/`basename`.
115
+ * - Compound (`.d.ts`) → strip `.d.ts` explicitly, since `extname`
116
+ * would return only `.ts` and leave a trailing `.d` (`Card.d`).
117
+ *
118
+ * Keeps the rule simple and consistent: file basename === component
119
+ * name. Multi-component files (a `.d.ts` exporting many React
120
+ * components from one barrel) are NOT supported through this path —
121
+ * the sidecar `cmsConfig` mechanism (future task) covers those.
122
+ */
123
+ function componentNameFromPath(filepath) {
124
+ const base = basename(filepath);
125
+ if (base.endsWith('.d.ts'))
126
+ return base.slice(0, -'.d.ts'.length);
127
+ return base.slice(0, -extname(base).length);
128
+ }
129
+ /**
130
+ * Scan every npm-style import source referenced in the MDX usage scan
131
+ * and treat any `.astro` / `.tsx` file inside the resolved package as a
132
+ * candidate component. Resolves each unique specifier via Node's
133
+ * `require.resolve` (run from `projectRoot` so packages are looked up
134
+ * in the consumer's `node_modules`, not ours), walks up to the package
135
+ * root, then globs the package for component-shaped files.
136
+ *
137
+ * The returned `source` on each result is the ORIGINAL specifier from
138
+ * the MDX import (e.g. `@astrojs/starlight/components`) — not the
139
+ * resolved file path. That's what makes the merge work: `scan-mdx`
140
+ * records imports by their literal source string, so for the merge
141
+ * registry to dedupe local-folder scan ⨯ MDX-usage scan we need both
142
+ * sides to key on the same specifier. Vite's `ssrLoadModule` handles
143
+ * the specifier itself at render time, so we don't need an absolute
144
+ * file path on the descriptor.
145
+ *
146
+ * Caveats:
147
+ * - Specifiers that look like local paths (`./foo`, `/abs/path`) are
148
+ * intentionally skipped here — those are local components, already
149
+ * covered by `scanLocalComponents`.
150
+ * - One specifier per package: if a package is imported via two
151
+ * different specifiers (`@pkg/components` and `@pkg`), we'll scan
152
+ * it twice and emit two descriptor sets keyed on each specifier.
153
+ * The merge layer's collision resolution picks the one with more
154
+ * real usage, so this is self-correcting in practice.
155
+ * - We cap glob depth at 4 to avoid walking into deeply-nested
156
+ * library internals (most component packages put their exports
157
+ * near the root). Components nested deeper won't surface; hosts
158
+ * can either re-export them at a shallower path or add a sidecar
159
+ * `cmsConfig` (when sidecar support lands).
160
+ */
161
+ export async function scanExternalComponents(mdxScans, projectRoot) {
162
+ const specifiers = collectExternalSpecifiers(mdxScans);
163
+ if (specifiers.size === 0)
164
+ return [];
165
+ // Same Project-per-scan rationale as scanLocalComponents — pay the
166
+ // checker init cost once, share across every external file.
167
+ const tsConfigFilePath = findTsConfig(projectRoot);
168
+ const project = createScanProject(tsConfigFilePath);
169
+ const results = [];
170
+ // `createRequire(projectRoot/package.json)` so resolution starts in
171
+ // the consumer's tree. Without this, Node looks up modules relative
172
+ // to wherever this file lives (our package), which would miss the
173
+ // consumer's installed dependencies.
174
+ const requireFromProject = createRequire(`${projectRoot.replace(/\/$/, '')}/package.json`);
175
+ for (const specifier of specifiers) {
176
+ try {
177
+ const resolved = requireFromProject.resolve(specifier);
178
+ const packageRoot = findPackageRoot(resolved);
179
+ if (!packageRoot)
180
+ continue;
181
+ // First try: parse the resolved file as a re-export barrel
182
+ // (`export { default as Card } from './user-components/Card.astro'`).
183
+ // If we find re-exports, scan ONLY those files — the package's
184
+ // own author has declared the public surface, and everything
185
+ // else is internal noise we don't want in the registry.
186
+ //
187
+ // This is the Starlight case: `@astrojs/starlight/components`
188
+ // resolves to a barrel `.ts` listing exactly the 12 components
189
+ // the package intends for MDX use, hiding ~30 internal layout
190
+ // components in the same `node_modules` tree.
191
+ const barrelFiles = await collectBarrelExports(resolved, packageRoot);
192
+ let scanFiles;
193
+ if (barrelFiles.length > 0) {
194
+ scanFiles = barrelFiles;
195
+ }
196
+ else {
197
+ // Fallback: glob the whole package. Source files (`.astro`,
198
+ // `.tsx`) first, then `.d.ts` as a last-resort schema source
199
+ // for compiled packages. Dedupe by component name so a package
200
+ // shipping BOTH `Card.tsx` and `Card.d.ts` uses the source
201
+ // file (more reliable schema) and ignores the declaration.
202
+ const sourceFiles = await fg('**/*.{astro,tsx}', {
203
+ cwd: packageRoot,
204
+ absolute: true,
205
+ dot: false,
206
+ deep: 4,
207
+ });
208
+ const dtsFiles = await fg('**/*.d.ts', {
209
+ cwd: packageRoot,
210
+ absolute: true,
211
+ dot: false,
212
+ deep: 4,
213
+ });
214
+ const seen = new Set();
215
+ scanFiles = [];
216
+ for (const file of [...sourceFiles, ...dtsFiles]) {
217
+ const name = componentNameFromPath(file);
218
+ if (seen.has(name))
219
+ continue;
220
+ seen.add(name);
221
+ scanFiles.push(file);
222
+ }
223
+ }
224
+ for (const file of scanFiles) {
225
+ try {
226
+ const r = await scanExternalFile(file, specifier, project);
227
+ if (r)
228
+ results.push(r);
229
+ }
230
+ catch (err) {
231
+ console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);
232
+ }
233
+ }
234
+ }
235
+ catch (err) {
236
+ // Resolution failures are common and expected — a `./local.css`
237
+ // import or a missing optional peer dep both land here. Skip
238
+ // quietly rather than failing the whole registry build.
239
+ console.warn(`[conloca:discovery] could not resolve '${specifier}' from ${projectRoot}:`, err instanceof Error ? err.message : err);
240
+ }
241
+ }
242
+ return results;
243
+ }
244
+ /**
245
+ * Same parsing as `scanFile`, but with `source` set to the original
246
+ * npm specifier instead of the absolute file path. See the function
247
+ * doc on `scanExternalComponents` for why.
248
+ */
249
+ async function scanExternalFile(filepath, specifier, project) {
250
+ const content = await readFile(filepath, 'utf8');
251
+ const name = componentNameFromPath(filepath);
252
+ if (!/^[A-Z]/.test(name))
253
+ return null;
254
+ const props = extractPropsForFile(project, filepath, content, name);
255
+ return {
256
+ filepath,
257
+ name,
258
+ // CRITICAL: source = specifier (not filepath) so merge-registry
259
+ // joins this entry with MDX-usage entries that key on the same
260
+ // specifier. See the merge logic at `byKey` in merge-registry.ts.
261
+ source: specifier,
262
+ importSpecifier: specifier,
263
+ kind: 'flow',
264
+ props,
265
+ };
266
+ }
267
+ /**
268
+ * Pick out unique npm-style specifiers from every import seen in the
269
+ * MDX scan. Local paths (`./foo`, `/abs`) are dropped — `scanLocalComponents`
270
+ * covers those via its folder glob.
271
+ */
272
+ function collectExternalSpecifiers(mdxScans) {
273
+ const out = new Set();
274
+ for (const scan of mdxScans) {
275
+ for (const imp of Object.values(scan.imports)) {
276
+ const src = imp.source;
277
+ if (!src)
278
+ continue;
279
+ // Local-path indicators per ESM spec: starts with `.` (`./foo`,
280
+ // `../bar`) or `/` (absolute). Everything else is treated as
281
+ // npm-resolvable.
282
+ if (src.startsWith('.') || src.startsWith('/'))
283
+ continue;
284
+ out.add(src);
285
+ }
286
+ }
287
+ return out;
288
+ }
289
+ /**
290
+ * If `resolvedFile` is a barrel (re-export aggregator), return the
291
+ * absolute paths of every re-exported component file. Otherwise
292
+ * return an empty array.
293
+ *
294
+ * Patterns recognized:
295
+ * - `export { default as Foo } from './path/to/Foo.astro'`
296
+ * - `export { Foo } from './path/to/Foo'`
297
+ * - `export { Foo, Bar } from './path/to/m'`
298
+ * - `export * from './path/to/m'` (treated as opaque — we
299
+ * can't enumerate the
300
+ * names without a real
301
+ * parser, so we skip and
302
+ * fall back to glob-all)
303
+ *
304
+ * The barrel must resolve to a real file we can re-resolve to one of
305
+ * the supported extensions (`.astro`, `.tsx`, `.d.ts`). Missing or
306
+ * unsupported targets are dropped quietly. Comments are stripped
307
+ * first to avoid matching commented-out exports.
308
+ *
309
+ * Why this matters: Starlight's `@astrojs/starlight/components`
310
+ * barrel lists exactly the 12 MDX-friendly components. Globbing the
311
+ * whole package would also pull in ~30 internal layout components
312
+ * (Banner, Hero, Pagination, ...) — they'd litter the slash menu
313
+ * even though they're not meant for author use.
314
+ */
315
+ async function collectBarrelExports(resolvedFile, packageRoot) {
316
+ // Only `.ts` / `.js` / `.mjs` source files can be barrels; an
317
+ // `.astro` or `.tsx` file is the component itself, not an
318
+ // aggregator. Bail early to avoid reading binary or unsupported
319
+ // file types.
320
+ if (!/\.(?:m?[jt]s)$/.test(resolvedFile))
321
+ return [];
322
+ let content;
323
+ try {
324
+ content = await readFile(resolvedFile, 'utf8');
325
+ }
326
+ catch {
327
+ return [];
328
+ }
329
+ const cleaned = content.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/[^\n]*/g, '$1');
330
+ // Collect the relative source paths from every `export {...} from '<path>'`.
331
+ // We don't need the export names here — we just need the files to
332
+ // scan. Each scanned file's component name comes from its own
333
+ // basename, the same way local components work.
334
+ const pathRe = /export\s*(?:\{[^}]*\}|\*)\s*from\s*['"]([^'"]+)['"]/g;
335
+ const relPaths = new Set();
336
+ for (const m of cleaned.matchAll(pathRe)) {
337
+ const rel = m[1];
338
+ // Skip `export *` — we can't enumerate without a real parser, and
339
+ // re-running the barrel collector recursively would invite cycles.
340
+ // Falls through to glob-all below if no other re-exports exist.
341
+ if (!rel)
342
+ continue;
343
+ relPaths.add(rel);
344
+ }
345
+ if (relPaths.size === 0)
346
+ return [];
347
+ // Resolve each relative path. `import.meta.resolve` doesn't take a
348
+ // base file, so use the barrel's directory as the resolution root.
349
+ const barrelDir = dirname(resolvedFile);
350
+ const requireFromBarrel = createRequire(`${barrelDir}/_.js`);
351
+ const resolved = [];
352
+ for (const rel of relPaths) {
353
+ try {
354
+ const target = requireFromBarrel.resolve(rel);
355
+ // Only keep targets that look like component files we can
356
+ // scan (extensions our extractor supports) AND live inside
357
+ // the package root (defensive — barrels in the wild can
358
+ // re-export from sibling packages, which we don't want to
359
+ // descend into).
360
+ if (!/\.(?:astro|tsx|d\.ts)$/.test(target))
361
+ continue;
362
+ if (!target.startsWith(packageRoot))
363
+ continue;
364
+ resolved.push(target);
365
+ }
366
+ catch {
367
+ // Missing optional file or extension we don't handle — skip.
368
+ }
369
+ }
370
+ return resolved;
371
+ }
372
+ /**
373
+ * Walk up from a resolved file path until we find the directory that
374
+ * contains the closest `package.json`. That's the package root we'll
375
+ * glob for component files. Returns `null` if no package.json is found
376
+ * within a reasonable depth (defensive — shouldn't happen for a real
377
+ * resolution).
378
+ */
379
+ function findPackageRoot(resolvedPath) {
380
+ let dir = dirname(resolvedPath);
381
+ for (let i = 0; i < 10; i++) {
382
+ // Sync existsSync is fine here — the walk is at most ~10 hops per
383
+ // package and runs once per unique specifier per scan.
384
+ if (existsSync(`${dir}/package.json`))
385
+ return dir;
386
+ const parent = dirname(dir);
387
+ if (parent === dir)
388
+ return null;
389
+ dir = parent;
390
+ }
391
+ return null;
392
+ }
393
+ // Prop extraction lives in `./extract-props-ts.ts` (TypeScript
394
+ // compiler API via ts-morph). The previous regex-based scanner —
395
+ // `extractPropsInterface` + `parseTypeExpr` — was removed in the
396
+ // migration: it silently dropped options for derived types like
397
+ // `(typeof asideVariants)[number]`, mapped types, conditional types,
398
+ // and imported aliases. The ts-morph path resolves all of those.
399
+ // Astro frontmatter extraction lives in `./astro-frontmatter.ts`.
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Walks the content directory for `.mdx` files, parses each one, and
3
+ * returns a per-file record of:
4
+ *
5
+ * - **imports** — every `import { Foo, Bar as Baz } from 'pkg'` /
6
+ * `import Default from 'pkg'` declaration in the file's ESM
7
+ * header, keyed by the LOCAL name as seen in the JSX usages
8
+ * below. The `aliasedFrom` field records when the local name
9
+ * differs from the canonical export, so the save serializer can
10
+ * preserve the alias when rewriting the file.
11
+ *
12
+ * - **usages** — every `<Foo>` / `<Foo />` element in the file's
13
+ * body, in source order, with its observed string attributes.
14
+ *
15
+ * The merge step (downstream) joins each usage to its import via
16
+ * the local name to build the final component descriptor list.
17
+ *
18
+ * Parsing uses `mdast-util-from-markdown` with the full MDX extension
19
+ * bundle (`micromark-extension-mdxjs` + `mdast-util-mdx`) — the same
20
+ * stack the editor uses on every save, so what we observe here is
21
+ * exactly what the editor's save path can round-trip.
22
+ */
23
+ export interface MdxImport {
24
+ /** The npm-style or relative source path. */
25
+ source: string;
26
+ /** True for `import Foo from '...'`; false for named imports. */
27
+ defaultExport: boolean;
28
+ /** The canonical export name on the package side. For
29
+ * `import { Aside as Callout }`, this is `'Aside'` while the
30
+ * local key is `'Callout'`. For default imports this is `'default'`. */
31
+ exportName: string;
32
+ /** Local alias used in this file, if it differs from `exportName`.
33
+ * `undefined` when the file uses the canonical name unchanged. */
34
+ aliasedFrom?: string;
35
+ }
36
+ export interface MdxUsage {
37
+ /** The local name used in the JSX tag — `<Foo>` → `'Foo'`. */
38
+ name: string;
39
+ /** Observed attributes as raw strings. Expression-valued attrs
40
+ * (`prop={42}`) and complex values are not captured here; this
41
+ * field is for inferring "values seen in real usage" to populate
42
+ * dropdown choices on the prop panel. */
43
+ attrs: Record<string, string>;
44
+ /** `'flow'` (block-level) or `'text'` (inline-level) — matches the
45
+ * mdast node type. Used to set the descriptor's `kind`. */
46
+ kind: 'flow' | 'text';
47
+ }
48
+ export interface MdxScanResult {
49
+ /** Absolute path of the scanned file. */
50
+ filepath: string;
51
+ /** Local name → import declaration. */
52
+ imports: Record<string, MdxImport>;
53
+ /** All JSX usages in document order. */
54
+ usages: MdxUsage[];
55
+ }
56
+ /**
57
+ * Scan every `.mdx` file under `rootDir` (recursive). Returns one
58
+ * result per file. Files that fail to parse are skipped with a
59
+ * warning rather than throwing — the discovery flow shouldn't take
60
+ * down the dev server on a single broken file.
61
+ */
62
+ export declare function scanMdxFiles(rootDir: string): Promise<MdxScanResult[]>;
63
+ //# sourceMappingURL=scan-mdx.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan-mdx.d.ts","sourceRoot":"","sources":["../../../src/discovery/scan-mdx.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,WAAW,SAAS;IACxB,6CAA6C;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,iEAAiE;IACjE,aAAa,EAAE,OAAO,CAAC;IACvB;;4EAEwE;IACxE,UAAU,EAAE,MAAM,CAAC;IACnB;sEACkE;IAClE,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,QAAQ;IACvB,8DAA8D;IAC9D,IAAI,EAAE,MAAM,CAAC;IACb;;;6CAGyC;IACzC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B;+DAC2D;IAC3D,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,aAAa;IAC5B,yCAAyC;IACzC,QAAQ,EAAE,MAAM,CAAC;IACjB,uCAAuC;IACvC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACnC,wCAAwC;IACxC,MAAM,EAAE,QAAQ,EAAE,CAAC;CACpB;AAED;;;;;GAKG;AACH,wBAAsB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAW5E"}
@@ -0,0 +1,112 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import fg from 'fast-glob';
3
+ import { fromMarkdown } from 'mdast-util-from-markdown';
4
+ import { mdxFromMarkdown } from 'mdast-util-mdx';
5
+ import { mdxjs } from 'micromark-extension-mdxjs';
6
+ /**
7
+ * Scan every `.mdx` file under `rootDir` (recursive). Returns one
8
+ * result per file. Files that fail to parse are skipped with a
9
+ * warning rather than throwing — the discovery flow shouldn't take
10
+ * down the dev server on a single broken file.
11
+ */
12
+ export async function scanMdxFiles(rootDir) {
13
+ const files = await fg('**/*.mdx', { cwd: rootDir, absolute: true, dot: false });
14
+ const results = [];
15
+ for (const file of files) {
16
+ try {
17
+ results.push(await scanFile(file));
18
+ }
19
+ catch (err) {
20
+ console.warn(`[conloca:discovery] failed to scan ${file}:`, err instanceof Error ? err.message : err);
21
+ }
22
+ }
23
+ return results;
24
+ }
25
+ async function scanFile(filepath) {
26
+ const content = await readFile(filepath, 'utf8');
27
+ const tree = fromMarkdown(content, {
28
+ extensions: [mdxjs()],
29
+ mdastExtensions: [mdxFromMarkdown()],
30
+ });
31
+ const imports = {};
32
+ const usages = [];
33
+ walk(tree, (node) => {
34
+ if (isEsmNode(node)) {
35
+ collectImports(node, imports);
36
+ }
37
+ else if (node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement') {
38
+ const name = typeof node.name === 'string' ? node.name : '';
39
+ if (!name)
40
+ return;
41
+ const attrs = {};
42
+ const rawAttrs = node.attributes ?? [];
43
+ for (const a of rawAttrs) {
44
+ if (a.type !== 'mdxJsxAttribute' || typeof a.name !== 'string')
45
+ continue;
46
+ if (typeof a.value === 'string') {
47
+ attrs[a.name] = a.value;
48
+ }
49
+ // Expression values (`prop={...}`) and null (boolean
50
+ // shorthand) are intentionally ignored here — they don't
51
+ // contribute to the "observed string values" we use to
52
+ // suggest dropdown options. The full attribute set per node
53
+ // lives in the editor's mdast node anyway.
54
+ }
55
+ usages.push({
56
+ name,
57
+ attrs,
58
+ kind: node.type === 'mdxJsxFlowElement' ? 'flow' : 'text',
59
+ });
60
+ }
61
+ });
62
+ return { filepath, imports, usages };
63
+ }
64
+ function isEsmNode(node) {
65
+ return node.type === 'mdxjsEsm';
66
+ }
67
+ function collectImports(esmNode, out) {
68
+ const estree = esmNode.data?.estree;
69
+ if (!estree?.body)
70
+ return;
71
+ for (const stmt of estree.body) {
72
+ if (stmt.type !== 'ImportDeclaration')
73
+ continue;
74
+ const source = stmt.source?.value;
75
+ if (typeof source !== 'string')
76
+ continue;
77
+ for (const spec of stmt.specifiers ?? []) {
78
+ const local = spec.local?.name;
79
+ if (typeof local !== 'string')
80
+ continue;
81
+ if (spec.type === 'ImportDefaultSpecifier') {
82
+ out[local] = { source, defaultExport: true, exportName: 'default' };
83
+ }
84
+ else if (spec.type === 'ImportSpecifier') {
85
+ const exportName = spec.imported?.type === 'Identifier'
86
+ ? spec.imported.name
87
+ : typeof spec.imported?.value === 'string'
88
+ ? spec.imported.value
89
+ : local;
90
+ out[local] = {
91
+ source,
92
+ defaultExport: false,
93
+ exportName: exportName ?? local,
94
+ ...(exportName && exportName !== local ? { aliasedFrom: exportName } : {}),
95
+ };
96
+ }
97
+ // ImportNamespaceSpecifier (`import * as X`) is rare in MDX and
98
+ // wouldn't produce a usable component descriptor on its own —
99
+ // we'd see `<X.Foo>` namespaced usages we don't model. Skip.
100
+ }
101
+ }
102
+ }
103
+ /** Depth-first walk; visits every node including the root. */
104
+ function walk(node, fn) {
105
+ fn(node);
106
+ if (Array.isArray(node.children)) {
107
+ for (const child of node.children) {
108
+ if (child && typeof child === 'object')
109
+ walk(child, fn);
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Host-provided override for an auto-discovered component descriptor.
3
+ *
4
+ * Lives in a sidecar JSON file inside the configured overrides folder
5
+ * (default `src/cms-overrides/`). One file per component, keyed by
6
+ * basename: `Card.cms.json` overrides the auto-discovered `Card`.
7
+ *
8
+ * Why JSON, not TS:
9
+ * - Zero tooling. The host doesn't need to import any types, set up
10
+ * build steps, or worry about which export shape we expect.
11
+ * - Static — we don't have to spin up Vite's SSR loader to read it.
12
+ * - Survives copy/paste between projects.
13
+ *
14
+ * The shape is intentionally a flat subset of `MdxJsxComponentDescriptor` —
15
+ * not the full union — because hosts only need to override the
16
+ * fields that come up in practice (insert menu hints, prop schema
17
+ * tweaks, defaults). New fields can be added later without breaking
18
+ * existing JSON files.
19
+ */
20
+ export interface CmsOverride {
21
+ /** Override the slash-menu / toolbar entry (label, category, icon, etc.). */
22
+ insert?: {
23
+ label?: string;
24
+ description?: string;
25
+ category?: string;
26
+ icon?: string;
27
+ keywords?: string[];
28
+ };
29
+ /** Override the insert-time starter attribute values. Merges over
30
+ * the auto-derived `defaults.attributes` so hosts can pin specific
31
+ * placeholder text or set a default for a prop the inference missed. */
32
+ defaults?: {
33
+ attributes?: Record<string, string | number | boolean>;
34
+ /** Raw MDX snippet parsed to mdast children at insert time. */
35
+ children?: string;
36
+ };
37
+ /** Per-prop overrides keyed by prop name. Fields here merge over
38
+ * the inferred prop schema (matched by `name`). Useful when:
39
+ * - The interface scan missed `required` (rare type pattern).
40
+ * - You want explicit help text or a friendly label.
41
+ * - You want a curated `options` list instead of usage-observed values. */
42
+ props?: Record<string, {
43
+ required?: boolean;
44
+ label?: string;
45
+ help?: string;
46
+ options?: Array<{
47
+ value: string;
48
+ label: string;
49
+ }>;
50
+ }>;
51
+ /** Override whether the component accepts children. Inferred to
52
+ * `true` by default; set to `false` for self-closing components. */
53
+ hasChildren?: boolean;
54
+ /** Override the flow/text kind. The flow-wins promotion in
55
+ * `merge-registry.ts` usually gets this right, but a host can
56
+ * pin the kind explicitly here if their fixtures don't exercise
57
+ * the block-context usage. */
58
+ kind?: 'flow' | 'text';
59
+ }
60
+ /**
61
+ * Read every `*.cms.json` file under `folder` (recursive) and return
62
+ * the parsed overrides keyed by basename (`Card.cms.json` → `Card`).
63
+ *
64
+ * Failures are skipped with a warning — a broken JSON file shouldn't
65
+ * take down the rest of the registry build. The folder being empty
66
+ * (or not existing) returns an empty map silently; that's the
67
+ * common zero-config case where the host hasn't added any
68
+ * overrides yet.
69
+ */
70
+ export declare function loadCmsOverrides(folder: string, projectRoot: string): Promise<Map<string, CmsOverride>>;
71
+ //# sourceMappingURL=scan-overrides.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan-overrides.d.ts","sourceRoot":"","sources":["../../../src/discovery/scan-overrides.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,WAAW,WAAW;IAC1B,6EAA6E;IAC7E,MAAM,CAAC,EAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;KACrB,CAAC;IACF;;4EAEwE;IACxE,QAAQ,CAAC,EAAE;QACT,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC;QACvD,+DAA+D;QAC/D,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,CAAC;IACF;;;;iFAI6E;IAC7E,KAAK,CAAC,EAAE,MAAM,CACZ,MAAM,EACN;QACE,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,KAAK,CAAC;YAAE,KAAK,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KACnD,CACF,CAAC;IACF;wEACoE;IACpE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;kCAG8B;IAC9B,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CACxB;AAED;;;;;;;;;GASG;AACH,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAiB7G"}