astrocms 0.3.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 +26 -2
  2. package/backend/config.ts +40 -1
  3. package/backend/github.ts +95 -0
  4. package/backend/parsers/components.ts +2 -2
  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 +29 -29
  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
@@ -94,7 +94,11 @@ AstroCMS reads an optional `astrocms.json` at the project root:
94
94
  "contentDir": "src/content",
95
95
  "contentConfig": "src/content.config.ts",
96
96
  "assetsDir": "src/assets",
97
- "componentsDir": "src/components"
97
+ "componentsDir": "src/components",
98
+ "git": {
99
+ "prBasedEdits": true,
100
+ "baseBranch": "main"
101
+ }
98
102
  }
99
103
  ```
100
104
 
@@ -106,6 +110,8 @@ All fields are optional.
106
110
  | `contentConfig` | Path to the Zod schema file | `src/content.config.ts` |
107
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)* |
108
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 |
109
115
 
110
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.
111
117
 
@@ -115,6 +121,7 @@ Any `astrocms.json` field can also be set via environment variable. Env values o
115
121
  | `ASTROCMS_CONTENT_CONFIG` | `contentConfig` |
116
122
  | `ASTROCMS_ASSETS_DIR` | `assetsDir` |
117
123
  | `ASTROCMS_COMPONENTS_DIR` | `componentsDir` |
124
+ | `ASTROCMS_PR_BASED_EDITS` | `git.prBasedEdits` (`1`/`true` enables, any other non-empty value disables) |
118
125
 
119
126
  Deployment-only environment variables:
120
127
 
@@ -125,13 +132,29 @@ Deployment-only environment variables:
125
132
  | `ASTROCMS_DEV_PORT` | Port the dev server listens on (used for the proxy and for probing). | `4321` when `ASTROCMS_DEV_CMD` is set |
126
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)* |
127
134
  | `GIT_REPO_URL` | Git repo URL (Docker mode) | *(auto-detected)* |
128
- | `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` |
129
136
  | `GIT_PAT` | GitHub Personal Access Token | *(none)* |
130
137
  | `GIT_USER_EMAIL` | Git commit email | `cms@astrocms.dev` |
131
138
  | `GIT_USER_NAME` | Git commit author | `AstroCMS` |
132
139
 
133
140
  A `.env` file at the project root is auto-loaded when running `astrocms` locally. Shell variables take precedence over `.env` values.
134
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
+
135
158
  ## Best practices
136
159
 
137
160
  ### Pass components to `<Content />` rather than importing them in MDX
@@ -262,6 +285,7 @@ With that, `http://localhost:4001/` serves the live site and `http://localhost:4
262
285
  2. **Repository access**: select **Only select repositories** and pick the repo you'll point `GIT_REPO_URL` at.
263
286
  3. **Repository permissions**:
264
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)
265
289
  - **Metadata**: `Read-only` (selected automatically)
266
290
  4. Click **Generate token** and copy the value, which is shown only once.
267
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
+ }
@@ -185,9 +185,9 @@ function resolveType(
185
185
  typeNode.type === 'TSTypeReference' &&
186
186
  isIdentifier(typeNode.typeName) &&
187
187
  typeNode.typeName.name === 'Array' &&
188
- typeNode.typeParameters?.params.length === 1
188
+ typeNode.typeArguments?.params.length === 1
189
189
  ) {
190
- elementType = typeNode.typeParameters.params[0]
190
+ elementType = typeNode.typeArguments.params[0]
191
191
  }
192
192
 
193
193
  if (elementType) {
@@ -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 } : {}),