diff --git a/packages/core/src/discovery/fold-import.test.ts b/packages/core/src/discovery/fold-import.test.ts index 97bede4516..5ac915b6f0 100644 --- a/packages/core/src/discovery/fold-import.test.ts +++ b/packages/core/src/discovery/fold-import.test.ts @@ -166,7 +166,28 @@ describe("tryFoldFile", () => { expect(result.ok).toBe(false); if (result.ok) return; - expect(result.reason).toContain("LocalStack"); + // chant #1054 — locks in the ONE wording for "a call used as a value, + // not foldable" (../fold/subset.ts's `callExpressionMessage`), which + // `resolveCallExpression` now reuses instead of its own hand-written + // "call expression as a value" copy. + expect(result.reason).toBe('"stack" is not foldable: function call as a value is not foldable: LocalStack(...)'); + }); + + test("falls back when a top-level export's callee isn't a plain identifier (chant #1054: same wording as any other call-as-a-value rejection)", async () => { + const file = join(testDir, "main.ts"); + await writeFile( + file, + ` + const builder = { build: (props: { name: string }) => ({ name: props.name }) }; + export const stack = builder.build({ name: "x" }); + `, + ); + + const result = await tryFoldFile(file); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).toBe('"stack" is not foldable: function call as a value is not foldable: builder.build(...)'); }); test("falls back when a prop value is not foldable", async () => { @@ -287,6 +308,77 @@ describe("tryFoldFile", () => { DependsOn: "otherResource", }); }); + + // chant #1054 — a destructured composite export's fallback reason used to + // embed `decl.node.getText()`: the ENTIRE call expression, which for a + // real multi-prop composite call is many lines, burying the real error + // after all of it. These lock in the fix: the reason names the binding(s) + // and the callee briefly instead, and stays on one line. + test("a destructured composite export whose source fails to resolve reports a brief, single-line reason naming the binding names and the callee", async () => { + await writeFile( + join(testDir, "composites.ts"), + ` + import { createResource } from ${JSON.stringify(runtimePath)}; + import { Composite } from ${JSON.stringify(compositePath)}; + const Cluster = createResource("Test::Cluster", "gcp", {}); + const NodePool = createResource("Test::NodePool", "gcp", {}); + export const GkeCluster = Composite<{ name: string; location: string }>((props) => { + const cluster = new Cluster({ name: props.name }); + const nodePool = new NodePool({ location: props.location }); + return { cluster, nodePool }; + }, "GkeCluster"); + `, + ); + const file = join(testDir, "cluster.ts"); + await writeFile( + file, + ` + import { GkeCluster } from "./composites"; + export const { cluster, nodePool } = GkeCluster({ + name: config.clusterName, + location: config.region, + }); + `, + ); + + const result = await tryFoldFile(file); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).not.toContain("\n"); + expect(result.reason).toContain('"cluster, nodePool" (destructured from GkeCluster(...))'); + expect(result.reason).toContain("unresolved identifier: config"); + // The whole multi-line source is gone — the reason never reproduces the + // call's own argument list verbatim. + expect(result.reason).not.toContain("clusterName"); + }); + + test("a destructured export whose source resolves but isn't an object still reports a brief, single-line reason", async () => { + await writeFile( + join(testDir, "factory.ts"), + ` + export function StringFactory(props: { text: string }): string { + return props.text; + } + `, + ); + const file = join(testDir, "main.ts"); + await writeFile( + file, + ` + import { StringFactory } from "./factory"; + export const { length } = StringFactory({ text: "hello" }); + `, + ); + + const result = await tryFoldFile(file); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.reason).toBe( + '"length" (destructured from StringFactory(...)) is not foldable: not a composite call or object', + ); + }); }); // chant #1020 (epic #1019) — cross-file resolution: an imported binding now diff --git a/packages/core/src/discovery/fold-import.ts b/packages/core/src/discovery/fold-import.ts index 9cd89c37a9..3e2d5c7b80 100644 --- a/packages/core/src/discovery/fold-import.ts +++ b/packages/core/src/discovery/fold-import.ts @@ -21,6 +21,7 @@ import { type SymbolicValue, } from "../fold/fold"; import { isChantOwnedSpecifier } from "../fold/foldable-helpers"; +import { briefNodeText, callExpressionMessage } from "../fold/subset"; import { importModule } from "./import"; import type { IntrinsicDef } from "../lexicon"; import type { BuildParamValue } from "../build-params"; @@ -1101,13 +1102,18 @@ async function resolveLiveValue(node: ts.Expression, ctx: ResolveCtx): Promise { + // chant #1054 — reuses ../fold/subset's `callExpressionMessage` (the SAME + // builder `fold()` throws with for a call used as a prop value) rather + // than a hand-written "call expression as a value" copy: the two used to + // say different things for the identical rejection, which silently broke + // any tooling grouping fallback reasons by text. if (!ts.isIdentifier(node.expression)) { - throw cheapError(`call expression as a value is not foldable: ${node.expression.getText()}(...)`); + throw cheapError(callExpressionMessage(node)); } const calleeName = node.expression.text; const binding = ctx.imports.get(calleeName); if (!binding) { - throw cheapError(`call expression as a value is not foldable: ${calleeName}(...)`); + throw cheapError(callExpressionMessage(node)); } let modulePath: string; @@ -1592,6 +1598,18 @@ function describeFoldFailure(err: unknown, ctx: ResolveCtx): string { return err.message; } +/** + * chant #1054 — a short, single-line label for a destructured export's + * source expression, for a fold fallback reason: the callee plus `(...)` + * for the common composite-call source (`GkeCluster(...)`), or a brief, + * bounded rendering of whatever else it is otherwise. Never the source's own + * `getText()` — for a real composite call that's the entire multi-line + * argument list. + */ +function describeDestructureSource(node: ts.Expression): string { + return ts.isCallExpression(node) ? `${briefNodeText(node.expression)}(...)` : briefNodeText(node); +} + /** Build a located `FoldError`'s formatted "line:col - message" string anchored at `node` — for a cross-file failure detected here in fold-import.ts (an import cycle, a name genuinely absent from the target module's exports) rather than inside `fold()` itself. */ function locatedMessage(node: ts.Node, message: string): string { const { line, column } = locate(node); @@ -1911,18 +1929,26 @@ async function tryFoldFileCore(file: string, session: FoldSession): Promise el.bindingName).join(", "); + const source = describeDestructureSource(decl.node); try { value = (await resolveDeclaratorValue(decl.node, ctx)).value; } catch (err) { return { ok: false, - reason: `destructured export from "${decl.node.getText()}" is not foldable: ${describeFoldFailure(err, ctx)}`, + reason: `"${boundNames}" (destructured from ${source}) is not foldable: ${describeFoldFailure(err, ctx)}`, }; } if (!isIndexableObject(value)) { return { ok: false, - reason: `destructured export from "${decl.node.getText()}" is not foldable (not a composite call or object)`, + reason: `"${boundNames}" (destructured from ${source}) is not foldable: not a composite call or object`, }; } for (const { propKey, bindingName } of decl.elements) { diff --git a/packages/core/src/fold/fold.ts b/packages/core/src/fold/fold.ts index 467de9919a..25473f1034 100644 --- a/packages/core/src/fold/fold.ts +++ b/packages/core/src/fold/fold.ts @@ -5,6 +5,7 @@ import { SUPPORTED_UNARY_OPERATORS, UNSUPPORTED_OBJECT_MEMBER_MESSAGE, UNSUPPORTED_UNARY_MESSAGE, + briefNodeText, callExpressionMessage, computedPropertyNameMessage, dynamicElementAccessMessage, @@ -396,7 +397,7 @@ function foldTaggedTemplate( const tagName = node.tag.getText(); const isRegistered = intrinsics.some((i) => i.name === tagName && intrinsicTagFolds(i)); if (!isRegistered) { - throw foldError(node, `unregistered tagged template intrinsic: ${tagName}\`...\``); + throw foldError(node, `unregistered tagged template intrinsic: ${briefNodeText(node.tag)}\`...\``); } const template = node.template; @@ -635,7 +636,10 @@ export function fold( // Reject so the file falls back to run, which constructs and serializes it // correctly. EVL permits this statically — it's a documented fold/EVL // divergence, like identifier resolution and spread runtime type. - throw foldError(node, `nested \`new ${node.expression.getText()}(...)\` as a value is not foldable — falls back to run`); + throw foldError( + node, + `nested \`new ${briefNodeText(node.expression)}(...)\` as a value is not foldable — falls back to run`, + ); } if (ts.isCallExpression(node)) { diff --git a/packages/core/src/fold/subset.test.ts b/packages/core/src/fold/subset.test.ts index 34035c5fd9..2567dd85b3 100644 --- a/packages/core/src/fold/subset.test.ts +++ b/packages/core/src/fold/subset.test.ts @@ -1,7 +1,7 @@ import { describe, test, expect } from "vitest"; import * as ts from "typescript"; import { fold, foldResource, collectConsts, FoldError } from "./fold"; -import { findSubsetViolation } from "./subset"; +import { briefNodeText, callExpressionMessage, findSubsetViolation } from "./subset"; import { evl001NonLiteralExpressionRule } from "../lint/rules/evl001-non-literal-expression"; import { evl003DynamicPropertyAccessRule } from "../lint/rules/evl003-dynamic-property-access"; import { evl004SpreadNonConstRule } from "../lint/rules/evl004-spread-non-const"; @@ -350,3 +350,69 @@ describe("findSubsetViolation — optional intrinsic registry (#1044)", () => { expect(evl001NonLiteralExpressionRule.check(context).length).toBeGreaterThan(0); }); }); + +/** + * chant #1054 — `briefNodeText` is what keeps every fold fallback reason + * that used to embed a node's raw `getText()` down to one bounded line. A + * real composite call's source is many lines; a fold reason that reproduces + * it verbatim buries the actual error after all of it (the bug this issue + * reports) and breaks any line-oriented consumer of `[fold:run]` output. + */ +describe("briefNodeText — single-line, bounded diagnostic text (chant #1054)", () => { + function initializerOf(source: string): ts.Expression { + const sourceFile = ts.createSourceFile("t.ts", source, ts.ScriptTarget.Latest, true); + const consts = collectConsts(sourceFile); + const init = consts.get("x"); + if (!init) throw new Error(`fixture error: "x" did not parse in ${JSON.stringify(source)}`); + return init; + } + + test("a short, single-line node passes through unchanged", () => { + expect(briefNodeText(initializerOf(`const x = GkeCluster;`))).toBe("GkeCluster"); + }); + + test("a multi-line node's newlines collapse to spaces — the result is always one line", () => { + const text = briefNodeText( + initializerOf(` + const x = GkeCluster({ + name: config.clusterName, + location: config.region, + }); + `), + ); + expect(text).not.toContain("\n"); + expect(text.split("\n")).toHaveLength(1); + }); + + test("text over the length cap is truncated with a trailing marker rather than left unbounded", () => { + const text = briefNodeText( + initializerOf(`const x = { aVeryLongPropertyNameNumberOne: 1, aVeryLongPropertyNameNumberTwo: 2 };`), + 20, + ); + expect(text.length).toBe(20); + expect(text.endsWith("...")).toBe(true); + }); +}); + +describe("callExpressionMessage — one line regardless of the call's own argument list (chant #1054)", () => { + test("only the callee is embedded — a multi-line argument list never leaks into the message", () => { + const sourceFile = ts.createSourceFile( + "t.ts", + ` + const x = GkeCluster({ + name: config.clusterName, + location: config.region, + machineType: "n2-standard-2", + }); + `, + ts.ScriptTarget.Latest, + true, + ); + const consts = collectConsts(sourceFile); + const call = consts.get("x") as ts.CallExpression; + + const message = callExpressionMessage(call); + + expect(message).toBe("function call as a value is not foldable: GkeCluster(...)"); + }); +}); diff --git a/packages/core/src/fold/subset.ts b/packages/core/src/fold/subset.ts index f9d0e09e8d..82127142f4 100644 --- a/packages/core/src/fold/subset.ts +++ b/packages/core/src/fold/subset.ts @@ -141,6 +141,22 @@ export function isLiteralElementKey(node: ts.Expression): node is ts.StringLiter return ts.isStringLiteral(node) || ts.isNumericLiteral(node); } +/** + * A short, single-line rendering of `node`'s source text for embedding in a + * diagnostic message — never the raw `getText()`, which reproduces the + * node's ENTIRE source verbatim and can span dozens of lines for a real + * composite call or object literal (chant #1054: a fold fallback reason that + * embeds one of these buries the actual error after it, and breaks any + * line-oriented consumer of `[fold:run]` output). Internal whitespace + * (including newlines) collapses to a single space, and the result is capped + * to a bounded length so one pathological node can't blow out an otherwise + * one-line reason either. + */ +export function briefNodeText(node: ts.Node, maxLength = 60): string { + const collapsed = node.getText().replace(/\s+/g, " ").trim(); + return collapsed.length > maxLength ? `${collapsed.slice(0, maxLength - 3)}...` : collapsed; +} + // --------------------------------------------------------------------------- // Shared message builders — `fold()` and `findSubsetViolation` both call // these so the diagnostic text for the same violation kind is the same @@ -148,11 +164,11 @@ export function isLiteralElementKey(node: ts.Expression): node is ts.StringLiter // --------------------------------------------------------------------------- export function computedPropertyNameMessage(node: ts.PropertyName): string { - return `computed/dynamic property name not foldable: ${node.getText()}`; + return `computed/dynamic property name not foldable: ${briefNodeText(node)}`; } export function dynamicElementAccessMessage(keyNode: ts.Expression): string { - return `dynamic property access — computed key must be a string or numeric literal: ${keyNode.getText()}`; + return `dynamic property access — computed key must be a string or numeric literal: ${briefNodeText(keyNode)}`; } export const UNSUPPORTED_OBJECT_MEMBER_MESSAGE = "unsupported object member"; @@ -163,8 +179,19 @@ export function unsupportedBinaryMessage(opKind: ts.SyntaxKind): string { return `unsupported binary operator: ${ts.SyntaxKind[opKind]}`; } +/** + * chant #1054 — the ONE wording for "a bare function/method call used where + * chant needs a value it can fold." Before this, `fold()` (this message) and + * `../discovery/fold-import.ts`'s `resolveCallExpression` (a top-level + * export's own call-as-a-value check) had each grown their own hand-written + * copy — "function call as a value" here, "call expression as a value" + * there — for the identical rejection, which meant a tool grouping fallback + * reasons by text had to match both to avoid silently under-counting one of + * them. `resolveCallExpression` now calls this function directly instead of + * building its own string. + */ export function callExpressionMessage(node: ts.CallExpression): string { - return `function call as a value is not foldable: ${node.expression.getText()}(...)`; + return `function call as a value is not foldable: ${briefNodeText(node.expression)}(...)`; } export function unsupportedExpressionMessage(node: ts.Node): string {