TypeScript dialect
This page covers the ops of @pbuilder/sdk/typescript. How a dialect handle works, queries and .modify() are the same for every dialect and are described in Dialects.
import * as ts from "@pbuilder/sdk/typescript";
await ts.find("src/index.ts") .addImport("readFileSync", "node:fs") .addFunction("hi", "(): void {}", { export: true });| Op | What it does |
|---|---|
addImport(name, from, opts?) |
Adds import { name } from "from", merging into an existing clause from the same module. Idempotent: calling it twice never duplicates the import. With { position: "sorted" } it places the import in order instead of appending it. See Sorted imports. |
addDefaultImport(name, from) |
Adds import name from "from", merging into a declaration of that module with no default yet. Rejects a second default under another name. |
addNamespaceImport(name, from) |
Adds import * as name from "from", merging into a default-only declaration. Beside named imports it opens its own declaration. |
addTypeImport(name, from) |
Adds import type { name } from "from" as its own statement, never merged into a value import. A no-op when the module already imports name, by value or as a type. |
addSideEffectImport(from) |
Adds import "from". A no-op when that bare import already exists. |
addReExport(name, from) |
Adds export { name } from "from", merging into an existing re-export of that module. Rejects a name the file already exports. |
addExportAll(from, { as? }) |
Adds export * from "from", or export * as ns from "from" with { as: "ns" }. |
removeImport(name, from) |
Removes the named binding; deletes the whole statement when it was the last one. Idempotent on an absent binding. |
removeExport(name, from) |
Removes a named re-export; deletes the statement when it was the last one. Idempotent on an absent one. |
removeExportAll(from, { as? }) |
Removes export * from "from" (or the as form). Idempotent on an absent one. |
sortImports() |
Sorts the file’s import declarations by module, and the names inside each one’s braces. Only reorders. A no-op on a sorted file. See Sorted imports. |
addFunction(name, source, opts?) |
Appends a top-level function. source includes the braces ("(): void {}"). |
addVariable(name, initializer, opts?) |
Appends a top-level variable (kind defaults to const). |
addClass(name, source, opts?) |
Appends a top-level class. source excludes the braces, and the op adds them. |
addArrayElement(locator, element) |
Appends element to the array literal that locator points at, keeping the list’s layout. A no-op when the element is already there. See Nested arrays. |
addClassProperty(className, name, initializer, opts?) |
Adds name = initializer; after the last property of the only class named className. A no-op when the same property exists. |
.modify(fn) |
The universal escape hatch: direct ts-morph access to the file’s AST for anything the named ops don’t cover. |
Note the deliberate contrast between the two source conventions:
// addFunction: source INCLUDES bracesawait ts.find("src/index.ts").addFunction("hi", "(): void {}", { export: true });// -> export function hi(): void {}
// addClass: source EXCLUDES braces (the op adds them)await ts.find("src/index.ts").addClass("Point", " x = 0;");// -> class Point {\n x = 0;\n}addVariable emits {export }{kind} {name} = {initializer};. kind accepts "const"
(default), "let", or "var", and rejects any other value:
await ts.find("src/index.ts").addVariable("counter", "0", { export: true, kind: "let" });// -> export let counter = 0;Import forms and barrel files
Section titled “Import forms and barrel files”Each import form has its own op. Running one twice changes the file once:
await ts .find("src/main.ts") .addDefaultImport("express", "express") .addTypeImport("Request", "express") .addSideEffectImport("reflect-metadata");// -> import express from "express";// -> import type { Request } from "express";// -> import "reflect-metadata";The re-export ops build barrel files. Generate a file, then export it from index.ts:
import { create } from "@pbuilder/sdk/commons";import * as ts from "@pbuilder/sdk/typescript";
create("src/user.service.ts", { template: "export class UserService {}", options: {} });await ts .find("src/index.ts") .addReExport("UserService", "./user.service") .addExportAll("./dto");// -> export { UserService } from "./user.service";// -> export * from "./dto";addReExport and addExportAll reject a name the file already exports by any route (another
re-export, an export * as, or an exported declaration), because two exports sharing a name
are invalid TypeScript. addReExport and removeExport match by source name, so
export { name as Y } already counts. removeExport never touches a local export { x } or
an export *, and each export * form only removes itself.
Name validation. Every op checks name before it touches the file. It must be a plain
ASCII JavaScript identifier (^[A-Za-z_$][A-Za-z0-9_$]*$), not a reserved or
strict-mode-restricted word (class, await, eval, arguments, …), and not __proto__,
constructor, or prototype. A rejected name leaves the file unchanged, and removeImport
rejects it even when there was nothing to remove.
Collision rules. The add* ops fail loud on a name collision with an existing value
declaration or import binding, because two value declarations sharing a name is invalid
TypeScript. An import binding is any import form: named, default (import X from "m") and
namespace (import * as X from "m"), type-only ones included. A type/interface sharing the
name does not collide (TypeScript legally permits a value and a type to share an
identifier).
source/initializer strings are inserted verbatim, never validated or sanitized, so the
author owns their syntax, and anything derived from untrusted input (schema options, CLI
answers, network data) is the author’s responsibility to sanitize.
Sorted imports
Section titled “Sorted imports”addImport appends by default. Pass { position: "sorted" } to keep a file’s imports in order:
the name goes into its alphabetical place inside the braces, and a new declaration goes next to
its folder siblings, before the first of them that sorts after it.
// import { BookOpen, Users } from "lucide-react";// import { authorHandlers } from "./domains/authors.mock";// import { config } from "./config";await ts.find("src/mocks/handlers.ts") .addImport("LayoutDashboard", "lucide-react", { position: "sorted" }) .addImport("bookHandlers", "./domains/books.mock", { position: "sorted" });// import { BookOpen, LayoutDashboard, Users } from "lucide-react";// import { authorHandlers } from "./domains/authors.mock";// import { bookHandlers } from "./domains/books.mock";// import { config } from "./config";sortImports() sorts the whole file instead: its import declarations by module, and the names
inside each declaration’s braces, in the same order. A multi-line brace layout is kept.
Both follow the same rules:
- Sorting is case-insensitive, and package specifiers (
react,node:fs,@/lib) sort ahead of relative ones. - A module’s folder siblings are the existing imports that share the most leading path segments
with
from. In a file with no imports, the declaration goes where the unsorted form puts it. - Sorted
addImportnever moves existing imports, so a file that was out of order stays out of order around the new line. A new declaration goes above a comment attached to the import it precedes. - Without the option,
addImportbehaves as before. Any otherpositionvalue rejects and leaves the file unchanged. - Inserted imports match the file’s quotes and semicolons, like every insertion.
sortImportsonly reorders. It never combines two declarations of one module, removes an unused import, or reformats one, and on a sorted file it writes nothing.- Declarations move only within a run of consecutive imports. A blank line, a comment, a
side-effect import (
import "./polyfills";, whose position changes behaviour), or a declaration with a comment attached ends the run, and nothing crosses it. Braces that contain a comment keep their order.
Nested arrays: addArrayElement
Section titled “Nested arrays: addArrayElement”Most generators create a file and then register it somewhere: a provider in appConfig, a
guard on a route, a module in @NgModule. addArrayElement(locator, element) makes that edit.
The locator names a root and then a path from that root to the array:
| Root | Starts at |
|---|---|
{ variable: "appConfig", path } |
The initializer of that top-level variable |
{ call: "bootstrapApplication", argument: 1, path } |
That argument of the only call to bootstrapApplication |
{ decorator: "NgModule", path } |
The argument of the only @NgModule(...) |
Each path segment is an object key ("providers") or a match such as { path: "admin" },
which selects the only array element whose path property is "admin". There are no numeric
indices, because an index points at the wrong element once someone reorders the array. At each
step the op looks through as, satisfies, <T> assertions, ! and parentheses.
await ts .find("src/app/app.config.ts") .addImport("provideHttpClient", "@angular/common/http") .addArrayElement({ variable: "appConfig", path: ["providers"] }, { expression: "provideHttpClient()" });// before: providers: [provideRouter(routes)],// after: providers: [provideRouter(routes), provideHttpClient()],A match walks into one entry of a list. Here the admin route has no providers key yet, so
the op creates it:
await ts .find("src/app/app.routes.ts") .addImport("AdminGuard", "./admin/admin.guard") .addArrayElement({ variable: "routes", path: [{ path: "admin" }, "providers"] }, "AdminGuard");// beforeexport const routes: Routes = [ { path: "", component: HomeComponent }, { path: "admin", component: AdminComponent, },];
// afterexport const routes: Routes = [ { path: "", component: HomeComponent }, { path: "admin", component: AdminComponent, providers: [AdminGuard], },];The op creates a missing key ({} becomes { providers: [X] }) and the next missing argument
of a call or decorator (bootstrapApplication(App) becomes
bootstrapApplication(App, { providers: [X] })). It rejects, and leaves the file unchanged,
when:
- the root does not exist, or a match selects nothing;
- the root or a match selects more than one node;
- the argument is past the next one, such as
argument: 2onbootstrapApplication(App); - the missing key could already come from a spread (
{ ...base }), a computed key, or a getter or setter, since a new key might shadow it.
element is an identifier, or { expression: "..." } for code. The expression must parse as
exactly one expression, so it cannot close the array or add a statement. The op inserts it
verbatim otherwise, so never build it from consumer input. An element that is already in the
array is a no-op: elements are compared token by token, and spacing, comments and trailing
commas don’t count. The new element follows the list’s layout. A one-line list stays on one
line, a multi-line list gets a new line at the last entry’s indentation, and a trailing comma
stays. The op adds no import, so pair it with addImport.
Class properties: addClassProperty
Section titled “Class properties: addClassProperty”addClassProperty(className, name, initializer, options?) writes
{scope }{readonly }name = initializer; into an existing class. options is
{ scope?: "public" | "protected" | "private"; readonly?: boolean }, and an omitted option
writes nothing.
await ts .find("src/app/user.service.ts") .addImport("inject", "@angular/core") .addClassProperty("UserService", "http", "inject(HttpClient)", { scope: "private", readonly: true });// beforeexport class UserService { private readonly cache = new Map<string, User>();
load(id: string) { return this.cache.get(id); }}
// afterexport class UserService { private readonly cache = new Map<string, User>(); private readonly http = inject(HttpClient);
load(id: string) { return this.cache.get(id); }}The property goes after the class’s last property, which keeps properties above the
constructor and methods. A class without properties gets it as its first member. The file must
have exactly one class named className. A property with the same declaration is a no-op, and
any other member named name, a method included, rejects. initializer must parse as one
expression and is inserted verbatim, like { expression }. The op adds no import.
Idempotency: safe to re-run
Section titled “Idempotency: safe to re-run”Factories re-run against already-generated projects, and the import ops are built for that:
addImport called twice with the same name and module never duplicates the import line, and
removeImport on an absent binding is a no-op (zero directives emitted), so you don’t need
your own “is it already there?” check.
Example: register a route (TypeScript)
Section titled “Example: register a route (TypeScript)”addArrayElement takes only code you wrote yourself. When the
element comes from consumer input, build it in .modify() so you control the quoting. This
factory adds a path from its input to an exported routes array, and does nothing when the path
is already there:
export const routes = [ "/", "/about",];import { find, astLibrary } from "@pbuilder/sdk/typescript";
type ArrayLiteral = astLibrary.ArrayLiteralExpression;
export default async (input: { path: string }) => { await find("src/routes.ts").modify((ast) => { const routes: ArrayLiteral = ast .getVariableDeclarationOrThrow("routes") .getInitializerIfKindOrThrow(astLibrary.SyntaxKind.ArrayLiteralExpression);
const alreadyRegistered = routes .getElements() .some((el) => astLibrary.Node.isStringLiteral(el) && el.getLiteralValue() === input.path);
if (!alreadyRegistered) { routes.addElement(JSON.stringify(input.path)); } });};export const routes = [ "/", "/about", "/pricing"];Running it again with the same input leaves the file unchanged.