@hakubase/cli 0.0.0-stage → 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/README.md +103 -2
- package/astro.js +16 -0
- package/bin/hakubase.js +10 -0
- package/lib/commands.js +281 -0
- package/lib/project.js +112 -0
- package/lib/types.js +100 -0
- package/lib/zip.js +105 -0
- package/package.json +33 -4
- package/vite.js +69 -0
package/README.md
CHANGED
|
@@ -1,3 +1,104 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hakubase/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The command line of Hakubase **code sites**: link a project to its site, generate the types of the CMS collections, develop against real data, deploy.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm i -D @hakubase/cli
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Link
|
|
10
|
+
|
|
11
|
+
Create a **development key** in the site's settings (tab *Settings*, *Keys*), then:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npx hakubase link https://noesis.hakubase.com <site-id> --key hb_…
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
It writes `.hakubase/project.json` (addresses only, safe to commit) and puts the key in `.env.local` as `HAKUBASE_KEY`, adding `.env.local` to `.gitignore` when the project has one. The key is never printed whole.
|
|
18
|
+
|
|
19
|
+
The key is read from `--key`, then the `HAKUBASE_KEY` variable, then `.env.local`.
|
|
20
|
+
|
|
21
|
+
## Types
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npx hakubase types # writes hakubase.d.ts
|
|
25
|
+
npx hakubase types --out src/hakubase.d.ts
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`hb.cms.list('articles')` from `@hakubase/sdk` then returns items whose `values` carry the collection's fields. Run it again when the collections change.
|
|
29
|
+
|
|
30
|
+
## Develop
|
|
31
|
+
|
|
32
|
+
The plugin forwards `/_data`, `/_fn`, `/_m` and `/_hb` from the dev server to the real site and adds the key on the way: the browser sees one origin, the key never reaches the bundle.
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
// vite.config.js
|
|
36
|
+
import { defineConfig } from 'vite'
|
|
37
|
+
import hakubase from '@hakubase/cli/vite'
|
|
38
|
+
|
|
39
|
+
export default defineConfig({ plugins: [hakubase()] })
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
// astro.config.mjs
|
|
44
|
+
import { defineConfig } from 'astro/config'
|
|
45
|
+
import hakubase from '@hakubase/cli/astro'
|
|
46
|
+
|
|
47
|
+
export default defineConfig({ integrations: [hakubase()] })
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
With the development key the CMS also returns drafts, and form submits are tests: same answers, no lead. `hb.init({ mode: 'live' })` makes them real.
|
|
51
|
+
|
|
52
|
+
## Deploy
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
npm run build
|
|
56
|
+
npx hakubase deploy # dist, build or out
|
|
57
|
+
npx hakubase deploy dist --publish --message "New home"
|
|
58
|
+
npx hakubase publish 12 # put an uploaded version online
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`deploy` zips the folder (up to 32 MB), adds `hakubase.json` from the project root if the folder does not have one, and uploads it as a new version. Without `--publish` the version stays in preview and the command prints its preview link; with it, the version goes online.
|
|
62
|
+
|
|
63
|
+
Deploying needs a **publishing key**.
|
|
64
|
+
|
|
65
|
+
## GitHub
|
|
66
|
+
|
|
67
|
+
Put the publishing key in the repository secrets as `HAKUBASE_KEY` and add `.github/workflows/hakubase.yml`:
|
|
68
|
+
|
|
69
|
+
```yaml
|
|
70
|
+
name: Hakubase
|
|
71
|
+
on: { push: { branches: [main] } }
|
|
72
|
+
jobs:
|
|
73
|
+
deploy:
|
|
74
|
+
runs-on: ubuntu-latest
|
|
75
|
+
steps:
|
|
76
|
+
- uses: actions/checkout@v4
|
|
77
|
+
- uses: actions/setup-node@v4
|
|
78
|
+
with: { node-version: 22 }
|
|
79
|
+
- run: npm ci
|
|
80
|
+
- run: npm run build
|
|
81
|
+
- run: npx @hakubase/cli deploy --publish
|
|
82
|
+
env:
|
|
83
|
+
HAKUBASE_KEY: "${{ secrets.HAKUBASE_KEY }}"
|
|
84
|
+
HAKUBASE_API: "https://noesis.hakubase.com"
|
|
85
|
+
HAKUBASE_SITE: "<site-id>"
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`HAKUBASE_API` and `HAKUBASE_SITE` stand in for `.hakubase/project.json` and win over it. On GitHub the version records the commit and its message.
|
|
89
|
+
|
|
90
|
+
## Commands
|
|
91
|
+
|
|
92
|
+
| Command | What it does |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `hakubase link <workspace-url> <site-id> [--key hb_…]` | Links the folder to a code site |
|
|
95
|
+
| `hakubase types [--out file]` | Writes the TypeScript types of the collections |
|
|
96
|
+
| `hakubase deploy [dir] [--publish] [--message m] [--commit sha] [--via cli\|github]` | Uploads the built folder as a new version |
|
|
97
|
+
| `hakubase publish <number>` | Puts a version online |
|
|
98
|
+
| `hakubase help` | Shows the usage |
|
|
99
|
+
|
|
100
|
+
On an error the command prints the server's answer and exits with code 1.
|
|
101
|
+
|
|
102
|
+
## License
|
|
103
|
+
|
|
104
|
+
MIT
|
package/astro.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// The Astro integration of @hakubase/cli: the Vite plugin, wired in.
|
|
2
|
+
|
|
3
|
+
import hakubaseVite from './vite.js'
|
|
4
|
+
|
|
5
|
+
export default function hakubase(options = {}) {
|
|
6
|
+
return {
|
|
7
|
+
name: '@hakubase/cli',
|
|
8
|
+
hooks: {
|
|
9
|
+
'astro:config:setup': ({ updateConfig }) => {
|
|
10
|
+
updateConfig({ vite: { plugins: [hakubaseVite(options)] } })
|
|
11
|
+
},
|
|
12
|
+
},
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export { hakubase }
|
package/bin/hakubase.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { main } from '../lib/commands.js'
|
|
3
|
+
|
|
4
|
+
main(process.argv.slice(2)).then(
|
|
5
|
+
(code) => { process.exitCode = code },
|
|
6
|
+
(error) => {
|
|
7
|
+
process.stderr.write(`${error && error.stack ? error.stack : error}\n`)
|
|
8
|
+
process.exitCode = 1
|
|
9
|
+
},
|
|
10
|
+
)
|
package/lib/commands.js
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
// The commands of `hakubase`. Each one returns its exit code; output
|
|
2
|
+
// goes through `io` so the tests can read it.
|
|
3
|
+
|
|
4
|
+
import { execFileSync } from 'node:child_process'
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
ensureGitignored, findRoot, maskKey, readProject, resolveKey, writeEnvKey, writeProject,
|
|
10
|
+
} from './project.js'
|
|
11
|
+
import { generateTypes } from './types.js'
|
|
12
|
+
import { createZip } from './zip.js'
|
|
13
|
+
|
|
14
|
+
export const MAX_ZIP = 32 * 1024 * 1024
|
|
15
|
+
export const BUILD_DIRS = ['dist', 'build', 'out']
|
|
16
|
+
// What an operating system leaves in a folder, never part of a site.
|
|
17
|
+
const JUNK = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini'])
|
|
18
|
+
|
|
19
|
+
export class CliError extends Error {}
|
|
20
|
+
|
|
21
|
+
export const USAGE = `Usage: hakubase <command> [options]
|
|
22
|
+
|
|
23
|
+
Commands:
|
|
24
|
+
link <workspace-url> <site-id> [--key hb_…] Link this folder to a code site
|
|
25
|
+
types [--out hakubase.d.ts] Write the TypeScript types of the collections
|
|
26
|
+
deploy [dir] [--publish] [--message m] Upload the built folder as a new version
|
|
27
|
+
[--commit sha] [--via cli|github] (dir: dist, build or out by default)
|
|
28
|
+
publish <number> Put a version online
|
|
29
|
+
help Show this help
|
|
30
|
+
|
|
31
|
+
The key comes from --key, the HAKUBASE_KEY variable or .env.local.
|
|
32
|
+
Without .hakubase/project.json (in CI), HAKUBASE_API and HAKUBASE_SITE say where to deploy.
|
|
33
|
+
`
|
|
34
|
+
|
|
35
|
+
export function parseArgs(argv) {
|
|
36
|
+
const positional = []
|
|
37
|
+
const flags = {}
|
|
38
|
+
for (let i = 0; i < argv.length; i++) {
|
|
39
|
+
const arg = argv[i]
|
|
40
|
+
if (arg === '--') {
|
|
41
|
+
positional.push(...argv.slice(i + 1))
|
|
42
|
+
break
|
|
43
|
+
}
|
|
44
|
+
if (arg.startsWith('--')) {
|
|
45
|
+
const eq = arg.indexOf('=')
|
|
46
|
+
if (eq > 0) {
|
|
47
|
+
flags[arg.slice(2, eq)] = arg.slice(eq + 1)
|
|
48
|
+
} else {
|
|
49
|
+
const name = arg.slice(2)
|
|
50
|
+
const next = argv[i + 1]
|
|
51
|
+
if (['publish', 'help'].includes(name) || next === undefined || next.startsWith('--')) {
|
|
52
|
+
flags[name] = true
|
|
53
|
+
} else {
|
|
54
|
+
flags[name] = next
|
|
55
|
+
i++
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
} else if (arg === '-h') {
|
|
59
|
+
flags.help = true
|
|
60
|
+
} else {
|
|
61
|
+
positional.push(arg)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return { positional, flags }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** `noesis.hakubase.com`, `https://noesis.hakubase.com/app` → `https://noesis.hakubase.com`. */
|
|
68
|
+
export function workspaceOrigin(value) {
|
|
69
|
+
const raw = String(value || '').trim()
|
|
70
|
+
if (!raw) throw new CliError('Say the address of the workspace, e.g. https://noesis.hakubase.com.')
|
|
71
|
+
try {
|
|
72
|
+
return new URL(/^https?:\/\//i.test(raw) ? raw : `https://${raw}`).origin
|
|
73
|
+
} catch {
|
|
74
|
+
throw new CliError(`${raw} is not an address.`)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function detailOf(body, status) {
|
|
79
|
+
if (body && typeof body === 'object') {
|
|
80
|
+
const detail = body.detail ?? body.error ?? body.message
|
|
81
|
+
if (Array.isArray(detail)) {
|
|
82
|
+
return detail.map((d) => (d && d.msg ? `${(d.loc || []).slice(1).join('.')}: ${d.msg}` : String(d))).join('; ')
|
|
83
|
+
}
|
|
84
|
+
if (detail) return String(detail)
|
|
85
|
+
}
|
|
86
|
+
if (typeof body === 'string' && body.trim()) return body.trim().slice(0, 300)
|
|
87
|
+
return `HTTP ${status}`
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function request(ctx, method, url, { key, body } = {}) {
|
|
91
|
+
const headers = { accept: 'application/json', 'user-agent': 'hakubase-cli' }
|
|
92
|
+
if (key) headers.authorization = `Bearer ${key}`
|
|
93
|
+
let response
|
|
94
|
+
try {
|
|
95
|
+
response = await ctx.fetch(url, { method, headers, body })
|
|
96
|
+
} catch (error) {
|
|
97
|
+
throw new CliError(`Could not reach ${new URL(url).origin}: ${error.cause?.message || error.message}`)
|
|
98
|
+
}
|
|
99
|
+
const text = await response.text()
|
|
100
|
+
let parsed = text
|
|
101
|
+
try {
|
|
102
|
+
parsed = text ? JSON.parse(text) : null
|
|
103
|
+
} catch {
|
|
104
|
+
parsed = text
|
|
105
|
+
}
|
|
106
|
+
if (!response.ok) throw new CliError(detailOf(parsed, response.status))
|
|
107
|
+
return parsed
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Where to talk and with which key: project.json, overridden by HAKUBASE_API and HAKUBASE_SITE. */
|
|
111
|
+
export function target(ctx, flags) {
|
|
112
|
+
const root = findRoot(ctx.cwd) || ctx.cwd
|
|
113
|
+
const project = readProject(root) || {}
|
|
114
|
+
const api = ctx.env.HAKUBASE_API ? workspaceOrigin(ctx.env.HAKUBASE_API) : project.api
|
|
115
|
+
const site = ctx.env.HAKUBASE_SITE || project.site_id
|
|
116
|
+
if (!api || !site) {
|
|
117
|
+
throw new CliError('This folder is not linked: run `hakubase link <workspace-url> <site-id>`, or set HAKUBASE_API and HAKUBASE_SITE.')
|
|
118
|
+
}
|
|
119
|
+
const key = resolveKey(root, typeof flags.key === 'string' ? flags.key : '', ctx.env)
|
|
120
|
+
if (!key) throw new CliError('No key: pass --key, set HAKUBASE_KEY or run `hakubase link` with --key.')
|
|
121
|
+
return { root, api, site, key, siteUrl: project.site_url || '' }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export async function link(ctx, positional, flags) {
|
|
125
|
+
const [workspace, siteId] = positional
|
|
126
|
+
if (!workspace || !siteId) throw new CliError('Usage: hakubase link <workspace-url> <site-id> [--key hb_…]')
|
|
127
|
+
const api = workspaceOrigin(workspace)
|
|
128
|
+
const root = ctx.cwd
|
|
129
|
+
const given = typeof flags.key === 'string' ? flags.key : ''
|
|
130
|
+
const key = resolveKey(root, given, ctx.env)
|
|
131
|
+
if (!key) throw new CliError('No key: pass --key hb_… (a development or publishing key of this site).')
|
|
132
|
+
const info = await request(ctx, 'GET', `${api}/api/sites/${encodeURIComponent(siteId)}/code-site`, { key })
|
|
133
|
+
writeProject(root, { api, site_id: info.id || siteId, site_url: info.url || '' })
|
|
134
|
+
if (given) writeEnvKey(root, given)
|
|
135
|
+
ensureGitignored(root)
|
|
136
|
+
const where = given ? ` Key ${maskKey(given)} in .env.local.` : ''
|
|
137
|
+
ctx.out(`Linked to ${info.name || siteId} (${info.url || api}).${where}`)
|
|
138
|
+
return 0
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export async function types(ctx, positional, flags) {
|
|
142
|
+
const t = target(ctx, flags)
|
|
143
|
+
const collections = await request(ctx, 'GET', `${t.api}/api/sites/${encodeURIComponent(t.site)}/collections`, { key: t.key })
|
|
144
|
+
const out = path.resolve(ctx.cwd, typeof flags.out === 'string' ? flags.out : 'hakubase.d.ts')
|
|
145
|
+
fs.writeFileSync(out, generateTypes(Array.isArray(collections) ? collections : []))
|
|
146
|
+
const count = (Array.isArray(collections) ? collections : []).filter((c) => c.kind !== 'members').length
|
|
147
|
+
ctx.out(`Types of ${count} ${count === 1 ? 'collection' : 'collections'} written to ${path.relative(ctx.cwd, out) || out}.`)
|
|
148
|
+
return 0
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The folder to deploy: the one given, or the first of dist, build, out that exists. */
|
|
152
|
+
export function buildDir(cwd, given) {
|
|
153
|
+
if (given) {
|
|
154
|
+
const dir = path.resolve(cwd, given)
|
|
155
|
+
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new CliError(`${given} is not a folder.`)
|
|
156
|
+
return dir
|
|
157
|
+
}
|
|
158
|
+
for (const name of BUILD_DIRS) {
|
|
159
|
+
const dir = path.resolve(cwd, name)
|
|
160
|
+
if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) return dir
|
|
161
|
+
}
|
|
162
|
+
throw new CliError('No built folder: build the site first, or say which folder to deploy (dist, build, out).')
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Every file of the folder, as zip entries with forward-slash names. */
|
|
166
|
+
export function collectFiles(dir) {
|
|
167
|
+
const entries = []
|
|
168
|
+
const walk = (current, prefix) => {
|
|
169
|
+
for (const dirent of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
170
|
+
if (JUNK.has(dirent.name)) continue
|
|
171
|
+
const full = path.join(current, dirent.name)
|
|
172
|
+
const name = prefix ? `${prefix}/${dirent.name}` : dirent.name
|
|
173
|
+
if (dirent.isSymbolicLink()) throw new CliError(`${name} is a symbolic link: Hakubase takes files only.`)
|
|
174
|
+
if (dirent.isDirectory()) walk(full, name)
|
|
175
|
+
else if (dirent.isFile()) entries.push({ name, data: fs.readFileSync(full), mtime: fs.statSync(full).mtime })
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
walk(dir, '')
|
|
179
|
+
return entries
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function megabytes(bytes) {
|
|
183
|
+
if (bytes < 1024 * 1024) return `${Math.ceil(bytes / 1024)} KB`
|
|
184
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function gitSubject(cwd) {
|
|
188
|
+
try {
|
|
189
|
+
return execFileSync('git', ['log', '-1', '--pretty=%s'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
|
|
190
|
+
} catch {
|
|
191
|
+
return ''
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export async function deploy(ctx, positional, flags) {
|
|
196
|
+
const t = target(ctx, flags)
|
|
197
|
+
const dir = buildDir(ctx.cwd, positional[0])
|
|
198
|
+
const entries = collectFiles(dir)
|
|
199
|
+
if (!entries.length) throw new CliError(`${path.relative(ctx.cwd, dir) || dir} is empty.`)
|
|
200
|
+
const manifest = path.join(t.root, 'hakubase.json')
|
|
201
|
+
if (!entries.some((e) => e.name === 'hakubase.json') && fs.existsSync(manifest)) {
|
|
202
|
+
entries.push({ name: 'hakubase.json', data: fs.readFileSync(manifest), mtime: fs.statSync(manifest).mtime })
|
|
203
|
+
}
|
|
204
|
+
const zip = createZip(entries)
|
|
205
|
+
if (zip.length > MAX_ZIP) {
|
|
206
|
+
throw new CliError(`The zip is ${megabytes(zip.length)}: Hakubase takes up to 32 MB. Put the videos in the File library.`)
|
|
207
|
+
}
|
|
208
|
+
const github = Boolean(ctx.env.GITHUB_SHA)
|
|
209
|
+
const commit = typeof flags.commit === 'string' ? flags.commit : (ctx.env.GITHUB_SHA || '')
|
|
210
|
+
const via = typeof flags.via === 'string' ? flags.via : (github ? 'github' : 'cli')
|
|
211
|
+
const message = typeof flags.message === 'string' ? flags.message : (github ? gitSubject(ctx.cwd) : '')
|
|
212
|
+
const form = new FormData()
|
|
213
|
+
form.append('file', new Blob([zip], { type: 'application/zip' }), 'site.zip')
|
|
214
|
+
form.append('publish', flags.publish ? 'true' : 'false')
|
|
215
|
+
form.append('message', message)
|
|
216
|
+
form.append('commit', commit)
|
|
217
|
+
form.append('via', via)
|
|
218
|
+
const version = await request(ctx, 'POST', `${t.api}/api/sites/${encodeURIComponent(t.site)}/code-site/versions`, { key: t.key, body: form })
|
|
219
|
+
ctx.out(`Version ${version.number} uploaded (${version.files} files, ${megabytes(version.size || 0)}, ${megabytes(version.uploaded || 0)} new).`)
|
|
220
|
+
if (version.online) {
|
|
221
|
+
ctx.out(`Online: ${t.siteUrl || await siteUrl(ctx, t)}`)
|
|
222
|
+
} else {
|
|
223
|
+
ctx.out(`Preview: ${version.preview_url}`)
|
|
224
|
+
}
|
|
225
|
+
return 0
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function siteUrl(ctx, t) {
|
|
229
|
+
try {
|
|
230
|
+
const info = await request(ctx, 'GET', `${t.api}/api/sites/${encodeURIComponent(t.site)}/code-site`, { key: t.key })
|
|
231
|
+
return info.url || t.api
|
|
232
|
+
} catch {
|
|
233
|
+
return t.api
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export async function publish(ctx, positional, flags) {
|
|
238
|
+
const number = Number.parseInt(positional[0], 10)
|
|
239
|
+
if (!Number.isInteger(number) || number < 1) throw new CliError('Usage: hakubase publish <number>')
|
|
240
|
+
const t = target(ctx, flags)
|
|
241
|
+
await request(ctx, 'POST', `${t.api}/api/sites/${encodeURIComponent(t.site)}/code-site/versions/${number}/publish`, { key: t.key })
|
|
242
|
+
ctx.out(`Version ${number} online: ${t.siteUrl || await siteUrl(ctx, t)}`)
|
|
243
|
+
return 0
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const COMMANDS = { link, types, deploy, publish }
|
|
247
|
+
|
|
248
|
+
export async function main(argv, ctx = {}) {
|
|
249
|
+
const full = {
|
|
250
|
+
cwd: process.cwd(),
|
|
251
|
+
env: process.env,
|
|
252
|
+
fetch: (...args) => globalThis.fetch(...args),
|
|
253
|
+
out: (line) => process.stdout.write(line + '\n'),
|
|
254
|
+
err: (line) => process.stderr.write(line + '\n'),
|
|
255
|
+
...ctx,
|
|
256
|
+
}
|
|
257
|
+
const [name, ...rest] = argv
|
|
258
|
+
if (!name || name === 'help' || name === '--help' || name === '-h') {
|
|
259
|
+
full.out(USAGE.trimEnd())
|
|
260
|
+
return 0
|
|
261
|
+
}
|
|
262
|
+
const command = COMMANDS[name]
|
|
263
|
+
if (!command) {
|
|
264
|
+
full.err(`Unknown command: ${name}\n\n${USAGE.trimEnd()}`)
|
|
265
|
+
return 1
|
|
266
|
+
}
|
|
267
|
+
const { positional, flags } = parseArgs(rest)
|
|
268
|
+
if (flags.help) {
|
|
269
|
+
full.out(USAGE.trimEnd())
|
|
270
|
+
return 0
|
|
271
|
+
}
|
|
272
|
+
try {
|
|
273
|
+
return await command(full, positional, flags)
|
|
274
|
+
} catch (error) {
|
|
275
|
+
if (error instanceof CliError) {
|
|
276
|
+
full.err(error.message)
|
|
277
|
+
return 1
|
|
278
|
+
}
|
|
279
|
+
throw error
|
|
280
|
+
}
|
|
281
|
+
}
|
package/lib/project.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Where a project keeps its link to Hakubase: `.hakubase/project.json`
|
|
2
|
+
// for the addresses, `.env.local` for the key. The key never goes in
|
|
3
|
+
// project.json, and is never printed whole.
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
|
|
8
|
+
export const PROJECT_FILE = path.join('.hakubase', 'project.json')
|
|
9
|
+
export const ENV_FILE = '.env.local'
|
|
10
|
+
const KEY_LINE = /^\s*(?:export\s+)?HAKUBASE_KEY\s*=\s*(.*)$/
|
|
11
|
+
|
|
12
|
+
/** The nearest directory, from `start` up, that holds a linked project; null if none. */
|
|
13
|
+
export function findRoot(start = process.cwd()) {
|
|
14
|
+
let dir = path.resolve(start)
|
|
15
|
+
for (;;) {
|
|
16
|
+
if (fs.existsSync(path.join(dir, PROJECT_FILE))) return dir
|
|
17
|
+
const parent = path.dirname(dir)
|
|
18
|
+
if (parent === dir) return null
|
|
19
|
+
dir = parent
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function readProject(root) {
|
|
24
|
+
if (!root) return null
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(fs.readFileSync(path.join(root, PROJECT_FILE), 'utf8'))
|
|
27
|
+
} catch {
|
|
28
|
+
return null
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function writeProject(root, project) {
|
|
33
|
+
fs.mkdirSync(path.join(root, '.hakubase'), { recursive: true })
|
|
34
|
+
fs.writeFileSync(path.join(root, PROJECT_FILE), JSON.stringify(project, null, 2) + '\n')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function unquote(value) {
|
|
38
|
+
const v = value.trim()
|
|
39
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
|
|
40
|
+
return v.slice(1, -1)
|
|
41
|
+
}
|
|
42
|
+
return v.replace(/\s+#.*$/, '')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The key written in `.env.local`, or ''. */
|
|
46
|
+
export function readEnvKey(root) {
|
|
47
|
+
if (!root) return ''
|
|
48
|
+
let text
|
|
49
|
+
try {
|
|
50
|
+
text = fs.readFileSync(path.join(root, ENV_FILE), 'utf8')
|
|
51
|
+
} catch {
|
|
52
|
+
return ''
|
|
53
|
+
}
|
|
54
|
+
for (const line of text.split(/\r?\n/)) {
|
|
55
|
+
const match = line.match(KEY_LINE)
|
|
56
|
+
if (match) return unquote(match[1])
|
|
57
|
+
}
|
|
58
|
+
return ''
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The key to use: `--key`, then the HAKUBASE_KEY variable, then `.env.local`. */
|
|
62
|
+
export function resolveKey(root, flag, env = process.env) {
|
|
63
|
+
return flag || env.HAKUBASE_KEY || readEnvKey(root) || ''
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Writes the key in `.env.local`, replacing its line or adding one. */
|
|
67
|
+
export function writeEnvKey(root, key) {
|
|
68
|
+
const file = path.join(root, ENV_FILE)
|
|
69
|
+
let text = ''
|
|
70
|
+
try {
|
|
71
|
+
text = fs.readFileSync(file, 'utf8')
|
|
72
|
+
} catch {
|
|
73
|
+
text = ''
|
|
74
|
+
}
|
|
75
|
+
const lines = text ? text.split(/\r?\n/) : []
|
|
76
|
+
if (lines.length && lines[lines.length - 1] === '') lines.pop()
|
|
77
|
+
let found = false
|
|
78
|
+
const out = []
|
|
79
|
+
for (const line of lines) {
|
|
80
|
+
if (KEY_LINE.test(line)) {
|
|
81
|
+
if (!found) out.push(`HAKUBASE_KEY=${key}`)
|
|
82
|
+
found = true
|
|
83
|
+
} else {
|
|
84
|
+
out.push(line)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (!found) out.push(`HAKUBASE_KEY=${key}`)
|
|
88
|
+
fs.writeFileSync(file, out.join('\n') + '\n', { mode: 0o600 })
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Where a .gitignore exists, makes sure it keeps `.env.local` out. Returns true when it added the line. */
|
|
92
|
+
export function ensureGitignored(root) {
|
|
93
|
+
const file = path.join(root, '.gitignore')
|
|
94
|
+
let text
|
|
95
|
+
try {
|
|
96
|
+
text = fs.readFileSync(file, 'utf8')
|
|
97
|
+
} catch {
|
|
98
|
+
return false
|
|
99
|
+
}
|
|
100
|
+
const covered = text.split(/\r?\n/).map((l) => l.trim()).some((l) =>
|
|
101
|
+
l === ENV_FILE || l === '/' + ENV_FILE || l === '.env*' || l === '*.local' || l === '.env.*')
|
|
102
|
+
if (covered) return false
|
|
103
|
+
fs.writeFileSync(file, text + (text && !text.endsWith('\n') ? '\n' : '') + ENV_FILE + '\n')
|
|
104
|
+
return true
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** `hb_…f3a9`: enough to tell keys apart, never enough to use one. */
|
|
108
|
+
export function maskKey(key) {
|
|
109
|
+
if (!key) return ''
|
|
110
|
+
const tail = key.length > 12 ? key.slice(-4) : ''
|
|
111
|
+
return `${key.slice(0, 3)}…${tail}`
|
|
112
|
+
}
|
package/lib/types.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// `hakubase types`: the collections of the site as TypeScript, merged
|
|
2
|
+
// into the `Collections` interface of @hakubase/sdk. The shapes follow
|
|
3
|
+
// what `/_data` answers: select options as their labels, relations as
|
|
4
|
+
// the related items, images as a URL or {url, alt, focal}, empty
|
|
5
|
+
// fields absent.
|
|
6
|
+
|
|
7
|
+
const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/
|
|
8
|
+
|
|
9
|
+
function prop(key) {
|
|
10
|
+
return IDENT.test(key) ? key : JSON.stringify(key)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function comment(text, indent) {
|
|
14
|
+
const clean = String(text || '').replace(/\*\//g, '* /').trim()
|
|
15
|
+
return clean ? `${indent}/** ${clean} */\n` : ''
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function optionLabels(field) {
|
|
19
|
+
const labels = []
|
|
20
|
+
for (const option of field.options || []) {
|
|
21
|
+
const label = typeof option === 'string' ? option : option && (option.label ?? option.id)
|
|
22
|
+
if (label !== undefined && label !== null && label !== '' && !labels.includes(String(label))) {
|
|
23
|
+
labels.push(String(label))
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return labels
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function union(labels) {
|
|
30
|
+
return labels.length ? labels.map((l) => JSON.stringify(l)).join(' | ') : 'string'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function scalarType(kind) {
|
|
34
|
+
switch (kind) {
|
|
35
|
+
case 'text':
|
|
36
|
+
case 'textarea':
|
|
37
|
+
case 'richtext':
|
|
38
|
+
case 'url':
|
|
39
|
+
case 'color':
|
|
40
|
+
case 'date':
|
|
41
|
+
case 'datetime':
|
|
42
|
+
return 'string'
|
|
43
|
+
case 'number':
|
|
44
|
+
return 'number'
|
|
45
|
+
case 'boolean':
|
|
46
|
+
return 'boolean'
|
|
47
|
+
case 'image':
|
|
48
|
+
case 'file':
|
|
49
|
+
return 'CmsImage'
|
|
50
|
+
case 'geo':
|
|
51
|
+
return 'CmsGeo'
|
|
52
|
+
case 'json':
|
|
53
|
+
return 'unknown'
|
|
54
|
+
default:
|
|
55
|
+
return null
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function fieldType(field, indent = ' ') {
|
|
60
|
+
const kind = field.kind || 'text'
|
|
61
|
+
if (kind === 'select') return union(optionLabels(field))
|
|
62
|
+
if (kind === 'multiselect') {
|
|
63
|
+
return `Array<${union(optionLabels(field))}>`
|
|
64
|
+
}
|
|
65
|
+
if (kind === 'relation') return 'CmsRelated[]'
|
|
66
|
+
if (kind === 'group') {
|
|
67
|
+
// Subfields of a repeater are stored as written: no label mapping.
|
|
68
|
+
const inner = (field.fields || []).map((sub) => {
|
|
69
|
+
const type = sub.kind === 'select' || sub.kind === 'multiselect'
|
|
70
|
+
? (sub.kind === 'multiselect' ? 'string[]' : 'string')
|
|
71
|
+
: scalarType(sub.kind) || 'unknown'
|
|
72
|
+
return `${indent} ${prop(sub.key)}?: ${type}\n`
|
|
73
|
+
}).join('')
|
|
74
|
+
return `Array<{\n${inner}${indent}}>`
|
|
75
|
+
}
|
|
76
|
+
return scalarType(kind) || 'unknown'
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function publicFields(collection) {
|
|
80
|
+
return (collection.fields || []).filter((f) => f && f.key && f.active !== false && !f.private)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function generateTypes(collections, { date = new Date() } = {}) {
|
|
84
|
+
const usable = (collections || []).filter((c) => c && c.key && c.kind !== 'members')
|
|
85
|
+
const body = usable.map((c) => {
|
|
86
|
+
const fields = publicFields(c).map((f) => {
|
|
87
|
+
// A reserved field leaves the site only for members who qualify:
|
|
88
|
+
// for everybody else it is absent, required or not.
|
|
89
|
+
const optional = !f.required || f.reserved ? '?' : ''
|
|
90
|
+
return comment(f.label && f.label !== f.key ? f.label : '', ' ') +
|
|
91
|
+
` ${prop(f.key)}${optional}: ${fieldType(f)}\n`
|
|
92
|
+
}).join('')
|
|
93
|
+
return comment(c.name, ' ') + ` ${prop(c.key)}: {\n${fields} }\n`
|
|
94
|
+
}).join('')
|
|
95
|
+
const day = date.toISOString().slice(0, 10)
|
|
96
|
+
return `// Generated by \`hakubase types\` on ${day}. Do not edit: run it again.\n` +
|
|
97
|
+
`import type { CmsGeo, CmsImage, CmsRelated } from '@hakubase/sdk'\n\n` +
|
|
98
|
+
`declare module '@hakubase/sdk' {\n` +
|
|
99
|
+
` interface Collections {\n${body} }\n}\n`
|
|
100
|
+
}
|
package/lib/zip.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// A minimal zip writer: deflate or store, UTF-8 names, no zip64.
|
|
2
|
+
// Enough for a built site, which Hakubase caps well below the limits
|
|
3
|
+
// of the classic format (2,000 files, 100 MB uncompressed).
|
|
4
|
+
|
|
5
|
+
import zlib from 'node:zlib'
|
|
6
|
+
|
|
7
|
+
let table = null
|
|
8
|
+
|
|
9
|
+
function crcTable() {
|
|
10
|
+
if (table) return table
|
|
11
|
+
table = new Uint32Array(256)
|
|
12
|
+
for (let n = 0; n < 256; n++) {
|
|
13
|
+
let c = n
|
|
14
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
|
15
|
+
table[n] = c >>> 0
|
|
16
|
+
}
|
|
17
|
+
return table
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function crc32(data) {
|
|
21
|
+
if (typeof zlib.crc32 === 'function') return zlib.crc32(data) >>> 0
|
|
22
|
+
const t = crcTable()
|
|
23
|
+
let c = 0xffffffff
|
|
24
|
+
for (let i = 0; i < data.length; i++) c = t[(c ^ data[i]) & 0xff] ^ (c >>> 8)
|
|
25
|
+
return (c ^ 0xffffffff) >>> 0
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function dosDateTime(date) {
|
|
29
|
+
const d = date instanceof Date && !Number.isNaN(date.getTime()) ? date : new Date()
|
|
30
|
+
const year = Math.max(1980, d.getFullYear())
|
|
31
|
+
const time = (d.getHours() << 11) | (d.getMinutes() << 5) | Math.floor(d.getSeconds() / 2)
|
|
32
|
+
const day = ((year - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate()
|
|
33
|
+
return { time, day }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const UTF8 = 0x0800
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* entries: [{ name: 'assets/app.js', data: Buffer, mtime?: Date }]
|
|
40
|
+
* Returns the zip as one Buffer.
|
|
41
|
+
*/
|
|
42
|
+
export function createZip(entries) {
|
|
43
|
+
if (entries.length > 0xffff) throw new Error('Too many files for a zip without zip64.')
|
|
44
|
+
const locals = []
|
|
45
|
+
const centrals = []
|
|
46
|
+
let offset = 0
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
const name = Buffer.from(String(entry.name).replace(/\\/g, '/').replace(/^\/+/, ''), 'utf8')
|
|
49
|
+
const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data)
|
|
50
|
+
const crc = crc32(data)
|
|
51
|
+
const deflated = zlib.deflateRawSync(data)
|
|
52
|
+
const stored = deflated.length >= data.length
|
|
53
|
+
const body = stored ? data : deflated
|
|
54
|
+
const method = stored ? 0 : 8
|
|
55
|
+
const { time, day } = dosDateTime(entry.mtime)
|
|
56
|
+
|
|
57
|
+
const local = Buffer.alloc(30)
|
|
58
|
+
local.writeUInt32LE(0x04034b50, 0)
|
|
59
|
+
local.writeUInt16LE(20, 4)
|
|
60
|
+
local.writeUInt16LE(UTF8, 6)
|
|
61
|
+
local.writeUInt16LE(method, 8)
|
|
62
|
+
local.writeUInt16LE(time, 10)
|
|
63
|
+
local.writeUInt16LE(day, 12)
|
|
64
|
+
local.writeUInt32LE(crc, 14)
|
|
65
|
+
local.writeUInt32LE(body.length, 18)
|
|
66
|
+
local.writeUInt32LE(data.length, 22)
|
|
67
|
+
local.writeUInt16LE(name.length, 26)
|
|
68
|
+
local.writeUInt16LE(0, 28)
|
|
69
|
+
|
|
70
|
+
const central = Buffer.alloc(46)
|
|
71
|
+
central.writeUInt32LE(0x02014b50, 0)
|
|
72
|
+
central.writeUInt16LE(20, 4)
|
|
73
|
+
central.writeUInt16LE(20, 6)
|
|
74
|
+
central.writeUInt16LE(UTF8, 8)
|
|
75
|
+
central.writeUInt16LE(method, 10)
|
|
76
|
+
central.writeUInt16LE(time, 12)
|
|
77
|
+
central.writeUInt16LE(day, 14)
|
|
78
|
+
central.writeUInt32LE(crc, 16)
|
|
79
|
+
central.writeUInt32LE(body.length, 20)
|
|
80
|
+
central.writeUInt32LE(data.length, 24)
|
|
81
|
+
central.writeUInt16LE(name.length, 28)
|
|
82
|
+
central.writeUInt16LE(0, 30)
|
|
83
|
+
central.writeUInt16LE(0, 32)
|
|
84
|
+
central.writeUInt16LE(0, 34)
|
|
85
|
+
central.writeUInt16LE(0, 36)
|
|
86
|
+
central.writeUInt32LE(0, 38)
|
|
87
|
+
central.writeUInt32LE(offset, 42)
|
|
88
|
+
|
|
89
|
+
locals.push(local, name, body)
|
|
90
|
+
centrals.push(central, name)
|
|
91
|
+
offset += local.length + name.length + body.length
|
|
92
|
+
if (offset > 0xffffffff) throw new Error('The zip is too big for a zip without zip64.')
|
|
93
|
+
}
|
|
94
|
+
const directory = Buffer.concat(centrals)
|
|
95
|
+
const end = Buffer.alloc(22)
|
|
96
|
+
end.writeUInt32LE(0x06054b50, 0)
|
|
97
|
+
end.writeUInt16LE(0, 4)
|
|
98
|
+
end.writeUInt16LE(0, 6)
|
|
99
|
+
end.writeUInt16LE(entries.length, 8)
|
|
100
|
+
end.writeUInt16LE(entries.length, 10)
|
|
101
|
+
end.writeUInt32LE(directory.length, 12)
|
|
102
|
+
end.writeUInt32LE(offset, 16)
|
|
103
|
+
end.writeUInt16LE(0, 20)
|
|
104
|
+
return Buffer.concat([...locals, directory, end])
|
|
105
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hakubase/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Link, type, develop and deploy Hakubase code sites; Vite and Astro plugins for development with real data.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"hakubase": "./bin/hakubase.js"
|
|
8
|
+
},
|
|
9
|
+
"exports": {
|
|
10
|
+
"./vite": "./vite.js",
|
|
11
|
+
"./astro": "./astro.js",
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"bin",
|
|
16
|
+
"lib",
|
|
17
|
+
"vite.js",
|
|
18
|
+
"astro.js",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=20"
|
|
23
|
+
},
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"keywords": [
|
|
26
|
+
"hakubase",
|
|
27
|
+
"cli",
|
|
28
|
+
"deploy",
|
|
29
|
+
"vite-plugin",
|
|
30
|
+
"astro-integration"
|
|
31
|
+
],
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "node --test"
|
|
34
|
+
}
|
|
35
|
+
}
|
package/vite.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// The Vite plugin of @hakubase/cli: in development, Hakubase's own
|
|
2
|
+
// paths go from localhost to the real site, with the key added on the
|
|
3
|
+
// way. The browser sees one origin; the key stays in this process and
|
|
4
|
+
// never reaches the bundle.
|
|
5
|
+
|
|
6
|
+
import { findRoot, readProject, resolveKey } from './lib/project.js'
|
|
7
|
+
|
|
8
|
+
export const PROXY_PATHS = '^/(_hb|_data|_fn|_m)(/|$)'
|
|
9
|
+
|
|
10
|
+
let warned = false
|
|
11
|
+
|
|
12
|
+
function warnOnce(log, message) {
|
|
13
|
+
if (warned) return
|
|
14
|
+
warned = true
|
|
15
|
+
log(`[hakubase] ${message}`)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function stripDomain(cookie) {
|
|
19
|
+
return cookie.split(';').filter((part) => !/^\s*domain\s*=/i.test(part)).join(';')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The proxy entry for a linked project, or null. Exported for the tests. */
|
|
23
|
+
export function proxyFor({ siteUrl, key }) {
|
|
24
|
+
const targetOrigin = new URL(siteUrl).origin
|
|
25
|
+
return {
|
|
26
|
+
[PROXY_PATHS]: {
|
|
27
|
+
target: targetOrigin,
|
|
28
|
+
changeOrigin: true,
|
|
29
|
+
secure: true,
|
|
30
|
+
headers: key ? { authorization: `Bearer ${key}` } : {},
|
|
31
|
+
configure(proxy) {
|
|
32
|
+
proxy.on('proxyReq', (proxyReq) => {
|
|
33
|
+
if (key) proxyReq.setHeader('authorization', `Bearer ${key}`)
|
|
34
|
+
// The members area refuses a write whose Origin is not the
|
|
35
|
+
// site: seen from there, the page is the site.
|
|
36
|
+
if (proxyReq.getHeader('origin')) proxyReq.setHeader('origin', targetOrigin)
|
|
37
|
+
})
|
|
38
|
+
proxy.on('proxyRes', (proxyRes) => {
|
|
39
|
+
// A cookie for the site's domain would not stick on localhost.
|
|
40
|
+
const cookies = proxyRes.headers['set-cookie']
|
|
41
|
+
if (Array.isArray(cookies)) proxyRes.headers['set-cookie'] = cookies.map(stripDomain)
|
|
42
|
+
else if (typeof cookies === 'string') proxyRes.headers['set-cookie'] = stripDomain(cookies)
|
|
43
|
+
})
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export default function hakubase(options = {}) {
|
|
50
|
+
const log = options.log || ((message) => console.warn(message))
|
|
51
|
+
return {
|
|
52
|
+
name: 'hakubase',
|
|
53
|
+
apply: 'serve',
|
|
54
|
+
config() {
|
|
55
|
+
const root = findRoot(options.root || process.cwd())
|
|
56
|
+
const project = readProject(root)
|
|
57
|
+
if (!project || !project.site_url) {
|
|
58
|
+
warnOnce(log, 'This project is not linked: run `npx hakubase link <workspace-url> <site-id> --key hb_…`. Nothing is proxied.')
|
|
59
|
+
return {}
|
|
60
|
+
}
|
|
61
|
+
const key = resolveKey(root, options.key || '')
|
|
62
|
+
if (!key) warnOnce(log, 'No key in HAKUBASE_KEY or .env.local: only published content answers.')
|
|
63
|
+
const proxy = proxyFor({ siteUrl: project.site_url, key })
|
|
64
|
+
return { server: { proxy }, preview: { proxy } }
|
|
65
|
+
},
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export { hakubase }
|