astrocms 0.1.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.
- package/backend/auth.ts +54 -0
- package/backend/config.ts +50 -0
- package/backend/parsers/collections.ts +279 -0
- package/backend/parsers/components.ts +184 -0
- package/backend/parsers/frontmatter.ts +67 -0
- package/backend/parsers/glob.ts +57 -0
- package/backend/root.ts +7 -0
- package/backend/routes/auth.ts +42 -0
- package/backend/routes/claude.ts +401 -0
- package/backend/routes/collections.ts +9 -0
- package/backend/routes/components.ts +9 -0
- package/backend/routes/config.ts +7 -0
- package/backend/routes/file.ts +179 -0
- package/backend/routes/git.ts +458 -0
- package/backend/routes/tree.ts +100 -0
- package/backend/routes/upload.ts +33 -0
- package/backend/server.ts +173 -0
- package/backend/stubs/astro-content.ts +14 -0
- package/backend/stubs/astro-loaders.ts +17 -0
- package/bin/astrocms.js +66 -0
- package/dist/_cms/apl-B4CMkyY2.js +1 -0
- package/dist/_cms/asciiarmor-Df11BRmG.js +1 -0
- package/dist/_cms/asn1-EdZsLKOL.js +1 -0
- package/dist/_cms/asterisk-B-8jnY81.js +1 -0
- package/dist/_cms/brainfuck-C4LP7Hcl.js +1 -0
- package/dist/_cms/clike-B9uivgTg.js +1 -0
- package/dist/_cms/clojure-BMjYHr_A.js +1 -0
- package/dist/_cms/cmake-BQqOBYOt.js +1 -0
- package/dist/_cms/cobol-CWcv1MsR.js +1 -0
- package/dist/_cms/coffeescript-S37ZYGWr.js +1 -0
- package/dist/_cms/commonlisp-DBKNyK5s.js +1 -0
- package/dist/_cms/crystal-SjHAIU92.js +1 -0
- package/dist/_cms/css-BnMrqG3P.js +1 -0
- package/dist/_cms/cypher-C_CwsFkJ.js +1 -0
- package/dist/_cms/d-pRatUO7H.js +1 -0
- package/dist/_cms/diff-DbItnlRl.js +1 -0
- package/dist/_cms/dockerfile-BKs6k2Af.js +1 -0
- package/dist/_cms/dtd-DF_7sFjM.js +1 -0
- package/dist/_cms/dylan-DwRh75JA.js +1 -0
- package/dist/_cms/ebnf-CDyGwa7X.js +1 -0
- package/dist/_cms/ecl-Cabwm37j.js +1 -0
- package/dist/_cms/eiffel-CnydiIhH.js +1 -0
- package/dist/_cms/elm-vLlmbW-K.js +1 -0
- package/dist/_cms/erlang-BNw1qcRV.js +1 -0
- package/dist/_cms/factor-kuTfRLto.js +1 -0
- package/dist/_cms/fcl-Kvtd6kyn.js +1 -0
- package/dist/_cms/forth-Ffai-XNe.js +1 -0
- package/dist/_cms/fortran-DYz_wnZ1.js +1 -0
- package/dist/_cms/gas-Bneqetm1.js +1 -0
- package/dist/_cms/gherkin-heZmZLOM.js +1 -0
- package/dist/_cms/groovy-D9Dt4D0W.js +1 -0
- package/dist/_cms/haskell-Cw1EW3IL.js +1 -0
- package/dist/_cms/haxe-H-WmDvRZ.js +1 -0
- package/dist/_cms/http-DBlCnlav.js +1 -0
- package/dist/_cms/idl-BEugSyMb.js +1 -0
- package/dist/_cms/index-7Pc6H4sv.js +1 -0
- package/dist/_cms/index-893Rzaov.js +1 -0
- package/dist/_cms/index-9o-llXDY.js +508 -0
- package/dist/_cms/index-BdC39RoS.js +1 -0
- package/dist/_cms/index-BdChuKfE.js +7 -0
- package/dist/_cms/index-Bpfn86Of.js +1 -0
- package/dist/_cms/index-Bvz8WTJL.js +1 -0
- package/dist/_cms/index-C2vDuCBy.js +1 -0
- package/dist/_cms/index-C9zUJLja.css +1 -0
- package/dist/_cms/index-Cdwq3Ev5.js +1 -0
- package/dist/_cms/index-Ce64khPN.js +3 -0
- package/dist/_cms/index-CoIA6zkf.js +1 -0
- package/dist/_cms/index-DAAZmIPw.js +1 -0
- package/dist/_cms/index-DM5GktYD.js +1 -0
- package/dist/_cms/index-DQf5bTbe.js +1 -0
- package/dist/_cms/index-M4bKZFGh.js +1 -0
- package/dist/_cms/index-NwHME3i3.js +1 -0
- package/dist/_cms/index-enNvjuOI.js +2 -0
- package/dist/_cms/index-wHleENT0.js +1 -0
- package/dist/_cms/javascript-iXu5QeM3.js +1 -0
- package/dist/_cms/julia-DuME0IfC.js +1 -0
- package/dist/_cms/livescript-BwQOo05w.js +1 -0
- package/dist/_cms/lua-BgMRiT3U.js +1 -0
- package/dist/_cms/mathematica-DTrFuWx2.js +1 -0
- package/dist/_cms/mbox-CNhZ1qSd.js +1 -0
- package/dist/_cms/mirc-CjQqDB4T.js +1 -0
- package/dist/_cms/mllike-CXdrOF99.js +1 -0
- package/dist/_cms/modelica-Dc1JOy9r.js +1 -0
- package/dist/_cms/mscgen-BA5vi2Kp.js +1 -0
- package/dist/_cms/mumps-BT43cFF4.js +1 -0
- package/dist/_cms/nginx-DdIZxoE0.js +1 -0
- package/dist/_cms/nsis-LdVXkNf5.js +1 -0
- package/dist/_cms/ntriples-BfvgReVJ.js +1 -0
- package/dist/_cms/octave-Ck1zUtKM.js +1 -0
- package/dist/_cms/oz-BzwKVEFT.js +1 -0
- package/dist/_cms/pascal--L3eBynH.js +1 -0
- package/dist/_cms/perl-CdXCOZ3F.js +1 -0
- package/dist/_cms/pig-CevX1Tat.js +1 -0
- package/dist/_cms/powershell-CFHJl5sT.js +1 -0
- package/dist/_cms/properties-C78fOPTZ.js +1 -0
- package/dist/_cms/protobuf-ChK-085T.js +1 -0
- package/dist/_cms/pug-DeIclll2.js +1 -0
- package/dist/_cms/puppet-DMA9R1ak.js +1 -0
- package/dist/_cms/python-BuPzkPfP.js +1 -0
- package/dist/_cms/q-pXgVlZs6.js +1 -0
- package/dist/_cms/r-B6wPVr8A.js +1 -0
- package/dist/_cms/rpm-CTu-6PCP.js +1 -0
- package/dist/_cms/ruby-B2Rjki9n.js +1 -0
- package/dist/_cms/sas-B4kiWyti.js +1 -0
- package/dist/_cms/scheme-C41bIUwD.js +1 -0
- package/dist/_cms/shell-CjFT_Tl9.js +1 -0
- package/dist/_cms/sieve-C3Gn_uJK.js +1 -0
- package/dist/_cms/simple-mode-GW_nhZxv.js +1 -0
- package/dist/_cms/smalltalk-CnHTOXQT.js +1 -0
- package/dist/_cms/solr-DehyRSwq.js +1 -0
- package/dist/_cms/sparql-DkYu6x3z.js +1 -0
- package/dist/_cms/spreadsheet-BCZA_wO0.js +1 -0
- package/dist/_cms/sql-D0XecflT.js +1 -0
- package/dist/_cms/stex-C3f8Ysf7.js +1 -0
- package/dist/_cms/stylus-B533Al4x.js +1 -0
- package/dist/_cms/swift-BzpIVaGY.js +1 -0
- package/dist/_cms/tcl-DVfN8rqt.js +1 -0
- package/dist/_cms/textile-CnDTJFAw.js +1 -0
- package/dist/_cms/tiddlywiki-DO-Gjzrf.js +1 -0
- package/dist/_cms/tiki-DGYXhP31.js +1 -0
- package/dist/_cms/toml-Bm5Em-hy.js +1 -0
- package/dist/_cms/troff-wAsdV37c.js +1 -0
- package/dist/_cms/ttcn-CfJYG6tj.js +1 -0
- package/dist/_cms/ttcn-cfg-B9xdYoR4.js +1 -0
- package/dist/_cms/turtle-B1tBg_DP.js +1 -0
- package/dist/_cms/vb-CmGdzxic.js +1 -0
- package/dist/_cms/vbscript-BuJXcnF6.js +1 -0
- package/dist/_cms/velocity-D8B20fx6.js +1 -0
- package/dist/_cms/verilog-C6RDOZhf.js +1 -0
- package/dist/_cms/vhdl-lSbBsy5d.js +1 -0
- package/dist/_cms/webidl-ZXfAyPTL.js +1 -0
- package/dist/_cms/xquery-DzFWVndE.js +1 -0
- package/dist/_cms/yacas-BJ4BC0dw.js +1 -0
- package/dist/_cms/z80-Hz9HOZM7.js +1 -0
- package/dist/index.html +13 -0
- package/package.json +77 -0
- package/patches/hast-util-to-estree+3.1.3.patch +14 -0
package/backend/auth.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'crypto'
|
|
2
|
+
import type { Context, MiddlewareHandler } from 'hono'
|
|
3
|
+
import { getCookie } from 'hono/cookie'
|
|
4
|
+
|
|
5
|
+
export const AUTH_COOKIE = 'astrocms_auth'
|
|
6
|
+
|
|
7
|
+
const PASSWORD = process.env.ASTROCMS_PASSWORD ?? ''
|
|
8
|
+
const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000
|
|
9
|
+
|
|
10
|
+
export function isAuthRequired(): boolean {
|
|
11
|
+
return PASSWORD.length > 0
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function checkPassword(input: string): boolean {
|
|
15
|
+
return isAuthRequired() && input === PASSWORD
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function sign(payload: string): string {
|
|
19
|
+
return createHmac('sha256', PASSWORD).update(payload).digest('hex')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createToken(): string {
|
|
23
|
+
const payload = Date.now().toString(36)
|
|
24
|
+
return `${payload}.${sign(payload)}`
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function isValidToken(token: string | undefined): boolean {
|
|
28
|
+
if (!token) return false
|
|
29
|
+
const dot = token.indexOf('.')
|
|
30
|
+
if (dot < 0) return false
|
|
31
|
+
const payload = token.slice(0, dot)
|
|
32
|
+
const sig = token.slice(dot + 1)
|
|
33
|
+
const expected = sign(payload)
|
|
34
|
+
if (sig.length !== expected.length) return false
|
|
35
|
+
const a = Buffer.from(sig, 'hex')
|
|
36
|
+
const b = Buffer.from(expected, 'hex')
|
|
37
|
+
if (a.length !== b.length) return false
|
|
38
|
+
if (!timingSafeEqual(a, b)) return false
|
|
39
|
+
const ts = parseInt(payload, 36)
|
|
40
|
+
if (!Number.isFinite(ts)) return false
|
|
41
|
+
return Date.now() - ts <= MAX_AGE_MS
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function getSessionToken(c: Context): string | undefined {
|
|
45
|
+
return getCookie(c, AUTH_COOKIE)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
|
49
|
+
if (!isAuthRequired()) return next()
|
|
50
|
+
if (c.req.path.includes('/api/auth/')) return next()
|
|
51
|
+
const token = getSessionToken(c)
|
|
52
|
+
if (!isValidToken(token)) return c.json({ error: 'Unauthorized' }, 401)
|
|
53
|
+
return next()
|
|
54
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { readFile } from 'fs/promises'
|
|
2
|
+
import { join } from 'path'
|
|
3
|
+
import { ROOT_DIR } from './root.js'
|
|
4
|
+
|
|
5
|
+
export interface AstroCmsConfig {
|
|
6
|
+
contentDir: string
|
|
7
|
+
contentConfig: string
|
|
8
|
+
assetsDir?: string
|
|
9
|
+
componentsDir?: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const envOverrides = {
|
|
13
|
+
contentDir: 'ASTROCMS_CONTENT_DIR',
|
|
14
|
+
contentConfig: 'ASTROCMS_CONTENT_CONFIG',
|
|
15
|
+
assetsDir: 'ASTROCMS_ASSETS_DIR',
|
|
16
|
+
componentsDir: 'ASTROCMS_COMPONENTS_DIR',
|
|
17
|
+
} as const
|
|
18
|
+
|
|
19
|
+
let cached: AstroCmsConfig | null = null
|
|
20
|
+
|
|
21
|
+
function pick(
|
|
22
|
+
key: keyof typeof envOverrides,
|
|
23
|
+
fileValue: string | undefined,
|
|
24
|
+
defaultValue?: string,
|
|
25
|
+
): string | undefined {
|
|
26
|
+
const fromEnv = process.env[envOverrides[key]]
|
|
27
|
+
if (fromEnv && fromEnv.length > 0) return fromEnv
|
|
28
|
+
return fileValue ?? defaultValue
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function loadConfig(): Promise<AstroCmsConfig> {
|
|
32
|
+
if (cached) return cached
|
|
33
|
+
|
|
34
|
+
let fileConfig: Partial<AstroCmsConfig> = {}
|
|
35
|
+
try {
|
|
36
|
+
const raw = await readFile(join(ROOT_DIR, 'astrocms.json'), 'utf-8')
|
|
37
|
+
fileConfig = JSON.parse(raw)
|
|
38
|
+
} catch {
|
|
39
|
+
// No config file, use defaults
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
cached = {
|
|
43
|
+
contentDir: pick('contentDir', fileConfig.contentDir, 'src/content')!,
|
|
44
|
+
contentConfig: pick('contentConfig', fileConfig.contentConfig, 'src/content.config.ts')!,
|
|
45
|
+
assetsDir: pick('assetsDir', fileConfig.assetsDir),
|
|
46
|
+
componentsDir: pick('componentsDir', fileConfig.componentsDir),
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return cached
|
|
50
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { join, dirname, relative, resolve } from 'path'
|
|
2
|
+
import { fileURLToPath } from 'url'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import { createJiti } from 'jiti'
|
|
5
|
+
import { z } from 'zod'
|
|
6
|
+
import { ROOT_DIR } from '../root.js'
|
|
7
|
+
import { loadConfig } from '../config.js'
|
|
8
|
+
import { matchGlob } from './glob.js'
|
|
9
|
+
|
|
10
|
+
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
11
|
+
// Absolute path to AstroCMS's own zod so user configs that `import 'zod'`
|
|
12
|
+
// can resolve even when the user project doesn't depend on zod directly.
|
|
13
|
+
const ZOD_PATH = createRequire(import.meta.url).resolve('zod')
|
|
14
|
+
|
|
15
|
+
export interface FrontmatterFieldSchema {
|
|
16
|
+
name: string
|
|
17
|
+
type:
|
|
18
|
+
| 'string'
|
|
19
|
+
| 'number'
|
|
20
|
+
| 'boolean'
|
|
21
|
+
| 'select'
|
|
22
|
+
| 'json'
|
|
23
|
+
| 'image'
|
|
24
|
+
| 'date'
|
|
25
|
+
| 'string-array'
|
|
26
|
+
| 'object'
|
|
27
|
+
required?: boolean
|
|
28
|
+
options?: string[]
|
|
29
|
+
itemSchema?: FrontmatterFieldSchema[]
|
|
30
|
+
children?: FrontmatterFieldSchema[]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface CollectionInfo {
|
|
34
|
+
schema: FrontmatterFieldSchema[] | null
|
|
35
|
+
/** Kind of loader declared in content.config.ts. */
|
|
36
|
+
loader?: 'glob' | 'file'
|
|
37
|
+
/** Glob pattern from the loader (glob kind only). Relative to `base`. */
|
|
38
|
+
pattern?: string | string[]
|
|
39
|
+
/**
|
|
40
|
+
* Loader base, made relative to the CMS `contentDir`. For a typical Astro
|
|
41
|
+
* project this matches the collection folder name (e.g. `blog`). Undefined
|
|
42
|
+
* if the loader has no `base` or if `base` is outside the content dir.
|
|
43
|
+
*/
|
|
44
|
+
base?: string
|
|
45
|
+
/**
|
|
46
|
+
* For `file` loader: path to the single data file, relative to `contentDir`.
|
|
47
|
+
* The whole file holds a dict of entries keyed by id; the schema describes
|
|
48
|
+
* one entry, not the file as a whole.
|
|
49
|
+
*/
|
|
50
|
+
filePath?: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let cache:
|
|
54
|
+
| { collections: Record<string, CollectionInfo>; error?: string }
|
|
55
|
+
| undefined
|
|
56
|
+
|
|
57
|
+
/** Cached collections info (parsed once per server run). */
|
|
58
|
+
export async function getCollections(): Promise<{
|
|
59
|
+
collections: Record<string, CollectionInfo>
|
|
60
|
+
error?: string
|
|
61
|
+
}> {
|
|
62
|
+
if (!cache) {
|
|
63
|
+
try {
|
|
64
|
+
cache = { collections: await parseCollections() }
|
|
65
|
+
} catch (err) {
|
|
66
|
+
console.error('[astrocms] Failed to parse content.config.ts:', err)
|
|
67
|
+
cache = {
|
|
68
|
+
collections: {},
|
|
69
|
+
error: err instanceof Error ? err.message : String(err),
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return cache
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Return the collection a file belongs to based on path + glob pattern.
|
|
78
|
+
* Falls back to first-segment match when the collection has no loader info.
|
|
79
|
+
*/
|
|
80
|
+
export function resolveCollection(
|
|
81
|
+
filePath: string,
|
|
82
|
+
collections: Record<string, CollectionInfo>
|
|
83
|
+
): string | undefined {
|
|
84
|
+
for (const [name, info] of Object.entries(collections)) {
|
|
85
|
+
if (info.loader === 'file' && info.filePath) {
|
|
86
|
+
if (filePath === info.filePath) return name
|
|
87
|
+
} else if (info.base !== undefined && info.pattern !== undefined) {
|
|
88
|
+
const prefix = info.base ? info.base + '/' : ''
|
|
89
|
+
if (info.base && !filePath.startsWith(prefix)) continue
|
|
90
|
+
const rel = info.base ? filePath.slice(prefix.length) : filePath
|
|
91
|
+
if (matchGlob(rel, info.pattern)) return name
|
|
92
|
+
} else if (filePath.split('/')[0] === name) {
|
|
93
|
+
return name
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return undefined
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Sentinel symbol to identify image() fields
|
|
100
|
+
const IMAGE_MARKER = Symbol('image')
|
|
101
|
+
|
|
102
|
+
interface RawLoader {
|
|
103
|
+
__kind?: 'glob' | 'file'
|
|
104
|
+
pattern?: string | string[]
|
|
105
|
+
base?: string
|
|
106
|
+
path?: string
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Load content.config.ts at runtime using jiti, with mocked Astro modules.
|
|
111
|
+
* Then introspect the Zod schemas and the loader args to build CollectionInfo.
|
|
112
|
+
*/
|
|
113
|
+
async function parseCollections(): Promise<Record<string, CollectionInfo>> {
|
|
114
|
+
const config = await loadConfig()
|
|
115
|
+
const configPath = join(ROOT_DIR, config.contentConfig)
|
|
116
|
+
const contentDirAbs = resolve(ROOT_DIR, config.contentDir)
|
|
117
|
+
|
|
118
|
+
const jiti = createJiti(import.meta.url, {
|
|
119
|
+
moduleCache: false,
|
|
120
|
+
alias: {
|
|
121
|
+
'astro:content': join(__dirname, '../stubs/astro-content.ts'),
|
|
122
|
+
'astro/loaders': join(__dirname, '../stubs/astro-loaders.ts'),
|
|
123
|
+
'astro/zod': ZOD_PATH,
|
|
124
|
+
zod: ZOD_PATH,
|
|
125
|
+
},
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
const mod = (await jiti.import(configPath)) as {
|
|
129
|
+
collections: Record<string, { schema?: unknown; loader?: RawLoader }>
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const result: Record<string, CollectionInfo> = {}
|
|
133
|
+
|
|
134
|
+
for (const [name, collection] of Object.entries(mod.collections)) {
|
|
135
|
+
const info: CollectionInfo = { schema: null }
|
|
136
|
+
|
|
137
|
+
// Loader: capture kind and the relevant args (relative to contentDir).
|
|
138
|
+
const loader = collection.loader
|
|
139
|
+
if (loader && typeof loader === 'object') {
|
|
140
|
+
if (loader.__kind === 'glob' || loader.__kind === 'file') {
|
|
141
|
+
info.loader = loader.__kind
|
|
142
|
+
}
|
|
143
|
+
if (loader.__kind === 'glob') {
|
|
144
|
+
if (loader.pattern !== undefined) info.pattern = loader.pattern
|
|
145
|
+
if (typeof loader.base === 'string' && loader.base.length > 0) {
|
|
146
|
+
const abs = resolve(ROOT_DIR, loader.base)
|
|
147
|
+
const rel = relative(contentDirAbs, abs)
|
|
148
|
+
if (!rel.startsWith('..')) info.base = rel
|
|
149
|
+
}
|
|
150
|
+
} else if (loader.__kind === 'file' && typeof loader.path === 'string') {
|
|
151
|
+
const abs = resolve(ROOT_DIR, loader.path)
|
|
152
|
+
const rel = relative(contentDirAbs, abs)
|
|
153
|
+
if (!rel.startsWith('..')) info.filePath = rel
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Schema: z.object, or ({ image }) => z.object(...)
|
|
158
|
+
if (collection.schema) {
|
|
159
|
+
let zodSchema: z.ZodObject<z.ZodRawShape> | null = null
|
|
160
|
+
if (typeof collection.schema === 'function') {
|
|
161
|
+
zodSchema = (collection.schema as any)({
|
|
162
|
+
image: () => {
|
|
163
|
+
const s = z.string()
|
|
164
|
+
;(s as any)[IMAGE_MARKER] = true
|
|
165
|
+
return s
|
|
166
|
+
},
|
|
167
|
+
})
|
|
168
|
+
} else if (collection.schema instanceof z.ZodObject) {
|
|
169
|
+
zodSchema = collection.schema
|
|
170
|
+
}
|
|
171
|
+
if (zodSchema instanceof z.ZodObject) {
|
|
172
|
+
info.schema = parseZodShape(zodSchema)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
result[name] = info
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return result
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function parseZodShape(
|
|
183
|
+
schema: z.ZodObject<z.ZodRawShape>
|
|
184
|
+
): FrontmatterFieldSchema[] {
|
|
185
|
+
const fields: FrontmatterFieldSchema[] = []
|
|
186
|
+
const shape = schema.shape
|
|
187
|
+
|
|
188
|
+
for (const [name, fieldSchema] of Object.entries(shape)) {
|
|
189
|
+
const field = resolveZodField(name, fieldSchema as z.ZodTypeAny)
|
|
190
|
+
if (field) fields.push(field)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return fields
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function resolveZodField(
|
|
197
|
+
name: string,
|
|
198
|
+
schema: z.ZodTypeAny
|
|
199
|
+
): FrontmatterFieldSchema | undefined {
|
|
200
|
+
let required = true
|
|
201
|
+
let inner = schema
|
|
202
|
+
|
|
203
|
+
// Unwrap ZodOptional
|
|
204
|
+
if (inner instanceof z.ZodOptional) {
|
|
205
|
+
required = false
|
|
206
|
+
inner = inner.unwrap()
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Unwrap ZodDefault
|
|
210
|
+
if (inner instanceof z.ZodDefault) {
|
|
211
|
+
required = false
|
|
212
|
+
inner = inner._def.innerType
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Image sentinel
|
|
216
|
+
if ((inner as any)[IMAGE_MARKER]) {
|
|
217
|
+
return { name, type: 'image', required }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// z.string()
|
|
221
|
+
if (inner instanceof z.ZodString) {
|
|
222
|
+
return { name, type: 'string', required }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// z.number()
|
|
226
|
+
if (inner instanceof z.ZodNumber) {
|
|
227
|
+
return { name, type: 'number', required }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// z.boolean()
|
|
231
|
+
if (inner instanceof z.ZodBoolean) {
|
|
232
|
+
return { name, type: 'boolean', required }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// z.date() or z.coerce.date()
|
|
236
|
+
if (inner instanceof z.ZodDate) {
|
|
237
|
+
return { name, type: 'date', required }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// z.enum([...])
|
|
241
|
+
if (inner instanceof z.ZodEnum) {
|
|
242
|
+
return { name, type: 'select', required, options: inner.options }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// z.object(...)
|
|
246
|
+
if (inner instanceof z.ZodObject) {
|
|
247
|
+
return {
|
|
248
|
+
name,
|
|
249
|
+
type: 'object',
|
|
250
|
+
required,
|
|
251
|
+
children: parseZodShape(inner as z.ZodObject<z.ZodRawShape>),
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// z.array(...)
|
|
256
|
+
if (inner instanceof z.ZodArray) {
|
|
257
|
+
const element = unwrapOptional(inner.element)
|
|
258
|
+
if (element instanceof z.ZodString || element instanceof z.ZodUnion) {
|
|
259
|
+
return { name, type: 'string-array', required }
|
|
260
|
+
}
|
|
261
|
+
if (element instanceof z.ZodObject) {
|
|
262
|
+
return {
|
|
263
|
+
name,
|
|
264
|
+
type: 'json',
|
|
265
|
+
required,
|
|
266
|
+
itemSchema: parseZodShape(element as z.ZodObject<z.ZodRawShape>),
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return { name, type: 'json', required }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return { name, type: 'string', required }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function unwrapOptional(schema: z.ZodTypeAny): z.ZodTypeAny {
|
|
276
|
+
if (schema instanceof z.ZodOptional) return schema.unwrap()
|
|
277
|
+
if (schema instanceof z.ZodDefault) return schema._def.innerType
|
|
278
|
+
return schema
|
|
279
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { readdir, readFile } from 'fs/promises'
|
|
2
|
+
import { join } from 'path'
|
|
3
|
+
import * as ts from 'typescript'
|
|
4
|
+
import { ROOT_DIR } from '../root.js'
|
|
5
|
+
import { loadConfig } from '../config.js'
|
|
6
|
+
|
|
7
|
+
export interface PropSchema {
|
|
8
|
+
name: string
|
|
9
|
+
type: 'string' | 'number' | 'boolean' | 'select' | 'json' | 'image'
|
|
10
|
+
optional?: boolean
|
|
11
|
+
options?: string[]
|
|
12
|
+
itemSchema?: PropSchema[]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ComponentDescriptor {
|
|
16
|
+
name: string
|
|
17
|
+
props: PropSchema[]
|
|
18
|
+
slots: string[]
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Parse interface Props from Astro frontmatter using the TypeScript compiler
|
|
22
|
+
function parseProps(frontmatter: string): PropSchema[] {
|
|
23
|
+
const sourceFile = ts.createSourceFile(
|
|
24
|
+
'props.ts',
|
|
25
|
+
frontmatter,
|
|
26
|
+
ts.ScriptTarget.Latest,
|
|
27
|
+
true
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
const interfaces = new Map<string, ts.InterfaceDeclaration>()
|
|
31
|
+
ts.forEachChild(sourceFile, (node) => {
|
|
32
|
+
if (ts.isInterfaceDeclaration(node)) {
|
|
33
|
+
interfaces.set(node.name.text, node)
|
|
34
|
+
}
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
const propsInterface = interfaces.get('Props')
|
|
38
|
+
if (!propsInterface) return []
|
|
39
|
+
return parseMembers(propsInterface, interfaces)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function parseMembers(
|
|
43
|
+
node: ts.InterfaceDeclaration,
|
|
44
|
+
interfaces: Map<string, ts.InterfaceDeclaration>
|
|
45
|
+
): PropSchema[] {
|
|
46
|
+
return node.members.filter(ts.isPropertySignature).map((member) => {
|
|
47
|
+
const name = (member.name as ts.Identifier).text
|
|
48
|
+
const optional = !!member.questionToken
|
|
49
|
+
if (!member.type) return { name, type: 'string' as const, optional }
|
|
50
|
+
return { name, optional, ...resolveType(member.type, interfaces) }
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function resolveType(
|
|
55
|
+
typeNode: ts.TypeNode,
|
|
56
|
+
interfaces: Map<string, ts.InterfaceDeclaration>
|
|
57
|
+
): Omit<PropSchema, 'name'> {
|
|
58
|
+
// String literal union: 'a' | 'b' | 'c'
|
|
59
|
+
if (ts.isUnionTypeNode(typeNode)) {
|
|
60
|
+
const allStringLiterals = typeNode.types.every(
|
|
61
|
+
(t) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal)
|
|
62
|
+
)
|
|
63
|
+
if (allStringLiterals) {
|
|
64
|
+
const options = typeNode.types.map(
|
|
65
|
+
(t) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text
|
|
66
|
+
)
|
|
67
|
+
return { type: 'select', options }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (
|
|
72
|
+
ts.isTypeReferenceNode(typeNode) &&
|
|
73
|
+
ts.isIdentifier(typeNode.typeName) &&
|
|
74
|
+
typeNode.typeName.text === 'ImagePath'
|
|
75
|
+
) {
|
|
76
|
+
return { type: 'image' }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (typeNode.kind === ts.SyntaxKind.StringKeyword) return { type: 'string' }
|
|
80
|
+
if (typeNode.kind === ts.SyntaxKind.NumberKeyword) return { type: 'number' }
|
|
81
|
+
if (typeNode.kind === ts.SyntaxKind.BooleanKeyword) return { type: 'boolean' }
|
|
82
|
+
|
|
83
|
+
let elementType: ts.TypeNode | undefined
|
|
84
|
+
if (ts.isArrayTypeNode(typeNode)) {
|
|
85
|
+
elementType = typeNode.elementType
|
|
86
|
+
} else if (
|
|
87
|
+
ts.isTypeReferenceNode(typeNode) &&
|
|
88
|
+
ts.isIdentifier(typeNode.typeName) &&
|
|
89
|
+
typeNode.typeName.text === 'Array' &&
|
|
90
|
+
typeNode.typeArguments?.length === 1
|
|
91
|
+
) {
|
|
92
|
+
elementType = typeNode.typeArguments[0]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (elementType) {
|
|
96
|
+
if (
|
|
97
|
+
ts.isTypeReferenceNode(elementType) &&
|
|
98
|
+
ts.isIdentifier(elementType.typeName)
|
|
99
|
+
) {
|
|
100
|
+
const refInterface = interfaces.get(elementType.typeName.text)
|
|
101
|
+
if (refInterface) {
|
|
102
|
+
return {
|
|
103
|
+
type: 'json',
|
|
104
|
+
itemSchema: parseMembers(refInterface, interfaces),
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return { type: 'json' }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return { type: 'string' }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Parse slot names from an Astro component source.
|
|
115
|
+
// Detects <slot> tags in the template and Astro.slots.render/has calls in
|
|
116
|
+
// the frontmatter. Empty string "" represents the default (unnamed) slot.
|
|
117
|
+
function parseSlots(source: string): string[] {
|
|
118
|
+
const fmMatch = source.match(/^---\n([\s\S]*?)\n---/)
|
|
119
|
+
const frontmatter = fmMatch ? fmMatch[1] : ''
|
|
120
|
+
const parts = source.split('---')
|
|
121
|
+
const template = parts.slice(2).join('---')
|
|
122
|
+
|
|
123
|
+
const slots: string[] = []
|
|
124
|
+
const add = (name: string) => {
|
|
125
|
+
const normalized = name === 'default' ? '' : name
|
|
126
|
+
if (!slots.includes(normalized)) slots.push(normalized)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const tagRe = /<slot([\s/][^>]*)?>/g
|
|
130
|
+
let tagMatch
|
|
131
|
+
while ((tagMatch = tagRe.exec(template)) !== null) {
|
|
132
|
+
const rest = tagMatch[1] || ''
|
|
133
|
+
const nameMatch = rest.match(/name=["']([^"']+)["']/)
|
|
134
|
+
add(nameMatch ? nameMatch[1] : '')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const apiRe = /Astro\.slots\.(?:render|has)\s*\(\s*["']([^"']+)["']/g
|
|
138
|
+
let apiMatch
|
|
139
|
+
while ((apiMatch = apiRe.exec(frontmatter)) !== null) {
|
|
140
|
+
add(apiMatch[1])
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return slots
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function parseComponent(source: string): {
|
|
147
|
+
props: PropSchema[]
|
|
148
|
+
slots: string[]
|
|
149
|
+
} {
|
|
150
|
+
const fmMatch = source.match(/^---\n([\s\S]*?)\n---/)
|
|
151
|
+
const props = fmMatch ? parseProps(fmMatch[1]) : []
|
|
152
|
+
const slots = parseSlots(source)
|
|
153
|
+
return { props, slots }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Scan the project's componentsDir and return a descriptor per .astro file. */
|
|
157
|
+
export async function scanComponents(): Promise<ComponentDescriptor[]> {
|
|
158
|
+
const components: ComponentDescriptor[] = []
|
|
159
|
+
|
|
160
|
+
async function scan(dir: string) {
|
|
161
|
+
const entries = await readdir(dir, { withFileTypes: true })
|
|
162
|
+
for (const entry of entries) {
|
|
163
|
+
if (entry.isDirectory()) {
|
|
164
|
+
await scan(join(dir, entry.name))
|
|
165
|
+
} else if (entry.name.endsWith('.astro')) {
|
|
166
|
+
const name = entry.name.replace('.astro', '')
|
|
167
|
+
const source = await readFile(join(dir, entry.name), 'utf-8')
|
|
168
|
+
const { props, slots } = parseComponent(source)
|
|
169
|
+
components.push({ name, props, slots })
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const config = await loadConfig()
|
|
175
|
+
if (config.componentsDir) {
|
|
176
|
+
await scan(join(ROOT_DIR, config.componentsDir))
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Wildcard descriptor: catch-all for HTML tags and unknown MDX components
|
|
180
|
+
components.push({ name: '*', props: [], slots: [''] })
|
|
181
|
+
|
|
182
|
+
components.sort((a, b) => a.name.localeCompare(b.name))
|
|
183
|
+
return components
|
|
184
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { readFile, stat } from 'fs/promises'
|
|
2
|
+
import { extname } from 'path'
|
|
3
|
+
import YAML from 'yaml'
|
|
4
|
+
|
|
5
|
+
const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---/
|
|
6
|
+
|
|
7
|
+
const cache = new Map<
|
|
8
|
+
string,
|
|
9
|
+
{ mtimeMs: number; frontmatter: Record<string, unknown> }
|
|
10
|
+
>()
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Read & parse frontmatter for a supported content file.
|
|
14
|
+
* Cached in-memory; re-parsed only when the file's mtime changes.
|
|
15
|
+
*
|
|
16
|
+
* For .md/.mdx: parses the YAML frontmatter block.
|
|
17
|
+
* For .yaml/.yml/.json: parses the whole document as frontmatter.
|
|
18
|
+
*/
|
|
19
|
+
export async function getFrontmatter(
|
|
20
|
+
absPath: string
|
|
21
|
+
): Promise<Record<string, unknown>> {
|
|
22
|
+
let mtimeMs: number
|
|
23
|
+
try {
|
|
24
|
+
const s = await stat(absPath)
|
|
25
|
+
mtimeMs = s.mtimeMs
|
|
26
|
+
} catch {
|
|
27
|
+
return {}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const cached = cache.get(absPath)
|
|
31
|
+
if (cached && cached.mtimeMs === mtimeMs) return cached.frontmatter
|
|
32
|
+
|
|
33
|
+
const ext = extname(absPath)
|
|
34
|
+
let frontmatter: Record<string, unknown> = {}
|
|
35
|
+
try {
|
|
36
|
+
const content = await readFile(absPath, 'utf-8')
|
|
37
|
+
if (ext === '.md' || ext === '.mdx') {
|
|
38
|
+
const m = content.match(FRONTMATTER_RE)
|
|
39
|
+
if (m) {
|
|
40
|
+
const parsed = YAML.parse(m[1])
|
|
41
|
+
if (parsed && typeof parsed === 'object') frontmatter = parsed
|
|
42
|
+
}
|
|
43
|
+
} else if (ext === '.yaml' || ext === '.yml') {
|
|
44
|
+
const parsed = YAML.parse(content)
|
|
45
|
+
if (parsed && typeof parsed === 'object') frontmatter = parsed
|
|
46
|
+
} else if (ext === '.json') {
|
|
47
|
+
const parsed = JSON.parse(content)
|
|
48
|
+
if (parsed && typeof parsed === 'object') frontmatter = parsed
|
|
49
|
+
}
|
|
50
|
+
} catch {
|
|
51
|
+
frontmatter = {}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
cache.set(absPath, { mtimeMs, frontmatter })
|
|
55
|
+
return frontmatter
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function getByPath(obj: unknown, path: string): unknown {
|
|
59
|
+
if (!obj || typeof obj !== 'object') return undefined
|
|
60
|
+
const parts = path.split('.')
|
|
61
|
+
let cur: any = obj
|
|
62
|
+
for (const p of parts) {
|
|
63
|
+
if (cur == null || typeof cur !== 'object') return undefined
|
|
64
|
+
cur = cur[p]
|
|
65
|
+
}
|
|
66
|
+
return cur
|
|
67
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal glob-to-regex for Astro content patterns like:
|
|
3
|
+
* - `**\/*.mdx`
|
|
4
|
+
* - `**\/*.{md,mdx}`
|
|
5
|
+
* - `*.yaml`
|
|
6
|
+
* - `data/**\/*.json`
|
|
7
|
+
*
|
|
8
|
+
* Supports `**`, `*`, `?`, and `{a,b,...}` brace groups. No negation, no
|
|
9
|
+
* character classes — these aren't used in Astro `glob()` calls.
|
|
10
|
+
*/
|
|
11
|
+
function globToRegex(pattern: string): RegExp {
|
|
12
|
+
// Extract brace groups first so their commas don't get escaped.
|
|
13
|
+
const groups: string[] = []
|
|
14
|
+
let idx = 0
|
|
15
|
+
let p = pattern.replace(/\{([^{}]+)\}/g, (_, g) => {
|
|
16
|
+
groups.push(g)
|
|
17
|
+
return `\x00${idx++}\x00`
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
// Escape regex-special chars (brace placeholders and wildcards survive).
|
|
21
|
+
p = p.replace(/[.+^$|()\\[\]]/g, '\\$&')
|
|
22
|
+
|
|
23
|
+
// Translate wildcards, using distinctive placeholders for `**` first so
|
|
24
|
+
// `*` replacement doesn't eat them.
|
|
25
|
+
p = p
|
|
26
|
+
.replace(/\*\*\//g, '\x01')
|
|
27
|
+
.replace(/\*\*/g, '\x02')
|
|
28
|
+
.replace(/\*/g, '[^/]*')
|
|
29
|
+
.replace(/\?/g, '[^/]')
|
|
30
|
+
.replace(/\x01/g, '(?:.*/)?')
|
|
31
|
+
.replace(/\x02/g, '.*')
|
|
32
|
+
|
|
33
|
+
// Restore brace groups as alternations.
|
|
34
|
+
p = p.replace(/\x00(\d+)\x00/g, (_, i) => {
|
|
35
|
+
const alts = groups[Number(i)]
|
|
36
|
+
.split(',')
|
|
37
|
+
.map((s) => s.replace(/[.+^$|()\\[\]*?]/g, '\\$&'))
|
|
38
|
+
return `(?:${alts.join('|')})`
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
return new RegExp(`^${p}$`)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Match a file path (forward-slash separated, relative to the base) against
|
|
46
|
+
* one or more glob patterns.
|
|
47
|
+
*/
|
|
48
|
+
export function matchGlob(
|
|
49
|
+
filePath: string,
|
|
50
|
+
patterns: string | string[]
|
|
51
|
+
): boolean {
|
|
52
|
+
const list = Array.isArray(patterns) ? patterns : [patterns]
|
|
53
|
+
for (const pattern of list) {
|
|
54
|
+
if (globToRegex(pattern).test(filePath)) return true
|
|
55
|
+
}
|
|
56
|
+
return false
|
|
57
|
+
}
|
package/backend/root.ts
ADDED