astrocms 0.2.0 → 0.4.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 (44) hide show
  1. package/README.md +34 -12
  2. package/backend/config.ts +40 -1
  3. package/backend/github.ts +95 -0
  4. package/backend/parsers/components.ts +158 -53
  5. package/backend/routes/claude.ts +30 -1
  6. package/backend/routes/git.ts +518 -28
  7. package/dist/_cms/{dist-CNW8yujW.js → dist-B-U1HbZe.js} +1 -1
  8. package/dist/_cms/{dist-DyweOumh.js → dist-B5lxSXQA.js} +1 -1
  9. package/dist/_cms/{dist-BzcZNbxs.js → dist-BHEftLf_.js} +1 -1
  10. package/dist/_cms/{dist-D4bsfpFv.js → dist-B__wx9rF.js} +1 -1
  11. package/dist/_cms/{dist-7J3SMScN.js → dist-BozHj44A.js} +1 -1
  12. package/dist/_cms/{dist-3q3EeGvf.js → dist-CGHYW9fS.js} +1 -1
  13. package/dist/_cms/dist-CO-NIlqm.js +13 -0
  14. package/dist/_cms/{dist-CKTtGY0K.js → dist-CUglZnrz.js} +1 -1
  15. package/dist/_cms/{dist-Bi_DBs0h.js → dist-CaNy2dj8.js} +1 -1
  16. package/dist/_cms/{dist-DJjiXz-_.js → dist-CpXzxSa1.js} +1 -1
  17. package/dist/_cms/{dist-G1pI55d8.js → dist-D-YsnogG.js} +1 -1
  18. package/dist/_cms/{dist-BcBf0brb.js → dist-D7aKFs3B.js} +1 -1
  19. package/dist/_cms/{dist-8nvsczSZ.js → dist-DE3H-ivn.js} +1 -1
  20. package/dist/_cms/{dist-BCyZQxMf.js → dist-DNOejY2M.js} +1 -1
  21. package/dist/_cms/{dist-CL9duWcU.js → dist-LPIQyUY-.js} +1 -1
  22. package/dist/_cms/{dist-D3O5UDsl.js → dist-Sq2nMXd6.js} +1 -1
  23. package/dist/_cms/{dist-zip7q785.js → dist-XuBGExCX.js} +1 -1
  24. package/dist/_cms/dist-e0WTphLy.js +1 -0
  25. package/dist/_cms/forth-D6RzAl64.js +1 -0
  26. package/dist/_cms/index-8CiAna8Q.js +455 -0
  27. package/dist/_cms/index-BlPJDWp0.css +1 -0
  28. package/dist/_cms/javascript-Bu8mWwtz.js +1 -0
  29. package/dist/_cms/{lua-CiA1ziua.js → lua-DPCEkfD_.js} +1 -1
  30. package/dist/_cms/{nginx-BMaDbqW3.js → nginx-8H7HVH4w.js} +1 -1
  31. package/dist/_cms/{pug-Gsm0M45u.js → pug-3K-JMW4g.js} +1 -1
  32. package/dist/_cms/{sieve-BAxa3IjF.js → sieve-tLWDfEkZ.js} +1 -1
  33. package/dist/_cms/solr-B78wSQJQ.js +1 -0
  34. package/dist/_cms/{verilog-7LoJAqYT.js → verilog-CjI9Y6RI.js} +1 -1
  35. package/dist/index.html +3 -3
  36. package/package.json +32 -27
  37. package/dist/_cms/dist-Cvt9tHuf.js +0 -1
  38. package/dist/_cms/dist-IOAcKAnp.js +0 -13
  39. package/dist/_cms/forth-Cezjo90N.js +0 -1
  40. package/dist/_cms/index-CTA91OkF.js +0 -466
  41. package/dist/_cms/index-Dp1gAhoa.css +0 -1
  42. package/dist/_cms/javascript-DoL9Wb-Q.js +0 -1
  43. package/dist/_cms/solr-BBopId9w.js +0 -1
  44. package/patches/hast-util-to-estree+3.1.3.patch +0 -14
package/README.md CHANGED
@@ -4,19 +4,17 @@ A simple, database-free CMS for [Astro](https://astro.build) static websites wit
4
4
 
5
5
  AstroCMS edits your Markdown and MDX files directly, manages media assets, commits and pushes to your GitHub repository, and ships with an optional Claude Code integration for AI-assisted authoring.
6
6
 
7
- <picture>
8
- <source media="(prefers-color-scheme: dark)" srcset="./astrocms/docs/screenshots/editor-dark.png">
9
- <img alt="Editing a blog post in AstroCMS: file tree, frontmatter form generated from the collection schema, and visual MDX editor" src="https://raw.githubusercontent.com/lonestone/astrocms/main/docs/screenshots/editor-light.png">
10
- </picture>
7
+ Editing a blog post: the frontmatter form comes from your Zod schema, the body is real MDX.
11
8
 
12
- <p align="center"><em>Editing a blog post: the frontmatter form comes from your Zod schema, the body is real MDX.</em></p>
9
+ | Light | Dark |
10
+ | :---: | :---: |
11
+ | ![Editing a blog post in AstroCMS, light theme](https://raw.githubusercontent.com/lonestone/astrocms/main/docs/screenshots/editor-light.png) | ![Editing a blog post in AstroCMS, dark theme](https://raw.githubusercontent.com/lonestone/astrocms/main/docs/screenshots/editor-dark.png) |
13
12
 
14
- <picture>
15
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/lonestone/astrocms/main/docs/screenshots/agent-dark.png">
16
- <img alt="The AstroCMS agent panel writing a blog post, showing its tool calls and the generated entry in the editor" src="https://raw.githubusercontent.com/lonestone/astrocms/main/docs/screenshots/agent-light.png">
17
- </picture>
13
+ Asking the built-in Claude Code agent for a new post, with every tool call visible as it works.
18
14
 
19
- <p align="center"><em>Asking the built-in Claude Code agent for a new post, with every tool call visible as it works.</em></p>
15
+ | Light | Dark |
16
+ | :---: | :---: |
17
+ | ![The AstroCMS agent panel writing a blog post, light theme](https://raw.githubusercontent.com/lonestone/astrocms/main/docs/screenshots/agent-light.png) | ![The AstroCMS agent panel writing a blog post, dark theme](https://raw.githubusercontent.com/lonestone/astrocms/main/docs/screenshots/agent-dark.png) |
20
18
 
21
19
  ## Why AstroCMS
22
20
 
@@ -96,7 +94,11 @@ AstroCMS reads an optional `astrocms.json` at the project root:
96
94
  "contentDir": "src/content",
97
95
  "contentConfig": "src/content.config.ts",
98
96
  "assetsDir": "src/assets",
99
- "componentsDir": "src/components"
97
+ "componentsDir": "src/components",
98
+ "git": {
99
+ "prBasedEdits": true,
100
+ "baseBranch": "main"
101
+ }
100
102
  }
101
103
  ```
102
104
 
@@ -108,6 +110,8 @@ All fields are optional.
108
110
  | `contentConfig` | Path to the Zod schema file | `src/content.config.ts` |
109
111
  | `assetsDir` | Extra directory the media picker can browse and upload to, shown as an "Assets" tab. Uploads default to the folder of the content being edited. If unset, only `contentDir` is available. | *(content only)* |
110
112
  | `componentsDir` | Astro components available in the MDX editor. If unset, component discovery is skipped entirely. | *(components disabled)* |
113
+ | `git.prBasedEdits` | Enable [PR-based edits](#pr-based-edits): the CMS never commits or pushes to the base branch; edits happen on a working branch you create from the UI, and pushing opens a pull request. | `false` |
114
+ | `git.baseBranch` | The protected base branch that pull requests target. | `GIT_BRANCH`, or `main` if unset |
111
115
 
112
116
  Any `astrocms.json` field can also be set via environment variable. Env values override the JSON file when both are present. This is useful for Docker deployments where the config lives outside the container image.
113
117
 
@@ -117,6 +121,7 @@ Any `astrocms.json` field can also be set via environment variable. Env values o
117
121
  | `ASTROCMS_CONTENT_CONFIG` | `contentConfig` |
118
122
  | `ASTROCMS_ASSETS_DIR` | `assetsDir` |
119
123
  | `ASTROCMS_COMPONENTS_DIR` | `componentsDir` |
124
+ | `ASTROCMS_PR_BASED_EDITS` | `git.prBasedEdits` (`1`/`true` enables, any other non-empty value disables) |
120
125
 
121
126
  Deployment-only environment variables:
122
127
 
@@ -127,13 +132,29 @@ Deployment-only environment variables:
127
132
  | `ASTROCMS_DEV_PORT` | Port the dev server listens on (used for the proxy and for probing). | `4321` when `ASTROCMS_DEV_CMD` is set |
128
133
  | `ASTROCMS_INSTALL_CMD` | Override the project dependency install command in the container. By default the entrypoint auto-detects npm / pnpm / yarn / bun from the lockfile. | *(auto-detected)* |
129
134
  | `GIT_REPO_URL` | Git repo URL (Docker mode) | *(auto-detected)* |
130
- | `GIT_BRANCH` | Git branch | `main` |
135
+ | `GIT_BRANCH` | Git branch. With PR-based edits enabled this names the **base** branch (the protected one), not a working branch. | `main` |
131
136
  | `GIT_PAT` | GitHub Personal Access Token | *(none)* |
132
137
  | `GIT_USER_EMAIL` | Git commit email | `cms@astrocms.dev` |
133
138
  | `GIT_USER_NAME` | Git commit author | `AstroCMS` |
134
139
 
135
140
  A `.env` file at the project root is auto-loaded when running `astrocms` locally. Shell variables take precedence over `.env` values.
136
141
 
142
+ ### PR-based edits
143
+
144
+ With `git.prBasedEdits` enabled, the CMS never commits or pushes to the base branch (e.g. `main`). Instead:
145
+
146
+ 1. Create a working branch from the review UI ("Review changes" → **Create branch**). It always starts from the latest base.
147
+ 2. Commit as usual. Commits land on the working branch only, and nothing is pushed yet.
148
+ 3. Push from the review UI with a title: AstroCMS pushes the branch and opens a pull request against the base. If a PR is already open for the branch, pushing just updates it and no title is needed.
149
+
150
+ The review UI always shows the current branch, how far ahead of / behind the base it is (with an **Update from \<base\>** button that merges the base into the working branch), and a link to the open PR. While you are on the base branch, committing is disabled until you create a working branch.
151
+
152
+ Notes:
153
+
154
+ - The AI agent can commit but cannot push in this mode; pushing is always a deliberate action from the review UI.
155
+ - The token additionally needs **Pull requests: Read and write** (see [Generating a GitHub PAT](#generating-a-github-pat)).
156
+ - Requires a GitHub repository; other forges are not supported yet.
157
+
137
158
  ## Best practices
138
159
 
139
160
  ### Pass components to `<Content />` rather than importing them in MDX
@@ -264,6 +285,7 @@ With that, `http://localhost:4001/` serves the live site and `http://localhost:4
264
285
  2. **Repository access**: select **Only select repositories** and pick the repo you'll point `GIT_REPO_URL` at.
265
286
  3. **Repository permissions**:
266
287
  - **Contents**: `Read and write` (required for clone, pull, push)
288
+ - **Pull requests**: `Read and write` (only for [PR-based edits](#pr-based-edits): creating and listing pull requests)
267
289
  - **Metadata**: `Read-only` (selected automatically)
268
290
  4. Click **Generate token** and copy the value, which is shown only once.
269
291
  5. Paste it into `.env` as `GIT_PAT=github_pat_...`.
package/backend/config.ts CHANGED
@@ -2,11 +2,32 @@ import { readFile } from 'fs/promises'
2
2
  import { join } from 'path'
3
3
  import { ROOT_DIR } from './root.js'
4
4
 
5
+ export interface GitFlowConfig {
6
+ /** PR-based edits: the CMS works on a branch and opens pull requests. */
7
+ prBasedEdits: boolean
8
+ /** The protected base branch (main/master) that PRs target. */
9
+ baseBranch: string
10
+ }
11
+
5
12
  export interface AstroCmsConfig {
6
13
  contentDir: string
7
14
  contentConfig: string
8
15
  assetsDir?: string
9
16
  componentsDir?: string
17
+ /** Optional in astrocms.json; loadConfig fills it with defaults. */
18
+ git?: GitFlowConfig
19
+ }
20
+
21
+ /** Shape of the astrocms.json file; every key is optional. */
22
+ interface FileConfig {
23
+ contentDir?: string
24
+ contentConfig?: string
25
+ assetsDir?: string
26
+ componentsDir?: string
27
+ git?: {
28
+ prBasedEdits?: boolean
29
+ baseBranch?: string
30
+ }
10
31
  }
11
32
 
12
33
  const envOverrides = {
@@ -28,10 +49,16 @@ function pick(
28
49
  return fileValue ?? defaultValue
29
50
  }
30
51
 
52
+ /** '1'/'true' (any case) is true, any other non-empty value is false. */
53
+ function parseBoolEnv(value: string | undefined): boolean | undefined {
54
+ if (!value || value.length === 0) return undefined
55
+ return ['1', 'true'].includes(value.toLowerCase())
56
+ }
57
+
31
58
  export async function loadConfig(): Promise<AstroCmsConfig> {
32
59
  if (cached) return cached
33
60
 
34
- let fileConfig: Partial<AstroCmsConfig> = {}
61
+ let fileConfig: FileConfig = {}
35
62
  try {
36
63
  const raw = await readFile(join(ROOT_DIR, 'astrocms.json'), 'utf-8')
37
64
  fileConfig = JSON.parse(raw)
@@ -39,11 +66,23 @@ export async function loadConfig(): Promise<AstroCmsConfig> {
39
66
  // No config file, use defaults
40
67
  }
41
68
 
69
+ const gitFile = fileConfig.git ?? {}
70
+ // ASTROCMS_PR_BASED_EDITS flips the feature without touching the repo,
71
+ // e.g. in Docker deployments where astrocms.json lives in the clone.
72
+ const prEnv = parseBoolEnv(process.env.ASTROCMS_PR_BASED_EDITS)
73
+
42
74
  cached = {
43
75
  contentDir: pick('contentDir', fileConfig.contentDir, 'src/content')!,
44
76
  contentConfig: pick('contentConfig', fileConfig.contentConfig, 'src/content.config.ts')!,
45
77
  assetsDir: pick('assetsDir', fileConfig.assetsDir),
46
78
  componentsDir: pick('componentsDir', fileConfig.componentsDir),
79
+ git: {
80
+ prBasedEdits: prEnv ?? gitFile.prBasedEdits ?? false,
81
+ // An explicit baseBranch in the file wins over GIT_BRANCH. In PR mode
82
+ // GIT_BRANCH is a legacy fallback that names the base branch, not a
83
+ // working branch.
84
+ baseBranch: gitFile.baseBranch || process.env.GIT_BRANCH || 'main',
85
+ },
47
86
  }
48
87
 
49
88
  return cached
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Minimal GitHub REST client for PR-based edits. Only the two endpoints the
3
+ * CMS needs: list open pull requests and create one. Auth reuses GIT_PAT.
4
+ *
5
+ * The API base is injectable via ASTROCMS_GITHUB_API_BASE (default:
6
+ * https://api.github.com) so tests can point at a local mock server and
7
+ * GitHub Enterprise users can target their own host.
8
+ */
9
+
10
+ export interface GitHubPr {
11
+ number: number
12
+ title: string
13
+ url: string
14
+ }
15
+
16
+ function apiBase(): string {
17
+ return process.env.ASTROCMS_GITHUB_API_BASE || 'https://api.github.com'
18
+ }
19
+
20
+ function authHeaders(): Record<string, string> {
21
+ return {
22
+ authorization: `Bearer ${process.env.GIT_PAT ?? ''}`,
23
+ accept: 'application/vnd.github+json',
24
+ 'user-agent': 'astrocms',
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Extract { owner, repo } from a GitHub remote URL. Accepts the https form
30
+ * (with or without embedded credentials and .git suffix) and the ssh
31
+ * shorthand. Returns null for anything else (other forges are out of scope).
32
+ */
33
+ export function parseRepoFromUrl(
34
+ url: string
35
+ ): { owner: string; repo: string } | null {
36
+ let normalized = url.trim()
37
+ const ssh = normalized.match(/^git@github\.com:(.+)$/)
38
+ if (ssh) normalized = `https://github.com/${ssh[1]}`
39
+ const m = normalized.match(
40
+ /^https?:\/\/(?:[^@/]+@)?github\.com\/([^/]+)\/([^/?#]+)/i
41
+ )
42
+ if (!m) return null
43
+ const repo = m[2].replace(/\.git$/, '')
44
+ if (!m[1] || !repo) return null
45
+ return { owner: m[1], repo }
46
+ }
47
+
48
+ function mapPr(raw: any): GitHubPr {
49
+ return { number: raw.number, title: raw.title, url: raw.html_url }
50
+ }
51
+
52
+ async function githubError(res: Response): Promise<never> {
53
+ let message = `GitHub API ${res.status}`
54
+ try {
55
+ const data: any = await res.json()
56
+ if (data?.message) message += `: ${data.message}`
57
+ } catch {
58
+ // Non-JSON error body; the status code alone is still useful.
59
+ }
60
+ throw new Error(message)
61
+ }
62
+
63
+ /** The open PR for `owner:head`, or null when there is none. */
64
+ export async function findOpenPr(
65
+ owner: string,
66
+ repo: string,
67
+ head: string
68
+ ): Promise<GitHubPr | null> {
69
+ const url = `${apiBase()}/repos/${owner}/${repo}/pulls?state=open&head=${encodeURIComponent(
70
+ `${owner}:${head}`
71
+ )}`
72
+ const res = await fetch(url, { headers: authHeaders() })
73
+ if (!res.ok) return githubError(res)
74
+ const data = (await res.json()) as any[]
75
+ return Array.isArray(data) && data.length ? mapPr(data[0]) : null
76
+ }
77
+
78
+ export async function createPullRequest(
79
+ owner: string,
80
+ repo: string,
81
+ input: { title: string; body: string; head: string; base: string }
82
+ ): Promise<GitHubPr> {
83
+ const res = await fetch(`${apiBase()}/repos/${owner}/${repo}/pulls`, {
84
+ method: 'POST',
85
+ headers: authHeaders(),
86
+ body: JSON.stringify({
87
+ title: input.title,
88
+ body: input.body,
89
+ head: input.head,
90
+ base: input.base,
91
+ }),
92
+ })
93
+ if (!res.ok) return githubError(res)
94
+ return mapPr((await res.json()) as any)
95
+ }
@@ -1,6 +1,16 @@
1
1
  import { readdir, readFile } from 'fs/promises'
2
2
  import { join } from 'path'
3
- import * as ts from 'typescript'
3
+ import { parse } from '@babel/parser'
4
+ import type {
5
+ File,
6
+ Identifier,
7
+ Node,
8
+ Statement,
9
+ StringLiteral,
10
+ TSLiteralType,
11
+ TSPropertySignature,
12
+ TSTypeElement,
13
+ } from '@babel/types'
4
14
  import { ROOT_DIR } from '../root.js'
5
15
  import { loadConfig } from '../config.js'
6
16
  import { extractRawFrontmatter } from '../../shared/frontmatter.js'
@@ -19,90 +29,185 @@ export interface ComponentDescriptor {
19
29
  slots: string[]
20
30
  }
21
31
 
22
- // Parse interface Props from Astro frontmatter using the TypeScript compiler
23
- function parseProps(frontmatter: string): PropSchema[] {
24
- const sourceFile = ts.createSourceFile(
25
- 'props.ts',
26
- frontmatter,
27
- ts.ScriptTarget.Latest,
28
- true
29
- )
30
-
31
- const interfaces = new Map<string, ts.InterfaceDeclaration>()
32
- ts.forEachChild(sourceFile, (node) => {
33
- if (ts.isInterfaceDeclaration(node)) {
34
- interfaces.set(node.name.text, node)
35
- }
36
- })
32
+ // Parse the Props declaration of an Astro frontmatter using @babel/parser with
33
+ // the TypeScript plugin. Malformed input is caught and yields no props, so this
34
+ // function never throws on invalid frontmatter.
35
+ export function parseProps(frontmatter: string): PropSchema[] {
36
+ let file: File
37
+ try {
38
+ file = parse(frontmatter, {
39
+ sourceType: 'module',
40
+ plugins: ['typescript'],
41
+ errorRecovery: true,
42
+ })
43
+ } catch {
44
+ return []
45
+ }
46
+
47
+ const shapes: ShapeMap = new Map()
48
+ for (const statement of file.program.body) {
49
+ const shape = declaredShape(unwrapExport(statement))
50
+ if (shape) shapes.set(shape.name, shape.members)
51
+ }
52
+
53
+ const props = shapes.get('Props')
54
+ if (!props) return []
55
+ return parseMembers(props, shapes, new Set(['Props']))
56
+ }
57
+
58
+ /** Named object shapes declared in the frontmatter, by name. */
59
+ type ShapeMap = Map<string, TSTypeElement[]>
60
+
61
+ /**
62
+ * Members of a named object shape. Astro components declare their props
63
+ * either as `interface Props {}` or as `type Props = {}`; both are indexed
64
+ * so either form works for Props itself and for array element types.
65
+ */
66
+ function declaredShape(
67
+ node: Node | null
68
+ ): { name: string; members: TSTypeElement[] } | null {
69
+ if (node?.type === 'TSInterfaceDeclaration') {
70
+ return { name: node.id.name, members: node.body.body }
71
+ }
72
+ if (
73
+ node?.type === 'TSTypeAliasDeclaration' &&
74
+ node.typeAnnotation.type === 'TSTypeLiteral'
75
+ ) {
76
+ return { name: node.id.name, members: node.typeAnnotation.members }
77
+ }
78
+ return null
79
+ }
80
+
81
+ /**
82
+ * `export interface Props {}` and `export default interface Props {}` wrap the
83
+ * declaration in an export node, unlike a bare `interface Props {}`. Return the
84
+ * declaration in both cases so exported interfaces are indexed too.
85
+ */
86
+ function unwrapExport(statement: Statement): Node | null {
87
+ if (
88
+ statement.type === 'ExportNamedDeclaration' ||
89
+ statement.type === 'ExportDefaultDeclaration'
90
+ ) {
91
+ return statement.declaration ?? null
92
+ }
93
+ return statement
94
+ }
95
+
96
+ function isIdentifier(node: Node | null | undefined): node is Identifier {
97
+ return !!node && node.type === 'Identifier'
98
+ }
99
+
100
+ function isPropertySignature(node: Node): node is TSPropertySignature {
101
+ return node.type === 'TSPropertySignature'
102
+ }
37
103
 
38
- const propsInterface = interfaces.get('Props')
39
- if (!propsInterface) return []
40
- return parseMembers(propsInterface, interfaces)
104
+ /**
105
+ * Name of a property signature, or null when it has no static name a form can
106
+ * bind to (a computed key such as `[key]: string`).
107
+ */
108
+ function memberName(member: TSPropertySignature): string | null {
109
+ const key = member.key
110
+ if (!member.computed && key.type === 'Identifier') return key.name
111
+ if (key.type === 'StringLiteral') return key.value
112
+ if (key.type === 'NumericLiteral') return String(key.value)
113
+ return null
41
114
  }
42
115
 
116
+ function isStringLiteralType(node: Node): node is TSLiteralType {
117
+ return node.type === 'TSLiteralType' && node.literal.type === 'StringLiteral'
118
+ }
119
+
120
+ /**
121
+ * `expanding` holds the names of the shapes on the current expansion path, so
122
+ * a self-referencing element type such as `interface Item { kids: Item[] }`
123
+ * stops at a plain json field instead of recursing forever.
124
+ */
43
125
  function parseMembers(
44
- node: ts.InterfaceDeclaration,
45
- interfaces: Map<string, ts.InterfaceDeclaration>
126
+ members: TSTypeElement[],
127
+ shapes: ShapeMap,
128
+ expanding: Set<string>
46
129
  ): PropSchema[] {
47
- return node.members.filter(ts.isPropertySignature).map((member) => {
48
- const name = (member.name as ts.Identifier).text
49
- const optional = !!member.questionToken
50
- if (!member.type) return { name, type: 'string' as const, optional }
51
- return { name, optional, ...resolveType(member.type, interfaces) }
52
- })
130
+ const props: PropSchema[] = []
131
+ for (const member of members.filter(isPropertySignature)) {
132
+ const name = memberName(member)
133
+ if (name === null) continue
134
+ const optional = !!member.optional
135
+ if (member.typeAnnotation) {
136
+ props.push({
137
+ name,
138
+ optional,
139
+ ...resolveType(member.typeAnnotation.typeAnnotation, shapes, expanding),
140
+ })
141
+ } else {
142
+ props.push({ name, type: 'string', optional })
143
+ }
144
+ }
145
+ return props
53
146
  }
54
147
 
55
148
  function resolveType(
56
- typeNode: ts.TypeNode,
57
- interfaces: Map<string, ts.InterfaceDeclaration>
149
+ typeNode: Node,
150
+ shapes: ShapeMap,
151
+ expanding: Set<string>
58
152
  ): Omit<PropSchema, 'name'> {
153
+ // `readonly T[]` is the array type behind a type operator
154
+ if (typeNode.type === 'TSTypeOperator' && typeNode.operator === 'readonly') {
155
+ return resolveType(typeNode.typeAnnotation, shapes, expanding)
156
+ }
157
+
59
158
  // String literal union: 'a' | 'b' | 'c'
60
- if (ts.isUnionTypeNode(typeNode)) {
61
- const allStringLiterals = typeNode.types.every(
62
- (t) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal)
63
- )
159
+ if (typeNode.type === 'TSUnionType') {
160
+ const allStringLiterals = typeNode.types.every(isStringLiteralType)
64
161
  if (allStringLiterals) {
65
162
  const options = typeNode.types.map(
66
- (t) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text
163
+ (t) => ((t as TSLiteralType).literal as StringLiteral).value
67
164
  )
68
165
  return { type: 'select', options }
69
166
  }
70
167
  }
71
168
 
72
169
  if (
73
- ts.isTypeReferenceNode(typeNode) &&
74
- ts.isIdentifier(typeNode.typeName) &&
75
- typeNode.typeName.text === 'ImagePath'
170
+ typeNode.type === 'TSTypeReference' &&
171
+ isIdentifier(typeNode.typeName) &&
172
+ typeNode.typeName.name === 'ImagePath'
76
173
  ) {
77
174
  return { type: 'image' }
78
175
  }
79
176
 
80
- if (typeNode.kind === ts.SyntaxKind.StringKeyword) return { type: 'string' }
81
- if (typeNode.kind === ts.SyntaxKind.NumberKeyword) return { type: 'number' }
82
- if (typeNode.kind === ts.SyntaxKind.BooleanKeyword) return { type: 'boolean' }
177
+ if (typeNode.type === 'TSStringKeyword') return { type: 'string' }
178
+ if (typeNode.type === 'TSNumberKeyword') return { type: 'number' }
179
+ if (typeNode.type === 'TSBooleanKeyword') return { type: 'boolean' }
83
180
 
84
- let elementType: ts.TypeNode | undefined
85
- if (ts.isArrayTypeNode(typeNode)) {
181
+ let elementType: Node | undefined
182
+ if (typeNode.type === 'TSArrayType') {
86
183
  elementType = typeNode.elementType
87
184
  } else if (
88
- ts.isTypeReferenceNode(typeNode) &&
89
- ts.isIdentifier(typeNode.typeName) &&
90
- typeNode.typeName.text === 'Array' &&
91
- typeNode.typeArguments?.length === 1
185
+ typeNode.type === 'TSTypeReference' &&
186
+ isIdentifier(typeNode.typeName) &&
187
+ typeNode.typeName.name === 'Array' &&
188
+ typeNode.typeArguments?.params.length === 1
92
189
  ) {
93
- elementType = typeNode.typeArguments[0]
190
+ elementType = typeNode.typeArguments.params[0]
94
191
  }
95
192
 
96
193
  if (elementType) {
194
+ // Inline object elements: { label: string }[]
195
+ if (elementType.type === 'TSTypeLiteral') {
196
+ return {
197
+ type: 'json',
198
+ itemSchema: parseMembers(elementType.members, shapes, expanding),
199
+ }
200
+ }
97
201
  if (
98
- ts.isTypeReferenceNode(elementType) &&
99
- ts.isIdentifier(elementType.typeName)
202
+ elementType.type === 'TSTypeReference' &&
203
+ isIdentifier(elementType.typeName)
100
204
  ) {
101
- const refInterface = interfaces.get(elementType.typeName.text)
102
- if (refInterface) {
205
+ const name = elementType.typeName.name
206
+ const members = shapes.get(name)
207
+ if (members && !expanding.has(name)) {
103
208
  return {
104
209
  type: 'json',
105
- itemSchema: parseMembers(refInterface, interfaces),
210
+ itemSchema: parseMembers(members, shapes, new Set(expanding).add(name)),
106
211
  }
107
212
  }
108
213
  }
@@ -115,7 +220,7 @@ function resolveType(
115
220
  // Parse slot names from an Astro component source.
116
221
  // Detects <slot> tags in the template and Astro.slots.render/has calls in
117
222
  // the frontmatter. Empty string "" represents the default (unnamed) slot.
118
- function parseSlots(source: string): string[] {
223
+ export function parseSlots(source: string): string[] {
119
224
  const frontmatter = extractRawFrontmatter(source) ?? ''
120
225
  const parts = source.split('---')
121
226
  const template = parts.slice(2).join('---')
@@ -11,6 +11,7 @@ import {
11
11
  import { readFile } from 'fs/promises'
12
12
  import { join } from 'path'
13
13
  import { ROOT_DIR } from '../root.js'
14
+ import { loadConfig } from '../config.js'
14
15
 
15
16
  export const claudeRoutes = new Hono()
16
17
 
@@ -33,6 +34,34 @@ const allowedTools = [
33
34
  'Bash(cd * && git push*)',
34
35
  ]
35
36
 
37
+ // PR-based edits: the agent must never push. Pushing is a deliberate user
38
+ // action in the review UI that opens (or reuses) a pull request, so it is
39
+ // dropped here entirely — which also removes any path to pushing the base
40
+ // branch. The agent can still inspect, stage and commit on the working branch.
41
+ const prModeAllowedTools = [
42
+ 'Read',
43
+ 'Edit',
44
+ 'Write',
45
+ 'Grep',
46
+ 'Glob',
47
+ 'Agent',
48
+ 'TodoWrite',
49
+ 'NotebookEdit',
50
+ 'Bash(ls:*)',
51
+ 'Bash(find:*)',
52
+ 'Bash(mkdir:*)',
53
+ 'Bash(git status:*)',
54
+ 'Bash(git diff:*)',
55
+ 'Bash(git add:*)',
56
+ 'Bash(git commit:*)',
57
+ 'Bash(git log:*)',
58
+ ]
59
+
60
+ async function effectiveAllowedTools(): Promise<string[]> {
61
+ const config = await loadConfig()
62
+ return (config.git?.prBasedEdits ?? false) ? prModeAllowedTools : allowedTools
63
+ }
64
+
36
65
  // --- Permission request handling ---
37
66
 
38
67
  interface PendingPermission {
@@ -213,7 +242,7 @@ claudeRoutes.post('/chat', async (c) => {
213
242
 
214
243
  const result = streamText({
215
244
  model: claudeCode('sonnet', {
216
- allowedTools,
245
+ allowedTools: await effectiveAllowedTools(),
217
246
  canUseTool,
218
247
  cwd: ROOT_DIR,
219
248
  ...(sessionId ? { resume: sessionId } : {}),