web-dc-api 0.1.5 → 0.1.6

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.
Files changed (148) hide show
  1. package/dist/cjs/index.js +1 -1
  2. package/dist/dc.min.js +1 -1
  3. package/dist/esm/index.js +1 -1
  4. package/dist/index.d.ts +934 -878
  5. package/package.json +4 -8
  6. package/dist/cjs/helia-core-B1Xqha7a.js +0 -1
  7. package/dist/cjs/helia-core-D8Uv1KjQ.js +0 -1
  8. package/dist/cjs/polkadot-api-7PhQf3ws.js +0 -1
  9. package/dist/cjs/polkadot-api-CtrJVWuZ.js +0 -1
  10. package/dist/esm/chunks/helia-core-BxMqyK2Y.js +0 -1
  11. package/dist/esm/chunks/helia-core-DMXRpcO-.js +0 -1
  12. package/dist/esm/chunks/polkadot-api-5Y9Bw8VT.js +0 -1
  13. package/dist/esm/chunks/polkadot-api-D69Ioun_.js +0 -1
  14. package/lib/common/blowfish/block.ts +0 -259
  15. package/lib/common/blowfish/cipher.ts +0 -144
  16. package/lib/common/blowfish/const.ts +0 -195
  17. package/lib/common/chain.ts +0 -469
  18. package/lib/common/commonclient.ts +0 -202
  19. package/lib/common/constants.ts +0 -55
  20. package/lib/common/dc-key/ed25519.ts +0 -343
  21. package/lib/common/dc-key/keyManager.ts +0 -424
  22. package/lib/common/dcapi.ts +0 -98
  23. package/lib/common/dcutil.ts +0 -627
  24. package/lib/common/define.ts +0 -70
  25. package/lib/common/error.ts +0 -67
  26. package/lib/common/grpc-dc.ts +0 -104
  27. package/lib/common/module-system.ts +0 -184
  28. package/lib/common/service-worker.ts +0 -234
  29. package/lib/common/types/types.ts +0 -344
  30. package/lib/dc.ts +0 -701
  31. package/lib/implements/account/client.ts +0 -185
  32. package/lib/implements/account/manager.ts +0 -683
  33. package/lib/implements/aiproxy/client.ts +0 -357
  34. package/lib/implements/aiproxy/manager.ts +0 -670
  35. package/lib/implements/cache/client.ts +0 -105
  36. package/lib/implements/cache/manager.ts +0 -127
  37. package/lib/implements/comment/client.ts +0 -982
  38. package/lib/implements/comment/manager.ts +0 -1151
  39. package/lib/implements/dc/client.ts +0 -51
  40. package/lib/implements/dc/manager.ts +0 -33
  41. package/lib/implements/file/client.ts +0 -253
  42. package/lib/implements/file/file-cache-manager.ts +0 -142
  43. package/lib/implements/file/manager.ts +0 -1240
  44. package/lib/implements/file/seekableFileStream.ts +0 -344
  45. package/lib/implements/file/streamwriter.ts +0 -322
  46. package/lib/implements/keyvalue/client.ts +0 -376
  47. package/lib/implements/keyvalue/manager.ts +0 -759
  48. package/lib/implements/message/client.ts +0 -250
  49. package/lib/implements/message/manager.ts +0 -215
  50. package/lib/implements/threaddb/cbor/coding.ts +0 -62
  51. package/lib/implements/threaddb/cbor/event.ts +0 -336
  52. package/lib/implements/threaddb/cbor/node.ts +0 -542
  53. package/lib/implements/threaddb/cbor/record.ts +0 -398
  54. package/lib/implements/threaddb/common/AsyncMutex.ts +0 -24
  55. package/lib/implements/threaddb/common/addrinfo.ts +0 -135
  56. package/lib/implements/threaddb/common/dispatcher.ts +0 -81
  57. package/lib/implements/threaddb/common/idbstore-adapter.ts +0 -260
  58. package/lib/implements/threaddb/common/json-patcher.ts +0 -204
  59. package/lib/implements/threaddb/common/key.ts +0 -290
  60. package/lib/implements/threaddb/common/level-adapter.ts +0 -235
  61. package/lib/implements/threaddb/common/lineReader.ts +0 -79
  62. package/lib/implements/threaddb/common/logstore.ts +0 -215
  63. package/lib/implements/threaddb/common/transformed-datastore.ts +0 -308
  64. package/lib/implements/threaddb/core/app.ts +0 -206
  65. package/lib/implements/threaddb/core/core.ts +0 -230
  66. package/lib/implements/threaddb/core/db.ts +0 -249
  67. package/lib/implements/threaddb/core/event.ts +0 -54
  68. package/lib/implements/threaddb/core/head.ts +0 -89
  69. package/lib/implements/threaddb/core/identity.ts +0 -171
  70. package/lib/implements/threaddb/core/logstore.ts +0 -137
  71. package/lib/implements/threaddb/core/options.ts +0 -14
  72. package/lib/implements/threaddb/core/record.ts +0 -54
  73. package/lib/implements/threaddb/db/collection.ts +0 -1910
  74. package/lib/implements/threaddb/db/db.ts +0 -698
  75. package/lib/implements/threaddb/db/json2Query.ts +0 -192
  76. package/lib/implements/threaddb/db/query.ts +0 -524
  77. package/lib/implements/threaddb/dbclient.ts +0 -543
  78. package/lib/implements/threaddb/dbmanager.ts +0 -1906
  79. package/lib/implements/threaddb/lsstoreds/addr_book.ts +0 -549
  80. package/lib/implements/threaddb/lsstoreds/cache.ts +0 -36
  81. package/lib/implements/threaddb/lsstoreds/cyclic_batch.ts +0 -87
  82. package/lib/implements/threaddb/lsstoreds/global.ts +0 -151
  83. package/lib/implements/threaddb/lsstoreds/headbook.ts +0 -373
  84. package/lib/implements/threaddb/lsstoreds/keybook.ts +0 -297
  85. package/lib/implements/threaddb/lsstoreds/logstore.ts +0 -29
  86. package/lib/implements/threaddb/lsstoreds/metadata.ts +0 -223
  87. package/lib/implements/threaddb/net/define.ts +0 -149
  88. package/lib/implements/threaddb/net/grpcClient.ts +0 -589
  89. package/lib/implements/threaddb/net/grpcserver.ts +0 -146
  90. package/lib/implements/threaddb/net/net.ts +0 -2047
  91. package/lib/implements/threaddb/pb/lstore.proto +0 -38
  92. package/lib/implements/threaddb/pb/lstore.ts +0 -393
  93. package/lib/implements/threaddb/pb/lstore_pb.d.ts +0 -433
  94. package/lib/implements/threaddb/pb/lstore_pb.js +0 -1085
  95. package/lib/implements/threaddb/pb/net.proto +0 -194
  96. package/lib/implements/threaddb/pb/net_pb.d.ts +0 -2349
  97. package/lib/implements/threaddb/pb/net_pb.js +0 -5525
  98. package/lib/implements/threaddb/pb/proto-custom-types.ts +0 -212
  99. package/lib/implements/util/client.ts +0 -72
  100. package/lib/implements/util/manager.ts +0 -146
  101. package/lib/implements/wallet/manager.ts +0 -671
  102. package/lib/index.ts +0 -57
  103. package/lib/interfaces/DCContext.ts +0 -51
  104. package/lib/interfaces/aiproxy-interface.ts +0 -145
  105. package/lib/interfaces/auth-interface.ts +0 -118
  106. package/lib/interfaces/cache-interface.ts +0 -22
  107. package/lib/interfaces/client-interface.ts +0 -11
  108. package/lib/interfaces/comment-interface.ts +0 -167
  109. package/lib/interfaces/components/news-component.ts +0 -0
  110. package/lib/interfaces/database-interface.ts +0 -169
  111. package/lib/interfaces/file-interface.ts +0 -120
  112. package/lib/interfaces/index.ts +0 -10
  113. package/lib/interfaces/keyvalue-interface.ts +0 -156
  114. package/lib/interfaces/message-interface.ts +0 -22
  115. package/lib/interfaces/util-interface.ts +0 -31
  116. package/lib/modules/aiproxy-module.ts +0 -246
  117. package/lib/modules/auth-module.ts +0 -753
  118. package/lib/modules/cache-module.ts +0 -99
  119. package/lib/modules/client-module.ts +0 -71
  120. package/lib/modules/comment-module.ts +0 -429
  121. package/lib/modules/components/news-components.ts +0 -390
  122. package/lib/modules/database-module.ts +0 -598
  123. package/lib/modules/file-module.ts +0 -291
  124. package/lib/modules/index.ts +0 -13
  125. package/lib/modules/keyvalue-module.ts +0 -379
  126. package/lib/modules/message-module.ts +0 -107
  127. package/lib/modules/util-module.ts +0 -148
  128. package/lib/polyfills/process-env-browser.ts +0 -1
  129. package/lib/proto/datasource.ts +0 -93
  130. package/lib/proto/dcnet.proto +0 -1601
  131. package/lib/proto/dcnet_proto.d.ts +0 -22857
  132. package/lib/proto/dcnet_proto.js +0 -55204
  133. package/lib/proto/dcnet_proto_sparse.js +0 -55166
  134. package/lib/proto/oidfetch.proto +0 -25
  135. package/lib/proto/oidfetch_proto.d.ts +0 -585
  136. package/lib/proto/oidfetch_proto.js +0 -1247
  137. package/lib/serverless/babel-browser.ts +0 -39
  138. package/lib/serverless/base_entity.ts +0 -78
  139. package/lib/serverless/base_repository.ts +0 -414
  140. package/lib/serverless/browser_schema_extractor.ts +0 -283
  141. package/lib/serverless/decorator_factory.ts +0 -322
  142. package/lib/util/BrowserLineReader.ts +0 -73
  143. package/lib/util/base64.ts +0 -105
  144. package/lib/util/bcrypt.ts +0 -206
  145. package/lib/util/curve25519Encryption.ts +0 -418
  146. package/lib/util/dccrypt.ts +0 -73
  147. package/lib/util/logger.ts +0 -104
  148. package/lib/util/utils.ts +0 -289
@@ -1,206 +0,0 @@
1
- // app.ts
2
- import EventEmitter from 'eventemitter3';
3
- import { ThreadID } from '@textile/threads-id'
4
- import { IThreadRecord } from './record'
5
- import { Key as ThreadKey } from '../common/key';
6
- import { IThreadLogInfo, SymKey, ThreadInfo } from './core';
7
- import { ThreadToken } from './identity';
8
- import { Ed25519PubKey } from '../../../common/dc-key/ed25519';
9
- import { INet as net_Net } from './core'
10
- import { Context } from './core'
11
- import { IPLDNode } from './core';
12
- import { PeerId } from '@libp2p/interface';
13
- import { Head } from './head';
14
- import {net as net_pb} from "../pb/net_pb";
15
- import { DBClient } from '../dbclient';
16
- import { Blocks } from 'helia';
17
- import { AsyncMutex } from '../common/AsyncMutex';
18
- import { DAGCBOR } from '@helia/dag-cbor';
19
-
20
-
21
-
22
- // 类型定义
23
- export type PubKey = Ed25519PubKey
24
- export type Token = Uint8Array
25
-
26
- // 错误定义
27
- export const ErrThreadInUse = new Error('thread is in use')
28
- export const ErrInvalidNetRecordBody = new Error('app denied net record body')
29
-
30
- // 核心接口
31
- export interface App {
32
- validateNetRecordBody( body: IPLDNode, identity: PubKey): Promise<Error | undefined>
33
- handleNetRecord( rec: IThreadRecord, key?: ThreadKey): Promise<Error | undefined>
34
- getNetRecordCreateTime(rec: IThreadRecord, key?: ThreadKey): Promise<BigInt>
35
- }
36
-
37
- // 本地事件总线实现
38
- export class LocalEventsBus {
39
- private bus = new EventEmitter()
40
- private static readonly busTimeout = 15000 // 15秒
41
-
42
- send(event: LocalEvent): Promise<void> {
43
- return new Promise((resolve, reject) => {
44
- const timeout = setTimeout(() =>
45
- reject(new Error('Event send timeout')), LocalEventsBus.busTimeout
46
- )
47
-
48
- this.bus.emit('event', event, () => {
49
- clearTimeout(timeout)
50
- resolve()
51
- })
52
- })
53
- }
54
-
55
- listen(): LocalEventListener {
56
- return new LocalEventListener(this.bus)
57
- }
58
-
59
- discard() {
60
- this.bus.removeAllListeners()
61
- }
62
- }
63
-
64
- export class LocalEventListener {
65
- private handler: (event: LocalEvent) => void
66
-
67
- constructor(private bus: EventEmitter) {
68
- this.handler = (event: LocalEvent) => this.onEvent(event)
69
- bus.on('event', this.handler)
70
- }
71
-
72
- private onEvent(event: LocalEvent) {
73
- // 处理事件
74
- }
75
-
76
- discard() {
77
- this.bus.off('event', this.handler)
78
- }
79
- }
80
-
81
- export interface LocalEvent {
82
- node: IPLDNode
83
- token: ThreadToken
84
- }
85
-
86
- // 网络接口
87
- export interface Net extends net_Net {
88
- bstore: Blocks;
89
- connectApp(app: App, threadId: ThreadID): Promise<Connector>
90
-
91
- createRecord(
92
- threadId: ThreadID,
93
- body: IPLDNode,
94
- options?: { threadToken?: ThreadToken, apiToken?: Token }
95
- ): Promise<IThreadRecord>
96
-
97
- getDagService(): DAGCBOR ;
98
-
99
- validate(
100
- id: ThreadID,
101
- token?: ThreadToken
102
- ): Promise<Ed25519PubKey |undefined>
103
- exchange(id: ThreadID): Promise<void>
104
- threadOffsets(tid: ThreadID): Promise<[Record<string, Head>, PeerId[]]>
105
- buildGetRecordsRequest(
106
- tid: ThreadID,
107
- offsets: Record<string,Head>,
108
- limit: number
109
- ): Promise<{ req: net_pb.pb.IGetRecordsRequest, serviceKey: SymKey }>
110
- updateRecordsFromPeer(tid: ThreadID,peerId: PeerId|null,client?:DBClient): Promise<void>
111
- getMutexForThread(threadId: string): AsyncMutex
112
- preLoadLogs(tid: ThreadID, logs: net_pb.pb.Log[]): Promise<void>
113
- createExternalLogsIfNotExist(tid: ThreadID, logs: IThreadLogInfo[]): Promise<void>
114
- createExternalLogsIfNotExistForPreload(tid: ThreadID, logs: IThreadLogInfo[]): Promise<void>
115
- }
116
-
117
- // 连接器实现
118
- export class Connector {
119
- public readonly token: Token
120
-
121
- constructor(
122
- public net: Net,
123
- private app: App,
124
- private threadInfo: ThreadInfo
125
- ) {
126
- if (!threadInfo.key?.canRead()) {
127
- throw new Error(`Read key not found for thread ${threadInfo.id}`)
128
- }
129
- this.token = this.generateRandomBytes(32)
130
- }
131
-
132
- get threadId(): ThreadID {
133
- return this.threadInfo.id
134
- }
135
-
136
- get threadKey(): ThreadKey|undefined {
137
- return this.threadInfo.key
138
- }
139
-
140
-
141
- // 调用 net.createRecord 并提供线程 ID 和 API 令牌
142
- async createNetRecord(
143
- body: IPLDNode,
144
- token?: ThreadToken
145
- ): Promise<IThreadRecord> {
146
- return this.net.createRecord(
147
- this.threadId,
148
- body,
149
- {
150
- ...(token !== undefined ? { threadToken: token } : {}),
151
- apiToken: this.token
152
- }
153
- );
154
- }
155
-
156
- // 验证线程令牌
157
- async validate(
158
- token?: ThreadToken
159
- ): Promise<Error | undefined> {
160
- try{
161
- await this.net.validate( this.threadId, token);
162
- return
163
- }catch(err:any){
164
- return err
165
- }
166
- }
167
-
168
- // 调用连接应用的 ValidateNetRecordBody
169
- async validateNetRecordBody(
170
- body: IPLDNode,
171
- identity: PubKey
172
- ): Promise<Error|undefined> {
173
- return this.app.validateNetRecordBody( body, identity);
174
- }
175
-
176
- // 调用连接应用的 HandleNetRecord 并提供线程密钥
177
- async handleNetRecord(
178
- rec: IThreadRecord
179
- ): Promise<Error | undefined> {
180
- return this.app.handleNetRecord( rec, this.threadKey);
181
- }
182
-
183
- // 调用连接应用的 GetNetRecordCreateTime 解析记录创建时间
184
- async getNetRecordCreateTime(
185
- rec: IThreadRecord
186
- ): Promise<BigInt> {
187
- return this.app.getNetRecordCreateTime(rec, this.threadKey);
188
- }
189
-
190
- private generateRandomBytes(size: number): Uint8Array {
191
- return crypto.getRandomValues(new Uint8Array(size))
192
- }
193
- }
194
-
195
- // 工具函数
196
- export function NewConnector(
197
- app: App,
198
- net: Net,
199
- threadInfo: ThreadInfo
200
- ): [Connector | null, Error | null] {
201
- try {
202
- return [new Connector(net, app, threadInfo), null]
203
- } catch (err) {
204
- return [null, err as Error]
205
- }
206
- }
@@ -1,230 +0,0 @@
1
-
2
-
3
- import { Key,Datastore,Query,Batch } from 'interface-datastore';
4
- import { Key as ThreadKey } from '../common/key';
5
- import { ThreadID } from '@textile/threads-id';
6
- import type { PeerId,PublicKey,PrivateKey } from "@libp2p/interface";
7
- import { Multiaddr as TMultiaddr } from '@multiformats/multiaddr';
8
- import { Head } from './head';
9
- import { type AnySchema, type JSONSchemaType } from "ajv";
10
- import { dcnet } from "../../../proto/dcnet_proto";
11
- import { EventCodec } from "./db";
12
- import type { CID } from 'multiformats/cid'
13
- import { Link } from 'multiformats/link'
14
- import { DAGCBOR} from '@helia/dag-cbor'
15
- import { ThreadToken } from './identity';
16
- import { Ed25519PrivKey, Ed25519PubKey } from '../../../common/dc-key/ed25519';
17
- import {net as net_pb} from "../pb/net_pb";
18
- import { Protocol } from '../net/define';
19
-
20
-
21
-
22
- // 上下文接口
23
- export interface Context {
24
- signal?: AbortSignal | undefined
25
- deadline?: Date | undefined
26
- }
27
-
28
- export interface IPLDNode {
29
- cid(): CID
30
- links(): Link[]
31
- size(): number
32
- data(): Uint8Array
33
- }
34
-
35
-
36
- export interface IBlock {
37
- data(): Uint8Array;
38
- cid(): CID;
39
- }
40
-
41
-
42
- // 接口定义
43
- export interface INet {
44
- createThread( id: ThreadID, options: { token: ThreadToken; logKey?: Ed25519PrivKey|Ed25519PubKey, threadKey?: ThreadKey }): Promise<ThreadInfo>;
45
- addThread(addr: ThreadMuliaddr,options: { token?: ThreadToken | undefined; logKey?: Ed25519PrivKey | Ed25519PubKey | undefined; threadKey?: ThreadKey | undefined } ): Promise<ThreadInfo>;
46
- getThread( id: ThreadID, ...opts: any[]): Promise<ThreadInfo>;
47
- getThreadFromPeer( id: ThreadID, peer: PeerId, options: { token?: ThreadToken }): Promise<ThreadInfo>;
48
- deleteThread( id: ThreadID, ...opts: any[]): Promise<void>;
49
- pullThread( id: ThreadID,timeout: number, options: { token?: ThreadToken | undefined; multiPeersFlag?: boolean | undefined;} ): Promise<void>;
50
- getPbLogs( id: ThreadID): Promise<[net_pb.pb.ILog[], IThreadInfo]>;
51
- }
52
-
53
-
54
-
55
- export interface ICollectionConfig {
56
- name: string;
57
- schema: AnySchema;
58
- indexes?: Index[];
59
- writeValidator?: string;
60
- readFilter?: string;
61
- }
62
-
63
- export interface Index {
64
- path: string;
65
- unique: boolean;
66
- }
67
-
68
- export interface DBInfo {
69
- name: string;
70
- addrs: string[];
71
- key: Uint8Array;
72
- }
73
-
74
-
75
-
76
-
77
- export class NewOptions {
78
- name?: string | undefined;
79
- collections?: ICollectionConfig[] | undefined;
80
- eventCodec?: EventCodec | undefined;
81
- debug?: boolean | undefined;
82
- key?: ThreadKey | undefined;
83
- logKey?: Ed25519PrivKey | Ed25519PubKey | undefined;
84
- block?: boolean | undefined;
85
- token?: ThreadToken | undefined;
86
-
87
- constructor(init?: Partial<NewOptions>) {
88
- Object.assign(this, init);
89
- }
90
- }
91
-
92
- export type Token = Uint8Array;
93
-
94
- class TokenUtil {
95
- // 判断两个 Token 是否相等
96
- static equal(t: Token, b: Token): boolean {
97
- if (t.length !== b.length) {
98
- return false;
99
- }
100
- for (let i = 0; i < t.length; i++) {
101
- if (t[i] !== b[i]) {
102
- return false;
103
- }
104
- }
105
- return true;
106
- }
107
- }
108
-
109
- export interface ManagedOptions {
110
- name: string;
111
- key: ThreadKey;
112
- logKey: Ed25519PrivKey | Ed25519PubKey;
113
- token?: ThreadToken;
114
- collections: ICollectionConfig[];
115
- block: boolean;
116
- }
117
-
118
-
119
- // ======== 事务接口 ========
120
-
121
-
122
- // ======== 键转换接口 ========
123
-
124
-
125
- export interface AbortOptions {
126
- signal?: AbortSignal
127
- }
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
- // 定义对称密钥类型
136
- export interface SymKey {
137
- key: CryptoKey;
138
- raw: Uint8Array;
139
- }
140
-
141
-
142
- export class ThreadMuliaddr{
143
- addr: TMultiaddr
144
- id: ThreadID
145
- constructor(addr: TMultiaddr, id: ThreadID) {
146
- this.id = id
147
- this.addr = addr
148
- }
149
- getMultiaddrString(): string {
150
- const addr = this.addr.toString()
151
- const id = this.id.toString()
152
- const addrStr = addr + '/' + Protocol.name + '/' + id
153
- return addrStr
154
- }
155
- }
156
-
157
- // 定义 Thread Info 的接口
158
- export interface IThreadInfo {
159
- id: ThreadID;
160
- key: ThreadKey | undefined;
161
- logs: IThreadLogInfo[];
162
- addrs: ThreadMuliaddr[];
163
- getFirstPrivKeyLog() :IThreadLogInfo | undefined
164
- }
165
-
166
- export interface IDBInfo {
167
- id: string;
168
- name: string;
169
- addrs: string[];
170
- key: string | undefined;
171
- }
172
-
173
- export class ThreadInfo implements IThreadInfo {
174
- public id: ThreadID;
175
- public logs: IThreadLogInfo[];
176
- public addrs: ThreadMuliaddr[];
177
- public key: ThreadKey | undefined;
178
- constructor(
179
- id: ThreadID,
180
- logs: IThreadLogInfo[],
181
- addrs: ThreadMuliaddr[] ,
182
- key?: ThreadKey,
183
- ) {
184
- this.id = id;
185
- this.logs = logs;
186
- this.addrs = addrs;
187
- if (key) {
188
- this.key = key;
189
- }else {
190
- this.key = undefined;
191
- }
192
-
193
- }
194
-
195
-
196
- public getFirstPrivKeyLog() :IThreadLogInfo | undefined {
197
- for (const lg of this.logs) {
198
- if (lg.privKey) {
199
- return lg
200
- }
201
- }
202
- return
203
- }
204
-
205
- }
206
-
207
- export interface IThreadLogInfo {
208
- // id is the log's identifier.
209
- id: PeerId;
210
- // privKey is the log's private key.
211
- privKey?: PrivateKey;
212
- // pubKey is the log's public key.
213
- pubKey?: PublicKey;
214
- // Addrs are the addresses associated with the given log.
215
- addrs: TMultiaddr[];
216
- // Managed logs are any logs directly added/created by the host, and/or logs for which we have the private key
217
- managed: boolean;
218
- // Head is the log's current head.
219
- head?: Head;
220
- }
221
-
222
- // 定义 Store 接口
223
- export interface Store {
224
- addThread(info: IThreadInfo): Promise<void>;
225
- addLog(id: ThreadID, logInfo: IThreadLogInfo): Promise<void>;
226
- putBytes(id: ThreadID, identity: string, bytes: Uint8Array): Promise<void>;
227
- }
228
-
229
-
230
-
@@ -1,249 +0,0 @@
1
- import { ulid } from 'ulid';
2
- import { Key, Query,Batch, Datastore } from 'interface-datastore';
3
-
4
- import { IPLDNode } from './core';
5
- import {ThreadToken} from './identity';
6
- import { Ed25519PubKey as PubKey} from "../../../common/dc-key/ed25519";
7
- import { Connector,LocalEventsBus } from './app';
8
- import { Dispatcher } from '../common/dispatcher';
9
-
10
-
11
- export const Errors = {
12
- ErrDBNotFound: new Error('db not found'),
13
- ErrDBExists: new Error('db already exists'),
14
- ErrInvalidName: new Error('invalid name'),
15
- ErrThreadReadKeyRequired: new Error('thread read key required'),
16
- ErrorThreadIDValidation: new Error('thread id validation error'),
17
- ErrThreadNotFound: new Error('thread not found'),
18
- ErrLogNotFound: new Error('log not found'),
19
- ErrLogExists: new Error('log already exists'),
20
- ErrP2pNetworkNotInit: new Error('p2p network not initialized'),
21
- ErrNoDbManager: new Error('no db manager'),
22
- ErrNoDcPeerConnected: new Error('no dc peer connected'),
23
- ErrInvalidCollectionSchema: new Error("the collection schema _id property must be a string"),
24
- ErrCannotIndexIDField: new Error(`cannot create custom index `),
25
- ErrCollectionNotFound: new Error('collection not found'),
26
- ErrNodeAddrIsNull: new Error('node address is null'),
27
- ErrNoThreadOnDc: new Error('no thread on dc'),
28
- ErrNoDcNodeClient: new Error('no dc node client'),
29
- ErrFileNotFound: new Error('file not found'),
30
- };
31
-
32
- export const pullThreadBackgroundTimeout = 3600000; // 1 hour in milliseconds
33
- export const PullTimeout = 20000; // 20 seconds in milliseconds
34
-
35
- export const dsPrefix = new Key("/db");
36
- export const DBPrefix = {
37
- dsPrefix: dsPrefix,
38
- dsName: dsPrefix.child(new Key("name")),
39
- dsSchemas: dsPrefix.child(new Key("schema")),
40
- dsIndexes: dsPrefix.child(new Key("index")),
41
- dsValidators: dsPrefix.child(new Key("validator")),
42
- dsFilters: dsPrefix.child(new Key("filter")),
43
- dsVerno: dsPrefix.child(new Key("verno")),
44
- }
45
- export const idFieldName = "_id";
46
- export const modFieldName = "_mod";
47
-
48
-
49
-
50
-
51
-
52
- export type InstanceID = string;
53
- export const EmptyInstanceID: InstanceID = '';
54
-
55
- // NewInstanceID generates a new identity for an instance.
56
- export function NewInstanceID(): InstanceID {
57
- const id = ulid();
58
- return id.toLowerCase();
59
- }
60
-
61
- // InstanceID string representation
62
- export function instanceIDToString(id: InstanceID): string {
63
- return id;
64
- }
65
-
66
-
67
- export enum CoreActionType {
68
- Create = 0,
69
- Save = 1,
70
- Delete = 2
71
- }
72
-
73
-
74
-
75
- /**
76
- * Transaction class for collections
77
- */
78
- export interface ITxn{
79
- /**
80
- * Create new instances
81
- */
82
- create(...newInstances: Uint8Array[]): Promise<InstanceID[]>;
83
- /**
84
- * Verify instance changes without saving them
85
- */
86
- verify(...updated: Uint8Array[]): Promise<void>;
87
- /**
88
- * Save instance changes
89
- */
90
- save(...updated: Uint8Array[]): Promise<void>;
91
- /**
92
- * Delete instances
93
- */
94
- delete(...ids: InstanceID[]): Promise<void>;
95
- /**
96
- * Check if instances exist
97
- */
98
- has(...ids: InstanceID[]): Promise<boolean>;
99
- /**
100
- * Find instance by ID
101
- */
102
- findByID(id: InstanceID): Promise<Object> ;
103
- /**
104
- * Find instances matching a query
105
- */
106
- find(q?: Query): Promise<Object[]>;
107
- /**
108
- * Get instances modified since a specific time
109
- *
110
- * The _mod field tracks modified instances, but not those that have been deleted, so we need
111
- * to query the dispatcher for all (unique) instances in this collection that have been modified
112
- * at all since `time`.
113
- */
114
- modifiedSince(time: number): Promise<InstanceID[]>;
115
- /**
116
- * Commit the transaction
117
- */
118
- commit(): Promise<void>;
119
-
120
- /**
121
- * Discard the transaction
122
- */
123
- discard(): void;
124
- /**
125
- * Refresh collection reference
126
- */
127
- refreshCollection(): void
128
- }
129
- export interface ICollection {
130
- baseKey(): Key ;
131
- getName(): string ;
132
- getSchema(): Uint8Array;
133
- getWriteValidator(): Uint8Array;
134
- getReadFilter(): Uint8Array;
135
- readTxn(fn: (txn: ITxn) => Promise<void> , token?: ThreadToken): Promise<void> ;
136
- writeTxn(fn: (txn: ITxn) => Promise<void> , token?: ThreadToken): Promise<void>
137
- findByID(id: InstanceID, token?: ThreadToken): Promise<Object> ;
138
- create(v: Uint8Array, token?: ThreadToken): Promise<InstanceID> ;
139
- createMany(vs: Uint8Array[], token?: ThreadToken): Promise<InstanceID[]> ;
140
- delete(id: InstanceID, token?: ThreadToken): Promise<void> ;
141
- deleteMany(ids: InstanceID[], token?: ThreadToken): Promise<void> ;
142
- save(v: Uint8Array, token?: ThreadToken): Promise<void> ;
143
- saveMany(vs: Uint8Array[], token?: ThreadToken): Promise<void> ;
144
- verify(v: Uint8Array, token?: ThreadToken): Promise<void>;
145
- verifyMany(vs: Uint8Array[], token?: ThreadToken): Promise<void> ;
146
- has(id: InstanceID, token?: ThreadToken): Promise<boolean>;
147
- hasMany(ids: InstanceID[], token?: ThreadToken): Promise<boolean> ;
148
- find(q: Query, token?: ThreadToken): Promise<Object[]>
149
- modifiedSince(time: number, token?: ThreadToken): Promise<InstanceID[]>;
150
- validInstance(v: Uint8Array): void;
151
- validWrite(identity: PubKey, e: Event): Promise<void>;
152
- filterRead(identity: PubKey, instance: Uint8Array): Promise<Uint8Array | null>;
153
- }
154
- export interface IDB {
155
- datastore: TxnDatastoreExtended;
156
- connector: Connector|null; //
157
- dispatcher: Dispatcher | null;
158
- eventcodec: EventCodec;
159
- localEventsBus: LocalEventsBus | null;
160
- collections: Map<string, ICollection> ;
161
- readTxn(collection: ICollection, fn: (txn: ITxn) => Promise<void> , token?: ThreadToken): Promise<void>;
162
- writeTxn(collection: ICollection, fn: (txn: ITxn) => Promise<void> , token?: ThreadToken): Promise<void>;
163
- notifyTxnEvents(node: IPLDNode, token?: ThreadToken): Promise<void>;
164
- }
165
-
166
-
167
- export interface Event<T = any> {
168
- /** 事件时间戳 (Unix纳秒时间戳) */
169
- readonly timestamp: BigInt;
170
- /** 关联的实例ID */
171
- readonly instanceID: InstanceID;
172
- /** 所属集合名称 */
173
- readonly collection: string;
174
- /** 事件负载数据 */
175
- readonly payload: T;
176
-
177
- /** 序列化为Uint8Array */
178
- marshal(): Promise<Uint8Array>;
179
- }
180
-
181
-
182
- export interface QueryResult {
183
- key: string;
184
- value: Uint8Array;
185
- size?: number;
186
- }
187
-
188
- export interface QueryExt extends Query {
189
- seekPrefix?: string;
190
- }
191
-
192
- export interface Transaction {
193
- put( key: Key, value: Uint8Array): Promise<Key>;
194
- delete( key: Key): Promise<void>;
195
- get( key: Key): Promise<Uint8Array|undefined>;
196
- has( key: Key): Promise<boolean>;
197
- commit(): Promise<void>;
198
- discard(): void;
199
- query( q: Query): AsyncIterable<QueryResult>;
200
- queryExtended( q: QueryExt): AsyncIterable<QueryResult>;
201
- }
202
-
203
-
204
- interface DatastoreExtensions {
205
- newTransactionExtended( readOnly: boolean): Promise<Transaction>
206
- queryExtended( q: QueryExt): AsyncIterable<QueryResult>
207
- }
208
-
209
- export interface TxnDatastoreExtended extends Datastore, DatastoreExtensions {
210
- batch(): Batch;
211
- newTransactionExtended( readOnly: boolean): Promise<Transaction>
212
- }
213
-
214
- export type IndexFunc = (
215
- collection: string,
216
- key: Key,
217
- txn: Transaction ,
218
- oldData?: Uint8Array,
219
- newData?: Uint8Array,
220
-
221
- ) => Promise<void>;
222
-
223
- export interface Action {
224
- type: CoreActionType;
225
- instanceID: InstanceID;
226
- collectionName: string;
227
- previous?: Uint8Array;
228
- current?: Uint8Array;
229
- }
230
-
231
- export interface ReduceAction {
232
- type: CoreActionType;
233
- collection: string;
234
- instanceID: InstanceID;
235
- }
236
- export interface EventCodec {
237
- reduce(
238
- events: Event[],
239
- store: TxnDatastoreExtended,
240
- baseKey: Key,
241
- indexFn: IndexFunc
242
- ): Promise<ReduceAction[]>;
243
-
244
- create(actions: Action[]): Promise<[Event[], IPLDNode ]>;
245
-
246
- eventsFromBytes(data: Uint8Array): Promise<Event[]> ;
247
-
248
- }
249
-