@typesugar/strings
v0.1.0
Published
🧊 String interpolation macros (regex, html, fmt, json, raw) for typesugar
Maintainers
Readme
@typesugar/strings
Compile-time validated string macros.
Overview
@typesugar/strings provides tagged template macros for string processing with compile-time validation: regex validation, HTML XSS escaping, printf-style formatting, JSON parsing, and raw strings.
Installation
npm install @typesugar/strings
# or
pnpm add @typesugar/stringsUsage
regex — Compile-Time Validated Regular Expressions
import { regex } from "@typesugar/strings";
// Validated at compile time
const email = regex`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`;
// Compiles to: new RegExp("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$")
// Invalid regex causes compile-time error
const bad = regex`[invalid`;
// Error: Invalid regular expression: Unterminated character classhtml — XSS-Safe HTML Templates
import { html } from "@typesugar/strings";
const userInput = "<script>alert('xss')</script>";
// Interpolations are automatically escaped
const safe = html`<div>${userInput}</div>`;
// Result: "<div><script>alert('xss')</script></div>"fmt — Printf-Style Formatting
import { fmt } from "@typesugar/strings";
const name = "Alice";
const age = 30;
const message = fmt`Hello, ${name}! You are ${age} years old.`;
// Result: "Hello, Alice! You are 30 years old."json — Compile-Time JSON Parsing
import { json } from "@typesugar/strings";
// Parsed and validated at compile time
const config = json`{
"name": "my-app",
"version": "1.0.0",
"features": ["auth", "logging"]
}`;
// Compiles to: { name: "my-app", version: "1.0.0", features: ["auth", "logging"] }
// Invalid JSON causes compile-time error
const bad = json`{ invalid json }`;
// Error: Invalid JSON: Unexpected token 'i'raw — Raw Strings (No Escape Processing)
import { raw } from "@typesugar/strings";
// Escape sequences preserved
const path = raw`C:\Users\name\Documents`;
// Result: "C:\\Users\\name\\Documents"
const regex = raw`\d+\.\d+`;
// Result: "\\d+\\.\\d+"API Reference
Tagged Template Macros
regex— Compile-time validated regular expressionshtml— HTML with automatic XSS escapingfmt— Printf-style string formattingjson— Compile-time JSON parsingraw— Raw strings without escape processing
Functions
register()— Register macros (called automatically on import)
Runtime Helper
// Used internally by html macro
function __typemacro_escapeHtml(str: unknown): string;Compile-Time Benefits
| Macro | Compile-Time Feature |
| ------- | ------------------------------------------- |
| regex | Syntax validation, catches invalid patterns |
| html | Auto-injection of escape calls |
| fmt | Could be extended for type checking |
| json | Parse errors, valid AST generation |
| raw | Escape sequence preservation |
License
MIT
