From 1172a6bd3df88b3ccf8155783aa4229cd6e00d84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Sat, 24 Oct 2026 17:28:58 +0800 Subject: [PATCH] feat --- packages/protocol/vitest.config.ts | 3 +- packages/proton/README.md | 349 ++---- packages/proton/protobuf.d.ts | 36 - packages/proton/src/ast/analyzer.ts | 420 ------- packages/proton/src/ast/callsite.ts | 141 --- packages/proton/src/ast/collector.ts | 244 ---- packages/proton/src/ast/import-resolver.ts | 1114 ----------------- packages/proton/src/ast/monomorphizer.ts | 173 --- packages/proton/src/ast/types.ts | 83 -- packages/proton/src/ast/utils.ts | 115 -- packages/proton/src/codegen/buffer.ts | 13 + packages/proton/src/codegen/decoder.ts | 271 ++-- .../dependencies.ts} | 25 +- packages/proton/src/codegen/encoder.ts | 872 +------------ packages/proton/src/codegen/fields.ts | 141 +++ packages/proton/src/codegen/generator.ts | 320 ++--- packages/proton/src/codegen/helpers.ts | 98 ++ packages/proton/src/codegen/model.ts | 42 + packages/proton/src/codegen/unknown.ts | 60 + packages/proton/src/codegen/utf8.ts | 159 +++ packages/proton/src/codegen/write.ts | 56 + packages/proton/src/compiler/analysis.ts | 559 +++++++++ .../proton/src/compiler/callback-types.ts | 169 +++ packages/proton/src/compiler/callbacks.ts | 323 +++++ packages/proton/src/compiler/compiler.ts | 326 +++++ packages/proton/src/compiler/edits.ts | 80 ++ packages/proton/src/compiler/model.ts | 99 ++ packages/proton/src/compiler/receivers.ts | 404 ++++++ packages/proton/src/compiler/signatures.ts | 212 ++++ packages/proton/src/compiler/targets.ts | 345 +++++ packages/proton/src/compiler/validate.ts | 140 +++ packages/proton/src/index.ts | 166 +-- packages/proton/src/package.ts | 1 + packages/proton/src/runtime-map.ts | 78 -- packages/proton/src/runtime.ts | 296 +---- packages/proton/src/schema/message.ts | 143 +++ packages/proton/src/schema/objects.ts | 249 ++++ packages/proton/src/schema/operators.ts | 246 ++++ packages/proton/src/schema/relations.ts | 137 ++ packages/proton/src/schema/resolver.ts | 600 +++++++++ packages/proton/src/schema/types.ts | 38 + packages/proton/src/source/context.ts | 423 +++++++ packages/proton/src/source/entries.ts | 43 + packages/proton/src/transform/replacer.ts | 79 -- .../proton/test/__tests__/analyzer.test.ts | 169 --- .../test/__tests__/compatibility.test.ts | 242 ++++ .../proton/test/__tests__/cross-file.test.ts | 402 ------ .../test/__tests__/cross-package.test.ts | 188 --- .../proton/test/__tests__/generator.test.ts | 16 +- packages/proton/test/__tests__/plugin.test.ts | 348 ----- .../proton/test/__tests__/replacer.test.ts | 104 -- .../__tests__/runtime-map-fallback.test.ts | 113 -- .../proton/test/fixtures/aliased-pb-marker.ts | 21 - .../fixtures/cross-file/aliased-consumer.ts | 7 - .../test/fixtures/cross-file/consumer.ts | 6 - .../proton/test/fixtures/cross-file/deep.ts | 5 - .../fixtures/cross-file/generic-consumer.ts | 6 - .../test/fixtures/cross-file/generic-types.ts | 5 - .../proton/test/fixtures/cross-file/inner.ts | 5 - .../cross-file/local-wrapper-consumer.ts | 11 - .../proton/test/fixtures/cross-file/mid.ts | 7 - .../proton/test/fixtures/cross-file/outer.ts | 10 - .../test/fixtures/cross-file/protobuf.ts | 5 - .../proton/test/fixtures/cross-file/top.ts | 10 - .../proton/test/fixtures/cross-file/types.ts | 6 - .../cross-file/value-import-consumer.ts | 7 - .../test/fixtures/cross-file/wrapper-api.ts | 49 - .../cross-file/wrapper-complex-consumer.ts | 21 - .../fixtures/cross-file/wrapper-consumer.ts | 7 - .../cross-file/wrapper-edge-consumer.ts | 21 - .../cross-file/wrapper-type-source-base.ts | 6 - .../wrapper-type-source-consumer.ts | 15 - .../cross-file/wrapper-type-source.ts | 25 - .../proton/test/fixtures/generic-template.ts | 3 - .../proton/test/fixtures/generic-usage.ts | 8 - .../fixtures/generic-with-generic-field.ts | 24 - packages/proton/test/fixtures/multi-field.ts | 5 - .../test/fixtures/nested-generic-field.ts | 24 - packages/proton/test/fixtures/no-pb.ts | 3 - packages/proton/test/fixtures/real.ts | 12 - packages/proton/test/helpers/index.ts | 11 - .../test/upstream/codegen/buffer.test.ts | 94 ++ .../test/upstream/codegen/generator.test.ts | 245 ++++ .../proton/test/upstream/codegen/utf8.test.ts | 209 ++++ .../proton/test/upstream/codegen/wire.test.ts | 202 +++ packages/proton/test/upstream/compile.ts | 24 + .../test/upstream/compiler/callbacks.test.ts | 332 +++++ .../test/upstream/compiler/classes.test.ts | 196 +++ .../test/upstream/compiler/compile.test.ts | 424 +++++++ .../upstream/compiler/composition.test.ts | 201 +++ .../upstream/compiler/diagnostics.test.ts | 114 ++ .../test/upstream/compiler/evaluation.test.ts | 75 ++ .../test/upstream/compiler/modules.test.ts | 54 + .../test/upstream/compiler/types.test.ts | 87 ++ .../test/upstream/plugin/package-name.test.ts | 25 + .../proton/test/upstream/plugin/vite.test.ts | 108 ++ packages/proton/test/upstream/project.ts | 79 ++ packages/proton/test/upstream/schema.ts | 40 + packages/proton/tsconfig.json | 1 + packages/proton/vitest.config.ts | 2 +- 100 files changed, 8305 insertions(+), 6025 deletions(-) delete mode 100644 packages/proton/src/ast/analyzer.ts delete mode 100644 packages/proton/src/ast/callsite.ts delete mode 100644 packages/proton/src/ast/collector.ts delete mode 100644 packages/proton/src/ast/import-resolver.ts delete mode 100644 packages/proton/src/ast/monomorphizer.ts delete mode 100644 packages/proton/src/ast/types.ts delete mode 100644 packages/proton/src/ast/utils.ts create mode 100644 packages/proton/src/codegen/buffer.ts rename packages/proton/src/{ast/dependency-graph.ts => codegen/dependencies.ts} (50%) create mode 100644 packages/proton/src/codegen/fields.ts create mode 100644 packages/proton/src/codegen/helpers.ts create mode 100644 packages/proton/src/codegen/model.ts create mode 100644 packages/proton/src/codegen/unknown.ts create mode 100644 packages/proton/src/codegen/utf8.ts create mode 100644 packages/proton/src/codegen/write.ts create mode 100644 packages/proton/src/compiler/analysis.ts create mode 100644 packages/proton/src/compiler/callback-types.ts create mode 100644 packages/proton/src/compiler/callbacks.ts create mode 100644 packages/proton/src/compiler/compiler.ts create mode 100644 packages/proton/src/compiler/edits.ts create mode 100644 packages/proton/src/compiler/model.ts create mode 100644 packages/proton/src/compiler/receivers.ts create mode 100644 packages/proton/src/compiler/signatures.ts create mode 100644 packages/proton/src/compiler/targets.ts create mode 100644 packages/proton/src/compiler/validate.ts create mode 100644 packages/proton/src/package.ts delete mode 100644 packages/proton/src/runtime-map.ts create mode 100644 packages/proton/src/schema/message.ts create mode 100644 packages/proton/src/schema/objects.ts create mode 100644 packages/proton/src/schema/operators.ts create mode 100644 packages/proton/src/schema/relations.ts create mode 100644 packages/proton/src/schema/resolver.ts create mode 100644 packages/proton/src/schema/types.ts create mode 100644 packages/proton/src/source/context.ts create mode 100644 packages/proton/src/source/entries.ts delete mode 100644 packages/proton/src/transform/replacer.ts delete mode 100644 packages/proton/test/__tests__/analyzer.test.ts create mode 100644 packages/proton/test/__tests__/compatibility.test.ts delete mode 100644 packages/proton/test/__tests__/cross-file.test.ts delete mode 100644 packages/proton/test/__tests__/cross-package.test.ts delete mode 100644 packages/proton/test/__tests__/plugin.test.ts delete mode 100644 packages/proton/test/__tests__/replacer.test.ts delete mode 100644 packages/proton/test/__tests__/runtime-map-fallback.test.ts delete mode 100644 packages/proton/test/fixtures/aliased-pb-marker.ts delete mode 100644 packages/proton/test/fixtures/cross-file/aliased-consumer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/consumer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/deep.ts delete mode 100644 packages/proton/test/fixtures/cross-file/generic-consumer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/generic-types.ts delete mode 100644 packages/proton/test/fixtures/cross-file/inner.ts delete mode 100644 packages/proton/test/fixtures/cross-file/local-wrapper-consumer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/mid.ts delete mode 100644 packages/proton/test/fixtures/cross-file/outer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/protobuf.ts delete mode 100644 packages/proton/test/fixtures/cross-file/top.ts delete mode 100644 packages/proton/test/fixtures/cross-file/types.ts delete mode 100644 packages/proton/test/fixtures/cross-file/value-import-consumer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/wrapper-api.ts delete mode 100644 packages/proton/test/fixtures/cross-file/wrapper-complex-consumer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/wrapper-consumer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/wrapper-edge-consumer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/wrapper-type-source-base.ts delete mode 100644 packages/proton/test/fixtures/cross-file/wrapper-type-source-consumer.ts delete mode 100644 packages/proton/test/fixtures/cross-file/wrapper-type-source.ts delete mode 100644 packages/proton/test/fixtures/generic-template.ts delete mode 100644 packages/proton/test/fixtures/generic-usage.ts delete mode 100644 packages/proton/test/fixtures/generic-with-generic-field.ts delete mode 100644 packages/proton/test/fixtures/multi-field.ts delete mode 100644 packages/proton/test/fixtures/nested-generic-field.ts delete mode 100644 packages/proton/test/fixtures/no-pb.ts delete mode 100644 packages/proton/test/fixtures/real.ts create mode 100644 packages/proton/test/upstream/codegen/buffer.test.ts create mode 100644 packages/proton/test/upstream/codegen/generator.test.ts create mode 100644 packages/proton/test/upstream/codegen/utf8.test.ts create mode 100644 packages/proton/test/upstream/codegen/wire.test.ts create mode 100644 packages/proton/test/upstream/compile.ts create mode 100644 packages/proton/test/upstream/compiler/callbacks.test.ts create mode 100644 packages/proton/test/upstream/compiler/classes.test.ts create mode 100644 packages/proton/test/upstream/compiler/compile.test.ts create mode 100644 packages/proton/test/upstream/compiler/composition.test.ts create mode 100644 packages/proton/test/upstream/compiler/diagnostics.test.ts create mode 100644 packages/proton/test/upstream/compiler/evaluation.test.ts create mode 100644 packages/proton/test/upstream/compiler/modules.test.ts create mode 100644 packages/proton/test/upstream/compiler/types.test.ts create mode 100644 packages/proton/test/upstream/plugin/package-name.test.ts create mode 100644 packages/proton/test/upstream/plugin/vite.test.ts create mode 100644 packages/proton/test/upstream/project.ts create mode 100644 packages/proton/test/upstream/schema.ts diff --git a/packages/protocol/vitest.config.ts b/packages/protocol/vitest.config.ts index 3088a732..616ebb45 100644 --- a/packages/protocol/vitest.config.ts +++ b/packages/protocol/vitest.config.ts @@ -6,8 +6,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ // proton's vite plugin inlines `protobuf_encode` / `protobuf_decode` // call sites at build time. Required for both tests and benchmarks - // to hit the production code path rather than proton's runtime - // fallback (which throws unless a runtime-map JSON is loaded). + // to exercise the production codecs. Untransformed calls throw at runtime. plugins: [protobufVitePlugin()], test: { include: ['tests/**/*.test.ts'], diff --git a/packages/proton/README.md b/packages/proton/README.md index 2839133b..ac173fff 100644 --- a/packages/proton/README.md +++ b/packages/proton/README.md @@ -1,272 +1,131 @@ # @snowluma/proton -Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript -interfaces in, fully-inlined zero-runtime codec functions out. +Compile-time protobuf codecs for SnowLuma. TypeScript schemas and generic calls +are compiled into specialized encoders and decoders without runtime schema lookup. -> Vendored from [SnowLuma/protobuf-dsl](https://github.com/SnowLuma/protobuf-dsl) -> with edge-case fixes applied. +Vendored from [SnowLuma/protobuf-dsl](https://github.com/SnowLuma/protobuf-dsl) +(`protobuf-fastdsl`, commit `22e382a`), whose README declares the MIT license. +SnowLuma retains the `@snowluma/proton` package name, manifest and wire compatibility +rules described below. -## What it does +## Setup -You declare your wire schema as plain TypeScript interfaces marked up with -`pb`. At build time a Vite plugin walks the call sites of -`protobuf_encode` / `protobuf_decode` and replaces them with -type-specific, fully-inlined codec functions. No runtime schema lookup, -no reflection, no `.proto` files, no `protoc`. +Add `@snowluma/proton: workspace:*` to the consuming package's dependencies and +enable the plugin in its Vite or Vitest configuration: ```ts -import type { pb, pb_repeated, uint_32, bool } from '@snowluma/proton'; -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; - -interface UserProfile { - id?: pb<1, uint_32>; - username?: pb<2, string>; - active?: pb<3, bool>; - tags?: pb_repeated<4, string>; -} - -const bytes = protobuf_encode({ - id: 42, username: 'alice', active: true, tags: ['admin'], -}); -const user = protobuf_decode(bytes); -``` - -After the plugin transform, this becomes: - -```js -// pre-computed tag literals, inlined varint loops, no function-call overhead -const bytes = protobuf_encode_UserProfile({ id: 42, ... }); -const user = protobuf_decode_UserProfile(bytes); -``` - -If the plugin **isn't** installed, calling `protobuf_encode` / `protobuf_decode` -throws a loud error rather than silently producing wrong bytes. - -## Setup in SnowLuma - -The package is already wired into `@snowluma/core`'s `vitest.config.ts`. To use -it elsewhere in the monorepo: - -```ts -// vite.config.ts (or vitest.config.ts) import { defineConfig } from 'vite'; import protobufVitePlugin from '@snowluma/proton/vite'; export default defineConfig({ - plugins: [protobufVitePlugin()], + plugins: [protobufVitePlugin()], }); ``` -Add the workspace dep: - -```json -{ - "dependencies": { "@snowluma/proton": "workspace:*" } -} -``` - -## Primitive types - -The marker is `pb` (or `pb_repeated` for -arrays). Available primitives: - -| Marker | TS type | Wire | -| ----------- | ------------ | ---------------- | -| `bool` | `boolean` | varint | -| `uint_32` | `number` | varint | -| `int_32` | `number` | varint | -| `sint_32` | `number` | varint (zigzag) | -| `uint_64` | `bigint` | varint | -| `int_64` | `bigint` | varint | -| `sint_64` | `bigint` | varint (zigzag) | -| `fixed_32` | `number` | 32-bit | -| `fixed_64` | `bigint` | 64-bit | -| `sfixed_32` | `number` | 32-bit | -| `sfixed_64` | `bigint` | 64-bit | -| `float` | `number` | 32-bit | -| `double` | `number` | 64-bit | -| `string` | `string` | length-delimited | -| `bytes` | `Uint8Array` | length-delimited | - -Plus message types (any other interface marked with `pb<>` fields) used as -the second type-arg to `pb<>` / `pb_repeated<>`. - -## Generic templates - -You can declare reusable wrappers as generic interfaces: +The plugin entry resolves to a built artifact. After editing the compiler, run +`pnpm --filter @snowluma/proton build` before testing consuming packages. +Calls without the plugin throw a diagnostic naming `@snowluma/proton/vite`. ```ts -interface Wrapper { - value?: pb<1, T>; +import type { pb, pb_optional, pb_repeated, uint_32 } from '@snowluma/proton'; +import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; + +interface Profile { + id?: pb<1, uint_32>; + name?: pb<2, string>; + tags?: pb_repeated<3, string>; + state?: pb_optional<4, uint_32>; } -const bytes = protobuf_encode>({ value: 42 }); -// ^ instantiated at the call site +const bytes = protobuf_encode({ id: 42, name: 'alice', state: 0 }); +const profile = protobuf_decode(bytes); ``` -Nested instantiations work too — `Wrapper>` mono-morphizes to -`Wrapper__string` + `Wrapper__Wrapper__string` and both end up in the registry -at build time. +## Schema and compiler support -Compose them in concrete interfaces: +`pb` marks a singular field, `pb_repeated` marks a repeated field, +and `pb_optional` gives a singular field explicit wire presence. -```ts -interface Container { - wrapped?: pb<5, Wrapper>; -} +| Types | TypeScript value | Wire format | +| --- | --- | --- | +| `uint_32`, `int_32`, `sint_32` | `number` | Varint; `sint_32` uses zigzag | +| `uint_64`, `int_64`, `sint_64` | `bigint` | Varint; `sint_64` uses zigzag | +| `bool` | `boolean` | Varint | +| `fixed_32`, `sfixed_32`, `float` | `number` | 32-bit | +| `fixed_64`, `sfixed_64` | `bigint` | 64-bit | +| `double` | `number` | 64-bit | +| `string`, `bytes` | `string`, `Uint8Array` | Length-delimited | +| Message interfaces | Object | Length-delimited | + +The compiler resolves aliases, namespace imports, `export *`, relative and bare +package imports, nested generic schemas, generic functions and classes, and +forwarded callbacks. It preserves wrapper bodies and passes generated codecs +through generic calls. It also supports resolvable mapped, conditional and utility +types; ambiguous unions and unresolved schemas fail during compilation. + +Only required codecs and helpers are emitted. Nested message encoders measure and +write into a shared output buffer. Returned bytes may be a view into a larger +buffer; use `byteOffset` and `byteLength`, or `bytes.slice()` when an independent +backing buffer is needed. Later encodes do not overwrite previously returned bytes. + +## SnowLuma wire compatibility + +- Plain `pb<>` scalars omit default values (`0`, `0n`, `false`, empty strings and + empty bytes), including fields marked with TypeScript `?`. Missing optional + singular fields decode to `null`. +- `pb_optional<>` emits present default values while omitting `null`/`undefined`. + This preserves the explicit `state=0` needed to disable whole-group mute. +- Negative `int_32` values retain SnowLuma's five-byte outbound encoding. Decoders + accept both that form and canonical ten-byte sign-extended values. +- `uint_32` values consume a complete valid varint of up to ten bytes and retain + the low 32 bits. Tags and lengths remain limited to valid 32-bit framing. +- Decoders reject truncated/overflowing fields, invalid bounds and malformed + groups. Unknown groups are skipped within their parent frame with bounded depth. +- Unknown tags retain non-enumerable metadata, available through + `protobuf_getUnknownFields` and `protobuf_getUnknownFieldMetadata`. Metadata + aggregates occurrences, retains at most 64 field/wire kinds per message, and + summarizes omitted kinds without retaining their payloads. + +The previous runtime-map fallback and plugin option have been removed. Consumers +must compile encode/decode calls with the plugin. + +## Migration audit + +The upstream implementation was checked against Proton's source history before +replacement. The following behavior is covered by regression tests: + +| Proton history | Upstream status / retained behavior | +| --- | --- | +| Initial vendor fixes (`194165f4`) and generic OIDB migration (`58028123`) | Aliased markers, nested generic fields and forwarded wrappers are covered by the new compiler and integration tests. | +| Barrel exports (`f21740a5`) and bare imports (`994633ea`) | Supported by the new source resolver; tested through bundled cross-file and package fixtures. | +| Explicit presence (`90f26ca4`) | Added `pb_optional` to the new schema pipeline and kept `?` separate from wire presence. | +| Decoder hardening (`b7d648ea`) | Upstream already checks varints and field boundaries; retained integer bounds, group handling, bounded unknown metadata and legacy outbound `int32` bytes. | +| Extended `uint32` (`b53004ee`, `613b2b1e`) | Upstream consumes full value varints; retained the existing QQ regression fixtures. | +| Cleanup (`c7428363`) | Superseded by the new compiler/source module structure. | + +## Validation and layout + +From the repository root: + +```sh +pnpm --filter @snowluma/proton build +pnpm --filter @snowluma/proton typecheck +pnpm --filter @snowluma/proton test ``` -…or in other generic templates: +`test/upstream` contains the imported compiler, codegen and plugin suite, adjusted +for SnowLuma's package layout and wire rules. `test/__tests__` retains Proton's +wire regression tests and adds migration compatibility cases. Consumer tests in +`packages/protocol/tests` exercise real QQ schemas with the built plugin. -```ts -interface Outer { - wrapped?: pb<5, Wrapper>; -} -const bytes = protobuf_encode>({ wrapped: { value: 42 } }); -``` - -Both forms are covered by regression tests. - -## Cross-file & wrapper-binding - -Schemas can live in one file and call sites in another: - -```ts -// schema/user.ts -export interface UserProfile { id?: pb<1, uint_32>; } - -// usage.ts -import type { UserProfile } from './schema/user'; -import { protobuf_encode } from '@snowluma/proton'; -const bytes = protobuf_encode({ id: 42 }); -``` - -You can also build thin generic wrappers around `protobuf_encode` / `_decode` -and the plugin will trace through them, including across file boundaries: - -```ts -// schema/wrap.ts -export function encodeWrapped(v: Wrapper): Uint8Array { - return protobuf_encode>(v); -} - -// usage.ts -import { encodeWrapped } from './schema/wrap'; -const bytes = encodeWrapped({ value: 'hi' }); -// ^ plugin rewrites to protobuf_encode_Wrapper__string(...) -``` - -Chained forwarders also work (`A` forwards to `B` which is imported from -another module, etc.). - -## proto3 default-value semantics - -**Important behavioural detail.** Proton follows the proto3 wire format spec: -fields whose value equals the type's default (`0` / `false` / `""` / -empty bytes) are **not emitted** on the wire. This is byte-different from -SnowLuma's legacy `protoEncode` runtime, which always emits every field. - -Both forms are wire-compatible with any conforming proto3 reader (missing -fields decode as the default value). When migrating legacy schemas to proton, -do **not** treat byte-level inequality on default values as a regression — see -[`packages/core/tests/proton-parity.test.ts`](../../packages/core/tests/proton-parity.test.ts) -for the test that pins this divergence. - -If you have a wire consumer that depends on byte-level identity (e.g. for -hashing or signing), prefer to set non-default values explicitly rather than -relying on the encoder. - -## Diagnostics - -Anything that doesn't resolve to a primitive or a registered message **throws -at build time** rather than silently leaking a wrong wire type: - -``` -Cannot resolve protobuf field type "Partial__UserProfile" on message "Foo" -(field "bar", field number 3). The analyzer did not produce a primitive or -registered message for this type. Common causes: union / intersection / -mapped / conditional types, TypeScript utility types (Partial, Pick, …), -qualified names (ns.Type), or a missing import. -``` - -This is the safety net for TypeScript constructs the analyzer doesn't model. -Currently unsupported: - -- Union / intersection types (`A | B`, `A & B`) -- Conditional / mapped types (`T extends X ? A : B`, `{ [K in keyof T]: ... }`) -- TS utility types (`Partial`, `Pick`, `Readonly`, …) -- Qualified type names (`ns.Type`) -- Wrapper functions reached via namespace import (`import * as ns from`) - -…all of these will throw with a clear message instead of producing bad bytes. - -## Optional: runtime-map fallback - -If a call site can't be statically resolved (e.g. dynamic loading after build), -the plugin can emit a JSON map that the runtime can consume to generate codecs -on the fly. Off by default. - -```ts -import protobufVitePlugin from '@snowluma/proton/vite'; - -export default defineConfig({ - plugins: [protobufVitePlugin({ - runtimeMap: { enabled: true, fileName: 'snowluma-proton.runtime-map.json' }, - })], -}); -``` - -```ts -import runtimeMap from './snowluma-proton.runtime-map.json'; -import { protobuf_enableRuntimeMapFallback } from '@snowluma/proton'; - -protobuf_enableRuntimeMapFallback(runtimeMap); -``` - -## Edge cases fixed on top of upstream - -Each has a regression test in `test/__tests__/analyzer.test.ts`: - -| # | What used to break | -| - | --------------------- | -| 1 | `import { pb as P }` — aliased markers were ignored; fields dropped silently | -| 2 | `interface Foo { x: pb<1, Wrapper> }` — typeName stuck at `"Wrapper"`, no mono of the inner instantiation | -| 3 | `interface Outer { x: pb<1, Wrapper> }` — outer mono didn't re-instantiate the inner generic | -| 4 | Wrapper-binding synthetic SourceFile had empty text → `getText()` returned garbage | -| 5 | Cross-file forwarded wrappers (chain → imported base) not detected | -| 6 | `matchForwardedKnownWrapper` didn't propagate `typePattern` — chain treated `` as the encoded type instead of `Wrapper` | -| 7 | Synthetic-SF WeakMap was private to analyzer.ts → replacer used the wrong SF | - -Plus the build-time guard (above) that turns future analyzer gaps into hard -errors instead of silent miscodes. - -## Scripts - -``` -pnpm --filter @snowluma/proton build # bundle src/index.ts → dist/index.js -pnpm --filter @snowluma/proton test # vitest run (95 tests) -pnpm --filter @snowluma/proton typecheck # tsc --noEmit -``` - -## Layout - -``` +```text src/ - ast/ analyzer + type-tracking pipeline - analyzer.ts single-walk message + call-site collection - collector.ts interface → ProtobufField/GenericFieldTemplate - monomorphizer.ts generic instantiation → concrete ProtobufMessage - import-resolver.ts cross-file definition + wrapper resolution - callsite.ts matches protobuf_encode/decode invocations - utils.ts name resolution + synthetic-SF tracking - dependency-graph.ts topo sort + reachability - types.ts shared schema types - codegen/ inlined wire-format emitters - transform/ Vite plugin string edits - index.ts plugin entry (./vite) - runtime.ts runtime stubs + map fallback (.) - runtime-map.ts serialized map format - -protobuf.d.ts public types (pb<>, pb_repeated<>, primitive aliases) -test/ vitest suite (analyzer + cross-file + plugin) + source/ source files, TypeScript module resolution and build entries + schema/ type resolution and message construction + compiler/ call analysis, generic codec propagation and source rewriting + codegen/ wire emitters and selected helper generation + index.ts Vite plugin + package.ts package identity from package.json + runtime.ts uncompiled-call errors and unknown-field diagnostics +protobuf.d.ts public field markers and runtime declarations ``` diff --git a/packages/proton/protobuf.d.ts b/packages/proton/protobuf.d.ts index 5262feec..90354d7b 100644 --- a/packages/proton/protobuf.d.ts +++ b/packages/proton/protobuf.d.ts @@ -47,39 +47,3 @@ export interface ProtobufUnknownFieldMetadata { } export function protobuf_getUnknownFields(value: unknown): readonly ProtobufUnknownField[]; export function protobuf_getUnknownFieldMetadata(value: unknown): ProtobufUnknownFieldMetadata; - -// ── Optional runtime map fallback (disabled by default) ─────────────── -export interface ProtobufRuntimeField { - name: string; - fieldNumber: number; - typeName: string; - wireType: 0 | 1 | 2 | 5; - isMessage: boolean; - isOptional: boolean; - isRepeated: boolean; -} - -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; diff --git a/packages/proton/src/ast/analyzer.ts b/packages/proton/src/ast/analyzer.ts deleted file mode 100644 index 2e801ccf..00000000 --- a/packages/proton/src/ast/analyzer.ts +++ /dev/null @@ -1,420 +0,0 @@ -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, - getCallableName, - 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 instantiateWrapperTypePattern( - binding: WrapperBinding, - callerTypeArgs: ts.NodeArray, - 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; - 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(); - const mono = new Map(); - const callSites: CallSiteRecord[] = []; - const deferredTypeArgs: ts.TypeNode[] = []; - const importBindings = collectProtobufImportBindings(sf); - const resolveImportedTypeName = createImportedTypeNameResolver(sf); - const wrapperBindings = imported?.wrapperBindings ?? new Map(); - - // Seed with imported definitions - if (imported) { - concrete.push(...imported.concrete); - - for (const [k, v] of imported.templates) { - templates.set(k, v); - } - } - - // Stack of generic-function type-param scopes. When visiting a - // `protobuf_encode/decode` call whose type arg references one of - // these (e.g. `protobuf_encode>(env)` inside - // `function encodeOidbEnv(...)`), we MUST skip monomorphization — - // the type arg only resolves once the wrapper itself is instantiated - // at a downstream call site, and that case is handled separately by - // the wrapper-binding path in `matchForwardedProtobufFn`. Without - // this skip, the analyzer would happily mint a literal `OidbBase__T` - // registry entry with a `body.typeName = 'T'` field, which the - // wire-type guard then trips on. - const enclosingTypeParamStack: Set[] = []; - - function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean { - if (enclosingTypeParamStack.length === 0) { - return false; - } - - let found = false; - - function check(n: ts.Node): void { - if (found) { - return; - } - - if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) { - const name = n.typeName.text; - - for (const scope of enclosingTypeParamStack) { - if (scope.has(name)) { - found = true; - return; - } - } - } - - ts.forEachChild(n, check); - } - - check(typeArg); - return found; - } - - function nodeIntroducesTypeParams( - n: ts.Node, - ): readonly ts.TypeParameterDeclaration[] | undefined { - if (ts.isFunctionDeclaration(n)) { - return n.typeParameters; - } - - if (ts.isFunctionExpression(n)) { - return n.typeParameters; - } - - if (ts.isArrowFunction(n)) { - return n.typeParameters; - } - - if (ts.isMethodDeclaration(n)) { - return n.typeParameters; - } - - return undefined; - } - - // ── single walk ───────────────────────────────────────────────────── - ts.forEachChild(sf, function visit(node) { - const introduced = nodeIntroducesTypeParams(node); - const pushedScope = !!(introduced && introduced.length); - - if (pushedScope) { - enclosingTypeParamStack.push(new Set(introduced!.map((p) => p.name.text))); - } - - try { - if (ts.isInterfaceDeclaration(node)) { - if (node.typeParameters?.length) { - const tpl = collectGenericInterface(node, sf, resolveImportedTypeName); - - if (tpl) { - templates.set(tpl.name, tpl); - } - } else { - const msg = collectInterface(node, sf, resolveImportedTypeName); - - if (msg) { - concrete.push(msg); - } - - // Queue any generic-instantiated type-args appearing as field types - // (e.g. `wrapped: pb<5, Wrapper>`) for monomorphization. - // The call-site queue only sees the outer concrete type, so without - // this the nested instantiation would never reach the registry. - for (const ta of collectConcreteFieldGenericTypeArgs( - node, - resolveImportedTypeName, - )) { - deferredTypeArgs.push(ta); - } - } - } - - if (ts.isCallExpression(node)) { - const cs = matchProtobufCallSite(node, sf, importBindings, { - allowLegacyUnboundCanonical: true, - }); - - if (cs) { - if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) { - deferredTypeArgs.push(cs.firstTypeArg); - callSites.push(cs); - } - // else: this call sits inside a generic wrapper definition; the - // wrapper-binding path will materialise concrete codecs at each - // downstream call site instead. - } else if ( - node.typeArguments?.length && - getCallableName(node.expression) && - wrapperBindings.has(getCallableName(node.expression)!) - ) { - const binding = wrapperBindings.get(getCallableName(node.expression)!)!; - const firstTypeArg = instantiateWrapperTypePattern( - binding, - node.typeArguments, - sf, - ); - - if (!firstTypeArg) { - ts.forEachChild(node, visit); - return; - } - - const exprStart = node.expression.getStart(sf); - const lc = sf.getLineAndCharacterOfPosition(exprStart); - deferredTypeArgs.push(firstTypeArg); - callSites.push({ - fnName: binding.fnName, - exprStart, - typeArgsEnd: node.typeArguments.end + 1, - firstTypeArg, - line: lc.line + 1, - column: lc.character + 1, - }); - } - } - - ts.forEachChild(node, visit); - } finally { - if (pushedScope) { - enclosingTypeParamStack.pop(); - } - } - }); - - // ── post-walk: monomorphize deferred type args ────────────────────── - for (const typeArg of deferredTypeArgs) { - const typeSf = resolveSourceFileForTypeNode(typeArg, sf); - const typeResolver = createImportedTypeNameResolver(typeSf); - monomorphizeTypeNode(typeArg, typeSf, templates, mono, typeResolver); - } - - 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, Pick, …), ` + - `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(); - const resolved: ResolvedCallSiteRecord[] = []; - - for (const cs of callSites) { - const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile); - const typeName = typeNodeToMangledName( - cs.firstTypeArg, - typeSf, - createImportedTypeNameResolver(typeSf), - ); - - if (!registry.has(typeName)) { - continue; - } - - roots.add(typeName); - resolved.push({ ...cs, typeName }); - } - - 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(); - const visiting = new Set(); - - 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])); -} diff --git a/packages/proton/src/ast/callsite.ts b/packages/proton/src/ast/callsite.ts deleted file mode 100644 index f6dc77d9..00000000 --- a/packages/proton/src/ast/callsite.ts +++ /dev/null @@ -1,141 +0,0 @@ -import ts from 'typescript'; - -export type CanonicalProtobufFn = 'protobuf_encode' | 'protobuf_decode'; - -const CANONICAL = new Set(['protobuf_encode', 'protobuf_decode']); -const PROTOBUF_RUNTIME_MODULES = new Set(['@snowluma/proton']); - -export interface ProtobufImportBindings { - identifierToCanonical: Map; - namespaceAliases: Set; - blockedLegacyCanonical: Set; - 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(); - const namespaceAliases = new Set(); - const blockedLegacyCanonical = new Set(); - 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, - }; -} diff --git a/packages/proton/src/ast/collector.ts b/packages/proton/src/ast/collector.ts deleted file mode 100644 index 1515e33f..00000000 --- a/packages/proton/src/ast/collector.ts +++ /dev/null @@ -1,244 +0,0 @@ -import ts from 'typescript'; -import { - WireType, - PB_MARKER, - PB_REPEATED_MARKER, - PB_OPTIONAL_MARKER, - type ProtobufField, - type ProtobufMessage, - type GenericProtobufTemplate, - type GenericFieldTemplate, -} from './types.js'; -import { - isKeywordTypeNode, - typeNodeToMangledName, - type ImportedTypeNameResolver, -} from './utils.js'; - -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>` - * yields the `Wrapper` 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 { - 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); - } - } - - // 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, -): 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 && marker !== PB_OPTIONAL_MARKER) { - return null; - } - - const ta = t.typeArguments; - - if (!ta || ta.length !== 2) { - return null; - } - - const fnNode = ta[0]; - - if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) { - return null; - } - - return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] }; -} - -function resolveTypeName( - node: ts.TypeNode, - sf: ts.SourceFile, - resolveImportedTypeName: ImportedTypeNameResolver, -): string | null { - if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) { - // Generic instantiations (e.g. `Wrapper`) 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, - explicitPresence: parsed.marker === PB_OPTIONAL_MARKER, - }; -} - -function extractGenericField( - member: ts.PropertySignature, - sf: ts.SourceFile, - tpSet: Set, - resolveImportedTypeName: ImportedTypeNameResolver, -): GenericFieldTemplate | null { - const parsed = parsePbTypeRef(member, resolveImportedTypeName); - - if (!parsed) { - return null; - } - - const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName); - - if (!raw || !ts.isIdentifier(member.name)) { - return null; - } - - const result: GenericFieldTemplate = { - name: (member.name as ts.Identifier).text, - fieldNumber: parsed.fieldNumber, - rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw), - isTypeParam: tpSet.has(raw), - isOptional: member.questionToken != null, - isRepeated: parsed.marker === PB_REPEATED_MARKER, - explicitPresence: parsed.marker === PB_OPTIONAL_MARKER, - }; - // If the field's type-arg is itself a generic instantiation (`Wrapper`, - // 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; -} diff --git a/packages/proton/src/ast/import-resolver.ts b/packages/proton/src/ast/import-resolver.ts deleted file mode 100644 index 31464cc6..00000000 --- a/packages/proton/src/ast/import-resolver.ts +++ /dev/null @@ -1,1114 +0,0 @@ -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, - getCallableName, - 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; - importedTypeSources: Map; - exportAllTypeSources: Map; - resolveImportedTypeName: ImportedTypeNameResolver; - exportedWrappers: Map; -} - -export interface ImportedDefinitions { - concrete: ProtobufMessage[]; - templates: Map; - wrapperBindings: Map; -} - -interface ImportClause { - importedName: string; - localName: string; - specifier: string; -} - -/** 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; -} - -function extractExportAllSpecifiers(sf: ts.SourceFile): string[] { - const result: string[] = []; - - for (const stmt of sf.statements) { - if (!ts.isExportDeclaration(stmt) || stmt.exportClause) { - continue; - } - - const spec = stmt.moduleSpecifier; - - if (spec && ts.isStringLiteral(spec)) { - result.push(spec.text); - } - } - - return result; -} - -// Compiler options used for bare-specifier module resolution. `Bundler` -// matches modern monorepo + vite tooling: it understands `package.json` -// `exports`, `main`, and workspace symlinks without forcing the caller -// to spell out file extensions. We pass these once per process — the -// only consumer here is `ts.resolveModuleName` and it doesn't mutate -// them. -const BARE_SPECIFIER_COMPILER_OPTIONS: ts.CompilerOptions = { - moduleResolution: ts.ModuleResolutionKind.Bundler, - module: ts.ModuleKind.ESNext, - target: ts.ScriptTarget.Latest, - allowImportingTsExtensions: true, -}; - -// Per-process cache for `ts.resolveModuleName`. Hot paths (rebuild on -// HMR) call this hundreds of times — without the cache each call -// re-walks `node_modules` and `package.json` lookups. -let bareModuleResolutionCache: ts.ModuleResolutionCache | null = null; - -function getBareModuleResolutionCache(): ts.ModuleResolutionCache { - if (!bareModuleResolutionCache) { - bareModuleResolutionCache = ts.createModuleResolutionCache( - process.cwd(), - (s) => s, - BARE_SPECIFIER_COMPILER_OPTIONS, - ); - } - - 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. - */ -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 - 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; - } - - // ── Bare specifier branch ── - const result = ts.resolveModuleName( - specifier, - importerPath, - BARE_SPECIFIER_COMPILER_OPTIONS, - ts.sys, - getBareModuleResolutionCache(), - ); - const resolved = result.resolvedModule; - - if (!resolved) { - return null; - } - - // Only accept .ts source — see doc comment above for why. - if (resolved.extension !== ts.Extension.Ts) { - return null; - } - - return resolved.resolvedFileName; -} - -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, -): 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, -): 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, - 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, -): 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 `` as the encoded type rather than the - // wrapped form (e.g. `Wrapper`). - 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 = new Map(), -): Map { - const wrappers = new Map(); - const localWrapperMembers = new Map>(); - 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(v) { return encodeBar(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(); - - 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(); - - 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 = new Map(), -): Map { - 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(v) { return encodeBase(v); }` - * where `encodeBase` is imported from another module — can be detected. - */ -function parseFileForDefinitions( - absolutePath: string, - code?: string, - cache?: Map, - parsing?: Set, -): 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(); - const resolveImportedTypeName = createImportedTypeNameResolver(sf); - const importedTypeSources = new Map(); - const exportAllTypeSources = new Map(); - - // 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(); - - if (cache) { - const inProgress = parsing ?? new Set(); - 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); - } - - if (cache) { - const inProgress = parsing ?? new Set(); - inProgress.add(absolutePath); - - for (const specifier of extractExportAllSpecifiers(sf)) { - const resolved = resolveModulePath(specifier, absolutePath); - - if (!resolved || inProgress.has(resolved)) { - continue; - } - - let entry = cache.get(resolved); - - if (!entry) { - entry = parseFileForDefinitions(resolved, undefined, cache, inProgress); - cache.set(resolved, entry); - } - - for (const msg of entry.concrete) { - exportAllTypeSources.set(msg.name, resolved); - } - - for (const name of entry.templates.keys()) { - exportAllTypeSources.set(name, resolved); - } - - for (const [name, source] of entry.exportAllTypeSources) { - exportAllTypeSources.set(name, source); - } - } - - inProgress.delete(absolutePath); - } - - 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, - exportAllTypeSources, - 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, -): ImportedDefinitions { - const entryPath = resolve(importerPath); - const entry = parseFileForDefinitions(entryPath, code, cache); - const concrete = new Map(); - const templates = new Map(); - const fileEntries = new Map([[entryPath, entry]]); - const visitedConcrete = new Set(); - const visitedTemplates = new Set(); - const importedObjectWrapperMembers = new Map>(); - - 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 { - const names = new Set(); - - 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 { - const bindings = new Map(); - 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(); - - 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) ?? from.exportAllTypeSources.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 }; -} diff --git a/packages/proton/src/ast/monomorphizer.ts b/packages/proton/src/ast/monomorphizer.ts deleted file mode 100644 index a5e08dfe..00000000 --- a/packages/proton/src/ast/monomorphizer.ts +++ /dev/null @@ -1,173 +0,0 @@ -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>` → 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, - out: Map, - 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(); - - 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>`). Substitute the params into - // the captured text, re-parse, and re-monomorphize so the resulting - // concrete instantiation (`Wrapper`) lands in `out`. - let substituted = f.genericTypeArgText; - - for (const [paramName, value] of paramMap) { - substituted = substituted.replace( - new RegExp(`\\b${paramName}\\b`, 'g'), - value.text, - ); - } - - const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName; - const innerSf = ts.createSourceFile( - innerSfPath, - `type __X = ${substituted};`, - ts.ScriptTarget.Latest, - true, - ); - const stmt = innerSf.statements[0]; - let resolvedTypeName: string | null = null; - - if (ts.isTypeAliasDeclaration(stmt)) { - const innerResolver = createImportedTypeNameResolver(innerSf); - resolvedTypeName = monomorphizeTypeNode( - stmt.type, - innerSf, - templates, - out, - innerResolver, - ); - } - - return { - name: f.name, - fieldNumber: f.fieldNumber, - typeName: resolvedTypeName ?? f.rawTypeName, - wireType: WireType.Varint, - isMessage: false, - isOptional: f.isOptional, - isRepeated: f.isRepeated, - explicitPresence: f.explicitPresence, - }; - } - - return { - name: f.name, - fieldNumber: f.fieldNumber, - typeName: f.isTypeParam - ? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName) - : f.rawTypeName, - wireType: WireType.Varint, - isMessage: false, - isOptional: f.isOptional, - isRepeated: f.isRepeated, - explicitPresence: f.explicitPresence, - }; - }); - - out.set(mangledName, { name: mangledName, fields }); - return mangledName; -} - -function resolveTypeArg( - node: ts.TypeNode, - sf: ts.SourceFile, - templates: Map, - out: Map, - 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; -} diff --git a/packages/proton/src/ast/types.ts b/packages/proton/src/ast/types.ts deleted file mode 100644 index 09bf4369..00000000 --- a/packages/proton/src/ast/types.ts +++ /dev/null @@ -1,83 +0,0 @@ -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; - /** - * Explicit presence (proto3 `optional`), set only by the `pb_optional<>` - * marker. When true, a scalar field serialises even at its zero/default - * value. Distinct from `isOptional` (which merely tracks the TS `?` and is - * true for almost every field) — the encoder keys off THIS flag, never - * `isOptional`, so existing `pb<>` fields are unaffected. - */ - explicitPresence: boolean; -} - -export interface ProtobufMessage { - name: string; - fields: ProtobufField[]; -} - -/** Generic interface template, e.g. `interface Wrapper { 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; - /** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */ - explicitPresence: boolean; - /** - * For fields whose type-arg is itself a generic instantiation - * (e.g. `wrapped: pb<5, Wrapper>` 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` 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; - -export const PRIMITIVE_TYPE_MAP: Record = { - 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'; -export const PB_OPTIONAL_MARKER = 'pb_optional'; diff --git a/packages/proton/src/ast/utils.ts b/packages/proton/src/ast/utils.ts deleted file mode 100644 index b662cb85..00000000 --- a/packages/proton/src/ast/utils.ts +++ /dev/null @@ -1,115 +0,0 @@ -import ts from 'typescript'; - -export type ImportedTypeNameResolver = (name: string) => string; - -export 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 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(); - -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(); - - 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` → `Foo__string` - * `Foo>` → `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); -} diff --git a/packages/proton/src/codegen/buffer.ts b/packages/proton/src/codegen/buffer.ts new file mode 100644 index 00000000..ef73c9e0 --- /dev/null +++ b/packages/proton/src/codegen/buffer.ts @@ -0,0 +1,13 @@ +export const buffers = `let __pool; +let __poolOffset = 0; +function __allocate(size) { + if (size > 4096) return new Uint8Array(size); + let buffer = __pool; + if (!buffer || __poolOffset + size > buffer.length) { + buffer = __pool = new Uint8Array(8192); + __poolOffset = 0; + } + const start = __poolOffset; + __poolOffset += size; + return buffer.subarray(start, start + size); +}`; diff --git a/packages/proton/src/codegen/decoder.ts b/packages/proton/src/codegen/decoder.ts index c863b245..cbd65b94 100644 --- a/packages/proton/src/codegen/decoder.ts +++ b/packages/proton/src/codegen/decoder.ts @@ -3,84 +3,118 @@ import { PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, - type MessageRegistry, -} from '../ast/types.js'; +} from '../codegen/model.js'; -function tagValue(field: ProtobufField): number { - const wireType = - field.isMessage || field.typeName === 'string' || field.typeName === 'bytes' - ? WireType.LengthDelim - : field.wireType; +function tagValue(field: ProtobufField, wireType = field.wireType): number { return ((field.fieldNumber << 3) | wireType) >>> 0; } -/** Emit inline varint decode, storing result in `varName`. */ -function varintDec(varName: string, ind: string): string { +/** Read the low 32 bits, consuming sign-extended int32 varints without shift wraparound. */ +function varintDec( + varName: string, + ind: string, + end = 'end', + maxBytes = 10, + truthy = false, + checkInitial = true, +): string { + const lastShift = (maxBytes - 1) * 7; + const lastByte = maxBytes === 5 ? 0x0f : 0x01; return [ - `${ind}const [${varName}, ${varName}_offset] = __readVarint32(data, offset, end);`, - `${ind}offset = ${varName}_offset;`, + ...(checkInitial + ? [`${ind}if (offset >= ${end}) throw new Error('Truncated protobuf varint');`] + : []), + `${ind}let ${varName} = data[offset++];`, + `${ind}if (${varName} & 0x80) {`, + `${ind} let _s = 7, _b;`, + `${ind} ${varName} &= 0x7f;`, + `${ind} do {`, + `${ind} if (offset >= ${end}) throw new Error('Truncated protobuf varint');`, + `${ind} _b = data[offset++];`, + `${ind} if (_s === ${lastShift} && _b > ${lastByte}) throw new Error('Invalid protobuf varint');`, + truthy + ? `${ind} ${varName} |= _b & 0x7f;` + : `${ind} if (_s < 32) ${varName} |= (_b & 0x7f) << _s;`, + `${ind} _s += 7;`, + `${ind} } while (_b & 0x80);`, + `${ind} ${varName} >>>= 0;`, + `${ind}}`, ].join('\n'); } -function varintDec64(varName: string, ind: string): string { +function varintDec64(varName: string, ind: string, end: string): string { return [ - `${ind}const [${varName}, ${varName}_offset] = __readVarint64(data, offset, end);`, - `${ind}offset = ${varName}_offset;`, + `${ind}let _lo = 0, _hi = 0, _s = 0, _b;`, + `${ind}do {`, + `${ind} if (offset >= ${end}) throw new Error('Truncated protobuf varint');`, + `${ind} _b = data[offset++];`, + `${ind} if (_s === 63 && _b > 1) throw new Error('Invalid protobuf varint');`, + `${ind} if (_s < 28) _lo |= (_b & 0x7f) << _s;`, + `${ind} else if (_s === 28) { _lo |= (_b & 0x7f) << 28; _hi = (_b & 0x7f) >>> 4; }`, + `${ind} else _hi |= (_b & 0x7f) << (_s - 32);`, + `${ind} _s += 7;`, + `${ind}} while (_b & 0x80);`, + `${ind}const ${varName} = _hi === 0 ? BigInt(_lo >>> 0) : BigInt(_lo >>> 0) | (BigInt(_hi >>> 0) << 32n);`, ].join('\n'); } -function varintDec32Value(varName: string, ind: string): string { - return [ - `${ind}const [${varName}, ${varName}_offset] = __readVarint32Value(data, offset, end);`, - `${ind}offset = ${varName}_offset;`, - ].join('\n'); +function checkLength(length: string | number, ind: string, end: string): string { + return `${ind}if (offset + ${length} > ${end}) throw new Error('Truncated protobuf field');`; } -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 = ` offset = __skipUnknownField(data, offset, end, wireType, _tag >>> 3);`; - -export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string { +export function generateDecoder(msg: ProtobufMessage): 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 result = msg.fields + .map( + (field, index) => + `${field.name === '__proto__' ? '["__proto__"]' : JSON.stringify(field.name)}: _f${index}`, + ) + .join(', '); - const L = [ + const lines = [ `function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`, - ` if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(end) || offset < 0 || end < offset || end > data.length) {`, - ` throw new Error('protobuf decoder bounds are invalid');`, - ` }`, + ` if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(end) || offset < 0 || end > data.length || offset > end) throw new Error('Invalid protobuf bounds');`, ...locals, ` let _unknownFields = null;`, ` let _unknownFieldsByKey = null;`, ` let _unknownTotalOccurrences = 0;`, ` let _unknownOmittedOccurrences = 0;`, ` let _unknownOmittedByteLength = 0;`, + ` while (offset < end) {`, - ` const _fieldStart = offset;`, - ` const [_tag, _tagOffset] = __readVarint32(data, offset, end);`, - ` offset = _tagOffset;`, - ` if ((_tag >>> 3) === 0) throw new Error('protobuf field number 0 is invalid');`, + varintDec('_tag', ' ', 'end', 5, false, false), + ` if ((_tag >>> 3) === 0) throw new Error('Invalid protobuf field number');`, ` switch (_tag) {`, ]; msg.fields.forEach((field, index) => { - L.push(decodeField(field, index)); + lines.push(` case ${tagValue(field)}: {`); + lines.push(...decodeValue(field, index, ' ', 'end')); + lines.push(` break;`, ` }`); + + if (field.isRepeated && !field.isMessage && field.wireType !== WireType.LengthDelim) { + lines.push( + ` case ${tagValue(field, WireType.LengthDelim)}: {`, + varintDec('_len', ' ', 'end', 5), + checkLength('_len', ' ', 'end'), + ` const _packedEnd = offset + _len;`, + ` while (offset < _packedEnd) {`, + ...decodeValue(field, index, ' ', '_packedEnd'), + ` }`, + ` break;`, + ` }`, + ); + } }); - L.push( + lines.push( ` default: {`, ` const _unknownStart = offset;`, ` const wireType = _tag & 0x7;`, - INLINE_SKIP, + ` offset = __skipUnknownField(data, offset, end, wireType, _tag >>> 3);`, ` const _unknownFieldNumber = _tag >>> 3;`, ` const _unknownByteLength = offset - _unknownStart;`, ` const _unknownKey = (_unknownFieldNumber * 8) + wireType;`, @@ -102,10 +136,10 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry ` _unknownOmittedOccurrences++;`, ` _unknownOmittedByteLength += _unknownByteLength;`, ` }`, + ` break;`, ` }`, ` }`, - ` if (offset <= _fieldStart || offset > end) throw new Error('protobuf decoder made invalid progress');`, ` }`, ` const _result = { ${result} };`, ` if (_unknownTotalOccurrences > 0) Object.defineProperty(`, @@ -124,96 +158,83 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry ` return _result;`, `}`, ); - return L.join('\n'); + return lines.join('\n'); } -function decodeField(field: ProtobufField, index: number): string { +/** Shared by ordinary fields and packed repeated payloads. */ +function decodeValue(field: ProtobufField, index: number, ind: string, end: string): 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};`; + isRepeated ? `${ind}${local}.push(${expr});` : `${ind}${local} = ${expr};`; + const lines: string[] = []; - const L: string[] = [` case ${tagValue(field)}: {`]; - - if (isMessage) { - L.push(varintDec('_len', I)); - L.push(`${I}const _end = __checkedEnd(offset, _len, end);`); - L.push(assign(`protobuf_decode_${typeName}(data, offset, _end)`)); - L.push(`${I}offset = _end;`); - } else if (typeName === 'string') { - L.push(varintDec('_len', I)); - L.push(`${I}const _end = __checkedEnd(offset, _len, end);`); - L.push(assign(`__td.decode(data.subarray(offset, _end))`)); - L.push(`${I}offset = _end;`); - } else if (typeName === 'bytes') { - L.push(varintDec('_len', I)); - L.push(`${I}const _end = __checkedEnd(offset, _len, end);`); - L.push(assign(`data.slice(offset, _end)`)); - L.push(`${I}offset = _end;`); - } else if (typeName === 'bool') { - L.push(varintDec('_val', I)); - L.push(assign(`_val !== 0`)); - } else if (isVarint64(typeName)) { - L.push(varintDec64('_val', I)); - - if (typeName === 'uint_64') { - L.push(assign(`_val`)); - } else if (typeName === 'int_64') { - L.push(assign(`BigInt.asIntN(64, _val)`)); - } else { - L.push(assign(`__zigZagDecode64(_val)`)); - } - } else if (typeName === 'int_32') { - // Protobuf encodes negative int32 values as a sign-extended 10-byte - // varint. Read the full uint64 representation, then keep its signed low - // 32 bits. - L.push(varintDec64('_val', I)); - L.push(assign(`Number(BigInt.asIntN(32, _val))`)); - } else if (typeName === 'sint_32') { - L.push(varintDec('_val', I)); - L.push(assign(`(_val >>> 1) ^ -(_val & 1)`)); - } else if (wireType === WireType.Varint) { - L.push(varintDec32Value('_val', I)); - L.push(assign(`_val >>> 0`)); - } else if (typeName === 'float') { - L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated float field');`); - L.push(assign(`__readFloat32(data, offset)`)); - L.push(`${I}offset += 4;`); - } else if (wireType === WireType.Bit32) { - L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');`); - L.push( - assign( - `data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`, - ), - ); - L.push(`${I}offset += 4;`); - } else if (typeName === 'double') { - L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated double field');`); - L.push(assign(`__readFloat64(data, offset)`)); - L.push(`${I}offset += 8;`); - } else if (isFixed64BigInt(typeName)) { - L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`); - - if (typeName === 'fixed_64') { - L.push(assign(`__readFixed64(data, offset)`)); - } else { - L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`)); - } - - L.push(`${I}offset += 8;`); - } else if (wireType === WireType.Bit64) { - L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`); - L.push( - assign( - `data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`, - ), - ); - L.push(`${I}offset += 8;`); + if (wireType === WireType.Bit32) { + lines.push(checkLength(4, ind, end)); } - L.push(`${I}break;`, ` }`); - return L.join('\n'); + if (wireType === WireType.Bit64) { + lines.push(checkLength(8, ind, end)); + } + + if (isMessage || typeName === 'string' || typeName === 'bytes') { + lines.push(varintDec('_len', ind, end, 5), checkLength('_len', ind, end)); + + if (isMessage) { + lines.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`)); + } else if (typeName === 'string') { + lines.push( + assign( + `_len <= 32 ? __utf8Read(data, offset, offset + _len) : __utf8ReadLong(data, offset, offset + _len)`, + ), + ); + } else { + lines.push(assign(`data.slice(offset, offset + _len)`)); + } + + lines.push(`${ind}offset += _len;`); + } else if (typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64') { + lines.push(varintDec64('_val', ind, end)); + const value = + typeName === 'uint_64' + ? '_val' + : typeName === 'int_64' + ? 'BigInt.asIntN(64, _val)' + : '__zigZagDecode64(_val)'; + lines.push(assign(value)); + } else if (wireType === WireType.Varint) { + lines.push(varintDec('_val', ind, end, 10, typeName === 'bool')); + const value = + typeName === 'bool' + ? '_val !== 0' + : typeName === 'sint_32' + ? '(_val >>> 1) ^ -(_val & 1)' + : typeName === 'int_32' + ? '_val | 0' + : '_val'; + lines.push(assign(value)); + } else if (typeName === 'float') { + lines.push(assign('__readFloat32(data, offset)'), `${ind}offset += 4;`); + } else if (wireType === WireType.Bit32) { + const value = + '(data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24))'; + lines.push( + assign(typeName === 'fixed_32' ? `${value} >>> 0` : value), + `${ind}offset += 4;`, + ); + } else if (typeName === 'double') { + lines.push(assign('__readFloat64(data, offset)'), `${ind}offset += 8;`); + } else if (typeName === 'fixed_64' || typeName === 'sfixed_64') { + const value = + typeName === 'fixed_64' + ? '__readFixed64(data, offset)' + : 'BigInt.asIntN(64, __readFixed64(data, offset))'; + lines.push(assign(value), `${ind}offset += 8;`); + } else { + throw new Error(`Unsupported protobuf field type: ${typeName}`); + } + + return lines; } function getDefault(field: ProtobufField): string { diff --git a/packages/proton/src/ast/dependency-graph.ts b/packages/proton/src/codegen/dependencies.ts similarity index 50% rename from packages/proton/src/ast/dependency-graph.ts rename to packages/proton/src/codegen/dependencies.ts index 91c0acc5..5e4cc7ac 100644 --- a/packages/proton/src/ast/dependency-graph.ts +++ b/packages/proton/src/codegen/dependencies.ts @@ -1,4 +1,4 @@ -import type { MessageRegistry } from './types.js'; +import type { MessageRegistry } from './model.js'; export function collectDependencyClosure( registry: MessageRegistry, @@ -32,26 +32,3 @@ export function collectDependencyClosure( return selected; } - -export function pickRegistrySubset( - registry: MessageRegistry, - selectedNames: Set, -): 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, -): MessageRegistry { - const selected = collectDependencyClosure(registry, roots); - return pickRegistrySubset(registry, selected); -} diff --git a/packages/proton/src/codegen/encoder.ts b/packages/proton/src/codegen/encoder.ts index 5055b7f9..b165193f 100644 --- a/packages/proton/src/codegen/encoder.ts +++ b/packages/proton/src/codegen/encoder.ts @@ -1,845 +1,51 @@ -import { - WireType, - type ProtobufField, - type ProtobufMessage, - type MessageRegistry, -} from '../ast/types.js'; +import type { ProtobufMessage } from './model.js'; +import { fieldBlock } from './fields.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 { +export function generateEncoderHelpers(message: ProtobufMessage): string { + const blocks = message.fields.map((field, index) => fieldBlock(field, index, true)); 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}}`, + `function __size_${message.name}(obj, sizes) {`, + ' let size = 0;', + ...blocks.flatMap((block) => block.declare), + ...blocks.flatMap((block) => block.size), + ' return size;', + '}', + `function __write_${message.name}(obj, buf, offset, sizes) {`, + ...blocks.flatMap((block) => block.declare), + ...blocks.flatMap((block) => block.write), + ' return offset;', + '}', ].join('\n'); } -function isVarint64(typeName: string): boolean { - return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64'; -} +export function generateEncoder(message: ProtobufMessage, pooled = false): string { + const allocation = pooled + ? ' const buf = size <= 64 ? new Uint8Array(size) : __allocate(size);' + : ' const buf = new Uint8Array(size);'; -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 (message.fields.some((field) => field.isMessage)) { + return [ + `function protobuf_encode_${message.name}(obj) {`, + ' const sizes = [1];', + ...(pooled + ? [` const size = __size_${message.name}(obj, sizes);`, allocation] + : [` const buf = new Uint8Array(__size_${message.name}(obj, sizes));`]), + ` __write_${message.name}(obj, buf, 0, sizes);`, + ' return buf;', + '}', + ].join('\n'); } - 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;`, + const blocks = message.fields.map((field, index) => fieldBlock(field, index, false)); + return [ + `function protobuf_encode_${message.name}(obj) {`, + ' let size = 0;', ...blocks.flatMap((block) => block.declare), ...blocks.flatMap((block) => block.size), - ` const buf = new Uint8Array(size);`, - ` let offset = 0;`, + allocation, + ' 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; - - // `pb_optional<>` scalar → serialise even at the zero value (proto3 explicit - // presence). Message fields already emit on `!= null`, so they stay on the - // default path; only scalars need the dedicated guard. Every `pb<>` / - // `pb_repeated<>` field has `explicitPresence === false` and so takes the - // untouched branches below — their generated code is byte-for-byte unchanged. - if (field.explicitPresence && !isMessage) { - return buildExplicitPresenceScalarBlock(field, index); - } - - 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: [] }; -} - -/** - * Encoder block for a singular scalar field marked `pb_optional<>` (proto3 - * explicit presence). Identical to the default scalar paths EXCEPT the guard - * is `!= null` instead of `!= null && !== `, so the field — and a - * `bool`'s real value — is written even when zero/false/empty. Reached only - * when `field.explicitPresence === true`, so default `pb<>` fields never run - * this code. - */ -function buildExplicitPresenceScalarBlock(field: ProtobufField, index: number): EncoderBlock { - const { name, fieldNumber, typeName, wireType } = field; - const valueVar = `_f${index}`; - const cacheVar = `_c${index}`; - const isLenDelim = typeName === 'string' || typeName === 'bytes'; - const tagLength = computeTagBytes(fieldNumber, isLenDelim ? 2 : wireType).length; - const declareVal = ` const ${valueVar} = obj.${name};`; - const present = `${valueVar} != null`; - - if (typeName === 'string') { - return { - declare: [declareVal, ` let ${cacheVar};`], - size: [ - ` if (${present}) {`, - ` ${cacheVar} = __utf8Len(${valueVar});`, - ` const _len = ${cacheVar};`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ], - write: [ - ` if (${present}) {`, - writeTag(fieldNumber, 2, ' '), - ` const _len = ${cacheVar};`, - writeVarint('_len', ' '), - ` offset = __utf8Write(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } - - if (typeName === 'bytes') { - return { - declare: [declareVal], - size: [ - ` if (${present}) {`, - ` const _len = ${valueVar}.length;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ], - write: [ - ` if (${present}) {`, - writeTag(fieldNumber, 2, ' '), - ` const _len = ${valueVar}.length;`, - writeVarint('_len', ' '), - ` buf.set(${valueVar}, offset);`, - ` offset += _len;`, - ` }`, - ], - }; - } - - if (typeName === 'bool') { - return { - declare: [declareVal], - size: [` if (${present}) size += ${tagLength + 1};`], - write: [ - ` if (${present}) {`, - writeTag(fieldNumber, 0, ' '), - ` buf[offset++] = ${valueVar} ? 1 : 0;`, - ` }`, - ], - }; - } - - if (isVarint64(typeName)) { - const bigintExpr = bigintVarintExpr(typeName, valueVar); - return { - declare: [declareVal], - size: [ - ` if (${present}) {`, - ` const _val = ${bigintExpr};`, - ` size += ${tagLength};`, - ` size += __varint64Size(_val);`, - ` }`, - ], - write: [ - ` if (${present}) {`, - ` const _val = ${bigintExpr};`, - writeTag(fieldNumber, 0, ' '), - ` offset = __writeVarint64(buf, offset, _val);`, - ` }`, - ], - }; - } - - if (typeName === 'sint_32') { - return { - declare: [declareVal], - size: [ - ` if (${present}) {`, - ` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ], - write: [ - ` if (${present}) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '), - ` }`, - ], - }; - } - - if (wireType === WireType.Varint) { - return { - declare: [declareVal], - size: [ - ` if (${present}) {`, - ` const _val = ${valueVar} >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ], - write: [ - ` if (${present}) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`${valueVar} >>> 0`, ' '), - ` }`, - ], - }; - } - - if (typeName === 'float') { - return { - declare: [declareVal], - size: [` if (${present}) size += ${tagLength + 4};`], - write: [ - ` if (${present}) {`, - writeTag(fieldNumber, 5, ' '), - ` offset = __writeFloat32(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } - - if (wireType === WireType.Bit32) { - return { - declare: [declareVal], - size: [` if (${present}) size += ${tagLength + 4};`], - write: [ - ` if (${present}) {`, - 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: [declareVal], - size: [` if (${present}) size += ${tagLength + 8};`], - write: [ - ` if (${present}) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFloat64(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } - - if (isFixed64BigInt(typeName)) { - return { - declare: [declareVal], - size: [` if (${present}) size += ${tagLength + 8};`], - write: [ - ` if (${present}) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFixed64(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } - - if (wireType === WireType.Bit64) { - return { - declare: [declareVal], - size: [` if (${present}) size += ${tagLength + 8};`], - write: [ - ` if (${present}) {`, - 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: [] }; + ' return buf;', + '}', + ].join('\n'); } diff --git a/packages/proton/src/codegen/fields.ts b/packages/proton/src/codegen/fields.ts new file mode 100644 index 00000000..df7c538d --- /dev/null +++ b/packages/proton/src/codegen/fields.ts @@ -0,0 +1,141 @@ +import { WireType, type ProtobufField } from './model.js'; +import { computeTagBytes, varintSize, writeTag, writeVarint } from './write.js'; + +export interface FieldBlock { + declare: string[]; + size: string[]; + write: string[]; +} + +export function fieldBlock(field: ProtobufField, index: number, shared: boolean): FieldBlock { + const { fieldNumber, wireType, typeName, isRepeated, isMessage } = field; + const variable = `_f${index}`; + const item = isRepeated ? `${variable}[_i]` : variable; + const cached = `_c${index}`; + const slot = isRepeated ? `${cached}[_i]` : cached; + const indent = isRepeated ? ' ' : ' '; + const tag = computeTagBytes(fieldNumber, wireType).length; + const condition = isRepeated + ? `${variable} != null && ${variable}.length > 0` + : presence(field, variable); + const start = [` if (${condition}) {`]; + const loop = isRepeated ? [` for (let _i = 0; _i < ${variable}.length; _i++) {`] : []; + const end = [...(isRepeated ? [' }'] : []), ' }']; + const declare = [` const ${variable} = obj[${JSON.stringify(field.name)}];`]; + const setup: string[] = []; + const size: string[] = []; + const write: string[] = [writeTag(fieldNumber, wireType, indent)]; + const emit = (lines: string[]) => lines.map((line) => indent + line); + + if (wireType === WireType.LengthDelim) { + if (isMessage) { + size.push( + ...emit([ + 'const _slot = sizes.length;', + 'sizes.push(0);', + `const _len = __size_${typeName}(${item}, sizes);`, + 'sizes[_slot] = _len;', + ]), + ); + write.push(...emit(['const _len = sizes[sizes[0]++];'])); + } else if (typeName === 'string') { + if (shared) { + size.push(...emit([`const _len = __utf8Len(${item});`, 'sizes.push(_len);'])); + write.push(...emit(['const _len = sizes[sizes[0]++];'])); + } else { + declare.push(` let ${cached};`); + + if (isRepeated) { + setup.push(` ${cached} = new Array(${variable}.length);`); + } + + size.push(...emit([`const _len = __utf8Len(${item});`, `${slot} = _len;`])); + write.push(...emit([`const _len = ${slot};`])); + } + } else { + size.push(...emit([`const _len = ${item}.length;`])); + write.push(...emit([`const _len = ${item}.length;`])); + } + + size.push(...emit([`size += ${tag} + _len;`]), varintSize('_len', indent)); + write.push( + writeVarint('_len', indent), + ...emit( + isMessage + ? [`offset = __write_${typeName}(${item}, buf, offset, sizes);`] + : typeName === 'string' + ? [ + `offset = _len >= 128 ? __utf8WriteLong(buf, offset, ${item}) : _len === ${item}.length ? __asciiWrite(buf, offset, ${item}) : __utf8Write(buf, offset, ${item});`, + ] + : [`buf.set(${item}, offset);`, 'offset += _len;'], + ), + ); + } else if (typeName === 'bool') { + size.push(...emit([`size += ${tag + 1};`])); + write.push(...emit([`buf[offset++] = ${item} ? 1 : 0;`])); + } else if (wireType === WireType.Varint) { + if (typeName.endsWith('_64')) { + const normalized = + typeName === 'sint_64' + ? `__zigZagEncode64(${item})` + : `BigInt.asUintN(64, ${item})`; + size.push(...emit([`size += ${tag} + __varint64Size(${normalized});`])); + write.push(...emit([`offset = __writeVarint64(buf, offset, ${normalized});`])); + } else { + // Preserve QQ's established five-byte negative int32 encoding. Decoders + // also accept the canonical sign-extended ten-byte representation. + const normalized = + typeName === 'sint_32' + ? `((${item} << 1) ^ (${item} >> 31)) >>> 0` + : `${item} >>> 0`; + size.push( + ...emit([`const _val = ${normalized};`, `size += ${tag};`]), + varintSize('_val', indent), + ); + write.push(writeVarint(normalized, indent)); + } + } else { + size.push(...emit([`size += ${tag + (wireType === WireType.Bit32 ? 4 : 8)};`])); + + if (typeName === 'float' || typeName === 'double') { + write.push( + ...emit([ + `offset = __writeFloat${typeName === 'float' ? 32 : 64}(buf, offset, ${item});`, + ]), + ); + } else if (wireType === WireType.Bit64) { + write.push(...emit([`offset = __writeFixed64(buf, offset, ${item});`])); + } else { + write.push( + ...emit([ + `const _val = ${item};`, + ...[0, 8, 16, 24].map((shift) => `buf[offset++] = (_val >>> ${shift}) & 0xff;`), + ]), + ); + } + } + + return { + declare, + size: [...start, ...setup, ...loop, ...size, ...end], + write: [...start, ...loop, ...write, ...end], + }; +} + +function presence(field: ProtobufField, value: string): string { + // TypeScript optionality controls missing decoded values, not wire presence. + if (field.explicitPresence || field.isMessage) { + return `${value} != null`; + } + + if (field.typeName === 'bool') { + return `${value} === true`; + } + + if (field.typeName === 'bytes') { + return `${value} != null && ${value}.length > 0`; + } + + const empty = field.typeName === 'string' ? '""' : field.typeName.endsWith('_64') ? '0n' : '0'; + return `${value} != null && ${value} !== ${empty}`; +} diff --git a/packages/proton/src/codegen/generator.ts b/packages/proton/src/codegen/generator.ts index e5d156c3..0aaceb66 100644 --- a/packages/proton/src/codegen/generator.ts +++ b/packages/proton/src/codegen/generator.ts @@ -1,251 +1,99 @@ -import type { MessageRegistry } from '../ast/types.js'; -import { generateEncoder } from './encoder.js'; +import { WireType, type MessageRegistry, type ProtobufMessage } from './model.js'; +import { generateEncoder, generateEncoderHelpers } from './encoder.js'; import { generateDecoder } from './decoder.js'; +import { collectDependencyClosure } from '../codegen/dependencies.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 __readVarint32(data, offset, end) { - let value = 0; - for (let i = 0; i < 5; i++) { - if (offset >= end) throw new Error('protobuf truncated uint32 varint'); - const byte = data[offset++]; - if (i === 4 && (byte & 0xf0) !== 0) throw new Error('protobuf uint32 varint overflow'); - value += (byte & 0x7f) * (2 ** (i * 7)); - if ((byte & 0x80) === 0) return [value >>> 0, offset]; - } - throw new Error('protobuf uint32 varint overflow'); -} -function __readVarint64(data, offset, end) { - let value = 0n; - for (let i = 0; i < 10; i++) { - if (offset >= end) throw new Error('protobuf truncated uint64 varint'); - const byte = data[offset++]; - if (i === 9 && byte > 1) throw new Error('protobuf uint64 varint overflow'); - value |= BigInt(byte & 0x7f) << BigInt(i * 7); - if ((byte & 0x80) === 0) return [value, offset]; - } - throw new Error('protobuf uint64 varint overflow'); -} -function __readVarint32Value(data, offset, end) { - const [value, next] = __readVarint64(data, offset, end); - // QQ-compatible protobuf runtimes consume a complete, well-formed uint32 - // value varint and retain its low 32 bits. Keep tags and lengths on - // __readVarint32 so malformed framing still fails before it affects bounds. - return [Number(BigInt.asUintN(32, value)), next]; -} -function __skipVarint(data, offset, end) { - for (let i = 0; i < 10; i++) { - if (offset >= end) throw new Error('protobuf truncated varint'); - const byte = data[offset++]; - if (i === 9 && byte > 1) throw new Error('protobuf varint overflow'); - if ((byte & 0x80) === 0) return offset; - } - throw new Error('protobuf varint overflow'); -} -function __checkedEnd(offset, length, end) { - if (length > end - offset) throw new Error('protobuf length-delimited field exceeds parent bounds'); - return offset + length; -} -function __skipUnknownField(data, offset, end, wireType, fieldNumber, depth = 0) { - if (depth > 64) throw new Error('protobuf group nesting exceeds 64'); - if (wireType === 0) return __skipVarint(data, offset, end); - if (wireType === 1) { - if (end - offset < 8) throw new Error('protobuf truncated fixed64 field'); - return offset + 8; - } - if (wireType === 2) { - const [length, next] = __readVarint32(data, offset, end); - return __checkedEnd(next, length, end); - } - if (wireType === 3) { - while (offset < end) { - const [tag, next] = __readVarint32(data, offset, end); - offset = next; - const nestedField = tag >>> 3; - const nestedWire = tag & 0x7; - if (nestedField === 0) throw new Error('protobuf field number 0 is invalid'); - if (nestedWire === 4) { - if (nestedField !== fieldNumber) throw new Error('protobuf mismatched end-group tag'); - return offset; - } - offset = __skipUnknownField(data, offset, end, nestedWire, nestedField, depth + 1); - } - throw new Error('protobuf unterminated group'); - } - if (wireType === 4) throw new Error('protobuf unexpected end-group tag'); - if (wireType === 5) { - if (end - offset < 4) throw new Error('protobuf truncated fixed32 field'); - return offset + 4; - } - throw new Error('protobuf invalid wire type ' + wireType); -} -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); -}`; +import { helpers } from './helpers.js'; /** * Generate fully self-contained encode/decode source code. * No runtime imports needed — all wire-format logic is inlined. */ -export function generateCode(registry: MessageRegistry): string { +export interface CodegenOptions { + encodeRoots?: Iterable; + decodeRoots?: Iterable; +} + +export function generateCode(registry: MessageRegistry, options: CodegenOptions = {}): string { if (registry.size === 0) { return ''; } - const parts: string[] = [CODEGEN_PREAMBLE]; + const encodeRoots = new Set(options.encodeRoots ?? registry.keys()); + const decodeNames = collectDependencyClosure(registry, options.decodeRoots ?? registry.keys()); + const nestedRoots = [...encodeRoots].filter((name) => + registry.get(name)?.fields.some((field) => field.isMessage), + ); + const encoderHelpers = collectDependencyClosure(registry, nestedRoots); + const bounds = new Map(); - for (const msg of registry.values()) { - parts.push(generateEncoder(msg, registry)); - parts.push(generateDecoder(msg, registry)); + function sizeBound(message: ProtobufMessage): number { + const cached = bounds.get(message.name); + + if (cached !== undefined) { + return cached; + } + + bounds.set(message.name, Infinity); + let size = 0; + + for (const field of message.fields) { + if (field.isRepeated || (!field.isMessage && field.wireType === WireType.LengthDelim)) { + return Infinity; + } + + // A scalar needs at most 5 tag bytes and 10 payload bytes. + size += 16; + + if (field.isMessage) { + size += sizeBound(registry.get(field.typeName)!); + } + + if (size > 64) { + return Infinity; + } + } + + bounds.set(message.name, size); + return size; } - return parts.join('\n'); + const parts: string[] = []; + + for (const msg of registry.values()) { + if (encodeRoots.has(msg.name)) { + parts.push(generateEncoder(msg, sizeBound(msg) > 64)); + } + + if (encoderHelpers.has(msg.name)) { + parts.push(generateEncoderHelpers(msg)); + } + + if (decodeNames.has(msg.name)) { + parts.push(generateDecoder(msg)); + } + } + + const body = parts.join('\n'); + const selected = new Set(); + + function include(text: string): void { + for (const match of text.matchAll(/\b__\w+/g)) { + const name = match[0]; + + if (selected.has(name) || !helpers.has(name)) { + continue; + } + + selected.add(name); + include(helpers.get(name)!); + } + } + + include(body); + return [...helpers] + .filter(([name]) => selected.has(name)) + .map(([, text]) => text) + .concat(body) + .join('\n'); } diff --git a/packages/proton/src/codegen/helpers.ts b/packages/proton/src/codegen/helpers.ts new file mode 100644 index 00000000..824172ef --- /dev/null +++ b/packages/proton/src/codegen/helpers.ts @@ -0,0 +1,98 @@ +import { utf8 } from './utf8.js'; +import { unknownFields } from './unknown.js'; +import { buffers } from './buffer.js'; + +const CODEGEN_PREAMBLE = `${utf8} +${buffers} +${unknownFields} +const __scratch = new DataView(new ArrayBuffer(8)); +function __varint64Size(value) { + if (value < 0x80n) return 1; + const hi = Number(value >> 32n); + const bits = hi ? 64 - Math.clz32(hi) : 32 - Math.clz32(Number(value)); + return ((bits + 6) / 7) | 0; +} +function __writeVarint64(buf, offset, value) { + let lo = Number(value & 0xffffffffn) >>> 0; + let hi = Number(value >> 32n) >>> 0; + while (hi || lo > 0x7f) { + buf[offset++] = (lo & 0x7f) | 0x80; + lo = ((lo >>> 7) | (hi << 25)) >>> 0; + hi >>>= 7; + } + buf[offset++] = lo; + 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); + const lo = Number(value & 0xffffffffn), hi = Number(value >> 32n); + buf[offset++] = lo; + buf[offset++] = lo >>> 8; + buf[offset++] = lo >>> 16; + buf[offset++] = lo >>> 24; + buf[offset++] = hi; + buf[offset++] = hi >>> 8; + buf[offset++] = hi >>> 16; + buf[offset++] = hi >>> 24; + return offset; +} +function __readFixed64(data, offset) { + const lo = (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0; + const hi = (data[offset + 4] | (data[offset + 5] << 8) | (data[offset + 6] << 16) | (data[offset + 7] << 24)) >>> 0; + return BigInt(lo) | (BigInt(hi) << 32n); +}`; + +export const helpers = new Map(); +const helperStarts = [...CODEGEN_PREAMBLE.matchAll(/^(?:function|const|let) (__\w+)/gm)]; + +for (let i = 0; i < helperStarts.length; i++) { + helpers.set( + helperStarts[i][1], + CODEGEN_PREAMBLE.slice(helperStarts[i].index, helperStarts[i + 1]?.index).trim(), + ); +} diff --git a/packages/proton/src/codegen/model.ts b/packages/proton/src/codegen/model.ts new file mode 100644 index 00000000..4acee9a2 --- /dev/null +++ b/packages/proton/src/codegen/model.ts @@ -0,0 +1,42 @@ +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; + explicitPresence?: boolean; +} + +export interface ProtobufMessage { + name: string; + fields: ProtobufField[]; +} + +export type MessageRegistry = Map; + +export const PRIMITIVE_TYPE_MAP: Record = { + uint_32: { wireType: WireType.Varint, defaultValue: '0' }, + int_32: { wireType: WireType.Varint, defaultValue: '0' }, + uint_64: { wireType: WireType.Varint, defaultValue: '0n' }, + int_64: { wireType: WireType.Varint, defaultValue: '0n' }, + sint_32: { wireType: WireType.Varint, defaultValue: '0' }, + sint_64: { wireType: WireType.Varint, defaultValue: '0n' }, + 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: '0n' }, + sfixed_32: { wireType: WireType.Bit32, defaultValue: '0' }, + sfixed_64: { wireType: WireType.Bit64, defaultValue: '0n' }, +}; diff --git a/packages/proton/src/codegen/unknown.ts b/packages/proton/src/codegen/unknown.ts new file mode 100644 index 00000000..f9dad9bd --- /dev/null +++ b/packages/proton/src/codegen/unknown.ts @@ -0,0 +1,60 @@ +// Bound unknown fields and groups to the current message frame. +export const unknownFields = ` +function __readVarint32(data, offset, end) { + let value = 0; + for (let i = 0; i < 5; i++) { + if (offset >= end) throw new Error('protobuf truncated uint32 varint'); + const byte = data[offset++]; + if (i === 4 && (byte & 0xf0) !== 0) throw new Error('protobuf uint32 varint overflow'); + value += (byte & 0x7f) * (2 ** (i * 7)); + if ((byte & 0x80) === 0) return [value >>> 0, offset]; + } + throw new Error('protobuf uint32 varint overflow'); +} +function __skipVarint(data, offset, end) { + for (let i = 0; i < 10; i++) { + if (offset >= end) throw new Error('protobuf truncated varint'); + const byte = data[offset++]; + if (i === 9 && byte > 1) throw new Error('protobuf varint overflow'); + if ((byte & 0x80) === 0) return offset; + } + throw new Error('protobuf varint overflow'); +} +function __checkedEnd(offset, length, end) { + if (length > end - offset) throw new Error('protobuf length-delimited field exceeds parent bounds'); + return offset + length; +} +function __skipUnknownField(data, offset, end, wireType, fieldNumber, depth = 0) { + if (depth > 64) throw new Error('protobuf group nesting exceeds 64'); + if (wireType === 0) return __skipVarint(data, offset, end); + if (wireType === 1) { + if (end - offset < 8) throw new Error('protobuf truncated fixed64 field'); + return offset + 8; + } + if (wireType === 2) { + const [length, next] = __readVarint32(data, offset, end); + return __checkedEnd(next, length, end); + } + if (wireType === 3) { + while (offset < end) { + const [tag, next] = __readVarint32(data, offset, end); + offset = next; + const nestedField = tag >>> 3; + const nestedWire = tag & 0x7; + if (nestedField === 0) throw new Error('protobuf field number 0 is invalid'); + if (nestedWire === 4) { + if (nestedField !== fieldNumber) throw new Error('protobuf mismatched end-group tag'); + return offset; + } + offset = __skipUnknownField(data, offset, end, nestedWire, nestedField, depth + 1); + } + throw new Error('protobuf unterminated group'); + } + if (wireType === 4) throw new Error('protobuf unexpected end-group tag'); + if (wireType === 5) { + if (end - offset < 4) throw new Error('protobuf truncated fixed32 field'); + return offset + 4; + } + throw new Error('protobuf invalid wire type ' + wireType); +} +`; diff --git a/packages/proton/src/codegen/utf8.ts b/packages/proton/src/codegen/utf8.ts new file mode 100644 index 00000000..63cc1133 --- /dev/null +++ b/packages/proton/src/codegen/utf8.ts @@ -0,0 +1,159 @@ +export const utf8 = `const __td = new TextDecoder(); +const __te = new TextEncoder(); +const __nonAscii = /[^\\x00-\\x7f]/; +let __utf8Scratch; +const __tdStrict = new TextDecoder('utf-8', { fatal: true }); +function __utf8LenLong(value) { + const buffer = __utf8Scratch ??= new Uint8Array(4096); + let length = 0; + for (;;) { + const result = __te.encodeInto(value, buffer); + length += result.written; + if (result.read === value.length) return length; + value = value.slice(result.read); + } +} +function __utf8Len(value) { + if (value.length >= 32) return __utf8LenLong(value); + if (value.length >= 8 && value.charCodeAt(0) < 0x80 && !__nonAscii.test(value)) return value.length; + 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 __utf8WriteLong(buf, offset, value) { + return offset + __te.encodeInto(value, buf.subarray(offset)).written; +} +function __asciiWrite(buf, offset, value) { + let i = 0; + for (; i + 7 < value.length; i += 8) { + buf[offset++] = value.charCodeAt(i); + buf[offset++] = value.charCodeAt(i + 1); + buf[offset++] = value.charCodeAt(i + 2); + buf[offset++] = value.charCodeAt(i + 3); + buf[offset++] = value.charCodeAt(i + 4); + buf[offset++] = value.charCodeAt(i + 5); + buf[offset++] = value.charCodeAt(i + 6); + buf[offset++] = value.charCodeAt(i + 7); + } + for (; i < value.length; i++) buf[offset++] = value.charCodeAt(i); + return offset; +} +function __utf8ReadLong(data, start, end) { + const bytes = data.subarray(start, end); + if (end - start < 128) return __td.decode(bytes); + try { + return __tdStrict.decode(bytes); + } catch { + return __td.decode(bytes); + } +} +function __utf8Read(data, start, end) { + let value = '', offset = start; + while (offset + 7 < end) { + const a = data[offset], b = data[offset + 1], c = data[offset + 2], d = data[offset + 3]; + const e = data[offset + 4], f = data[offset + 5], g = data[offset + 6], h = data[offset + 7]; + if ((a | b | c | d | e | f | g | h) & 0x80) break; + value += String.fromCharCode(a, b, c, d, e, f, g, h); + offset += 8; + } + if (offset + 3 < end) { + const a = data[offset], b = data[offset + 1], c = data[offset + 2], d = data[offset + 3]; + if (!((a | b | c | d) & 0x80)) { + value += String.fromCharCode(a, b, c, d); + offset += 4; + } + } + while (offset < end) { + const a = data[offset++]; + if (a < 0x80) { + value += String.fromCharCode(a); + } else if (a >= 0xc2 && a < 0xe0 && offset < end) { + const b = data[offset++]; + if ((b & 0xc0) !== 0x80) return __td.decode(data.subarray(start, end)); + value += String.fromCharCode(((a & 0x1f) << 6) | (b & 0x3f)); + } else if (a >= 0xe0 && a < 0xf0 && offset + 1 < end) { + const b = data[offset++], c = data[offset++]; + if ((b & 0xc0) !== 0x80 || (c & 0xc0) !== 0x80 || + (a === 0xe0 && b < 0xa0) || (a === 0xed && b >= 0xa0)) { + return __td.decode(data.subarray(start, end)); + } + const code = ((a & 0x0f) << 12) | ((b & 0x3f) << 6) | (c & 0x3f); + // Match TextDecoder's handling of a leading BOM. + if (code !== 0xfeff || offset !== start + 3) value += String.fromCharCode(code); + } else if (a >= 0xf0 && a < 0xf5 && offset + 2 < end) { + const b = data[offset++], c = data[offset++], d = data[offset++]; + if ((b & 0xc0) !== 0x80 || (c & 0xc0) !== 0x80 || (d & 0xc0) !== 0x80 || + (a === 0xf0 && b < 0x90) || (a === 0xf4 && b >= 0x90)) { + return __td.decode(data.subarray(start, end)); + } + const code = (((a & 7) << 18) | ((b & 0x3f) << 12) | ((c & 0x3f) << 6) | (d & 0x3f)) - 0x10000; + value += String.fromCharCode(0xd800 | (code >>> 10), 0xdc00 | (code & 0x3ff)); + } else { + return __td.decode(data.subarray(start, end)); + } + } + return value; +} +`; diff --git a/packages/proton/src/codegen/write.ts b/packages/proton/src/codegen/write.ts new file mode 100644 index 00000000..4b23f1ea --- /dev/null +++ b/packages/proton/src/codegen/write.ts @@ -0,0 +1,56 @@ +export 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; +} + +export function writeTag(fieldNumber: number, wireType: number, ind: string): string { + return computeTagBytes(fieldNumber, wireType) + .map((byte) => `${ind}buf[offset++] = ${byte};`) + .join('\n'); +} + +export function varintSize(varName: string, ind: string, signed = false): string { + const negativeSize = signed ? `${varName} < 0 ? 10 : ` : ''; + return `${ind}size += ${negativeSize}${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`; +} + +export function writeVarint(expr: string, ind: string, signed = false): string { + return [ + `${ind}let _v = ${expr};`, + ...(signed + ? [ + `${ind}if (_v < 0) {`, + `${ind} offset = __writeVarint64(buf, offset, BigInt.asUintN(64, BigInt(_v)));`, + ] + : []), + `${ind}${signed ? '} else if' : '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'); +} diff --git a/packages/proton/src/compiler/analysis.ts b/packages/proton/src/compiler/analysis.ts new file mode 100644 index 00000000..b4fb8ae6 --- /dev/null +++ b/packages/proton/src/compiler/analysis.ts @@ -0,0 +1,559 @@ +import { unique } from './edits.js'; +import { Callbacks, mentionsGeneric } from './callbacks.js'; +import ts from 'typescript'; +import { packageName } from '../package.js'; +import { SourceContext, fail, runtimeImportName } from '../source/context.js'; +import { SchemaResolver } from '../schema/resolver.js'; +import type { TypeEnvironment, TypeValue } from '../schema/types.js'; +import { + callable, + constructorOf, + type Owner, + type Plan, + type Requirement, + type Site, +} from './model.js'; +import { CallTargets } from './targets.js'; + +export class CallAnalysis { + readonly plans = new Map(); + readonly sites = new Map(); + readonly targets: CallTargets; + readonly callbacks = new Callbacks(this); + private readonly runtimePlans = new Map(); + + constructor( + readonly context: SourceContext, + readonly resolver: SchemaResolver, + ) { + this.targets = new CallTargets(context, resolver, this); + } + + runtimePlan(fn: Requirement['fn']): Plan { + let plan = this.runtimePlans.get(fn); + + if (!plan) { + const source = ts.createSourceFile( + `${fn}.internal.ts`, + `function ${fn}(value: T) {}`, + ts.ScriptTarget.Latest, + true, + ); + plan = this.plan(source.statements[0] as ts.FunctionDeclaration); + plan.runtime = fn; + const type = plan.env.get('T')!; + const requirement = { key: `${fn}:${type.key}`, fn, type, node: plan.node }; + plan.requirements.set(requirement.key, requirement); + this.runtimePlans.set(fn, plan); + } + + return plan; + } + + scan(source: ts.SourceFile): void { + if (this.sites.has(source)) { + return; + } + + const sites: Site[] = []; + this.sites.set(source, sites); + + if (source.isDeclarationFile) { + return; + } + + for (const statement of source.statements) { + if ( + (!ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement)) || + !statement.moduleSpecifier || + !ts.isStringLiteral(statement.moduleSpecifier) + ) { + continue; + } + + const imported = this.context.module(statement.moduleSpecifier.text, source); + + if ( + imported && + !imported.isDeclarationFile && + !imported.fileName.includes('/node_modules/') + ) { + this.scan(imported); + } + } + + let env: TypeEnvironment = new Map(); + let owner: Plan | undefined; + + const visit = (node: ts.Node): void => { + this.callbacks.record(node); + + if ( + ts.isTypeNode(node) || + ts.isInterfaceDeclaration(node) || + ts.isImportDeclaration(node) || + ts.isExportDeclaration(node) + ) { + return; + } + + const outerEnv = env; + const outerOwner = owner; + + if (ts.isClassDeclaration(node)) { + this.plan(node); + } + + if ((callable(node) || ts.isClassDeclaration(node)) && node.typeParameters?.length) { + owner = this.plan(node); + env = owner.env; + } + + if (ts.isCallExpression(node) || ts.isNewExpression(node)) { + let fn = ts.isCallExpression(node) + ? this.protobufFunction(node.expression, source) + : undefined; + const target = fn ? undefined : this.targets.target(node.expression, source, env); + + if (!fn && ts.isCallExpression(node) && target) { + fn = this.plan(target.node).runtime; + } + + if (fn) { + const typeNode = + node.typeArguments?.[0] ?? + (fn === 'protobuf_encode' && node.arguments?.[0] + ? this.targets.infer(node.arguments[0], source) + : undefined); + + if (!typeNode) { + fail( + node, + 'Cannot infer protobuf schema; supply an explicit type argument.', + ); + } + + const type = this.resolver.type(typeNode, typeNode.getSourceFile(), env); + const direct: Requirement = { key: `${fn}:${type.key}`, fn, type, node }; + + if (type.dynamic && owner) { + owner.requirements.set(direct.key, direct); + } + + sites.push({ node, owner, direct }); + } else { + if (target) { + const plan = this.plan(target.node); + sites.push({ + node, + owner, + target: plan, + bindings: target.bindings, + typeArgs: node.typeArguments, + env, + }); + this.scan(target.node.getSourceFile()); + } + } + } + + ts.forEachChild(node, visit); + env = outerEnv; + owner = outerOwner; + }; + + visit(source); + } + + propagate(): void { + const consumers = new Map< + Plan, + { owner?: Plan; bindings: () => Map }[] + >(); + + const connect = ( + target: Plan, + owner: Plan | undefined, + bindings: () => Map, + ) => { + const list = consumers.get(target) ?? []; + list.push({ owner, bindings }); + consumers.set(target, list); + }; + + for (const sites of this.sites.values()) { + for (const site of sites) { + if (site.target) { + connect(site.target, site.owner, () => this.bindings(site)); + } + } + } + + for (const adapter of this.callbacks.connections()) { + connect(adapter.target, adapter.owner, adapter.bindings); + } + + for (const plan of this.plans.values()) { + if (plan.base) { + connect(plan.base.plan, plan, () => plan.base!.bindings); + } + } + + const queue = [...this.plans.values()].flatMap((plan) => + [...plan.requirements.values()].map((requirement) => ({ plan, requirement })), + ); + + for (let index = 0; index < queue.length; index++) { + const { plan, requirement } = queue[index]; + + for (const consumer of consumers.get(plan) ?? []) { + const instantiated = this.instantiate(requirement, consumer.bindings()); + const owner = consumer.owner; + + if ( + !instantiated.type.dynamic || + !owner || + owner.requirements.has(instantiated.key) + ) { + continue; + } + + if (owner.requirements.size >= 128) { + fail(owner.node, 'Generic codec expansion does not converge.'); + } + + owner.requirements.set(instantiated.key, instantiated); + queue.push({ plan: owner, requirement: instantiated }); + } + } + } + + instantiate(req: Requirement, bindings: Map): Requirement { + const type = this.resolver.substitute(req.type, bindings); + return { ...req, type, key: `${req.fn}:${type.key}` }; + } + + bindings(site: Site, partial = false): Map { + if (!site.bound) { + const plan = site.target!; + + // Ordinary calls cannot contribute generic codec bindings. Resolving + // their parameter types would treat unrelated application data as schemas. + if (plan.env.size === 0 && !plan.base) { + site.bound = true; + return site.bindings!; + } + + if (!site.typeArgs?.length) { + this.parameters(plan.node)?.forEach((param, index) => { + const argument = site.node.arguments?.[index]; + const actual = + argument && this.targets.infer(argument, site.node.getSourceFile()); + + if ( + param.type && + actual && + mentionsGeneric(param.type, this.environment(param)) && + !this.targets.signature(param.type, plan.env) + ) { + // Matching generic containers expose their arguments directly; + // unrelated members need not be expanded as protobuf schemas. + const pattern = param.type; + + if ( + ts.isTypeReferenceNode(pattern) && + ts.isTypeReferenceNode(actual) && + pattern.typeArguments?.length && + pattern.typeArguments.length === actual.typeArguments?.length && + this.context.typeName(pattern.typeName, pattern.getSourceFile()) + ?.node && + this.context.typeName(pattern.typeName, pattern.getSourceFile()) + ?.node === + this.context.typeName(actual.typeName, actual.getSourceFile())?.node + ) { + pattern.typeArguments.forEach((type, i) => + this.unify( + this.resolver.type( + type, + type.getSourceFile(), + this.environment(param), + ), + partial + ? this.resolver.lazy( + actual.typeArguments![i], + actual.getSourceFile(), + site.env!, + ) + : this.resolver.type( + actual.typeArguments![i], + actual.getSourceFile(), + site.env, + ), + site.bindings!, + site.node, + ), + ); + return; + } + + this.unify( + this.resolver.type( + param.type, + param.getSourceFile(), + this.environment(param), + ), + this.resolver.type(actual, actual.getSourceFile(), site.env), + site.bindings!, + site.node, + ); + } + }); + const bases: NonNullable[] = []; + + for (let base = plan.base; base; base = base.plan.base) { + bases.push(base); + } + + for (const base of bases.reverse()) { + for (const [key, pattern] of base.bindings) { + const actual = site.bindings!.get(key); + + if (actual) { + this.unify(pattern, actual, site.bindings!, site.node); + } + } + } + } + + const local = this.targets.environment({ node: plan.node, bindings: site.bindings! }); + + for (let i = 0; i < (plan.node.typeParameters?.length ?? 0); i++) { + const param = plan.node.typeParameters![i]; + const key = plan.env.get(param.name.text)!.key; + const arg = site.typeArgs?.[i]; + const actual = + site.bindings!.get(key) ?? + (arg + ? partial + ? this.resolver.lazy(arg, arg.getSourceFile(), site.env!) + : this.resolver.type(arg, arg.getSourceFile(), site.env!) + : param.default + ? this.resolver.type(param.default, param.getSourceFile(), local) + : undefined); + + if (!actual && partial) { + continue; + } + + if (!actual) { + fail( + site.node, + `Cannot infer ${param.name.text}; supply an explicit generic argument.`, + ); + } + + site.bindings!.set(key, actual); + local.set(param.name.text, actual); + } + + site.bound = !partial; + } + + return site.bindings!; + } + + unify( + pattern: TypeValue, + actual: TypeValue, + bindings: Map, + node: ts.Node, + seen = new Set(), + ): void { + const key = `${pattern.key}:${actual.key}`; + + if (seen.has(key)) { + return; + } + + seen.add(key); + + if (pattern.kind === 'parameter') { + const previous = bindings.get(pattern.key); + + if (previous && previous.key !== actual.key) { + fail( + node, + `Conflicting inference for ${pattern.name}; supply an explicit type argument.`, + ); + } + + bindings.set(pattern.key, actual); + } else if ( + pattern.application && + actual.application && + pattern.application.declaration === actual.application.declaration + ) { + pattern.application.arguments.forEach((type, index) => + this.unify(type, actual.application!.arguments[index], bindings, node, seen), + ); + } else if (pattern.fields && actual.fields) { + for (const [name, property] of pattern.fields) { + const field = actual.fields.get(name); + + if (field) { + this.unify(property.type, field.type, bindings, node, seen); + } + } + } else if ( + pattern.values && + actual.values && + pattern.values.length === actual.values.length + ) { + pattern.values.forEach((type, index) => + this.unify(type, actual.values![index], bindings, node, seen), + ); + } + } + + owner(node: ts.Node): Owner | undefined { + for (let parent = node.parent; parent; parent = parent.parent) { + if ( + (callable(parent) || ts.isClassDeclaration(parent)) && + parent.typeParameters?.length + ) { + return parent; + } + } + + return; + } + + environment(node: ts.Node): TypeEnvironment { + const owners: Owner[] = []; + + for (let parent: ts.Node | undefined = node; parent; parent = parent.parent) { + if ( + (callable(parent) || ts.isClassDeclaration(parent)) && + parent.typeParameters?.length + ) { + owners.push(parent); + } + } + + const env: TypeEnvironment = new Map(); + + for (const owner of owners.reverse()) { + for (const param of owner.typeParameters!) { + env.set(param.name.text, this.resolver.parameter(param.name.text, owner)); + } + } + + return env; + } + + plan(node: Owner): Plan { + let plan = this.plans.get(node); + + if (!plan) { + plan = { node, env: this.environment(node), requirements: new Map(), names: new Map() }; + this.plans.set(node, plan); + + if (ts.isClassDeclaration(node)) { + const heritage = node.heritageClauses?.find( + (clause) => clause.token === ts.SyntaxKind.ExtendsKeyword, + )?.types[0]; + + if (heritage) { + const target = this.targets.target( + heritage.expression, + node.getSourceFile(), + plan.env, + ); + + if (target && ts.isClassDeclaration(target.node)) { + const base = this.plan(target.node); + + for ( + let ancestor: Plan | undefined = base; + ancestor; + ancestor = ancestor.base?.plan + ) { + if (ancestor === plan) { + fail(heritage, 'Circular class inheritance.'); + } + } + + const args = this.resolver.arguments( + target.node.typeParameters, + heritage.typeArguments, + node.getSourceFile(), + plan.env, + target.node, + ); + const bindings = new Map(); + + for (const [name, type] of args) { + bindings.set(base.env.get(name)!.key, type); + } + + plan.base = { plan: base, bindings }; + this.scan(target.node.getSourceFile()); + } + } + } + } + + return plan; + } + + protobufFunction( + expression: ts.Expression, + source: ts.SourceFile, + ): Requirement['fn'] | undefined { + let name: string | undefined; + + if (ts.isIdentifier(expression)) { + const declaration = this.context.lookup(expression.text, expression, source); + name = declaration ? runtimeImportName(declaration.node) : undefined; + } else if ( + ts.isPropertyAccessExpression(expression) && + ts.isIdentifier(expression.expression) + ) { + const declaration = this.context.lookup(expression.expression.text, expression, source); + + if ( + declaration && + ts.isNamespaceImport(declaration.node) && + (declaration.node.parent.parent.moduleSpecifier as ts.StringLiteral).text === + packageName + ) { + name = expression.name.text; + } + } + + return name === 'protobuf_encode' || name === 'protobuf_decode' ? name : undefined; + } + + parameters(node: Owner): readonly ts.ParameterDeclaration[] | undefined { + const parameters = ts.isClassDeclaration(node) + ? (constructorOf(node)?.parameters ?? + (this.plan(node).base ? this.parameters(this.plan(node).base!.plan.node) : undefined)) + : node.parameters; + return parameters?.filter( + (param) => !ts.isIdentifier(param.name) || param.name.text !== 'this', + ); + } + parameterName(plan: Plan, key: string): string { + let name = plan.names.get(key); + + if (!name) { + name = unique( + plan.node.getSourceFile(), + `__pb_codec_${plan.node.pos}_${plan.names.size}`.replace(/-/g, '_'), + ); + plan.names.set(key, name); + } + + return name; + } +} diff --git a/packages/proton/src/compiler/callback-types.ts b/packages/proton/src/compiler/callback-types.ts new file mode 100644 index 00000000..3f4e3ffb --- /dev/null +++ b/packages/proton/src/compiler/callback-types.ts @@ -0,0 +1,169 @@ +import ts from 'typescript'; +import { fail } from '../source/context.js'; +import type { TypeEnvironment } from '../schema/types.js'; +import { memberType, type Signature } from './signatures.js'; +import { callable } from './model.js'; +import type { CallAnalysis } from './analysis.js'; + +interface Expected { + type: ts.TypeNode; + env: TypeEnvironment; +} + +export class CallbackTypes { + constructor(private readonly graph: CallAnalysis) {} + + context( + node: ts.Expression, + env: TypeEnvironment, + ): { signature?: Signature; types?: ts.TypeNode[] } | undefined { + const expected = this.expected(node, env); + const signature = expected && this.graph.targets.signature(expected.type, expected.env); + + if (signature) { + return { signature }; + } + + const parent = node.parent; + + if ( + ts.isCallExpression(parent) && + parent.arguments[0] === node && + ts.isPropertyAccessExpression(parent.expression) && + ['map', 'forEach', 'flatMap', 'filter', 'find', 'some', 'every'].includes( + parent.expression.name.text, + ) + ) { + const array = this.graph.targets.infer( + parent.expression.expression, + node.getSourceFile(), + ); + const element = array && this.element(array); + + if (element) { + return { types: [element] }; + } + } + + return; + } + + private expected(node: ts.Node, env: TypeEnvironment): Expected | undefined { + const graph = this.graph; + let child = node; + + if ( + ts.isPropertyAccessExpression(child.parent) && + child.parent.name.text === 'bind' && + ts.isCallExpression(child.parent.parent) + ) { + child = child.parent.parent; + } + + while ( + ts.isParenthesizedExpression(child.parent) || + ts.isConditionalExpression(child.parent) + ) { + child = child.parent; + } + + const parent = child.parent; + + if ( + (ts.isVariableDeclaration(parent) || + ts.isParameter(parent) || + ts.isPropertyDeclaration(parent) || + ts.isAsExpression(parent) || + ts.isSatisfiesExpression(parent)) && + parent.type + ) { + return { type: parent.type, env }; + } + + if ( + ts.isBinaryExpression(parent) && + parent.right === child && + parent.operatorToken.kind === ts.SyntaxKind.EqualsToken + ) { + const type = graph.targets.infer(parent.left, node.getSourceFile()); + + if (type) { + return { type, env }; + } + } + + if ( + (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && + ts.isObjectLiteralExpression(parent.parent) + ) { + const object = this.expected(parent.parent, env); + return ( + object && + memberType( + object.type, + parent.name.getText().replace(/^['"]|['"]$/g, ''), + object.env, + graph.context, + graph.resolver, + ) + ); + } + + if (ts.isArrayLiteralExpression(parent)) { + const array = this.expected(parent, env); + const type = array && this.element(array.type); + return type && array ? { type, env: array.env } : undefined; + } + + if (ts.isReturnStatement(parent) || (ts.isArrowFunction(parent) && parent.body === child)) { + for (let fn: ts.Node | undefined = parent; fn; fn = fn.parent) { + if (callable(fn)) { + return fn.type ? { type: fn.type, env } : undefined; + } + } + } + + if (ts.isCallExpression(parent)) { + const index = parent.arguments.indexOf(child as ts.Expression); + const site = graph.sites + .get(node.getSourceFile()) + ?.find((site) => site.node === parent); + const parameter = site?.target && graph.parameters(site.target.node)?.[index]; + + if (site?.target && parameter?.type) { + const bindings = graph.bindings(site, true); + const local = new Map( + [...site.target.env].map(([name, value]) => [ + name, + graph.resolver.substitute(value, bindings), + ]), + ); + const signature = graph.targets.signature(parameter.type, local); + + if ( + signature?.node.typeParameters?.length && + (site.target.node.getSourceFile().isDeclarationFile || + (ts.isFunctionDeclaration(site.target.node) && !site.target.node.body)) + ) { + fail( + node, + 'Polymorphic callbacks require the receiving implementation to participate in the build.', + ); + } + + return { type: parameter.type, env: local }; + } + } + + return; + } + + private element(type: ts.TypeNode): ts.TypeNode | undefined { + return ts.isArrayTypeNode(type) + ? type.elementType + : ts.isTypeReferenceNode(type) && + ['Array', 'ReadonlyArray'].includes(type.typeName.getText()) + ? type.typeArguments?.[0] + : undefined; + } +} diff --git a/packages/proton/src/compiler/callbacks.ts b/packages/proton/src/compiler/callbacks.ts new file mode 100644 index 00000000..329f687d --- /dev/null +++ b/packages/proton/src/compiler/callbacks.ts @@ -0,0 +1,323 @@ +import ts from 'typescript'; +import { fail } from '../source/context.js'; +import type { TypeEnvironment, TypeValue } from '../schema/types.js'; +import type { CallAnalysis } from './analysis.js'; +import { callable, type Plan, type Requirement, type Edit } from './model.js'; +import { codecIndex, unique } from './edits.js'; +import { CallbackTypes } from './callback-types.js'; + +interface Adapter { + node: ts.Expression; + target: Plan; + bindings: Map; + owner?: Plan; + signature?: Plan; +} + +export class Callbacks { + readonly adapters = new Map(); + private readonly candidates: ts.Expression[] = []; + private cursor = 0; + private readonly types: CallbackTypes; + + constructor(private readonly graph: CallAnalysis) { + this.types = new CallbackTypes(graph); + } + + record(node: ts.Node): void { + switch (node.kind) { + case ts.SyntaxKind.ExpressionWithTypeArguments: + if (!ts.isHeritageClause(node.parent)) { + this.candidates.push(node as ts.ExpressionWithTypeArguments); + } + + break; + case ts.SyntaxKind.VariableDeclaration: + case ts.SyntaxKind.Parameter: + case ts.SyntaxKind.PropertyDeclaration: + case ts.SyntaxKind.PropertyAssignment: + this.candidate((node as ts.VariableDeclaration).initializer); + break; + case ts.SyntaxKind.CallExpression: + for (const argument of (node as ts.CallExpression).arguments) { + this.candidate(argument); + } + + break; + case ts.SyntaxKind.ArrayLiteralExpression: + for (const element of (node as ts.ArrayLiteralExpression).elements) { + this.candidate(element); + } + + break; + case ts.SyntaxKind.ShorthandPropertyAssignment: + this.candidate((node as ts.ShorthandPropertyAssignment).name); + break; + case ts.SyntaxKind.ReturnStatement: + case ts.SyntaxKind.ParenthesizedExpression: + case ts.SyntaxKind.AsExpression: + case ts.SyntaxKind.SatisfiesExpression: + this.candidate((node as ts.ReturnStatement).expression); + break; + + case ts.SyntaxKind.ConditionalExpression: { + const expression = node as ts.ConditionalExpression; + this.candidate(expression.whenTrue); + this.candidate(expression.whenFalse); + break; + } + + case ts.SyntaxKind.BinaryExpression: { + const expression = node as ts.BinaryExpression; + + if (expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) { + this.candidate(expression.right); + } + + break; + } + + case ts.SyntaxKind.PropertyAccessExpression: { + const expression = node as ts.PropertyAccessExpression; + + if (expression.name.text === 'bind') { + this.candidate(expression.expression); + } + } + } + } + + private candidate(node: ts.Expression | undefined): void { + if ( + node && + (ts.isIdentifier(node) || + ts.isPropertyAccessExpression(node) || + ts.isElementAccessExpression(node) || + callable(node)) + ) { + this.candidates.push(node); + } + } + + collect(): void { + while (this.cursor < this.candidates.length) { + this.add(this.candidates[this.cursor++]); + } + } + + private add(node: ts.Expression): void { + const graph = this.graph; + const env = graph.environment(node); + const explicit = ts.isExpressionWithTypeArguments(node) ? node : undefined; + const target = graph.targets.target( + explicit?.expression ?? node, + node.getSourceFile(), + env, + ); + + if (!target || ts.isClassDeclaration(target.node)) { + return; + } + + const plan = graph.plan(target.node); + + if (!plan.node.typeParameters?.length) { + return; + } + + graph.scan(plan.node.getSourceFile()); + const ownerNode = graph.owner(node); + const adapter: Adapter = { + node, + target: plan, + bindings: new Map(target.bindings), + owner: ownerNode ? graph.plan(ownerNode) : undefined, + }; + + if (explicit) { + const args = graph.resolver.arguments( + plan.node.typeParameters, + explicit.typeArguments, + node.getSourceFile(), + env, + plan.node, + ); + + for (const [name, type] of args) { + adapter.bindings.set(plan.env.get(name)!.key, type); + } + } else { + const context = this.types.context(node, env); + + if (!context) { + return; + } + + const signature = context.signature; + const local = new Map(signature?.env ?? env); + + if (signature?.node.typeParameters?.length) { + adapter.signature = graph.plan(signature.node); + + for (const param of signature.node.typeParameters) { + local.set(param.name.text, adapter.signature.env.get(param.name.text)!); + } + } + + const parameters = graph.parameters(plan.node) ?? []; + const actual = + context.types ?? graph.parameters(signature!.node)!.map((param) => param.type); + parameters.forEach((param, index) => { + if ( + param.type && + actual[index] && + plan.runtime !== 'protobuf_decode' && + mentionsGeneric(param.type, plan.env) + ) { + graph.unify( + graph.resolver.type(param.type, param.getSourceFile(), plan.env), + graph.resolver.type(actual[index]!, actual[index]!.getSourceFile(), local), + adapter.bindings, + node, + ); + } + }); + + if (plan.runtime === 'protobuf_decode' && signature) { + adapter.bindings.set( + plan.env.get('T')!.key, + graph.resolver.type( + signature.node.type!, + signature.node.getSourceFile(), + local, + ), + ); + } + + for (const parameter of plan.node.typeParameters ?? []) { + const key = plan.env.get(parameter.name.text)!.key; + + if (!adapter.bindings.has(key) && parameter.default) { + adapter.bindings.set( + key, + graph.resolver.type(parameter.default, parameter.getSourceFile(), env), + ); + } + } + } + + this.adapters.set(node, adapter); + } + + connections(): { target: Plan; owner?: Plan; bindings: () => Map }[] { + return [...this.adapters.values()].map((adapter) => ({ + target: adapter.target, + owner: adapter.signature ?? adapter.owner, + bindings: () => adapter.bindings, + })); + } + + emit( + source: ts.SourceFile, + reference: (req: Requirement, owner?: Plan) => string, + edits: Edit[], + ): void { + for (const adapter of this.adapters.values()) { + if (adapter.node.getSourceFile() !== source || !adapter.target.requirements.size) { + continue; + } + + const { target, signature, node } = adapter; + + if (target === signature) { + continue; + } + + const requirements = [...target.requirements.values()].map((req) => + this.graph.instantiate(req, adapter.bindings), + ); + + for (const req of requirements) { + if ( + [...target.env.values()].some( + (type) => type.dynamic && req.type.key === type.key, + ) + ) { + fail( + node, + 'Cannot infer callback schema; annotate its parameter type or supply type arguments.', + ); + } + } + + const codecs = requirements.map((req) => reference(req, signature ?? adapter.owner)); + + if (target.runtime && !signature) { + const text = + target.runtime === 'protobuf_decode' + ? `(bytes => ${codecs[0]}(bytes))` + : codecs[0]; + edits.push({ start: node.getStart(source), end: node.end, text }); + continue; + } + + const params = this.graph.parameters(target.node) ?? []; + const count = params.findIndex((param) => !!param.dotDotDotToken); + const arity = count < 0 ? params.length : count; + const signatureParams = signature && this.graph.parameters(signature.node)!; + const signatureRest = + signatureParams?.findIndex((param) => !!param.dotDotDotToken) ?? -1; + const incomingArity = signatureParams + ? signatureRest < 0 + ? signatureParams.length + : signatureRest + : arity; + const prefix = unique(source, '__pb_callback'); + const args = Array.from( + { length: Math.max(arity, incomingArity) }, + (_, index) => `${prefix}_${index}`, + ); + const hidden = signature + ? [...signature.requirements.keys()].map((key) => + this.graph.parameterName(signature, key), + ) + : []; + const incoming = args.map((name, index) => + params[index]?.initializer ? `${name} = undefined` : name, + ); + incoming.splice(incomingArity, 0, ...hidden.map((name) => `${name} = undefined`)); + + if (count >= 0) { + incoming.push(`...${prefix}_rest`); + } + + const index = codecIndex(params); + const forwarded = [...args.slice(0, index), ...codecs, ...args.slice(index, arity)]; + + if (count >= 0) { + forwarded.push(...args.slice(arity), `...${prefix}_rest`); + } + + const call = target.runtime + ? `${codecs[0]}(${args[0]})` + : `${prefix}_fn.call(this, ${forwarded.join(', ')})`; + const property = ts.isShorthandPropertyAssignment(node.parent) + ? node.getText(source) + ': ' + : ''; + edits.push({ + start: node.getStart(source), + end: node.getStart(source), + text: `${property}((${prefix}_fn) => function(${incoming.join(', ')}) { return ${call}; })(`, + }); + edits.push({ start: node.end, end: node.end, text: ')', order: -1 }); + } + } +} + +export function mentionsGeneric(node: ts.Node, env: TypeEnvironment): boolean { + if (ts.isIdentifier(node) && env.get(node.text)?.dynamic) { + return true; + } + + return ts.forEachChild(node, (child) => mentionsGeneric(child, env)) ?? false; +} diff --git a/packages/proton/src/compiler/compiler.ts b/packages/proton/src/compiler/compiler.ts new file mode 100644 index 00000000..784aaa70 --- /dev/null +++ b/packages/proton/src/compiler/compiler.ts @@ -0,0 +1,326 @@ +import { codecIndex, insertArguments, insertParameters, unique } from './edits.js'; +import ts from 'typescript'; +import { SourceContext, fail } from '../source/context.js'; +import { SchemaResolver } from '../schema/resolver.js'; +import { generateCode } from '../codegen/generator.js'; + +import { constructorOf, type Plan, type Requirement, type Edit } from './model.js'; +import { CallAnalysis } from './analysis.js'; +import { validateSource } from './validate.js'; + +/** Generic calls receive generated codec functions, preserving the original body and closure. */ +export class ProtobufCompiler { + readonly context = new SourceContext(); + private resolver = new SchemaResolver(this.context); + private graph = new CallAnalysis(this.context, this.resolver); + private output = new Map(); + private entries = new Set(); + + clear(): void { + this.reset(); + this.entries.clear(); + } + + private reset(): void { + this.context.clear(); + this.output.clear(); + this.resolver = new SchemaResolver(this.context); + this.graph = new CallAnalysis(this.context, this.resolver); + } + + prepare(files: Iterable): void { + for (const file of files) { + this.entries.add(file); + } + + try { + for (const file of this.entries) { + this.graph.scan(this.context.source(file)); + } + + this.graph.callbacks.collect(); + this.graph.propagate(); + } catch (error) { + this.reset(); + throw error; + } + } + + compile(code: string, file: string): string | null { + try { + return this.transform(code, file); + } catch (error) { + this.reset(); + throw error; + } + } + + private transform(code: string, file: string): string | null { + const cached = this.output.get(file); + + if (cached?.source === code) { + return cached.code; + } + + const revision = this.context.revision; + const source = this.context.source(file, code); + + if (!this.graph.sites.size && this.entries.size) { + this.prepare(this.entries); + } + + if (cached || this.context.revision !== revision) { + const entries = [...this.entries]; + this.clear(); + this.context.files.set(source.fileName, source); + this.prepare(entries); + } + + this.graph.scan(source); + this.graph.callbacks.collect(); + this.graph.propagate(); + validateSource(this.graph, source); + const edits: Edit[] = []; + const encodeRoots = new Set(); + const decodeRoots = new Set(); + + const reference = (requirement: Requirement, owner?: Plan, constructor = false): string => { + if (requirement.type.dynamic) { + if (!owner) { + fail( + requirement.node, + 'Unresolved generic codec outside a generic function or class.', + ); + } + + const name = this.graph.parameterName(owner, requirement.key); + return ts.isClassDeclaration(owner.node) && !constructor ? `this.#${name}` : name; + } + + const name = this.resolver.message(requirement.type, requirement.node); + (requirement.fn === 'protobuf_encode' ? encodeRoots : decodeRoots).add(name); + return `${requirement.fn}_${name}`; + }; + + for (const site of this.graph.sites.get(source) ?? []) { + let constructor = false; + + for ( + let parent: ts.Node | undefined = site.node; + parent && parent !== site.owner?.node; + parent = parent.parent + ) { + if (ts.isConstructorDeclaration(parent)) { + constructor = true; + break; + } + } + + if (site.direct) { + edits.push({ + start: site.node.expression.getStart(source), + end: site.node.typeArguments + ? site.node.typeArguments.end + 1 + : site.node.expression.end, + text: reference(site.direct, site.owner, constructor), + }); + } else if (site.target?.requirements.size) { + const args = [...site.target.requirements.values()].map((req) => + reference( + this.graph.instantiate(req, this.graph.bindings(site)), + site.owner, + constructor, + ), + ); + insertArguments( + site.node, + this.graph.parameters(site.target.node), + args, + edits, + source, + ); + } + } + + this.graph.callbacks.emit(source, reference, edits); + + for (const plan of this.graph.plans.values()) { + if ( + ts.isTypeNode(plan.node) || + ts.isCallSignatureDeclaration(plan.node) || + plan.node.getSourceFile() !== source || + (plan.requirements.size === 0 && !plan.base?.plan.requirements.size) + ) { + continue; + } + + const names = [...plan.requirements.keys()].map((key) => + this.graph.parameterName(plan, key), + ); + + if (ts.isClassDeclaration(plan.node)) { + const constructor = constructorOf(plan.node); + const assignments = names.map((name) => `this.#${name} = ${name};`).join('\n'); + + if (names.length) { + edits.push({ + start: plan.node.members.pos, + end: plan.node.members.pos, + text: '\n' + names.map((name) => `#${name};`).join('\n') + '\n', + }); + } + + if (constructor?.body) { + if (names.length) { + insertParameters(constructor.parameters, names, edits, source); + } + + const superStatement = constructor.body.statements.find( + (statement) => + ts.isExpressionStatement(statement) && + ts.isCallExpression(statement.expression) && + statement.expression.expression.kind === ts.SyntaxKind.SuperKeyword, + ); + + if (plan.base && !superStatement) { + fail( + constructor, + 'Generic derived constructors require a top-level super(...) call.', + ); + } + + const position = superStatement?.end ?? constructor.body.getStart(source) + 1; + edits.push({ start: position, end: position, text: assignments }); + } else if (plan.base) { + const inherited = this.graph.parameters(plan.base.plan.node); + const count = codecIndex(inherited); + const argsName = unique(source, '__pb_constructor_args'); + const locals = names + .map((name, i) => `const ${name} = ${argsName}[${count + i}];`) + .join('\n'); + const codecs = [...plan.base.plan.requirements.values()].map((req) => + reference(this.graph.instantiate(req, plan.base!.bindings), plan, true), + ); + const forwarded = [ + `...${argsName}.slice(0, ${count})`, + ...codecs, + `...${argsName}.slice(${count + names.length})`, + ]; + edits.push({ + start: plan.node.members.pos, + end: plan.node.members.pos, + text: `\nconstructor(...${argsName}) { ${locals}\nsuper(${forwarded.join(', ')});\n${assignments} }\n`, + }); + } else { + edits.push({ + start: plan.node.members.pos, + end: plan.node.members.pos, + text: `\nconstructor(${names.map((name) => name + ' = undefined').join(', ')}) { ${assignments} }\n`, + }); + } + } else { + insertParameters(plan.node.parameters, names, edits, source); + } + } + + if (!edits.length) { + this.output.set(file, { source: code, code: null }); + return null; + } + + edits.sort((a, b) => a.start - b.start || (a.order ?? 0) - (b.order ?? 0) || a.end - b.end); + const parts: string[] = []; + let offset = 0; + + for (const edit of edits) { + if (edit.start < offset) { + throw new Error('Overlapping protobuf compiler edits.'); + } + + offset = edit.end; + } + + let generated = generateCode(this.resolver.registry, { + encodeRoots, + decodeRoots, + }); + // Keep generated identifiers out of the user's namespace, including helper names. + const prefix = unique(source, '__pb_generated_'); + const generatedNames = new Set( + [ + ...generated.matchAll( + /\b(?:function|const|let)\s+((?:protobuf_(?:encode|decode)_|__)[\p{ID_Continue}$]+)/gu, + ), + ].map((match) => match[1]), + ); + const hasCollision = [...generatedNames].some((name) => source.text.includes(name)); + + const renamed = (text: string): string => { + if (!hasCollision) { + return text; + } + + const scanner = ts.createScanner( + ts.ScriptTarget.Latest, + false, + ts.LanguageVariant.Standard, + text, + ); + const chunks: string[] = []; + let position = 0; + + for ( + let token = scanner.scan(); + token !== ts.SyntaxKind.EndOfFileToken; + token = scanner.scan() + ) { + if ( + token !== ts.SyntaxKind.Identifier || + !generatedNames.has(scanner.getTokenText()) + ) { + continue; + } + + chunks.push( + text.slice(position, scanner.getTokenPos()), + prefix + scanner.getTokenText(), + ); + position = scanner.getTextPos(); + } + + return chunks.join('') + text.slice(position); + }; + + generated = renamed(generated); + + // Rename only inserted codec references, never arbitrary source strings or user identifiers. + for (const edit of edits) { + edit.text = renamed(edit.text); + } + + parts.length = 0; + offset = 0; + + for (const edit of edits) { + parts.push(code.slice(offset, edit.start), edit.text); + offset = edit.end; + } + + parts.push(code.slice(offset)); + const rewritten = parts.join(''); + let preambleAt = code.startsWith('#!') ? code.indexOf('\n') + 1 : 0; + + for (const statement of source.statements) { + if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) { + break; + } + + preambleAt = statement.end; + } + + const transformed = + rewritten.slice(0, preambleAt) + '\n' + generated + '\n' + rewritten.slice(preambleAt); + this.output.set(file, { source: code, code: transformed }); + return transformed; + } +} diff --git a/packages/proton/src/compiler/edits.ts b/packages/proton/src/compiler/edits.ts new file mode 100644 index 00000000..d7d21a48 --- /dev/null +++ b/packages/proton/src/compiler/edits.ts @@ -0,0 +1,80 @@ +import ts from 'typescript'; +import type { Edit, Site } from './model.js'; + +export function unique(source: ts.SourceFile, base: string): string { + while (source.text.includes(base)) { + base += '_'; + } + + return base; +} + +export function codecIndex(params: readonly ts.ParameterDeclaration[] = []): number { + const index = params.findIndex((param) => !!param.initializer || !!param.dotDotDotToken); + return index < 0 ? params.length : index; +} + +export function insertParameters( + params: ts.NodeArray, + names: string[], + edits: Edit[], + source: ts.SourceFile, +): void { + names = names.map((name) => name + ' = undefined'); + const index = codecIndex(params); + + if (index < params.length) { + edits.push({ + start: params[index].getStart(source), + end: params[index].getStart(source), + text: names.join(', ') + ', ', + }); + } else { + edits.push({ + start: params.end, + end: params.end, + text: (params.length && !params.hasTrailingComma ? ', ' : '') + names.join(', '), + }); + } +} + +export function insertArguments( + node: Site['node'], + params: readonly ts.ParameterDeclaration[] | undefined, + args: string[], + edits: Edit[], + source: ts.SourceFile, +): void { + const index = codecIndex(params); + const actual = node.arguments; + + if (actual?.some(ts.isSpreadElement)) { + const values = unique(source, '__pb_arguments'); + edits.push({ + start: actual[0].getStart(source), + end: actual[0].getStart(source), + text: `...((${values}) => { while (${values}.length < ${index}) ${values}.push(undefined); ${values}.splice(${index}, 0, ${args.join(', ')}); return ${values}; })([`, + }); + edits.push({ start: actual.end, end: actual.end, text: '])', order: 1 }); + return; + } + + const missing = Math.max(0, index - (actual?.length ?? 0)); + const text = [...Array(missing).fill('undefined'), ...args].join(', '); + + if (!actual) { + edits.push({ start: node.end, end: node.end, text: `(${text})` }); + } else if (actual.length > index) { + edits.push({ + start: actual[index].getStart(source), + end: actual[index].getStart(source), + text: text + ', ', + }); + } else { + edits.push({ + start: actual.end, + end: actual.end, + text: (actual.length && !actual.hasTrailingComma ? ', ' : '') + text, + }); + } +} diff --git a/packages/proton/src/compiler/model.ts b/packages/proton/src/compiler/model.ts new file mode 100644 index 00000000..cd74c579 --- /dev/null +++ b/packages/proton/src/compiler/model.ts @@ -0,0 +1,99 @@ +import ts from 'typescript'; +import type { TypeEnvironment, TypeValue } from '../schema/types.js'; + +export type Callable = + | ts.FunctionDeclaration + | ts.FunctionExpression + | ts.ArrowFunction + | ts.MethodDeclaration + | ts.FunctionTypeNode + | ts.CallSignatureDeclaration; +export type Owner = Callable | ts.ClassDeclaration; +export interface Requirement { + key: string; + fn: 'protobuf_encode' | 'protobuf_decode'; + type: TypeValue; + node: ts.Node; +} +export interface Plan { + runtime?: Requirement['fn']; + node: Owner; + env: TypeEnvironment; + requirements: Map; + names: Map; + base?: { plan: Plan; bindings: Map }; +} +export interface Target { + node: Owner; + bindings: Map; +} +export interface Site { + node: ts.CallExpression | ts.NewExpression; + owner?: Plan; + direct?: Requirement; + target?: Plan; + bindings?: Map; + typeArgs?: readonly ts.TypeNode[]; + env?: TypeEnvironment; + bound?: boolean; +} +export interface Edit { + order?: number; + start: number; + end: number; + text: string; +} + +export function callable(node: ts.Node): node is Callable { + switch (node.kind) { + case ts.SyntaxKind.FunctionDeclaration: + case ts.SyntaxKind.FunctionExpression: + case ts.SyntaxKind.ArrowFunction: + case ts.SyntaxKind.MethodDeclaration: + case ts.SyntaxKind.FunctionType: + case ts.SyntaxKind.CallSignature: + return true; + default: + return false; + } +} + +export function constructorOf(node: ts.ClassDeclaration): ts.ConstructorDeclaration | undefined { + return node.members.find( + (member): member is ts.ConstructorDeclaration => + ts.isConstructorDeclaration(member) && !!member.body, + ); +} + +export function memberName(name: ts.PropertyName): string | undefined { + if (ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) { + return name.text; + } + + if ( + ts.isComputedPropertyName(name) && + (ts.isStringLiteralLike(name.expression) || ts.isNumericLiteral(name.expression)) + ) { + return name.expression.text; + } + + return; +} + +export function access( + expression: ts.Expression, +): { receiver: ts.Expression; name: string } | undefined { + if (ts.isPropertyAccessExpression(expression)) { + return { receiver: expression.expression, name: expression.name.text }; + } + + if ( + ts.isElementAccessExpression(expression) && + (ts.isStringLiteralLike(expression.argumentExpression) || + ts.isNumericLiteral(expression.argumentExpression)) + ) { + return { receiver: expression.expression, name: expression.argumentExpression.text }; + } + + return; +} diff --git a/packages/proton/src/compiler/receivers.ts b/packages/proton/src/compiler/receivers.ts new file mode 100644 index 00000000..a2adc4c3 --- /dev/null +++ b/packages/proton/src/compiler/receivers.ts @@ -0,0 +1,404 @@ +import ts from 'typescript'; +import { fail } from '../source/context.js'; +import type { TypeEnvironment } from '../schema/types.js'; +import { + access, + callable, + constructorOf, + memberName, + type Callable, + type Target, +} from './model.js'; +import type { CallTargets } from './targets.js'; + +interface Receiver { + node: ts.ClassDeclaration | ts.ObjectLiteralExpression; + bindings: Target['bindings']; + env: TypeEnvironment; +} +type Returning = Callable | ts.GetAccessorDeclaration; + +export class Receivers { + private readonly returns = new WeakMap(); + + constructor(private readonly targets: CallTargets) {} + + resolve( + expression: ts.Expression, + source: ts.SourceFile, + env: TypeEnvironment, + seen = new Set(), + ): Receiver | undefined { + if (seen.has(expression)) { + return; + } + + seen.add(expression); + const { context } = this.targets; + + if ( + ts.isParenthesizedExpression(expression) || + ts.isNonNullExpression(expression) || + ts.isSatisfiesExpression(expression) + ) { + return this.resolve(expression.expression, source, env, seen); + } + + if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)) { + return ( + this.annotation(expression.type, env, seen) ?? + this.resolve(expression.expression, source, env, seen) + ); + } + + if (ts.isObjectLiteralExpression(expression)) { + return { node: expression, env, bindings: new Map() }; + } + + if (expression.kind === ts.SyntaxKind.ThisKeyword) { + for (let parent = expression.parent; parent; parent = parent.parent) { + if (ts.isClassDeclaration(parent)) { + const target = this.targets.capture( + expression, + { node: parent, bindings: new Map() }, + env, + ); + return { + node: parent, + bindings: target.bindings, + env: this.targets.environment(target), + }; + } + } + } + + if (ts.isIdentifier(expression)) { + const declaration = context.lookup(expression.text, expression, source)?.node; + + if (declaration && ts.isClassDeclaration(declaration)) { + return { + node: declaration, + bindings: new Map(), + env: this.targets.graph.plan(declaration).env, + }; + } + + if ( + declaration && + (ts.isVariableDeclaration(declaration) || ts.isParameter(declaration)) + ) { + const annotated = declaration.type && this.annotation(declaration.type, env, seen); + + if (annotated) { + return annotated; + } + + if (declaration.initializer) { + return this.resolve( + declaration.initializer, + declaration.getSourceFile(), + env, + seen, + ); + } + } + } + + const property = access(expression); + + if (property) { + const receiver = this.resolve(property.receiver, source, env, seen); + const member = receiver && this.member(receiver, property.name); + + if (!member) { + return; + } + + const node = member.node; + + if ('type' in node && node.type) { + const annotated = this.annotation(node.type, member.env, seen); + + if (annotated) { + return annotated; + } + } + + if (ts.isGetAccessorDeclaration(node)) { + return this.returned(node, member.env, seen, expression); + } + + if ('initializer' in node && node.initializer) { + return this.resolve(node.initializer, node.getSourceFile(), member.env, seen); + } + + if (ts.isShorthandPropertyAssignment(node)) { + return this.resolve(node.name, node.getSourceFile(), member.env, seen); + } + } + + if (ts.isNewExpression(expression) || ts.isCallExpression(expression)) { + const target = this.targets.target(expression.expression, source, env, seen); + + if (!target) { + return; + } + + const specialized = this.targets.specialize(expression, target, env); + const local = this.targets.environment(specialized); + + if (ts.isNewExpression(expression)) { + return ts.isClassDeclaration(target.node) + ? { node: target.node, bindings: specialized.bindings, env: local } + : undefined; + } + + if (!callable(target.node)) { + return; + } + + const annotated = target.node.type && this.annotation(target.node.type, local, seen); + return annotated || this.returned(target.node, local, seen, expression); + } + + if (ts.isConditionalExpression(expression)) { + return this.merge([expression.whenTrue, expression.whenFalse], env, seen, expression); + } + + return; + } + + member( + receiver: Receiver, + name: string, + ): + | { + node: ts.ClassElement | ts.ObjectLiteralElementLike | ts.ParameterDeclaration; + bindings: Target['bindings']; + env: TypeEnvironment; + } + | undefined { + const { graph, resolver } = this.targets; + let node = receiver.node; + const bindings = new Map(receiver.bindings); + + for (;;) { + const members = ts.isClassDeclaration(node) ? node.members : node.properties; + const member = + members.find( + (member) => + member.name && + memberName(member.name) === name && + (!ts.isMethodDeclaration(member) || !!member.body), + ) ?? + (ts.isClassDeclaration(node) + ? constructorOf(node)?.parameters.find( + (param) => + ts.isIdentifier(param.name) && + param.name.text === name && + param.modifiers?.length, + ) + : undefined); + + if (member) { + const env = ts.isClassDeclaration(node) + ? this.targets.environment({ node, bindings }) + : receiver.env; + return { node: member, bindings, env }; + } + + const base = ts.isClassDeclaration(node) && graph.plan(node).base; + + if (!base || !ts.isClassDeclaration(base.plan.node)) { + return; + } + + for (const [key, type] of base.bindings) { + bindings.set(key, resolver.substitute(type, bindings)); + } + + node = base.plan.node; + } + } + + private annotation( + type: ts.TypeNode, + env: TypeEnvironment, + seen: Set, + ): Receiver | undefined { + if (seen.has(type)) { + return; + } + + seen.add(type); + + if (ts.isParenthesizedTypeNode(type)) { + return this.annotation(type.type, env, seen); + } + + if (ts.isUnionTypeNode(type)) { + const types = type.types.filter( + (item) => + item.kind !== ts.SyntaxKind.UndefinedKeyword && + !( + ts.isLiteralTypeNode(item) && + item.literal.kind === ts.SyntaxKind.NullKeyword + ), + ); + + if (types.length === 1) { + return this.annotation(types[0], env, seen); + } + + return; + } + + if (!ts.isTypeReferenceNode(type)) { + return; + } + + const { context, resolver, graph } = this.targets; + const ref = context.typeName(type.typeName, type.getSourceFile()); + + if (!ref || (!ts.isClassDeclaration(ref.node) && !ts.isTypeAliasDeclaration(ref.node))) { + return; + } + + if (ts.isTypeAliasDeclaration(ref.node) && !this.classShape(ref.node.type)) { + return; + } + + const args = resolver.arguments( + ref.node.typeParameters, + type.typeArguments, + type.getSourceFile(), + env, + ref.node, + ); + + if (ts.isTypeAliasDeclaration(ref.node)) { + return this.annotation(ref.node.type, new Map([...env, ...args]), seen); + } + + const plan = graph.plan(ref.node); + const target = this.targets.capture( + type, + { + node: ref.node, + bindings: new Map([...args].map(([name, type]) => [plan.env.get(name)!.key, type])), + }, + env, + ); + return { node: ref.node, bindings: target.bindings, env: this.targets.environment(target) }; + } + + private classShape(type: ts.TypeNode, seen = new Set()): boolean { + if (seen.has(type)) { + return false; + } + + seen.add(type); + + if (ts.isParenthesizedTypeNode(type)) { + return this.classShape(type.type, seen); + } + + if (ts.isUnionTypeNode(type)) { + return type.types.some((member) => this.classShape(member, seen)); + } + + if (!ts.isTypeReferenceNode(type)) { + return false; + } + + const node = this.targets.context.typeName(type.typeName, type.getSourceFile())?.node; + return ( + !!node && + (ts.isClassDeclaration(node) || + (ts.isTypeAliasDeclaration(node) && this.classShape(node.type, seen))) + ); + } + + private returned( + node: Returning, + env: TypeEnvironment, + seen: Set, + origin: ts.Node, + ): Receiver | undefined { + const cached = this.returns.get(node); + + if (cached) { + return this.merge(cached, env, seen, origin); + } + + const expressions: ts.Expression[] = []; + + if ('body' in node && node.body) { + if (ts.isBlock(node.body)) { + const visit = (child: ts.Node): void => { + if (ts.isFunctionLike(child) || ts.isClassDeclaration(child)) { + return; + } + + if (ts.isReturnStatement(child)) { + if (child.expression) { + expressions.push(child.expression); + } + } else { + ts.forEachChild(child, visit); + } + }; + + visit(node.body); + } else { + expressions.push(node.body); + } + } + + this.returns.set(node, expressions); + return this.merge(expressions, env, seen, origin); + } + + private merge( + expressions: ts.Expression[], + env: TypeEnvironment, + seen: Set, + origin: ts.Node, + ): Receiver | undefined { + let result: Receiver | undefined; + + for (const expression of expressions) { + const next = this.resolve(expression, expression.getSourceFile(), env, new Set(seen)); + + if (!next) { + return; + } + + if ( + result && + (result.node !== next.node || + [...result.env].some(([name, type]) => next.env.get(name)?.key !== type.key)) + ) { + // Data objects returned by ordinary functions need no codec + // specialization, even when their branches have different shapes. + if ( + ts.isObjectLiteralExpression(result.node) && + ts.isObjectLiteralExpression(next.node) && + ![...result.node.properties, ...next.node.properties].some( + (member) => + callable(member) || + (ts.isPropertyAssignment(member) && callable(member.initializer)), + ) + ) { + return; + } + + fail(origin, 'Receiver branches must resolve to the same specialization.'); + } + + result = next; + } + + return result; + } +} diff --git a/packages/proton/src/compiler/signatures.ts b/packages/proton/src/compiler/signatures.ts new file mode 100644 index 00000000..7d1f3457 --- /dev/null +++ b/packages/proton/src/compiler/signatures.ts @@ -0,0 +1,212 @@ +import ts from 'typescript'; +import type { SourceContext } from '../source/context.js'; +import type { SchemaResolver } from '../schema/resolver.js'; +import type { TypeEnvironment } from '../schema/types.js'; + +export interface Signature { + node: ts.FunctionTypeNode | ts.CallSignatureDeclaration; + env: TypeEnvironment; +} + +export function memberType( + type: ts.TypeNode, + name: string, + env: TypeEnvironment, + context: SourceContext, + resolver: SchemaResolver, + seen = new Set(), +): { type: ts.TypeNode; env: TypeEnvironment } | undefined { + if (seen.has(type)) { + return; + } + + seen.add(type); + + if (ts.isTypeLiteralNode(type)) { + const member = type.members.find( + (member) => + member.name && + (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) && + member.name.text === name, + ); + return member && ts.isPropertySignature(member) && member.type + ? { type: member.type, env } + : undefined; + } + + if (ts.isTypeReferenceNode(type)) { + const ref = context.typeName(type.typeName, type.getSourceFile()); + + if ( + !ref || + (!ts.isTypeAliasDeclaration(ref.node) && !ts.isInterfaceDeclaration(ref.node)) + ) { + return; + } + + if (ts.isTypeAliasDeclaration(ref.node) && !memberShape(ref.node.type, name, context)) { + return; + } + + const local = new Map([ + ...env, + ...resolver.arguments( + ref.node.typeParameters, + type.typeArguments, + type.getSourceFile(), + env, + ref.node, + true, + ), + ]); + + if (ts.isTypeAliasDeclaration(ref.node)) { + return memberType(ref.node.type, name, local, context, resolver, seen); + } + + const member = ref.node.members.find( + (member) => member.name?.getText(ref.source).replace(/^['"]|['"]$/g, '') === name, + ); + return member && ts.isPropertySignature(member) && member.type + ? { type: member.type, env: local } + : undefined; + } + + return; +} + +export function resolveSignature( + type: ts.TypeNode, + env: TypeEnvironment, + context: SourceContext, + resolver: SchemaResolver, + seen = new Set(), +): Signature | undefined { + if (seen.has(type)) { + return; + } + + seen.add(type); + + if (ts.isParenthesizedTypeNode(type)) { + return resolveSignature(type.type, env, context, resolver, seen); + } + + if (ts.isFunctionTypeNode(type)) { + return { node: type, env }; + } + + if (ts.isTypeLiteralNode(type)) { + const signatures = type.members.filter(ts.isCallSignatureDeclaration); + + if (signatures.length === 1) { + return { node: signatures[0], env }; + } + } + + if (ts.isTypeReferenceNode(type)) { + const ref = context.typeName(type.typeName, type.getSourceFile()); + + if (!ref) { + return; + } + + const node = ref.node; + + if (!ts.isTypeAliasDeclaration(node) && !ts.isInterfaceDeclaration(node)) { + return; + } + + if (!callableShape(type, context)) { + return; + } + + const local = new Map([ + ...env, + ...resolver.arguments( + node.typeParameters, + type.typeArguments, + type.getSourceFile(), + env, + node, + true, + ), + ]); + return ts.isTypeAliasDeclaration(node) + ? resolveSignature(node.type, local, context, resolver, seen) + : { node: node.members.find(ts.isCallSignatureDeclaration)!, env: local }; + } + + return; +} + +export function callableShape( + type: ts.TypeNode, + context: SourceContext, + seen = new Set(), +): boolean { + if (seen.has(type)) { + return false; + } + + seen.add(type); + + if (ts.isFunctionTypeNode(type)) { + return true; + } + + if (ts.isParenthesizedTypeNode(type)) { + return callableShape(type.type, context, seen); + } + + if (ts.isTypeLiteralNode(type)) { + return type.members.filter(ts.isCallSignatureDeclaration).length === 1; + } + + if (!ts.isTypeReferenceNode(type)) { + return false; + } + + const node = context.typeName(type.typeName, type.getSourceFile())?.node; + return ( + !!node && + (ts.isTypeAliasDeclaration(node) + ? callableShape(node.type, context, seen) + : ts.isInterfaceDeclaration(node) && + node.members.filter(ts.isCallSignatureDeclaration).length === 1) + ); +} + +function memberShape( + type: ts.TypeNode, + name: string, + context: SourceContext, + seen = new Set(), +): boolean { + if (seen.has(type)) { + return false; + } + + seen.add(type); + + if (ts.isTypeLiteralNode(type)) { + return type.members.some( + (member) => member.name?.getText().replace(/^['"]|['"]$/g, '') === name, + ); + } + + if (!ts.isTypeReferenceNode(type)) { + return false; + } + + const node = context.typeName(type.typeName, type.getSourceFile())?.node; + return ( + !!node && + (ts.isTypeAliasDeclaration(node) + ? memberShape(node.type, name, context, seen) + : ts.isInterfaceDeclaration(node) && + node.members.some( + (member) => member.name?.getText().replace(/^['"]|['"]$/g, '') === name, + )) + ); +} diff --git a/packages/proton/src/compiler/targets.ts b/packages/proton/src/compiler/targets.ts new file mode 100644 index 00000000..f213fd7b --- /dev/null +++ b/packages/proton/src/compiler/targets.ts @@ -0,0 +1,345 @@ +import ts from 'typescript'; +import { packageName } from '../package.js'; +import { SourceContext, runtimeImportName, type DeclarationRef } from '../source/context.js'; +import { SchemaResolver } from '../schema/resolver.js'; +import type { TypeEnvironment, TypeValue } from '../schema/types.js'; +import { access, callable, type Plan, type Target, type Requirement, type Site } from './model.js'; +import { Receivers } from './receivers.js'; +import { callableShape, memberType, resolveSignature, type Signature } from './signatures.js'; + +interface Plans { + environment(node: ts.Node): TypeEnvironment; + plan(node: Target['node']): Plan; + runtimePlan(fn: Requirement['fn']): Plan; + bindings(site: Site, partial?: boolean): Map; +} + +export class CallTargets { + private readonly receivers = new Receivers(this); + constructor( + readonly context: SourceContext, + readonly resolver: SchemaResolver, + readonly graph: Plans, + ) {} + + signature(type: ts.TypeNode, env: TypeEnvironment) { + return resolveSignature(type, env, this.context, this.resolver); + } + + signatureTarget(signature: Signature): Target { + const plan = this.graph.plan(signature.node); + return { + node: signature.node, + bindings: new Map( + [...signature.env].flatMap(([name, type]) => { + if (signature.node.typeParameters?.some((param) => param.name.text === name)) { + return []; + } + + const parameter = plan.env.get(name); + return parameter ? [[parameter.key, type] as const] : []; + }), + ), + }; + } + + target( + expression: ts.Expression, + source: ts.SourceFile, + env: TypeEnvironment, + seen = new Set(), + ): Target | undefined { + if (seen.has(expression)) { + return; + } + + seen.add(expression); + + if (callable(expression)) { + return { node: expression, bindings: new Map() }; + } + + if (ts.isCallExpression(expression)) { + const factory = this.target(expression.expression, source, env, seen); + + if ( + factory && + callable(factory.node) && + factory.node.type && + callableShape(factory.node.type, this.context) + ) { + const local = this.environment(this.specialize(expression, factory, env)); + const signature = this.signature(factory.node.type, local); + + if (signature) { + return this.signatureTarget(signature); + } + } + + return; + } + + if ( + ts.isParenthesizedExpression(expression) || + ts.isAsExpression(expression) || + ts.isNonNullExpression(expression) + ) { + return this.target(expression.expression, source, env, seen); + } + + if (expression.kind === ts.SyntaxKind.SuperKeyword) { + for (let parent: ts.Node | undefined = expression; parent; parent = parent.parent) { + if (ts.isClassDeclaration(parent)) { + const base = this.graph.plan(parent).base; + return base + ? { node: base.plan.node, bindings: new Map(base.bindings) } + : undefined; + } + } + } + + let ref: DeclarationRef | undefined; + const property = access(expression); + + if (ts.isIdentifier(expression)) { + ref = this.context.lookup(expression.text, expression, source); + } else if (property) { + let receiver: ts.Expression = property.receiver; + + while (ts.isParenthesizedExpression(receiver)) { + receiver = receiver.expression; + } + + const declaration = ts.isIdentifier(receiver) + ? this.context.lookup(receiver.text, receiver, source)?.node + : undefined; + + if ( + declaration && + (ts.isVariableDeclaration(declaration) || ts.isParameter(declaration)) && + declaration.type + ) { + const member = memberType( + declaration.type, + property.name, + env, + this.context, + this.resolver, + ); + const signature = member && this.signature(member.type, member.env); + + if (signature) { + return this.signatureTarget(signature); + } + } + + if (declaration && ts.isNamespaceImport(declaration)) { + const specifier = (declaration.parent.parent.moduleSpecifier as ts.StringLiteral) + .text; + + if ( + specifier === packageName && + (property.name === 'protobuf_encode' || property.name === 'protobuf_decode') + ) { + return { + node: this.graph.runtimePlan(property.name).node, + bindings: new Map(), + }; + } + + const module = this.context.module(specifier, declaration.getSourceFile()); + ref = module ? this.context.exported(property.name, module) : undefined; + } else { + const value = this.receivers.resolve(receiver, source, env, seen); + const member = value && this.receivers.member(value, property.name); + + if (member) { + if (callable(member.node)) { + return { node: member.node, bindings: member.bindings }; + } + + if ('initializer' in member.node && member.node.initializer) { + const target = this.target( + member.node.initializer, + member.node.getSourceFile(), + member.env, + seen, + ); + + if (target) { + return { + node: target.node, + bindings: new Map([...member.bindings, ...target.bindings]), + }; + } + } + + if (ts.isShorthandPropertyAssignment(member.node)) { + return this.target( + member.node.name, + member.node.getSourceFile(), + member.env, + seen, + ); + } + } + } + } + + if (!ref) { + return; + } + + // Ambient library declarations have no body in which to thread codecs. + // Their unrelated generic arguments must not enter schema inference. + if (ref.source.isDeclarationFile) { + return; + } + + const runtime = runtimeImportName(ref.node); + + if (runtime === 'protobuf_encode' || runtime === 'protobuf_decode') { + return { node: this.graph.runtimePlan(runtime).node, bindings: new Map() }; + } + + if ((ts.isParameter(ref.node) || ts.isVariableDeclaration(ref.node)) && ref.node.type) { + const signature = this.signature(ref.node.type, env); + + if (signature) { + return this.signatureTarget(signature); + } + } + + if ( + ts.isBindingElement(ref.node) && + ts.isObjectBindingPattern(ref.node.parent) && + (ts.isVariableDeclaration(ref.node.parent.parent) || + ts.isParameter(ref.node.parent.parent)) + ) { + const declaration = ref.node.parent.parent; + const initializer = declaration.initializer; + const name = ref.node.propertyName ?? ref.node.name; + + if (declaration.type && (ts.isIdentifier(name) || ts.isStringLiteral(name))) { + const property = memberType( + declaration.type, + name.text, + env, + this.context, + this.resolver, + ); + const signature = property && this.signature(property.type, property.env); + + if (signature) { + return this.signatureTarget(signature); + } + } + + if (initializer && (ts.isIdentifier(name) || ts.isStringLiteral(name))) { + return this.target( + ts.factory.createPropertyAccessExpression(initializer, name.text), + ref.source, + env, + seen, + ); + } + } + + if (callable(ref.node) || ts.isClassDeclaration(ref.node)) { + return { node: ref.node, bindings: new Map() }; + } + + if (ts.isVariableDeclaration(ref.node) && ref.node.initializer) { + if (callable(ref.node.initializer)) { + return { node: ref.node.initializer, bindings: new Map() }; + } + + return this.target(ref.node.initializer, ref.source, env, seen); + } + + return; + } + + specialize( + node: ts.CallExpression | ts.NewExpression, + target: Target, + env: TypeEnvironment, + ): Target { + return { + node: target.node, + bindings: this.graph.bindings( + { + node, + target: this.graph.plan(target.node), + bindings: this.capture(node, target, env).bindings, + typeArgs: node.typeArguments, + env, + }, + true, + ), + }; + } + + capture(node: ts.Node, target: Target, env: TypeEnvironment): Target { + const bindings = new Map(target.bindings); + const lexical = this.graph.environment(node); + + for (const [name, type] of this.graph.plan(target.node).env) { + if ( + !bindings.has(type.key) && + !target.node.typeParameters?.some((param) => param.name.text === name) && + lexical.get(name)?.key === type.key && + env.has(name) + ) { + bindings.set(type.key, env.get(name)!); + } + } + + return { node: target.node, bindings }; + } + + environment(target: Target): TypeEnvironment { + return new Map( + [...this.graph.plan(target.node).env].map(([name, type]) => [ + name, + this.resolver.substitute(type, target.bindings), + ]), + ); + } + + infer( + expression: ts.Expression, + source: ts.SourceFile, + seen = new Set(), + ): ts.TypeNode | undefined { + if (seen.has(expression)) { + return; + } + + seen.add(expression); + + if ( + ts.isAsExpression(expression) || + ts.isTypeAssertionExpression(expression) || + ts.isSatisfiesExpression(expression) + ) { + return expression.type; + } + + if (ts.isIdentifier(expression)) { + const ref = this.context.lookup(expression.text, expression, source); + + if (ref && (ts.isVariableDeclaration(ref.node) || ts.isParameter(ref.node))) { + if (ref.node.type) { + return ref.node.type; + } + + if (ref.node.initializer) { + return this.infer(ref.node.initializer, ref.source, seen); + } + } + } + + return; + } +} diff --git a/packages/proton/src/compiler/validate.ts b/packages/proton/src/compiler/validate.ts new file mode 100644 index 00000000..ef3f75f1 --- /dev/null +++ b/packages/proton/src/compiler/validate.ts @@ -0,0 +1,140 @@ +import ts from 'typescript'; +import { fail } from '../source/context.js'; +import { callable } from './model.js'; +import type { CallAnalysis } from './analysis.js'; + +export function validateSource(graph: CallAnalysis, source: ts.SourceFile): void { + if (![...graph.plans.values()].some((plan) => plan.requirements.size)) { + return; + } + + const visit = (node: ts.Node): void => { + if (ts.isExpressionWithTypeArguments(node) && !ts.isHeritageClause(node.parent)) { + const target = graph.targets.target(node.expression, source, graph.environment(node)); + + if ( + target && + graph.plan(target.node).requirements.size && + !graph.callbacks.adapters.has(node) + ) { + fail(node, 'Generic function values require an explicitly typed arrow adapter.'); + } + } + + if (ts.isTypeNode(node) || ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { + return; + } + + if (ts.isIdentifier(node) && node.text === 'arguments') { + const owner = graph.owner(node); + + if (owner && graph.plan(owner).requirements.size) { + fail( + node, + 'Generic codec functions cannot reflect on arguments; use named or rest parameters.', + ); + } + } + + if ( + (ts.isIdentifier(node) || + ts.isPropertyAccessExpression(node) || + ts.isElementAccessExpression(node) || + ts.isArrowFunction(node) || + ts.isFunctionExpression(node)) && + isValuePosition(node) + ) { + const target = graph.targets.target(node, source, graph.environment(node)); + const owner = target && graph.owner(target.node); + + if ( + target && + !graph.callbacks.adapters.has(node) && + !ts.isClassDeclaration(target.node) && + (graph.plan(target.node).requirements.size || + (ts.isMethodDeclaration(target.node) && + owner && + graph.plan(owner).requirements.size)) + ) { + fail( + node, + 'Cannot infer callback schema; annotate the callback type or supply concrete type arguments.', + ); + } + } + + if ( + (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + ts.isVariableDeclaration(node.parent) && + node.parent.initializer === node + ) { + const target = graph.targets.target(node, source, graph.environment(node)); + const owner = target && graph.owner(target.node); + + if ( + target && + ts.isMethodDeclaration(target.node) && + !target.node.typeParameters?.length && + owner && + ts.isClassDeclaration(owner) && + graph.plan(owner).requirements.size + ) { + fail( + node, + 'Instance codec methods require their receiver; use an arrow adapter instead of detaching the method.', + ); + } + } + + ts.forEachChild(node, visit); + }; + + visit(source); + + for (const site of graph.sites.get(source) ?? []) { + if (!site.direct?.type.dynamic || !site.owner || !ts.isClassDeclaration(site.owner.node)) { + continue; + } + + for ( + let parent = site.node.parent; + parent && parent !== site.owner.node; + parent = parent.parent + ) { + if (callable(parent) || ts.isConstructorDeclaration(parent)) { + break; + } + + if (ts.isPropertyDeclaration(parent)) { + fail( + site.node, + 'Move generic codec calls from class field initializers into the constructor body.', + ); + } + } + } +} + +function isValuePosition(node: ts.Expression): boolean { + let value: ts.Node = node; + + while ( + ts.isParenthesizedExpression(value.parent) || + ts.isAsExpression(value.parent) || + ts.isSatisfiesExpression(value.parent) + ) { + value = value.parent; + } + + const parent = value.parent; + return ( + (ts.isCallExpression(parent) && parent.expression !== value) || + ts.isReturnStatement(parent) || + ts.isShorthandPropertyAssignment(parent) || + ts.isArrayLiteralExpression(parent) || + (ts.isPropertyAssignment(parent) && parent.initializer === value) || + (ts.isBinaryExpression(parent) && + parent.right === value && + parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) + ); +} diff --git a/packages/proton/src/index.ts b/packages/proton/src/index.ts index e1e4e2f8..4d6b0784 100644 --- a/packages/proton/src/index.ts +++ b/packages/proton/src/index.ts @@ -1,140 +1,74 @@ -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'; +import type { Plugin, ResolvedConfig } from 'vite'; +import { ProtobufCompiler } from './compiler/compiler.js'; +import { buildEntries } from './source/entries.js'; +import { packageName } from './package.js'; -export interface ProtobufRuntimeMapPluginOptions { - enabled?: boolean; - fileName?: string; -} +export default function protobufVitePlugin(): Plugin { + const compiler = new ProtobufCompiler(); + const transformedFiles = new Set(); + let config: ResolvedConfig | undefined; + let needsPreparation = true; -export interface ProtobufVitePluginOptions { - runtimeMap?: ProtobufRuntimeMapPluginOptions; -} - -interface RuntimeMapFileEntry { - messages: MessageRegistry; - callSites: RuntimeMapCallSite[]; -} - -export default function protobufVitePlugin(options: ProtobufVitePluginOptions = {}): Plugin { - const fileCache = new Map(); - const runtimeMapByFile = new Map(); - const runtimeMapEnabled = options.runtimeMap?.enabled === true; - const runtimeMapFileName = options.runtimeMap?.fileName ?? 'snowluma-proton.runtime-map.json'; + const invalidate = () => { + compiler.clear(); + needsPreparation = true; + }; return { - name: 'vite-plugin-protobuf', + name: `${packageName}:vite`, enforce: 'pre', + configResolved(resolved) { + config = resolved; + }, + + buildStart() { + invalidate(); + transformedFiles.clear(); + }, + + watchChange() { + invalidate(); + }, + transform(code, id) { const cleanId = id.split('?')[0]; - if (!cleanId.endsWith('.ts') || cleanId.endsWith('.d.ts')) { + if (!/\.[cm]?tsx?$/.test(cleanId) || /\.d\.[cm]?ts$/.test(cleanId)) { return null; } - const imported = resolveImports(code, cleanId, fileCache); - const { registry, callSites, sourceFile } = analyze(code, cleanId, imported); + if (needsPreparation) { + if (config) { + compiler.prepare(buildEntries(config)); + } - if (registry.size === 0 && callSites.length === 0) { - return null; + needsPreparation = false; } - const used = selectUsedRegistry(registry, callSites, sourceFile); + const transformed = compiler.compile(code, cleanId); - if (used.registry.size === 0) { - runtimeMapByFile.delete(cleanId); - return null; + if (transformed !== null) { + transformedFiles.add(cleanId); + + for (const dependency of compiler.context.files.keys()) { + this.addWatchFile?.(dependency); + } } - 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, - })), + return transformed === null ? null : { code: transformed, map: null }; + }, + + handleHotUpdate({ file, server }) { + if (/\.[cm]?tsx?$/.test(file)) { + invalidate(); + return [...transformedFiles].flatMap((id) => { + const module = server.moduleGraph.getModuleById(id); + return module ? [module] : []; }); } - 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), - }); + return; }, }; } - -export { - analyze, - analyzeSource, - generateCode, - replaceCallSites, - applyReplacements, - typeNodeToMangledName, - resolveImports, - selectUsedRegistry, - createRuntimeMap, -}; - -export type { ProtobufRuntimeMap, RuntimeMapCallSite } from './runtime-map.js'; diff --git a/packages/proton/src/package.ts b/packages/proton/src/package.ts new file mode 100644 index 00000000..e8d23d3a --- /dev/null +++ b/packages/proton/src/package.ts @@ -0,0 +1 @@ +export { name as packageName } from '../package.json'; diff --git a/packages/proton/src/runtime-map.ts b/packages/proton/src/runtime-map.ts deleted file mode 100644 index c1d6e298..00000000 --- a/packages/proton/src/runtime-map.ts +++ /dev/null @@ -1,78 +0,0 @@ -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, - explicitPresence: field.explicitPresence ?? false, - }; -} - -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(); - - 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()], - }; -} diff --git a/packages/proton/src/runtime.ts b/packages/proton/src/runtime.ts index 2a0dbb97..05319c7b 100644 --- a/packages/proton/src/runtime.ts +++ b/packages/proton/src/runtime.ts @@ -1,16 +1,18 @@ -import { buildDependencyRegistry } from './ast/dependency-graph.js'; -import type { MessageRegistry } from './ast/types.js'; -import { generateCode } from './codegen/generator.js'; -import { - normalizeRuntimeMapPath, - runtimeMapToRegistry, - type ProtobufRuntimeMap, - type RuntimeMapCallSite, - type RuntimeMapFnName, -} from './runtime-map.js'; +import { packageName } from './package.js'; -type DynamicEncode = (params: unknown) => Uint8Array; -type DynamicDecode = (data: Uint8Array) => unknown; +function uncompiled(operation: string): never { + throw new Error( + `${operation}() was not transformed by the ${packageName} Vite plugin. Add the plugin from ${packageName}/vite to your build.`, + ); +} + +export function protobuf_encode(_value: T): Uint8Array { + return uncompiled('protobuf_encode'); +} + +export function protobuf_decode(_bytes: Uint8Array): T { + return uncompiled('protobuf_decode'); +} export interface ProtobufUnknownField { fieldNumber: number; @@ -65,273 +67,3 @@ export function protobuf_getUnknownFieldMetadata(value: unknown): ProtobufUnknow omittedByteLength: candidate.omittedByteLength ?? 0, }; } - -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(); - -/** - * 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(_params: T): Uint8Array { - const dynamic = tryDynamicInvoke('protobuf_encode', _params); - - if (dynamic !== DYNAMIC_MISS) { - return dynamic as Uint8Array; - } - - throw new Error( - 'protobuf_encode() 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(_data: Uint8Array): T { - const dynamic = tryDynamicInvoke('protobuf_decode', _data); - - if (dynamic !== DYNAMIC_MISS) { - return dynamic as T; - } - - throw new Error( - 'protobuf_decode() 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; -} diff --git a/packages/proton/src/schema/message.ts b/packages/proton/src/schema/message.ts new file mode 100644 index 00000000..ff30b3a9 --- /dev/null +++ b/packages/proton/src/schema/message.ts @@ -0,0 +1,143 @@ +import type ts from 'typescript'; +import { fail } from '../source/context.js'; +import { + PRIMITIVE_TYPE_MAP, + WireType, + type MessageRegistry, + type ProtobufField, +} from '../codegen/model.js'; +import type { TypeValue } from './types.js'; + +export class MessageBuilder { + readonly registry: MessageRegistry = new Map(); + private readonly messageNames = new Map(); + private readonly nameOwners = new Map(); + + build(type: TypeValue, node: ts.Node): string { + if (type.dynamic) { + fail( + node, + `Cannot statically resolve protobuf type ${type.name}. Supply concrete generic arguments at its call site.`, + ); + } + + if (type.kind !== 'object' || !type.fields) { + fail(node, `Expected a protobuf message, received ${type.name}.`); + } + + const cached = this.messageNames.get(type.key); + + if (cached) { + return cached; + } + + let name = type.name.replace(/[^\p{ID_Continue}$]/gu, '_'); + + if (!/^[\p{ID_Start}_$]/u.test(name)) { + name = '_' + name; + } + + if (this.nameOwners.has(name) && this.nameOwners.get(name) !== type.key) { + let hash = 2166136261; + + for (const char of type.key) { + hash = Math.imul(hash ^ char.charCodeAt(0), 16777619); + } + + name += '_' + (hash >>> 0).toString(36); + } + + this.nameOwners.set(name, type.key); + this.messageNames.set(type.key, name); + const fields: ProtobufField[] = []; + this.registry.set(name, { name, fields }); + const numbers = new Set(); + + for (const [fieldName, property] of type.fields) { + let marker = property.type; + let optional = property.optional; + + if (marker.kind === 'union') { + optional ||= marker.values!.some((item) => item.kind === 'null'); + const members = marker.values!.filter((item) => item.kind !== 'null'); + + if (members.length !== 1) { + fail(property.node, `Ambiguous protobuf union on field ${fieldName}.`); + } + + marker = members[0]; + } + + if (marker.kind !== 'marker') { + fail( + property.node, + `Field ${fieldName} must use pb, pb_optional or pb_repeated.`, + ); + } + + const number = marker.fieldNumber!; + + if ( + !Number.isInteger(number) || + number < 1 || + number > 536870911 || + (number >= 19000 && number <= 19999) + ) { + fail(property.node, `Invalid or reserved protobuf field number ${number}.`); + } + + if (numbers.has(number)) { + fail(property.node, `Duplicate protobuf field number ${number}.`); + } + + numbers.add(number); + let payload = marker.values![0]; + + if (payload.kind === 'marker') { + payload = payload.values![0]; + } + + if (payload.kind === 'union') { + optional ||= payload.values!.some((item) => item.kind === 'null'); + const members = payload.values!.filter((item) => item.kind !== 'null'); + + if (members.length !== 1) { + fail(property.node, `Ambiguous protobuf union on field ${fieldName}.`); + } + + payload = members[0]; + } + + const repeated = marker.repeated || payload.kind === 'array'; + + if (payload.kind === 'array') { + payload = payload.values![0]; + } + + const isMessage = payload.kind === 'object'; + const typeName = isMessage ? this.build(payload, property.node) : payload.name; + const primitive = PRIMITIVE_TYPE_MAP[typeName]; + + if (!isMessage && !primitive) { + fail( + property.node, + `Unsupported protobuf field type ${typeName}. Use an explicit protobuf scalar type.`, + ); + } + + fields.push({ + name: fieldName, + fieldNumber: number, + typeName, + wireType: isMessage ? WireType.LengthDelim : primitive.wireType, + isMessage, + isRepeated: !!repeated, + isOptional: optional, + explicitPresence: marker.explicitPresence, + }); + } + + fields.sort((a, b) => a.fieldNumber - b.fieldNumber); + return name; + } +} diff --git a/packages/proton/src/schema/objects.ts b/packages/proton/src/schema/objects.ts new file mode 100644 index 00000000..ca7c1e03 --- /dev/null +++ b/packages/proton/src/schema/objects.ts @@ -0,0 +1,249 @@ +import ts from 'typescript'; +import { fail, type DeclarationRef } from '../source/context.js'; +import type { SchemaResolver } from './resolver.js'; +import { value, type TypeEnvironment, type TypeValue } from './types.js'; + +export class ObjectTypes { + private readonly types = new Map(); + private readonly aliases = new Set(); + private readonly concrete = new WeakMap(); + private readonly bases = new Set(); + + constructor(private readonly resolver: SchemaResolver) {} + + declaration( + ref: DeclarationRef, + args: readonly ts.TypeNode[], + caller: ts.SourceFile, + env: TypeEnvironment, + origin: ts.TypeNode, + heritage = false, + ): TypeValue { + const node = ref.node; + + if ( + !ts.isInterfaceDeclaration(node) && + !ts.isTypeAliasDeclaration(node) && + !ts.isClassDeclaration(node) + ) { + fail(origin, 'Expected an interface, type alias or class schema.'); + } + + const concrete = !node.typeParameters?.length && ts.isSourceFile(node.parent); + const previous = concrete && this.concrete.get(node); + + if (previous && heritage && this.bases.has(previous.key)) { + fail(origin, 'Circular schema inheritance.'); + } + + if (previous) { + return previous; + } + + const local = this.resolver.arguments(node.typeParameters, args, caller, env, node); + + for (let scope = node.parent; scope; scope = scope.parent) { + if (!ts.isFunctionLike(scope) && !ts.isClassDeclaration(scope)) { + continue; + } + + for (const parameter of scope.typeParameters ?? []) { + const name = parameter.name.text; + + if (!local.has(name)) { + local.set(name, env.get(name) ?? this.resolver.parameter(name, scope)); + } + } + } + + const parameters = [...local.values()]; + const key = `${ref.source.fileName}:${node.pos}<${parameters.map((type) => type.key).join(',')}>`; + + if (heritage && this.bases.has(key)) { + fail(origin, 'Circular schema inheritance.'); + } + + if (heritage && this.bases.size >= 128) { + fail(origin, 'Schema inheritance exceeds 128 levels.'); + } + + const cached = this.types.get(key); + + if (cached) { + return cached; + } + + if (ts.isTypeAliasDeclaration(node)) { + if (ts.isTypeLiteralNode(node.type)) { + const result = this.object( + node.name.text + parameters.map((type) => '__' + type.name).join(''), + key, + ); + result.origin = { node: origin, source: caller, env: new Map(env) }; + + if (parameters.length) { + result.application = { declaration: node, arguments: parameters }; + } + + this.types.set(key, result); + + if (concrete) { + this.concrete.set(node, result); + } + + return this.members(node.type.members, result, ref.source, local); + } + + if (this.aliases.has(key)) { + fail(node, 'Circular type alias.'); + } + + this.aliases.add(key); + + try { + const result = this.resolver.type(node.type, ref.source, local); + this.types.set(key, result); + + if (concrete) { + this.concrete.set(node, result); + } + + return result; + } finally { + this.aliases.delete(key); + } + } + + const name = + (node.name?.text ?? 'Default') + parameters.map((type) => '__' + type.name).join(''); + const result = this.object(name, key); + result.dynamic = parameters.some((type) => type.dynamic); + + if (parameters.length) { + result.application = { declaration: node, arguments: parameters }; + } + + result.origin = { node: origin, source: caller, env: new Map(env) }; + this.types.set(key, result); + + if (concrete) { + this.concrete.set(node, result); + } + + this.bases.add(key); + + try { + for (const clause of node.heritageClauses ?? []) { + if (clause.token !== ts.SyntaxKind.ExtendsKeyword) { + continue; + } + + for (const base of clause.types) { + const declaration = this.resolver.context.reference( + base.expression, + ref.source, + true, + ); + + if (!declaration) { + fail(base, 'Unresolved base schema.'); + } + + this.merge( + result, + this.declaration( + declaration, + base.typeArguments ?? [], + ref.source, + local, + origin, + true, + ), + base, + ); + } + } + } finally { + this.bases.delete(key); + } + + return this.members(node.members, result, ref.source, local); + } + + members( + members: ts.NodeArray, + result: TypeValue, + source: ts.SourceFile, + env: TypeEnvironment, + ): TypeValue { + const fields = members.flatMap( + (member) => + ts.isConstructorDeclaration(member) + ? member.parameters.filter((parameter) => + parameter.modifiers?.some((modifier) => + [ + ts.SyntaxKind.PublicKeyword, + ts.SyntaxKind.PrivateKeyword, + ts.SyntaxKind.ProtectedKeyword, + ts.SyntaxKind.ReadonlyKeyword, + ].includes(modifier.kind), + ), + ) + : [member], + ); + + for (const member of fields) { + if ( + !ts.isPropertySignature(member) && + !ts.isPropertyDeclaration(member) && + !ts.isParameter(member) + ) { + continue; + } + + if ( + member.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword) + ) { + continue; + } + + if (!member.type || !member.name || ts.isComputedPropertyName(member.name)) { + fail(member, 'Schema fields require static names and explicit field markers.'); + } + + const name = + ts.isIdentifier(member.name) || + ts.isStringLiteral(member.name) || + ts.isNumericLiteral(member.name) + ? member.name.text + : fail(member, 'Unsupported field name.'); + const type = this.resolver.type(member.type, source, env); + result.fields!.set(name, { type, optional: !!member.questionToken, node: member }); + result.dynamic ||= type.dynamic; + } + + return result; + } + + merge(target: TypeValue, source: TypeValue, node: ts.Node): void { + if (!source.fields) { + fail(node, 'Schema intersections and bases must be object types.'); + } + + for (const [name, property] of source.fields) { + const existing = target.fields!.get(name); + + if (existing && existing.type.key !== property.type.key) { + fail(node, `Conflicting inherited field ${name}.`); + } + + target.fields!.set(name, property); + } + + target.dynamic ||= source.dynamic; + } + + object(name: string, key: string): TypeValue { + return { ...value('object', name, key), fields: new Map() }; + } +} diff --git a/packages/proton/src/schema/operators.ts b/packages/proton/src/schema/operators.ts new file mode 100644 index 00000000..240ffe2e --- /dev/null +++ b/packages/proton/src/schema/operators.ts @@ -0,0 +1,246 @@ +import ts from 'typescript'; +import { fail } from '../source/context.js'; +import type { SchemaResolver } from './resolver.js'; +import { assignable } from './relations.js'; +import { value, type TypeEnvironment, type TypeValue } from './types.js'; + +const utilities = new Set([ + 'Promise', + 'Awaited', + 'ReturnType', + 'Parameters', + 'InstanceType', + 'ConstructorParameters', + 'Extract', + 'Exclude', + 'Uppercase', + 'Lowercase', + 'Capitalize', + 'Uncapitalize', +]); + +function container(kind: TypeValue['kind'], values: TypeValue[]): TypeValue { + return { + kind, + values, + key: `${kind}<${values.map((type) => type.key)}>`, + name: kind, + dynamic: values.some((type) => type.dynamic), + }; +} + +export function resolveOperator( + node: ts.TypeNode, + source: ts.SourceFile, + env: TypeEnvironment, + resolver: SchemaResolver, +): TypeValue | undefined { + if ( + ts.isTypeReferenceNode(node) && + (!ts.isIdentifier(node.typeName) || !utilities.has(node.typeName.text)) + ) { + return; + } + + const resolve = (type: ts.TypeNode) => resolver.type(type, type.getSourceFile(), env); + + if (ts.isInferTypeNode(node)) { + return value('inference', node.typeParameter.name.text); + } + + if (ts.isTupleTypeNode(node)) { + return container( + 'tuple', + node.elements.map((type) => resolve(ts.isNamedTupleMember(type) ? type.type : type)), + ); + } + + if (ts.isOptionalTypeNode(node)) { + return container('union', [resolve(node.type), value('null', 'undefined')]); + } + + if (ts.isRestTypeNode(node)) { + return resolve(node.type); + } + + if (ts.isFunctionTypeNode(node) || ts.isConstructorTypeNode(node)) { + const local = new Map(env); + + for (const param of node.typeParameters ?? []) { + local.set(param.name.text, resolver.parameter(param.name.text, node)); + } + + const parameters = node.parameters.filter( + (param) => !ts.isIdentifier(param.name) || param.name.text !== 'this', + ); + return container(ts.isFunctionTypeNode(node) ? 'function' : 'constructor', [ + container( + 'tuple', + parameters.map((param) => + param.type + ? resolver.type(param.type, source, local) + : value('primitive', 'unknown'), + ), + ), + resolver.type(node.type, source, local), + ]); + } + + if (ts.isTypeQueryNode(node)) { + const ref = ts.isIdentifier(node.exprName) + ? resolver.context.lookup(node.exprName.text, node.exprName, source) + : resolver.context.typeName(node.exprName, source); + const declaration = ref?.node; + + if (declaration && (ts.isVariableDeclaration(declaration) || ts.isParameter(declaration))) { + if (declaration.type) { + return resolve(declaration.type); + } + + const initializer = declaration.initializer; + + if ( + initializer && + (ts.isAsExpression(initializer) || ts.isSatisfiesExpression(initializer)) + ) { + return resolve(initializer.type); + } + } + + if (declaration && ts.isFunctionDeclaration(declaration) && declaration.type) { + return container('function', [ + container( + 'tuple', + declaration.parameters.map((param) => + param.type ? resolve(param.type) : value('primitive', 'unknown'), + ), + ), + resolve(declaration.type), + ]); + } + + fail( + node, + 'Type queries used in schemas require an explicit variable or function return annotation.', + ); + } + + if (ts.isTemplateLiteralTypeNode(node)) { + let strings = [node.head.text]; + + for (const span of node.templateSpans) { + const type = resolve(span.type); + + if (type.dynamic) { + return resolver.defer(node, source, env); + } + + const options = type.kind === 'union' ? type.values! : [type]; + + if (options.some((type) => type.kind !== 'literal')) { + fail(node, 'Template schema keys require literal types.'); + } + + strings = strings.flatMap((prefix) => + options.map((type) => prefix + type.name + span.literal.text), + ); + + if (strings.length > 128) { + fail(node, 'Template type expansion exceeds 128 keys.'); + } + } + + const literals = strings.map((text) => value('literal', text, JSON.stringify(text))); + return literals.length === 1 ? literals[0] : container('union', literals); + } + + if (!ts.isTypeReferenceNode(node) || !ts.isIdentifier(node.typeName)) { + return; + } + + const name = node.typeName.text; + + if (!utilities.has(name) || resolver.context.typeName(node.typeName, source)) { + return; + } + + const args = node.typeArguments; + + if (!args?.length) { + fail(node, `${name} requires a type argument.`); + } + + const operand = resolve(args[0]); + + if (name === 'Promise') { + return container('promise', [operand]); + } + + if (operand.dynamic) { + return resolver.defer(node, source, env); + } + + if (name === 'Awaited') { + const unwrap = (type: TypeValue): TypeValue => + type.kind === 'promise' + ? unwrap(type.values![0]) + : type.kind === 'union' + ? container('union', type.values!.map(unwrap)) + : type; + return unwrap(operand); + } + + if (['ReturnType', 'Parameters', 'InstanceType', 'ConstructorParameters'].includes(name)) { + const expected = + name === 'InstanceType' || name === 'ConstructorParameters' + ? 'constructor' + : 'function'; + + if (operand.kind !== expected) { + fail(node, `${name} requires a ${expected} type.`); + } + + return operand.values![name.endsWith('Parameters') ? 0 : 1]; + } + + if (name === 'Extract' || name === 'Exclude') { + if (!args[1]) { + fail(node, `${name} requires two type arguments.`); + } + + const constraint = resolve(args[1]); + + if (constraint.dynamic) { + return resolver.defer(node, source, env); + } + + const selected = (operand.kind === 'union' ? operand.values! : [operand]).filter( + (type) => assignable(type, constraint) === (name === 'Extract'), + ); + return selected.length === 0 + ? value('primitive', 'never') + : selected.length === 1 + ? selected[0] + : container('union', selected); + } + + const transform = (type: TypeValue): TypeValue => { + if (type.kind !== 'literal' || !/^["']/.test(type.key)) { + fail(node, `${name} requires literal string keys.`); + } + + const text = + name === 'Uppercase' + ? type.name.toUpperCase() + : name === 'Lowercase' + ? type.name.toLowerCase() + : (name === 'Capitalize' + ? (type.name[0] ?? '').toUpperCase() + : (type.name[0] ?? '').toLowerCase()) + type.name.slice(1); + return value('literal', text, JSON.stringify(text)); + }; + + return operand.kind === 'union' + ? container('union', operand.values!.map(transform)) + : transform(operand); +} diff --git a/packages/proton/src/schema/relations.ts b/packages/proton/src/schema/relations.ts new file mode 100644 index 00000000..faaeafdf --- /dev/null +++ b/packages/proton/src/schema/relations.ts @@ -0,0 +1,137 @@ +import type { TypeValue } from './types.js'; + +export function assignable( + source: TypeValue, + target: TypeValue, + seen = new Set(), +): boolean { + if ( + source.key === target.key || + target.name === 'unknown' || + target.name === 'any' || + source.name === 'never' + ) { + return true; + } + + if (target.name === 'object') { + return ( + !!source.fields || + ['array', 'tuple', 'function', 'constructor', 'promise'].includes(source.kind) + ); + } + + const key = `${source.key}:${target.key}`; + + if (seen.has(key)) { + return true; + } + + seen.add(key); + + if (source.kind === 'marker') { + return assignable(source.values![0], target, seen); + } + + if (target.kind === 'marker') { + return assignable(source, target.values![0], seen); + } + + if (source.kind === 'union') { + return source.values!.every((type) => assignable(type, target, new Set(seen))); + } + + if (target.kind === 'union') { + return target.values!.some((type) => assignable(source, type, new Set(seen))); + } + + if (source.kind === target.kind && source.values && target.values) { + return ( + source.values.length === target.values.length && + source.values.every((type, index) => assignable(type, target.values![index], seen)) + ); + } + + if (source.fields && target.fields) { + return [...target.fields].every(([name, field]) => { + const actual = source.fields!.get(name); + return actual + ? (field.optional || !actual.optional) && assignable(actual.type, field.type, seen) + : field.optional; + }); + } + + if (target.kind === 'primitive' && source.kind === 'literal') { + return target.name === 'string' + ? /^["']/.test(source.key) + : target.name === 'number' + ? !Number.isNaN(Number(source.name)) + : target.name === 'bool' && /^(true|false)$/.test(source.name); + } + + if (target.name === 'number') { + return /^(?:u?int_32|sint_32|s?fixed_32|float|double)$/.test(source.name); + } + + if (target.name === 'bigint') { + return /^(?:u?int_64|sint_64|s?fixed_64)$/.test(source.name); + } + + return false; +} + +export function matchInferred( + source: TypeValue, + pattern: TypeValue, + inferred: Map, + seen = new Set(), +): boolean { + if (pattern.kind === 'inference') { + const previous = inferred.get(pattern.name); + + if (previous && previous.key !== source.key) { + return false; + } + + inferred.set(pattern.name, source); + return true; + } + + const key = `${source.key}:${pattern.key}`; + + if (seen.has(key)) { + return true; + } + + seen.add(key); + + if (source.kind === 'function' && pattern.kind === 'function') { + const args = pattern.values![0].values!; + const variadicAny = + args.length === 1 && args[0].kind === 'array' && args[0].values![0].name === 'any'; + return ( + (variadicAny || matchInferred(source.values![0], pattern.values![0], inferred, seen)) && + matchInferred(source.values![1], pattern.values![1], inferred, seen) + ); + } + + if (source.fields && pattern.fields) { + return [...pattern.fields].every(([name, property]) => { + const actual = source.fields!.get(name); + return actual + ? matchInferred(actual.type, property.type, inferred, seen) + : property.optional; + }); + } + + if (source.kind === pattern.kind && source.values && pattern.values) { + return ( + source.values.length === pattern.values.length && + source.values.every((type, index) => + matchInferred(type, pattern.values![index], inferred, seen), + ) + ); + } + + return assignable(source, pattern); +} diff --git a/packages/proton/src/schema/resolver.ts b/packages/proton/src/schema/resolver.ts new file mode 100644 index 00000000..0e447a33 --- /dev/null +++ b/packages/proton/src/schema/resolver.ts @@ -0,0 +1,600 @@ +import { packageName } from '../package.js'; +import ts from 'typescript'; +import { SourceContext, fail, runtimeImportName } from '../source/context.js'; +import { PRIMITIVE_TYPE_MAP } from '../codegen/model.js'; + +import { value, type TypeEnvironment, type TypeValue } from './types.js'; +import { MessageBuilder } from './message.js'; +import { matchInferred } from './relations.js'; +import { resolveOperator } from './operators.js'; +import { ObjectTypes } from './objects.js'; + +const primitiveNames = new Set(Object.keys(PRIMITIVE_TYPE_MAP)); + +/** Lazily resolves only types reached by codec calls; no project-wide type checker. */ +export class SchemaResolver { + private readonly messages = new MessageBuilder(); + readonly registry = this.messages.registry; + private readonly objects = new ObjectTypes(this); + private depth = 0; + private readonly resolvedLazy = new WeakMap(); + + constructor(readonly context: SourceContext) {} + + parameter(name: string, owner: ts.Node): TypeValue { + return value('parameter', name, `${owner.getSourceFile().fileName}:${owner.pos}:${name}`); + } + + substitute(type: TypeValue, bindings: Map): TypeValue { + if (type.kind === 'lazy') { + const { node, source, env } = type.origin!; + return this.lazy( + node, + source, + new Map([...env].map(([name, val]) => [name, this.substitute(val, bindings)])), + ); + } + + if (!type.dynamic) { + return type; + } + + if (type.kind === 'parameter') { + return bindings.get(type.key) ?? type; + } + + if (type.origin) { + const { node, source, env } = type.origin; + return this.type( + node, + source, + new Map([...env].map(([name, val]) => [name, this.substitute(val, bindings)])), + ); + } + + return type; + } + + type( + node: ts.TypeNode, + source = node.getSourceFile(), + env: TypeEnvironment = new Map(), + ): TypeValue { + if (++this.depth > 128) { + this.depth--; + return fail( + node, + 'Type expansion exceeds 128 levels (possibly an expanding recursive generic).', + ); + } + + try { + const result = this.resolve(node, source, env); + + if (result.dynamic && result.kind !== 'parameter' && !result.origin) { + result.origin = { node, source, env: new Map(env) }; + } + + return result; + } finally { + this.depth--; + } + } + + arguments( + params: readonly ts.TypeParameterDeclaration[] | undefined, + args: readonly ts.TypeNode[] | undefined, + source: ts.SourceFile, + outer: TypeEnvironment, + declaration: ts.Node, + lazy = false, + ): TypeEnvironment { + const result = new Map(); + + if ((args?.length ?? 0) > (params?.length ?? 0)) { + fail(declaration, 'Too many generic type arguments.'); + } + + for (let i = 0; i < (params?.length ?? 0); i++) { + const param = params![i]; + const arg = args?.[i]; + const resolved = arg + ? lazy + ? this.lazy(arg, source, outer) + : this.type(arg, source, outer) + : param.default + ? lazy + ? this.lazy(param.default, declaration.getSourceFile(), result) + : this.type(param.default, declaration.getSourceFile(), result) + : undefined; + + if (!resolved) { + fail(declaration, `Missing concrete type argument for ${param.name.text}.`); + } + + result.set(param.name.text, resolved); + } + + return result; + } + + message(type: TypeValue, node: ts.Node): string { + return this.messages.build(this.materialize(type), node); + } + + /** Receiver discovery carries application types without expanding them until + * a protobuf requirement actually consumes the binding. */ + lazy(node: ts.TypeNode, source: ts.SourceFile, env: TypeEnvironment): TypeValue { + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) { + const bound = env.get(node.typeName.text); + + if (bound) { + return bound; + } + + if (primitiveNames.has(node.typeName.text)) { + return this.type(node, source, env); + } + } + + const mentionsParameter = (child: ts.Node): boolean => + (ts.isIdentifier(child) && env.get(child.text)?.dynamic === true) || + (ts.forEachChild(child, mentionsParameter) ?? false); + + return { + ...value( + 'lazy', + node.getText(source), + `lazy:${source.fileName}:${node.getText(source)}<${[...env.values()].map((v) => v.key)}>`, + ), + dynamic: mentionsParameter(node), + origin: { node, source, env: new Map(env) }, + }; + } + + private materialize(type: TypeValue): TypeValue { + if (type.kind !== 'lazy') { + return type; + } + + const cached = this.resolvedLazy.get(type); + + if (cached) { + return cached; + } + + const { node, source, env } = type.origin!; + const resolved = this.type(node, source, env); + this.resolvedLazy.set(type, resolved); + return resolved; + } + + private resolve(node: ts.TypeNode, source: ts.SourceFile, env: TypeEnvironment): TypeValue { + if (ts.isTypeReferenceNode(node)) { + return this.reference(node, source, env); + } + + const operator = resolveOperator(node, source, env, this); + + if (operator) { + return operator; + } + + if (ts.isParenthesizedTypeNode(node)) { + return this.type(node.type, source, env); + } + + if (node.kind === ts.SyntaxKind.StringKeyword) { + return value('primitive', 'string'); + } + + if (node.kind === ts.SyntaxKind.BooleanKeyword) { + return value('primitive', 'bool'); + } + + if ( + [ + ts.SyntaxKind.ObjectKeyword, + ts.SyntaxKind.NumberKeyword, + ts.SyntaxKind.BigIntKeyword, + ts.SyntaxKind.AnyKeyword, + ts.SyntaxKind.UnknownKeyword, + ts.SyntaxKind.NeverKeyword, + ].includes(node.kind) + ) { + return value('primitive', node.getText(source)); + } + + if ( + node.kind === ts.SyntaxKind.UndefinedKeyword || + node.kind === ts.SyntaxKind.VoidKeyword + ) { + return value('null', 'undefined'); + } + + if (ts.isLiteralTypeNode(node)) { + if (node.literal.kind === ts.SyntaxKind.NullKeyword) { + return value('null', 'null'); + } + + if (ts.isStringLiteral(node.literal)) { + return value('literal', node.literal.text, JSON.stringify(node.literal.text)); + } + + return value('literal', node.literal.getText(source)); + } + + if (ts.isArrayTypeNode(node)) { + return this.container( + 'array', + [this.type(node.elementType, source, env)], + node, + source, + env, + ); + } + + if (ts.isUnionTypeNode(node)) { + const members = [ + ...new Map( + node.types + .flatMap((item) => { + const type = this.type(item, source, env); + return type.kind === 'union' ? type.values! : [type]; + }) + .map((item) => [item.key, item]), + ).values(), + ]; + return members.length === 1 + ? members[0] + : this.container('union', members, node, source, env); + } + + if (ts.isIntersectionTypeNode(node)) { + const members = node.types.map((item) => this.type(item, source, env)); + + if (members.some((item) => item.dynamic && item.kind !== 'object')) { + return this.defer(node, source, env); + } + + const result = this.objects.object( + 'Intersection', + members.map((item) => item.key).join('&'), + ); + + for (const member of members) { + this.objects.merge(result, member, node); + } + + return result; + } + + if (ts.isTypeLiteralNode(node)) { + return this.objects.members( + node.members, + this.objects.object( + 'Anonymous', + `${source.fileName}:${node.pos}<${[...env.values()].map((type) => type.key)}>`, + ), + source, + env, + ); + } + + if (ts.isTypeOperatorNode(node)) { + const operand = this.type(node.type, source, env); + + if (node.operator === ts.SyntaxKind.ReadonlyKeyword) { + return operand; + } + + if (operand.dynamic && !operand.fields) { + return this.defer(node, source, env); + } + + if (node.operator === ts.SyntaxKind.KeyOfKeyword && operand.fields) { + return this.container( + 'union', + [...operand.fields.keys()].map((key) => + value('literal', key, JSON.stringify(key)), + ), + node, + source, + env, + ); + } + } + + if (ts.isIndexedAccessTypeNode(node)) { + const object = this.type(node.objectType, source, env); + const index = this.type(node.indexType, source, env); + + if (object.dynamic || index.dynamic) { + return this.defer(node, source, env); + } + + const keys = index.kind === 'union' ? index.values! : [index]; + const values = keys.map( + (key) => + object.fields?.get(key.name)?.type ?? + (object.kind === 'tuple' + ? object.values?.[Number(key.name)] + : object.kind === 'array' + ? object.values?.[0] + : undefined) ?? + fail(node, `Unknown indexed property ${key.name}.`), + ); + return values.length === 1 + ? values[0] + : this.container('union', values, node, source, env); + } + + if (ts.isConditionalTypeNode(node)) { + const check = this.type(node.checkType, source, env); + const constraint = this.type(node.extendsType, source, env); + + if (check.dynamic || constraint.dynamic) { + return this.defer(node, source, env); + } + + if ( + check.kind === 'union' && + ts.isTypeReferenceNode(node.checkType) && + ts.isIdentifier(node.checkType.typeName) && + env.has(node.checkType.typeName.text) + ) { + const results = check.values!.map((type) => + this.type( + node, + source, + new Map(env).set( + (node.checkType as ts.TypeReferenceNode).typeName.getText(source), + type, + ), + ), + ); + const distinct = [...new Map(results.map((type) => [type.key, type])).values()]; + return distinct.length === 1 + ? distinct[0] + : this.container('union', distinct, node, source, env); + } + + const inferred = new Map(); + const matches = matchInferred(check, constraint, inferred); + return this.type( + matches ? node.trueType : node.falseType, + source, + new Map([...env, ...inferred]), + ); + } + + if (ts.isMappedTypeNode(node) && node.type && node.typeParameter.constraint) { + const keys = this.type(node.typeParameter.constraint, source, env); + + if (keys.dynamic) { + return this.defer(node, source, env); + } + + const result = this.objects.object( + 'Mapped', + `${source.fileName}:${node.pos}<${[...env.values()].map((v) => v.key)}>`, + ); + + for (const key of keys.kind === 'union' ? keys.values! : [keys]) { + const local = new Map(env).set(node.typeParameter.name.text, key); + const remapped = node.nameType ? this.type(node.nameType, source, local) : key; + + if (remapped.name === 'never') { + continue; + } + + const inherited = ts.isIndexedAccessTypeNode(node.type) + ? (this.type(node.type.objectType, source, local).fields?.get(key.name) + ?.optional ?? false) + : false; + const optional = node.questionToken + ? node.questionToken.kind !== ts.SyntaxKind.MinusToken + : inherited; + + for (const name of remapped.kind === 'union' ? remapped.values! : [remapped]) { + result.fields!.set(name.name, { + type: this.type(node.type, source, local), + optional, + node, + }); + } + } + + return result; + } + + fail(node, `Unsupported or ambiguous type expression ${node.getText(source)}.`); + } + + private reference( + node: ts.TypeReferenceNode, + source: ts.SourceFile, + env: TypeEnvironment, + ): TypeValue { + const simple = ts.isIdentifier(node.typeName) ? node.typeName.text : undefined; + + if (simple && env.has(simple)) { + return this.materialize(env.get(simple)!); + } + + const operator = resolveOperator(node, source, env, this); + + if (operator) { + return operator; + } + + const ref = this.context.typeName(node.typeName, source); + let name = simple + ? (ref && runtimeImportName(ref.node)) || simple + : node.typeName.getText(source); + + if (ts.isQualifiedName(node.typeName) && ts.isIdentifier(node.typeName.left)) { + const namespace = this.context.lookup(node.typeName.left.text, node, source, true); + + if ( + namespace && + ts.isNamespaceImport(namespace.node) && + (namespace.node.parent.parent.moduleSpecifier as ts.StringLiteral).text === + packageName + ) { + name = node.typeName.right.text; + } + } + + const args = node.typeArguments ?? []; + + if ( + ref && + (ts.isImportSpecifier(ref.node) || ts.isImportClause(ref.node)) && + !runtimeImportName(ref.node) + ) { + fail(node, `Unresolved imported type ${name}.`); + } + + if ( + ref && + !runtimeImportName(ref.node) && + !ts.isImportSpecifier(ref.node) && + !ts.isNamespaceImport(ref.node) + ) { + return this.objects.declaration(ref, args, source, env, node); + } + + if (primitiveNames.has(name)) { + return value('primitive', name); + } + + if (name === 'pb' || name === 'pb_repeated' || name === 'pb_optional') { + if (args.length !== 2) { + fail(node, `${name} requires a field number and a field type.`); + } + + const fieldNumber = this.type(args[0], source, env); + const payload = this.type(args[1], source, env); + const marker = this.container('marker', [payload], node, source, env); + return { + ...marker, + key: `${name}:${marker.key}:${fieldNumber.key}`, + dynamic: fieldNumber.dynamic || marker.dynamic, + fieldNumber: Number(fieldNumber.name), + repeated: name === 'pb_repeated', + explicitPresence: name === 'pb_optional', + }; + } + + if (name === 'Array' || name === 'ReadonlyArray') { + return this.container('array', [this.type(args[0], source, env)], node, source, env); + } + + if (['Partial', 'Required', 'Readonly', 'Pick', 'Omit', 'NonNullable'].includes(name)) { + const operand = this.type(args[0], source, env); + + if (operand.dynamic) { + return this.defer(node, source, env); + } + + if (name === 'Readonly') { + return operand; + } + + if (name === 'NonNullable') { + const members = + operand.kind === 'union' + ? operand.values!.filter((item) => item.kind !== 'null') + : [operand]; + return members.length === 1 + ? members[0] + : this.container('union', members, node, source, env); + } + + if (!operand.fields) { + fail(node, `${name} requires an object type.`); + } + + const keys = args[1] ? this.type(args[1], source, env) : undefined; + const selected = new Set( + keys ? (keys.kind === 'union' ? keys.values! : [keys]).map((key) => key.name) : [], + ); + + if (name === 'Pick') { + for (const key of selected) { + if (!operand.fields.has(key)) { + fail(node, `Unknown Pick property ${key}.`); + } + } + } + + const result = this.objects.object( + `${name}__${operand.name}`, + `${name}<${operand.key},${keys?.key ?? ''}>`, + ); + + for (const [key, property] of operand.fields) { + if ( + (name === 'Pick' && !selected.has(key)) || + (name === 'Omit' && selected.has(key)) + ) { + continue; + } + + result.fields!.set(key, { + ...property, + optional: name === 'Partial' || (name !== 'Required' && property.optional), + }); + } + + return result; + } + + if (ref) { + return this.objects.declaration(ref, args, source, env, node); + } + + fail(node, `Unresolved type ${name}.`); + } + + defer(node: ts.TypeNode, source: ts.SourceFile, env: TypeEnvironment): TypeValue { + return { + ...value( + 'deferred', + node.getText(source), + `${source.fileName}:${node.pos}<${[...env.values()].map((v) => v.key)}>`, + ), + dynamic: true, + origin: { node, source, env: new Map(env) }, + }; + } + private container( + kind: TypeValue['kind'], + values: TypeValue[], + node: ts.TypeNode, + source: ts.SourceFile, + env: TypeEnvironment, + ): TypeValue { + if (kind === 'union') { + values = values.filter((type) => type.name !== 'never'); + + if (!values.length) { + return value('primitive', 'never'); + } + + if (values.length === 1) { + return values[0]; + } + } + + return { + kind, + name: values.map((type) => type.name).join('__'), + key: `${kind}<${JSON.stringify(values.map((type) => type.key))}>`, + values, + dynamic: values.some((type) => type.dynamic), + origin: { node, source, env: new Map(env) }, + }; + } +} diff --git a/packages/proton/src/schema/types.ts b/packages/proton/src/schema/types.ts new file mode 100644 index 00000000..7ecb342e --- /dev/null +++ b/packages/proton/src/schema/types.ts @@ -0,0 +1,38 @@ +import type ts from 'typescript'; + +export interface TypeValue { + kind: + | 'primitive' + | 'literal' + | 'null' + | 'parameter' + | 'object' + | 'marker' + | 'union' + | 'array' + | 'tuple' + | 'function' + | 'constructor' + | 'promise' + | 'inference' + | 'lazy' + | 'deferred'; + key: string; + name: string; + dynamic: boolean; + fields?: Map; + values?: TypeValue[]; + fieldNumber?: number; + repeated?: boolean; + explicitPresence?: boolean; + origin?: { node: ts.TypeNode; source: ts.SourceFile; env: TypeEnvironment }; + application?: { declaration: ts.Declaration; arguments: TypeValue[] }; +} +export type TypeEnvironment = Map; + +export const value = (kind: TypeValue['kind'], name: string, key = name): TypeValue => ({ + kind, + key, + name, + dynamic: kind === 'parameter', +}); diff --git a/packages/proton/src/source/context.ts b/packages/proton/src/source/context.ts new file mode 100644 index 00000000..93647789 --- /dev/null +++ b/packages/proton/src/source/context.ts @@ -0,0 +1,423 @@ +import { packageName } from '../package.js'; +import ts from 'typescript'; +import { readFileSync, statSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; + +export interface DeclarationRef { + node: ts.Declaration; + source: ts.SourceFile; +} + +export function runtimeImportName(node: ts.Declaration): string | undefined { + const declaration = ts.isImportSpecifier(node) + ? node.parent.parent.parent + : ts.isExportSpecifier(node) + ? node.parent.parent + : undefined; + + if ( + declaration?.moduleSpecifier && + ts.isStringLiteral(declaration.moduleSpecifier) && + declaration.moduleSpecifier.text === packageName + ) { + return ( + (node as ts.ImportSpecifier | ts.ExportSpecifier).propertyName?.text ?? + (node as ts.ImportSpecifier | ts.ExportSpecifier).name.text + ); + } + + return; +} + +const extensions = ['.ts', '.tsx', '.mts', '.cts', '/index.ts', '/index.tsx']; +export const normalizePath = (path: string): string => resolve(path).replace(/\\/g, '/'); + +/** One parse per source revision, shared by schema and generic-call analysis. */ +export class SourceContext { + readonly files = new Map(); + revision = 0; + private readonly modules = new Map(); + private readonly names = new WeakMap>(); + private readonly typeNames = new WeakMap>(); + private readonly options = new Map(); + + clear(): void { + this.files.clear(); + this.modules.clear(); + this.options.clear(); + } + + source(path: string, code?: string): ts.SourceFile { + const key = normalizePath(path); + const cached = this.files.get(key); + + if (cached && (code === undefined || cached.text === code)) { + return cached; + } + + if (cached) { + this.revision++; + } + + const source = ts.createSourceFile( + key, + code ?? readFileSync(key, 'utf8'), + ts.ScriptTarget.Latest, + true, + ); + this.files.set(key, source); + return source; + } + + module(specifier: string, source: ts.SourceFile): ts.SourceFile | undefined { + if (specifier === packageName) { + return; + } + + const key = `${source.fileName}:${specifier}`; + let path = this.modules.get(key); + + if (path === undefined) { + if (specifier.startsWith('.')) { + const base = normalizePath(resolve(dirname(source.fileName), specifier)); + const stem = base.replace(/\.(?:mjs|cjs|js)$/, ''); + path = + [base, ...extensions.map((ext) => stem + ext)].find((candidate) => { + try { + return statSync(candidate).isFile(); + } catch { + return false; + } + }) ?? null; + } else { + const directory = dirname(source.fileName); + let options = this.options.get(directory); + + if (!options) { + const config = ts.findConfigFile(directory, ts.sys.fileExists); + options = config ? this.options.get(config) : undefined; + options ??= config + ? ts.parseJsonConfigFileContent( + ts.readConfigFile(config, ts.sys.readFile).config, + { ...ts.sys, readDirectory: () => [] }, + dirname(config), + ).options + : {}; + + if (config) { + this.options.set(config, options); + } + + this.options.set(directory, options); + } + + path = + ts.resolveModuleName(specifier, source.fileName, options, ts.sys).resolvedModule + ?.resolvedFileName ?? null; + } + + this.modules.set(key, path); + } + + return path ? this.source(path) : undefined; + } + + lookup( + name: string, + location: ts.Node, + source = location.getSourceFile(), + typeOnly = false, + ): DeclarationRef | undefined { + for (let scope: ts.Node | undefined = location; scope; scope = scope.parent) { + if (!typeOnly && ts.isFunctionLike(scope)) { + const parameter = scope.parameters.find( + (param) => ts.isIdentifier(param.name) && param.name.text === name, + ); + + if (parameter) { + return { node: parameter, source }; + } + + for (const param of scope.parameters) { + if (!ts.isObjectBindingPattern(param.name)) { + continue; + } + + const element = param.name.elements.find( + (element) => ts.isIdentifier(element.name) && element.name.text === name, + ); + + if (element) { + return { node: element, source }; + } + } + } + + if (!ts.isSourceFile(scope) && !ts.isBlock(scope) && !ts.isModuleBlock(scope)) { + continue; + } + + const declaration = this.declarations(scope, typeOnly).get(name); + + if (declaration) { + return this.follow(declaration, source, new Set(), typeOnly); + } + } + + const declaration = this.declarations(source, typeOnly).get(name); + return declaration ? this.follow(declaration, source, new Set(), typeOnly) : undefined; + } + + typeName(name: ts.EntityName, source: ts.SourceFile): DeclarationRef | undefined { + return this.reference(name, source, true); + } + + reference( + name: ts.EntityName | ts.Expression, + source: ts.SourceFile, + typeOnly = false, + ): DeclarationRef | undefined { + if (ts.isIdentifier(name)) { + return this.lookup(name.text, name, source, typeOnly); + } + + if (!ts.isQualifiedName(name) && !ts.isPropertyAccessExpression(name)) { + return; + } + + const left = this.reference( + ts.isQualifiedName(name) ? name.left : name.expression, + source, + typeOnly, + ); + const right = ts.isQualifiedName(name) ? name.right : name.name; + + if (!left) { + return; + } + + if (ts.isNamespaceImport(left.node)) { + const declaration = left.node.parent.parent; + const imported = this.module( + (declaration.moduleSpecifier as ts.StringLiteral).text, + left.source, + ); + return imported ? this.exported(right.text, imported, new Set(), typeOnly) : undefined; + } + + if ( + ts.isModuleDeclaration(left.node) && + left.node.body && + ts.isModuleBlock(left.node.body) + ) { + const declaration = this.declarations(left.node.body, typeOnly).get(right.text); + return declaration ? { node: declaration, source: left.source } : undefined; + } + + return; + } + + private declarations( + scope: ts.SourceFile | ts.Block | ts.ModuleBlock, + typeOnly = false, + ): Map { + const cache = typeOnly ? this.typeNames : this.names; + let names = cache.get(scope); + + if (names) { + return names; + } + + names = new Map(); + + for (const statement of scope.statements) { + if (ts.isVariableStatement(statement)) { + if (typeOnly) { + continue; + } + + for (const declaration of statement.declarationList.declarations) { + if (ts.isIdentifier(declaration.name)) { + names.set(declaration.name.text, declaration); + } else if (ts.isObjectBindingPattern(declaration.name)) { + for (const element of declaration.name.elements) { + if (ts.isIdentifier(element.name)) { + names.set(element.name.text, element); + } + } + } + } + } else if (ts.isImportDeclaration(statement)) { + const clause = statement.importClause; + + if (clause?.name) { + names.set(clause.name.text, clause); + } + + const bindings = clause?.namedBindings; + + if (bindings && ts.isNamedImports(bindings)) { + for (const binding of bindings.elements) { + names.set(binding.name.text, binding); + } + } else if (bindings) { + names.set(bindings.name.text, bindings); + } + } else if ( + 'name' in statement && + statement.name && + ts.isIdentifier(statement.name as ts.Node) + ) { + if (typeOnly && ts.isFunctionDeclaration(statement)) { + continue; + } + + if ( + !typeOnly && + (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) + ) { + continue; + } + + names.set( + (statement.name as ts.Identifier).text, + statement as unknown as ts.Declaration, + ); + } + } + + cache.set(scope, names); + return names; + } + + private follow( + node: ts.Declaration, + source: ts.SourceFile, + seen: Set, + typeOnly = false, + ): DeclarationRef | undefined { + if (seen.has(node)) { + return; + } + + seen.add(node); + + if (ts.isImportSpecifier(node)) { + const declaration = node.parent.parent.parent; + const imported = this.module( + (declaration.moduleSpecifier as ts.StringLiteral).text, + source, + ); + + if (imported) { + return this.exported( + (node.propertyName ?? node.name).text, + imported, + seen, + typeOnly, + ); + } + } else if (ts.isImportClause(node)) { + const imported = this.module( + (node.parent.moduleSpecifier as ts.StringLiteral).text, + source, + ); + + if (imported) { + return this.exported('default', imported, seen, typeOnly); + } + } + + return { node, source }; + } + + exported( + name: string, + source: ts.SourceFile, + seen = new Set(), + typeOnly = false, + ): DeclarationRef | undefined { + const local = this.declarations(source, typeOnly).get(name); + + if (local) { + return this.follow(local, source, seen, typeOnly); + } + + for (const statement of source.statements) { + if (name === 'default') { + if ( + (ts.isClassDeclaration(statement) || + ts.isFunctionDeclaration(statement) || + ts.isInterfaceDeclaration(statement)) && + statement.modifiers?.some( + (modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword, + ) + ) { + return { node: statement, source }; + } + + if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) { + return this.lookup( + statement.expression.text, + statement.expression, + source, + typeOnly, + ); + } + } + + if (!ts.isExportDeclaration(statement) || seen.has(statement)) { + continue; + } + + seen.add(statement); + const imported = + statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) + ? this.module(statement.moduleSpecifier.text, source) + : source; + + if (!imported) { + if (statement.exportClause && ts.isNamedExports(statement.exportClause)) { + const element = statement.exportClause.elements.find( + (element) => element.name.text === name, + ); + + if (element && runtimeImportName(element)) { + return { node: element, source }; + } + } + + continue; + } + + if (!statement.exportClause) { + const ref = this.exported(name, imported, seen, typeOnly); + + if (ref) { + return ref; + } + } else if (ts.isNamedExports(statement.exportClause)) { + const element = statement.exportClause.elements.find((el) => el.name.text === name); + + if (element) { + return this.exported( + (element.propertyName ?? element.name).text, + imported, + seen, + typeOnly, + ); + } + } + } + + return; + } +} + +export function fail(node: ts.Node, message: string): never { + const source = node.getSourceFile(); + const position = source.getLineAndCharacterOfPosition(node.getStart(source)); + throw new Error( + `[${packageName}] ${source.fileName}:${position.line + 1}:${position.character + 1}: ${message}`, + ); +} diff --git a/packages/proton/src/source/entries.ts b/packages/proton/src/source/entries.ts new file mode 100644 index 00000000..75611bb8 --- /dev/null +++ b/packages/proton/src/source/entries.ts @@ -0,0 +1,43 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { ResolvedConfig } from 'vite'; + +export function buildEntries(config: ResolvedConfig): string[] { + const input = + config.build.rolldownOptions.input ?? + (config.build.lib && config.build.lib.entry) ?? + 'index.html'; + const files = + typeof input === 'string' ? [input] : Array.isArray(input) ? input : Object.values(input); + return files.flatMap((file) => { + const path = resolve(config.root, file); + + if (!existsSync(path)) { + return []; + } + + if (/\.[cm]?[jt]sx?$/.test(path)) { + return [path]; + } + + if (!path.endsWith('.html')) { + return []; + } + + return [ + ...readFileSync(path, 'utf8').matchAll( + /]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi, + ), + ].flatMap(([, src]) => { + if (/^(?:[a-z]+:)?\/\//i.test(src)) { + return []; + } + + const entry = resolve( + src.startsWith('/') ? config.root : resolve(path, '..'), + src.replace(/^\//, '').split('?')[0], + ); + return /\.[cm]?[jt]sx?$/.test(entry) && existsSync(entry) ? [entry] : []; + }); + }); +} diff --git a/packages/proton/src/transform/replacer.ts b/packages/proton/src/transform/replacer.ts deleted file mode 100644 index 5eae95e0..00000000 --- a/packages/proton/src/transform/replacer.ts +++ /dev/null @@ -1,79 +0,0 @@ -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); -} diff --git a/packages/proton/test/__tests__/analyzer.test.ts b/packages/proton/test/__tests__/analyzer.test.ts deleted file mode 100644 index bd0ad8cb..00000000 --- a/packages/proton/test/__tests__/analyzer.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -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>` previously - // resolved the field's typeName to the bare identifier `"Wrapper"` and - // never enqueued `Wrapper` 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>` — - // 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`, 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({} 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, - }); - }); -}); diff --git a/packages/proton/test/__tests__/compatibility.test.ts b/packages/proton/test/__tests__/compatibility.test.ts new file mode 100644 index 00000000..12d21652 --- /dev/null +++ b/packages/proton/test/__tests__/compatibility.test.ts @@ -0,0 +1,242 @@ +import { describe, expect, it } from 'vitest'; +import { run, imports } from '../upstream/compile'; +import { bundle } from '../upstream/project'; +import { schemaCodecs, schemaRegistry } from '../upstream/schema'; +import { generateCode } from '../../src/codegen/generator'; +import { protobuf_getUnknownFields } from '../../src/runtime'; +import { ProtobufCompiler } from '../../src/compiler/compiler'; +import { withProject } from '../upstream/project'; +import { join } from 'node:path'; + +describe('SnowLuma compatibility', () => { + it('leaves generic data unions and nested business types outside codec discovery', () => { + expect( + run(` + type Json = string | Json[]; + interface Field {value:T; metadata:Json;} + type Wrapper = Field & { extra?:Json }; + function identity(value:Field) {return value;} + function generic(field:Field>) {return identity(field);} + function result(ok:boolean, value:T) {if(ok) return {ok:true, value}; return {ok:false, value};} + const field:Field> = {value:{value:'ok', metadata:[]}, metadata:[]}; + export const output = result(true, generic(field)).value.value.value; + `).output, + ).toBe('ok'); + }); + + it('keeps unrelated callback aliases and inferred containers lazy', () => { + expect( + run(` + type Json = string | Json[]; + type Handler = (value:T) => void; + interface Field {value:T; metadata:Json;} + const field:Field = {value:'ok', metadata:[]}; + function wrap(value:Field) {return {get(){return value.value;}};} + const handler:Handler = (value) => {}; + handler('x'); + export const result = wrap(field).get(); + `).result, + ).toBe('ok'); + }); + + it('propagates composite class bindings through generic factories', () => { + expect( + run(` + interface Box { value:pb<1,T>; } + class Codec { encode(value:T) { return protobuf_encode(value); } } + function create() { return new Codec>(); } + export const result = [...create().encode({value:7})]; + `).result, + ).toEqual([8, 7]); + }); + + it('defers unrelated class type arguments but validates codec class schemas', () => { + expect( + run(` + type Json = string | Json[]; + class Field { value(): null { return null; } } + function field() { return new Field(); } + export const result = field().value(); + `).result, + ).toBeNull(); + expect(() => + run(` + class Codec { encode(value:T) {return protobuf_encode(value);} } + new Codec().encode({}); + `), + ).toThrow(/Unresolved type Missing/); + }); + + it('infers matching generic containers without expanding unrelated recursive data', () => { + expect( + run(` + type Json = string | Json[]; + interface Field { value: T; metadata: Json; } + function arrayField(field: Field) { return Object.assign({}, { get: () => field.value }); } + function wrap(field: Field) { return arrayField(field); } + const field: Field = { value:'ok', metadata:[] }; + export const result = wrap(field).get(); + `).result, + ).toBe('ok'); + }); + + it('does not resolve recursive data aliases while looking for class receivers', () => { + expect( + run(` + type Data = { children: T[]; name: string }; + type Element = Data; + type Wrapped = T; + function data(): Wrapped { return { children: [], name: 'ok' }; } + export const result = data().name.toUpperCase(); + `).result, + ).toBe('OK'); + }); + + it('does not resolve ordinary generic return values or data alias members as callbacks', () => { + expect( + run(` + type Id = T; + interface Data { value: string; children: Id[]; } + const data: Id = {value:'ok', children:[]}; + function decode(raw: Uint8Array, callback: () => T): T | null { return callback(); } + const raw: Uint8Array = new Uint8Array(); + const decoded = decode(raw, () => data); + export const result = [decoded.value, data.value]; + `).result, + ).toEqual(['ok', 'ok']); + }); + + it('does not specialize ambient library functions', async () => { + const source = `import { expect } from './external'; + const data: Record = {}; + expect(data).check();`; + await withProject( + { + 'external.d.ts': 'export declare function expect(value: T): { check(): void };', + 'entry.ts': source, + }, + (directory) => { + expect( + new ProtobufCompiler().compile(source, join(directory, 'entry.ts')), + ).toBeNull(); + }, + ); + }); + + it('leaves ordinary calls and data receivers outside schema resolution', () => { + expect( + run(` + interface Options { meta?: Record; } + function options(value: Options): Options { return value; } + const input: Options = { meta: { source: 'test' } }; + const copy = options(input); + function data(flag: boolean) { if (flag) return { value: 7 }; return { value: 8 }; } + function bytes(value: Uint8Array): Uint8Array { return value; } + const raw: Uint8Array = new Uint8Array([1]); + export const result = [copy.meta.source, data(true).value, bytes(raw).length]; + `).result, + ).toEqual(['test', 7, 1]); + }); + + it('keeps TypeScript optionality separate from explicit wire presence', () => { + const result = run(` + interface Msg { + plain?: pb<1, uint_32>; + flag?: pb<2, bool>; + text?: pb<3, string>; + data?: pb<4, bytes>; + big?: pb<5, uint_64>; + forced?: pb_optional<6, uint_32>; + } + export const wire = [...protobuf_encode({ + plain: 0, flag: false, text: '', data: new Uint8Array(), big: 0n, forced: 0, + })]; + export const decoded = protobuf_decode(new Uint8Array(wire)); + `); + expect(result.wire).toEqual([48, 0]); + expect(result.decoded).toEqual({ + plain: null, + flag: null, + text: null, + data: null, + big: null, + forced: 0, + }); + }); + + it('retains aliased markers and presence through exported generic wrappers', async () => { + const result = await bundle({ + 'schema.ts': `import type { pb as P, pb_optional as O, pb_repeated as R, uint_32 } from '@snowluma/proton'; + export interface Box { value?: P<1, T>; } + export interface Msg { plain?: P<1, uint_32>; forced?: O<2, uint_32>; items?: R<3, uint_32>; } + export interface Outer { inner?: P<1, Box>; }`, + 'barrel.ts': `export * from './schema';`, + 'wrapper.ts': `${imports} import type {Outer} from './barrel'; + export function encode(value:Outer) { return protobuf_encode>(value); }`, + 'forward.ts': `import {encode} from './wrapper'; import type {Outer} from './barrel'; + export function forward(value:Outer) { return encode(value); }`, + 'entry.ts': `${imports} import type {Msg} from './barrel'; import {forward} from './forward'; + export const wire = [...forward({inner:{value:{plain:0,forced:0,items:[0,7]}}})];`, + }); + expect(result.wire).toEqual([10, 8, 10, 6, 16, 0, 24, 0, 24, 7]); + }); + + it.each([true, false])('resolves package exports with tsconfig=%s', async (withConfig) => { + const result = await bundle({ + ...(withConfig + ? { + 'tsconfig.json': JSON.stringify({ + compilerOptions: { moduleResolution: 'bundler', module: 'esnext' }, + }), + } + : {}), + 'node_modules/@fake/schemas/package.json': JSON.stringify({ + name: '@fake/schemas', + type: 'module', + exports: { '.': { types: './index.ts', default: './index.ts' } }, + }), + 'node_modules/@fake/schemas/index.ts': `export * from './schema';`, + 'node_modules/@fake/schemas/schema.ts': `export interface Msg { value:pb<1,uint_32>; }`, + 'entry.ts': `${imports} import type {Msg} from '@fake/schemas'; + export const result = protobuf_decode(protobuf_encode({value:42}));`, + }); + expect(result).toEqual({ result: { value: 42 } }); + }); + + const codec = schemaCodecs<{ value: number }>('interface Msg { value:pb<1,uint_32>; }'); + it.each([ + ['unterminated group', [0x13, 8, 7]], + ['mismatched group', [0x13, 0x1c]], + ['unexpected group end', [0x14]], + ['invalid group tag', [0x13, 0]], + ['group payload exceeds frame', [0x13, 0x1a, 4, 0x14]], + ['group recursion limit', [...Array(66).fill(0x13), ...Array(66).fill(0x14)]], + ] as const)('rejects %s', (_name, bytes) => { + expect(() => codec.decode(Uint8Array.from(bytes))).toThrow(/protobuf/); + }); + + it('skips nested groups and retains non-enumerable metadata', () => { + const decoded = codec.decode(Uint8Array.from([0x13, 0x1b, 8, 99, 0x1c, 0x14, 8, 7])); + expect(decoded).toEqual({ value: 7 }); + expect(protobuf_getUnknownFields(decoded)).toEqual([ + { fieldNumber: 2, wireType: 3, count: 1, totalByteLength: 5 }, + ]); + expect(JSON.stringify(decoded)).toBe('{"value":7}'); + expect([...codec.encode(decoded)]).toEqual([8, 7]); + }); + + it.each([ + [NaN, 0], + [0, NaN], + [0.5, 1], + [0, 0.5], + [-1, 1], + [1, 0], + [0, 3], + [0, Infinity], + ])('rejects invalid decoder bounds %s..%s', (offset, end) => { + const generated = generateCode(schemaRegistry('interface Msg { value:pb<1,uint_32>; }')); + const decode = new Function(generated + '\nreturn protobuf_decode_Msg;')(); + expect(() => decode(new Uint8Array([8, 1]), offset, end)).toThrow(/bounds/); + }); +}); diff --git a/packages/proton/test/__tests__/cross-file.test.ts b/packages/proton/test/__tests__/cross-file.test.ts deleted file mode 100644 index 117275f8..00000000 --- a/packages/proton/test/__tests__/cross-file.test.ts +++ /dev/null @@ -1,402 +0,0 @@ -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(); - 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(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); - - const result = execAndGet( - 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(); - 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(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); - - const result = execAndGet( - 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(); - 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(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); - - const result = execAndGet( - 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(); - 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(); - 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>'); - }); - - it('handles local wrapper functions in the entry file', () => { - const { code, path } = loadCross('local-wrapper-consumer.ts'); - const cache = new Map(); - 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(); - 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>'); - }); - - it('handles wrapper protobuf type derived from another generic type', () => { - const { code, path } = loadCross('wrapper-type-source-consumer.ts'); - const cache = new Map(); - 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'); - }); - - // ── Transitive imports ─────────────────────────────────────────── - - it('resolves transitive imports (A → B → C)', () => { - const { code, path } = loadCross('top.ts'); - const cache = new Map(); - 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(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); - - const result = execAndGet( - 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(); - - 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(); - - 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({ id: 42, name: 'alice' }); -`; - const fakePath = resolve(crossDir, 'on-demand.ts'); - const cache = new Map(); - - 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(); - 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(); - const imported = resolveImports(code, path, cache); - const registry = analyzeSource(code, path, imported); - const gen = generateCode(registry); - - const result = execAndGet( - 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(); - 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('); - }); -}); diff --git a/packages/proton/test/__tests__/cross-package.test.ts b/packages/proton/test/__tests__/cross-package.test.ts deleted file mode 100644 index 8d46b66a..00000000 --- a/packages/proton/test/__tests__/cross-package.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -// Cross-package bare-specifier resolution. -// -// Companion to `cross-file.test.ts` — that suite covers relative-path -// imports between sibling files in the same package. Here we exercise -// the OTHER branch of `resolveModulePath`: a TypeScript-driven module -// resolution path that handles bare specifiers (`@scope/pkg`, -// `pkg-name`, …) so monorepo workspaces / npm packages can host proto -// definitions used from a different package. -// -// The motivating use case is decoupling `bridge/proto/proton/*.ts` -// from `@snowluma/core` into a standalone `@snowluma/proto-defs` -// package, so SnowLumaExtended (and any other consumer) can reuse the -// same wire definitions without copy-pasting them. -// -// The fixture is built in `os.tmpdir()` per-test-suite rather than -// committed to `test/fixtures/`. The reason: the resolution lookup -// has to find a real `node_modules/@fake/proto-defs/...` layout, and -// the repo-level `.gitignore` rule `**/node_modules/` would clobber a -// committed copy of that layout. A scratch tmpdir sidesteps the issue -// entirely and self-cleans in `afterAll`. - -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs'; -import { join, resolve } from 'path'; -import { tmpdir } from 'os'; -import { analyze, analyzeSource } 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'; - -describe('cross-package import resolution (bare specifier)', () => { - let tmpRoot: string; - let consumerPath: string; - - beforeAll(() => { - // Build a tiny fake monorepo layout: - // - // / - // consumer.ts ← uses `import { RemoteMsg } from '@fake/proto-defs'` - // node_modules/ - // @fake/ - // proto-defs/ - // package.json ← exports → ./src/index.ts - // src/ - // index.ts ← exported interfaces - // - // Bundler-mode `ts.resolveModuleName` walks importer → parent - // dirs looking for `node_modules`, so placing the consumer at - // `/consumer.ts` lets `/node_modules/...` satisfy the - // lookup. - tmpRoot = mkdtempSync(join(tmpdir(), 'proton-cross-pkg-')); - - const pkgDir = resolve(tmpRoot, 'node_modules', '@fake', 'proto-defs'); - mkdirSync(resolve(pkgDir, 'src'), { recursive: true }); - - // `exports."."` must point at a `.ts` source file — proton walks - // interface AST nodes to collect `pb<…>` field tags, and a - // generated `.d.ts` typically strips those generic args. Telling - // consumers to ship source `.ts` is the same model - // `@snowluma/proton` itself uses (`"default": "./src/runtime.ts"`). - writeFileSync( - resolve(pkgDir, 'package.json'), - JSON.stringify( - { - name: '@fake/proto-defs', - version: '1.0.0', - type: 'module', - main: './src/index.ts', - types: './src/index.ts', - exports: { - '.': { - types: './src/index.ts', - default: './src/index.ts', - }, - }, - }, - null, - 2, - ), - ); - - writeFileSync( - resolve(pkgDir, 'src', 'index.ts'), - // proton's `collectInterface` recognises `pb` as a marker - // type by NAME — no actual import of `@snowluma/proton` is - // needed for the fixture to parse. Matches the existing - // cross-file fixtures (`fixtures/cross-file/types.ts` does the - // same). - 'export interface RemoteMsg {\n' + - ' id?: pb<1, uint_32>;\n' + - ' name?: pb<2, string>;\n' + - '}\n', - ); - - consumerPath = resolve(tmpRoot, 'consumer.ts'); - writeFileSync( - consumerPath, - "import type { RemoteMsg } from '@fake/proto-defs';\n" + - '\n' + - "const buf = protobuf_encode({ id: 42, name: 'alice' });\n" + - 'const decoded = protobuf_decode(buf);\n' + - '\n' + - 'export { buf, decoded };\n', - ); - }); - - afterAll(() => { - if (tmpRoot) { - rmSync(tmpRoot, { recursive: true, force: true }); - } - }); - - it('collects interfaces from a `@fake/proto-defs` bare-specifier import', () => { - // Smoke test: the import resolver MUST find the package and pick - // up `RemoteMsg`. If this fails, `ts.resolveModuleName` likely - // can't find the fake node_modules layout (check that the - // BARE_SPECIFIER_COMPILER_OPTIONS in import-resolver.ts still - // sets `moduleResolution: Bundler`). - const code = readFileSync(consumerPath, 'utf-8'); - const cache = new Map(); - const imported = resolveImports(code, consumerPath, cache); - - expect(imported.concrete.some((m) => m.name === 'RemoteMsg')).toBe(true); - }); - - it('rewrites encode/decode call sites against the imported type', () => { - const code = readFileSync(consumerPath, 'utf-8'); - const cache = new Map(); - const imported = resolveImports(code, consumerPath, cache); - - const { registry, callSites, sourceFile } = analyze(code, consumerPath, imported); - expect(registry.has('RemoteMsg')).toBe(true); - - const { transformedCode, hasReplacements } = applyReplacements( - code, - sourceFile, - callSites, - registry, - ); - expect(hasReplacements).toBe(true); - expect(transformedCode).toContain('protobuf_encode_RemoteMsg'); - expect(transformedCode).toContain('protobuf_decode_RemoteMsg'); - }); - - it('round-trips encode/decode of a bare-specifier-imported message', () => { - // End-to-end: parse → analyze → generate codec → encode → - // decode → assert payload survived. The same shape as - // cross-file.test.ts's "Scenario A round-trip", but with the - // type sourced from a separate package. - const code = readFileSync(consumerPath, 'utf-8'); - const cache = new Map(); - const imported = resolveImports(code, consumerPath, cache); - const registry = analyzeSource(code, consumerPath, imported); - const gen = generateCode(registry); - - const result = execAndGet<{ id: number; name: string }>( - gen + - '\n' + - "const enc = protobuf_encode_RemoteMsg({ id: 42, name: 'alice' });\n" + - 'globalThis.__r = protobuf_decode_RemoteMsg(enc);\n', - '__r', - ); - expect(result.id).toBe(42); - expect(result.name).toBe('alice'); - }); - - it('returns null for an unresolvable bare specifier (does not throw)', () => { - // Pre-existing relative-path behavior: missing files return - // null, never throw. The bare-specifier branch must match that - // — otherwise a typo in a package name turns into a build crash - // rather than a silent "no codec emitted" warning further down - // the pipeline. - const orphanPath = resolve(tmpRoot, 'orphan.ts'); - writeFileSync( - orphanPath, - "import type { Whatever } from '@does-not-exist/nope';\n" + - 'export type _ = Whatever;\n', - ); - const code = readFileSync(orphanPath, 'utf-8'); - const cache = new Map(); - // resolveImports swallows resolution failures by design — it - // simply produces an empty `concrete` for the unresolvable - // import. The assertion is that we got here without an exception. - const imported = resolveImports(code, orphanPath, cache); - expect(imported.concrete).toEqual([]); - }); -}); diff --git a/packages/proton/test/__tests__/generator.test.ts b/packages/proton/test/__tests__/generator.test.ts index 2f48408d..76fb2876 100644 --- a/packages/proton/test/__tests__/generator.test.ts +++ b/packages/proton/test/__tests__/generator.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { analyzeSource } from '../../src/ast/analyzer'; +import { schemaRegistry as analyzeSource } from '../upstream/schema'; import { generateCode } from '../../src/codegen/generator'; import { protobuf_getUnknownFieldMetadata } from '../../src/runtime'; import { loadFixture } from '../helpers'; @@ -72,8 +72,8 @@ describe('code generator', () => { it('generates nested message code', () => { const gen = generateCode(analyzeSource(loadFixture('nested.ts'), 't.ts')); - expect(gen).toContain('protobuf_encode_Inner('); - expect(gen).toContain('protobuf_decode_Inner(data, offset, _end)'); + expect(gen).toContain('__write_Inner('); + expect(gen).toContain('protobuf_decode_Inner(data, offset, offset + _len)'); }); it('round-trip uint_32', () => { @@ -212,23 +212,21 @@ interface Int32Msg { // Compatibility applies only to complete uint64 varints. Truncated input // and values wider than 64 bits must still fail loudly. - expect(() => dec(Uint8Array.from([0x08, 0x80]))).toThrow(/truncated uint64 varint/); + expect(() => dec(Uint8Array.from([0x08, 0x80]))).toThrow(/[Tt]runcated.*varint/); expect(() => dec( Uint8Array.from([0x08, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02]), ), - ).toThrow(/uint64 varint overflow/); + ).toThrow(/Invalid protobuf varint/); }); it('rejects malformed length-delimited fields without leaving parent bounds', () => { const schema = `interface BytesMsg { data: pb<1, bytes>; }`; - const gen = generateCode(analyzeSource(schema, 'BytesMsg.ts')); const { dec } = makeRoundTripFromSchema(schema, 'BytesMsg'); - expect(gen).toContain('const _end = __checkedEnd(offset, _len, end);'); - expect(() => dec(Uint8Array.from([0x0a, 0x80]))).toThrow(/truncated uint32 varint/); + expect(() => dec(Uint8Array.from([0x0a, 0x80]))).toThrow(/[Tt]runcated.*varint/); expect(() => dec(Uint8Array.from([0x0a, 0x80, 0x80, 0x80, 0x80, 0x10]))).toThrow( - /uint32 varint overflow/, + /Invalid protobuf varint/, ); }); diff --git a/packages/proton/test/__tests__/plugin.test.ts b/packages/proton/test/__tests__/plugin.test.ts deleted file mode 100644 index a6a42d57..00000000 --- a/packages/proton/test/__tests__/plugin.test.ts +++ /dev/null @@ -1,348 +0,0 @@ -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( - 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( - 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( - 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( - 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( - 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( - 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( - 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({ id: 1 }); -const decoded = protobuf_decode(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({ id: 42, name: 'test' }); -const decoded = protobuf_decode(buf); -`; - const registry = analyzeSource(code, 'import-test.ts'); - const gen = generateCode(registry); - const result = execAndGet( - 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({ id: 1 }); -const decoded = decode(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'); - expect(transformedCode).not.toContain('decode'); - }); - - 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({ val: 99, name: 'x' }); -`; - const registry = analyzeSource(code, 'alias-rt.ts'); - const gen = generateCode(registry); - const result = execAndGet( - 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({ 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({ 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({ id: 1, name: 'a' }); -const decoded = protobuf_decode(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'); - }); -}); diff --git a/packages/proton/test/__tests__/replacer.test.ts b/packages/proton/test/__tests__/replacer.test.ts deleted file mode 100644 index 05532f94..00000000 --- a/packages/proton/test/__tests__/replacer.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -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 with protobuf_encode_T', () => { - const code = - loadFixture('simple.ts') + `\nconst data = protobuf_encode({ 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'); - }); - - it('replaces protobuf_decode', () => { - const code = - loadFixture('simple.ts') + `\nconst result = protobuf_decode(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({ value: 1 }); -const b = protobuf_decode(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({ 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({ v: 1 });\n`; - const registry = analyzeSource(code, 't.ts'); - const { hasReplacements, transformedCode } = replaceCallSites(code, registry); - expect(hasReplacements).toBe(false); - expect(transformedCode).toContain('protobuf_encode'); - }); - - 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({ id: 1 }); -const b = pbx.protobuf_decode(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({ id: 1 }); -`; - const registry = analyzeSource(code, 'guard.ts'); - const { transformedCode, hasReplacements } = replaceCallSites(code, registry); - expect(hasReplacements).toBe(false); - expect(transformedCode).toContain('protobuf_encode({ id: 1 })'); - }); -}); diff --git a/packages/proton/test/__tests__/runtime-map-fallback.test.ts b/packages/proton/test/__tests__/runtime-map-fallback.test.ts deleted file mode 100644 index 68009260..00000000 --- a/packages/proton/test/__tests__/runtime-map-fallback.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -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); - }); -}); diff --git a/packages/proton/test/fixtures/aliased-pb-marker.ts b/packages/proton/test/fixtures/aliased-pb-marker.ts deleted file mode 100644 index 52c55d74..00000000 --- a/packages/proton/test/fixtures/aliased-pb-marker.ts +++ /dev/null @@ -1,21 +0,0 @@ -// 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({ id: 1, tags: ['a', 'b'] }); -const decoded = protobuf_decode(data); - -export { }; diff --git a/packages/proton/test/fixtures/cross-file/aliased-consumer.ts b/packages/proton/test/fixtures/cross-file/aliased-consumer.ts deleted file mode 100644 index adb3cccf..00000000 --- a/packages/proton/test/fixtures/cross-file/aliased-consumer.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; -import type { UserMsg as AliasMsg } from './types'; - -const buf = protobuf_encode({ id: 42, name: 'alice' }); -const decoded = protobuf_decode(buf); - -export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/consumer.ts b/packages/proton/test/fixtures/cross-file/consumer.ts deleted file mode 100644 index 03dc04d1..00000000 --- a/packages/proton/test/fixtures/cross-file/consumer.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { UserMsg } from './types'; - -const buf = protobuf_encode({ id: 42, name: 'alice' }); -const decoded = protobuf_decode(buf); - -export { }; diff --git a/packages/proton/test/fixtures/cross-file/deep.ts b/packages/proton/test/fixtures/cross-file/deep.ts deleted file mode 100644 index eccfaca7..00000000 --- a/packages/proton/test/fixtures/cross-file/deep.ts +++ /dev/null @@ -1,5 +0,0 @@ -interface Deep { - val: pb<1, uint_32>; -} - -export type { Deep }; diff --git a/packages/proton/test/fixtures/cross-file/generic-consumer.ts b/packages/proton/test/fixtures/cross-file/generic-consumer.ts deleted file mode 100644 index 64e927bc..00000000 --- a/packages/proton/test/fixtures/cross-file/generic-consumer.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { Wrapper } from './generic-types'; - -const buf = protobuf_encode>({ value: 'hello' }); -const decoded = protobuf_decode>(buf); - -export { }; diff --git a/packages/proton/test/fixtures/cross-file/generic-types.ts b/packages/proton/test/fixtures/cross-file/generic-types.ts deleted file mode 100644 index 8315901d..00000000 --- a/packages/proton/test/fixtures/cross-file/generic-types.ts +++ /dev/null @@ -1,5 +0,0 @@ -interface Wrapper { - value: pb<1, T>; -} - -export type { Wrapper }; diff --git a/packages/proton/test/fixtures/cross-file/inner.ts b/packages/proton/test/fixtures/cross-file/inner.ts deleted file mode 100644 index a086d31e..00000000 --- a/packages/proton/test/fixtures/cross-file/inner.ts +++ /dev/null @@ -1,5 +0,0 @@ -interface Inner { - value: pb<1, uint_32>; -} - -export type { Inner }; diff --git a/packages/proton/test/fixtures/cross-file/local-wrapper-consumer.ts b/packages/proton/test/fixtures/cross-file/local-wrapper-consumer.ts deleted file mode 100644 index 8d07ddef..00000000 --- a/packages/proton/test/fixtures/cross-file/local-wrapper-consumer.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { Wrapper } from './generic-types'; -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; - -function localEncode(value: T): Uint8Array { - return protobuf_encode(value); -} - -const buf = localEncode>({ value: 'local' }); -const decoded = protobuf_decode>(buf); - -export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/mid.ts b/packages/proton/test/fixtures/cross-file/mid.ts deleted file mode 100644 index 5a902861..00000000 --- a/packages/proton/test/fixtures/cross-file/mid.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Deep } from './deep'; - -interface Mid { - inner: pb<1, Deep>; -} - -export type { Mid }; diff --git a/packages/proton/test/fixtures/cross-file/outer.ts b/packages/proton/test/fixtures/cross-file/outer.ts deleted file mode 100644 index 01c0a94d..00000000 --- a/packages/proton/test/fixtures/cross-file/outer.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Inner } from './inner'; - -interface Outer { - inner: pb<1, Inner>; -} - -const buf = protobuf_encode({ inner: { value: 42 } }); -const decoded = protobuf_decode(buf); - -export { }; diff --git a/packages/proton/test/fixtures/cross-file/protobuf.ts b/packages/proton/test/fixtures/cross-file/protobuf.ts deleted file mode 100644 index 8514d7c8..00000000 --- a/packages/proton/test/fixtures/cross-file/protobuf.ts +++ /dev/null @@ -1,5 +0,0 @@ -interface SimpleMessage { - id: pb<1, uint_32>; -} - -export { SimpleMessage }; diff --git a/packages/proton/test/fixtures/cross-file/top.ts b/packages/proton/test/fixtures/cross-file/top.ts deleted file mode 100644 index 44a563ca..00000000 --- a/packages/proton/test/fixtures/cross-file/top.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Mid } from './mid'; - -interface Top { - nested: pb<1, Mid>; -} - -const buf = protobuf_encode({ nested: { inner: { val: 99 } } }); -const decoded = protobuf_decode(buf); - -export { }; diff --git a/packages/proton/test/fixtures/cross-file/types.ts b/packages/proton/test/fixtures/cross-file/types.ts deleted file mode 100644 index d1e1d944..00000000 --- a/packages/proton/test/fixtures/cross-file/types.ts +++ /dev/null @@ -1,6 +0,0 @@ -interface UserMsg { - id: pb<1, uint_32>; - name: pb<2, string>; -} - -export type { UserMsg }; diff --git a/packages/proton/test/fixtures/cross-file/value-import-consumer.ts b/packages/proton/test/fixtures/cross-file/value-import-consumer.ts deleted file mode 100644 index afdaf22e..00000000 --- a/packages/proton/test/fixtures/cross-file/value-import-consumer.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { SimpleMessage } from './protobuf'; -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; - -const bytes = protobuf_encode({ id: 42 }); -const decoded = protobuf_decode(bytes); - -export { }; diff --git a/packages/proton/test/fixtures/cross-file/wrapper-api.ts b/packages/proton/test/fixtures/cross-file/wrapper-api.ts deleted file mode 100644 index dc3a697e..00000000 --- a/packages/proton/test/fixtures/cross-file/wrapper-api.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { protobuf_encode, protobuf_decode } from '@snowluma/proton'; - -export function encodeViaWrapper(value: T): Uint8Array { - return protobuf_encode(value); -} - -export function decodeViaWrapper(data: Uint8Array): T { - return protobuf_decode(data); -} - -export const encodeArrowWrapper = (value: T): Uint8Array => protobuf_encode(value); - -export const decodeArrowWrapper = (data: Uint8Array): T => protobuf_decode(data); - -export function encodeSecondGeneric(_ignored: Ignored, value: T): Uint8Array { - return protobuf_encode(value); -} - -export function passthroughOnly(value: T): T { - return value; -} - -export const wrapperObject = { - encode(value: T): Uint8Array { - return protobuf_encode(value); - }, - decode(data: Uint8Array): T { - return protobuf_decode(data); - }, - encodeArrow: (value: T): Uint8Array => protobuf_encode(value), -}; - -export function encodeWithBranch(value: T, enabled: boolean): Uint8Array { - if (enabled) { - return protobuf_encode(value); - } - return protobuf_encode(value); -} - -export function encodeWithNestedHelper(value: T): Uint8Array { - function inner(payload: T): Uint8Array { - return protobuf_encode(payload); - } - return inner(value); -} - -export function encodeChained(value: T): Uint8Array { - return encodeViaWrapper(value); -} \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-complex-consumer.ts b/packages/proton/test/fixtures/cross-file/wrapper-complex-consumer.ts deleted file mode 100644 index 373dbe70..00000000 --- a/packages/proton/test/fixtures/cross-file/wrapper-complex-consumer.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { Wrapper } from './generic-types'; -import { - wrapperObject, - encodeWithBranch, - encodeWithNestedHelper, - encodeChained, -} from './wrapper-api'; - -const objectBuf = wrapperObject.encode>({ value: 'object' }); -const objectDecoded = wrapperObject.decode>(objectBuf); - -const arrowMemberBuf = wrapperObject.encodeArrow>>({ value: { value: 'member' } }); - -const { encodeArrow } = wrapperObject; -const destructuredBuf = encodeArrow>({ value: 'destructured' }); - -const branchBuf = encodeWithBranch>({ value: 'branch' }, true); -const nestedHelperBuf = encodeWithNestedHelper>({ value: 'nested-helper' }); -const chainedBuf = encodeChained>({ value: 'chained' }); - -export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-consumer.ts b/packages/proton/test/fixtures/cross-file/wrapper-consumer.ts deleted file mode 100644 index 8976bd19..00000000 --- a/packages/proton/test/fixtures/cross-file/wrapper-consumer.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Wrapper } from './generic-types'; -import { encodeViaWrapper, decodeViaWrapper } from './wrapper-api'; - -const buf = encodeViaWrapper>({ value: 'hello' }); -const decoded = decodeViaWrapper>(buf); - -export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-edge-consumer.ts b/packages/proton/test/fixtures/cross-file/wrapper-edge-consumer.ts deleted file mode 100644 index 242f8948..00000000 --- a/packages/proton/test/fixtures/cross-file/wrapper-edge-consumer.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { Wrapper } from './generic-types'; -import { - encodeViaWrapper as encAlias, - decodeViaWrapper as decAlias, - encodeArrowWrapper, - decodeArrowWrapper, - encodeSecondGeneric, - passthroughOnly, -} from './wrapper-api'; - -const aliasBuf = encAlias>({ value: 'alias' }); -const aliasDecoded = decAlias>(aliasBuf); - -const arrowBuf = encodeArrowWrapper>>({ value: { value: 'nested' } }); -const arrowDecoded = decodeArrowWrapper>>(arrowBuf); - -const secondBuf = encodeSecondGeneric>(1, { value: 'second' }); - -const passthrough = passthroughOnly>({ value: 'ignored' }); - -export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-type-source-base.ts b/packages/proton/test/fixtures/cross-file/wrapper-type-source-base.ts deleted file mode 100644 index 636b8ddf..00000000 --- a/packages/proton/test/fixtures/cross-file/wrapper-type-source-base.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { Wrapper } from './generic-types'; -import { protobuf_encode } from '@snowluma/proton'; - -export function encodeBoxed(value: Wrapper): Uint8Array { - return protobuf_encode>(value); -} \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-type-source-consumer.ts b/packages/proton/test/fixtures/cross-file/wrapper-type-source-consumer.ts deleted file mode 100644 index 4cf55089..00000000 --- a/packages/proton/test/fixtures/cross-file/wrapper-type-source-consumer.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { - encodeBoxed, - decodeBoxed, - encodeAliasBoxed, - encodeNestedBoxed, - encodeBoxedChain, -} from './wrapper-type-source'; - -const boxedBuf = encodeBoxed({ value: 'boxed' }); -const boxedDecoded = decodeBoxed(boxedBuf); -const aliasBuf = encodeAliasBoxed({ value: 'alias' }); -const nestedBuf = encodeNestedBoxed({ value: { value: 'nested' } }); -const chainedBuf = encodeBoxedChain({ value: 'chain' }); - -export { }; \ No newline at end of file diff --git a/packages/proton/test/fixtures/cross-file/wrapper-type-source.ts b/packages/proton/test/fixtures/cross-file/wrapper-type-source.ts deleted file mode 100644 index 7e3ac616..00000000 --- a/packages/proton/test/fixtures/cross-file/wrapper-type-source.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 = Wrapper; - -export function encodeBoxed(value: Wrapper): Uint8Array { - return protobuf_encode>(value); -} - -export function decodeBoxed(data: Uint8Array): Wrapper { - return protobuf_decode>(data); -} - -export function encodeAliasBoxed(value: AliasWrapper): Uint8Array { - return protobuf_encode>(value); -} - -export function encodeNestedBoxed(value: Wrapper>): Uint8Array { - return protobuf_encode>>(value); -} - -export function encodeBoxedChain(value: Wrapper): Uint8Array { - return encodeBoxedBase(value); -} \ No newline at end of file diff --git a/packages/proton/test/fixtures/generic-template.ts b/packages/proton/test/fixtures/generic-template.ts deleted file mode 100644 index 6b2b9685..00000000 --- a/packages/proton/test/fixtures/generic-template.ts +++ /dev/null @@ -1,3 +0,0 @@ -interface TestProtobufAny { - name?: pb<1, T>; -} diff --git a/packages/proton/test/fixtures/generic-usage.ts b/packages/proton/test/fixtures/generic-usage.ts deleted file mode 100644 index a23e869f..00000000 --- a/packages/proton/test/fixtures/generic-usage.ts +++ /dev/null @@ -1,8 +0,0 @@ -interface TestProtobufAny { - name?: pb<1, T>; -} - -const dataT = protobuf_encode>>({ name: { name: "test" } }); -const decodedT = protobuf_decode>>(dataT); - -export { }; diff --git a/packages/proton/test/fixtures/generic-with-generic-field.ts b/packages/proton/test/fixtures/generic-with-generic-field.ts deleted file mode 100644 index cbe86190..00000000 --- a/packages/proton/test/fixtures/generic-with-generic-field.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Generic template with a generic-instantiated message field. -// -// The outer template's type param (`U`) shows up *inside* an inner generic -// instantiation (`Wrapper`). When the outer is monomorphized at the call -// site (`Outer`), the inner instantiation must be re-instantiated -// with the substitution (becoming `Wrapper`) 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 { - value: pb<1, T>; -} - -interface Outer { - wrapped: pb<5, Wrapper>; -} - -const data = protobuf_encode>({ wrapped: { value: 42 } }); -const decoded = protobuf_decode>(data); - -export { }; diff --git a/packages/proton/test/fixtures/multi-field.ts b/packages/proton/test/fixtures/multi-field.ts deleted file mode 100644 index 708eec73..00000000 --- a/packages/proton/test/fixtures/multi-field.ts +++ /dev/null @@ -1,5 +0,0 @@ -interface UserProfile { - id: pb<1, uint_32>; - username: pb<2, string>; - active: pb<3, bool>; -} diff --git a/packages/proton/test/fixtures/nested-generic-field.ts b/packages/proton/test/fixtures/nested-generic-field.ts deleted file mode 100644 index cfaaa9df..00000000 --- a/packages/proton/test/fixtures/nested-generic-field.ts +++ /dev/null @@ -1,24 +0,0 @@ -// 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` 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 { - value: pb<1, T>; -} - -interface Container { - wrapped: pb<5, Wrapper>; -} - -const data = protobuf_encode({ wrapped: { value: 42 } }); -const decoded = protobuf_decode(data); - -export { }; diff --git a/packages/proton/test/fixtures/no-pb.ts b/packages/proton/test/fixtures/no-pb.ts deleted file mode 100644 index f1a6d072..00000000 --- a/packages/proton/test/fixtures/no-pb.ts +++ /dev/null @@ -1,3 +0,0 @@ -interface Foo { - bar: string; -} diff --git a/packages/proton/test/fixtures/real.ts b/packages/proton/test/fixtures/real.ts deleted file mode 100644 index b1f8df1b..00000000 --- a/packages/proton/test/fixtures/real.ts +++ /dev/null @@ -1,12 +0,0 @@ -interface TestProtobuf { - name: pb<1, uint_32>; -} - -interface TestProtobufOutput { - name: pb<1, TestProtobuf>; -} - -const data = protobuf_encode({ name: 123 }); -const decoded = protobuf_decode(data); - -export { }; diff --git a/packages/proton/test/helpers/index.ts b/packages/proton/test/helpers/index.ts index 9ac63567..b2c26b73 100644 --- a/packages/proton/test/helpers/index.ts +++ b/packages/proton/test/helpers/index.ts @@ -8,14 +8,3 @@ const fixturesDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixt 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(code: string, globalKey: string): T { - new Function(code)(); - const val = (globalThis as any)[globalKey] as T; - delete (globalThis as any)[globalKey]; - return val; -} diff --git a/packages/proton/test/upstream/codegen/buffer.test.ts b/packages/proton/test/upstream/codegen/buffer.test.ts new file mode 100644 index 00000000..35e32abd --- /dev/null +++ b/packages/proton/test/upstream/codegen/buffer.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from 'vitest'; +import { schemaCodecs } from '../schema'; + +const bytesSchema = 'interface Msg { data: pb<1,bytes>; }'; + +describe('encoded buffers', () => { + it('round-trips messages around allocation and slab boundaries', () => { + const codec = schemaCodecs<{ data: Uint8Array }>(bytesSchema); + + for (const length of [ + 0, 1, 61, 62, 63, 64, 65, 125, 127, 128, 4092, 4093, 4094, 4095, 4096, 8192, + ]) { + const data = Uint8Array.from({ length }, (_, i) => (i * 13) & 255); + const encoded = codec.encode({ data }); + expect(codec.decode(encoded)).toEqual({ data }); + + if (encoded.length <= 64 || encoded.length > 4096) { + expect(encoded.byteOffset).toBe(0); + expect(encoded.buffer.byteLength).toBe(encoded.length); + } + } + }); + + it('keeps retained results intact across slab rotation and subsequent mutations', () => { + const codec = schemaCodecs<{ data: Uint8Array }>(bytesSchema); + const retained = Array.from({ length: 200 }, (_, index) => { + const data = new Uint8Array([63, 128, 800, 1300][index % 4]).fill(index); + const encoded = codec.encode({ data }); + return { data, encoded, snapshot: encoded.slice() }; + }); + expect(retained.some(({ encoded }) => encoded.byteOffset > 0)).toBe(true); + + for (const { data, encoded, snapshot } of retained) { + expect(encoded).toEqual(snapshot); + expect(codec.decode(encoded)).toEqual({ data }); + } + + retained[0].encoded.fill(0); + + for (const { encoded, snapshot } of retained.slice(1)) { + expect(encoded).toEqual(snapshot); + } + }); + + it('supports encoding from a getter without reusing the inner result', () => { + const codec = schemaCodecs<{ data: Uint8Array }>(bytesSchema); + const inner = new Uint8Array(128).fill(7); + const outer = new Uint8Array(256).fill(9); + let nested: Uint8Array | undefined; + const encoded = codec.encode({ + get data() { + nested = codec.encode({ data: inner }); + return outer; + }, + }); + expect(codec.decode(encoded)).toEqual({ data: outer }); + expect(codec.decode(nested!)).toEqual({ data: inner }); + }); + + it('replaces a slab whose backing buffer was transferred', () => { + const codec = schemaCodecs<{ data: Uint8Array }>(bytesSchema); + const data = new Uint8Array(128).fill(3); + const first = codec.encode({ data }); + const transferred = structuredClone(first, { transfer: [first.buffer as ArrayBuffer] }); + expect(first.byteLength).toBe(0); + expect(codec.decode(transferred)).toEqual({ data }); + expect(codec.decode(codec.encode({ data }))).toEqual({ data }); + }); + + it('decodes unaligned pooled messages containing strings, fixed values and nested data', () => { + const codec = schemaCodecs<{ + text: string; + ratio: number; + inner: { value: bigint; data: Uint8Array }; + }>(` + interface Inner {value:pb<1,fixed_64>;data:pb<2,bytes>;} + interface Msg {text:pb<1,string>;ratio:pb<2,double>;inner:pb<3,Inner>;} + `); + let unaligned = false; + + for (let i = 0; i < 100; i++) { + const value = { + text: '中文🚀'.repeat(8) + i, + ratio: Math.PI + i, + inner: { value: (1n << 63n) + BigInt(i), data: new Uint8Array(17 + i).fill(i) }, + }; + const encoded = codec.encode(value); + unaligned ||= encoded.byteOffset % 8 !== 0; + expect(codec.decode(encoded)).toEqual(value); + } + + expect(unaligned).toBe(true); + }); +}); diff --git a/packages/proton/test/upstream/codegen/generator.test.ts b/packages/proton/test/upstream/codegen/generator.test.ts new file mode 100644 index 00000000..97fcc606 --- /dev/null +++ b/packages/proton/test/upstream/codegen/generator.test.ts @@ -0,0 +1,245 @@ +import { describe, it, expect } from 'vitest'; +import { schemaRegistry } from '../schema'; +import { generateCode } from '../../../src/codegen/generator'; +const simple = 'interface SimpleMsg { value: pb<1, uint_32>; }'; +const nested = + 'interface Inner { value: pb<1, uint_32>; } interface Outer { inner: pb<1, Inner>; }'; +const string = 'interface StringMsg { text: pb<1, string>; }'; +const bool = 'interface BoolMsg { active: pb<1, bool>; }'; +const repeated = + 'interface RepeatedMsg { ids: pb_repeated<1, uint_32>; names: pb_repeated<2, string>; }'; + +function makeRoundTrip(schema: string, msgName: string) { + const gen = generateCode(schemaRegistry(schema, `${msgName}.ts`)); + return new Function( + gen + `\nreturn { enc: protobuf_encode_${msgName}, dec: protobuf_decode_${msgName} };`, + )() as { + enc: (obj: any) => Uint8Array; + dec: (data: Uint8Array) => any; + }; +} + +describe('code generator', () => { + it('allocates one output buffer for nested repeated messages', () => { + const schema = `interface Leaf { text: pb<1,string>; } interface Msg { children: pb_repeated<1,Leaf>; }`; + const registry = schemaRegistry(schema, 'allocation.ts'); + const code = generateCode(registry, { encodeRoots: ['Msg'], decodeRoots: [] }); + let allocations = 0; + class CountingBytes extends Uint8Array { + constructor(size: number) { + super(size); + allocations++; + } + static get [Symbol.species]() { + return Uint8Array; + } + } + const encode = new Function('Uint8Array', code + '\nreturn protobuf_encode_Msg;')( + CountingBytes, + ); + const input = { children: Array.from({ length: 32 }, (_, i) => ({ text: '你好' + i })) }; + const encoded = encode(input); + expect(allocations).toBe(1); + expect(makeRoundTrip(schema, 'Msg').dec(encoded)).toEqual(input); + }); + + it('omits unused helpers and decoder functions from encode-only output', () => { + const code = generateCode( + schemaRegistry('interface Msg { value: pb<1,uint_32>; }', 'minimal.ts'), + { + encodeRoots: ['Msg'], + decodeRoots: [], + }, + ); + expect(code).not.toContain('TextDecoder'); + expect(code).not.toContain('TextEncoder'); + expect(code).not.toContain('DataView'); + expect(code).not.toContain('BigInt'); + expect(code).not.toContain('protobuf_decode_'); + }); + + it('round-trips a deep mixture of strings and nested messages', () => { + const schema = Array.from( + { length: 24 }, + (_, i) => + `interface M${i} { text: pb<1,string>; ${i < 23 ? `next: pb<2,M${i + 1}>;` : ''} }`, + ).join('\n'); + let input: any = { text: 'end' }; + + for (let i = 22; i >= 0; i--) { + input = { text: 'level' + i, next: input }; + } + + const { enc, dec } = makeRoundTrip(schema, 'M0'); + expect(dec(enc(input))).toEqual(input); + }); + it('round-trips int_32 and preserves five-byte negative varints', () => { + const { enc, dec } = makeRoundTrip( + `interface IntMsg { + value: pb<1, int_32>; + values: pb_repeated<2, int_32>; + }`, + 'IntMsg', + ); + expect([...enc({ value: -1 })]).toEqual([0x08, 0xff, 0xff, 0xff, 0xff, 0x0f]); + const input = { value: -2147483648, values: [-1, -2147483648, 0, 2147483647] }; + expect(dec(enc(input))).toEqual(input); + }); + + it('preserves fixed_32 unsigned values and sfixed_32 signed values', () => { + const { enc, dec } = makeRoundTrip( + `interface FixedMsg { + unsigned: pb<1, fixed_32>; + signed: pb<2, sfixed_32>; + values: pb_repeated<3, fixed_32>; + }`, + 'FixedMsg', + ); + const input = { + unsigned: 0xffffffff, + signed: -2147483648, + values: [0x80000000, 0xffffffff], + }; + expect(dec(enc(input))).toEqual(input); + }); + + it('uses bigint defaults for all 64-bit integer fields', () => { + const { enc, dec } = makeRoundTrip( + `interface Defaults { + 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>; + }`, + 'Defaults', + ); + const result = dec(new Uint8Array()); + expect(result).toEqual({ unsigned: 0n, signed: 0n, zigzag: 0n, fixed: 0n, sfixed: 0n }); + expect(enc(result)).toEqual(new Uint8Array()); + }); + + it('decodes tags with the highest valid field number', () => { + const { enc, dec } = makeRoundTrip( + 'interface HighTag { value: pb<536870911, uint_32>; }', + 'HighTag', + ); + const bytes = new Uint8Array([0xf8, 0xff, 0xff, 0xff, 0x0f, 7]); + expect(enc({ value: 7 })).toEqual(bytes); + expect(dec(bytes)).toEqual({ value: 7 }); + }); + + it('generates encode/decode for simple uint_32', () => { + const gen = generateCode(schemaRegistry(simple, '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(schemaRegistry(nested, '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, 'SimpleMsg'); + expect(dec(enc({ value: 42 })).value).toBe(42); + }); + + it('round-trip nested message', () => { + const { enc, dec } = makeRoundTrip(nested, 'Outer'); + expect(dec(enc({ inner: { value: 999 } })).inner.value).toBe(999); + }); + + it('round-trip string', () => { + const { enc, dec } = makeRoundTrip(string, 'StringMsg'); + expect(dec(enc({ text: 'hello world' })).text).toBe('hello world'); + }); + + it('round-trip unicode string', () => { + const { enc, dec } = makeRoundTrip(string, 'StringMsg'); + expect(dec(enc({ text: '你好,protobuf🚀' })).text).toBe('你好,protobuf🚀'); + }); + + it('round-trip bool', () => { + const { enc, dec } = makeRoundTrip(bool, '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, 'SimpleMsg'); + expect(enc({ value: 0 }).length).toBe(0); + }); + + it('round-trip repeated uint_32', () => { + const { enc, dec } = makeRoundTrip(repeated, '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, '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, '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 } = makeRoundTrip(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 } = makeRoundTrip(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 } = makeRoundTrip(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); + }); +}); diff --git a/packages/proton/test/upstream/codegen/utf8.test.ts b/packages/proton/test/upstream/codegen/utf8.test.ts new file mode 100644 index 00000000..73fc337d --- /dev/null +++ b/packages/proton/test/upstream/codegen/utf8.test.ts @@ -0,0 +1,209 @@ +import { describe, it, expect } from 'vitest'; +import { schemaRegistry } from '../schema'; +import { generateCode } from '../../../src/codegen/generator'; + +const code = generateCode( + schemaRegistry(` + interface Text { value: pb<1,string>; } + interface Nested { texts: pb_repeated<1,Text>; } +`), +); +const { encode, decode, encodeNested, decodeNested } = new Function(`${code} + return { + encode: protobuf_encode_Text, decode: protobuf_decode_Text, + encodeNested: protobuf_encode_Nested, decodeNested: protobuf_decode_Nested, + };`)() as { + decode(bytes: Uint8Array): { value: string }; + encode(value: { value: string }): Uint8Array; + encodeNested(value: { texts: { value: string }[] }): Uint8Array; + decodeNested(bytes: Uint8Array): { texts: { value: string }[] }; +}; +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +function wire(payload: Uint8Array): Uint8Array { + const prefix = [10]; + let length = payload.length; + + do { + prefix.push((length & 127) | (length >= 128 ? 128 : 0)); + length >>>= 7; + } while (length); + + return Uint8Array.from([...prefix, ...payload]); +} + +describe('UTF-8 codecs', () => { + it('matches TextEncoder across native encoding boundaries, including unpaired surrogates', () => { + for (const length of [31, 32, 33, 42, 43, 63, 64, 65, 127, 128, 129, 4096]) { + for (const unit of ['a', 'é', '中文', '🚀', '\ud800', '\udc00', 'a\ud800']) { + const value = unit.repeat(length); + expect(encode({ value })).toEqual(wire(encoder.encode(value))); + } + } + }); + + it('preserves every ASCII byte across short and native decoding boundaries', () => { + for (const length of [ + 0, 1, 3, 4, 7, 8, 15, 16, 23, 24, 30, 31, 32, 33, 63, 64, 127, 128, 4096, + ]) { + for (let byte = 0; byte < 128; byte++) { + const value = String.fromCharCode(byte).repeat(length); + expect(encode({ value })).toEqual( + length ? wire(encoder.encode(value)) : new Uint8Array(), + ); + expect(decode(wire(encoder.encode(value)))).toEqual({ value }); + } + } + }); + + it('matches TextDecoder for Unicode after ASCII prefixes and at slice boundaries', () => { + const suffixes = [ + '\u0080', + 'é', + '\u07ff', + '\u0800', + '中文', + '\ud7ff', + '\ue000', + '\uffff', + '🚀', + '\u{10000}', + '\u{10ffff}', + '\ufeff', + '\ufeffx\ufeff', + '\ud800', + '\udc00', + ]; + + for (let length = 0; length <= 64; length++) { + for (const suffix of suffixes) { + const value = 'a'.repeat(length) + suffix; + const payload = encoder.encode(value); + const bytes = wire(payload); + const padded = Uint8Array.from([255, 255, ...bytes, 128, 128]); + expect(decode(padded.subarray(2, 2 + bytes.length)).value).toBe( + decoder.decode(payload), + ); + } + } + }); + + it('matches replacement behavior for all one-byte and two-byte sequences', () => { + const payload = new Uint8Array(2); + + for (let first = 0; first < 256; first++) { + payload[0] = first; + const one = payload.subarray(0, 1); + expect(decode(wire(one)).value).toBe(decoder.decode(one)); + + for (let second = 0; second < 256; second++) { + payload[1] = second; + expect(decode(wire(payload)).value).toBe(decoder.decode(payload)); + } + } + }); + + it('matches TextDecoder across randomized valid Unicode strings', () => { + let state = 0x5a17cafe; + + for (let sample = 0; sample < 5000; sample++) { + let value = 'a'.repeat(sample % 17); + + for (let index = 0; index < sample % 21; index++) { + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + value += String.fromCodePoint(state % 0x110000); + } + + const payload = encoder.encode(value); + expect(decode(wire(payload)).value).toBe(decoder.decode(payload)); + } + }); + + it('matches TextDecoder for invalid and truncated multibyte sequences', () => { + const sequences = [ + [0xe0, 0x80, 0x80], + [0xed, 0xa0, 0x80], + [0xf0, 0x80, 0x80, 0x80], + [0xf4, 0x90, 0x80, 0x80], + [0xf5, 0x80, 0x80, 0x80], + [0xff], + [0xc2], + [0xe1, 0x80], + [0xf1, 0x80, 0x80], + [0xe1, 65, 0x80], + [0xf1, 0x80, 65, 0x80], + [0xef, 0xbb, 0xbf, 0xff], + ]; + + for (let length = 0; length <= 33; length++) { + for (const sequence of sequences) { + const payload = Uint8Array.from([...Array(length).fill(65), ...sequence]); + expect(decode(wire(payload)).value).toBe(decoder.decode(payload)); + } + } + + let state = 0x42abcdef; + + for (let sample = 0; sample < 5000; sample++) { + const payload = Uint8Array.from({ length: sample % 65 }, () => { + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + return state >>> 24; + }); + expect(decode(wire(payload)).value).toBe(decoder.decode(payload)); + } + }); + + it('keeps nested and repeated strings independent', () => { + const texts = [ + '', + 'ascii', + 'a'.repeat(31), + 'a'.repeat(32), + '中文🚀', + 'a\ufeffb', + '\ufeffx', + '中文🚀'.repeat(64), + ].map((value) => ({ value })); + expect(decodeNested(encodeNested({ texts }))).toEqual({ + texts: texts.map(({ value }) => ({ value: decoder.decode(encoder.encode(value)) })), + }); + // A truncated UTF-8 sequence must not consume bytes from the following field. + const first = wire(Uint8Array.from([0xf0, 0x9f])); + const second = wire(encoder.encode('next')); + const nested = Uint8Array.from([10, first.length, ...first, 10, second.length, ...second]); + expect(decodeNested(nested)).toEqual({ texts: [{ value: '�' }, { value: 'next' }] }); + }); + + it('measures UTF-8 correctly when a code point crosses a scratch-buffer boundary', () => { + for (const length of [4093, 4094, 4095, 4096, 4097, 8191]) { + for (const suffix of ['é', '中', '🚀', '\ud800', '\udc00', '\ud800x']) { + const value = 'a'.repeat(length) + suffix + '中文🚀'.repeat(4000); + expect(encode({ value })).toEqual(wire(encoder.encode(value))); + } + } + }); + + it('preserves replacement and BOM behavior after long malformed inputs', () => { + for (const length of [127, 128, 129, 255, 4095, 4096, 4097]) { + for (const sequence of [ + [0xff], + [0xe0, 0x80, 0x80], + [0xed, 0xa0, 0x80], + [0xf0, 0x9f], + [0xef, 0xbb, 0xbf], + ]) { + for (const prefix of [[], [0xef, 0xbb, 0xbf]]) { + const payload = Uint8Array.from([ + ...prefix, + ...Array(length).fill(65), + ...sequence, + ]); + expect(decode(wire(payload)).value).toBe(decoder.decode(payload)); + const valid = encoder.encode('中文🚀'.repeat(64)); + expect(decode(wire(valid)).value).toBe(decoder.decode(valid)); + } + } + } + }); +}); diff --git a/packages/proton/test/upstream/codegen/wire.test.ts b/packages/proton/test/upstream/codegen/wire.test.ts new file mode 100644 index 00000000..5ced78bb --- /dev/null +++ b/packages/proton/test/upstream/codegen/wire.test.ts @@ -0,0 +1,202 @@ +import { describe, it, expect } from 'vitest'; +import { schemaCodecs as codecs } from '../schema'; + +describe('generated wire format', () => { + it('matches TextEncoder at UTF-8 length-prefix boundaries', () => { + const codec = codecs<{ value: string }>('interface Msg {value:pb<1,string>;}'); + + for (const length of [127, 128, 16383, 16384]) { + for (const value of ['a'.repeat(length), '界🚀\ud800'.repeat(length)]) { + const payload = new TextEncoder().encode(value); + const prefix = [10]; + let remaining = payload.length; + + do { + prefix.push((remaining % 128) | (remaining >= 128 ? 128 : 0)); + remaining = Math.floor(remaining / 128); + } while (remaining); + + const expected = new Uint8Array(prefix.length + payload.length); + expected.set(prefix); + expected.set(payload, prefix.length); + expect(codec.encode({ value })).toEqual(expected); + expect(codec.decode(expected)).toEqual({ + value: new TextDecoder().decode(payload), + }); + } + } + }); + + it('decodes floating-point, fixed-width and byte fields from unaligned subarrays', () => { + const codec = codecs<{ f: number; d: number; fixed: bigint; data: Uint8Array }>( + `interface Msg {f:pb<1,float>;d:pb<2,double>;fixed:pb<3,fixed_64>;data:pb<4,bytes>;}`, + ); + const input = { + f: Math.fround(1 / 3), + d: -Number.MAX_VALUE, + fixed: (1n << 64n) - 1n, + data: new Uint8Array([0, 1, 255]), + }; + const wire = codec.encode(input); + + for (const padding of [1, 3, 7, 31]) { + const buffer = new Uint8Array(wire.length + padding + 5).fill(255); + buffer.set(wire, padding); + expect(codec.decode(buffer.subarray(padding, padding + wire.length))).toEqual(input); + } + }); + it('matches an independent bigint varint reference at every byte boundary', () => { + const codec = codecs<{ value: bigint }>('interface Msg { value: pb<1, uint_64>; }'); + const values = new Set([0n, 1n, (1n << 64n) - 1n]); + + for (let bit = 1n; bit < 64n; bit++) { + values.add((1n << bit) - 1n); + values.add(1n << bit); + values.add((1n << bit) + 1n); + } + + for (const value of values) { + let rest = value; + const bytes = []; + + do { + bytes.push(Number(rest & 127n) | (rest > 127n ? 128 : 0)); + rest >>= 7n; + } while (rest); + + const wire = new Uint8Array([8, ...bytes]); + expect(codec.encode({ value })).toEqual(value === 0n ? new Uint8Array() : wire); + expect(codec.decode(wire)).toEqual({ value }); + } + }); + + it('decodes nonzero booleans whose low 32 bits are zero', () => { + const codec = codecs<{ value: boolean }>('interface Msg { value: pb<1, bool>; }'); + expect(codec.decode(new Uint8Array([8, 128, 128, 128, 128, 16]))).toEqual({ value: true }); + }); + const uint32 = codecs<{ value: number }>('interface Msg { value: pb<1, uint_32>; }'); + const varints: [number, number[]][] = [ + [1, [0x01]], + [127, [0x7f]], + [128, [0x80, 0x01]], + [300, [0xac, 0x02]], + [16384, [0x80, 0x80, 0x01]], + [0xffffffff, [0xff, 0xff, 0xff, 0xff, 0x0f]], + ]; + + it.each(varints)('encodes uint32 %i using the expected wire bytes', (value, bytes) => { + expect([...uint32.encode({ value })]).toEqual([0x08, ...bytes]); + }); + + it.each(varints)('decodes uint32 %i from independent wire bytes', (value, bytes) => { + expect(uint32.decode(new Uint8Array([0x08, ...bytes]))).toEqual({ value }); + }); + + it('omits scalar zero and decodes an explicit zero', () => { + expect(uint32.encode({ value: 0 })).toEqual(new Uint8Array()); + expect(uint32.decode(new Uint8Array([8, 0]))).toEqual({ value: 0 }); + }); + + it.each(['hello', '', '你好', '🚀', '\ud800', '\udc00'])('encodes UTF-8 %j', (value) => { + const codec = codecs<{ value: string }>('interface Msg { value: pb<1, string>; }'); + const payload = new TextEncoder().encode(value); + const bytes = new Uint8Array([0x0a, payload.length, ...payload]); + expect(codec.encode({ value })).toEqual(value === '' ? new Uint8Array() : bytes); + expect(codec.decode(bytes)).toEqual({ value: new TextDecoder().decode(payload) }); + }); + + it('encodes bytes with a length prefix and copies the decoded data', () => { + const codec = codecs<{ value: Uint8Array }>('interface Msg { value: pb<1, bytes>; }'); + const bytes = new Uint8Array([10, 3, 1, 128, 255]); + const value = new Uint8Array([1, 128, 255]); + expect(codec.encode({ value })).toEqual(bytes); + const result = codec.decode(bytes); + bytes[2] = 0; + expect(result.value).toEqual(value); + }); + + it.each([ + ['varint', [0x10, 0xac, 0x02]], + ['64-bit', [0x11, 1, 2, 3, 4, 5, 6, 7, 8]], + ['length-delimited', [0x12, 3, 0x41, 0x42, 0x43]], + ['32-bit', [0x15, 1, 2, 3, 4]], + ])('skips unknown %s fields and resumes decoding', (_name, bytes) => { + expect(uint32.decode(new Uint8Array([...(bytes as number[]), 8, 7]))).toEqual({ value: 7 }); + }); + + const packedCases: [string, (number | bigint | boolean)[], number[]][] = [ + ['uint_32', [1, 300], [1, 0xac, 2]], + ['int_32', [1, -2], [1, 0xfe, ...Array(8).fill(0xff), 1]], + ['sint_32', [-1, 1], [1, 2]], + ['bool', [true, false], [1, 0]], + ['uint_64', [1n, 300n], [1, 0xac, 2]], + ['int_64', [1n, -2n], [1, 0xfe, ...Array(8).fill(0xff), 1]], + ['sint_64', [-1n, 1n], [1, 2]], + ['fixed_32', [0xffffffff, 1], [255, 255, 255, 255, 1, 0, 0, 0]], + ['sfixed_32', [-1, 1], [255, 255, 255, 255, 1, 0, 0, 0]], + ['fixed_64', [1n], [1, 0, 0, 0, 0, 0, 0, 0]], + ['sfixed_64', [-1n], Array(8).fill(255)], + ['float', [1], [0, 0, 128, 63]], + ['double', [1], [0, 0, 0, 0, 0, 0, 240, 63]], + ]; + + it.each(packedCases)( + 'decodes packed, unpacked and split %s arrays', + (type, values, payload) => { + const codec = codecs<{ values: typeof values }>( + `interface Msg { values: pb_repeated<1, ${type}>; }`, + ); + const packed = [10, payload.length, ...payload]; + const unpacked = codec.encode({ values }); + expect(codec.decode(new Uint8Array(packed))).toEqual({ values }); + expect(codec.decode(new Uint8Array([...packed, ...unpacked, ...packed]))).toEqual({ + values: [...values, ...values, ...values], + }); + expect(codec.decode(new Uint8Array([10, 0]))).toEqual({ values: [] }); + }, + ); + + const malformedCodec = codecs(` + interface Inner { value: pb<1, uint_32>; } + interface Msg { + value: pb<1, uint_32>; + big: pb<2, uint_64>; + text: pb<3, string>; + data: pb<4, bytes>; + float: pb<5, float>; + double: pb<6, double>; + inner: pb<7, Inner>; + values: pb_repeated<8, uint_32>; + fixed: pb_repeated<9, fixed_32>; + } + `); + const invalidCases: [string, number[]][] = [ + ['zero tag', [0]], + ['invalid wire type', [15]], + ['truncated tag', [128]], + ['overflowing tag', [255, 255, 255, 255, 31]], + ['missing varint', [8]], + ['unterminated varint', [8, 128]], + ['overflowing varint', [8, ...Array(10).fill(255)]], + ['truncated bigint', [16, 128]], + ['overflowing bigint', [16, ...Array(9).fill(255), 2]], + ['missing string length', [26]], + ['truncated string', [26, 2, 65]], + ['overflowing length', [26, 255, 255, 255, 255, 31]], + ['truncated bytes', [34, 2, 1]], + ['truncated float', [45, 0]], + ['truncated double', [49, 0]], + ['nested message exceeds parent', [58, 5, 8, 1]], + ['nested varint exceeds nested boundary', [58, 2, 8, 128, 8, 7]], + ['packed varint exceeds packed boundary', [66, 1, 128, 8, 7]], + ['packed fixed32 has partial value', [74, 3, 1, 2, 3, 8, 7]], + ['unknown truncated varint', [80, 128]], + ['unknown truncated fixed64', [81, 0]], + ['unknown truncated bytes', [82, 5, 1]], + ['unknown truncated fixed32', [85, 0]], + ]; + + it.each(invalidCases)('rejects %s', (_name, bytes) => { + expect(() => malformedCodec.decode(new Uint8Array(bytes))).toThrow(/protobuf/); + }); +}); diff --git a/packages/proton/test/upstream/compile.ts b/packages/proton/test/upstream/compile.ts new file mode 100644 index 00000000..02c48db8 --- /dev/null +++ b/packages/proton/test/upstream/compile.ts @@ -0,0 +1,24 @@ +import ts from 'typescript'; +import { ProtobufCompiler } from '../../src/compiler/compiler'; +import { packageName } from '../../src/package'; + +export const imports = `import { protobuf_encode, protobuf_decode } from '${packageName}';`; + +export function run(body: string): any { + const compiler = new ProtobufCompiler(); + const source = imports + '\n' + body; + const transformed = compiler.compile(source, 'test-entry.ts') ?? source; + const js = ts.transpileModule(transformed, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + }).outputText; + const exports = {}; + new Function('exports', 'require', js)(exports, () => ({ + protobuf_encode() { + throw new Error('Uncompiled encode'); + }, + protobuf_decode() { + throw new Error('Uncompiled decode'); + }, + })); + return exports; +} diff --git a/packages/proton/test/upstream/compiler/callbacks.test.ts b/packages/proton/test/upstream/compiler/callbacks.test.ts new file mode 100644 index 00000000..9e7fd16a --- /dev/null +++ b/packages/proton/test/upstream/compiler/callbacks.test.ts @@ -0,0 +1,332 @@ +import { bundle } from '../project'; +import { describe, expect, it } from 'vitest'; +import { run, imports } from '../compile'; + +const schema = `interface Msg { value: pb<1,uint_32>; } +function encode(value:T) { return protobuf_encode(value); }`; + +describe('generic callbacks', () => { + it.each([ + 'const callbacks=[encode];', + 'const api={send:encode};', + '[{value:7}].map((value:T)=>protobuf_encode(value));', + '[{value:7}].map((encode));', + ])('rejects callback values without enough schema context: %s', (expression) => { + expect(() => run(schema + expression)).toThrow(/Cannot infer callback schema/); + }); + it('supports callbacks in default parameters and codec calls in parameter initializers', () => { + expect( + run(`${schema} + function apply(value:T, callback:(value:T)=>Uint8Array=protobuf_encode) {return callback(value);} + function defaults(value:T, bytes=protobuf_encode(value)) {return bytes;} + export const result=[[...apply({value:7})],[...defaults({value:8})]]; + export const lengths=[apply.length, defaults.length]; + `), + ).toEqual({ + result: [ + [8, 7], + [8, 8], + ], + lengths: [1, 1], + }); + }); + + it('supports destructured polymorphic callback parameters', () => { + expect( + run(`${schema} + interface Api {encode:(value:T)=>Uint8Array;} + function use({encode:fn}:Api,value:T) {return fn(value);} + export const result=[...use({encode},{value:7})]; + `).result, + ).toEqual([8, 7]); + }); + it('propagates object callback signatures through function parameters', () => { + expect( + run(`${schema} + interface Api {encode:(value:T)=>Uint8Array;} + function use(api:Api,value:T) {return api.encode(value);} + export const result=[...use({encode},{value:7})]; + `).result, + ).toEqual([8, 7]); + }); + + it('adapts typed assignments and callbacks stored in arrays', () => { + expect( + run(`${schema} + type Encoder=(value:Msg)=>Uint8Array; + let callback:Encoder; + callback=encode; + const callbacks:Encoder[]=[encode,callback]; + export const result=callbacks.map(fn=>[...fn({value:7})]); + `).result, + ).toEqual([ + [8, 7], + [8, 7], + ]); + }); + + it('reports opaque polymorphic consumers at build time', () => { + expect(() => + run(`${schema} + declare function external(fn:(value:T)=>Uint8Array):void; + external(encode); + `), + ).toThrow(/receiving implementation/); + }); + it('supports class arrow fields as callbacks with lexical this', () => { + expect( + run(`${schema} + class Codec { calls=0; encode=(value:T)=>{this.calls++;return protobuf_encode(value);}; } + const codec=new Codec(); + export const result=[{value:7}].map(codec.encode).map(bytes=>[...bytes]); + export const calls=codec.calls; + `), + ).toEqual({ result: [[8, 7]], calls: 1 }); + }); + + it('preserves spread evaluation, method receivers and rest arguments', () => { + expect( + run(`${schema} + const events:string[]=[]; + const api={calls:0,send(value:T,...labels:string[]){this.calls++;events.push(...labels);return protobuf_encode(value);}}; + function args():[Msg,string,string] {events.push('args');return [{value:7},'a','b'];} + export const result=[...api.send(...args())]; + export const calls=api.calls; + export {events}; + `), + ).toEqual({ result: [8, 7], calls: 1, events: ['args', 'a', 'b'] }); + }); + it('analyzes shared higher order functions across multiple build entries', async () => { + expect( + await bundle( + { + 'apply.ts': + 'export function apply(value:T, callback:(value:U)=>Uint8Array) { return callback(value); }', + 'plain.ts': `${imports} import {apply} from './apply'; interface Msg {value:pb<1,uint_32>;} + function encode(value:T) {return protobuf_encode(value);} + export const result=[...apply({value:7},encode)];`, + 'boxed.ts': `${imports} import {apply} from './apply'; interface Msg {value:pb<1,uint_32>;} interface Box {value:pb<1,T>;} + function encode(value:T) {return protobuf_encode>({value});} + export const result=[...apply({value:8},encode)];`, + }, + ['plain.ts', 'boxed.ts'], + ), + ).toEqual({ plain: { result: [8, 7] }, boxed: { result: [10, 2, 8, 8] } }); + }); + it('preserves this parameters, bound generic methods and class arguments', () => { + expect( + run(`${schema} + interface Pair {first:pb<1,T>;second:pb<2,U>;} + class Codec { + calls=0; + encode(this:Codec, value:Pair) { this.calls++; return protobuf_encode>(value); } + } + const codec = new Codec(); + const callback = codec.encode.bind(codec); + export const result = [...callback({first:7,second:'x'})]; + export const calls = codec.calls; + `), + ).toEqual({ result: [8, 7, 18, 1, 120], calls: 1 }); + }); + + it('supports returned polymorphic functions and typed object callbacks', () => { + expect( + run(`${schema} + type Encoder = (value:T)=>Uint8Array; + function factory(): Encoder { return encode; } + const callback = factory(); + const api: {encode:Encoder} = {encode}; + export const result = [[...callback({value:7})], [...api.encode({value:8})], [...factory()({value:9})]]; + `).result, + ).toEqual([ + [8, 7], + [8, 8], + [8, 9], + ]); + }); + + it('supports nested generic callback aliases', () => { + expect( + run(`${schema} + type Callback = (value:T)=>Uint8Array; + type Alias = Callback; + const callback: Alias = encode; + export const result = [...callback({value:7})]; + `).result, + ).toEqual([8, 7]); + }); + + it('passes all required codecs when callback implementations differ', () => { + expect( + run(`${schema} + interface Box {value:pb<1,T>;} + function boxed(value:T) { return protobuf_encode>({value}); } + function apply(value:T, callback:(value:U)=>Uint8Array) { return callback(value); } + export const result = [[...apply({value:7}, encode)], [...apply({value:8}, boxed)]]; + `).result, + ).toEqual([ + [8, 7], + [10, 2, 8, 8], + ]); + }); + + it('supports a callback implementation accepting fewer parameters than its signature', () => { + expect( + run(`${schema} + function apply(callback:(value:T, index:number)=>Uint8Array) { return callback({value:7}, 42); } + export const result = [...apply(encode)]; + `).result, + ).toEqual([8, 7]); + }); + + it('preserves default parameter evaluation and callback length', () => { + expect( + run(`${schema} + let defaults=0; + function callback(value:T, flag=++defaults) { return flag ? protobuf_encode(value) : new Uint8Array(); } + const cb = callback; + export const result = [...cb({value:7})]; + export const length = cb.length; + export {defaults}; + `), + ).toEqual({ result: [8, 7], length: 1, defaults: 1 }); + }); + + it('propagates nested schema substitutions through callback chains', () => { + expect( + run(`${schema} + interface Box {value:pb<1,T>;} + function nested(value:Box) { return protobuf_encode>(value); } + function apply(value:Box, fn:(value:Box)=>Uint8Array) { return fn(value); } + export const result = [...apply({value:{value:7}}, nested)]; + `).result, + ).toEqual([10, 2, 8, 7]); + }); + + it('preserves async callback bodies', async () => { + const result = run(`${schema} + async function send(value:T) { await Promise.resolve(); return protobuf_encode(value); } + const values: Msg[] = [{value:7},{value:8}]; + export const result = Promise.all(values.map(send)); + `); + expect((await result.result).map((bytes: Uint8Array) => [...bytes])).toEqual([ + [8, 7], + [8, 8], + ]); + }); + it('materializes instantiation expressions in variables, returns and arrays', () => { + expect( + run(`${schema} + const callback = encode; + function factory() { return encode; } + const values = [encode, factory(), callback]; + export const result = values.map(fn => [...fn({value:7})]); + `).result, + ).toEqual([ + [8, 7], + [8, 7], + [8, 7], + ]); + }); + + it('infers array callbacks and preserves side effects and rest arguments', () => { + expect( + run(`${schema} + const values: Msg[] = [{value:7}, {value:8}]; + const calls: number[] = []; + function callback(value:T, ...rest: unknown[]) { calls.push(rest[0] as number); return protobuf_encode(value); } + export const result = values.map(callback).map(bytes => [...bytes]); + export { calls }; + `), + ).toEqual({ + result: [ + [8, 7], + [8, 8], + ], + calls: [0, 1], + }); + }); + + it('adapts runtime function values directly', () => { + expect( + run(`${schema} + const values: Msg[] = [{value:7}]; + const encodeMsg = protobuf_encode; + const decodeMsg: (bytes: Uint8Array) => Msg = protobuf_decode; + export const result = [decodeMsg(encodeMsg(values[0])), ...values.map(protobuf_encode).map(decodeMsg)]; + `).result, + ).toEqual([{ value: 7 }, { value: 7 }]); + }); + + it('passes codecs through a generic higher order function', () => { + expect( + run(`${schema} + function apply(value:T, callback:(value:T)=>Uint8Array) { return callback(value); } + export const result = [...apply({value:7}, encode)]; + `).result, + ).toEqual([8, 7]); + }); + + it('supports independently generic callbacks and transitive forwarding', () => { + expect( + run(`${schema} + type Encoder = (value:T)=>Uint8Array; + function invoke(value:T, callback:Encoder) { return callback(value); } + function forward(value:T, callback:Encoder) { return invoke(value, callback); } + export const result = [...forward({value:7}, encode)]; + `).result, + ).toEqual([8, 7]); + }); + + it('keeps distinct schemas when one generic callback is reused', () => { + expect( + run(`${schema} + interface Text { value: pb<1,string>; } + function both(callback:(value:T)=>Uint8Array) { + return [[...callback({value:7})], [...callback({value:'x'})]]; + } + export const result = both(encode); + `).result, + ).toEqual([ + [8, 7], + [10, 1, 120], + ]); + }); + + it('captures codecs in returned callbacks and contextual aliases', () => { + expect( + run(`${schema} + type Encoder = (value:T)=>Uint8Array; + function factory(): Encoder { return encode; } + const callback: Encoder = encode; + export const result = [[...callback({value:7})], [...factory()({value:8})]]; + `).result, + ).toEqual([ + [8, 7], + [8, 8], + ]); + }); + + it('supports generic inline callbacks and preserves native thisArg', () => { + expect( + run(`${schema} + const values: Msg[] = [{value:7}]; + const state = { calls:0 }; + function callback(value:T) { this.calls++; return protobuf_encode(value); } + export const a = values.map(callback, state).map(bytes => [...bytes]); + export const b = values.map((value:T) => protobuf_encode(value)).map(bytes => [...bytes]); + export const calls = state.calls; + `), + ).toEqual({ a: [[8, 7]], b: [[8, 7]], calls: 1 }); + }); + + it('handles imported higher order functions and callback aliases', async () => { + expect( + await bundle({ + 'encoder.ts': `${imports} export function encode(value:T) { return protobuf_encode(value); }`, + 'apply.ts': `export function apply(value:T, fn:(value:U)=>Uint8Array) { return fn(value); }`, + 'entry.ts': `import {encode as callback} from './encoder'; import {apply} from './apply'; interface Msg {value:pb<1,uint_32>;} export const result = [...apply({value:7}, callback)];`, + }), + ).toEqual({ result: [8, 7] }); + }); +}); diff --git a/packages/proton/test/upstream/compiler/classes.test.ts b/packages/proton/test/upstream/compiler/classes.test.ts new file mode 100644 index 00000000..632d32ff --- /dev/null +++ b/packages/proton/test/upstream/compiler/classes.test.ts @@ -0,0 +1,196 @@ +import { bundle } from '../project'; +import { describe, expect, it } from 'vitest'; +import { run, imports } from '../compile'; +import { ProtobufCompiler } from '../../../src/compiler/compiler'; + +const box = 'interface Box {value:pb<1,T>;}'; +const codec = `${box} + class Codec { + encode(value:Box) {return protobuf_encode>(value);} + decode(bytes:Uint8Array) {return protobuf_decode>(bytes);} + }`; + +describe('generic class instances', () => { + it('isolates uint32 and string instances across alternating calls', () => { + const result = run(`${codec} + const numbers=new Codec(); const strings=new Codec(); + export const result=Array.from({length:32},(_,i)=>[numbers.decode(numbers.encode({value:i})),strings.decode(strings.encode({value:'v'+i}))]); + export const sharedMethod=numbers.encode===strings.encode; + export const keys=Object.keys(numbers); + `); + expect(result.result).toEqual( + Array.from({ length: 32 }, (_, i) => [{ value: i }, { value: 'v' + i }]), + ); + expect(result.sharedMethod).toBe(true); + expect(result.keys).toEqual([]); + }); + + it('emits one codec per concrete type for many instances', () => { + const declarations = Array.from( + { length: 32 }, + (_, i) => `const n${i}=new Codec(); const s${i}=new Codec();`, + ).join('\n'); + const output = new ProtobufCompiler().compile(imports + codec + declarations, 'reuse.ts')!; + expect(output.match(/function protobuf_encode_Box__uint_32\(/g)).toHaveLength(1); + expect(output.match(/function protobuf_decode_Box__uint_32\(/g)).toHaveLength(1); + expect(output.match(/function protobuf_encode_Box__string\(/g)).toHaveLength(1); + expect(output.match(/function protobuf_decode_Box__string\(/g)).toHaveLength(1); + }); + + it('alternates method type arguments on one instance', () => { + expect( + run(`${box} + class Codec {roundtrip(value:Box) {return protobuf_decode>(protobuf_encode>(value));}} + const instance=new Codec(); + export const result=[instance.roundtrip({value:7}),instance.roundtrip({value:'x'}),instance.roundtrip({value:8})]; + `).result, + ).toEqual([{ value: 7 }, { value: 'x' }, { value: 8 }]); + }); + + it('forwards outer generics through factories returning class instances', () => { + expect( + run(`${codec} + function create() {return new Codec();} + const n=create(); const s=create(); + export const result=[n.decode(n.encode({value:7})),s.decode(s.encode({value:'x'}))]; + `).result, + ).toEqual([{ value: 7 }, { value: 'x' }]); + }); + + it('combines factory class arguments and independent method arguments', () => { + expect( + run(`interface Pair {first:pb<1,T>;second:pb<2,U>;} + class Codec {roundtrip(value:Pair) {return protobuf_decode>(protobuf_encode>(value));}} + function create():Codec {return new Codec();} + const n=create(); const s=create(); const alias=n; + export const result=[n.roundtrip({first:7,second:'x'}),s.roundtrip({first:'y',second:8}),alias.roundtrip({first:9,second:10}),create().roundtrip({first:'a',second:'b'})]; + `).result, + ).toEqual([ + { first: 7, second: 'x' }, + { first: 'y', second: 8 }, + { first: 9, second: 10 }, + { first: 'a', second: 'b' }, + ]); + }); + + it('infers constructor generics from annotated arguments', () => { + expect( + run(`${box} + class Codec {constructor(readonly value:Box) {} encode(){return protobuf_encode>(this.value);}} + const n:Box={value:7}; const s:Box={value:'x'}; + const numbers=new Codec(n); const strings=new Codec(s); + export const result=[[...numbers.encode()],[...strings.encode()]]; + `).result, + ).toEqual([ + [8, 7], + [10, 1, 120], + ]); + }); + + it('infers factories and inherited constructors with renamed parameters', () => { + expect( + run(`${box} + class Codec {constructor(readonly value:Box) {} encode(){return protobuf_encode>(this.value);}} + class Middle extends Codec {} + class Derived extends Middle {} + function create(value:Box) {return new Derived(value);} + const n:Box={value:7}; const s:Box={value:'x'}; + const numbers=create(n); const strings=create(s); + export const result=[[...numbers.encode()],[...strings.encode()]]; + `).result, + ).toEqual([ + [8, 7], + [10, 1, 120], + ]); + }); + + it('specializes unannotated factories, aliases and default class arguments', () => { + expect( + run(`interface Pair {first:pb<1,T>;second:pb<2,U>;} + class Codec {roundtrip(value:Pair) {return protobuf_decode>(protobuf_encode>(value));}} + const create=()=>new Codec(); + type Alias = Codec; + function use(instance:Alias, first:T) {return instance.roundtrip({first,second:'ok'});} + export const result=[create().roundtrip({first:7,second:'x'}),new Codec().roundtrip({first:'y',second:8}),use(create(),'z')]; + `).result, + ).toEqual([ + { first: 7, second: 'x' }, + { first: 'y', second: 8 }, + { first: 'z', second: 'ok' }, + ]); + }); + + it('retains class bindings in generic callback adapters', () => { + expect( + run(`interface Pair {first:pb<1,T>;second:pb<2,U>;} + class Codec {roundtrip(value:Pair) {return protobuf_decode>(protobuf_encode>(value));}} + function create():Codec {return new Codec();} + const numbers=create(); const strings=create(); + const n=numbers.roundtrip.bind(numbers); const s=strings.roundtrip.bind(strings); + export const result=[n({first:7,second:'x'}),s({first:'y',second:8})]; + `).result, + ).toEqual([ + { first: 7, second: 'x' }, + { first: 'y', second: 8 }, + ]); + }); + + it('separates specializations through inherited constructors', () => { + expect( + run(`${codec} + class Derived extends Codec {} + const n=new Derived(); const s=new Derived(); + export const result=[n.decode(n.encode({value:7})),s.decode(s.encode({value:'x'}))]; + `).result, + ).toEqual([{ value: 7 }, { value: 'x' }]); + }); + + it('keeps cross-file factory instances specialized', async () => { + expect( + await bundle({ + 'codec.ts': `${imports} ${codec} export function create() {return new Codec();}`, + 'entry.ts': `import {create} from './codec'; const n=create();const s=create(); export const result=[n.decode(n.encode({value:7})),s.decode(s.encode({value:'x'}))];`, + }), + ).toEqual({ result: [{ value: 7 }, { value: 'x' }] }); + }); + + it('resolves method defaults from the class type argument', () => { + expect( + run(`interface Pair {first:pb<1,T>;second:pb<2,U>;} + class Codec {roundtrip(value:Pair) {return protobuf_decode>(protobuf_encode>(value));}} + function create():Codec {return new Codec();} + export const result=[create().roundtrip({first:7,second:8}),create().roundtrip({first:'x',second:'y'})]; + `).result, + ).toEqual([ + { first: 7, second: 8 }, + { first: 'x', second: 'y' }, + ]); + }); + + it('specializes inherited static generic methods', () => { + expect( + run(`${box} + class Base {static roundtrip(value:Box) {return protobuf_decode>(protobuf_encode>(value));}} + class Codec extends Base {} + export const result=[Codec.roundtrip({value:7}),Codec.roundtrip({value:'x'})]; + `).result, + ).toEqual([{ value: 7 }, { value: 'x' }]); + }); + + it('combines cross-file class and method generics', async () => { + expect( + await bundle({ + 'codec.ts': `${imports} export interface Pair {first:pb<1,T>;second:pb<2,U>;} + class Codec {roundtrip(value:Pair) {return protobuf_decode>(protobuf_encode>(value));}} + export const create=()=>new Codec();`, + 'entry.ts': `import {create} from './codec'; const n=create(); const s=create(); + export const result=[n.roundtrip({first:7,second:'x'}),s.roundtrip({first:'y',second:8})];`, + }), + ).toEqual({ + result: [ + { first: 7, second: 'x' }, + { first: 'y', second: 8 }, + ], + }); + }); +}); diff --git a/packages/proton/test/upstream/compiler/compile.test.ts b/packages/proton/test/upstream/compiler/compile.test.ts new file mode 100644 index 00000000..de129d17 --- /dev/null +++ b/packages/proton/test/upstream/compiler/compile.test.ts @@ -0,0 +1,424 @@ +import { bundle } from '../project'; +import { packageName } from '../../../src/package'; +import { describe, expect, it } from 'vitest'; +import { ProtobufCompiler } from '../../../src/compiler/compiler'; + +import { run, imports } from '../compile'; + +describe('semantic compiler', () => { + it('invalidates preloaded schema types when the transform receives different source', () => { + const compiler = new ProtobufCompiler(); + const source = `${imports} interface Msg {value:pb<1,uint_32>;} protobuf_encode({value:7});`; + compiler.context.source('preloaded.ts', source); + compiler.prepare(['preloaded.ts']); + expect(compiler.compile(source.replace('pb<1,', 'pb<2,'), 'preloaded.ts')).toContain( + 'buf[offset++] = 16;', + ); + }); + it('preserves async generic function bodies and return values', async () => { + const result = run(`interface Msg { value: pb<1,uint_32>; } + async function encode(value:T) { await Promise.resolve(); return protobuf_encode(value); } + export const result = encode({value:7}); + `); + expect([...(await result.result)]).toEqual([8, 7]); + }); + it('supports namespace markers and namespace runtime functions', () => { + expect( + run(` + import * as p from '${packageName}'; + interface Msg { value: p.pb<1, p.uint_32>; } + export const result = [...p.protobuf_encode({value: 7})]; + `).result, + ).toEqual([8, 7]); + }); + + it('supports default generic classes and re-exported runtime bindings', async () => { + expect( + await bundle({ + 'runtime.ts': `export { protobuf_encode as encode } from '${packageName}';`, + 'codec.ts': `import { encode } from './runtime'; export default class Codec { encode(value:T) { return encode(value); } }`, + 'entry.ts': `import Codec from './codec'; interface Msg { value: pb<1,uint_32>; } const codec = new Codec(); export const result = [...codec.encode({value:7})];`, + }), + ).toEqual({ result: [8, 7] }); + }); + + it('resolves generic parameters containing dollar signs without text substitution', () => { + expect( + run(`interface Box<$T> { value: pb<1,$T>; } + function encode<$T>(value:Box<$T>) { return protobuf_encode>(value); } + export const result = [...encode({value:'x'})]; + `).result, + ).toEqual([10, 1, 120]); + }); + + it('preserves directive prologues', () => { + const code = `'use client';\n${imports}\ninterface Msg { value: pb<1,uint_32>; } protobuf_encode({value:7});`; + expect(new ProtobufCompiler().compile(code, 'directive.ts')).toMatch(/^'use client';/); + }); + + it('does not mix anonymous fields instantiated with different generic arguments', () => { + expect( + run(` + interface Box { nested: pb<1, { value: pb<1, T>; }>; } + export const a = protobuf_decode>(protobuf_encode>({ nested: { value: 7 } })); + export const b = protobuf_decode>(protobuf_encode>({ nested: { value: 'x' } })); + `), + ).toEqual({ a: { nested: { value: 7 } }, b: { nested: { value: 'x' } } }); + }); + + it('evaluates conditional schema types structurally', () => { + expect( + run(` + interface Base { id: pb<1, uint_32>; } + interface Child extends Base { text: pb<2, string>; } + type Chosen = T extends Base ? Child : never; + export const result = protobuf_decode>(protobuf_encode>({ id: 7, text: 'x' })); + `).result, + ).toEqual({ id: 7, text: 'x' }); + }); + + it('supports destructured generic object methods and aliases', () => { + expect( + run(` + interface Msg { value: pb<1, uint_32>; } + const api = { encode(value: T) { return protobuf_encode(value); } }; + const { encode: send } = api; + export const result = [...send({ value: 7 })]; + `).result, + ).toEqual([8, 7]); + }); + + it('rejects generic callbacks without a concrete adapter', () => { + expect(() => + run(` + interface Msg { value: pb<1, uint_32>; } + function encode(value: T) { return protobuf_encode(value); } + [{ value: 7 }].map(encode); + `), + ).toThrow(/Cannot infer callback schema/); + }); + + it('rejects detached instance codec methods', () => { + expect(() => + run(`interface Msg { value: pb<1,uint_32>; } + class Codec { encode(value:T) { return protobuf_encode(value); } } + const codec = new Codec(); const encode = codec.encode; + `), + ).toThrow(/receiver/); + }); + + it('rejects class field calls that run before codec initialization', () => { + expect(() => run(`class Codec { value = protobuf_encode({} as T); }`)).toThrow( + /field initializers/, + ); + }); + + it('keeps function length stable after generic codec injection', () => { + expect( + run(` + interface Msg { value: pb<1, uint_32>; } + function encode(value: T) { return protobuf_encode(value); } + export const length = encode.length; + export const result = [...encode({ value: 7 })]; + `), + ).toEqual({ length: 1, result: [8, 7] }); + }); + + it('reuses exact transform results and clears changed-source caches', () => { + const compiler = new ProtobufCompiler(); + const source = `${imports} interface Msg { value: pb<1, uint_32>; } protobuf_encode({value: 7});`; + const first = compiler.compile(source, 'cache.ts'); + expect(compiler.compile(source, 'cache.ts')).toBe(first); + const second = compiler.compile(source.replace('pb<1,', 'pb<2,'), 'cache.ts'); + expect(second).toContain('buf[offset++] = 16;'); + expect(second).not.toEqual(first); + }); + + it('resolves tsconfig path aliases', async () => { + expect( + await bundle({ + 'tsconfig.json': JSON.stringify({ + compilerOptions: { baseUrl: '.', paths: { '@schema/*': ['schema/*'] } }, + }), + 'schema/msg.ts': 'export interface Msg { value: pb<1, uint_32>; }', + 'entry.ts': `${imports} import type { Msg } from '@schema/msg'; export const result = [...protobuf_encode({value:7})];`, + }), + ).toEqual({ result: [8, 7] }); + }); + + it('supports recursive generic aliases and nested generic inference', () => { + expect( + run(` + type Node = { value: pb<1, T>; next?: pb<2, Node>; }; + function encode(value: Node) { return protobuf_encode>(value); } + const value: Node = { value: 'a', next: { value: 'b' } }; + export const result = protobuf_decode>(encode(value)); + `).result, + ).toEqual({ value: 'a', next: { value: 'b', next: null } }); + }); + + it('supports inferred generic forwarding and inherited generic methods', () => { + expect( + run(` + interface Pair { a: pb<1, T>; b: pb<2, U>; } + class Base { encode(v: Pair) { return protobuf_encode>(v); } } + class Derived extends Base {} + const codec = new Derived(); + export const result = [...codec.encode({ a: 7, b: 'x' })]; + `).result, + ).toEqual([8, 7, 18, 1, 120]); + }); + + it('keeps generated helper names and user property strings separate', () => { + expect( + run(` + const __td = 'user decoder'; + const protobuf_encode_Msg = 'user encoder'; + interface Msg { '__td': pb<1, string>; } + export const result = protobuf_decode(protobuf_encode({ __td: 'ok' })); + export const untouched = [__td, protobuf_encode_Msg]; + `), + ).toEqual({ result: { __td: 'ok' }, untouched: ['user decoder', 'user encoder'] }); + }); + + it('shares codecs across distinct instantiations without mixing schemas', () => { + expect( + run(` + interface A { value: pb<1, uint_32>; } + interface B { value: pb<2, string>; } + const encode = (value: T) => protobuf_encode(value); + export const result = [[...encode({ value: 7 })], [...encode({ value: 'x' })]]; + `).result, + ).toEqual([ + [8, 7], + [18, 1, 120], + ]); + }); + + it('supports generic field-number aliases and preserves mapped optionality', () => { + expect( + run(` + type Field = pb_optional; + interface Msg { value?: Field<3, uint_32>; } + type Copy = { [K in keyof T]: T[K] }; + export const result = [...protobuf_encode>({ value: 0 })]; + `).result, + ).toEqual([24, 0]); + }); + + it('forwards codecs through implicit and explicit generic derived constructors', () => { + expect( + run(` + interface Msg { value: pb<1, uint_32>; } + class Base { + constructor(public label = 'base') {} + encode(value: T) { return protobuf_encode(value); } + } + class Middle extends Base {} + class Derived extends Middle { + constructor(label: string) { super(label); } + } + const codec = new Derived('ok'); + export const result = [...codec.encode({ value: 7 })]; + export const label = codec.label; + `), + ).toEqual({ result: [8, 7], label: 'ok' }); + }); + + it('forwards concrete codecs through a non-generic derived class', () => { + expect( + run(` + interface Msg { value: pb<1, uint_32>; } + class Base { encode(value: T) { return protobuf_encode(value); } } + class Codec extends Base {} + export const result = [...new Codec().encode({ value: 7 })]; + `).result, + ).toEqual([8, 7]); + }); + + it('preserves explicitly present optional default values and quoted field names', () => { + const result = run(` + interface Msg { 'a-b'?: pb_optional<1, uint_32>; flag?: pb_optional<2, bool>; text?: pb_optional<3, string>; big?: pb_optional<4, uint_64>; '__proto__'?: pb<5, string>; } + const input = { 'a-b': 0, flag: false, text: '', big: 0n, ['__proto__']: 'safe' }; + export const result = protobuf_decode(protobuf_encode(input)); + `).result; + expect(result).toEqual({ 'a-b': 0, flag: false, text: '', big: 0n, ['__proto__']: 'safe' }); + expect(Object.getPrototypeOf(result)).toBe(Object.prototype); + }); + it('preserves imported generic wrappers and transitive aliases across .js imports and barrels', async () => { + const result = await bundle({ + 'types.ts': `export interface Box { value: pb<1, T>; }`, + 'codec.ts': `${imports} import type { Box as B } from './types.js'; + let count = 0; + export function wrap(value: B) { count++; return protobuf_encode>(value); } + export function calls() { return count; }`, + 'barrel.ts': `export { wrap as encode, calls } from './codec.js'; export type { Box as Shape } from './types.js';`, + 'entry.ts': `${imports} import { encode, calls } from './barrel.js'; import type { Shape } from './barrel.js'; + export const result = protobuf_decode>(encode({ value: 'ok' })); + export const count = calls();`, + }); + expect(result).toEqual({ result: { value: 'ok' }, count: 1 }); + }); + + it('keeps same-named schemas from different files distinct', async () => { + const result = await bundle({ + 'a.ts': `export interface Msg { value: pb<1, uint_32>; }`, + 'b.ts': `export interface Msg { value: pb<2, string>; }`, + 'entry.ts': `${imports} import type { Msg as A } from './a'; import type * as b from './b'; + export const a = [...protobuf_encode({ value: 7 })]; + export const b = [...protobuf_encode({ value: 'x' })];`, + }); + expect(result).toEqual({ a: [8, 7], b: [18, 1, 120] }); + }); + + it('supports generic arrow functions and rest parameters without reordering user arguments', () => { + expect( + run(` + interface Msg { value: pb<1, uint_32>; } + const encode = (value: T, ...suffix: number[]) => [...protobuf_encode(value), ...suffix]; + export const result = encode({ value: 7 }, 9, 10); + `).result, + ).toEqual([8, 7, 9, 10]); + }); + + it('does not rewrite shadowed protobuf identifiers or unrelated object methods', () => { + expect( + run(` + interface Msg { value: pb<1, uint_32>; } + function custom(protobuf_encode: (v: T) => number) { return protobuf_encode({ value: 7 }); } + const unrelated = { encode(value: T) { return value; } }; + export const result = custom(() => 99) + unrelated.encode(1); + `).result, + ).toBe(100); + }); + + it('preserves generic wrapper branches, argument positions, closures and side effects', () => { + const result = run(` + interface Msg { value: pb<1, uint_32>; } + let count = 0; + function wrap(ignored: I, data: T, enabled = true) { + count++; + if (!enabled) return new Uint8Array([99]); + return protobuf_encode(data); + } + export const a = [...wrap('unused', { value: 7 })]; + export const b = [...wrap('unused', { value: 8 }, false)]; + export const calls = count; + `); + expect(result).toEqual({ a: [8, 7], b: [99], calls: 2 }); + }); + + it('propagates concrete codecs through multiple generic functions and nested closures', () => { + const result = run(` + interface Box { value: pb<1, T>; } + function inner(value: Box) { return protobuf_encode>(value); } + function outer(value: Box) { + function forward() { return inner(value); } + return forward(); + } + export const result = protobuf_decode>(outer({ value: 'ok' })); + `); + expect(result.result).toEqual({ value: 'ok' }); + }); + + it('resolves aliases, generic defaults, inheritance, intersections and indexed access', () => { + const result = run(` + type Scalar = uint_32; + interface Base { id: pb<1, T>; } + interface Extra { title: pb<2, string>; } + interface Child extends Base { title: Extra['title']; } + type Alias = T; + type Shape = Alias>; + export const result = protobuf_decode(protobuf_encode({ id: 7, title: 'x' })); + `); + expect(result.result).toEqual({ id: 7, title: 'x' }); + }); + + it('supports mapped and conditional generic types', () => { + const result = run(` + interface Msg { id: pb<1, uint_32>; text: pb<2, string>; } + type Copy = { [K in keyof T]: T[K] }; + type Choice = T extends string ? Copy : never; + export const result = protobuf_decode>(protobuf_encode>({ id: 5, text: 'ok' })); + `); + expect(result.result).toEqual({ id: 5, text: 'ok' }); + }); + + it('passes class type parameters through constructor and instance methods', () => { + const result = run(` + interface Msg { value: pb<1, uint_32>; } + class Codec { + constructor(public label = 'default') {} + encode(data: T) { return protobuf_encode(data); } + decode(bytes: Uint8Array) { return protobuf_decode(bytes); } + } + const a = new Codec(); + const b = new Codec('named'); + export const result = a.decode(b.encode({ value: 9 })); + export const labels = [a.label, b.label]; + export const keys = Object.keys(a); + `); + expect(result).toEqual({ + result: { value: 9 }, + labels: ['default', 'named'], + keys: ['label'], + }); + }); + + it('supports generic class methods with class and method type arguments', () => { + const result = run(` + interface Pair { first: pb<1, T>; second: pb<2, U>; } + class Codec { + encode(value: Pair) { return protobuf_encode>(value); } + } + const codec = new Codec(); + export const result = protobuf_decode>(codec.encode({ first: 7, second: 'x' })); + `); + expect(result.result).toEqual({ first: 7, second: 'x' }); + }); + + it('supports recursive message schemas and nullable links', () => { + const result = run(` + interface Node { value: pb<1, uint_32>; next?: pb<2, Node | undefined>; } + export const result = protobuf_decode(protobuf_encode({ value: 1, next: { value: 2 } })); + `); + expect(result.result).toEqual({ value: 1, next: { value: 2, next: null } }); + }); + + it('infers a generic argument from an annotated variable', () => { + const result = run(` + interface Msg { value: pb<1, uint_32>; } + const data: Msg = { value: 7 }; + function wrap(value: T) { return protobuf_encode(value); } + export const result = [...wrap(data)]; + `); + expect(result.result).toEqual([8, 7]); + }); + + it('does not inspect unused unsupported schema declarations', () => { + expect( + run(` + interface Unused { value: pb<1, MissingType>; } + interface Msg { value: pb<1, uint_32>; } + export const result = [...protobuf_encode({ value: 7 })]; + `).result, + ).toEqual([8, 7]); + }); + + it.each(['0', '-1', '1.5', '19000', '536870912'])( + 'rejects invalid field number %s at compile time', + (number) => { + expect(() => + run( + `interface Msg { value: pb<${number}, uint_32>; } protobuf_encode({ value: 7 });`, + ), + ).toThrow(packageName); + }, + ); + + it('rejects duplicate field numbers', () => { + expect(() => + run('interface Msg { a: pb<1, uint_32>; b: pb<1, string>; } protobuf_encode({});'), + ).toThrow(/Duplicate/); + }); +}); diff --git a/packages/proton/test/upstream/compiler/composition.test.ts b/packages/proton/test/upstream/compiler/composition.test.ts new file mode 100644 index 00000000..79bc82a9 --- /dev/null +++ b/packages/proton/test/upstream/compiler/composition.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, it } from 'vitest'; +import { run, imports } from '../compile'; +import { bundle } from '../project'; +import { packageName } from '../../../src/package'; + +const schema = + 'interface Box {value:pb<1,T>;} interface Pair {first:pb<1,T>;second:pb<2,U>;}'; +const codec = `${schema} class Codec { + roundtrip(value:Pair) {return protobuf_decode>(protobuf_encode>(value));} +}`; + +describe('generic composition', () => { + it('propagates two specializations across a 64-function call chain', () => { + const functions = Array.from( + { length: 64 }, + (_, i) => + `function f${i}(value:Box) {return ${i === 63 ? 'protobuf_encode>(value)' : `f${i + 1}(value)`};}`, + ).join('\n'); + expect( + run( + `${schema} ${functions} export const result=[[...f0({value:7})],[...f0({value:'x'})]];`, + ).result, + ).toEqual([ + [8, 7], + [10, 1, 120], + ]); + }); + + it('composes deferred mapped types, promises, classes and polymorphic callbacks', () => { + expect( + run(` + interface Msg {id:pb<1,uint_32>;text:pb<2,string>;ignore:pb<3,bool>;} + type Payload = Pick,'id'|'text'>; + interface Envelope {value:pb<1,Payload>;} + function encode(value:Envelope) {return protobuf_encode>(value);} + function apply(value:Envelope,fn:(value:Envelope)=>Uint8Array) {return fn(value);} + class Codec {encode(value:Envelope){return apply(value,encode);}} + const codec=new Codec>(); + export const result=protobuf_decode>(codec.encode({value:{id:7,text:'x'}})); + `).result, + ).toEqual({ value: { id: 7, text: 'x' } }); + }); + it('retains outer type arguments across nested local factories', () => { + expect( + run(`${codec} + function outer() {function inner() {return new Codec();} return inner();} + const n=outer(); const s=outer(); + export const result=[n.roundtrip({first:7,second:'x'}),s.roundtrip({first:'y',second:8})]; + `).result, + ).toEqual([ + { first: 7, second: 'x' }, + { first: 'y', second: 8 }, + ]); + }); + + it('resolves instances through parameter properties and getters', () => { + expect( + run(`${codec} + class Holder { + constructor(readonly codec:Codec) {} + get current():Codec {return this.codec;} + } + const holder=new Holder(new Codec()); + export const result=holder.current.roundtrip({first:'x',second:7}); + `).result, + ).toEqual({ first: 'x', second: 7 }); + }); + + it('resolves static element access without changing this', () => { + expect( + run(`${codec} + const c=new Codec(); + export const result=c['roundtrip']({first:7,second:'x'}); + `).result, + ).toEqual({ first: 7, second: 'x' }); + }); + + it('supports overloaded generic methods and constructors', () => { + expect( + run(`${schema} + class Codec { + value:Box; + constructor(value:Box); + constructor(value:Box, label:string); + constructor(value:Box, public label='default') {this.value=value;} + encode() {return protobuf_encode>(this.value);} + roundtrip(value:Box):Box; + roundtrip(value:Box):Box {return protobuf_decode>(protobuf_encode>(value));} + } + const n:Box={value:7}; const c=new Codec(n); + export const result=[[...c.encode()],c.roundtrip({value:'x'}),c.label]; + `).result, + ).toEqual([[8, 7], { value: 'x' }, 'default']); + }); + + it('forwards shadowed generic names through deeply nested callbacks', () => { + expect( + run(`${schema} + function roundtrip(value:Box) {return protobuf_decode>(protobuf_encode>(value));} + function outer(first:Box, fn:(value:Box)=>Box) { + function middle(next:Box) { + function inner(value:Box) {return fn(value);} + return [inner(first),inner(next)]; + } + return middle({value:'x'}); + } + export const result=outer({value:7},roundtrip); + `).result, + ).toEqual([{ value: 7 }, { value: 'x' }]); + }); + + it('converges through mutually recursive generic functions', () => { + expect( + run(`${schema} + function a(value:Box, depth:number):Box {return depth ? b(value,depth-1) : protobuf_decode>(protobuf_encode>(value));} + function b(value:Box, depth:number):Box {return a(value,depth);} + export const result=[a({value:7},32),a({value:'x'},33)]; + `).result, + ).toEqual([{ value: 7 }, { value: 'x' }]); + }); + + it('keeps class factory specializations through cyclic re-export modules', async () => { + expect( + await bundle({ + 'codec.ts': `${imports} ${codec} export const create=()=>new Codec();`, + 'first.ts': `export * from './second'; export {create} from './codec';`, + 'second.ts': `export * from './first';`, + 'entry.ts': `import {create} from './second'; export const result=create().roundtrip({first:'x',second:7});`, + }), + ).toEqual({ result: { first: 'x', second: 7 } }); + }); + + it('recognizes parenthesized runtime aliases and namespace element access', () => { + expect( + run(`${schema} import * as runtime from '${packageName}'; + const encode=protobuf_encode; const alias=encode; + export const result=[ + [...(alias)>({value:7})], + runtime['protobuf_decode']>(runtime['protobuf_encode']>({value:'x'})) + ]; + `).result, + ).toEqual([[8, 7], { value: 'x' }]); + }); + + it('adapts typed callbacks selected by static element access', () => { + expect( + run(`${codec} + const c=new Codec(); + const callback:(value:Pair)=>Pair = c['roundtrip'].bind(c); + export const result=callback({first:7,second:'x'}); + `).result, + ).toEqual({ first: 7, second: 'x' }); + }); + + it('captures outer generics in a local class returned from a factory', () => { + expect( + run(`${schema} + function create() { + class Local {roundtrip(value:Pair) {return protobuf_decode>(protobuf_encode>(value));}} + return new Local(); + } + export const result=[create().roundtrip({first:7,second:'x'}),create().roundtrip({first:'y',second:8})]; + `).result, + ).toEqual([ + { first: 7, second: 'x' }, + { first: 'y', second: 8 }, + ]); + }); + + it('resolves namespaced base schemas and separates imported type and value names', async () => { + expect( + await bundle({ + 'types.ts': `export interface Base {value:pb<1,T>;} export const Base=123;`, + 'entry.ts': `${imports} import type * as types from './types'; + interface Msg extends types.Base {text:pb<2,string>;} + export const result=protobuf_decode>(protobuf_encode>({value:7,text:'x'}));`, + }), + ).toEqual({ result: { value: 7, text: 'x' } }); + }); + + it('keeps valid recursive references through inherited generic fields', () => { + expect( + run(` + interface Base {next:pb<1,Link|null>;} + interface Link extends Base {value:pb<2,T>;} + const value:Link={value:'a',next:{value:'b',next:null}}; + export const result=protobuf_decode>(protobuf_encode>(value)); + `).result, + ).toEqual({ value: 'a', next: { value: 'b', next: null } }); + }); + + it('resolves imported type and value names independently of declaration order', async () => { + expect( + await bundle({ + 'types.ts': `export const Msg=42; export interface Msg {value:pb<1,uint_32>;}`, + 'barrel.ts': `export {Msg} from './types';`, + 'entry.ts': `${imports} import {Msg} from './barrel'; export const result=[Msg,[...protobuf_encode({value:7})]];`, + }), + ).toEqual({ result: [42, [8, 7]] }); + }); +}); diff --git a/packages/proton/test/upstream/compiler/diagnostics.test.ts b/packages/proton/test/upstream/compiler/diagnostics.test.ts new file mode 100644 index 00000000..fd15a9a4 --- /dev/null +++ b/packages/proton/test/upstream/compiler/diagnostics.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, it } from 'vitest'; +import { ProtobufCompiler } from '../../../src/compiler/compiler'; +import { imports, run } from '../compile'; +import { withProject } from '../project'; +import { join } from 'node:path'; +import { writeFileSync } from 'node:fs'; + +describe('compiler failure recovery', () => { + it('rejects circular class inheritance without looping during member resolution', () => { + expect(() => + run( + `class A extends B {} class B extends A {} new A().missing();`, + ), + ).toThrow(/Circular class inheritance/); + }); + + it('rejects circular schema inheritance without caching an empty message', () => { + expect(() => + run(`interface A extends B {} interface B extends A {} protobuf_encode({});`), + ).toThrow(/Circular schema inheritance/); + }); + it('does not cache a partially validated schema after failure', () => { + const compiler = new ProtobufCompiler(); + const source = `${imports} interface Msg {a:pb<1,uint_32>;b:pb<1,string>;} protobuf_encode({a:7,b:'x'});`; + + for (let i = 0; i < 3; i++) { + expect(() => compiler.compile(source, 'invalid.ts')).toThrow( + /Duplicate protobuf field number/, + ); + } + + expect(compiler.compile(source.replace('b:pb<1,', 'b:pb<2,'), 'invalid.ts')).toContain( + 'protobuf_encode_Msg', + ); + }); + + it('reports expanding recursive schema aliases before overflowing the stack', () => { + expect(() => + run( + `type Grow={value:pb<1,T>;next?:pb<2,Grow>>;}; protobuf_encode>({value:7});`, + ), + ).toThrow(/128 levels|does not converge/); + }); + + it('reports circular aliases with a source location', () => { + expect(() => run(`type A=B; type B=A; protobuf_encode({});`)).toThrow( + /test-entry.ts:\d+:\d+: Circular type alias/, + ); + }); + + it('replaces specialized code when the same module repeatedly changes wire types', () => { + const compiler = new ProtobufCompiler(); + + for (let i = 0; i < 32; i++) { + const type = i % 2 ? 'string' : 'uint_32'; + const other = i % 2 ? 'uint_32' : 'string'; + const source = `${imports} interface Box {value:pb<1,T>;} class Codec {encode(value:Box) {return protobuf_encode>(value);}} new Codec<${type}>();`; + const output = compiler.compile(source, 'changing.ts'); + expect(output).toContain(`function protobuf_encode_Box__${type}(`); + expect(output).not.toContain(`function protobuf_encode_Box__${other}(`); + } + }); + + it('rejects ambiguous factory specializations with a build diagnostic', () => { + expect(() => + run(`interface Box {value:pb<1,T>;} + class Codec {encode(value:Box) {return protobuf_encode>(value);}} + function create(flag:boolean) {if(flag) return new Codec();return new Codec();} + create(true).encode({value:7}); + `), + ).toThrow(/Receiver branches must resolve to the same specialization/); + }); + + it('reconstructs all entry requirements after a failed compilation', async () => { + const shared = + 'export function apply(value:T, fn:(value:U)=>Uint8Array) {return fn(value);}'; + await withProject( + { + 'shared.ts': shared, + 'a.ts': `${imports} import {apply} from './shared'; interface Msg {value:pb<1,uint_32>;} function encode(value:T) {return protobuf_encode(value);} apply({value:7},encode);`, + 'b.ts': `${imports} import {apply} from './shared'; interface Msg {value:pb<1,uint_32>;} interface Box {value:pb<1,T>;} function encode(value:T) {return protobuf_encode>({value});} apply({value:8},encode);`, + }, + (directory) => { + const compiler = new ProtobufCompiler(); + compiler.prepare([join(directory, 'a.ts'), join(directory, 'b.ts')]); + const baseline = compiler.compile(shared, join(directory, 'shared.ts')); + expect(() => + compiler.compile( + `${imports} protobuf_encode({});`, + join(directory, 'bad.ts'), + ), + ).toThrow(/Unresolved type/); + expect(compiler.compile(shared, join(directory, 'shared.ts'))).toBe(baseline); + }, + ); + }); + + it('recovers when entry preparation fails before a corrected source is saved', async () => { + const source = `${imports} interface Msg {value:pb<1,uint_32>;} function encode(value:T) {return protobuf_encode(value);} encode({value:7});`; + await withProject({ 'entry.ts': source }, (directory) => { + const compiler = new ProtobufCompiler(); + const file = join(directory, 'entry.ts'); + + for (let i = 0; i < 2; i++) { + expect(() => compiler.prepare([file])).toThrow(/Cannot infer T/); + } + + const corrected = source.replace('encode({', 'encode({'); + writeFileSync(file, corrected); + compiler.prepare([file]); + expect(compiler.compile(corrected, file)).toContain('protobuf_encode_Msg'); + }); + }); +}); diff --git a/packages/proton/test/upstream/compiler/evaluation.test.ts b/packages/proton/test/upstream/compiler/evaluation.test.ts new file mode 100644 index 00000000..535ba86a --- /dev/null +++ b/packages/proton/test/upstream/compiler/evaluation.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest'; +import { run } from '../compile'; + +const schema = 'interface Msg {value:pb<1,uint_32>;}'; + +describe('call evaluation', () => { + it('preserves optional receiver short circuiting and single evaluation', () => { + expect( + run(`${schema} + const events:string[]=[]; + class Codec {encode(value:T) {events.push('encode');return protobuf_encode(value);}} + function get(present:boolean):Codec|undefined {events.push('get');return present ? new Codec() : undefined;} + function argument():Msg {events.push('argument');return {value:7};} + export const absent=get(false)?.encode(argument()); + export const result=[...get(true)?.encode(argument())!]; + export {events}; + `), + ).toEqual({ + absent: undefined, + result: [8, 7], + events: ['get', 'get', 'argument', 'encode'], + }); + }); + + it('preserves getter receivers, multiple spreads and trailing commas', () => { + expect( + run(`${schema} + const events:string[]=[]; + const codec={encode(value:T,...labels:string[]) {events.push(...labels);return protobuf_encode(value);}}; + const holder={get current(){events.push('get');return codec;}}; + function values():[Msg] {events.push('values');return [{value:7}];} + function labels():string[] {events.push('labels');return ['a','b'];} + export const result=[...holder.current.encode(...values(),...labels(),)]; + export {events}; + `), + ).toEqual({ result: [8, 7], events: ['get', 'values', 'labels', 'a', 'b'] }); + }); + + it('evaluates constructor defaults before the body and preserves rest arguments', () => { + expect( + run(`${schema} + const events:string[]=[]; + class Codec { + constructor(public value:T, public bytes=protobuf_encode(value), ...labels:string[]) {events.push(...labels);} + decode() {return protobuf_decode(this.bytes);} + } + function args():[Msg,undefined,string,string] {events.push('args');return [{value:7},undefined,'a','b'];} + const c=new Codec(...args()); + export const result=c.decode(); export {events}; + export const length=Codec.length; + `), + ).toEqual({ result: { value: 7 }, events: ['args', 'a', 'b'], length: 1 }); + }); + + it('preserves default codec calls in generic callback implementations', () => { + expect( + run(`${schema} + function encode(value:T, bytes=protobuf_encode(value)) {return bytes;} + function apply(value:T, fn:(value:U, bytes?:Uint8Array)=>Uint8Array) {return fn(value);} + export const result=[...apply({value:7},encode)]; + `).result, + ).toEqual([8, 7]); + }); + + it('supports generator and async generator bodies', async () => { + const result = run(`${schema} + function* encode(value:T) {yield protobuf_encode(value);} + async function* later(value:T) {yield protobuf_encode(value);} + export const result=[...encode({value:7})].map(bytes=>[...bytes]); + export const pending=later({value:8}).next(); + `); + expect(result.result).toEqual([[8, 7]]); + expect([...(await result.pending).value]).toEqual([8, 8]); + }); +}); diff --git a/packages/proton/test/upstream/compiler/modules.test.ts b/packages/proton/test/upstream/compiler/modules.test.ts new file mode 100644 index 00000000..a7277e60 --- /dev/null +++ b/packages/proton/test/upstream/compiler/modules.test.ts @@ -0,0 +1,54 @@ +import { bundle } from '../project'; +import { describe, expect, it } from 'vitest'; +import { imports } from '../compile'; + +describe('module graph', () => { + it('resolves nested imported schemas and renamed exports', async () => { + expect( + await bundle({ + 'inner.ts': 'export interface Inner {value:pb<1,uint_32>;} ', + 'outer.ts': + "import type {Inner} from './inner'; export interface Outer {inner:pb<1,Inner>;}", + 'barrel.ts': "export {Outer as Message} from './outer';", + 'entry.ts': `${imports} import type {Message as Msg} from './barrel'; export const result = protobuf_decode(protobuf_encode({inner:{value:7}}));`, + }), + ).toEqual({ result: { inner: { value: 7 } } }); + }); + + it('keeps wrapper control flow, object receivers and transitive generic aliases', async () => { + expect( + await bundle({ + 'schema.ts': + 'export interface Box {value:pb<1,T>;} export type Message = Box>;', + 'codec.ts': `${imports} import type {Message} from './schema'; + export const api = { count:0, encode(value:Message, enabled=true) { + this.count++; if (!enabled) return new Uint8Array(); + const inner = () => protobuf_encode>(value); return inner(); + }};`, + 'entry.ts': `${imports} import {api} from './codec'; import type {Message} from './schema'; + export const result = protobuf_decode>(api.encode({value:{value:'x'}})); + export const empty = api.encode({value:{value:'x'}}, false).length; + export const count = api.count;`, + }), + ).toEqual({ result: { value: { value: 'x' } }, empty: 0, count: 2 }); + }); + + it('handles recursive types across modules', async () => { + expect( + await bundle({ + 'a.ts': "import type {B} from './b'; export interface A {value:pb<1,uint_32>; next?:pb<2,B>;}", + 'b.ts': "import type {A} from './a'; export interface B {text:pb<1,string>; next?:pb<2,A>;}", + 'entry.ts': `${imports} import type {A} from './a'; export const result = protobuf_decode(protobuf_encode({value:7,next:{text:'x'}}));`, + }), + ).toEqual({ result: { value: 7, next: { text: 'x', next: null } } }); + }); + + it('resolves nested generic functions with non-first schema parameters', async () => { + expect( + await bundle({ + 'codec.ts': `${imports} export function send(context:Context, value:T) { if (!context) throw new Error('context'); return protobuf_encode(value); }`, + 'entry.ts': `import {send} from './codec'; interface Msg {value:pb<1,uint_32>;} export const result = [...send('ok',{value:7})];`, + }), + ).toEqual({ result: [8, 7] }); + }); +}); diff --git a/packages/proton/test/upstream/compiler/types.test.ts b/packages/proton/test/upstream/compiler/types.test.ts new file mode 100644 index 00000000..a5ff2bba --- /dev/null +++ b/packages/proton/test/upstream/compiler/types.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest'; +import { run } from '../compile'; + +const schema = 'interface Msg {id:pb<1,uint_32>; text:pb<2,string>;}'; + +describe('schema type transformations', () => { + it('uses class parameter properties and ignores static metadata', () => { + expect( + run(` + class Msg {static label='message';constructor(public value:pb<1,T>) {}} + export const result=protobuf_decode>(protobuf_encode>(new Msg(7))); + `).result, + ).toEqual({ value: 7 }); + }); + it('captures function generics in local schemas without mixing instantiations', () => { + expect( + run(` + function encode(value:T) { interface Local {value:pb<1,T>;} return protobuf_encode({value}); } + export const result=[[...encode(7)], [...encode('x')]]; + `).result, + ).toEqual([ + [8, 7], + [10, 1, 120], + ]); + }); + it('extracts schema types through infer, functions and promises', () => { + expect( + run(`${schema} + type Result = T extends (...args:any[])=>infer R ? R : never; + type Unwrap = T extends Promise ? Unwrap : T; + type Schema = UnwrapPromise>>>; + export const result = protobuf_decode(protobuf_encode({id:7,text:'x'})); + `).result, + ).toEqual({ id: 7, text: 'x' }); + }); + + it('supports Awaited, ReturnType, Parameters and type queries', () => { + expect( + run(`${schema} + function load(value:Msg): Promise {return Promise.resolve(value);} + type Result = Awaited>; + type Input = Parameters[0]; + export const result = protobuf_decode(protobuf_encode({id:7,text:'x'})); + `).result, + ).toEqual({ id: 7, text: 'x' }); + }); + + it('propagates deferred conditional transformations through generic functions', () => { + expect( + run(`${schema} + type Unwrap = T extends Promise ? U : T; + function encode(value:Unwrap) {return protobuf_encode>(value);} + export const result = protobuf_decode(encode>({id:7,text:'x'})); + `).result, + ).toEqual({ id: 7, text: 'x' }); + }); + + it('remaps literal field names and omits never keys', () => { + expect( + run(`${schema} + type Rename = {[K in keyof T as K extends 'text' ? never : \`field_\${Capitalize}\`]:T[K]}; + export const result = protobuf_decode>(protobuf_encode>({field_Id:7})); + `).result, + ).toEqual({ field_Id: 7 }); + }); + + it('selects explicit schemas with Extract and Exclude', () => { + expect( + run(`${schema} + type Schema = Extract; + type Chosen = Exclude; + export const result = protobuf_decode(protobuf_encode({id:7,text:'x'})); + `).result, + ).toEqual({ id: 7, text: 'x' }); + }); + + it('supports constructor signatures and indexed tuple transformations', () => { + expect( + run(`${schema} + type Constructor = new(value:Msg)=>Msg; + type Instance = InstanceType; + type Input = ConstructorParameters[0]; + export const result = protobuf_decode(protobuf_encode({id:7,text:'x'})); + `).result, + ).toEqual({ id: 7, text: 'x' }); + }); +}); diff --git a/packages/proton/test/upstream/plugin/package-name.test.ts b/packages/proton/test/upstream/plugin/package-name.test.ts new file mode 100644 index 00000000..d5b08043 --- /dev/null +++ b/packages/proton/test/upstream/plugin/package-name.test.ts @@ -0,0 +1,25 @@ +import { expect, it, vi } from 'vitest'; + +vi.mock('../../../package.json', () => ({ name: '@test/renamed-codec' })); + +import protobufPlugin from '../../../src/index'; +import { ProtobufCompiler } from '../../../src/compiler/compiler'; +import { protobuf_encode } from '../../../src/runtime'; + +it('uses the manifest name for imports, plugin identity and diagnostics', () => { + expect(protobufPlugin().name).toBe('@test/renamed-codec:vite'); + expect( + new ProtobufCompiler().compile( + `import {protobuf_encode} from '@test/renamed-codec'; + interface Msg {value:pb<1,uint_32>;} protobuf_encode({value:7});`, + 'renamed.ts', + ), + ).toContain('protobuf_encode_Msg({value:7})'); + expect(() => protobuf_encode({})).toThrow('@test/renamed-codec Vite plugin'); + expect(() => + new ProtobufCompiler().compile( + `import {protobuf_encode} from '@test/renamed-codec'; protobuf_encode({});`, + 'error.ts', + ), + ).toThrow('[@test/renamed-codec]'); +}); diff --git a/packages/proton/test/upstream/plugin/vite.test.ts b/packages/proton/test/upstream/plugin/vite.test.ts new file mode 100644 index 00000000..a84d3c92 --- /dev/null +++ b/packages/proton/test/upstream/plugin/vite.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest'; +import protobufPlugin from '../../../src/index'; +import { packageName } from '../../../src/package'; +import { ProtobufCompiler } from '../../../src/compiler/compiler'; +import { run, imports } from '../compile'; +import { withProject } from '../project'; +import { join } from 'node:path'; +import { writeFileSync } from 'node:fs'; + +const schema = 'interface Msg { value: pb<1,uint_32>; }'; + +describe('plugin entry', () => { + it('watches type-only dependencies and rebuilds importers after schema changes', async () => { + await withProject( + { 'message.ts': 'export interface Msg { value: pb<1, uint_32>; }' }, + (directory) => { + const plugin = protobufPlugin(); + const transformHook = plugin.transform!; + const transform = + typeof transformHook === 'function' ? transformHook : transformHook.handler; + const dependencies: string[] = []; + const context = { addWatchFile: (path: string) => dependencies.push(path) } as any; + const file = join(directory, 'entry.ts').replaceAll('\\', '/'); + const message = join(directory, 'message.ts').replaceAll('\\', '/'); + const source = `${imports} import type { Msg } from './message'; protobuf_encode({value:7});`; + const initial = transform.call(context, source, file) as { code: string }; + expect(initial.code).toContain('buf[offset++] = 8;'); + expect(dependencies).toContain(message); + writeFileSync(message, 'export interface Msg { value: pb<2, uint_32>; }'); + const updateHook = plugin.handleHotUpdate!; + const update = typeof updateHook === 'function' ? updateHook : updateHook.handler; + const module = { id: file }; + expect( + update.call( + {} as any, + { + file: message, + server: { + moduleGraph: { + getModuleById: (id: string) => + id === file ? module : undefined, + }, + }, + } as any, + ), + ).toEqual([module]); + const updated = transform.call(context, source, file) as { code: string }; + expect(updated.code).toContain('buf[offset++] = 16;'); + }, + ); + }); + + it('recognizes the package name from package.json', () => { + const plugin = protobufPlugin(); + const hook = plugin.transform!; + const transform = typeof hook === 'function' ? hook : hook.handler; + const result = transform.call( + {} as any, + `import {protobuf_encode as encode} from '${packageName}'; ${schema} encode({value:7});`, + 'entry.ts', + ) as { code: string }; + expect(result.code).toContain('protobuf_encode_Msg({value:7})'); + }); + + it('leaves unrelated modules and declaration files alone', () => { + const plugin = protobufPlugin(); + const hook = plugin.transform!; + const transform = typeof hook === 'function' ? hook : hook.handler; + + for (const file of ['entry.js', 'schema.d.ts', 'schema.d.mts']) { + expect(transform.call({} as any, schema, file)).toBeNull(); + } + + expect(new ProtobufCompiler().compile(schema, 'schema.ts')).toBeNull(); + }); + + it('generates only codecs reachable from actual calls', () => { + const code = new ProtobufCompiler().compile( + `import {protobuf_encode} from '${packageName}'; ${schema} + interface Unused {value:pb<1,Missing>;} + protobuf_encode({value:7});`, + 'used.ts', + )!; + expect(code).not.toContain('function protobuf_decode_'); + expect(code).not.toContain('function protobuf_encode_Unused'); + expect(code).toContain('function protobuf_encode_Msg'); + }); + + it('reports unresolved types instead of leaving runtime calls behind', () => { + expect(() => run('protobuf_encode({});')).toThrow(/Unresolved type Missing/); + }); + + it('fails clearly when the build plugin is absent', async () => { + const runtime = await import('../../../src/runtime'); + expect(Object.keys(runtime).sort()).toEqual([ + 'protobuf_decode', + 'protobuf_encode', + 'protobuf_getUnknownFieldMetadata', + 'protobuf_getUnknownFields', + ]); + expect(() => runtime.protobuf_encode({})).toThrow( + `not transformed by the ${packageName} Vite plugin`, + ); + expect(() => runtime.protobuf_decode(new Uint8Array())).toThrow( + `not transformed by the ${packageName} Vite plugin`, + ); + }); +}); diff --git a/packages/proton/test/upstream/project.ts b/packages/proton/test/upstream/project.ts new file mode 100644 index 00000000..9bd58a4b --- /dev/null +++ b/packages/proton/test/upstream/project.ts @@ -0,0 +1,79 @@ +import { build } from 'vite'; +import protobufPlugin from '../../src/index'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, dirname, posix } from 'node:path'; +import { packageName } from '../../src/package'; + +export async function withProject( + files: Record, + action: (directory: string) => T | Promise, +): Promise { + const directory = mkdtempSync(join(tmpdir(), 'protobuf-compiler-')); + + try { + for (const [name, text] of Object.entries(files)) { + const path = join(directory, name); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, text); + } + + return await action(directory); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +export function bundle( + files: Record, + entry: string | string[] = 'entry.ts', +): Promise { + return withProject(files, async (directory) => { + const output = await build({ + configFile: false, + root: directory, + logLevel: 'silent', + plugins: [protobufPlugin()], + build: { + write: false, + minify: false, + target: 'es2022', + lib: { + entry: Array.isArray(entry) + ? entry.map((file) => join(directory, file)) + : join(directory, entry), + formats: ['cjs'], + }, + rolldownOptions: { external: [packageName] }, + }, + }); + const result = (Array.isArray(output) ? output[0] : output) as { + output: { code?: string; fileName: string; name: string; isEntry?: boolean }[]; + }; + const cache = new Map>(); + + const load = (name: string): Record => { + if (cache.has(name)) { + return cache.get(name)!; + } + + const chunk = result.output.find((chunk) => chunk.fileName === name); + + if (!chunk?.code) { + throw new Error(`Unexpected runtime dependency: ${name}`); + } + + const exports = {}; + cache.set(name, exports); + new Function('exports', 'require', chunk.code)(exports, (specifier: string) => + load(posix.normalize(posix.join(posix.dirname(name), specifier))), + ); + return Object.fromEntries(Object.entries(exports)); + }; + + const entries = result.output.filter((chunk) => chunk.isEntry); + return Array.isArray(entry) + ? Object.fromEntries(entries.map((chunk) => [chunk.name, load(chunk.fileName)])) + : load(entries[0].fileName); + }); +} diff --git a/packages/proton/test/upstream/schema.ts b/packages/proton/test/upstream/schema.ts new file mode 100644 index 00000000..55542702 --- /dev/null +++ b/packages/proton/test/upstream/schema.ts @@ -0,0 +1,40 @@ +import ts from 'typescript'; +import { SourceContext } from '../../src/source/context'; +import { SchemaResolver } from '../../src/schema/resolver'; +import { generateCode } from '../../src/codegen/generator'; + +export function schemaCodecs(code: string, name = 'Msg') { + const generated = generateCode(schemaRegistry(code)); + return new Function( + `${generated}\nreturn { encode: protobuf_encode_${name}, decode: protobuf_decode_${name} };`, + )() as { + encode(value: T): Uint8Array; + decode(bytes: Uint8Array): T; + }; +} + +export function schemaRegistry(code: string, file = 'schema.ts') { + const context = new SourceContext(); + const source = context.source(file, code); + const resolver = new SchemaResolver(context); + const roots: string[] = []; + + for (const statement of source.statements) { + if (ts.isInterfaceDeclaration(statement) && !statement.typeParameters?.length) { + roots.push(statement.name.text); + } + } + + const expanded = context.source( + file, + code + roots.map((name, i) => `\ntype __TestRoot${i} = ${name};`).join(''), + ); + + for (const statement of expanded.statements) { + if (ts.isTypeAliasDeclaration(statement) && statement.name.text.startsWith('__TestRoot')) { + resolver.message(resolver.type(statement.type), statement); + } + } + + return resolver.registry; +} diff --git a/packages/proton/tsconfig.json b/packages/proton/tsconfig.json index 2d718364..6ca23ff3 100644 --- a/packages/proton/tsconfig.json +++ b/packages/proton/tsconfig.json @@ -8,6 +8,7 @@ "src/**/*", "test/__tests__/**/*", "test/helpers/**/*", + "test/upstream/**/*", "protobuf.d.ts" ], "exclude": [ diff --git a/packages/proton/vitest.config.ts b/packages/proton/vitest.config.ts index fe98fc2e..5ab9cb52 100644 --- a/packages/proton/vitest.config.ts +++ b/packages/proton/vitest.config.ts @@ -2,6 +2,6 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { - include: ['test/__tests__/**/*.test.ts'], + include: ['test/**/*.test.ts'], }, });