-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathceramic-cli-utils.ts
More file actions
409 lines (350 loc) · 13 KB
/
ceramic-cli-utils.ts
File metadata and controls
409 lines (350 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import os from "os"
import path from "path"
import { randomBytes } from '@stablelib/random'
const fs = require('fs').promises
import IdentityWallet from "identity-wallet"
import CeramicClient from "@ceramicnetwork/ceramic-http-client"
import { CeramicApi, DoctypeUtils } from "@ceramicnetwork/ceramic-common"
import DocID from '@ceramicnetwork/docid'
import CeramicDaemon, { CreateOpts } from "./ceramic-daemon"
import Ipfs from "ipfs"
import dagJose from 'dag-jose'
// @ts-ignore
import multiformats from 'multiformats/basics'
// @ts-ignore
import legacy from 'multiformats/legacy'
import ipfsClient from "ipfs-http-client"
const DEFAULT_CLI_CONFIG_FILE = 'config.json'
export const DEFAULT_PINNING_STORE_PATH = ".pinning.store"
const DEFAULT_CLI_CONFIG_PATH = path.join(os.homedir(), '.ceramic')
/**
* CLI configuration
*/
interface CliConfig {
seed?: string;
ceramicHost?: string;
[index: string]: any; // allow arbitrary properties
}
/**
* Ceramic CLI utility functions
*/
export class CeramicCliUtils {
/**
* Create CeramicDaemon instance
* @param ipfsApi - IPFS api
* @param ethereumRpc - Ethereum RPC URL
* @param anchorServiceApi - Anchor service API URL
* @param validateDocs - Validate docs according to schemas or not
* @param pinning - Pinning endpoint
* @param stateStorePath - State store path
* @param gateway - read only endpoints available. It is disabled by default
* @param port - port daemon is availabe. Default is 7007
* @param debug - Enable debug logging level
* @param logToFiles - Enable writing logs to files
* @param logPath - Store log files in this directory
*/
static async createDaemon(ipfsApi: string, ethereumRpc: string, anchorServiceApi: string, validateDocs: boolean, pinning: string[], stateStorePath: string, gateway: boolean, port: number, debug: boolean, logToFiles: boolean, logPath: string): Promise<CeramicDaemon> {
if (stateStorePath == null) {
stateStorePath = DEFAULT_PINNING_STORE_PATH
}
const config: CreateOpts = {
ethereumRpcUrl: ethereumRpc,
anchorServiceUrl: anchorServiceApi,
stateStorePath: stateStorePath,
validateDocs,
pinning: pinning,
gateway,
port,
debug,
logToFiles,
logPath
}
multiformats.multicodec.add(dagJose)
const format = legacy(multiformats, dagJose.name)
let ipfs
if (ipfsApi) {
ipfs = ipfsClient({ url: ipfsApi, ipld: { formats: [format] } })
} else {
ipfs = await Ipfs.create({ ipld: { formats: [format] } })
}
config.ipfs = ipfs
return CeramicDaemon.create(config)
}
/**
* Create document
* @param doctype - Document type
* @param content - Document content
* @param controllers - Document controllers
* @param onlyGenesis - Create only a genesis record (no publish or anchor)
* @param isUnique - Should document be unique?
* @param schemaDocId - Schema document ID
*/
static async createDoc(doctype: string, content: string, controllers: string, onlyGenesis: boolean, isUnique: boolean, schemaDocId: string = null): Promise<void> {
await CeramicCliUtils._runWithCeramic(async (ceramic: CeramicClient) => {
const parsedControllers = CeramicCliUtils._parseControllers(controllers)
const parsedContent = CeramicCliUtils._parseContent(content)
const params = {
content: parsedContent, metadata: {
controllers: parsedControllers, isUnique, schema: schemaDocId
}
}
const doc = await ceramic.createDocument(doctype, params, {
applyOnly: onlyGenesis
})
console.log(doc.id)
console.log(JSON.stringify(doc.content, null, 2))
})
}
/**
* Change document
* @param docId - Document ID
* @param content - Document content
* @param controllers - Document controllers
* @param schemaDocId - Optional schema document ID
*/
static async change(docId: string, content: string, controllers: string, schemaDocId?: string): Promise<void> {
const id = DocID.fromString(docId)
const version = id.version
if (version) {
console.error(`No versions allowed. Invalid docId: ${id.toString()}`)
return
}
await CeramicCliUtils._runWithCeramic(async (ceramic: CeramicClient) => {
const parsedControllers = CeramicCliUtils._parseControllers(controllers)
const parsedContent = CeramicCliUtils._parseContent(content)
const doc = await ceramic.loadDocument(id)
await doc.change({
content: parsedContent, metadata: {
controllers: parsedControllers, schema: schemaDocId
}
})
console.log(JSON.stringify(doc.content, null, 2))
})
}
/**
* Show document content
* @param docId - Document ID
*/
static async show(docId: string): Promise<void> {
const id = DocID.fromString(docId)
await CeramicCliUtils._runWithCeramic(async (ceramic: CeramicApi) => {
const doc = await ceramic.loadDocument(id)
console.log(JSON.stringify(doc.content, null, 2))
})
}
/**
* Show document state
* @param docId - Document ID
*/
static async state(docId: string): Promise<void> {
const id = DocID.fromString(docId)
await CeramicCliUtils._runWithCeramic(async (ceramic: CeramicApi) => {
const doc = await ceramic.loadDocument(id)
console.log(JSON.stringify(DoctypeUtils.serializeState(doc.state), null, 2))
})
}
/**
* Watch document state periodically
* @param docId - Document ID
*/
static async watch(docId: string): Promise<void> {
const id = DocID.fromString(docId)
await CeramicCliUtils._runWithCeramic(async (ceramic: CeramicApi) => {
const doc = await ceramic.loadDocument(id)
console.log(JSON.stringify(doc.content, null, 2))
doc.on('change', () => {
console.log('--- document changed ---')
console.log(JSON.stringify(doc.content, null, 2))
})
})
}
/**
* Get document versions
* @param docId - Document ID
*/
static async versions(docId: string): Promise<void> {
const id = DocID.fromString(docId)
await CeramicCliUtils._runWithCeramic(async (ceramic: CeramicApi) => {
const versions = await ceramic.listVersions(id)
console.log(JSON.stringify(versions, null, 2))
})
}
/**
* Create schema document
* @param content - Schema content
* @param controllers - Schema controllers
* @param onlyGenesis - Create only a genesis record (no publish or anchor)
* @param isUnique - Should document be unique?
*/
static async schemaCreateDoc(content: string, controllers: string, onlyGenesis: boolean, isUnique: boolean): Promise<void> {
// TODO validate schema on the client side
return CeramicCliUtils.createDoc('tile', content, controllers, onlyGenesis, isUnique)
}
/**
* Change schema document
* @param schemaDocId - Schema document ID
* @param content - Schema document content
* @param controllers - Schema document controllers
*/
static async schemaChangeDoc(schemaDocId: string, content: string, controllers: string): Promise<void> {
DocID.fromString(schemaDocId)
// TODO validate schema on the client side
return CeramicCliUtils.change(schemaDocId, content, controllers, null)
}
/**
* Pin document
* @param docId - Document ID
*/
static async pinAdd(docId: string): Promise<void> {
const id = DocID.fromString(docId)
await CeramicCliUtils._runWithCeramic(async (ceramic: CeramicApi) => {
const result = await ceramic.pin.add(id)
console.log(JSON.stringify(result, null, 2))
})
}
/**
* Unpin document
* @param docId - Document ID
*/
static async pinRm(docId: string): Promise<void> {
const id = DocID.fromString(docId)
await CeramicCliUtils._runWithCeramic(async (ceramic: CeramicApi) => {
const result = await ceramic.pin.rm(id)
console.log(JSON.stringify(result, null, 2))
})
}
/**
* List pinned documents
* @param docId - optional document ID filter
*/
static async pinLs(docId?: string): Promise<void> {
const id = DocID.fromString(docId)
await CeramicCliUtils._runWithCeramic(async (ceramic: CeramicApi) => {
const pinnedDocIds = []
const iterator = await ceramic.pin.ls(id)
for await (const id of iterator) {
pinnedDocIds.push(id)
}
console.log(JSON.stringify(pinnedDocIds, null, 2))
})
}
/**
* Open Ceramic and execute function
* @param fn - Function to be executed
* @private
*/
static async _runWithCeramic(fn: (ceramic: CeramicClient) => Promise<void>): Promise<void> {
const cliConfig = await CeramicCliUtils._loadCliConfig()
if (!cliConfig.seed) {
cliConfig.seed = CeramicCliUtils._generateSeed()
await CeramicCliUtils._saveCliConfig(cliConfig)
}
let ceramic
const { ceramicHost } = cliConfig
if (ceramicHost !== undefined) {
ceramic = new CeramicClient(ceramicHost)
} else {
ceramic = new CeramicClient()
}
await IdentityWallet.create({
getPermission: async (): Promise<Array<string>> => [], seed: cliConfig.seed, ceramic,
disableIDX: true,
})
try {
await fn(ceramic)
} catch (e) {
console.error(e.message)
process.exit(-1)
} finally {
ceramic.close()
}
}
/**
* Set Ceramic Daemon host
*/
static async showConfig(): Promise<void> {
const cliConfig = await this._loadCliConfig()
console.log(JSON.stringify(cliConfig, null, 2))
}
/**
* Set Ceramic Daemon host
* @param variable - CLI config variable
* @param value - CLI config variable value
*/
static async setConfig(variable: string, value: any): Promise<void> {
let cliConfig = await this._loadCliConfig()
if (cliConfig == null) {
cliConfig = {}
}
Object.assign(cliConfig, {
[variable]: value
})
await this._saveCliConfig(cliConfig)
console.log(`Ceramic CLI configuration ${variable} set to ${value}`)
console.log(JSON.stringify(cliConfig))
}
/**
* Set Ceramic Daemon host
* @param variable - Name of the configuration variable
*/
static async unsetConfig(variable: string): Promise<void> {
const cliConfig = await this._loadCliConfig()
delete cliConfig[variable]
await this._saveCliConfig(cliConfig)
console.log(`Ceramic CLI configuration ${variable} unset`)
console.log(JSON.stringify(cliConfig, null, 2))
}
/**
* Load CLI configuration file
* @private
*/
static async _loadCliConfig(): Promise<CliConfig> {
const fullCliConfigPath = path.join(DEFAULT_CLI_CONFIG_PATH, DEFAULT_CLI_CONFIG_FILE)
try {
await fs.access(fullCliConfigPath)
return JSON.parse(await fs.readFile(fullCliConfigPath, { encoding: 'utf8' }))
} catch (e) {
// TODO handle invalid configuration
}
return await this._saveCliConfig({})
}
/**
* Save CLI configuration file
* @param cliConfig - CLI configuration
* @private
*/
static async _saveCliConfig(cliConfig: CliConfig): Promise<CliConfig> {
await fs.mkdir(DEFAULT_CLI_CONFIG_PATH, { recursive: true }) // create dirs if there are no
const fullCliConfigPath = path.join(DEFAULT_CLI_CONFIG_PATH, DEFAULT_CLI_CONFIG_FILE)
await fs.writeFile(fullCliConfigPath, JSON.stringify(cliConfig, null, 2))
return cliConfig
}
/**
* Generate new seed
* @private
*/
static _generateSeed(): string {
const seed = '0x' + Buffer.from(randomBytes(32)).toString('hex')
console.log('Identity wallet seed generated')
return seed
}
/**
* Parse input content
* @param content - Input content
* @private
*/
static _parseContent(content: string): any {
return content == null ? null : JSON.parse(content)
}
/**
* Parse input controllers
* @param controllers - Input controllers
* @private
*/
static _parseControllers(controllers: string): string[] {
if (controllers == null) {
return [ ]
}
return controllers.includes(',') ? controllers.split(',') : [controllers]
}
}