feat(proton): add @snowluma/proton — compile-time protobuf DSL
Vendors SnowLuma/protobuf-dsl into the monorepo as @snowluma/proton, with
edge-case fixes applied on top of the upstream source. Reference copy of
the unmodified upstream is kept under dev/protobuf-dsl/.
Edge cases fixed (each with a regression test):
- Aliased pb / pb_repeated marker imports (`import { pb as P }`)
— collector now resolves the marker name through the import resolver
- Concrete interface with a generic-instantiated message field
(`wrapped: pb<5, Wrapper<uint_32>>`) — field typeName now resolves
to the mangled form, and the inner instantiation is queued for
monomorphization
- Generic template with a generic-instantiated field
(`interface Outer<U> { x: pb<5, Wrapper<U>> }`) — the inner
instantiation is now re-substituted and re-monomorphized at outer
instantiation time
- Wrapper-binding synthetic SourceFile was empty-text — getText()
returned garbage, breaking mangled name computation downstream
- Cross-file forwarded wrappers (chain → imported base) were not
detected — parseFileForDefinitions now resolves imports recursively
(value imports only, with cycle protection)
- matchForwardedKnownWrapper did not propagate typePattern — chain
treated <X> as the encoded type instead of Wrapper<X>
- Synthetic-SF WeakMap was private to analyzer.ts — replacer could
not see it. Moved to utils.ts so typeNodeToMangledName picks it up
automatically.
Defensive guard: any field whose typeName resolves to neither a primitive
nor a known message now throws at analyze() time, instead of silently
leaking the WireType.Varint placeholder into codegen.
95/95 tests pass; tsc --noEmit clean.
This commit is contained in:
62 files changed
+4714
No files matched your search
@@ -0,0 +1,145 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { WireType } from '../../src/ast/types';
|
||||
import { loadFixture } from '../helpers';
|
||||
|
||||
describe('AST analyzer', () => {
|
||||
it('collects TestProtobuf with correct fields', () => {
|
||||
const registry = analyzeSource(loadFixture('real.ts'), 'real.ts');
|
||||
const msg = registry.get('TestProtobuf')!;
|
||||
expect(msg).toBeDefined();
|
||||
expect(msg.fields).toHaveLength(1);
|
||||
expect(msg.fields[0]).toMatchObject({ name: 'name', fieldNumber: 1, typeName: 'uint_32', isMessage: false });
|
||||
});
|
||||
|
||||
it('collects nested message field', () => {
|
||||
const registry = analyzeSource(loadFixture('real.ts'), 'real.ts');
|
||||
const msg = registry.get('TestProtobufOutput')!;
|
||||
expect(msg.fields[0]).toMatchObject({ name: 'name', fieldNumber: 1, typeName: 'TestProtobuf', isMessage: true });
|
||||
});
|
||||
|
||||
it('topological order: dependencies first', () => {
|
||||
const keys = [...analyzeSource(loadFixture('real.ts'), 'real.ts').keys()];
|
||||
expect(keys.indexOf('TestProtobuf')).toBeLessThan(keys.indexOf('TestProtobufOutput'));
|
||||
});
|
||||
|
||||
it('skips generic interfaces (no call sites)', () => {
|
||||
expect(analyzeSource(loadFixture('generic-template.ts'), 'g.ts').size).toBe(0);
|
||||
});
|
||||
|
||||
it('returns empty for non-pb interfaces', () => {
|
||||
expect(analyzeSource(loadFixture('no-pb.ts'), 'no.ts').size).toBe(0);
|
||||
});
|
||||
|
||||
it('handles multiple fields', () => {
|
||||
const msg = analyzeSource(loadFixture('multi-field.ts'), 't.ts').get('UserProfile')!;
|
||||
expect(msg.fields).toHaveLength(3);
|
||||
expect(msg.fields[0]).toMatchObject({ name: 'id', fieldNumber: 1, typeName: 'uint_32' });
|
||||
expect(msg.fields[1]).toMatchObject({ name: 'username', fieldNumber: 2, typeName: 'string' });
|
||||
expect(msg.fields[2]).toMatchObject({ name: 'active', fieldNumber: 3, typeName: 'bool' });
|
||||
});
|
||||
|
||||
it('collects repeated fields', () => {
|
||||
const msg = analyzeSource(loadFixture('repeated.ts'), 't.ts').get('RepeatedMsg')!;
|
||||
expect(msg.fields).toHaveLength(2);
|
||||
expect(msg.fields[0]).toMatchObject({ name: 'ids', fieldNumber: 1, typeName: 'uint_32', isRepeated: true });
|
||||
expect(msg.fields[1]).toMatchObject({ name: 'names', fieldNumber: 2, typeName: 'string', isRepeated: true });
|
||||
});
|
||||
|
||||
it('monomorphizes generics from call sites', () => {
|
||||
const registry = analyzeSource(loadFixture('generic-usage.ts'), 'g.ts');
|
||||
expect(registry.has('TestProtobufAny__string')).toBe(true);
|
||||
expect(registry.has('TestProtobufAny__TestProtobufAny__string')).toBe(true);
|
||||
});
|
||||
|
||||
// ── Edge cases (originally silently dropped / wrong wire type) ──────
|
||||
|
||||
it('edge: monomorphizes a generic-instantiated field on a concrete interface', () => {
|
||||
// Regression: a concrete interface with `pb<N, Wrapper<T>>` previously
|
||||
// resolved the field's typeName to the bare identifier `"Wrapper"` and
|
||||
// never enqueued `Wrapper<T>` for monomorphization. The field was left
|
||||
// with the placeholder WireType.Varint, corrupting the wire format.
|
||||
const registry = analyzeSource(loadFixture('nested-generic-field.ts'), 'n.ts');
|
||||
|
||||
expect(registry.has('Wrapper__uint_32')).toBe(true);
|
||||
|
||||
const container = registry.get('Container')!;
|
||||
expect(container).toBeDefined();
|
||||
expect(container.fields[0]).toMatchObject({
|
||||
name: 'wrapped',
|
||||
fieldNumber: 5,
|
||||
typeName: 'Wrapper__uint_32',
|
||||
isMessage: true,
|
||||
wireType: WireType.LengthDelim,
|
||||
});
|
||||
});
|
||||
|
||||
it('edge: monomorphizes a generic-instantiated field on a generic template', () => {
|
||||
// Regression: a generic template field typed as `pb<N, Wrapper<U>>` —
|
||||
// where `U` is the outer template's type param — was stored with the
|
||||
// mangled-but-unsubstituted name `'Wrapper__U'` and never re-instantiated
|
||||
// with the concrete substitution at monomorphization time. The field
|
||||
// ended up referencing `Wrapper__U` instead of `Wrapper__uint_32` and the
|
||||
// inner mangled instantiation was missing from the registry.
|
||||
const registry = analyzeSource(loadFixture('generic-with-generic-field.ts'), 'g.ts');
|
||||
|
||||
expect(registry.has('Outer__uint_32')).toBe(true);
|
||||
expect(registry.has('Wrapper__uint_32')).toBe(true);
|
||||
|
||||
const outer = registry.get('Outer__uint_32')!;
|
||||
expect(outer.fields[0]).toMatchObject({
|
||||
name: 'wrapped',
|
||||
fieldNumber: 5,
|
||||
typeName: 'Wrapper__uint_32',
|
||||
isMessage: true,
|
||||
wireType: WireType.LengthDelim,
|
||||
});
|
||||
|
||||
const wrapper = registry.get('Wrapper__uint_32')!;
|
||||
expect(wrapper.fields[0]).toMatchObject({
|
||||
name: 'value',
|
||||
fieldNumber: 1,
|
||||
typeName: 'uint_32',
|
||||
isMessage: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('edge: throws when a field references an unresolved type name', () => {
|
||||
// Defensive guard: anything that escapes the analyzer's type tracking
|
||||
// (unions, intersections, mapped/conditional types, `Partial<T>`, etc.)
|
||||
// used to silently leak `WireType.Varint` into the codegen. Now it has
|
||||
// to fail loudly so future edge cases surface immediately.
|
||||
const source = `
|
||||
interface BadMsg {
|
||||
weird: pb<1, MissingType>;
|
||||
}
|
||||
const buf = protobuf_encode<BadMsg>({} as any);
|
||||
`;
|
||||
expect(() => analyzeSource(source, 'b.ts')).toThrow(/MissingType/);
|
||||
});
|
||||
|
||||
it('edge: recognises aliased pb / pb_repeated marker imports', () => {
|
||||
// Regression: `parsePbTypeRef` compared the literal type-ref identifier
|
||||
// text against the constants `'pb'` / `'pb_repeated'`. With
|
||||
// `import { pb as P }` the text became `'P'`, so every field on the
|
||||
// interface was silently dropped and `Aliased` never made it into the
|
||||
// registry.
|
||||
const registry = analyzeSource(loadFixture('aliased-pb-marker.ts'), 'a.ts');
|
||||
|
||||
const aliased = registry.get('Aliased')!;
|
||||
expect(aliased).toBeDefined();
|
||||
expect(aliased.fields).toHaveLength(2);
|
||||
expect(aliased.fields[0]).toMatchObject({
|
||||
name: 'id',
|
||||
fieldNumber: 1,
|
||||
typeName: 'uint_32',
|
||||
isRepeated: false,
|
||||
});
|
||||
expect(aliased.fields[1]).toMatchObject({
|
||||
name: 'tags',
|
||||
fieldNumber: 2,
|
||||
typeName: 'string',
|
||||
isRepeated: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { readFileSync } from 'fs';
|
||||
import { resolve, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer';
|
||||
import { generateCode } from '../../src/codegen/generator';
|
||||
import { applyReplacements } from '../../src/transform/replacer';
|
||||
import { resolveImports, type ParsedFileEntry } from '../../src/ast/import-resolver';
|
||||
import { execAndGet } from '../helpers';
|
||||
|
||||
const crossDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures', 'cross-file');
|
||||
|
||||
function loadCross(name: string): { code: string; path: string } {
|
||||
const path = resolve(crossDir, name);
|
||||
return { code: readFileSync(path, 'utf-8'), path };
|
||||
}
|
||||
|
||||
describe('cross-file import resolution', () => {
|
||||
// ── Scenario A: imported type in encode/decode call site ──────────
|
||||
|
||||
it('resolves imported type for protobuf_encode/decode call site', () => {
|
||||
const { code, path } = loadCross('consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.concrete.some(m => m.name === 'UserMsg')).toBe(true);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
expect(registry.has('UserMsg')).toBe(true);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_UserMsg');
|
||||
expect(transformedCode).toContain('protobuf_decode_UserMsg');
|
||||
});
|
||||
|
||||
it('Scenario A round-trip', () => {
|
||||
const { code, path } = loadCross('consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_UserMsg({ id: 42, name: 'alice' });
|
||||
globalThis.__r = protobuf_decode_UserMsg(enc);
|
||||
`, '__r');
|
||||
expect(result.id).toBe(42);
|
||||
expect(result.name).toBe('alice');
|
||||
});
|
||||
|
||||
// ── Scenario B: imported type as pb<> field ──────────────────────
|
||||
|
||||
it('resolves imported nested message type', () => {
|
||||
const { code, path } = loadCross('outer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.concrete.some(m => m.name === 'Inner')).toBe(true);
|
||||
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
expect(registry.has('Inner')).toBe(true);
|
||||
expect(registry.has('Outer')).toBe(true);
|
||||
|
||||
const outer = registry.get('Outer')!;
|
||||
const innerField = outer.fields.find(f => f.name === 'inner')!;
|
||||
expect(innerField.isMessage).toBe(true);
|
||||
});
|
||||
|
||||
it('Scenario B round-trip', () => {
|
||||
const { code, path } = loadCross('outer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Outer({ inner: { value: 42 } });
|
||||
globalThis.__r = protobuf_decode_Outer(enc);
|
||||
`, '__r');
|
||||
expect(result.inner.value).toBe(42);
|
||||
});
|
||||
|
||||
// ── Generic template import ──────────────────────────────────────
|
||||
|
||||
it('resolves imported generic template', () => {
|
||||
const { code, path } = loadCross('generic-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.templates.has('Wrapper')).toBe(true);
|
||||
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
expect(registry.has('Wrapper__string')).toBe(true);
|
||||
});
|
||||
|
||||
it('generic import round-trip', () => {
|
||||
const { code, path } = loadCross('generic-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Wrapper__string({ value: 'hello' });
|
||||
globalThis.__r = protobuf_decode_Wrapper__string(enc);
|
||||
`, '__r');
|
||||
expect(result.value).toBe('hello');
|
||||
});
|
||||
|
||||
it('resolves generic type passed through imported wrapper functions', () => {
|
||||
const { code, path } = loadCross('wrapper-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.templates.has('Wrapper')).toBe(true);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(2);
|
||||
expect(used.callSites[0].fnName).toBe('protobuf_encode');
|
||||
expect(used.callSites[1].fnName).toBe('protobuf_decode');
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
});
|
||||
|
||||
it('handles wrapper aliases, arrows, nested generics, and non-first generic forwarding', () => {
|
||||
const { code, path } = loadCross('wrapper-edge-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(5);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__Wrapper__string(');
|
||||
expect(transformedCode).toContain('passthroughOnly<Wrapper<string>>');
|
||||
});
|
||||
|
||||
it('handles local wrapper functions in the entry file', () => {
|
||||
const { code, path } = loadCross('local-wrapper-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(2);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
});
|
||||
|
||||
it('handles complex wrapper objects, branches, nested helpers, and chains', () => {
|
||||
const { code, path } = loadCross('wrapper-complex-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(7);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
|
||||
expect(transformedCode).not.toContain('encodeChained<Wrapper<string>>');
|
||||
});
|
||||
|
||||
it('handles wrapper protobuf type derived from another generic type', () => {
|
||||
const { code, path } = loadCross('wrapper-type-source-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(5);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
|
||||
expect(transformedCode).not.toContain('encodeBoxed<string>');
|
||||
});
|
||||
|
||||
// ── Transitive imports ───────────────────────────────────────────
|
||||
|
||||
it('resolves transitive imports (A → B → C)', () => {
|
||||
const { code, path } = loadCross('top.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.concrete.some(m => m.name === 'Mid')).toBe(true);
|
||||
expect(imported.concrete.some(m => m.name === 'Deep')).toBe(true);
|
||||
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
expect(registry.has('Top')).toBe(true);
|
||||
expect(registry.has('Mid')).toBe(true);
|
||||
expect(registry.has('Deep')).toBe(true);
|
||||
});
|
||||
|
||||
it('transitive import round-trip', () => {
|
||||
const { code, path } = loadCross('top.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Top({ nested: { inner: { val: 99 } } });
|
||||
globalThis.__r = protobuf_decode_Top(enc);
|
||||
`, '__r');
|
||||
expect(result.nested.inner.val).toBe(99);
|
||||
});
|
||||
|
||||
// ── Cache behavior ───────────────────────────────────────────────
|
||||
|
||||
it('uses cache on repeated resolves', () => {
|
||||
const { code, path } = loadCross('consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
|
||||
resolveImports(code, path, cache);
|
||||
expect(cache.size).toBeGreaterThan(0);
|
||||
|
||||
const cached = new Map(cache);
|
||||
resolveImports(code, path, cache);
|
||||
|
||||
// Same entries, not re-created
|
||||
for (const [key, val] of cache) {
|
||||
expect(val).toBe(cached.get(key));
|
||||
}
|
||||
});
|
||||
|
||||
// ── Graceful fallback ────────────────────────────────────────────
|
||||
|
||||
it('handles missing import file gracefully', () => {
|
||||
const code = `import type { Ghost } from './nonexistent';\nconst x = 1;`;
|
||||
const fakePath = resolve(crossDir, 'fake.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
|
||||
const imported = resolveImports(code, fakePath, cache);
|
||||
expect(imported.concrete).toEqual([]);
|
||||
expect(imported.templates.size).toBe(0);
|
||||
});
|
||||
|
||||
it('only resolves imports reachable from protobuf call roots', () => {
|
||||
const code = `
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { UserMsg } from './types';
|
||||
import type { Inner } from './inner';
|
||||
|
||||
const buf = protobuf_encode<UserMsg>({ id: 42, name: 'alice' });
|
||||
`;
|
||||
const fakePath = resolve(crossDir, 'on-demand.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
|
||||
const imported = resolveImports(code, fakePath, cache);
|
||||
|
||||
expect(imported.concrete.map(m => m.name)).toEqual(['UserMsg']);
|
||||
expect(cache.has(resolve(crossDir, 'types.ts'))).toBe(true);
|
||||
expect(cache.has(resolve(crossDir, 'inner.ts'))).toBe(false);
|
||||
});
|
||||
|
||||
// ── Value import (non-type import) ───────────────────────────────
|
||||
|
||||
it('resolves value import { SimpleMessage } (not import type)', () => {
|
||||
const { code, path } = loadCross('value-import-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.concrete.some(m => m.name === 'SimpleMessage')).toBe(true);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
expect(registry.has('SimpleMessage')).toBe(true);
|
||||
expect(callSites.length).toBe(2);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_SimpleMessage(');
|
||||
expect(transformedCode).toContain('protobuf_decode_SimpleMessage(');
|
||||
});
|
||||
|
||||
it('value import round-trip', () => {
|
||||
const { code, path } = loadCross('value-import-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_SimpleMessage({ id: 42 });
|
||||
globalThis.__r = protobuf_decode_SimpleMessage(enc);
|
||||
`, '__r');
|
||||
expect(result.id).toBe(42);
|
||||
});
|
||||
|
||||
it('canonicalizes imported type aliases to the original message name', () => {
|
||||
const { code, path } = loadCross('aliased-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('UserMsg')).toBe(true);
|
||||
expect(used.registry.has('AliasMsg')).toBe(false);
|
||||
expect(used.callSites).toHaveLength(2);
|
||||
expect(used.callSites[0].typeName).toBe('UserMsg');
|
||||
expect(used.callSites[1].typeName).toBe('UserMsg');
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_UserMsg(');
|
||||
expect(transformedCode).toContain('protobuf_decode_UserMsg(');
|
||||
expect(transformedCode).not.toContain('protobuf_encode_AliasMsg(');
|
||||
expect(transformedCode).not.toContain('protobuf_decode_AliasMsg(');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { generateCode } from '../../src/codegen/generator';
|
||||
import { loadFixture, execAndGet } from '../helpers';
|
||||
|
||||
/** Analyze fixture → generate → eval → return encode/decode pair */
|
||||
function makeRoundTrip(fixtureName: string, msgName: string) {
|
||||
const gen = generateCode(analyzeSource(loadFixture(fixtureName), fixtureName));
|
||||
new Function(gen + `\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`)();
|
||||
const enc = (globalThis as any).__enc as (obj: any) => Uint8Array;
|
||||
const dec = (globalThis as any).__dec as (data: Uint8Array) => any;
|
||||
delete (globalThis as any).__enc;
|
||||
delete (globalThis as any).__dec;
|
||||
return { enc, dec };
|
||||
}
|
||||
|
||||
function makeRoundTripFromSchema(schema: string, msgName: string) {
|
||||
const gen = generateCode(analyzeSource(schema, `${msgName}.ts`));
|
||||
new Function(gen + `\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`)();
|
||||
const enc = (globalThis as any).__enc as (obj: any) => Uint8Array;
|
||||
const dec = (globalThis as any).__dec as (data: Uint8Array) => any;
|
||||
delete (globalThis as any).__enc;
|
||||
delete (globalThis as any).__dec;
|
||||
return { enc, dec };
|
||||
}
|
||||
|
||||
describe('code generator', () => {
|
||||
it('generates encode/decode for simple uint_32', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('simple.ts'), 't.ts'));
|
||||
expect(gen).toContain('function protobuf_encode_SimpleMsg(obj)');
|
||||
expect(gen).toContain('function protobuf_decode_SimpleMsg(data');
|
||||
// Tag for field 1, varint should be pre-computed as 0x08
|
||||
expect(gen).toContain('buf[offset++] = 8;');
|
||||
});
|
||||
|
||||
it('generates nested message code', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('nested.ts'), 't.ts'));
|
||||
expect(gen).toContain('protobuf_encode_Inner(');
|
||||
expect(gen).toContain('protobuf_decode_Inner(data, offset, offset + _len)');
|
||||
});
|
||||
|
||||
it('round-trip uint_32', () => {
|
||||
const { enc, dec } = makeRoundTrip('simple.ts', 'SimpleMsg');
|
||||
expect(dec(enc({ value: 42 })).value).toBe(42);
|
||||
});
|
||||
|
||||
it('round-trip nested message', () => {
|
||||
const { enc, dec } = makeRoundTrip('nested.ts', 'Outer');
|
||||
expect(dec(enc({ inner: { value: 999 } })).inner.value).toBe(999);
|
||||
});
|
||||
|
||||
it('round-trip string', () => {
|
||||
const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg');
|
||||
expect(dec(enc({ text: 'hello world' })).text).toBe('hello world');
|
||||
});
|
||||
|
||||
it('round-trip unicode string', () => {
|
||||
const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg');
|
||||
expect(dec(enc({ text: '你好,protobuf🚀' })).text).toBe('你好,protobuf🚀');
|
||||
});
|
||||
|
||||
it('round-trip bool', () => {
|
||||
const { enc, dec } = makeRoundTrip('bool-msg.ts', 'BoolMsg');
|
||||
expect(dec(enc({ active: true })).active).toBe(true);
|
||||
const empty = enc({ active: false });
|
||||
expect(empty.length).toBe(0);
|
||||
expect(dec(empty).active).toBe(false);
|
||||
});
|
||||
|
||||
it('proto3 default encoding (0 → empty)', () => {
|
||||
const { enc } = makeRoundTrip('simple.ts', 'SimpleMsg');
|
||||
expect(enc({ value: 0 }).length).toBe(0);
|
||||
});
|
||||
|
||||
it('round-trip repeated uint_32', () => {
|
||||
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
|
||||
const result = dec(enc({ ids: [10, 20, 30], names: [] }));
|
||||
expect(result.ids).toEqual([10, 20, 30]);
|
||||
expect(result.names).toEqual([]);
|
||||
});
|
||||
|
||||
it('round-trip repeated string', () => {
|
||||
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
|
||||
const result = dec(enc({ ids: [], names: ['hello', 'world'] }));
|
||||
expect(result.ids).toEqual([]);
|
||||
expect(result.names).toEqual(['hello', 'world']);
|
||||
});
|
||||
|
||||
it('repeated empty arrays round-trip', () => {
|
||||
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
|
||||
const result = dec(enc({ ids: [], names: [] }));
|
||||
expect(result.ids).toEqual([]);
|
||||
expect(result.names).toEqual([]);
|
||||
});
|
||||
|
||||
it('round-trip bigint-backed 64-bit integers', () => {
|
||||
const schema = `
|
||||
interface BigIntMsg {
|
||||
unsigned: pb<1, uint_64>;
|
||||
signed: pb<2, int_64>;
|
||||
zigzag: pb<3, sint_64>;
|
||||
fixed: pb<4, fixed_64>;
|
||||
sfixed: pb<5, sfixed_64>;
|
||||
ids: pb_repeated<6, uint_64>;
|
||||
}`;
|
||||
const { enc, dec } = makeRoundTripFromSchema(schema, 'BigIntMsg');
|
||||
const input = {
|
||||
unsigned: 18446744073709551615n,
|
||||
signed: -1n,
|
||||
zigzag: -1234567890123456789n,
|
||||
fixed: 0x0102030405060708n,
|
||||
sfixed: -0x0102030405060708n,
|
||||
ids: [1n, 2n, 9007199254740993n],
|
||||
};
|
||||
expect(dec(enc(input))).toEqual(input);
|
||||
});
|
||||
|
||||
it('round-trip sint_32 with negative values', () => {
|
||||
const schema = `
|
||||
interface Sint32Msg {
|
||||
value: pb<1, sint_32>;
|
||||
values: pb_repeated<2, sint_32>;
|
||||
}`;
|
||||
const { enc, dec } = makeRoundTripFromSchema(schema, 'Sint32Msg');
|
||||
const input = { value: -789, values: [-1, 0, 1, -789, 2147483647, -2147483648] };
|
||||
expect(dec(enc(input))).toEqual(input);
|
||||
});
|
||||
|
||||
it('round-trip double as ieee754 number', () => {
|
||||
const schema = `
|
||||
interface DoubleMsg {
|
||||
value: pb<1, double>;
|
||||
values: pb_repeated<2, double>;
|
||||
}`;
|
||||
const { enc, dec } = makeRoundTripFromSchema(schema, 'DoubleMsg');
|
||||
const result = dec(enc({ value: Math.PI, values: [Math.E, -0.5] }));
|
||||
expect(result.value).toBeCloseTo(Math.PI);
|
||||
expect(result.values[0]).toBeCloseTo(Math.E);
|
||||
expect(result.values[1]).toBeCloseTo(-0.5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,307 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import protobufVitePlugin from '../../src/index';
|
||||
import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer';
|
||||
import { generateCode } from '../../src/codegen/generator';
|
||||
import { replaceCallSites } from '../../src/transform/replacer';
|
||||
import { loadFixture, execAndGet } from '../helpers';
|
||||
|
||||
describe('plugin integration', () => {
|
||||
it('full transform pipeline', () => {
|
||||
const code = loadFixture('real.ts');
|
||||
const registry = analyzeSource(code, 'real.ts');
|
||||
expect(registry.size).toBe(2);
|
||||
expect([...registry.keys()]).toEqual(['TestProtobuf', 'TestProtobufOutput']);
|
||||
|
||||
const gen = generateCode(registry);
|
||||
expect(gen).toContain('protobuf_encode_TestProtobuf');
|
||||
expect(gen).toContain('protobuf_decode_TestProtobufOutput');
|
||||
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_TestProtobuf({ name: 123 })');
|
||||
expect(transformedCode).toContain('protobuf_decode_TestProtobufOutput(data)');
|
||||
});
|
||||
|
||||
it('end-to-end round-trip', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const wr = protobuf_encode_TestProtobufOutput({ name: { name: 123 } });
|
||||
globalThis.__r = protobuf_decode_TestProtobufOutput(wr);
|
||||
`, '__r');
|
||||
expect(result.name.name).toBe(123);
|
||||
});
|
||||
|
||||
it('wire format: TestProtobuf { name: 123 }', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts'));
|
||||
const enc = execAndGet<Uint8Array>(gen + `\n
|
||||
globalThis.__r = protobuf_encode_TestProtobuf({ name: 123 });
|
||||
`, '__r');
|
||||
expect(enc.length).toBe(2);
|
||||
expect(enc[0]).toBe(0x08);
|
||||
expect(enc[1]).toBe(123);
|
||||
});
|
||||
|
||||
it('wire format: nested message', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts'));
|
||||
const enc = execAndGet<Uint8Array>(gen + `\n
|
||||
globalThis.__r = protobuf_encode_TestProtobufOutput({ name: { name: 456 } });
|
||||
`, '__r');
|
||||
expect(enc[0]).toBe(0x0a);
|
||||
expect(enc[1]).toBe(3);
|
||||
expect(enc[2]).toBe(0x08);
|
||||
expect(enc[3]).toBe(0xc8);
|
||||
expect(enc[4]).toBe(0x03);
|
||||
});
|
||||
|
||||
it('multi-field round-trip', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('multi-field.ts'), 't.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_UserProfile({ id: 42, username: "alice", active: true });
|
||||
globalThis.__r = protobuf_decode_UserProfile(enc);
|
||||
`, '__r');
|
||||
expect(result.id).toBe(42);
|
||||
expect(result.username).toBe('alice');
|
||||
expect(result.active).toBe(true);
|
||||
});
|
||||
|
||||
// ── generic monomorphization ───────────────────────────────────────
|
||||
|
||||
it('generic monomorphization registry', () => {
|
||||
const registry = analyzeSource(loadFixture('generic-usage.ts'), 'g.ts');
|
||||
expect(registry.has('TestProtobufAny__string')).toBe(true);
|
||||
expect(registry.has('TestProtobufAny__TestProtobufAny__string')).toBe(true);
|
||||
});
|
||||
|
||||
it('generic round-trip', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('generic-usage.ts'), 'g.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_TestProtobufAny__TestProtobufAny__string({ name: { name: "hello" } });
|
||||
globalThis.__r = protobuf_decode_TestProtobufAny__TestProtobufAny__string(enc);
|
||||
`, '__r');
|
||||
expect(result.name.name).toBe('hello');
|
||||
});
|
||||
|
||||
// ── repeated fields ────────────────────────────────────────────────
|
||||
|
||||
it('repeated fields round-trip', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_RepeatedMsg({ ids: [10, 20, 30], names: ["foo", "bar"] });
|
||||
globalThis.__r = protobuf_decode_RepeatedMsg(enc);
|
||||
`, '__r');
|
||||
expect(result.ids).toEqual([10, 20, 30]);
|
||||
expect(result.names).toEqual(['foo', 'bar']);
|
||||
});
|
||||
|
||||
it('repeated empty arrays', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_RepeatedMsg({ ids: [], names: [] });
|
||||
globalThis.__r = protobuf_decode_RepeatedMsg(enc);
|
||||
`, '__r');
|
||||
expect(result.ids).toEqual([]);
|
||||
expect(result.names).toEqual([]);
|
||||
});
|
||||
|
||||
// ── import-based usage ──────────────────────────────────────────────
|
||||
|
||||
it('handles code with import { protobuf_encode } from "@snowluma/proton"', () => {
|
||||
const code = `
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
|
||||
const buf = protobuf_encode<Msg>({ id: 1 });
|
||||
const decoded = protobuf_decode<Msg>(buf);
|
||||
`;
|
||||
const registry = analyzeSource(code, 'import-test.ts');
|
||||
expect(registry.has('Msg')).toBe(true);
|
||||
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Msg(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Msg(');
|
||||
// import line preserved
|
||||
expect(transformedCode).toContain("from '@snowluma/proton'");
|
||||
});
|
||||
|
||||
it('import-based round-trip', () => {
|
||||
const code = `
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; name: pb<2, string>; }
|
||||
|
||||
const buf = protobuf_encode<Msg>({ id: 42, name: 'test' });
|
||||
const decoded = protobuf_decode<Msg>(buf);
|
||||
`;
|
||||
const registry = analyzeSource(code, 'import-test.ts');
|
||||
const gen = generateCode(registry);
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Msg({ id: 42, name: 'test' });
|
||||
globalThis.__r = protobuf_decode_Msg(enc);
|
||||
`, '__r');
|
||||
expect(result.id).toBe(42);
|
||||
expect(result.name).toBe('test');
|
||||
});
|
||||
|
||||
it('runtime fallback throws error', async () => {
|
||||
const { protobuf_encode, protobuf_decode } = await import('../../src/runtime');
|
||||
expect(() => protobuf_encode({})).toThrow('not transformed');
|
||||
expect(() => protobuf_decode(new Uint8Array())).toThrow('not transformed');
|
||||
});
|
||||
|
||||
// ── import rename alias ─────────────────────────────────────────────
|
||||
|
||||
it('handles import { protobuf_encode as encode }', () => {
|
||||
const code = `
|
||||
import { protobuf_encode as encode, protobuf_decode as decode } from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
|
||||
const buf = encode<Msg>({ id: 1 });
|
||||
const decoded = decode<Msg>(buf);
|
||||
`;
|
||||
const registry = analyzeSource(code, 'alias-test.ts');
|
||||
expect(registry.has('Msg')).toBe(true);
|
||||
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Msg(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Msg(');
|
||||
// alias calls replaced, import preserved
|
||||
expect(transformedCode).not.toContain('encode<Msg>');
|
||||
expect(transformedCode).not.toContain('decode<Msg>');
|
||||
});
|
||||
|
||||
it('rename alias round-trip', () => {
|
||||
const code = `
|
||||
import { protobuf_encode as enc } from '@snowluma/proton';
|
||||
|
||||
interface Item { val: pb<1, uint_32>; name: pb<2, string>; }
|
||||
|
||||
const buf = enc<Item>({ val: 99, name: 'x' });
|
||||
`;
|
||||
const registry = analyzeSource(code, 'alias-rt.ts');
|
||||
const gen = generateCode(registry);
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Item({ val: 99, name: 'x' });
|
||||
globalThis.__r = protobuf_decode_Item(enc);
|
||||
`, '__r');
|
||||
expect(result.val).toBe(99);
|
||||
expect(result.name).toBe('x');
|
||||
});
|
||||
|
||||
it('collects call roots first and generates only used dependency closure', () => {
|
||||
const code = `
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
|
||||
interface Inner { id: pb<1, uint_32>; }
|
||||
interface UsedMsg { inner: pb<1, Inner>; }
|
||||
interface UnusedMsg { value: pb<1, string>; }
|
||||
|
||||
const buf = protobuf_encode<UsedMsg>({ inner: { id: 1 } });
|
||||
`;
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, 'used-only.ts');
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('UsedMsg')).toBe(true);
|
||||
expect(used.registry.has('Inner')).toBe(true);
|
||||
expect(used.registry.has('UnusedMsg')).toBe(false);
|
||||
|
||||
const gen = generateCode(used.registry);
|
||||
expect(gen).toContain('protobuf_encode_UsedMsg');
|
||||
expect(gen).toContain('protobuf_encode_Inner');
|
||||
expect(gen).not.toContain('protobuf_encode_UnusedMsg');
|
||||
});
|
||||
|
||||
it('emits runtime map asset when runtimeMap is enabled', () => {
|
||||
const code = `
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
const buf = protobuf_encode<Msg>({ id: 1 });
|
||||
`;
|
||||
|
||||
const plugin = protobufVitePlugin({
|
||||
runtimeMap: {
|
||||
enabled: true,
|
||||
fileName: 'pb.runtime-map.json',
|
||||
},
|
||||
});
|
||||
|
||||
const transformHook = plugin.transform!;
|
||||
const transform = typeof transformHook === 'function' ? transformHook : transformHook.handler;
|
||||
const transformResult = transform.call({} as any, code, 'entry.ts');
|
||||
expect(transformResult).toBeTruthy();
|
||||
|
||||
const emitted: any[] = [];
|
||||
const generateHook = plugin.generateBundle!;
|
||||
const generateBundle = typeof generateHook === 'function' ? generateHook : generateHook.handler;
|
||||
const testContext: any = {
|
||||
emitFile(asset: any) {
|
||||
emitted.push(asset);
|
||||
return 'asset-id';
|
||||
},
|
||||
};
|
||||
|
||||
generateBundle.call(
|
||||
testContext,
|
||||
{} as any,
|
||||
{} as any,
|
||||
false,
|
||||
);
|
||||
|
||||
expect(emitted).toHaveLength(1);
|
||||
expect(emitted[0].type).toBe('asset');
|
||||
expect(emitted[0].fileName).toBe('pb.runtime-map.json');
|
||||
|
||||
const payload = JSON.parse(emitted[0].source);
|
||||
expect(payload.version).toBe(1);
|
||||
expect(payload.callSites).toHaveLength(1);
|
||||
expect(payload.callSites[0].fnName).toBe('protobuf_encode');
|
||||
expect(payload.callSites[0].typeName).toBe('Msg');
|
||||
});
|
||||
|
||||
it('emits canonical runtime map entries for imported type aliases', () => {
|
||||
const code = `
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import type { UserMsg as AliasMsg } from './types';
|
||||
|
||||
const buf = protobuf_encode<AliasMsg>({ id: 1, name: 'a' });
|
||||
const decoded = protobuf_decode<AliasMsg>(buf);
|
||||
`;
|
||||
|
||||
const plugin = protobufVitePlugin({
|
||||
runtimeMap: {
|
||||
enabled: true,
|
||||
fileName: 'pb.runtime-map.json',
|
||||
},
|
||||
});
|
||||
|
||||
const transformHook = plugin.transform!;
|
||||
const transform = typeof transformHook === 'function' ? transformHook : transformHook.handler;
|
||||
const transformResult = transform.call({} as any, code, 'test/fixtures/cross-file/aliased-consumer.ts');
|
||||
expect(transformResult).toBeTruthy();
|
||||
|
||||
const emitted: any[] = [];
|
||||
const generateHook = plugin.generateBundle!;
|
||||
const generateBundle = typeof generateHook === 'function' ? generateHook : generateHook.handler;
|
||||
const testContext: any = {
|
||||
emitFile(asset: any) {
|
||||
emitted.push(asset);
|
||||
return 'asset-id';
|
||||
},
|
||||
};
|
||||
|
||||
generateBundle.call(testContext, {} as any, {} as any, false);
|
||||
|
||||
expect(emitted).toHaveLength(1);
|
||||
const payload = JSON.parse(emitted[0].source);
|
||||
expect(payload.messages.some((msg: { name: string }) => msg.name === 'UserMsg')).toBe(true);
|
||||
expect(payload.messages.some((msg: { name: string }) => msg.name === 'AliasMsg')).toBe(false);
|
||||
expect(payload.callSites).toHaveLength(2);
|
||||
expect(payload.callSites[0].typeName).toBe('UserMsg');
|
||||
expect(payload.callSites[1].typeName).toBe('UserMsg');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { replaceCallSites } from '../../src/transform/replacer';
|
||||
import { loadFixture } from '../helpers';
|
||||
|
||||
describe('call-site replacer', () => {
|
||||
it('replaces protobuf_encode<T> with protobuf_encode_T', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst data = protobuf_encode<SimpleMsg>({ value: 1 });\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_SimpleMsg({ value: 1 })');
|
||||
expect(transformedCode).not.toContain('protobuf_encode<SimpleMsg>');
|
||||
});
|
||||
|
||||
it('replaces protobuf_decode<T>', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst result = protobuf_decode<SimpleMsg>(data);\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_decode_SimpleMsg(data)');
|
||||
});
|
||||
|
||||
it('replaces multiple calls', () => {
|
||||
const code = loadFixture('simple.ts') + `
|
||||
const a = protobuf_encode<SimpleMsg>({ value: 1 });
|
||||
const b = protobuf_decode<SimpleMsg>(a);
|
||||
`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode } = replaceCallSites(code, registry);
|
||||
expect(transformedCode).toContain('protobuf_encode_SimpleMsg({ value: 1 })');
|
||||
expect(transformedCode).toContain('protobuf_decode_SimpleMsg(a)');
|
||||
});
|
||||
|
||||
it('preserves await keyword', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst a = await protobuf_encode<SimpleMsg>({ value: 1 });\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode } = replaceCallSites(code, registry);
|
||||
expect(transformedCode).toContain('await protobuf_encode_SimpleMsg({ value: 1 })');
|
||||
});
|
||||
|
||||
it('returns hasReplacements=false when no calls match', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst x = 123;\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
expect(replaceCallSites(code, registry).hasReplacements).toBe(false);
|
||||
});
|
||||
|
||||
it('does not replace unknown type arguments', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst a = protobuf_encode<Unknown>({ v: 1 });\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { hasReplacements, transformedCode } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(false);
|
||||
expect(transformedCode).toContain('protobuf_encode<Unknown>');
|
||||
});
|
||||
|
||||
it('replaces generic call-sites with mangled names', () => {
|
||||
const code = loadFixture('generic-usage.ts');
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_TestProtobufAny__TestProtobufAny__string');
|
||||
expect(transformedCode).toContain('protobuf_decode_TestProtobufAny__TestProtobufAny__string');
|
||||
});
|
||||
|
||||
it('replaces namespace import calls', () => {
|
||||
const code = `
|
||||
import * as pbx from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
|
||||
const a = pbx.protobuf_encode<Msg>({ id: 1 });
|
||||
const b = pbx.protobuf_decode<Msg>(a);
|
||||
`;
|
||||
const registry = analyzeSource(code, 'ns.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('const a = protobuf_encode_Msg({ id: 1 });');
|
||||
expect(transformedCode).toContain('const b = protobuf_decode_Msg(a);');
|
||||
});
|
||||
|
||||
it('does not replace same-name imports from non-runtime modules', () => {
|
||||
const code = `
|
||||
import { protobuf_encode } from './other';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
|
||||
const a = protobuf_encode<Msg>({ id: 1 });
|
||||
`;
|
||||
const registry = analyzeSource(code, 'guard.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(false);
|
||||
expect(transformedCode).toContain('protobuf_encode<Msg>({ id: 1 })');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { createRuntimeMap } from '../../src/runtime-map';
|
||||
import {
|
||||
protobuf_decode,
|
||||
protobuf_disableRuntimeMapFallback,
|
||||
protobuf_enableRuntimeMapFallback,
|
||||
protobuf_encode,
|
||||
} from '../../src/runtime';
|
||||
|
||||
function captureFrameFromThrow(fn: () => unknown, sourceFile: string): { line: number; column: number } {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
const stack = err instanceof Error ? err.stack ?? '' : '';
|
||||
for (const raw of stack.split('\n')) {
|
||||
const line = raw.trim();
|
||||
if (!line.includes(sourceFile)) continue;
|
||||
|
||||
const location = line.endsWith(')') && line.includes('(')
|
||||
? line.slice(line.lastIndexOf('(') + 1, -1)
|
||||
: line.replace(/^at\s+/, '');
|
||||
|
||||
const lastColon = location.lastIndexOf(':');
|
||||
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
|
||||
if (lastColon < 0 || secondLastColon < 0) continue;
|
||||
|
||||
const parsedLine = Number(location.slice(secondLastColon + 1, lastColon));
|
||||
const parsedColumn = Number(location.slice(lastColon + 1));
|
||||
if (Number.isFinite(parsedLine) && Number.isFinite(parsedColumn)) {
|
||||
return { line: parsedLine, column: parsedColumn };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unable to capture stack frame for ${sourceFile}`);
|
||||
}
|
||||
|
||||
function invokeEncode(): Uint8Array {
|
||||
return new Function(
|
||||
'protobuf_encode',
|
||||
`\n//# sourceURL=runtime-map-encode.js\nreturn protobuf_encode({ value: 7 });`,
|
||||
)(protobuf_encode) as Uint8Array;
|
||||
}
|
||||
|
||||
function invokeDecode(data: Uint8Array): any {
|
||||
return new Function(
|
||||
'protobuf_decode',
|
||||
'data',
|
||||
`\n//# sourceURL=runtime-map-decode.js\nreturn protobuf_decode(data);`,
|
||||
)(protobuf_decode, data);
|
||||
}
|
||||
|
||||
describe('runtime map fallback', () => {
|
||||
afterEach(() => {
|
||||
protobuf_disableRuntimeMapFallback();
|
||||
});
|
||||
|
||||
it('dynamically generates encode/decode from runtime map when enabled', () => {
|
||||
const schema = `
|
||||
interface SimpleMsg {
|
||||
value: pb<1, uint_32>;
|
||||
}
|
||||
`;
|
||||
const registry = analyzeSource(schema, 'schema.ts');
|
||||
|
||||
const encodeFrame = captureFrameFromThrow(invokeEncode, 'runtime-map-encode.js');
|
||||
const decodeFrame = captureFrameFromThrow(() => invokeDecode(new Uint8Array([0x08, 0x07])), 'runtime-map-decode.js');
|
||||
|
||||
const runtimeMap = createRuntimeMap({
|
||||
messages: registry,
|
||||
callSites: [
|
||||
{
|
||||
file: 'runtime-map-encode.js',
|
||||
line: encodeFrame.line,
|
||||
column: encodeFrame.column,
|
||||
fnName: 'protobuf_encode',
|
||||
typeName: 'SimpleMsg',
|
||||
},
|
||||
{
|
||||
file: 'runtime-map-decode.js',
|
||||
line: decodeFrame.line,
|
||||
column: decodeFrame.column,
|
||||
fnName: 'protobuf_decode',
|
||||
typeName: 'SimpleMsg',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
protobuf_enableRuntimeMapFallback(runtimeMap);
|
||||
|
||||
const encoded = invokeEncode();
|
||||
expect([...encoded]).toEqual([0x08, 0x07]);
|
||||
|
||||
const decoded = invokeDecode(encoded);
|
||||
expect(decoded.value).toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { encodeVarint, decodeVarint, writeTag, writeString, readString, skipField } from '../../src/codegen/wire';
|
||||
|
||||
describe('wire format primitives', () => {
|
||||
describe('varint', () => {
|
||||
const cases: [number, number[]][] = [
|
||||
[0, [0x00]],
|
||||
[1, [0x01]],
|
||||
[127, [0x7f]],
|
||||
[128, [0x80, 0x01]],
|
||||
[300, [0xac, 0x02]],
|
||||
[16384, [0x80, 0x80, 0x01]],
|
||||
];
|
||||
|
||||
it.each(cases)('encodeVarint(%i) produces correct bytes', (value, expected) => {
|
||||
const buf: number[] = [];
|
||||
encodeVarint(value, buf);
|
||||
expect(buf).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each(cases)('decodeVarint round-trip for %i', (value) => {
|
||||
const buf: number[] = [];
|
||||
encodeVarint(value, buf);
|
||||
const data = new Uint8Array(buf);
|
||||
const [decoded, offset] = decodeVarint(data, 0);
|
||||
expect(decoded).toBe(value);
|
||||
expect(offset).toBe(buf.length);
|
||||
});
|
||||
|
||||
it('handles max uint32', () => {
|
||||
const value = 0xFFFFFFFF;
|
||||
const buf: number[] = [];
|
||||
encodeVarint(value, buf);
|
||||
const [decoded] = decodeVarint(new Uint8Array(buf), 0);
|
||||
expect(decoded).toBe(value);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tag encoding', () => {
|
||||
it('field 1, varint (wire type 0) produces 0x08', () => {
|
||||
const buf: number[] = [];
|
||||
writeTag(1, 0, buf);
|
||||
expect(buf).toEqual([0x08]);
|
||||
});
|
||||
|
||||
it('field 1, length-delimited (wire type 2) produces 0x0A', () => {
|
||||
const buf: number[] = [];
|
||||
writeTag(1, 2, buf);
|
||||
expect(buf).toEqual([0x0a]);
|
||||
});
|
||||
|
||||
it('field 2, varint produces 0x10', () => {
|
||||
const buf: number[] = [];
|
||||
writeTag(2, 0, buf);
|
||||
expect(buf).toEqual([0x10]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('string encoding', () => {
|
||||
it('encodes and decodes "hello"', () => {
|
||||
const buf: number[] = [];
|
||||
writeString('hello', buf);
|
||||
const data = new Uint8Array(buf);
|
||||
// First byte is length (5), followed by UTF-8 bytes
|
||||
expect(data[0]).toBe(5);
|
||||
const decoded = readString(data, 1, 5);
|
||||
expect(decoded).toBe('hello');
|
||||
});
|
||||
|
||||
it('handles empty string', () => {
|
||||
const buf: number[] = [];
|
||||
writeString('', buf);
|
||||
expect(buf).toEqual([0]); // length 0
|
||||
});
|
||||
|
||||
it('handles unicode', () => {
|
||||
const buf: number[] = [];
|
||||
writeString('你好', buf);
|
||||
const data = new Uint8Array(buf);
|
||||
const [len, offset] = [data[0], 1];
|
||||
const decoded = readString(data, offset, len);
|
||||
expect(decoded).toBe('你好');
|
||||
});
|
||||
});
|
||||
|
||||
describe('skipField', () => {
|
||||
it('skips varint field', () => {
|
||||
const buf: number[] = [];
|
||||
encodeVarint(300, buf); // multi-byte varint
|
||||
const data = new Uint8Array(buf);
|
||||
const newOffset = skipField(data, 0, 0);
|
||||
expect(newOffset).toBe(buf.length);
|
||||
});
|
||||
|
||||
it('skips length-delimited field', () => {
|
||||
// length=3 followed by 3 bytes
|
||||
const data = new Uint8Array([3, 0x41, 0x42, 0x43]);
|
||||
const newOffset = skipField(data, 0, 2);
|
||||
expect(newOffset).toBe(4);
|
||||
});
|
||||
|
||||
it('skips 32-bit field', () => {
|
||||
expect(skipField(new Uint8Array(4), 0, 5)).toBe(4);
|
||||
});
|
||||
|
||||
it('skips 64-bit field', () => {
|
||||
expect(skipField(new Uint8Array(8), 0, 1)).toBe(8);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
// Aliased import of the pb / pb_repeated markers.
|
||||
//
|
||||
// `parsePbTypeRef` compared the literal type-ref identifier text against
|
||||
// the constants `'pb'` / `'pb_repeated'`. With `import { pb as P }` the
|
||||
// identifier text becomes `'P'`, so the field was silently dropped from
|
||||
// the message — interfaces ended up looking empty.
|
||||
//
|
||||
// Fix: resolve the marker name through the imported-name resolver before
|
||||
// comparing.
|
||||
|
||||
import type { pb as P, pb_repeated as PR, uint_32 } from '@snowluma/proton';
|
||||
|
||||
interface Aliased {
|
||||
id: P<1, uint_32>;
|
||||
tags: PR<2, string>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<Aliased>({ id: 1, tags: ['a', 'b'] });
|
||||
const decoded = protobuf_decode<Aliased>(data);
|
||||
|
||||
export { };
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
interface BoolMsg {
|
||||
active: pb<1, bool>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import type { UserMsg as AliasMsg } from './types';
|
||||
|
||||
const buf = protobuf_encode<AliasMsg>({ id: 42, name: 'alice' });
|
||||
const decoded = protobuf_decode<AliasMsg>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { UserMsg } from './types';
|
||||
|
||||
const buf = protobuf_encode<UserMsg>({ id: 42, name: 'alice' });
|
||||
const decoded = protobuf_decode<UserMsg>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface Deep {
|
||||
val: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
export type { Deep };
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
|
||||
const buf = protobuf_encode<Wrapper<string>>({ value: 'hello' });
|
||||
const decoded = protobuf_decode<Wrapper<string>>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface Wrapper<T> {
|
||||
value: pb<1, T>;
|
||||
}
|
||||
|
||||
export type { Wrapper };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface Inner {
|
||||
value: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
export type { Inner };
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
function localEncode<T>(value: T): Uint8Array {
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
|
||||
const buf = localEncode<Wrapper<string>>({ value: 'local' });
|
||||
const decoded = protobuf_decode<Wrapper<string>>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Deep } from './deep';
|
||||
|
||||
interface Mid {
|
||||
inner: pb<1, Deep>;
|
||||
}
|
||||
|
||||
export type { Mid };
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Inner } from './inner';
|
||||
|
||||
interface Outer {
|
||||
inner: pb<1, Inner>;
|
||||
}
|
||||
|
||||
const buf = protobuf_encode<Outer>({ inner: { value: 42 } });
|
||||
const decoded = protobuf_decode<Outer>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface SimpleMessage {
|
||||
id: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
export { SimpleMessage };
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import type { Mid } from './mid';
|
||||
|
||||
interface Top {
|
||||
nested: pb<1, Mid>;
|
||||
}
|
||||
|
||||
const buf = protobuf_encode<Top>({ nested: { inner: { val: 99 } } });
|
||||
const decoded = protobuf_decode<Top>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,6 @@
|
||||
interface UserMsg {
|
||||
id: pb<1, uint_32>;
|
||||
name: pb<2, string>;
|
||||
}
|
||||
|
||||
export type { UserMsg };
|
||||
@@ -0,0 +1,7 @@
|
||||
import { SimpleMessage } from './protobuf';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
const bytes = protobuf_encode<SimpleMessage>({ id: 42 });
|
||||
const decoded = protobuf_decode<SimpleMessage>(bytes);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,49 @@
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
export function encodeViaWrapper<T>(value: T): Uint8Array {
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
|
||||
export function decodeViaWrapper<T>(data: Uint8Array): T {
|
||||
return protobuf_decode<T>(data);
|
||||
}
|
||||
|
||||
export const encodeArrowWrapper = <T>(value: T): Uint8Array => protobuf_encode<T>(value);
|
||||
|
||||
export const decodeArrowWrapper = <T>(data: Uint8Array): T => protobuf_decode<T>(data);
|
||||
|
||||
export function encodeSecondGeneric<Ignored, T>(_ignored: Ignored, value: T): Uint8Array {
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
|
||||
export function passthroughOnly<T>(value: T): T {
|
||||
return value;
|
||||
}
|
||||
|
||||
export const wrapperObject = {
|
||||
encode<T>(value: T): Uint8Array {
|
||||
return protobuf_encode<T>(value);
|
||||
},
|
||||
decode<T>(data: Uint8Array): T {
|
||||
return protobuf_decode<T>(data);
|
||||
},
|
||||
encodeArrow: <T>(value: T): Uint8Array => protobuf_encode<T>(value),
|
||||
};
|
||||
|
||||
export function encodeWithBranch<T>(value: T, enabled: boolean): Uint8Array {
|
||||
if (enabled) {
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
|
||||
export function encodeWithNestedHelper<T>(value: T): Uint8Array {
|
||||
function inner(payload: T): Uint8Array {
|
||||
return protobuf_encode<T>(payload);
|
||||
}
|
||||
return inner(value);
|
||||
}
|
||||
|
||||
export function encodeChained<T>(value: T): Uint8Array {
|
||||
return encodeViaWrapper<T>(value);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import {
|
||||
wrapperObject,
|
||||
encodeWithBranch,
|
||||
encodeWithNestedHelper,
|
||||
encodeChained,
|
||||
} from './wrapper-api';
|
||||
|
||||
const objectBuf = wrapperObject.encode<Wrapper<string>>({ value: 'object' });
|
||||
const objectDecoded = wrapperObject.decode<Wrapper<string>>(objectBuf);
|
||||
|
||||
const arrowMemberBuf = wrapperObject.encodeArrow<Wrapper<Wrapper<string>>>({ value: { value: 'member' } });
|
||||
|
||||
const { encodeArrow } = wrapperObject;
|
||||
const destructuredBuf = encodeArrow<Wrapper<string>>({ value: 'destructured' });
|
||||
|
||||
const branchBuf = encodeWithBranch<Wrapper<string>>({ value: 'branch' }, true);
|
||||
const nestedHelperBuf = encodeWithNestedHelper<Wrapper<string>>({ value: 'nested-helper' });
|
||||
const chainedBuf = encodeChained<Wrapper<string>>({ value: 'chained' });
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import { encodeViaWrapper, decodeViaWrapper } from './wrapper-api';
|
||||
|
||||
const buf = encodeViaWrapper<Wrapper<string>>({ value: 'hello' });
|
||||
const decoded = decodeViaWrapper<Wrapper<string>>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import {
|
||||
encodeViaWrapper as encAlias,
|
||||
decodeViaWrapper as decAlias,
|
||||
encodeArrowWrapper,
|
||||
decodeArrowWrapper,
|
||||
encodeSecondGeneric,
|
||||
passthroughOnly,
|
||||
} from './wrapper-api';
|
||||
|
||||
const aliasBuf = encAlias<Wrapper<string>>({ value: 'alias' });
|
||||
const aliasDecoded = decAlias<Wrapper<string>>(aliasBuf);
|
||||
|
||||
const arrowBuf = encodeArrowWrapper<Wrapper<Wrapper<string>>>({ value: { value: 'nested' } });
|
||||
const arrowDecoded = decodeArrowWrapper<Wrapper<Wrapper<string>>>(arrowBuf);
|
||||
|
||||
const secondBuf = encodeSecondGeneric<number, Wrapper<string>>(1, { value: 'second' });
|
||||
|
||||
const passthrough = passthroughOnly<Wrapper<string>>({ value: 'ignored' });
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
|
||||
export function encodeBoxed<T>(value: Wrapper<T>): Uint8Array {
|
||||
return protobuf_encode<Wrapper<T>>(value);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import {
|
||||
encodeBoxed,
|
||||
decodeBoxed,
|
||||
encodeAliasBoxed,
|
||||
encodeNestedBoxed,
|
||||
encodeBoxedChain,
|
||||
} from './wrapper-type-source';
|
||||
|
||||
const boxedBuf = encodeBoxed<string>({ value: 'boxed' });
|
||||
const boxedDecoded = decodeBoxed<string>(boxedBuf);
|
||||
const aliasBuf = encodeAliasBoxed<string>({ value: 'alias' });
|
||||
const nestedBuf = encodeNestedBoxed<string>({ value: { value: 'nested' } });
|
||||
const chainedBuf = encodeBoxedChain<string>({ value: 'chain' });
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import { encodeBoxed as encodeBoxedBase } from './wrapper-type-source-base';
|
||||
|
||||
export type AliasWrapper<T> = Wrapper<T>;
|
||||
|
||||
export function encodeBoxed<T>(value: Wrapper<T>): Uint8Array {
|
||||
return protobuf_encode<Wrapper<T>>(value);
|
||||
}
|
||||
|
||||
export function decodeBoxed<T>(data: Uint8Array): Wrapper<T> {
|
||||
return protobuf_decode<Wrapper<T>>(data);
|
||||
}
|
||||
|
||||
export function encodeAliasBoxed<T>(value: AliasWrapper<T>): Uint8Array {
|
||||
return protobuf_encode<Wrapper<T>>(value);
|
||||
}
|
||||
|
||||
export function encodeNestedBoxed<T>(value: Wrapper<Wrapper<T>>): Uint8Array {
|
||||
return protobuf_encode<Wrapper<Wrapper<T>>>(value);
|
||||
}
|
||||
|
||||
export function encodeBoxedChain<T>(value: Wrapper<T>): Uint8Array {
|
||||
return encodeBoxedBase<T>(value);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
interface TestProtobufAny<T> {
|
||||
name?: pb<1, T>;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
interface TestProtobufAny<T> {
|
||||
name?: pb<1, T>;
|
||||
}
|
||||
|
||||
const dataT = protobuf_encode<TestProtobufAny<TestProtobufAny<string>>>({ name: { name: "test" } });
|
||||
const decodedT = protobuf_decode<TestProtobufAny<TestProtobufAny<string>>>(dataT);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,24 @@
|
||||
// Generic template with a generic-instantiated message field.
|
||||
//
|
||||
// The outer template's type param (`U`) shows up *inside* an inner generic
|
||||
// instantiation (`Wrapper<U>`). When the outer is monomorphized at the call
|
||||
// site (`Outer<uint_32>`), the inner instantiation must be re-instantiated
|
||||
// with the substitution (becoming `Wrapper<uint_32>`) and put into the
|
||||
// registry under its mangled name `Wrapper__uint_32`.
|
||||
//
|
||||
// Without the fix, the field's `rawTypeName` was `'Wrapper__U'` and the
|
||||
// substituted-mono never produced `Wrapper__uint_32`, leaving the field's
|
||||
// wire-type unresolved.
|
||||
|
||||
interface Wrapper<T> {
|
||||
value: pb<1, T>;
|
||||
}
|
||||
|
||||
interface Outer<U> {
|
||||
wrapped: pb<5, Wrapper<U>>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<Outer<uint_32>>({ wrapped: { value: 42 } });
|
||||
const decoded = protobuf_decode<Outer<uint_32>>(data);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface UserProfile {
|
||||
id: pb<1, uint_32>;
|
||||
username: pb<2, string>;
|
||||
active: pb<3, bool>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Concrete interface with a generic-instantiated message field.
|
||||
//
|
||||
// The call site only references the concrete outer type (`Container`), so
|
||||
// the analyzer must independently:
|
||||
// 1) resolve the field's typeName to the *mangled* form (`Wrapper__uint_32`)
|
||||
// so it matches what monomorphization produces,
|
||||
// 2) enqueue `Wrapper<uint_32>` for monomorphization itself, since the
|
||||
// call-site-driven queue only sees `Container`.
|
||||
//
|
||||
// Without both, wire-type resolution silently leaves the field at the
|
||||
// `WireType.Varint` placeholder and codegen emits a wrong wire format.
|
||||
|
||||
interface Wrapper<T> {
|
||||
value: pb<1, T>;
|
||||
}
|
||||
|
||||
interface Container {
|
||||
wrapped: pb<5, Wrapper<uint_32>>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<Container>({ wrapped: { value: 42 } });
|
||||
const decoded = protobuf_decode<Container>(data);
|
||||
|
||||
export { };
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
interface Inner {
|
||||
value: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
interface Outer {
|
||||
inner: pb<1, Inner>;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
interface Foo {
|
||||
bar: string;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
interface TestProtobuf {
|
||||
name: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
interface TestProtobufOutput {
|
||||
name: pb<1, TestProtobuf>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<TestProtobuf>({ name: 123 });
|
||||
const decoded = protobuf_decode<TestProtobufOutput>(data);
|
||||
|
||||
export { };
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
interface RepeatedMsg {
|
||||
ids: pb_repeated<1, uint_32>;
|
||||
names: pb_repeated<2, string>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<RepeatedMsg>({ ids: [1, 2, 3], names: ["a", "b"] });
|
||||
const decoded = protobuf_decode<RepeatedMsg>(data);
|
||||
|
||||
export { };
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
interface SimpleMsg {
|
||||
value: pb<1, uint_32>;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
interface StringMsg {
|
||||
text: pb<1, string>;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const fixturesDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures');
|
||||
|
||||
/** Load a fixture file as a string. */
|
||||
export function loadFixture(name: string): string {
|
||||
return readFileSync(resolve(fixturesDir, name), 'utf-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Run generated code via `new Function()` and return a named global value.
|
||||
* Cleans up the global after retrieval.
|
||||
*/
|
||||
export function execAndGet<T>(code: string, globalKey: string): T {
|
||||
new Function(code)();
|
||||
const val = (globalThis as any)[globalKey] as T;
|
||||
delete (globalThis as any)[globalKey];
|
||||
return val;
|
||||
}
|
||||
Reference in new issue
Block a user