@optimystic/quereus-plugin-optimystic 0.3.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/README.md +358 -0
- package/dist/index.d.ts +96 -0
- package/dist/index.js +2973 -0
- package/dist/index.js.map +1 -0
- package/dist/plugin-B1lVAVv0.d.ts +596 -0
- package/dist/plugin.d.ts +4 -0
- package/dist/plugin.js +2873 -0
- package/dist/plugin.js.map +1 -0
- package/examples/README.md +232 -0
- package/examples/quoomb.config.absolute.json +22 -0
- package/examples/quoomb.config.dev.json +16 -0
- package/examples/quoomb.config.linked.json +25 -0
- package/examples/quoomb.config.local.json +22 -0
- package/examples/quoomb.config.node1.json +23 -0
- package/examples/quoomb.config.node2.env.json +28 -0
- package/examples/quoomb.config.node2.json +29 -0
- package/examples/quoomb.config.single-node.json +25 -0
- package/examples/quoomb.config.web.json +30 -0
- package/examples/start-mesh.ps1 +48 -0
- package/examples/start-mesh.sh +44 -0
- package/examples/test-comprehensive.sql +25 -0
- package/examples/test-manual-plugin.txt +23 -0
- package/examples/test-multi-insert.sql +11 -0
- package/examples/test-network.sql +20 -0
- package/examples/test-plugin.sql +20 -0
- package/examples/test-single-insert.sql +20 -0
- package/examples/test-single-node.sql +20 -0
- package/package.json +131 -0
- package/src/functions/transaction-id.ts +29 -0
- package/src/index.ts +42 -0
- package/src/optimystic-adapter/collection-factory.ts +337 -0
- package/src/optimystic-adapter/key-network.ts +106 -0
- package/src/optimystic-adapter/txn-bridge.ts +272 -0
- package/src/optimystic-adapter/vtab-connection.ts +76 -0
- package/src/optimystic-module.ts +1064 -0
- package/src/plugin.ts +64 -0
- package/src/schema/index-manager.ts +266 -0
- package/src/schema/row-codec.ts +312 -0
- package/src/schema/schema-manager.ts +217 -0
- package/src/schema/statistics-collector.ts +173 -0
- package/src/transaction/index.ts +16 -0
- package/src/transaction/quereus-engine.ts +174 -0
- package/src/types.ts +91 -0
- package/src/util/generate-transaction-id.ts +41 -0
- package/test/README.md +313 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/optimystic-adapter/key-network.ts","../src/optimystic-adapter/collection-factory.ts","../node_modules/multiformats/src/bases/base58.ts","../node_modules/multiformats/src/bytes.ts","../node_modules/multiformats/src/vendor/base-x.js","../node_modules/multiformats/src/bases/base.ts","../node_modules/multiformats/src/bases/base32.ts","../node_modules/multiformats/src/bases/base36.ts","../node_modules/multiformats/src/vendor/varint.js","../node_modules/multiformats/src/varint.ts","../node_modules/multiformats/src/hashes/digest.ts","../node_modules/multiformats/src/hashes/identity.ts","../node_modules/uint8arrays/src/util/as-uint8array.node.ts","../node_modules/uint8arrays/src/alloc.node.ts","../node_modules/multiformats/src/bases/base10.ts","../node_modules/multiformats/src/bases/base16.ts","../node_modules/multiformats/src/bases/base2.ts","../node_modules/multiformats/src/bases/base256emoji.ts","../node_modules/multiformats/src/bases/base64.ts","../node_modules/multiformats/src/bases/base8.ts","../node_modules/multiformats/src/bases/identity.ts","../node_modules/multiformats/src/codecs/json.ts","../node_modules/multiformats/src/hashes/sha2.ts","../node_modules/multiformats/src/hashes/hasher.ts","../node_modules/multiformats/src/basics.ts","../node_modules/uint8arrays/src/util/bases.ts","../node_modules/uint8arrays/src/to-string.node.ts","../node_modules/@libp2p/crypto/src/random-bytes.ts","../src/util/generate-transaction-id.ts","../src/optimystic-adapter/txn-bridge.ts","../src/optimystic-adapter/vtab-connection.ts","../src/schema/schema-manager.ts","../src/schema/row-codec.ts","../src/schema/index-manager.ts","../src/schema/statistics-collector.ts","../src/optimystic-module.ts","../src/functions/transaction-id.ts","../src/plugin.ts"],"names":["name","createLibp2pNode","node","coordinatedRepo","Libp2pKeyPeerNetwork","getCustomRegistry","encode","length","i","j","decode","string","alphabet","code","digest","Buffer","identity_exports","identity","from","toString","base","randB","sha256","cache","TEXT_TYPE"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,IAAA,mBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,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IACA;AAAA,GACD;AACD","file":"plugin.js","sourcesContent":["import type { Libp2p } from '@libp2p/interface';\r\nimport type { IKeyNetwork } from '@optimystic/db-core';\r\nimport { Libp2pKeyPeerNetwork } from '@optimystic/db-p2p';\r\nimport { createLibp2pNode } from '@optimystic/db-p2p';\r\nimport type { LibP2PNodeOptions, CustomImplementationRegistry } from '../types.js';\r\n\r\n/**\r\n * Global registry for custom implementations\r\n */\r\nconst customRegistry: CustomImplementationRegistry = {\r\n transactors: new Map(),\r\n keyNetworks: new Map(),\r\n};\r\n\r\n/**\r\n * Register a custom key network implementation\r\n */\r\nexport function registerKeyNetwork(name: string, implementation: new (...args: any[]) => IKeyNetwork): void {\r\n customRegistry.keyNetworks.set(name, implementation);\r\n}\r\n\r\n/**\r\n * Register a custom transactor implementation\r\n */\r\nexport function registerTransactor(name: string, implementation: new (...args: any[]) => any): void {\r\n customRegistry.transactors.set(name, implementation);\r\n}\r\n\r\n/**\r\n * Create a key network instance based on configuration\r\n */\r\nexport async function createKeyNetwork(\r\n type: 'libp2p' | 'test' | string,\r\n libp2p?: Libp2p,\r\n libp2pOptions?: LibP2PNodeOptions\r\n): Promise<IKeyNetwork> {\r\n switch (type) {\r\n case 'libp2p':\r\n return await createLibp2pKeyNetwork(libp2p, libp2pOptions);\r\n\r\n case 'test':\r\n return await createTestKeyNetwork();\r\n\r\n default:\r\n return await createCustomKeyNetwork(type);\r\n }\r\n}\r\n\r\n/**\r\n * Create a libp2p-based key network\r\n */\r\nasync function createLibp2pKeyNetwork(\r\n existingLibp2p?: Libp2p,\r\n options?: LibP2PNodeOptions\r\n): Promise<IKeyNetwork> {\r\n let libp2p: Libp2p;\r\n\r\n if (existingLibp2p) {\r\n libp2p = existingLibp2p;\r\n } else {\r\n // Create a new libp2p node with default options\r\n const nodeOptions = {\r\n port: options?.port ?? 0, // Use random port if not specified\r\n networkName: options?.networkName ?? 'optimystic',\r\n bootstrapNodes: options?.bootstrapNodes ?? [],\r\n };\r\n\r\n libp2p = await createLibp2pNode(nodeOptions);\r\n }\r\n\r\n return new Libp2pKeyPeerNetwork(libp2p);\r\n}\r\n\r\n/**\r\n * Create a test key network (for testing purposes)\r\n */\r\nasync function createTestKeyNetwork(): Promise<IKeyNetwork> {\r\n // Provide a local stub to avoid build-time dependency on non-existent test utilities\r\n return {\r\n async findCoordinator() {\r\n throw new Error('Test key network is not available in this build.');\r\n },\r\n async findCluster() {\r\n throw new Error('Test key network is not available in this build.');\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Create a custom key network implementation\r\n */\r\nasync function createCustomKeyNetwork(name: string): Promise<IKeyNetwork> {\r\n const CustomKeyNetwork = customRegistry.keyNetworks.get(name);\r\n if (!CustomKeyNetwork) {\r\n throw new Error(`Custom key network '${name}' not found. Register it first using registerKeyNetwork().`);\r\n }\r\n\r\n return new CustomKeyNetwork();\r\n}\r\n\r\n/**\r\n * Get the custom implementation registry (for testing/debugging)\r\n */\r\nexport function getCustomRegistry(): CustomImplementationRegistry {\r\n return customRegistry;\r\n}\r\n","import type { ITransactor, CollectionId } from '@optimystic/db-core';\r\nimport { Tree } from '@optimystic/db-core';\r\nimport { NetworkTransactor } from '@optimystic/db-core';\r\nimport type { RowData, ParsedOptimysticOptions, TransactionState } from '../types.js';\r\nimport { createKeyNetwork } from './key-network.js';\r\nimport type { IRepo } from '@optimystic/db-core';\r\nimport type { PeerId, Libp2p } from '@libp2p/interface';\r\n\r\n/**\r\n * Factory for creating and managing tree collections\r\n */\r\nexport class CollectionFactory {\r\n private transactors = new Map<string, ITransactor>();\r\n private libp2pNodes = new Map<string, { node: Libp2p; coordinatedRepo: IRepo }>();\r\n\r\n /**\r\n * Create or get a tree collection\r\n * Collections are only cached within a transaction to ensure proper isolation\r\n */\r\n async createOrGetCollection(\r\n options: ParsedOptimysticOptions,\r\n txnState?: TransactionState\r\n ): Promise<Tree<string, RowData>> {\r\n const collectionKey = this.getCollectionKey(options);\r\n\r\n // Check transaction-specific cache (only cache within transaction scope)\r\n if (txnState?.isActive && txnState.collections.has(collectionKey)) {\r\n return txnState.collections.get(collectionKey)!;\r\n }\r\n\r\n // Create new collection\r\n const transactor = await this.getOrCreateTransactor(options);\r\n const collectionId = this.parseCollectionId(options.collectionUri);\r\n\r\n const compare = (a: string, b: string): -1 | 0 | 1 => (a < b ? -1 : a > b ? 1 : 0);\r\n\r\n // Schema tree uses simple [key, value] tuples, not RowData arrays\r\n const isSchemaTree = options.collectionUri === 'tree://optimystic/schema';\r\n const keyExtractor = isSchemaTree\r\n ? (entry: any) => entry[0] as string // For schema tree: [tableName, schema]\r\n : (entry: RowData) => this.extractKeyFromEntry(entry); // For data trees: extract from RowData\r\n\r\n const collection = await Tree.createOrOpen<string, RowData>(\r\n transactor,\r\n collectionId,\r\n keyExtractor,\r\n compare // Total order\r\n );\r\n\r\n // Store in transaction-specific cache (if we have an active transaction)\r\n if (txnState?.isActive) {\r\n txnState.collections.set(collectionKey, collection);\r\n }\r\n\r\n return collection;\r\n }\r\n\r\n /**\r\n * Create a transactor for the given configuration\r\n */\r\n async createTransactor(options: ParsedOptimysticOptions): Promise<ITransactor> {\r\n switch (options.transactor) {\r\n case 'network':\r\n return await this.createNetworkTransactor(options);\r\n\r\n case 'local':\r\n return await this.createLocalTransactor();\r\n\r\n case 'test':\r\n return await this.createTestTransactor();\r\n\r\n default:\r\n return await this.createCustomTransactor(options.transactor);\r\n }\r\n }\r\n\r\n /**\r\n * Get or create a transactor (with caching)\r\n */\r\n async getOrCreateTransactor(options: ParsedOptimysticOptions): Promise<ITransactor> {\r\n const transactorKey = this.getTransactorKey(options);\r\n\r\n if (this.transactors.has(transactorKey)) {\r\n return this.transactors.get(transactorKey)!;\r\n }\r\n\r\n const transactor = await this.createTransactor(options);\r\n this.transactors.set(transactorKey, transactor);\r\n return transactor;\r\n }\r\n\r\n /**\r\n * Create a network transactor\r\n */\r\n private async createNetworkTransactor(options: ParsedOptimysticOptions): Promise<ITransactor> {\r\n // Create or get libp2p node\r\n const nodeKey = this.getNodeKey(options);\r\n let nodeInfo = this.libp2pNodes.get(nodeKey);\r\n\r\n if (!nodeInfo) {\r\n // Create a new libp2p node with all necessary services\r\n const { createLibp2pNode } = await import('@optimystic/db-p2p');\r\n\r\n const node = await createLibp2pNode({\r\n port: options.libp2pOptions?.port ?? 0,\r\n networkName: options.libp2pOptions?.networkName ?? 'optimystic',\r\n bootstrapNodes: options.libp2pOptions?.bootstrapNodes ?? [],\r\n storageType: 'memory',\r\n fretProfile: 'edge',\r\n clusterSize: 1,\r\n clusterPolicy: {\r\n allowDownsize: true,\r\n sizeTolerance: 1.0\r\n },\r\n arachnode: {\r\n enableRingZulu: true\r\n }\r\n });\r\n\r\n // Get the coordinatedRepo that was created by createLibp2pNode\r\n const coordinatedRepo = (node as any).coordinatedRepo as IRepo;\r\n if (!coordinatedRepo) {\r\n throw new Error('Failed to get coordinatedRepo from libp2p node');\r\n }\r\n\r\n nodeInfo = { node, coordinatedRepo };\r\n this.libp2pNodes.set(nodeKey, nodeInfo);\r\n }\r\n\r\n const { node, coordinatedRepo } = nodeInfo;\r\n\r\n // Create Libp2pKeyPeerNetwork which implements both IKeyNetwork and IPeerNetwork\r\n const { Libp2pKeyPeerNetwork, RepoClient } = await import('@optimystic/db-p2p');\r\n const keyNetwork = new Libp2pKeyPeerNetwork(node);\r\n const protocolPrefix = `/optimystic/${options.libp2pOptions?.networkName ?? 'optimystic'}`;\r\n\r\n const getRepo = (peerId: PeerId): IRepo => {\r\n // If it's the local peer, return the coordinated repo\r\n if (peerId.toString() === node.peerId.toString()) {\r\n return coordinatedRepo;\r\n }\r\n // For remote peers, create a RepoClient\r\n return RepoClient.create(peerId, keyNetwork, protocolPrefix);\r\n };\r\n\r\n return new NetworkTransactor({\r\n timeoutMs: 30_000,\r\n abortOrCancelTimeoutMs: 5_000,\r\n keyNetwork,\r\n getRepo,\r\n });\r\n }\r\n\r\n /**\r\n * Create a local transactor (in-memory, single-node, no network)\r\n */\r\n private async createLocalTransactor(): Promise<ITransactor> {\r\n const { StorageRepo, BlockStorage, MemoryRawStorage } = await import('@optimystic/db-p2p');\r\n\r\n // Create a shared memory storage for all blocks\r\n const memoryStorage = new MemoryRawStorage();\r\n const storageRepo = new StorageRepo((blockId: string) => new BlockStorage(blockId, memoryStorage));\r\n\r\n // LocalTransactor implementation (simple wrapper around StorageRepo)\r\n return {\r\n async get(blockGets) {\r\n return await storageRepo.get(blockGets);\r\n },\r\n async getStatus(_trxRefs) {\r\n throw new Error('getStatus not implemented in local transactor');\r\n },\r\n async pend(request) {\r\n return await storageRepo.pend(request);\r\n },\r\n async commit(request) {\r\n return await storageRepo.commit(request);\r\n },\r\n async cancel(trxRef) {\r\n return await storageRepo.cancel(trxRef);\r\n },\r\n } as ITransactor;\r\n }\r\n\r\n /**\r\n * Create a test transactor (in-memory, single-node)\r\n */\r\n private async createTestTransactor(): Promise<ITransactor> {\r\n const { StorageRepo, BlockStorage, MemoryRawStorage } = await import('@optimystic/db-p2p');\r\n\r\n // Create a shared memory storage for all blocks\r\n const memoryStorage = new MemoryRawStorage();\r\n\r\n const storageRepo = new StorageRepo((blockId) => new BlockStorage(blockId, memoryStorage));\r\n\r\n // Simple local transactor that wraps StorageRepo\r\n return {\r\n async get(blockGets) {\r\n return await storageRepo.get(blockGets);\r\n },\r\n async getStatus(_trxRefs) {\r\n throw new Error('getStatus not implemented in test transactor');\r\n },\r\n async pend(request) {\r\n return await storageRepo.pend(request);\r\n },\r\n async commit(request) {\r\n return await storageRepo.commit(request);\r\n },\r\n async cancel(trxRef) {\r\n return await storageRepo.cancel(trxRef);\r\n },\r\n } as ITransactor;\r\n }\r\n\r\n /**\r\n * Create a custom transactor\r\n */\r\n private async createCustomTransactor(name: string): Promise<ITransactor> {\r\n // This would use the custom registry from key-network.ts\r\n const { getCustomRegistry } = await import('./key-network.js');\r\n const registry = getCustomRegistry();\r\n\r\n const CustomTransactor = registry.transactors.get(name);\r\n if (!CustomTransactor) {\r\n throw new Error(`Custom transactor '${name}' not found. Register it first using registerTransactor().`);\r\n }\r\n\r\n return new CustomTransactor();\r\n }\r\n\r\n /**\r\n * Parse collection URI to extract collection ID\r\n */\r\n private parseCollectionId(uri: string): CollectionId {\r\n if (!uri) {\r\n throw new Error('Collection URI is required');\r\n }\r\n // Parse URIs like 'tree://mydb/users' or just 'users'\r\n if (uri.startsWith('tree://')) {\r\n const path = uri.substring(7); // Remove 'tree://'\r\n const parts = path.split('/');\r\n if (parts.length >= 2) {\r\n return parts[1]! as unknown as CollectionId; // collection name part\r\n }\r\n return path as unknown as CollectionId;\r\n }\r\n return uri as unknown as CollectionId;\r\n }\r\n\r\n /**\r\n * Extract key from entry\r\n * Entry format: [primaryKey, encodedRow]\r\n */\r\n private extractKeyFromEntry(entry: RowData): string {\r\n return entry[0];\r\n }\r\n\r\n /**\r\n * Generate a unique key for collection caching\r\n */\r\n private getCollectionKey(options: ParsedOptimysticOptions): string {\r\n return `${options.collectionUri}:${options.transactor}:${options.keyNetwork}`;\r\n }\r\n\r\n /**\r\n * Generate a unique key for transactor caching\r\n */\r\n private getTransactorKey(options: ParsedOptimysticOptions): string {\r\n return `${options.transactor}:${options.keyNetwork}`;\r\n }\r\n\r\n /**\r\n * Get the peer ID from the current libp2p node (if available)\r\n */\r\n getPeerId(options: ParsedOptimysticOptions): string | undefined {\r\n const nodeKey = this.getNodeKey(options);\r\n const nodeInfo = this.libp2pNodes.get(nodeKey);\r\n return nodeInfo?.node.peerId.toString();\r\n }\r\n\r\n /**\r\n * Register an existing libp2p node for use by the factory.\r\n * This allows tests to inject pre-created nodes instead of having the factory create new ones.\r\n */\r\n registerLibp2pNode(networkName: string, node: Libp2p, coordinatedRepo: IRepo): void {\r\n const nodeKey = `${networkName}:0`; // Use port 0 as default for registered nodes\r\n this.libp2pNodes.set(nodeKey, { node, coordinatedRepo });\r\n }\r\n\r\n /**\r\n * Register an existing transactor for use by the factory.\r\n * This allows tests to inject pre-created transactors.\r\n */\r\n registerTransactor(key: string, transactor: ITransactor): void {\r\n this.transactors.set(key, transactor);\r\n }\r\n\r\n /**\r\n * Generate a unique key for libp2p node caching\r\n */\r\n private getNodeKey(options: ParsedOptimysticOptions): string {\r\n const networkName = options.libp2pOptions?.networkName ?? 'optimystic';\r\n const port = options.libp2pOptions?.port ?? 0;\r\n return `${networkName}:${port}`;\r\n }\r\n\r\n /**\r\n * Clear all cached transactors (useful for testing or cleanup)\r\n * Note: Collections are only cached within transactions, not globally\r\n */\r\n clearCache(): void {\r\n this.transactors.clear();\r\n }\r\n\r\n /**\r\n * Shutdown all libp2p nodes\r\n */\r\n async shutdown(): Promise<void> {\r\n for (const [key, { node }] of this.libp2pNodes.entries()) {\r\n console.log(`Stopping libp2p node: ${key}`);\r\n await node.stop();\r\n }\r\n this.libp2pNodes.clear();\r\n }\r\n\r\n /**\r\n * Sync a collection (call collection.sync())\r\n */\r\n async syncCollection(collection: Tree<string, RowData>): Promise<void> {\r\n // The Tree class doesn't expose sync directly, but we can call updateAndSync\r\n // This is a placeholder - we'd need to check the actual Tree API\r\n // await collection.updateAndSync();\r\n\r\n // For now, we'll assume the sync happens as part of the replace operation\r\n // which calls updateAndSync internally\r\n }\r\n}\r\n","import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n","export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) { return true }\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') { return o }\n if (o instanceof ArrayBuffer) { return new Uint8Array(o) }\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n","import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = alphabetIdx[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n const alphabetIdx = createAlphabetIdx(alphabet)\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabetIdx, bitsPerChar, name)\n }\n })\n}\n","import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n","import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n","/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n","import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n","import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n return digest.code === code\n}\n","import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\nimport type { DigestOptions } from './hasher.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array, options?: DigestOptions): Digest.Digest<typeof code, number> {\n if (options?.truncate != null && options.truncate !== input.byteLength) {\n if (options.truncate < 0 || options.truncate > input.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`)\n }\n\n input = input.subarray(0, options.truncate)\n }\n\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n","/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array {\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)\n}\n","import { Buffer } from 'node:buffer'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return asUint8Array(Buffer.alloc(size))\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return asUint8Array(Buffer.allocUnsafe(size))\n}\n","import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n","import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n","import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n","import { from } from './base.js'\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\nconst alphabetBytesToChars: string[] = (alphabet.reduce<string[]>((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce<number[]>((p, c, i) => {\n const codePoint = c.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`)\n }\n p[codePoint] = i\n return p\n}, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const codePoint = char.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`)\n }\n const byt = alphabetCharsToBytes[codePoint]\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode <T> (node: T): ByteView<T> {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode <T> (data: ByteView<T> | ArrayBufferView<T>): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","import crypto from 'crypto'\nimport { coerce } from '../bytes.js'\nimport { from } from './hasher.js'\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: (input) => coerce(crypto.createHash('sha256').update(input).digest())\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: input => coerce(crypto.createHash('sha512').update(input).digest())\n})\n","import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await<T> = Promise<T> | T\n\nconst DEFAULT_MIN_DIGEST_LENGTH = 20\n\nexport interface HasherInit <Name extends string, Code extends number> {\n name: Name\n code: Code\n encode(input: Uint8Array): Await<Uint8Array>\n\n /**\n * The minimum length a hash is allowed to be truncated to in bytes\n *\n * @default 20\n */\n minDigestLength?: number\n\n /**\n * The maximum length a hash is allowed to be truncated to in bytes. If not\n * specified it will be inferred from the length of the digest.\n */\n maxDigestLength?: number\n}\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode, minDigestLength, maxDigestLength }: HasherInit<Name, Code>): Hasher<Name, Code> {\n return new Hasher(name, code, encode, minDigestLength, maxDigestLength)\n}\n\nexport interface DigestOptions {\n /**\n * Truncate the returned digest to this number of bytes.\n *\n * This may cause the digest method to throw/reject if the passed value is\n * greater than the digest length or below a threshold under which the risk of\n * hash collisions is significant.\n *\n * The actual value of this threshold can depend on the hashing algorithm in\n * use.\n */\n truncate?: number\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher<Name extends string, Code extends number> implements MultihashHasher<Code> {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await<Uint8Array>\n readonly minDigestLength: number\n readonly maxDigestLength?: number\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>, minDigestLength?: number, maxDigestLength?: number) {\n this.name = name\n this.code = code\n this.encode = encode\n this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH\n this.maxDigestLength = maxDigestLength\n }\n\n digest (input: Uint8Array, options?: DigestOptions): Await<Digest.Digest<Code, number>> {\n if (options?.truncate != null) {\n if (options.truncate < this.minDigestLength) {\n throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`)\n }\n\n if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)\n }\n }\n\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n\n if (result instanceof Uint8Array) {\n return createDigest(result, this.code, options?.truncate)\n }\n\n return result.then(digest => createDigest(digest, this.code, options?.truncate))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * Create a Digest from the passed uint8array and code, optionally truncating it\n * first.\n */\nfunction createDigest <Code extends number> (digest: Uint8Array, code: Code, truncate?: number): Digest.Digest<Code, number> {\n if (truncate != null && truncate !== digest.byteLength) {\n if (truncate > digest.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`)\n }\n\n digest = digest.subarray(0, truncate)\n }\n\n return Digest.create(code, digest)\n}\n","import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n","import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec<any> {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record<SupportedEncodings, MultibaseCodec<any>> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n","import { Buffer } from 'node:buffer'\nimport bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n if (encoding === 'utf8' || encoding === 'utf-8') {\n return Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString('utf8')\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n","import { InvalidParametersError } from '@libp2p/interface'\nimport { randomBytes as randB } from '@noble/hashes/utils.js'\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes (length: number): Uint8Array {\n if (isNaN(length) || length <= 0) {\n throw new InvalidParametersError('random bytes length must be a Number bigger than 0')\n }\n return randB(length)\n}\n","import { randomBytes } from '@libp2p/crypto';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { sha256 } from '@noble/hashes/sha256';\n\n/**\n * Generates a unique transaction ID that includes a hash of the peer ID\n * to reduce collision probability across distributed nodes.\n * \n * Format: {peerIdHash}-{randomBytes}\n * - peerIdHash: First 16 bytes of SHA-256 hash of peer ID (base64url)\n * - randomBytes: 16 random bytes (base64url)\n * - Total: 32 bytes, base64url encoded\n * \n * @param peerId Optional peer ID to include in the hash. If not provided, only random bytes are used.\n * @returns A unique transaction ID string\n */\nexport function generateTransactionId(peerId?: string): string {\n\tconst randomPart = randomBytes(16);\n\t\n\tif (peerId) {\n\t\t// Hash the peer ID and take first 16 bytes\n\t\tconst peerIdBytes = new TextEncoder().encode(peerId);\n\t\tconst peerIdHash = sha256(peerIdBytes);\n\t\tconst peerIdHashPart = peerIdHash.slice(0, 16);\n\t\t\n\t\t// Combine peer ID hash and random bytes\n\t\tconst combined = new Uint8Array(32);\n\t\tcombined.set(peerIdHashPart, 0);\n\t\tcombined.set(randomPart, 16);\n\t\t\n\t\treturn uint8ArrayToString(combined, 'base64url');\n\t}\n\t\n\t// Fallback: just use random bytes (padded to 32 bytes for consistency)\n\tconst fallback = new Uint8Array(32);\n\tfallback.set(randomPart, 0);\n\tfallback.set(randomBytes(16), 16);\n\t\n\treturn uint8ArrayToString(fallback, 'base64url');\n}\n\n","import type { ITransactor, TransactionCoordinator, ITransactionEngine } from '@optimystic/db-core';\r\nimport { TransactionSession, createTransactionStamp, createTransactionId } from '@optimystic/db-core';\r\nimport type { TransactionState, ParsedOptimysticOptions } from '../types.js';\r\nimport { CollectionFactory } from './collection-factory.js';\r\nimport { generateTransactionId as generateLegacyTransactionId } from '../util/generate-transaction-id.js';\r\nimport { QUEREUS_ENGINE_ID } from '../transaction/quereus-engine.js';\r\n\r\n/**\r\n * Transaction bridge between Quereus and Optimystic.\r\n *\r\n * This bridge handles both:\r\n * 1. Legacy mode: Direct collection sync (when no coordinator/engine is set)\r\n * 2. Transaction mode: Using TransactionSession for distributed consensus\r\n */\r\nexport class TransactionBridge {\r\n private currentTransaction: TransactionState | null = null;\r\n private collectionFactory: CollectionFactory;\r\n /** Accumulated SQL statements for the current transaction */\r\n private accumulatedStatements: string[] = [];\r\n /** Optional transaction session for distributed consensus */\r\n private session: TransactionSession | null = null;\r\n /** Optional coordinator for transaction mode */\r\n private coordinator: TransactionCoordinator | null = null;\r\n /** Optional engine for transaction mode */\r\n private engine: ITransactionEngine | null = null;\r\n /** Schema hash provider function */\r\n private schemaHashProvider: (() => Promise<string>) | null = null;\r\n\r\n constructor(collectionFactory: CollectionFactory) {\r\n this.collectionFactory = collectionFactory;\r\n }\r\n\r\n /**\r\n * Configure the transaction bridge for distributed consensus mode.\r\n *\r\n * When configured, transactions will use TransactionSession for\r\n * coordinated commit with validation.\r\n *\r\n * @param coordinator - The transaction coordinator\r\n * @param engine - The transaction engine (e.g., QuereusEngine)\r\n * @param schemaHashProvider - Function to get the current schema hash\r\n */\r\n configureTransactionMode(\r\n coordinator: TransactionCoordinator,\r\n engine: ITransactionEngine,\r\n schemaHashProvider: () => Promise<string>\r\n ): void {\r\n this.coordinator = coordinator;\r\n this.engine = engine;\r\n this.schemaHashProvider = schemaHashProvider;\r\n }\r\n\r\n /**\r\n * Check if transaction mode is enabled.\r\n */\r\n isTransactionModeEnabled(): boolean {\r\n return this.coordinator !== null && this.engine !== null;\r\n }\r\n\r\n /**\r\n * Begin a new transaction.\r\n *\r\n * If transaction mode is enabled, creates a TransactionSession for\r\n * distributed consensus. Otherwise, uses legacy direct sync mode.\r\n *\r\n * Following SQLite semantics: if a transaction is already active,\r\n * this is a no-op and returns the existing transaction.\r\n */\r\n async beginTransaction(options: ParsedOptimysticOptions): Promise<TransactionState> {\r\n if (this.currentTransaction?.isActive) {\r\n // Already in transaction - SQLite semantics: BEGIN is a no-op\r\n return this.currentTransaction;\r\n }\r\n\r\n const transactor = await this.collectionFactory.getOrCreateTransactor(options);\r\n const peerId = this.collectionFactory.getPeerId(options);\r\n\r\n // Clear any previously accumulated statements\r\n this.accumulatedStatements = [];\r\n\r\n // Create TransactionSession if transaction mode is enabled\r\n if (this.coordinator && this.engine && this.schemaHashProvider) {\r\n const schemaHash = await this.schemaHashProvider();\r\n this.session = new TransactionSession(\r\n this.coordinator,\r\n this.engine,\r\n peerId,\r\n schemaHash\r\n );\r\n } else {\r\n this.session = null;\r\n }\r\n\r\n // Generate transaction ID from session or legacy method\r\n const transactionId = this.session\r\n ? this.session.getStampId()\r\n : generateLegacyTransactionId(peerId);\r\n\r\n this.currentTransaction = {\r\n transactor,\r\n isActive: true,\r\n collections: new Map(),\r\n transactionId,\r\n };\r\n\r\n return this.currentTransaction;\r\n }\r\n\r\n /**\r\n * Commit the current transaction.\r\n *\r\n * If transaction mode is enabled, commits through TransactionSession\r\n * for distributed consensus. Otherwise, uses legacy direct sync.\r\n */\r\n async commitTransaction(): Promise<void> {\r\n if (!this.currentTransaction?.isActive) {\r\n throw new Error('No active transaction to commit');\r\n }\r\n\r\n try {\r\n if (this.session) {\r\n // Transaction mode: commit through session for distributed consensus\r\n const result = await this.session.commit();\r\n if (!result.success) {\r\n throw new Error(result.error || 'Transaction commit failed');\r\n }\r\n } else {\r\n // Legacy mode: sync all collections directly\r\n for (const [, collection] of this.currentTransaction.collections) {\r\n await this.collectionFactory.syncCollection(collection);\r\n }\r\n }\r\n\r\n this.currentTransaction.isActive = false;\r\n this.accumulatedStatements = [];\r\n this.session = null;\r\n\r\n } catch (error) {\r\n // If commit fails, rollback\r\n await this.rollbackTransaction();\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Rollback the current transaction.\r\n *\r\n * Discards local changes and clears session state.\r\n */\r\n async rollbackTransaction(): Promise<void> {\r\n if (!this.currentTransaction?.isActive) {\r\n throw new Error('No active transaction to rollback');\r\n }\r\n\r\n // Rollback session if in transaction mode\r\n if (this.session && !this.session.isRolledBack()) {\r\n try {\r\n await this.session.rollback();\r\n } catch {\r\n // Ignore rollback errors - we're already cleaning up\r\n }\r\n }\r\n\r\n // Clean up local state\r\n this.currentTransaction.collections.clear();\r\n this.currentTransaction.isActive = false;\r\n\r\n this.accumulatedStatements = [];\r\n this.session = null;\r\n\r\n // Note: We intentionally do NOT clear the collection factory cache here.\r\n // The transactor cache contains pre-registered transactors that should persist\r\n // across transactions. Clearing them would cause the factory to create new\r\n // disconnected transactors instead of using the registered ones.\r\n }\r\n\r\n /**\r\n * Get the current transaction state.\r\n */\r\n getCurrentTransaction(): TransactionState | null {\r\n return this.currentTransaction;\r\n }\r\n\r\n /**\r\n * Get the current transaction session (if in transaction mode).\r\n */\r\n getSession(): TransactionSession | null {\r\n return this.session;\r\n }\r\n\r\n /**\r\n * Check if a transaction is currently active.\r\n */\r\n isTransactionActive(): boolean {\r\n return this.currentTransaction?.isActive ?? false;\r\n }\r\n\r\n /**\r\n * Add a SQL statement to the accumulated statements for the current transaction.\r\n * Statements are only accumulated when a transaction is active.\r\n *\r\n * In transaction mode, this also forwards the statement to the TransactionSession\r\n * for distributed consensus tracking.\r\n *\r\n * @param statement The deterministic SQL statement to accumulate\r\n */\r\n addStatement(statement: string): void {\r\n if (!this.currentTransaction?.isActive) {\r\n return;\r\n }\r\n\r\n this.accumulatedStatements.push(statement);\r\n\r\n // In transaction mode, also track in session\r\n // Note: We pass empty actions since the virtual table already applied changes\r\n // The session just needs to track the statement for the Transaction record\r\n if (this.session) {\r\n // We don't await here - statement tracking is synchronous\r\n // The session's execute() will just accumulate the statement\r\n // Actions are already applied by the virtual table\r\n void this.session.execute(statement, []);\r\n }\r\n }\r\n\r\n /**\r\n * Get all accumulated SQL statements for the current transaction.\r\n * @returns Array of SQL statements in execution order\r\n */\r\n getStatements(): readonly string[] {\r\n return this.accumulatedStatements;\r\n }\r\n\r\n /**\r\n * Get the count of accumulated statements\r\n */\r\n getStatementCount(): number {\r\n return this.accumulatedStatements.length;\r\n }\r\n\r\n /**\r\n * Savepoint support (if needed by Quereus)\r\n */\r\n async savepoint(name: string): Promise<void> {\r\n // Optimystic doesn't have explicit savepoint support\r\n // This would need to be implemented using collection snapshots\r\n throw new Error('Savepoints not yet implemented');\r\n }\r\n\r\n /**\r\n * Release savepoint\r\n */\r\n async releaseSavepoint(name: string): Promise<void> {\r\n throw new Error('Savepoints not yet implemented');\r\n }\r\n\r\n /**\r\n * Rollback to savepoint\r\n */\r\n async rollbackToSavepoint(name: string): Promise<void> {\r\n throw new Error('Savepoints not yet implemented');\r\n }\r\n\r\n /**\r\n * Cleanup resources\r\n */\r\n async cleanup(): Promise<void> {\r\n if (this.currentTransaction?.isActive) {\r\n await this.rollbackTransaction();\r\n }\r\n this.currentTransaction = null;\r\n }\r\n}\r\n","/**\n * VirtualTableConnection implementation for Optimystic tables.\n * Wraps the TransactionBridge to provide the generic VirtualTableConnection interface.\n */\n\nimport type { VirtualTableConnection } from '@quereus/quereus';\nimport type { TransactionBridge } from './txn-bridge.js';\nimport type { ParsedOptimysticOptions } from '../types.js';\n\nlet connectionCounter = 0;\n\n/**\n * Connection wrapper that bridges Quereus transaction lifecycle to Optimystic TransactionBridge\n */\nexport class OptimysticVirtualTableConnection implements VirtualTableConnection {\n\tpublic readonly connectionId: string;\n\tpublic readonly tableName: string;\n\tprivate txnBridge: TransactionBridge;\n\tprivate options: ParsedOptimysticOptions;\n\n\tconstructor(tableName: string, txnBridge: TransactionBridge, options: ParsedOptimysticOptions) {\n\t\tthis.connectionId = `optimystic-${tableName}-${++connectionCounter}`;\n\t\tthis.tableName = tableName;\n\t\tthis.txnBridge = txnBridge;\n\t\tthis.options = options;\n\t}\n\n\t/** Begins a transaction on this connection */\n\tasync begin(): Promise<void> {\n\t\tawait this.txnBridge.beginTransaction(this.options);\n\t}\n\n\t/** Commits the current transaction */\n\tasync commit(): Promise<void> {\n\t\t// For implicit transactions, Quereus may call commit() without calling begin() first\n\t\t// In this case, we need to start a transaction before committing\n\t\tconst currentTxn = this.txnBridge.getCurrentTransaction();\n\t\tif (!currentTxn?.isActive) {\n\t\t\tawait this.txnBridge.beginTransaction(this.options);\n\t\t}\n\t\tawait this.txnBridge.commitTransaction();\n\t}\n\n\t/** Rolls back the current transaction */\n\tasync rollback(): Promise<void> {\n\t\tawait this.txnBridge.rollbackTransaction();\n\t}\n\n\t/** Creates a savepoint with the given index */\n\tcreateSavepoint(_index: number): void {\n\t\t// Optimystic doesn't currently support savepoints\n\t\t// This is a no-op for now\n\t}\n\n\t/** Releases a savepoint with the given index */\n\treleaseSavepoint(_index: number): void {\n\t\t// Optimystic doesn't currently support savepoints\n\t\t// This is a no-op for now\n\t}\n\n\t/** Rolls back to a savepoint with the given index */\n\trollbackToSavepoint(_index: number): void {\n\t\t// Optimystic doesn't currently support savepoints\n\t\t// This is a no-op for now\n\t}\n\n\t/** Disconnects and cleans up this connection */\n\tasync disconnect(): Promise<void> {\n\t\t// If there's an active transaction, roll it back\n\t\tconst currentTxn = this.txnBridge.getCurrentTransaction();\n\t\tif (currentTxn?.isActive) {\n\t\t\tawait this.txnBridge.rollbackTransaction();\n\t\t}\n\t}\n}\n\n","/**\n * SchemaManager - Manages table schemas in Optimystic trees\n *\n * Stores and retrieves table schema definitions from distributed Optimystic trees.\n * Schema is stored in a dedicated tree at `tree://schema/{tableName}`.\n */\n\nimport type { Tree } from '@optimystic/db-core';\nimport type { TableSchema, ColumnSchema } from '@quereus/quereus';\nimport type { ITransactor } from '@optimystic/db-core';\n\n// IndexSchema type from TableSchema.indexes\ntype IndexSchema = NonNullable<TableSchema['indexes']>[number];\n\n/**\n * Serializable schema storage format\n */\nexport interface StoredTableSchema {\n\tname: string;\n\tschemaName: string;\n\tcolumns: StoredColumnSchema[];\n\tprimaryKeyDefinition: StoredPrimaryKeyColumn[];\n\tindexes: StoredIndexSchema[];\n\tvtabModuleName: string;\n\tvtabArgs?: Record<string, any>;\n\tisTemporary?: boolean;\n\testimatedRows?: number;\n}\n\nexport interface StoredColumnSchema {\n\tname: string;\n\taffinity: string;\n\tnotNull: boolean;\n\tprimaryKey: boolean;\n\tpkOrder: number;\n\tdefaultValue?: any;\n\tcollation: string;\n\tgenerated: boolean;\n\tpkDirection?: 'asc' | 'desc';\n}\n\nexport interface StoredPrimaryKeyColumn {\n\tindex: number;\n\tdesc?: boolean;\n\tautoIncrement?: boolean;\n\tcollation?: string;\n}\n\nexport interface StoredIndexSchema {\n\tname: string;\n\tcolumns: StoredIndexColumn[];\n\tunique?: boolean;\n}\n\nexport interface StoredIndexColumn {\n\tindex: number;\n\tdesc?: boolean;\n\tcollation?: string;\n}\n\n/**\n * Manages schema storage and retrieval in Optimystic trees\n */\nexport class SchemaManager {\n\tprivate schemaCache = new Map<string, StoredTableSchema>();\n\n\tconstructor(\n\t\tprivate readonly getSchemaTree: (transactor?: ITransactor) => Promise<Tree<string, any>>\n\t) {}\n\n\t/**\n\t * Store a table schema\n\t */\n\tasync storeSchema(schema: TableSchema, transactor?: ITransactor): Promise<void> {\n\t\tconst stored = this.tableSchemaToStored(schema);\n\t\tthis.schemaCache.set(schema.name, stored);\n\n\t\tconst tree = await this.getSchemaTree(transactor);\n\t\tawait tree.replace([[schema.name, stored]]);\n\t}\n\n\t/**\n\t * Retrieve a table schema\n\t */\n\tasync getSchema(tableName: string, transactor?: ITransactor): Promise<StoredTableSchema | undefined> {\n\t\t// Check cache first\n\t\tconst cached = this.schemaCache.get(tableName);\n\t\tif (cached) {\n\t\t\treturn cached;\n\t\t}\n\n\t\t// Load from tree\n\t\tconst tree = await this.getSchemaTree(transactor);\n\t\tconst path = await tree.find(tableName);\n\t\tif (!tree.isValid(path)) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst entry = tree.at(path) as [string, StoredTableSchema];\n\t\tif (entry && entry.length >= 2) {\n\t\t\tconst stored = entry[1];\n\t\t\tthis.schemaCache.set(tableName, stored);\n\t\t\treturn stored;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Delete a table schema\n\t */\n\tasync deleteSchema(tableName: string, transactor?: ITransactor): Promise<void> {\n\t\tthis.schemaCache.delete(tableName);\n\n\t\tconst tree = await this.getSchemaTree(transactor);\n\t\tawait tree.replace([[tableName, undefined]]);\n\t}\n\n\t/**\n\t * List all table names\n\t */\n\tasync listTables(transactor?: ITransactor): Promise<string[]> {\n\t\tconst tree = await this.getSchemaTree(transactor);\n\t\tconst tables: string[] = [];\n\n\t\tfor await (const path of tree.range({ isAscending: true } as any)) {\n\t\t\tif (!tree.isValid(path)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst entry = tree.at(path) as [string, any];\n\t\t\tif (entry && entry.length >= 1) {\n\t\t\t\ttables.push(entry[0]);\n\t\t\t}\n\t\t}\n\n\t\treturn tables;\n\t}\n\n\t/**\n\t * Clear the schema cache\n\t */\n\tclearCache(): void {\n\t\tthis.schemaCache.clear();\n\t}\n\n\t/**\n\t * Convert TableSchema to storable format\n\t */\n\tprivate tableSchemaToStored(schema: TableSchema): StoredTableSchema {\n\t\treturn {\n\t\t\tname: schema.name,\n\t\t\tschemaName: schema.schemaName,\n\t\t\tcolumns: schema.columns.map(col => this.columnSchemaToStored(col)),\n\t\t\tprimaryKeyDefinition: schema.primaryKeyDefinition.map(pk => ({\n\t\t\t\tindex: pk.index,\n\t\t\t\tdesc: pk.desc,\n\t\t\t\tautoIncrement: pk.autoIncrement,\n\t\t\t\tcollation: pk.collation,\n\t\t\t})),\n\t\t\tindexes: (schema.indexes || []).map(idx => this.indexSchemaToStored(idx)),\n\t\t\tvtabModuleName: schema.vtabModuleName,\n\t\t\tvtabArgs: schema.vtabArgs as Record<string, any>,\n\t\t\tisTemporary: schema.isTemporary,\n\t\t\testimatedRows: schema.estimatedRows,\n\t\t};\n\t}\n\n\t/**\n\t * Convert ColumnSchema to storable format\n\t */\n\tprivate columnSchemaToStored(col: ColumnSchema): StoredColumnSchema {\n\t\treturn {\n\t\t\tname: col.name,\n\t\t\taffinity: col.logicalType.name, // Use logicalType.name for storage\n\t\t\tnotNull: col.notNull,\n\t\t\tprimaryKey: col.primaryKey,\n\t\t\tpkOrder: col.pkOrder,\n\t\t\tdefaultValue: col.defaultValue ? this.serializeExpression(col.defaultValue) : undefined,\n\t\t\tcollation: col.collation,\n\t\t\tgenerated: col.generated,\n\t\t\tpkDirection: col.pkDirection,\n\t\t};\n\t}\n\n\t/**\n\t * Convert IndexSchema to storable format\n\t */\n\tprivate indexSchemaToStored(idx: IndexSchema): StoredIndexSchema {\n\t\treturn {\n\t\t\tname: idx.name,\n\t\t\tcolumns: idx.columns.map((col: { index: number; desc?: boolean; collation?: string }) => ({\n\t\t\t\tindex: col.index,\n\t\t\t\tdesc: col.desc,\n\t\t\t\tcollation: col.collation,\n\t\t\t})),\n\t\t};\n\t}\n\n\t/**\n\t * Serialize an expression for storage\n\t * For now, we'll store a simplified representation\n\t */\n\tprivate serializeExpression(expr: any): any {\n\t\t// TODO: Implement proper expression serialization\n\t\t// For now, just store the expression as-is if it's a simple value\n\t\tif (typeof expr === 'object' && expr !== null) {\n\t\t\tif ('type' in expr && expr.type === 'literal') {\n\t\t\t\treturn { type: 'literal', value: expr.value };\n\t\t\t}\n\t\t\t// For complex expressions, we'll need to implement full serialization\n\t\t\treturn { type: 'complex', raw: JSON.stringify(expr) };\n\t\t}\n\t\treturn expr;\n\t}\n}\n\n","/**\n * RowCodec - Encodes and decodes rows with schema awareness\n *\n * Handles serialization/deserialization of multi-column rows to/from\n * the format stored in Optimystic trees.\n */\n\nimport type { Row, SqlValue } from '@quereus/quereus';\nimport { resolveCollation, compareSqlValues, type CollationFunction } from '@quereus/quereus';\nimport type { StoredTableSchema } from './schema-manager.js';\n\n/**\n * Encoding format for row data\n */\nexport type EncodingFormat = 'json' | 'msgpack';\n\n/**\n * Encoded row data stored in the tree\n */\nexport type EncodedRow = Uint8Array | string;\n\n/**\n * Primary key value (can be composite)\n */\nexport type PrimaryKeyValue = string;\n\n/**\n * Handles encoding/decoding of rows based on table schema\n */\nexport class RowCodec {\n\tconstructor(\n\t\tprivate readonly schema: StoredTableSchema,\n\t\tprivate readonly encoding: EncodingFormat = 'json'\n\t) {}\n\n\t/**\n\t * Encode a row for storage in the tree\n\t */\n\tencodeRow(row: Row): EncodedRow {\n\t\t// Convert Row (array) to object format for storage\n\t\tconst rowObj: Record<string, SqlValue> = {};\n\n\t\tfor (let i = 0; i < this.schema.columns.length; i++) {\n\t\t\tconst col = this.schema.columns[i];\n\t\t\tif (!col) continue;\n\t\t\tconst value = row[i];\n\t\t\trowObj[col.name] = this.normalizeValue(value ?? null);\n\t\t}\n\n\t\tif (this.encoding === 'msgpack') {\n\t\t\t// TODO: Add msgpack support when dependency is added\n\t\t\tthrow new Error('msgpack encoding not yet implemented');\n\t\t}\n\n\t\treturn JSON.stringify(rowObj);\n\t}\n\n\t/**\n\t * Decode a row from storage format\n\t */\n\tdecodeRow(encoded: EncodedRow): Row {\n\t\tlet rowObj: Record<string, SqlValue>;\n\n\t\tif (this.encoding === 'msgpack') {\n\t\t\t// TODO: Add msgpack support when dependency is added\n\t\t\tthrow new Error('msgpack decoding not yet implemented');\n\t\t} else {\n\t\t\trowObj = JSON.parse(encoded as string);\n\t\t}\n\n\t\t// Convert object back to Row (array) format\n\t\tconst row: Row = [];\n\t\tfor (let i = 0; i < this.schema.columns.length; i++) {\n\t\t\tconst col = this.schema.columns[i];\n\t\t\tif (!col) continue;\n\t\t\trow[i] = rowObj[col.name] ?? null;\n\t\t}\n\n\t\treturn row;\n\t}\n\n\t/**\n\t * Extract primary key value from a row\n\t */\n\textractPrimaryKey(row: Row): PrimaryKeyValue {\n\t\tconst pkParts: string[] = [];\n\n\t\tfor (const pkCol of this.schema.primaryKeyDefinition) {\n\t\t\tconst value = row[pkCol.index];\n\t\t\tpkParts.push(this.serializeKeyPart(value ?? null));\n\t\t}\n\n\t\t// For single-column keys, return the value directly\n\t\tif (pkParts.length === 1 && pkParts[0]) {\n\t\t\treturn pkParts[0];\n\t\t}\n\n\t\t// For composite keys, join with a separator\n\t\t// Use a separator that's unlikely to appear in data\n\t\treturn pkParts.join('\\x00');\n\t}\n\n\t/**\n\t * Create a primary key from individual column values\n\t */\n\tcreatePrimaryKey(values: SqlValue[]): PrimaryKeyValue {\n\t\tif (values.length !== this.schema.primaryKeyDefinition.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`Primary key requires ${this.schema.primaryKeyDefinition.length} values, got ${values.length}`\n\t\t\t);\n\t\t}\n\n\t\tconst pkParts = values.map(v => this.serializeKeyPart(v ?? null));\n\n\t\tif (pkParts.length === 1 && pkParts[0]) {\n\t\t\treturn pkParts[0];\n\t\t}\n\n\t\treturn pkParts.join('\\x00');\n\t}\n\n\t/**\n\t * Get the indices of primary key columns\n\t */\n\tgetPrimaryKeyIndices(): number[] {\n\t\treturn this.schema.primaryKeyDefinition.map(pk => pk.index);\n\t}\n\n\t/**\n\t * Get the number of columns in the schema\n\t */\n\tgetColumnCount(): number {\n\t\treturn this.schema.columns.length;\n\t}\n\n\t/**\n\t * Get column name by index\n\t */\n\tgetColumnName(index: number): string {\n\t\treturn this.schema.columns[index]?.name || '';\n\t}\n\n\t/**\n\t * Get column index by name\n\t */\n\tgetColumnIndex(name: string): number {\n\t\treturn this.schema.columns.findIndex(col => col.name.toLowerCase() === name.toLowerCase());\n\t}\n\n\t/**\n\t * Serialize a single key part to string\n\t */\n\tprivate serializeKeyPart(value: SqlValue): string {\n\t\tif (value === null || value === undefined) {\n\t\t\treturn '\\x01NULL\\x01';\n\t\t}\n\n\t\tif (typeof value === 'string') {\n\t\t\treturn value;\n\t\t}\n\n\t\tif (typeof value === 'number') {\n\t\t\t// Pad numbers for lexicographic sorting\n\t\t\t// This is a simplified approach; a production system would need more sophisticated encoding\n\t\t\treturn value.toString();\n\t\t}\n\n\t\tif (typeof value === 'bigint') {\n\t\t\treturn value.toString();\n\t\t}\n\n\t\tif (typeof value === 'boolean') {\n\t\t\treturn value ? '1' : '0';\n\t\t}\n\n\t\tif (value instanceof Uint8Array) {\n\t\t\t// Convert to base64 for string representation\n\t\t\treturn Buffer.from(value).toString('base64');\n\t\t}\n\n\t\t// Fallback\n\t\treturn String(value);\n\t}\n\n\t/**\n\t * Normalize a value for storage\n\t */\n\tprivate normalizeValue(value: SqlValue): SqlValue {\n\t\t// Convert bigint to number for JSON compatibility\n\t\tif (typeof value === 'bigint') {\n\t\t\treturn Number(value);\n\t\t}\n\n\t\t// Uint8Array needs special handling for JSON\n\t\tif (value instanceof Uint8Array && this.encoding === 'json') {\n\t\t\treturn Buffer.from(value).toString('base64');\n\t\t}\n\n\t\treturn value;\n\t}\n\n\t/**\n\t * Check if a column is part of the primary key\n\t */\n\tisColumnInPrimaryKey(columnIndex: number): boolean {\n\t\treturn this.schema.primaryKeyDefinition.some(pk => pk.index === columnIndex);\n\t}\n\n\t/**\n\t * Get the schema\n\t */\n\tgetSchema(): StoredTableSchema {\n\t\treturn this.schema;\n\t}\n\n\t/**\n\t * Create a comparison function for primary keys that respects collations\n\t * This is used by the Tree to maintain proper sort order\n\t */\n\tcreatePrimaryKeyComparator(): (a: string, b: string) => -1 | 0 | 1 {\n\t\tconst pkDef = this.schema.primaryKeyDefinition;\n\n\t\t// For empty primary key (singleton table), all keys are equal\n\t\tif (pkDef.length === 0) {\n\t\t\treturn () => 0;\n\t\t}\n\n\t\t// For single-column primary key\n\t\tif (pkDef.length === 1) {\n\t\t\tconst collationName = pkDef[0]?.collation || 'BINARY';\n\t\t\tconst collationFunc = resolveCollation(collationName);\n\t\t\tconst desc = pkDef[0]?.desc || false;\n\t\t\tconst multiplier = desc ? -1 : 1;\n\n\t\t\treturn (a: string, b: string): -1 | 0 | 1 => {\n\t\t\t\t// Deserialize the key parts\n\t\t\t\tconst valueA = this.deserializeKeyPart(a);\n\t\t\t\tconst valueB = this.deserializeKeyPart(b);\n\n\t\t\t\t// Compare using the appropriate collation\n\t\t\t\tconst result = this.compareValues(valueA, valueB, collationFunc);\n\t\t\t\treturn (result * multiplier) as -1 | 0 | 1;\n\t\t\t};\n\t\t}\n\n\t\t// For composite primary key\n\t\tconst collationFuncs = pkDef.map(def => resolveCollation(def.collation || 'BINARY'));\n\t\tconst descFlags = pkDef.map(def => def.desc || false);\n\n\t\treturn (a: string, b: string): -1 | 0 | 1 => {\n\t\t\t// Split composite keys\n\t\t\tconst partsA = a.split('\\x00');\n\t\t\tconst partsB = b.split('\\x00');\n\n\t\t\t// Compare each part in order\n\t\t\tfor (let i = 0; i < pkDef.length; i++) {\n\t\t\t\tconst valueA = this.deserializeKeyPart(partsA[i] || '');\n\t\t\t\tconst valueB = this.deserializeKeyPart(partsB[i] || '');\n\n\t\t\t\tconst result = this.compareValues(valueA, valueB, collationFuncs[i]!);\n\t\t\t\tif (result !== 0) {\n\t\t\t\t\tconst multiplier = descFlags[i] ? -1 : 1;\n\t\t\t\t\treturn (result * multiplier) as -1 | 0 | 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t};\n\t}\n\n\t/**\n\t * Deserialize a key part back to its original value\n\t */\n\tprivate deserializeKeyPart(serialized: string): SqlValue {\n\t\tif (serialized === '\\x01NULL\\x01') {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Try to parse as number\n\t\tconst num = Number(serialized);\n\t\tif (!isNaN(num) && serialized !== '') {\n\t\t\treturn num;\n\t\t}\n\n\t\t// Otherwise treat as string\n\t\treturn serialized;\n\t}\n\n\t/**\n\t * Compare two values using the specified collation\n\t */\n\tprivate compareValues(a: SqlValue, b: SqlValue, collationFunc: CollationFunction): number {\n\t\t// Handle nulls first\n\t\tif (a === null && b === null) return 0;\n\t\tif (a === null) return -1;\n\t\tif (b === null) return 1;\n\n\t\t// For strings, use the collation function\n\t\tif (typeof a === 'string' && typeof b === 'string') {\n\t\t\treturn collationFunc(a, b);\n\t\t}\n\n\t\t// For numbers, use numeric comparison\n\t\tif (typeof a === 'number' && typeof b === 'number') {\n\t\t\treturn a < b ? -1 : a > b ? 1 : 0;\n\t\t}\n\n\t\t// For mixed types, use SQL comparison rules\n\t\treturn compareSqlValues(a, b, 'BINARY');\n\t}\n}\n\n","/**\n * IndexManager - Manages secondary indexes for Optimystic tables\n *\n * Creates and maintains secondary indexes stored in separate Optimystic trees.\n * Each index is stored as Tree<IndexKey, PrimaryKey> where IndexKey is a composite\n * of indexed column values.\n */\n\nimport type { Tree } from '@optimystic/db-core';\nimport type { ITransactor } from '@optimystic/db-core';\nimport type { Row, SqlValue } from '@quereus/quereus';\nimport type { StoredTableSchema, StoredIndexSchema } from './schema-manager.js';\n\n/**\n * Index key format: composite of indexed column values joined with separator\n */\nexport type IndexKey = string;\n\n/**\n * Primary key format: composite of primary key column values joined with separator\n */\nexport type PrimaryKey = string;\n\n/**\n * Index entry: maps index key to primary key\n */\nexport type IndexEntry = [IndexKey, PrimaryKey];\n\n/**\n * Factory function to create/get index trees\n */\nexport type IndexTreeFactory = (\n\tindexName: string,\n\ttransactor?: ITransactor\n) => Promise<Tree<IndexKey, PrimaryKey>>;\n\n/**\n * Manages secondary indexes for a table\n */\nexport class IndexManager {\n\tprivate indexTrees = new Map<string, Tree<IndexKey, PrimaryKey>>();\n\n\tconstructor(\n\t\tprivate schema: StoredTableSchema,\n\t\tprivate indexTreeFactory: IndexTreeFactory\n\t) {}\n\n\t/**\n\t * Initialize all indexes for the table\n\t */\n\tasync initialize(transactor?: ITransactor): Promise<void> {\n\t\tfor (const index of this.schema.indexes) {\n\t\t\tconst tree = await this.indexTreeFactory(index.name, transactor);\n\t\t\tthis.indexTrees.set(index.name, tree);\n\t\t}\n\t}\n\n\t/**\n\t * Get an index tree by name\n\t */\n\tgetIndexTree(indexName: string): Tree<IndexKey, PrimaryKey> | undefined {\n\t\treturn this.indexTrees.get(indexName);\n\t}\n\n\t/**\n\t * Create index key from row values\n\t */\n\tcreateIndexKey(indexSchema: StoredIndexSchema, row: Row): IndexKey {\n\t\tconst keyParts: string[] = [];\n\n\t\tfor (const indexCol of indexSchema.columns) {\n\t\t\tconst value = row[indexCol.index];\n\t\t\tconst stringValue = this.serializeValue(value ?? null);\n\t\t\tkeyParts.push(stringValue);\n\t\t}\n\n\t\t// Join with null separator (same as primary key encoding)\n\t\treturn keyParts.join('\\x00');\n\t}\n\n\t/**\n\t * Insert index entries for a new row\n\t */\n\tasync insertIndexEntries(\n\t\trow: Row,\n\t\tprimaryKey: PrimaryKey,\n\t\ttransactor?: ITransactor\n\t): Promise<void> {\n\t\tconst updates: Array<[string, IndexEntry[]]> = [];\n\n\t\tfor (const index of this.schema.indexes) {\n\t\t\tconst indexKey = this.createIndexKey(index, row);\n\t\t\tconst tree = this.indexTrees.get(index.name);\n\t\t\tif (!tree) {\n\t\t\t\tthrow new Error(`Index tree not found: ${index.name}`);\n\t\t\t}\n\n\t\t\tupdates.push([index.name, [[indexKey, primaryKey]]]);\n\t\t}\n\n\t\t// Apply all index updates\n\t\tfor (const [indexName, entries] of updates) {\n\t\t\tconst tree = this.indexTrees.get(indexName);\n\t\t\tif (tree) {\n\t\t\t\tawait tree.replace(entries);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Delete index entries for a row\n\t */\n\tasync deleteIndexEntries(\n\t\trow: Row,\n\t\tprimaryKey: PrimaryKey,\n\t\ttransactor?: ITransactor\n\t): Promise<void> {\n\t\tconst updates: Array<[string, Array<[IndexKey, undefined]>]> = [];\n\n\t\tfor (const index of this.schema.indexes) {\n\t\t\tconst indexKey = this.createIndexKey(index, row);\n\t\t\tconst tree = this.indexTrees.get(index.name);\n\t\t\tif (!tree) {\n\t\t\t\tthrow new Error(`Index tree not found: ${index.name}`);\n\t\t\t}\n\n\t\t\tupdates.push([index.name, [[indexKey, undefined]]]);\n\t\t}\n\n\t\t// Apply all index deletions\n\t\tfor (const [indexName, entries] of updates) {\n\t\t\tconst tree = this.indexTrees.get(indexName);\n\t\t\tif (tree) {\n\t\t\t\tawait tree.replace(entries);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Update index entries when a row changes\n\t */\n\tasync updateIndexEntries(\n\t\toldRow: Row,\n\t\tnewRow: Row,\n\t\toldPrimaryKey: PrimaryKey,\n\t\tnewPrimaryKey: PrimaryKey,\n\t\ttransactor?: ITransactor\n\t): Promise<void> {\n\t\t// For each index, check if the indexed columns changed\n\t\tfor (const index of this.schema.indexes) {\n\t\t\tconst oldIndexKey = this.createIndexKey(index, oldRow);\n\t\t\tconst newIndexKey = this.createIndexKey(index, newRow);\n\n\t\t\tconst tree = this.indexTrees.get(index.name);\n\t\t\tif (!tree) {\n\t\t\t\tthrow new Error(`Index tree not found: ${index.name}`);\n\t\t\t}\n\n\t\t\tif (oldIndexKey !== newIndexKey || oldPrimaryKey !== newPrimaryKey) {\n\t\t\t\t// Index key or primary key changed - delete old, insert new\n\t\t\t\tawait tree.replace([\n\t\t\t\t\t[oldIndexKey, undefined],\n\t\t\t\t\t[newIndexKey, newPrimaryKey]\n\t\t\t\t]);\n\t\t\t}\n\t\t\t// If both keys are the same, no update needed\n\t\t}\n\t}\n\n\t/**\n\t * Find rows using an index\n\t */\n\tasync* findByIndex(\n\t\tindexName: string,\n\t\tindexKey: IndexKey\n\t): AsyncIterable<PrimaryKey> {\n\t\tconst tree = this.indexTrees.get(indexName);\n\t\tif (!tree) {\n\t\t\tthrow new Error(`Index tree not found: ${indexName}`);\n\t\t}\n\n\t\tconst path = await tree.find(indexKey);\n\t\tif (!tree.isValid(path)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst entry = tree.at(path) as unknown as [IndexKey, PrimaryKey];\n\t\tif (entry && entry.length >= 2) {\n\t\t\tyield entry[1];\n\t\t}\n\t}\n\n\t/**\n\t * Scan index range\n\t */\n\tasync* scanIndexRange(\n\t\tindexName: string,\n\t\tstartKey?: IndexKey,\n\t\tendKey?: IndexKey,\n\t\tascending = true\n\t): AsyncIterable<PrimaryKey> {\n\t\tconst tree = this.indexTrees.get(indexName);\n\t\tif (!tree) {\n\t\t\tthrow new Error(`Index tree not found: ${indexName}`);\n\t\t}\n\n\t\t// TODO: Implement proper range scanning with KeyRange\n\t\t// For now, do a full scan and filter\n\t\tconst iterator = tree.range({ isAscending: ascending } as any);\n\n\t\tfor await (const path of iterator) {\n\t\t\tif (!tree.isValid(path)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst entry = tree.at(path) as unknown as [IndexKey, PrimaryKey];\n\t\t\tif (entry && entry.length >= 2) {\n\t\t\t\tconst [key, primaryKey] = entry;\n\n\t\t\t\t// Apply range filters\n\t\t\t\tif (startKey !== undefined && key < startKey) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (endKey !== undefined && key > endKey) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tyield primaryKey;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get index schema by name\n\t */\n\tgetIndexSchema(indexName: string): StoredIndexSchema | undefined {\n\t\treturn this.schema.indexes.find(idx => idx.name === indexName);\n\t}\n\n\t/**\n\t * Serialize a value for use in index key\n\t */\n\tprivate serializeValue(value: SqlValue): string {\n\t\tif (value === null || value === undefined) {\n\t\t\treturn '\\x01'; // Special marker for NULL\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\treturn value;\n\t\t}\n\t\tif (typeof value === 'number') {\n\t\t\t// Pad numbers for lexicographic sorting\n\t\t\t// Use scientific notation with fixed precision\n\t\t\treturn value.toExponential(15);\n\t\t}\n\t\tif (typeof value === 'bigint') {\n\t\t\treturn value.toString();\n\t\t}\n\t\tif (value instanceof Uint8Array) {\n\t\t\t// Convert to base64 for string representation\n\t\t\treturn btoa(String.fromCharCode(...value));\n\t\t}\n\t\t// Fallback\n\t\treturn String(value);\n\t}\n}\n\n","/**\n * StatisticsCollector - Collects and maintains table statistics for query optimization\n *\n * Tracks row counts, distinct values, and provides cost estimates for query planning.\n */\n\nimport type { StoredTableSchema } from './schema-manager.js';\n\n/**\n * Statistics for a single column\n */\nexport interface ColumnStatistics {\n\t/** Approximate number of distinct values */\n\tdistinctCount: number;\n\t/** Approximate number of NULL values */\n\tnullCount: number;\n\t/** Sample of values for histogram (optional) */\n\tsampleValues?: unknown[];\n}\n\n/**\n * Statistics for a table\n */\nexport interface TableStatistics {\n\t/** Total number of rows (approximate) */\n\trowCount: number;\n\t/** Statistics per column */\n\tcolumnStats: Map<number, ColumnStatistics>;\n\t/** Last update timestamp */\n\tlastUpdated: number;\n}\n\n/**\n * Collects and maintains statistics for query optimization\n */\nexport class StatisticsCollector {\n\tprivate stats: TableStatistics;\n\n\tconstructor(private schema: StoredTableSchema) {\n\t\tthis.stats = {\n\t\t\trowCount: 0,\n\t\t\tcolumnStats: new Map(),\n\t\t\tlastUpdated: Date.now(),\n\t\t};\n\n\t\t// Initialize column stats\n\t\tfor (let i = 0; i < schema.columns.length; i++) {\n\t\t\tthis.stats.columnStats.set(i, {\n\t\t\t\tdistinctCount: 0,\n\t\t\t\tnullCount: 0,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Get current table statistics\n\t */\n\tgetStatistics(): TableStatistics {\n\t\treturn this.stats;\n\t}\n\n\t/**\n\t * Get estimated row count\n\t */\n\tgetRowCount(): number {\n\t\treturn this.stats.rowCount;\n\t}\n\n\t/**\n\t * Get estimated distinct count for a column\n\t */\n\tgetDistinctCount(columnIndex: number): number {\n\t\tconst colStats = this.stats.columnStats.get(columnIndex);\n\t\treturn colStats?.distinctCount || 0;\n\t}\n\n\t/**\n\t * Increment row count (called on INSERT)\n\t */\n\tincrementRowCount(): void {\n\t\tthis.stats.rowCount++;\n\t\tthis.stats.lastUpdated = Date.now();\n\t}\n\n\t/**\n\t * Decrement row count (called on DELETE)\n\t */\n\tdecrementRowCount(): void {\n\t\tthis.stats.rowCount = Math.max(0, this.stats.rowCount - 1);\n\t\tthis.stats.lastUpdated = Date.now();\n\t}\n\n\t/**\n\t * Estimate selectivity of an equality constraint\n\t * Returns a value between 0 and 1 representing the fraction of rows that match\n\t */\n\testimateEqualitySelectivity(columnIndex: number): number {\n\t\tconst distinctCount = this.getDistinctCount(columnIndex);\n\t\tif (distinctCount === 0) {\n\t\t\treturn 0.1; // Default estimate\n\t\t}\n\t\treturn 1.0 / distinctCount;\n\t}\n\n\t/**\n\t * Estimate selectivity of a range constraint\n\t * Returns a value between 0 and 1 representing the fraction of rows that match\n\t */\n\testimateRangeSelectivity(_columnIndex: number): number {\n\t\t// Simple heuristic: assume range matches 25% of rows\n\t\treturn 0.25;\n\t}\n\n\t/**\n\t * Estimate cost of a full table scan\n\t */\n\testimateTableScanCost(): number {\n\t\t// Cost is proportional to row count\n\t\t// Base cost of 1.0 per row\n\t\treturn Math.max(1000, this.stats.rowCount);\n\t}\n\n\t/**\n\t * Estimate cost of an index scan\n\t */\n\testimateIndexScanCost(selectivity: number): number {\n\t\t// Cost includes:\n\t\t// 1. Index lookup cost (logarithmic)\n\t\t// 2. Row fetch cost (proportional to selected rows)\n\t\tconst indexLookupCost = Math.log2(Math.max(1, this.stats.rowCount)) * 2;\n\t\tconst rowFetchCost = this.stats.rowCount * selectivity;\n\t\treturn indexLookupCost + rowFetchCost;\n\t}\n\n\t/**\n\t * Estimate number of rows returned by a constraint\n\t */\n\testimateRowsForConstraint(columnIndex: number, isEquality: boolean): number {\n\t\tif (isEquality) {\n\t\t\tconst selectivity = this.estimateEqualitySelectivity(columnIndex);\n\t\t\treturn Math.max(1, Math.floor(this.stats.rowCount * selectivity));\n\t\t} else {\n\t\t\tconst selectivity = this.estimateRangeSelectivity(columnIndex);\n\t\t\treturn Math.max(1, Math.floor(this.stats.rowCount * selectivity));\n\t\t}\n\t}\n\n\t/**\n\t * Update statistics based on actual data (called periodically)\n\t * This is a simplified version - a real implementation would sample the data\n\t */\n\tasync updateStatistics(sampleSize = 1000): Promise<void> {\n\t\t// TODO: Implement actual statistics collection by sampling the table\n\t\t// For now, we just update the timestamp\n\t\tthis.stats.lastUpdated = Date.now();\n\t}\n\n\t/**\n\t * Reset statistics\n\t */\n\treset(): void {\n\t\tthis.stats.rowCount = 0;\n\t\tthis.stats.columnStats.clear();\n\t\tfor (let i = 0; i < this.schema.columns.length; i++) {\n\t\t\tthis.stats.columnStats.set(i, {\n\t\t\t\tdistinctCount: 0,\n\t\t\t\tnullCount: 0,\n\t\t\t});\n\t\t}\n\t\tthis.stats.lastUpdated = Date.now();\n\t}\n}\n\n","/**\n * Optimystic Virtual Table Module for Quereus\n *\n * This module implements the VirtualTableModule interface to create\n * virtual tables backed by Optimystic distributed tree collections.\n */\n\nimport { CollectionFactory } from './optimystic-adapter/collection-factory.js';\nimport { TransactionBridge } from './optimystic-adapter/txn-bridge.js';\nimport { OptimysticVirtualTableConnection } from './optimystic-adapter/vtab-connection.js';\nimport type { ParsedOptimysticOptions } from './types.js';\nimport { VirtualTable } from '@quereus/quereus';\nimport type { VirtualTableModule, BaseModuleConfig, Database, TableSchema, Row, FilterInfo, BestAccessPlanRequest, BestAccessPlanResult, OrderingSpec, VirtualTableConnection, TableIndexSchema as IndexSchema, RowOp } from '@quereus/quereus';\nimport { ConflictResolution } from '@quereus/quereus';\n\n/**\n * Arguments passed to VirtualTable.update() method.\n * Mirrors the interface from @quereus/quereus vtab/table.ts\n */\ninterface UpdateArgs {\n\toperation: RowOp;\n\tvalues: Row | undefined;\n\toldKeyValues?: Row;\n\tonConflict?: ConflictResolution;\n\tmutationStatement?: string;\n}\nimport { Tree } from '@optimystic/db-core';\nimport { KeyRange } from '@optimystic/db-core';\nimport { SchemaManager } from './schema/schema-manager.js';\nimport { RowCodec, type EncodedRow } from './schema/row-codec.js';\nimport { SqlDataType } from '@quereus/quereus';\nimport { INTEGER_TYPE, REAL_TYPE, TEXT_TYPE, BLOB_TYPE, NUMERIC_TYPE, NULL_TYPE, BOOLEAN_TYPE, type LogicalType } from '@quereus/quereus';\nimport { IndexManager } from './schema/index-manager.js';\nimport { StatisticsCollector } from './schema/statistics-collector.js';\n\n\n\n/**\n * Configuration interface for Optimystic module\n */\nexport interface OptimysticModuleConfig extends BaseModuleConfig {\n collectionUri: string;\n transactor?: string;\n keyNetwork?: string;\n port?: number;\n networkName?: string;\n cache?: boolean;\n encoding?: 'json' | 'msgpack';\n}\n\nlet instanceCounter = 0;\n\n/**\n * Helper function to convert SqlDataType affinity to LogicalType\n */\nfunction affinityToLogicalType(affinity: SqlDataType): LogicalType {\n\tswitch (affinity) {\n\t\tcase SqlDataType.NULL:\n\t\t\treturn NULL_TYPE;\n\t\tcase SqlDataType.INTEGER:\n\t\t\treturn INTEGER_TYPE;\n\t\tcase SqlDataType.REAL:\n\t\t\treturn REAL_TYPE;\n\t\tcase SqlDataType.TEXT:\n\t\t\treturn TEXT_TYPE;\n\t\tcase SqlDataType.BLOB:\n\t\t\treturn BLOB_TYPE;\n\t\tcase SqlDataType.NUMERIC:\n\t\t\treturn NUMERIC_TYPE;\n\t\tcase SqlDataType.BOOLEAN:\n\t\t\treturn BOOLEAN_TYPE;\n\t\tdefault:\n\t\t\treturn BLOB_TYPE; // Default fallback\n\t}\n}\n\n/**\n * Production-grade virtual table for Optimystic tree collections\n */\nexport class OptimysticVirtualTable extends VirtualTable {\n private instanceId = ++instanceCounter;\n private collection?: Tree<string, any>;\n private isInitialized = false;\n private initializationPromise?: Promise<void>;\n private txnBridge: TransactionBridge;\n private collectionFactory: CollectionFactory;\n private options: ParsedOptimysticOptions;\n private schemaManager: SchemaManager;\n private rowCodec?: RowCodec;\n private indexManager?: IndexManager;\n private statisticsCollector?: StatisticsCollector;\n private connection?: OptimysticVirtualTableConnection;\n public tableSchema: TableSchema; // Changed from private to public to match base class\n\n constructor(\n db: Database,\n module: VirtualTableModule<any, any>,\n schemaName: string,\n tableName: string,\n tableSchema: TableSchema,\n options: ParsedOptimysticOptions,\n collectionFactory: CollectionFactory,\n txnBridge: TransactionBridge,\n schemaManager: SchemaManager\n ) {\n super(db, module, schemaName, tableName);\n this.tableSchema = tableSchema;\n this.options = options;\n this.collectionFactory = collectionFactory;\n this.txnBridge = txnBridge;\n this.schemaManager = schemaManager;\n\n // Enable statement capture for replication/transaction logging\n this.wantStatements = true;\n }\n\n /**\n * Initialize the table and its collection\n */\n async initialize(): Promise<void> {\n if (this.isInitialized) {\n return;\n }\n\n // If initialization is already in progress, wait for it\n if (this.initializationPromise) {\n return this.initializationPromise;\n }\n\n // Start initialization\n this.initializationPromise = this.doInitialize();\n return this.initializationPromise;\n }\n\n /**\n * Internal initialization logic\n */\n private async doInitialize(): Promise<void> {\n try {\n const txnState = this.txnBridge.getCurrentTransaction();\n this.collection = await this.collectionFactory.createOrGetCollection(\n this.options,\n txnState || undefined\n );\n\n // If this is a new table (xCreate), store the schema\n // If connecting to existing table (xConnect), load the schema\n let storedSchema = await this.schemaManager.getSchema(this.tableName, txnState?.transactor);\n\n if (!storedSchema) {\n // New table - store the schema\n if (this.tableSchema.columns.length === 0) {\n throw new Error('Cannot create table without column definitions');\n }\n await this.schemaManager.storeSchema(this.tableSchema, txnState?.transactor);\n storedSchema = await this.schemaManager.getSchema(this.tableName, txnState?.transactor);\n if (!storedSchema) {\n throw new Error('Failed to store and retrieve schema');\n }\n } else {\n // Existing table - update our tableSchema with the loaded schema\n // This is important for connect() which creates a minimal schema\n this.tableSchema.columns = storedSchema.columns.map((col, index) => ({\n name: col.name,\n affinity: col.affinity as any,\n logicalType: affinityToLogicalType(col.affinity as any),\n notNull: col.notNull,\n primaryKey: col.primaryKey,\n pkOrder: col.pkOrder,\n defaultValue: col.defaultValue,\n collation: col.collation,\n generated: col.generated,\n pkDirection: col.pkDirection,\n index,\n }));\n this.tableSchema.columnIndexMap = new Map(\n storedSchema.columns.map((col, index) => [col.name.toLowerCase(), index])\n );\n this.tableSchema.primaryKeyDefinition = storedSchema.primaryKeyDefinition.map(pk => ({\n index: pk.index,\n desc: pk.desc,\n autoIncrement: pk.autoIncrement,\n collation: pk.collation,\n }));\n }\n\n this.rowCodec = new RowCodec(storedSchema, this.options.encoding);\n\n // Create and initialize index manager\n this.indexManager = new IndexManager(storedSchema, async (indexName, transactor) => {\n const indexOptions: ParsedOptimysticOptions = {\n ...this.options,\n collectionUri: `${this.options.collectionUri}/index/${indexName}`,\n };\n const tree = await this.collectionFactory.createOrGetCollection(\n indexOptions,\n transactor ? { transactor, isActive: true, collections: new Map(), transactionId: '' } : undefined\n );\n // Index trees store string->string mappings (IndexKey->PrimaryKey)\n return tree as unknown as Tree<string, string>;\n });\n\n await this.indexManager.initialize(txnState?.transactor);\n\n // Create statistics collector\n this.statisticsCollector = new StatisticsCollector(storedSchema);\n\n this.isInitialized = true;\n } catch (error) {\n const message = `Failed to initialize Optimystic table: ${error instanceof Error ? error.message : String(error)}`;\n this.setErrorMessage(message);\n throw new Error(message);\n }\n }\n\n /**\n * Disconnects from this virtual table connection instance\n * Note: We don't reset isInitialized or collection here because the table\n * should remain initialized across multiple statements/connections\n */\n async disconnect(): Promise<void> {\n // Don't reset state - the table should remain initialized\n }\n\n /**\n * Ensures a connection is established and registered with the database\n * This is called automatically on first table access, but can also be called\n * explicitly to register the connection early (e.g., for transaction support)\n */\n async ensureConnectionRegistered(): Promise<OptimysticVirtualTableConnection> {\n if (!this.connection) {\n // Check if there's already an active connection for this table in the database\n // Using type assertion to access internal methods\n const db = this.db as any;\n const existingConnections = db.getConnectionsForTable(this.tableName);\n if (existingConnections.length > 0 && existingConnections[0] instanceof OptimysticVirtualTableConnection) {\n this.connection = existingConnections[0] as OptimysticVirtualTableConnection;\n } else {\n // Create a new connection and register it with the database\n this.connection = new OptimysticVirtualTableConnection(this.tableName, this.txnBridge, this.options);\n await db.registerConnection(this.connection);\n }\n }\n return this.connection;\n }\n\n /**\n * Creates a new VirtualTableConnection for transaction support\n */\n createConnection(): VirtualTableConnection {\n return new OptimysticVirtualTableConnection(this.tableName, this.txnBridge, this.options);\n }\n\n /**\n * Gets the current connection if this table maintains one internally\n */\n getConnection(): VirtualTableConnection | undefined {\n return this.connection;\n }\n\n /**\n * Opens a direct data stream for this virtual table based on filter criteria\n */\n async* query(filterInfo: FilterInfo): AsyncIterable<Row> {\n // Ensure connection is registered\n await this.ensureConnectionRegistered();\n\n // Wait for initialization if needed\n if (!this.isInitialized) {\n await this.initialize();\n }\n\n if (!this.collection || !this.rowCodec || !this.indexManager) {\n throw new Error('Table not initialized');\n }\n\n try {\n // Parse idxStr to determine access strategy\n // Quereus uses idxStr like 'idx=_primary_(0);plan=2' for equality seeks\n const planType = this.parsePlanType(filterInfo.idxStr);\n\n if (planType === 2 && filterInfo.args.length > 0) {\n // Primary key equality seek (plan=2)\n yield* this.executePointLookup(String(filterInfo.args[0]));\n } else if (planType === 3) {\n // Range query on primary key (plan=3)\n yield* this.executeRangeQuery(filterInfo);\n } else if (filterInfo.idxNum === 1) {\n // Legacy: Point lookup on primary key\n yield* this.executePointLookup(filterInfo.args[0] ? String(filterInfo.args[0]) : '');\n } else if (filterInfo.idxNum === 2) {\n // Legacy: Range query on primary key\n yield* this.executeRangeQuery(filterInfo);\n } else if (filterInfo.idxNum >= 10) {\n // Index-based scan\n const indexName = filterInfo.idxStr;\n if (!indexName || typeof indexName !== 'string') {\n throw new Error('Index name not provided for index scan');\n }\n yield* this.executeIndexScan(indexName, filterInfo.args);\n } else {\n // Full table scan\n yield* this.executeTableScan();\n }\n } catch (error) {\n const message = `Query failed: ${error instanceof Error ? error.message : String(error)}`;\n this.setErrorMessage(message);\n throw new Error(message);\n }\n }\n\n /**\n * Parse the plan type from idxStr\n * Quereus uses format like 'idx=_primary_(0);plan=2'\n */\n private parsePlanType(idxStr: string | null): number | undefined {\n if (!idxStr) return undefined;\n const match = idxStr.match(/plan=(\\d+)/);\n return match?.[1] ? parseInt(match[1], 10) : undefined;\n }\n\n /**\n * Execute a point lookup query\n */\n private async* executePointLookup(key: string): AsyncIterable<Row> {\n if (!this.collection || !this.rowCodec) return;\n\n // Update from network to get latest data\n await this.collection.update();\n\n const path = await this.collection.find(key);\n if (!this.collection.isValid(path)) {\n return;\n }\n\n const entry = this.collection.at(path) as [string, EncodedRow] | undefined;\n if (entry && entry.length >= 2) {\n const encodedRow = entry[1];\n const row = this.rowCodec.decodeRow(encodedRow);\n yield row;\n }\n }\n\n /**\n * Execute a range query\n */\n private async* executeRangeQuery(_filterInfo: FilterInfo): AsyncIterable<Row> {\n if (!this.collection) return;\n\n // For now, fall back to full scan\n // TODO: Implement proper range queries based on filter args\n yield* this.executeTableScan();\n }\n\n /**\n * Execute an index-based scan\n */\n private async* executeIndexScan(indexName: string, args: readonly unknown[]): AsyncIterable<Row> {\n if (!this.collection || !this.rowCodec || !this.indexManager) return;\n\n const indexSchema = this.indexManager.getIndexSchema(indexName);\n if (!indexSchema) {\n throw new Error(`Index not found: ${indexName}`);\n }\n\n // Build index key from constraint values\n // args contains the values for the matched constraints in order\n const indexKeyParts: string[] = [];\n for (let i = 0; i < args.length && i < indexSchema.columns.length; i++) {\n const value = args[i];\n indexKeyParts.push(this.serializeValueForIndex(value));\n }\n\n const indexKey = indexKeyParts.join('\\x00');\n\n // Look up primary keys using the index\n for await (const primaryKey of this.indexManager.findByIndex(indexName, indexKey)) {\n // Fetch the row from the main table using the primary key\n const path = await this.collection.find(primaryKey);\n if (!this.collection.isValid(path)) {\n continue;\n }\n\n const entry = this.collection.at(path) as [string, any];\n if (entry && entry.length >= 2) {\n const encodedRow = entry[1];\n const row = this.rowCodec.decodeRow(encodedRow);\n yield row;\n }\n }\n }\n\n /**\n * Serialize a value for use in index key (helper for executeIndexScan)\n */\n private serializeValueForIndex(value: unknown): string {\n if (value === null || value === undefined) {\n return '\\x01'; // Special marker for NULL\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number') {\n return value.toExponential(15);\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n if (value instanceof Uint8Array) {\n return btoa(String.fromCharCode(...value));\n }\n return String(value);\n }\n\n /**\n * Execute a full table scan with retry on path invalidation\n * In a distributed system, incoming replicated changes can mutate the tree during iteration.\n * This method handles path invalidation by restarting from the last known key.\n */\n private async* executeTableScan(): AsyncIterable<Row> {\n if (!this.collection || !this.rowCodec) return;\n\n // Update from network to get latest data\n await this.collection.update();\n\n const maxRetries = 5;\n let retryCount = 0;\n let lastKey: string | undefined;\n const yieldedKeys = new Set<string>();\n\n while (retryCount < maxRetries) {\n try {\n // Create range starting from lastKey (exclusive) if we're retrying\n const range = lastKey\n ? new KeyRange<string>({ key: lastKey, inclusive: false }, undefined, true)\n : new KeyRange<string>(undefined, undefined, true);\n\n const iterator = this.collection.range(range);\n\n for await (const path of iterator) {\n if (!this.collection.isValid(path)) {\n continue;\n }\n\n const entry = this.collection.at(path);\n if (entry && Array.isArray(entry) && entry.length >= 2) {\n const key = entry[0] as string;\n // Skip if we've already yielded this key (shouldn't happen but safety check)\n if (yieldedKeys.has(key)) {\n lastKey = key;\n continue;\n }\n\n const encodedRow = entry[1];\n const row = this.rowCodec.decodeRow(encodedRow);\n yieldedKeys.add(key);\n lastKey = key;\n yield row;\n }\n }\n // Successfully completed iteration\n return;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (errorMessage.includes('Path is invalid due to mutation')) {\n // Tree was mutated during iteration, retry from last known position\n retryCount++;\n if (retryCount >= maxRetries) {\n throw new Error(`Table scan failed after ${maxRetries} retries due to concurrent mutations`);\n }\n // Small delay before retry to let mutations settle\n await new Promise(resolve => setTimeout(resolve, 50));\n continue;\n }\n // Re-throw non-mutation errors\n throw error;\n }\n }\n }\n\n /**\n * Performs an INSERT, UPDATE, or DELETE operation\n */\n async update(args: UpdateArgs): Promise<Row | undefined> {\n const { operation, values, oldKeyValues, mutationStatement } = args;\n\n // Ensure connection is registered\n await this.ensureConnectionRegistered();\n\n // Wait for initialization if needed\n if (!this.isInitialized) {\n await this.initialize();\n }\n\n if (!this.collection || !this.rowCodec || !this.indexManager) {\n throw new Error('Table not initialized');\n }\n\n // Capture the mutation statement if provided (for transaction replication)\n if (mutationStatement) {\n this.txnBridge.addStatement(mutationStatement);\n }\n\n const txnState = this.txnBridge.getCurrentTransaction();\n\n try {\n switch (operation) {\n case 'insert':\n if (!values) {\n throw new Error('INSERT requires values');\n }\n {\n const insertKey = this.rowCodec.extractPrimaryKey(values);\n const encodedRow = this.rowCodec.encodeRow(values);\n\n // Insert into main table\n // Entry format: [primaryKey, encodedRow]\n await this.collection.replace([[insertKey, [insertKey, encodedRow]]]);\n\n // Insert into all indexes\n await this.indexManager.insertIndexEntries(values, insertKey, txnState?.transactor);\n\n // Update statistics\n this.statisticsCollector?.incrementRowCount();\n\n return values;\n }\n\n case 'update':\n if (!values) {\n throw new Error('UPDATE requires values');\n }\n if (!oldKeyValues) {\n throw new Error('UPDATE requires old key values');\n }\n {\n const oldKey = this.rowCodec.extractPrimaryKey(oldKeyValues);\n const newKey = this.rowCodec.extractPrimaryKey(values);\n const encodedRow = this.rowCodec.encodeRow(values);\n\n // Update main table\n if (oldKey !== newKey) {\n // Key changed - delete old, insert new\n await this.collection.replace([\n [oldKey, undefined],\n [newKey, [newKey, encodedRow]]\n ]);\n } else {\n // Simple update\n await this.collection.replace([[newKey, [newKey, encodedRow]]]);\n }\n\n // Update all indexes\n await this.indexManager.updateIndexEntries(\n oldKeyValues,\n values,\n oldKey,\n newKey,\n txnState?.transactor\n );\n\n return values;\n }\n\n case 'delete':\n if (!oldKeyValues) {\n throw new Error('DELETE requires old key values');\n }\n {\n const deleteKey = this.rowCodec.extractPrimaryKey(oldKeyValues);\n\n // Delete from main table\n await this.collection.replace([[deleteKey, undefined]]);\n\n // Delete from all indexes\n await this.indexManager.deleteIndexEntries(oldKeyValues, deleteKey, txnState?.transactor);\n\n // Update statistics\n this.statisticsCollector?.decrementRowCount();\n\n return undefined;\n }\n\n default:\n throw new Error(`Unsupported operation: ${operation}`);\n }\n } catch (error) {\n const message = `${operation} failed: ${error instanceof Error ? error.message : String(error)}`;\n this.setErrorMessage(message);\n throw new Error(message);\n }\n }\n\n /**\n * Add an index to the table schema\n */\n async addIndex(indexSchema: IndexSchema): Promise<void> {\n // Wait for initialization if needed\n if (!this.isInitialized) {\n await this.initialize();\n }\n\n if (!this.schemaManager || !this.indexManager) {\n throw new Error('Table not initialized');\n }\n\n // Update the stored schema with the new index\n const storedSchema = await this.schemaManager.getSchema(this.tableName);\n if (!storedSchema) {\n throw new Error('Schema not found');\n }\n\n // Add the index to the stored schema\n const updatedSchema = {\n ...storedSchema,\n indexes: [...storedSchema.indexes, {\n name: indexSchema.name,\n columns: indexSchema.columns.map((col: { index: number; desc?: boolean; collation?: string }) => ({\n index: col.index,\n desc: col.desc,\n collation: col.collation,\n })),\n }],\n };\n\n // Save the updated schema\n const txnState = this.txnBridge.getCurrentTransaction();\n await this.schemaManager.storeSchema({\n ...this.tableSchema,\n indexes: updatedSchema.indexes.map(idx => ({\n name: idx.name,\n columns: idx.columns,\n })),\n }, txnState?.transactor);\n\n // Initialize the new index tree\n const indexTreeFactory = async (indexName: string, transactor?: any) => {\n const indexOptions: ParsedOptimysticOptions = {\n ...this.options,\n collectionUri: `${this.options.collectionUri}/index/${indexName}`,\n };\n const tree = await this.collectionFactory.createOrGetCollection(\n indexOptions,\n transactor ? { transactor, isActive: true, collections: new Map(), transactionId: '' } : undefined\n );\n return tree as unknown as Tree<string, string>;\n };\n\n const indexTree = await indexTreeFactory(indexSchema.name, txnState?.transactor);\n\n // Add the index to the index manager\n if (this.indexManager) {\n (this.indexManager as any).indexTrees.set(indexSchema.name, indexTree);\n (this.indexManager as any).schema = updatedSchema;\n }\n\n // Populate the index with existing data\n if (this.collection && this.rowCodec) {\n const firstPath = await this.collection.first();\n for await (const path of this.collection.ascending(firstPath)) {\n const encodedRow = this.collection.at(path);\n if (encodedRow) {\n const row = this.rowCodec.decodeRow(encodedRow);\n const primaryKey = this.rowCodec.extractPrimaryKey(row);\n await this.indexManager.insertIndexEntries(row, primaryKey, txnState?.transactor);\n }\n }\n }\n }\n\n /**\n * Begin a transaction on this virtual table\n */\n async begin(): Promise<void> {\n try {\n await this.ensureConnectionRegistered();\n await this.txnBridge.beginTransaction(this.options);\n } catch (error) {\n const message = `Begin transaction failed: ${error instanceof Error ? error.message : String(error)}`;\n this.setErrorMessage(message);\n throw new Error(message);\n }\n }\n\n /**\n * Commit the virtual table transaction\n */\n async commit(): Promise<void> {\n try {\n await this.txnBridge.commitTransaction();\n } catch (error) {\n const message = `Commit transaction failed: ${error instanceof Error ? error.message : String(error)}`;\n this.setErrorMessage(message);\n throw new Error(message);\n }\n }\n\n /**\n * Rollback the virtual table transaction\n */\n async rollback(): Promise<void> {\n try {\n await this.txnBridge.rollbackTransaction();\n } catch (error) {\n const message = `Rollback transaction failed: ${error instanceof Error ? error.message : String(error)}`;\n this.setErrorMessage(message);\n throw new Error(message);\n }\n }\n}\n\n/**\n * Optimystic Virtual Table Module\n */\nexport class OptimysticModule implements VirtualTableModule<OptimysticVirtualTable, OptimysticModuleConfig> {\n private schemaManager: SchemaManager;\n private tables = new Map<string, OptimysticVirtualTable>();\n\n constructor(\n private collectionFactory: CollectionFactory,\n private txnBridge: TransactionBridge\n ) {\n // Schema manager will be created per-table with appropriate transactor settings\n this.schemaManager = new SchemaManager(async (_transactor) => {\n throw new Error('Schema manager not initialized - this should not be called');\n });\n }\n\n /**\n * Create a schema manager for a specific table's transactor configuration\n */\n private createSchemaManager(tableOptions: ParsedOptimysticOptions): SchemaManager {\n return new SchemaManager(async (transactor) => {\n const schemaOptions: ParsedOptimysticOptions = {\n collectionUri: 'tree://optimystic/schema',\n transactor: tableOptions.transactor,\n keyNetwork: tableOptions.keyNetwork,\n libp2p: tableOptions.libp2p,\n libp2pOptions: tableOptions.libp2pOptions,\n cache: true,\n encoding: 'json',\n };\n return await this.collectionFactory.createOrGetCollection(\n schemaOptions,\n transactor ? { transactor, isActive: true, collections: new Map(), transactionId: '' } : undefined\n );\n });\n }\n\n /**\n * Parse table schema options into configuration\n */\n private parseTableSchema(tableSchema: TableSchema): ParsedOptimysticOptions {\n const args = tableSchema.vtabArgs || {};\n\n // Extract collection URI from first positional argument or use default\n const collectionUri = (args['0'] as string) || `tree://default/${tableSchema.name}`;\n\n // Extract named arguments\n const transactor = (args['transactor'] as string) || 'network';\n const keyNetwork = (args['keyNetwork'] as string) || 'libp2p';\n const port = typeof args['port'] === 'number' ? args['port'] : 0;\n const networkName = (args['networkName'] as string) || 'optimystic';\n const cache = args['cache'] !== false;\n const encoding = (args['encoding'] as 'json' | 'msgpack') || 'json';\n\n const options: ParsedOptimysticOptions = {\n collectionUri,\n transactor,\n keyNetwork,\n libp2pOptions: {\n port,\n networkName,\n bootstrapNodes: [],\n },\n cache,\n encoding,\n };\n\n return options;\n }\n\n /**\n * Creates the persistent definition of a virtual table\n */\n async create(\n db: Database,\n tableSchema: TableSchema\n ): Promise<OptimysticVirtualTable> {\n const tableKey = `${tableSchema.schemaName}.${tableSchema.name}`.toLowerCase();\n\n // Check if table already exists\n if (this.tables.has(tableKey)) {\n throw new Error(`Optimystic table '${tableSchema.name}' already exists in schema '${tableSchema.schemaName}'.`);\n }\n\n const options = this.parseTableSchema(tableSchema);\n const schemaManager = this.createSchemaManager(options);\n const table = new OptimysticVirtualTable(\n db,\n this,\n tableSchema.schemaName || 'main',\n tableSchema.name,\n tableSchema,\n options,\n this.collectionFactory,\n this.txnBridge,\n schemaManager\n );\n\n // Cache the table\n this.tables.set(tableKey, table);\n\n // Initialize table and register connection before returning\n // This ensures the table is fully ready for queries and transactions\n await table.initialize();\n await table.ensureConnectionRegistered();\n\n return table;\n }\n\n /**\n * Connects to an existing virtual table definition\n */\n async connect(\n db: Database,\n _pAux: unknown,\n _moduleName: string,\n schemaName: string,\n tableName: string,\n _options: OptimysticModuleConfig\n ): Promise<OptimysticVirtualTable> {\n const tableKey = `${schemaName}.${tableName}`.toLowerCase();\n const existingTable = this.tables.get(tableKey);\n\n if (!existingTable) {\n throw new Error(`Optimystic table definition for '${tableName}' not found. Cannot connect.`);\n }\n\n // Ensure the table is initialized before returning\n // (should already be initialized from create(), but this handles edge cases)\n await existingTable.initialize();\n\n return existingTable;\n }\n\n /**\n * Creates an index on an Optimystic virtual table\n */\n async createIndex(\n _db: Database,\n schemaName: string,\n tableName: string,\n indexSchema: IndexSchema\n ): Promise<void> {\n const tableKey = `${schemaName}.${tableName}`.toLowerCase();\n const table = this.tables.get(tableKey);\n\n if (!table) {\n throw new Error(`Optimystic table '${tableName}' not found in schema '${schemaName}'. Cannot create index.`);\n }\n\n // Update the stored schema with the new index\n await table.addIndex(indexSchema);\n }\n\n /**\n * Modern access planning interface using BestAccessPlanRequest/Result\n */\n getBestAccessPlan(\n _db: Database,\n tableInfo: TableSchema,\n request: BestAccessPlanRequest\n ): BestAccessPlanResult {\n // Get statistics for cost estimation - note: statisticsCollector is per-table, not per-module\n // For now, use default estimates\n const tableRowCount = tableInfo.estimatedRows || 1000000;\n const tableScanCost = Math.max(1000, tableRowCount);\n\n // Track best plan found\n let bestCost = tableScanCost;\n let bestRows = tableRowCount;\n let bestHandledFilters: boolean[] = request.filters.map(() => false);\n let bestOrdering: OrderingSpec[] | undefined = undefined;\n let bestIsSet = false;\n let bestExplains = `Full table scan (${tableRowCount} rows)`;\n\n // Check primary key constraints first\n const pkColumns = tableInfo.primaryKeyDefinition.map(pk => pk.index);\n for (let i = 0; i < request.filters.length; i++) {\n const filter = request.filters[i];\n if (!filter || !filter.usable) continue;\n\n // Check if this is a primary key column\n const isPkColumn = pkColumns.includes(filter.columnIndex);\n\n if (isPkColumn && filter.op === '=') {\n // Primary key equality - best case: O(log n)\n const pkCost = Math.log2(Math.max(2, tableRowCount)) * 2;\n bestCost = pkCost;\n bestRows = 1;\n bestHandledFilters = request.filters.map((_, idx) => idx === i);\n bestIsSet = true; // PK lookup guarantees unique row\n bestExplains = `Primary key equality seek (cost: ${pkCost.toFixed(2)})`;\n\n // Point lookup always satisfies any ORDER BY (single row)\n if (request.requiredOrdering && request.requiredOrdering.length > 0) {\n bestOrdering = [...request.requiredOrdering];\n }\n break; // Can't get better than this\n } else if (isPkColumn && ['>', '>=', '<', '<='].includes(filter.op)) {\n // Primary key range scan: O(log n + k)\n const selectivity = 0.25; // Heuristic for range queries\n const rangeCost = Math.log2(Math.max(2, tableRowCount)) * 2 + tableRowCount * selectivity;\n const rangeRows = Math.floor(tableRowCount * selectivity);\n\n if (rangeCost < bestCost) {\n bestCost = rangeCost;\n bestRows = rangeRows;\n bestHandledFilters = request.filters.map((_, idx) => idx === i);\n bestIsSet = false;\n bestExplains = `Primary key range scan (selectivity: ${selectivity.toFixed(2)}, cost: ${rangeCost.toFixed(2)})`;\n\n // Check if ORDER BY matches primary key order\n if (request.requiredOrdering && this.orderingMatchesPrimaryKey(request.requiredOrdering, tableInfo)) {\n bestOrdering = [...request.requiredOrdering];\n }\n }\n }\n }\n\n // Check secondary indexes if we haven't found a PK equality match\n if (bestCost > 10 && tableInfo.indexes && tableInfo.indexes.length > 0) {\n for (const index of tableInfo.indexes) {\n // Try to match constraints to this index\n const indexColumns = index.columns.map(col => col.index);\n let selectivity = 1.0;\n let matchedFilterIndices: number[] = [];\n\n // Check if we have equality constraints on the index columns\n for (let colIdx = 0; colIdx < indexColumns.length; colIdx++) {\n const indexCol = indexColumns[colIdx];\n let foundEq = false;\n\n for (let i = 0; i < request.filters.length; i++) {\n const filter = request.filters[i];\n if (!filter || !filter.usable) continue;\n\n if (filter.columnIndex === indexCol && filter.op === '=') {\n matchedFilterIndices.push(i);\n foundEq = true;\n // Each equality constraint reduces selectivity\n const colSelectivity = 0.1; // Heuristic selectivity estimate\n selectivity *= colSelectivity;\n break;\n }\n }\n\n // If we didn't find an equality constraint for this column, stop matching\n if (!foundEq) {\n break;\n }\n }\n\n // Calculate cost and rows for this index\n if (matchedFilterIndices.length > 0) {\n const indexCost = Math.log2(Math.max(2, tableRowCount)) * 2 + tableRowCount * selectivity;\n const indexRows = Math.max(1, Math.floor(tableRowCount * selectivity));\n\n // If this index is better than what we have, use it\n if (indexCost < bestCost) {\n bestCost = indexCost;\n bestRows = indexRows;\n bestHandledFilters = request.filters.map((_, idx) => matchedFilterIndices.includes(idx));\n // Note: IndexSchema doesn't have unique property in quereus 0.4.8, so we can't determine uniqueness\n bestIsSet = false;\n bestExplains = `Index seek on ${index.name} ` +\n `(selectivity: ${selectivity.toFixed(4)}, cost: ${indexCost.toFixed(2)})`;\n\n // Check if ORDER BY matches index order\n if (request.requiredOrdering && this.orderingMatchesIndex(request.requiredOrdering, index)) {\n bestOrdering = [...request.requiredOrdering];\n }\n }\n }\n }\n }\n\n // Return the best access plan found\n return {\n handledFilters: bestHandledFilters,\n cost: bestCost,\n rows: bestRows,\n providesOrdering: bestOrdering,\n isSet: bestIsSet,\n explains: bestExplains,\n };\n }\n\n /**\n * Helper: Check if required ordering matches primary key order\n */\n private orderingMatchesPrimaryKey(\n requiredOrdering: readonly OrderingSpec[],\n tableInfo: TableSchema\n ): boolean {\n const pkColumns = tableInfo.primaryKeyDefinition;\n if (requiredOrdering.length > pkColumns.length) return false;\n\n for (let i = 0; i < requiredOrdering.length; i++) {\n const orderSpec = requiredOrdering[i];\n const pkCol = pkColumns[i];\n\n if (!orderSpec || !pkCol) return false;\n if (orderSpec.columnIndex !== pkCol.index) return false;\n\n // Check if sort direction matches\n const pkDesc = pkCol.desc || false;\n if (orderSpec.desc !== pkDesc) return false;\n }\n\n return true;\n }\n\n /**\n * Helper: Check if required ordering matches index order\n */\n private orderingMatchesIndex(\n requiredOrdering: readonly OrderingSpec[],\n index: { columns: readonly { index: number; desc?: boolean }[] }\n ): boolean {\n if (requiredOrdering.length > index.columns.length) return false;\n\n for (let i = 0; i < requiredOrdering.length; i++) {\n const orderSpec = requiredOrdering[i];\n const indexCol = index.columns[i];\n\n if (!orderSpec || !indexCol) return false;\n if (orderSpec.columnIndex !== indexCol.index) return false;\n\n // Check if sort direction matches\n const indexDesc = indexCol.desc || false;\n if (orderSpec.desc !== indexDesc) return false;\n }\n\n return true;\n }\n\n /**\n * Destroys the underlying persistent representation of the virtual table\n */\n async destroy(\n _db: Database,\n _pAux: unknown,\n _moduleName: string,\n schemaName: string,\n tableName: string\n ): Promise<void> {\n // For now, this is a no-op since we don't have persistent schema storage\n // In a full implementation, this would clean up any metadata or resources\n void schemaName;\n void tableName;\n }\n}\n","import type { SqlValue } from '@quereus/quereus';\nimport type { TransactionBridge } from '../optimystic-adapter/txn-bridge.js';\n\n/**\n * StampId() SQL function\n *\n * Returns the current transaction (stamp) ID if a transaction is active, NULL otherwise.\n * The stamp ID is unique across the distributed system and stable within\n * a transaction, cycling between transactions. It is primarily used for passing\n * to `WITH CONTEXT` clauses to track transaction provenance.\n *\n * Format: 32 bytes base64url encoded\n * - First 16 bytes: SHA-256 hash of peer ID (for distributed uniqueness)\n * - Last 16 bytes: Random bytes (for collision resistance)\n *\n * @returns The current stamp ID string, or NULL if no transaction is active\n */\nexport function createStampIdFunction(txnBridge: TransactionBridge) {\n\treturn function stampId(): SqlValue {\n\t\tconst currentTxn = txnBridge.getCurrentTransaction();\n\n\t\tif (!currentTxn || !currentTxn.isActive) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn currentTxn.transactionId;\n\t};\n}\n\n","/**\r\n * Quereus Plugin Entry Point for Optimystic\r\n *\r\n * This module provides the plugin registration following Quereus 0.4.5 format.\r\n * All metadata is in package.json - no manifest export needed.\r\n */\r\n\r\nimport type { Database, SqlValue, FunctionFlags } from '@quereus/quereus';\r\nimport { TEXT_TYPE } from '@quereus/quereus';\r\nimport { CollectionFactory } from './optimystic-adapter/collection-factory.js';\r\nimport { TransactionBridge } from './optimystic-adapter/txn-bridge.js';\r\nimport { OptimysticModule } from './optimystic-module.js';\r\nimport { createStampIdFunction } from './functions/transaction-id.js';\r\n\r\n/**\r\n * Plugin registration function\r\n * This is called by Quereus when the plugin is loaded\r\n */\r\nexport default function register(db: Database, config: Record<string, SqlValue> = {}) {\r\n\tif (config.debug) {\r\n\t\tconsole.log('Optimystic plugin loading with config:', config);\r\n\t}\r\n\r\n\t// Global factory instances\r\n\tconst collectionFactory = new CollectionFactory();\r\n\tconst txnBridge = new TransactionBridge(collectionFactory);\r\n\tconst optimysticModule = new OptimysticModule(collectionFactory, txnBridge);\r\n\r\n\t// Create the StampId function\r\n\tconst stampIdFunc = createStampIdFunction(txnBridge);\r\n\r\n\t// Note: Transaction hooks are handled by the virtual table's begin, commit, rollback methods\r\n\r\n\treturn {\r\n\t\tvtables: [\r\n\t\t\t{\r\n\t\t\t\tname: 'optimystic',\r\n\t\t\t\tmodule: optimysticModule,\r\n\t\t\t\tauxData: config,\r\n\t\t\t},\r\n\t\t],\r\n\t\tfunctions: [\r\n\t\t\t{\r\n\t\t\t\tschema: {\r\n\t\t\t\t\tname: 'StampId',\r\n\t\t\t\t\tnumArgs: 0,\r\n\t\t\t\t\tflags: 1 as FunctionFlags, // UTF8\r\n\t\t\t\t\treturnType: {\r\n\t\t\t\t\t\ttypeClass: 'scalar' as const,\r\n\t\t\t\t\t\tlogicalType: TEXT_TYPE,\r\n\t\t\t\t\t\tnullable: true,\r\n\t\t\t\t\t\tisReadOnly: true,\r\n\t\t\t\t\t},\r\n\t\t\t\t\timplementation: stampIdFunc,\r\n\t\t\t\t},\r\n\t\t\t},\r\n\t\t],\r\n\t\tcollations: [],\r\n\t\t// Expose internal components for testing and advanced usage\r\n\t\tcollectionFactory,\r\n\t\ttxnBridge,\r\n\t};\r\n}\r\n\r\n"]}
|