Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.metaobjects.generator.kotlin

import com.metaobjects.metadata.ktx.loadDirectory
import com.metaobjects.metadata.ktx.loadString
import java.nio.file.Files
import kotlin.test.Test
Expand Down Expand Up @@ -249,4 +250,83 @@ class KotlinPayloadGeneratorTest {
outDir.toFile().deleteRecursively()
}
}

@Test fun `nested field-object objectRef given as a cross-package FQN emits bare payload names, no package-qualified identifier`() {
// Regression companion to the TS promptRender FQN-leak fix (0.15.17): a payload VO whose
// naked `field.object @objectRef` points at ANOTHER object.value declared in a DIFFERENT
// package. The target's resolved name is a real FQN (`acme::ai::Note`), so
// PackageMapping.splitFqn must strip the package for BOTH the emitted property type and
// the nested data-class name — an FQN contains `::`, which is not a valid Kotlin
// identifier. (The TS port leaked `List<acme::ai::Note>` / `data class acme::ai::Note`;
// Kotlin's ClassName(pkg, simpleName) construction is FQN-safe — this pins it.)
//
// Two packages ⇒ two files (a single loadString supports only one root/package), so the
// prefix is genuinely non-empty when it reaches splitFqn.
val noteJson = """{
"metadata.root": { "package": "acme::ai", "children": [
{ "object.value": { "name": "Note", "children": [
{ "field.string": { "name": "text" } }
] } }
] }
}""".trimIndent()
val reportJson = """{
"metadata.root": { "package": "acme::demo", "children": [
{ "object.value": { "name": "Report", "children": [
{ "field.string": { "name": "title" } },
{ "field.object": { "name": "notes",
"@objectRef": "acme::ai::Note", "isArray": true } }
] } },
{ "template.prompt": { "name": "ReportPrompt",
"@payloadRef": "Report", "@textRef": "demo/report" } }
] }
}""".trimIndent()

val srcDir = Files.createTempDirectory("kpay-fqn-src-")
val outDir = Files.createTempDirectory("kpay-fqn-out-")
try {
// note.json sorts before report.json — but cross-file @objectRef resolution is
// load-order-independent (ADR-0041), so ordering is not load-bearing here.
Files.writeString(srcDir.resolve("note.json"), noteJson)
Files.writeString(srcDir.resolve("report.json"), reportJson)

val gen = KotlinPayloadGenerator()
gen.setArgs(mapOf("outputDir" to outDir.toString()))
gen.execute(loadDirectory("test-fqn", srcDir))

// Nested payload for a cross-package target co-locates in the REFERRING template's
// prompts package (acme.demo.prompts), keyed by the target's bare short name.
val parentFile = outDir.resolve("acme/demo/prompts/ReportPromptPayload.kt")
val nestedFile = outDir.resolve("acme/demo/prompts/NotePayload.kt")
assertTrue(Files.exists(parentFile),
"expected $parentFile; files=${Files.walk(outDir).toList()}")
assertTrue(Files.exists(nestedFile),
"expected $nestedFile; files=${Files.walk(outDir).toList()}")

val parentSrc = Files.readString(parentFile)
// Bare, FQN-stripped array-of-nested-payload type — NOT `List<acme::ai::Note>`.
assertTrue("val notes: List<NotePayload>" in parentSrc, parentSrc)
assertTrue("val title: String" in parentSrc, parentSrc)

val nestedSrc = Files.readString(nestedFile)
// Bare data-class name — NOT `data class acme::ai::Note`.
assertTrue("data class NotePayload" in nestedSrc, nestedSrc)
assertTrue("val text: String" in nestedSrc, nestedSrc)
assertTrue("package acme.demo.prompts" in nestedSrc, nestedSrc)

// No emitted IDENTIFIER may contain `::`. The FQN legitimately survives only in KDoc
// comment lines (which document the source object `acme::ai::Note`); every other line
// must be `::`-free. Filter comment lines (leading `*` or `/`), then assert clean.
for ((label, src) in listOf("parent" to parentSrc, "nested" to nestedSrc)) {
val offenders = src.lines().filter { line ->
val t = line.trimStart()
"::" in line && !t.startsWith("*") && !t.startsWith("/")
}
assertTrue(offenders.isEmpty(),
"$label: no emitted identifier may contain '::'; offenders=$offenders\n$src")
}
} finally {
srcDir.toFile().deleteRecursively()
outDir.toFile().deleteRecursively()
}
}
}
58 changes: 58 additions & 0 deletions server/python/tests/codegen/test_payload_vo_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ def _field_with_origin(name: str, sub: str, origin: MetaOrigin) -> MetaField:
return f


def _object_field(name: str, object_ref: str, *, is_array: bool = False) -> MetaField:
"""A plain ``field.object`` carrying an ``@objectRef`` (no origin child). The
ref is passed in the FQN form the loader produces post-ADR-0041 (e.g.
``acme::ai::Note``) so the generator's package-stripping is exercised."""
f = MetaField(TYPE_FIELD, fc.FIELD_SUBTYPE_OBJECT, name)
f.set_attr(fc.FIELD_ATTR_OBJECT_REF, object_ref)
f.is_array = is_array
return f


def _passthrough(from_ref: str) -> MetaOrigin:
o = MetaOrigin(TYPE_ORIGIN, ORIGIN_SUBTYPE_PASSTHROUGH, "from")
o.set_attr(ORIGIN_ATTR_FROM, from_ref)
Expand Down Expand Up @@ -370,6 +380,54 @@ def test_origin_collection_nested_payload_deduped_within_file() -> None:
assert "drafts: list[PostPayload]" in out


# ---------------------------------------------------------------------------
# Plain field.object @objectRef (no origin) — the FQN must be stripped to the
# bare name for BOTH the emitted field annotation AND the nested class
# declaration. Cross-port regression guard: the TS payload generator once
# emitted the raw ``@objectRef`` FQN verbatim (``notes: acme::ai::Note[]`` and
# ``interface acme::ai::Note``). Python resolves the ref to the target
# MetaObject and names off ``target.name`` (always bare), so this must stay
# clean — this test locks that in.
# ---------------------------------------------------------------------------


def test_plain_object_field_strips_fqn_to_bare_nested_payload() -> None:
"""A ``field.object`` whose ``@objectRef`` is a package-qualified FQN
(``acme::ai::Note`` — the form the loader emits post-ADR-0041) must type as
``list[NotePayload]`` and emit ``class NotePayload(BaseModel):`` — the BARE
name — never the raw FQN. Guards the cross-port payload FQN leak that was
TS-only (``notes: acme::ai::Note[]`` / ``interface acme::ai::Note``)."""
note = _value_object(
"Note", [_field("text", fc.FIELD_SUBTYPE_STRING)], package="acme::ai"
)
report = _value_object(
"Report",
[_object_field("notes", "acme::ai::Note", is_array=True)],
package="acme::ai",
)
tmpl = _template("ReportOutput", "Report")
root = _root([note, report, tmpl])
out = render_payload_vo(tmpl, root)
assert out is not None
# Field annotation types to the BARE nested-payload class, wrapped as a list.
assert "notes: list[NotePayload]" in out
# Nested payload class declared under its BARE name, before the primary class.
assert "class NotePayload(BaseModel):" in out
assert out.find("class NotePayload(BaseModel):") < out.find(
"class ReportOutputPayload(BaseModel):"
)
assert "text: str" in out
# __all__ carries both BARE class names.
assert '__all__ = ["ReportOutputPayload", "NotePayload"]' in out
# The referenced VO's FQN must NOT leak anywhere in the emitted source.
assert "acme::ai::Note" not in out
# No package separator in the emitted CODE. (The generated header comment
# legitimately carries the module's OWN FQN — ``acme::ai::ReportOutput`` —
# so the ``::``-free check is scoped to non-comment lines.)
code = "\n".join(ln for ln in out.splitlines() if not ln.lstrip().startswith("#"))
assert "::" not in code


# ---------------------------------------------------------------------------
# Resolution edge cases.
# ---------------------------------------------------------------------------
Expand Down
Loading