@tokamaq/build 0.0.0-stage → 0.1.0-dev.1
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/LICENSE +21 -0
- package/README.md +346 -2
- package/package.json +71 -4
- package/src/artifact-bundle.ts +86 -0
- package/src/auth-dependencies.ts +65 -0
- package/src/build.ts +73 -0
- package/src/client-surface.ts +179 -0
- package/src/compiler.ts +47 -0
- package/src/component-parts.ts +928 -0
- package/src/contributions.ts +534 -0
- package/src/css.ts +25 -0
- package/src/descriptor.ts +8 -0
- package/src/exports.ts +79 -0
- package/src/hook-targets.ts +46 -0
- package/src/part-props.ts +172 -0
- package/src/plugin-boundary.ts +48 -0
- package/src/ui-build-config.ts +48 -0
- package/src/vite.ts +284 -0
- package/src/window-state.ts +230 -0
- package/src/window-test-config.ts +48 -0
|
@@ -0,0 +1,928 @@
|
|
|
1
|
+
import {
|
|
2
|
+
attributeFilters,
|
|
3
|
+
isAriaAttribute,
|
|
4
|
+
isSearchAttribute,
|
|
5
|
+
resolveScreenSearch,
|
|
6
|
+
screenElements,
|
|
7
|
+
screenTarget,
|
|
8
|
+
type ScreenSearch,
|
|
9
|
+
type ScreenTree,
|
|
10
|
+
unnamedTargetWarning,
|
|
11
|
+
} from "@tokamaq/sdk/internal/build";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
15
|
+
import type MagicString from "magic-string";
|
|
16
|
+
import ts from "typescript";
|
|
17
|
+
import { brand, importModule, inSource, unalias, type Element, type ElementMount } from "./compiler.ts";
|
|
18
|
+
import { partProps } from "./part-props.ts";
|
|
19
|
+
|
|
20
|
+
type Part = {
|
|
21
|
+
target: string;
|
|
22
|
+
props: string;
|
|
23
|
+
type: string;
|
|
24
|
+
elementType?: () => string;
|
|
25
|
+
fingerprint?: string;
|
|
26
|
+
ambiguous?: boolean;
|
|
27
|
+
row?: string;
|
|
28
|
+
unnamed?: boolean;
|
|
29
|
+
attributes?: string[];
|
|
30
|
+
computed?: string[];
|
|
31
|
+
};
|
|
32
|
+
type Tree = {
|
|
33
|
+
part?: Part;
|
|
34
|
+
renderFunction?: Part;
|
|
35
|
+
opening?: ts.JsxOpeningLikeElement;
|
|
36
|
+
children: Map<string, Tree>;
|
|
37
|
+
entries: { name: string; node: ts.Node; fixed: boolean; tree: Tree }[];
|
|
38
|
+
};
|
|
39
|
+
type Row = { item: string; index: string; type: () => string; value: () => string };
|
|
40
|
+
type Scope = { tree: Tree; props: string; type: () => string; row?: Row; renderFunction?: () => void };
|
|
41
|
+
type Binding = { node: ts.ConciseBody; parameter: ts.ParameterDeclaration };
|
|
42
|
+
|
|
43
|
+
const branch = (): Tree => ({ children: new Map(), entries: [] });
|
|
44
|
+
const voidTags = new Set("area base br col embed hr img input link meta param source track wbr".split(" "));
|
|
45
|
+
|
|
46
|
+
function child(parent: Tree, name: string, node: ts.Node, fixed = false) {
|
|
47
|
+
const tree = branch();
|
|
48
|
+
parent.entries.push({ name, node, fixed, tree });
|
|
49
|
+
return tree;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function tagIdentity(opening: ts.JsxOpeningLikeElement, part: Part) {
|
|
53
|
+
// Only what says which element this is; anything else is an ordinary edit.
|
|
54
|
+
const properties = opening.attributes.properties;
|
|
55
|
+
const lastSpread = properties.map(ts.isJsxSpreadAttribute).lastIndexOf(true);
|
|
56
|
+
const attributes = properties
|
|
57
|
+
.flatMap((attribute, index) => {
|
|
58
|
+
if (!ts.isJsxAttribute(attribute)) return [];
|
|
59
|
+
const name = attribute.name.getText();
|
|
60
|
+
const value = attribute.initializer;
|
|
61
|
+
const expression = value && ts.isJsxExpression(value) ? value.expression : value;
|
|
62
|
+
const text = expression && ts.isStringLiteralLike(expression) ? expression.text : null;
|
|
63
|
+
if (isSearchAttribute(name) || isAriaAttribute(name)) {
|
|
64
|
+
// A later spread can replace the value when the screen runs, so only
|
|
65
|
+
// a literal that nothing can override is safe to search by.
|
|
66
|
+
if (text !== null && index > lastSpread) (part.attributes ??= []).push(name, text);
|
|
67
|
+
else (part.computed ??= []).push(name);
|
|
68
|
+
}
|
|
69
|
+
if (isSearchAttribute(name) || name === "name" || name === "for") return [[name, text]];
|
|
70
|
+
// A static ARIA value tells siblings apart; a computed one is state.
|
|
71
|
+
return /^aria-/.test(name) && text !== null ? [[name, text]] : [];
|
|
72
|
+
})
|
|
73
|
+
.sort(([a], [b]) => String(a).localeCompare(String(b)));
|
|
74
|
+
return [opening.tagName.getText(), attributes];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function assignParts(
|
|
78
|
+
tree: Tree,
|
|
79
|
+
prefix: string,
|
|
80
|
+
paths: Map<string, Part>,
|
|
81
|
+
inherited?: string,
|
|
82
|
+
ambiguous = false,
|
|
83
|
+
) {
|
|
84
|
+
const fixed = new Map<string, ts.Node>();
|
|
85
|
+
const scopes = new Map<string, ts.Node>();
|
|
86
|
+
const fixedCounts = new Map<string, number>();
|
|
87
|
+
const counts = new Map<string, number>();
|
|
88
|
+
const identities = new Map<Tree, string>();
|
|
89
|
+
const times = new Map<string, number>();
|
|
90
|
+
// A render function with no elements of its own (a fragment, a provider) is
|
|
91
|
+
// only something to attach to. Two with one name cannot be told apart, so
|
|
92
|
+
// they leave the tree instead of failing a build that worked before.
|
|
93
|
+
const groups = new Map<string, number>();
|
|
94
|
+
for (const { name, tree: child } of tree.entries)
|
|
95
|
+
if (!child.part) groups.set(name, (groups.get(name) ?? 0) + 1);
|
|
96
|
+
tree.entries = tree.entries.filter(
|
|
97
|
+
({ name, tree: child }) => child.part || child.entries.length || groups.get(name) === 1,
|
|
98
|
+
);
|
|
99
|
+
for (const { name, node, fixed: named, tree: child } of tree.entries) {
|
|
100
|
+
if (named) {
|
|
101
|
+
if (!fixed.has(name)) fixed.set(name, node);
|
|
102
|
+
fixedCounts.set(name, (fixedCounts.get(name) ?? 0) + 1);
|
|
103
|
+
}
|
|
104
|
+
if (!child.part) {
|
|
105
|
+
const previous = scopes.get(name);
|
|
106
|
+
if (previous)
|
|
107
|
+
throw problem(
|
|
108
|
+
node,
|
|
109
|
+
`Duplicate screen segment "${name}" (first declared in ${previous.getSourceFile().fileName})`,
|
|
110
|
+
);
|
|
111
|
+
scopes.set(name, node);
|
|
112
|
+
}
|
|
113
|
+
counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
114
|
+
if (child.opening) {
|
|
115
|
+
const identity = JSON.stringify(tagIdentity(child.opening, child.part!));
|
|
116
|
+
identities.set(child, identity);
|
|
117
|
+
const key = name + ":" + identity;
|
|
118
|
+
times.set(key, (times.get(key) ?? 0) + 1);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const positions = new Map<string, number>();
|
|
122
|
+
for (const { name, node, fixed: named, tree: child } of tree.entries) {
|
|
123
|
+
const first = named && fixed.get(name) === node;
|
|
124
|
+
const position = first ? 1 : (positions.get(name) ?? (fixed.has(name) ? 1 : 0)) + 1;
|
|
125
|
+
if (!first) positions.set(name, position);
|
|
126
|
+
const key = position === 1 ? name : `${name}$${position}`;
|
|
127
|
+
const target = `${prefix}.${key}`;
|
|
128
|
+
tree.children.set(key, child);
|
|
129
|
+
const positional = child.opening && counts.get(name)! > 1 && (!first || fixedCounts.get(name)! > 1);
|
|
130
|
+
// A unique explicit name still carries any positional ancestors.
|
|
131
|
+
let fingerprint = inherited;
|
|
132
|
+
let uncertain = ambiguous;
|
|
133
|
+
if (positional) {
|
|
134
|
+
const identity = identities.get(child)!;
|
|
135
|
+
// Siblings their attributes cannot tell apart: a swap goes unnoticed, so
|
|
136
|
+
// the add-on's build asks for a name. Their contents stay out of the
|
|
137
|
+
// fingerprint, or every edit inside would read as a move.
|
|
138
|
+
uncertain ||= times.get(name + ":" + identity)! > 1;
|
|
139
|
+
fingerprint = createHash("sha256")
|
|
140
|
+
.update(JSON.stringify([inherited, identity]))
|
|
141
|
+
.digest("base64url")
|
|
142
|
+
.slice(0, 12);
|
|
143
|
+
}
|
|
144
|
+
if (child.part) {
|
|
145
|
+
Object.assign(child.part, { target, fingerprint, ambiguous: uncertain });
|
|
146
|
+
paths.set(target, child.part);
|
|
147
|
+
}
|
|
148
|
+
if (child.renderFunction) {
|
|
149
|
+
child.renderFunction.target = target;
|
|
150
|
+
paths.set(target, child.renderFunction);
|
|
151
|
+
}
|
|
152
|
+
assignParts(child, target, paths, fingerprint, uncertain);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function segment(name: string) {
|
|
157
|
+
return name
|
|
158
|
+
.replace(/[^\w]/g, (c) => `$${c.charCodeAt(0).toString(16)}$`)
|
|
159
|
+
.replace(/^(target|fingerprint|__proto__|constructor|prototype)$/, (name) => "$" + name);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function componentParts(entry: ts.SourceFile, program: ts.Program, plugin: string, root: string) {
|
|
163
|
+
const files = new Map<ts.SourceFile, Map<Element, Part>>();
|
|
164
|
+
const bindings = new Map<ts.SourceFile, (Binding & { name: string })[]>();
|
|
165
|
+
const functions = new Map<ts.SourceFile, Map<ts.ConciseBody, Part>>();
|
|
166
|
+
const rows = new Map<
|
|
167
|
+
ts.SourceFile,
|
|
168
|
+
{ node: ts.ArrowFunction | ts.FunctionExpression; item: string; index: string }[]
|
|
169
|
+
>();
|
|
170
|
+
const paths = new Map<string, Part>();
|
|
171
|
+
const tree = branch();
|
|
172
|
+
const checker = program.getTypeChecker();
|
|
173
|
+
const module = checker.getSymbolAtLocation(entry);
|
|
174
|
+
const exports = module ? checker.getExportsOfModule(module) : [];
|
|
175
|
+
const find = exports.find((symbol) => symbol.name === "find");
|
|
176
|
+
if (find)
|
|
177
|
+
throw problem(
|
|
178
|
+
find.declarations?.[0] ?? entry,
|
|
179
|
+
"The plugin builder generates the public find export; use a different name",
|
|
180
|
+
);
|
|
181
|
+
const exported = new Map(exports.map((symbol) => [unalias(checker, symbol), symbol.name]));
|
|
182
|
+
const entryImport = JSON.stringify(
|
|
183
|
+
"../" + relative(dirname(entry.fileName), entry.fileName).replace(/\.tsx?$/, ""),
|
|
184
|
+
);
|
|
185
|
+
|
|
186
|
+
const sources = program
|
|
187
|
+
.getSourceFiles()
|
|
188
|
+
.filter((file) => !file.isDeclarationFile && inSource(root, file.fileName))
|
|
189
|
+
.sort((a, b) => a.fileName.localeCompare(b.fileName));
|
|
190
|
+
const { propsType, typeShape, componentValue, annotation, privateDeclarations } = partProps(
|
|
191
|
+
entry,
|
|
192
|
+
checker,
|
|
193
|
+
root,
|
|
194
|
+
sources,
|
|
195
|
+
);
|
|
196
|
+
const aliases = new Map<string, string>();
|
|
197
|
+
let captures = 0;
|
|
198
|
+
const solidBuiltins = new Set([
|
|
199
|
+
"Show",
|
|
200
|
+
"For",
|
|
201
|
+
"Index",
|
|
202
|
+
"Switch",
|
|
203
|
+
"Match",
|
|
204
|
+
"Suspense",
|
|
205
|
+
"ErrorBoundary",
|
|
206
|
+
"Dynamic",
|
|
207
|
+
"Portal",
|
|
208
|
+
"Errored",
|
|
209
|
+
]);
|
|
210
|
+
|
|
211
|
+
function solidTag(tag: ts.JsxTagNameExpression) {
|
|
212
|
+
const name = ts.isPropertyAccessExpression(tag) ? tag.name : tag;
|
|
213
|
+
const binding = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(tag) ? tag.expression : tag);
|
|
214
|
+
const declaration = binding?.declarations?.find(
|
|
215
|
+
(node) => ts.isImportSpecifier(node) || ts.isNamespaceImport(node),
|
|
216
|
+
);
|
|
217
|
+
const module = importModule(declaration);
|
|
218
|
+
if (module !== "solid-js" && module !== "@solidjs/web" && module !== "solid-js/web") return;
|
|
219
|
+
return declaration && ts.isImportSpecifier(declaration)
|
|
220
|
+
? (declaration.propertyName ?? declaration.name).text
|
|
221
|
+
: name.getText();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function alias(shape: string) {
|
|
225
|
+
if (shape === "{}") return shape;
|
|
226
|
+
const name = aliases.get(shape) ?? `P${aliases.size + 1}`;
|
|
227
|
+
aliases.set(shape, name);
|
|
228
|
+
return name;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
for (const source of sources) {
|
|
232
|
+
const elements = new Map<Element, Part>();
|
|
233
|
+
const pending: (Binding & { name: string })[] = [];
|
|
234
|
+
const renderFunctions = new Map<ts.ConciseBody, Part>();
|
|
235
|
+
const rowBindings: { node: ts.ArrowFunction | ts.FunctionExpression; item: string; index: string }[] = [];
|
|
236
|
+
const base: Scope = { tree, props: "{}", type: () => "{}" };
|
|
237
|
+
|
|
238
|
+
function visit(node: ts.Node, scope: Scope) {
|
|
239
|
+
if (ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
|
|
240
|
+
const variable = ts.isVariableDeclaration(node.parent)
|
|
241
|
+
? node.parent
|
|
242
|
+
: ts.isCallExpression(node.parent) &&
|
|
243
|
+
ts.isVariableDeclaration(node.parent.parent) &&
|
|
244
|
+
brand(checker.getTypeAtLocation(node.parent), "viewBrand")
|
|
245
|
+
? node.parent.parent
|
|
246
|
+
: undefined;
|
|
247
|
+
const name = ts.isFunctionDeclaration(node) ? node.name : variable?.name;
|
|
248
|
+
const isDefault =
|
|
249
|
+
ts.isExportAssignment(node.parent) ||
|
|
250
|
+
(ts.isFunctionDeclaration(node) &&
|
|
251
|
+
node.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword));
|
|
252
|
+
if ((isDefault || (name && ts.isIdentifier(name))) && node.body) {
|
|
253
|
+
// Named functions own their JSX; inline callbacks retain the enclosing element and props.
|
|
254
|
+
const declared = name && checker.getSymbolAtLocation(name);
|
|
255
|
+
const publicName = isDefault ? "default" : declared && exported.get(declared);
|
|
256
|
+
const parameter = node.parameters[0];
|
|
257
|
+
const props = parameter ? `__tokamaqProps${++captures}` : scope.props;
|
|
258
|
+
const outer = scope;
|
|
259
|
+
let group: ReturnType<typeof child>;
|
|
260
|
+
const identity = () =>
|
|
261
|
+
(group ??= child(outer.tree, segment(name?.getText(source) ?? "Default"), node, true));
|
|
262
|
+
let type: string;
|
|
263
|
+
scope = {
|
|
264
|
+
get tree() {
|
|
265
|
+
return identity();
|
|
266
|
+
},
|
|
267
|
+
props,
|
|
268
|
+
row: outer.row,
|
|
269
|
+
type: () => {
|
|
270
|
+
if (type) return type;
|
|
271
|
+
if (!parameter) return outer.type();
|
|
272
|
+
pending.push({ node: node.body!, parameter, name: props });
|
|
273
|
+
const callable = declared && checker.getTypeOfSymbolAtLocation(declared, node);
|
|
274
|
+
const shape =
|
|
275
|
+
publicName && callable && (!ts.isCallExpression(node.parent) || brand(callable, "viewBrand"))
|
|
276
|
+
? `Parameters<typeof import(${entryImport})[${JSON.stringify(publicName)}]>[0]`
|
|
277
|
+
: propsType(parameter);
|
|
278
|
+
return (type = alias(shape));
|
|
279
|
+
},
|
|
280
|
+
renderFunction: () => {
|
|
281
|
+
const body = node.body!;
|
|
282
|
+
// A component is named like one. A lowercase helper that returns
|
|
283
|
+
// JSX is called, not mounted, so it has no instance to attach to.
|
|
284
|
+
if (!isDefault && !/^[A-Z]/.test(name!.getText(source))) return;
|
|
285
|
+
if (renderFunctions.has(body)) return;
|
|
286
|
+
const part = { target: "", props, type: scope.type() };
|
|
287
|
+
identity().renderFunction = part;
|
|
288
|
+
renderFunctions.set(body, part);
|
|
289
|
+
},
|
|
290
|
+
};
|
|
291
|
+
visit(node.body, scope);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (ts.isJsxFragment(node) || ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node))
|
|
297
|
+
scope.renderFunction?.();
|
|
298
|
+
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {
|
|
299
|
+
const opening = ts.isJsxElement(node) ? node.openingElement : node;
|
|
300
|
+
if (
|
|
301
|
+
opening.attributes.properties.some(
|
|
302
|
+
(attribute) => ts.isJsxAttribute(attribute) && attribute.name.getText() === "data-part-ignore",
|
|
303
|
+
)
|
|
304
|
+
)
|
|
305
|
+
return;
|
|
306
|
+
const tag = opening.tagName;
|
|
307
|
+
const original =
|
|
308
|
+
ts.isPropertyAccessExpression(tag) && tag.name.text === "Children" ? tag.expression : tag;
|
|
309
|
+
if (brand(checker.getTypeAtLocation(original), "originalElementBrand")) {
|
|
310
|
+
ts.forEachChild(node, (child) => visit(child, scope));
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const builtin = solidTag(tag);
|
|
314
|
+
if (builtin && solidBuiltins.has(builtin)) {
|
|
315
|
+
const callback = builtin === "For" || builtin === "Index" ? childCallback(node) : undefined;
|
|
316
|
+
if (callback && !callback.parameters.some((p) => p.dotDotDotToken)) {
|
|
317
|
+
const item = `__tokamaqItem${++captures}`;
|
|
318
|
+
const index = `__tokamaqIndex${captures}`;
|
|
319
|
+
let rowType: string | undefined;
|
|
320
|
+
const parent = scope.row;
|
|
321
|
+
const row: Row = {
|
|
322
|
+
item,
|
|
323
|
+
index,
|
|
324
|
+
value: () => `{ item: ${item}, index: ${index}${parent ? `, parent: ${parent.value()}` : ""} }`,
|
|
325
|
+
type: () => {
|
|
326
|
+
if (rowType) return rowType;
|
|
327
|
+
rowBindings.push({ node: callback, item, index });
|
|
328
|
+
const [first, second] = callback.parameters;
|
|
329
|
+
const contextual = checker.getContextualType(callback);
|
|
330
|
+
const signature = contextual?.getCallSignatures()[0];
|
|
331
|
+
const contextualItem = signature?.parameters[0];
|
|
332
|
+
const itemType = first
|
|
333
|
+
? propsType(first)
|
|
334
|
+
: contextualItem
|
|
335
|
+
? checker.typeToString(checker.getTypeOfSymbolAtLocation(contextualItem, callback))
|
|
336
|
+
: "unknown";
|
|
337
|
+
const keyed = opening.attributes.properties.find(
|
|
338
|
+
(attr): attr is ts.JsxAttribute =>
|
|
339
|
+
ts.isJsxAttribute(attr) && attr.name.getText() === "keyed",
|
|
340
|
+
)?.initializer;
|
|
341
|
+
const positional =
|
|
342
|
+
keyed && ts.isJsxExpression(keyed) && keyed.expression?.kind === ts.SyntaxKind.FalseKeyword;
|
|
343
|
+
const indexType = second
|
|
344
|
+
? propsType(second)
|
|
345
|
+
: positional || builtin === "Index"
|
|
346
|
+
? "number"
|
|
347
|
+
: "() => number";
|
|
348
|
+
return (rowType = `{ readonly item: ${itemType}; readonly index: ${indexType}${parent ? `; readonly parent: ${parent.type()}` : ""} }`);
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
function visitRow(child: ts.Node) {
|
|
352
|
+
if (child === callback) visit(callback.body, { ...scope, row });
|
|
353
|
+
else if (ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child)) visit(child, scope);
|
|
354
|
+
else ts.forEachChild(child, visitRow);
|
|
355
|
+
}
|
|
356
|
+
ts.forEachChild(node, visitRow);
|
|
357
|
+
} else ts.forEachChild(node, (child) => visit(child, scope));
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
const tagName = tag.getText(source);
|
|
361
|
+
const named = staticName(opening, "data-part") ?? staticName(opening, "id");
|
|
362
|
+
const group = child(scope.tree, segment(named ?? tagName), node, named !== undefined);
|
|
363
|
+
const type = scope.type();
|
|
364
|
+
const part: Part = {
|
|
365
|
+
target: "",
|
|
366
|
+
unnamed: named === undefined && /^[a-z][\w-]*$/.test(tagName),
|
|
367
|
+
props: scope.props,
|
|
368
|
+
elementType: () => {
|
|
369
|
+
if (/^[a-z][\w-]*$/.test(tagName)) return JSON.stringify(tagName);
|
|
370
|
+
const signature = checker.getResolvedSignature(opening);
|
|
371
|
+
const parameter = signature?.parameters[0];
|
|
372
|
+
if (!parameter) return "{}";
|
|
373
|
+
const declaration = parameter.valueDeclaration;
|
|
374
|
+
const type = checker.getTypeOfSymbolAtLocation(parameter, opening);
|
|
375
|
+
if (
|
|
376
|
+
declaration &&
|
|
377
|
+
ts.isParameter(declaration) &&
|
|
378
|
+
inSource(root, declaration.getSourceFile().fileName) &&
|
|
379
|
+
checker.getTypeAtLocation(declaration) === type
|
|
380
|
+
)
|
|
381
|
+
return propsType(declaration);
|
|
382
|
+
const value = componentValue(tag);
|
|
383
|
+
if (value) {
|
|
384
|
+
const args = opening.typeArguments?.map(annotation).join(", ");
|
|
385
|
+
return `C<typeof ${value}${args ? `<${args}>` : ""}>`;
|
|
386
|
+
}
|
|
387
|
+
return typeShape(type);
|
|
388
|
+
},
|
|
389
|
+
type: scope.row ? alias(`${type} & { readonly $row: ${scope.row.type()} }`) : type,
|
|
390
|
+
row: scope.row?.value(),
|
|
391
|
+
};
|
|
392
|
+
group.part = part;
|
|
393
|
+
group.opening = opening;
|
|
394
|
+
scope = { ...scope, tree: group };
|
|
395
|
+
ts.forEachChild(node, (child) => visit(child, scope));
|
|
396
|
+
elements.set(node, part);
|
|
397
|
+
} else ts.forEachChild(node, (child) => visit(child, scope));
|
|
398
|
+
}
|
|
399
|
+
visit(source, base);
|
|
400
|
+
if (elements.size) files.set(source, elements);
|
|
401
|
+
if (renderFunctions.size) functions.set(source, renderFunctions);
|
|
402
|
+
if (pending.length) bindings.set(source, pending);
|
|
403
|
+
if (rowBindings.length) rows.set(source, rowBindings);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
assignParts(tree, plugin, paths);
|
|
407
|
+
|
|
408
|
+
function compactParts(node: Tree, root = false): ScreenTree {
|
|
409
|
+
const fingerprint = node.part?.fingerprint ?? null;
|
|
410
|
+
return [
|
|
411
|
+
...(node.part
|
|
412
|
+
? ["", node.part.attributes ? [fingerprint, ...node.part.attributes] : fingerprint]
|
|
413
|
+
: root || !node.renderFunction
|
|
414
|
+
? [":", null]
|
|
415
|
+
: []),
|
|
416
|
+
...[...node.children].flatMap(([key, child]) => [
|
|
417
|
+
key,
|
|
418
|
+
child.part && !child.children.size && !child.part.attributes
|
|
419
|
+
? (child.part.fingerprint ?? null)
|
|
420
|
+
: compactParts(child),
|
|
421
|
+
]),
|
|
422
|
+
];
|
|
423
|
+
}
|
|
424
|
+
const compact = compactParts(tree, true);
|
|
425
|
+
const elements = screenElements(plugin, compact).map((element) => {
|
|
426
|
+
const computed = paths.get(element.target)?.computed;
|
|
427
|
+
return computed ? { ...element, computed } : element;
|
|
428
|
+
});
|
|
429
|
+
const renderFunctions = screenElements(plugin, compact, "render function");
|
|
430
|
+
// Pack the shape into a string so the bundle keeps its compact layout.
|
|
431
|
+
const packed = JSON.stringify(compact);
|
|
432
|
+
|
|
433
|
+
return {
|
|
434
|
+
has: (node: Element) => files.get(node.getSourceFile())?.has(node) ?? false,
|
|
435
|
+
resolve(search: ScreenSearch, action: string) {
|
|
436
|
+
const attach = action === "attach";
|
|
437
|
+
const result = resolveScreenSearch(
|
|
438
|
+
attach ? renderFunctions : elements,
|
|
439
|
+
search,
|
|
440
|
+
undefined,
|
|
441
|
+
attach ? "render function" : "element",
|
|
442
|
+
);
|
|
443
|
+
if (
|
|
444
|
+
result.reason &&
|
|
445
|
+
!(attach ? renderFunctions : elements).some(({ name }) => name === search.name) &&
|
|
446
|
+
(attach ? elements : renderFunctions).some(({ name }) => name === search.name)
|
|
447
|
+
)
|
|
448
|
+
return {
|
|
449
|
+
...result,
|
|
450
|
+
reason: `${action} requires ${attach ? "a render function" : "an element"}; ${result.reason}`,
|
|
451
|
+
};
|
|
452
|
+
const part = result.element && paths.get(result.element.target);
|
|
453
|
+
return { ...result, ambiguous: part?.ambiguous, unnamed: part?.unnamed };
|
|
454
|
+
},
|
|
455
|
+
transform(
|
|
456
|
+
source: ts.SourceFile,
|
|
457
|
+
output: MagicString,
|
|
458
|
+
mounts: ReadonlyMap<Element, ElementMount> | undefined,
|
|
459
|
+
erased: (node: ts.Node) => boolean,
|
|
460
|
+
) {
|
|
461
|
+
const elements = files.get(source) ?? new Map<Element, Part>();
|
|
462
|
+
const renderFunctions = functions.get(source);
|
|
463
|
+
const setup = new Map<ts.ConciseBody, string>();
|
|
464
|
+
if (elements.size || renderFunctions?.size) {
|
|
465
|
+
for (const { node, item, index } of rows.get(source) ?? []) {
|
|
466
|
+
if (erased(node)) continue;
|
|
467
|
+
output.prependLeft(node.getStart(source), `(${item}, ${index}) => (`);
|
|
468
|
+
}
|
|
469
|
+
type Site = {
|
|
470
|
+
node: Element;
|
|
471
|
+
part: Part;
|
|
472
|
+
children: Site[];
|
|
473
|
+
holes: Element[];
|
|
474
|
+
text: ts.JsxExpression[];
|
|
475
|
+
};
|
|
476
|
+
const native = new Set<Element>();
|
|
477
|
+
const nativeRoots = new Map<Element, { table: string; rootHole: boolean }>();
|
|
478
|
+
const holes = new Map<Element, number>();
|
|
479
|
+
const addresses = new Map<string, { variable: string; suffixes: string[] }>();
|
|
480
|
+
function address({ target }: Part) {
|
|
481
|
+
const segments = target.split(".");
|
|
482
|
+
const prefix = segments.slice(0, 2).join(".");
|
|
483
|
+
let group = addresses.get(prefix);
|
|
484
|
+
if (!group) {
|
|
485
|
+
group = { variable: `__tokamaqAddresses${addresses.size + 1}`, suffixes: [] };
|
|
486
|
+
addresses.set(prefix, group);
|
|
487
|
+
}
|
|
488
|
+
const index = group.suffixes.push(segments.slice(2).join(".")) - 1;
|
|
489
|
+
return `${group.variable}[${index}]`;
|
|
490
|
+
}
|
|
491
|
+
for (const { node, parameter, name } of bindings.get(source) ?? []) {
|
|
492
|
+
if (erased(node)) continue;
|
|
493
|
+
const binding = parameter.name.getText(source);
|
|
494
|
+
const destructured = !ts.isIdentifier(parameter.name);
|
|
495
|
+
if (destructured) output.overwrite(parameter.name.getStart(source), parameter.name.end, name);
|
|
496
|
+
setup.set(node, destructured ? `const ${binding} = ${name};` : `const ${name} = ${binding};`);
|
|
497
|
+
}
|
|
498
|
+
for (const [node, part] of renderFunctions ?? []) {
|
|
499
|
+
if (!part.target) continue; // Left out of the tree: nothing can attach to it.
|
|
500
|
+
if (erased(node)) continue;
|
|
501
|
+
const props = part.props === "{}" ? "" : `, ${part.props}`;
|
|
502
|
+
setup.set(node, `${setup.get(node) ?? ""}__tokamaqAttach(${address(part)}${props});`);
|
|
503
|
+
}
|
|
504
|
+
for (const [node, code] of setup) {
|
|
505
|
+
if (ts.isBlock(node)) output.appendLeft(node.getStart(source) + 1, code);
|
|
506
|
+
else output.prependLeft(node.getStart(source), `{ ${code} return (`);
|
|
507
|
+
}
|
|
508
|
+
const tables: string[] = [];
|
|
509
|
+
function collect(node: Element): Site | undefined {
|
|
510
|
+
const opening = ts.isJsxElement(node) ? node.openingElement : node;
|
|
511
|
+
const part = elements!.get(node);
|
|
512
|
+
const tag = opening.tagName.getText(source);
|
|
513
|
+
if (!part || !/^[a-z][\w-]*$/.test(tag) || mounts?.has(node)) return;
|
|
514
|
+
if (
|
|
515
|
+
opening.attributes.properties.some(
|
|
516
|
+
(attr) =>
|
|
517
|
+
!ts.isJsxAttribute(attr) ||
|
|
518
|
+
/^(children|innerHTML|outerHTML|textContent)$/.test(attr.name.getText(source)),
|
|
519
|
+
)
|
|
520
|
+
)
|
|
521
|
+
return;
|
|
522
|
+
const children: Site[] = [];
|
|
523
|
+
const holes: Element[] = [];
|
|
524
|
+
const text: ts.JsxExpression[] = [];
|
|
525
|
+
if (ts.isJsxElement(node))
|
|
526
|
+
for (const child of node.children) {
|
|
527
|
+
if (ts.isJsxText(child)) continue;
|
|
528
|
+
if (ts.isJsxExpression(child)) {
|
|
529
|
+
if (!child.expression) continue;
|
|
530
|
+
const type = checker.getTypeAtLocation(child.expression);
|
|
531
|
+
if (type.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike)) {
|
|
532
|
+
text.push(child);
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
if (!ts.isJsxElement(child) && !ts.isJsxSelfClosingElement(child)) return;
|
|
538
|
+
const site = collect(child);
|
|
539
|
+
if (site) children.push(site);
|
|
540
|
+
else {
|
|
541
|
+
const tag = (ts.isJsxElement(child) ? child.openingElement : child).tagName.getText(source);
|
|
542
|
+
if (!elements!.has(child) || /^[a-z][\w-]*$/.test(tag)) return;
|
|
543
|
+
holes.push(child);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
// A mixed child list uses compiler refs to avoid inferring DOM positions
|
|
547
|
+
// from a child component's variable number of rendered elements.
|
|
548
|
+
if (
|
|
549
|
+
holes.length &&
|
|
550
|
+
children.some(
|
|
551
|
+
({ node }) =>
|
|
552
|
+
holes.some((hole) => hole.end <= node.pos) &&
|
|
553
|
+
(ts.isJsxElement(node) ? node.openingElement : node).attributes.properties.some(
|
|
554
|
+
(attr) => ts.isJsxAttribute(attr) && attr.name.getText(source) === "ref",
|
|
555
|
+
),
|
|
556
|
+
)
|
|
557
|
+
)
|
|
558
|
+
return;
|
|
559
|
+
return { node, part, children, holes, text };
|
|
560
|
+
}
|
|
561
|
+
for (const node of [...elements.keys()].reverse()) {
|
|
562
|
+
if (erased(node) || native.has(node)) continue;
|
|
563
|
+
const site = collect(node);
|
|
564
|
+
if (
|
|
565
|
+
!site ||
|
|
566
|
+
(!site.children.length &&
|
|
567
|
+
(site.holes.length || !(ts.isJsxElement(node) && node.children.some(ts.isJsxExpression))))
|
|
568
|
+
)
|
|
569
|
+
continue;
|
|
570
|
+
let nextRef = 0;
|
|
571
|
+
let nextHole = 0;
|
|
572
|
+
function serialize(site: Site, ref: number | null = null, root = false): string {
|
|
573
|
+
native.add(site.node);
|
|
574
|
+
const grouped = site.holes.length ? nextHole++ : null;
|
|
575
|
+
const node = site.node;
|
|
576
|
+
if (
|
|
577
|
+
site.text.length === 1 &&
|
|
578
|
+
ts.isJsxElement(node) &&
|
|
579
|
+
node.children.every(
|
|
580
|
+
(child) =>
|
|
581
|
+
ts.isJsxExpression(child) ||
|
|
582
|
+
(ts.isJsxText(child) && /^\s*[\r\n]\s*$/.test(child.getFullText(source))),
|
|
583
|
+
)
|
|
584
|
+
) {
|
|
585
|
+
const tag = node.openingElement.tagName.getText(source);
|
|
586
|
+
const value = site.text[0]!.expression!;
|
|
587
|
+
// Let Solid keep special native element semantics, such as
|
|
588
|
+
// resynchronizing a select when its option's text changes.
|
|
589
|
+
const special = /^(option|textarea|script|style|title)$/.test(tag);
|
|
590
|
+
output.prependLeft(value.getStart(source), special ? "[" : "__tokamaqScalarText(");
|
|
591
|
+
output.appendLeft(value.end, special ? "]" : ")");
|
|
592
|
+
}
|
|
593
|
+
if (ref !== null) {
|
|
594
|
+
const opening = ts.isJsxElement(node) ? node.openingElement : node;
|
|
595
|
+
output.appendLeft(opening.attributes.end, ` ref={(__el) => { __tokamaqRefs[${ref}] = __el; }}`);
|
|
596
|
+
}
|
|
597
|
+
for (const hole of site.holes) holes.set(hole, grouped!);
|
|
598
|
+
const children = site.children.map((child) =>
|
|
599
|
+
serialize(child, site.holes.some((hole) => hole.end <= child.node.pos) ? nextRef++ : null),
|
|
600
|
+
);
|
|
601
|
+
if (root) return `[${children.join(",")}]`;
|
|
602
|
+
return `[${address(site.part)},${JSON.stringify(site.part.fingerprint ?? null)},[${children.join(",")}]${ref !== null || grouped !== null ? `,${ref},${grouped}` : ""}]`;
|
|
603
|
+
}
|
|
604
|
+
const name = `__tokamaqIsland${nativeRoots.size + 1}`;
|
|
605
|
+
const data = serialize(site, null, true);
|
|
606
|
+
tables.push(`const ${name} = ${data};`);
|
|
607
|
+
nativeRoots.set(node, { table: name, rootHole: !!site.holes.length });
|
|
608
|
+
}
|
|
609
|
+
// Edit in JSX postorder so adjacent boundaries at the same offset
|
|
610
|
+
// close the previous sibling before opening the next one.
|
|
611
|
+
for (const [node, part] of elements) {
|
|
612
|
+
if (erased(node)) continue;
|
|
613
|
+
const island = nativeRoots.get(node);
|
|
614
|
+
if (!island) {
|
|
615
|
+
if (!native.has(node))
|
|
616
|
+
transformElement(node, part, address(part), output, source, mounts?.get(node), holes.get(node));
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
const container = ts.isJsxElement(node.parent) || ts.isJsxFragment(node.parent);
|
|
620
|
+
output.appendLeft(
|
|
621
|
+
node.getStart(source),
|
|
622
|
+
`${container ? "{" : ""}__tokamaqRenderNativePart(${partArguments(part, address(part))}, (__tokamaqRefs, __tokamaqHole) => `,
|
|
623
|
+
);
|
|
624
|
+
output.appendLeft(
|
|
625
|
+
node.end,
|
|
626
|
+
`, ${island.table}${island.rootHole ? ", 0" : ""})${container ? "}" : ""}`,
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
if (tables.length) output.prepend(tables.join("\n") + "\n");
|
|
630
|
+
output.prepend(
|
|
631
|
+
[...addresses]
|
|
632
|
+
.map(
|
|
633
|
+
([prefix, { variable, suffixes }]) =>
|
|
634
|
+
`const ${variable} = __tokamaqPartPaths(${JSON.stringify(prefix)}, ${JSON.stringify(suffixes)});\n`,
|
|
635
|
+
)
|
|
636
|
+
.join(""),
|
|
637
|
+
);
|
|
638
|
+
for (const node of setup.keys()) if (!ts.isBlock(node)) output.appendLeft(node.end, "); }");
|
|
639
|
+
for (const { node, item, index } of rows.get(source) ?? []) {
|
|
640
|
+
if (!erased(node)) output.appendLeft(node.end, `)(${item}, ${index})`);
|
|
641
|
+
}
|
|
642
|
+
output.prepend(
|
|
643
|
+
'import { __renderComponentPart as __tokamaqRenderComponentPart, __renderPlainPart as __tokamaqRenderPlainPart, __renderNativePart as __tokamaqRenderNativePart, __partPaths as __tokamaqPartPaths, __attachRenderFunction as __tokamaqAttach } from "@tokamaq/sdk/client";\n',
|
|
644
|
+
);
|
|
645
|
+
}
|
|
646
|
+
if (source === entry)
|
|
647
|
+
output.append(
|
|
648
|
+
`\nimport { __defineScreenFind } from "@tokamaq/sdk/client";\nconst __tokamaqFind = __defineScreenFind(${JSON.stringify(plugin)}, ${JSON.stringify(packed)});\nexport { __tokamaqFind as find };\n`,
|
|
649
|
+
);
|
|
650
|
+
return !!(elements.size || renderFunctions?.size) || source === entry;
|
|
651
|
+
},
|
|
652
|
+
publish(warn: (message: string) => void, catalog?: string) {
|
|
653
|
+
const path = join(dirname(entry.fileName), "_generated/components.d.ts");
|
|
654
|
+
const attributeTypes = new Map<string, string>();
|
|
655
|
+
const modules = new Map<string, string[]>();
|
|
656
|
+
const compactType = (type: string) =>
|
|
657
|
+
type.startsWith('"') || type === "{}" || type.startsWith("C<") ? type : alias(type);
|
|
658
|
+
function shape(candidates: typeof elements, scoped = false) {
|
|
659
|
+
const names = new Map<string, typeof elements>();
|
|
660
|
+
for (const element of candidates) {
|
|
661
|
+
const matches = names.get(element.name);
|
|
662
|
+
if (matches) matches.push(element);
|
|
663
|
+
else names.set(element.name, [element]);
|
|
664
|
+
}
|
|
665
|
+
return [...names]
|
|
666
|
+
.map(([name, matches]) => {
|
|
667
|
+
const types = scoped ? [] : matches.map((element) => paths.get(element.target)!.elementType!());
|
|
668
|
+
const type = types[0]!;
|
|
669
|
+
const shared = types.every((entry) => entry === type);
|
|
670
|
+
if (!scoped && shared && type !== JSON.stringify(name)) {
|
|
671
|
+
const imported = /^C<typeof (import\("[^"]+"\))\.([\w$.]+)>$/.exec(type);
|
|
672
|
+
if (imported && imported[2] === name) {
|
|
673
|
+
const module = imported[1]!;
|
|
674
|
+
const names = modules.get(module);
|
|
675
|
+
if (names) names.push(name);
|
|
676
|
+
else modules.set(module, [name]);
|
|
677
|
+
} else attributeTypes.set(name, compactType(type));
|
|
678
|
+
}
|
|
679
|
+
const only = matches[0]!;
|
|
680
|
+
if (!scoped && matches.length === 1 && !only.attributes)
|
|
681
|
+
return ` ${JSON.stringify(name)}: ${paths.get(only.target)!.type};\n`;
|
|
682
|
+
const entries = matches.map((element, index) => {
|
|
683
|
+
const part = paths.get(element.target)!;
|
|
684
|
+
const scopes = [...new Set(element.ancestors)].map((name) => JSON.stringify(name));
|
|
685
|
+
const filters = element.attributes && JSON.stringify(attributeFilters(element.attributes));
|
|
686
|
+
const attrs =
|
|
687
|
+
!shared && types[index] !== JSON.stringify(name) ? compactType(types[index]!) : "";
|
|
688
|
+
return `[${scopes.join(" | ") || "never"}, ${part.type}${attrs ? `, ${filters ?? "undefined"}, ${attrs}` : filters ? `, ${filters}` : ""}]`;
|
|
689
|
+
});
|
|
690
|
+
return ` ${JSON.stringify(name)}: [${entries.join(", ")}];\n`;
|
|
691
|
+
})
|
|
692
|
+
.join("");
|
|
693
|
+
}
|
|
694
|
+
const elementShape = shape(elements);
|
|
695
|
+
const functionShape = renderFunctions.length ? `{\n${shape(renderFunctions, true)}}` : "{}";
|
|
696
|
+
const attributes =
|
|
697
|
+
[
|
|
698
|
+
...(attributeTypes.size
|
|
699
|
+
? [
|
|
700
|
+
`{ ${[...attributeTypes].map(([name, type]) => `${JSON.stringify(name)}:${type}`).join("; ")} }`,
|
|
701
|
+
]
|
|
702
|
+
: []),
|
|
703
|
+
...[...modules].map(
|
|
704
|
+
([module, names]) =>
|
|
705
|
+
`A<typeof ${module}, ${names.map((name) => JSON.stringify(name)).join("|")}>`,
|
|
706
|
+
),
|
|
707
|
+
].join(" & ") || "{}";
|
|
708
|
+
const types =
|
|
709
|
+
elementShape.includes("C<typeof ") || attributes.includes("C<typeof ")
|
|
710
|
+
? 'import type { ComponentProps as C } from "@solidjs/web";\n'
|
|
711
|
+
: "";
|
|
712
|
+
const helpers = modules.size
|
|
713
|
+
? 'import type { ComponentAttributes as A } from "@tokamaq/sdk/client";\n'
|
|
714
|
+
: "";
|
|
715
|
+
const previous = readOptional(path);
|
|
716
|
+
const declarations =
|
|
717
|
+
privateDeclarations() +
|
|
718
|
+
[...aliases]
|
|
719
|
+
.map(([shape, name]) => `type ${name} = Extract<NonNullable<${shape}>, object>;\n`)
|
|
720
|
+
.join("");
|
|
721
|
+
const next = `// Generated plugin screen search types. Commit this file.\nexport * from ${entryImport};\n${types}${helpers}${declarations}export declare const find: import("@tokamaq/sdk/client").ScreenFind<{\n${elementShape}}, ${functionShape}, ${attributes}>;\n`;
|
|
722
|
+
const reported = new Set<string>();
|
|
723
|
+
const catalogs = new Set([
|
|
724
|
+
dirname(root),
|
|
725
|
+
process.env.TOKAMAQ_PLUGIN_DIR,
|
|
726
|
+
catalog && resolve(root, catalog),
|
|
727
|
+
]);
|
|
728
|
+
for (const directory of catalogs) {
|
|
729
|
+
if (!directory || !ts.sys.directoryExists(directory)) continue;
|
|
730
|
+
const folders = readdirSync(directory, { withFileTypes: true })
|
|
731
|
+
.filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
|
|
732
|
+
.map((entry) => resolve(directory, entry.name));
|
|
733
|
+
for (const folder of [directory, ...folders]) {
|
|
734
|
+
const manifest =
|
|
735
|
+
readOptional(resolve(folder, "manifest.json")) ??
|
|
736
|
+
readOptional(resolve(folder, "dist/manifest.json"));
|
|
737
|
+
if (!manifest) continue;
|
|
738
|
+
let installed;
|
|
739
|
+
try {
|
|
740
|
+
installed = JSON.parse(manifest).plugin;
|
|
741
|
+
} catch {
|
|
742
|
+
continue; // The catalog reports invalid artifacts.
|
|
743
|
+
}
|
|
744
|
+
for (const options of installed?.contributes?.["component-action"] ?? []) {
|
|
745
|
+
const previous = screenTarget(options);
|
|
746
|
+
if (
|
|
747
|
+
typeof options.owner === "string"
|
|
748
|
+
? options.owner !== plugin
|
|
749
|
+
: !previous.target.startsWith(plugin + ".")
|
|
750
|
+
)
|
|
751
|
+
continue;
|
|
752
|
+
const attach = options.action === "attach";
|
|
753
|
+
const { reason, element } = resolveScreenSearch(
|
|
754
|
+
attach ? renderFunctions : elements,
|
|
755
|
+
previous.search,
|
|
756
|
+
previous,
|
|
757
|
+
attach ? "render function" : "element",
|
|
758
|
+
);
|
|
759
|
+
if (reason) {
|
|
760
|
+
const message = `Plugin "${installed.id}": ${reason}; skipping this addition`;
|
|
761
|
+
if (reported.has(message)) continue;
|
|
762
|
+
reported.add(message);
|
|
763
|
+
warn(message);
|
|
764
|
+
} else if (previous.search && element && paths.get(element.target)?.unnamed) {
|
|
765
|
+
const key = JSON.stringify([installed.id, element.target]);
|
|
766
|
+
if (reported.has(key)) continue;
|
|
767
|
+
reported.add(key);
|
|
768
|
+
warn(unnamedTargetWarning(installed.id, previous.search, element.target));
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
if (next !== previous) {
|
|
774
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
775
|
+
writeFileSync(path, next);
|
|
776
|
+
}
|
|
777
|
+
},
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function readOptional(path: string) {
|
|
782
|
+
try {
|
|
783
|
+
return readFileSync(path, "utf8");
|
|
784
|
+
} catch (error) {
|
|
785
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
function staticName(opening: ts.JsxOpeningLikeElement, key: string) {
|
|
790
|
+
for (const attribute of opening.attributes.properties) {
|
|
791
|
+
if (!ts.isJsxAttribute(attribute) || attribute.name.getText() !== key) continue;
|
|
792
|
+
const value = attribute.initializer;
|
|
793
|
+
const expression = value && ts.isJsxExpression(value) ? value.expression : value;
|
|
794
|
+
if (expression && ts.isStringLiteralLike(expression) && expression.text) return expression.text;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
function childrenAttribute(opening: ts.JsxOpeningLikeElement) {
|
|
799
|
+
return opening.attributes.properties.find(
|
|
800
|
+
(attribute): attribute is ts.JsxAttribute =>
|
|
801
|
+
ts.isJsxAttribute(attribute) && attribute.name.getText() === "children",
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
function childExpression(children: readonly ts.JsxChild[]) {
|
|
806
|
+
const [only, ...rest] = children.filter((n) => !ts.isJsxText(n) || !!n.getText().trim());
|
|
807
|
+
return !rest.length && only && ts.isJsxExpression(only) ? only.expression : undefined;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
function childCallback(node: Element) {
|
|
811
|
+
const value = ts.isJsxElement(node) ? undefined : childrenAttribute(node)?.initializer;
|
|
812
|
+
return inlineCallback(
|
|
813
|
+
ts.isJsxElement(node)
|
|
814
|
+
? childExpression(node.children)
|
|
815
|
+
: value && ts.isJsxExpression(value)
|
|
816
|
+
? value.expression
|
|
817
|
+
: undefined,
|
|
818
|
+
);
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function partArguments(part: Part, target: string) {
|
|
822
|
+
const row = part.row ? `() => (${part.row})` : "undefined";
|
|
823
|
+
return `${target}, ${JSON.stringify(part.fingerprint)}, ${part.props} ?? {}, ${row}`;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
function transformElement(
|
|
827
|
+
node: Element,
|
|
828
|
+
part: Part,
|
|
829
|
+
target: string,
|
|
830
|
+
output: MagicString,
|
|
831
|
+
source: ts.SourceFile,
|
|
832
|
+
mount?: ElementMount,
|
|
833
|
+
hole?: number,
|
|
834
|
+
) {
|
|
835
|
+
const parent = node.parent;
|
|
836
|
+
// <div><Send /></div> → <div>{renderPart(…, () => <Send />)}</div>;
|
|
837
|
+
// () => <Send /> → () => renderPart(…, () => <Send />).
|
|
838
|
+
const child = ts.isJsxElement(parent) || ts.isJsxFragment(parent);
|
|
839
|
+
const opening = ts.isJsxElement(node) ? node.openingElement : node;
|
|
840
|
+
const component = !/^[a-z][\w-]*$/.test(opening.tagName.getText(source));
|
|
841
|
+
const entry = component ? "__tokamaqRenderComponentPart" : "__tokamaqRenderPlainPart";
|
|
842
|
+
const prefix = `${child ? "{" : ""}${hole === undefined ? "" : `__tokamaqHole(${hole}, () => `}${entry}(${partArguments(part, target)}, (__tokamaqContents) => `;
|
|
843
|
+
const suffix = `)${hole === undefined ? "" : ")"}${child ? "}" : ""}`;
|
|
844
|
+
output.appendLeft(
|
|
845
|
+
node.getStart(source),
|
|
846
|
+
prefix + (mount?.prefix ?? "") + (component ? "__tokamaqComponent(" : ""),
|
|
847
|
+
);
|
|
848
|
+
const endMount = (component ? ")" : "") + (mount?.suffix ?? "");
|
|
849
|
+
|
|
850
|
+
if (ts.isJsxSelfClosingElement(node)) {
|
|
851
|
+
const tag = node.tagName.getText(source);
|
|
852
|
+
if (voidTags.has(tag)) {
|
|
853
|
+
// <input /> → renderPart(…, () => <input />): a void tag
|
|
854
|
+
// stays self-closing so outside actions do not create invalid children.
|
|
855
|
+
output.appendLeft(node.end, endMount + suffix);
|
|
856
|
+
return;
|
|
857
|
+
}
|
|
858
|
+
const attribute = childrenAttribute(node);
|
|
859
|
+
const spread = node.attributes.properties.filter(ts.isJsxSpreadAttribute).at(-1);
|
|
860
|
+
if (!attribute && spread) {
|
|
861
|
+
// A caller can supply children through forwarded attributes, such as a render prop.
|
|
862
|
+
output.prependLeft(spread.expression.getStart(source), "__tokamaqContents.spread(");
|
|
863
|
+
output.appendLeft(spread.expression.end, ")");
|
|
864
|
+
output.appendLeft(node.end, endMount + suffix);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
const value = attribute?.initializer;
|
|
868
|
+
const expression = value && ts.isJsxExpression(value) ? value : undefined;
|
|
869
|
+
// Include the braces when slicing so inserts at the start of a nested
|
|
870
|
+
// JSX expression move with it.
|
|
871
|
+
const authored = expression?.expression
|
|
872
|
+
? output.slice(expression.getStart(source), expression.end).slice(1, -1)
|
|
873
|
+
: value && ts.isStringLiteral(value)
|
|
874
|
+
? JSON.stringify(value.text)
|
|
875
|
+
: undefined;
|
|
876
|
+
if (attribute) output.remove(attribute.getStart(source), attribute.end);
|
|
877
|
+
// <Region /> → <Region>{contents()}</Region> to allow inside additions.
|
|
878
|
+
// <For children={row => …} /> → <For>{row => contents(() => renderRow(row))}</For>.
|
|
879
|
+
const callback = childCallback(node);
|
|
880
|
+
const contents = callback && authored ? renderProp(callback, authored) : "__tokamaqContents()";
|
|
881
|
+
const original = authored && !callback ? `, () => (${authored})` : "";
|
|
882
|
+
output.overwrite(node.end - 2, node.end, `>{${contents}}</${tag}>${endMount}${original}${suffix}`);
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
const close = node.closingElement;
|
|
887
|
+
const tag = opening.tagName.getText(source);
|
|
888
|
+
const callback = childCallback(node);
|
|
889
|
+
if (callback) {
|
|
890
|
+
const { prefix, suffix: end } = renderPropCall(callback);
|
|
891
|
+
output.overwrite(opening.end, callback.getStart(source), `{${prefix}`);
|
|
892
|
+
output.overwrite(callback.end, close.end, `${end}}</${tag}>${endMount}${suffix}`);
|
|
893
|
+
} else {
|
|
894
|
+
// <div><b>Text</b></div> → renderPart(…, contents => <div>{contents()}</div>,
|
|
895
|
+
// () => <><b>Text</b></>): hide and replace can now skip the original children.
|
|
896
|
+
output.prependLeft(opening.end, `{__tokamaqContents()}</${tag}>${endMount}, () => <>`);
|
|
897
|
+
output.overwrite(close.getStart(source), close.end, `</>${suffix}`);
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
function inlineCallback(node: ts.Expression | undefined) {
|
|
902
|
+
return node && (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) ? node : undefined;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
function renderPropCall(callback: ts.ArrowFunction | ts.FunctionExpression) {
|
|
906
|
+
// Solid uses Function.length to distinguish render props and provide a list index.
|
|
907
|
+
const optional = callback.parameters.findIndex(
|
|
908
|
+
(parameter) => parameter.initializer || parameter.dotDotDotToken,
|
|
909
|
+
);
|
|
910
|
+
const required = optional === -1 ? callback.parameters.length : optional;
|
|
911
|
+
const args = Array.from({ length: required }, (_, i) => `__tokamaqArg${i}`);
|
|
912
|
+
const params = [...args, "...__tokamaqRest"].join(", ");
|
|
913
|
+
return {
|
|
914
|
+
prefix: `(${params}) => __tokamaqContents(() => (`,
|
|
915
|
+
suffix: `)(${params}))`,
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
function renderProp(callback: ts.ArrowFunction | ts.FunctionExpression, source: string) {
|
|
920
|
+
const { prefix, suffix } = renderPropCall(callback);
|
|
921
|
+
return prefix + source + suffix;
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
export function problem(node: ts.Node, message: string) {
|
|
925
|
+
const source = node.getSourceFile();
|
|
926
|
+
const { line, character } = source.getLineAndCharacterOfPosition(node.getStart(source));
|
|
927
|
+
return new Error(`${source.fileName}:${line + 1}:${character + 1}: ${message}`);
|
|
928
|
+
}
|