This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

+25 -25
View File
@@ -34,48 +34,48 @@ export function protobuf_decode<T>(data: Uint8Array): T;
/** Non-enumerable metadata retained for protobuf tags unknown to the schema. */
export interface ProtobufUnknownField {
fieldNumber: number;
wireType: number;
count: number;
totalByteLength: number;
fieldNumber: number;
wireType: number;
count: number;
totalByteLength: number;
}
export interface ProtobufUnknownFieldMetadata {
fields: readonly ProtobufUnknownField[];
totalOccurrences: number;
omittedOccurrences: number;
omittedByteLength: number;
fields: readonly ProtobufUnknownField[];
totalOccurrences: number;
omittedOccurrences: number;
omittedByteLength: number;
}
export function protobuf_getUnknownFields(value: unknown): readonly ProtobufUnknownField[];
export function protobuf_getUnknownFieldMetadata(value: unknown): ProtobufUnknownFieldMetadata;
// ── Optional runtime map fallback (disabled by default) ───────────────
export interface ProtobufRuntimeField {
name: string;
fieldNumber: number;
typeName: string;
wireType: 0 | 1 | 2 | 5;
isMessage: boolean;
isOptional: boolean;
isRepeated: boolean;
name: string;
fieldNumber: number;
typeName: string;
wireType: 0 | 1 | 2 | 5;
isMessage: boolean;
isOptional: boolean;
isRepeated: boolean;
}
export interface ProtobufRuntimeMessage {
name: string;
fields: ProtobufRuntimeField[];
name: string;
fields: ProtobufRuntimeField[];
}
export interface ProtobufRuntimeCallSite {
file: string;
line: number;
column: number;
fnName: 'protobuf_encode' | 'protobuf_decode';
typeName: string;
file: string;
line: number;
column: number;
fnName: 'protobuf_encode' | 'protobuf_decode';
typeName: string;
}
export interface ProtobufRuntimeMap {
version: 1;
messages: ProtobufRuntimeMessage[];
callSites: ProtobufRuntimeCallSite[];
version: 1;
messages: ProtobufRuntimeMessage[];
callSites: ProtobufRuntimeCallSite[];
}
/** Enables map-based runtime dynamic code generation fallback. */
+351 -235
View File
@@ -1,84 +1,111 @@
import ts from 'typescript';
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufMessage, type MessageRegistry, type GenericProtobufTemplate } from './types.js';
import { collectInterface, collectGenericInterface, collectConcreteFieldGenericTypeArgs } from './collector.js';
import {
WireType,
PRIMITIVE_TYPE_MAP,
type ProtobufMessage,
type MessageRegistry,
type GenericProtobufTemplate,
} from './types.js';
import {
collectInterface,
collectGenericInterface,
collectConcreteFieldGenericTypeArgs,
} from './collector.js';
import { monomorphizeTypeNode } from './monomorphizer.js';
import {
createImportedTypeNameResolver,
typeNodeToMangledName,
registerSyntheticTypeSourceFile,
resolveSourceFileForTypeNode,
createImportedTypeNameResolver,
typeNodeToMangledName,
registerSyntheticTypeSourceFile,
resolveSourceFileForTypeNode,
} from './utils.js';
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
import {
collectProtobufImportBindings,
matchProtobufCallSite,
type CanonicalProtobufFn,
collectProtobufImportBindings,
matchProtobufCallSite,
type CanonicalProtobufFn,
} from './callsite.js';
import { buildDependencyRegistry } from './dependency-graph.js';
export { typeNodeToMangledName } from './utils.js';
function getCallableName(expr: ts.Expression): string | null {
if (ts.isIdentifier(expr)) return expr.text;
if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
return null;
if (ts.isIdentifier(expr)) {
return expr.text;
}
if (ts.isPropertyAccessExpression(expr)) {
return expr.name.text;
}
return null;
}
function instantiateWrapperTypePattern(
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
): ts.TypeNode | null {
if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null;
if (!binding.typePattern || !binding.typeParamNames?.length) {
return callerTypeArgs[binding.typeArgIndex] ?? null;
}
let text = binding.typePattern;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) return null;
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
let text = binding.typePattern;
// Parse the substituted type pattern into a fresh source file whose
// `fileName` is the binding's origin (so subsequent import resolution can
// find the right module) AND whose `text` contains the substituted source
// (so `getText()` on the resulting TypeNode returns the actual type, not
// garbage from an empty-text companion file).
const parsed = ts.createSourceFile(
binding.sourceFilePath ?? sf.fileName,
`type __T = ${text};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) return null;
registerSyntheticTypeSourceFile(stmt.type, parsed);
return stmt.type;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) {
return null;
}
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
// Parse the substituted type pattern into a fresh source file whose
// `fileName` is the binding's origin (so subsequent import resolution can
// find the right module) AND whose `text` contains the substituted source
// (so `getText()` on the resulting TypeNode returns the actual type, not
// garbage from an empty-text companion file).
const parsed = ts.createSourceFile(
binding.sourceFilePath ?? sf.fileName,
`type __T = ${text};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) {
return null;
}
registerSyntheticTypeSourceFile(stmt.type, parsed);
return stmt.type;
}
/** A recorded call-site for later replacement. */
export interface CallSiteRecord {
fnName: CanonicalProtobufFn;
exprStart: number; // position of identifier start
typeArgsEnd: number; // position after closing '>'
firstTypeArg: ts.TypeNode; // the type argument node
line: number; // 1-based line for runtime map lookup
column: number; // 1-based column for runtime map lookup
fnName: CanonicalProtobufFn;
exprStart: number; // position of identifier start
typeArgsEnd: number; // position after closing '>'
firstTypeArg: ts.TypeNode; // the type argument node
line: number; // 1-based line for runtime map lookup
column: number; // 1-based column for runtime map lookup
}
export interface ResolvedCallSiteRecord extends CallSiteRecord {
typeName: string;
typeName: string;
}
export interface AnalysisResult {
registry: MessageRegistry;
callSites: CallSiteRecord[];
sourceFile: ts.SourceFile;
registry: MessageRegistry;
callSites: CallSiteRecord[];
sourceFile: ts.SourceFile;
}
export interface UsedRegistryResult {
registry: MessageRegistry;
roots: Set<string>;
callSites: ResolvedCallSiteRecord[];
registry: MessageRegistry;
roots: Set<string>;
callSites: ResolvedCallSiteRecord[];
}
/**
@@ -90,171 +117,236 @@ export interface UsedRegistryResult {
*
* Then post-processes: monomorphize → resolve wire types → topo sort.
*/
export function analyze(code: string, filePath: string, imported?: ImportedDefinitions): AnalysisResult {
const sf = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true);
const concrete: ProtobufMessage[] = [];
const templates = new Map<string, GenericProtobufTemplate>();
const mono = new Map<string, ProtobufMessage>();
const callSites: CallSiteRecord[] = [];
const deferredTypeArgs: ts.TypeNode[] = [];
const importBindings = collectProtobufImportBindings(sf);
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
const wrapperBindings = imported?.wrapperBindings ?? new Map<string, WrapperBinding>();
export function analyze(
code: string,
filePath: string,
imported?: ImportedDefinitions,
): AnalysisResult {
const sf = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true);
const concrete: ProtobufMessage[] = [];
const templates = new Map<string, GenericProtobufTemplate>();
const mono = new Map<string, ProtobufMessage>();
const callSites: CallSiteRecord[] = [];
const deferredTypeArgs: ts.TypeNode[] = [];
const importBindings = collectProtobufImportBindings(sf);
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
const wrapperBindings = imported?.wrapperBindings ?? new Map<string, WrapperBinding>();
// Seed with imported definitions
if (imported) {
concrete.push(...imported.concrete);
for (const [k, v] of imported.templates) templates.set(k, v);
}
// Seed with imported definitions
if (imported) {
concrete.push(...imported.concrete);
// Stack of generic-function type-param scopes. When visiting a
// `protobuf_encode/decode<X>` call whose type arg references one of
// these (e.g. `protobuf_encode<OidbBase<T>>(env)` inside
// `function encodeOidbEnv<T>(...)`), we MUST skip monomorphization —
// the type arg only resolves once the wrapper itself is instantiated
// at a downstream call site, and that case is handled separately by
// the wrapper-binding path in `matchForwardedProtobufFn`. Without
// this skip, the analyzer would happily mint a literal `OidbBase__T`
// registry entry with a `body.typeName = 'T'` field, which the
// wire-type guard then trips on.
const enclosingTypeParamStack: Set<string>[] = [];
function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean {
if (enclosingTypeParamStack.length === 0) return false;
let found = false;
function check(n: ts.Node): void {
if (found) return;
if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) {
const name = n.typeName.text;
for (const scope of enclosingTypeParamStack) {
if (scope.has(name)) { found = true; return; }
for (const [k, v] of imported.templates) {
templates.set(k, v);
}
}
ts.forEachChild(n, check);
}
check(typeArg);
return found;
}
function nodeIntroducesTypeParams(n: ts.Node): readonly ts.TypeParameterDeclaration[] | undefined {
if (ts.isFunctionDeclaration(n)) return n.typeParameters;
if (ts.isFunctionExpression(n)) return n.typeParameters;
if (ts.isArrowFunction(n)) return n.typeParameters;
if (ts.isMethodDeclaration(n)) return n.typeParameters;
return undefined;
}
// ── single walk ─────────────────────────────────────────────────────
ts.forEachChild(sf, function visit(node) {
const introduced = nodeIntroducesTypeParams(node);
const pushedScope = !!(introduced && introduced.length);
if (pushedScope) {
enclosingTypeParamStack.push(new Set(introduced!.map(p => p.name.text)));
}
try {
if (ts.isInterfaceDeclaration(node)) {
if (node.typeParameters?.length) {
const tpl = collectGenericInterface(node, sf, resolveImportedTypeName);
if (tpl) templates.set(tpl.name, tpl);
} else {
const msg = collectInterface(node, sf, resolveImportedTypeName);
if (msg) concrete.push(msg);
// Queue any generic-instantiated type-args appearing as field types
// (e.g. `wrapped: pb<5, Wrapper<uint_32>>`) for monomorphization.
// The call-site queue only sees the outer concrete type, so without
// this the nested instantiation would never reach the registry.
for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) {
deferredTypeArgs.push(ta);
}
}
}
// Stack of generic-function type-param scopes. When visiting a
// `protobuf_encode/decode<X>` call whose type arg references one of
// these (e.g. `protobuf_encode<OidbBase<T>>(env)` inside
// `function encodeOidbEnv<T>(...)`), we MUST skip monomorphization —
// the type arg only resolves once the wrapper itself is instantiated
// at a downstream call site, and that case is handled separately by
// the wrapper-binding path in `matchForwardedProtobufFn`. Without
// this skip, the analyzer would happily mint a literal `OidbBase__T`
// registry entry with a `body.typeName = 'T'` field, which the
// wire-type guard then trips on.
const enclosingTypeParamStack: Set<string>[] = [];
function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean {
if (enclosingTypeParamStack.length === 0) {
return false;
}
let found = false;
function check(n: ts.Node): void {
if (found) {
return;
}
if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) {
const name = n.typeName.text;
for (const scope of enclosingTypeParamStack) {
if (scope.has(name)) {
found = true;
return;
}
}
}
ts.forEachChild(n, check);
}
check(typeArg);
return found;
}
function nodeIntroducesTypeParams(
n: ts.Node,
): readonly ts.TypeParameterDeclaration[] | undefined {
if (ts.isFunctionDeclaration(n)) {
return n.typeParameters;
}
if (ts.isFunctionExpression(n)) {
return n.typeParameters;
}
if (ts.isArrowFunction(n)) {
return n.typeParameters;
}
if (ts.isMethodDeclaration(n)) {
return n.typeParameters;
}
return undefined;
}
// ── single walk ─────────────────────────────────────────────────────
ts.forEachChild(sf, function visit(node) {
const introduced = nodeIntroducesTypeParams(node);
const pushedScope = !!(introduced && introduced.length);
if (pushedScope) {
enclosingTypeParamStack.push(new Set(introduced!.map((p) => p.name.text)));
}
try {
if (ts.isInterfaceDeclaration(node)) {
if (node.typeParameters?.length) {
const tpl = collectGenericInterface(node, sf, resolveImportedTypeName);
if (tpl) {
templates.set(tpl.name, tpl);
}
} else {
const msg = collectInterface(node, sf, resolveImportedTypeName);
if (msg) {
concrete.push(msg);
}
// Queue any generic-instantiated type-args appearing as field types
// (e.g. `wrapped: pb<5, Wrapper<uint_32>>`) for monomorphization.
// The call-site queue only sees the outer concrete type, so without
// this the nested instantiation would never reach the registry.
for (const ta of collectConcreteFieldGenericTypeArgs(
node,
resolveImportedTypeName,
)) {
deferredTypeArgs.push(ta);
}
}
}
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) {
if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) {
deferredTypeArgs.push(cs.firstTypeArg);
callSites.push(cs);
}
// else: this call sits inside a generic wrapper definition; the
// wrapper-binding path will materialise concrete codecs at each
// downstream call site instead.
} else if (
node.typeArguments?.length &&
getCallableName(node.expression) &&
wrapperBindings.has(getCallableName(node.expression)!)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!)!;
const firstTypeArg = instantiateWrapperTypePattern(
binding,
node.typeArguments,
sf,
);
if (!firstTypeArg) {
ts.forEachChild(node, visit);
return;
}
const exprStart = node.expression.getStart(sf);
const lc = sf.getLineAndCharacterOfPosition(exprStart);
deferredTypeArgs.push(firstTypeArg);
callSites.push({
fnName: binding.fnName,
exprStart,
typeArgsEnd: node.typeArguments.end + 1,
firstTypeArg,
line: lc.line + 1,
column: lc.character + 1,
});
}
}
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) {
if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) {
deferredTypeArgs.push(cs.firstTypeArg);
callSites.push(cs);
}
// else: this call sits inside a generic wrapper definition; the
// wrapper-binding path will materialise concrete codecs at each
// downstream call site instead.
} else if (
node.typeArguments?.length &&
getCallableName(node.expression) &&
wrapperBindings.has(getCallableName(node.expression)!)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!)!;
const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf);
if (!firstTypeArg) {
ts.forEachChild(node, visit);
return;
}
const exprStart = node.expression.getStart(sf);
const lc = sf.getLineAndCharacterOfPosition(exprStart);
deferredTypeArgs.push(firstTypeArg);
callSites.push({
fnName: binding.fnName,
exprStart,
typeArgsEnd: node.typeArguments.end + 1,
firstTypeArg,
line: lc.line + 1,
column: lc.character + 1,
});
} finally {
if (pushedScope) {
enclosingTypeParamStack.pop();
}
}
}
});
ts.forEachChild(node, visit);
} finally {
if (pushedScope) enclosingTypeParamStack.pop();
// ── post-walk: monomorphize deferred type args ──────────────────────
for (const typeArg of deferredTypeArgs) {
const typeSf = resolveSourceFileForTypeNode(typeArg, sf);
const typeResolver = createImportedTypeNameResolver(typeSf);
monomorphizeTypeNode(typeArg, typeSf, templates, mono, typeResolver);
}
});
// ── post-walk: monomorphize deferred type args ──────────────────────
for (const typeArg of deferredTypeArgs) {
const typeSf = resolveSourceFileForTypeNode(typeArg, sf);
const typeResolver = createImportedTypeNameResolver(typeSf);
monomorphizeTypeNode(typeArg, typeSf, templates, mono, typeResolver);
}
for (const m of mono.values()) concrete.push(m);
// ── resolve wire types ──────────────────────────────────────────────
// Anything that doesn't resolve to a primitive or a registered message is
// a type-tracking miss — historically these leaked the placeholder
// `WireType.Varint` into codegen and corrupted the wire format silently.
// Throw loudly instead so future analyzer gaps surface immediately.
const names = new Set(concrete.map(m => m.name));
for (const msg of concrete) {
for (const f of msg.fields) {
const prim = PRIMITIVE_TYPE_MAP[f.typeName];
if (prim) {
f.wireType = prim.wireType;
f.isMessage = false;
} else if (names.has(f.typeName)) {
f.wireType = WireType.LengthDelim;
f.isMessage = true;
} else {
throw new Error(
`Cannot resolve protobuf field type "${f.typeName}" on message "${msg.name}" ` +
`(field "${f.name}", field number ${f.fieldNumber}). The analyzer did not produce ` +
`a primitive or registered message for this type. Common causes: union / intersection / ` +
`mapped / conditional types, TypeScript utility types (Partial<T>, Pick<T>, …), ` +
`qualified names (ns.Type), or a missing import.`,
);
}
for (const m of mono.values()) {
concrete.push(m);
}
}
return { registry: topoSort(concrete), callSites, sourceFile: sf };
// ── resolve wire types ──────────────────────────────────────────────
// Anything that doesn't resolve to a primitive or a registered message is
// a type-tracking miss — historically these leaked the placeholder
// `WireType.Varint` into codegen and corrupted the wire format silently.
// Throw loudly instead so future analyzer gaps surface immediately.
const names = new Set(concrete.map((m) => m.name));
for (const msg of concrete) {
for (const f of msg.fields) {
const prim = PRIMITIVE_TYPE_MAP[f.typeName];
if (prim) {
f.wireType = prim.wireType;
f.isMessage = false;
} else if (names.has(f.typeName)) {
f.wireType = WireType.LengthDelim;
f.isMessage = true;
} else {
throw new Error(
`Cannot resolve protobuf field type "${f.typeName}" on message "${msg.name}" ` +
`(field "${f.name}", field number ${f.fieldNumber}). The analyzer did not produce ` +
`a primitive or registered message for this type. Common causes: union / intersection / ` +
`mapped / conditional types, TypeScript utility types (Partial<T>, Pick<T>, …), ` +
`qualified names (ns.Type), or a missing import.`,
);
}
}
}
return { registry: topoSort(concrete), callSites, sourceFile: sf };
}
/**
* Backward-compatible wrapper: returns only the MessageRegistry.
* Uses the same single-walk analysis internally.
*/
export function analyzeSource(code: string, filePath: string, imported?: ImportedDefinitions): MessageRegistry {
return analyze(code, filePath, imported).registry;
export function analyzeSource(
code: string,
filePath: string,
imported?: ImportedDefinitions,
): MessageRegistry {
return analyze(code, filePath, imported).registry;
}
/**
@@ -262,54 +354,78 @@ export function analyzeSource(code: string, filePath: string, imported?: Importe
* their transitive message dependencies.
*/
export function selectUsedRegistry(
registry: MessageRegistry,
callSites: CallSiteRecord[],
sourceFile: ts.SourceFile,
registry: MessageRegistry,
callSites: CallSiteRecord[],
sourceFile: ts.SourceFile,
): UsedRegistryResult {
const roots = new Set<string>();
const resolved: ResolvedCallSiteRecord[] = [];
for (const cs of callSites) {
const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile);
const typeName = typeNodeToMangledName(cs.firstTypeArg, typeSf, createImportedTypeNameResolver(typeSf));
if (!registry.has(typeName)) continue;
roots.add(typeName);
resolved.push({ ...cs, typeName });
}
const roots = new Set<string>();
const resolved: ResolvedCallSiteRecord[] = [];
if (roots.size === 0) {
return { registry: new Map(), roots, callSites: resolved };
}
for (const cs of callSites) {
const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile);
const typeName = typeNodeToMangledName(
cs.firstTypeArg,
typeSf,
createImportedTypeNameResolver(typeSf),
);
return {
registry: buildDependencyRegistry(registry, roots),
roots,
callSites: resolved,
};
if (!registry.has(typeName)) {
continue;
}
roots.add(typeName);
resolved.push({ ...cs, typeName });
}
if (roots.size === 0) {
return { registry: new Map(), roots, callSites: resolved };
}
return {
registry: buildDependencyRegistry(registry, roots),
roots,
callSites: resolved,
};
}
// ── topological sort ──────────────────────────────────────────────────
function topoSort(messages: ProtobufMessage[]): MessageRegistry {
const map = new Map(messages.map(m => [m.name, m]));
const deps = new Map(messages.map(m => [
m.name,
new Set(m.fields.filter(f => map.has(f.typeName)).map(f => f.typeName)),
]));
const map = new Map(messages.map((m) => [m.name, m]));
const deps = new Map(
messages.map((m) => [
m.name,
new Set(m.fields.filter((f) => map.has(f.typeName)).map((f) => f.typeName)),
]),
);
const sorted: ProtobufMessage[] = [];
const visited = new Set<string>();
const visiting = new Set<string>();
const sorted: ProtobufMessage[] = [];
const visited = new Set<string>();
const visiting = new Set<string>();
function dfs(name: string): void {
if (visited.has(name)) return;
if (visiting.has(name)) throw new Error(`Circular dependency: ${name}`);
visiting.add(name);
for (const d of deps.get(name) || []) dfs(d);
visiting.delete(name);
visited.add(name);
sorted.push(map.get(name)!);
}
function dfs(name: string): void {
if (visited.has(name)) {
return;
}
for (const m of messages) dfs(m.name);
return new Map(sorted.map(m => [m.name, m]));
if (visiting.has(name)) {
throw new Error(`Circular dependency: ${name}`);
}
visiting.add(name);
for (const d of deps.get(name) || []) {
dfs(d);
}
visiting.delete(name);
visited.add(name);
sorted.push(map.get(name)!);
}
for (const m of messages) {
dfs(m.name);
}
return new Map(sorted.map((m) => [m.name, m]));
}
+109 -87
View File
@@ -3,117 +3,139 @@ import ts from 'typescript';
export type CanonicalProtobufFn = 'protobuf_encode' | 'protobuf_decode';
const CANONICAL = new Set<CanonicalProtobufFn>(['protobuf_encode', 'protobuf_decode']);
const PROTOBUF_RUNTIME_MODULES = new Set([
'@snowluma/proton',
]);
const PROTOBUF_RUNTIME_MODULES = new Set(['@snowluma/proton']);
export interface ProtobufImportBindings {
identifierToCanonical: Map<string, CanonicalProtobufFn>;
namespaceAliases: Set<string>;
blockedLegacyCanonical: Set<CanonicalProtobufFn>;
hasRuntimeImport: boolean;
identifierToCanonical: Map<string, CanonicalProtobufFn>;
namespaceAliases: Set<string>;
blockedLegacyCanonical: Set<CanonicalProtobufFn>;
hasRuntimeImport: boolean;
}
export interface ProtobufCallSite {
fnName: CanonicalProtobufFn;
exprStart: number;
typeArgsEnd: number;
firstTypeArg: ts.TypeNode;
line: number;
column: number;
fnName: CanonicalProtobufFn;
exprStart: number;
typeArgsEnd: number;
firstTypeArg: ts.TypeNode;
line: number;
column: number;
}
export function collectProtobufImportBindings(sf: ts.SourceFile): ProtobufImportBindings {
const identifierToCanonical = new Map<string, CanonicalProtobufFn>();
const namespaceAliases = new Set<string>();
const blockedLegacyCanonical = new Set<CanonicalProtobufFn>();
let hasRuntimeImport = false;
const identifierToCanonical = new Map<string, CanonicalProtobufFn>();
const namespaceAliases = new Set<string>();
const blockedLegacyCanonical = new Set<CanonicalProtobufFn>();
let hasRuntimeImport = false;
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
if (!ts.isStringLiteral(stmt.moduleSpecifier)) continue;
const fromRuntime = PROTOBUF_RUNTIME_MODULES.has(stmt.moduleSpecifier.text);
if (fromRuntime) hasRuntimeImport = true;
const bindings = stmt.importClause.namedBindings;
const defaultImport = stmt.importClause.name?.text;
if (defaultImport && CANONICAL.has(defaultImport as CanonicalProtobufFn) && !fromRuntime) {
blockedLegacyCanonical.add(defaultImport as CanonicalProtobufFn);
}
if (!bindings) continue;
if (ts.isNamedImports(bindings)) {
for (const el of bindings.elements) {
const imported = (el.propertyName ?? el.name).text;
if (fromRuntime && CANONICAL.has(imported as CanonicalProtobufFn)) {
identifierToCanonical.set(el.name.text, imported as CanonicalProtobufFn);
continue;
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) {
continue;
}
if (CANONICAL.has(el.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(el.name.text as CanonicalProtobufFn);
if (!ts.isStringLiteral(stmt.moduleSpecifier)) {
continue;
}
const fromRuntime = PROTOBUF_RUNTIME_MODULES.has(stmt.moduleSpecifier.text);
if (fromRuntime) {
hasRuntimeImport = true;
}
const bindings = stmt.importClause.namedBindings;
const defaultImport = stmt.importClause.name?.text;
if (defaultImport && CANONICAL.has(defaultImport as CanonicalProtobufFn) && !fromRuntime) {
blockedLegacyCanonical.add(defaultImport as CanonicalProtobufFn);
}
if (!bindings) {
continue;
}
if (ts.isNamedImports(bindings)) {
for (const el of bindings.elements) {
const imported = (el.propertyName ?? el.name).text;
if (fromRuntime && CANONICAL.has(imported as CanonicalProtobufFn)) {
identifierToCanonical.set(el.name.text, imported as CanonicalProtobufFn);
continue;
}
if (CANONICAL.has(el.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(el.name.text as CanonicalProtobufFn);
}
}
continue;
}
if (fromRuntime && ts.isNamespaceImport(bindings)) {
namespaceAliases.add(bindings.name.text);
} else if (CANONICAL.has(bindings.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(bindings.name.text as CanonicalProtobufFn);
}
}
continue;
}
if (fromRuntime && ts.isNamespaceImport(bindings)) {
namespaceAliases.add(bindings.name.text);
} else if (CANONICAL.has(bindings.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(bindings.name.text as CanonicalProtobufFn);
}
}
return { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport };
return { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport };
}
interface MatchOptions {
allowLegacyUnboundCanonical?: boolean;
allowLegacyUnboundCanonical?: boolean;
}
export function matchProtobufCallSite(
node: ts.CallExpression,
sf: ts.SourceFile,
bindings: ProtobufImportBindings,
options?: MatchOptions,
node: ts.CallExpression,
sf: ts.SourceFile,
bindings: ProtobufImportBindings,
options?: MatchOptions,
): ProtobufCallSite | null {
const ta = node.typeArguments;
if (!ta?.length) return null;
const ta = node.typeArguments;
const expr = node.expression;
const allowLegacy = options?.allowLegacyUnboundCanonical === true;
let fnName: CanonicalProtobufFn | null = null;
let exprStart = expr.getStart(sf);
if (ts.isIdentifier(expr)) {
fnName = bindings.identifierToCanonical.get(expr.text) ?? null;
if (
!fnName &&
allowLegacy &&
!bindings.hasRuntimeImport &&
CANONICAL.has(expr.text as CanonicalProtobufFn) &&
!bindings.blockedLegacyCanonical.has(expr.text as CanonicalProtobufFn)
) {
fnName = expr.text as CanonicalProtobufFn;
if (!ta?.length) {
return null;
}
} else if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression)) {
if (bindings.namespaceAliases.has(expr.expression.text) && CANONICAL.has(expr.name.text as CanonicalProtobufFn)) {
fnName = expr.name.text as CanonicalProtobufFn;
exprStart = expr.getStart(sf);
const expr = node.expression;
const allowLegacy = options?.allowLegacyUnboundCanonical === true;
let fnName: CanonicalProtobufFn | null = null;
let exprStart = expr.getStart(sf);
if (ts.isIdentifier(expr)) {
fnName = bindings.identifierToCanonical.get(expr.text) ?? null;
if (
!fnName &&
allowLegacy &&
!bindings.hasRuntimeImport &&
CANONICAL.has(expr.text as CanonicalProtobufFn) &&
!bindings.blockedLegacyCanonical.has(expr.text as CanonicalProtobufFn)
) {
fnName = expr.text as CanonicalProtobufFn;
}
} else if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression)) {
if (
bindings.namespaceAliases.has(expr.expression.text) &&
CANONICAL.has(expr.name.text as CanonicalProtobufFn)
) {
fnName = expr.name.text as CanonicalProtobufFn;
exprStart = expr.getStart(sf);
}
}
}
if (!fnName) return null;
const lc = sf.getLineAndCharacterOfPosition(exprStart);
if (!fnName) {
return null;
}
return {
fnName,
exprStart,
typeArgsEnd: ta.end + 1,
firstTypeArg: ta[0],
line: lc.line + 1,
column: lc.character + 1,
};
const lc = sf.getLineAndCharacterOfPosition(exprStart);
return {
fnName,
exprStart,
typeArgsEnd: ta.end + 1,
firstTypeArg: ta[0],
line: lc.line + 1,
column: lc.character + 1,
};
}
+191 -114
View File
@@ -1,14 +1,22 @@
import ts from 'typescript';
import {
WireType,
PB_MARKER, PB_REPEATED_MARKER, PB_OPTIONAL_MARKER,
type ProtobufField, type ProtobufMessage,
type GenericProtobufTemplate, type GenericFieldTemplate,
WireType,
PB_MARKER,
PB_REPEATED_MARKER,
PB_OPTIONAL_MARKER,
type ProtobufField,
type ProtobufMessage,
type GenericProtobufTemplate,
type GenericFieldTemplate,
} from './types.js';
import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js';
import {
isKeywordTypeNode,
typeNodeToMangledName,
type ImportedTypeNameResolver,
} from './utils.js';
function identityImportedTypeName(name: string): string {
return name;
return name;
}
/**
@@ -19,149 +27,218 @@ function identityImportedTypeName(name: string): string {
* type; nested generic instantiations on its fields would otherwise be missed.)
*/
export function* collectConcreteFieldGenericTypeArgs(
node: ts.InterfaceDeclaration,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
node: ts.InterfaceDeclaration,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): IterableIterator<ts.TypeNode> {
if (node.typeParameters?.length) return;
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue;
const parsed = parsePbTypeRef(m, resolveImportedTypeName);
if (!parsed) continue;
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
yield ta;
if (node.typeParameters?.length) {
return;
}
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) {
continue;
}
const parsed = parsePbTypeRef(m, resolveImportedTypeName);
if (!parsed) {
continue;
}
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
yield ta;
}
}
}
}
/** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */
export function collectInterface(
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): ProtobufMessage | null {
const fields: ProtobufField[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue;
const f = extractField(m, sf, resolveImportedTypeName);
if (f) fields.push(f);
}
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as
// zero-field proto messages — proto3 wire format allows them and
// downstream code routinely uses them for "this OIDB call has no
// meaningful response body" placeholders. Interfaces that have
// members but no pb-marked fields are NOT proto messages — they
// belong to regular TS types and must stay unregistered to avoid
// polluting the registry.
if (fields.length === 0 && node.members.length > 0) return null;
return { name: node.name.text, fields };
const fields: ProtobufField[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) {
continue;
}
const f = extractField(m, sf, resolveImportedTypeName);
if (f) {
fields.push(f);
}
}
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as
// zero-field proto messages — proto3 wire format allows them and
// downstream code routinely uses them for "this OIDB call has no
// meaningful response body" placeholders. Interfaces that have
// members but no pb-marked fields are NOT proto messages — they
// belong to regular TS types and must stay unregistered to avoid
// polluting the registry.
if (fields.length === 0 && node.members.length > 0) {
return null;
}
return { name: node.name.text, fields };
}
/** Collect a generic interface template. */
export function collectGenericInterface(
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): GenericProtobufTemplate | null {
const typeParams = node.typeParameters!.map(p => p.name.text);
const tpSet = new Set(typeParams);
const fields: GenericFieldTemplate[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue;
const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName);
if (f) fields.push(f);
}
return fields.length ? { name: node.name.text, typeParams, fields } : null;
const typeParams = node.typeParameters!.map((p) => p.name.text);
const tpSet = new Set(typeParams);
const fields: GenericFieldTemplate[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) {
continue;
}
const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName);
if (f) {
fields.push(f);
}
}
return fields.length ? { name: node.name.text, typeParams, fields } : null;
}
// ── helpers ───────────────────────────────────────────────────────────
function parsePbTypeRef(
member: ts.PropertySignature,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
member: ts.PropertySignature,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): { marker: string; fieldNumber: number; typeArgNode: ts.TypeNode } | null {
const t = member.type!;
if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null;
// Resolve the marker name through aliased imports so `import { pb as P }`
// / `import { pb_repeated as PR }` still match the marker constants.
const marker = resolveImportedTypeName(t.typeName.text);
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER && marker !== PB_OPTIONAL_MARKER) return null;
const ta = t.typeArguments;
if (!ta || ta.length !== 2) return null;
const fnNode = ta[0];
if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null;
return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] };
const t = member.type!;
if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) {
return null;
}
// Resolve the marker name through aliased imports so `import { pb as P }`
// / `import { pb_repeated as PR }` still match the marker constants.
const marker = resolveImportedTypeName(t.typeName.text);
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER && marker !== PB_OPTIONAL_MARKER) {
return null;
}
const ta = t.typeArguments;
if (!ta || ta.length !== 2) {
return null;
}
const fnNode = ta[0];
if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) {
return null;
}
return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] };
}
function resolveTypeName(
node: ts.TypeNode,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
node: ts.TypeNode,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
): string | null {
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
// Generic instantiations (e.g. `Wrapper<uint_32>`) must resolve to the
// mangled name produced by monomorphization so wire-type resolution can
// find the message in the registry. Without this the field would carry
// the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`.
if (node.typeArguments && node.typeArguments.length > 0) {
return typeNodeToMangledName(node, sf, resolveImportedTypeName);
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
// Generic instantiations (e.g. `Wrapper<uint_32>`) must resolve to the
// mangled name produced by monomorphization so wire-type resolution can
// find the message in the registry. Without this the field would carry
// the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`.
if (node.typeArguments && node.typeArguments.length > 0) {
return typeNodeToMangledName(node, sf, resolveImportedTypeName);
}
return resolveImportedTypeName(node.typeName.text);
}
return resolveImportedTypeName(node.typeName.text);
}
if (isKeywordTypeNode(node)) return node.getText(sf);
return null;
if (isKeywordTypeNode(node)) {
return node.getText(sf);
}
return null;
}
function extractField(
member: ts.PropertySignature,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
member: ts.PropertySignature,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
): ProtobufField | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) return null;
const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!typeName || !ts.isIdentifier(member.name)) return null;
return {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
typeName,
wireType: WireType.Varint, // placeholder
isMessage: false, // placeholder
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
};
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) {
return null;
}
const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!typeName || !ts.isIdentifier(member.name)) {
return null;
}
return {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
typeName,
wireType: WireType.Varint, // placeholder
isMessage: false, // placeholder
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
};
}
function extractGenericField(
member: ts.PropertySignature,
sf: ts.SourceFile,
tpSet: Set<string>,
resolveImportedTypeName: ImportedTypeNameResolver,
member: ts.PropertySignature,
sf: ts.SourceFile,
tpSet: Set<string>,
resolveImportedTypeName: ImportedTypeNameResolver,
): GenericFieldTemplate | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) return null;
const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!raw || !ts.isIdentifier(member.name)) return null;
const result: GenericFieldTemplate = {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw),
isTypeParam: tpSet.has(raw),
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
};
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) {
return null;
}
const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!raw || !ts.isIdentifier(member.name)) {
return null;
}
const result: GenericFieldTemplate = {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw),
isTypeParam: tpSet.has(raw),
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
};
// If the field's type-arg is itself a generic instantiation (`Wrapper<U>`,
// where U is a type param of the enclosing template), capture the original
// source text so monomorphization can substitute U and re-instantiate the
// inner generic. Without this the field's `rawTypeName` would stay at the
// unsubstituted `'Wrapper__U'` form and the substituted instantiation
// would never reach the registry.
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
result.genericTypeArgText = ta.getText(sf);
result.genericTypeArgSourceFilePath = sf.fileName;
}
return result;
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
result.genericTypeArgText = ta.getText(sf);
result.genericTypeArgSourceFilePath = sf.fileName;
}
return result;
}
+46 -21
View File
@@ -1,32 +1,57 @@
import type { MessageRegistry } from './types.js';
export function collectDependencyClosure(registry: MessageRegistry, roots: Iterable<string>): Set<string> {
const selected = new Set<string>();
export function collectDependencyClosure(
registry: MessageRegistry,
roots: Iterable<string>,
): Set<string> {
const selected = new Set<string>();
function visit(name: string): void {
if (selected.has(name)) return;
const msg = registry.get(name);
if (!msg) return;
function visit(name: string): void {
if (selected.has(name)) {
return;
}
selected.add(name);
for (const field of msg.fields) {
if (registry.has(field.typeName)) visit(field.typeName);
const msg = registry.get(name);
if (!msg) {
return;
}
selected.add(name);
for (const field of msg.fields) {
if (registry.has(field.typeName)) {
visit(field.typeName);
}
}
}
}
for (const root of roots) visit(root);
return selected;
for (const root of roots) {
visit(root);
}
return selected;
}
export function pickRegistrySubset(registry: MessageRegistry, selectedNames: Set<string>): MessageRegistry {
const subset: MessageRegistry = new Map();
for (const [name, msg] of registry) {
if (selectedNames.has(name)) subset.set(name, msg);
}
return subset;
export function pickRegistrySubset(
registry: MessageRegistry,
selectedNames: Set<string>,
): MessageRegistry {
const subset: MessageRegistry = new Map();
for (const [name, msg] of registry) {
if (selectedNames.has(name)) {
subset.set(name, msg);
}
}
return subset;
}
export function buildDependencyRegistry(registry: MessageRegistry, roots: Iterable<string>): MessageRegistry {
const selected = collectDependencyClosure(registry, roots);
return pickRegistrySubset(registry, selected);
export function buildDependencyRegistry(
registry: MessageRegistry,
roots: Iterable<string>,
): MessageRegistry {
const selected = collectDependencyClosure(registry, roots);
return pickRegistrySubset(registry, selected);
}
File diff suppressed because it is too large. Load diff
+142 -102
View File
@@ -1,15 +1,20 @@
import ts from 'typescript';
import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js';
import {
isKeywordTypeNode,
createImportedTypeNameResolver,
resolveSourceFileForTypeNode,
type ImportedTypeNameResolver,
typeNodeToMangledName,
WireType,
type ProtobufField,
type ProtobufMessage,
type GenericProtobufTemplate,
} from './types.js';
import {
isKeywordTypeNode,
createImportedTypeNameResolver,
resolveSourceFileForTypeNode,
type ImportedTypeNameResolver,
typeNodeToMangledName,
} from './utils.js';
function identityImportedTypeName(name: string): string {
return name;
return name;
}
/** Resolved value for a single template type parameter. */
@@ -28,106 +33,141 @@ interface ResolvedTypeArg {
* Returns the mangled name of the concrete type, or null if it cannot be resolved.
*/
export function monomorphizeTypeNode(
typeNode: ts.TypeNode,
sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
typeNode: ts.TypeNode,
sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): string | null {
if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null;
const baseName = resolveImportedTypeName(typeNode.typeName.text);
const typeArgs = typeNode.typeArguments;
if (!typeArgs || typeArgs.length === 0) return baseName; // already concrete
const tpl = templates.get(baseName);
if (!tpl || typeArgs.length !== tpl.typeParams.length) return null;
const mangledName = typeNodeToMangledName(typeNode, sf, resolveImportedTypeName);
if (out.has(mangledName)) return mangledName; // already done
// Resolve each type parameter → both mangled name AND source text.
const paramMap = new Map<string, ResolvedTypeArg>();
for (let i = 0; i < tpl.typeParams.length; i++) {
const resolved = resolveTypeArg(typeArgs[i], sf, templates, out, resolveImportedTypeName);
if (!resolved) return null;
paramMap.set(tpl.typeParams[i], resolved);
}
// Substitute type params in template fields.
const fields: ProtobufField[] = tpl.fields.map(f => {
if (f.genericTypeArgText) {
// Field type is an inner generic instantiation referencing template
// type params (e.g. `pb<N, Wrapper<U>>`). Substitute the params into
// the captured text, re-parse, and re-monomorphize so the resulting
// concrete instantiation (`Wrapper<uint_32>`) lands in `out`.
let substituted = f.genericTypeArgText;
for (const [paramName, value] of paramMap) {
substituted = substituted.replace(
new RegExp(`\\b${paramName}\\b`, 'g'),
value.text,
);
}
const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName;
const innerSf = ts.createSourceFile(
innerSfPath,
`type __X = ${substituted};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = innerSf.statements[0];
let resolvedTypeName: string | null = null;
if (ts.isTypeAliasDeclaration(stmt)) {
const innerResolver = createImportedTypeNameResolver(innerSf);
resolvedTypeName = monomorphizeTypeNode(stmt.type, innerSf, templates, out, innerResolver);
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: resolvedTypeName ?? f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
explicitPresence: f.explicitPresence,
};
if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) {
return null;
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: f.isTypeParam ? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName) : f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
explicitPresence: f.explicitPresence,
};
});
out.set(mangledName, { name: mangledName, fields });
return mangledName;
const baseName = resolveImportedTypeName(typeNode.typeName.text);
const typeArgs = typeNode.typeArguments;
if (!typeArgs || typeArgs.length === 0) {
return baseName;
} // already concrete
const tpl = templates.get(baseName);
if (!tpl || typeArgs.length !== tpl.typeParams.length) {
return null;
}
const mangledName = typeNodeToMangledName(typeNode, sf, resolveImportedTypeName);
if (out.has(mangledName)) {
return mangledName;
} // already done
// Resolve each type parameter → both mangled name AND source text.
const paramMap = new Map<string, ResolvedTypeArg>();
for (let i = 0; i < tpl.typeParams.length; i++) {
const resolved = resolveTypeArg(typeArgs[i], sf, templates, out, resolveImportedTypeName);
if (!resolved) {
return null;
}
paramMap.set(tpl.typeParams[i], resolved);
}
// Substitute type params in template fields.
const fields: ProtobufField[] = tpl.fields.map((f) => {
if (f.genericTypeArgText) {
// Field type is an inner generic instantiation referencing template
// type params (e.g. `pb<N, Wrapper<U>>`). Substitute the params into
// the captured text, re-parse, and re-monomorphize so the resulting
// concrete instantiation (`Wrapper<uint_32>`) lands in `out`.
let substituted = f.genericTypeArgText;
for (const [paramName, value] of paramMap) {
substituted = substituted.replace(
new RegExp(`\\b${paramName}\\b`, 'g'),
value.text,
);
}
const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName;
const innerSf = ts.createSourceFile(
innerSfPath,
`type __X = ${substituted};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = innerSf.statements[0];
let resolvedTypeName: string | null = null;
if (ts.isTypeAliasDeclaration(stmt)) {
const innerResolver = createImportedTypeNameResolver(innerSf);
resolvedTypeName = monomorphizeTypeNode(
stmt.type,
innerSf,
templates,
out,
innerResolver,
);
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: resolvedTypeName ?? f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
explicitPresence: f.explicitPresence,
};
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: f.isTypeParam
? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName)
: f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
explicitPresence: f.explicitPresence,
};
});
out.set(mangledName, { name: mangledName, fields });
return mangledName;
}
function resolveTypeArg(
node: ts.TypeNode,
sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver,
node: ts.TypeNode,
sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver,
): ResolvedTypeArg | null {
const effectiveSf = resolveSourceFileForTypeNode(node, sf);
// Try recursive monomorphization first (handles nested generics).
const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName);
if (mono) return { mangled: mono, text: node.getText(effectiveSf) };
// Keyword type (string, number, …)
if (isKeywordTypeNode(node)) {
const text = node.getText(effectiveSf);
return { mangled: text, text };
}
// Simple identifier (uint_32, SomeMsg, …)
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) {
const name = resolveImportedTypeName(node.typeName.text);
return { mangled: name, text: name };
}
return null;
const effectiveSf = resolveSourceFileForTypeNode(node, sf);
// Try recursive monomorphization first (handles nested generics).
const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName);
if (mono) {
return { mangled: mono, text: node.getText(effectiveSf) };
}
// Keyword type (string, number, …)
if (isKeywordTypeNode(node)) {
const text = node.getText(effectiveSf);
return { mangled: text, text };
}
// Simple identifier (uint_32, SomeMsg, …)
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) {
const name = resolveImportedTypeName(node.typeName.text);
return { mangled: name, text: name };
}
return null;
}
+58 -58
View File
@@ -1,80 +1,80 @@
export enum WireType {
Varint = 0,
Bit64 = 1,
LengthDelim = 2,
Bit32 = 5,
Varint = 0,
Bit64 = 1,
LengthDelim = 2,
Bit32 = 5,
}
export interface ProtobufField {
name: string;
fieldNumber: number;
typeName: string;
wireType: WireType;
isMessage: boolean;
isOptional: boolean;
isRepeated: boolean;
/**
* Explicit presence (proto3 `optional`), set only by the `pb_optional<>`
* marker. When true, a scalar field serialises even at its zero/default
* value. Distinct from `isOptional` (which merely tracks the TS `?` and is
* true for almost every field) — the encoder keys off THIS flag, never
* `isOptional`, so existing `pb<>` fields are unaffected.
*/
explicitPresence: boolean;
name: string;
fieldNumber: number;
typeName: string;
wireType: WireType;
isMessage: boolean;
isOptional: boolean;
isRepeated: boolean;
/**
* Explicit presence (proto3 `optional`), set only by the `pb_optional<>`
* marker. When true, a scalar field serialises even at its zero/default
* value. Distinct from `isOptional` (which merely tracks the TS `?` and is
* true for almost every field) — the encoder keys off THIS flag, never
* `isOptional`, so existing `pb<>` fields are unaffected.
*/
explicitPresence: boolean;
}
export interface ProtobufMessage {
name: string;
fields: ProtobufField[];
name: string;
fields: ProtobufField[];
}
/** Generic interface template, e.g. `interface Wrapper<T> { val: pb<1, T>; }` */
export interface GenericProtobufTemplate {
name: string;
typeParams: string[];
fields: GenericFieldTemplate[];
name: string;
typeParams: string[];
fields: GenericFieldTemplate[];
}
export interface GenericFieldTemplate {
name: string;
fieldNumber: number;
rawTypeName: string;
isTypeParam: boolean;
isOptional: boolean;
isRepeated: boolean;
/** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */
explicitPresence: boolean;
/**
* For fields whose type-arg is itself a generic instantiation
* (e.g. `wrapped: pb<5, Wrapper<U>>` where `U` is a template type
* parameter), the original type-arg source text. At monomorphization
* time the substituted text is re-parsed and re-instantiated so
* `Wrapper<uint_32>` ends up in the registry under its mangled name.
*/
genericTypeArgText?: string;
/** Source-file path captured alongside `genericTypeArgText`, used as
* the synthetic file name when re-parsing the substituted text. */
genericTypeArgSourceFilePath?: string;
name: string;
fieldNumber: number;
rawTypeName: string;
isTypeParam: boolean;
isOptional: boolean;
isRepeated: boolean;
/** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */
explicitPresence: boolean;
/**
* For fields whose type-arg is itself a generic instantiation
* (e.g. `wrapped: pb<5, Wrapper<U>>` where `U` is a template type
* parameter), the original type-arg source text. At monomorphization
* time the substituted text is re-parsed and re-instantiated so
* `Wrapper<uint_32>` ends up in the registry under its mangled name.
*/
genericTypeArgText?: string;
/** Source-file path captured alongside `genericTypeArgText`, used as
* the synthetic file name when re-parsing the substituted text. */
genericTypeArgSourceFilePath?: string;
}
export type MessageRegistry = Map<string, ProtobufMessage>;
export const PRIMITIVE_TYPE_MAP: Record<string, { wireType: WireType; defaultValue: string }> = {
uint_32: { wireType: WireType.Varint, defaultValue: '0' },
int_32: { wireType: WireType.Varint, defaultValue: '0' },
uint_64: { wireType: WireType.Varint, defaultValue: '0' },
int_64: { wireType: WireType.Varint, defaultValue: '0' },
sint_32: { wireType: WireType.Varint, defaultValue: '0' },
sint_64: { wireType: WireType.Varint, defaultValue: '0' },
bool: { wireType: WireType.Varint, defaultValue: 'false' },
string: { wireType: WireType.LengthDelim, defaultValue: '""' },
bytes: { wireType: WireType.LengthDelim, defaultValue: 'new Uint8Array(0)' },
float: { wireType: WireType.Bit32, defaultValue: '0' },
double: { wireType: WireType.Bit64, defaultValue: '0' },
fixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
fixed_64: { wireType: WireType.Bit64, defaultValue: '0' },
sfixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
sfixed_64: { wireType: WireType.Bit64, defaultValue: '0' },
uint_32: { wireType: WireType.Varint, defaultValue: '0' },
int_32: { wireType: WireType.Varint, defaultValue: '0' },
uint_64: { wireType: WireType.Varint, defaultValue: '0' },
int_64: { wireType: WireType.Varint, defaultValue: '0' },
sint_32: { wireType: WireType.Varint, defaultValue: '0' },
sint_64: { wireType: WireType.Varint, defaultValue: '0' },
bool: { wireType: WireType.Varint, defaultValue: 'false' },
string: { wireType: WireType.LengthDelim, defaultValue: '""' },
bytes: { wireType: WireType.LengthDelim, defaultValue: 'new Uint8Array(0)' },
float: { wireType: WireType.Bit32, defaultValue: '0' },
double: { wireType: WireType.Bit64, defaultValue: '0' },
fixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
fixed_64: { wireType: WireType.Bit64, defaultValue: '0' },
sfixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
sfixed_64: { wireType: WireType.Bit64, defaultValue: '0' },
};
/** Marker identifiers recognised in type references */
+57 -39
View File
@@ -3,7 +3,7 @@ import ts from 'typescript';
export type ImportedTypeNameResolver = (name: string) => string;
function identityImportedTypeName(name: string): string {
return name;
return name;
}
// Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in
@@ -13,47 +13,56 @@ function identityImportedTypeName(name: string): string {
const syntheticTypeSourceFiles = new WeakMap<ts.TypeNode, ts.SourceFile>();
export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void {
syntheticTypeSourceFiles.set(node, sf);
syntheticTypeSourceFiles.set(node, sf);
}
export function resolveSourceFileForTypeNode(node: ts.TypeNode, fallback: ts.SourceFile): ts.SourceFile {
return syntheticTypeSourceFiles.get(node) ?? fallback;
export function resolveSourceFileForTypeNode(
node: ts.TypeNode,
fallback: ts.SourceFile,
): ts.SourceFile {
return syntheticTypeSourceFiles.get(node) ?? fallback;
}
// TS 5.9+ removed ts.isKeywordTypeNode — manual kind-based check
const KEYWORD_TYPE_KINDS = new Set([
ts.SyntaxKind.StringKeyword,
ts.SyntaxKind.NumberKeyword,
ts.SyntaxKind.BooleanKeyword,
ts.SyntaxKind.AnyKeyword,
ts.SyntaxKind.VoidKeyword,
ts.SyntaxKind.UndefinedKeyword,
ts.SyntaxKind.NullKeyword,
ts.SyntaxKind.NeverKeyword,
ts.SyntaxKind.UnknownKeyword,
ts.SyntaxKind.BigIntKeyword,
ts.SyntaxKind.SymbolKeyword,
ts.SyntaxKind.ObjectKeyword,
ts.SyntaxKind.StringKeyword,
ts.SyntaxKind.NumberKeyword,
ts.SyntaxKind.BooleanKeyword,
ts.SyntaxKind.AnyKeyword,
ts.SyntaxKind.VoidKeyword,
ts.SyntaxKind.UndefinedKeyword,
ts.SyntaxKind.NullKeyword,
ts.SyntaxKind.NeverKeyword,
ts.SyntaxKind.UnknownKeyword,
ts.SyntaxKind.BigIntKeyword,
ts.SyntaxKind.SymbolKeyword,
ts.SyntaxKind.ObjectKeyword,
]);
export function isKeywordTypeNode(node: ts.Node): boolean {
return KEYWORD_TYPE_KINDS.has(node.kind);
return KEYWORD_TYPE_KINDS.has(node.kind);
}
export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver {
const localToImported = new Map<string, string>();
const localToImported = new Map<string, string>();
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
const bindings = stmt.importClause.namedBindings;
if (!bindings || !ts.isNamedImports(bindings)) continue;
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) {
continue;
}
for (const el of bindings.elements) {
localToImported.set(el.name.text, (el.propertyName ?? el.name).text);
const bindings = stmt.importClause.namedBindings;
if (!bindings || !ts.isNamedImports(bindings)) {
continue;
}
for (const el of bindings.elements) {
localToImported.set(el.name.text, (el.propertyName ?? el.name).text);
}
}
}
return (name: string) => localToImported.get(name) ?? name;
return (name: string) => localToImported.get(name) ?? name;
}
/**
@@ -67,19 +76,28 @@ export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeN
* the substituted type text rather than garbage from `sf`.
*/
export function typeNodeToMangledName(
typeNode: ts.TypeNode,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
typeNode: ts.TypeNode,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): string {
const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf);
if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
const base = resolveImportedTypeName(typeNode.typeName.text);
if (typeNode.typeArguments && typeNode.typeArguments.length > 0) {
const args = typeNode.typeArguments.map(a => typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName));
return base + '__' + args.join('__');
const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf);
if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
const base = resolveImportedTypeName(typeNode.typeName.text);
if (typeNode.typeArguments && typeNode.typeArguments.length > 0) {
const args = typeNode.typeArguments.map((a) =>
typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName),
);
return base + '__' + args.join('__');
}
return base;
}
return base;
}
if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf);
return typeNode.getText(effectiveSf);
if (isKeywordTypeNode(typeNode)) {
return typeNode.getText(effectiveSf);
}
return typeNode.getText(effectiveSf);
}
+193 -170
View File
@@ -1,207 +1,230 @@
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js';
import {
WireType,
PRIMITIVE_TYPE_MAP,
type ProtobufField,
type ProtobufMessage,
type MessageRegistry,
} from '../ast/types.js';
function tagValue(field: ProtobufField): number {
const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes'
? WireType.LengthDelim
: field.wireType;
return ((field.fieldNumber << 3) | wireType) >>> 0;
const wireType =
field.isMessage || field.typeName === 'string' || field.typeName === 'bytes'
? WireType.LengthDelim
: field.wireType;
return ((field.fieldNumber << 3) | wireType) >>> 0;
}
/** Emit inline varint decode, storing result in `varName`. */
function varintDec(varName: string, ind: string): string {
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint32(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint32(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
}
function varintDec64(varName: string, ind: string): string {
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint64(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint64(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
}
function varintDec32Value(varName: string, ind: string): string {
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint32Value(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint32Value(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
}
function isVarint64(typeName: string): boolean {
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
}
function isFixed64BigInt(typeName: string): boolean {
return typeName === 'fixed_64' || typeName === 'sfixed_64';
return typeName === 'fixed_64' || typeName === 'sfixed_64';
}
const INLINE_SKIP = ` offset = __skipUnknownField(data, offset, end, wireType, _tag >>> 3);`;
export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
const locals = msg.fields.map((field, index) => {
const keyword = field.isRepeated ? 'const' : 'let';
return ` ${keyword} _f${index} = ${getDefault(field)};`;
});
const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', ');
const locals = msg.fields.map((field, index) => {
const keyword = field.isRepeated ? 'const' : 'let';
return ` ${keyword} _f${index} = ${getDefault(field)};`;
});
const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', ');
const L = [
`function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`,
` if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(end) || offset < 0 || end < offset || end > data.length) {`,
` throw new Error('protobuf decoder bounds are invalid');`,
` }`,
...locals,
` let _unknownFields = null;`,
` let _unknownFieldsByKey = null;`,
` let _unknownTotalOccurrences = 0;`,
` let _unknownOmittedOccurrences = 0;`,
` let _unknownOmittedByteLength = 0;`,
` while (offset < end) {`,
` const _fieldStart = offset;`,
` const [_tag, _tagOffset] = __readVarint32(data, offset, end);`,
` offset = _tagOffset;`,
` if ((_tag >>> 3) === 0) throw new Error('protobuf field number 0 is invalid');`,
` switch (_tag) {`,
];
const L = [
`function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`,
` if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(end) || offset < 0 || end < offset || end > data.length) {`,
` throw new Error('protobuf decoder bounds are invalid');`,
` }`,
...locals,
` let _unknownFields = null;`,
` let _unknownFieldsByKey = null;`,
` let _unknownTotalOccurrences = 0;`,
` let _unknownOmittedOccurrences = 0;`,
` let _unknownOmittedByteLength = 0;`,
` while (offset < end) {`,
` const _fieldStart = offset;`,
` const [_tag, _tagOffset] = __readVarint32(data, offset, end);`,
` offset = _tagOffset;`,
` if ((_tag >>> 3) === 0) throw new Error('protobuf field number 0 is invalid');`,
` switch (_tag) {`,
];
msg.fields.forEach((field, index) => {
L.push(decodeField(field, index));
});
msg.fields.forEach((field, index) => {
L.push(decodeField(field, index));
});
L.push(
` default: {`,
` const _unknownStart = offset;`,
` const wireType = _tag & 0x7;`,
INLINE_SKIP,
` const _unknownFieldNumber = _tag >>> 3;`,
` const _unknownByteLength = offset - _unknownStart;`,
` const _unknownKey = (_unknownFieldNumber * 8) + wireType;`,
` _unknownTotalOccurrences++;`,
` const _knownUnknown = _unknownFieldsByKey?.get(_unknownKey);`,
` if (_knownUnknown) {`,
` _knownUnknown.count++;`,
` _knownUnknown.totalByteLength += _unknownByteLength;`,
` } else if ((_unknownFields?.length ?? 0) < 64) {`,
` const _unknown = {`,
` fieldNumber: _unknownFieldNumber,`,
` wireType,`,
` count: 1,`,
` totalByteLength: _unknownByteLength,`,
` };`,
` (_unknownFields ??= []).push(_unknown);`,
` (_unknownFieldsByKey ??= new Map()).set(_unknownKey, _unknown);`,
` } else {`,
` _unknownOmittedOccurrences++;`,
` _unknownOmittedByteLength += _unknownByteLength;`,
` }`,
` break;`,
` }`,
` }`,
` if (offset <= _fieldStart || offset > end) throw new Error('protobuf decoder made invalid progress');`,
` }`,
` const _result = { ${result} };`,
` if (_unknownTotalOccurrences > 0) Object.defineProperty(`,
` _result,`,
` Symbol.for('snowluma.proton.unknownFields'),`,
` {`,
` value: {`,
` fields: _unknownFields ?? [],`,
` totalOccurrences: _unknownTotalOccurrences,`,
` omittedOccurrences: _unknownOmittedOccurrences,`,
` omittedByteLength: _unknownOmittedByteLength,`,
` },`,
` enumerable: false,`,
` },`,
` );`,
` return _result;`,
`}`,
);
return L.join('\n');
L.push(
` default: {`,
` const _unknownStart = offset;`,
` const wireType = _tag & 0x7;`,
INLINE_SKIP,
` const _unknownFieldNumber = _tag >>> 3;`,
` const _unknownByteLength = offset - _unknownStart;`,
` const _unknownKey = (_unknownFieldNumber * 8) + wireType;`,
` _unknownTotalOccurrences++;`,
` const _knownUnknown = _unknownFieldsByKey?.get(_unknownKey);`,
` if (_knownUnknown) {`,
` _knownUnknown.count++;`,
` _knownUnknown.totalByteLength += _unknownByteLength;`,
` } else if ((_unknownFields?.length ?? 0) < 64) {`,
` const _unknown = {`,
` fieldNumber: _unknownFieldNumber,`,
` wireType,`,
` count: 1,`,
` totalByteLength: _unknownByteLength,`,
` };`,
` (_unknownFields ??= []).push(_unknown);`,
` (_unknownFieldsByKey ??= new Map()).set(_unknownKey, _unknown);`,
` } else {`,
` _unknownOmittedOccurrences++;`,
` _unknownOmittedByteLength += _unknownByteLength;`,
` }`,
` break;`,
` }`,
` }`,
` if (offset <= _fieldStart || offset > end) throw new Error('protobuf decoder made invalid progress');`,
` }`,
` const _result = { ${result} };`,
` if (_unknownTotalOccurrences > 0) Object.defineProperty(`,
` _result,`,
` Symbol.for('snowluma.proton.unknownFields'),`,
` {`,
` value: {`,
` fields: _unknownFields ?? [],`,
` totalOccurrences: _unknownTotalOccurrences,`,
` omittedOccurrences: _unknownOmittedOccurrences,`,
` omittedByteLength: _unknownOmittedByteLength,`,
` },`,
` enumerable: false,`,
` },`,
` );`,
` return _result;`,
`}`,
);
return L.join('\n');
}
function decodeField(field: ProtobufField, index: number): string {
const { typeName, wireType, isMessage, isRepeated } = field;
const I = ' ';
const local = `_f${index}`;
const assign = (expr: string) => isRepeated
? `${I}${local}.push(${expr});`
: `${I}${local} = ${expr};`;
const { typeName, wireType, isMessage, isRepeated } = field;
const I = ' ';
const local = `_f${index}`;
const assign = (expr: string) =>
isRepeated ? `${I}${local}.push(${expr});` : `${I}${local} = ${expr};`;
const L: string[] = [` case ${tagValue(field)}: {`];
const L: string[] = [` case ${tagValue(field)}: {`];
if (isMessage) {
L.push(varintDec('_len', I));
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`protobuf_decode_${typeName}(data, offset, _end)`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'string') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`__td.decode(data.subarray(offset, _end))`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bytes') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`data.slice(offset, _end)`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bool') {
L.push(varintDec('_val', I));
L.push(assign(`_val !== 0`));
} else if (isVarint64(typeName)) {
L.push(varintDec64('_val', I));
if (typeName === 'uint_64') {
L.push(assign(`_val`));
} else if (typeName === 'int_64') {
L.push(assign(`BigInt.asIntN(64, _val)`));
} else {
L.push(assign(`__zigZagDecode64(_val)`));
if (isMessage) {
L.push(varintDec('_len', I));
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`protobuf_decode_${typeName}(data, offset, _end)`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'string') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`__td.decode(data.subarray(offset, _end))`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bytes') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`data.slice(offset, _end)`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bool') {
L.push(varintDec('_val', I));
L.push(assign(`_val !== 0`));
} else if (isVarint64(typeName)) {
L.push(varintDec64('_val', I));
if (typeName === 'uint_64') {
L.push(assign(`_val`));
} else if (typeName === 'int_64') {
L.push(assign(`BigInt.asIntN(64, _val)`));
} else {
L.push(assign(`__zigZagDecode64(_val)`));
}
} else if (typeName === 'int_32') {
// Protobuf encodes negative int32 values as a sign-extended 10-byte
// varint. Read the full uint64 representation, then keep its signed low
// 32 bits.
L.push(varintDec64('_val', I));
L.push(assign(`Number(BigInt.asIntN(32, _val))`));
} else if (typeName === 'sint_32') {
L.push(varintDec('_val', I));
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
} else if (wireType === WireType.Varint) {
L.push(varintDec32Value('_val', I));
L.push(assign(`_val >>> 0`));
} else if (typeName === 'float') {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated float field');`);
L.push(assign(`__readFloat32(data, offset)`));
L.push(`${I}offset += 4;`);
} else if (wireType === WireType.Bit32) {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');`);
L.push(
assign(
`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`,
),
);
L.push(`${I}offset += 4;`);
} else if (typeName === 'double') {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated double field');`);
L.push(assign(`__readFloat64(data, offset)`));
L.push(`${I}offset += 8;`);
} else if (isFixed64BigInt(typeName)) {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`);
if (typeName === 'fixed_64') {
L.push(assign(`__readFixed64(data, offset)`));
} else {
L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`));
}
L.push(`${I}offset += 8;`);
} else if (wireType === WireType.Bit64) {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`);
L.push(
assign(
`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`,
),
);
L.push(`${I}offset += 8;`);
}
} else if (typeName === 'int_32') {
// Protobuf encodes negative int32 values as a sign-extended 10-byte
// varint. Read the full uint64 representation, then keep its signed low
// 32 bits.
L.push(varintDec64('_val', I));
L.push(assign(`Number(BigInt.asIntN(32, _val))`));
} else if (typeName === 'sint_32') {
L.push(varintDec('_val', I));
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
} else if (wireType === WireType.Varint) {
L.push(varintDec32Value('_val', I));
L.push(assign(`_val >>> 0`));
} else if (typeName === 'float') {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated float field');`);
L.push(assign(`__readFloat32(data, offset)`));
L.push(`${I}offset += 4;`);
} else if (wireType === WireType.Bit32) {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');`);
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 4;`);
} else if (typeName === 'double') {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated double field');`);
L.push(assign(`__readFloat64(data, offset)`));
L.push(`${I}offset += 8;`);
} else if (isFixed64BigInt(typeName)) {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`);
if (typeName === 'fixed_64') {
L.push(assign(`__readFixed64(data, offset)`));
} else {
L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`));
}
L.push(`${I}offset += 8;`);
} else if (wireType === WireType.Bit64) {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`);
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 8;`);
}
L.push(`${I}break;`, ` }`);
return L.join('\n');
L.push(`${I}break;`, ` }`);
return L.join('\n');
}
function getDefault(field: ProtobufField): string {
if (field.isRepeated) return '[]';
if (field.isOptional || field.isMessage) return 'null';
const primitive = PRIMITIVE_TYPE_MAP[field.typeName];
return primitive ? primitive.defaultValue : 'null';
if (field.isRepeated) {
return '[]';
}
if (field.isOptional || field.isMessage) {
return 'null';
}
const primitive = PRIMITIVE_TYPE_MAP[field.typeName];
return primitive ? primitive.defaultValue : 'null';
}
File diff suppressed because it is too large. Load diff
+12 -7
View File
@@ -236,11 +236,16 @@ function __readFixed64(data, offset) {
* No runtime imports needed — all wire-format logic is inlined.
*/
export function generateCode(registry: MessageRegistry): string {
if (registry.size === 0) return '';
const parts: string[] = [CODEGEN_PREAMBLE];
for (const msg of registry.values()) {
parts.push(generateEncoder(msg, registry));
parts.push(generateDecoder(msg, registry));
}
return parts.join('\n');
if (registry.size === 0) {
return '';
}
const parts: string[] = [CODEGEN_PREAMBLE];
for (const msg of registry.values()) {
parts.push(generateEncoder(msg, registry));
parts.push(generateDecoder(msg, registry));
}
return parts.join('\n');
}
+52 -29
View File
@@ -2,51 +2,74 @@
// The generated code no longer depends on these (everything is inlined).
export function encodeVarint(value: number, buf: number[]): void {
value = value >>> 0;
while (value > 0x7f) {
buf.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
buf.push(value & 0x7f);
value = value >>> 0;
while (value > 0x7f) {
buf.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
buf.push(value & 0x7f);
}
export function decodeVarint(data: Uint8Array, offset: number): [number, number] {
let result = 0;
let shift = 0;
let byte: number;
do {
byte = data[offset++];
result |= (byte & 0x7f) << shift;
shift += 7;
} while (byte & 0x80);
return [result >>> 0, offset];
let result = 0;
let shift = 0;
let byte: number;
do {
byte = data[offset++];
result |= (byte & 0x7f) << shift;
shift += 7;
} while (byte & 0x80);
return [result >>> 0, offset];
}
export function writeTag(fieldNumber: number, wireType: number, buf: number[]): void {
encodeVarint((fieldNumber << 3) | wireType, buf);
encodeVarint((fieldNumber << 3) | wireType, buf);
}
export function writeString(value: string, buf: number[]): void {
const encoded = new TextEncoder().encode(value);
encodeVarint(encoded.length, buf);
for (let i = 0; i < encoded.length; i++) buf.push(encoded[i]);
const encoded = new TextEncoder().encode(value);
encodeVarint(encoded.length, buf);
for (let i = 0; i < encoded.length; i++) {
buf.push(encoded[i]);
}
}
export function readString(data: Uint8Array, offset: number, length: number): string {
return new TextDecoder().decode(data.subarray(offset, offset + length));
return new TextDecoder().decode(data.subarray(offset, offset + length));
}
export function writeBytes(value: Uint8Array, buf: number[]): void {
encodeVarint(value.length, buf);
for (let i = 0; i < value.length; i++) buf.push(value[i]);
encodeVarint(value.length, buf);
for (let i = 0; i < value.length; i++) {
buf.push(value[i]);
}
}
export function skipField(data: Uint8Array, offset: number, wireType: number): number {
switch (wireType) {
case 0: while (data[offset] & 0x80) offset++; return offset + 1;
case 1: return offset + 8;
case 2: { const [len, o] = decodeVarint(data, offset); return o + len; }
case 5: return offset + 4;
default: throw new Error(`Unknown wire type: ${wireType}`);
}
switch (wireType) {
case 0:
while (data[offset] & 0x80) {
offset++;
}
return offset + 1;
case 1:
return offset + 8;
case 2: {
const [len, o] = decodeVarint(data, offset);
return o + len;
}
case 5:
return offset + 4;
default:
throw new Error(`Unknown wire type: ${wireType}`);
}
}
+103 -76
View File
@@ -1,5 +1,10 @@
import type { Plugin } from 'vite';
import { analyze, analyzeSource, selectUsedRegistry, typeNodeToMangledName } from './ast/analyzer.js';
import {
analyze,
analyzeSource,
selectUsedRegistry,
typeNodeToMangledName,
} from './ast/analyzer.js';
import { generateCode } from './codegen/generator.js';
import { applyReplacements, replaceCallSites } from './transform/replacer.js';
import type { MessageRegistry } from './ast/types.js';
@@ -7,107 +12,129 @@ import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
import { createRuntimeMap, type RuntimeMapCallSite } from './runtime-map.js';
export interface ProtobufRuntimeMapPluginOptions {
enabled?: boolean;
fileName?: string;
enabled?: boolean;
fileName?: string;
}
export interface ProtobufVitePluginOptions {
runtimeMap?: ProtobufRuntimeMapPluginOptions;
runtimeMap?: ProtobufRuntimeMapPluginOptions;
}
interface RuntimeMapFileEntry {
messages: MessageRegistry;
callSites: RuntimeMapCallSite[];
messages: MessageRegistry;
callSites: RuntimeMapCallSite[];
}
export default function protobufVitePlugin(options: ProtobufVitePluginOptions = {}): Plugin {
const fileCache = new Map<string, ParsedFileEntry>();
const runtimeMapByFile = new Map<string, RuntimeMapFileEntry>();
const runtimeMapEnabled = options.runtimeMap?.enabled === true;
const runtimeMapFileName = options.runtimeMap?.fileName ?? 'snowluma-proton.runtime-map.json';
const fileCache = new Map<string, ParsedFileEntry>();
const runtimeMapByFile = new Map<string, RuntimeMapFileEntry>();
const runtimeMapEnabled = options.runtimeMap?.enabled === true;
const runtimeMapFileName = options.runtimeMap?.fileName ?? 'snowluma-proton.runtime-map.json';
return {
name: 'vite-plugin-protobuf',
enforce: 'pre',
return {
name: 'vite-plugin-protobuf',
enforce: 'pre',
transform(code, id) {
const cleanId = id.split('?')[0];
if (!cleanId.endsWith('.ts') || cleanId.endsWith('.d.ts')) return null;
transform(code, id) {
const cleanId = id.split('?')[0];
const imported = resolveImports(code, cleanId, fileCache);
const { registry, callSites, sourceFile } = analyze(code, cleanId, imported);
if (registry.size === 0 && callSites.length === 0) return null;
if (!cleanId.endsWith('.ts') || cleanId.endsWith('.d.ts')) {
return null;
}
const used = selectUsedRegistry(registry, callSites, sourceFile);
if (used.registry.size === 0) {
runtimeMapByFile.delete(cleanId);
return null;
}
const imported = resolveImports(code, cleanId, fileCache);
const { registry, callSites, sourceFile } = analyze(code, cleanId, imported);
if (runtimeMapEnabled) {
runtimeMapByFile.set(cleanId, {
messages: used.registry,
callSites: used.callSites.map(cs => ({
file: cleanId,
line: cs.line,
column: cs.column,
fnName: cs.fnName as RuntimeMapCallSite['fnName'],
typeName: cs.typeName,
})),
});
}
if (registry.size === 0 && callSites.length === 0) {
return null;
}
const generatedCode = generateCode(used.registry);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
if (!hasReplacements && generatedCode === '') return null;
const used = selectUsedRegistry(registry, callSites, sourceFile);
return { code: generatedCode + '\n' + transformedCode, map: null };
},
if (used.registry.size === 0) {
runtimeMapByFile.delete(cleanId);
return null;
}
handleHotUpdate({ file }) {
if (file.endsWith('.ts')) {
fileCache.delete(file);
runtimeMapByFile.delete(file);
}
},
if (runtimeMapEnabled) {
runtimeMapByFile.set(cleanId, {
messages: used.registry,
callSites: used.callSites.map((cs) => ({
file: cleanId,
line: cs.line,
column: cs.column,
fnName: cs.fnName as RuntimeMapCallSite['fnName'],
typeName: cs.typeName,
})),
});
}
generateBundle() {
if (!runtimeMapEnabled) return;
const generatedCode = generateCode(used.registry);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
used.registry,
);
const mergedMessages: MessageRegistry = new Map();
const mergedCallSites: RuntimeMapCallSite[] = [];
if (!hasReplacements && generatedCode === '') {
return null;
}
for (const entry of runtimeMapByFile.values()) {
for (const [name, msg] of entry.messages) mergedMessages.set(name, msg);
mergedCallSites.push(...entry.callSites);
}
return { code: generatedCode + '\n' + transformedCode, map: null };
},
if (mergedMessages.size === 0 || mergedCallSites.length === 0) return;
handleHotUpdate({ file }) {
if (file.endsWith('.ts')) {
fileCache.delete(file);
runtimeMapByFile.delete(file);
}
},
const runtimeMap = createRuntimeMap({
messages: mergedMessages,
callSites: mergedCallSites,
});
generateBundle() {
if (!runtimeMapEnabled) {
return;
}
this.emitFile({
type: 'asset',
fileName: runtimeMapFileName,
source: JSON.stringify(runtimeMap, null, 2),
});
},
};
const mergedMessages: MessageRegistry = new Map();
const mergedCallSites: RuntimeMapCallSite[] = [];
for (const entry of runtimeMapByFile.values()) {
for (const [name, msg] of entry.messages) {
mergedMessages.set(name, msg);
}
mergedCallSites.push(...entry.callSites);
}
if (mergedMessages.size === 0 || mergedCallSites.length === 0) {
return;
}
const runtimeMap = createRuntimeMap({
messages: mergedMessages,
callSites: mergedCallSites,
});
this.emitFile({
type: 'asset',
fileName: runtimeMapFileName,
source: JSON.stringify(runtimeMap, null, 2),
});
},
};
}
export {
analyze,
analyzeSource,
generateCode,
replaceCallSites,
applyReplacements,
typeNodeToMangledName,
resolveImports,
selectUsedRegistry,
createRuntimeMap,
analyze,
analyzeSource,
generateCode,
replaceCallSites,
applyReplacements,
typeNodeToMangledName,
resolveImports,
selectUsedRegistry,
createRuntimeMap,
};
export type { ProtobufRuntimeMap, RuntimeMapCallSite } from './runtime-map.js';
+51 -45
View File
@@ -3,70 +3,76 @@ import type { MessageRegistry, ProtobufField, ProtobufMessage } from './ast/type
export type RuntimeMapFnName = 'protobuf_encode' | 'protobuf_decode';
export interface RuntimeMapCallSite {
file: string;
line: number;
column: number;
fnName: RuntimeMapFnName;
typeName: string;
file: string;
line: number;
column: number;
fnName: RuntimeMapFnName;
typeName: string;
}
export interface ProtobufRuntimeMap {
version: 1;
messages: ProtobufMessage[];
callSites: RuntimeMapCallSite[];
version: 1;
messages: ProtobufMessage[];
callSites: RuntimeMapCallSite[];
}
function cloneField(field: ProtobufField): ProtobufField {
return {
name: field.name,
fieldNumber: field.fieldNumber,
typeName: field.typeName,
wireType: field.wireType,
isMessage: field.isMessage,
isOptional: field.isOptional,
isRepeated: field.isRepeated,
explicitPresence: field.explicitPresence ?? false,
};
return {
name: field.name,
fieldNumber: field.fieldNumber,
typeName: field.typeName,
wireType: field.wireType,
isMessage: field.isMessage,
isOptional: field.isOptional,
isRepeated: field.isRepeated,
explicitPresence: field.explicitPresence ?? false,
};
}
function cloneMessage(msg: ProtobufMessage): ProtobufMessage {
return {
name: msg.name,
fields: msg.fields.map(cloneField),
};
return {
name: msg.name,
fields: msg.fields.map(cloneField),
};
}
export function registryToRuntimeMapMessages(registry: MessageRegistry): ProtobufMessage[] {
return [...registry.values()].map(cloneMessage);
return [...registry.values()].map(cloneMessage);
}
export function runtimeMapToRegistry(map: ProtobufRuntimeMap): MessageRegistry {
const registry: MessageRegistry = new Map();
for (const msg of map.messages) {
registry.set(msg.name, cloneMessage(msg));
}
return registry;
const registry: MessageRegistry = new Map();
for (const msg of map.messages) {
registry.set(msg.name, cloneMessage(msg));
}
return registry;
}
export function normalizeRuntimeMapPath(filePath: string): string {
const noQuery = filePath.replace(/[?#].*$/, '');
return noQuery.replace(/\\/g, '/').replace(/^file:\/\//, '');
const noQuery = filePath.replace(/[?#].*$/, '');
return noQuery.replace(/\\/g, '/').replace(/^file:\/\//, '');
}
export function createRuntimeMap(map: { messages: MessageRegistry; callSites: RuntimeMapCallSite[] }): ProtobufRuntimeMap {
const dedupedCallSites = new Map<string, RuntimeMapCallSite>();
for (const cs of map.callSites) {
const normalized = {
...cs,
file: normalizeRuntimeMapPath(cs.file),
export function createRuntimeMap(map: {
messages: MessageRegistry;
callSites: RuntimeMapCallSite[];
}): ProtobufRuntimeMap {
const dedupedCallSites = new Map<string, RuntimeMapCallSite>();
for (const cs of map.callSites) {
const normalized = {
...cs,
file: normalizeRuntimeMapPath(cs.file),
};
const key = `${normalized.file}:${normalized.line}:${normalized.column}:${normalized.fnName}:${normalized.typeName}`;
dedupedCallSites.set(key, normalized);
}
return {
version: 1,
messages: registryToRuntimeMapMessages(map.messages),
callSites: [...dedupedCallSites.values()],
};
const key = `${normalized.file}:${normalized.line}:${normalized.column}:${normalized.fnName}:${normalized.typeName}`;
dedupedCallSites.set(key, normalized);
}
return {
version: 1,
messages: registryToRuntimeMapMessages(map.messages),
callSites: [...dedupedCallSites.values()],
};
}
+232 -152
View File
@@ -2,68 +2,79 @@ import { buildDependencyRegistry } from './ast/dependency-graph.js';
import type { MessageRegistry } from './ast/types.js';
import { generateCode } from './codegen/generator.js';
import {
normalizeRuntimeMapPath,
runtimeMapToRegistry,
type ProtobufRuntimeMap,
type RuntimeMapCallSite,
type RuntimeMapFnName,
normalizeRuntimeMapPath,
runtimeMapToRegistry,
type ProtobufRuntimeMap,
type RuntimeMapCallSite,
type RuntimeMapFnName,
} from './runtime-map.js';
type DynamicEncode = (params: unknown) => Uint8Array;
type DynamicDecode = (data: Uint8Array) => unknown;
export interface ProtobufUnknownField {
fieldNumber: number;
wireType: number;
count: number;
totalByteLength: number;
fieldNumber: number;
wireType: number;
count: number;
totalByteLength: number;
}
export interface ProtobufUnknownFieldMetadata {
fields: readonly ProtobufUnknownField[];
totalOccurrences: number;
omittedOccurrences: number;
omittedByteLength: number;
fields: readonly ProtobufUnknownField[];
totalOccurrences: number;
omittedOccurrences: number;
omittedByteLength: number;
}
const PROTOBUF_UNKNOWN_FIELDS = Symbol.for('snowluma.proton.unknownFields');
const EMPTY_UNKNOWN_FIELD_METADATA: ProtobufUnknownFieldMetadata = Object.freeze({
fields: Object.freeze([]),
totalOccurrences: 0,
omittedOccurrences: 0,
omittedByteLength: 0,
fields: Object.freeze([]),
totalOccurrences: 0,
omittedOccurrences: 0,
omittedByteLength: 0,
});
/** Unknown wire tags retained by generated decoders. The symbol-backed
* metadata is non-enumerable, so decoded object shapes and re-encoding remain
* unchanged while protocol boundaries can make schema drift observable. */
export function protobuf_getUnknownFields(value: unknown): readonly ProtobufUnknownField[] {
return protobuf_getUnknownFieldMetadata(value).fields;
return protobuf_getUnknownFieldMetadata(value).fields;
}
export function protobuf_getUnknownFieldMetadata(value: unknown): ProtobufUnknownFieldMetadata {
if (typeof value !== 'object' || value === null) return EMPTY_UNKNOWN_FIELD_METADATA;
const metadata = (value as Record<PropertyKey, unknown>)[PROTOBUF_UNKNOWN_FIELDS];
if (typeof metadata !== 'object' || metadata === null) return EMPTY_UNKNOWN_FIELD_METADATA;
const candidate = metadata as Partial<ProtobufUnknownFieldMetadata>;
if (!Array.isArray(candidate.fields)) return EMPTY_UNKNOWN_FIELD_METADATA;
return {
fields: candidate.fields,
totalOccurrences: candidate.totalOccurrences ?? candidate.fields.length,
omittedOccurrences: candidate.omittedOccurrences ?? 0,
omittedByteLength: candidate.omittedByteLength ?? 0,
};
if (typeof value !== 'object' || value === null) {
return EMPTY_UNKNOWN_FIELD_METADATA;
}
const metadata = (value as Record<PropertyKey, unknown>)[PROTOBUF_UNKNOWN_FIELDS];
if (typeof metadata !== 'object' || metadata === null) {
return EMPTY_UNKNOWN_FIELD_METADATA;
}
const candidate = metadata as Partial<ProtobufUnknownFieldMetadata>;
if (!Array.isArray(candidate.fields)) {
return EMPTY_UNKNOWN_FIELD_METADATA;
}
return {
fields: candidate.fields,
totalOccurrences: candidate.totalOccurrences ?? candidate.fields.length,
omittedOccurrences: candidate.omittedOccurrences ?? 0,
omittedByteLength: candidate.omittedByteLength ?? 0,
};
}
interface DynamicTypeFns {
encode?: DynamicEncode;
decode?: DynamicDecode;
encode?: DynamicEncode;
decode?: DynamicDecode;
}
interface StackFrame {
file: string;
line: number;
column: number;
file: string;
line: number;
column: number;
}
const DYNAMIC_MISS = Symbol('snowluma-proton-dynamic-miss');
@@ -78,180 +89,249 @@ const dynamicTypeCache = new Map<string, DynamicTypeFns>();
* This is disabled by default.
*/
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void {
runtimeMapFallback = map;
runtimeMapRegistry = runtimeMapToRegistry(map);
runtimeMapCallSites = map.callSites.map(cs => ({
...cs,
file: normalizeRuntimeMapPath(cs.file),
}));
dynamicTypeCache.clear();
runtimeMapFallback = map;
runtimeMapRegistry = runtimeMapToRegistry(map);
runtimeMapCallSites = map.callSites.map((cs) => ({
...cs,
file: normalizeRuntimeMapPath(cs.file),
}));
dynamicTypeCache.clear();
}
/** Disable dynamic runtime fallback and clear all generated function caches. */
export function protobuf_disableRuntimeMapFallback(): void {
runtimeMapFallback = null;
runtimeMapRegistry = null;
runtimeMapCallSites = [];
dynamicTypeCache.clear();
runtimeMapFallback = null;
runtimeMapRegistry = null;
runtimeMapCallSites = [];
dynamicTypeCache.clear();
}
export function protobuf_encode<T>(_params: T): Uint8Array {
const dynamic = tryDynamicInvoke('protobuf_encode', _params);
if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array;
const dynamic = tryDynamicInvoke('protobuf_encode', _params);
throw new Error(
'protobuf_encode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
);
if (dynamic !== DYNAMIC_MISS) {
return dynamic as Uint8Array;
}
throw new Error(
'protobuf_encode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
);
}
export function protobuf_decode<T>(_data: Uint8Array): T {
const dynamic = tryDynamicInvoke('protobuf_decode', _data);
if (dynamic !== DYNAMIC_MISS) return dynamic as T;
const dynamic = tryDynamicInvoke('protobuf_decode', _data);
throw new Error(
'protobuf_decode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
);
if (dynamic !== DYNAMIC_MISS) {
return dynamic as T;
}
throw new Error(
'protobuf_decode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
);
}
function tryDynamicInvoke(fnName: RuntimeMapFnName, payload: unknown): unknown {
if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) {
return DYNAMIC_MISS;
}
if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) {
return DYNAMIC_MISS;
}
const caller = getFirstUserFrame();
if (!caller) return DYNAMIC_MISS;
const caller = getFirstUserFrame();
const callSite = resolveCallSite(fnName, caller);
if (!callSite) return DYNAMIC_MISS;
if (!caller) {
return DYNAMIC_MISS;
}
const typeFns = ensureTypeFunctions(callSite.typeName);
if (!typeFns) return DYNAMIC_MISS;
const callSite = resolveCallSite(fnName, caller);
const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode;
if (typeof fn !== 'function') return DYNAMIC_MISS;
if (!callSite) {
return DYNAMIC_MISS;
}
return fn(payload as never);
const typeFns = ensureTypeFunctions(callSite.typeName);
if (!typeFns) {
return DYNAMIC_MISS;
}
const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode;
if (typeof fn !== 'function') {
return DYNAMIC_MISS;
}
return fn(payload as never);
}
function ensureTypeFunctions(typeName: string): DynamicTypeFns | null {
const cached = dynamicTypeCache.get(typeName);
if (cached) return cached;
if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null;
const cached = dynamicTypeCache.get(typeName);
const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]);
if (subset.size === 0) return null;
if (cached) {
return cached;
}
const generated = generateCode(subset);
if (!generated) return null;
if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) {
return null;
}
const factory = new Function(
`${generated}\nreturn {\n` +
` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` +
` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` +
`};`,
) as () => DynamicTypeFns;
const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]);
const compiled = factory();
dynamicTypeCache.set(typeName, compiled);
return compiled;
if (subset.size === 0) {
return null;
}
const generated = generateCode(subset);
if (!generated) {
return null;
}
const factory = new Function(
`${generated}\nreturn {\n` +
` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` +
` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` +
`};`,
) as () => DynamicTypeFns;
const compiled = factory();
dynamicTypeCache.set(typeName, compiled);
return compiled;
}
function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeMapCallSite | null {
const callerFile = normalizeRuntimeMapPath(caller.file);
const callerFile = normalizeRuntimeMapPath(caller.file);
const candidates = runtimeMapCallSites.filter(cs =>
cs.fnName === fnName &&
cs.line === caller.line &&
pathsLikelySame(callerFile, cs.file),
);
const candidates = runtimeMapCallSites.filter(
(cs) =>
cs.fnName === fnName && cs.line === caller.line && pathsLikelySame(callerFile, cs.file),
);
if (candidates.length === 0) return null;
if (candidates.length === 1) return candidates[0];
let best = candidates[0];
let bestDistance = Math.abs(best.column - caller.column);
for (let i = 1; i < candidates.length; i++) {
const dist = Math.abs(candidates[i].column - caller.column);
if (dist < bestDistance) {
best = candidates[i];
bestDistance = dist;
if (candidates.length === 0) {
return null;
}
}
return best;
if (candidates.length === 1) {
return candidates[0];
}
let best = candidates[0];
let bestDistance = Math.abs(best.column - caller.column);
for (let i = 1; i < candidates.length; i++) {
const dist = Math.abs(candidates[i].column - caller.column);
if (dist < bestDistance) {
best = candidates[i];
bestDistance = dist;
}
}
return best;
}
function getFirstUserFrame(): StackFrame | null {
const err = new Error();
if (!err.stack) return null;
const err = new Error();
const lines = err.stack.split('\n').slice(1);
for (const raw of lines) {
const frame = parseStackLine(raw);
if (!frame) continue;
if (!err.stack) {
return null;
}
const file = normalizeRuntimeMapPath(frame.file);
if (isRuntimeInternalFile(file)) continue;
const lines = err.stack.split('\n').slice(1);
return {
file,
line: frame.line,
column: frame.column,
};
}
for (const raw of lines) {
const frame = parseStackLine(raw);
return null;
if (!frame) {
continue;
}
const file = normalizeRuntimeMapPath(frame.file);
if (isRuntimeInternalFile(file)) {
continue;
}
return {
file,
line: frame.line,
column: frame.column,
};
}
return null;
}
function parseStackLine(line: string): StackFrame | null {
const trimmed = line.trim();
if (!trimmed) return null;
const trimmed = line.trim();
let location = trimmed;
const atPrefix = 'at ';
if (location.startsWith(atPrefix)) {
location = location.slice(atPrefix.length).trim();
}
if (!trimmed) {
return null;
}
const openParen = location.lastIndexOf('(');
if (openParen >= 0 && location.endsWith(')')) {
location = location.slice(openParen + 1, -1);
}
let location = trimmed;
const atPrefix = 'at ';
const lastColon = location.lastIndexOf(':');
if (lastColon < 0) return null;
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
if (secondLastColon < 0) return null;
if (location.startsWith(atPrefix)) {
location = location.slice(atPrefix.length).trim();
}
const file = location.slice(0, secondLastColon);
const linePart = location.slice(secondLastColon + 1, lastColon);
const colPart = location.slice(lastColon + 1);
const openParen = location.lastIndexOf('(');
const parsedLine = Number(linePart);
const parsedCol = Number(colPart);
if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) return null;
if (openParen >= 0 && location.endsWith(')')) {
location = location.slice(openParen + 1, -1);
}
return {
file,
line: parsedLine,
column: parsedCol,
};
const lastColon = location.lastIndexOf(':');
if (lastColon < 0) {
return null;
}
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
if (secondLastColon < 0) {
return null;
}
const file = location.slice(0, secondLastColon);
const linePart = location.slice(secondLastColon + 1, lastColon);
const colPart = location.slice(lastColon + 1);
const parsedLine = Number(linePart);
const parsedCol = Number(colPart);
if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) {
return null;
}
return {
file,
line: parsedLine,
column: parsedCol,
};
}
function isRuntimeInternalFile(file: string): boolean {
return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js');
return (
file.endsWith('/runtime.ts') ||
file.endsWith('/runtime.js') ||
file.includes('/dist/runtime.js')
);
}
function pathsLikelySame(a: string, b: string): boolean {
if (a === b) return true;
const aBase = basename(a);
const bBase = basename(b);
return aBase !== '' && aBase === bBase;
if (a === b) {
return true;
}
const aBase = basename(a);
const bBase = basename(b);
return aBase !== '' && aBase === bBase;
}
function basename(file: string): string {
const normalized = normalizeRuntimeMapPath(file);
const idx = normalized.lastIndexOf('/');
return idx >= 0 ? normalized.slice(idx + 1) : normalized;
const normalized = normalizeRuntimeMapPath(file);
const idx = normalized.lastIndexOf('/');
return idx >= 0 ? normalized.slice(idx + 1) : normalized;
}
+53 -35
View File
@@ -4,58 +4,76 @@ import { createImportedTypeNameResolver, typeNodeToMangledName } from '../ast/ut
import { collectProtobufImportBindings, matchProtobufCallSite } from '../ast/callsite.js';
import ts from 'typescript';
interface TextEdit { start: number; end: number; replacement: string }
interface TextEdit {
start: number;
end: number;
replacement: string;
}
/**
* Apply replacements using pre-recorded call-sites from analyze().
* No parsing or AST walking — just position-based string edits.
*/
export function applyReplacements(
code: string,
sf: ts.SourceFile,
callSites: CallSiteRecord[],
registry: MessageRegistry,
code: string,
sf: ts.SourceFile,
callSites: CallSiteRecord[],
registry: MessageRegistry,
): { transformedCode: string; hasReplacements: boolean } {
const edits: TextEdit[] = [];
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
const edits: TextEdit[] = [];
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
for (const cs of callSites) {
const mangled = typeNodeToMangledName(cs.firstTypeArg, sf, resolveImportedTypeName);
if (registry.has(mangled)) {
edits.push({
start: cs.exprStart,
end: cs.typeArgsEnd,
replacement: `${cs.fnName}_${mangled}`,
});
for (const cs of callSites) {
const mangled = typeNodeToMangledName(cs.firstTypeArg, sf, resolveImportedTypeName);
if (registry.has(mangled)) {
edits.push({
start: cs.exprStart,
end: cs.typeArgsEnd,
replacement: `${cs.fnName}_${mangled}`,
});
}
}
}
if (!edits.length) return { transformedCode: code, hasReplacements: false };
if (!edits.length) {
return { transformedCode: code, hasReplacements: false };
}
edits.sort((a, b) => b.start - a.start);
let result = code;
for (const ed of edits) result = result.slice(0, ed.start) + ed.replacement + result.slice(ed.end);
return { transformedCode: result, hasReplacements: true };
edits.sort((a, b) => b.start - a.start);
let result = code;
for (const ed of edits) {
result = result.slice(0, ed.start) + ed.replacement + result.slice(ed.end);
}
return { transformedCode: result, hasReplacements: true };
}
/**
* Backward-compatible: parses + walks on its own.
* Prefer applyReplacements() with pre-recorded call-sites from analyze().
*/
export function replaceCallSites(code: string, registry: MessageRegistry): { transformedCode: string; hasReplacements: boolean } {
const sf = ts.createSourceFile('input.ts', code, ts.ScriptTarget.Latest, true);
const callSites: CallSiteRecord[] = [];
const importBindings = collectProtobufImportBindings(sf);
export function replaceCallSites(
code: string,
registry: MessageRegistry,
): { transformedCode: string; hasReplacements: boolean } {
const sf = ts.createSourceFile('input.ts', code, ts.ScriptTarget.Latest, true);
const callSites: CallSiteRecord[] = [];
const importBindings = collectProtobufImportBindings(sf);
ts.forEachChild(sf, function visit(node) {
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) callSites.push(cs);
}
ts.forEachChild(node, visit);
});
ts.forEachChild(sf, function visit(node) {
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
return applyReplacements(code, sf, callSites, registry);
if (cs) {
callSites.push(cs);
}
}
ts.forEachChild(node, visit);
});
return applyReplacements(code, sf, callSites, registry);
}
+151 -127
View File
@@ -4,142 +4,166 @@ 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,
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,
});
});
const wrapper = registry.get('Wrapper__uint_32')!;
expect(wrapper.fields[0]).toMatchObject({
name: 'value',
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('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 = `
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(() => analyzeSource(source, 'b.ts')).toThrow(/MissingType/);
});
expect(aliased.fields[1]).toMatchObject({
name: 'tags',
fieldNumber: 2,
typeName: 'string',
isRepeated: true,
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,
});
});
});
});
+301 -241
View File
@@ -11,332 +11,392 @@ 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 };
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 ──────────
// ── 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);
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);
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 { 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');
});
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);
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 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');
});
`,
'__r',
);
expect(result.id).toBe(42);
expect(result.name).toBe('alice');
});
// ── Scenario B: imported type as pb<> field ──────────────────────
// ── 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);
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);
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 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);
});
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);
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 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);
});
`,
'__r',
);
expect(result.inner.value).toBe(42);
});
// ── Generic template import ──────────────────────────────────────
// ── 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);
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);
expect(imported.templates.has('Wrapper')).toBe(true);
const registry = analyzeSource(code, path, imported);
expect(registry.has('Wrapper__string')).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);
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 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');
});
`,
'__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);
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);
expect(imported.templates.has('Wrapper')).toBe(true);
const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile);
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');
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(');
});
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);
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);
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);
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>>');
});
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);
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);
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.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(');
});
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);
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);
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);
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>>');
});
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);
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);
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);
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>');
});
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 ───────────────────────────────────────────
// ── 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);
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);
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);
});
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);
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 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);
});
`,
'__r',
);
expect(result.nested.inner.val).toBe(99);
});
// ── Cache behavior ───────────────────────────────────────────────
// ── Cache behavior ───────────────────────────────────────────────
it('uses cache on repeated resolves', () => {
const { code, path } = loadCross('consumer.ts');
const cache = new Map<string, ParsedFileEntry>();
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);
resolveImports(code, path, cache);
expect(cache.size).toBeGreaterThan(0);
const cached = new Map(cache);
resolveImports(code, path, cache);
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));
}
});
// Same entries, not re-created
for (const [key, val] of cache) {
expect(val).toBe(cached.get(key));
}
});
// ── Graceful fallback ────────────────────────────────────────────
// ── 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>();
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);
});
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 = `
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 fakePath = resolve(crossDir, 'on-demand.ts');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, fakePath, cache);
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);
});
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) ───────────────────────────────
// ── 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);
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);
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 { 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(');
});
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);
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 result = execAndGet<any>(
gen +
`\n
const enc = protobuf_encode_SimpleMessage({ id: 42 });
globalThis.__r = protobuf_decode_SimpleMessage(enc);
`, '__r');
expect(result.id).toBe(42);
});
`,
'__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);
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);
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');
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(');
});
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(');
});
});
@@ -30,147 +30,159 @@ import { resolveImports, type ParsedFileEntry } from '../../src/ast/import-resol
import { execAndGet } from '../helpers';
describe('cross-package import resolution (bare specifier)', () => {
let tmpRoot: string;
let consumerPath: string;
let tmpRoot: string;
let consumerPath: string;
beforeAll(() => {
// Build a tiny fake monorepo layout:
//
// <tmp>/
// consumer.ts ← uses `import { RemoteMsg } from '@fake/proto-defs'`
// node_modules/
// @fake/
// proto-defs/
// package.json ← exports → ./src/index.ts
// src/
// index.ts ← exported interfaces
//
// Bundler-mode `ts.resolveModuleName` walks importer → parent
// dirs looking for `node_modules`, so placing the consumer at
// `<tmp>/consumer.ts` lets `<tmp>/node_modules/...` satisfy the
// lookup.
tmpRoot = mkdtempSync(join(tmpdir(), 'proton-cross-pkg-'));
beforeAll(() => {
// Build a tiny fake monorepo layout:
//
// <tmp>/
// consumer.ts ← uses `import { RemoteMsg } from '@fake/proto-defs'`
// node_modules/
// @fake/
// proto-defs/
// package.json ← exports → ./src/index.ts
// src/
// index.ts ← exported interfaces
//
// Bundler-mode `ts.resolveModuleName` walks importer → parent
// dirs looking for `node_modules`, so placing the consumer at
// `<tmp>/consumer.ts` lets `<tmp>/node_modules/...` satisfy the
// lookup.
tmpRoot = mkdtempSync(join(tmpdir(), 'proton-cross-pkg-'));
const pkgDir = resolve(tmpRoot, 'node_modules', '@fake', 'proto-defs');
mkdirSync(resolve(pkgDir, 'src'), { recursive: true });
const pkgDir = resolve(tmpRoot, 'node_modules', '@fake', 'proto-defs');
mkdirSync(resolve(pkgDir, 'src'), { recursive: true });
// `exports."."` must point at a `.ts` source file — proton walks
// interface AST nodes to collect `pb<…>` field tags, and a
// generated `.d.ts` typically strips those generic args. Telling
// consumers to ship source `.ts` is the same model
// `@snowluma/proton` itself uses (`"default": "./src/runtime.ts"`).
writeFileSync(
resolve(pkgDir, 'package.json'),
JSON.stringify({
name: '@fake/proto-defs',
version: '1.0.0',
type: 'module',
main: './src/index.ts',
types: './src/index.ts',
exports: {
'.': {
types: './src/index.ts',
default: './src/index.ts',
},
},
}, null, 2),
);
// `exports."."` must point at a `.ts` source file — proton walks
// interface AST nodes to collect `pb<…>` field tags, and a
// generated `.d.ts` typically strips those generic args. Telling
// consumers to ship source `.ts` is the same model
// `@snowluma/proton` itself uses (`"default": "./src/runtime.ts"`).
writeFileSync(
resolve(pkgDir, 'package.json'),
JSON.stringify(
{
name: '@fake/proto-defs',
version: '1.0.0',
type: 'module',
main: './src/index.ts',
types: './src/index.ts',
exports: {
'.': {
types: './src/index.ts',
default: './src/index.ts',
},
},
},
null,
2,
),
);
writeFileSync(
resolve(pkgDir, 'src', 'index.ts'),
// proton's `collectInterface` recognises `pb<N, T>` as a marker
// type by NAME — no actual import of `@snowluma/proton` is
// needed for the fixture to parse. Matches the existing
// cross-file fixtures (`fixtures/cross-file/types.ts` does the
// same).
'export interface RemoteMsg {\n' +
' id?: pb<1, uint_32>;\n' +
' name?: pb<2, string>;\n' +
'}\n',
);
writeFileSync(
resolve(pkgDir, 'src', 'index.ts'),
// proton's `collectInterface` recognises `pb<N, T>` as a marker
// type by NAME — no actual import of `@snowluma/proton` is
// needed for the fixture to parse. Matches the existing
// cross-file fixtures (`fixtures/cross-file/types.ts` does the
// same).
'export interface RemoteMsg {\n' +
' id?: pb<1, uint_32>;\n' +
' name?: pb<2, string>;\n' +
'}\n',
);
consumerPath = resolve(tmpRoot, 'consumer.ts');
writeFileSync(
consumerPath,
'import type { RemoteMsg } from \'@fake/proto-defs\';\n' +
'\n' +
'const buf = protobuf_encode<RemoteMsg>({ id: 42, name: \'alice\' });\n' +
'const decoded = protobuf_decode<RemoteMsg>(buf);\n' +
'\n' +
'export { buf, decoded };\n',
);
});
consumerPath = resolve(tmpRoot, 'consumer.ts');
writeFileSync(
consumerPath,
"import type { RemoteMsg } from '@fake/proto-defs';\n" +
'\n' +
"const buf = protobuf_encode<RemoteMsg>({ id: 42, name: 'alice' });\n" +
'const decoded = protobuf_decode<RemoteMsg>(buf);\n' +
'\n' +
'export { buf, decoded };\n',
);
});
afterAll(() => {
if (tmpRoot) rmSync(tmpRoot, { recursive: true, force: true });
});
afterAll(() => {
if (tmpRoot) {
rmSync(tmpRoot, { recursive: true, force: true });
}
});
it('collects interfaces from a `@fake/proto-defs` bare-specifier import', () => {
// Smoke test: the import resolver MUST find the package and pick
// up `RemoteMsg`. If this fails, `ts.resolveModuleName` likely
// can't find the fake node_modules layout (check that the
// BARE_SPECIFIER_COMPILER_OPTIONS in import-resolver.ts still
// sets `moduleResolution: Bundler`).
const code = readFileSync(consumerPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, consumerPath, cache);
it('collects interfaces from a `@fake/proto-defs` bare-specifier import', () => {
// Smoke test: the import resolver MUST find the package and pick
// up `RemoteMsg`. If this fails, `ts.resolveModuleName` likely
// can't find the fake node_modules layout (check that the
// BARE_SPECIFIER_COMPILER_OPTIONS in import-resolver.ts still
// sets `moduleResolution: Bundler`).
const code = readFileSync(consumerPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, consumerPath, cache);
expect(imported.concrete.some(m => m.name === 'RemoteMsg')).toBe(true);
});
expect(imported.concrete.some((m) => m.name === 'RemoteMsg')).toBe(true);
});
it('rewrites encode/decode call sites against the imported type', () => {
const code = readFileSync(consumerPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, consumerPath, cache);
it('rewrites encode/decode call sites against the imported type', () => {
const code = readFileSync(consumerPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, consumerPath, cache);
const { registry, callSites, sourceFile } = analyze(code, consumerPath, imported);
expect(registry.has('RemoteMsg')).toBe(true);
const { registry, callSites, sourceFile } = analyze(code, consumerPath, imported);
expect(registry.has('RemoteMsg')).toBe(true);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_RemoteMsg');
expect(transformedCode).toContain('protobuf_decode_RemoteMsg');
});
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
registry,
);
expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_RemoteMsg');
expect(transformedCode).toContain('protobuf_decode_RemoteMsg');
});
it('round-trips encode/decode of a bare-specifier-imported message', () => {
// End-to-end: parse → analyze → generate codec → encode →
// decode → assert payload survived. The same shape as
// cross-file.test.ts's "Scenario A round-trip", but with the
// type sourced from a separate package.
const code = readFileSync(consumerPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, consumerPath, cache);
const registry = analyzeSource(code, consumerPath, imported);
const gen = generateCode(registry);
it('round-trips encode/decode of a bare-specifier-imported message', () => {
// End-to-end: parse → analyze → generate codec → encode →
// decode → assert payload survived. The same shape as
// cross-file.test.ts's "Scenario A round-trip", but with the
// type sourced from a separate package.
const code = readFileSync(consumerPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, consumerPath, cache);
const registry = analyzeSource(code, consumerPath, imported);
const gen = generateCode(registry);
const result = execAndGet<{ id: number; name: string }>(
gen + '\n' +
'const enc = protobuf_encode_RemoteMsg({ id: 42, name: \'alice\' });\n' +
'globalThis.__r = protobuf_decode_RemoteMsg(enc);\n',
'__r',
);
expect(result.id).toBe(42);
expect(result.name).toBe('alice');
});
const result = execAndGet<{ id: number; name: string }>(
gen +
'\n' +
"const enc = protobuf_encode_RemoteMsg({ id: 42, name: 'alice' });\n" +
'globalThis.__r = protobuf_decode_RemoteMsg(enc);\n',
'__r',
);
expect(result.id).toBe(42);
expect(result.name).toBe('alice');
});
it('returns null for an unresolvable bare specifier (does not throw)', () => {
// Pre-existing relative-path behavior: missing files return
// null, never throw. The bare-specifier branch must match that
// — otherwise a typo in a package name turns into a build crash
// rather than a silent "no codec emitted" warning further down
// the pipeline.
const orphanPath = resolve(tmpRoot, 'orphan.ts');
writeFileSync(
orphanPath,
'import type { Whatever } from \'@does-not-exist/nope\';\n' +
'export type _ = Whatever;\n',
);
const code = readFileSync(orphanPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
// resolveImports swallows resolution failures by design — it
// simply produces an empty `concrete` for the unresolvable
// import. The assertion is that we got here without an exception.
const imported = resolveImports(code, orphanPath, cache);
expect(imported.concrete).toEqual([]);
});
it('returns null for an unresolvable bare specifier (does not throw)', () => {
// Pre-existing relative-path behavior: missing files return
// null, never throw. The bare-specifier branch must match that
// — otherwise a typo in a package name turns into a build crash
// rather than a silent "no codec emitted" warning further down
// the pipeline.
const orphanPath = resolve(tmpRoot, 'orphan.ts');
writeFileSync(
orphanPath,
"import type { Whatever } from '@does-not-exist/nope';\n" +
'export type _ = Whatever;\n',
);
const code = readFileSync(orphanPath, 'utf-8');
const cache = new Map<string, ParsedFileEntry>();
// resolveImports swallows resolution failures by design — it
// simply produces an empty `concrete` for the unresolvable
// import. The assertion is that we got here without an exception.
const imported = resolveImports(code, orphanPath, cache);
expect(imported.concrete).toEqual([]);
});
});
+258 -251
View File
@@ -6,108 +6,120 @@ import { loadFixture } 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 };
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 };
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 };
}
function encodeVarint32(value: number): number[] {
const bytes: number[] = [];
let remaining = value >>> 0;
do {
let byte = remaining & 0x7f;
remaining >>>= 7;
if (remaining !== 0) byte |= 0x80;
bytes.push(byte);
} while (remaining !== 0);
return bytes;
const bytes: number[] = [];
let remaining = value >>> 0;
do {
let byte = remaining & 0x7f;
remaining >>>= 7;
if (remaining !== 0) {
byte |= 0x80;
}
bytes.push(byte);
} while (remaining !== 0);
return bytes;
}
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 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, _end)');
});
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, _end)');
});
it('round-trip uint_32', () => {
const { enc, dec } = makeRoundTrip('simple.ts', 'SimpleMsg');
expect(dec(enc({ value: 42 })).value).toBe(42);
});
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 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 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 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('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('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 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('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('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 = `
it('round-trip bigint-backed 64-bit integers', () => {
const schema = `
interface BigIntMsg {
unsigned: pb<1, uint_64>;
signed: pb<2, int_64>;
@@ -116,210 +128,205 @@ interface BigIntMsg {
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);
});
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 = `
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);
});
const { enc, dec } = makeRoundTripFromSchema(schema, 'Sint32Msg');
const input = { value: -789, values: [-1, 0, 1, -789, 2147483647, -2147483648] };
expect(dec(enc(input))).toEqual(input);
});
it('preserves legacy outbound int_32 bytes while accepting canonical negative varints', () => {
const schema = `
it('preserves legacy outbound int_32 bytes while accepting canonical negative varints', () => {
const schema = `
interface Int32Msg {
value: pb<1, int_32>;
values: pb_repeated<2, int_32>;
forced: pb_optional<3, int_32>;
}`;
const { enc, dec } = makeRoundTripFromSchema(schema, 'Int32Msg');
const input = {
value: -1,
values: [-2147483648, -1, 0, 1, 2147483647],
forced: -2147483648,
};
const encoded = enc(input);
const { enc, dec } = makeRoundTripFromSchema(schema, 'Int32Msg');
const input = {
value: -1,
values: [-2147483648, -1, 0, 1, 2147483647],
forced: -2147483648,
};
const encoded = enc(input);
// Keep SnowLuma's established five-byte negative int32 encoding on the
// outbound path until QQ interoperability is verified on a live account.
// The decoder remains liberal and accepts protobuf's canonical ten-byte
// negative form below.
expect(Array.from(encoded.slice(0, 6))).toEqual([
0x08,
0xff, 0xff, 0xff, 0xff, 0x0f,
]);
expect(dec(encoded)).toEqual(input);
expect(dec(Uint8Array.from([
0x08,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01,
])).value).toBe(-1);
});
// Keep SnowLuma's established five-byte negative int32 encoding on the
// outbound path until QQ interoperability is verified on a live account.
// The decoder remains liberal and accepts protobuf's canonical ten-byte
// negative form below.
expect(Array.from(encoded.slice(0, 6))).toEqual([0x08, 0xff, 0xff, 0xff, 0xff, 0x0f]);
expect(dec(encoded)).toEqual(input);
expect(
dec(Uint8Array.from([0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]))
.value,
).toBe(-1);
});
it('retains the low 32 bits of extended uint_32 field varints', () => {
const { dec } = makeRoundTripFromSchema(
`interface Uint32Msg { value: pb<1, uint_32>; }`,
'Uint32Msg',
);
it('retains the low 32 bits of extended uint_32 field varints', () => {
const { dec } = makeRoundTripFromSchema(
`interface Uint32Msg { value: pb<1, uint_32>; }`,
'Uint32Msg',
);
// QQ sometimes serializes a signed 32-bit source into a schema slot that
// clients expose as uint32. Protobuf readers consume the full ten-byte
// varint and retain its low 32 bits for wire compatibility.
expect(dec(Uint8Array.from([
0x08,
0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01,
])).value).toBe(0xfffffffe);
// QQ sometimes serializes a signed 32-bit source into a schema slot that
// clients expose as uint32. Protobuf readers consume the full ten-byte
// varint and retain its low 32 bits for wire compatibility.
expect(
dec(Uint8Array.from([0x08, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]))
.value,
).toBe(0xfffffffe);
// QQ-compatible uint32 readers consume up to a full 64-bit varint and
// retain its low 32 bits. Some push-envelope sequences use that wire
// representation, so values with non-zero high bits must remain decodable.
expect(dec(Uint8Array.from([
0x08,
0x80, 0x80, 0x80, 0x80, 0x10,
])).value).toBe(0);
expect(dec(Uint8Array.from([
0x08,
0x87, 0x80, 0x80, 0x80, 0x10,
])).value).toBe(7);
// QQ-compatible uint32 readers consume up to a full 64-bit varint and
// retain its low 32 bits. Some push-envelope sequences use that wire
// representation, so values with non-zero high bits must remain decodable.
expect(dec(Uint8Array.from([0x08, 0x80, 0x80, 0x80, 0x80, 0x10])).value).toBe(0);
expect(dec(Uint8Array.from([0x08, 0x87, 0x80, 0x80, 0x80, 0x10])).value).toBe(7);
// Compatibility applies only to complete uint64 varints. Truncated input
// and values wider than 64 bits must still fail loudly.
expect(() => dec(Uint8Array.from([
0x08,
0x80,
]))).toThrow(/truncated uint64 varint/);
expect(() => dec(Uint8Array.from([
0x08,
0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02,
]))).toThrow(/uint64 varint overflow/);
});
// Compatibility applies only to complete uint64 varints. Truncated input
// and values wider than 64 bits must still fail loudly.
expect(() => dec(Uint8Array.from([0x08, 0x80]))).toThrow(/truncated uint64 varint/);
expect(() =>
dec(
Uint8Array.from([0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02]),
),
).toThrow(/uint64 varint overflow/);
});
it('rejects malformed length-delimited fields without leaving parent bounds', () => {
const schema = `interface BytesMsg { data: pb<1, bytes>; }`;
const gen = generateCode(analyzeSource(schema, 'BytesMsg.ts'));
const { dec } = makeRoundTripFromSchema(schema, 'BytesMsg');
it('rejects malformed length-delimited fields without leaving parent bounds', () => {
const schema = `interface BytesMsg { data: pb<1, bytes>; }`;
const gen = generateCode(analyzeSource(schema, 'BytesMsg.ts'));
const { dec } = makeRoundTripFromSchema(schema, 'BytesMsg');
expect(gen).toContain('const _end = __checkedEnd(offset, _len, end);');
expect(() => dec(Uint8Array.from([0x0a, 0x80]))).toThrow(/truncated uint32 varint/);
expect(() => dec(Uint8Array.from([0x0a, 0x80, 0x80, 0x80, 0x80, 0x10]))).toThrow(/uint32 varint overflow/);
});
expect(gen).toContain('const _end = __checkedEnd(offset, _len, end);');
expect(() => dec(Uint8Array.from([0x0a, 0x80]))).toThrow(/truncated uint32 varint/);
expect(() => dec(Uint8Array.from([0x0a, 0x80, 0x80, 0x80, 0x80, 0x10]))).toThrow(
/uint32 varint overflow/,
);
});
it('skips unknown groups without decoding their fields into the parent', () => {
const schema = `
it('skips unknown groups without decoding their fields into the parent', () => {
const schema = `
interface Text { str: pb<1, string>; }
interface Elem { text: pb<1, Text>; }
`;
const { dec } = makeRoundTripFromSchema(schema, 'Elem');
const decoded = dec(Uint8Array.from([
0x7b,
0x0a, 0x08, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x67, 0x65, 0x64,
0x7c,
]));
const { dec } = makeRoundTripFromSchema(schema, 'Elem');
const decoded = dec(
Uint8Array.from([
0x7b, 0x0a, 0x08, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x67, 0x65, 0x64, 0x7c,
]),
);
expect(decoded.text).toBeNull();
expect(protobuf_getUnknownFieldMetadata(decoded).fields).toMatchObject([
{ fieldNumber: 15, wireType: 3 },
]);
});
it('aggregates repeated unknown fields instead of retaining every occurrence', () => {
const { dec } = makeRoundTripFromSchema(
`interface UnknownMsg { known: pb<1, uint_32>; }`,
'UnknownMsg',
);
const wire: number[] = [];
const tag = encodeVarint32((60 << 3) | 0);
for (let index = 0; index < 1_000; index++) wire.push(...tag, 0);
const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire)));
expect(metadata).toEqual({
fields: [{ fieldNumber: 60, wireType: 0, count: 1_000, totalByteLength: 1_000 }],
totalOccurrences: 1_000,
omittedOccurrences: 0,
omittedByteLength: 0,
expect(decoded.text).toBeNull();
expect(protobuf_getUnknownFieldMetadata(decoded).fields).toMatchObject([
{ fieldNumber: 15, wireType: 3 },
]);
});
});
it('caps retained unknown field kinds and summarizes overflow', () => {
const { dec } = makeRoundTripFromSchema(
`interface UnknownKindsMsg { known: pb<1, uint_32>; }`,
'UnknownKindsMsg',
);
const wire: number[] = [];
for (let fieldNumber = 2; fieldNumber <= 66; fieldNumber++) {
wire.push(...encodeVarint32((fieldNumber << 3) | 0), 0);
}
it('aggregates repeated unknown fields instead of retaining every occurrence', () => {
const { dec } = makeRoundTripFromSchema(
`interface UnknownMsg { known: pb<1, uint_32>; }`,
'UnknownMsg',
);
const wire: number[] = [];
const tag = encodeVarint32((60 << 3) | 0);
const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire)));
expect(metadata.fields).toHaveLength(64);
expect(metadata.totalOccurrences).toBe(65);
expect(metadata.omittedOccurrences).toBe(1);
expect(metadata.omittedByteLength).toBe(1);
});
for (let index = 0; index < 1_000; index++) {
wire.push(...tag, 0);
}
it('round-trip double as ieee754 number', () => {
const schema = `
const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire)));
expect(metadata).toEqual({
fields: [{ fieldNumber: 60, wireType: 0, count: 1_000, totalByteLength: 1_000 }],
totalOccurrences: 1_000,
omittedOccurrences: 0,
omittedByteLength: 0,
});
});
it('caps retained unknown field kinds and summarizes overflow', () => {
const { dec } = makeRoundTripFromSchema(
`interface UnknownKindsMsg { known: pb<1, uint_32>; }`,
'UnknownKindsMsg',
);
const wire: number[] = [];
for (let fieldNumber = 2; fieldNumber <= 66; fieldNumber++) {
wire.push(...encodeVarint32((fieldNumber << 3) | 0), 0);
}
const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire)));
expect(metadata.fields).toHaveLength(64);
expect(metadata.totalOccurrences).toBe(65);
expect(metadata.omittedOccurrences).toBe(1);
expect(metadata.omittedByteLength).toBe(1);
});
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);
});
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);
});
});
describe('pb_optional explicit presence', () => {
it('serialises a zero scalar (where pb<> would omit it)', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface OptMsg { forced: pb_optional<1, uint_32>; }`,
'OptMsg',
);
// field 1, varint, value 0 → tag 0x08 then payload 0x00 (NOT empty).
expect(Array.from(enc({ forced: 0 }))).toEqual([0x08, 0x00]);
expect(dec(enc({ forced: 0 })).forced).toBe(0);
});
it('serialises a zero scalar (where pb<> would omit it)', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface OptMsg { forced: pb_optional<1, uint_32>; }`,
'OptMsg',
);
// field 1, varint, value 0 → tag 0x08 then payload 0x00 (NOT empty).
expect(Array.from(enc({ forced: 0 }))).toEqual([0x08, 0x00]);
expect(dec(enc({ forced: 0 })).forced).toBe(0);
});
it('still omits the field when the value is absent (undefined)', () => {
const { enc } = makeRoundTripFromSchema(
`interface OptMsg2 { forced: pb_optional<1, uint_32>; }`,
'OptMsg2',
);
expect(enc({}).length).toBe(0);
});
it('still omits the field when the value is absent (undefined)', () => {
const { enc } = makeRoundTripFromSchema(
`interface OptMsg2 { forced: pb_optional<1, uint_32>; }`,
'OptMsg2',
);
expect(enc({}).length).toBe(0);
});
it('does not change a sibling plain pb<> field (it still omits its zero)', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface MixMsg { plain: pb<1, uint_32>; forced: pb_optional<2, uint_32>; }`,
'MixMsg',
);
// plain=0 omitted (unchanged); only forced=0 is emitted (field 2 → tag 0x10).
expect(Array.from(enc({ plain: 0, forced: 0 }))).toEqual([0x10, 0x00]);
expect(dec(enc({ plain: 7, forced: 9 }))).toEqual({ plain: 7, forced: 9 });
});
it('does not change a sibling plain pb<> field (it still omits its zero)', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface MixMsg { plain: pb<1, uint_32>; forced: pb_optional<2, uint_32>; }`,
'MixMsg',
);
// plain=0 omitted (unchanged); only forced=0 is emitted (field 2 → tag 0x10).
expect(Array.from(enc({ plain: 0, forced: 0 }))).toEqual([0x10, 0x00]);
expect(dec(enc({ plain: 7, forced: 9 }))).toEqual({ plain: 7, forced: 9 });
});
it('forces a false bool onto the wire', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface BoolOpt { flag: pb_optional<1, bool>; }`,
'BoolOpt',
);
expect(Array.from(enc({ flag: false }))).toEqual([0x08, 0x00]);
expect(dec(enc({ flag: false })).flag).toBe(false);
expect(Array.from(enc({ flag: true }))).toEqual([0x08, 0x01]);
});
it('forces a false bool onto the wire', () => {
const { enc, dec } = makeRoundTripFromSchema(
`interface BoolOpt { flag: pb_optional<1, bool>; }`,
'BoolOpt',
);
expect(Array.from(enc({ flag: false }))).toEqual([0x08, 0x00]);
expect(dec(enc({ flag: false })).flag).toBe(false);
expect(Array.from(enc({ flag: true }))).toEqual([0x08, 0x01]);
});
});
+246 -205
View File
@@ -6,107 +6,135 @@ 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']);
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 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)');
});
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
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);
});
`,
'__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
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);
});
`,
'__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
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);
});
`,
'__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
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);
});
`,
'__r',
);
expect(result.id).toBe(42);
expect(result.username).toBe('alice');
expect(result.active).toBe(true);
});
// ── generic monomorphization ───────────────────────────────────────
// ── 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 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
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');
});
`,
'__r',
);
expect(result.name.name).toBe('hello');
});
// ── repeated fields ────────────────────────────────────────────────
// ── repeated fields ────────────────────────────────────────────────
it('repeated fields round-trip', () => {
const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts'));
const result = execAndGet<any>(gen + `\n
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']);
});
`,
'__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
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([]);
});
`,
'__r',
);
expect(result.ids).toEqual([]);
expect(result.names).toEqual([]);
});
// ── import-based usage ──────────────────────────────────────────────
// ── import-based usage ──────────────────────────────────────────────
it('handles code with import { protobuf_encode } from "@snowluma/proton"', () => {
const code = `
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>; }
@@ -114,19 +142,19 @@ 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 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'");
});
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 = `
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>; }
@@ -134,26 +162,30 @@ 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 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');
});
`,
'__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');
});
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 ─────────────────────────────────────────────
// ── import rename alias ─────────────────────────────────────────────
it('handles import { protobuf_encode as encode }', () => {
const code = `
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>; }
@@ -161,38 +193,42 @@ 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 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>');
});
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 = `
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 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');
});
`,
'__r',
);
expect(result.val).toBe(99);
expect(result.name).toBe('x');
});
it('collects call roots first and generates only used dependency closure', () => {
const code = `
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>; }
@@ -202,69 +238,66 @@ 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);
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);
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');
});
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 = `
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 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');
});
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 = `
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';
@@ -272,36 +305,44 @@ 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 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');
});
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');
});
});
+73 -63
View File
@@ -4,66 +4,76 @@ 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_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 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') + `
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)');
});
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('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('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('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 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 = `
it('replaces namespace import calls', () => {
const code = `
import * as pbx from '@snowluma/proton';
interface Msg { id: pb<1, uint_32>; }
@@ -71,24 +81,24 @@ 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);');
});
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 = `
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 })');
});
const registry = analyzeSource(code, 'guard.ts');
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
expect(hasReplacements).toBe(false);
expect(transformedCode).toContain('protobuf_encode<Msg>({ id: 1 })');
});
});
@@ -2,97 +2,112 @@ 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,
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;
function captureFrameFromThrow(
fn: () => unknown,
sourceFile: string,
): { line: number; column: number } {
try {
fn();
} catch (err) {
const stack = err instanceof Error ? (err.stack ?? '') : '';
const location = line.endsWith(')') && line.includes('(')
? line.slice(line.lastIndexOf('(') + 1, -1)
: line.replace(/^at\s+/, '');
for (const raw of stack.split('\n')) {
const line = raw.trim();
const lastColon = location.lastIndexOf(':');
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
if (lastColon < 0 || secondLastColon < 0) continue;
if (!line.includes(sourceFile)) {
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 };
}
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}`);
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;
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);
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();
});
afterEach(() => {
protobuf_disableRuntimeMapFallback();
});
it('dynamically generates encode/decode from runtime map when enabled', () => {
const schema = `
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 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 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',
},
],
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);
});
protobuf_enableRuntimeMapFallback(runtimeMap);
const encoded = invokeEncode();
expect([...encoded]).toEqual([0x08, 0x07]);
const decoded = invokeDecode(encoded);
expect(decoded.value).toBe(7);
});
});
+101 -94
View File
@@ -1,110 +1,117 @@
import { describe, it, expect } from 'vitest';
import { encodeVarint, decodeVarint, writeTag, writeString, readString, skipField } from '../../src/codegen/wire';
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]],
];
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)('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);
});
});
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);
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]);
});
});
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('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');
});
describe('tag encoding', () => {
it('field 1, varint (wire type 0) produces 0x08', () => {
const buf: number[] = [];
writeTag(1, 0, buf);
expect(buf).toEqual([0x08]);
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('你好');
});
});
it('field 1, length-delimited (wire type 2) produces 0x0A', () => {
const buf: number[] = [];
writeTag(1, 2, buf);
expect(buf).toEqual([0x0a]);
});
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('field 2, varint produces 0x10', () => {
const buf: number[] = [];
writeTag(2, 0, buf);
expect(buf).toEqual([0x10]);
});
});
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);
});
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('skips 32-bit field', () => {
expect(skipField(new Uint8Array(4), 0, 5)).toBe(4);
});
it('handles empty string', () => {
const buf: number[] = [];
writeString('', buf);
expect(buf).toEqual([0]); // length 0
it('skips 64-bit field', () => {
expect(skipField(new Uint8Array(8), 0, 1)).toBe(8);
});
});
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);
});
});
});
+5 -5
View File
@@ -6,7 +6,7 @@ const fixturesDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixt
/** Load a fixture file as a string. */
export function loadFixture(name: string): string {
return readFileSync(resolve(fixturesDir, name), 'utf-8');
return readFileSync(resolve(fixturesDir, name), 'utf-8');
}
/**
@@ -14,8 +14,8 @@ export function loadFixture(name: string): string {
* 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;
new Function(code)();
const val = (globalThis as any)[globalKey] as T;
delete (globalThis as any)[globalKey];
return val;
}
+3 -3
View File
@@ -1,7 +1,7 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['test/__tests__/**/*.test.ts'],
},
test: {
include: ['test/__tests__/**/*.test.ts'],
},
});