@nsnanocat/flatbuffer-root

@nsnanocat/flatbuffer-root 基于 FlatBuffers JavaScript 生成模型,按根表 slot 解码、修改并重新组装 FlatBuffer。它只解析显式注册的产品表,同时保留未知、未修改以及未来 schema 新增的根表 slot。

安装

flatbuffers 是 peer dependency,支持 >=24.12.23 <26

npm
yarn
pnpm
bun
deno
npm add @nsnanocat/flatbuffer-root flatbuffers

如果从 GitHub Packages 安装:

.npmrc
@nsnanocat:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}

配置完成后,仍使用上面的安装命令。

处理模型

处理器从生成的根表类推导 slot 名称和顺序,并为需要读写的 slot 注册 codec:

  • rootClass.prototype 上除 constructor__init 外的方法按声明顺序映射到物理 slot。
  • 每个根 accessor 都必须存在对应的静态 add{Name} 方法。
  • 根字段必须是 table offset;scalar、string、vector 等根字段不在支持范围内。
  • 未注册 codec 的 schema slot 不会被解析,但使用源 FlatBuffer 编码时仍会透明保留。
  • 超出当前 schema 的物理 slot 同样会作为 opaque arena 保留。

快速开始

import { ByteBuffer } from "flatbuffers";
import { FlatBufferRootProcessor } from "@nsnanocat/flatbuffer-root";

const processor = new FlatBufferRootProcessor({
  name: "Example",
  rootClass: ExampleRoot,
  codecs: {
    product: {
      tableClass: ExampleProduct,
      decode: (table) => decodeProduct(table),
      encode: (builder, json) => encodeProduct(builder, json),
    },
  },
  configurableRootNames: ["product"],
});

const source = new ByteBuffer(rawBody);
const rootNames = processor.filterRootNames(requestedRootNames, enabledRootNames);
const json = processor.decode(source, rootNames);
const output = processor.encode(source, {
  product: updateProduct(json.product),
});

构造处理器时会校验根表类、产品表类、codec 和可配置根名称;无效配置会立即抛出异常。

API

filterRootNames(requestedRootNames, enabledRootNames)

过滤 configurableRootNames 中受业务开关控制的名称,并保持请求的原始顺序。未列为 configurable 的名称会原样保留。

decode(byteBuffer, rootNames = [])

按物理 slot 顺序解码已请求且已注册 codec 的产品表,返回成功解码的部分对象。未知名称、缺失 slot 和可隔离的 单 slot 失败会写入诊断日志;无效根表或越界数据会抛出异常。

encode(byteBuffer = undefined, patch = {})

每个 patch slot 会独立编译。成功的 slot 会替换源数据中的对应 slot,失败或未知 patch 不会覆盖原值;未修改和未知的 源 slot 会保留。省略 byteBuffer 时会创建只包含成功 patch 的新根表。

诊断日志

配置错误和不可恢复的输入错误通过 @nsnanocat/utilConsole.error 记录后抛出。可隔离的未知、缺失或失败 slot 使用 Console.warn,完整成功的阶段统计使用 Console.debug

Tip

这是面向 FlatBuffers JavaScript 生成模型的根表处理器,不是 FlatBuffers schema 编译器。请先使用对应版本的 flatc 生成根表和产品表类,再注册实际需要读写的 codec。