@hakubase/cli 0.3.0 → 0.4.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/README.md CHANGED
@@ -35,7 +35,7 @@ npx hakubase types --out src/hakubase.d.ts
35
35
 
36
36
  ## Develop
37
37
 
38
- 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.
39
39
 
40
40
  ```js
41
41
  // vite.config.js
@@ -53,6 +53,15 @@ import hakubase from '@hakubase/cli/astro'
53
53
  export default defineConfig({ integrations: [hakubase()] })
54
54
  ```
55
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
+
56
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.
57
66
 
58
67
  ## Deploy
package/astro.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { HakubaseViteOptions } from './vite.js'
2
+ /** The Vite plugin of @hakubase/cli, as an Astro integration. */
3
+ export default function hakubase(options?: HakubaseViteOptions): { name: string; hooks: Record<string, (...args: any[]) => void> }
4
+ export { hakubase }
package/next.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ export interface HakubaseNextOptions {
2
+ /** The site's address; else HAKUBASE_SITE_URL, else the linked project. */
3
+ siteUrl?: string
4
+ /** The key; else HAKUBASE_KEY, else .env.local. */
5
+ key?: string
6
+ /** Where to look for the linked project. */
7
+ root?: string
8
+ log?(message: string): void
9
+ }
10
+
11
+ type Config = Record<string, any>
12
+ type ConfigFunction = (phase: string, context: { defaultConfig: Config }) => Config | Promise<Config>
13
+
14
+ /**
15
+ * In `next dev`, Hakubase's paths (/_hb, /_data, /_fn, /_m) reach the real
16
+ * site with the key; the build sees the config untouched.
17
+ */
18
+ export declare function withHakubase<T extends Config>(config: T | ConfigFunction, options?: HakubaseNextOptions):
19
+ (phase: string, context: { defaultConfig: Config }) => Promise<T>
20
+ export default withHakubase
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,14 +1,24 @@
1
1
  {
2
2
  "name": "@hakubase/cli",
3
- "version": "0.3.0",
4
- "description": "Link, type, develop and deploy Hakubase code sites; Vite and Astro plugins for development with real data.",
3
+ "version": "0.4.1",
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"
8
8
  },
9
9
  "exports": {
10
- "./vite": "./vite.js",
11
- "./astro": "./astro.js",
10
+ "./vite": {
11
+ "types": "./vite.d.ts",
12
+ "default": "./vite.js"
13
+ },
14
+ "./astro": {
15
+ "types": "./astro.d.ts",
16
+ "default": "./astro.js"
17
+ },
18
+ "./next": {
19
+ "types": "./next.d.ts",
20
+ "default": "./next.js"
21
+ },
12
22
  "./package.json": "./package.json"
13
23
  },
14
24
  "files": [
@@ -16,7 +26,11 @@
16
26
  "lib",
17
27
  "vite.js",
18
28
  "astro.js",
19
- "README.md"
29
+ "next.js",
30
+ "README.md",
31
+ "vite.d.ts",
32
+ "astro.d.ts",
33
+ "next.d.ts"
20
34
  ],
21
35
  "engines": {
22
36
  "node": ">=20"
package/vite.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export interface HakubaseViteOptions {
2
+ root?: string
3
+ key?: string
4
+ log?(message: string): void
5
+ }
6
+ /** In development, Hakubase's paths reach the real site with the key. */
7
+ export default function hakubase(options?: HakubaseViteOptions): { name: string; apply: 'serve'; config(): Record<string, unknown> }
8
+ export { hakubase }