@geoprotocol/grc-20

中文文档
0.4.1发布于 2026/03/10MITTypeScriptES Module近 30 天下载 1万

GRC-20 TypeScript library for binary property graph encoding/decoding

原始使用文档
文档目录18 节
  1. Installation
  2. Quick Start
  3. Features
  4. Bundle Sizes
  5. Lazy Loading
  6. API Reference
  7. Types
  8. Builders
  9. Ops (Functional API)
  10. Codec
  11. Compression
  12. ID Utilities
  13. Validation
  14. Data Types Reference
  15. Genesis IDs
  16. Entry Points
  17. Development
  18. License

@geoprotocol/grc-20

TypeScript library for encoding and decoding GRC-20 binary property graph data.

Installation

npm install @geoprotocol/grc-20

Quick Start

import {
  EditBuilder,
  encodeEdit,
  decodeEdit,
  randomId,
  properties,
} from "@geoprotocol/grc-20";

// Create an edit with an entity
const edit = new EditBuilder(randomId())
  .setName("Create Alice")
  .addAuthor(randomId())
  .setCreatedNow()
  .createEntity(randomId(), (e) =>
    e
      .text(properties.name(), "Alice", undefined)
      .text(properties.description(), "A person", undefined)
  )
  .build();

// Encode to binary
const bytes = encodeEdit(edit);

// Decode back
const decoded = decodeEdit(bytes);

Features

  • Type-safe API - Full TypeScript definitions
  • Builder pattern - Fluent API for constructing edits
  • Binary codec - Pure TypeScript encoder/decoder
  • Zstd compression - Optional WASM-based compression (lazy-loaded)
  • Tree-shakeable - Separate entry points for minimal bundles
  • Cross-platform - Works in Node.js and browsers

Bundle Sizes

Entry PointGzipped
Full library~12 KB
Types only~1.4 KB
Builder only~1.2 KB
Codec only~8 KB
Genesis IDs~1.7 KB
Utilities~1.6 KB
Zstd WASM (lazy)~81 KB

The Zstd WASM module is only loaded when compression functions are used.

Lazy Loading

For optimal initial load, import the codec separately:

// Initial load (~4.4 KB gzipped)
import { EditBuilder, randomId, properties } from "@geoprotocol/grc-20/builder";
import { properties } from "@geoprotocol/grc-20/genesis";

// Lazy load codec when needed (~8 KB gzipped)
const { encodeEdit } = await import("@geoprotocol/grc-20/codec");

// WASM only loads if you use compression (~81 KB additional)
const { encodeEditAuto } = await import("@geoprotocol/grc-20/codec");

API Reference

Types

import {
  Id,              // 16-byte UUID (Uint8Array branded type)
  Edit,            // Batch of operations with metadata
  Op,              // Union of all operation types
  Value,           // Union of all value types
  DataType,        // Enum: Boolean, Integer, Float, Text, etc.
  PropertyValue,   // Property ID + Value pair
} from "@geoprotocol/grc-20";

Builders

import {
  EditBuilder,          // Build Edit objects
  EntityBuilder,        // Build entity values
  UpdateEntityBuilder,  // Build update operations
  RelationBuilder,      // Build relation operations
  UpdateRelationBuilder,// Build relation update operations
} from "@geoprotocol/grc-20";

EditBuilder

const edit = new EditBuilder(editId)
  .setName("My Edit")
  .addAuthor(authorId)
  .setCreatedAt(BigInt(Date.now()) * 1000n)  // microseconds
  .createEntity(entityId, e => e
    .text(propId, "value", languageId)
    .integer(propId, 42n, unitId)
    .float(propId, 3.14, undefined)
    .decimal(propId, { exponent: -2, mantissa: 1234n }, undefined)
    .boolean(propId, true)
    .bytes(propId, new Uint8Array([1, 2, 3]))
    .point(propId, 40.7128, -74.006)
    .date(propId, "2024-01-15Z")             // RFC 3339 date
    .time(propId, "10:30:00Z")               // RFC 3339 time
    .datetime(propId, "2024-01-15T10:30:00Z")// RFC 3339 datetime
  )
  .updateEntity(entityId, u => u
    .setText(propId, "new value", undefined)
    .setInteger(propId, 100n, undefined)
    .unsetLanguage(propId, languageId)  // Unset specific language
    .unsetAll(propId)                   // Unset all values for property
  )
  .deleteEntity(entityId)
  .restoreEntity(entityId)
  .createRelation(r => r
    .id(relationId)
    .from(fromId)
    .to(toId)
    .relationType(relationTypeId)
  )
  .deleteRelation(relationId)
  .restoreRelation(relationId)
  .addOp({ type: 'createValueRef', id: valueRefId, entity: entityId, property: propId })
  .build();

Ops (Functional API)

createEdit defaults id to randomId() and createdAt to 0n when omitted.

import {
  createEdit,
  createEntity,
  createRelation,
  randomId,
  properties,
  relationTypes,
} from "@geoprotocol/grc-20";

const entityId = randomId();
const authorId = randomId();

const ops = [
  createEntity({
    id: entityId,
    values: [
      { property: properties.name(), value: { type: "text", value: "Alice" } },
      { property: properties.description(), value: { type: "text", value: "A person" } },
    ],
  }),
  createRelation({
    id: randomId(),
    relationType: relationTypes.types(),
    from: entityId,
    to: randomId(),
  }),
];

const edit = createEdit({
  name: "Create Alice",
  author: authorId,
  ops,
});

Codec

import { encodeEdit, decodeEdit } from "@geoprotocol/grc-20";

// Encode (uncompressed)
const bytes = encodeEdit(edit);
const bytesCanonical = encodeEdit(edit, { canonical: true });

// Decode (uncompressed)
const edit = decodeEdit(bytes);

Compression

The library supports Zstd compression via a lazy-loaded WASM module. The WASM is only downloaded when compression functions are first used.

import {
  preloadCompression,
  isCompressionReady,
  encodeEditAuto,
  decodeEditAuto,
  encodeEditCompressed,
  decodeEditCompressed,
} from "@geoprotocol/grc-20";

// Preload WASM on app startup (recommended)
await preloadCompression();

// Check if compression is ready
if (isCompressionReady()) {
  console.log("Compression ready!");
}

// Auto encode/decode (recommended for most use cases)
// Compresses if data > 256 bytes, otherwise uncompressed
const data = await encodeEditAuto(edit);
const decoded = await decodeEditAuto(data);

// Control compression threshold
const data = await encodeEditAuto(edit, { threshold: 0 });       // always compress
const data = await encodeEditAuto(edit, { threshold: 1024 });    // compress if > 1KB
const data = await encodeEditAuto(edit, { threshold: Infinity }); // never compress

// Explicit compressed encode/decode
const compressed = await encodeEditCompressed(edit);
const decoded = await decodeEditCompressed(compressed);

Browser Usage (without bundler)

If using native ES modules without a bundler, add an import map for the WASM dependency:

<script type="importmap">
{
  "imports": {
    "@bokuweb/zstd-wasm": "https://esm.sh/@bokuweb/[email protected]"
  }
}
</script>

ID Utilities

import {
  randomId,             // Generate random UUIDv4
  parseId,              // Parse hex string to Id
  formatId,             // Format Id as hex string
  derivedUuid,          // Derive UUIDv8 from bytes (SHA-256, sync)
  derivedUuidAsync,     // Derive UUIDv8 from bytes (SHA-256, async)
  derivedUuidFromString,
  uniqueRelationId,     // Derive relation ID from endpoints
  relationEntityId,     // Derive entity ID from relation ID
  idsEqual,             // Compare two Ids for equality
  compareIds,           // Compare two Ids for ordering (-1, 0, 1)
  NIL_ID,               // Zero UUID
} from "@geoprotocol/grc-20";

Validation

Validate values and positions before encoding:

import { validateValue, validatePosition } from "@geoprotocol/grc-20";

// Validate a value matches its declared type
const result = validateValue(value, DataType.Text);
if (!result.valid) {
  console.error(result.error);
}

// Validate position string format
const posResult = validatePosition("a0");
if (!posResult.valid) {
  console.error(posResult.error);
}

Data Types Reference

TypeTypeScript Representation
BOOLEAN{ type: "boolean", value: boolean }
INTEGER{ type: "integer", value: bigint, unit?: Id }
FLOAT{ type: "float", value: number, unit?: Id }
DECIMAL{ type: "decimal", exponent: number, mantissa: bigint, unit?: Id }
TEXT{ type: "text", value: string, language?: Id }
BYTES{ type: "bytes", value: Uint8Array }
DATE{ type: "date", value: string } (RFC 3339, e.g. "2024-01-15Z")
TIME{ type: "time", value: string } (RFC 3339, e.g. "14:30:00Z")
DATETIME{ type: "datetime", value: string } (RFC 3339, e.g. "2024-01-15T14:30:00Z")
SCHEDULE{ type: "schedule", value: string } (RFC 5545/7953 iCalendar)
POINT{ type: "point", lat: number, lon: number, alt?: number }
RECT{ type: "rect", minLat: number, minLon: number, maxLat: number, maxLon: number }
EMBEDDING{ type: "embedding", subType: EmbeddingSubType, dims: number, data: Uint8Array }

Genesis IDs

Well-known IDs from the Genesis Space:

import { properties, types, relationTypes, languages } from "@geoprotocol/grc-20";

// Properties
properties.name()        // a126ca530c8e48d5b88882c734c38935 - Name (TEXT)
properties.description() // 9b1f76ff9711404c861e59dc3fa7d037 - Description (TEXT)
properties.cover()       // 34f535072e6b42c5a84443981a77cfa2 - Cover image URL (TEXT)

// Types
types.image()            // f3f790c4c74e4d23a0a91e8ef84e30d9 - Image entity

// Relation Types
relationTypes.types()    // 8f151ba4de204e3c9cb499ddf96f48f1 - Type membership

// Languages (derived from BCP 47 codes)
languages.english()      // or languages.fromCode("en")
languages.spanish()
languages.french()
// ... etc

Entry Points

For tree-shaking, use specific entry points:

import { ... } from "@geoprotocol/grc-20";          // Full library
import { ... } from "@geoprotocol/grc-20/types";    // Types only
import { ... } from "@geoprotocol/grc-20/builder";  // Builders only
import { ... } from "@geoprotocol/grc-20/codec";    // Codec only
import { ... } from "@geoprotocol/grc-20/genesis";  // Genesis IDs only
import { ... } from "@geoprotocol/grc-20/util";     // Utilities only

Development

# Install dependencies
npm install

# Build
npm run build

# Test (Node.js)
npm test

# Test (Browser via Playwright)
npm run test:browser

# Test both
npm run test:all

# Analyze bundle sizes
npm run bundle:analyze

# Run performance benchmark
npm run benchmark

# Run browser demo
npm run demo
# Then open http://localhost:3000/examples/browser-demo.html

License

MIT

版本与发布记录

@geoprotocol/grc-20 共发布 14 个版本,首次发布于 2026/01/10;过去 12 个月发布了 14 个版本。

版本发布日期距今
0.4.1latest2026/03/108 个月前
0.4.02026/02/109 个月前
0.3.12026/02/109 个月前
0.3.02026/01/289 个月前
0.2.32026/01/279 个月前
0.2.22026/01/249 个月前

关于 @geoprotocol/grc-20 的常见问题

@geoprotocol/grc-20 是什么?

GRC-20 TypeScript library for binary property graph encoding/decoding

如何安装 @geoprotocol/grc-20?

在项目目录运行 npm install @geoprotocol/grc-20,或使用 pnpm add / yarn add / bun add。

@geoprotocol/grc-20 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@geoprotocol/grc-20 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@geoprotocol/grc-20 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@geoprotocol/grc-20 可以商用吗?

@geoprotocol/grc-20 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@geoprotocol/grc-20 的下载量有多少?

根据 npm 官方下载统计,@geoprotocol/grc-20 在 2026/10/16 – 2026/11/14 这 30 天内被下载 10,193 次,日均约 340 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@geoprotocol/grc-20 还在维护吗?

最新版本 0.4.1 发布于 2026/03/10(8 个月前);至今共发布 14 个版本,其中过去 12 个月发布了 14 个;首次发布于 2026/01/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。