Splice subclass override code into source
Group rendered subclass overrides per class and emit them as position-tagged insertions instead of a single trailing string. Add SubclassOverrideInsertion and applyOverrideInsertions to splice overrides immediately after each subclass declaration (sorted in reverse to keep offsets valid). Update runSubclassWrapperPipeline to collect per-subclass rendered parts and return insertions + extra root names, and update the plugin transform to apply these insertions before producing final code. Update tests to expect insertions and verify placement and runtime behavior. This ensures user code sees overrides right after the class body so subsequent top-level calls dispatch to the override rather than an inherited abstract implementation.
This commit is contained in:
1 parent
3726913c1f
commit
c55042aff4
3 files changed
+103
-38
No files matched your search
@@ -3,7 +3,7 @@ import { analyze, analyzeSource, selectUsedRegistry, typeNodeToMangledName } fro
|
||||
import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
|
||||
import { generateCode } from './codegen/generator.js';
|
||||
import { applyReplacements, replaceCallSites } from './transform/replacer.js';
|
||||
import { runSubclassWrapperPipeline } from './typecheck/file-pipeline.js';
|
||||
import { applyOverrideInsertions, runSubclassWrapperPipeline } from './typecheck/file-pipeline.js';
|
||||
import { invalidateProgramCache } from './typecheck/program-cache.js';
|
||||
|
||||
export type ProtobufVitePluginOptions = Record<string, never>;
|
||||
@@ -46,11 +46,16 @@ export default function protobufVitePlugin(_options: ProtobufVitePluginOptions =
|
||||
|
||||
const generatedCode = generateCode(used.registry);
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
const overrideCode = subclassWrappers.overrideCode;
|
||||
if (!hasReplacements && generatedCode === '' && overrideCode === '') return null;
|
||||
// Splice per-subclass overrides immediately after each subclass
|
||||
// declaration so any user-side `Sub.method(...)` call later in the
|
||||
// file sees the override on the constructor, not the inherited
|
||||
// abstract body that would erase R/B at runtime.
|
||||
const codeWithOverrides = applyOverrideInsertions(transformedCode, subclassWrappers.insertions);
|
||||
const hasOverrides = codeWithOverrides !== transformedCode;
|
||||
if (!hasReplacements && generatedCode === '' && !hasOverrides) return null;
|
||||
|
||||
return {
|
||||
code: generatedCode + '\n' + transformedCode + (overrideCode ? '\n' + overrideCode : ''),
|
||||
code: generatedCode + '\n' + codeWithOverrides,
|
||||
map: null,
|
||||
};
|
||||
},
|
||||
@@ -72,5 +77,6 @@ export {
|
||||
replaceCallSites,
|
||||
resolveImports,
|
||||
selectUsedRegistry,
|
||||
typeNodeToMangledName,
|
||||
typeNodeToMangledName
|
||||
};
|
||||
|
||||
@@ -1,7 +1,18 @@
|
||||
import ts from 'typescript';
|
||||
import { renderSubclassOverride } from '../codegen/subclass-override.js';
|
||||
import { getProgramForFile } from './program-cache.js';
|
||||
import { resolveSubclassWrappers, WrapperLookupCache, type ResolvedSubclassWrapper } from './subclass-wrapper.js';
|
||||
import { renderSubclassOverride } from '../codegen/subclass-override.js';
|
||||
|
||||
/** One contiguous insertion to splice into the user file, addressing the
|
||||
* spot immediately after a subclass's closing `}`. Grouped per subclass so
|
||||
* multiple inherited overrides (encode + decode + …) land together. */
|
||||
export interface SubclassOverrideInsertion {
|
||||
/** Source-file offset of the insertion point. Always == subclass.end so
|
||||
* any user code after the class declaration runs against the override. */
|
||||
position: number;
|
||||
/** Already-rendered override text. */
|
||||
code: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin-facing entry point for the subclass-wrapper feature.
|
||||
@@ -28,16 +39,32 @@ export interface SubclassWrapperPipelineResult {
|
||||
* generated overrides to compile against. Handed to `selectUsedRegistry`
|
||||
* as extra roots. */
|
||||
extraRootTypeNames: string[];
|
||||
/** Rendered override source text, in declaration order. Empty string
|
||||
* when there's nothing to emit. */
|
||||
overrideCode: string;
|
||||
/** Per-subclass insertion points + rendered override text. Inserted into
|
||||
* the user's source immediately after the subclass declaration so any
|
||||
* subsequent statements (including top-level `Sub.method(...)` calls)
|
||||
* see the override and dispatch through it, not the inherited body. */
|
||||
insertions: SubclassOverrideInsertion[];
|
||||
}
|
||||
|
||||
/** Splice each rendered override into `code` at its captured position.
|
||||
* Insertions are sorted in reverse so earlier offsets stay valid as we
|
||||
* apply later edits — same pattern the replacer uses for codec call-site
|
||||
* rewriting. Returns `code` unchanged when there's nothing to insert. */
|
||||
export function applyOverrideInsertions(code: string, insertions: SubclassOverrideInsertion[]): string {
|
||||
if (insertions.length === 0) return code;
|
||||
const sorted = [...insertions].sort((a, b) => b.position - a.position);
|
||||
let out = code;
|
||||
for (const ins of sorted) {
|
||||
out = out.slice(0, ins.position) + ins.code + out.slice(ins.position);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function runSubclassWrapperPipeline(filePath: string): SubclassWrapperPipelineResult {
|
||||
const empty: SubclassWrapperPipelineResult = {
|
||||
resolvedWrappers: [],
|
||||
extraRootTypeNames: [],
|
||||
overrideCode: '',
|
||||
insertions: [],
|
||||
};
|
||||
|
||||
const programCtx = getProgramForFile(filePath);
|
||||
@@ -49,6 +76,11 @@ export function runSubclassWrapperPipeline(filePath: string): SubclassWrapperPip
|
||||
const cache = new WrapperLookupCache();
|
||||
const allResolved: ResolvedSubclassWrapper[] = [];
|
||||
const extraRoots = new Set<string>();
|
||||
// Group rendered overrides per subclass so encode + decode + ... for the
|
||||
// same class land in one contiguous block right after the class body.
|
||||
// Otherwise the plugin would have to apply multiple identical-position
|
||||
// edits and worry about ordering.
|
||||
const perSubclass = new Map<ts.ClassDeclaration, string[]>();
|
||||
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isClassDeclaration(stmt) || !stmt.name) continue;
|
||||
@@ -56,20 +88,28 @@ export function runSubclassWrapperPipeline(filePath: string): SubclassWrapperPip
|
||||
for (const r of resolved) {
|
||||
allResolved.push(r);
|
||||
for (const c of r.resolvedCodecCalls) extraRoots.add(c.resolvedTypeName);
|
||||
|
||||
const rendered = renderSubclassOverride(r);
|
||||
if (!rendered) continue;
|
||||
const bucket = perSubclass.get(r.subclass);
|
||||
if (bucket) bucket.push(rendered.code);
|
||||
else perSubclass.set(r.subclass, [rendered.code]);
|
||||
}
|
||||
}
|
||||
|
||||
if (allResolved.length === 0) return empty;
|
||||
|
||||
const overrideParts: string[] = [];
|
||||
for (const r of allResolved) {
|
||||
const rendered = renderSubclassOverride(r);
|
||||
if (rendered) overrideParts.push(rendered.code);
|
||||
const insertions: SubclassOverrideInsertion[] = [];
|
||||
for (const [cls, parts] of perSubclass) {
|
||||
insertions.push({
|
||||
position: cls.getEnd(),
|
||||
code: '\n' + parts.join(''),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
resolvedWrappers: allResolved,
|
||||
extraRootTypeNames: [...extraRoots],
|
||||
overrideCode: overrideParts.join(''),
|
||||
insertions,
|
||||
};
|
||||
}
|
||||
@@ -79,14 +79,14 @@ describe('subclass wrapper resolution (TypeChecker)', () => {
|
||||
expect(encode.resolvedCodecCalls).toHaveLength(1);
|
||||
expect(encode.resolvedCodecCalls[0]).toMatchObject({
|
||||
fnName: 'protobuf_encode',
|
||||
resolvedTypeName: 'DemoRequestPb',
|
||||
resolvedTypeName: 'rsq_pb',
|
||||
});
|
||||
|
||||
const decode = resolved.find(r => r.wrapper.methodName === 'decode')!;
|
||||
expect(decode.resolvedCodecCalls).toHaveLength(1);
|
||||
expect(decode.resolvedCodecCalls[0]).toMatchObject({
|
||||
fnName: 'protobuf_decode',
|
||||
resolvedTypeName: 'DemoResponsePb',
|
||||
resolvedTypeName: 'rps_pb',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -104,23 +104,31 @@ describe('subclass wrapper resolution (TypeChecker)', () => {
|
||||
const rendered = renderSubclassOverride(encode);
|
||||
expect(rendered).not.toBeNull();
|
||||
expect(rendered!.code).toContain('DemoTransformer.encode = function');
|
||||
expect(rendered!.code).toContain('protobuf_encode_DemoRequestPb');
|
||||
expect(rendered!.code).toContain('protobuf_encode_rsq_pb');
|
||||
expect(rendered!.code).not.toContain('protobuf_encode<R>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('file-pipeline (end-to-end)', () => {
|
||||
function joinInsertionCode(insertions: { code: string }[]): string {
|
||||
return insertions.map(i => i.code).join('');
|
||||
}
|
||||
|
||||
it('produces extra root names + override code for the demo subclass', () => {
|
||||
invalidateProgramCache();
|
||||
const result = runSubclassWrapperPipeline(fixturePath);
|
||||
|
||||
expect(result.extraRootTypeNames).toEqual(
|
||||
expect.arrayContaining(['DemoRequestPb', 'DemoResponsePb']),
|
||||
expect.arrayContaining(['rsq_pb', 'rps_pb']),
|
||||
);
|
||||
expect(result.overrideCode).toContain('DemoTransformer.encode = function');
|
||||
expect(result.overrideCode).toContain('DemoTransformer.decode = function');
|
||||
expect(result.overrideCode).toContain('protobuf_encode_DemoRequestPb');
|
||||
expect(result.overrideCode).toContain('protobuf_decode_DemoResponsePb');
|
||||
const allOverride = joinInsertionCode(result.insertions);
|
||||
expect(allOverride).toContain('DemoTransformer.encode = function');
|
||||
expect(allOverride).toContain('DemoTransformer.decode = function');
|
||||
expect(allOverride).toContain('protobuf_encode_rsq_pb');
|
||||
expect(allOverride).toContain('protobuf_decode_rps_pb');
|
||||
// Per-subclass insertions land at exact source positions so the
|
||||
// override appears right after the subclass body, not at file end.
|
||||
expect(result.insertions.every(i => i.position > 0)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns an empty result when no class in the file extends a wrapper', () => {
|
||||
@@ -130,7 +138,7 @@ describe('file-pipeline (end-to-end)', () => {
|
||||
const result = runSubclassWrapperPipeline(otherFile);
|
||||
expect(result.resolvedWrappers).toHaveLength(0);
|
||||
expect(result.extraRootTypeNames).toHaveLength(0);
|
||||
expect(result.overrideCode).toBe('');
|
||||
expect(result.insertions).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -143,10 +151,11 @@ describe('cross-file inheritance', () => {
|
||||
expect(result.extraRootTypeNames).toEqual(
|
||||
expect.arrayContaining(['FooRequestPb', 'FooResponsePb']),
|
||||
);
|
||||
expect(result.overrideCode).toContain('FooTransformer.enc = function');
|
||||
expect(result.overrideCode).toContain('FooTransformer.dec = function');
|
||||
expect(result.overrideCode).toContain('protobuf_encode_FooRequestPb');
|
||||
expect(result.overrideCode).toContain('protobuf_decode_FooResponsePb');
|
||||
const allOverride = result.insertions.map(i => i.code).join('');
|
||||
expect(allOverride).toContain('FooTransformer.enc = function');
|
||||
expect(allOverride).toContain('FooTransformer.dec = function');
|
||||
expect(allOverride).toContain('protobuf_encode_FooRequestPb');
|
||||
expect(allOverride).toContain('protobuf_decode_FooResponsePb');
|
||||
});
|
||||
|
||||
it('does not generate overrides on the abstract base file itself', () => {
|
||||
@@ -155,7 +164,7 @@ describe('cross-file inheritance', () => {
|
||||
const result = runSubclassWrapperPipeline(baseFile);
|
||||
// No subclasses defined in the base file → no overrides emitted there.
|
||||
expect(result.resolvedWrappers).toHaveLength(0);
|
||||
expect(result.overrideCode).toBe('');
|
||||
expect(result.insertions).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -175,8 +184,8 @@ describe('plugin transform integration', () => {
|
||||
|
||||
// Concrete codecs got generated for the types extracted from
|
||||
// serialize/deserialize annotations.
|
||||
expect(out).toContain('protobuf_encode_DemoRequestPb');
|
||||
expect(out).toContain('protobuf_decode_DemoResponsePb');
|
||||
expect(out).toContain('protobuf_encode_rsq_pb');
|
||||
expect(out).toContain('protobuf_decode_rps_pb');
|
||||
|
||||
// Per-subclass overrides replace the inherited abstract bodies.
|
||||
expect(out).toContain('DemoTransformer.encode = function');
|
||||
@@ -207,20 +216,29 @@ describe('plugin transform integration', () => {
|
||||
.replace(/^export\s+/gm, '');
|
||||
}
|
||||
|
||||
it('end-to-end: override actually invokes the concrete codec at runtime', () => {
|
||||
it('end-to-end: DemoTransformer.encode(undefined, { param: 42 }) produces the expected wire bytes', () => {
|
||||
const stripped = toPlainJs(runPluginOnFixture());
|
||||
|
||||
// Silence the `console.log` that the fixture's deserialize() performs;
|
||||
// we only verify the encode path in this test, but the fixture's
|
||||
// top-level call exercises encode, not decode, so the stub is just a
|
||||
// defensive measure against future fixture edits.
|
||||
const harness = `
|
||||
const console = { log: () => {} };
|
||||
${stripped}
|
||||
const bytes = DemoTransformer.encode(undefined, { param: 42 });
|
||||
const decoded = protobuf_decode_DemoRequestPb(bytes);
|
||||
globalThis.__r = { bytesLength: bytes.length, decoded };
|
||||
const decoded = protobuf_decode_rsq_pb(bytes);
|
||||
globalThis.__r = { bytes: Array.from(bytes), decoded };
|
||||
`;
|
||||
new Function(harness)();
|
||||
const r = (globalThis as unknown as { __r: { bytesLength: number; decoded: { param: number; id: number } } }).__r;
|
||||
const r = (globalThis as unknown as { __r: { bytes: number[]; decoded: { param: number; id: number } } }).__r;
|
||||
delete (globalThis as unknown as { __r?: unknown }).__r;
|
||||
|
||||
expect(r.bytesLength).toBeGreaterThan(0);
|
||||
// serialize({ param: 42 }) → { param: 42, id: 123 }
|
||||
// rsq_pb declares `param: pb<3, int_32>` then `id: pb<1, int_32>`; the
|
||||
// generator emits fields in declaration order:
|
||||
// field 3, varint, value 42 → tag 0x18, payload 0x2A
|
||||
// field 1, varint, value 123 → tag 0x08, payload 0x7B
|
||||
expect(r.bytes).toEqual([0x18, 0x2a, 0x08, 0x7b]);
|
||||
expect(r.decoded).toEqual({ param: 42, id: 123 });
|
||||
});
|
||||
|
||||
@@ -228,10 +246,11 @@ describe('plugin transform integration', () => {
|
||||
const stripped = toPlainJs(runPluginOnFixture());
|
||||
|
||||
const harness = `
|
||||
const console = { log: () => {} };
|
||||
${stripped}
|
||||
// Build a response payload using the concrete encoder, then feed it
|
||||
// through the subclass's generated decode override.
|
||||
const responseBytes = protobuf_encode_DemoResponsePb({ result: 7, id: 99 });
|
||||
const responseBytes = protobuf_encode_rps_pb({ result: 7, id: 99 });
|
||||
globalThis.__r = DemoTransformer.decode(undefined, responseBytes);
|
||||
`;
|
||||
new Function(harness)();
|
||||
|
||||
Reference in new issue
Block a user