@zabaca/zbc 0.4.0 → 0.6.1
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/package.json +5 -4
- package/src/commands/add.ts +143 -67
- package/src/commands/init.ts +2 -2
- package/src/utils/copy-template.ts +5 -0
- package/templates/CLAUDE.md +1 -1
- package/templates/apps/inbox/package.json +19 -0
- package/templates/apps/inbox/public/index.html +189 -0
- package/templates/apps/inbox/registry.json +9 -0
- package/templates/apps/inbox/tsconfig.json +17 -0
- package/templates/apps/inbox/worker/inbox-do.ts +141 -0
- package/templates/apps/inbox/worker/index.ts +210 -0
- package/templates/apps/inbox/wrangler.jsonc +35 -0
- package/templates/gitignore +2 -1
- package/templates/infra/modules/cloudflare/index.ts +183 -44
- package/templates/infra/modules/cloudflare/registry.json +1 -1
- package/templates/infra/modules/cloudflare-email/index.ts +512 -0
- package/templates/infra/modules/cloudflare-email/registry.json +12 -0
- package/templates/workflows/preview.yml +3 -2
- package/templates/infra/modules/nats-server/index.ts +0 -267
- package/templates/infra/modules/nats-server/registry.json +0 -12
- package/templates/infra/modules/vercel/index.ts +0 -358
- package/templates/infra/modules/vercel/registry.json +0 -15
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zabaca/zbc",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Zabaca stack CLI — scaffold and deploy infrastructure",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -10,9 +10,11 @@
|
|
|
10
10
|
"files": [
|
|
11
11
|
"bin",
|
|
12
12
|
"src",
|
|
13
|
-
"templates"
|
|
13
|
+
"templates",
|
|
14
|
+
"!templates/**/*.test.ts"
|
|
14
15
|
],
|
|
15
16
|
"scripts": {
|
|
17
|
+
"test": "bun test",
|
|
16
18
|
"publish:npm": "bun publish --access public"
|
|
17
19
|
},
|
|
18
20
|
"publishConfig": {
|
|
@@ -24,7 +26,6 @@
|
|
|
24
26
|
"yaml": "^2.8.3"
|
|
25
27
|
},
|
|
26
28
|
"devDependencies": {
|
|
27
|
-
"@types/bun": "^1.3.12"
|
|
28
|
-
"vercel": "^50.44.0"
|
|
29
|
+
"@types/bun": "^1.3.12"
|
|
29
30
|
}
|
|
30
31
|
}
|
package/src/commands/add.ts
CHANGED
|
@@ -3,7 +3,13 @@ import * as fs from 'node:fs/promises'
|
|
|
3
3
|
import { spawn } from 'node:child_process'
|
|
4
4
|
import { defineCommand } from 'citty'
|
|
5
5
|
import { findProjectRoot } from '../utils/find-project-root'
|
|
6
|
-
import {
|
|
6
|
+
import { loadConfig } from '../utils/load-config'
|
|
7
|
+
import {
|
|
8
|
+
bundledAppsCandidates,
|
|
9
|
+
bundledModulesCandidates,
|
|
10
|
+
copyTemplateDir,
|
|
11
|
+
copyTemplateFile,
|
|
12
|
+
} from '../utils/copy-template'
|
|
7
13
|
|
|
8
14
|
interface RegistryFile {
|
|
9
15
|
path: string
|
|
@@ -11,8 +17,15 @@ interface RegistryFile {
|
|
|
11
17
|
|
|
12
18
|
interface RegistryManifest {
|
|
13
19
|
name: string
|
|
20
|
+
/** 'module' (default): vendored into packages/infra/modules/. 'app': a full
|
|
21
|
+
* package scaffolded into targetDir (e.g. packages/inbox). */
|
|
22
|
+
kind?: 'module' | 'app'
|
|
14
23
|
description?: string
|
|
15
|
-
files
|
|
24
|
+
files?: RegistryFile[]
|
|
25
|
+
/** app only: where the package lands, relative to the project root. */
|
|
26
|
+
targetDir?: string
|
|
27
|
+
/** app only: infra modules this app depends on — auto-vendored first. */
|
|
28
|
+
modules?: string[]
|
|
16
29
|
dependencies?: Record<string, string>
|
|
17
30
|
devDependencies?: Record<string, string>
|
|
18
31
|
optionalDependencies?: Record<string, string>
|
|
@@ -22,17 +35,29 @@ interface RegistryManifest {
|
|
|
22
35
|
instructions?: string
|
|
23
36
|
}
|
|
24
37
|
|
|
25
|
-
async function
|
|
26
|
-
for (const candidate of bundledModulesCandidates()) {
|
|
38
|
+
async function resolveBundledDir(name: string): Promise<string> {
|
|
39
|
+
for (const candidate of [...bundledModulesCandidates(), ...bundledAppsCandidates()]) {
|
|
27
40
|
const dir = path.join(candidate, name)
|
|
28
41
|
const registry = path.join(dir, 'registry.json')
|
|
29
42
|
if (await Bun.file(registry).exists()) return dir
|
|
30
43
|
}
|
|
31
44
|
throw new Error(
|
|
32
|
-
`
|
|
45
|
+
`"${name}" not found in built-in registry. Available: cloudflare, cloudflare-email, turso, inbox.`,
|
|
33
46
|
)
|
|
34
47
|
}
|
|
35
48
|
|
|
49
|
+
function run(cwd: string, cmd: string, args: string[]): Promise<void> {
|
|
50
|
+
console.log(` ${cmd} ${args.join(' ')} (in ${path.relative(process.cwd(), cwd) || '.'})`)
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
const proc = spawn(cmd, args, { cwd, stdio: 'inherit' })
|
|
53
|
+
proc.on('close', (code) => {
|
|
54
|
+
if (code === 0) resolve()
|
|
55
|
+
else reject(new Error(`${cmd} ${args[0]} exited with code ${code}`))
|
|
56
|
+
})
|
|
57
|
+
proc.on('error', reject)
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
36
61
|
function bunAdd(
|
|
37
62
|
cwd: string,
|
|
38
63
|
deps: Record<string, string>,
|
|
@@ -40,39 +65,128 @@ function bunAdd(
|
|
|
40
65
|
): Promise<void> {
|
|
41
66
|
const entries = Object.entries(deps)
|
|
42
67
|
if (entries.length === 0) return Promise.resolve()
|
|
43
|
-
|
|
44
68
|
const args = ['add']
|
|
45
69
|
if (flag) args.push(flag)
|
|
46
|
-
for (const [name, version] of entries) {
|
|
47
|
-
|
|
70
|
+
for (const [name, version] of entries) args.push(`${name}@${version}`)
|
|
71
|
+
return run(cwd, 'bun', args)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function printPostInstall(registry: RegistryManifest): void {
|
|
75
|
+
console.log('')
|
|
76
|
+
console.log(`✓ ${registry.name} installed`)
|
|
77
|
+
console.log('')
|
|
78
|
+
if (registry.secrets && registry.secrets.length > 0) {
|
|
79
|
+
console.log('Required secrets:')
|
|
80
|
+
for (const s of registry.secrets) console.log(` - ${s}`)
|
|
81
|
+
}
|
|
82
|
+
if (registry.signupUrl) console.log(`Sign up: ${registry.signupUrl}`)
|
|
83
|
+
if (registry.tokenUrl) console.log(`Get token: ${registry.tokenUrl}`)
|
|
84
|
+
if (registry.instructions) {
|
|
85
|
+
console.log('')
|
|
86
|
+
console.log(registry.instructions)
|
|
48
87
|
}
|
|
88
|
+
}
|
|
49
89
|
|
|
50
|
-
|
|
90
|
+
/** Vendor a module into packages/infra/modules/<name>. Skips if installed. */
|
|
91
|
+
async function installModule(
|
|
92
|
+
moduleName: string,
|
|
93
|
+
infraDir: string,
|
|
94
|
+
opts: { quietSkip?: boolean } = {},
|
|
95
|
+
): Promise<RegistryManifest | null> {
|
|
96
|
+
const sourceDir = await resolveBundledDir(moduleName)
|
|
97
|
+
const destDir = path.join(infraDir, 'modules', moduleName)
|
|
98
|
+
|
|
99
|
+
if (await Bun.file(path.join(destDir, 'registry.json')).exists()) {
|
|
100
|
+
if (!opts.quietSkip) {
|
|
101
|
+
console.log(
|
|
102
|
+
`✓ ${moduleName} already installed at packages/infra/modules/${moduleName}/ — skipping`,
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
return null
|
|
106
|
+
}
|
|
51
107
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
})
|
|
58
|
-
|
|
108
|
+
const registry = (await Bun.file(
|
|
109
|
+
path.join(sourceDir, 'registry.json'),
|
|
110
|
+
).json()) as RegistryManifest
|
|
111
|
+
|
|
112
|
+
if (registry.kind === 'app') {
|
|
113
|
+
throw new Error(`"${moduleName}" is an app template, not an infra module`)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
console.log(`zbc add: ${moduleName}`)
|
|
117
|
+
|
|
118
|
+
await fs.mkdir(destDir, { recursive: true })
|
|
119
|
+
for (const f of registry.files ?? []) {
|
|
120
|
+
await copyTemplateFile(path.join(sourceDir, f.path), path.join(destDir, f.path))
|
|
121
|
+
}
|
|
122
|
+
// Always copy registry.json (used as install marker + future upgrade ref)
|
|
123
|
+
await copyTemplateFile(path.join(sourceDir, 'registry.json'), path.join(destDir, 'registry.json'))
|
|
124
|
+
|
|
125
|
+
if (registry.dependencies) await bunAdd(infraDir, registry.dependencies)
|
|
126
|
+
if (registry.devDependencies) await bunAdd(infraDir, registry.devDependencies, '--dev')
|
|
127
|
+
if (registry.optionalDependencies) {
|
|
128
|
+
await bunAdd(infraDir, registry.optionalDependencies, '--optional')
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return registry
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Scaffold an app template (a full package) into its targetDir. */
|
|
135
|
+
async function installApp(
|
|
136
|
+
registry: RegistryManifest,
|
|
137
|
+
sourceDir: string,
|
|
138
|
+
projectRoot: string,
|
|
139
|
+
infraDir: string,
|
|
140
|
+
): Promise<void> {
|
|
141
|
+
if (!registry.targetDir) {
|
|
142
|
+
throw new Error(`app template "${registry.name}" is missing targetDir in registry.json`)
|
|
143
|
+
}
|
|
144
|
+
const destDir = path.join(projectRoot, registry.targetDir)
|
|
145
|
+
|
|
146
|
+
if (await Bun.file(path.join(destDir, 'package.json')).exists()) {
|
|
147
|
+
console.log(`✓ ${registry.name} already scaffolded at ${registry.targetDir}/ — skipping`)
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
console.log(`zbc add: ${registry.name} (app)`)
|
|
152
|
+
|
|
153
|
+
// 1. Auto-vendor the infra modules this app depends on.
|
|
154
|
+
for (const dep of registry.modules ?? []) {
|
|
155
|
+
const depRegistry = await installModule(dep, infraDir, { quietSkip: true })
|
|
156
|
+
if (depRegistry) {
|
|
157
|
+
console.log(` ↳ vendored dependency module: ${dep}`)
|
|
158
|
+
printPostInstall(depRegistry)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// 2. Copy the package, substituting {{PROJECT_NAME}} (worker/bucket names,
|
|
163
|
+
// package name). registry.json stays in the CLI — it's not app code.
|
|
164
|
+
const { project } = await loadConfig(projectRoot)
|
|
165
|
+
await copyTemplateDir(sourceDir, destDir, {
|
|
166
|
+
vars: { PROJECT_NAME: project },
|
|
167
|
+
exclude: ['registry.json', 'node_modules'],
|
|
59
168
|
})
|
|
169
|
+
|
|
170
|
+
// 3. Install workspace deps (the app ships its own package.json).
|
|
171
|
+
await run(projectRoot, 'bun', ['install'])
|
|
172
|
+
|
|
173
|
+
printPostInstall(registry)
|
|
60
174
|
}
|
|
61
175
|
|
|
62
176
|
export const addCommand = defineCommand({
|
|
63
177
|
meta: {
|
|
64
178
|
name: 'add',
|
|
65
|
-
description: 'Vendor a built-in infra module into
|
|
179
|
+
description: 'Vendor a built-in infra module or app template into this project',
|
|
66
180
|
},
|
|
67
181
|
args: {
|
|
68
182
|
module: {
|
|
69
183
|
type: 'positional',
|
|
70
|
-
description: 'Module name (e.g. turso,
|
|
184
|
+
description: 'Module or app name (e.g. turso, cloudflare, cloudflare-email, inbox)',
|
|
71
185
|
required: true,
|
|
72
186
|
},
|
|
73
187
|
},
|
|
74
188
|
async run({ args }) {
|
|
75
|
-
const
|
|
189
|
+
const name = args.module
|
|
76
190
|
const projectRoot = await findProjectRoot()
|
|
77
191
|
const infraDir = path.join(projectRoot, 'packages/infra')
|
|
78
192
|
|
|
@@ -81,61 +195,23 @@ export const addCommand = defineCommand({
|
|
|
81
195
|
process.exit(1)
|
|
82
196
|
}
|
|
83
197
|
|
|
84
|
-
const sourceDir = await
|
|
85
|
-
const destDir = path.join(infraDir, 'modules', moduleName)
|
|
86
|
-
|
|
87
|
-
if (await Bun.file(path.join(destDir, 'registry.json')).exists()) {
|
|
88
|
-
console.log(
|
|
89
|
-
`✓ ${moduleName} already installed at packages/infra/modules/${moduleName}/ — skipping`,
|
|
90
|
-
)
|
|
91
|
-
return
|
|
92
|
-
}
|
|
93
|
-
|
|
198
|
+
const sourceDir = await resolveBundledDir(name)
|
|
94
199
|
const registry = (await Bun.file(
|
|
95
200
|
path.join(sourceDir, 'registry.json'),
|
|
96
201
|
).json()) as RegistryManifest
|
|
97
202
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
await fs.mkdir(destDir, { recursive: true })
|
|
102
|
-
for (const f of registry.files) {
|
|
103
|
-
await copyTemplateFile(path.join(sourceDir, f.path), path.join(destDir, f.path))
|
|
104
|
-
}
|
|
105
|
-
// Always copy registry.json (used as install marker + future upgrade ref)
|
|
106
|
-
await copyTemplateFile(
|
|
107
|
-
path.join(sourceDir, 'registry.json'),
|
|
108
|
-
path.join(destDir, 'registry.json'),
|
|
109
|
-
)
|
|
110
|
-
|
|
111
|
-
// Install deps in packages/infra
|
|
112
|
-
if (registry.dependencies) {
|
|
113
|
-
await bunAdd(infraDir, registry.dependencies)
|
|
114
|
-
}
|
|
115
|
-
if (registry.devDependencies) {
|
|
116
|
-
await bunAdd(infraDir, registry.devDependencies, '--dev')
|
|
117
|
-
}
|
|
118
|
-
if (registry.optionalDependencies) {
|
|
119
|
-
await bunAdd(infraDir, registry.optionalDependencies, '--optional')
|
|
203
|
+
if (registry.kind === 'app') {
|
|
204
|
+
await installApp(registry, sourceDir, projectRoot, infraDir)
|
|
205
|
+
return
|
|
120
206
|
}
|
|
121
207
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
console.log('')
|
|
126
|
-
if (registry.secrets && registry.secrets.length > 0) {
|
|
127
|
-
console.log('Required secrets:')
|
|
128
|
-
for (const s of registry.secrets) console.log(` - ${s}`)
|
|
129
|
-
}
|
|
130
|
-
if (registry.signupUrl) console.log(`Sign up: ${registry.signupUrl}`)
|
|
131
|
-
if (registry.tokenUrl) console.log(`Get token: ${registry.tokenUrl}`)
|
|
132
|
-
if (registry.instructions) {
|
|
208
|
+
const installed = await installModule(name, infraDir)
|
|
209
|
+
if (installed) {
|
|
210
|
+
printPostInstall(installed)
|
|
133
211
|
console.log('')
|
|
134
|
-
console.log(
|
|
212
|
+
console.log(
|
|
213
|
+
`Next: create an instance file under packages/infra/environments/<env>/ that imports from ../../modules/${name}.`,
|
|
214
|
+
)
|
|
135
215
|
}
|
|
136
|
-
console.log('')
|
|
137
|
-
console.log(
|
|
138
|
-
`Next: create an instance file under packages/infra/environments/<env>/ that imports from ../../modules/${moduleName}.`,
|
|
139
|
-
)
|
|
140
216
|
},
|
|
141
217
|
})
|
package/src/commands/init.ts
CHANGED
|
@@ -124,12 +124,12 @@ export const initCommand = defineCommand({
|
|
|
124
124
|
console.log('Next steps:')
|
|
125
125
|
console.log(' 1. bun install')
|
|
126
126
|
console.log(' 2. Add your age public keys to .sops.yaml')
|
|
127
|
-
console.log(' 3. bunx @zabaca/zbc add turso # or
|
|
127
|
+
console.log(' 3. bunx @zabaca/zbc add turso # or cloudflare')
|
|
128
128
|
} else {
|
|
129
129
|
console.log('Next steps:')
|
|
130
130
|
console.log(' 1. bun install # pick up packages/infra')
|
|
131
131
|
console.log(' 2. Add your age public keys to .sops.yaml')
|
|
132
|
-
console.log(' 3. bunx @zabaca/zbc add turso # or
|
|
132
|
+
console.log(' 3. bunx @zabaca/zbc add turso # or cloudflare')
|
|
133
133
|
}
|
|
134
134
|
},
|
|
135
135
|
})
|
|
@@ -80,3 +80,8 @@ export function templatesRoot(): string {
|
|
|
80
80
|
export function bundledModulesCandidates(): string[] {
|
|
81
81
|
return [path.resolve(import.meta.dir, '../../templates/infra/modules')]
|
|
82
82
|
}
|
|
83
|
+
|
|
84
|
+
/** Path to bundled app templates: packages/cli/templates/apps/. */
|
|
85
|
+
export function bundledAppsCandidates(): string[] {
|
|
86
|
+
return [path.resolve(import.meta.dir, '../../templates/apps')]
|
|
87
|
+
}
|
package/templates/CLAUDE.md
CHANGED
|
@@ -13,7 +13,7 @@ This project uses [zbc](https://github.com/Zabaca/zbc) for infrastructure scaffo
|
|
|
13
13
|
## Common commands
|
|
14
14
|
|
|
15
15
|
- `bun install` — install dependencies
|
|
16
|
-
- `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `
|
|
16
|
+
- `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`) or scaffold an app template (`inbox` — an agent-accessible email inbox; auto-vendors its module dependencies)
|
|
17
17
|
- `bunx @zabaca/zbc apply <env>` — apply infrastructure for an environment
|
|
18
18
|
- `bunx @zabaca/zbc destroy <env>` — tear down an ephemeral environment
|
|
19
19
|
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@{{PROJECT_NAME}}/inbox",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"dev": "wrangler dev",
|
|
8
|
+
"deploy": "wrangler deploy",
|
|
9
|
+
"typecheck": "tsc --noEmit"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"postal-mime": "^2.4.4"
|
|
13
|
+
},
|
|
14
|
+
"devDependencies": {
|
|
15
|
+
"@cloudflare/workers-types": "^4.20250101.0",
|
|
16
|
+
"typescript": "^5.7.0",
|
|
17
|
+
"wrangler": "^4.0.0"
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>{{PROJECT_NAME}} inbox</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root { color-scheme: light dark; --border: #8884; --accent: #4f46e5; }
|
|
9
|
+
* { box-sizing: border-box; }
|
|
10
|
+
body { margin: 0; font: 14px/1.5 ui-sans-serif, system-ui, sans-serif; }
|
|
11
|
+
header { display: flex; align-items: center; gap: 12px; padding: 10px 16px; border-bottom: 1px solid var(--border); }
|
|
12
|
+
header h1 { font-size: 15px; margin: 0; }
|
|
13
|
+
header .spacer { flex: 1; }
|
|
14
|
+
button { font: inherit; padding: 4px 12px; border: 1px solid var(--border); border-radius: 6px; background: transparent; cursor: pointer; }
|
|
15
|
+
button.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
|
|
16
|
+
main { display: grid; grid-template-columns: minmax(260px, 380px) 1fr; height: calc(100vh - 45px); }
|
|
17
|
+
#list { overflow-y: auto; border-right: 1px solid var(--border); }
|
|
18
|
+
.msg { padding: 10px 14px; border-bottom: 1px solid var(--border); cursor: pointer; }
|
|
19
|
+
.msg:hover, .msg.active { background: #8881; }
|
|
20
|
+
.msg .from { font-weight: 600; }
|
|
21
|
+
.msg .subject { display: block; }
|
|
22
|
+
.msg .snippet { opacity: .6; font-size: 12.5px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
|
23
|
+
.msg .meta { font-size: 12px; opacity: .55; }
|
|
24
|
+
#reader { overflow-y: auto; padding: 18px 22px; }
|
|
25
|
+
#reader .headers { border-bottom: 1px solid var(--border); padding-bottom: 10px; margin-bottom: 14px; }
|
|
26
|
+
#reader h2 { margin: 0 0 6px; font-size: 18px; }
|
|
27
|
+
#reader pre { white-space: pre-wrap; word-wrap: break-word; font: inherit; }
|
|
28
|
+
#reader iframe { width: 100%; min-height: 60vh; border: 1px solid var(--border); border-radius: 6px; background: #fff; }
|
|
29
|
+
dialog { border: 1px solid var(--border); border-radius: 10px; padding: 20px; min-width: min(560px, 92vw); }
|
|
30
|
+
dialog::backdrop { background: #0006; }
|
|
31
|
+
form.compose { display: grid; gap: 8px; }
|
|
32
|
+
form.compose input, form.compose textarea { font: inherit; padding: 6px 8px; border: 1px solid var(--border); border-radius: 6px; background: transparent; width: 100%; }
|
|
33
|
+
form.compose textarea { min-height: 160px; }
|
|
34
|
+
.row { display: flex; gap: 8px; justify-content: flex-end; }
|
|
35
|
+
.empty { padding: 40px; text-align: center; opacity: .5; }
|
|
36
|
+
#loadmore { margin: 12px; width: calc(100% - 24px); }
|
|
37
|
+
</style>
|
|
38
|
+
</head>
|
|
39
|
+
<body>
|
|
40
|
+
<header>
|
|
41
|
+
<h1>{{PROJECT_NAME}} inbox</h1>
|
|
42
|
+
<span id="addr" style="opacity:.5">agent inbox</span>
|
|
43
|
+
<span class="spacer"></span>
|
|
44
|
+
<button id="compose-btn" class="primary">Compose</button>
|
|
45
|
+
<button id="refresh-btn">Refresh</button>
|
|
46
|
+
<button id="token-btn">Token</button>
|
|
47
|
+
</header>
|
|
48
|
+
<main>
|
|
49
|
+
<div id="list"><div class="empty">Loading…</div></div>
|
|
50
|
+
<div id="reader"><div class="empty">Select a message</div></div>
|
|
51
|
+
</main>
|
|
52
|
+
|
|
53
|
+
<dialog id="compose">
|
|
54
|
+
<form class="compose" id="compose-form" method="dialog">
|
|
55
|
+
<input name="to" placeholder="To" required>
|
|
56
|
+
<input name="from" placeholder="From (optional — worker default applies)">
|
|
57
|
+
<input name="subject" placeholder="Subject" required>
|
|
58
|
+
<input name="inReplyTo" placeholder="In-Reply-To Message-ID (optional)">
|
|
59
|
+
<textarea name="text" placeholder="Message" required></textarea>
|
|
60
|
+
<div class="row">
|
|
61
|
+
<button type="button" id="compose-cancel">Cancel</button>
|
|
62
|
+
<button type="submit" class="primary">Send</button>
|
|
63
|
+
</div>
|
|
64
|
+
</form>
|
|
65
|
+
</dialog>
|
|
66
|
+
|
|
67
|
+
<script>
|
|
68
|
+
const $ = (s) => document.querySelector(s)
|
|
69
|
+
let token = localStorage.getItem('inbox_token') || ''
|
|
70
|
+
let cursor = null
|
|
71
|
+
let current = null
|
|
72
|
+
|
|
73
|
+
function askToken(force) {
|
|
74
|
+
if (token && !force) return token
|
|
75
|
+
const t = prompt('Inbox API token (stored in localStorage):', token)
|
|
76
|
+
if (t !== null) { token = t.trim(); localStorage.setItem('inbox_token', token) }
|
|
77
|
+
return token
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function api(path, opts = {}) {
|
|
81
|
+
const res = await fetch(path, {
|
|
82
|
+
...opts,
|
|
83
|
+
headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json', ...(opts.headers || {}) },
|
|
84
|
+
})
|
|
85
|
+
if (res.status === 401) { askToken(true); throw new Error('unauthorized — token updated, retry') }
|
|
86
|
+
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || res.statusText)
|
|
87
|
+
return res.json()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]))
|
|
91
|
+
const fmtDate = (d) => { const t = new Date(d); return isNaN(t) ? '' : t.toLocaleString() }
|
|
92
|
+
|
|
93
|
+
async function loadList(append) {
|
|
94
|
+
askToken(false)
|
|
95
|
+
try {
|
|
96
|
+
const q = append && cursor ? '?cursor=' + encodeURIComponent(cursor) : ''
|
|
97
|
+
const data = await api('/api/messages' + q)
|
|
98
|
+
cursor = data.nextCursor
|
|
99
|
+
const html = data.messages.map((m) => `
|
|
100
|
+
<div class="msg" data-id="${esc(m.id)}">
|
|
101
|
+
<span class="from">${esc(m.from_addr)}</span>
|
|
102
|
+
<span class="meta"> → ${esc(m.to_addr)} · ${esc(fmtDate(m.created_at))}</span>
|
|
103
|
+
<span class="subject">${esc(m.subject) || '(no subject)'}</span>
|
|
104
|
+
<span class="snippet">${esc(m.snippet)}</span>
|
|
105
|
+
</div>`).join('')
|
|
106
|
+
const more = cursor ? '<button id="loadmore">Load more</button>' : ''
|
|
107
|
+
if (append) { $('#loadmore')?.remove(); $('#list').insertAdjacentHTML('beforeend', html + more) }
|
|
108
|
+
else $('#list').innerHTML = (html || '<div class="empty">No messages yet</div>') + more
|
|
109
|
+
} catch (e) {
|
|
110
|
+
$('#list').innerHTML = '<div class="empty">' + esc(e.message) + '</div>'
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function openMessage(id) {
|
|
115
|
+
document.querySelectorAll('.msg').forEach((el) => el.classList.toggle('active', el.dataset.id === id))
|
|
116
|
+
$('#reader').innerHTML = '<div class="empty">Loading…</div>'
|
|
117
|
+
try {
|
|
118
|
+
const m = await api('/api/messages/' + encodeURIComponent(id))
|
|
119
|
+
current = m
|
|
120
|
+
const body = m.html_body
|
|
121
|
+
? `<iframe sandbox="" referrerpolicy="no-referrer"></iframe>`
|
|
122
|
+
: `<pre>${esc(m.text_body)}</pre>`
|
|
123
|
+
$('#reader').innerHTML = `
|
|
124
|
+
<div class="headers">
|
|
125
|
+
<h2>${esc(m.subject) || '(no subject)'}</h2>
|
|
126
|
+
<div><b>${esc(m.from_addr)}</b> → ${esc(m.to_addr)} · ${esc(fmtDate(m.date))}</div>
|
|
127
|
+
<div class="row" style="justify-content:flex-start; margin-top:8px">
|
|
128
|
+
<button id="reply-btn">Reply</button>
|
|
129
|
+
<a href="/api/messages/${esc(m.id)}/raw"><button type="button" id="raw-btn">Raw</button></a>
|
|
130
|
+
<button id="delete-btn">Delete</button>
|
|
131
|
+
</div>
|
|
132
|
+
</div>${body}`
|
|
133
|
+
const frame = $('#reader iframe')
|
|
134
|
+
if (frame) frame.srcdoc = m.html_body
|
|
135
|
+
$('#reply-btn').onclick = () => openCompose({
|
|
136
|
+
to: m.from_addr, from: m.to_addr,
|
|
137
|
+
subject: (m.subject || '').startsWith('Re:') ? m.subject : 'Re: ' + (m.subject || ''),
|
|
138
|
+
inReplyTo: m.message_id,
|
|
139
|
+
})
|
|
140
|
+
$('#raw-btn').onclick = async (e) => {
|
|
141
|
+
e.preventDefault()
|
|
142
|
+
const res = await fetch('/api/messages/' + m.id + '/raw', { headers: { authorization: 'Bearer ' + token } })
|
|
143
|
+
const blob = await res.blob()
|
|
144
|
+
const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(blob), download: m.id + '.eml' })
|
|
145
|
+
a.click()
|
|
146
|
+
}
|
|
147
|
+
$('#delete-btn').onclick = async () => {
|
|
148
|
+
if (!confirm('Delete this message?')) return
|
|
149
|
+
await api('/api/messages/' + m.id, { method: 'DELETE' })
|
|
150
|
+
$('#reader').innerHTML = '<div class="empty">Deleted</div>'
|
|
151
|
+
loadList()
|
|
152
|
+
}
|
|
153
|
+
} catch (e) {
|
|
154
|
+
$('#reader').innerHTML = '<div class="empty">' + esc(e.message) + '</div>'
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function openCompose(prefill = {}) {
|
|
159
|
+
const f = $('#compose-form')
|
|
160
|
+
f.reset()
|
|
161
|
+
for (const [k, v] of Object.entries(prefill)) if (f[k]) f[k].value = v || ''
|
|
162
|
+
$('#compose').showModal()
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
$('#compose-form').addEventListener('submit', async (e) => {
|
|
166
|
+
e.preventDefault()
|
|
167
|
+
const f = e.target
|
|
168
|
+
const body = Object.fromEntries(['to', 'from', 'subject', 'inReplyTo', 'text']
|
|
169
|
+
.map((k) => [k, f[k].value.trim()]).filter(([, v]) => v))
|
|
170
|
+
try {
|
|
171
|
+
await api('/api/send', { method: 'POST', body: JSON.stringify(body) })
|
|
172
|
+
$('#compose').close()
|
|
173
|
+
} catch (err) { alert('Send failed: ' + err.message) }
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
$('#compose-cancel').onclick = () => $('#compose').close()
|
|
177
|
+
$('#compose-btn').onclick = () => openCompose()
|
|
178
|
+
$('#refresh-btn').onclick = () => loadList()
|
|
179
|
+
$('#token-btn').onclick = () => { askToken(true); loadList() }
|
|
180
|
+
$('#list').addEventListener('click', (e) => {
|
|
181
|
+
if (e.target.id === 'loadmore') return loadList(true)
|
|
182
|
+
const msg = e.target.closest('.msg')
|
|
183
|
+
if (msg) openMessage(msg.dataset.id)
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
loadList()
|
|
187
|
+
</script>
|
|
188
|
+
</body>
|
|
189
|
+
</html>
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "inbox",
|
|
3
|
+
"kind": "app",
|
|
4
|
+
"description": "Agent-accessible email inbox: a Cloudflare Worker that receives routed mail (SQLite DO metadata + R2 raw MIME), sends via Email Sending, and exposes a bearer-authed JSON API plus a minimal web UI",
|
|
5
|
+
"targetDir": "packages/inbox",
|
|
6
|
+
"modules": ["cloudflare-email"],
|
|
7
|
+
"secrets": ["INBOX_TOKEN", "CLOUDFLARE_API_TOKEN"],
|
|
8
|
+
"instructions": "1) Edit packages/inbox/wrangler.jsonc: set DEFAULT_FROM to an address on your email domain (e.g. inbox@mail.example.com).\n2) Create two instance files in packages/infra/environments/<env>/:\n\n // inbox.ts\n import { cloudflareModule } from '../../modules/cloudflare'\n export default cloudflareModule.instance({\n name: 'inbox',\n config: { workdir: 'packages/inbox', accountId: '<account id>', workerSecrets: ['INBOX_TOKEN'] },\n })\n\n // email.ts\n import { cloudflareEmailModule } from '../../modules/cloudflare-email'\n import inbox from './inbox'\n export default cloudflareEmailModule.instance({\n name: 'email',\n imports: [inbox],\n config: {\n accountId: '<account id>', zoneId: '<zone id>', domain: 'mail.<your-domain>',\n enableSending: true, enableRouting: true,\n catchAll: { action: 'worker', workerName: { from: 'inbox', output: 'workerName' } },\n },\n })\n\n3) Add INBOX_TOKEN (any long random string, e.g. `openssl rand -hex 32`) to secrets.yaml, and make sure CLOUDFLARE_API_TOKEN has the scopes the cloudflare-email module documents.\n4) `zbc apply <env>`. Create the R2 bucket if wrangler asks for it (`wrangler r2 bucket create <project>-inbox-raw`).\nNote: Cloudflare holds newly onboarded sending domains in a preview sandbox (verified recipients only) for a short period after DNS validates; arbitrary-recipient sending starts working once it drops."
|
|
9
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "esnext",
|
|
4
|
+
"module": "esnext",
|
|
5
|
+
"moduleResolution": "bundler",
|
|
6
|
+
"strict": true,
|
|
7
|
+
"esModuleInterop": true,
|
|
8
|
+
"skipLibCheck": true,
|
|
9
|
+
"forceConsistentCasingInFileNames": true,
|
|
10
|
+
"resolveJsonModule": true,
|
|
11
|
+
"noUncheckedIndexedAccess": true,
|
|
12
|
+
"noEmit": true,
|
|
13
|
+
"lib": ["esnext"],
|
|
14
|
+
"types": ["@cloudflare/workers-types"]
|
|
15
|
+
},
|
|
16
|
+
"include": ["worker"]
|
|
17
|
+
}
|