Apply formatting and fix web request utilities
Add consistent indent rule to ESLint and normalize formatting/indentation across multiple files. Refactor RequestUtil: improve cookie extraction, redirect handling, and HttpGetJson/HttpGetText request flow; fix cookie string builder formatting. Fix uploadGroupNoticeImage promise/error handling and network request flow. Also apply minor style/refactor tweaks in bridge web APIs, onebot handlers, message-store SQL alignment, and Proton AST collector utilities to improve readability and correctness.
This commit is contained in:
1 parent
aea2676c31
commit
36c3ed031b
22 files changed
+2144
-2140
No files matched your search
@@ -1,14 +1,14 @@
|
||||
import ts from 'typescript';
|
||||
import {
|
||||
WireType,
|
||||
PB_MARKER, PB_REPEATED_MARKER,
|
||||
type ProtobufField, type ProtobufMessage,
|
||||
type GenericProtobufTemplate, type GenericFieldTemplate,
|
||||
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;
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -19,147 +19,147 @@ function identityImportedTypeName(name: string): string {
|
||||
* type; nested generic instantiations on its fields would otherwise be missed.)
|
||||
*/
|
||||
export function* collectConcreteFieldGenericTypeArgs(
|
||||
node: ts.InterfaceDeclaration,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
node: ts.InterfaceDeclaration,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
): IterableIterator<ts.TypeNode> {
|
||||
if (node.typeParameters?.length) return;
|
||||
for (const m of node.members) {
|
||||
if (!ts.isPropertySignature(m) || !m.type) continue;
|
||||
const parsed = parsePbTypeRef(m, resolveImportedTypeName);
|
||||
if (!parsed) continue;
|
||||
const ta = parsed.typeArgNode;
|
||||
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
|
||||
yield ta;
|
||||
}
|
||||
if (node.typeParameters?.length) return;
|
||||
for (const m of node.members) {
|
||||
if (!ts.isPropertySignature(m) || !m.type) continue;
|
||||
const parsed = parsePbTypeRef(m, resolveImportedTypeName);
|
||||
if (!parsed) continue;
|
||||
const ta = parsed.typeArgNode;
|
||||
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
|
||||
yield ta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */
|
||||
export function collectInterface(
|
||||
node: ts.InterfaceDeclaration,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
node: ts.InterfaceDeclaration,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
): ProtobufMessage | null {
|
||||
const fields: ProtobufField[] = [];
|
||||
for (const m of node.members) {
|
||||
if (!ts.isPropertySignature(m) || !m.type) continue;
|
||||
const f = extractField(m, sf, resolveImportedTypeName);
|
||||
if (f) fields.push(f);
|
||||
}
|
||||
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as
|
||||
// zero-field proto messages — proto3 wire format allows them and
|
||||
// downstream code routinely uses them for "this OIDB call has no
|
||||
// meaningful response body" placeholders. Interfaces that have
|
||||
// members but no pb-marked fields are NOT proto messages — they
|
||||
// belong to regular TS types and must stay unregistered to avoid
|
||||
// polluting the registry.
|
||||
if (fields.length === 0 && node.members.length > 0) return null;
|
||||
return { name: node.name.text, fields };
|
||||
const fields: ProtobufField[] = [];
|
||||
for (const m of node.members) {
|
||||
if (!ts.isPropertySignature(m) || !m.type) continue;
|
||||
const f = extractField(m, sf, resolveImportedTypeName);
|
||||
if (f) fields.push(f);
|
||||
}
|
||||
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as
|
||||
// zero-field proto messages — proto3 wire format allows them and
|
||||
// downstream code routinely uses them for "this OIDB call has no
|
||||
// meaningful response body" placeholders. Interfaces that have
|
||||
// members but no pb-marked fields are NOT proto messages — they
|
||||
// belong to regular TS types and must stay unregistered to avoid
|
||||
// polluting the registry.
|
||||
if (fields.length === 0 && node.members.length > 0) return null;
|
||||
return { name: node.name.text, fields };
|
||||
}
|
||||
|
||||
/** Collect a generic interface template. */
|
||||
export function collectGenericInterface(
|
||||
node: ts.InterfaceDeclaration,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
node: ts.InterfaceDeclaration,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
): GenericProtobufTemplate | null {
|
||||
const typeParams = node.typeParameters!.map(p => p.name.text);
|
||||
const tpSet = new Set(typeParams);
|
||||
const fields: GenericFieldTemplate[] = [];
|
||||
for (const m of node.members) {
|
||||
if (!ts.isPropertySignature(m) || !m.type) continue;
|
||||
const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName);
|
||||
if (f) fields.push(f);
|
||||
}
|
||||
return fields.length ? { name: node.name.text, typeParams, fields } : null;
|
||||
const typeParams = node.typeParameters!.map(p => p.name.text);
|
||||
const tpSet = new Set(typeParams);
|
||||
const fields: GenericFieldTemplate[] = [];
|
||||
for (const m of node.members) {
|
||||
if (!ts.isPropertySignature(m) || !m.type) continue;
|
||||
const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName);
|
||||
if (f) fields.push(f);
|
||||
}
|
||||
return fields.length ? { name: node.name.text, typeParams, fields } : null;
|
||||
}
|
||||
|
||||
// ── helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
function parsePbTypeRef(
|
||||
member: ts.PropertySignature,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
member: ts.PropertySignature,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
): { marker: string; fieldNumber: number; typeArgNode: ts.TypeNode } | null {
|
||||
const t = member.type!;
|
||||
if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null;
|
||||
// Resolve the marker name through aliased imports so `import { pb as P }`
|
||||
// / `import { pb_repeated as PR }` still match the marker constants.
|
||||
const marker = resolveImportedTypeName(t.typeName.text);
|
||||
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null;
|
||||
const ta = t.typeArguments;
|
||||
if (!ta || ta.length !== 2) return null;
|
||||
const fnNode = ta[0];
|
||||
if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null;
|
||||
return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] };
|
||||
const t = member.type!;
|
||||
if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null;
|
||||
// Resolve the marker name through aliased imports so `import { pb as P }`
|
||||
// / `import { pb_repeated as PR }` still match the marker constants.
|
||||
const marker = resolveImportedTypeName(t.typeName.text);
|
||||
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null;
|
||||
const ta = t.typeArguments;
|
||||
if (!ta || ta.length !== 2) return null;
|
||||
const fnNode = ta[0];
|
||||
if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null;
|
||||
return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] };
|
||||
}
|
||||
|
||||
function resolveTypeName(
|
||||
node: ts.TypeNode,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver,
|
||||
node: ts.TypeNode,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver,
|
||||
): string | null {
|
||||
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
|
||||
// Generic instantiations (e.g. `Wrapper<uint_32>`) must resolve to the
|
||||
// mangled name produced by monomorphization so wire-type resolution can
|
||||
// find the message in the registry. Without this the field would carry
|
||||
// the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`.
|
||||
if (node.typeArguments && node.typeArguments.length > 0) {
|
||||
return typeNodeToMangledName(node, sf, resolveImportedTypeName);
|
||||
}
|
||||
return resolveImportedTypeName(node.typeName.text);
|
||||
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
|
||||
// Generic instantiations (e.g. `Wrapper<uint_32>`) must resolve to the
|
||||
// mangled name produced by monomorphization so wire-type resolution can
|
||||
// find the message in the registry. Without this the field would carry
|
||||
// the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`.
|
||||
if (node.typeArguments && node.typeArguments.length > 0) {
|
||||
return typeNodeToMangledName(node, sf, resolveImportedTypeName);
|
||||
}
|
||||
if (isKeywordTypeNode(node)) return node.getText(sf);
|
||||
return null;
|
||||
return resolveImportedTypeName(node.typeName.text);
|
||||
}
|
||||
if (isKeywordTypeNode(node)) return node.getText(sf);
|
||||
return null;
|
||||
}
|
||||
|
||||
function extractField(
|
||||
member: ts.PropertySignature,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver,
|
||||
member: ts.PropertySignature,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver,
|
||||
): ProtobufField | null {
|
||||
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
|
||||
if (!parsed) return null;
|
||||
const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
|
||||
if (!typeName || !ts.isIdentifier(member.name)) return null;
|
||||
return {
|
||||
name: (member.name as ts.Identifier).text,
|
||||
fieldNumber: parsed.fieldNumber,
|
||||
typeName,
|
||||
wireType: WireType.Varint, // placeholder
|
||||
isMessage: false, // placeholder
|
||||
isOptional: member.questionToken != null,
|
||||
isRepeated: parsed.marker === PB_REPEATED_MARKER,
|
||||
};
|
||||
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,
|
||||
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,
|
||||
};
|
||||
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;
|
||||
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;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,15 +1,15 @@
|
||||
import ts from 'typescript';
|
||||
import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js';
|
||||
import {
|
||||
isKeywordTypeNode,
|
||||
createImportedTypeNameResolver,
|
||||
resolveSourceFileForTypeNode,
|
||||
type ImportedTypeNameResolver,
|
||||
typeNodeToMangledName,
|
||||
isKeywordTypeNode,
|
||||
createImportedTypeNameResolver,
|
||||
resolveSourceFileForTypeNode,
|
||||
type ImportedTypeNameResolver,
|
||||
typeNodeToMangledName,
|
||||
} from './utils.js';
|
||||
|
||||
function identityImportedTypeName(name: string): string {
|
||||
return name;
|
||||
return name;
|
||||
}
|
||||
|
||||
/** Resolved value for a single template type parameter. */
|
||||
@@ -28,104 +28,104 @@ interface ResolvedTypeArg {
|
||||
* Returns the mangled name of the concrete type, or null if it cannot be resolved.
|
||||
*/
|
||||
export function monomorphizeTypeNode(
|
||||
typeNode: ts.TypeNode,
|
||||
sf: ts.SourceFile,
|
||||
templates: Map<string, GenericProtobufTemplate>,
|
||||
out: Map<string, ProtobufMessage>,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
typeNode: ts.TypeNode,
|
||||
sf: ts.SourceFile,
|
||||
templates: Map<string, GenericProtobufTemplate>,
|
||||
out: Map<string, ProtobufMessage>,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
): string | null {
|
||||
if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null;
|
||||
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 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 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
|
||||
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);
|
||||
// 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,
|
||||
};
|
||||
});
|
||||
|
||||
// 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;
|
||||
out.set(mangledName, { name: mangledName, fields });
|
||||
return mangledName;
|
||||
}
|
||||
|
||||
function resolveTypeArg(
|
||||
node: ts.TypeNode,
|
||||
sf: ts.SourceFile,
|
||||
templates: Map<string, GenericProtobufTemplate>,
|
||||
out: Map<string, ProtobufMessage>,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver,
|
||||
node: ts.TypeNode,
|
||||
sf: ts.SourceFile,
|
||||
templates: Map<string, GenericProtobufTemplate>,
|
||||
out: Map<string, ProtobufMessage>,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver,
|
||||
): ResolvedTypeArg | null {
|
||||
const effectiveSf = resolveSourceFileForTypeNode(node, sf);
|
||||
// Try recursive monomorphization first (handles nested generics).
|
||||
const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName);
|
||||
if (mono) return { mangled: mono, text: node.getText(effectiveSf) };
|
||||
// Keyword type (string, number, …)
|
||||
if (isKeywordTypeNode(node)) {
|
||||
const text = node.getText(effectiveSf);
|
||||
return { mangled: text, text };
|
||||
}
|
||||
// Simple identifier (uint_32, SomeMsg, …)
|
||||
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) {
|
||||
const name = resolveImportedTypeName(node.typeName.text);
|
||||
return { mangled: name, text: name };
|
||||
}
|
||||
return null;
|
||||
const effectiveSf = resolveSourceFileForTypeNode(node, sf);
|
||||
// Try recursive monomorphization first (handles nested generics).
|
||||
const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName);
|
||||
if (mono) return { mangled: mono, text: node.getText(effectiveSf) };
|
||||
// Keyword type (string, number, …)
|
||||
if (isKeywordTypeNode(node)) {
|
||||
const text = node.getText(effectiveSf);
|
||||
return { mangled: text, text };
|
||||
}
|
||||
// Simple identifier (uint_32, SomeMsg, …)
|
||||
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) {
|
||||
const name = resolveImportedTypeName(node.typeName.text);
|
||||
return { mangled: name, text: name };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import ts from 'typescript';
|
||||
export type ImportedTypeNameResolver = (name: string) => string;
|
||||
|
||||
function identityImportedTypeName(name: string): string {
|
||||
return name;
|
||||
return name;
|
||||
}
|
||||
|
||||
// Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in
|
||||
@@ -13,47 +13,47 @@ function identityImportedTypeName(name: string): string {
|
||||
const syntheticTypeSourceFiles = new WeakMap<ts.TypeNode, ts.SourceFile>();
|
||||
|
||||
export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void {
|
||||
syntheticTypeSourceFiles.set(node, sf);
|
||||
syntheticTypeSourceFiles.set(node, sf);
|
||||
}
|
||||
|
||||
export function resolveSourceFileForTypeNode(node: ts.TypeNode, fallback: ts.SourceFile): ts.SourceFile {
|
||||
return syntheticTypeSourceFiles.get(node) ?? fallback;
|
||||
return syntheticTypeSourceFiles.get(node) ?? fallback;
|
||||
}
|
||||
|
||||
// TS 5.9+ removed ts.isKeywordTypeNode — manual kind-based check
|
||||
const KEYWORD_TYPE_KINDS = new Set([
|
||||
ts.SyntaxKind.StringKeyword,
|
||||
ts.SyntaxKind.NumberKeyword,
|
||||
ts.SyntaxKind.BooleanKeyword,
|
||||
ts.SyntaxKind.AnyKeyword,
|
||||
ts.SyntaxKind.VoidKeyword,
|
||||
ts.SyntaxKind.UndefinedKeyword,
|
||||
ts.SyntaxKind.NullKeyword,
|
||||
ts.SyntaxKind.NeverKeyword,
|
||||
ts.SyntaxKind.UnknownKeyword,
|
||||
ts.SyntaxKind.BigIntKeyword,
|
||||
ts.SyntaxKind.SymbolKeyword,
|
||||
ts.SyntaxKind.ObjectKeyword,
|
||||
ts.SyntaxKind.StringKeyword,
|
||||
ts.SyntaxKind.NumberKeyword,
|
||||
ts.SyntaxKind.BooleanKeyword,
|
||||
ts.SyntaxKind.AnyKeyword,
|
||||
ts.SyntaxKind.VoidKeyword,
|
||||
ts.SyntaxKind.UndefinedKeyword,
|
||||
ts.SyntaxKind.NullKeyword,
|
||||
ts.SyntaxKind.NeverKeyword,
|
||||
ts.SyntaxKind.UnknownKeyword,
|
||||
ts.SyntaxKind.BigIntKeyword,
|
||||
ts.SyntaxKind.SymbolKeyword,
|
||||
ts.SyntaxKind.ObjectKeyword,
|
||||
]);
|
||||
|
||||
export function isKeywordTypeNode(node: ts.Node): boolean {
|
||||
return KEYWORD_TYPE_KINDS.has(node.kind);
|
||||
return KEYWORD_TYPE_KINDS.has(node.kind);
|
||||
}
|
||||
|
||||
export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver {
|
||||
const localToImported = new Map<string, string>();
|
||||
const localToImported = new Map<string, string>();
|
||||
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
|
||||
const bindings = stmt.importClause.namedBindings;
|
||||
if (!bindings || !ts.isNamedImports(bindings)) continue;
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
|
||||
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);
|
||||
}
|
||||
for (const el of bindings.elements) {
|
||||
localToImported.set(el.name.text, (el.propertyName ?? el.name).text);
|
||||
}
|
||||
}
|
||||
|
||||
return (name: string) => localToImported.get(name) ?? name;
|
||||
return (name: string) => localToImported.get(name) ?? name;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,19 +67,19 @@ export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeN
|
||||
* the substituted type text rather than garbage from `sf`.
|
||||
*/
|
||||
export function typeNodeToMangledName(
|
||||
typeNode: ts.TypeNode,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
typeNode: ts.TypeNode,
|
||||
sf: ts.SourceFile,
|
||||
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
|
||||
): string {
|
||||
const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf);
|
||||
if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
|
||||
const base = resolveImportedTypeName(typeNode.typeName.text);
|
||||
if (typeNode.typeArguments && typeNode.typeArguments.length > 0) {
|
||||
const args = typeNode.typeArguments.map(a => typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName));
|
||||
return base + '__' + args.join('__');
|
||||
}
|
||||
return base;
|
||||
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('__');
|
||||
}
|
||||
if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf);
|
||||
return typeNode.getText(effectiveSf);
|
||||
return base;
|
||||
}
|
||||
if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf);
|
||||
return typeNode.getText(effectiveSf);
|
||||
}
|
||||
@@ -1,154 +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;
|
||||
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');
|
||||
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');
|
||||
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';
|
||||
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
|
||||
}
|
||||
|
||||
function isFixed64BigInt(typeName: string): boolean {
|
||||
return typeName === 'fixed_64' || typeName === 'sfixed_64';
|
||||
return typeName === 'fixed_64' || typeName === 'sfixed_64';
|
||||
}
|
||||
|
||||
const INLINE_SKIP = [
|
||||
` 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;`,
|
||||
` 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 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) {`,
|
||||
];
|
||||
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));
|
||||
});
|
||||
msg.fields.forEach((field, index) => {
|
||||
L.push(decodeField(field, index));
|
||||
});
|
||||
|
||||
L.push(
|
||||
` default: {`,
|
||||
INLINE_SKIP,
|
||||
` break;`,
|
||||
` }`,
|
||||
` }`,
|
||||
` }`,
|
||||
` return { ${result} };`,
|
||||
`}`,
|
||||
);
|
||||
return L.join('\n');
|
||||
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 { typeName, wireType, isMessage, isRepeated } = field;
|
||||
const I = ' ';
|
||||
const local = `_f${index}`;
|
||||
const assign = (expr: string) => isRepeated
|
||||
? `${I}${local}.push(${expr});`
|
||||
: `${I}${local} = ${expr};`;
|
||||
|
||||
const L: string[] = [` case ${tagValue(field)}: {`];
|
||||
const L: string[] = [` case ${tagValue(field)}: {`];
|
||||
|
||||
if (isMessage) {
|
||||
L.push(varintDec('_len', I));
|
||||
L.push(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;`);
|
||||
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');
|
||||
L.push(`${I}break;`, ` }`);
|
||||
return L.join('\n');
|
||||
}
|
||||
|
||||
function getDefault(field: ProtobufField): string {
|
||||
if (field.isRepeated) return '[]';
|
||||
if (field.isOptional || field.isMessage) return 'null';
|
||||
const primitive = PRIMITIVE_TYPE_MAP[field.typeName];
|
||||
return primitive ? primitive.defaultValue : 'null';
|
||||
if (field.isRepeated) return '[]';
|
||||
if (field.isOptional || field.isMessage) return 'null';
|
||||
const primitive = PRIMITIVE_TYPE_MAP[field.typeName];
|
||||
return primitive ? primitive.defaultValue : 'null';
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+115
-115
@@ -8,11 +8,11 @@ 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,
|
||||
normalizeRuntimeMapPath,
|
||||
runtimeMapToRegistry,
|
||||
type ProtobufRuntimeMap,
|
||||
type RuntimeMapCallSite,
|
||||
type RuntimeMapFnName,
|
||||
} from './runtime-map.js';
|
||||
|
||||
type DynamicEncode = (params: unknown) => Uint8Array;
|
||||
@@ -41,180 +41,180 @@ const dynamicTypeCache = new Map<string, DynamicTypeFns>();
|
||||
* This is disabled by default.
|
||||
*/
|
||||
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void {
|
||||
runtimeMapFallback = map;
|
||||
runtimeMapRegistry = runtimeMapToRegistry(map);
|
||||
runtimeMapCallSites = map.callSites.map(cs => ({
|
||||
...cs,
|
||||
file: normalizeRuntimeMapPath(cs.file),
|
||||
}));
|
||||
dynamicTypeCache.clear();
|
||||
runtimeMapFallback = map;
|
||||
runtimeMapRegistry = runtimeMapToRegistry(map);
|
||||
runtimeMapCallSites = map.callSites.map(cs => ({
|
||||
...cs,
|
||||
file: normalizeRuntimeMapPath(cs.file),
|
||||
}));
|
||||
dynamicTypeCache.clear();
|
||||
}
|
||||
|
||||
/** Disable dynamic runtime fallback and clear all generated function caches. */
|
||||
export function protobuf_disableRuntimeMapFallback(): void {
|
||||
runtimeMapFallback = null;
|
||||
runtimeMapRegistry = null;
|
||||
runtimeMapCallSites = [];
|
||||
dynamicTypeCache.clear();
|
||||
runtimeMapFallback = null;
|
||||
runtimeMapRegistry = null;
|
||||
runtimeMapCallSites = [];
|
||||
dynamicTypeCache.clear();
|
||||
}
|
||||
|
||||
export function protobuf_encode<T>(_params: T): Uint8Array {
|
||||
const dynamic = tryDynamicInvoke('protobuf_encode', _params);
|
||||
if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array;
|
||||
const dynamic = tryDynamicInvoke('protobuf_encode', _params);
|
||||
if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array;
|
||||
|
||||
throw new Error(
|
||||
'protobuf_encode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
|
||||
throw new Error(
|
||||
'protobuf_encode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
|
||||
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
|
||||
);
|
||||
);
|
||||
}
|
||||
|
||||
export function protobuf_decode<T>(_data: Uint8Array): T {
|
||||
const dynamic = tryDynamicInvoke('protobuf_decode', _data);
|
||||
if (dynamic !== DYNAMIC_MISS) return dynamic as T;
|
||||
const dynamic = tryDynamicInvoke('protobuf_decode', _data);
|
||||
if (dynamic !== DYNAMIC_MISS) return dynamic as T;
|
||||
|
||||
throw new Error(
|
||||
'protobuf_decode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
|
||||
throw new Error(
|
||||
'protobuf_decode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
|
||||
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
|
||||
);
|
||||
);
|
||||
}
|
||||
|
||||
function tryDynamicInvoke(fnName: RuntimeMapFnName, payload: unknown): unknown {
|
||||
if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) {
|
||||
return DYNAMIC_MISS;
|
||||
}
|
||||
if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) {
|
||||
return DYNAMIC_MISS;
|
||||
}
|
||||
|
||||
const caller = getFirstUserFrame();
|
||||
if (!caller) return DYNAMIC_MISS;
|
||||
const caller = getFirstUserFrame();
|
||||
if (!caller) return DYNAMIC_MISS;
|
||||
|
||||
const callSite = resolveCallSite(fnName, caller);
|
||||
if (!callSite) return DYNAMIC_MISS;
|
||||
const callSite = resolveCallSite(fnName, caller);
|
||||
if (!callSite) return DYNAMIC_MISS;
|
||||
|
||||
const typeFns = ensureTypeFunctions(callSite.typeName);
|
||||
if (!typeFns) 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;
|
||||
const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode;
|
||||
if (typeof fn !== 'function') return DYNAMIC_MISS;
|
||||
|
||||
return fn(payload as never);
|
||||
return fn(payload as never);
|
||||
}
|
||||
|
||||
function ensureTypeFunctions(typeName: string): DynamicTypeFns | null {
|
||||
const cached = dynamicTypeCache.get(typeName);
|
||||
if (cached) return cached;
|
||||
if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null;
|
||||
const cached = dynamicTypeCache.get(typeName);
|
||||
if (cached) return cached;
|
||||
if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null;
|
||||
|
||||
const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]);
|
||||
if (subset.size === 0) return null;
|
||||
const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]);
|
||||
if (subset.size === 0) return null;
|
||||
|
||||
const generated = generateCode(subset);
|
||||
if (!generated) return null;
|
||||
const generated = generateCode(subset);
|
||||
if (!generated) return null;
|
||||
|
||||
const factory = new Function(
|
||||
`${generated}\nreturn {\n` +
|
||||
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;
|
||||
) as () => DynamicTypeFns;
|
||||
|
||||
const compiled = factory();
|
||||
dynamicTypeCache.set(typeName, compiled);
|
||||
return compiled;
|
||||
const compiled = factory();
|
||||
dynamicTypeCache.set(typeName, compiled);
|
||||
return compiled;
|
||||
}
|
||||
|
||||
function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeMapCallSite | null {
|
||||
const callerFile = normalizeRuntimeMapPath(caller.file);
|
||||
const callerFile = normalizeRuntimeMapPath(caller.file);
|
||||
|
||||
const candidates = runtimeMapCallSites.filter(cs =>
|
||||
cs.fnName === fnName &&
|
||||
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];
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function getFirstUserFrame(): StackFrame | null {
|
||||
const err = new Error();
|
||||
if (!err.stack) return 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 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;
|
||||
const file = normalizeRuntimeMapPath(frame.file);
|
||||
if (isRuntimeInternalFile(file)) continue;
|
||||
|
||||
return {
|
||||
file,
|
||||
line: frame.line,
|
||||
column: frame.column,
|
||||
};
|
||||
}
|
||||
return {
|
||||
file,
|
||||
line: frame.line,
|
||||
column: frame.column,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseStackLine(line: string): StackFrame | null {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return 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();
|
||||
}
|
||||
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 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 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 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;
|
||||
const parsedLine = Number(linePart);
|
||||
const parsedCol = Number(colPart);
|
||||
if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) return null;
|
||||
|
||||
return {
|
||||
file,
|
||||
line: parsedLine,
|
||||
column: parsedCol,
|
||||
};
|
||||
return {
|
||||
file,
|
||||
line: parsedLine,
|
||||
column: parsedCol,
|
||||
};
|
||||
}
|
||||
|
||||
function isRuntimeInternalFile(file: string): boolean {
|
||||
return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js');
|
||||
return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js');
|
||||
}
|
||||
|
||||
function pathsLikelySame(a: string, b: string): boolean {
|
||||
if (a === b) return true;
|
||||
const aBase = basename(a);
|
||||
const bBase = basename(b);
|
||||
return aBase !== '' && aBase === bBase;
|
||||
if (a === b) return true;
|
||||
const aBase = basename(a);
|
||||
const bBase = basename(b);
|
||||
return aBase !== '' && aBase === bBase;
|
||||
}
|
||||
|
||||
function basename(file: string): string {
|
||||
const normalized = normalizeRuntimeMapPath(file);
|
||||
const idx = normalized.lastIndexOf('/');
|
||||
return idx >= 0 ? normalized.slice(idx + 1) : normalized;
|
||||
const normalized = normalizeRuntimeMapPath(file);
|
||||
const idx = normalized.lastIndexOf('/');
|
||||
return idx >= 0 ? normalized.slice(idx + 1) : normalized;
|
||||
}
|
||||
Reference in new issue
Block a user