@pbuilder/sdk 0.5.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -2
- package/dist/core/define-dialect.d.ts +6 -2
- package/dist/core/define-dialect.js +1 -0
- package/dist/core/dialect-handle.d.ts +14 -1
- package/dist/core/dialect-handle.js +47 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +1 -1
- package/dist/core/jsx-name-validator.d.ts +6 -1
- package/dist/core/jsx-name-validator.js +12 -4
- package/dist/dialects/angular/index.d.ts +63 -0
- package/dist/dialects/angular/index.js +68 -0
- package/dist/dialects/angular/ops.d.ts +110 -0
- package/dist/dialects/angular/ops.js +342 -0
- package/dist/dialects/css/ast.d.ts +7 -0
- package/dist/dialects/css/ast.js +16 -0
- package/dist/dialects/css/index.d.ts +40 -0
- package/dist/dialects/css/index.js +38 -0
- package/dist/dialects/css/ops.d.ts +44 -0
- package/dist/dialects/css/ops.js +216 -0
- package/dist/dialects/nestjs/ops.js +1 -26
- package/dist/dialects/typescript/array-element.d.ts +41 -0
- package/dist/dialects/typescript/array-element.js +323 -0
- package/dist/dialects/typescript/class-property.d.ts +24 -0
- package/dist/dialects/typescript/class-property.js +98 -0
- package/dist/dialects/typescript/index.d.ts +6 -1
- package/dist/dialects/typescript/index.js +2 -1
- package/dist/dialects/typescript/pack.d.ts +4 -0
- package/dist/dialects/typescript/pack.js +4 -0
- package/dist/runner-manifest.json +2 -2
- package/package.json +12 -1
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { Node, SyntaxKind, } from "ts-morph";
|
|
2
|
+
import { dialectError } from "../../core/dialect-error.js";
|
|
3
|
+
import { handlePathFor } from "../../core/dialect-handle.js";
|
|
4
|
+
import { assertValidImportBinding } from "../../core/jsx-name-validator.js";
|
|
5
|
+
import { elementNameEcho } from "../../core/reject-tail.js";
|
|
6
|
+
import { appendArrayElement, appendEntry, elementText, isSameElement, unwrap, } from "../typescript/array-element.js";
|
|
7
|
+
import { parse } from "../typescript/ast.js";
|
|
8
|
+
import { insertClassProperty } from "../typescript/class-property.js";
|
|
9
|
+
import { addImport } from "../typescript/ops.js";
|
|
10
|
+
const IMPORTS_SHAPE = "`imports` must be a list of { name, from } strings — fix the imports, or use `.modify()` to make this edit directly.";
|
|
11
|
+
function assertImports(imports) {
|
|
12
|
+
if (imports === undefined)
|
|
13
|
+
return;
|
|
14
|
+
const valid = Array.isArray(imports) &&
|
|
15
|
+
imports.every((entry) => typeof entry === "object" &&
|
|
16
|
+
entry !== null &&
|
|
17
|
+
Object.keys(entry).sort().join() === "from,name" &&
|
|
18
|
+
typeof entry.name === "string" &&
|
|
19
|
+
typeof entry.from === "string");
|
|
20
|
+
if (!valid)
|
|
21
|
+
throw dialectError(IMPORTS_SHAPE);
|
|
22
|
+
for (const { name } of imports)
|
|
23
|
+
assertValidImportBinding(name);
|
|
24
|
+
}
|
|
25
|
+
// An insert op: `locate` turns the file into the array the element goes to, then every
|
|
26
|
+
// import the element needs is added with `addImport`'s rules.
|
|
27
|
+
function insertOp(opName, locate) {
|
|
28
|
+
return (ast, element, imports) => {
|
|
29
|
+
assertImports(imports);
|
|
30
|
+
const label = `${opName}("${elementNameEcho(elementText(element))}")`;
|
|
31
|
+
const fail = (reason) => {
|
|
32
|
+
throw dialectError(`${label} on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
|
|
33
|
+
};
|
|
34
|
+
appendArrayElement(ast, locate(ast, fail), element, label);
|
|
35
|
+
for (const { name, from } of imports ?? [])
|
|
36
|
+
addImport(ast, name, from);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
// The declared type of a top-level variable: its annotation, or the type it `satisfies`.
|
|
40
|
+
function declaredType(decl) {
|
|
41
|
+
const initializer = decl.getInitializer();
|
|
42
|
+
return decl.getTypeNode()?.getText() ?? (Node.isSatisfiesExpression(initializer) ? initializer.getTypeNode()?.getText() : undefined);
|
|
43
|
+
}
|
|
44
|
+
function typedVariables(ast, types) {
|
|
45
|
+
return ast.getVariableDeclarations().filter((decl) => types.includes(declaredType(decl) ?? ""));
|
|
46
|
+
}
|
|
47
|
+
function rootProviders(ast, fail) {
|
|
48
|
+
const configs = typedVariables(ast, ["ApplicationConfig"]);
|
|
49
|
+
if (configs.length > 1)
|
|
50
|
+
fail(`${configs.length} top-level variables are typed ApplicationConfig; exactly one is required`);
|
|
51
|
+
if (configs.length === 1)
|
|
52
|
+
return { variable: configs[0].getName(), path: ["providers"] };
|
|
53
|
+
const calls = ast
|
|
54
|
+
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
55
|
+
.filter((call) => call.getExpression().getText() === "bootstrapApplication");
|
|
56
|
+
if (calls.length === 0)
|
|
57
|
+
fail("no top-level variable typed ApplicationConfig and no bootstrapApplication call was found");
|
|
58
|
+
// Providers passed by reference live where that config is declared, usually another file.
|
|
59
|
+
const config = calls.length === 1 ? calls[0].getArguments()[1] : undefined;
|
|
60
|
+
if (Node.isIdentifier(config)) {
|
|
61
|
+
const name = config.getText();
|
|
62
|
+
const from = ast
|
|
63
|
+
.getImportDeclarations()
|
|
64
|
+
.find((decl) => decl.getNamedImports().some((spec) => (spec.getAliasNode() ?? spec.getNameNode()).getText() === name))
|
|
65
|
+
?.getModuleSpecifierValue();
|
|
66
|
+
fail(`the bootstrapApplication config is "${elementNameEcho(name)}"` +
|
|
67
|
+
(from === undefined ? "; add the provider where it is declared" : `, imported from "${elementNameEcho(from)}"; add the provider in that file`));
|
|
68
|
+
}
|
|
69
|
+
return { call: "bootstrapApplication", argument: 1, path: ["providers"] };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Appends `element` to the `imports` of the file's only `@Component`, creating the metadata
|
|
73
|
+
* object or the array when missing, then adds each of `imports`. An equal element is a no-op.
|
|
74
|
+
*/
|
|
75
|
+
export const addComponentImport = insertOp("addComponentImport", () => ({ decorator: "Component", path: ["imports"] }));
|
|
76
|
+
/** Same as `addComponentImport`, for the component's `providers`. */
|
|
77
|
+
export const addComponentProvider = insertOp("addComponentProvider", () => ({ decorator: "Component", path: ["providers"] }));
|
|
78
|
+
/**
|
|
79
|
+
* Appends `element` to the application's root `providers`: those of the file's only top-level
|
|
80
|
+
* variable typed `ApplicationConfig`, else those of the only `bootstrapApplication(...)` call's
|
|
81
|
+
* config object, created when missing. A config passed by name rejects with the module to edit.
|
|
82
|
+
*/
|
|
83
|
+
export const addRootProvider = insertOp("addRootProvider", rootProviders);
|
|
84
|
+
const ngModuleOp = (opName, property) => insertOp(opName, () => ({ decorator: "NgModule", path: [property] }));
|
|
85
|
+
/**
|
|
86
|
+
* Appends `element` to `imports` of the file's only `@NgModule`, creating the metadata object
|
|
87
|
+
* or the array when missing, then adds each of `imports`. An equal element is a no-op.
|
|
88
|
+
*/
|
|
89
|
+
export const addNgModuleImport = ngModuleOp("addNgModuleImport", "imports");
|
|
90
|
+
/** Same as `addNgModuleImport`, for `declarations`: components, directives and pipes declared `standalone: false`. */
|
|
91
|
+
export const addDeclaration = ngModuleOp("addDeclaration", "declarations");
|
|
92
|
+
/** Same as `addNgModuleImport`, for `providers`. */
|
|
93
|
+
export const addNgModuleProvider = ngModuleOp("addNgModuleProvider", "providers");
|
|
94
|
+
/** Same as `addNgModuleImport`, for `exports`. */
|
|
95
|
+
export const addNgModuleExport = ngModuleOp("addNgModuleExport", "exports");
|
|
96
|
+
/** Same as `addNgModuleImport`, for `bootstrap`. */
|
|
97
|
+
export const addBootstrap = ngModuleOp("addBootstrap", "bootstrap");
|
|
98
|
+
const ROUTE_SHAPE = "`route` must be { path, component, from } strings — fix the route, or use `.modify()` to make this edit directly.";
|
|
99
|
+
const LAZY_ROUTE_SHAPE = "`route` must be { path, loadComponent | loadChildren, export? } strings — fix the route, or use `.modify()` to make this edit " +
|
|
100
|
+
"directly.";
|
|
101
|
+
function isStringRecord(value, required, optional = []) {
|
|
102
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
103
|
+
return false;
|
|
104
|
+
const keys = Object.keys(value);
|
|
105
|
+
return (required.every((key) => keys.includes(key)) &&
|
|
106
|
+
keys.every((key) => required.includes(key) || optional.includes(key)) &&
|
|
107
|
+
Object.values(value).every((field) => typeof field === "string"));
|
|
108
|
+
}
|
|
109
|
+
function pathOf(element) {
|
|
110
|
+
const route = unwrap(element);
|
|
111
|
+
if (!Node.isObjectLiteralExpression(route))
|
|
112
|
+
return undefined;
|
|
113
|
+
const value = route.getProperty("path")?.asKind(SyntaxKind.PropertyAssignment)?.getInitializer();
|
|
114
|
+
return Node.isStringLiteral(value) || Node.isNoSubstitutionTemplateLiteral(value) ? value.getLiteralValue() : undefined;
|
|
115
|
+
}
|
|
116
|
+
// The file's routes: the only variable typed `Routes`/`Route[]`, else the routes of the only
|
|
117
|
+
// `RouterModule.forRoot`/`forChild` call — inline, or a same-file variable it names.
|
|
118
|
+
function routesList(ast, fail) {
|
|
119
|
+
const declarations = typedVariables(ast, ["Routes", "Route[]"]);
|
|
120
|
+
if (declarations.length > 1)
|
|
121
|
+
fail(`${declarations.length} top-level variables are typed Routes or Route[]; exactly one is required`);
|
|
122
|
+
if (declarations.length === 1) {
|
|
123
|
+
const list = unwrap(declarations[0].getInitializerOrThrow());
|
|
124
|
+
if (!Node.isArrayLiteralExpression(list))
|
|
125
|
+
fail(`"${elementNameEcho(declarations[0].getName())}" is not an array literal`);
|
|
126
|
+
return list;
|
|
127
|
+
}
|
|
128
|
+
const calls = ast.getDescendantsOfKind(SyntaxKind.CallExpression).filter((call) => {
|
|
129
|
+
const callee = call.getExpression();
|
|
130
|
+
return (Node.isPropertyAccessExpression(callee) &&
|
|
131
|
+
callee.getExpression().getText() === "RouterModule" &&
|
|
132
|
+
["forRoot", "forChild"].includes(callee.getName()));
|
|
133
|
+
});
|
|
134
|
+
if (calls.length === 0)
|
|
135
|
+
fail("no top-level variable typed Routes or Route[] and no RouterModule.forRoot or forChild call was found");
|
|
136
|
+
if (calls.length > 1)
|
|
137
|
+
fail(`${calls.length} RouterModule.forRoot or forChild calls were found; exactly one is required`);
|
|
138
|
+
let routes = calls[0].getArguments()[0];
|
|
139
|
+
if (Node.isIdentifier(routes)) {
|
|
140
|
+
const named = routes.getText();
|
|
141
|
+
const declaration = ast.getVariableDeclarations().filter((decl) => decl.getName() === named);
|
|
142
|
+
routes = declaration.length === 1 ? declaration[0].getInitializer() : undefined;
|
|
143
|
+
}
|
|
144
|
+
const list = routes === undefined ? undefined : unwrap(routes);
|
|
145
|
+
if (!Node.isArrayLiteralExpression(list))
|
|
146
|
+
fail("the RouterModule routes are not an array literal in this file");
|
|
147
|
+
return list;
|
|
148
|
+
}
|
|
149
|
+
// Adds `text` to the file's routes. Angular matches routes in order and the first
|
|
150
|
+
// match wins, so a new route goes before a top-level `**` route instead of after it.
|
|
151
|
+
function insertRoute(ast, opName, path, text) {
|
|
152
|
+
const label = `${opName}("${elementNameEcho(path)}")`;
|
|
153
|
+
const fail = (reason) => {
|
|
154
|
+
throw dialectError(`${label} on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
|
|
155
|
+
};
|
|
156
|
+
if (path.startsWith("/"))
|
|
157
|
+
fail('a route path cannot start with "/"');
|
|
158
|
+
const element = { expression: text };
|
|
159
|
+
elementText(element);
|
|
160
|
+
const list = routesList(ast, fail);
|
|
161
|
+
const elements = list.getElements();
|
|
162
|
+
const samePath = elements.find((candidate) => pathOf(candidate) === path);
|
|
163
|
+
if (samePath !== undefined) {
|
|
164
|
+
if (isSameElement(samePath, element))
|
|
165
|
+
return;
|
|
166
|
+
fail(`a different route with path "${elementNameEcho(path)}" already exists`);
|
|
167
|
+
}
|
|
168
|
+
const wildcard = elements.find((candidate) => pathOf(candidate) === "**");
|
|
169
|
+
if (wildcard === undefined) {
|
|
170
|
+
appendEntry(ast, list, elements, text, `[${text}]`);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const source = ast.getFullText();
|
|
174
|
+
if (!source.slice(list.getStart(), list.getEnd()).includes("\n")) {
|
|
175
|
+
ast.insertText(wildcard.getStart(), `${text}, `);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const indent = /^[ \t]*/.exec(source.slice(source.lastIndexOf("\n", wildcard.getStart()) + 1))[0];
|
|
179
|
+
ast.insertText(wildcard.getStart(), `${text},\n${indent}`);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Imports `route.component` from `route.from` and adds `{ path, component }` to the file's only
|
|
183
|
+
* top-level variable typed `Routes` or `Route[]`, before a `**` route when there is one. An
|
|
184
|
+
* equal route is a no-op; a different route with the same `path` rejects.
|
|
185
|
+
*/
|
|
186
|
+
export function addRoute(ast, route) {
|
|
187
|
+
if (!isStringRecord(route, ["path", "component", "from"]))
|
|
188
|
+
throw dialectError(ROUTE_SHAPE);
|
|
189
|
+
assertValidImportBinding(route.component, "component");
|
|
190
|
+
insertRoute(ast, "addRoute", route.path, `{ path: ${JSON.stringify(route.path)}, component: ${route.component} }`);
|
|
191
|
+
addImport(ast, route.component, route.from);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Same placement and duplicate rules as `addRoute`, for a lazy route:
|
|
195
|
+
* `{ path, loadComponent: () => import("<module>") }`, or `loadChildren`, followed by
|
|
196
|
+
* `.then((m) => m.<export>)` when `export` is given. Adds no import.
|
|
197
|
+
*/
|
|
198
|
+
export function addLazyRoute(ast, route) {
|
|
199
|
+
if (!isStringRecord(route, ["path"], ["loadComponent", "loadChildren", "export"]))
|
|
200
|
+
throw dialectError(LAZY_ROUTE_SHAPE);
|
|
201
|
+
const kind = route.loadComponent !== undefined ? "loadComponent" : "loadChildren";
|
|
202
|
+
const from = route[kind];
|
|
203
|
+
if (from === undefined || (route.loadComponent !== undefined && route.loadChildren !== undefined))
|
|
204
|
+
throw dialectError(LAZY_ROUTE_SHAPE);
|
|
205
|
+
if (route.export !== undefined)
|
|
206
|
+
assertValidImportBinding(route.export, "export");
|
|
207
|
+
const loader = `import(${JSON.stringify(from)})${route.export === undefined ? "" : `.then((m) => m.${route.export})`}`;
|
|
208
|
+
insertRoute(ast, "addLazyRoute", route.path, `{ path: ${JSON.stringify(route.path)}, ${kind}: () => ${loader} }`);
|
|
209
|
+
}
|
|
210
|
+
// Angular only reads input(), model() and output() in component and directive initializers.
|
|
211
|
+
const VIEW_DECORATORS = ["Component", "Directive"];
|
|
212
|
+
const INJECTABLE_DECORATORS = ["Component", "Directive", "Pipe", "Injectable", "Service"];
|
|
213
|
+
function decoratorList(decorators) {
|
|
214
|
+
const names = decorators.map((name) => `@${name}`);
|
|
215
|
+
return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} or ${names.at(-1)}`;
|
|
216
|
+
}
|
|
217
|
+
function decoratedClass(ast, decorators, fail) {
|
|
218
|
+
const classes = ast
|
|
219
|
+
.getDescendantsOfKind(SyntaxKind.ClassDeclaration)
|
|
220
|
+
.filter((cls) => cls.getDecorators().some((decorator) => decorators.includes(decorator.getName())));
|
|
221
|
+
if (classes.length === 0)
|
|
222
|
+
fail(`no class decorated with ${decoratorList(decorators)} was found`);
|
|
223
|
+
if (classes.length > 1)
|
|
224
|
+
fail(`${classes.length} classes are decorated with ${decoratorList(decorators)}; exactly one is required`);
|
|
225
|
+
return classes[0];
|
|
226
|
+
}
|
|
227
|
+
function assertOptions(options, keys) {
|
|
228
|
+
if (options === undefined)
|
|
229
|
+
return;
|
|
230
|
+
const shape = `\`options\` must be { ${keys.map((key) => `${key}?`).join(", ")} } — fix the options, or use \`.modify()\` to make this edit directly.`;
|
|
231
|
+
if (typeof options !== "object" || options === null || Array.isArray(options))
|
|
232
|
+
throw dialectError(shape);
|
|
233
|
+
const record = options;
|
|
234
|
+
const valid = Object.keys(record).every((key) => {
|
|
235
|
+
const value = record[key];
|
|
236
|
+
if (!keys.includes(key))
|
|
237
|
+
return false;
|
|
238
|
+
if (key === "required")
|
|
239
|
+
return typeof value === "boolean";
|
|
240
|
+
if (key === "scope")
|
|
241
|
+
return value === "public" || value === "protected" || value === "private";
|
|
242
|
+
if (key === "imports")
|
|
243
|
+
return true;
|
|
244
|
+
return typeof value === "string";
|
|
245
|
+
});
|
|
246
|
+
if (!valid)
|
|
247
|
+
throw dialectError(shape);
|
|
248
|
+
assertImports(record.imports);
|
|
249
|
+
}
|
|
250
|
+
const TYPE_RULE = "`type` must be exactly one TypeScript type — fix the type, or use `.modify()` to make this edit directly.";
|
|
251
|
+
// `<type>` once proven to be one type: a breakout such as `T>(); evil(<T` parses differently.
|
|
252
|
+
function typeArgument(type) {
|
|
253
|
+
if (type === undefined)
|
|
254
|
+
return "";
|
|
255
|
+
let statements;
|
|
256
|
+
try {
|
|
257
|
+
statements = parse(`let x: ${type};`).getStatements();
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
throw dialectError(TYPE_RULE);
|
|
261
|
+
}
|
|
262
|
+
const [statement, ...rest] = statements;
|
|
263
|
+
const declaration = statement?.asKind(SyntaxKind.VariableStatement)?.getDeclarations();
|
|
264
|
+
const typeNode = declaration?.length === 1 ? declaration[0].getTypeNode() : undefined;
|
|
265
|
+
if (rest.length > 0 || typeNode === undefined || declaration[0].hasInitializer() || typeNode.getText() !== type.trim()) {
|
|
266
|
+
throw dialectError(TYPE_RULE);
|
|
267
|
+
}
|
|
268
|
+
return `<${typeNode.getText()}>`;
|
|
269
|
+
}
|
|
270
|
+
// Adds `property` to the file's only class with one of `decorators`, then the Angular
|
|
271
|
+
// function it calls (from `@angular/core`) and the author's `imports`.
|
|
272
|
+
function addMember(ast, opName, name, decorators, property, imports) {
|
|
273
|
+
const fail = (reason) => {
|
|
274
|
+
throw dialectError(`${opName}("${elementNameEcho(name)}") on "${handlePathFor(ast)}" — ${reason}. Edit it with .modify().`);
|
|
275
|
+
};
|
|
276
|
+
const cls = decoratedClass(ast, decorators, fail);
|
|
277
|
+
insertClassProperty(ast, cls, { name, initializer: property.initializer, scope: property.scope, readonly: true }, fail);
|
|
278
|
+
addImport(ast, property.core, "@angular/core");
|
|
279
|
+
for (const entry of imports ?? [])
|
|
280
|
+
addImport(ast, entry.name, entry.from);
|
|
281
|
+
}
|
|
282
|
+
function signalInputOp(opName, fn) {
|
|
283
|
+
return (ast, name, options) => {
|
|
284
|
+
assertValidImportBinding(name, "name");
|
|
285
|
+
assertOptions(options, ["type", "initial", "required", "imports"]);
|
|
286
|
+
if (options?.required && options.initial !== undefined) {
|
|
287
|
+
throw dialectError("`required` and `initial` cannot be combined — drop one, or use `.modify()` to make this edit directly.");
|
|
288
|
+
}
|
|
289
|
+
const generic = typeArgument(options?.type);
|
|
290
|
+
const initial = options?.initial === undefined ? "" : elementText({ expression: options.initial });
|
|
291
|
+
const initializer = options?.required ? `${fn}.required${generic}()` : `${fn}${generic}(${initial})`;
|
|
292
|
+
addMember(ast, opName, name, VIEW_DECORATORS, { initializer, core: fn }, options?.imports);
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Adds `readonly name = input<type>(initial)`, or `input.required<type>()` with `required`, to
|
|
297
|
+
* the file's only `@Component` or `@Directive` class, after its last property, and imports
|
|
298
|
+
* `input`. The same declaration already there is a no-op.
|
|
299
|
+
*/
|
|
300
|
+
export const addInput = signalInputOp("addInput", "input");
|
|
301
|
+
/** Same as `addInput`, with `model()` for a two-way bound property. */
|
|
302
|
+
export const addModel = signalInputOp("addModel", "model");
|
|
303
|
+
/** Adds `readonly name = output<type>()` to the file's only `@Component` or `@Directive` class and imports `output`. */
|
|
304
|
+
export function addOutput(ast, name, options) {
|
|
305
|
+
assertValidImportBinding(name, "name");
|
|
306
|
+
assertOptions(options, ["type", "imports"]);
|
|
307
|
+
addMember(ast, "addOutput", name, VIEW_DECORATORS, { initializer: `output${typeArgument(options?.type)}()`, core: "output" }, options?.imports);
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Adds `private readonly name = inject(token)` to the file's only class decorated with
|
|
311
|
+
* `@Component`, `@Directive`, `@Pipe`, `@Injectable` or `@Service`, and imports `inject`.
|
|
312
|
+
* `token` is an identifier or `{ expression }`; `options.scope` replaces `private`.
|
|
313
|
+
*/
|
|
314
|
+
export function addInjection(ast, name, token, options) {
|
|
315
|
+
assertValidImportBinding(name, "name");
|
|
316
|
+
assertOptions(options, ["scope", "imports"]);
|
|
317
|
+
const initializer = `inject(${elementText(token)})`;
|
|
318
|
+
addMember(ast, "addInjection", name, INJECTABLE_DECORATORS, { initializer, scope: options?.scope ?? "private", core: "inject" }, options?.imports);
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Adds `protected readonly name = signal<type>(initial)` to the file's only `@Component` or
|
|
322
|
+
* `@Directive` class and imports `signal`. `options.scope` replaces `protected`.
|
|
323
|
+
*/
|
|
324
|
+
export function addSignal(ast, name, initial, options) {
|
|
325
|
+
assertValidImportBinding(name, "name");
|
|
326
|
+
assertOptions(options, ["type", "scope", "imports"]);
|
|
327
|
+
const initializer = `signal${typeArgument(options?.type)}(${elementText({ expression: initial })})`;
|
|
328
|
+
addMember(ast, "addSignal", name, VIEW_DECORATORS, { initializer, scope: options?.scope ?? "protected", core: "signal" }, options?.imports);
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Adds `protected readonly name = computed<type>(() => expression)` to the file's only
|
|
332
|
+
* `@Component` or `@Directive` class and imports `computed`. `options.scope` replaces `protected`.
|
|
333
|
+
*/
|
|
334
|
+
export function addComputed(ast, name, expression, options) {
|
|
335
|
+
assertValidImportBinding(name, "name");
|
|
336
|
+
assertOptions(options, ["type", "scope", "imports"]);
|
|
337
|
+
const body = elementText({ expression });
|
|
338
|
+
// An arrow function reads a leading `{` as a block, so an object literal needs parentheses.
|
|
339
|
+
const arrow = body.startsWith("{") ? `() => (${body})` : `() => ${body}`;
|
|
340
|
+
const initializer = `computed${typeArgument(options?.type)}(${arrow})`;
|
|
341
|
+
addMember(ast, "addComputed", name, VIEW_DECORATORS, { initializer, scope: options?.scope ?? "protected", core: "computed" }, options?.imports);
|
|
342
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Root } from "postcss";
|
|
2
|
+
/**
|
|
3
|
+
* Parses `source` into a PostCSS `Root`, throwing on a CSS syntax error. PostCSS keeps every
|
|
4
|
+
* whitespace, comment, and BOM byte in node `raws`, so `print` returns an unedited source as is.
|
|
5
|
+
*/
|
|
6
|
+
export declare function parse(source: string): Root;
|
|
7
|
+
export declare function print(root: Root): string;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { parse as parseCss } from "postcss";
|
|
2
|
+
/**
|
|
3
|
+
* Parses `source` into a PostCSS `Root`, throwing on a CSS syntax error. PostCSS keeps every
|
|
4
|
+
* whitespace, comment, and BOM byte in node `raws`, so `print` returns an unedited source as is.
|
|
5
|
+
*/
|
|
6
|
+
export function parse(source) {
|
|
7
|
+
try {
|
|
8
|
+
return parseCss(source);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
throw new Error("invalid CSS");
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function print(root) {
|
|
15
|
+
return root.toString();
|
|
16
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Root } from "postcss";
|
|
2
|
+
import { type Handle, type Query } from "../../core/define-dialect.ts";
|
|
3
|
+
import { getDeclaration, type CssTarget, type DeclarationOptions } from "./ops.ts";
|
|
4
|
+
export * as astLibrary from "postcss";
|
|
5
|
+
export { getDeclaration };
|
|
6
|
+
export type { CssTarget, DeclarationOptions };
|
|
7
|
+
type CssOps = {
|
|
8
|
+
setDeclaration: (ast: Root, target: CssTarget, property: string, value: string, options?: DeclarationOptions) => void;
|
|
9
|
+
removeDeclaration: (ast: Root, target: CssTarget, property: string) => void;
|
|
10
|
+
getDeclaration: Query<Root, [target: CssTarget, property: string], ReturnType<typeof getDeclaration>>;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Opens a `.css` file to set and remove declarations. A target names one top-level block —
|
|
14
|
+
* `{ selector: ":root" }`, `{ atRule: "theme" }`, or `{ atRule: "media", params, selector }` —
|
|
15
|
+
* and every op edits only the declaration it addresses: comments, `@import`s, other rules,
|
|
16
|
+
* indentation, line endings, and a BOM survive. Any other extension throws synchronously with
|
|
17
|
+
* the `dialect operation failed: ` prefix. `.modify(fn)` hands `fn` the live PostCSS `Root`;
|
|
18
|
+
* use `astLibrary` (`postcss`) for anything the ops do not cover.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* import * as css from "@pbuilder/sdk/css";
|
|
22
|
+
*
|
|
23
|
+
* // tokens.css before: @import "tailwindcss";\n\n@theme {\n --color-primary: #0b254d;\n}\n
|
|
24
|
+
* export const run = async () => {
|
|
25
|
+
* await css
|
|
26
|
+
* .find("tokens.css")
|
|
27
|
+
* .setDeclaration({ atRule: "theme" }, "--color-primary", "#1974f9")
|
|
28
|
+
* .setDeclaration({ selector: "html[data-theme='nylon']" }, "--color-primary", "#0b254d");
|
|
29
|
+
* };
|
|
30
|
+
* // -> @import "tailwindcss";
|
|
31
|
+
* // ->
|
|
32
|
+
* // -> @theme {
|
|
33
|
+
* // -> --color-primary: #1974f9;
|
|
34
|
+
* // -> }
|
|
35
|
+
* // ->
|
|
36
|
+
* // -> html[data-theme='nylon'] {
|
|
37
|
+
* // -> --color-primary: #0b254d;
|
|
38
|
+
* // -> }
|
|
39
|
+
*/
|
|
40
|
+
export declare function find(path: string): Handle<"found", Root, CssOps>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { defineDialect, defineOpPack, query, withOps } from "../../core/define-dialect.js";
|
|
2
|
+
import { parse, print } from "./ast.js";
|
|
3
|
+
import { getDeclaration, removeDeclaration, setDeclaration } from "./ops.js";
|
|
4
|
+
export * as astLibrary from "postcss";
|
|
5
|
+
export { getDeclaration };
|
|
6
|
+
const opsPack = defineOpPack({ setDeclaration, removeDeclaration, getDeclaration: query(getDeclaration) });
|
|
7
|
+
const cssDialect = withOps(defineDialect({ extensions: [".css"], ast: { parse, print }, ops: {} }), opsPack);
|
|
8
|
+
/**
|
|
9
|
+
* Opens a `.css` file to set and remove declarations. A target names one top-level block —
|
|
10
|
+
* `{ selector: ":root" }`, `{ atRule: "theme" }`, or `{ atRule: "media", params, selector }` —
|
|
11
|
+
* and every op edits only the declaration it addresses: comments, `@import`s, other rules,
|
|
12
|
+
* indentation, line endings, and a BOM survive. Any other extension throws synchronously with
|
|
13
|
+
* the `dialect operation failed: ` prefix. `.modify(fn)` hands `fn` the live PostCSS `Root`;
|
|
14
|
+
* use `astLibrary` (`postcss`) for anything the ops do not cover.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* import * as css from "@pbuilder/sdk/css";
|
|
18
|
+
*
|
|
19
|
+
* // tokens.css before: @import "tailwindcss";\n\n@theme {\n --color-primary: #0b254d;\n}\n
|
|
20
|
+
* export const run = async () => {
|
|
21
|
+
* await css
|
|
22
|
+
* .find("tokens.css")
|
|
23
|
+
* .setDeclaration({ atRule: "theme" }, "--color-primary", "#1974f9")
|
|
24
|
+
* .setDeclaration({ selector: "html[data-theme='nylon']" }, "--color-primary", "#0b254d");
|
|
25
|
+
* };
|
|
26
|
+
* // -> @import "tailwindcss";
|
|
27
|
+
* // ->
|
|
28
|
+
* // -> @theme {
|
|
29
|
+
* // -> --color-primary: #1974f9;
|
|
30
|
+
* // -> }
|
|
31
|
+
* // ->
|
|
32
|
+
* // -> html[data-theme='nylon'] {
|
|
33
|
+
* // -> --color-primary: #0b254d;
|
|
34
|
+
* // -> }
|
|
35
|
+
*/
|
|
36
|
+
export function find(path) {
|
|
37
|
+
return cssDialect.find(path);
|
|
38
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type Root } from "postcss";
|
|
2
|
+
/**
|
|
3
|
+
* Addresses one top-level block: `{ selector }` is a rule, `{ atRule, params? }` is an at-rule's
|
|
4
|
+
* own body (`@theme`), and both together are a rule inside that at-rule. The selector and params
|
|
5
|
+
* match after trimming; the at-rule name, written without `@`, matches case-insensitively.
|
|
6
|
+
*/
|
|
7
|
+
export interface CssTarget {
|
|
8
|
+
selector?: string;
|
|
9
|
+
atRule?: string;
|
|
10
|
+
params?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface DeclarationOptions {
|
|
13
|
+
before?: string;
|
|
14
|
+
after?: string;
|
|
15
|
+
important?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Sets `property` to `value` in the `target` block: an existing declaration is updated in place,
|
|
19
|
+
* a new one goes last in the block or next to the `before` / `after` anchor, and a missing block
|
|
20
|
+
* is created at the end of the file. Setting the value a declaration already has changes nothing.
|
|
21
|
+
*/
|
|
22
|
+
export declare const setDeclaration: (ast: Root, args_0: CssTarget, args_1: string, args_2: string, args_3?: DeclarationOptions | undefined) => void;
|
|
23
|
+
/**
|
|
24
|
+
* Reads `property` from the `target` block of a parsed `Root`, such as the one `.modify(fn)`
|
|
25
|
+
* receives: `{ value, important }`, or `undefined` when the block or declaration is missing.
|
|
26
|
+
* Not an op — it returns a value — so it is called directly, never chained on a handle.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* import * as css from "@pbuilder/sdk/css";
|
|
30
|
+
*
|
|
31
|
+
* // tokens.css: @theme {\n --radius: 4px;\n}\n
|
|
32
|
+
* export const run = async () => {
|
|
33
|
+
* await css.find("tokens.css").modify((root) => {
|
|
34
|
+
* const radius = css.getDeclaration(root, { atRule: "theme" }, "--radius");
|
|
35
|
+
* // -> { value: "4px", important: false }
|
|
36
|
+
* });
|
|
37
|
+
* };
|
|
38
|
+
*/
|
|
39
|
+
export declare function getDeclaration(root: Root, target: CssTarget, property: string): {
|
|
40
|
+
value: string;
|
|
41
|
+
important: boolean;
|
|
42
|
+
} | undefined;
|
|
43
|
+
/** Removes `property` from the `target` block; a missing block or declaration is a no-op. */
|
|
44
|
+
export declare const removeDeclaration: (ast: Root, args_0: CssTarget, args_1: string) => void;
|