incode
TypeScript icon, indicating that this package has built-in type declarations

0.3.0 • Public • Published

incode is a library for building code injectors.

Example

Code with injectable regions:

class User {
  // inj:emit("User", "pck")
  // inj:end
}

Code injector:

import { createDirectiveMatcher, inject } from "incode";
 
const s = inject(
  text, // code with injectable regions
  createDirectiveMatcher("inj"),
  (region) => {
    return `${region.args[1]}() { console.log("${region.args[0]} injected method"); }`;
  },
);

Result after injection:

// inj:assign({ schema: "User" })
class User {
  // inj:emit("pck")
  pck() { console.log("User injected method"); }
  // inj:end
}

Features

  • Block-scoped variables
  • Indentation autodection for injectable regions
  • Automatic removal of existing code in injectable regions

Directives

  • begin - begin local scope
  • end - end region
  • assign(data: JSON) - assign data to a local scope Object.assign
  • merge(data: JSON) - merge data to a local scope _.merge
  • emit(...args: Array<JSON>) - emit code

API

function createDirectiveMatcher(prefix: string): RegExp;

createDirectiveMatcher creates a RegExp object that will be used as a directive matcher.

interface InjectableRegion {
  readonly args: any[];
  readonly data: {};
  readonly padding: string;
  readonly start: number;
  readonly end: number;
}
 
function extractRegions(
  text: string,
  directiveMatcher: RegExp,
  data = {},
): InjectableRegion[];

extractRegions extracts InjectableRegions from text.

function inject(
  text: string,
  directiveMatcher: RegExp,
  cb: (region: InjectableRegion) => string,
  data = {},
): string;

inject invokes cb function and injects its result into a text.

Readme

Keywords

Package Sidebar

Install

npm i incode

Weekly Downloads

0

Version

0.3.0

License

MIT

Last publish

Collaborators

  • localvoid