diff --git a/.changeset/index-list-bullets.md b/.changeset/index-list-bullets.md new file mode 100644 index 000000000..0fc26ec7e --- /dev/null +++ b/.changeset/index-list-bullets.md @@ -0,0 +1,5 @@ +--- +'@doc-kit/core': patch +--- + +Read `index` files whose list items start with `-` or `+`, not only `*` diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index f32a68b16..58826d4c6 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -10,46 +10,60 @@ on: concurrency: group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true + # Runs on main are the baselines pull requests compare against + cancel-in-progress: ${{ github.event_name == 'pull_request' }} permissions: contents: read jobs: + # A pull request runs the targets its changes can affect, and CodSpeed + # reports the others from the base's run + plan: + name: Plan + runs-on: ubuntu-latest + outputs: + targets: ${{ steps.affected.outputs.targets }} + steps: + - name: Setup environment + uses: nodejs/web-team/actions/setup-environment@4c0b18db11a8357664683d70ef1f27af08ecc766 + with: + use-version-file: true + pnpm: true + # A pull request's merge commit and its base + fetch-depth: 2 + + - name: Find affected targets + id: affected + env: + SINCE: ${{ github.event_name == 'pull_request' && 'HEAD^1' || '' }} + run: echo "targets=$(node bench/affected.mjs $SINCE)" >> "$GITHUB_OUTPUT" + benchmarks: - name: Benchmarks + name: ${{ matrix.target }} (${{ matrix.mode }}) + needs: plan + if: needs.plan.outputs.targets != '[]' runs-on: ubuntu-latest + timeout-minutes: 60 permissions: contents: read - id-token: write - env: - NODE_SHA: 768315cf7165e9ff9b636844b776488e9d1703fc + id-token: write # Uploads results to CodSpeed + strategy: + fail-fast: false + matrix: + target: ${{ fromJSON(needs.plan.outputs.targets) }} + mode: [simulation, memory] steps: - - name: Harden Runner - uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 - with: - egress-policy: audit - - name: Setup environment uses: nodejs/web-team/actions/setup-environment@4c0b18db11a8357664683d70ef1f27af08ecc766 with: use-version-file: true pnpm: true - - name: Checkout Node.js sources - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - repository: nodejs/node - ref: ${{ env.NODE_SHA }} - sparse-checkout: | - doc - lib - . - path: node - + # Valgrind can't reserve the address space V8 guards WebAssembly memory + # with, so bounds are checked inline instead - name: Run benchmarks - uses: CodSpeedHQ/action@af75f77f17a054769abefaa42fe8dc2975469b5f # v5.6.3 + uses: CodSpeedHQ/action@ca909ca8b60401c041f627a1d9117aa90dce9524 # v5.8.1 with: - mode: simulation,memory - run: node --run bench + mode: ${{ matrix.mode }} + run: node --disable-wasm-trap-handler bench/generate.bench.mjs ${{ matrix.target }} diff --git a/.oxlintrc.json b/.oxlintrc.json index 115ebace0..972cb4701 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -219,6 +219,12 @@ "es2026": true, "browser": true } + }, + { + "files": ["docs/showcase/*.js"], + "env": { + "commonjs": true + } } ] } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8b41d24fc..266621010 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -340,12 +340,14 @@ node --test packages/core/src/utils/__tests__/parser.test.mjs ## Benchmarks Generation speed and memory are measured with [CodSpeed](https://codspeed.io) -(`bench/generate.bench.mjs`), on one thread. The workflow checks `nodejs/node` -out at `NODE_SHA` into `./node`, and the suite reads that directory. It runs on -every pull request and reports CPU and memory there. +(`bench/generate.bench.mjs`), on one thread. Each target in +`bench/doc-kit.config.mjs` builds the [showcase](docs/showcase/index.md), which is also on the website. A +pull request measures only the targets its changes can affect +(`bench/affected.mjs`), and CodSpeed reports the others from the base's run. ```bash node --run bench +node --run bench -- html legacy-html ``` ## Code Quality diff --git a/bench/affected.mjs b/bench/affected.mjs new file mode 100644 index 000000000..1a41127f1 --- /dev/null +++ b/bench/affected.mjs @@ -0,0 +1,64 @@ +// Prints, as a JSON array, the targets of `doc-kit.config.mjs` that the changes +// since a commit can affect, or all of them without one. +// +// node bench/affected.mjs [commit] + +import { execFileSync } from 'node:child_process'; +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { loadGenerators } from '@doc-kit/core/generators/loader.mjs'; + +import config from './doc-kit.config.mjs'; + +const ROOT = join(import.meta.dirname, '..'); + +// Changes to these can affect every target +const SHARED = + /^(bench|docs\/showcase)\/|^(package\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|\.nvmrc|\.github\/workflows\/codspeed\.yml)$/; + +// Changes to these affect no target +const INERT = /(^|\/)__tests__\/|\.(md|d\.ts)$/; + +const [since] = process.argv.slice(2); +let affected = config.target; + +if (since) { + const changed = execFileSync( + 'git', + ['diff', '--name-only', '--no-renames', since], + { cwd: ROOT, encoding: 'utf-8' } + ) + .split('\n') + .filter(Boolean); + + if (!changed.some(file => SHARED.test(file))) { + const relevant = changed.filter(file => !INERT.test(file)); + + // Each workspace package's directory, by package name + const directories = new Map( + readdirSync(join(ROOT, 'packages')).map(dir => [ + JSON.parse( + readFileSync(join(ROOT, 'packages', dir, 'package.json'), 'utf-8') + ).name, + `packages/${dir}/`, + ]) + ); + + affected = []; + + for (const target of config.target) { + // The packages of the target's generator and of those it depends on + const generators = await loadGenerators([target]); + const owners = [...generators.keys()].map(specifier => + directories.get(specifier.split('/', 2).join('/')) + ); + + if (relevant.some(file => owners.some(dir => file.startsWith(dir)))) { + affected.push(target); + } + } + } +} + +console.log(JSON.stringify(affected)); diff --git a/bench/doc-kit.config.mjs b/bench/doc-kit.config.mjs new file mode 100644 index 000000000..0b4c56ae7 --- /dev/null +++ b/bench/doc-kit.config.mjs @@ -0,0 +1,31 @@ +import { join } from 'node:path'; + +const SHOWCASE = join(import.meta.dirname, '..', 'docs', 'showcase'); + +export default { + target: [ + 'json', + 'json-simple', + 'legacy-json', + 'legacy-html', + 'html', + 'llms-txt', + 'orama-db', + 'man-page', + 'addon-verify', + 'api-links', + ], + + global: { + input: [join(SHOWCASE, '*.md')], + index: join(SHOWCASE, 'index.md'), + }, + + 'ast-js': { + input: [join(SHOWCASE, '*.js')], + }, + + 'man-page': { + envVarsHeaderSlug: 'environment-variables', + }, +}; diff --git a/bench/generate.bench.mjs b/bench/generate.bench.mjs index f7972136a..c9f562e3e 100644 --- a/bench/generate.bench.mjs +++ b/bench/generate.bench.mjs @@ -1,5 +1,5 @@ -import { mkdir, rm } from 'node:fs/promises'; -import path from 'node:path'; +import { rm } from 'node:fs/promises'; +import { join } from 'node:path'; import { withCodSpeed } from '@codspeed/tinybench-plugin'; import createGenerator from '@doc-kit/core'; @@ -7,60 +7,46 @@ import logger from '@doc-kit/core/logger/index.mjs'; import { setConfig } from '@doc-kit/core/utils/configuration/index.mjs'; import { Bench } from 'tinybench'; -logger.setLogLevel('warn'); - -const node = path.join(import.meta.dirname, '../node'); -const at = (...parts) => path.join(node, ...parts); +import config from './doc-kit.config.mjs'; -const shared = { - threads: 1, - index: at('doc/api/index.md'), - typeMap: at('doc/type-map.json'), - changelog: at('CHANGELOG.md'), -}; - -const docs = at('doc/api/*.md'); +logger.setLogLevel('warn'); -const targets = [ - ['json', docs], - ['json-simple', docs], - ['legacy-json', docs], - ['legacy-html', docs], - ['html', docs], - ['llms-txt', docs], - ['orama-db', docs], - ['man-page', at('doc/api/cli.md')], - ['addon-verify', at('doc/api/addons.md')], - ['api-links', at('lib/*.js')], -]; +const configFile = join(import.meta.dirname, 'doc-kit.config.mjs'); +const targets = process.argv.length > 2 ? process.argv.slice(2) : config.target; const bench = withCodSpeed( new Bench({ warmup: false, iterations: 1, time: 0, throws: true }) ); -for (const [name, input] of targets) { - const output = path.join(import.meta.dirname, '../out', name); +for (const name of targets) { + const output = join(import.meta.dirname, '../out', name); let runGenerators; - let config; + let options; + let start; - bench.add(name, () => runGenerators(config), { + // tinybench calls a function that isn't `async` to see if it returns a + // promise, before `beforeAll` has set `runGenerators` + bench.add(name, async () => runGenerators(options), { beforeAll: async () => { - await rm(output, { recursive: true, force: true }); - await mkdir(output, { recursive: true }); ({ runGenerators } = createGenerator()); - config = await setConfig({ - ...shared, + // CodSpeed's CPU simulation runs one thread at a time + options = await setConfig({ + configFile, target: [name], - input: [input], output, + threads: 1, }); }, + beforeEach: () => { + start = performance.now(); + }, + afterEach: () => { + console.log( + `${name}: ${((performance.now() - start) / 1000).toFixed(2)}s` + ); + }, afterAll: () => rm(output, { recursive: true, force: true }), }); } await bench.run(); - -if (process.env.CODSPEED_ENV === undefined) { - console.table(bench.table()); -} diff --git a/docs/showcase/addons.md b/docs/showcase/addons.md new file mode 100644 index 000000000..cdb397e63 --- /dev/null +++ b/docs/showcase/addons.md @@ -0,0 +1,124 @@ +# C++ addons + + + + + +A kitten's purr is synthesized in C++. These examples build a native addon +that purrs. + +## Hello world + +The addon exports one function, `purr()`, which returns a string: + +```cpp +// purr.cc +#include + +namespace kittens { + +using v8::FunctionCallbackInfo; +using v8::Isolate; +using v8::Local; +using v8::Object; +using v8::String; +using v8::Value; + +void Purr(const FunctionCallbackInfo& args) { + Isolate* isolate = args.GetIsolate(); + args.GetReturnValue().Set( + String::NewFromUtf8(isolate, "purr").ToLocalChecked()); +} + +void Initialize(Local exports) { + NODE_SET_METHOD(exports, "purr", Purr); +} + +NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) + +} // namespace kittens +``` + +Build it with a `binding.gyp` next to the source: + +```json displayName="binding.gyp" +{ + "targets": [ + { + "target_name": "addon", + "sources": ["purr.cc"] + } + ] +} +``` + +Then load it from JavaScript: + +```js +// test.js +const addon = require('./build/Release/addon'); + +console.log(addon.purr()); +// Prints: 'purr' +``` + +## Function arguments + +This one takes a number of seconds and purrs once for each: + +```cpp +// purr.cc +#include +#include + +namespace kittens { + +using v8::Exception; +using v8::FunctionCallbackInfo; +using v8::Isolate; +using v8::Local; +using v8::Object; +using v8::String; +using v8::Value; + +void Purr(const FunctionCallbackInfo& args) { + Isolate* isolate = args.GetIsolate(); + + if (args.Length() < 1 || !args[0]->IsNumber()) { + isolate->ThrowException(Exception::TypeError( + String::NewFromUtf8(isolate, "Expected seconds").ToLocalChecked())); + return; + } + + int seconds = args[0].As()->Value(); + std::string purr; + + for (int i = 0; i < seconds; i++) { + purr += i == 0 ? "purr" : " purr"; + } + + args.GetReturnValue().Set( + String::NewFromUtf8(isolate, purr.c_str()).ToLocalChecked()); +} + +void Initialize(Local exports) { + NODE_SET_METHOD(exports, "purr", Purr); +} + +NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) + +} // namespace kittens +``` + +```js +// test.js +const assert = require('node:assert'); +const addon = require('./build/Release/addon'); + +assert.strictEqual(addon.purr(3), 'purr purr purr'); +assert.throws(() => addon.purr('loud'), TypeError); +``` + +> [!NOTE] +> An addon is compiled for one version of Node.js. Rebuild it with +> `node-gyp rebuild` after upgrading. diff --git a/docs/showcase/cli.md b/docs/showcase/cli.md new file mode 100644 index 000000000..7a6106a75 --- /dev/null +++ b/docs/showcase/cli.md @@ -0,0 +1,119 @@ +# Command-line API + + + + + +The `kittens` command adopts and cares for kittens from a terminal. + +## Synopsis + +`kittens [options] [name]` + +```console +$ kittens --breed=siamese Mittens +Welcome home, Mittens! +``` + +## Options + + + +### `-b`, `--breed=breed` + + + +The breed to adopt, one of [`kittens.breeds`][]. **Default:** `tabby`. + +### `--age=weeks` + + + +The kitten's age, in weeks. + +```bash +kittens --age=10 Socks +``` + +### `--litter=count` + + + +> Stability: 1 - Experimental + +Adopts `count` kittens from one litter, as [`kittens.litter()`][] does. + +### `--feed-all` + + + +> Stability: 0 - Deprecated: Feed each kitten instead. + +Feeds every kitten before exiting. + +### `-h`, `--help` + + + +Prints the options and exits. + +### `-v`, `--version` + + + +Prints the version of `kittens` and exits. + +## Environment variables + +### `KITTENS_HOME=dir` + + + +Where adopted kittens' records are kept. **Default:** `~/.kittens`. + +### `KITTENS_OPTIONS=options` + + + +Options to apply before the command line's, separated by spaces: + +```bash +KITTENS_OPTIONS="--breed=persian --age=9" kittens Fluffy +``` + +### `NO_COLOR=` + +Turns off colors in the output, as described at . + +## Exit codes + +| Code | Meaning | +| ---: | --------------------------------- | +| `0` | The kitten went home. | +| `1` | The adoption failed. | +| `9` | An option was invalid or missing. | + +[`kittens.breeds`]: kittens.md#kittensbreeds +[`kittens.litter()`]: kittens.md#kittenslittercount-options diff --git a/docs/showcase/globals.md b/docs/showcase/globals.md new file mode 100644 index 000000000..56b5299df --- /dev/null +++ b/docs/showcase/globals.md @@ -0,0 +1,52 @@ +# Global objects + + + + + +Once the `kittens` module is loaded, these are available everywhere, with no +`import` or `require()`. + +## Class: `Kitten` + + + +The [`kittens.Kitten`][] class. + +## `adoptKitten(name[, options])` + + + +- `name` {string|null} +- `options` {Object} +- Returns: {Promise} + +The same function as [`kittens.adopt()`][]. + +## `catnip` + + + +> Stability: 1 - Experimental + +- Type: {Symbol} + +A well-known symbol. A kitten treats an object with a `[catnip]` method as a +toy. + +```js +const ball = { + [catnip]() { + return 'bounce'; + }, +}; +``` + +[`kittens.Kitten`]: kittens.md#class-kittenskitten +[`kittens.adopt()`]: kittens.md#kittensadoptname-options diff --git a/docs/showcase/index.md b/docs/showcase/index.md new file mode 100644 index 000000000..4052bd705 --- /dev/null +++ b/docs/showcase/index.md @@ -0,0 +1,8 @@ +# Showcase + + + +- [Kittens](kittens.md) +- [Command-line API](cli.md) +- [C++ addons](addons.md) +- [Global objects](globals.md) diff --git a/docs/showcase/kittens.js b/docs/showcase/kittens.js new file mode 100644 index 000000000..e8ddb99b5 --- /dev/null +++ b/docs/showcase/kittens.js @@ -0,0 +1,54 @@ +'use strict'; + +const BREEDS = ['mainecoon', 'persian', 'siamese', 'tabby']; + +class Kitten extends EventTarget { + constructor(name, options = {}) { + super(); + this.name = name; + this.age = options.age ?? 12; + this.breed = options.breed ?? 'tabby'; + } + + static from(record) { + return new Kitten(record.name, { breed: record.breed }); + } + + feed(food, amount = 1, unit = 'g', callback) { + callback?.(food, amount, unit); + return true; + } + + pet(...spots) { + if (spots.length > 0) { + this.dispatchEvent(new Event('purr')); + } + } + + toJSON() { + return { name: this.name, breed: this.breed }; + } +} + +function adopt(name, options = {}) { + if ((options.age ?? 12) < 8) { + const error = new RangeError('A kitten must be at least 8 weeks old'); + error.code = 'ERR_KITTEN_TOO_YOUNG'; + return Promise.reject(error); + } + + return Promise.resolve(new Kitten(name ?? 'Mittens', options)); +} + +function litter(count, options) { + return Promise.all( + Array.from({ length: count }, (_, i) => adopt(`Kitten ${i + 1}`, options)) + ).then(kittens => new Map(kittens.map(kitten => [kitten.name, kitten]))); +} + +module.exports = { + adopt, + breeds: BREEDS, + Kitten, + litter, +}; diff --git a/docs/showcase/kittens.md b/docs/showcase/kittens.md new file mode 100644 index 000000000..25b781bdb --- /dev/null +++ b/docs/showcase/kittens.md @@ -0,0 +1,466 @@ +# Kittens + + + +> Stability: 2 - Stable + + + + + + + +The `kittens` module adopts, feeds and pets kittens. + +```bash displayName="npm" +npm install kittens +``` + +```bash displayName="pnpm" +pnpm add kittens +``` + +It can be accessed using: + +```mjs +import { adopt } from 'kittens'; + +const kitten = await adopt('Mittens', { breed: 'tabby' }); +kitten.pet('chin'); +``` + +```cjs +const { adopt } = require('kittens'); + +adopt('Mittens', { breed: 'tabby' }).then(kitten => { + kitten.pet('chin'); +}); +``` + +Every kitten is a [`kittens.Kitten`][], an {EventTarget} that dispatches +[`'purr'`][] and [`'nap'`][] events. Names are picked with getrandom(2) when +you don't give one, and the [command-line tool](cli.md) wraps the same API. + +> [!TIP] +> Kittens sleep up to 20 hours a day. Adopt in the evening, when they're awake. + +## Adoption at a glance + +| Breed | Energy | Lap time | Grooming | +| ------------- | ------ | -------: | ------------ | +| `'tabby'` | High | 20 min | Weekly | +| `'siamese'` | Vocal | 45 min | Weekly | +| `'persian'` | Calm | 2 h | Daily | +| `'mainecoon'` | Gentle | 1 h | Twice a week | + +> [!NOTE] +> Lap time is the median over a hundred naps, measured at room temperature. + +## `kittens.adopt(name[, options])` + + + +- `name` {string|null} The kitten's name. When `null`, a name is picked at + random. +- `options` {Object} + - `breed` {string} One of [`kittens.breeds`][]. **Default:** `'tabby'`. + - `age` {number} Age in weeks, at least `8`. **Default:** `12`. + - `toys` {string[]} Toys that come with the kitten. **Default:** `[]`. + - `vet` {Object} Where to book checkups. + - `name` {string} The clinic's name. + - `phone` {string} A phone number, in E.164 format. + - `signal` {AbortSignal} Cancels the adoption. +- Returns: {Promise} Fulfills with the kitten once its + paperwork is done. + +Adopts a kitten. The promise rejects with an `ERR_KITTEN_TOO_YOUNG` error when +`options.age` is under `8`, and with an `AbortError` when `options.signal` +aborts first. + +```mjs +import { adopt } from 'kittens'; + +const controller = new AbortController(); +setTimeout(() => controller.abort(), 1000); + +try { + const kitten = await adopt(null, { + breed: 'siamese', + toys: ['feather', 'laser'], + signal: controller.signal, + }); + console.log(`Welcome home, ${kitten.name}!`); +} catch (error) { + if (error.name === 'AbortError') { + console.log('Adoption canceled.'); + } +} +``` + +```cjs +const { adopt } = require('kittens'); + +const controller = new AbortController(); +setTimeout(() => controller.abort(), 1000); + +adopt(null, { + breed: 'siamese', + toys: ['feather', 'laser'], + signal: controller.signal, +}) + .then(kitten => console.log(`Welcome home, ${kitten.name}!`)) + .catch(error => { + if (error.name === 'AbortError') { + console.log('Adoption canceled.'); + } + }); +``` + +> [!IMPORTANT] +> A kitten under eight weeks of age stays with its mother. Pass `age` as a +> number of weeks, not months. + +## `kittens.breeds` + + + +- Type: {string[]} + +The breeds [`kittens.adopt()`][] accepts, in alphabetical order. + +## `kittens.litter(count[, options])` + + + +> Stability: 1 - Experimental. The size of a litter may change between minor +> releases, and so may the order of the kittens in it. + +- `count` {number} How many kittens to adopt, from `1` to `6`. +- `options` {Object} The options of [`kittens.adopt()`][], applied to every + kitten. +- Returns: {Promise>} Fulfills with the kittens, + keyed by name. + +Adopts several kittens from one litter, which keeps siblings together. + +## `kittens.watch(kitten, listener)` + + + +> Stability: 1.1 - Active development + +- `kitten` {kittens.Kitten} +- `listener` {(event: Event) => void} Called with each event the kitten + dispatches. +- Returns: {Function} Stops watching. + +Calls `listener` for every event `kitten` dispatches, whatever its type. + +## `kittens.trackSleep(kitten[, interval])` + + + +> Stability: 1.0 - Early development + +- `kitten` {kittens.Kitten} +- `interval` {number} How often to check on the kitten, in milliseconds. + **Default:** `60000`. +- Returns: {AsyncIterable} Yields the minutes of each nap. + +## `kittens.microchip(kitten)` + + + +> Stability: 1.2 - Release candidate + +- `kitten` {kittens.Kitten} +- Returns: {string} The chip's 15-digit identifier. + +## `kittens.feedAll(food)` + + + +> Stability: 0 - Deprecated: Use [`kitten.feed()`][] on each kitten instead. + +- `food` {string} + +Feeds every kitten adopted by this process. + +> [!WARNING] +> Kittens eat at their own pace. Feeding them all at once leaves the slowest +> one hungry. + +## `kittens.callback(name, callback)` + + + +> Stability: 3 - Legacy: Use [`kittens.adopt()`][] instead, which returns a +> {Promise}. + +- `name` {string} +- `callback` {Function} + - `err` {Error|null} + - `kitten` {kittens.Kitten} + +The callback form of [`kittens.adopt()`][], from before it returned a promise. + +## `kittens.declaw(kitten)` + + + +> Stability: 0 - Deprecated + +> [!CAUTION] +> Declawing harms kittens. This method has no replacement. + +## Class: `kittens.Kitten` + + + +- Extends: {EventTarget} + +A kitten. Create one with [`kittens.adopt()`][] or `new kittens.Kitten()`. + +### `new kittens.Kitten(name[, options])` + + + +- `name` {string} +- `options` {Object} The options of [`kittens.adopt()`][]. + +### Static method: `kittens.Kitten.from(record)` + + + +- `record` {Object} A record from a shelter's database. + - `name` {string} + - `born` {Date} + - `breed` {string} +- Returns: {kittens.Kitten} + +Creates a kitten from a shelter record. A `record.born` less than eight weeks +ago throws a {RangeError}. + +```js +const { Kitten } = require('kittens'); + +const kitten = Kitten.from({ + name: 'Socks', + born: new Date('2025-01-15'), + breed: 'persian', +}); +``` + +### Event: `'purr'` + + + +- `event` {Event} + +Dispatched while the kitten is content, at most once a second. + +### Event: `'nap'` + + + +- `event` {CustomEvent} + - `detail` {Object} + - `minutes` {number} How long the nap lasted. + +Dispatched when the kitten wakes from a nap. + +```mjs +import { adopt } from 'kittens'; + +const kitten = await adopt('Whiskers'); +kitten.addEventListener('nap', ({ detail }) => { + console.log(`Slept for ${detail.minutes} minutes`); +}); +``` + +### `kitten.name` + + + +- Type: {string} + +The kitten's name. Renaming a kitten doesn't change its microchip. + +### `kitten.age` + + + +- Type: {number} + +The kitten's age, in weeks. + +### `kitten.feed(food[, amount[, unit]][, callback])` + + + +- `food` {string|Buffer} What to serve. +- `amount` {number} **Default:** `1`. +- `unit` {string} `'g'` or `'oz'`. **Default:** `'g'`. +- `callback` {Function} Called once the bowl is empty. +- Returns: {boolean} `false` when the kitten isn't hungry. + +Fills the kitten's bowl. + +```diff +- kitten.feed('tuna', 50); ++ kitten.feed('tuna', 50, 'g'); +``` + +### `kitten.pet([...spots])` + + + +- `...spots` {string} Where to pet the kitten, such as `'chin'` or `'ears'`. + **Default:** `'head'`. +- Returns: {undefined} + +Pets the kitten. A content kitten dispatches a [`'purr'`][] event. + +### `kitten.toJSON()` + + + +- Returns: {Object} A record that [`kittens.Kitten.from()`][] reads back. + +```json displayName="Mittens.json" +{ + "name": "Mittens", + "born": "2025-03-02T00:00:00.000Z", + "breed": "tabby" +} +``` + +### `kitten[Symbol.asyncIterator]()` + + + +- Returns: {AsyncIterator} + +Iterates over the events the kitten dispatches. + +```mjs +import { adopt } from 'kittens'; + +for await (const event of await adopt('Shadow')) { + console.log(event.type); +} +``` + +### `kitten.whiskers` + + + +A kitten has about 24 whiskers, and it doesn't like them touched. They aren't +exposed as a property. + +## Promises API + + + +The same functions are also exported from `kittens/promises`. + +```mjs +import { adopt } from 'kittens/promises'; +``` + +```cjs +const { adopt } = require('kittens/promises'); +``` + +### `kittensPromises.adopt(name[, options])` + + + +- `name` {string|null} +- `options` {Object} The options of [`kittens.adopt()`][]. +- Returns: {Promise} + +The same function as [`kittens.adopt()`][]. + +## TypeScript + +The package ships its own types: + +```ts displayName="adopt.ts" +import { adopt, type Kitten } from 'kittens'; + +const kitten: Kitten = await adopt('Luna', { breed: 'mainecoon' }); +``` + +[`'nap'`]: #event-nap +[`'purr'`]: #event-purr +[`kitten.feed()`]: #kittenfeedfood-amount-unit-callback +[`kittens.Kitten`]: #class-kittenskitten +[`kittens.Kitten.from()`]: #static-method-kittenskittenfromrecord +[`kittens.adopt()`]: #kittensadoptname-options +[`kittens.breeds`]: #kittensbreeds diff --git a/packages/core/src/parsers/__tests__/markdown.test.mjs b/packages/core/src/parsers/__tests__/markdown.test.mjs index 71c0d681b..60eed1b5b 100644 --- a/packages/core/src/parsers/__tests__/markdown.test.mjs +++ b/packages/core/src/parsers/__tests__/markdown.test.mjs @@ -37,8 +37,8 @@ describe('parseIndex', () => { # API Documentation * [Assert](assert.md) - * [Buffer](buffer.md) - * [Child Process](child_process.md) + - [Buffer](buffer.md) + + [Child Process](child_process.md) * [Something](not-a-markdown-file) `; diff --git a/packages/core/src/parsers/markdown.mjs b/packages/core/src/parsers/markdown.mjs index 05286013f..26c3fd5dc 100644 --- a/packages/core/src/parsers/markdown.mjs +++ b/packages/core/src/parsers/markdown.mjs @@ -8,7 +8,7 @@ import { loadFromURL } from '#utils/loaders.mjs'; const NODE_VERSIONS_REGEX = /\* \[Node\.js ([0-9.]+)\]\S+ (.*)\r?\n/g; // A ReGeX for retrieving the list items in the index document -const LIST_ITEM_REGEX = /\* \[(.*?)\]\((.*?)\.md\)/g; +const LIST_ITEM_REGEX = /[*+-] \[(.*?)\]\((.*?)\.md\)/g; // A ReGeX for checking if a Node.js version is an LTS release const NODE_LTS_VERSION_REGEX = /Long Term Support/i; diff --git a/scripts/build-docs-content.mjs b/scripts/build-docs-content.mjs index 0e5c6fd64..ddae287c1 100644 --- a/scripts/build-docs-content.mjs +++ b/scripts/build-docs-content.mjs @@ -6,6 +6,7 @@ // docs/*.md the authored pages, guides, and reference docs // www/pages/*.mdx the site's own pages, such as the home page // docs/contributing/*.md repo-contributor docs, kept under `contributing/` +// docs/showcase/*.md the showcase, kept under `showcase/` // packages/*/README.md package READMEs, written to `packages/.md` // packages/*/src/{,generators/}*/README.md // per-generator config reference (core nests its @@ -17,7 +18,7 @@ // invoking the `html` generator against it. import { glob, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; -import { basename, dirname, join } from 'node:path'; +import { basename, dirname, join, relative } from 'node:path'; const ROOT = join(import.meta.dirname, '..'); const CONTENT = join(ROOT, 'www', 'content'); @@ -25,8 +26,8 @@ const CONTENT = join(ROOT, 'www', 'content'); const SOURCES = [ { pattern: '{docs,www/pages}/*.{md,mdx}', rename: basename }, { - pattern: 'docs/contributing/*.md', - rename: file => `contributing/${basename(file)}`, + pattern: 'docs/{contributing,showcase}/*.md', + rename: file => relative('docs', file), }, { pattern: 'packages/*/README.md', diff --git a/www/doc-kit.config.mjs b/www/doc-kit.config.mjs index d32d3edd2..115b757b1 100644 --- a/www/doc-kit.config.mjs +++ b/www/doc-kit.config.mjs @@ -199,6 +199,16 @@ export default { { label: 'Markdown specification', link: '/specification' }, ], }, + { + groupName: 'Showcase', + items: [ + { label: 'Overview', link: '/showcase/index' }, + { label: 'Kittens', link: '/showcase/kittens' }, + { label: 'Command-line API', link: '/showcase/cli' }, + { label: 'C++ addons', link: '/showcase/addons' }, + { label: 'Global objects', link: '/showcase/globals' }, + ], + }, { groupName: 'Generators', items: generatorItems }, { groupName: 'Under the hood', items: stageItems }, {