feat(proton): add @snowluma/proton — compile-time protobuf DSL
Vendors SnowLuma/protobuf-dsl into the monorepo as @snowluma/proton, with
edge-case fixes applied on top of the upstream source. Reference copy of
the unmodified upstream is kept under dev/protobuf-dsl/.
Edge cases fixed (each with a regression test):
- Aliased pb / pb_repeated marker imports (`import { pb as P }`)
— collector now resolves the marker name through the import resolver
- Concrete interface with a generic-instantiated message field
(`wrapped: pb<5, Wrapper<uint_32>>`) — field typeName now resolves
to the mangled form, and the inner instantiation is queued for
monomorphization
- Generic template with a generic-instantiated field
(`interface Outer<U> { x: pb<5, Wrapper<U>> }`) — the inner
instantiation is now re-substituted and re-monomorphized at outer
instantiation time
- Wrapper-binding synthetic SourceFile was empty-text — getText()
returned garbage, breaking mangled name computation downstream
- Cross-file forwarded wrappers (chain → imported base) were not
detected — parseFileForDefinitions now resolves imports recursively
(value imports only, with cycle protection)
- matchForwardedKnownWrapper did not propagate typePattern — chain
treated <X> as the encoded type instead of Wrapper<X>
- Synthetic-SF WeakMap was private to analyzer.ts — replacer could
not see it. Moved to utils.ts so typeNodeToMangledName picks it up
automatically.
Defensive guard: any field whose typeName resolves to neither a primitive
nor a known message now throws at analyze() time, instead of silently
leaking the WireType.Varint placeholder into codegen.
95/95 tests pass; tsc --noEmit clean.
This commit is contained in:
62 files changed
+4714
No files matched your search
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "@snowluma/proton",
|
||||
"version": "1.8.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
|
||||
"main": "./src/runtime.ts",
|
||||
"types": "./protobuf.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./protobuf.d.ts",
|
||||
"default": "./src/runtime.ts"
|
||||
},
|
||||
"./vite": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"typescript": "catalog:"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vite": "catalog:"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"vite": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"vite": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
Vendored
+61
@@ -0,0 +1,61 @@
|
||||
// ── Protobuf field markers ────────────────────────────────────────────
|
||||
/** Marks a singular protobuf field: `name: pb<fieldNumber, Type>` */
|
||||
export type pb<_ProtoNumber extends number, Type> = Type;
|
||||
/** Marks a repeated protobuf field: `ids: pb_repeated<fieldNumber, Type>` → Type[] */
|
||||
export type pb_repeated<_ProtoNumber extends number, Type> = Type[];
|
||||
|
||||
// ── Protobuf primitive types ──────────────────────────────────────────
|
||||
export type uint_32 = number;
|
||||
export type int_32 = number;
|
||||
export type uint_64 = bigint;
|
||||
export type int_64 = bigint;
|
||||
export type sint_32 = number;
|
||||
export type sint_64 = bigint;
|
||||
export type bool = boolean;
|
||||
export type float = number;
|
||||
export type double = number;
|
||||
export type fixed_32 = number;
|
||||
export type fixed_64 = bigint;
|
||||
export type sfixed_32 = number;
|
||||
export type sfixed_64 = bigint;
|
||||
export type bytes = Uint8Array;
|
||||
|
||||
// ── Encode / decode (replaced at compile-time by the vite plugin) ────
|
||||
export function protobuf_encode<T>(params: T): Uint8Array;
|
||||
export function protobuf_decode<T>(data: Uint8Array): T;
|
||||
|
||||
// ── 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;
|
||||
}
|
||||
|
||||
export interface ProtobufRuntimeMessage {
|
||||
name: string;
|
||||
fields: ProtobufRuntimeField[];
|
||||
}
|
||||
|
||||
export interface ProtobufRuntimeCallSite {
|
||||
file: string;
|
||||
line: number;
|
||||
column: number;
|
||||
fnName: 'protobuf_encode' | 'protobuf_decode';
|
||||
typeName: string;
|
||||
}
|
||||
|
||||
export interface ProtobufRuntimeMap {
|
||||
version: 1;
|
||||
messages: ProtobufRuntimeMessage[];
|
||||
callSites: ProtobufRuntimeCallSite[];
|
||||
}
|
||||
|
||||
/** Enables map-based runtime dynamic code generation fallback. */
|
||||
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void;
|
||||
|
||||
/** Disables map-based runtime fallback and clears generated function cache. */
|
||||
export function protobuf_disableRuntimeMapFallback(): void;
|
||||
@@ -0,0 +1,267 @@
|
||||
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 { monomorphizeTypeNode } from './monomorphizer.js';
|
||||
import {
|
||||
createImportedTypeNameResolver,
|
||||
typeNodeToMangledName,
|
||||
registerSyntheticTypeSourceFile,
|
||||
resolveSourceFileForTypeNode,
|
||||
} from './utils.js';
|
||||
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
|
||||
import {
|
||||
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;
|
||||
}
|
||||
|
||||
function instantiateWrapperTypePattern(
|
||||
binding: WrapperBinding,
|
||||
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
|
||||
sf: ts.SourceFile,
|
||||
): ts.TypeNode | 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));
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
export interface ResolvedCallSiteRecord extends CallSiteRecord {
|
||||
typeName: string;
|
||||
}
|
||||
|
||||
export interface AnalysisResult {
|
||||
registry: MessageRegistry;
|
||||
callSites: CallSiteRecord[];
|
||||
sourceFile: ts.SourceFile;
|
||||
}
|
||||
|
||||
export interface UsedRegistryResult {
|
||||
registry: MessageRegistry;
|
||||
roots: Set<string>;
|
||||
callSites: ResolvedCallSiteRecord[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze TypeScript source in a **single parse + single walk**.
|
||||
*
|
||||
* One walk handles both:
|
||||
* - Collecting concrete + generic interfaces
|
||||
* - Recording protobuf_encode/decode call-sites
|
||||
*
|
||||
* 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>();
|
||||
|
||||
// Seed with imported definitions
|
||||
if (imported) {
|
||||
concrete.push(...imported.concrete);
|
||||
for (const [k, v] of imported.templates) templates.set(k, v);
|
||||
}
|
||||
|
||||
// ── single walk ─────────────────────────────────────────────────────
|
||||
ts.forEachChild(sf, function visit(node) {
|
||||
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) {
|
||||
deferredTypeArgs.push(cs.firstTypeArg);
|
||||
callSites.push(cs);
|
||||
} 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
ts.forEachChild(node, visit);
|
||||
});
|
||||
|
||||
// ── 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.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a minimal message registry by collecting only call-site root types and
|
||||
* their transitive message dependencies.
|
||||
*/
|
||||
export function selectUsedRegistry(
|
||||
registry: MessageRegistry,
|
||||
callSites: CallSiteRecord[],
|
||||
sourceFile: ts.SourceFile,
|
||||
): UsedRegistryResult {
|
||||
const roots = new Set<string>();
|
||||
const resolved: ResolvedCallSiteRecord[] = [];
|
||||
const resolveImportedTypeName = createImportedTypeNameResolver(sourceFile);
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
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 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)!);
|
||||
}
|
||||
|
||||
for (const m of messages) dfs(m.name);
|
||||
return new Map(sorted.map(m => [m.name, m]));
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
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',
|
||||
]);
|
||||
|
||||
export interface ProtobufImportBindings {
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport };
|
||||
}
|
||||
|
||||
interface MatchOptions {
|
||||
allowLegacyUnboundCanonical?: boolean;
|
||||
}
|
||||
|
||||
export function matchProtobufCallSite(
|
||||
node: ts.CallExpression,
|
||||
sf: ts.SourceFile,
|
||||
bindings: ProtobufImportBindings,
|
||||
options?: MatchOptions,
|
||||
): ProtobufCallSite | null {
|
||||
const ta = node.typeArguments;
|
||||
if (!ta?.length) return null;
|
||||
|
||||
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);
|
||||
|
||||
return {
|
||||
fnName,
|
||||
exprStart,
|
||||
typeArgsEnd: ta.end + 1,
|
||||
firstTypeArg: ta[0],
|
||||
line: lc.line + 1,
|
||||
column: lc.character + 1,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import ts from 'typescript';
|
||||
import {
|
||||
WireType,
|
||||
PB_MARKER, PB_REPEATED_MARKER,
|
||||
type ProtobufField, type ProtobufMessage,
|
||||
type GenericProtobufTemplate, type GenericFieldTemplate,
|
||||
} from './types.js';
|
||||
import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js';
|
||||
|
||||
function identityImportedTypeName(name: string): string {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Yield generic-instantiated type-arg nodes appearing as field types on a
|
||||
* **concrete** (non-generic) interface — e.g. `wrapped: pb<5, Wrapper<uint_32>>`
|
||||
* yields the `Wrapper<uint_32>` node so the analyzer can enqueue it for
|
||||
* monomorphization. (The call-site-driven queue only sees the outer concrete
|
||||
* type; nested generic instantiations on its fields would otherwise be missed.)
|
||||
*/
|
||||
export function* collectConcreteFieldGenericTypeArgs(
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */
|
||||
export function collectInterface(
|
||||
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);
|
||||
}
|
||||
return fields.length ? { name: node.name.text, fields } : null;
|
||||
}
|
||||
|
||||
/** Collect a generic interface template. */
|
||||
export function collectGenericInterface(
|
||||
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;
|
||||
}
|
||||
|
||||
// ── helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
function parsePbTypeRef(
|
||||
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) 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,
|
||||
): 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);
|
||||
}
|
||||
return resolveImportedTypeName(node.typeName.text);
|
||||
}
|
||||
if (isKeywordTypeNode(node)) return node.getText(sf);
|
||||
return null;
|
||||
}
|
||||
|
||||
function extractField(
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
function extractGenericField(
|
||||
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,
|
||||
};
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { MessageRegistry } from './types.js';
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,659 @@
|
||||
import ts from 'typescript';
|
||||
import { readFileSync, existsSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
import { collectInterface, collectGenericInterface } from './collector.js';
|
||||
import { PRIMITIVE_TYPE_MAP, type ProtobufMessage, type GenericProtobufTemplate } from './types.js';
|
||||
import { createImportedTypeNameResolver, isKeywordTypeNode, type ImportedTypeNameResolver } from './utils.js';
|
||||
import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalProtobufFn } from './callsite.js';
|
||||
|
||||
export interface WrapperBinding {
|
||||
fnName: CanonicalProtobufFn;
|
||||
typeArgIndex: number;
|
||||
typePattern?: string;
|
||||
typeParamNames?: string[];
|
||||
sourceFilePath?: string;
|
||||
}
|
||||
|
||||
export interface ParsedFileEntry {
|
||||
filePath: string;
|
||||
concrete: ProtobufMessage[];
|
||||
templates: Map<string, GenericProtobufTemplate>;
|
||||
importedTypeSources: Map<string, string>;
|
||||
resolveImportedTypeName: ImportedTypeNameResolver;
|
||||
exportedWrappers: Map<string, WrapperBinding>;
|
||||
}
|
||||
|
||||
export interface ImportedDefinitions {
|
||||
concrete: ProtobufMessage[];
|
||||
templates: Map<string, GenericProtobufTemplate>;
|
||||
wrapperBindings: Map<string, WrapperBinding>;
|
||||
}
|
||||
|
||||
interface ImportClause {
|
||||
importedName: string;
|
||||
localName: string;
|
||||
specifier: string;
|
||||
}
|
||||
|
||||
function getCallableName(expr: ts.Expression): string | null {
|
||||
if (ts.isIdentifier(expr)) return expr.text;
|
||||
if (ts.isPropertyAccessExpression(expr)) return expr.name.text;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Extract all named imports from the source file (both type and value imports). */
|
||||
function extractImports(sf: ts.SourceFile): ImportClause[] {
|
||||
const result: ImportClause[] = [];
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
|
||||
const spec = stmt.moduleSpecifier;
|
||||
if (!ts.isStringLiteral(spec)) continue;
|
||||
const specifier = spec.text;
|
||||
|
||||
const clause = stmt.importClause;
|
||||
if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
|
||||
for (const el of clause.namedBindings.elements) {
|
||||
result.push({
|
||||
importedName: (el.propertyName ?? el.name).text,
|
||||
localName: el.name.text,
|
||||
specifier,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Like `extractImports`, but skips `import type { ... }` and `import { type X }`
|
||||
* entries. Wrapper functions are values, so type-only imports can't introduce
|
||||
* one and we shouldn't eagerly parse their source files just to look for wrappers. */
|
||||
function extractValueImports(sf: ts.SourceFile): ImportClause[] {
|
||||
const result: ImportClause[] = [];
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
|
||||
if (stmt.importClause.isTypeOnly) continue;
|
||||
const spec = stmt.moduleSpecifier;
|
||||
if (!ts.isStringLiteral(spec)) continue;
|
||||
const specifier = spec.text;
|
||||
|
||||
const clause = stmt.importClause;
|
||||
if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
|
||||
for (const el of clause.namedBindings.elements) {
|
||||
if (el.isTypeOnly) continue;
|
||||
result.push({
|
||||
importedName: (el.propertyName ?? el.name).text,
|
||||
localName: el.name.text,
|
||||
specifier,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Resolve a relative module specifier to an absolute file path. Returns null if not found. */
|
||||
function resolveModulePath(specifier: string, importerPath: string): string | null {
|
||||
if (!specifier.startsWith('.')) return null; // skip bare/alias specifiers
|
||||
|
||||
const base = resolve(dirname(importerPath), specifier);
|
||||
|
||||
// Try exact path (e.g., './types.ts')
|
||||
if (existsSync(base) && !base.endsWith('.ts') === false) return base;
|
||||
if (base.endsWith('.ts') && existsSync(base)) return base;
|
||||
|
||||
// Try appending .ts
|
||||
const withTs = base + '.ts';
|
||||
if (existsSync(withTs)) return withTs;
|
||||
|
||||
// Try as directory with index.ts
|
||||
const indexTs = resolve(base, 'index.ts');
|
||||
if (existsSync(indexTs)) return indexTs;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasExportModifier(node: ts.Node): boolean {
|
||||
return ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword);
|
||||
}
|
||||
|
||||
function matchForwardedProtobufFn(
|
||||
body: ts.ConciseBody | ts.Block | undefined,
|
||||
sf: ts.SourceFile,
|
||||
typeParams: readonly ts.TypeParameterDeclaration[] | undefined,
|
||||
): WrapperBinding | null {
|
||||
if (!body || !typeParams?.length) return null;
|
||||
const typeParamIndexes = new Map(typeParams.map((p, index) => [p.name.text, index]));
|
||||
const typeParamNames = typeParams.map(p => p.name.text);
|
||||
const bindings = collectProtobufImportBindings(sf);
|
||||
let found: WrapperBinding | null = null;
|
||||
|
||||
function visit(node: ts.Node): void {
|
||||
if (found) return;
|
||||
if (ts.isCallExpression(node)) {
|
||||
const cs = matchProtobufCallSite(node, sf, bindings, {
|
||||
allowLegacyUnboundCanonical: true,
|
||||
});
|
||||
if (
|
||||
cs &&
|
||||
ts.isTypeReferenceNode(cs.firstTypeArg) &&
|
||||
ts.isIdentifier(cs.firstTypeArg.typeName) &&
|
||||
typeParamIndexes.has(cs.firstTypeArg.typeName.text)
|
||||
) {
|
||||
found = {
|
||||
fnName: cs.fnName,
|
||||
typeArgIndex: typeParamIndexes.get(cs.firstTypeArg.typeName.text)!,
|
||||
sourceFilePath: sf.fileName,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (cs && containsTypeParameter(cs.firstTypeArg, typeParamIndexes)) {
|
||||
found = {
|
||||
fnName: cs.fnName,
|
||||
typeArgIndex: firstTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) ?? 0,
|
||||
typePattern: cs.firstTypeArg.getText(sf),
|
||||
typeParamNames,
|
||||
sourceFilePath: sf.fileName,
|
||||
};
|
||||
return;
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
|
||||
visit(body);
|
||||
return found;
|
||||
}
|
||||
|
||||
function containsTypeParameter(typeNode: ts.TypeNode, typeParamIndexes: Map<string, number>): boolean {
|
||||
let found = false;
|
||||
function visit(node: ts.Node): void {
|
||||
if (found) return;
|
||||
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) {
|
||||
found = true;
|
||||
return;
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(typeNode);
|
||||
return found;
|
||||
}
|
||||
|
||||
function firstTypeParameterIndex(typeNode: ts.TypeNode, typeParamIndexes: Map<string, number>): number | null {
|
||||
let index: number | null = null;
|
||||
function visit(node: ts.Node): void {
|
||||
if (index !== null) return;
|
||||
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) {
|
||||
index = typeParamIndexes.get(node.typeName.text)!;
|
||||
return;
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
visit(typeNode);
|
||||
return index;
|
||||
}
|
||||
|
||||
function instantiateWrapperTypePattern(
|
||||
binding: WrapperBinding,
|
||||
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
|
||||
sf: ts.SourceFile,
|
||||
): ts.TypeNode | 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));
|
||||
}
|
||||
|
||||
const parsed = ts.createSourceFile('wrapper-type.ts', `type __T = ${text};`, ts.ScriptTarget.Latest, true);
|
||||
const stmt = parsed.statements[0];
|
||||
if (!ts.isTypeAliasDeclaration(stmt)) return null;
|
||||
return stmt.type;
|
||||
}
|
||||
|
||||
function matchForwardedKnownWrapper(
|
||||
body: ts.ConciseBody | ts.Block | undefined,
|
||||
typeParams: readonly ts.TypeParameterDeclaration[] | undefined,
|
||||
knownWrappers: Map<string, WrapperBinding>,
|
||||
): WrapperBinding | null {
|
||||
if (!body || !typeParams?.length) return null;
|
||||
const tps = typeParams; // narrowed copy for closure scope
|
||||
const typeParamIndexes = new Map(tps.map((p, index) => [p.name.text, index]));
|
||||
let found: WrapperBinding | null = null;
|
||||
|
||||
function visit(node: ts.Node): void {
|
||||
if (found) return;
|
||||
if (ts.isCallExpression(node) && node.typeArguments?.length) {
|
||||
const callableName = getCallableName(node.expression);
|
||||
const wrapper = callableName ? knownWrappers.get(callableName) : undefined;
|
||||
const forwardedTypeArg = wrapper ? node.typeArguments[wrapper.typeArgIndex] : undefined;
|
||||
if (
|
||||
wrapper &&
|
||||
forwardedTypeArg &&
|
||||
ts.isTypeReferenceNode(forwardedTypeArg) &&
|
||||
ts.isIdentifier(forwardedTypeArg.typeName) &&
|
||||
!forwardedTypeArg.typeArguments?.length &&
|
||||
typeParamIndexes.has(forwardedTypeArg.typeName.text)
|
||||
) {
|
||||
const chainTypeArgIndex = typeParamIndexes.get(forwardedTypeArg.typeName.text)!;
|
||||
const binding: WrapperBinding = {
|
||||
fnName: wrapper.fnName,
|
||||
typeArgIndex: chainTypeArgIndex,
|
||||
};
|
||||
// Propagate the typePattern from the inner wrapper, substituting
|
||||
// its type-param names with the chain's own. Otherwise the chain
|
||||
// would treat its own `<X>` as the encoded type rather than the
|
||||
// wrapped form (e.g. `Wrapper<X>`).
|
||||
if (wrapper.typePattern && wrapper.typeParamNames?.length === 1) {
|
||||
const chainParamName = tps[chainTypeArgIndex].name.text;
|
||||
const wrapperParamName = wrapper.typeParamNames[0];
|
||||
binding.typePattern = wrapperParamName === chainParamName
|
||||
? wrapper.typePattern
|
||||
: wrapper.typePattern.replace(new RegExp(`\\b${wrapperParamName}\\b`, 'g'), chainParamName);
|
||||
binding.typeParamNames = [chainParamName];
|
||||
binding.sourceFilePath = wrapper.sourceFilePath;
|
||||
}
|
||||
found = binding;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
|
||||
visit(body);
|
||||
return found;
|
||||
}
|
||||
|
||||
function collectWrapperCandidates(
|
||||
sf: ts.SourceFile,
|
||||
exportedOnly: boolean,
|
||||
): Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> {
|
||||
const candidates: Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> = [];
|
||||
|
||||
for (const stmt of sf.statements) {
|
||||
if (ts.isFunctionDeclaration(stmt) && stmt.name && (!exportedOnly || hasExportModifier(stmt))) {
|
||||
candidates.push({ name: stmt.name.text, body: stmt.body, typeParameters: stmt.typeParameters });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue;
|
||||
for (const decl of stmt.declarationList.declarations) {
|
||||
if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;
|
||||
const init = decl.initializer;
|
||||
if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) {
|
||||
candidates.push({ name: decl.name.text, body: init.body, typeParameters: init.typeParameters });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ts.isObjectLiteralExpression(init)) {
|
||||
for (const prop of init.properties) {
|
||||
if (ts.isPropertyAssignment(prop)) {
|
||||
const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null;
|
||||
const propInit = prop.initializer;
|
||||
if (propName && (ts.isArrowFunction(propInit) || ts.isFunctionExpression(propInit))) {
|
||||
candidates.push({ name: propName, body: propInit.body, typeParameters: propInit.typeParameters });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ts.isMethodDeclaration(prop)) {
|
||||
const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null;
|
||||
if (propName) candidates.push({ name: propName, body: prop.body, typeParameters: prop.typeParameters });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return candidates;
|
||||
}
|
||||
|
||||
function collectWrappers(
|
||||
sf: ts.SourceFile,
|
||||
exportedOnly: boolean,
|
||||
externalKnownWrappers: Map<string, WrapperBinding> = new Map(),
|
||||
): Map<string, WrapperBinding> {
|
||||
const wrappers = new Map<string, WrapperBinding>();
|
||||
const localWrapperMembers = new Map<string, Map<string, WrapperBinding>>();
|
||||
const candidates = collectWrapperCandidates(sf, exportedOnly);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const fn = matchForwardedProtobufFn(candidate.body, sf, candidate.typeParameters);
|
||||
if (fn) wrappers.set(candidate.name, fn);
|
||||
}
|
||||
|
||||
// Detect both intra-file forwarders (`encodeFoo<T>(v) { return encodeBar<T>(v); }`
|
||||
// where `encodeBar` is local) AND cross-file forwarders to wrappers imported
|
||||
// from already-parsed modules. Externally known wrappers are seeded by the
|
||||
// caller (`parseFileForDefinitions`) after it resolves imports.
|
||||
const knownForForwarding = new Map<string, WrapperBinding>();
|
||||
for (const [k, v] of externalKnownWrappers) knownForForwarding.set(k, v);
|
||||
for (const [k, v] of wrappers) knownForForwarding.set(k, v);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (wrappers.has(candidate.name)) continue;
|
||||
const fn = matchForwardedKnownWrapper(candidate.body, candidate.typeParameters, knownForForwarding);
|
||||
if (fn) wrappers.set(candidate.name, fn);
|
||||
}
|
||||
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue;
|
||||
for (const decl of stmt.declarationList.declarations) {
|
||||
if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;
|
||||
const init = decl.initializer;
|
||||
if (ts.isObjectLiteralExpression(init)) {
|
||||
const memberWrappers = new Map<string, WrapperBinding>();
|
||||
for (const prop of init.properties) {
|
||||
if (!('name' in prop) || !prop.name) continue;
|
||||
const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null;
|
||||
if (!propName) continue;
|
||||
const fn = wrappers.get(propName);
|
||||
if (fn) {
|
||||
memberWrappers.set(propName, fn);
|
||||
}
|
||||
}
|
||||
if (memberWrappers.size) localWrapperMembers.set(decl.name.text, memberWrappers);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const stmt of sf.statements) {
|
||||
if (exportedOnly || !ts.isVariableStatement(stmt)) continue;
|
||||
for (const decl of stmt.declarationList.declarations) {
|
||||
if (!ts.isIdentifier(decl.name) || !decl.initializer || !ts.isPropertyAccessExpression(decl.initializer)) continue;
|
||||
if (!ts.isIdentifier(decl.initializer.expression)) continue;
|
||||
const memberWrappers = localWrapperMembers.get(decl.initializer.expression.text);
|
||||
const fn = memberWrappers?.get(decl.initializer.name.text);
|
||||
if (fn) wrappers.set(decl.name.text, fn);
|
||||
}
|
||||
}
|
||||
|
||||
return wrappers;
|
||||
}
|
||||
|
||||
function collectExportedWrappers(
|
||||
sf: ts.SourceFile,
|
||||
externalKnownWrappers: Map<string, WrapperBinding> = new Map(),
|
||||
): Map<string, WrapperBinding> {
|
||||
return collectWrappers(sf, true, externalKnownWrappers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a file and extract its protobuf interfaces and generic templates.
|
||||
*
|
||||
* When `cache` is provided, this resolves the file's imports recursively
|
||||
* (with cycle protection) so cross-file forwarded wrappers — e.g.
|
||||
* `export function encodeChain<T>(v) { return encodeBase<T>(v); }`
|
||||
* where `encodeBase` is imported from another module — can be detected.
|
||||
*/
|
||||
function parseFileForDefinitions(
|
||||
absolutePath: string,
|
||||
code?: string,
|
||||
cache?: Map<string, ParsedFileEntry>,
|
||||
parsing?: Set<string>,
|
||||
): ParsedFileEntry {
|
||||
const sourceText = code ?? readFileSync(absolutePath, 'utf-8');
|
||||
const sf = ts.createSourceFile(absolutePath, sourceText, ts.ScriptTarget.Latest, true);
|
||||
const concrete: ProtobufMessage[] = [];
|
||||
const templates = new Map<string, GenericProtobufTemplate>();
|
||||
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
|
||||
const importedTypeSources = new Map<string, string>();
|
||||
|
||||
// Collect imported wrapper bindings under their LOCAL names so this file's
|
||||
// forwarders can match against them. Skip work entirely if there's no cache
|
||||
// (legacy callers that don't care about cross-file forwarding).
|
||||
//
|
||||
// Only descends into value imports (not `import type { ... }`), since
|
||||
// type-only imports can never introduce a wrapper function. This avoids
|
||||
// pulling unrelated type-only modules into the cache.
|
||||
const importedKnownWrappers = new Map<string, WrapperBinding>();
|
||||
if (cache) {
|
||||
const inProgress = parsing ?? new Set<string>();
|
||||
inProgress.add(absolutePath);
|
||||
for (const imp of extractValueImports(sf)) {
|
||||
const resolved = resolveModulePath(imp.specifier, absolutePath);
|
||||
if (!resolved) continue;
|
||||
if (inProgress.has(resolved)) continue; // cycle guard
|
||||
let entry = cache.get(resolved);
|
||||
if (!entry) {
|
||||
entry = parseFileForDefinitions(resolved, undefined, cache, inProgress);
|
||||
cache.set(resolved, entry);
|
||||
}
|
||||
const wrapperFn = entry.exportedWrappers.get(imp.importedName);
|
||||
if (wrapperFn) importedKnownWrappers.set(imp.localName, wrapperFn);
|
||||
}
|
||||
inProgress.delete(absolutePath);
|
||||
}
|
||||
|
||||
const exportedWrappers = collectExportedWrappers(sf, importedKnownWrappers);
|
||||
|
||||
for (const imp of extractImports(sf)) {
|
||||
const resolved = resolveModulePath(imp.specifier, absolutePath);
|
||||
if (!resolved) continue;
|
||||
importedTypeSources.set(imp.importedName, resolved);
|
||||
importedTypeSources.set(imp.localName, resolved);
|
||||
}
|
||||
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isInterfaceDeclaration(stmt)) continue;
|
||||
if (stmt.typeParameters?.length) {
|
||||
const tpl = collectGenericInterface(stmt, sf, resolveImportedTypeName);
|
||||
if (tpl) templates.set(tpl.name, tpl);
|
||||
} else {
|
||||
const msg = collectInterface(stmt, sf, resolveImportedTypeName);
|
||||
if (msg) concrete.push(msg);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
filePath: absolutePath,
|
||||
concrete,
|
||||
templates,
|
||||
importedTypeSources,
|
||||
resolveImportedTypeName,
|
||||
exportedWrappers,
|
||||
};
|
||||
}
|
||||
|
||||
function collectCallRootTypeNodes(sf: ts.SourceFile): ts.TypeNode[] {
|
||||
const roots: ts.TypeNode[] = [];
|
||||
const importBindings = collectProtobufImportBindings(sf);
|
||||
|
||||
ts.forEachChild(sf, function visit(node) {
|
||||
if (ts.isCallExpression(node)) {
|
||||
const cs = matchProtobufCallSite(node, sf, importBindings, {
|
||||
allowLegacyUnboundCanonical: true,
|
||||
});
|
||||
if (cs) roots.push(cs.firstTypeArg);
|
||||
}
|
||||
|
||||
ts.forEachChild(node, visit);
|
||||
});
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
interface RootTypeNode {
|
||||
typeNode: ts.TypeNode;
|
||||
from: ParsedFileEntry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve only the import definitions reachable from protobuf call-site roots.
|
||||
*/
|
||||
export function resolveImports(
|
||||
code: string,
|
||||
importerPath: string,
|
||||
cache: Map<string, ParsedFileEntry>,
|
||||
): ImportedDefinitions {
|
||||
const entryPath = resolve(importerPath);
|
||||
const entry = parseFileForDefinitions(entryPath, code, cache);
|
||||
const concrete = new Map<string, ProtobufMessage>();
|
||||
const templates = new Map<string, GenericProtobufTemplate>();
|
||||
const fileEntries = new Map<string, ParsedFileEntry>([[entryPath, entry]]);
|
||||
const visitedConcrete = new Set<string>();
|
||||
const visitedTemplates = new Set<string>();
|
||||
const importedObjectWrapperMembers = new Map<string, Map<string, WrapperBinding>>();
|
||||
|
||||
function getEntry(filePath: string): ParsedFileEntry {
|
||||
const abs = resolve(filePath);
|
||||
const known = fileEntries.get(abs);
|
||||
if (known) return known;
|
||||
|
||||
let parsed = cache.get(abs);
|
||||
if (!parsed) {
|
||||
parsed = parseFileForDefinitions(abs, undefined, cache);
|
||||
cache.set(abs, parsed);
|
||||
}
|
||||
|
||||
fileEntries.set(abs, parsed);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function collectCalledGenericIdentifiers(sf: ts.SourceFile): Set<string> {
|
||||
const names = new Set<string>();
|
||||
|
||||
ts.forEachChild(sf, function visit(node) {
|
||||
if (ts.isCallExpression(node) && node.typeArguments?.length) {
|
||||
const callableName = getCallableName(node.expression);
|
||||
if (callableName) names.add(callableName);
|
||||
}
|
||||
|
||||
ts.forEachChild(node, visit);
|
||||
});
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
function collectWrapperBindings(from: ParsedFileEntry, sf: ts.SourceFile): Map<string, WrapperBinding> {
|
||||
const bindings = new Map<string, WrapperBinding>();
|
||||
const localWrappers = from.filePath === entryPath ? collectWrappers(sf, false) : from.exportedWrappers;
|
||||
for (const [name, fn] of localWrappers) bindings.set(name, fn);
|
||||
|
||||
const calledGenericIdentifiers = collectCalledGenericIdentifiers(sf);
|
||||
for (const imp of extractImports(sf)) {
|
||||
if (!calledGenericIdentifiers.has(imp.localName)) continue;
|
||||
const resolved = resolveModulePath(imp.specifier, from.filePath);
|
||||
if (!resolved) continue;
|
||||
const wrapperFn = getEntry(resolved).exportedWrappers.get(imp.importedName);
|
||||
if (wrapperFn) bindings.set(imp.localName, wrapperFn);
|
||||
|
||||
const importedEntry = getEntry(resolved);
|
||||
const memberNames = [...importedEntry.exportedWrappers.keys()].filter(name => calledGenericIdentifiers.has(name));
|
||||
if (memberNames.length) {
|
||||
const members = new Map<string, WrapperBinding>();
|
||||
for (const name of memberNames) {
|
||||
const memberBinding = importedEntry.exportedWrappers.get(name)!;
|
||||
members.set(name, memberBinding);
|
||||
bindings.set(name, memberBinding);
|
||||
}
|
||||
importedObjectWrapperMembers.set(imp.localName, members);
|
||||
}
|
||||
}
|
||||
|
||||
return bindings;
|
||||
}
|
||||
|
||||
function resolveTypeName(typeName: string, from: ParsedFileEntry): void {
|
||||
if (typeName in PRIMITIVE_TYPE_MAP) return;
|
||||
|
||||
const concreteMsg = from.concrete.find(msg => msg.name === typeName);
|
||||
if (concreteMsg) {
|
||||
const visitKey = `${from.filePath}:message:${typeName}`;
|
||||
if (visitedConcrete.has(visitKey)) return;
|
||||
visitedConcrete.add(visitKey);
|
||||
|
||||
if (from.filePath !== entryPath && !concrete.has(concreteMsg.name)) {
|
||||
concrete.set(concreteMsg.name, concreteMsg);
|
||||
}
|
||||
|
||||
for (const field of concreteMsg.fields) {
|
||||
resolveTypeName(field.typeName, from);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const template = from.templates.get(typeName);
|
||||
if (template) {
|
||||
const visitKey = `${from.filePath}:template:${typeName}`;
|
||||
if (visitedTemplates.has(visitKey)) return;
|
||||
visitedTemplates.add(visitKey);
|
||||
|
||||
if (from.filePath !== entryPath && !templates.has(template.name)) {
|
||||
templates.set(template.name, template);
|
||||
}
|
||||
|
||||
for (const field of template.fields) {
|
||||
if (!field.isTypeParam) resolveTypeName(field.rawTypeName, from);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const importedPath = from.importedTypeSources.get(typeName);
|
||||
if (!importedPath) return;
|
||||
|
||||
resolveTypeName(typeName, getEntry(importedPath));
|
||||
}
|
||||
|
||||
function resolveTypeNode(typeNode: ts.TypeNode, from: ParsedFileEntry): void {
|
||||
if (isKeywordTypeNode(typeNode)) return;
|
||||
if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return;
|
||||
|
||||
const typeName = from.resolveImportedTypeName(typeNode.typeName.text);
|
||||
resolveTypeName(typeName, from);
|
||||
|
||||
if (!typeNode.typeArguments?.length) return;
|
||||
for (const typeArg of typeNode.typeArguments) {
|
||||
resolveTypeNode(typeArg, from);
|
||||
}
|
||||
}
|
||||
|
||||
const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true))
|
||||
.map(typeNode => ({ typeNode, from: entry }));
|
||||
const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true);
|
||||
const wrapperBindings = collectWrapperBindings(entry, entrySourceFile);
|
||||
|
||||
ts.forEachChild(entrySourceFile, function visit(node) {
|
||||
if (
|
||||
ts.isCallExpression(node) &&
|
||||
node.typeArguments?.length &&
|
||||
getCallableName(node.expression) &&
|
||||
(
|
||||
wrapperBindings.has(getCallableName(node.expression)!) ||
|
||||
(
|
||||
ts.isPropertyAccessExpression(node.expression) &&
|
||||
ts.isIdentifier(node.expression.expression) &&
|
||||
importedObjectWrapperMembers.get(node.expression.expression.text)?.has(node.expression.name.text)
|
||||
)
|
||||
)
|
||||
) {
|
||||
const binding = wrapperBindings.get(getCallableName(node.expression)!) ?? (
|
||||
ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)
|
||||
? importedObjectWrapperMembers.get(node.expression.expression.text)?.get(node.expression.name.text)
|
||||
: undefined
|
||||
);
|
||||
if (!binding) return;
|
||||
const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile);
|
||||
if (typeArg) rootTypeNodes.push({
|
||||
typeNode: typeArg,
|
||||
from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry,
|
||||
});
|
||||
if (binding.typePattern) {
|
||||
for (const callerTypeArg of node.typeArguments) {
|
||||
rootTypeNodes.push({ typeNode: callerTypeArg, from: entry });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ts.forEachChild(node, visit);
|
||||
});
|
||||
|
||||
for (const root of rootTypeNodes) {
|
||||
resolveTypeNode(root.typeNode, root.from);
|
||||
}
|
||||
|
||||
return { concrete: [...concrete.values()], templates, wrapperBindings };
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import ts from 'typescript';
|
||||
import { 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;
|
||||
}
|
||||
|
||||
/** Resolved value for a single template type parameter. */
|
||||
interface ResolvedTypeArg {
|
||||
/** Mangled-name form used when substituting into a `rawTypeName` slot
|
||||
* for an `isTypeParam` field. */
|
||||
mangled: string;
|
||||
/** Original TypeScript source text — used when re-substituting into a
|
||||
* field's `genericTypeArgText` so the substituted text remains parseable. */
|
||||
text: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively monomorphize a generic type instantiation into concrete ProtobufMessages.
|
||||
* E.g. `Wrapper<Wrapper<string>>` → creates `Wrapper__string` and `Wrapper__Wrapper__string`.
|
||||
* 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,
|
||||
): 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,
|
||||
};
|
||||
}
|
||||
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,
|
||||
};
|
||||
});
|
||||
|
||||
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,
|
||||
): 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;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
export enum WireType {
|
||||
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;
|
||||
}
|
||||
|
||||
export interface ProtobufMessage {
|
||||
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[];
|
||||
}
|
||||
|
||||
export interface GenericFieldTemplate {
|
||||
name: string;
|
||||
fieldNumber: number;
|
||||
rawTypeName: string;
|
||||
isTypeParam: boolean;
|
||||
isOptional: boolean;
|
||||
isRepeated: 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' },
|
||||
};
|
||||
|
||||
/** Marker identifiers recognised in type references */
|
||||
export const PB_MARKER = 'pb';
|
||||
export const PB_REPEATED_MARKER = 'pb_repeated';
|
||||
@@ -0,0 +1,85 @@
|
||||
import ts from 'typescript';
|
||||
|
||||
export type ImportedTypeNameResolver = (name: string) => string;
|
||||
|
||||
function identityImportedTypeName(name: string): string {
|
||||
return name;
|
||||
}
|
||||
|
||||
// Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in
|
||||
// their own SourceFile, not in the caller's. Anyone that needs to read text or
|
||||
// resolve imports against such a node must use the registered SF; otherwise
|
||||
// `node.getText(callerSf)` reads garbage from the wrong buffer.
|
||||
const syntheticTypeSourceFiles = new WeakMap<ts.TypeNode, ts.SourceFile>();
|
||||
|
||||
export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void {
|
||||
syntheticTypeSourceFiles.set(node, sf);
|
||||
}
|
||||
|
||||
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,
|
||||
]);
|
||||
|
||||
export function isKeywordTypeNode(node: ts.Node): boolean {
|
||||
return KEYWORD_TYPE_KINDS.has(node.kind);
|
||||
}
|
||||
|
||||
export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver {
|
||||
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 el of bindings.elements) {
|
||||
localToImported.set(el.name.text, (el.propertyName ?? el.name).text);
|
||||
}
|
||||
}
|
||||
|
||||
return (name: string) => localToImported.get(name) ?? name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic mangled name for a type node.
|
||||
* `Foo` → `Foo`
|
||||
* `Foo<string>` → `Foo__string`
|
||||
* `Foo<Bar<uint_32>>` → `Foo__Bar__uint_32`
|
||||
*
|
||||
* If `typeNode` is a synthetic node produced by wrapper-binding instantiation,
|
||||
* its registered source file is used automatically so `getText()` returns
|
||||
* the substituted type text rather than garbage from `sf`.
|
||||
*/
|
||||
export function typeNodeToMangledName(
|
||||
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('__');
|
||||
}
|
||||
return base;
|
||||
}
|
||||
if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf);
|
||||
return typeNode.getText(effectiveSf);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/** Emit inline varint decode, storing result in `varName`. */
|
||||
function varintDec(varName: string, ind: string): string {
|
||||
return [
|
||||
`${ind}let ${varName} = data[offset++];`,
|
||||
`${ind}if (${varName} & 0x80) {`,
|
||||
`${ind} let _s = 7, _b;`,
|
||||
`${ind} ${varName} &= 0x7f;`,
|
||||
`${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`,
|
||||
`${ind}}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function varintDec64(varName: string, ind: string): string {
|
||||
return [
|
||||
`${ind}let ${varName} = 0n, _s = 0n, _b;`,
|
||||
`${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function isVarint64(typeName: string): boolean {
|
||||
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
|
||||
}
|
||||
|
||||
function isFixed64BigInt(typeName: string): boolean {
|
||||
return typeName === 'fixed_64' || typeName === 'sfixed_64';
|
||||
}
|
||||
|
||||
const INLINE_SKIP = [
|
||||
` const wireType = _tag & 0x7;`,
|
||||
` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`,
|
||||
` else if (wireType === 1) offset += 8;`,
|
||||
` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`,
|
||||
` else if (wireType === 5) offset += 4;`,
|
||||
].join('\n');
|
||||
|
||||
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 L = [
|
||||
`function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`,
|
||||
...locals,
|
||||
` while (offset < end) {`,
|
||||
` let _tag = data[offset++];`,
|
||||
` if (_tag & 0x80) {`,
|
||||
` let _ts = 7, _tb;`,
|
||||
` _tag &= 0x7f;`,
|
||||
` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`,
|
||||
` }`,
|
||||
` switch (_tag) {`,
|
||||
];
|
||||
|
||||
msg.fields.forEach((field, index) => {
|
||||
L.push(decodeField(field, index));
|
||||
});
|
||||
|
||||
L.push(
|
||||
` default: {`,
|
||||
INLINE_SKIP,
|
||||
` break;`,
|
||||
` }`,
|
||||
` }`,
|
||||
` }`,
|
||||
` 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 L: string[] = [` case ${tagValue(field)}: {`];
|
||||
|
||||
if (isMessage) {
|
||||
L.push(varintDec('_len', I));
|
||||
L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`));
|
||||
L.push(`${I}offset += _len;`);
|
||||
} else if (typeName === 'string') {
|
||||
L.push(varintDec('_len', I));
|
||||
L.push(`${I}const _end = offset + _len;`);
|
||||
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 = offset + _len;`);
|
||||
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 === 'sint_32') {
|
||||
L.push(varintDec('_val', I));
|
||||
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
|
||||
} else if (wireType === WireType.Varint) {
|
||||
L.push(varintDec('_val', I));
|
||||
L.push(assign(`_val >>> 0`));
|
||||
} else if (typeName === 'float') {
|
||||
L.push(assign(`__readFloat32(data, offset)`));
|
||||
L.push(`${I}offset += 4;`);
|
||||
} else if (wireType === WireType.Bit32) {
|
||||
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(assign(`__readFloat64(data, offset)`));
|
||||
L.push(`${I}offset += 8;`);
|
||||
} else if (isFixed64BigInt(typeName)) {
|
||||
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(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');
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
import { WireType, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js';
|
||||
|
||||
/**
|
||||
* Pre-compute tag bytes at codegen time.
|
||||
* Field 1 + Varint(0) -> [0x08], Field 1 + LenDelim(2) -> [0x0a], etc.
|
||||
*/
|
||||
function computeTagBytes(fieldNumber: number, wireType: number): number[] {
|
||||
let value = ((fieldNumber << 3) | wireType) >>> 0;
|
||||
const bytes: number[] = [];
|
||||
while (value > 0x7f) {
|
||||
bytes.push((value & 0x7f) | 0x80);
|
||||
value >>>= 7;
|
||||
}
|
||||
bytes.push(value & 0x7f);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function writeTag(fieldNumber: number, wireType: number, ind: string): string {
|
||||
return computeTagBytes(fieldNumber, wireType)
|
||||
.map(byte => `${ind}buf[offset++] = ${byte};`)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function varintSize(varName: string, ind: string): string {
|
||||
return `${ind}size += ${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`;
|
||||
}
|
||||
|
||||
function writeVarint(expr: string, ind: string): string {
|
||||
return [
|
||||
`${ind}let _v = ${expr};`,
|
||||
`${ind}if (_v < 0x80) {`,
|
||||
`${ind} buf[offset++] = _v;`,
|
||||
`${ind}} else if (_v < 0x4000) {`,
|
||||
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = _v >>> 7;`,
|
||||
`${ind}} else if (_v < 0x200000) {`,
|
||||
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = _v >>> 14;`,
|
||||
`${ind}} else if (_v < 0x10000000) {`,
|
||||
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = _v >>> 21;`,
|
||||
`${ind}} else {`,
|
||||
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = _v >>> 28;`,
|
||||
`${ind}}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function isVarint64(typeName: string): boolean {
|
||||
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
|
||||
}
|
||||
|
||||
function isFixed64BigInt(typeName: string): boolean {
|
||||
return typeName === 'fixed_64' || typeName === 'sfixed_64';
|
||||
}
|
||||
|
||||
function bigintVarintExpr(typeName: string, expr: string): string {
|
||||
if (typeName === 'uint_64') return `BigInt.asUintN(64, ${expr})`;
|
||||
if (typeName === 'int_64') return `BigInt.asUintN(64, ${expr})`;
|
||||
return `__zigZagEncode64(${expr})`;
|
||||
}
|
||||
|
||||
interface EncoderBlock {
|
||||
declare: string[];
|
||||
size: string[];
|
||||
write: string[];
|
||||
}
|
||||
|
||||
export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
|
||||
const blocks = msg.fields.map((field, index) => field.isRepeated ? buildRepeatedBlock(field, index) : buildSingularBlock(field, index));
|
||||
|
||||
const L = [
|
||||
`function protobuf_encode_${msg.name}(obj) {`,
|
||||
` let size = 0;`,
|
||||
...blocks.flatMap(block => block.declare),
|
||||
...blocks.flatMap(block => block.size),
|
||||
` const buf = new Uint8Array(size);`,
|
||||
` let offset = 0;`,
|
||||
...blocks.flatMap(block => block.write),
|
||||
` return buf;`,
|
||||
`}`,
|
||||
];
|
||||
return L.join('\n');
|
||||
}
|
||||
|
||||
function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType, isMessage } = field;
|
||||
const valueVar = `_f${index}`;
|
||||
const cacheVar = `_c${index}`;
|
||||
const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length;
|
||||
|
||||
if (isMessage) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${valueVar} != null) {`,
|
||||
` ${cacheVar} = protobuf_encode_${typeName}(${valueVar});`,
|
||||
` const _len = ${cacheVar}.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null) {`,
|
||||
` const _data = ${cacheVar};`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = _data.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(_data, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'string') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar} !== "") {`,
|
||||
` ${cacheVar} = __utf8Len(${valueVar});`,
|
||||
` const _len = ${cacheVar};`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== "") {`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = ${cacheVar};`,
|
||||
writeVarint('_len', ' '),
|
||||
` offset = __utf8Write(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bytes') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar}.length > 0) {`,
|
||||
` const _len = ${valueVar}.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar}.length > 0) {`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = ${valueVar}.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(${valueVar}, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bool') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} === true) size += ${tagLength + 1};`],
|
||||
write: [
|
||||
` if (${valueVar} === true) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` buf[offset++] = 1;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isVarint64(typeName)) {
|
||||
const bigintExpr = bigintVarintExpr(typeName, valueVar);
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
` size += ${tagLength};`,
|
||||
` size += __varint64Size(_val);`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` offset = __writeVarint64(buf, offset, _val);`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'sint_32') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '),
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Varint) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
` const _val = ${valueVar} >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`${valueVar} >>> 0`, ' '),
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'float') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` offset = __writeFloat32(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit32) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` const _val = ${valueVar};`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'double') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFloat64(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isFixed64BigInt(typeName)) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0n) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFixed64(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit64) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` const _val = ${valueVar};`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return { declare: [], size: [], write: [] };
|
||||
}
|
||||
|
||||
function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType, isMessage } = field;
|
||||
const arrayVar = `_f${index}`;
|
||||
const cacheVar = `_c${index}`;
|
||||
const tagWireType = isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType;
|
||||
const tagLength = computeTagBytes(fieldNumber, tagWireType).length;
|
||||
|
||||
if (isMessage) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` ${cacheVar} = new Array(${arrayVar}.length);`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _data = protobuf_encode_${typeName}(${arrayVar}[_i]);`,
|
||||
` ${cacheVar}[_i] = _data;`,
|
||||
` const _len = _data.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _data = ${cacheVar}[_i];`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = _data.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(_data, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'string') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` ${cacheVar} = new Array(${arrayVar}.length);`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _len = __utf8Len(${arrayVar}[_i]);`,
|
||||
` ${cacheVar}[_i] = _len;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _len = ${cacheVar}[_i];`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
writeVarint('_len', ' '),
|
||||
` offset = __utf8Write(buf, offset, ${arrayVar}[_i]);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bytes') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _data = ${arrayVar}[_i];`,
|
||||
` const _len = _data.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _data = ${arrayVar}[_i];`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = _data.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(_data, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bool') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 1};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` buf[offset++] = ${arrayVar}[_i] ? 1 : 0;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isVarint64(typeName)) {
|
||||
const bigintExpr = bigintVarintExpr(typeName, `${arrayVar}[_i]`);
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
` size += ${tagLength};`,
|
||||
` size += __varint64Size(_val);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` offset = __writeVarint64(buf, offset, _val);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'sint_32') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _val = ((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0`, ' '),
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Varint) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _val = ${arrayVar}[_i] >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`${arrayVar}[_i] >>> 0`, ' '),
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'float') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` offset = __writeFloat32(buf, offset, ${arrayVar}[_i]);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit32) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` const _val = ${arrayVar}[_i];`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'double') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFloat64(buf, offset, ${arrayVar}[_i]);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isFixed64BigInt(typeName)) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFixed64(buf, offset, ${arrayVar}[_i]);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit64) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` const _val = ${arrayVar}[_i];`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return { declare: [], size: [], write: [] };
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import type { MessageRegistry } from '../ast/types.js';
|
||||
import { generateEncoder } from './encoder.js';
|
||||
import { generateDecoder } from './decoder.js';
|
||||
|
||||
/** Shared preamble: UTF-8 string helpers plus TextDecoder for decode. */
|
||||
const CODEGEN_PREAMBLE = `const __td = new TextDecoder();
|
||||
const __scratch = new DataView(new ArrayBuffer(8));
|
||||
function __utf8Len(value) {
|
||||
let length = 0;
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
const code = value.charCodeAt(i);
|
||||
if (code < 0x80) {
|
||||
length++;
|
||||
continue;
|
||||
}
|
||||
if (code < 0x800) {
|
||||
length += 2;
|
||||
continue;
|
||||
}
|
||||
if ((code & 0xfc00) === 0xd800) {
|
||||
if (i + 1 < value.length) {
|
||||
const next = value.charCodeAt(i + 1);
|
||||
if ((next & 0xfc00) === 0xdc00) {
|
||||
length += 4;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
length += 3;
|
||||
continue;
|
||||
}
|
||||
if ((code & 0xfc00) === 0xdc00) {
|
||||
length += 3;
|
||||
continue;
|
||||
}
|
||||
length += 3;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
function __utf8Write(buf, offset, value) {
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
let code = value.charCodeAt(i);
|
||||
if (code < 0x80) {
|
||||
buf[offset++] = code;
|
||||
continue;
|
||||
}
|
||||
if (code < 0x800) {
|
||||
buf[offset++] = 0xc0 | (code >> 6);
|
||||
buf[offset++] = 0x80 | (code & 0x3f);
|
||||
continue;
|
||||
}
|
||||
if ((code & 0xfc00) === 0xd800) {
|
||||
if (i + 1 < value.length) {
|
||||
const next = value.charCodeAt(i + 1);
|
||||
if ((next & 0xfc00) === 0xdc00) {
|
||||
const point = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000;
|
||||
buf[offset++] = 0xf0 | (point >> 18);
|
||||
buf[offset++] = 0x80 | ((point >> 12) & 0x3f);
|
||||
buf[offset++] = 0x80 | ((point >> 6) & 0x3f);
|
||||
buf[offset++] = 0x80 | (point & 0x3f);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
code = 0xfffd;
|
||||
} else if ((code & 0xfc00) === 0xdc00) {
|
||||
code = 0xfffd;
|
||||
}
|
||||
buf[offset++] = 0xe0 | (code >> 12);
|
||||
buf[offset++] = 0x80 | ((code >> 6) & 0x3f);
|
||||
buf[offset++] = 0x80 | (code & 0x3f);
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
function __varint64Size(value) {
|
||||
let size = 1;
|
||||
while (value > 0x7fn) {
|
||||
value >>= 7n;
|
||||
size++;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
function __writeVarint64(buf, offset, value) {
|
||||
while (value > 0x7fn) {
|
||||
buf[offset++] = Number((value & 0x7fn) | 0x80n);
|
||||
value >>= 7n;
|
||||
}
|
||||
buf[offset++] = Number(value);
|
||||
return offset;
|
||||
}
|
||||
function __zigZagEncode64(value) {
|
||||
value = BigInt.asIntN(64, value);
|
||||
return BigInt.asUintN(64, (value << 1n) ^ (value >> 63n));
|
||||
}
|
||||
function __zigZagDecode64(value) {
|
||||
return BigInt.asIntN(64, (value >> 1n) ^ -(value & 1n));
|
||||
}
|
||||
function __writeFloat32(buf, offset, value) {
|
||||
__scratch.setFloat32(0, value, true);
|
||||
buf[offset++] = __scratch.getUint8(0);
|
||||
buf[offset++] = __scratch.getUint8(1);
|
||||
buf[offset++] = __scratch.getUint8(2);
|
||||
buf[offset++] = __scratch.getUint8(3);
|
||||
return offset;
|
||||
}
|
||||
function __readFloat32(data, offset) {
|
||||
__scratch.setUint8(0, data[offset]);
|
||||
__scratch.setUint8(1, data[offset + 1]);
|
||||
__scratch.setUint8(2, data[offset + 2]);
|
||||
__scratch.setUint8(3, data[offset + 3]);
|
||||
return __scratch.getFloat32(0, true);
|
||||
}
|
||||
function __writeFloat64(buf, offset, value) {
|
||||
__scratch.setFloat64(0, value, true);
|
||||
buf[offset++] = __scratch.getUint8(0);
|
||||
buf[offset++] = __scratch.getUint8(1);
|
||||
buf[offset++] = __scratch.getUint8(2);
|
||||
buf[offset++] = __scratch.getUint8(3);
|
||||
buf[offset++] = __scratch.getUint8(4);
|
||||
buf[offset++] = __scratch.getUint8(5);
|
||||
buf[offset++] = __scratch.getUint8(6);
|
||||
buf[offset++] = __scratch.getUint8(7);
|
||||
return offset;
|
||||
}
|
||||
function __readFloat64(data, offset) {
|
||||
__scratch.setUint8(0, data[offset]);
|
||||
__scratch.setUint8(1, data[offset + 1]);
|
||||
__scratch.setUint8(2, data[offset + 2]);
|
||||
__scratch.setUint8(3, data[offset + 3]);
|
||||
__scratch.setUint8(4, data[offset + 4]);
|
||||
__scratch.setUint8(5, data[offset + 5]);
|
||||
__scratch.setUint8(6, data[offset + 6]);
|
||||
__scratch.setUint8(7, data[offset + 7]);
|
||||
return __scratch.getFloat64(0, true);
|
||||
}
|
||||
function __writeFixed64(buf, offset, value) {
|
||||
value = BigInt.asUintN(64, value);
|
||||
buf[offset++] = Number(value & 0xffn);
|
||||
buf[offset++] = Number((value >> 8n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 16n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 24n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 32n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 40n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 48n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 56n) & 0xffn);
|
||||
return offset;
|
||||
}
|
||||
function __readFixed64(data, offset) {
|
||||
return BigInt(data[offset])
|
||||
| (BigInt(data[offset + 1]) << 8n)
|
||||
| (BigInt(data[offset + 2]) << 16n)
|
||||
| (BigInt(data[offset + 3]) << 24n)
|
||||
| (BigInt(data[offset + 4]) << 32n)
|
||||
| (BigInt(data[offset + 5]) << 40n)
|
||||
| (BigInt(data[offset + 6]) << 48n)
|
||||
| (BigInt(data[offset + 7]) << 56n);
|
||||
}`;
|
||||
|
||||
/**
|
||||
* Generate fully self-contained encode/decode source code.
|
||||
* 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');
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Protobuf wire format helpers — used directly by wire.test.ts
|
||||
// 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);
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
export function writeTag(fieldNumber: number, wireType: number, buf: number[]): void {
|
||||
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]);
|
||||
}
|
||||
|
||||
export function readString(data: Uint8Array, offset: number, length: number): string {
|
||||
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]);
|
||||
}
|
||||
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { Plugin } from 'vite';
|
||||
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';
|
||||
import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
|
||||
import { createRuntimeMap, type RuntimeMapCallSite } from './runtime-map.js';
|
||||
|
||||
export interface ProtobufRuntimeMapPluginOptions {
|
||||
enabled?: boolean;
|
||||
fileName?: string;
|
||||
}
|
||||
|
||||
export interface ProtobufVitePluginOptions {
|
||||
runtimeMap?: ProtobufRuntimeMapPluginOptions;
|
||||
}
|
||||
|
||||
interface RuntimeMapFileEntry {
|
||||
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';
|
||||
|
||||
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;
|
||||
|
||||
const imported = resolveImports(code, cleanId, fileCache);
|
||||
const { registry, callSites, sourceFile } = analyze(code, cleanId, imported);
|
||||
if (registry.size === 0 && callSites.length === 0) return null;
|
||||
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
if (used.registry.size === 0) {
|
||||
runtimeMapByFile.delete(cleanId);
|
||||
return null;
|
||||
}
|
||||
|
||||
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,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
const generatedCode = generateCode(used.registry);
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
if (!hasReplacements && generatedCode === '') return null;
|
||||
|
||||
return { code: generatedCode + '\n' + transformedCode, map: null };
|
||||
},
|
||||
|
||||
handleHotUpdate({ file }) {
|
||||
if (file.endsWith('.ts')) {
|
||||
fileCache.delete(file);
|
||||
runtimeMapByFile.delete(file);
|
||||
}
|
||||
},
|
||||
|
||||
generateBundle() {
|
||||
if (!runtimeMapEnabled) return;
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
export type { ProtobufRuntimeMap, RuntimeMapCallSite } from './runtime-map.js';
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { MessageRegistry, ProtobufField, ProtobufMessage } from './ast/types.js';
|
||||
|
||||
export type RuntimeMapFnName = 'protobuf_encode' | 'protobuf_decode';
|
||||
|
||||
export interface RuntimeMapCallSite {
|
||||
file: string;
|
||||
line: number;
|
||||
column: number;
|
||||
fnName: RuntimeMapFnName;
|
||||
typeName: string;
|
||||
}
|
||||
|
||||
export interface ProtobufRuntimeMap {
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
function cloneMessage(msg: ProtobufMessage): ProtobufMessage {
|
||||
return {
|
||||
name: msg.name,
|
||||
fields: msg.fields.map(cloneField),
|
||||
};
|
||||
}
|
||||
|
||||
export function registryToRuntimeMapMessages(registry: MessageRegistry): ProtobufMessage[] {
|
||||
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;
|
||||
}
|
||||
|
||||
export function normalizeRuntimeMapPath(filePath: string): string {
|
||||
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),
|
||||
};
|
||||
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()],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* Runtime fallback functions.
|
||||
* If the Vite plugin is active, calls to protobuf_encode/decode are replaced
|
||||
* at compile-time with generated type-specific functions.
|
||||
* If NOT transformed, these fallbacks throw to alert the developer.
|
||||
*/
|
||||
import type { MessageRegistry } from './ast/types.js';
|
||||
import { buildDependencyRegistry } from './ast/dependency-graph.js';
|
||||
import { generateCode } from './codegen/generator.js';
|
||||
import {
|
||||
normalizeRuntimeMapPath,
|
||||
runtimeMapToRegistry,
|
||||
type ProtobufRuntimeMap,
|
||||
type RuntimeMapCallSite,
|
||||
type RuntimeMapFnName,
|
||||
} from './runtime-map.js';
|
||||
|
||||
type DynamicEncode = (params: unknown) => Uint8Array;
|
||||
type DynamicDecode = (data: Uint8Array) => unknown;
|
||||
|
||||
interface DynamicTypeFns {
|
||||
encode?: DynamicEncode;
|
||||
decode?: DynamicDecode;
|
||||
}
|
||||
|
||||
interface StackFrame {
|
||||
file: string;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
const DYNAMIC_MISS = Symbol('snowluma-proton-dynamic-miss');
|
||||
|
||||
let runtimeMapFallback: ProtobufRuntimeMap | null = null;
|
||||
let runtimeMapRegistry: MessageRegistry | null = null;
|
||||
let runtimeMapCallSites: RuntimeMapCallSite[] = [];
|
||||
const dynamicTypeCache = new Map<string, DynamicTypeFns>();
|
||||
|
||||
/**
|
||||
* Enable dynamic runtime fallback from a pre-collected map file.
|
||||
* 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();
|
||||
}
|
||||
|
||||
/** Disable dynamic runtime fallback and clear all generated function caches. */
|
||||
export function protobuf_disableRuntimeMapFallback(): void {
|
||||
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;
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const caller = getFirstUserFrame();
|
||||
if (!caller) return DYNAMIC_MISS;
|
||||
|
||||
const callSite = resolveCallSite(fnName, caller);
|
||||
if (!callSite) return DYNAMIC_MISS;
|
||||
|
||||
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 subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]);
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function getFirstUserFrame(): StackFrame | null {
|
||||
const err = new Error();
|
||||
if (!err.stack) return null;
|
||||
|
||||
const lines = err.stack.split('\n').slice(1);
|
||||
for (const raw of lines) {
|
||||
const frame = parseStackLine(raw);
|
||||
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;
|
||||
|
||||
let location = trimmed;
|
||||
const atPrefix = 'at ';
|
||||
if (location.startsWith(atPrefix)) {
|
||||
location = location.slice(atPrefix.length).trim();
|
||||
}
|
||||
|
||||
const openParen = location.lastIndexOf('(');
|
||||
if (openParen >= 0 && location.endsWith(')')) {
|
||||
location = location.slice(openParen + 1, -1);
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
function pathsLikelySame(a: string, b: string): boolean {
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { MessageRegistry } from '../ast/types.js';
|
||||
import type { CallSiteRecord } from '../ast/analyzer.js';
|
||||
import { createImportedTypeNameResolver, typeNodeToMangledName } from '../ast/utils.js';
|
||||
import { collectProtobufImportBindings, matchProtobufCallSite } from '../ast/callsite.js';
|
||||
import ts from 'typescript';
|
||||
|
||||
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,
|
||||
): { transformedCode: string; hasReplacements: boolean } {
|
||||
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}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
return applyReplacements(code, sf, callSites, registry);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { WireType } from '../../src/ast/types';
|
||||
import { loadFixture } from '../helpers';
|
||||
|
||||
describe('AST analyzer', () => {
|
||||
it('collects TestProtobuf with correct fields', () => {
|
||||
const registry = analyzeSource(loadFixture('real.ts'), 'real.ts');
|
||||
const msg = registry.get('TestProtobuf')!;
|
||||
expect(msg).toBeDefined();
|
||||
expect(msg.fields).toHaveLength(1);
|
||||
expect(msg.fields[0]).toMatchObject({ name: 'name', fieldNumber: 1, typeName: 'uint_32', isMessage: false });
|
||||
});
|
||||
|
||||
it('collects nested message field', () => {
|
||||
const registry = analyzeSource(loadFixture('real.ts'), 'real.ts');
|
||||
const msg = registry.get('TestProtobufOutput')!;
|
||||
expect(msg.fields[0]).toMatchObject({ name: 'name', fieldNumber: 1, typeName: 'TestProtobuf', isMessage: true });
|
||||
});
|
||||
|
||||
it('topological order: dependencies first', () => {
|
||||
const keys = [...analyzeSource(loadFixture('real.ts'), 'real.ts').keys()];
|
||||
expect(keys.indexOf('TestProtobuf')).toBeLessThan(keys.indexOf('TestProtobufOutput'));
|
||||
});
|
||||
|
||||
it('skips generic interfaces (no call sites)', () => {
|
||||
expect(analyzeSource(loadFixture('generic-template.ts'), 'g.ts').size).toBe(0);
|
||||
});
|
||||
|
||||
it('returns empty for non-pb interfaces', () => {
|
||||
expect(analyzeSource(loadFixture('no-pb.ts'), 'no.ts').size).toBe(0);
|
||||
});
|
||||
|
||||
it('handles multiple fields', () => {
|
||||
const msg = analyzeSource(loadFixture('multi-field.ts'), 't.ts').get('UserProfile')!;
|
||||
expect(msg.fields).toHaveLength(3);
|
||||
expect(msg.fields[0]).toMatchObject({ name: 'id', fieldNumber: 1, typeName: 'uint_32' });
|
||||
expect(msg.fields[1]).toMatchObject({ name: 'username', fieldNumber: 2, typeName: 'string' });
|
||||
expect(msg.fields[2]).toMatchObject({ name: 'active', fieldNumber: 3, typeName: 'bool' });
|
||||
});
|
||||
|
||||
it('collects repeated fields', () => {
|
||||
const msg = analyzeSource(loadFixture('repeated.ts'), 't.ts').get('RepeatedMsg')!;
|
||||
expect(msg.fields).toHaveLength(2);
|
||||
expect(msg.fields[0]).toMatchObject({ name: 'ids', fieldNumber: 1, typeName: 'uint_32', isRepeated: true });
|
||||
expect(msg.fields[1]).toMatchObject({ name: 'names', fieldNumber: 2, typeName: 'string', isRepeated: true });
|
||||
});
|
||||
|
||||
it('monomorphizes generics from call sites', () => {
|
||||
const registry = analyzeSource(loadFixture('generic-usage.ts'), 'g.ts');
|
||||
expect(registry.has('TestProtobufAny__string')).toBe(true);
|
||||
expect(registry.has('TestProtobufAny__TestProtobufAny__string')).toBe(true);
|
||||
});
|
||||
|
||||
// ── Edge cases (originally silently dropped / wrong wire type) ──────
|
||||
|
||||
it('edge: monomorphizes a generic-instantiated field on a concrete interface', () => {
|
||||
// Regression: a concrete interface with `pb<N, Wrapper<T>>` previously
|
||||
// resolved the field's typeName to the bare identifier `"Wrapper"` and
|
||||
// never enqueued `Wrapper<T>` for monomorphization. The field was left
|
||||
// with the placeholder WireType.Varint, corrupting the wire format.
|
||||
const registry = analyzeSource(loadFixture('nested-generic-field.ts'), 'n.ts');
|
||||
|
||||
expect(registry.has('Wrapper__uint_32')).toBe(true);
|
||||
|
||||
const container = registry.get('Container')!;
|
||||
expect(container).toBeDefined();
|
||||
expect(container.fields[0]).toMatchObject({
|
||||
name: 'wrapped',
|
||||
fieldNumber: 5,
|
||||
typeName: 'Wrapper__uint_32',
|
||||
isMessage: true,
|
||||
wireType: WireType.LengthDelim,
|
||||
});
|
||||
});
|
||||
|
||||
it('edge: monomorphizes a generic-instantiated field on a generic template', () => {
|
||||
// Regression: a generic template field typed as `pb<N, Wrapper<U>>` —
|
||||
// where `U` is the outer template's type param — was stored with the
|
||||
// mangled-but-unsubstituted name `'Wrapper__U'` and never re-instantiated
|
||||
// with the concrete substitution at monomorphization time. The field
|
||||
// ended up referencing `Wrapper__U` instead of `Wrapper__uint_32` and the
|
||||
// inner mangled instantiation was missing from the registry.
|
||||
const registry = analyzeSource(loadFixture('generic-with-generic-field.ts'), 'g.ts');
|
||||
|
||||
expect(registry.has('Outer__uint_32')).toBe(true);
|
||||
expect(registry.has('Wrapper__uint_32')).toBe(true);
|
||||
|
||||
const outer = registry.get('Outer__uint_32')!;
|
||||
expect(outer.fields[0]).toMatchObject({
|
||||
name: 'wrapped',
|
||||
fieldNumber: 5,
|
||||
typeName: 'Wrapper__uint_32',
|
||||
isMessage: true,
|
||||
wireType: WireType.LengthDelim,
|
||||
});
|
||||
|
||||
const wrapper = registry.get('Wrapper__uint_32')!;
|
||||
expect(wrapper.fields[0]).toMatchObject({
|
||||
name: 'value',
|
||||
fieldNumber: 1,
|
||||
typeName: 'uint_32',
|
||||
isMessage: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('edge: throws when a field references an unresolved type name', () => {
|
||||
// Defensive guard: anything that escapes the analyzer's type tracking
|
||||
// (unions, intersections, mapped/conditional types, `Partial<T>`, etc.)
|
||||
// used to silently leak `WireType.Varint` into the codegen. Now it has
|
||||
// to fail loudly so future edge cases surface immediately.
|
||||
const source = `
|
||||
interface BadMsg {
|
||||
weird: pb<1, MissingType>;
|
||||
}
|
||||
const buf = protobuf_encode<BadMsg>({} as any);
|
||||
`;
|
||||
expect(() => analyzeSource(source, 'b.ts')).toThrow(/MissingType/);
|
||||
});
|
||||
|
||||
it('edge: recognises aliased pb / pb_repeated marker imports', () => {
|
||||
// Regression: `parsePbTypeRef` compared the literal type-ref identifier
|
||||
// text against the constants `'pb'` / `'pb_repeated'`. With
|
||||
// `import { pb as P }` the text became `'P'`, so every field on the
|
||||
// interface was silently dropped and `Aliased` never made it into the
|
||||
// registry.
|
||||
const registry = analyzeSource(loadFixture('aliased-pb-marker.ts'), 'a.ts');
|
||||
|
||||
const aliased = registry.get('Aliased')!;
|
||||
expect(aliased).toBeDefined();
|
||||
expect(aliased.fields).toHaveLength(2);
|
||||
expect(aliased.fields[0]).toMatchObject({
|
||||
name: 'id',
|
||||
fieldNumber: 1,
|
||||
typeName: 'uint_32',
|
||||
isRepeated: false,
|
||||
});
|
||||
expect(aliased.fields[1]).toMatchObject({
|
||||
name: 'tags',
|
||||
fieldNumber: 2,
|
||||
typeName: 'string',
|
||||
isRepeated: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { readFileSync } from 'fs';
|
||||
import { resolve, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer';
|
||||
import { generateCode } from '../../src/codegen/generator';
|
||||
import { applyReplacements } from '../../src/transform/replacer';
|
||||
import { resolveImports, type ParsedFileEntry } from '../../src/ast/import-resolver';
|
||||
import { execAndGet } from '../helpers';
|
||||
|
||||
const crossDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures', 'cross-file');
|
||||
|
||||
function loadCross(name: string): { code: string; path: string } {
|
||||
const path = resolve(crossDir, name);
|
||||
return { code: readFileSync(path, 'utf-8'), path };
|
||||
}
|
||||
|
||||
describe('cross-file import resolution', () => {
|
||||
// ── Scenario A: imported type in encode/decode call site ──────────
|
||||
|
||||
it('resolves imported type for protobuf_encode/decode call site', () => {
|
||||
const { code, path } = loadCross('consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.concrete.some(m => m.name === 'UserMsg')).toBe(true);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
expect(registry.has('UserMsg')).toBe(true);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_UserMsg');
|
||||
expect(transformedCode).toContain('protobuf_decode_UserMsg');
|
||||
});
|
||||
|
||||
it('Scenario A round-trip', () => {
|
||||
const { code, path } = loadCross('consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_UserMsg({ id: 42, name: 'alice' });
|
||||
globalThis.__r = protobuf_decode_UserMsg(enc);
|
||||
`, '__r');
|
||||
expect(result.id).toBe(42);
|
||||
expect(result.name).toBe('alice');
|
||||
});
|
||||
|
||||
// ── Scenario B: imported type as pb<> field ──────────────────────
|
||||
|
||||
it('resolves imported nested message type', () => {
|
||||
const { code, path } = loadCross('outer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.concrete.some(m => m.name === 'Inner')).toBe(true);
|
||||
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
expect(registry.has('Inner')).toBe(true);
|
||||
expect(registry.has('Outer')).toBe(true);
|
||||
|
||||
const outer = registry.get('Outer')!;
|
||||
const innerField = outer.fields.find(f => f.name === 'inner')!;
|
||||
expect(innerField.isMessage).toBe(true);
|
||||
});
|
||||
|
||||
it('Scenario B round-trip', () => {
|
||||
const { code, path } = loadCross('outer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Outer({ inner: { value: 42 } });
|
||||
globalThis.__r = protobuf_decode_Outer(enc);
|
||||
`, '__r');
|
||||
expect(result.inner.value).toBe(42);
|
||||
});
|
||||
|
||||
// ── Generic template import ──────────────────────────────────────
|
||||
|
||||
it('resolves imported generic template', () => {
|
||||
const { code, path } = loadCross('generic-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.templates.has('Wrapper')).toBe(true);
|
||||
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
expect(registry.has('Wrapper__string')).toBe(true);
|
||||
});
|
||||
|
||||
it('generic import round-trip', () => {
|
||||
const { code, path } = loadCross('generic-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Wrapper__string({ value: 'hello' });
|
||||
globalThis.__r = protobuf_decode_Wrapper__string(enc);
|
||||
`, '__r');
|
||||
expect(result.value).toBe('hello');
|
||||
});
|
||||
|
||||
it('resolves generic type passed through imported wrapper functions', () => {
|
||||
const { code, path } = loadCross('wrapper-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.templates.has('Wrapper')).toBe(true);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(2);
|
||||
expect(used.callSites[0].fnName).toBe('protobuf_encode');
|
||||
expect(used.callSites[1].fnName).toBe('protobuf_decode');
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
});
|
||||
|
||||
it('handles wrapper aliases, arrows, nested generics, and non-first generic forwarding', () => {
|
||||
const { code, path } = loadCross('wrapper-edge-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(5);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__Wrapper__string(');
|
||||
expect(transformedCode).toContain('passthroughOnly<Wrapper<string>>');
|
||||
});
|
||||
|
||||
it('handles local wrapper functions in the entry file', () => {
|
||||
const { code, path } = loadCross('local-wrapper-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(2);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
});
|
||||
|
||||
it('handles complex wrapper objects, branches, nested helpers, and chains', () => {
|
||||
const { code, path } = loadCross('wrapper-complex-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(7);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
|
||||
expect(transformedCode).not.toContain('encodeChained<Wrapper<string>>');
|
||||
});
|
||||
|
||||
it('handles wrapper protobuf type derived from another generic type', () => {
|
||||
const { code, path } = loadCross('wrapper-type-source-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('Wrapper__string')).toBe(true);
|
||||
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
|
||||
expect(used.callSites).toHaveLength(5);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
|
||||
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
|
||||
expect(transformedCode).not.toContain('encodeBoxed<string>');
|
||||
});
|
||||
|
||||
// ── Transitive imports ───────────────────────────────────────────
|
||||
|
||||
it('resolves transitive imports (A → B → C)', () => {
|
||||
const { code, path } = loadCross('top.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.concrete.some(m => m.name === 'Mid')).toBe(true);
|
||||
expect(imported.concrete.some(m => m.name === 'Deep')).toBe(true);
|
||||
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
expect(registry.has('Top')).toBe(true);
|
||||
expect(registry.has('Mid')).toBe(true);
|
||||
expect(registry.has('Deep')).toBe(true);
|
||||
});
|
||||
|
||||
it('transitive import round-trip', () => {
|
||||
const { code, path } = loadCross('top.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Top({ nested: { inner: { val: 99 } } });
|
||||
globalThis.__r = protobuf_decode_Top(enc);
|
||||
`, '__r');
|
||||
expect(result.nested.inner.val).toBe(99);
|
||||
});
|
||||
|
||||
// ── Cache behavior ───────────────────────────────────────────────
|
||||
|
||||
it('uses cache on repeated resolves', () => {
|
||||
const { code, path } = loadCross('consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
|
||||
resolveImports(code, path, cache);
|
||||
expect(cache.size).toBeGreaterThan(0);
|
||||
|
||||
const cached = new Map(cache);
|
||||
resolveImports(code, path, cache);
|
||||
|
||||
// Same entries, not re-created
|
||||
for (const [key, val] of cache) {
|
||||
expect(val).toBe(cached.get(key));
|
||||
}
|
||||
});
|
||||
|
||||
// ── Graceful fallback ────────────────────────────────────────────
|
||||
|
||||
it('handles missing import file gracefully', () => {
|
||||
const code = `import type { Ghost } from './nonexistent';\nconst x = 1;`;
|
||||
const fakePath = resolve(crossDir, 'fake.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
|
||||
const imported = resolveImports(code, fakePath, cache);
|
||||
expect(imported.concrete).toEqual([]);
|
||||
expect(imported.templates.size).toBe(0);
|
||||
});
|
||||
|
||||
it('only resolves imports reachable from protobuf call roots', () => {
|
||||
const code = `
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { UserMsg } from './types';
|
||||
import type { Inner } from './inner';
|
||||
|
||||
const buf = protobuf_encode<UserMsg>({ id: 42, name: 'alice' });
|
||||
`;
|
||||
const fakePath = resolve(crossDir, 'on-demand.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
|
||||
const imported = resolveImports(code, fakePath, cache);
|
||||
|
||||
expect(imported.concrete.map(m => m.name)).toEqual(['UserMsg']);
|
||||
expect(cache.has(resolve(crossDir, 'types.ts'))).toBe(true);
|
||||
expect(cache.has(resolve(crossDir, 'inner.ts'))).toBe(false);
|
||||
});
|
||||
|
||||
// ── Value import (non-type import) ───────────────────────────────
|
||||
|
||||
it('resolves value import { SimpleMessage } (not import type)', () => {
|
||||
const { code, path } = loadCross('value-import-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
expect(imported.concrete.some(m => m.name === 'SimpleMessage')).toBe(true);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
expect(registry.has('SimpleMessage')).toBe(true);
|
||||
expect(callSites.length).toBe(2);
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_SimpleMessage(');
|
||||
expect(transformedCode).toContain('protobuf_decode_SimpleMessage(');
|
||||
});
|
||||
|
||||
it('value import round-trip', () => {
|
||||
const { code, path } = loadCross('value-import-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
const registry = analyzeSource(code, path, imported);
|
||||
const gen = generateCode(registry);
|
||||
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_SimpleMessage({ id: 42 });
|
||||
globalThis.__r = protobuf_decode_SimpleMessage(enc);
|
||||
`, '__r');
|
||||
expect(result.id).toBe(42);
|
||||
});
|
||||
|
||||
it('canonicalizes imported type aliases to the original message name', () => {
|
||||
const { code, path } = loadCross('aliased-consumer.ts');
|
||||
const cache = new Map<string, ParsedFileEntry>();
|
||||
const imported = resolveImports(code, path, cache);
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, path, imported);
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('UserMsg')).toBe(true);
|
||||
expect(used.registry.has('AliasMsg')).toBe(false);
|
||||
expect(used.callSites).toHaveLength(2);
|
||||
expect(used.callSites[0].typeName).toBe('UserMsg');
|
||||
expect(used.callSites[1].typeName).toBe('UserMsg');
|
||||
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_UserMsg(');
|
||||
expect(transformedCode).toContain('protobuf_decode_UserMsg(');
|
||||
expect(transformedCode).not.toContain('protobuf_encode_AliasMsg(');
|
||||
expect(transformedCode).not.toContain('protobuf_decode_AliasMsg(');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { generateCode } from '../../src/codegen/generator';
|
||||
import { loadFixture, execAndGet } from '../helpers';
|
||||
|
||||
/** Analyze fixture → generate → eval → return encode/decode pair */
|
||||
function makeRoundTrip(fixtureName: string, msgName: string) {
|
||||
const gen = generateCode(analyzeSource(loadFixture(fixtureName), fixtureName));
|
||||
new Function(gen + `\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`)();
|
||||
const enc = (globalThis as any).__enc as (obj: any) => Uint8Array;
|
||||
const dec = (globalThis as any).__dec as (data: Uint8Array) => any;
|
||||
delete (globalThis as any).__enc;
|
||||
delete (globalThis as any).__dec;
|
||||
return { enc, dec };
|
||||
}
|
||||
|
||||
function makeRoundTripFromSchema(schema: string, msgName: string) {
|
||||
const gen = generateCode(analyzeSource(schema, `${msgName}.ts`));
|
||||
new Function(gen + `\nglobalThis.__enc = protobuf_encode_${msgName}; globalThis.__dec = protobuf_decode_${msgName};`)();
|
||||
const enc = (globalThis as any).__enc as (obj: any) => Uint8Array;
|
||||
const dec = (globalThis as any).__dec as (data: Uint8Array) => any;
|
||||
delete (globalThis as any).__enc;
|
||||
delete (globalThis as any).__dec;
|
||||
return { enc, dec };
|
||||
}
|
||||
|
||||
describe('code generator', () => {
|
||||
it('generates encode/decode for simple uint_32', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('simple.ts'), 't.ts'));
|
||||
expect(gen).toContain('function protobuf_encode_SimpleMsg(obj)');
|
||||
expect(gen).toContain('function protobuf_decode_SimpleMsg(data');
|
||||
// Tag for field 1, varint should be pre-computed as 0x08
|
||||
expect(gen).toContain('buf[offset++] = 8;');
|
||||
});
|
||||
|
||||
it('generates nested message code', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('nested.ts'), 't.ts'));
|
||||
expect(gen).toContain('protobuf_encode_Inner(');
|
||||
expect(gen).toContain('protobuf_decode_Inner(data, offset, offset + _len)');
|
||||
});
|
||||
|
||||
it('round-trip uint_32', () => {
|
||||
const { enc, dec } = makeRoundTrip('simple.ts', 'SimpleMsg');
|
||||
expect(dec(enc({ value: 42 })).value).toBe(42);
|
||||
});
|
||||
|
||||
it('round-trip nested message', () => {
|
||||
const { enc, dec } = makeRoundTrip('nested.ts', 'Outer');
|
||||
expect(dec(enc({ inner: { value: 999 } })).inner.value).toBe(999);
|
||||
});
|
||||
|
||||
it('round-trip string', () => {
|
||||
const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg');
|
||||
expect(dec(enc({ text: 'hello world' })).text).toBe('hello world');
|
||||
});
|
||||
|
||||
it('round-trip unicode string', () => {
|
||||
const { enc, dec } = makeRoundTrip('string-msg.ts', 'StringMsg');
|
||||
expect(dec(enc({ text: '你好,protobuf🚀' })).text).toBe('你好,protobuf🚀');
|
||||
});
|
||||
|
||||
it('round-trip bool', () => {
|
||||
const { enc, dec } = makeRoundTrip('bool-msg.ts', 'BoolMsg');
|
||||
expect(dec(enc({ active: true })).active).toBe(true);
|
||||
const empty = enc({ active: false });
|
||||
expect(empty.length).toBe(0);
|
||||
expect(dec(empty).active).toBe(false);
|
||||
});
|
||||
|
||||
it('proto3 default encoding (0 → empty)', () => {
|
||||
const { enc } = makeRoundTrip('simple.ts', 'SimpleMsg');
|
||||
expect(enc({ value: 0 }).length).toBe(0);
|
||||
});
|
||||
|
||||
it('round-trip repeated uint_32', () => {
|
||||
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
|
||||
const result = dec(enc({ ids: [10, 20, 30], names: [] }));
|
||||
expect(result.ids).toEqual([10, 20, 30]);
|
||||
expect(result.names).toEqual([]);
|
||||
});
|
||||
|
||||
it('round-trip repeated string', () => {
|
||||
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
|
||||
const result = dec(enc({ ids: [], names: ['hello', 'world'] }));
|
||||
expect(result.ids).toEqual([]);
|
||||
expect(result.names).toEqual(['hello', 'world']);
|
||||
});
|
||||
|
||||
it('repeated empty arrays round-trip', () => {
|
||||
const { enc, dec } = makeRoundTrip('repeated.ts', 'RepeatedMsg');
|
||||
const result = dec(enc({ ids: [], names: [] }));
|
||||
expect(result.ids).toEqual([]);
|
||||
expect(result.names).toEqual([]);
|
||||
});
|
||||
|
||||
it('round-trip bigint-backed 64-bit integers', () => {
|
||||
const schema = `
|
||||
interface BigIntMsg {
|
||||
unsigned: pb<1, uint_64>;
|
||||
signed: pb<2, int_64>;
|
||||
zigzag: pb<3, sint_64>;
|
||||
fixed: pb<4, fixed_64>;
|
||||
sfixed: pb<5, sfixed_64>;
|
||||
ids: pb_repeated<6, uint_64>;
|
||||
}`;
|
||||
const { enc, dec } = makeRoundTripFromSchema(schema, 'BigIntMsg');
|
||||
const input = {
|
||||
unsigned: 18446744073709551615n,
|
||||
signed: -1n,
|
||||
zigzag: -1234567890123456789n,
|
||||
fixed: 0x0102030405060708n,
|
||||
sfixed: -0x0102030405060708n,
|
||||
ids: [1n, 2n, 9007199254740993n],
|
||||
};
|
||||
expect(dec(enc(input))).toEqual(input);
|
||||
});
|
||||
|
||||
it('round-trip sint_32 with negative values', () => {
|
||||
const schema = `
|
||||
interface Sint32Msg {
|
||||
value: pb<1, sint_32>;
|
||||
values: pb_repeated<2, sint_32>;
|
||||
}`;
|
||||
const { enc, dec } = makeRoundTripFromSchema(schema, 'Sint32Msg');
|
||||
const input = { value: -789, values: [-1, 0, 1, -789, 2147483647, -2147483648] };
|
||||
expect(dec(enc(input))).toEqual(input);
|
||||
});
|
||||
|
||||
it('round-trip double as ieee754 number', () => {
|
||||
const schema = `
|
||||
interface DoubleMsg {
|
||||
value: pb<1, double>;
|
||||
values: pb_repeated<2, double>;
|
||||
}`;
|
||||
const { enc, dec } = makeRoundTripFromSchema(schema, 'DoubleMsg');
|
||||
const result = dec(enc({ value: Math.PI, values: [Math.E, -0.5] }));
|
||||
expect(result.value).toBeCloseTo(Math.PI);
|
||||
expect(result.values[0]).toBeCloseTo(Math.E);
|
||||
expect(result.values[1]).toBeCloseTo(-0.5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,307 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import protobufVitePlugin from '../../src/index';
|
||||
import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer';
|
||||
import { generateCode } from '../../src/codegen/generator';
|
||||
import { replaceCallSites } from '../../src/transform/replacer';
|
||||
import { loadFixture, execAndGet } from '../helpers';
|
||||
|
||||
describe('plugin integration', () => {
|
||||
it('full transform pipeline', () => {
|
||||
const code = loadFixture('real.ts');
|
||||
const registry = analyzeSource(code, 'real.ts');
|
||||
expect(registry.size).toBe(2);
|
||||
expect([...registry.keys()]).toEqual(['TestProtobuf', 'TestProtobufOutput']);
|
||||
|
||||
const gen = generateCode(registry);
|
||||
expect(gen).toContain('protobuf_encode_TestProtobuf');
|
||||
expect(gen).toContain('protobuf_decode_TestProtobufOutput');
|
||||
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_TestProtobuf({ name: 123 })');
|
||||
expect(transformedCode).toContain('protobuf_decode_TestProtobufOutput(data)');
|
||||
});
|
||||
|
||||
it('end-to-end round-trip', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const wr = protobuf_encode_TestProtobufOutput({ name: { name: 123 } });
|
||||
globalThis.__r = protobuf_decode_TestProtobufOutput(wr);
|
||||
`, '__r');
|
||||
expect(result.name.name).toBe(123);
|
||||
});
|
||||
|
||||
it('wire format: TestProtobuf { name: 123 }', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts'));
|
||||
const enc = execAndGet<Uint8Array>(gen + `\n
|
||||
globalThis.__r = protobuf_encode_TestProtobuf({ name: 123 });
|
||||
`, '__r');
|
||||
expect(enc.length).toBe(2);
|
||||
expect(enc[0]).toBe(0x08);
|
||||
expect(enc[1]).toBe(123);
|
||||
});
|
||||
|
||||
it('wire format: nested message', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('real.ts'), 'real.ts'));
|
||||
const enc = execAndGet<Uint8Array>(gen + `\n
|
||||
globalThis.__r = protobuf_encode_TestProtobufOutput({ name: { name: 456 } });
|
||||
`, '__r');
|
||||
expect(enc[0]).toBe(0x0a);
|
||||
expect(enc[1]).toBe(3);
|
||||
expect(enc[2]).toBe(0x08);
|
||||
expect(enc[3]).toBe(0xc8);
|
||||
expect(enc[4]).toBe(0x03);
|
||||
});
|
||||
|
||||
it('multi-field round-trip', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('multi-field.ts'), 't.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_UserProfile({ id: 42, username: "alice", active: true });
|
||||
globalThis.__r = protobuf_decode_UserProfile(enc);
|
||||
`, '__r');
|
||||
expect(result.id).toBe(42);
|
||||
expect(result.username).toBe('alice');
|
||||
expect(result.active).toBe(true);
|
||||
});
|
||||
|
||||
// ── generic monomorphization ───────────────────────────────────────
|
||||
|
||||
it('generic monomorphization registry', () => {
|
||||
const registry = analyzeSource(loadFixture('generic-usage.ts'), 'g.ts');
|
||||
expect(registry.has('TestProtobufAny__string')).toBe(true);
|
||||
expect(registry.has('TestProtobufAny__TestProtobufAny__string')).toBe(true);
|
||||
});
|
||||
|
||||
it('generic round-trip', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('generic-usage.ts'), 'g.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_TestProtobufAny__TestProtobufAny__string({ name: { name: "hello" } });
|
||||
globalThis.__r = protobuf_decode_TestProtobufAny__TestProtobufAny__string(enc);
|
||||
`, '__r');
|
||||
expect(result.name.name).toBe('hello');
|
||||
});
|
||||
|
||||
// ── repeated fields ────────────────────────────────────────────────
|
||||
|
||||
it('repeated fields round-trip', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_RepeatedMsg({ ids: [10, 20, 30], names: ["foo", "bar"] });
|
||||
globalThis.__r = protobuf_decode_RepeatedMsg(enc);
|
||||
`, '__r');
|
||||
expect(result.ids).toEqual([10, 20, 30]);
|
||||
expect(result.names).toEqual(['foo', 'bar']);
|
||||
});
|
||||
|
||||
it('repeated empty arrays', () => {
|
||||
const gen = generateCode(analyzeSource(loadFixture('repeated.ts'), 't.ts'));
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_RepeatedMsg({ ids: [], names: [] });
|
||||
globalThis.__r = protobuf_decode_RepeatedMsg(enc);
|
||||
`, '__r');
|
||||
expect(result.ids).toEqual([]);
|
||||
expect(result.names).toEqual([]);
|
||||
});
|
||||
|
||||
// ── import-based usage ──────────────────────────────────────────────
|
||||
|
||||
it('handles code with import { protobuf_encode } from "@snowluma/proton"', () => {
|
||||
const code = `
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
|
||||
const buf = protobuf_encode<Msg>({ id: 1 });
|
||||
const decoded = protobuf_decode<Msg>(buf);
|
||||
`;
|
||||
const registry = analyzeSource(code, 'import-test.ts');
|
||||
expect(registry.has('Msg')).toBe(true);
|
||||
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Msg(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Msg(');
|
||||
// import line preserved
|
||||
expect(transformedCode).toContain("from '@snowluma/proton'");
|
||||
});
|
||||
|
||||
it('import-based round-trip', () => {
|
||||
const code = `
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; name: pb<2, string>; }
|
||||
|
||||
const buf = protobuf_encode<Msg>({ id: 42, name: 'test' });
|
||||
const decoded = protobuf_decode<Msg>(buf);
|
||||
`;
|
||||
const registry = analyzeSource(code, 'import-test.ts');
|
||||
const gen = generateCode(registry);
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Msg({ id: 42, name: 'test' });
|
||||
globalThis.__r = protobuf_decode_Msg(enc);
|
||||
`, '__r');
|
||||
expect(result.id).toBe(42);
|
||||
expect(result.name).toBe('test');
|
||||
});
|
||||
|
||||
it('runtime fallback throws error', async () => {
|
||||
const { protobuf_encode, protobuf_decode } = await import('../../src/runtime');
|
||||
expect(() => protobuf_encode({})).toThrow('not transformed');
|
||||
expect(() => protobuf_decode(new Uint8Array())).toThrow('not transformed');
|
||||
});
|
||||
|
||||
// ── import rename alias ─────────────────────────────────────────────
|
||||
|
||||
it('handles import { protobuf_encode as encode }', () => {
|
||||
const code = `
|
||||
import { protobuf_encode as encode, protobuf_decode as decode } from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
|
||||
const buf = encode<Msg>({ id: 1 });
|
||||
const decoded = decode<Msg>(buf);
|
||||
`;
|
||||
const registry = analyzeSource(code, 'alias-test.ts');
|
||||
expect(registry.has('Msg')).toBe(true);
|
||||
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_Msg(');
|
||||
expect(transformedCode).toContain('protobuf_decode_Msg(');
|
||||
// alias calls replaced, import preserved
|
||||
expect(transformedCode).not.toContain('encode<Msg>');
|
||||
expect(transformedCode).not.toContain('decode<Msg>');
|
||||
});
|
||||
|
||||
it('rename alias round-trip', () => {
|
||||
const code = `
|
||||
import { protobuf_encode as enc } from '@snowluma/proton';
|
||||
|
||||
interface Item { val: pb<1, uint_32>; name: pb<2, string>; }
|
||||
|
||||
const buf = enc<Item>({ val: 99, name: 'x' });
|
||||
`;
|
||||
const registry = analyzeSource(code, 'alias-rt.ts');
|
||||
const gen = generateCode(registry);
|
||||
const result = execAndGet<any>(gen + `\n
|
||||
const enc = protobuf_encode_Item({ val: 99, name: 'x' });
|
||||
globalThis.__r = protobuf_decode_Item(enc);
|
||||
`, '__r');
|
||||
expect(result.val).toBe(99);
|
||||
expect(result.name).toBe('x');
|
||||
});
|
||||
|
||||
it('collects call roots first and generates only used dependency closure', () => {
|
||||
const code = `
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
|
||||
interface Inner { id: pb<1, uint_32>; }
|
||||
interface UsedMsg { inner: pb<1, Inner>; }
|
||||
interface UnusedMsg { value: pb<1, string>; }
|
||||
|
||||
const buf = protobuf_encode<UsedMsg>({ inner: { id: 1 } });
|
||||
`;
|
||||
|
||||
const { registry, callSites, sourceFile } = analyze(code, 'used-only.ts');
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
|
||||
expect(used.registry.has('UsedMsg')).toBe(true);
|
||||
expect(used.registry.has('Inner')).toBe(true);
|
||||
expect(used.registry.has('UnusedMsg')).toBe(false);
|
||||
|
||||
const gen = generateCode(used.registry);
|
||||
expect(gen).toContain('protobuf_encode_UsedMsg');
|
||||
expect(gen).toContain('protobuf_encode_Inner');
|
||||
expect(gen).not.toContain('protobuf_encode_UnusedMsg');
|
||||
});
|
||||
|
||||
it('emits runtime map asset when runtimeMap is enabled', () => {
|
||||
const code = `
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
const buf = protobuf_encode<Msg>({ id: 1 });
|
||||
`;
|
||||
|
||||
const plugin = protobufVitePlugin({
|
||||
runtimeMap: {
|
||||
enabled: true,
|
||||
fileName: 'pb.runtime-map.json',
|
||||
},
|
||||
});
|
||||
|
||||
const transformHook = plugin.transform!;
|
||||
const transform = typeof transformHook === 'function' ? transformHook : transformHook.handler;
|
||||
const transformResult = transform.call({} as any, code, 'entry.ts');
|
||||
expect(transformResult).toBeTruthy();
|
||||
|
||||
const emitted: any[] = [];
|
||||
const generateHook = plugin.generateBundle!;
|
||||
const generateBundle = typeof generateHook === 'function' ? generateHook : generateHook.handler;
|
||||
const testContext: any = {
|
||||
emitFile(asset: any) {
|
||||
emitted.push(asset);
|
||||
return 'asset-id';
|
||||
},
|
||||
};
|
||||
|
||||
generateBundle.call(
|
||||
testContext,
|
||||
{} as any,
|
||||
{} as any,
|
||||
false,
|
||||
);
|
||||
|
||||
expect(emitted).toHaveLength(1);
|
||||
expect(emitted[0].type).toBe('asset');
|
||||
expect(emitted[0].fileName).toBe('pb.runtime-map.json');
|
||||
|
||||
const payload = JSON.parse(emitted[0].source);
|
||||
expect(payload.version).toBe(1);
|
||||
expect(payload.callSites).toHaveLength(1);
|
||||
expect(payload.callSites[0].fnName).toBe('protobuf_encode');
|
||||
expect(payload.callSites[0].typeName).toBe('Msg');
|
||||
});
|
||||
|
||||
it('emits canonical runtime map entries for imported type aliases', () => {
|
||||
const code = `
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import type { UserMsg as AliasMsg } from './types';
|
||||
|
||||
const buf = protobuf_encode<AliasMsg>({ id: 1, name: 'a' });
|
||||
const decoded = protobuf_decode<AliasMsg>(buf);
|
||||
`;
|
||||
|
||||
const plugin = protobufVitePlugin({
|
||||
runtimeMap: {
|
||||
enabled: true,
|
||||
fileName: 'pb.runtime-map.json',
|
||||
},
|
||||
});
|
||||
|
||||
const transformHook = plugin.transform!;
|
||||
const transform = typeof transformHook === 'function' ? transformHook : transformHook.handler;
|
||||
const transformResult = transform.call({} as any, code, 'test/fixtures/cross-file/aliased-consumer.ts');
|
||||
expect(transformResult).toBeTruthy();
|
||||
|
||||
const emitted: any[] = [];
|
||||
const generateHook = plugin.generateBundle!;
|
||||
const generateBundle = typeof generateHook === 'function' ? generateHook : generateHook.handler;
|
||||
const testContext: any = {
|
||||
emitFile(asset: any) {
|
||||
emitted.push(asset);
|
||||
return 'asset-id';
|
||||
},
|
||||
};
|
||||
|
||||
generateBundle.call(testContext, {} as any, {} as any, false);
|
||||
|
||||
expect(emitted).toHaveLength(1);
|
||||
const payload = JSON.parse(emitted[0].source);
|
||||
expect(payload.messages.some((msg: { name: string }) => msg.name === 'UserMsg')).toBe(true);
|
||||
expect(payload.messages.some((msg: { name: string }) => msg.name === 'AliasMsg')).toBe(false);
|
||||
expect(payload.callSites).toHaveLength(2);
|
||||
expect(payload.callSites[0].typeName).toBe('UserMsg');
|
||||
expect(payload.callSites[1].typeName).toBe('UserMsg');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { replaceCallSites } from '../../src/transform/replacer';
|
||||
import { loadFixture } from '../helpers';
|
||||
|
||||
describe('call-site replacer', () => {
|
||||
it('replaces protobuf_encode<T> with protobuf_encode_T', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst data = protobuf_encode<SimpleMsg>({ value: 1 });\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_SimpleMsg({ value: 1 })');
|
||||
expect(transformedCode).not.toContain('protobuf_encode<SimpleMsg>');
|
||||
});
|
||||
|
||||
it('replaces protobuf_decode<T>', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst result = protobuf_decode<SimpleMsg>(data);\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_decode_SimpleMsg(data)');
|
||||
});
|
||||
|
||||
it('replaces multiple calls', () => {
|
||||
const code = loadFixture('simple.ts') + `
|
||||
const a = protobuf_encode<SimpleMsg>({ value: 1 });
|
||||
const b = protobuf_decode<SimpleMsg>(a);
|
||||
`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode } = replaceCallSites(code, registry);
|
||||
expect(transformedCode).toContain('protobuf_encode_SimpleMsg({ value: 1 })');
|
||||
expect(transformedCode).toContain('protobuf_decode_SimpleMsg(a)');
|
||||
});
|
||||
|
||||
it('preserves await keyword', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst a = await protobuf_encode<SimpleMsg>({ value: 1 });\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode } = replaceCallSites(code, registry);
|
||||
expect(transformedCode).toContain('await protobuf_encode_SimpleMsg({ value: 1 })');
|
||||
});
|
||||
|
||||
it('returns hasReplacements=false when no calls match', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst x = 123;\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
expect(replaceCallSites(code, registry).hasReplacements).toBe(false);
|
||||
});
|
||||
|
||||
it('does not replace unknown type arguments', () => {
|
||||
const code = loadFixture('simple.ts') + `\nconst a = protobuf_encode<Unknown>({ v: 1 });\n`;
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { hasReplacements, transformedCode } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(false);
|
||||
expect(transformedCode).toContain('protobuf_encode<Unknown>');
|
||||
});
|
||||
|
||||
it('replaces generic call-sites with mangled names', () => {
|
||||
const code = loadFixture('generic-usage.ts');
|
||||
const registry = analyzeSource(code, 't.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('protobuf_encode_TestProtobufAny__TestProtobufAny__string');
|
||||
expect(transformedCode).toContain('protobuf_decode_TestProtobufAny__TestProtobufAny__string');
|
||||
});
|
||||
|
||||
it('replaces namespace import calls', () => {
|
||||
const code = `
|
||||
import * as pbx from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
|
||||
const a = pbx.protobuf_encode<Msg>({ id: 1 });
|
||||
const b = pbx.protobuf_decode<Msg>(a);
|
||||
`;
|
||||
const registry = analyzeSource(code, 'ns.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(true);
|
||||
expect(transformedCode).toContain('const a = protobuf_encode_Msg({ id: 1 });');
|
||||
expect(transformedCode).toContain('const b = protobuf_decode_Msg(a);');
|
||||
});
|
||||
|
||||
it('does not replace same-name imports from non-runtime modules', () => {
|
||||
const code = `
|
||||
import { protobuf_encode } from './other';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
|
||||
const a = protobuf_encode<Msg>({ id: 1 });
|
||||
`;
|
||||
const registry = analyzeSource(code, 'guard.ts');
|
||||
const { transformedCode, hasReplacements } = replaceCallSites(code, registry);
|
||||
expect(hasReplacements).toBe(false);
|
||||
expect(transformedCode).toContain('protobuf_encode<Msg>({ id: 1 })');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { createRuntimeMap } from '../../src/runtime-map';
|
||||
import {
|
||||
protobuf_decode,
|
||||
protobuf_disableRuntimeMapFallback,
|
||||
protobuf_enableRuntimeMapFallback,
|
||||
protobuf_encode,
|
||||
} from '../../src/runtime';
|
||||
|
||||
function captureFrameFromThrow(fn: () => unknown, sourceFile: string): { line: number; column: number } {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
const stack = err instanceof Error ? err.stack ?? '' : '';
|
||||
for (const raw of stack.split('\n')) {
|
||||
const line = raw.trim();
|
||||
if (!line.includes(sourceFile)) continue;
|
||||
|
||||
const location = line.endsWith(')') && line.includes('(')
|
||||
? line.slice(line.lastIndexOf('(') + 1, -1)
|
||||
: line.replace(/^at\s+/, '');
|
||||
|
||||
const lastColon = location.lastIndexOf(':');
|
||||
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
|
||||
if (lastColon < 0 || secondLastColon < 0) continue;
|
||||
|
||||
const parsedLine = Number(location.slice(secondLastColon + 1, lastColon));
|
||||
const parsedColumn = Number(location.slice(lastColon + 1));
|
||||
if (Number.isFinite(parsedLine) && Number.isFinite(parsedColumn)) {
|
||||
return { line: parsedLine, column: parsedColumn };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unable to capture stack frame for ${sourceFile}`);
|
||||
}
|
||||
|
||||
function invokeEncode(): Uint8Array {
|
||||
return new Function(
|
||||
'protobuf_encode',
|
||||
`\n//# sourceURL=runtime-map-encode.js\nreturn protobuf_encode({ value: 7 });`,
|
||||
)(protobuf_encode) as Uint8Array;
|
||||
}
|
||||
|
||||
function invokeDecode(data: Uint8Array): any {
|
||||
return new Function(
|
||||
'protobuf_decode',
|
||||
'data',
|
||||
`\n//# sourceURL=runtime-map-decode.js\nreturn protobuf_decode(data);`,
|
||||
)(protobuf_decode, data);
|
||||
}
|
||||
|
||||
describe('runtime map fallback', () => {
|
||||
afterEach(() => {
|
||||
protobuf_disableRuntimeMapFallback();
|
||||
});
|
||||
|
||||
it('dynamically generates encode/decode from runtime map when enabled', () => {
|
||||
const schema = `
|
||||
interface SimpleMsg {
|
||||
value: pb<1, uint_32>;
|
||||
}
|
||||
`;
|
||||
const registry = analyzeSource(schema, 'schema.ts');
|
||||
|
||||
const encodeFrame = captureFrameFromThrow(invokeEncode, 'runtime-map-encode.js');
|
||||
const decodeFrame = captureFrameFromThrow(() => invokeDecode(new Uint8Array([0x08, 0x07])), 'runtime-map-decode.js');
|
||||
|
||||
const runtimeMap = createRuntimeMap({
|
||||
messages: registry,
|
||||
callSites: [
|
||||
{
|
||||
file: 'runtime-map-encode.js',
|
||||
line: encodeFrame.line,
|
||||
column: encodeFrame.column,
|
||||
fnName: 'protobuf_encode',
|
||||
typeName: 'SimpleMsg',
|
||||
},
|
||||
{
|
||||
file: 'runtime-map-decode.js',
|
||||
line: decodeFrame.line,
|
||||
column: decodeFrame.column,
|
||||
fnName: 'protobuf_decode',
|
||||
typeName: 'SimpleMsg',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
protobuf_enableRuntimeMapFallback(runtimeMap);
|
||||
|
||||
const encoded = invokeEncode();
|
||||
expect([...encoded]).toEqual([0x08, 0x07]);
|
||||
|
||||
const decoded = invokeDecode(encoded);
|
||||
expect(decoded.value).toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { encodeVarint, decodeVarint, writeTag, writeString, readString, skipField } from '../../src/codegen/wire';
|
||||
|
||||
describe('wire format primitives', () => {
|
||||
describe('varint', () => {
|
||||
const cases: [number, number[]][] = [
|
||||
[0, [0x00]],
|
||||
[1, [0x01]],
|
||||
[127, [0x7f]],
|
||||
[128, [0x80, 0x01]],
|
||||
[300, [0xac, 0x02]],
|
||||
[16384, [0x80, 0x80, 0x01]],
|
||||
];
|
||||
|
||||
it.each(cases)('encodeVarint(%i) produces correct bytes', (value, expected) => {
|
||||
const buf: number[] = [];
|
||||
encodeVarint(value, buf);
|
||||
expect(buf).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each(cases)('decodeVarint round-trip for %i', (value) => {
|
||||
const buf: number[] = [];
|
||||
encodeVarint(value, buf);
|
||||
const data = new Uint8Array(buf);
|
||||
const [decoded, offset] = decodeVarint(data, 0);
|
||||
expect(decoded).toBe(value);
|
||||
expect(offset).toBe(buf.length);
|
||||
});
|
||||
|
||||
it('handles max uint32', () => {
|
||||
const value = 0xFFFFFFFF;
|
||||
const buf: number[] = [];
|
||||
encodeVarint(value, buf);
|
||||
const [decoded] = decodeVarint(new Uint8Array(buf), 0);
|
||||
expect(decoded).toBe(value);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tag encoding', () => {
|
||||
it('field 1, varint (wire type 0) produces 0x08', () => {
|
||||
const buf: number[] = [];
|
||||
writeTag(1, 0, buf);
|
||||
expect(buf).toEqual([0x08]);
|
||||
});
|
||||
|
||||
it('field 1, length-delimited (wire type 2) produces 0x0A', () => {
|
||||
const buf: number[] = [];
|
||||
writeTag(1, 2, buf);
|
||||
expect(buf).toEqual([0x0a]);
|
||||
});
|
||||
|
||||
it('field 2, varint produces 0x10', () => {
|
||||
const buf: number[] = [];
|
||||
writeTag(2, 0, buf);
|
||||
expect(buf).toEqual([0x10]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('string encoding', () => {
|
||||
it('encodes and decodes "hello"', () => {
|
||||
const buf: number[] = [];
|
||||
writeString('hello', buf);
|
||||
const data = new Uint8Array(buf);
|
||||
// First byte is length (5), followed by UTF-8 bytes
|
||||
expect(data[0]).toBe(5);
|
||||
const decoded = readString(data, 1, 5);
|
||||
expect(decoded).toBe('hello');
|
||||
});
|
||||
|
||||
it('handles empty string', () => {
|
||||
const buf: number[] = [];
|
||||
writeString('', buf);
|
||||
expect(buf).toEqual([0]); // length 0
|
||||
});
|
||||
|
||||
it('handles unicode', () => {
|
||||
const buf: number[] = [];
|
||||
writeString('你好', buf);
|
||||
const data = new Uint8Array(buf);
|
||||
const [len, offset] = [data[0], 1];
|
||||
const decoded = readString(data, offset, len);
|
||||
expect(decoded).toBe('你好');
|
||||
});
|
||||
});
|
||||
|
||||
describe('skipField', () => {
|
||||
it('skips varint field', () => {
|
||||
const buf: number[] = [];
|
||||
encodeVarint(300, buf); // multi-byte varint
|
||||
const data = new Uint8Array(buf);
|
||||
const newOffset = skipField(data, 0, 0);
|
||||
expect(newOffset).toBe(buf.length);
|
||||
});
|
||||
|
||||
it('skips length-delimited field', () => {
|
||||
// length=3 followed by 3 bytes
|
||||
const data = new Uint8Array([3, 0x41, 0x42, 0x43]);
|
||||
const newOffset = skipField(data, 0, 2);
|
||||
expect(newOffset).toBe(4);
|
||||
});
|
||||
|
||||
it('skips 32-bit field', () => {
|
||||
expect(skipField(new Uint8Array(4), 0, 5)).toBe(4);
|
||||
});
|
||||
|
||||
it('skips 64-bit field', () => {
|
||||
expect(skipField(new Uint8Array(8), 0, 1)).toBe(8);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
// Aliased import of the pb / pb_repeated markers.
|
||||
//
|
||||
// `parsePbTypeRef` compared the literal type-ref identifier text against
|
||||
// the constants `'pb'` / `'pb_repeated'`. With `import { pb as P }` the
|
||||
// identifier text becomes `'P'`, so the field was silently dropped from
|
||||
// the message — interfaces ended up looking empty.
|
||||
//
|
||||
// Fix: resolve the marker name through the imported-name resolver before
|
||||
// comparing.
|
||||
|
||||
import type { pb as P, pb_repeated as PR, uint_32 } from '@snowluma/proton';
|
||||
|
||||
interface Aliased {
|
||||
id: P<1, uint_32>;
|
||||
tags: PR<2, string>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<Aliased>({ id: 1, tags: ['a', 'b'] });
|
||||
const decoded = protobuf_decode<Aliased>(data);
|
||||
|
||||
export { };
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
interface BoolMsg {
|
||||
active: pb<1, bool>;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import type { UserMsg as AliasMsg } from './types';
|
||||
|
||||
const buf = protobuf_encode<AliasMsg>({ id: 42, name: 'alice' });
|
||||
const decoded = protobuf_decode<AliasMsg>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { UserMsg } from './types';
|
||||
|
||||
const buf = protobuf_encode<UserMsg>({ id: 42, name: 'alice' });
|
||||
const decoded = protobuf_decode<UserMsg>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface Deep {
|
||||
val: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
export type { Deep };
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
|
||||
const buf = protobuf_encode<Wrapper<string>>({ value: 'hello' });
|
||||
const decoded = protobuf_decode<Wrapper<string>>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface Wrapper<T> {
|
||||
value: pb<1, T>;
|
||||
}
|
||||
|
||||
export type { Wrapper };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface Inner {
|
||||
value: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
export type { Inner };
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
function localEncode<T>(value: T): Uint8Array {
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
|
||||
const buf = localEncode<Wrapper<string>>({ value: 'local' });
|
||||
const decoded = protobuf_decode<Wrapper<string>>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Deep } from './deep';
|
||||
|
||||
interface Mid {
|
||||
inner: pb<1, Deep>;
|
||||
}
|
||||
|
||||
export type { Mid };
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Inner } from './inner';
|
||||
|
||||
interface Outer {
|
||||
inner: pb<1, Inner>;
|
||||
}
|
||||
|
||||
const buf = protobuf_encode<Outer>({ inner: { value: 42 } });
|
||||
const decoded = protobuf_decode<Outer>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface SimpleMessage {
|
||||
id: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
export { SimpleMessage };
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import type { Mid } from './mid';
|
||||
|
||||
interface Top {
|
||||
nested: pb<1, Mid>;
|
||||
}
|
||||
|
||||
const buf = protobuf_encode<Top>({ nested: { inner: { val: 99 } } });
|
||||
const decoded = protobuf_decode<Top>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,6 @@
|
||||
interface UserMsg {
|
||||
id: pb<1, uint_32>;
|
||||
name: pb<2, string>;
|
||||
}
|
||||
|
||||
export type { UserMsg };
|
||||
@@ -0,0 +1,7 @@
|
||||
import { SimpleMessage } from './protobuf';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
const bytes = protobuf_encode<SimpleMessage>({ id: 42 });
|
||||
const decoded = protobuf_decode<SimpleMessage>(bytes);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,49 @@
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
export function encodeViaWrapper<T>(value: T): Uint8Array {
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
|
||||
export function decodeViaWrapper<T>(data: Uint8Array): T {
|
||||
return protobuf_decode<T>(data);
|
||||
}
|
||||
|
||||
export const encodeArrowWrapper = <T>(value: T): Uint8Array => protobuf_encode<T>(value);
|
||||
|
||||
export const decodeArrowWrapper = <T>(data: Uint8Array): T => protobuf_decode<T>(data);
|
||||
|
||||
export function encodeSecondGeneric<Ignored, T>(_ignored: Ignored, value: T): Uint8Array {
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
|
||||
export function passthroughOnly<T>(value: T): T {
|
||||
return value;
|
||||
}
|
||||
|
||||
export const wrapperObject = {
|
||||
encode<T>(value: T): Uint8Array {
|
||||
return protobuf_encode<T>(value);
|
||||
},
|
||||
decode<T>(data: Uint8Array): T {
|
||||
return protobuf_decode<T>(data);
|
||||
},
|
||||
encodeArrow: <T>(value: T): Uint8Array => protobuf_encode<T>(value),
|
||||
};
|
||||
|
||||
export function encodeWithBranch<T>(value: T, enabled: boolean): Uint8Array {
|
||||
if (enabled) {
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
return protobuf_encode<T>(value);
|
||||
}
|
||||
|
||||
export function encodeWithNestedHelper<T>(value: T): Uint8Array {
|
||||
function inner(payload: T): Uint8Array {
|
||||
return protobuf_encode<T>(payload);
|
||||
}
|
||||
return inner(value);
|
||||
}
|
||||
|
||||
export function encodeChained<T>(value: T): Uint8Array {
|
||||
return encodeViaWrapper<T>(value);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import {
|
||||
wrapperObject,
|
||||
encodeWithBranch,
|
||||
encodeWithNestedHelper,
|
||||
encodeChained,
|
||||
} from './wrapper-api';
|
||||
|
||||
const objectBuf = wrapperObject.encode<Wrapper<string>>({ value: 'object' });
|
||||
const objectDecoded = wrapperObject.decode<Wrapper<string>>(objectBuf);
|
||||
|
||||
const arrowMemberBuf = wrapperObject.encodeArrow<Wrapper<Wrapper<string>>>({ value: { value: 'member' } });
|
||||
|
||||
const { encodeArrow } = wrapperObject;
|
||||
const destructuredBuf = encodeArrow<Wrapper<string>>({ value: 'destructured' });
|
||||
|
||||
const branchBuf = encodeWithBranch<Wrapper<string>>({ value: 'branch' }, true);
|
||||
const nestedHelperBuf = encodeWithNestedHelper<Wrapper<string>>({ value: 'nested-helper' });
|
||||
const chainedBuf = encodeChained<Wrapper<string>>({ value: 'chained' });
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import { encodeViaWrapper, decodeViaWrapper } from './wrapper-api';
|
||||
|
||||
const buf = encodeViaWrapper<Wrapper<string>>({ value: 'hello' });
|
||||
const decoded = decodeViaWrapper<Wrapper<string>>(buf);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import {
|
||||
encodeViaWrapper as encAlias,
|
||||
decodeViaWrapper as decAlias,
|
||||
encodeArrowWrapper,
|
||||
decodeArrowWrapper,
|
||||
encodeSecondGeneric,
|
||||
passthroughOnly,
|
||||
} from './wrapper-api';
|
||||
|
||||
const aliasBuf = encAlias<Wrapper<string>>({ value: 'alias' });
|
||||
const aliasDecoded = decAlias<Wrapper<string>>(aliasBuf);
|
||||
|
||||
const arrowBuf = encodeArrowWrapper<Wrapper<Wrapper<string>>>({ value: { value: 'nested' } });
|
||||
const arrowDecoded = decodeArrowWrapper<Wrapper<Wrapper<string>>>(arrowBuf);
|
||||
|
||||
const secondBuf = encodeSecondGeneric<number, Wrapper<string>>(1, { value: 'second' });
|
||||
|
||||
const passthrough = passthroughOnly<Wrapper<string>>({ value: 'ignored' });
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
|
||||
export function encodeBoxed<T>(value: Wrapper<T>): Uint8Array {
|
||||
return protobuf_encode<Wrapper<T>>(value);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import {
|
||||
encodeBoxed,
|
||||
decodeBoxed,
|
||||
encodeAliasBoxed,
|
||||
encodeNestedBoxed,
|
||||
encodeBoxedChain,
|
||||
} from './wrapper-type-source';
|
||||
|
||||
const boxedBuf = encodeBoxed<string>({ value: 'boxed' });
|
||||
const boxedDecoded = decodeBoxed<string>(boxedBuf);
|
||||
const aliasBuf = encodeAliasBoxed<string>({ value: 'alias' });
|
||||
const nestedBuf = encodeNestedBoxed<string>({ value: { value: 'nested' } });
|
||||
const chainedBuf = encodeBoxedChain<string>({ value: 'chain' });
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Wrapper } from './generic-types';
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import { encodeBoxed as encodeBoxedBase } from './wrapper-type-source-base';
|
||||
|
||||
export type AliasWrapper<T> = Wrapper<T>;
|
||||
|
||||
export function encodeBoxed<T>(value: Wrapper<T>): Uint8Array {
|
||||
return protobuf_encode<Wrapper<T>>(value);
|
||||
}
|
||||
|
||||
export function decodeBoxed<T>(data: Uint8Array): Wrapper<T> {
|
||||
return protobuf_decode<Wrapper<T>>(data);
|
||||
}
|
||||
|
||||
export function encodeAliasBoxed<T>(value: AliasWrapper<T>): Uint8Array {
|
||||
return protobuf_encode<Wrapper<T>>(value);
|
||||
}
|
||||
|
||||
export function encodeNestedBoxed<T>(value: Wrapper<Wrapper<T>>): Uint8Array {
|
||||
return protobuf_encode<Wrapper<Wrapper<T>>>(value);
|
||||
}
|
||||
|
||||
export function encodeBoxedChain<T>(value: Wrapper<T>): Uint8Array {
|
||||
return encodeBoxedBase<T>(value);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
interface TestProtobufAny<T> {
|
||||
name?: pb<1, T>;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
interface TestProtobufAny<T> {
|
||||
name?: pb<1, T>;
|
||||
}
|
||||
|
||||
const dataT = protobuf_encode<TestProtobufAny<TestProtobufAny<string>>>({ name: { name: "test" } });
|
||||
const decodedT = protobuf_decode<TestProtobufAny<TestProtobufAny<string>>>(dataT);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,24 @@
|
||||
// Generic template with a generic-instantiated message field.
|
||||
//
|
||||
// The outer template's type param (`U`) shows up *inside* an inner generic
|
||||
// instantiation (`Wrapper<U>`). When the outer is monomorphized at the call
|
||||
// site (`Outer<uint_32>`), the inner instantiation must be re-instantiated
|
||||
// with the substitution (becoming `Wrapper<uint_32>`) and put into the
|
||||
// registry under its mangled name `Wrapper__uint_32`.
|
||||
//
|
||||
// Without the fix, the field's `rawTypeName` was `'Wrapper__U'` and the
|
||||
// substituted-mono never produced `Wrapper__uint_32`, leaving the field's
|
||||
// wire-type unresolved.
|
||||
|
||||
interface Wrapper<T> {
|
||||
value: pb<1, T>;
|
||||
}
|
||||
|
||||
interface Outer<U> {
|
||||
wrapped: pb<5, Wrapper<U>>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<Outer<uint_32>>({ wrapped: { value: 42 } });
|
||||
const decoded = protobuf_decode<Outer<uint_32>>(data);
|
||||
|
||||
export { };
|
||||
@@ -0,0 +1,5 @@
|
||||
interface UserProfile {
|
||||
id: pb<1, uint_32>;
|
||||
username: pb<2, string>;
|
||||
active: pb<3, bool>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Concrete interface with a generic-instantiated message field.
|
||||
//
|
||||
// The call site only references the concrete outer type (`Container`), so
|
||||
// the analyzer must independently:
|
||||
// 1) resolve the field's typeName to the *mangled* form (`Wrapper__uint_32`)
|
||||
// so it matches what monomorphization produces,
|
||||
// 2) enqueue `Wrapper<uint_32>` for monomorphization itself, since the
|
||||
// call-site-driven queue only sees `Container`.
|
||||
//
|
||||
// Without both, wire-type resolution silently leaves the field at the
|
||||
// `WireType.Varint` placeholder and codegen emits a wrong wire format.
|
||||
|
||||
interface Wrapper<T> {
|
||||
value: pb<1, T>;
|
||||
}
|
||||
|
||||
interface Container {
|
||||
wrapped: pb<5, Wrapper<uint_32>>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<Container>({ wrapped: { value: 42 } });
|
||||
const decoded = protobuf_decode<Container>(data);
|
||||
|
||||
export { };
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
interface Inner {
|
||||
value: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
interface Outer {
|
||||
inner: pb<1, Inner>;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
interface Foo {
|
||||
bar: string;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
interface TestProtobuf {
|
||||
name: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
interface TestProtobufOutput {
|
||||
name: pb<1, TestProtobuf>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<TestProtobuf>({ name: 123 });
|
||||
const decoded = protobuf_decode<TestProtobufOutput>(data);
|
||||
|
||||
export { };
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
interface RepeatedMsg {
|
||||
ids: pb_repeated<1, uint_32>;
|
||||
names: pb_repeated<2, string>;
|
||||
}
|
||||
|
||||
const data = protobuf_encode<RepeatedMsg>({ ids: [1, 2, 3], names: ["a", "b"] });
|
||||
const decoded = protobuf_decode<RepeatedMsg>(data);
|
||||
|
||||
export { };
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
interface SimpleMsg {
|
||||
value: pb<1, uint_32>;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
interface StringMsg {
|
||||
text: pb<1, string>;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const fixturesDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures');
|
||||
|
||||
/** Load a fixture file as a string. */
|
||||
export function loadFixture(name: string): string {
|
||||
return readFileSync(resolve(fixturesDir, name), 'utf-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Run generated code via `new Function()` and return a named global value.
|
||||
* Cleans up the global after retrieval.
|
||||
*/
|
||||
export function execAndGet<T>(code: string, globalKey: string): T {
|
||||
new Function(code)();
|
||||
const val = (globalThis as any)[globalKey] as T;
|
||||
delete (globalThis as any)[globalKey];
|
||||
return val;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*",
|
||||
"test/__tests__/**/*",
|
||||
"test/helpers/**/*",
|
||||
"protobuf.d.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist",
|
||||
"test/fixtures"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['test/__tests__/**/*.test.ts'],
|
||||
},
|
||||
});
|
||||
Generated
+16
@@ -64,6 +64,22 @@ importers:
|
||||
specifier: ^4.1.4
|
||||
version: 4.1.4(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))
|
||||
|
||||
packages/proton:
|
||||
dependencies:
|
||||
typescript:
|
||||
specifier: 'catalog:'
|
||||
version: 6.0.2
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^24.12.2
|
||||
version: 24.12.2
|
||||
vite:
|
||||
specifier: 'catalog:'
|
||||
version: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])
|
||||
vitest:
|
||||
specifier: ^4.1.4
|
||||
version: 4.1.4(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))
|
||||
|
||||
packages/runtime: {}
|
||||
|
||||
packages/sdk:
|
||||
|
||||
Reference in new issue
Block a user