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

typescript-expression-transformer

v1.1.1

Published

TypeScript expression transformer

Downloads

60

Readme

Typescript Expression Transformer

NPM version License: MIT Gitter chat

Expression trees for TypeScript similar to C#. This is the TypeScript transformer plugin.

Expression Type

type Expression<TType> = TType &
	{
		/**
		 * Compiled, executable, expression
		 */
		compiled?: TType;

		/**
		 * TypeScript expression tree
		 */
		expression?: ExpressionNode;

		/**
		 * Context variables
		 */
		context?: { [key: string]: any };
	};

This expression type is declared inside package which you need for runtime. It declares the Expression, ExpressionKind enum (taken from TypeScript) and maybe more runtime features in the future.

Example

An example demonstrating usage of member expression (PropertyAccessExpression) used to generate HTML Ids for model's elements. There is function fieldIdFor() which takes Expression argument. In TypeScript you set some arrow function as an argument (eg. m => m.foo). In transpile time, the transformer looks up all CallExpression of method/function declaration with parameter of type Expression<>. Then it takes the argument, creates the expression tree and replace the original expression with object (representing type Expression<>).

Get Started

Create project folder and run npm i typescript-expression-transformer ttypescript -D && npm i js-expr-tree

Source

src/field-id-for.ts

import {ExpressionKind} from "js-expr-tree"; // the runtime package of this transformer; it's a dependency

/**
 * Construct path from member expression
 * @param node
 * @param ignoredProperties
 * @param path
 */
function getPropertyPath(node, ignoredProperties: Array<string> = [], path: string = "") {
	if (!node) {
		return "";
	}

	let prefix = getPropertyPath(node.expression, ignoredProperties, path);
	return (prefix ? (prefix + "_") : "") + (node.name ? node.name.escapedText : "");
}

/**
 * Generate html id for model's property member expression
 * @param memberExpression
 */
export function fieldIdFor<TModel>(memberExpression: Expression<(m: TModel) => any>) {
	const expr = memberExpression.expression as ArrowFunctionExpressionNode;

	if (expr.kind != ExpressionKind.ArrowFunction) {
		throw new Error("Expression must be arrow function");
	}

	if (expr.body.kind != ExpressionKind.PropertyAccessExpression) {
		throw new Error("Arrow function body must be member expression without block body.");
	}

	const params = expr.parameters.map(p => p.name.escapedText);
	
	return getPropertyPath(expr.body, params);
}

This module exports the fieldIdFor function which returns the HTML id constructed by member expression tree.

Result Usage

Create random ts file with usage of fieldIdFor function.

index.ts

import {fieldIdFor} from "./src/field-id-for"

class Human {
	public name: string;
	public baz: { deepProp: string };
}

console.log("Generated id for property:", fieldIdFor<Human>(m => m.baz.deepProp));

Create typescript config file.

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "esnext",
    "plugins": [
      {
        "transform": "typescript-expression-transformer"
      }
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

Using ttypescript package, you can transpile source by running ttsc. index.js will be created.

Transpiled Code

index.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var field_id_for_1 = require("./field-id-for");
class Human {
}
console.log("Generated id for property:", field_id_for_1.fieldIdFor({ compiled: m => m.baz.deepProp, context: { Human }, expression: { "flags": 128, "kind": 197, "parameters": [{ "flags": 0, "kind": 151, "name": { "flags": 0, "escapedText": "m", "flowNode": { "flags": 2 } }, "symbol": { "flags": 1, "escapedName": "m", "declarations": [null], "exports": {} } }], "equalsGreaterThanToken": { "flags": 0, "kind": 37 }, "body": { "flags": 0, "kind": 189, "expression": { "flags": 0, "kind": 189, "expression": { "flags": 0, "escapedText": "m" }, "name": { "flags": 0, "escapedText": "baz" } }, "name": { "flags": 0, "escapedText": "deepProp" } }, "flowNode": { "flags": 2 }, "symbol": { "flags": 16, "escapedName": "__function", "declarations": [null] }, "locals": {} } }));

Run node index.js and you'll see the result.

Result

Generated id for property: baz_deepProp

Tip

For work with AST you can use https://astexplorer.net which prints tree nicely. Use the TypeScript AST.