Unify protobuf helpers and tidy comments

Export and centralize small utility helpers and remove duplicate implementations: identityImportedTypeName was exported from utils, and isVarint64/isFixed64BigInt were added to types and imported into encoder/decoder. Minor import reorders and formatting cleanups across collector, monomorphizer, import-resolver, static-wrapper, subclass-override and file-pipeline. Comments and JSDoc were tightened for clarity; behavior remains the same but common logic is now deduplicated and easier to maintain.
This commit is contained in:
手瓜一十雪 committed 2026-05-26 20:53:32 +08:00
1 parent aaed36aa19
commit 1b07005d91
10 files changed
+51 -138

No files matched your search

+10 -13
View File
@@ -1,15 +1,12 @@
import ts from 'typescript';
import {
WireType,
PB_MARKER, PB_REPEATED_MARKER,
WireType,
type GenericFieldTemplate,
type GenericProtobufTemplate,
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;
}
import { identityImportedTypeName, isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js';
/**
* Yield generic-instantiated type-arg nodes appearing as field types on a
@@ -150,12 +147,12 @@ function extractGenericField(
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.
// 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);
+5 -36
View File
@@ -140,44 +140,14 @@ function getBareModuleResolutionCache(): ts.ModuleResolutionCache {
return bareModuleResolutionCache;
}
/**
* Resolve a module specifier (relative OR bare) to an absolute `.ts`
* source-file path. Returns `null` if the resolution lands on something
* proton can't consume (a `.d.ts` declaration, a `.js` build artifact,
* or just not-found).
*
* Two code paths:
*
* - **Relative** (`./foo`, `../bar`): direct file-existence probe.
* Same behavior as before — fast, no TS dependency. Preserved
* verbatim so that the common case (cross-file imports inside a
* single package) is unaffected by the new bare-specifier logic.
*
* - **Bare** (`@scope/pkg`, `pkg-name`, `~alias`): delegate to
* TypeScript's module resolution so monorepo workspaces / npm
* packages / tsconfig paths / package.json `exports` all just work.
* Required to support proto definitions that live in a separate
* workspace package — e.g. moving `bridge/proto/proton/*.ts` into a
* dedicated `@snowluma/proto-defs` package while keeping the call
* sites in `@snowluma/core`.
*
* We deliberately require the resolved file to be `.ts` (not
* `.d.ts`): proton collects `pb<…>` field tags by walking interface
* AST nodes, and a hand-written `.d.ts` *would* work too — but the
* typical `dist/index.d.ts` strips away the `pb<>` type arguments
* proton needs. Asking proto-definition packages to ship source
* `.ts` (the same model `@snowluma/proton` itself uses) avoids that
* footgun entirely.
*/
/** Resolve a specifier (relative or bare) to an absolute `.ts` source path.
* Returns `null` for non-.ts files (`.d.ts`, `.js`) or unresolved paths.
* Relative specifiers use direct file probing; bare specifiers use TS bundler
* resolution so workspaces, path aliases, and `package.json` exports work.
* Only `.ts` source is accepted — `.d.ts` strips the `pb<>` type arguments. */
function resolveModulePath(specifier: string, importerPath: string): string | null {
if (specifier.startsWith('.')) {
// ── Relative path branch (preserved verbatim from the pre-bare-
// specifier implementation; existing callers depend on its
// exact behavior, including the .ts-only filter). ──
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
@@ -191,7 +161,6 @@ function resolveModulePath(specifier: string, importerPath: string): string | nu
return null;
}
// ── Bare specifier branch ──
const result = ts.resolveModuleName(
specifier,
importerPath,
+10 -13
View File
@@ -1,25 +1,22 @@
import ts from 'typescript';
import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js';
import { WireType, type GenericProtobufTemplate, type ProtobufField, type ProtobufMessage } from './types.js';
import {
isKeywordTypeNode,
createImportedTypeNameResolver,
identityImportedTypeName,
isKeywordTypeNode,
resolveSourceFileForTypeNode,
type ImportedTypeNameResolver,
typeNodeToMangledName,
type ImportedTypeNameResolver,
} 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;
/** 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;
}
/**
+3 -19
View File
@@ -3,10 +3,8 @@ import { getMethodName, isStaticMethod } from './ast-helpers.js';
import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalProtobufFn, type ProtobufImportBindings } from './callsite.js';
/**
* Static-method wrapper detection.
*
* A "wrapper" here is the abstract half of the pattern that motivates the
* whole feature:
* Static-method wrapper detection. Detects abstract static methods that
* forward a type parameter into `protobuf_encode`/`protobuf_decode`, e.g.:
*
* ```ts
* abstract class PacketTransformer {
@@ -16,21 +14,7 @@ import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalPro
* }
* ```
*
* The method itself can never run at the user's call site because `R` is
* erased at runtime. Proton's job is to walk every subclass of such a base,
* resolve `R` per subclass via TypeChecker, and emit a per-subclass override
* with a concrete codec inlined.
*
* This module only handles the AST-side detection — what the method looks
* like and which type parameter it pipes into protobuf_encode/decode. The
* subclass resolution + codegen lives in `typecheck/subclass-wrapper.ts`
* because both steps need a TypeChecker.
*
* The detector is intentionally name-agnostic: it doesn't care that the
* method is called `encode`, that the sibling is `serialize`, or that the
* base is `PacketTransformer`. It only looks at the structural pattern,
* which keeps it usable for user-defined variants (decode side, RPC chains,
* etc.) without further configuration.
* Subclass resolution and codegen live in `typecheck/subclass-wrapper.ts`.
*/
/** A single `protobuf_encode<X>(...)` / `protobuf_decode<X>(...)` call inside
+8
View File
@@ -70,3 +70,11 @@ export const PRIMITIVE_TYPE_MAP: Record<string, { wireType: WireType; defaultVal
/** Marker identifiers recognised in type references */
export const PB_MARKER = 'pb';
export const PB_REPEATED_MARKER = 'pb_repeated';
export function isVarint64(typeName: string): boolean {
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
}
export function isFixed64BigInt(typeName: string): boolean {
return typeName === 'fixed_64' || typeName === 'sfixed_64';
}
+1 -1
View File
@@ -2,7 +2,7 @@ import ts from 'typescript';
export type ImportedTypeNameResolver = (name: string) => string;
function identityImportedTypeName(name: string): string {
export function identityImportedTypeName(name: string): string {
return name;
}
+1 -9
View File
@@ -1,4 +1,4 @@
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js';
import { PRIMITIVE_TYPE_MAP, WireType, isFixed64BigInt, isVarint64, type MessageRegistry, type ProtobufField, type ProtobufMessage } from '../ast/types.js';
function tagValue(field: ProtobufField): number {
const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes'
@@ -26,14 +26,6 @@ function varintDec64(varName: string, ind: string): string {
].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++; }`,
+4 -12
View File
@@ -1,4 +1,4 @@
import { WireType, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js';
import { WireType, isFixed64BigInt, isVarint64, type MessageRegistry, type ProtobufField, type ProtobufMessage } from '../ast/types.js';
/**
* Pre-compute tag bytes at codegen time.
@@ -52,14 +52,6 @@ function writeVarint(expr: string, ind: string): string {
].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})`;
@@ -67,9 +59,9 @@ function bigintVarintExpr(typeName: string, expr: string): string {
}
interface EncoderBlock {
declare: string[];
size: string[];
write: string[];
declare: string[];
size: string[];
write: string[];
}
export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
@@ -2,25 +2,14 @@ import ts from 'typescript';
import type { ResolvedSubclassWrapper } from '../typecheck/subclass-wrapper.js';
/**
* Per-subclass override code generation.
*
* The abstract base class's static method body is copied verbatim, with
* every `protobuf_encode<R>` / `protobuf_decode<B>` occurrence rewritten to
* the concrete `protobuf_encode_${typeName}` / `protobuf_decode_${typeName}`
* identifier. The result is assigned onto the subclass:
* Per-subclass override code generation. Copies the wrapper body verbatim,
* rewrites every `protobuf_encode/decode<R>` to the concrete form, and emits:
*
* ```ts
* Sub.encode = function (ctx, params) { … rewritten body … };
* Sub.encode = function (ctx, params) { … };
* ```
*
* Output language:
* The generated text is appended into the subclass's own (already-TS)
* transform result. Anything TS-only inside the body (`as never`, return-
* type annotations on local vars, etc.) survives intact and is dropped
* downstream by the same TS-to-JS step that already handles the rest of
* the user file. We avoid running our own transpilation step here both
* because it adds latency and because re-transpiling once Vite is about
* to do it again would generate duplicate work for every transform.
* Output is TS-flavoured (not transpiled) — Vite handles the TS-to-JS pass.
*/
export interface SubclassOverrideRenderResult {
+5 -20
View File
@@ -14,22 +14,7 @@ export interface SubclassOverrideInsertion {
code: string;
}
/**
* Plugin-facing entry point for the subclass-wrapper feature.
*
* Pulls the file's TypeChecker (lazily — returns null and short-circuits
* if no tsconfig is reachable), walks every class declaration in the
* file's program-side SourceFile, runs the subclass resolver against each,
* and returns both the resolved wrappers and the extra root type names
* that the analyzer pipeline needs to drag into the codec registry.
*
* The function is intentionally side-effect free: caching of the Program
* lives in `program-cache.ts`, and the override text is materialised by
* `renderSubclassOverride`. Each call gets a fresh `WrapperLookupCache`
* because the underlying detect call is memoised per ClassDeclaration —
* the cache only matters across the iterations of a single file's
* subclasses (which is exactly what we do here).
*/
/** Result returned by `runSubclassWrapperPipeline`. */
export interface SubclassWrapperPipelineResult {
/** All resolved subclass overrides reachable from this file. Empty when
* TypeChecker is unavailable, when no class in the file extends a
@@ -46,6 +31,9 @@ export interface SubclassWrapperPipelineResult {
insertions: SubclassOverrideInsertion[];
}
/** Lazily retrieves the TypeChecker (returns empty result when no tsconfig is
* reachable), resolves inherited wrapper overrides for every class in the file,
* and returns resolved wrappers, extra codec roots, and insertion points. */
export function runSubclassWrapperPipeline(filePath: string): SubclassWrapperPipelineResult {
const empty: SubclassWrapperPipelineResult = {
resolvedWrappers: [],
@@ -62,10 +50,7 @@ export function runSubclassWrapperPipeline(filePath: string): SubclassWrapperPip
const cache = new WrapperLookupCache();
const allResolved: ResolvedSubclassWrapper[] = [];
const extraRoots = new Set<string>();
// Group rendered overrides per subclass so encode + decode + ... for the
// same class land in one contiguous block right after the class body.
// Otherwise the plugin would have to apply multiple identical-position
// edits and worry about ordering.
// Group per subclass so encode + decode + ... land in one contiguous block.
const perSubclass = new Map<ts.ClassDeclaration, string[]>();
for (const stmt of sf.statements) {