Node.js · API

Directive

Nodo del árbol que devuelve DON.parse. Representa una directiva: su nombre, sus argumentos y las directivas de su bloque.

class Directive {
  readonly name: string | symbol;
  readonly args: (number | string | boolean | HeredocValue)[];
  readonly children: Directive[];

  constructor(
    name: string | symbol,
    args: (number | string | boolean | HeredocValue)[],
    children?: Directive[],
  );

  get parent(): Directive | undefined;
  toJSON(): unknown;
  find(path: string): Directive | undefined;
  findAll(path: string): Directive[];
  at(path: string): Directive | undefined; // o el argumento, con sufijo [N]
  static tokensByDirective(directive: Directive): Token[] | undefined;
}

Propiedades

const root = DON.parse('a { b }');

root.name;                        // 'a'
root.children[0].parent === root; // true
root.parent;                      // undefined

Crear directivas a mano

import { Directive } from "donly";

const route = new Directive("route", ["GET"], [
  new Directive("respond", [200]),
]);

JSON.stringify(route);              // {"route":["GET",{"respond":200}]}
route.children[0].parent === route; // true

Buscar

find, findAll y at resuelven un camino absoluto tomando la directiva como raíz del documento. at admite un sufijo [N] para devolver un argumento (posiciones desde 1). La sintaxis de caminos está en Node.js.

toJSON

Lo usa JSON.stringify. Agrupa por el primer argumento. Para otras formas usa DirectiveJSONEncoder (ver ejemplo). Para el camino inverso, DirectiveJSONDecoder:

import { DirectiveJSONDecoder } from "donly";

const directive = new DirectiveJSONDecoder().decode([
  { name: "a", args: [1], children: [] },
]);
JSON.stringify(directive); // {"a":1}

tokensByDirective

Devuelve los tokens de la directiva (nombre y argumentos, no los de sus hijos), o undefined si no la produjo el parser.

const root = DON.parse('name "x"\nport 1');

Directive.tokensByDirective(root.children[0])
  ?.map((token) => token.text());
// [ 'name', 'x' ]   (nombre y argumentos, sin los hijos)

Directive.tokensByDirective(manualDirective); // undefined

HeredocValue

Un heredoc llega como argumento HeredocValue, con el descriptor y el contenido ya sin la indentación común. HeredocValue.parse(raw) interpreta el texto crudo de un token heredoc.

import { DON, HeredocValue } from "donly";

const root = DON.parse("template <<<HTML\n  <div/>\n");
const value = root.args[0];

value instanceof HeredocValue; // true
value.descriptor;              // 'HTML' (null si se omite)
value.content;                 // '<div/>\n'
String(value);                 // '<div/>\n'
JSON.stringify(root);          // {"template":"<div/>\n"}