zcap-spec-examples - v0.2.0
    Preparing search index...

    Module zcap-spec-examples

    Extract the code examples out of the zcap-spec — or any ReSpec document — as structured data.

    This module is both a command-line tool and a small library with no runtime dependencies. If you are here to use the JavaScript API, you almost certainly want extractExamples, and then parseExampleContent to read what it gives back.

    Give extractExamples a response, a stream, or a string of HTML, and get ZcapSpecExample objects back one at a time:

    import { extractExamples } from "zcap-spec-examples";

    const response = await fetch("https://w3c-ccg.github.io/zcap-spec/v0.4.0-draft/");

    for await (const example of extractExamples(response)) {
    console.log(example.name); // "example-1"
    console.log(example.url); // "https://w3c-ccg.github.io/zcap-spec/#example-1"
    console.log(example.mediaType); // "application/jsonc"
    }

    The response body is streamed: each example is yielded as soon as its closing tag arrives, and the document is never held in memory as a whole. Pass a string, a ReadableStream, or any async iterable of chunks instead if you prefer. If you already have the HTML as a string and want an array back, use extractExamplesFromHtml.

    Do not call JSON.parse(example.content). Most zcap-spec examples are annotated with // comments, which makes them JSONC, not JSON — that is what the "application/jsonc" media type means, and JSON.parse throws on them.

    Use parseExampleContent, which handles both and saves you bringing a JSONC parser of your own:

    import { extractExamples, parseExampleContent } from "zcap-spec-examples";

    for await (const example of extractExamples(response)) {
    const capability = parseExampleContent(example);
    console.log(capability["@context"]);
    }

    It throws a TypeError for media types with no object representation, such as "message/http" — read example.content directly for those. If you only want the comment stripping, stripJsonComments is exported too.

    ReSpec runs in the browser, so fetching a ReSpec spec gives you the source document: the examples have no id attributes yet, but the page still declares where it is published. extractExamples finds that (see discoverBaseUrl) and numbers the examples the same way ReSpec will, so example.url links to the right place on the rendered page. Pass ExtractExamplesOptions.baseUrl to override it.

    ZcapSpecExample
    discoverBaseUrl
    ExtractExamplesOptions
    extractExamplesFromHtml
    HtmlSource
    extractExamples
    stripJsonComments
    parseExampleContent
    formatExample
    formatExampleAsPrettyJson
    formatExamplesAsJson
    ZcapSpecExamplesCliOptions
    ZcapSpecExamplesCliDeps
    ZcapSpecExamplesCli
    NodejsZcapSpecExamplesCli
    decodeEntities
    getAttribute
    toText
    DEFAULT_ZCAP_SPEC_URL
    ZcapSpecExamplesOutputFormat
    FetchLike
    HELP_TEXT
    NODEJS_CLI_PARSE_ARGS_OPTIONS
    main