Skip to content
5 changes: 5 additions & 0 deletions .changeset/stream-pages.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@doc-kit/generator-react': minor
---

`jsx-ast` and `html` stream their input: with more than one thread, page building and rendering overlap with the generators before them. `html` bundles as soon as every page's metadata is known, and renders pages as they are built. Streaming leaves the generated files unchanged, but `jsx-ast` now yields pages in the order their entries arrive, not the order the site lists them, and, once every page has arrived, a `{ manifest }` item listing their heads in the order the site lists them, the synthetic pages last. Bundler adapters' `compile` can now be called before and while `buildServer` and `buildClient` run.
15 changes: 15 additions & 0 deletions packages/core/src/__tests__/caching.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,21 @@ describe('caching', () => {
strictEqual(iterations, 1);
});

it('should stream a result collected whole as its only chunk', async () => {
const cache = createCache();

async function* gen() {
yield [1];
yield [2];
}

cache.store('a', gen());

const stream = await cache.stream('a', { whole: true });

deepStrictEqual(await Array.fromAsync(stream), [[1, 2]]);
});

it('should stream a non-streaming result as a single chunk', async () => {
const cache = createCache();

Expand Down
55 changes: 41 additions & 14 deletions packages/core/src/caching.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
'use strict';

import logger from './logger/index.mjs';
import { once } from './utils/generators.mjs';
import { isAsyncIterable } from './utils/misc.mjs';
import { createTee } from './utils/tee.mjs';

const cachingLogger = logger.child('caching');

/**
* Gives a value as the single chunk of an async generator.
*
* @template T
* @param {T} value
* @returns {AsyncGenerator<T>}
*/
async function* once(value) {
yield value;
}

/**
* Collects all values from an async generator into a flat array.
* Each yielded chunk is spread into the results array.
Expand Down Expand Up @@ -91,6 +101,25 @@ export const createCache = () => {
return tees.get(name);
};

/**
* Collects a streamed result into one array, shared by every consumer that
* collects it.
*
* @param {string} name - Cache key (resolved generator specifier)
* @param {AsyncGenerator<unknown[]>} generator - The result
* @returns {Promise<unknown[]>}
*/
const collect = (name, generator) => {
if (!collections.has(name)) {
collections.set(
name,
collectAsyncGenerator(teeOf(name, generator).read())
);
}

return collections.get(name);
};

/**
* Counts a read, evicting the result once every expected consumer has read it.
*
Expand Down Expand Up @@ -188,15 +217,7 @@ export const createCache = () => {
let value = result;

if (isAsyncIterable(result)) {
// Consumers that collect it share one array, read like a stream
if (!collections.has(name)) {
collections.set(
name,
collectAsyncGenerator(teeOf(name, result).read())
);
}

value = await collections.get(name);
value = await collect(name, result);
}

release(name);
Expand Down Expand Up @@ -236,17 +257,23 @@ export const createCache = () => {
* reading, and this counts as one of its reads.
*
* @param {string} name - Cache key (resolved generator specifier) to stream
* @param {{ whole?: boolean }} [options] - With `whole`, a streamed result
* is collected first and given as its only chunk
* @returns {Promise<AsyncIterable<unknown[]>>}
*/
stream: async name => {
stream: async (name, { whole = false } = {}) => {
const result = await results[name];

let reader;

if (isAsyncIterable(result)) {
reader = teeOf(name, result).read();
} else {
if (!isAsyncIterable(result)) {
reader = once(result);
} else if (whole) {
const value = await collect(name, result);

reader = once(value);
} else {
reader = teeOf(name, result).read();
}

release(name);
Expand Down
9 changes: 1 addition & 8 deletions packages/core/src/generators.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { resolvePipeline } from './generators/pipeline.mjs';
import logger from './logger/index.mjs';
import createWorkerPool from './threading/index.mjs';
import createParallelWorker from './threading/parallel.mjs';
import { once } from './utils/generators.mjs';
import { loadMarkdownPlugins } from './utils/markdown/plugins.mjs';
import { isAsyncIterable } from './utils/misc.mjs';

Expand Down Expand Up @@ -46,16 +45,10 @@ const createGenerator = () => {
return cache.consume(dependsOn);
}

if (threads > 1) {
return cache.stream(dependsOn);
}

// With one thread nothing runs alongside, so streaming would only keep
// every stage's data alive at once: the input is collected whole first,
// and given as its only chunk
const whole = await cache.consume(dependsOn);

return once(whole);
return cache.stream(dependsOn, { whole: threads === 1 });
};

/**
Expand Down
9 changes: 0 additions & 9 deletions packages/core/src/utils/__tests__/generators.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
getVersionFromSemVer,
coerceSemVer,
getCompatibleVersions,
once,
} from '../generators.mjs';

describe('getEntryDescription', () => {
Expand Down Expand Up @@ -139,11 +138,3 @@ describe('getCompatibleVersions', () => {
assert.equal(result.length, 2);
});
});

describe('once', () => {
it('gives a value as the only chunk', async () => {
const chunks = await Array.fromAsync(once([1, 2]));

assert.deepEqual(chunks, [[1, 2]]);
});
});
11 changes: 0 additions & 11 deletions packages/core/src/utils/generators.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,6 @@ export const groupNodesByModule = nodes => {
return Map.groupBy(nodes, node => node.api);
};

/**
* Gives a value as the single chunk of an async generator.
*
* @template T
* @param {T} value
* @returns {AsyncGenerator<T>}
*/
export async function* once(value) {
yield value;
}

/**
* Parses the SemVer string into a Node.js-alike version
*
Expand Down
9 changes: 6 additions & 3 deletions packages/react/src/html/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -544,16 +544,19 @@ The `bundler` option takes a small adapter, so the site can be built with Vite

An adapter is an object with three methods. The generator calls `buildServer`
and `buildClient` once each and `compile` once per page, then renders the pages
from the compiled modules across the worker threads.
from the compiled modules across the worker threads. Pages are compiled as they
arrive, so `compile` can run before `buildServer`, and while either build still
runs: it must leave the module's imports as they are, as the library they point
to may not exist yet, and must not depend on the builds.

- `buildServer(options)` {Function} Bundles the component library for Node.js
and returns a promise of the `file:` URL of the built module.
- `entry` {string} The library's source: re-exports of every component a
page may render, Preact's `h` and `Fragment`, and `renderToStringAsync`.
- `virtualImports` {Object} In-memory modules to make available, by module
ID, `#theme/config` included.
- `outDir` {string} A temporary directory to write the library to, which the
generator removes afterwards.
- `outDir` {string} An empty temporary directory to write the library to,
which the generator removes afterwards.
- `config` {Object} The resolved `html` configuration.
- `compile(code, fileName)` {Function} Turns one page module, written in JSX,
into plain JavaScript Node.js can import, and returns a promise of it.
Expand Down
Loading
Loading