suppa-mcp-2 1.44.5 → 1.45.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 +5 -3
- package/dist/codeForm/api.js +150 -0
- package/dist/codeForm/typecheck.js +324 -0
- package/dist/codeForm/workspace.js +356 -0
- package/dist/server.js +49 -3
- package/dist/toolTable.js +1 -1
- package/dist/tools/formCode.js +644 -0
- package/dist/tools/formV2.js +53 -41
- package/dist/tools/forms.js +2 -2
- package/package.json +4 -3
- package/skills/suppa-cli/SKILL.md +1 -1
- package/skills/suppa-form-v2/SKILL.md +7 -0
- package/skills/suppa-form-v2/code-form/SOURCE.json +19 -0
- package/skills/suppa-form-v2/code-form/sdk/index.d.ts +55926 -0
- package/skills/suppa-form-v2/references/code-form.md +174 -0
- package/skills/suppa-form-v2/scripts/code-form/code-form-core.mjs +562 -0
package/README.md
CHANGED
|
@@ -30,7 +30,7 @@ No API key needed to start — the server authenticates interactively via the `s
|
|
|
30
30
|
|
|
31
31
|
## The `suppa` command
|
|
32
32
|
|
|
33
|
-
The same
|
|
33
|
+
The same 108 operations the MCP server exposes are available as a command, for
|
|
34
34
|
shells, scripts and CI:
|
|
35
35
|
|
|
36
36
|
```bash
|
|
@@ -414,7 +414,7 @@ extension table is created outside that check and is not subject to it.
|
|
|
414
414
|
|
|
415
415
|
## Available tools
|
|
416
416
|
|
|
417
|
-
|
|
417
|
+
108 tools across the areas below.
|
|
418
418
|
|
|
419
419
|
### Session & identity
|
|
420
420
|
|
|
@@ -547,7 +547,7 @@ Of the seven above, `suppa_get_form` reads both generations: since 1.43.3 a 2.x
|
|
|
547
547
|
the builder reads it (schema, variables, localizations, the Code Form's files). The other six are
|
|
548
548
|
**Suppa 1.0** forms: they read and write `data.formShema` (the platform's misspelling) and the v1
|
|
549
549
|
field types. A **Suppa 2.0** entity-builder form is a different product —
|
|
550
|
-
the `schema` column on the row since 2.1, 57 component types — and is served by the
|
|
550
|
+
the `schema` column on the row since 2.1, 57 component types — and is served by the eight below plus the bundled
|
|
551
551
|
`skills/suppa-form-v2` skill. The first two touch no tenant: they read files inside the package.
|
|
552
552
|
|
|
553
553
|
| Tool | Description |
|
|
@@ -557,6 +557,8 @@ the `schema` column on the row since 2.1, 57 component types — and is served b
|
|
|
557
557
|
| `suppa_write_form_draft` | Save a checked draft through the builder's own save (`PUT /core/forms/:id/schema`) — gated first against the live form (what the form already has does not block), guarded by the form's revision, recorded in History; saves the widget renders the gate compiled, never a hand-written one; `variables` only when the draft lists some. It never publishes |
|
|
558
558
|
| `suppa_create_form_v2` | Create a 2.0 form (create / update / custom) with its draft in one transaction — the routing flag and default variable the builder adds, optionally filed into a folder (confirm-gated) |
|
|
559
559
|
| `suppa_form_versions` | A form's published versions, the component diff between two of them, and a summary of recent draft saves (read-only) |
|
|
560
|
+
| `suppa_form_code` | A form's Code Form (TypeScript against `formAPI`) without a browser tab: the rules, `pull` (the draft's code into a workspace folder with the SDK and the form's own typings), `api` (an element's, a type's or `formAPI`'s members, events and docs, read by the checker), `check` (tsc as the builder's code editor runs it, the import rule, invented events, the agent's deny list) |
|
|
561
|
+
| `suppa_push_form_code` | Save the workspace's code changes to the DRAFT — only `code`, guarded by the revision; re-checked first, conflicts with someone else's save handed back to merge, `@shared` files read-only; the server's build result reported (a failed build keeps the previous one running). Confirm-gated, never publishes |
|
|
560
562
|
| `suppa_form_lifecycle` | Publish, roll back (restore + publish), discard (unrecoverable) or promote — gated on the form gate (a stored widget with an empty render is refused) and on the version belonging to the form (confirm-gated) |
|
|
561
563
|
|
|
562
564
|
### Migration (Suppa 1.0 → 2.0) & workspace
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { createWorkspaceProgram, eventNames, loadTs, toDiagnostic } from "./typecheck.js";
|
|
2
|
+
/** A `formAPI…` property path — no calls, no computed expressions: the probe is type-checked, never run, but it is still the agent's text going into a source file. */
|
|
3
|
+
const PATH_RE = /^formAPI(?:\.[A-Za-z_$][\w$]*|\[(?:'[^'\\\n]+'|"[^"\\\n]+")\])*$/;
|
|
4
|
+
const TYPE_RE = /^[A-Za-z][\w.-]*$/;
|
|
5
|
+
const PROBE_PATH = ".suppa-code/api-probe.ts";
|
|
6
|
+
const PROBE = "__suppaCodeProbe";
|
|
7
|
+
export function probeSource(subject) {
|
|
8
|
+
if (subject.type !== undefined) {
|
|
9
|
+
if (!TYPE_RE.test(subject.type))
|
|
10
|
+
throw new Error(`"${subject.type}" is not an element type`);
|
|
11
|
+
return `import type { ElementApiFor } from '@suppa/frontend-sdk';\ndeclare const ${PROBE}: ElementApiFor<'${subject.type}'>;\nexport {};\n`;
|
|
12
|
+
}
|
|
13
|
+
const path = subject.path ?? "formAPI";
|
|
14
|
+
if (!PATH_RE.test(path))
|
|
15
|
+
throw new Error(`"${path}" is not a formAPI path — write it like formAPI.elements.title or formAPI.services.ui`);
|
|
16
|
+
return `const ${PROBE} = ${path};\nexport {};\n`;
|
|
17
|
+
}
|
|
18
|
+
function find(ts, file, test) {
|
|
19
|
+
let found = null;
|
|
20
|
+
const visit = (node) => {
|
|
21
|
+
if (found)
|
|
22
|
+
return;
|
|
23
|
+
if (test(node))
|
|
24
|
+
found = node;
|
|
25
|
+
else
|
|
26
|
+
ts.forEachChild(node, visit);
|
|
27
|
+
};
|
|
28
|
+
visit(file);
|
|
29
|
+
return found;
|
|
30
|
+
}
|
|
31
|
+
function originOf(ts, symbol) {
|
|
32
|
+
const owner = symbol.getDeclarations()?.[0]?.parent;
|
|
33
|
+
return owner && (ts.isClassDeclaration(owner) || ts.isInterfaceDeclaration(owner)) && owner.name ? owner.name.text : null;
|
|
34
|
+
}
|
|
35
|
+
/** The named class or interface the subject is. The form's own `CurrentFormAPI` is an intersection, which has no symbol of its own — its first named part is what it is. */
|
|
36
|
+
function ownerName(type) {
|
|
37
|
+
for (const part of type.isIntersection() ? type.types : [type]) {
|
|
38
|
+
const name = part.getSymbol()?.getName();
|
|
39
|
+
if (name && !name.startsWith("__"))
|
|
40
|
+
return name;
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
function isHidden(ts, symbol) {
|
|
45
|
+
if (symbol.getName().startsWith("_") || symbol.getName().startsWith("#"))
|
|
46
|
+
return true;
|
|
47
|
+
const hidden = ts.ModifierFlags.Private | ts.ModifierFlags.Protected;
|
|
48
|
+
return (symbol.getDeclarations() ?? []).some((d) => (ts.getCombinedModifierFlags(d) & hidden) !== 0);
|
|
49
|
+
}
|
|
50
|
+
function isReadonly(ts, symbol) {
|
|
51
|
+
const declarations = symbol.getDeclarations() ?? [];
|
|
52
|
+
if (declarations.some((d) => ts.isGetAccessorDeclaration(d)) && !declarations.some((d) => ts.isSetAccessorDeclaration(d)))
|
|
53
|
+
return true;
|
|
54
|
+
return declarations.some((d) => (ts.getCombinedModifierFlags(d) & ts.ModifierFlags.Readonly) !== 0);
|
|
55
|
+
}
|
|
56
|
+
export async function describeApi(dir, subject) {
|
|
57
|
+
const ts = await loadTs();
|
|
58
|
+
const text = probeSource(subject);
|
|
59
|
+
const { root, program } = createWorkspaceProgram(ts, dir, { path: PROBE_PATH, text });
|
|
60
|
+
const file = program.getSourceFiles().find((s) => s.fileName.replace(/\\/g, "/").endsWith(PROBE_PATH));
|
|
61
|
+
if (!file)
|
|
62
|
+
throw new Error("the API probe did not compile");
|
|
63
|
+
const problems = [...program.getSyntacticDiagnostics(file), ...program.getSemanticDiagnostics(file)].filter((d) => d.category === ts.DiagnosticCategory.Error);
|
|
64
|
+
if (problems.length)
|
|
65
|
+
throw new Error(problems.map((d) => toDiagnostic(ts, root, d).message).join("\n"));
|
|
66
|
+
const checker = program.getTypeChecker();
|
|
67
|
+
const probe = find(ts, file, (n) => ts.isVariableDeclaration(n) && n.name.getText() === PROBE);
|
|
68
|
+
if (!probe)
|
|
69
|
+
throw new Error("the API probe has no subject");
|
|
70
|
+
const type = checker.getNonNullableType(checker.getTypeAtLocation(probe.name));
|
|
71
|
+
const format = ts.TypeFormatFlags.NoTruncation;
|
|
72
|
+
const members = checker
|
|
73
|
+
.getPropertiesOfType(type)
|
|
74
|
+
.filter((s) => !isHidden(ts, s))
|
|
75
|
+
.map((symbol) => {
|
|
76
|
+
const memberType = checker.getTypeOfSymbolAtLocation(symbol, probe);
|
|
77
|
+
const calls = memberType.getCallSignatures();
|
|
78
|
+
// A method is deprecated only when every overload is — `on` carries one retired overload beside the live ones.
|
|
79
|
+
const deprecatedCall = (sig) => sig.getJsDocTags().some((t) => t.name === "deprecated");
|
|
80
|
+
const tag = symbol.getJsDocTags(checker).find((t) => t.name === "deprecated");
|
|
81
|
+
const deprecated = tag && (!calls.length || calls.every(deprecatedCall)) ? tag : undefined;
|
|
82
|
+
return {
|
|
83
|
+
name: symbol.getName(),
|
|
84
|
+
kind: calls.length ? "method" : "property",
|
|
85
|
+
readonly: isReadonly(ts, symbol),
|
|
86
|
+
signatures: calls.length
|
|
87
|
+
? calls.map((sig) => `${symbol.getName()}${checker.signatureToString(sig, undefined, format)}${deprecatedCall(sig) && !deprecated ? " [deprecated overload]" : ""}`)
|
|
88
|
+
: [checker.typeToString(memberType, undefined, format)],
|
|
89
|
+
doc: ts.displayPartsToString(symbol.getDocumentationComment(checker)).trim(),
|
|
90
|
+
deprecated: deprecated ? ts.displayPartsToString(deprecated.text).trim() || "deprecated" : null,
|
|
91
|
+
origin: originOf(ts, symbol),
|
|
92
|
+
};
|
|
93
|
+
});
|
|
94
|
+
const typeName = checker.typeToString(type);
|
|
95
|
+
return {
|
|
96
|
+
subject: subject.type !== undefined ? `ElementApiFor<'${subject.type}'>` : subject.path ?? "formAPI",
|
|
97
|
+
type: typeName,
|
|
98
|
+
ownName: ownerName(type) ?? typeName.replace(/<.*$/, ""),
|
|
99
|
+
events: eventNames(ts, checker, type, probe),
|
|
100
|
+
members: members.sort((a, b) => a.name.localeCompare(b.name)),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
const SUMMARY_CHARS = 140;
|
|
104
|
+
const HEAD_CHARS = 200;
|
|
105
|
+
/** The first sentence of a doc comment, for the one-line listing. */
|
|
106
|
+
export function summaryOf(doc) {
|
|
107
|
+
const flat = doc.replace(/\s+/g, " ").trim();
|
|
108
|
+
const sentence = /^(.+?[.!?])(\s|$)/.exec(flat)?.[1] ?? flat;
|
|
109
|
+
return sentence.length > SUMMARY_CHARS ? `${sentence.slice(0, SUMMARY_CHARS - 1)}…` : sentence;
|
|
110
|
+
}
|
|
111
|
+
function memberHead(m, full = false) {
|
|
112
|
+
const head = m.kind === "method" ? m.signatures[0] : `${m.readonly ? "readonly " : ""}${m.name}: ${m.signatures[0]}`;
|
|
113
|
+
const more = m.signatures.length > 1 ? ` (+${m.signatures.length - 1} overload${m.signatures.length === 2 ? "" : "s"})` : "";
|
|
114
|
+
return full || head.length <= HEAD_CHARS ? `${head}${more}` : `${head.slice(0, HEAD_CHARS - 1)}…${more}`;
|
|
115
|
+
}
|
|
116
|
+
export const DEFAULT_API_LINES = 60;
|
|
117
|
+
/** The subject's own members one line each (signature + the first sentence of its doc), inherited ones by name only, and the events. */
|
|
118
|
+
export function formatApi(api, options = {}) {
|
|
119
|
+
if (options.member) {
|
|
120
|
+
const found = api.members.find((m) => m.name === options.member);
|
|
121
|
+
if (!found)
|
|
122
|
+
return `${api.subject} has no public member "${options.member}" — members: ${api.members.map((m) => m.name).join(", ")}`;
|
|
123
|
+
return [
|
|
124
|
+
`${api.subject}.${found.name}${found.origin ? ` (declared in ${found.origin})` : ""}${found.deprecated ? ` — DEPRECATED: ${found.deprecated}` : ""}`,
|
|
125
|
+
...(found.kind === "method" ? found.signatures : [memberHead(found, true)]),
|
|
126
|
+
found.doc || "(no documentation)",
|
|
127
|
+
].join("\n");
|
|
128
|
+
}
|
|
129
|
+
const needle = options.filter?.toLowerCase();
|
|
130
|
+
const matches = (m) => !needle || m.name.toLowerCase().includes(needle) || m.doc.toLowerCase().includes(needle);
|
|
131
|
+
const own = api.members.filter((m) => (!m.origin || m.origin === api.ownName) && matches(m));
|
|
132
|
+
const inherited = api.members.filter((m) => m.origin && m.origin !== api.ownName && matches(m));
|
|
133
|
+
const limit = options.maxLines ?? DEFAULT_API_LINES;
|
|
134
|
+
const lines = [`${api.subject}: ${api.type}${needle ? ` — members matching "${options.filter}"` : ""}`];
|
|
135
|
+
if (api.events && !needle)
|
|
136
|
+
lines.push(`events — on(name, handler): ${api.events.join(", ")}`);
|
|
137
|
+
for (const m of own.slice(0, limit))
|
|
138
|
+
lines.push(` ${memberHead(m)}${m.deprecated ? " [deprecated]" : ""}${m.doc ? ` — ${summaryOf(m.doc)}` : ""}`);
|
|
139
|
+
if (own.length > limit)
|
|
140
|
+
lines.push(` … ${own.length - limit} more of its own — narrow with filter: "<word>"`);
|
|
141
|
+
const byOrigin = new Map();
|
|
142
|
+
for (const m of inherited)
|
|
143
|
+
byOrigin.set(m.origin, [...(byOrigin.get(m.origin) ?? []), m.name]);
|
|
144
|
+
for (const [origin, names] of byOrigin)
|
|
145
|
+
lines.push(`inherited from ${origin}: ${names.join(", ")}`);
|
|
146
|
+
if (!own.length && !inherited.length)
|
|
147
|
+
lines.push(" (no public member matches)");
|
|
148
|
+
lines.push('one member in full: the same call with member: "<name>"');
|
|
149
|
+
return lines.join("\n");
|
|
150
|
+
}
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type-checking a Code Form workspace the way the builder's code editor does (fb-live-mcp 0.4.0
|
|
3
|
+
* code/typecheck.js), plus the rules the formbuilder agent's compile gate enforces on generated code
|
|
4
|
+
* (suppa-ai-agent formbuilder-agent codeform/compile.ts) — those as WARNINGS here, because the platform
|
|
5
|
+
* itself does not enforce them: the editor and the server build accept them, and the gate is the agent's.
|
|
6
|
+
*
|
|
7
|
+
* `typescript` is loaded on first use: it is ~9 MB of JavaScript, and a server that never checks code
|
|
8
|
+
* never pays for it.
|
|
9
|
+
*/
|
|
10
|
+
import { readFileSync, statSync } from "node:fs";
|
|
11
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
12
|
+
import { ENVIRONMENT_PATH, GLOBALS_PATH, SDK_PATH, SHARED_MODULES_PATH, readSources } from "./workspace.js";
|
|
13
|
+
let tsModule = null;
|
|
14
|
+
export async function loadTs() {
|
|
15
|
+
if (!tsModule) {
|
|
16
|
+
const mod = await import("typescript");
|
|
17
|
+
tsModule = (mod.default ?? mod);
|
|
18
|
+
}
|
|
19
|
+
return tsModule;
|
|
20
|
+
}
|
|
21
|
+
const inside = (root, path) => {
|
|
22
|
+
const rel = relative(root, resolve(path));
|
|
23
|
+
return rel === "" || (!rel.startsWith("..") && !rel.startsWith(sep) && !/^[a-zA-Z]:/.test(rel));
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Parsed declaration files, kept across calls. TypeScript's own lib files are a handful of shared paths. The SDK
|
|
27
|
+
* (~7 MB of text, ~50 MB parsed) is a copy per workspace, so it is NOT kept per path: only the last SDK_KEPT
|
|
28
|
+
* copies stay — checking the same form again is a hit, switching forms re-parses (about a second) rather than
|
|
29
|
+
* growing the heap by 50 MB per form for the life of the server. Keyed by path, size and mtime.
|
|
30
|
+
*/
|
|
31
|
+
const PARSED = new Map();
|
|
32
|
+
const SDK_KEPT = 2;
|
|
33
|
+
function cachedDeclaration(ts, path, target, sdk) {
|
|
34
|
+
let stamp;
|
|
35
|
+
try {
|
|
36
|
+
const st = statSync(path);
|
|
37
|
+
stamp = `${st.size}:${st.mtimeMs}:${target}`;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
const key = resolve(path);
|
|
43
|
+
const hit = PARSED.get(key);
|
|
44
|
+
if (hit && hit.stamp === stamp) {
|
|
45
|
+
// Most recently used last: Map keeps insertion order.
|
|
46
|
+
PARSED.delete(key);
|
|
47
|
+
PARSED.set(key, hit);
|
|
48
|
+
return hit.file;
|
|
49
|
+
}
|
|
50
|
+
const file = ts.createSourceFile(path, readFileSync(path, "utf8"), target, true);
|
|
51
|
+
PARSED.delete(key);
|
|
52
|
+
PARSED.set(key, { stamp, file, sdk });
|
|
53
|
+
if (sdk) {
|
|
54
|
+
const sdks = [...PARSED.entries()].filter(([, v]) => v.sdk);
|
|
55
|
+
for (const [k] of sdks.slice(0, Math.max(0, sdks.length - SDK_KEPT)))
|
|
56
|
+
PARSED.delete(k);
|
|
57
|
+
}
|
|
58
|
+
return file;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* A TypeScript program over the workspace, set up as the editor checks code: its tsconfig options, the SDK and
|
|
62
|
+
* the form's generated globals, and NOTHING of the disk around it — the workspace may sit inside a repo whose
|
|
63
|
+
* `node_modules` would resolve any bare import (`vue`, `lodash`) the browser sandbox does not have, so the
|
|
64
|
+
* compiler host sees only the workspace and TypeScript's own lib files. `extra` adds one in-memory file under the
|
|
65
|
+
* root (the API probe). `override` replaces `src/**` as a whole (the files the form holds BEFORE a change, for the
|
|
66
|
+
* baseline a push judges new errors against): only its files exist under `src/`, whatever the disk holds.
|
|
67
|
+
*/
|
|
68
|
+
export function createWorkspaceProgram(ts, dir, extra, override) {
|
|
69
|
+
const root = resolve(dir);
|
|
70
|
+
const tsconfig = JSON.parse(readFileSync(join(root, "tsconfig.json"), "utf8"));
|
|
71
|
+
const { options } = ts.convertCompilerOptionsFromJson(tsconfig.compilerOptions ?? {}, root);
|
|
72
|
+
const sources = override ?? readSources(root);
|
|
73
|
+
const libDir = dirname(ts.getDefaultLibFilePath(options));
|
|
74
|
+
const srcRoot = join(root, "src");
|
|
75
|
+
const virtual = override ? new Map(Object.entries(override).map(([p, text]) => [resolve(join(root, p)), text])) : null;
|
|
76
|
+
const isVirtual = (path) => virtual !== null && inside(srcRoot, path);
|
|
77
|
+
const visible = (path) => inside(root, path) || inside(libDir, path);
|
|
78
|
+
const extraPath = extra ? join(root, extra.path) : null;
|
|
79
|
+
const isExtra = (path) => extraPath !== null && resolve(path) === resolve(extraPath);
|
|
80
|
+
const sdkPath = resolve(join(root, SDK_PATH));
|
|
81
|
+
const host = ts.createCompilerHost(options, true);
|
|
82
|
+
const fileExists = host.fileExists.bind(host);
|
|
83
|
+
const directoryExists = host.directoryExists?.bind(host);
|
|
84
|
+
const readFile = host.readFile.bind(host);
|
|
85
|
+
const getSourceFile = host.getSourceFile.bind(host);
|
|
86
|
+
host.fileExists = (path) => isExtra(path) || (isVirtual(path) ? virtual.has(resolve(path)) : visible(path) && fileExists(path));
|
|
87
|
+
host.directoryExists = (path) => (visible(path) || inside(path, root)) && (directoryExists ? directoryExists(path) : true);
|
|
88
|
+
host.readFile = (path) => (isExtra(path) ? extra.text : isVirtual(path) ? virtual.get(resolve(path)) : readFile(path));
|
|
89
|
+
host.getSourceFile = (path, language, onError, shouldCreate) => {
|
|
90
|
+
if (isExtra(path))
|
|
91
|
+
return ts.createSourceFile(path, extra.text, language, true);
|
|
92
|
+
if (isVirtual(path)) {
|
|
93
|
+
const text = virtual.get(resolve(path));
|
|
94
|
+
return text === undefined ? undefined : ts.createSourceFile(path, text, language, true);
|
|
95
|
+
}
|
|
96
|
+
const languageVersion = typeof language === "object" ? language.languageVersion : language;
|
|
97
|
+
const sdk = resolve(path) === sdkPath;
|
|
98
|
+
if (sdk || inside(libDir, path)) {
|
|
99
|
+
return cachedDeclaration(ts, path, languageVersion, sdk) ?? getSourceFile(path, language, onError, shouldCreate);
|
|
100
|
+
}
|
|
101
|
+
return getSourceFile(path, language, onError, shouldCreate);
|
|
102
|
+
};
|
|
103
|
+
const rootNames = [
|
|
104
|
+
...Object.keys(sources).map((path) => join(root, path)),
|
|
105
|
+
join(root, GLOBALS_PATH),
|
|
106
|
+
join(root, ENVIRONMENT_PATH),
|
|
107
|
+
join(root, SHARED_MODULES_PATH),
|
|
108
|
+
...(extraPath ? [extraPath] : []),
|
|
109
|
+
];
|
|
110
|
+
return { root, program: ts.createProgram({ rootNames, options, host }), sources };
|
|
111
|
+
}
|
|
112
|
+
export function toDiagnostic(ts, root, d) {
|
|
113
|
+
const file = d.file ? relative(root, d.file.fileName).split(sep).join("/") : null;
|
|
114
|
+
const at = d.file && d.start !== undefined ? d.file.getLineAndCharacterOfPosition(d.start) : { line: 0, character: 0 };
|
|
115
|
+
return {
|
|
116
|
+
file,
|
|
117
|
+
line: at.line + 1,
|
|
118
|
+
column: at.character + 1,
|
|
119
|
+
category: d.category === ts.DiagnosticCategory.Error ? "error" : "warning",
|
|
120
|
+
code: d.code,
|
|
121
|
+
message: ts.flattenDiagnosticMessageText(d.messageText, "\n"),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The formbuilder agent's deny list (suppa-ai-agent codeform/compile.ts DENY_IDENTIFIERS, 2026-11). A bare
|
|
126
|
+
* reference to one of these that resolves to the real global — not to a local of the form's own code — is
|
|
127
|
+
* reported. Most are already a type error (no DOM lib); these are the ones the sandbox's typings DO declare.
|
|
128
|
+
*/
|
|
129
|
+
export const DENY_IDENTIFIERS = new Set([
|
|
130
|
+
"eval", "Function", "globalThis", "window", "document", "self", "top", "parent", "frames",
|
|
131
|
+
"process", "require", "module", "exports", "XMLHttpRequest", "importScripts",
|
|
132
|
+
"atob", "btoa", "setImmediate", "queueMicrotask", "WebSocket", "Worker", "Reflect", "Proxy",
|
|
133
|
+
"location", "history", "navigation", "navigator", "EventSource", "Image", "BroadcastChannel",
|
|
134
|
+
"localStorage", "sessionStorage", "indexedDB", "cookieStore", "caches",
|
|
135
|
+
"requestAnimationFrame", "requestIdleCallback", "MessageChannel", "SharedWorker", "ServiceWorker",
|
|
136
|
+
"open", "Audio", "RTCPeerConnection", "webkitRTCPeerConnection", "WebTransport", "FontFace",
|
|
137
|
+
"alert", "confirm", "prompt", "print", "postMessage", "Notification",
|
|
138
|
+
]);
|
|
139
|
+
/** What the platform offers instead, where it offers something. */
|
|
140
|
+
const DENY_REPLACEMENTS = {
|
|
141
|
+
alert: "formAPI.services.ui.notify", confirm: "formAPI.services.ui.confirm", prompt: "formAPI.promptFields",
|
|
142
|
+
open: "formAPI.openForm / formAPI.navigate(url, { newTab: true })", location: "formAPI.navigate",
|
|
143
|
+
localStorage: "formAPI.services.storage", sessionStorage: "formAPI.services.storage",
|
|
144
|
+
WebSocket: "formAPI.realtime.subscribe", setImmediate: "setTimeout", queueMicrotask: "Promise.resolve().then",
|
|
145
|
+
requestAnimationFrame: "setTimeout", globalThis: "formAPI", window: "formAPI", document: "an element's own query()/hostElement",
|
|
146
|
+
};
|
|
147
|
+
/** Members code must never touch: an element's schema holds widget code the page recompiles with full page access. */
|
|
148
|
+
const FORBIDDEN_MEMBERS = new Set(["schema", "customView", "compiledRender"]);
|
|
149
|
+
function isSdkDeclared(symbol) {
|
|
150
|
+
return (symbol?.getDeclarations() ?? []).some((d) => d.getSourceFile().fileName.replace(/\\/g, "/").includes("node_modules/@suppa/frontend-sdk/"));
|
|
151
|
+
}
|
|
152
|
+
function declaredInSources(symbol, root) {
|
|
153
|
+
return (symbol?.getDeclarations() ?? []).some((d) => {
|
|
154
|
+
const rel = relative(root, d.getSourceFile().fileName).split(sep).join("/");
|
|
155
|
+
return rel.startsWith("src/");
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/** Literal names of a string union, or null when the type is not one. */
|
|
159
|
+
export function literalNames(type) {
|
|
160
|
+
const parts = type.isUnion() ? type.types : [type];
|
|
161
|
+
const names = parts.filter((p) => p.isStringLiteral()).map((p) => p.value);
|
|
162
|
+
return names.length && names.length === parts.length ? names.sort() : null;
|
|
163
|
+
}
|
|
164
|
+
/** Every event name `on(name, …)` accepts on a type: the first parameter of each live overload — minus deprecated ones and the catch-all `string & {}`. */
|
|
165
|
+
export function eventNames(ts, checker, type, at, method = "on") {
|
|
166
|
+
const on = checker.getPropertyOfType(type, method);
|
|
167
|
+
if (!on)
|
|
168
|
+
return null;
|
|
169
|
+
const names = new Set();
|
|
170
|
+
for (const signature of checker.getTypeOfSymbolAtLocation(on, at).getCallSignatures()) {
|
|
171
|
+
if (signature.getJsDocTags().some((tag) => tag.name === "deprecated"))
|
|
172
|
+
continue;
|
|
173
|
+
const first = signature.getParameters()[0];
|
|
174
|
+
if (!first)
|
|
175
|
+
continue;
|
|
176
|
+
let paramType = checker.getTypeOfSymbolAtLocation(first, at);
|
|
177
|
+
if (paramType.flags & ts.TypeFlags.TypeParameter)
|
|
178
|
+
paramType = checker.getBaseConstraintOfType(paramType) ?? paramType;
|
|
179
|
+
for (const name of literalNames(paramType) ?? [])
|
|
180
|
+
names.add(name);
|
|
181
|
+
}
|
|
182
|
+
return names.size ? [...names].sort() : null;
|
|
183
|
+
}
|
|
184
|
+
/** The rules the editor does not check and the platform does not enforce, but code must keep — warnings. */
|
|
185
|
+
function policyFindings(ts, root, program) {
|
|
186
|
+
const checker = program.getTypeChecker();
|
|
187
|
+
const out = [];
|
|
188
|
+
for (const file of program.getSourceFiles()) {
|
|
189
|
+
const rel = relative(root, file.fileName).split(sep).join("/");
|
|
190
|
+
if (!rel.startsWith("src/"))
|
|
191
|
+
continue;
|
|
192
|
+
const at = (node, code, message) => {
|
|
193
|
+
const pos = file.getLineAndCharacterOfPosition(node.getStart(file));
|
|
194
|
+
out.push({ file: rel, line: pos.line + 1, column: pos.character + 1, category: "warning", code, message });
|
|
195
|
+
};
|
|
196
|
+
const visit = (node) => {
|
|
197
|
+
// A bare global from the deny list (not a property name, not a local of the form's own code).
|
|
198
|
+
if (ts.isIdentifier(node) && DENY_IDENTIFIERS.has(node.text)) {
|
|
199
|
+
const parent = node.parent;
|
|
200
|
+
const isName = (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
|
|
201
|
+
(ts.isPropertyAssignment(parent) && parent.name === node) ||
|
|
202
|
+
(ts.isMethodDeclaration(parent) && parent.name === node) ||
|
|
203
|
+
(ts.isPropertySignature(parent) && parent.name === node) ||
|
|
204
|
+
(ts.isPropertyDeclaration(parent) && parent.name === node) ||
|
|
205
|
+
ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent) ||
|
|
206
|
+
((ts.isVariableDeclaration(parent) || ts.isParameter(parent) || ts.isFunctionDeclaration(parent) || ts.isBindingElement(parent)) && parent.name === node);
|
|
207
|
+
if (!isName) {
|
|
208
|
+
const symbol = checker.getSymbolAtLocation(node);
|
|
209
|
+
if (symbol && !declaredInSources(symbol, root)) {
|
|
210
|
+
const instead = DENY_REPLACEMENTS[node.text];
|
|
211
|
+
at(node, "denied-global", `\`${node.text}\` is a browser/runtime global Code Form must not use (the formbuilder agent's gate drops code that does)${instead ? ` — use ${instead}` : ""}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
// fetch: declared on purpose, for THIRD-PARTY origins only.
|
|
216
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "fetch") {
|
|
217
|
+
const symbol = checker.getSymbolAtLocation(node.expression);
|
|
218
|
+
if (symbol && !declaredInSources(symbol, root)) {
|
|
219
|
+
at(node, "fetch", "fetch is for third-party origins only (a public API, a signed upload URL) — the tenant's own data goes through formAPI.services.api, which carries the auth, the request cache and its invalidation; a 4xx/5xx resolves, check response.ok");
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
// `.schema` on a platform object, `customView` / `compiledRender` anywhere.
|
|
223
|
+
if (ts.isPropertyAccessExpression(node) && FORBIDDEN_MEMBERS.has(node.name.text)) {
|
|
224
|
+
const name = node.name.text;
|
|
225
|
+
const receiver = checker.getTypeAtLocation(node.expression);
|
|
226
|
+
const fromSdk = isSdkDeclared(receiver.getSymbol()) || isSdkDeclared(checker.getSymbolAtLocation(node.name));
|
|
227
|
+
// Syntactic too, as the agent's gate is: a cast (`as any`) hides the type, not the element.
|
|
228
|
+
const onElement = /\bformAPI\s*\.\s*(?:elements\b|getElement\s*\()|\.\s*getElement\s*\(/.test(node.expression.getText(file));
|
|
229
|
+
if (name !== "schema" || fromSdk || onElement) {
|
|
230
|
+
at(node.name, "forbidden-member", `\`.${name}\` — an element's schema holds widget code the page recompiles with full page access; drive an element through its own methods (the formbuilder agent's gate drops code that touches it)`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) && (node.name.text === "customView" || node.name.text === "compiledRender")) {
|
|
234
|
+
at(node.name, "forbidden-member", `\`${node.name.text}\` as an object key — widget code is a person's, written in the widget editor; code must not carry it`);
|
|
235
|
+
}
|
|
236
|
+
// `debugger` freezes the page for every viewer.
|
|
237
|
+
if (node.kind === ts.SyntaxKind.DebuggerStatement)
|
|
238
|
+
at(node, "debugger", "a `debugger` statement freezes the form for every viewer with DevTools open — remove it");
|
|
239
|
+
// An element event that does not exist: the catch-all overload compiles it and the handler never runs.
|
|
240
|
+
if (ts.isCallExpression(node) &&
|
|
241
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
242
|
+
(node.expression.name.text === "on" || node.expression.name.text === "once") &&
|
|
243
|
+
node.arguments.length >= 1 &&
|
|
244
|
+
ts.isStringLiteralLike(node.arguments[0])) {
|
|
245
|
+
const receiver = checker.getTypeAtLocation(node.expression.expression);
|
|
246
|
+
const target = checker.getNonNullableType(receiver);
|
|
247
|
+
const parts = target.isUnion() ? target.types : [target];
|
|
248
|
+
const known = new Set();
|
|
249
|
+
let typed = false;
|
|
250
|
+
for (const part of parts) {
|
|
251
|
+
const names = eventNames(ts, checker, part, node, node.expression.name.text);
|
|
252
|
+
if (names) {
|
|
253
|
+
typed = true;
|
|
254
|
+
for (const n of names)
|
|
255
|
+
known.add(n);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const event = node.arguments[0].text;
|
|
259
|
+
if (typed && !known.has(event) && isSdkDeclared(checker.getPropertyOfType(parts[0], node.expression.name.text))) {
|
|
260
|
+
at(node.arguments[0], "unknown-event", `'${event}' is not an event of this element — it compiles through the catch-all overload and the handler NEVER runs; its events: ${[...known].join(", ")}`);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
ts.forEachChild(node, visit);
|
|
264
|
+
};
|
|
265
|
+
visit(file);
|
|
266
|
+
}
|
|
267
|
+
return out;
|
|
268
|
+
}
|
|
269
|
+
/** Type-checks the workspace the way the Code Form editor does — see {@link createWorkspaceProgram} — and adds the import rule and the policy warnings. `override`: check these `src/**` contents instead of the disk's. */
|
|
270
|
+
export async function checkWorkspace(dir, core, override) {
|
|
271
|
+
const ts = await loadTs();
|
|
272
|
+
const { root, program, sources } = createWorkspaceProgram(ts, dir, undefined, override);
|
|
273
|
+
const compiled = ts
|
|
274
|
+
.getPreEmitDiagnostics(program)
|
|
275
|
+
.filter((d) => d.category === ts.DiagnosticCategory.Error || d.category === ts.DiagnosticCategory.Warning)
|
|
276
|
+
.map((d) => toDiagnostic(ts, root, d))
|
|
277
|
+
.filter((d) => d.file === null || d.file.startsWith("src/"));
|
|
278
|
+
const importText = String(core.FORBIDDEN_IMPORT_TEXT ?? "Only relative imports, @suppa/frontend-sdk and shared modules (@shared/…) are allowed in Code Form.").replace(/\{'@'\}/g, "@");
|
|
279
|
+
const imports = Object.entries(sources).flatMap(([path, code]) => core.detectForbiddenImports(code).map((f) => ({
|
|
280
|
+
file: path, line: f.line, column: f.column, category: "error", code: "import",
|
|
281
|
+
message: `${importText} ("${f.specifier}")`,
|
|
282
|
+
})));
|
|
283
|
+
const policy = policyFindings(ts, root, program);
|
|
284
|
+
const diagnostics = [...compiled, ...imports, ...policy].sort((a, b) => (a.file ?? "").localeCompare(b.file ?? "") || a.line - b.line || a.column - b.column);
|
|
285
|
+
return { files: Object.keys(sources).length, diagnostics };
|
|
286
|
+
}
|
|
287
|
+
const MAX_DIAGNOSTICS = 50;
|
|
288
|
+
/**
|
|
289
|
+
* The errors `after` has that `before` did not — what a change CAUSED, in any file. Matched by file, code and
|
|
290
|
+
* message with multiplicity, never by position: an edit above an old error moves it without making it new.
|
|
291
|
+
*/
|
|
292
|
+
export function newErrors(before, after) {
|
|
293
|
+
const key = (d) => `${d.file ?? ""}|${d.code}|${d.message}`;
|
|
294
|
+
const left = new Map();
|
|
295
|
+
for (const d of before)
|
|
296
|
+
if (d.category === "error")
|
|
297
|
+
left.set(key(d), (left.get(key(d)) ?? 0) + 1);
|
|
298
|
+
const out = [];
|
|
299
|
+
for (const d of after) {
|
|
300
|
+
if (d.category !== "error")
|
|
301
|
+
continue;
|
|
302
|
+
const n = left.get(key(d)) ?? 0;
|
|
303
|
+
if (n > 0)
|
|
304
|
+
left.set(key(d), n - 1);
|
|
305
|
+
else
|
|
306
|
+
out.push(d);
|
|
307
|
+
}
|
|
308
|
+
return out;
|
|
309
|
+
}
|
|
310
|
+
export function diagnosticLine(d) {
|
|
311
|
+
return `${d.file ?? "(project)"}${d.file ? `:${d.line}:${d.column}` : ""} ${d.category} ${typeof d.code === "number" ? `TS${d.code}` : d.code}: ${d.message.split("\n").join(" ")}`;
|
|
312
|
+
}
|
|
313
|
+
export function formatCheck(result) {
|
|
314
|
+
const errors = result.diagnostics.filter((d) => d.category === "error").length;
|
|
315
|
+
const warnings = result.diagnostics.length - errors;
|
|
316
|
+
const n = (k, w) => `${k} ${w}${k === 1 ? "" : "s"}`;
|
|
317
|
+
if (!result.diagnostics.length)
|
|
318
|
+
return `✓ ${n(result.files, "file")}, no type errors, no warnings`;
|
|
319
|
+
const head = `${errors ? "✗" : "⚠"} ${n(errors, "error")}, ${n(warnings, "warning")} in ${n(result.files, "file")}`;
|
|
320
|
+
const shown = result.diagnostics.slice(0, MAX_DIAGNOSTICS).map(diagnosticLine);
|
|
321
|
+
if (result.diagnostics.length > MAX_DIAGNOSTICS)
|
|
322
|
+
shown.push(`… ${result.diagnostics.length - MAX_DIAGNOSTICS} more`);
|
|
323
|
+
return [head, ...shown].join("\n");
|
|
324
|
+
}
|