npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

target-injector

v0.1.1

Published

Wrapper to inject code into target

Downloads

18

Readme

npm version

target-injector

Handy wrapper to inject code into targets

// Insert a script element
new Injector('target.html');
  .parse()
  .select('html head') // cssauron syntax
  .validate('prependChild') // valid iff the number of selected node is 1
  .inject('<script src="injected-script.js"></script>')
  .dest(injected => console.log(`${injected}`))
  .dest('injected-target.html');

// Modify a code fragment
new Injector('target.js' /* not read as data is specified */,
    { data: 'function f() { const flag = true; }' }
  )
  .parse()
  .select( // esquery syntax
    '[type="FunctionDeclaration"][id.name="f"] ' +
    '[type="VariableDeclaration"][kind="const"] ' +
    '[type="VariableDeclarator"][id.name="flag"] ' +
    '[type="Literal"]'
  )
  .validate('replace')
  .inject('false')
  .dest(injected => console.log(`${injected}`));

Install

npm i target-injector
# dependent components for handlers
npm i htmlparser2 domhandler cssauron espree estraverse esquery

Set up Injector class

const { InjectorFactory, InjectionHandlerBase } = require('target-injector');
const { HtmlInjectionHandlerFactory } = require('target-injector/HtmlInjectionHandlerFactory.js');
const { JsInjectionHandlerFactory } = require('target-injector/JsInjectionHandlerFactory.js');

// Notes: 
//  - target-injector NPM package does NOT explicitly depend on any other packages
//  - These dependent components must be installed into the user project/package
const { Parser } = require("htmlparser2");
const { DomHandler } = require("domhandler");
const cssauron = require('cssauron');
const parser = require('espree'); // can be esprima or acorn
const estraverse = 'estraverse'; // hand the specifier to patch the component in InjectorFactory
const esquery = require('esquery');

const Injector = InjectorFactory({
  html: {
    factory: HtmlInjectionHandlerFactory,
    components: {
      Parser, DomHandler, cssauron,
    },
    extensions: [ '.html', '.htm' ],
  },
  js: {
    factory: JsInjectionHandlerFactory,
    components: {
      parser, estraverse, esquery, /*, parserOptions: parserOptions */
    },
    extensions: [ '.js', '.mjs' ],
  },
});

Examples

Injection with fallback

new Injector('target.html');
  .parse()
  .select('html head script[src=/injected-script.js/]', 'html head') // fallback selectors
  // Suppored actions: 'replace', 'insertBefore', 'insertAfter', 'prependChild', 'appendChild'
  .validate('replace', 'prependChild') // replace the script element if found
  .inject(...[ 'replaced', 'prepended' ].map(attr => `<script ${attr} src="injected-script.js"></script>`))
  .dest(injected => console.log(`${injected}`))
  .dest('injected-target.html');

Patch JavaScript code with chaining

// JavaScript: Extracted from target-injector/Injector.js
// Patch estraverse.attachComments for trailingComments to work
let estraverse = 'estraverse';
new Injector(require.resolve(estraverse))
  .parse().select(
    '[type="FunctionDeclaration"][id.name="attachComments"] ' +
    '[type="ObjectExpression"] ' +
    '[type="Property"][key.name="leave"] ' +
    '[type="BinaryExpression"][operator="<"] ' +
    '[type="MemberExpression"][object.property.name="extendedRange"]'
  ).validate('insertAfter').inject(' - 1')
  .parse().select(
    '[type="FunctionDeclaration"][id.name="attachComments"] ' +
    '[type="ObjectExpression"] ' +
    '[type="Property"][key.name="leave"] ' +
    '[type="BinaryExpression"][operator="==="] ' +
    '[type="MemberExpression"][object.property.name="extendedRange"]'
  ).validate('insertAfter').inject(' - 1')
  .parse().select(
    '[type="FunctionDeclaration"][id.name="attachComments"] ' +
    '[type="ObjectExpression"] ' +
    '[type="Property"][key.name="leave"] ' +
    '[type="BinaryExpression"][operator=">"] ' +
    '[type="MemberExpression"][object.property.name="extendedRange"]'
  ).validate('insertAfter').inject(' - 1')
  .dest(injected => {
    estraverse = {};
    let _module = { exports: estraverse };
    new Function('module', 'exports', 'require', injected)(_module, estraverse, require);
    Injector.handlers.js = handlers.js.factory(Object.assign(handlers.js.components, { estraverse }));
  });

Validator and Injection Strings as a callback function

// 
let injector = new Injector('target.html');
injector
  .parse()
  .select('html head meta[charset]', 'html head')
  .validate(function (injector) {
    // this === injector
    if (this.selected && this.selected.length === 1) {
      switch (this.selector) {
      case 'html head':
        injector.action = Injector.PREPEND_CHILD;
        break;
      case 'html head meta[charset]':
        injector.action = Injector.INSERT_AFTER;
        break;
      default:
        injector.action = Injector.INSERT_AFTER;
        break;
      }
      return true;
    }
    else {
      this.error = `only 1 node must be selected ${this.selected}`;
      return false;
    }
  })
  .inject(function (injector) {
    switch (this.selector) {
    case 'html head':
      attr = 'first-head-child';
      break;
    case 'html head meta[charset]':
      attr = 'after-meta-charset';
      break;
    default:
      attr = 'unknown';
      break;
    }
    return `<script ${attr} "injected-script.js"></script>`;
  }
  .dest('injected-target.html')

JavaScript injection with next and prev attributes

new Injector('target.js' /* not read as data is specified */, 
    { data: `const arr = ['a', 'b', 'c', 'd', 'e']` }
  )
  .parse()
  .select( // esquery syntax with next and prev attributes
    '[type="VariableDeclaration"][kind="const"] ' +
    '[type="VariableDeclarator"][id.name="arr"] ' +
    '[type="Literal"][prev.value="b"]'
  )
  .validate('insertAfter')
  .inject(`, 'inserted after c'`)
  .parse()
  .select( // esquery syntax with next and prev attributes
    '[type="VariableDeclaration"][kind="const"] ' +
    '[type="VariableDeclarator"][id.name="arr"] ' +
    '[type="Literal"][next.value=null]'
  )
  .validate('replace')
  .inject(`'replaced last element value'`)
  .dest(injected => {
    // injected === 
    // `const arr = ['a', 'b', 'c', 'inserted after c', 'd', 'replaced last element value']`
    console.log(`${injected}`);
  })

Select a node with trailingComments

new Injector('target.js' /* not read as data is specified */, { data: `
  obj.prop = {
    item1: true, // comment for item1
    item2: true, // comment for item2
  };
` })
  .parse()
  .select( // leadingComments and trailingComments are supported
    '[type="AssignmentExpression"][left.object.name="obj"][left.property.name="prop"] ' +
    '[type="ObjectExpression"] ' +
    '[type="Property"][value.trailingComments.0.value=/comment for item2/] '
  )
  .validate('replace').inject('item2: "new item2 value"')
  .dest(injected => { console.log(`${injected}`); })

License

BSD-2-Clause