@hakubase/cli 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.
package/README.md CHANGED
@@ -8,13 +8,19 @@ npm i -D @hakubase/cli
8
8
 
9
9
  ## Link
10
10
 
11
- Create a **development key** in the site's settings (tab *Settings*, *Keys*), then:
11
+ ```bash
12
+ npx hakubase link https://noesis.hakubase.com
13
+ ```
14
+
15
+ The command prints a code and opens the browser on the workspace. There, signed in, check that the code is the same, choose the code site and click *Collega*: the command receives a publishing key of that site, named after this computer, and revocable from the site's settings like any other. `--no-browser` only prints the address (on a remote machine, open it from your own). Add the site id to have it chosen already.
16
+
17
+ With a key made by hand in the site's settings (tab *Settings*, *Keys*), no browser:
12
18
 
13
19
  ```bash
14
20
  npx hakubase link https://noesis.hakubase.com <site-id> --key hb_…
15
21
  ```
16
22
 
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.
23
+ Either way 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
24
 
19
25
  The key is read from `--key`, then the `HAKUBASE_KEY` variable, then `.env.local`.
20
26
 
@@ -29,7 +35,7 @@ npx hakubase types --out src/hakubase.d.ts
29
35
 
30
36
  ## Develop
31
37
 
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.
38
+ The plugins forward `/_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
39
 
34
40
  ```js
35
41
  // vite.config.js
@@ -47,6 +53,15 @@ import hakubase from '@hakubase/cli/astro'
47
53
  export default defineConfig({ integrations: [hakubase()] })
48
54
  ```
49
55
 
56
+ ```js
57
+ // next.config.mjs — Next.js, also with output: 'export'
58
+ import { withHakubase } from '@hakubase/cli/next'
59
+
60
+ export default withHakubase({ output: 'export' })
61
+ ```
62
+
63
+ In `next dev` a small proxy in the same process adds the key, and Next rewrites the four paths to it (Next prints that rewrites do not work with `export`: in development they do, and the build is left untouched). The site comes from the linked project or from `HAKUBASE_SITE_URL`.
64
+
50
65
  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
66
 
52
67
  ## Deploy
@@ -91,7 +106,7 @@ jobs:
91
106
 
92
107
  | Command | What it does |
93
108
  |---|---|
94
- | `hakubase link <workspace-url> <site-id> [--key hb_…]` | Links the folder to a code site |
109
+ | `hakubase link <workspace-url> [site-id] [--key hb_…] [--no-browser]` | Links the folder to a code site: approved in the browser, or with a key |
95
110
  | `hakubase types [--out file]` | Writes the TypeScript types of the collections |
96
111
  | `hakubase deploy [dir] [--publish] [--message m] [--commit sha] [--via cli\|github]` | Uploads the built folder as a new version |
97
112
  | `hakubase publish <number>` | Puts a version online |
package/lib/commands.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // The commands of `hakubase`. Each one returns its exit code; output
2
2
  // goes through `io` so the tests can read it.
3
3
 
4
- import { execFileSync } from 'node:child_process'
4
+ import { execFileSync, spawn } from 'node:child_process'
5
5
  import crypto from 'node:crypto'
6
6
  import fs from 'node:fs'
7
+ import os from 'node:os'
7
8
  import path from 'node:path'
8
9
 
9
10
  import {
@@ -23,7 +24,8 @@ export class CliError extends Error {}
23
24
  export const USAGE = `Usage: hakubase <command> [options]
24
25
 
25
26
  Commands:
26
- link <workspace-url> <site-id> [--key hb_…] Link this folder to a code site
27
+ link <workspace-url> [site-id] Link this folder to a code site: the browser
28
+ [--key hb_…] [--no-browser] asks you to approve (with --key, no browser)
27
29
  types [--out hakubase.d.ts] Write the TypeScript types of the collections
28
30
  deploy [dir] [--publish] [--message m] Upload the built folder as a new version
29
31
  [--commit sha] [--via cli|github] (dir: dist, build or out by default)
@@ -50,7 +52,7 @@ export function parseArgs(argv) {
50
52
  } else {
51
53
  const name = arg.slice(2)
52
54
  const next = argv[i + 1]
53
- if (['publish', 'help'].includes(name) || next === undefined || next.startsWith('--')) {
55
+ if (['publish', 'help', 'no-browser'].includes(name) || next === undefined || next.startsWith('--')) {
54
56
  flags[name] = true
55
57
  } else {
56
58
  flags[name] = next
@@ -127,14 +129,52 @@ export function target(ctx, flags) {
127
129
  return { root, api, site, key, siteUrl: project.site_url || '' }
128
130
  }
129
131
 
132
+ /** Opens a page in the person's browser; a failure only means they open it by hand. */
133
+ export function openInBrowser(url) {
134
+ const [command, args] = process.platform === 'darwin' ? ['open', [url]]
135
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url.replace(/&/g, '^&')]]
136
+ : ['xdg-open', [url]]
137
+ try {
138
+ spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref()
139
+ } catch {
140
+ // The address is printed: the person opens it.
141
+ }
142
+ }
143
+
144
+ /** The key, approved by a person in the browser (ADR-0229). */
145
+ export async function keyFromBrowser(ctx, api, siteId, flags) {
146
+ const asked = await request(ctx, 'POST', `${api}/api/public/site-links`, {
147
+ json: { computer: ctx.computer || os.hostname(), site_id: siteId || '' },
148
+ })
149
+ ctx.out(`Open ${asked.url}`)
150
+ ctx.out(`and check that the code is ${asked.code}. Waiting for the approval…`)
151
+ if (!flags['no-browser']) (ctx.openBrowser || openInBrowser)(asked.url)
152
+ const sleep = ctx.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
153
+ const tries = Math.ceil((asked.expires_in || 600) / (asked.interval || 2))
154
+ for (let i = 0; i < tries; i++) {
155
+ await sleep((asked.interval || 2) * 1000)
156
+ const got = await request(ctx, 'POST', `${api}/api/public/site-links/collect`, { json: { device: asked.device } })
157
+ if (got.status === 'approved') return got
158
+ if (got.status === 'denied') throw new CliError('The link was refused in the browser.')
159
+ }
160
+ throw new CliError('The request expired: run hakubase link again.')
161
+ }
162
+
130
163
  export async function link(ctx, positional, flags) {
131
- const [workspace, siteId] = positional
132
- if (!workspace || !siteId) throw new CliError('Usage: hakubase link <workspace-url> <site-id> [--key hb_…]')
164
+ const [workspace, siteArg] = positional
165
+ if (!workspace) throw new CliError('Usage: hakubase link <workspace-url> [site-id] [--key hb_…]')
133
166
  const api = workspaceOrigin(workspace)
134
167
  const root = ctx.cwd
135
- const given = typeof flags.key === 'string' ? flags.key : ''
136
- const key = resolveKey(root, given, ctx.env)
137
- if (!key) throw new CliError('No key: pass --key hb_… (a development or publishing key of this site).')
168
+ let given = typeof flags.key === 'string' ? flags.key : ''
169
+ let key = resolveKey(root, given, ctx.env)
170
+ let siteId = siteArg
171
+ if (!key) {
172
+ const got = await keyFromBrowser(ctx, api, siteId, flags)
173
+ key = given = got.token
174
+ siteId = got.site_id
175
+ } else if (!siteId) {
176
+ throw new CliError('Usage: hakubase link <workspace-url> <site-id> --key hb_… (or no key, to approve in the browser)')
177
+ }
138
178
  const info = await request(ctx, 'GET', `${api}/api/sites/${encodeURIComponent(siteId)}/code-site`, { key })
139
179
  writeProject(root, { api, site_id: info.id || siteId, site_url: info.url || '' })
140
180
  if (given) writeEnvKey(root, given)
package/next.js ADDED
@@ -0,0 +1,115 @@
1
+ // The Next.js side of @hakubase/cli: in `next dev`, Hakubase's own paths
2
+ // (/_hb, /_data, /_fn, /_m) go from localhost to the real site, with the
3
+ // key added on the way — what the Vite plugin does with Vite's proxy.
4
+ //
5
+ // Next's rewrites cannot add a header, and the key must never reach the
6
+ // browser: so the rewrites point at a small proxy in this process, which
7
+ // adds it. Only in development; `next build` (and `output: 'export'`)
8
+ // see the config untouched.
9
+ //
10
+ // // next.config.mjs
11
+ // import { withHakubase } from '@hakubase/cli/next'
12
+ // export default withHakubase({ output: 'export' })
13
+
14
+ import http from 'node:http'
15
+ import https from 'node:https'
16
+
17
+ import { installLocalhostResolver } from './lib/localhost.js'
18
+ import { findRoot, readProject, resolveKey } from './lib/project.js'
19
+
20
+ export const PATHS = ['_hb', '_data', '_fn', '_m']
21
+ const DEVELOPMENT = 'phase-development-server'
22
+ const RUNNING = Symbol.for('hakubase.next.proxy')
23
+
24
+ function stripDomain(cookie) {
25
+ return cookie.split(';').filter((part) => !/^\s*domain\s*=/i.test(part)).join(';')
26
+ }
27
+
28
+ /** Where to send the requests, and with which key: options, then env, then the linked project. */
29
+ export function targetOf(options = {}, env = process.env, cwd = process.cwd()) {
30
+ const root = findRoot(options.root || cwd)
31
+ const project = readProject(root) || {}
32
+ const siteUrl = options.siteUrl || env.HAKUBASE_SITE_URL || project.site_url || ''
33
+ const key = resolveKey(root || cwd, options.key || '', env)
34
+ return { siteUrl, key }
35
+ }
36
+
37
+ /** The proxy: forwards to the site, adds the key, makes the page look like the site. */
38
+ export function createProxy({ siteUrl, key }) {
39
+ const target = new URL(siteUrl)
40
+ const client = target.protocol === 'https:' ? https : http
41
+ return http.createServer((req, res) => {
42
+ const headers = { ...req.headers, host: target.host }
43
+ delete headers['x-forwarded-host']
44
+ if (key) headers.authorization = `Bearer ${key}`
45
+ // The members area refuses a write whose Origin is not the site.
46
+ if (headers.origin) headers.origin = target.origin
47
+ const upstream = client.request({
48
+ protocol: target.protocol, hostname: target.hostname, port: target.port,
49
+ method: req.method, path: req.url, headers,
50
+ }, (answer) => {
51
+ const out = { ...answer.headers }
52
+ // A cookie for the site's domain would not stick on localhost.
53
+ const cookies = out['set-cookie']
54
+ if (Array.isArray(cookies)) out['set-cookie'] = cookies.map(stripDomain)
55
+ res.writeHead(answer.statusCode || 502, out)
56
+ answer.pipe(res)
57
+ })
58
+ upstream.on('error', (error) => {
59
+ res.writeHead(502, { 'content-type': 'text/plain' })
60
+ res.end(`Hakubase did not answer: ${error.message}`)
61
+ })
62
+ req.pipe(upstream)
63
+ })
64
+ }
65
+
66
+ async function startProxy(target, log) {
67
+ const running = globalThis[RUNNING]
68
+ if (running && running.siteUrl === target.siteUrl && running.key === target.key) return running.origin
69
+ installLocalhostResolver()
70
+ const server = createProxy(target)
71
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
72
+ server.unref()
73
+ const origin = `http://127.0.0.1:${server.address().port}`
74
+ globalThis[RUNNING] = { ...target, origin }
75
+ log(`[hakubase] ${PATHS.map((p) => '/' + p).join(', ')} → ${new URL(target.siteUrl).origin}${target.key ? ' (with the key)' : ''}`)
76
+ return origin
77
+ }
78
+
79
+ /** The rewrites to the local proxy, before Next's own routes. */
80
+ export function rewritesTo(origin) {
81
+ return PATHS.map((p) => ({ source: `/${p}/:path*`, destination: `${origin}/${p}/:path*` }))
82
+ }
83
+
84
+ function merge(own, ours) {
85
+ if (!own) return { beforeFiles: ours }
86
+ if (Array.isArray(own)) return { beforeFiles: ours, afterFiles: own }
87
+ return { ...own, beforeFiles: [...ours, ...(own.beforeFiles || [])] }
88
+ }
89
+
90
+ export function withHakubase(config = {}, options = {}) {
91
+ const log = options.log || ((message) => console.warn(message))
92
+ return async (phase, context) => {
93
+ const resolved = typeof config === 'function' ? await config(phase, context) : config
94
+ if (phase !== DEVELOPMENT) return resolved
95
+ const target = targetOf(options)
96
+ if (!target.siteUrl) {
97
+ log('[hakubase] This project is not linked: run `npx hakubase link <workspace-url>`, or set HAKUBASE_SITE_URL. Nothing is proxied.')
98
+ return resolved
99
+ }
100
+ if (!target.key) log('[hakubase] No key in HAKUBASE_KEY or .env.local: only published content answers, and forms are real.')
101
+ const origin = await startProxy(target, log)
102
+ const ownRewrites = resolved.rewrites
103
+ // `output: 'export'` has no rewrites; in development there is a
104
+ // server, and the proxy needs one. The build keeps the export.
105
+ return {
106
+ ...resolved,
107
+ async rewrites() {
108
+ const own = typeof ownRewrites === 'function' ? await ownRewrites() : ownRewrites
109
+ return merge(own, rewritesTo(origin))
110
+ },
111
+ }
112
+ }
113
+ }
114
+
115
+ export default withHakubase
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hakubase/cli",
3
- "version": "0.2.0",
4
- "description": "Link, type, develop and deploy Hakubase code sites; Vite and Astro plugins for development with real data.",
3
+ "version": "0.4.0",
4
+ "description": "Link, type, develop and deploy Hakubase code sites; Vite, Astro and Next.js helpers for development with real data.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "hakubase": "./bin/hakubase.js"
@@ -9,13 +9,15 @@
9
9
  "exports": {
10
10
  "./vite": "./vite.js",
11
11
  "./astro": "./astro.js",
12
- "./package.json": "./package.json"
12
+ "./package.json": "./package.json",
13
+ "./next": "./next.js"
13
14
  },
14
15
  "files": [
15
16
  "bin",
16
17
  "lib",
17
18
  "vite.js",
18
19
  "astro.js",
20
+ "next.js",
19
21
  "README.md"
20
22
  ],
21
23
  "engines": {