@naeemo/capnp 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as QueuedCallManager, c as AnswerTable, d as QuestionTable, i as PipelineResolutionTracker, l as ExportTable, n as PIPELINE_CLIENT_SYMBOL, o as createPipelineClient, r as PipelineOpTracker, s as isPipelineClient, t as RpcConnection, u as ImportTable } from "./rpc-connection-Dz3rYT1P.js";
1
+ import { C as QuestionTable, S as ImportTable, _ as QueuedCallManager, a as serializeGetSchemaParams, b as AnswerTable, c as serializeSchemaRequest, d as parseSchemaNodes, f as SchemaFormat, g as PipelineResolutionTracker, h as PipelineOpTracker, i as deserializeSchemaResponse, l as serializeSchemaResponse, m as PIPELINE_CLIENT_SYMBOL, n as SCHEMA_MESSAGE_TYPES, o as serializeGetSchemaResults, p as SchemaNodeType, r as deserializeSchemaRequest, s as serializeListSchemasResults, t as RpcConnection, u as createSchemaRegistry, v as createPipelineClient, x as ExportTable, y as isPipelineClient } from "./rpc-connection-C3-uEtpd.js";
2
2
  import { createRequire } from "node:module";
3
3
 
4
4
  //#region \0rolldown/runtime.js
@@ -2310,7 +2310,7 @@ var ConnectionManager = class {
2310
2310
  }
2311
2311
  }
2312
2312
  async doEstablishConnection(vatId, address) {
2313
- const { RpcConnection } = await import("./rpc-connection-C2C1wyga.js");
2313
+ const { RpcConnection } = await import("./rpc-connection-BPkslKv3.js");
2314
2314
  const connection = new RpcConnection(await this.options.connectionFactory(vatId, address), this.options.connectionOptions);
2315
2315
  await connection.start();
2316
2316
  this.registerConnection(vatId, connection);
@@ -4906,5 +4906,933 @@ function supportsStreaming(connection) {
4906
4906
  }
4907
4907
 
4908
4908
  //#endregion
4909
- export { AnswerTable, BaseCapabilityClient, BulkTransfer, BulkTransferManager, ConnectionManager, DEFAULT_BULK_CONFIG, DEFAULT_ESCROW_CONFIG, DEFAULT_FLOW_CONTROL, DEFAULT_JOIN_OPTIONS, DEFAULT_JOIN_SECURITY_POLICY, DEFAULT_REALTIME_CONFIG, DEFAULT_STREAMING_CAPABILITIES, DropPolicy, ElementSize, ExportTable, ImportTable, Level3Handlers, Level4Handlers, ListBuilder, ListReader, MemoryPool, MessageBuilder, MessageReader, MultiSegmentMessageBuilder, OptimizedRpcMessageBuilder, PIPELINE_CLIENT_SYMBOL, PipelineOpTracker, PipelineResolutionTracker, PointerTag, QuestionTable, QueuedCallManager, RealtimeStream, RealtimeStreamManager, RestoreHandler, RpcConnection, Segment, Stream, StreamManager, StreamPriority, StreamType, StreamingRpcConnection, StructBuilder, StructReader, SturdyRefManager, UnionBuilder, UnionReader, WORD_SIZE, WebSocketTransport, configureGlobalMemoryPool, createBulkTransferManager, createPipelineClient, createProvisionId, createRealtimeStreamManager, createRecipientId, createStream, createStreamManager, createStreamingConnection, createSturdyRef, createThirdPartyCapId, createUnionBuilder, createUnionReader, createZeroCopyView, decodePointer, deserializeRpcMessage, deserializeSturdyRef, encodeListPointer, encodeStructPointer, fastCopy, generateProvisionId, generateVatId, getGlobalMemoryPool, isPipelineClient, isSameBuffer, isStream, isSturdyRefValid, serializeRpcMessage, serializeSturdyRef, supportsStreaming };
4909
+ //#region src/rpc/dynamic-reader.ts
4910
+ /**
4911
+ * Create a dynamic reader from schema and buffer
4912
+ *
4913
+ * @param schema - The schema node describing the struct type
4914
+ * @param buffer - The Cap'n Proto message buffer
4915
+ * @returns A DynamicReader for accessing the message fields
4916
+ */
4917
+ function createDynamicReader(schema, buffer) {
4918
+ const messageReader = new MessageReader(buffer);
4919
+ if (!schema.structInfo) throw new Error(`Schema node ${schema.displayName} is not a struct`);
4920
+ const { dataWordCount, pointerCount } = schema.structInfo;
4921
+ return new DynamicReaderImpl(schema, messageReader.getRoot(dataWordCount, pointerCount), messageReader);
4922
+ }
4923
+ /**
4924
+ * Create a dynamic reader from an existing StructReader
4925
+ *
4926
+ * @param schema - The schema node describing the struct type
4927
+ * @param structReader - The StructReader to wrap
4928
+ * @param messageReader - The underlying MessageReader
4929
+ * @returns A DynamicReader for accessing the message fields
4930
+ */
4931
+ function createDynamicReaderFromStruct(schema, structReader, messageReader) {
4932
+ return new DynamicReaderImpl(schema, structReader, messageReader);
4933
+ }
4934
+ /**
4935
+ * Implementation of DynamicReader
4936
+ */
4937
+ var DynamicReaderImpl = class {
4938
+ fieldCache;
4939
+ pointerOffset;
4940
+ constructor(schema, structReader, messageReader) {
4941
+ this.schema = schema;
4942
+ this.structReader = structReader;
4943
+ this.messageReader = messageReader;
4944
+ this.fieldCache = /* @__PURE__ */ new Map();
4945
+ this.pointerOffset = schema.structInfo?.dataWordCount ?? 0;
4946
+ if (schema.structInfo?.fields) for (const field of schema.structInfo.fields) this.fieldCache.set(field.name, field);
4947
+ }
4948
+ get(fieldName) {
4949
+ const field = this.fieldCache.get(fieldName);
4950
+ if (!field) throw new Error(`Field '${fieldName}' not found in schema ${this.schema.displayName}`);
4951
+ return this.readFieldValue(field);
4952
+ }
4953
+ has(fieldName) {
4954
+ return this.fieldCache.has(fieldName);
4955
+ }
4956
+ getFieldNames() {
4957
+ return Array.from(this.fieldCache.keys());
4958
+ }
4959
+ getSchema() {
4960
+ return this.schema;
4961
+ }
4962
+ getStruct(fieldName) {
4963
+ const field = this.fieldCache.get(fieldName);
4964
+ if (!field) return;
4965
+ if (field.type.kind.type !== "struct") return;
4966
+ const pointerIndex = this.getPointerIndex(field);
4967
+ const nestedStruct = this.structReader.getStruct(pointerIndex, 0, 0);
4968
+ if (!nestedStruct) return;
4969
+ return new DynamicStructReaderWithoutSchema(nestedStruct, this.messageReader);
4970
+ }
4971
+ getList(fieldName) {
4972
+ const field = this.fieldCache.get(fieldName);
4973
+ if (!field) return;
4974
+ if (field.type.kind.type !== "list") return;
4975
+ const pointerIndex = this.getPointerIndex(field);
4976
+ const elementType = field.type.kind.elementType;
4977
+ return this.readListField(pointerIndex, elementType);
4978
+ }
4979
+ getRawReader() {
4980
+ return this.structReader;
4981
+ }
4982
+ /**
4983
+ * Read a field value based on its type
4984
+ */
4985
+ readFieldValue(field) {
4986
+ const kind = field.type.kind;
4987
+ switch (kind.type) {
4988
+ case "void": return;
4989
+ case "bool": return this.structReader.getBool(field.offset);
4990
+ case "int8": return this.structReader.getInt8(field.offset);
4991
+ case "int16": return this.structReader.getInt16(field.offset);
4992
+ case "int32": return this.structReader.getInt32(field.offset);
4993
+ case "int64": return this.structReader.getInt64(field.offset);
4994
+ case "uint8": return this.structReader.getUint8(field.offset);
4995
+ case "uint16": return this.structReader.getUint16(field.offset);
4996
+ case "uint32": return this.structReader.getUint32(field.offset);
4997
+ case "uint64": return this.structReader.getUint64(field.offset);
4998
+ case "float32": return this.structReader.getFloat32(field.offset);
4999
+ case "float64": return this.structReader.getFloat64(field.offset);
5000
+ case "text": return this.readTextField(field);
5001
+ case "data": return this.readDataField(field);
5002
+ case "list": return this.readListFieldBySchema(field);
5003
+ case "enum": return this.readEnumField(field);
5004
+ case "struct": return this.readStructField(field);
5005
+ case "interface": return this.readInterfaceField(field);
5006
+ case "anyPointer": return this.readAnyPointerField(field);
5007
+ default: throw new Error(`Unsupported field type: ${kind.type}`);
5008
+ }
5009
+ }
5010
+ /**
5011
+ * Get the pointer index for a field
5012
+ * In Cap'n Proto, pointer fields have offsets that start from 0 for the first pointer
5013
+ * The offset is measured in bits from the start of the data section
5014
+ * For pointer fields, offset = dataWordCount * 64 + pointerIndex * 64
5015
+ * So pointerIndex = (offset - dataWordCount * 64) / 64
5016
+ */
5017
+ getPointerIndex(field) {
5018
+ const dataSectionBits = (this.schema.structInfo?.dataWordCount ?? 0) * 64;
5019
+ return (field.offset - dataSectionBits) / 64;
5020
+ }
5021
+ /**
5022
+ * Read a text field
5023
+ */
5024
+ readTextField(field) {
5025
+ const pointerIndex = this.getPointerIndex(field);
5026
+ return this.structReader.getText(pointerIndex);
5027
+ }
5028
+ /**
5029
+ * Read a data field
5030
+ */
5031
+ readDataField(field) {
5032
+ const pointerIndex = this.getPointerIndex(field);
5033
+ const text = this.structReader.getText(pointerIndex);
5034
+ return new TextEncoder().encode(text);
5035
+ }
5036
+ /**
5037
+ * Read a list field using schema information
5038
+ */
5039
+ readListFieldBySchema(field) {
5040
+ if (field.type.kind.type !== "list") throw new Error(`Field '${field.name}' is not a list type`);
5041
+ const pointerIndex = this.getPointerIndex(field);
5042
+ const elementType = field.type.kind.elementType;
5043
+ return this.readListField(pointerIndex, elementType);
5044
+ }
5045
+ /**
5046
+ * Read a list field
5047
+ */
5048
+ readListField(pointerIndex, elementType) {
5049
+ const elementSize = this.mapTypeToElementSize(elementType);
5050
+ const listReader = this.structReader.getList(pointerIndex, elementSize);
5051
+ if (!listReader) return [];
5052
+ const result = [];
5053
+ const length = listReader.length;
5054
+ for (let i = 0; i < length; i++) result.push(this.readListElement(listReader, i, elementType));
5055
+ return result;
5056
+ }
5057
+ /**
5058
+ * Map schema type to ElementSize
5059
+ */
5060
+ mapTypeToElementSize(type) {
5061
+ switch (type.kind.type) {
5062
+ case "void": return ElementSize.VOID;
5063
+ case "bool": return ElementSize.BIT;
5064
+ case "int8":
5065
+ case "uint8": return ElementSize.BYTE;
5066
+ case "int16":
5067
+ case "uint16": return ElementSize.TWO_BYTES;
5068
+ case "int32":
5069
+ case "uint32":
5070
+ case "float32": return ElementSize.FOUR_BYTES;
5071
+ case "int64":
5072
+ case "uint64":
5073
+ case "float64": return ElementSize.EIGHT_BYTES;
5074
+ case "struct": return ElementSize.COMPOSITE;
5075
+ default: return ElementSize.POINTER;
5076
+ }
5077
+ }
5078
+ /**
5079
+ * Read a single list element
5080
+ */
5081
+ readListElement(listReader, index, elementType) {
5082
+ switch (elementType.kind.type) {
5083
+ case "void": return;
5084
+ case "bool": return listReader.getPrimitive(index) !== 0;
5085
+ case "int8": return listReader.getPrimitive(index);
5086
+ case "int16": return listReader.getPrimitive(index);
5087
+ case "int32": return listReader.getPrimitive(index);
5088
+ case "int64": return listReader.getPrimitive(index);
5089
+ case "uint8": return listReader.getPrimitive(index);
5090
+ case "uint16": return listReader.getPrimitive(index);
5091
+ case "uint32": return listReader.getPrimitive(index);
5092
+ case "uint64": return listReader.getPrimitive(index);
5093
+ case "float32": return listReader.getPrimitive(index);
5094
+ case "float64": return listReader.getPrimitive(index);
5095
+ case "struct": {
5096
+ const structReader = listReader.getStruct(index);
5097
+ if (!structReader) return void 0;
5098
+ return new DynamicStructReaderWithoutSchema(structReader, this.messageReader);
5099
+ }
5100
+ default: return;
5101
+ }
5102
+ }
5103
+ /**
5104
+ * Read an enum field
5105
+ */
5106
+ readEnumField(field) {
5107
+ return this.structReader.getUint16(field.offset);
5108
+ }
5109
+ /**
5110
+ * Read a struct field
5111
+ */
5112
+ readStructField(field) {
5113
+ const pointerIndex = this.getPointerIndex(field);
5114
+ const nestedStruct = this.structReader.getStruct(pointerIndex, 0, 0);
5115
+ if (!nestedStruct) return;
5116
+ return new DynamicStructReaderWithoutSchema(nestedStruct, this.messageReader);
5117
+ }
5118
+ /**
5119
+ * Read an interface field (capability)
5120
+ */
5121
+ readInterfaceField(_field) {
5122
+ throw new Error("Interface fields not yet supported in dynamic reader");
5123
+ }
5124
+ /**
5125
+ * Read an anyPointer field
5126
+ */
5127
+ readAnyPointerField(_field) {
5128
+ throw new Error("anyPointer fields not yet supported in dynamic reader");
5129
+ }
5130
+ };
5131
+ /**
5132
+ * A limited dynamic reader for structs without schema information
5133
+ * Provides basic field access but no type information
5134
+ */
5135
+ var DynamicStructReaderWithoutSchema = class {
5136
+ constructor(structReader, messageReader) {
5137
+ this.structReader = structReader;
5138
+ this.messageReader = messageReader;
5139
+ }
5140
+ get(_fieldName) {
5141
+ throw new Error("Cannot access fields without schema information");
5142
+ }
5143
+ has(_fieldName) {
5144
+ return false;
5145
+ }
5146
+ getFieldNames() {
5147
+ return [];
5148
+ }
5149
+ getSchema() {
5150
+ throw new Error("No schema information available");
5151
+ }
5152
+ getStruct(_fieldName) {}
5153
+ getList(_fieldName) {}
5154
+ getRawReader() {
5155
+ return this.structReader;
5156
+ }
5157
+ };
5158
+ /**
5159
+ * Create a dynamic reader for a specific type ID
5160
+ * This looks up the schema in a registry and creates the appropriate reader
5161
+ *
5162
+ * @param typeId - The type ID of the struct
5163
+ * @param buffer - The Cap'n Proto message buffer
5164
+ * @param schemaRegistry - A map of type IDs to schema nodes
5165
+ * @returns A DynamicReader for the message
5166
+ */
5167
+ function createDynamicReaderByTypeId(typeId, buffer, schemaRegistry) {
5168
+ const schema = schemaRegistry.get(typeId);
5169
+ if (!schema) throw new Error(`Schema not found for type ID: ${typeId}`);
5170
+ if (schema.type !== SchemaNodeType.STRUCT) throw new Error(`Type ${typeId} is not a struct`);
5171
+ return createDynamicReader(schema, buffer);
5172
+ }
5173
+ /**
5174
+ * Utility function to dump all fields from a dynamic reader
5175
+ * Useful for debugging and exploration
5176
+ *
5177
+ * @param reader - The DynamicReader to dump
5178
+ * @returns An object with all field names and values
5179
+ */
5180
+ function dumpDynamicReader(reader) {
5181
+ const result = {};
5182
+ for (const fieldName of reader.getFieldNames()) try {
5183
+ result[fieldName] = reader.get(fieldName);
5184
+ } catch (error) {
5185
+ result[fieldName] = `<error: ${error}>`;
5186
+ }
5187
+ return result;
5188
+ }
5189
+
5190
+ //#endregion
5191
+ //#region src/rpc/dynamic-writer.ts
5192
+ /**
5193
+ * Create a dynamic writer from schema
5194
+ *
5195
+ * @param schema - The schema node describing the struct type
5196
+ * @returns A DynamicWriter for setting message fields
5197
+ */
5198
+ function createDynamicWriter(schema) {
5199
+ if (!schema.structInfo) throw new Error(`Schema node ${schema.displayName} is not a struct`);
5200
+ const { dataWordCount, pointerCount } = schema.structInfo;
5201
+ const messageBuilder = new MessageBuilder();
5202
+ return new DynamicWriterImpl(schema, messageBuilder.initRoot(dataWordCount, pointerCount), messageBuilder);
5203
+ }
5204
+ /**
5205
+ * Create a dynamic writer for a nested struct
5206
+ *
5207
+ * @param schema - The schema node describing the struct type
5208
+ * @param structBuilder - The StructBuilder to wrap
5209
+ * @param messageBuilder - The underlying MessageBuilder
5210
+ * @returns A DynamicWriter for setting message fields
5211
+ */
5212
+ function createNestedDynamicWriter(schema, structBuilder, messageBuilder) {
5213
+ return new DynamicWriterImpl(schema, structBuilder, messageBuilder);
5214
+ }
5215
+ /**
5216
+ * Implementation of DynamicWriter
5217
+ */
5218
+ var DynamicWriterImpl = class {
5219
+ fieldCache;
5220
+ pointerOffset;
5221
+ constructor(schema, structBuilder, messageBuilder) {
5222
+ this.schema = schema;
5223
+ this.structBuilder = structBuilder;
5224
+ this.messageBuilder = messageBuilder;
5225
+ this.fieldCache = /* @__PURE__ */ new Map();
5226
+ this.pointerOffset = schema.structInfo?.dataWordCount ?? 0;
5227
+ if (schema.structInfo?.fields) for (const field of schema.structInfo.fields) this.fieldCache.set(field.name, field);
5228
+ }
5229
+ set(fieldName, value) {
5230
+ const field = this.fieldCache.get(fieldName);
5231
+ if (!field) throw new Error(`Field '${fieldName}' not found in schema ${this.schema.displayName}`);
5232
+ this.writeFieldValue(field, value);
5233
+ }
5234
+ setFields(fields) {
5235
+ for (const [name, value] of Object.entries(fields)) this.set(name, value);
5236
+ }
5237
+ initStruct(fieldName) {
5238
+ const field = this.fieldCache.get(fieldName);
5239
+ if (!field) throw new Error(`Field '${fieldName}' not found in schema ${this.schema.displayName}`);
5240
+ if (field.type.kind.type !== "struct") throw new Error(`Field '${fieldName}' is not a struct type`);
5241
+ const pointerIndex = this.getPointerIndex(field);
5242
+ return new DynamicWriterWithoutSchema(this.structBuilder.initStruct(pointerIndex, 0, 0), this.messageBuilder);
5243
+ }
5244
+ initList(fieldName, size) {
5245
+ const field = this.fieldCache.get(fieldName);
5246
+ if (!field) throw new Error(`Field '${fieldName}' not found in schema ${this.schema.displayName}`);
5247
+ if (field.type.kind.type !== "list") throw new Error(`Field '${fieldName}' is not a list type`);
5248
+ const pointerIndex = this.getPointerIndex(field);
5249
+ const elementType = field.type.kind.elementType;
5250
+ return this.createListWriter(pointerIndex, size, elementType);
5251
+ }
5252
+ setText(fieldName, value) {
5253
+ const field = this.fieldCache.get(fieldName);
5254
+ if (!field) throw new Error(`Field '${fieldName}' not found in schema ${this.schema.displayName}`);
5255
+ if (field.type.kind.type !== "text") throw new Error(`Field '${fieldName}' is not a text type`);
5256
+ const pointerIndex = this.getPointerIndex(field);
5257
+ this.structBuilder.setText(pointerIndex, value);
5258
+ }
5259
+ setData(fieldName, value) {
5260
+ const field = this.fieldCache.get(fieldName);
5261
+ if (!field) throw new Error(`Field '${fieldName}' not found in schema ${this.schema.displayName}`);
5262
+ if (field.type.kind.type !== "data") throw new Error(`Field '${fieldName}' is not a data type`);
5263
+ const pointerIndex = this.getPointerIndex(field);
5264
+ const textValue = new TextDecoder().decode(value);
5265
+ this.structBuilder.setText(pointerIndex, `${textValue}\0`);
5266
+ }
5267
+ getSchema() {
5268
+ return this.schema;
5269
+ }
5270
+ getRawBuilder() {
5271
+ return this.structBuilder;
5272
+ }
5273
+ toBuffer() {
5274
+ return this.messageBuilder.toArrayBuffer();
5275
+ }
5276
+ /**
5277
+ * Write a field value based on its type
5278
+ */
5279
+ writeFieldValue(field, value) {
5280
+ const kind = field.type.kind;
5281
+ switch (kind.type) {
5282
+ case "void": break;
5283
+ case "bool":
5284
+ this.structBuilder.setBool(field.offset, Boolean(value));
5285
+ break;
5286
+ case "int8":
5287
+ this.structBuilder.setInt8(field.offset, Number(value));
5288
+ break;
5289
+ case "int16":
5290
+ this.structBuilder.setInt16(field.offset, Number(value));
5291
+ break;
5292
+ case "int32":
5293
+ this.structBuilder.setInt32(field.offset, Number(value));
5294
+ break;
5295
+ case "int64":
5296
+ this.structBuilder.setInt64(field.offset, BigInt(value));
5297
+ break;
5298
+ case "uint8":
5299
+ this.structBuilder.setUint8(field.offset, Number(value));
5300
+ break;
5301
+ case "uint16":
5302
+ this.structBuilder.setUint16(field.offset, Number(value));
5303
+ break;
5304
+ case "uint32":
5305
+ this.structBuilder.setUint32(field.offset, Number(value));
5306
+ break;
5307
+ case "uint64":
5308
+ this.structBuilder.setUint64(field.offset, BigInt(value));
5309
+ break;
5310
+ case "float32":
5311
+ this.structBuilder.setFloat32(field.offset, Number(value));
5312
+ break;
5313
+ case "float64":
5314
+ this.structBuilder.setFloat64(field.offset, Number(value));
5315
+ break;
5316
+ case "text":
5317
+ this.setText(field.name, String(value));
5318
+ break;
5319
+ case "data":
5320
+ if (value instanceof Uint8Array) this.setData(field.name, value);
5321
+ else throw new Error(`Field '${field.name}' expects Uint8Array`);
5322
+ break;
5323
+ case "list":
5324
+ if (Array.isArray(value)) this.initList(field.name, value.length).setAll(value);
5325
+ else throw new Error(`Field '${field.name}' expects an array`);
5326
+ break;
5327
+ case "enum":
5328
+ this.structBuilder.setUint16(field.offset, Number(value));
5329
+ break;
5330
+ case "struct":
5331
+ if (typeof value === "object" && value !== null) {
5332
+ const structWriter = this.initStruct(field.name);
5333
+ if (!(value instanceof Uint8Array) && !Array.isArray(value)) structWriter.setFields(value);
5334
+ } else throw new Error(`Field '${field.name}' expects an object`);
5335
+ break;
5336
+ case "interface": throw new Error("Interface fields not yet supported in dynamic writer");
5337
+ case "anyPointer": throw new Error("anyPointer fields not yet supported in dynamic writer");
5338
+ default: throw new Error(`Unsupported field type: ${kind.type}`);
5339
+ }
5340
+ }
5341
+ /**
5342
+ * Get the pointer index for a field
5343
+ * In Cap'n Proto, pointer fields have offsets that start from 0 for the first pointer
5344
+ * The offset is measured in bits from the start of the data section
5345
+ * For pointer fields, offset = dataWordCount * 64 + pointerIndex * 64
5346
+ * So pointerIndex = (offset - dataWordCount * 64) / 64
5347
+ */
5348
+ getPointerIndex(field) {
5349
+ const dataSectionBits = (this.schema.structInfo?.dataWordCount ?? 0) * 64;
5350
+ return (field.offset - dataSectionBits) / 64;
5351
+ }
5352
+ /**
5353
+ * Create a list writer for a field
5354
+ */
5355
+ createListWriter(pointerIndex, size, elementType) {
5356
+ const elementSize = this.mapTypeToElementSize(elementType);
5357
+ let structSize;
5358
+ if (elementSize === ElementSize.COMPOSITE) structSize = {
5359
+ dataWords: 0,
5360
+ pointerCount: 0
5361
+ };
5362
+ return new DynamicListWriterImpl(this.structBuilder.initList(pointerIndex, elementSize, size, structSize), elementType, this.messageBuilder);
5363
+ }
5364
+ /**
5365
+ * Map schema type to ElementSize
5366
+ */
5367
+ mapTypeToElementSize(type) {
5368
+ switch (type.kind.type) {
5369
+ case "void": return ElementSize.VOID;
5370
+ case "bool": return ElementSize.BIT;
5371
+ case "int8":
5372
+ case "uint8": return ElementSize.BYTE;
5373
+ case "int16":
5374
+ case "uint16": return ElementSize.TWO_BYTES;
5375
+ case "int32":
5376
+ case "uint32":
5377
+ case "float32": return ElementSize.FOUR_BYTES;
5378
+ case "int64":
5379
+ case "uint64":
5380
+ case "float64": return ElementSize.EIGHT_BYTES;
5381
+ case "struct": return ElementSize.COMPOSITE;
5382
+ default: return ElementSize.POINTER;
5383
+ }
5384
+ }
5385
+ };
5386
+ /**
5387
+ * Implementation of DynamicListWriter
5388
+ */
5389
+ var DynamicListWriterImpl = class {
5390
+ constructor(listBuilder, elementType, messageBuilder) {
5391
+ this.listBuilder = listBuilder;
5392
+ this.elementType = elementType;
5393
+ this.messageBuilder = messageBuilder;
5394
+ }
5395
+ set(index, value) {
5396
+ if (index < 0 || index >= this.listBuilder.length) throw new Error(`Index ${index} out of bounds`);
5397
+ const kind = this.elementType.kind;
5398
+ switch (kind.type) {
5399
+ case "void": break;
5400
+ case "bool":
5401
+ this.listBuilder.setPrimitive(index, value ? 1 : 0);
5402
+ break;
5403
+ case "int8":
5404
+ case "uint8":
5405
+ case "int16":
5406
+ case "uint16":
5407
+ case "int32":
5408
+ case "uint32":
5409
+ case "float32":
5410
+ this.listBuilder.setPrimitive(index, Number(value));
5411
+ break;
5412
+ case "int64":
5413
+ case "uint64":
5414
+ case "float64":
5415
+ this.listBuilder.setPrimitive(index, BigInt(value));
5416
+ break;
5417
+ case "struct":
5418
+ if (typeof value === "object" && value !== null && !(value instanceof Uint8Array)) this.initStruct(index).setFields(value);
5419
+ break;
5420
+ default: throw new Error(`Unsupported list element type: ${kind.type}`);
5421
+ }
5422
+ }
5423
+ getSize() {
5424
+ return this.listBuilder.length;
5425
+ }
5426
+ getLength() {
5427
+ return this.listBuilder.length;
5428
+ }
5429
+ initStruct(index) {
5430
+ return new DynamicWriterWithoutSchema(this.listBuilder.getStruct(index), this.messageBuilder);
5431
+ }
5432
+ setAll(values) {
5433
+ if (values.length > this.getSize()) throw new Error(`Cannot set ${values.length} values in list of size ${this.getSize()}`);
5434
+ for (let i = 0; i < values.length; i++) this.set(i, values[i]);
5435
+ }
5436
+ };
5437
+ /**
5438
+ * A limited dynamic writer for structs without full schema information
5439
+ * Provides basic field setting but no type validation
5440
+ */
5441
+ var DynamicWriterWithoutSchema = class {
5442
+ constructor(structBuilder, messageBuilder) {
5443
+ this.structBuilder = structBuilder;
5444
+ this.messageBuilder = messageBuilder;
5445
+ }
5446
+ set(fieldName, _value) {
5447
+ throw new Error(`Cannot set field '${fieldName}' without schema information`);
5448
+ }
5449
+ setFields(_fields) {
5450
+ throw new Error("Cannot set fields without schema information");
5451
+ }
5452
+ initStruct(_fieldName) {
5453
+ throw new Error("Cannot init struct without schema information");
5454
+ }
5455
+ initList(_fieldName, _size) {
5456
+ throw new Error("Cannot init list without schema information");
5457
+ }
5458
+ setText(_fieldName, _value) {
5459
+ throw new Error("Cannot set text without schema information");
5460
+ }
5461
+ setData(_fieldName, _value) {
5462
+ throw new Error("Cannot set data without schema information");
5463
+ }
5464
+ getSchema() {
5465
+ throw new Error("No schema information available");
5466
+ }
5467
+ getRawBuilder() {
5468
+ return this.structBuilder;
5469
+ }
5470
+ toBuffer() {
5471
+ return this.messageBuilder.toArrayBuffer();
5472
+ }
5473
+ };
5474
+ /**
5475
+ * Create a dynamic writer for a specific type ID
5476
+ * This looks up the schema in a registry and creates the appropriate writer
5477
+ *
5478
+ * @param typeId - The type ID of the struct
5479
+ * @param schemaRegistry - A map of type IDs to schema nodes
5480
+ * @returns A DynamicWriter for the message
5481
+ */
5482
+ function createDynamicWriterByTypeId(typeId, schemaRegistry) {
5483
+ const schema = schemaRegistry.get(typeId);
5484
+ if (!schema) throw new Error(`Schema not found for type ID: ${typeId}`);
5485
+ if (schema.type !== SchemaNodeType.STRUCT) throw new Error(`Type ${typeId} is not a struct`);
5486
+ return createDynamicWriter(schema);
5487
+ }
5488
+ /**
5489
+ * Utility function to create a message from a plain object
5490
+ * Uses schema information to properly serialize the data
5491
+ *
5492
+ * @param schema - The schema node describing the struct type
5493
+ * @param data - The data object to serialize
5494
+ * @returns The serialized message buffer
5495
+ */
5496
+ function serializeDynamic(schema, data) {
5497
+ const writer = createDynamicWriter(schema);
5498
+ writer.setFields(data);
5499
+ return writer.toBuffer();
5500
+ }
5501
+ /**
5502
+ * Utility function to create a message from a plain object using type ID
5503
+ *
5504
+ * @param typeId - The type ID of the struct
5505
+ * @param data - The data object to serialize
5506
+ * @param schemaRegistry - A map of type IDs to schema nodes
5507
+ * @returns The serialized message buffer
5508
+ */
5509
+ function serializeDynamicByTypeId(typeId, data, schemaRegistry) {
5510
+ const writer = createDynamicWriterByTypeId(typeId, schemaRegistry);
5511
+ writer.setFields(data);
5512
+ return writer.toBuffer();
5513
+ }
5514
+
5515
+ //#endregion
5516
+ //#region src/rpc/schema-capability.ts
5517
+ /**
5518
+ * Server-side implementation of the SchemaCapability interface.
5519
+ * Provides schema information to remote clients.
5520
+ */
5521
+ var SchemaCapabilityServer = class {
5522
+ registry;
5523
+ schemasByName;
5524
+ /**
5525
+ * Create a new SchemaCapabilityServer
5526
+ * @param initialSchemas - Optional map of schemas to register initially
5527
+ */
5528
+ constructor(initialSchemas) {
5529
+ this.registry = new Map(initialSchemas);
5530
+ this.schemasByName = /* @__PURE__ */ new Map();
5531
+ for (const schema of this.registry.values()) this.schemasByName.set(schema.displayName, schema);
5532
+ }
5533
+ /**
5534
+ * Register a schema node
5535
+ * @param node - The schema node to register
5536
+ */
5537
+ registerSchema(node) {
5538
+ this.registry.set(node.id, node);
5539
+ this.schemasByName.set(node.displayName, node);
5540
+ }
5541
+ /**
5542
+ * Unregister a schema by ID
5543
+ * @param typeId - The type ID to unregister
5544
+ */
5545
+ unregisterSchema(typeId) {
5546
+ const node = this.registry.get(typeId);
5547
+ if (node) {
5548
+ this.registry.delete(typeId);
5549
+ this.schemasByName.delete(node.displayName);
5550
+ }
5551
+ }
5552
+ /**
5553
+ * Get schema information based on target specification
5554
+ * @param params - GetSchemaParams containing target and format
5555
+ * @returns GetSchemaResults with the schema payload
5556
+ */
5557
+ async getSchema(params) {
5558
+ const { target, format = SchemaFormat.BINARY } = params;
5559
+ let schemaData;
5560
+ let dependencies = [];
5561
+ switch (target.type) {
5562
+ case "byTypeId": {
5563
+ const node = this.registry.get(target.typeId);
5564
+ if (!node) throw new Error(`Schema not found for type ID: ${target.typeId.toString(16)}`);
5565
+ schemaData = this.serializeSchemaNode(node, format);
5566
+ dependencies = this.collectDependencies(node);
5567
+ break;
5568
+ }
5569
+ case "byTypeName": {
5570
+ const node = this.schemasByName.get(target.typeName);
5571
+ if (!node) throw new Error(`Schema not found for type name: ${target.typeName}`);
5572
+ schemaData = this.serializeSchemaNode(node, format);
5573
+ dependencies = this.collectDependencies(node);
5574
+ break;
5575
+ }
5576
+ case "byFileId": {
5577
+ const nodes = this.getSchemasByFileId(target.fileId);
5578
+ schemaData = this.serializeSchemaNodes(nodes, format);
5579
+ break;
5580
+ }
5581
+ case "byFileName": {
5582
+ const nodes = this.getSchemasByFileName(target.fileName);
5583
+ schemaData = this.serializeSchemaNodes(nodes, format);
5584
+ break;
5585
+ }
5586
+ case "allSchemas": {
5587
+ const nodes = Array.from(this.registry.values());
5588
+ schemaData = this.serializeSchemaNodes(nodes, format);
5589
+ break;
5590
+ }
5591
+ case "bootstrapInterface": {
5592
+ const bootstrapSchema = this.findBootstrapSchema();
5593
+ if (!bootstrapSchema) throw new Error("Bootstrap interface schema not available");
5594
+ schemaData = this.serializeSchemaNode(bootstrapSchema, format);
5595
+ dependencies = this.collectDependencies(bootstrapSchema);
5596
+ break;
5597
+ }
5598
+ default: throw new Error(`Unsupported schema target type: ${target.type}`);
5599
+ }
5600
+ return { payload: {
5601
+ schemaData,
5602
+ format,
5603
+ dependencies
5604
+ } };
5605
+ }
5606
+ /**
5607
+ * List all available schemas
5608
+ * @returns ListSchemasResults with available schema information
5609
+ */
5610
+ async listAvailableSchemas() {
5611
+ const schemas = [];
5612
+ for (const node of this.registry.values()) schemas.push({
5613
+ typeId: node.id,
5614
+ displayName: node.displayName,
5615
+ fileId: node.scopeId,
5616
+ fileName: this.inferFileName(node),
5617
+ isInterface: node.type === SchemaNodeType.INTERFACE,
5618
+ isStruct: node.type === SchemaNodeType.STRUCT,
5619
+ isEnum: node.type === SchemaNodeType.ENUM
5620
+ });
5621
+ return { schemas };
5622
+ }
5623
+ /**
5624
+ * Handle a raw schema request (for RPC integration)
5625
+ * @param requestData - The serialized SchemaRequest
5626
+ * @returns The serialized SchemaResponse
5627
+ */
5628
+ handleRequest(requestData) {
5629
+ try {
5630
+ const request = deserializeSchemaRequest(requestData);
5631
+ this.getSchema({ target: request.targetSchema });
5632
+ throw new Error("Async handling not implemented in handleRequest");
5633
+ } catch (error) {
5634
+ return serializeSchemaResponse({
5635
+ answerId: 0,
5636
+ result: {
5637
+ type: "exception",
5638
+ exception: {
5639
+ reason: error instanceof Error ? error.message : "Unknown error",
5640
+ type: "failed",
5641
+ obsoleteIsCallersFault: false,
5642
+ obsoleteDurability: 0
5643
+ }
5644
+ }
5645
+ });
5646
+ }
5647
+ }
5648
+ /**
5649
+ * Get the number of registered schemas
5650
+ */
5651
+ getSchemaCount() {
5652
+ return this.registry.size;
5653
+ }
5654
+ /**
5655
+ * Check if a schema is registered
5656
+ */
5657
+ hasSchema(typeId) {
5658
+ return this.registry.has(typeId);
5659
+ }
5660
+ serializeSchemaNode(node, format) {
5661
+ switch (format) {
5662
+ case SchemaFormat.BINARY: return this.serializeToBinary([node]);
5663
+ case SchemaFormat.JSON: return this.serializeToJson([node]);
5664
+ case SchemaFormat.CAPNP: return this.serializeToCapnp([node]);
5665
+ default: throw new Error(`Unsupported schema format: ${format}`);
5666
+ }
5667
+ }
5668
+ serializeSchemaNodes(nodes, format) {
5669
+ switch (format) {
5670
+ case SchemaFormat.BINARY: return this.serializeToBinary(nodes);
5671
+ case SchemaFormat.JSON: return this.serializeToJson(nodes);
5672
+ case SchemaFormat.CAPNP: return this.serializeToCapnp(nodes);
5673
+ default: throw new Error(`Unsupported schema format: ${format}`);
5674
+ }
5675
+ }
5676
+ serializeToBinary(nodes) {
5677
+ const encoder = new TextEncoder();
5678
+ const json = JSON.stringify(nodes, (_key, value) => {
5679
+ if (typeof value === "bigint") return value.toString();
5680
+ return value;
5681
+ });
5682
+ return encoder.encode(json);
5683
+ }
5684
+ serializeToJson(nodes) {
5685
+ const encoder = new TextEncoder();
5686
+ const json = JSON.stringify({ nodes: nodes.map((node) => ({
5687
+ id: node.id.toString(),
5688
+ displayName: node.displayName,
5689
+ displayNamePrefixLength: node.displayNamePrefixLength,
5690
+ scopeId: node.scopeId.toString(),
5691
+ type: node.type,
5692
+ structInfo: node.structInfo,
5693
+ enumInfo: node.enumInfo,
5694
+ interfaceInfo: node.interfaceInfo
5695
+ })) });
5696
+ return encoder.encode(json);
5697
+ }
5698
+ serializeToCapnp(nodes) {
5699
+ const lines = [];
5700
+ for (const node of nodes) if (node.structInfo) {
5701
+ lines.push(`struct ${node.displayName} {`);
5702
+ for (const field of node.structInfo.fields) lines.push(` ${field.name} @${field.codeOrder} :${this.typeToCapnp(field.type)};`);
5703
+ lines.push("}");
5704
+ }
5705
+ return new TextEncoder().encode(lines.join("\n"));
5706
+ }
5707
+ typeToCapnp(type) {
5708
+ switch (type.kind.type) {
5709
+ case "void": return "Void";
5710
+ case "bool": return "Bool";
5711
+ case "int8": return "Int8";
5712
+ case "int16": return "Int16";
5713
+ case "int32": return "Int32";
5714
+ case "int64": return "Int64";
5715
+ case "uint8": return "UInt8";
5716
+ case "uint16": return "UInt16";
5717
+ case "uint32": return "UInt32";
5718
+ case "uint64": return "UInt64";
5719
+ case "float32": return "Float32";
5720
+ case "float64": return "Float64";
5721
+ case "text": return "Text";
5722
+ case "data": return "Data";
5723
+ case "list": return "List";
5724
+ case "enum": return "UInt16";
5725
+ case "struct": return "AnyPointer";
5726
+ case "interface": return "Capability";
5727
+ default: return "AnyPointer";
5728
+ }
5729
+ }
5730
+ collectDependencies(_node) {
5731
+ return [];
5732
+ }
5733
+ getSchemasByFileId(fileId) {
5734
+ return Array.from(this.registry.values()).filter((node) => node.scopeId === fileId);
5735
+ }
5736
+ getSchemasByFileName(fileName) {
5737
+ return Array.from(this.registry.values()).filter((node) => {
5738
+ return this.inferFileName(node) === fileName || node.displayName.startsWith(fileName);
5739
+ });
5740
+ }
5741
+ inferFileName(node) {
5742
+ const parts = node.displayName.split(".");
5743
+ if (parts.length > 1) return `${parts.slice(0, -1).join("/")}.capnp`;
5744
+ return "unknown.capnp";
5745
+ }
5746
+ findBootstrapSchema() {
5747
+ for (const node of this.registry.values()) if (node.type === SchemaNodeType.INTERFACE) return node;
5748
+ }
5749
+ };
5750
+ /**
5751
+ * Client-side implementation for accessing remote SchemaCapability
5752
+ */
5753
+ var SchemaCapabilityClient = class {
5754
+ connection;
5755
+ /**
5756
+ * Create a new SchemaCapabilityClient
5757
+ * @param connection - The RPC connection to use
5758
+ */
5759
+ constructor(connection) {
5760
+ this.connection = connection;
5761
+ }
5762
+ /**
5763
+ * Fetch schema information from the remote server
5764
+ * @param target - The schema target specification
5765
+ * @param format - The desired format (defaults to BINARY)
5766
+ * @returns The schema node
5767
+ */
5768
+ async getSchema(target, format = SchemaFormat.BINARY) {
5769
+ if (target.type === "byTypeId") return this.connection.getDynamicSchema(target.typeId);
5770
+ if (target.type === "byTypeName") return this.connection.getDynamicSchemaByName(target.typeName);
5771
+ throw new Error(`Schema target type not implemented: ${target.type}`);
5772
+ }
5773
+ /**
5774
+ * Fetch schema by type ID
5775
+ * @param typeId - The type ID
5776
+ * @returns The schema node
5777
+ */
5778
+ async getSchemaById(typeId) {
5779
+ return this.connection.getDynamicSchema(typeId);
5780
+ }
5781
+ /**
5782
+ * Fetch schema by type name
5783
+ * @param typeName - The fully qualified type name
5784
+ * @returns The schema node
5785
+ */
5786
+ async getSchemaByName(typeName) {
5787
+ return this.connection.getDynamicSchemaByName(typeName);
5788
+ }
5789
+ /**
5790
+ * List all available schemas from the remote server
5791
+ * @returns Array of available schema information
5792
+ */
5793
+ async listAvailableSchemas() {
5794
+ return (await this.connection.listAvailableSchemas()).map((s) => ({
5795
+ typeId: s.typeId,
5796
+ displayName: s.displayName,
5797
+ fileId: BigInt(0),
5798
+ fileName: "",
5799
+ isInterface: false,
5800
+ isStruct: true,
5801
+ isEnum: false
5802
+ }));
5803
+ }
5804
+ /**
5805
+ * Fetch multiple schemas at once
5806
+ * @param typeIds - Array of type IDs to fetch
5807
+ * @returns Map of type ID to schema node
5808
+ */
5809
+ async getSchemas(typeIds) {
5810
+ const results = /* @__PURE__ */ new Map();
5811
+ await Promise.all(typeIds.map(async (typeId) => {
5812
+ try {
5813
+ const schema = await this.getSchemaById(typeId);
5814
+ results.set(typeId, schema);
5815
+ } catch (error) {
5816
+ console.warn(`Failed to fetch schema ${typeId.toString(16)}:`, error);
5817
+ }
5818
+ }));
5819
+ return results;
5820
+ }
5821
+ /**
5822
+ * Check if a schema is available on the remote server
5823
+ * @param typeId - The type ID to check
5824
+ * @returns True if the schema is available
5825
+ */
5826
+ async hasSchema(typeId) {
5827
+ try {
5828
+ await this.getSchemaById(typeId);
5829
+ return true;
5830
+ } catch {
5831
+ return false;
5832
+ }
5833
+ }
5834
+ };
5835
+
5836
+ //#endregion
5837
+ export { AnswerTable, BaseCapabilityClient, BulkTransfer, BulkTransferManager, ConnectionManager, DEFAULT_BULK_CONFIG, DEFAULT_ESCROW_CONFIG, DEFAULT_FLOW_CONTROL, DEFAULT_JOIN_OPTIONS, DEFAULT_JOIN_SECURITY_POLICY, DEFAULT_REALTIME_CONFIG, DEFAULT_STREAMING_CAPABILITIES, DropPolicy, ElementSize, ExportTable, ImportTable, Level3Handlers, Level4Handlers, ListBuilder, ListReader, MemoryPool, MessageBuilder, MessageReader, MultiSegmentMessageBuilder, OptimizedRpcMessageBuilder, PIPELINE_CLIENT_SYMBOL, PipelineOpTracker, PipelineResolutionTracker, PointerTag, QuestionTable, QueuedCallManager, RealtimeStream, RealtimeStreamManager, RestoreHandler, RpcConnection, SCHEMA_MESSAGE_TYPES, SchemaCapabilityClient, SchemaCapabilityServer, SchemaFormat, Segment, Stream, StreamManager, StreamPriority, StreamType, StreamingRpcConnection, StructBuilder, StructReader, SturdyRefManager, UnionBuilder, UnionReader, WORD_SIZE, WebSocketTransport, configureGlobalMemoryPool, createBulkTransferManager, createDynamicReader, createDynamicReaderByTypeId, createDynamicReaderFromStruct, createDynamicWriter, createDynamicWriterByTypeId, createNestedDynamicWriter, createPipelineClient, createProvisionId, createRealtimeStreamManager, createRecipientId, createSchemaRegistry, createStream, createStreamManager, createStreamingConnection, createSturdyRef, createThirdPartyCapId, createUnionBuilder, createUnionReader, createZeroCopyView, decodePointer, deserializeRpcMessage, deserializeSchemaRequest, deserializeSchemaResponse, deserializeSturdyRef, dumpDynamicReader, encodeListPointer, encodeStructPointer, fastCopy, generateProvisionId, generateVatId, getGlobalMemoryPool, isPipelineClient, isSameBuffer, isStream, isSturdyRefValid, parseSchemaNodes, serializeDynamic, serializeDynamicByTypeId, serializeGetSchemaParams, serializeGetSchemaResults, serializeListSchemasResults, serializeRpcMessage, serializeSchemaRequest, serializeSchemaResponse, serializeSturdyRef, supportsStreaming };
4910
5838
  //# sourceMappingURL=index.js.map