Skip to content

Commit 357b79a

Browse files
committed
fix: explain Bun API errors
Under Node, code that calls a Bun API failed with "Bun is not defined" and no way forward. Each such error now says to run bongo with Bun, in the CLI, the terminal, and the dev overlay. A partial that called such code was told to add {{#expect Bun}}. A partial now gets that advice only for a name in its own source.
1 parent 3c6a771 commit 357b79a

10 files changed

Lines changed: 79 additions & 12 deletions

File tree

‎docs/content/cli.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,14 @@ An unknown option, or a `--port` that is not a port number, stops the command wi
5555

5656
## Run with Bun
5757

58-
The `bongo` command starts with Node. Image processing needs Bun, so run the command through Bun to resize images:
58+
The `bongo` command starts with Node. Image processing needs Bun. So does your own code when it calls a Bun API, such as `Bun.markdown` in a `$utils` function or in the config. Run the command through Bun for either one:
5959

6060
```sh
6161
bunx --bun bongo build
6262
bun --bun run build # for a "build": "bongo build" script
6363
```
6464

65-
See [Images](/images/#bun-runtime).
65+
Under Node, code that calls a Bun API fails the build, and the error says to run bongo with Bun. See [Images](/images/#bun-runtime).
6666

6767
## Debug
6868

‎docs/content/partials.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ A `.hbs` partial is a tempura template. Declare the arguments that it reads with
6868
A partial that reads a name it does not declare fails the build, and the error gives the fix:
6969

7070
```
71-
partials/postmeta.hbs reads "date", but does not declare it. Add {{#expect date}} at the top of the partial.
71+
partials/postmeta.hbs reads "date", but does not declare it; add {{#expect date}} at the top of the partial
7272
```
7373

7474
See [Templates](/templates/#syntax) for the syntax.

‎docs/content/quick-start.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ bun run build
3232
```
3333

3434
<bongo:note>
35-
The `bongo` command starts with Node, and image processing needs Bun. To resize images, run the scripts through Bun: `bun --bun run dev` and `bun --bun run build`. See [Images](/images/#bun-runtime).
35+
The `bongo` command starts with Node. Image processing needs Bun, and so does your own code when it calls a Bun API, such as `Bun.markdown`. For either one, run the scripts through Bun: `bun --bun run dev` and `bun --bun run build`. See [Images](/images/#bun-runtime).
3636
</bongo:note>
3737

3838
## Starter files

‎packages/bongo/readme.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,7 @@ Each attribute after `src` is an argument. A value is a quoted string, a bare va
493493

494494
A partial in `partials/` gets its arguments, the config values (`$site`, `$utils`, `$data`, `$assets`), and the `$page`, `$pages`, `$section`, and `$tags` of the page that renders it. An argument with the same name wins: `{{#partial src="postmeta" $page=post}}`. A `$partials` function gets only its arguments. A partial that a Markdown element or a loader calls runs when the content file loads, before any page renders, so it gets no page values.
495495

496-
A `.hbs` partial declares the arguments that it reads with `{{#expect title, date}}`. `$slot`, the inner HTML of a Markdown element, is always declared. A partial that reads a name it does not declare fails the build with `partials/card.hbs reads "title", but does not declare it. Add {{#expect title}} at the top of the partial.`
496+
A `.hbs` partial declares the arguments that it reads with `{{#expect title, date}}`. `$slot`, the inner HTML of a Markdown element, is always declared. A partial that reads a name it does not declare fails the build with `partials/card.hbs reads "title", but does not declare it; add {{#expect title}} at the top of the partial`.
497497

498498
## Template Variables
499499

@@ -615,6 +615,8 @@ bun --bun run build # for a "build": "bongo build" script
615615

616616
Under Node, bongo copies each image as it is, under a hashed name, and prints one notice for each build. The build does not fail. It adds `width` and `height` only to SVG and GIF images.
617617

618+
Your own code needs Bun too when it calls a Bun API, such as `Bun.markdown` in a `$utils` function or in the config. Under Node, such code fails the build, and the error says to run bongo with Bun.
619+
618620
JPEG, PNG, and WebP files are encoded with the same codecs on every platform, so a build makes the same bytes on macOS, Linux, and Windows.
619621

620622
bongo adds `width` and `height` to images. If your CSS limits the width of images, also give them `height: auto`, so they keep their aspect ratio:

‎packages/bongo/src/build.test.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -896,7 +896,23 @@ describe('partials', () => {
896896
'content/index.html': '',
897897
});
898898
try {
899-
await expect(build({ cwd: root })).rejects.toThrow('partials/blog/meta.hbs reads "date", but does not declare it. Add {{#expect date}} at the top of the partial.');
899+
await expect(build({ cwd: root })).rejects.toThrow('partials/blog/meta.hbs reads "date", but does not declare it; add {{#expect date}} at the top of the partial, rendering content/index.html');
900+
} finally {
901+
await rm(root, { recursive: true, force: true });
902+
}
903+
});
904+
905+
test('a name that a function the partial calls cannot find is not a name of the partial', async () => {
906+
let root = await site({
907+
'bongo.config.ts': `export default { $site: { url: 'https://example.com/', title: 'T', lang: 'en' }, $utils: { lost: () => nowhere } };`,
908+
'partials/p.hbs': '<p>{{ $utils.lost() }}</p>',
909+
'layouts/html.hbs': '{{#partial src="p"}}',
910+
'content/index.html': '',
911+
});
912+
try {
913+
let err = await build({ cwd: root }).catch(e => e);
914+
expect(err.message).toStartWith('nowhere is not defined, rendering content/index.html');
915+
expect(err.message).not.toContain('{{#expect');
900916
} finally {
901917
await rm(root, { recursive: true, force: true });
902918
}

‎packages/bongo/src/build.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,8 @@ export async function build(argv: Argv, opts: BuildOptions = {}): Promise<void>
233233
await sink?.clear().catch(() => {});
234234
if (sink) MEMOS.delete(sink);
235235
}
236-
throw err;
236+
let fix = utils.runtime(err, argv.dev ? 'dev' : 'build');
237+
throw fix && err instanceof Error ? new Error(`${err.message}\n${fix}`, { cause: err }) : err;
237238
} finally {
238239
watch.stop();
239240
}

‎packages/bongo/src/cli.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,31 @@ describe('bongo cli', () => {
105105
}
106106
}, 30_000);
107107

108+
test('under Node, says to run with Bun when the config, a layout, or a partial calls a Bun API', async () => {
109+
let root = await site();
110+
let fix = 'bongo runs in Node, which has no Bun APIs; run it with Bun: bun --bun bongo build';
111+
try {
112+
await writeFile(join(root, 'bongo.config.mjs'), `export default { $site: { url: 'https://example.com/', title: 'T', lang: 'en' }, $utils: { md: s => Bun.markdown.html(s) } };`);
113+
await writeFile(join(root, 'layouts/html.hbs'), '{{{ $utils.md("x") }}}');
114+
let layout = await run(['build', '-C', root]);
115+
expect(layout.code).toBe(1);
116+
expect(layout.out).toContain('Bun is not defined, rendering content/index.html → layouts/html.hbs\n' + fix);
117+
118+
await mkdir(join(root, 'partials'));
119+
await writeFile(join(root, 'partials/p.hbs'), '{{{ $utils.md("x") }}}');
120+
await writeFile(join(root, 'layouts/html.hbs'), '{{#partial src="p"}}');
121+
let partial = await run(['build', '-C', root]);
122+
expect(partial.out).toContain(fix);
123+
expect(partial.out).not.toContain('{{#expect');
124+
125+
await writeFile(join(root, 'bongo.config.mjs'), `export default { $site: { url: 'https://example.com/', title: Bun.version, lang: 'en' } };`);
126+
let config = await run(['build', '-C', root]);
127+
expect(config.out).toContain(fix);
128+
} finally {
129+
await rm(root, { recursive: true, force: true });
130+
}
131+
}, 30_000);
132+
108133
test('sets NODE_ENV before it loads the config', async () => {
109134
let root = await site();
110135
try {

‎packages/bongo/src/dev.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,14 @@ export async function dev(argv: Argv) {
205205
if (flags.write) await sink.mirror(output.disk({ ...flags, dest: outdir(flags, next.config) }));
206206
} catch (err) {
207207
let failed = utils.cause(err, LoadError);
208-
let message = err instanceof Error ? err.message : String(err);
208+
let fix = utils.runtime(err, 'dev');
209+
let more = fix ? '\n' + fix : '';
210+
let message = (err instanceof Error ? err.message : String(err)) + more;
209211
failed?.files.forEach(file => tracked.add(file));
210212
stop();
211213
stop = await follow();
212214
log.error(message);
213-
report([failed ? failed.error : { message }]);
215+
report([failed ? { ...failed.error, message: failed.error.message + more } : { message }]);
214216
return false;
215217
}
216218

‎packages/bongo/src/utils/index.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,20 @@ export function cause<T extends Error>(err: unknown, type: new (...args: never[]
88
}
99
}
1010

11+
// V8 says "Bun is not defined"; JavaScriptCore says "Can't find variable: Bun"
12+
const NO_BUN = /^(?:Bun is not defined|Can't find variable: Bun)$/;
13+
14+
/**
15+
* How to fix an error from code that calls a Bun API while bongo runs in Node or Deno, or undefined for any other error.
16+
* @example let fix = utils.runtime(err, 'build');
17+
*/
18+
export function runtime(err: unknown, command: string): string | undefined {
19+
if (typeof Bun !== 'undefined') return;
20+
let missing = cause(err, ReferenceError);
21+
if (!missing || !NO_BUN.test(missing.message)) return;
22+
return `bongo runs in ${'Deno' in globalThis ? 'Deno' : 'Node'}, which has no Bun APIs; run it with Bun: bun --bun bongo ${command}`;
23+
}
24+
1125
export function debounce<T extends Function>(fn: T, delay: number): T {
1226
let timer: NodeJS.Timeout | null;
1327
// @ts-ignore

‎packages/bongo/src/utils/templates.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ const FILES: Map<string, string> = new Map;
3434

3535
// The registries that each layout ("layouts/html.hbs") and partial ("partials/nav") names in its source.
3636
const READS: Map<string, Read[]> = new Map;
37+
38+
// The source of each layout and partial, by the same names.
39+
const SOURCES: Map<string, string> = new Map;
3740
const REGISTRIES: Read[] = ['pages', 'section', 'tags'];
3841

3942
// The partials that render while a page renders; pages render one at a time.
@@ -168,6 +171,7 @@ export async function collect(argv: Required<Argv>, config: Context): Promise<vo
168171
Partials.clear();
169172
Layouts.clear();
170173
READS.clear();
174+
SOURCES.clear();
171175

172176
// Re-assign onto the exported const so ESM consumers see the new closures.
173177
Object.assign(blocks, made);
@@ -183,6 +187,7 @@ export async function collect(argv: Required<Argv>, config: Context): Promise<vo
183187
let file = join(dir, rel);
184188
let content = await fs.read(file, 'utf8');
185189
READS.set(name, reads(content));
190+
SOURCES.set(name, content);
186191
return tempura.compile(content, opts);
187192
} catch (err) {
188193
let type = parse(dir).name.slice(0, -1); // strip "s"
@@ -221,9 +226,11 @@ export async function collect(argv: Required<Argv>, config: Context): Promise<vo
221226
return await compiled(data, scope);
222227
} catch (err) {
223228
let found = err instanceof ReferenceError && UNDECLARED.exec(err.message);
224-
if (!found) throw err;
225-
let name = found[1] || found[2];
226-
throw new Error(`partials/${file.replace(/\\/g, '/')} reads "${name}", but does not declare it. Add {{#expect ${name}}} at the top of the partial.`, { cause: err });
229+
let name = found && (found[1] || found[2]);
230+
// a function that the partial calls can miss a name too, which the partial never names
231+
let named = name && new RegExp(`(?<![\\w$.])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(SOURCES.get('partials/' + key) ?? '');
232+
if (!named) throw err;
233+
throw new Error(`partials/${file.replace(/\\/g, '/')} reads "${name}", but does not declare it; add {{#expect ${name}}} at the top of the partial`, { cause: err });
227234
}
228235
};
229236
} else {

0 commit comments

Comments
 (0)