@sentio/sdk 1.26.4 → 1.27.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/lib/aptos/aptos-processor.d.ts +1 -1
- package/lib/aptos/aptos-processor.js +2 -2
- package/lib/aptos/aptos-processor.js.map +1 -1
- package/lib/aptos/index.d.ts +1 -1
- package/lib/aptos/index.js +2 -1
- package/lib/aptos/index.js.map +1 -1
- package/lib/aptos-codegen/codegen.js +1 -17
- package/lib/aptos-codegen/codegen.js.map +1 -1
- package/lib/cli/cli.js +3 -3
- package/lib/cli/cli.js.map +1 -1
- package/lib/cli/commands/login-server.d.ts +7 -0
- package/lib/cli/commands/login-server.js +134 -0
- package/lib/cli/commands/login-server.js.map +1 -0
- package/lib/cli/commands/run-login.js +77 -27
- package/lib/cli/commands/run-login.js.map +1 -1
- package/lib/cli/config.d.ts +5 -0
- package/lib/cli/config.js +28 -1
- package/lib/cli/config.js.map +1 -1
- package/package.json +7 -2
- package/src/aptos/aptos-processor.ts +2 -2
- package/src/aptos/index.ts +1 -1
- package/src/aptos-codegen/codegen.ts +1 -22
- package/src/cli/cli.ts +3 -3
- package/src/cli/commands/login-server.ts +120 -0
- package/src/cli/commands/run-login.ts +59 -28
- package/src/cli/config.ts +29 -0
@@ -61,7 +61,7 @@ export declare class AptosAccountProcessor {
|
|
61
61
|
protected constructor(options: AptosBindOptions);
|
62
62
|
getChainId(): string;
|
63
63
|
private onInterval;
|
64
|
-
onTimeInterval(handler: (resources: MoveResource[], ctx: AptosResourceContext) => void, timeIntervalInMinutes?: number,
|
64
|
+
onTimeInterval(handler: (resources: MoveResource[], ctx: AptosResourceContext) => void, timeIntervalInMinutes?: number, type?: string): this;
|
65
65
|
onVersionInterval(handler: (resources: MoveResource[], ctx: AptosResourceContext) => void, versionInterval?: number, typePrefix?: string): this;
|
66
66
|
}
|
67
67
|
export {};
|
@@ -155,8 +155,8 @@ class AptosAccountProcessor {
|
|
155
155
|
});
|
156
156
|
return this;
|
157
157
|
}
|
158
|
-
onTimeInterval(handler, timeIntervalInMinutes = 60,
|
159
|
-
return this.onInterval(handler, timeIntervalInMinutes, undefined,
|
158
|
+
onTimeInterval(handler, timeIntervalInMinutes = 60, type) {
|
159
|
+
return this.onInterval(handler, timeIntervalInMinutes, undefined, type);
|
160
160
|
}
|
161
161
|
onVersionInterval(handler, versionInterval = 100000, typePrefix) {
|
162
162
|
return this.onInterval(handler, undefined, versionInterval, typePrefix);
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"aptos-processor.js","sourceRoot":"","sources":["../../src/aptos/aptos-processor.ts"],"names":[],"mappings":";;;AACA,wBAOU;AAEV,mCAAsD;AACtD,uCAAsC;AAEtC,uCAAgD;AA6BhD,MAAM,YAAY;IAChB,OAAO,CAAe;IACtB,OAAO,CAAgE;CACxE;AAED,MAAM,WAAW;IACf,OAAO,CAA6B;IACpC,OAAO,CAA+D;CACvE;AAED,MAAa,+BAA+B;IAC1C,SAAS,CAAgB;IACzB,OAAO,CAAQ;IACf,SAAS,CAAQ;CAClB;AAJD,0EAIC;AAED,MAAM,gBAAgB;IACpB,IAAI,CAAS;IACb,eAAe,CAAS;IACxB,qBAAqB,CAAS;IAC9B,OAAO,CAAuE;CAC/E;AAED,MAAa,kBAAkB;IACpB,UAAU,CAAQ;IAC3B,MAAM,CAAgB;IACtB,aAAa,GAAmB,EAAE,CAAA;IAClC,YAAY,GAAkB,EAAE,CAAA;IAEhC,YAAY,UAAkB,EAAE,OAAyB;QACvD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC,OAAO,CAAC,CAAA;QAChC,MAAM,CAAC,eAAe,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACjD,IAAI,CAAC,SAAS,CAAC,qBAAa,CAAC,CAAA;IAC/B,CAAC;IAED,qCAAqC;IACrC,qBAAqB;IACrB,IAAI;IAEG,aAAa,C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AC,QAAQ;KAClD,CAAA;AACH,CAAC","sourcesContent":["import { ProcessResult } from '../gen'\nimport {\n AptosBindOptions,\n AptosContext,\n AptosNetwork,\n Transaction_UserTransaction,\n TransactionPayload_EntryFunctionPayload,\n TypeRegistry,\n} from '.'\n\nimport { EventInstance, TYPE_REGISTRY } from './types'\nimport { getChainId } from './network'\nimport { MoveResource } from 'aptos-sdk/src/generated'\nimport { AptosResourceContext } from './context'\n\ntype IndexConfigure = {\n address: string\n network: AptosNetwork\n startVersion: bigint\n // endSeqNumber?: Long\n}\n\n// TODO extends ArgumentsFilter\nexport interface EventFilter {\n type: string\n account?: string\n}\n\nexport interface FunctionNameAndCallFilter extends CallFilter {\n function: string\n}\n\n// TODO extends ArgumentsFilter\nexport interface CallFilter {\n includeFailed?: boolean\n typeArguments?: string[]\n}\n\nexport interface ArgumentsFilter {\n arguments?: string[]\n}\n\nclass EventHandler {\n filters: EventFilter[]\n handler: (event: Transaction_UserTransaction) => Promise<ProcessResult>\n}\n\nclass CallHandler {\n filters: FunctionNameAndCallFilter[]\n handler: (call: Transaction_UserTransaction) => Promise<ProcessResult>\n}\n\nexport class MoveResourcesWithVersionPayload {\n resources: MoveResource[]\n version: string\n timestamp: string\n}\n\nclass ResourceHandlder {\n type?: string\n versionInterval?: number\n timeIntervalInMinutes?: number\n handler: (resource: MoveResourcesWithVersionPayload) => Promise<ProcessResult>\n}\n\nexport class AptosBaseProcessor {\n readonly moduleName: string\n config: IndexConfigure\n eventHandlers: EventHandler[] = []\n callHandlers: CallHandler[] = []\n\n constructor(moduleName: string, options: AptosBindOptions) {\n this.moduleName = moduleName\n this.config = configure(options)\n global.PROCESSOR_STATE.aptosProcessors.push(this)\n this.loadTypes(TYPE_REGISTRY)\n }\n\n // getABI(): MoveModule | undefined {\n // return undefined\n // }\n\n public onTransaction(\n handler: (transaction: Transaction_UserTransaction, ctx: AptosContext) => void\n ): AptosBaseProcessor {\n // const address = this.config.address\n // const moduleName = this.moduleName\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const processor = this\n this.callHandlers.push({\n handler: async function (tx) {\n const ctx = new AptosContext(\n processor.moduleName,\n processor.config.network,\n processor.config.address,\n BigInt(tx.version),\n tx\n )\n if (tx) {\n await handler(tx, ctx)\n }\n return ctx.getProcessResult()\n },\n filters: [],\n })\n return this\n }\n\n public onEvent(\n handler: (event: EventInstance, ctx: AptosContext) => void,\n filter: EventFilter | EventFilter[]\n ): AptosBaseProcessor {\n let _filters: EventFilter[] = []\n\n if (Array.isArray(filter)) {\n _filters = filter\n } else {\n _filters.push(filter)\n }\n\n // const address = this.config.address\n // const moduleName = this.moduleName\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const processor = this\n\n this.eventHandlers.push({\n handler: async function (txn) {\n const ctx = new AptosContext(\n processor.moduleName,\n processor.config.network,\n processor.config.address,\n BigInt(txn.version),\n txn\n )\n if (txn && txn.events) {\n const events = txn.events\n txn.events = []\n for (const evt of events) {\n const eventInstance = evt as EventInstance\n const decoded = TYPE_REGISTRY.decodeEvent<any>(eventInstance)\n await handler(decoded || eventInstance, ctx)\n }\n }\n return ctx.getProcessResult()\n },\n filters: _filters,\n })\n return this\n }\n\n public onEntryFunctionCall(\n handler: (call: TransactionPayload_EntryFunctionPayload, ctx: AptosContext) => void,\n filter: FunctionNameAndCallFilter | FunctionNameAndCallFilter[]\n ): AptosBaseProcessor {\n let _filters: FunctionNameAndCallFilter[] = []\n\n if (Array.isArray(filter)) {\n _filters = filter\n } else {\n _filters.push(filter)\n }\n\n // const address = this.config.address\n // const moduleName = this.moduleName\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const processor = this\n\n this.callHandlers.push({\n handler: async function (tx) {\n const ctx = new AptosContext(\n processor.moduleName,\n processor.config.network,\n processor.config.address,\n BigInt(tx.version),\n tx\n )\n if (tx) {\n const payload = tx.payload as TransactionPayload_EntryFunctionPayload\n const decoded = TYPE_REGISTRY.decodeFunctionPayload(payload)\n await handler(decoded, ctx)\n }\n return ctx.getProcessResult()\n },\n filters: _filters,\n })\n return this\n }\n\n getChainId(): string {\n return getChainId(this.config.network)\n }\n\n loadTypes(registry: TypeRegistry) {\n if (registry.contains(this.config.address, this.moduleName)) {\n return\n }\n this.loadTypesInternal(registry)\n }\n\n protected loadTypesInternal(registry: TypeRegistry) {\n // should be override by subclass\n console.log('')\n }\n}\n\nexport class AptosAccountProcessor {\n config: IndexConfigure\n\n resourcesHandlers: ResourceHandlder[] = []\n\n static bind(options: AptosBindOptions): AptosAccountProcessor {\n return new AptosAccountProcessor(options)\n }\n\n protected constructor(options: AptosBindOptions) {\n this.config = configure(options)\n global.PROCESSOR_STATE.aptosAccountProcessors.push(this)\n }\n\n getChainId(): string {\n return getChainId(this.config.network)\n }\n\n private onInterval(\n handler: (resources: MoveResource[], ctx: AptosResourceContext) => void,\n timeInterval: number | undefined,\n versionInterval: number | undefined,\n type: string | undefined\n ) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const processor = this\n this.resourcesHandlers.push({\n handler: async function (arg) {\n const ctx = new AptosResourceContext(\n processor.config.network,\n processor.config.address,\n BigInt(arg.version),\n parseInt(arg.timestamp)\n )\n await handler(arg.resources, ctx)\n return ctx.getProcessResult()\n },\n timeIntervalInMinutes: timeInterval,\n versionInterval: versionInterval,\n type: type,\n })\n return this\n }\n\n public onTimeInterval(\n handler: (resources: MoveResource[], ctx: AptosResourceContext) => void,\n timeIntervalInMinutes = 60,\n typpe?: string\n ) {\n return this.onInterval(handler, timeIntervalInMinutes, undefined, typpe)\n }\n\n public onVersionInterval(\n handler: (resources: MoveResource[], ctx: AptosResourceContext) => void,\n versionInterval = 100000,\n typePrefix?: string\n ) {\n return this.onInterval(handler, undefined, versionInterval, typePrefix)\n }\n}\n\nfunction configure(options: AptosBindOptions): IndexConfigure {\n let startVersion = 0n\n if (options.startVersion !== undefined) {\n if (typeof options.startVersion === 'number') {\n startVersion = BigInt(options.startVersion)\n } else {\n startVersion = options.startVersion\n }\n }\n\n return {\n startVersion: startVersion,\n address: options.address,\n network: options.network || AptosNetwork.MAIN_NET,\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"aptos-processor.js","sourceRoot":"","sources":["../../src/aptos/aptos-processor.ts"],"names":[],"mappings":";;;AACA,wBAOU;AAEV,mCAAsD;AACtD,uCAAsC;AAEtC,uCAAgD;AA6BhD,MAAM,YAAY;IAChB,OAAO,CAAe;IACtB,OAAO,CAAgE;CACxE;AAED,MAAM,WAAW;IACf,OAAO,CAA6B;IACpC,OAAO,CAA+D;CACvE;AAED,MAAa,+BAA+B;IAC1C,SAAS,CAAgB;IACzB,OAAO,CAAQ;IACf,SAAS,CAAQ;CAClB;AAJD,0EAIC;AAED,MAAM,gBAAgB;IACpB,IAAI,CAAS;IACb,eAAe,CAAS;IACxB,qBAAqB,CAAS;IAC9B,OAAO,CAAuE;CAC/E;AAED,MAAa,kBAAkB;IACpB,UAAU,CAAQ;IAC3B,MAAM,CAAgB;IACtB,aAAa,GAAmB,EAAE,CAAA;IAClC,YAAY,GAAkB,EAAE,CAAA;IAEhC,YAAY,UAAkB,EAAE,OAAyB;QACvD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC,OAAO,CAAC,CAAA;QAChC,MAAM,CAAC,eAAe,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACjD,IAAI,CAAC,SAAS,CAAC,qBAAa,CAAC,CAAA;IAC/B,CAAC;IAED,qCAAqC;IACrC,qBAAqB;IACrB,IAAI;IAEG,aAAa,CAClB,OAA8E;QAE9E,sCAAsC;QACtC,qCAAqC;QACrC,4DAA4D;QAC5D,MAAM,SAAS,GAAG,IAAI,CAAA;QACtB,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC;YACrB,OAAO,EAAE,KAAK,WAAW,EAAE;gBACzB,MAAM,GAAG,GAAG,IAAI,eAAY,CAC1B,SAAS,CAAC,UAAU,EACpB,SAAS,CAAC,MAAM,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CAAC,CAAA;gBACjC,OAAO,GAAG,CAAC,gBAAgB,EAAE,CAAA;YAC/B,CAAC;YACD,qBAAqB,EAAE,YAAY;YACnC,eAAe,EAAE,eAAe;YAChC,IAAI,EAAE,IAAI;SACX,CAAC,CAAA;QACF,OAAO,IAAI,CAAA;IACb,CAAC;IAEM,cAAc,CACnB,OAAuE,EACvE,qBAAqB,GAAG,EAAE,EAC1B,IAAa;QAEb,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,qBAAqB,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;IACzE,CAAC;IAEM,iBAAiB,CACtB,OAAuE,EACvE,eAAe,GAAG,MAAM,EACxB,UAAmB;QAEnB,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,UAAU,CAAC,CAAA;IACzE,CAAC;CACF;AA3DD,sDA2DC;AAED,SAAS,SAAS,CAAC,OAAyB;IAC1C,IAAI,YAAY,GAAG,EAAE,CAAA;IACrB,IAAI,OAAO,CAAC,YAAY,KAAK,SAAS,EAAE;QACtC,IAAI,OAAO,OAAO,CAAC,YAAY,KAAK,QAAQ,EAAE;YAC5C,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;SAC5C;aAAM;YACL,YAAY,GAAG,OAAO,CAAC,YAAY,CAAA;SACpC;KACF;IAED,OAAO;QACL,YAAY,EAAE,YAAY;QAC1B,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,eAAY,CAAC,QAAQ;KAClD,CAAA;AACH,CAAC","sourcesContent":["import { ProcessResult } from '../gen'\nimport {\n AptosBindOptions,\n AptosContext,\n AptosNetwork,\n Transaction_UserTransaction,\n TransactionPayload_EntryFunctionPayload,\n TypeRegistry,\n} from '.'\n\nimport { EventInstance, TYPE_REGISTRY } from './types'\nimport { getChainId } from './network'\nimport { MoveResource } from 'aptos-sdk/src/generated'\nimport { AptosResourceContext } from './context'\n\ntype IndexConfigure = {\n address: string\n network: AptosNetwork\n startVersion: bigint\n // endSeqNumber?: Long\n}\n\n// TODO extends ArgumentsFilter\nexport interface EventFilter {\n type: string\n account?: string\n}\n\nexport interface FunctionNameAndCallFilter extends CallFilter {\n function: string\n}\n\n// TODO extends ArgumentsFilter\nexport interface CallFilter {\n includeFailed?: boolean\n typeArguments?: string[]\n}\n\nexport interface ArgumentsFilter {\n arguments?: string[]\n}\n\nclass EventHandler {\n filters: EventFilter[]\n handler: (event: Transaction_UserTransaction) => Promise<ProcessResult>\n}\n\nclass CallHandler {\n filters: FunctionNameAndCallFilter[]\n handler: (call: Transaction_UserTransaction) => Promise<ProcessResult>\n}\n\nexport class MoveResourcesWithVersionPayload {\n resources: MoveResource[]\n version: string\n timestamp: string\n}\n\nclass ResourceHandlder {\n type?: string\n versionInterval?: number\n timeIntervalInMinutes?: number\n handler: (resource: MoveResourcesWithVersionPayload) => Promise<ProcessResult>\n}\n\nexport class AptosBaseProcessor {\n readonly moduleName: string\n config: IndexConfigure\n eventHandlers: EventHandler[] = []\n callHandlers: CallHandler[] = []\n\n constructor(moduleName: string, options: AptosBindOptions) {\n this.moduleName = moduleName\n this.config = configure(options)\n global.PROCESSOR_STATE.aptosProcessors.push(this)\n this.loadTypes(TYPE_REGISTRY)\n }\n\n // getABI(): MoveModule | undefined {\n // return undefined\n // }\n\n public onTransaction(\n handler: (transaction: Transaction_UserTransaction, ctx: AptosContext) => void\n ): AptosBaseProcessor {\n // const address = this.config.address\n // const moduleName = this.moduleName\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const processor = this\n this.callHandlers.push({\n handler: async function (tx) {\n const ctx = new AptosContext(\n processor.moduleName,\n processor.config.network,\n processor.config.address,\n BigInt(tx.version),\n tx\n )\n if (tx) {\n await handler(tx, ctx)\n }\n return ctx.getProcessResult()\n },\n filters: [],\n })\n return this\n }\n\n public onEvent(\n handler: (event: EventInstance, ctx: AptosContext) => void,\n filter: EventFilter | EventFilter[]\n ): AptosBaseProcessor {\n let _filters: EventFilter[] = []\n\n if (Array.isArray(filter)) {\n _filters = filter\n } else {\n _filters.push(filter)\n }\n\n // const address = this.config.address\n // const moduleName = this.moduleName\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const processor = this\n\n this.eventHandlers.push({\n handler: async function (txn) {\n const ctx = new AptosContext(\n processor.moduleName,\n processor.config.network,\n processor.config.address,\n BigInt(txn.version),\n txn\n )\n if (txn && txn.events) {\n const events = txn.events\n txn.events = []\n for (const evt of events) {\n const eventInstance = evt as EventInstance\n const decoded = TYPE_REGISTRY.decodeEvent<any>(eventInstance)\n await handler(decoded || eventInstance, ctx)\n }\n }\n return ctx.getProcessResult()\n },\n filters: _filters,\n })\n return this\n }\n\n public onEntryFunctionCall(\n handler: (call: TransactionPayload_EntryFunctionPayload, ctx: AptosContext) => void,\n filter: FunctionNameAndCallFilter | FunctionNameAndCallFilter[]\n ): AptosBaseProcessor {\n let _filters: FunctionNameAndCallFilter[] = []\n\n if (Array.isArray(filter)) {\n _filters = filter\n } else {\n _filters.push(filter)\n }\n\n // const address = this.config.address\n // const moduleName = this.moduleName\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const processor = this\n\n this.callHandlers.push({\n handler: async function (tx) {\n const ctx = new AptosContext(\n processor.moduleName,\n processor.config.network,\n processor.config.address,\n BigInt(tx.version),\n tx\n )\n if (tx) {\n const payload = tx.payload as TransactionPayload_EntryFunctionPayload\n const decoded = TYPE_REGISTRY.decodeFunctionPayload(payload)\n await handler(decoded, ctx)\n }\n return ctx.getProcessResult()\n },\n filters: _filters,\n })\n return this\n }\n\n getChainId(): string {\n return getChainId(this.config.network)\n }\n\n loadTypes(registry: TypeRegistry) {\n if (registry.contains(this.config.address, this.moduleName)) {\n return\n }\n this.loadTypesInternal(registry)\n }\n\n protected loadTypesInternal(registry: TypeRegistry) {\n // should be override by subclass\n console.log('')\n }\n}\n\nexport class AptosAccountProcessor {\n config: IndexConfigure\n\n resourcesHandlers: ResourceHandlder[] = []\n\n static bind(options: AptosBindOptions): AptosAccountProcessor {\n return new AptosAccountProcessor(options)\n }\n\n protected constructor(options: AptosBindOptions) {\n this.config = configure(options)\n global.PROCESSOR_STATE.aptosAccountProcessors.push(this)\n }\n\n getChainId(): string {\n return getChainId(this.config.network)\n }\n\n private onInterval(\n handler: (resources: MoveResource[], ctx: AptosResourceContext) => void,\n timeInterval: number | undefined,\n versionInterval: number | undefined,\n type: string | undefined\n ) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const processor = this\n this.resourcesHandlers.push({\n handler: async function (arg) {\n const ctx = new AptosResourceContext(\n processor.config.network,\n processor.config.address,\n BigInt(arg.version),\n parseInt(arg.timestamp)\n )\n await handler(arg.resources, ctx)\n return ctx.getProcessResult()\n },\n timeIntervalInMinutes: timeInterval,\n versionInterval: versionInterval,\n type: type,\n })\n return this\n }\n\n public onTimeInterval(\n handler: (resources: MoveResource[], ctx: AptosResourceContext) => void,\n timeIntervalInMinutes = 60,\n type?: string\n ) {\n return this.onInterval(handler, timeIntervalInMinutes, undefined, type)\n }\n\n public onVersionInterval(\n handler: (resources: MoveResource[], ctx: AptosResourceContext) => void,\n versionInterval = 100000,\n typePrefix?: string\n ) {\n return this.onInterval(handler, undefined, versionInterval, typePrefix)\n }\n}\n\nfunction configure(options: AptosBindOptions): IndexConfigure {\n let startVersion = 0n\n if (options.startVersion !== undefined) {\n if (typeof options.startVersion === 'number') {\n startVersion = BigInt(options.startVersion)\n } else {\n startVersion = options.startVersion\n }\n }\n\n return {\n startVersion: startVersion,\n address: options.address,\n network: options.network || AptosNetwork.MAIN_NET,\n }\n}\n"]}
|
package/lib/aptos/index.d.ts
CHANGED
@@ -3,5 +3,5 @@ export type { EventInstance, TypedEventInstance, TypedEntryFunctionPayload } fro
|
|
3
3
|
export { TYPE_REGISTRY, TypeRegistry } from './types';
|
4
4
|
export type { FunctionNameAndCallFilter, EventFilter, CallFilter, ArgumentsFilter } from './aptos-processor';
|
5
5
|
export { AptosBaseProcessor, AptosAccountProcessor } from './aptos-processor';
|
6
|
-
export { AptosContext } from './context';
|
6
|
+
export { AptosContext, AptosResourceContext } from './context';
|
7
7
|
export { AptosBindOptions, AptosNetwork, getRpcClient } from './network';
|
package/lib/aptos/index.js
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.getRpcClient = exports.AptosNetwork = exports.AptosBindOptions = exports.AptosContext = exports.AptosAccountProcessor = exports.AptosBaseProcessor = exports.TypeRegistry = exports.TYPE_REGISTRY = void 0;
|
3
|
+
exports.getRpcClient = exports.AptosNetwork = exports.AptosBindOptions = exports.AptosResourceContext = exports.AptosContext = exports.AptosAccountProcessor = exports.AptosBaseProcessor = exports.TypeRegistry = exports.TYPE_REGISTRY = void 0;
|
4
4
|
var types_1 = require("./types");
|
5
5
|
Object.defineProperty(exports, "TYPE_REGISTRY", { enumerable: true, get: function () { return types_1.TYPE_REGISTRY; } });
|
6
6
|
Object.defineProperty(exports, "TypeRegistry", { enumerable: true, get: function () { return types_1.TypeRegistry; } });
|
@@ -9,6 +9,7 @@ Object.defineProperty(exports, "AptosBaseProcessor", { enumerable: true, get: fu
|
|
9
9
|
Object.defineProperty(exports, "AptosAccountProcessor", { enumerable: true, get: function () { return aptos_processor_1.AptosAccountProcessor; } });
|
10
10
|
var context_1 = require("./context");
|
11
11
|
Object.defineProperty(exports, "AptosContext", { enumerable: true, get: function () { return context_1.AptosContext; } });
|
12
|
+
Object.defineProperty(exports, "AptosResourceContext", { enumerable: true, get: function () { return context_1.AptosResourceContext; } });
|
12
13
|
var network_1 = require("./network");
|
13
14
|
Object.defineProperty(exports, "AptosBindOptions", { enumerable: true, get: function () { return network_1.AptosBindOptions; } });
|
14
15
|
Object.defineProperty(exports, "AptosNetwork", { enumerable: true, get: function () { return network_1.AptosNetwork; } });
|
package/lib/aptos/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/aptos/index.ts"],"names":[],"mappings":";;;AAEA,iCAAqD;AAA5C,sGAAA,aAAa,OAAA;AAAE,qGAAA,YAAY,OAAA;AAEpC,qDAA6E;AAApE,qHAAA,kBAAkB,OAAA;AAAE,wHAAA,qBAAqB,OAAA;AAClD,
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/aptos/index.ts"],"names":[],"mappings":";;;AAEA,iCAAqD;AAA5C,sGAAA,aAAa,OAAA;AAAE,qGAAA,YAAY,OAAA;AAEpC,qDAA6E;AAApE,qHAAA,kBAAkB,OAAA;AAAE,wHAAA,qBAAqB,OAAA;AAClD,qCAA8D;AAArD,uGAAA,YAAY,OAAA;AAAE,+GAAA,oBAAoB,OAAA;AAC3C,qCAAwE;AAA/D,2GAAA,gBAAgB,OAAA;AAAE,uGAAA,YAAY,OAAA;AAAE,uGAAA,YAAY,OAAA","sourcesContent":["export type { Transaction_UserTransaction, TransactionPayload_EntryFunctionPayload } from 'aptos-sdk/src/generated'\nexport type { EventInstance, TypedEventInstance, TypedEntryFunctionPayload } from './types'\nexport { TYPE_REGISTRY, TypeRegistry } from './types'\nexport type { FunctionNameAndCallFilter, EventFilter, CallFilter, ArgumentsFilter } from './aptos-processor'\nexport { AptosBaseProcessor, AptosAccountProcessor } from './aptos-processor'\nexport { AptosContext, AptosResourceContext } from './context'\nexport { AptosBindOptions, AptosNetwork, getRpcClient } from './network'\n"]}
|
@@ -53,7 +53,7 @@ async function generateForNetwork(srcDir, outputDir, network) {
|
|
53
53
|
}
|
54
54
|
while (loader.pendingAccounts.size > 0) {
|
55
55
|
for (const account of loader.pendingAccounts) {
|
56
|
-
console.log(`download
|
56
|
+
console.log(`download dependent module for account ${account} at ${(0, network_1.getChainName)(network)}`);
|
57
57
|
try {
|
58
58
|
const modules = await client.getAccountModules(account);
|
59
59
|
fs_1.default.writeFileSync(path_1.default.resolve(srcDir, account + '.json'), JSON.stringify(modules, null, '\t'));
|
@@ -330,22 +330,6 @@ function getEventStructs(module) {
|
|
330
330
|
}
|
331
331
|
return eventMap;
|
332
332
|
}
|
333
|
-
function isEvent(struct, module) {
|
334
|
-
const hasAbility = struct.abilities.includes('drop') && struct.abilities.includes('store');
|
335
|
-
if (!hasAbility) {
|
336
|
-
return false;
|
337
|
-
}
|
338
|
-
if (struct.name.endsWith('Event')) {
|
339
|
-
return true;
|
340
|
-
}
|
341
|
-
// for (const struct of module.structs) {
|
342
|
-
// for (const field of struct.fields) {
|
343
|
-
// if (field.type.startsWith('0x1::event::EventHandle')
|
344
|
-
// }
|
345
|
-
// }
|
346
|
-
return false;
|
347
|
-
//&&
|
348
|
-
}
|
349
333
|
function generateOnEvents(module, struct) {
|
350
334
|
// for struct that has drop + store
|
351
335
|
// if (!isEvent(struct, module)) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"codegen.js","sourceRoot":"","sources":["../../src/aptos-codegen/codegen.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAmB;AACnB,gDAAuB;AACvB,wDAA+B;AAE/B,uCAAkG;AAClG,0CAA0E;AAC1E,kDAAyB;AACzB,8CAA2E;AAEpE,KAAK,UAAU,QAAQ,CAAC,MAAc,EAAE,SAAiB;IAC9D,MAAM,kBAAkB,CAAC,MAAM,EAAE,SAAS,EAAE,sBAAY,CAAC,QAAQ,CAAC,CAAA;IAClE,MAAM,kBAAkB,CAAC,cAAI,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,EAAE,sBAAY,CAAC,QAAQ,CAAC,CAAA;AAChH,CAAC;AAHD,4BAGC;AAEM,KAAK,UAAU,kBAAkB,CAAC,MAAc,EAAE,SAAiB,EAAE,OAAqB;IAC/F,IAAI,CAAC,YAAE,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE;QAC1B,OAAM;KACP;IACD,IAAI,OAAO,KAAK,sB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,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AAC9E,CAAC","sourcesContent":["import fs from 'fs'\nimport path from 'path'\nimport prettier from 'prettier'\nimport { MoveFunction, MoveModule, MoveModuleBytecode, MoveStruct } from 'aptos-sdk/src/generated'\nimport { AccountModulesImportInfo, AccountRegister, generateType, parseMoveType } from './typegen'\nimport { isFrameworkAccount, moduleQname, SPLITTER } from '../aptos/utils'\nimport chalk from 'chalk'\nimport { AptosNetwork, getChainName, getRpcClient } from '../aptos/network'\n\nexport async function generate(srcDir: string, outputDir: string) {\n await generateForNetwork(srcDir, outputDir, AptosNetwork.MAIN_NET)\n await generateForNetwork(path.join(srcDir, 'testnet'), path.join(outputDir, 'testnet'), AptosNetwork.TEST_NET)\n}\n\nexport async function generateForNetwork(srcDir: string, outputDir: string, network: AptosNetwork) {\n if (!fs.existsSync(srcDir)) {\n return\n }\n if (network === AptosNetwork.TEST_NET) {\n console.log('Found testnet directory, generate code for testnet modules')\n }\n const files = fs.readdirSync(srcDir)\n outputDir = path.resolve(outputDir)\n const outputs: OutputFile[] = []\n\n fs.mkdirSync(outputDir, { recursive: true })\n\n const loader = new AccountRegister()\n\n // when generating user code, don't need to generate framework account\n loader.accountImports.set('0x1', new AccountModulesImportInfo('0x1', '0x1'))\n loader.accountImports.set('0x2', new AccountModulesImportInfo('0x2', '0x2'))\n loader.accountImports.set('0x3', new AccountModulesImportInfo('0x3', '0x3'))\n const client = getRpcClient(network)\n\n for (const file of files) {\n if (!file.endsWith('.json')) {\n continue\n }\n const fullPath = path.resolve(srcDir, file)\n const modules = JSON.parse(fs.readFileSync(fullPath, 'utf-8'))\n\n for (const module of modules) {\n if (module.abi) {\n loader.register(module.abi, path.basename(file, '.json'))\n }\n }\n const codeGen = new AccountCodegen(loader, modules, {\n fileName: path.basename(file, '.json'),\n outputDir: outputDir,\n network,\n })\n\n outputs.push(...codeGen.generate())\n }\n\n while (loader.pendingAccounts.size > 0) {\n for (const account of loader.pendingAccounts) {\n console.log(`download depended module for account ${account} at ${getChainName(network)}`)\n\n try {\n const modules = await client.getAccountModules(account)\n fs.writeFileSync(path.resolve(srcDir, account + '.json'), JSON.stringify(modules, null, '\\t'))\n\n for (const module of modules) {\n if (module.abi) {\n loader.register(module.abi, account)\n }\n }\n const codeGen = new AccountCodegen(loader, modules, {\n fileName: account,\n outputDir: outputDir,\n network,\n })\n\n outputs.push(...codeGen.generate())\n } catch (e) {\n console.error(\n chalk.red(\n 'Error downloading account module, check if you choose the right network,or download account modules manually into your director'\n )\n )\n console.error(e)\n process.exit(1)\n }\n }\n }\n\n for (const output of outputs) {\n const content = prettier.format(output.fileContent, { parser: 'typescript' })\n fs.writeFileSync(path.join(outputDir, output.fileName), content)\n }\n}\n\ninterface OutputFile {\n fileName: string\n fileContent: string\n}\n\ninterface Config {\n fileName: string\n outputDir: string\n network: AptosNetwork\n}\n\nexport class AccountCodegen {\n modules: MoveModuleBytecode[]\n config: Config\n loader: AccountRegister\n\n constructor(loader: AccountRegister, modules: MoveModuleBytecode[], config: Config) {\n // const json = fs.readFileSync(config.srcFile, 'utf-8')\n this.modules = modules\n this.config = config\n this.loader = loader\n }\n\n generate(): OutputFile[] {\n if (!this.modules) {\n return []\n }\n // const baseName = path.basename(this.config.fileName, '.json')\n\n let address: string | undefined\n for (const module of this.modules) {\n if (module.abi && module.abi.address) {\n address = module.abi.address\n }\n }\n if (!address) {\n return []\n }\n\n const imports = `\n import { aptos } from \"@sentio/sdk\"\n import { Address, MoveModule } from \"aptos-sdk/src/generated\"\n `\n\n const dependedAccounts: string[] = []\n\n const moduleImports: string[] = []\n\n const info = this.loader.accountImports.get(address)\n\n if (info) {\n for (const [account, moduleImported] of info.imports.entries()) {\n // Remap to user's filename if possible, TODO codepath not well tested\n let tsAccountModule = './' + (this.loader.accountImports.get(account)?.moduleName || account)\n if (isFrameworkAccount(account) && !isFrameworkAccount(address)) {\n // Decide where to find runtime library\n let srcRoot = 'lib'\n if (__dirname.includes('sdk/src/aptos-codegen')) {\n srcRoot = 'src'\n }\n tsAccountModule = `@sentio/sdk/${srcRoot}/builtin/aptos/${account}`\n }\n const items = Array.from(moduleImported)\n moduleImports.push(`import { ${items.join(',')} } from \"${tsAccountModule}\"`)\n\n // Ideally we should use per module's load types, but it doesn't matter since we are loading the entire\n // account modules anyway\n items.forEach((m) => dependedAccounts.push(m))\n }\n }\n\n const source = `\n /* Autogenerated file. Do not edit manually. */\n /* tslint:disable */\n /* eslint-disable */\n \n /* Generated modules for account ${address} */\n \n ${imports}\n \n ${moduleImports.join('\\n')}\n \n ${this.modules.map((m) => generateModule(m, this.config.network)).join('\\n')}\n \n function loadAllTypes(_r: aptos.TypeRegistry) {\n ${dependedAccounts.map((m) => `${m}.loadTypes(_r)`).join('\\n')}\n\n ${this.modules\n .map((m) => {\n return `_r.load(${m.abi?.name}.ABI)`\n })\n .join('\\n')}\n }\n ` // source\n\n return [\n {\n fileName: this.config.fileName + '.ts',\n fileContent: source,\n },\n ]\n }\n}\n\nfunction generateNetworkOption(network: AptosNetwork) {\n switch (network) {\n case AptosNetwork.TEST_NET:\n return 'TEST_NET'\n }\n return 'MAIN_NET'\n}\n\nfunction generateModule(moduleByteCode: MoveModuleBytecode, network: AptosNetwork) {\n if (!moduleByteCode.abi) {\n return ''\n }\n const module = moduleByteCode.abi\n\n const functions = module.exposed_functions.map((f) => generateOnEntryFunctions(module, f)).filter((s) => s !== '')\n\n const eventStructs = getEventStructs(module)\n const eventTypes = new Set(eventStructs.keys())\n const events = Array.from(eventStructs.values())\n .map((e) => generateOnEvents(module, e))\n .filter((s) => s !== '')\n const structs = module.structs.map((s) => generateStructs(module, s, eventTypes))\n const callArgs = module.exposed_functions.map((f) => generateCallArgsStructs(module, f))\n\n let processor = ''\n if (functions.length > 0 || events.length > 0) {\n processor = `export class ${module.name} extends aptos.AptosBaseProcessor {\n\n constructor(options: aptos.AptosBindOptions) {\n super(\"${module.name}\", options)\n }\n static DEFAULT_OPTIONS: aptos.AptosBindOptions = {\n address: \"${module.address}\",\n network: aptos.AptosNetwork.${generateNetworkOption(network)} \n }\n\n static bind(options: Partial<aptos.AptosBindOptions> = {}): ${module.name} {\n return new ${module.name}({ ...${module.name}.DEFAULT_OPTIONS, ...options })\n }\n \n ${functions.join('\\n')}\n \n ${events.join('\\n')}\n \n loadTypesInternal(registry: aptos.TypeRegistry) {\n loadAllTypes(registry)\n }\n }\n `\n }\n\n return `\n ${processor}\n\n export namespace ${module.name} {\n ${structs.join('\\n')}\n \n ${callArgs.join('\\n')}\n \n export function loadTypes(_r: aptos.TypeRegistry) {\n loadAllTypes(_r)\n }\n export const ABI: MoveModule = JSON.parse('${JSON.stringify(module)}')\n }\n `\n}\n\nfunction generateStructs(module: MoveModule, struct: MoveStruct, events: Set<string>) {\n const genericString = generateStructTypeParameters(struct)\n const genericStringAny = generateStructTypeParameters(struct, true)\n\n const fields = struct.fields.map((field) => {\n return `${field.name}: ${generateType(field.type)}`\n })\n\n let eventPayload = ''\n if (events.has(moduleQname(module) + SPLITTER + struct.name)) {\n eventPayload = `\n export interface ${struct.name}Instance extends \n aptos.TypedEventInstance<${struct.name}${genericStringAny}> {\n data_typed: ${struct.name}${genericStringAny}\n type_arguments: [${struct.generic_type_params.map((_) => 'string').join(', ')}]\n }\n `\n }\n\n return `\n export class ${struct.name}${genericString} {\n static TYPE_QNAME = '${module.address}::${module.name}::${struct.name}'\n ${fields.join('\\n')} \n }\n \n ${eventPayload}\n `\n}\n\n// function generateFunctionTypeParameters(func: MoveFunction) {\n// let genericString = ''\n// if (func.generic_type_params && func.generic_type_params.length > 0) {\n// const params = func.generic_type_params\n// .map((v, idx) => {\n// return 'T' + idx\n// })\n// .join(',')\n// genericString = `<${params}>`\n// }\n// return genericString\n// }\n\nfunction generateStructTypeParameters(struct: MoveStruct, useAny = false) {\n let genericString = ''\n\n if (struct.generic_type_params && struct.generic_type_params.length > 0) {\n const params = struct.generic_type_params\n .map((v, idx) => {\n return useAny ? 'any' : 'T' + idx\n })\n .join(',')\n genericString = `<${params}>`\n }\n return genericString\n}\n\nfunction generateCallArgsStructs(module: MoveModule, func: MoveFunction) {\n if (!func.is_entry) {\n return\n }\n\n // the first param is always signer so ignore\n // TODO check if there is any edge case\n const fields = func.params.slice(1).map((param) => {\n return `${generateType(param)}`\n })\n\n const camelFuncName = capitalizeFirstChar(camelize(func.name))\n\n // const genericString = generateFunctionTypeParameters(func)\n return `\n export interface ${camelFuncName}Payload\n extends aptos.TypedEntryFunctionPayload<[${fields.join(',')}]> {\n arguments_typed: [${fields.join(',')}],\n type_arguments: [${func.generic_type_params.map((_) => 'string').join(', ')}]\n }\n `\n}\n\nfunction generateOnEntryFunctions(module: MoveModule, func: MoveFunction) {\n if (!func.is_entry) {\n return ''\n }\n\n // const genericString = generateFunctionTypeParameters(func)\n\n const camelFuncName = capitalizeFirstChar(camelize(func.name))\n const source = `\n onEntry${camelFuncName}(func: (call: ${module.name}.${camelFuncName}Payload, ctx: aptos.AptosContext) => void, filter?: aptos.CallFilter): ${module.name} {\n this.onEntryFunctionCall(func, {\n ...filter,\n function: '${module.name}::${func.name}'\n })\n return this\n }`\n\n return source\n}\n\nfunction getEventStructs(module: MoveModule) {\n const qname = moduleQname(module)\n const structMap = new Map<string, MoveStruct>()\n const eventMap = new Map<string, MoveStruct>()\n\n for (const struct of module.structs) {\n structMap.set(qname + SPLITTER + struct.name, struct)\n }\n\n for (const struct of module.structs) {\n for (const field of struct.fields) {\n const t = parseMoveType(field.type)\n if (t.qname === '0x1::event::EventHandle') {\n const event = t.typeArgs[0].qname\n const eventStruct = structMap.get(event)\n if (eventStruct) {\n eventMap.set(event, eventStruct)\n }\n }\n }\n }\n\n return eventMap\n}\n\nfunction isEvent(struct: MoveStruct, module: MoveModule) {\n const hasAbility = struct.abilities.includes('drop') && struct.abilities.includes('store')\n\n if (!hasAbility) {\n return false\n }\n if (struct.name.endsWith('Event')) {\n return true\n }\n\n // for (const struct of module.structs) {\n // for (const field of struct.fields) {\n // if (field.type.startsWith('0x1::event::EventHandle')\n // }\n // }\n\n return false\n\n //&&\n}\n\nfunction generateOnEvents(module: MoveModule, struct: MoveStruct): string {\n // for struct that has drop + store\n // if (!isEvent(struct, module)) {\n // return ''\n // }\n\n // const genericString = generateStructTypeParameters(struct)\n\n const source = `\n onEvent${struct.name}(func: (event: ${module.name}.${struct.name}Instance, ctx: aptos.AptosContext) => void): ${module.name} {\n this.onEvent(func, {\n type: '${module.name}::${struct.name}'\n })\n return this\n }\n `\n return source\n}\n\nfunction camelize(input: string): string {\n return input\n .split('_')\n .reduce(\n (res, word, i) =>\n i === 0 ? word.toLowerCase() : `${res}${word.charAt(0).toUpperCase()}${word.substr(1).toLowerCase()}`,\n ''\n )\n}\n\nfunction capitalizeFirstChar(input: string): string {\n if (!input) {\n return input\n }\n return input[0].toUpperCase() + (input.length > 1 ? input.substring(1) : '')\n}\n"]}
|
1
|
+
{"version":3,"file":"codegen.js","sourceRoot":"","sources":["../../src/aptos-codegen/codegen.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAmB;AACnB,gDAAuB;AACvB,wDAA+B;AAE/B,uCAAkG;AAClG,0CAA0E;AAC1E,kDAAyB;AACzB,8CAA2E;AAEpE,KAAK,UAAU,QAAQ,CAAC,MAAc,EAAE,SAAiB;IAC9D,MAAM,kBAAkB,CAAC,MAAM,EAAE,SAAS,EAAE,sBAAY,CAAC,QAAQ,CAAC,CAAA;IAClE,MAAM,kBAAkB,CAAC,cAAI,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,EAAE,sBAAY,CAAC,QAAQ,CAAC,CAAA;AAChH,CAAC;AAHD,4BAGC;AAEM,KAAK,UAAU,kBAAkB,CAAC,MAAc,EAAE,SAAi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AA;iBACjC;aACF;SACF;KACF;IAED,OAAO,QAAQ,CAAA;AACjB,CAAC;AAED,SAAS,gBAAgB,CAAC,MAAkB,EAAE,MAAkB;IAC9D,mCAAmC;IACnC,kCAAkC;IAClC,cAAc;IACd,IAAI;IAEJ,6DAA6D;IAE7D,MAAM,MAAM,GAAG;WACN,MAAM,CAAC,IAAI,kBAAkB,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,gDAAgD,MAAM,CAAC,IAAI;;eAE9G,MAAM,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI;;;;GAIvC,CAAA;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAED,SAAS,QAAQ,CAAC,KAAa;IAC7B,OAAO,KAAK;SACT,KAAK,CAAC,GAAG,CAAC;SACV,MAAM,CACL,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,CACf,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,EAAE,EACvG,EAAE,CACH,CAAA;AACL,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,IAAI,CAAC,KAAK,EAAE;QACV,OAAO,KAAK,CAAA;KACb;IACD,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AAC9E,CAAC","sourcesContent":["import fs from 'fs'\nimport path from 'path'\nimport prettier from 'prettier'\nimport { MoveFunction, MoveModule, MoveModuleBytecode, MoveStruct } from 'aptos-sdk/src/generated'\nimport { AccountModulesImportInfo, AccountRegister, generateType, parseMoveType } from './typegen'\nimport { isFrameworkAccount, moduleQname, SPLITTER } from '../aptos/utils'\nimport chalk from 'chalk'\nimport { AptosNetwork, getChainName, getRpcClient } from '../aptos/network'\n\nexport async function generate(srcDir: string, outputDir: string) {\n await generateForNetwork(srcDir, outputDir, AptosNetwork.MAIN_NET)\n await generateForNetwork(path.join(srcDir, 'testnet'), path.join(outputDir, 'testnet'), AptosNetwork.TEST_NET)\n}\n\nexport async function generateForNetwork(srcDir: string, outputDir: string, network: AptosNetwork) {\n if (!fs.existsSync(srcDir)) {\n return\n }\n if (network === AptosNetwork.TEST_NET) {\n console.log('Found testnet directory, generate code for testnet modules')\n }\n const files = fs.readdirSync(srcDir)\n outputDir = path.resolve(outputDir)\n const outputs: OutputFile[] = []\n\n fs.mkdirSync(outputDir, { recursive: true })\n\n const loader = new AccountRegister()\n\n // when generating user code, don't need to generate framework account\n loader.accountImports.set('0x1', new AccountModulesImportInfo('0x1', '0x1'))\n loader.accountImports.set('0x2', new AccountModulesImportInfo('0x2', '0x2'))\n loader.accountImports.set('0x3', new AccountModulesImportInfo('0x3', '0x3'))\n const client = getRpcClient(network)\n\n for (const file of files) {\n if (!file.endsWith('.json')) {\n continue\n }\n const fullPath = path.resolve(srcDir, file)\n const modules = JSON.parse(fs.readFileSync(fullPath, 'utf-8'))\n\n for (const module of modules) {\n if (module.abi) {\n loader.register(module.abi, path.basename(file, '.json'))\n }\n }\n const codeGen = new AccountCodegen(loader, modules, {\n fileName: path.basename(file, '.json'),\n outputDir: outputDir,\n network,\n })\n\n outputs.push(...codeGen.generate())\n }\n\n while (loader.pendingAccounts.size > 0) {\n for (const account of loader.pendingAccounts) {\n console.log(`download dependent module for account ${account} at ${getChainName(network)}`)\n\n try {\n const modules = await client.getAccountModules(account)\n fs.writeFileSync(path.resolve(srcDir, account + '.json'), JSON.stringify(modules, null, '\\t'))\n\n for (const module of modules) {\n if (module.abi) {\n loader.register(module.abi, account)\n }\n }\n const codeGen = new AccountCodegen(loader, modules, {\n fileName: account,\n outputDir: outputDir,\n network,\n })\n\n outputs.push(...codeGen.generate())\n } catch (e) {\n console.error(\n chalk.red(\n 'Error downloading account module, check if you choose the right network,or download account modules manually into your director'\n )\n )\n console.error(e)\n process.exit(1)\n }\n }\n }\n\n for (const output of outputs) {\n const content = prettier.format(output.fileContent, { parser: 'typescript' })\n fs.writeFileSync(path.join(outputDir, output.fileName), content)\n }\n}\n\ninterface OutputFile {\n fileName: string\n fileContent: string\n}\n\ninterface Config {\n fileName: string\n outputDir: string\n network: AptosNetwork\n}\n\nexport class AccountCodegen {\n modules: MoveModuleBytecode[]\n config: Config\n loader: AccountRegister\n\n constructor(loader: AccountRegister, modules: MoveModuleBytecode[], config: Config) {\n // const json = fs.readFileSync(config.srcFile, 'utf-8')\n this.modules = modules\n this.config = config\n this.loader = loader\n }\n\n generate(): OutputFile[] {\n if (!this.modules) {\n return []\n }\n // const baseName = path.basename(this.config.fileName, '.json')\n\n let address: string | undefined\n for (const module of this.modules) {\n if (module.abi && module.abi.address) {\n address = module.abi.address\n }\n }\n if (!address) {\n return []\n }\n\n const imports = `\n import { aptos } from \"@sentio/sdk\"\n import { Address, MoveModule } from \"aptos-sdk/src/generated\"\n `\n\n const dependedAccounts: string[] = []\n\n const moduleImports: string[] = []\n\n const info = this.loader.accountImports.get(address)\n\n if (info) {\n for (const [account, moduleImported] of info.imports.entries()) {\n // Remap to user's filename if possible, TODO codepath not well tested\n let tsAccountModule = './' + (this.loader.accountImports.get(account)?.moduleName || account)\n if (isFrameworkAccount(account) && !isFrameworkAccount(address)) {\n // Decide where to find runtime library\n let srcRoot = 'lib'\n if (__dirname.includes('sdk/src/aptos-codegen')) {\n srcRoot = 'src'\n }\n tsAccountModule = `@sentio/sdk/${srcRoot}/builtin/aptos/${account}`\n }\n const items = Array.from(moduleImported)\n moduleImports.push(`import { ${items.join(',')} } from \"${tsAccountModule}\"`)\n\n // Ideally we should use per module's load types, but it doesn't matter since we are loading the entire\n // account modules anyway\n items.forEach((m) => dependedAccounts.push(m))\n }\n }\n\n const source = `\n /* Autogenerated file. Do not edit manually. */\n /* tslint:disable */\n /* eslint-disable */\n \n /* Generated modules for account ${address} */\n \n ${imports}\n \n ${moduleImports.join('\\n')}\n \n ${this.modules.map((m) => generateModule(m, this.config.network)).join('\\n')}\n \n function loadAllTypes(_r: aptos.TypeRegistry) {\n ${dependedAccounts.map((m) => `${m}.loadTypes(_r)`).join('\\n')}\n\n ${this.modules\n .map((m) => {\n return `_r.load(${m.abi?.name}.ABI)`\n })\n .join('\\n')}\n }\n ` // source\n\n return [\n {\n fileName: this.config.fileName + '.ts',\n fileContent: source,\n },\n ]\n }\n}\n\nfunction generateNetworkOption(network: AptosNetwork) {\n switch (network) {\n case AptosNetwork.TEST_NET:\n return 'TEST_NET'\n }\n return 'MAIN_NET'\n}\n\nfunction generateModule(moduleByteCode: MoveModuleBytecode, network: AptosNetwork) {\n if (!moduleByteCode.abi) {\n return ''\n }\n const module = moduleByteCode.abi\n\n const functions = module.exposed_functions.map((f) => generateOnEntryFunctions(module, f)).filter((s) => s !== '')\n\n const eventStructs = getEventStructs(module)\n const eventTypes = new Set(eventStructs.keys())\n const events = Array.from(eventStructs.values())\n .map((e) => generateOnEvents(module, e))\n .filter((s) => s !== '')\n const structs = module.structs.map((s) => generateStructs(module, s, eventTypes))\n const callArgs = module.exposed_functions.map((f) => generateCallArgsStructs(module, f))\n\n let processor = ''\n if (functions.length > 0 || events.length > 0) {\n processor = `export class ${module.name} extends aptos.AptosBaseProcessor {\n\n constructor(options: aptos.AptosBindOptions) {\n super(\"${module.name}\", options)\n }\n static DEFAULT_OPTIONS: aptos.AptosBindOptions = {\n address: \"${module.address}\",\n network: aptos.AptosNetwork.${generateNetworkOption(network)} \n }\n\n static bind(options: Partial<aptos.AptosBindOptions> = {}): ${module.name} {\n return new ${module.name}({ ...${module.name}.DEFAULT_OPTIONS, ...options })\n }\n \n ${functions.join('\\n')}\n \n ${events.join('\\n')}\n \n loadTypesInternal(registry: aptos.TypeRegistry) {\n loadAllTypes(registry)\n }\n }\n `\n }\n\n return `\n ${processor}\n\n export namespace ${module.name} {\n ${structs.join('\\n')}\n \n ${callArgs.join('\\n')}\n \n export function loadTypes(_r: aptos.TypeRegistry) {\n loadAllTypes(_r)\n }\n export const ABI: MoveModule = JSON.parse('${JSON.stringify(module)}')\n }\n `\n}\n\nfunction generateStructs(module: MoveModule, struct: MoveStruct, events: Set<string>) {\n const genericString = generateStructTypeParameters(struct)\n const genericStringAny = generateStructTypeParameters(struct, true)\n\n const fields = struct.fields.map((field) => {\n return `${field.name}: ${generateType(field.type)}`\n })\n\n let eventPayload = ''\n if (events.has(moduleQname(module) + SPLITTER + struct.name)) {\n eventPayload = `\n export interface ${struct.name}Instance extends \n aptos.TypedEventInstance<${struct.name}${genericStringAny}> {\n data_typed: ${struct.name}${genericStringAny}\n type_arguments: [${struct.generic_type_params.map((_) => 'string').join(', ')}]\n }\n `\n }\n\n return `\n export class ${struct.name}${genericString} {\n static TYPE_QNAME = '${module.address}::${module.name}::${struct.name}'\n ${fields.join('\\n')} \n }\n \n ${eventPayload}\n `\n}\n\n// function generateFunctionTypeParameters(func: MoveFunction) {\n// let genericString = ''\n// if (func.generic_type_params && func.generic_type_params.length > 0) {\n// const params = func.generic_type_params\n// .map((v, idx) => {\n// return 'T' + idx\n// })\n// .join(',')\n// genericString = `<${params}>`\n// }\n// return genericString\n// }\n\nfunction generateStructTypeParameters(struct: MoveStruct, useAny = false) {\n let genericString = ''\n\n if (struct.generic_type_params && struct.generic_type_params.length > 0) {\n const params = struct.generic_type_params\n .map((v, idx) => {\n return useAny ? 'any' : 'T' + idx\n })\n .join(',')\n genericString = `<${params}>`\n }\n return genericString\n}\n\nfunction generateCallArgsStructs(module: MoveModule, func: MoveFunction) {\n if (!func.is_entry) {\n return\n }\n\n // the first param is always signer so ignore\n // TODO check if there is any edge case\n const fields = func.params.slice(1).map((param) => {\n return `${generateType(param)}`\n })\n\n const camelFuncName = capitalizeFirstChar(camelize(func.name))\n\n // const genericString = generateFunctionTypeParameters(func)\n return `\n export interface ${camelFuncName}Payload\n extends aptos.TypedEntryFunctionPayload<[${fields.join(',')}]> {\n arguments_typed: [${fields.join(',')}],\n type_arguments: [${func.generic_type_params.map((_) => 'string').join(', ')}]\n }\n `\n}\n\nfunction generateOnEntryFunctions(module: MoveModule, func: MoveFunction) {\n if (!func.is_entry) {\n return ''\n }\n\n // const genericString = generateFunctionTypeParameters(func)\n\n const camelFuncName = capitalizeFirstChar(camelize(func.name))\n const source = `\n onEntry${camelFuncName}(func: (call: ${module.name}.${camelFuncName}Payload, ctx: aptos.AptosContext) => void, filter?: aptos.CallFilter): ${module.name} {\n this.onEntryFunctionCall(func, {\n ...filter,\n function: '${module.name}::${func.name}'\n })\n return this\n }`\n\n return source\n}\n\nfunction getEventStructs(module: MoveModule) {\n const qname = moduleQname(module)\n const structMap = new Map<string, MoveStruct>()\n const eventMap = new Map<string, MoveStruct>()\n\n for (const struct of module.structs) {\n structMap.set(qname + SPLITTER + struct.name, struct)\n }\n\n for (const struct of module.structs) {\n for (const field of struct.fields) {\n const t = parseMoveType(field.type)\n if (t.qname === '0x1::event::EventHandle') {\n const event = t.typeArgs[0].qname\n const eventStruct = structMap.get(event)\n if (eventStruct) {\n eventMap.set(event, eventStruct)\n }\n }\n }\n }\n\n return eventMap\n}\n\nfunction generateOnEvents(module: MoveModule, struct: MoveStruct): string {\n // for struct that has drop + store\n // if (!isEvent(struct, module)) {\n // return ''\n // }\n\n // const genericString = generateStructTypeParameters(struct)\n\n const source = `\n onEvent${struct.name}(func: (event: ${module.name}.${struct.name}Instance, ctx: aptos.AptosContext) => void): ${module.name} {\n this.onEvent(func, {\n type: '${module.name}::${struct.name}'\n })\n return this\n }\n `\n return source\n}\n\nfunction camelize(input: string): string {\n return input\n .split('_')\n .reduce(\n (res, word, i) =>\n i === 0 ? word.toLowerCase() : `${res}${word.charAt(0).toUpperCase()}${word.substr(1).toLowerCase()}`,\n ''\n )\n}\n\nfunction capitalizeFirstChar(input: string): string {\n if (!input) {\n return input\n }\n return input[0].toUpperCase() + (input.length > 1 ? input.substring(1) : '')\n}\n"]}
|
package/lib/cli/cli.js
CHANGED
@@ -13,9 +13,9 @@ const config_1 = require("./config");
|
|
13
13
|
const upload_1 = require("./upload");
|
14
14
|
const chalk_1 = __importDefault(require("chalk"));
|
15
15
|
const build_1 = require("./build");
|
16
|
-
const run_login_1 = require("./commands/run-login");
|
17
16
|
const run_create_1 = require("./commands/run-create");
|
18
17
|
const run_version_1 = require("./commands/run-version");
|
18
|
+
const run_login_1 = require("./commands/run-login");
|
19
19
|
const mainDefinitions = [{ name: 'command', defaultOption: true }];
|
20
20
|
const mainOptions = (0, command_line_args_1.default)(mainDefinitions, {
|
21
21
|
stopAtFirstUnknown: true,
|
@@ -160,12 +160,12 @@ function usage() {
|
|
160
160
|
header: 'Usage',
|
161
161
|
content: [
|
162
162
|
'sentio <command> --help\t\tshow detail usage of specific command',
|
163
|
-
'sentio login
|
163
|
+
'sentio login\t\t\t\tlogin to sentio',
|
164
164
|
'sentio create\t\t\t\tcreate a template project',
|
165
165
|
'sentio upload\t\t\t\tbuild and upload processor to sentio',
|
166
166
|
'sentio gen\t\t\t\tgenerate abi',
|
167
167
|
'sentio build\t\t\t\tgenerate abi and build',
|
168
|
-
'sentio version\t\t\
|
168
|
+
'sentio version\t\t\tcurrent cli version',
|
169
169
|
],
|
170
170
|
},
|
171
171
|
]);
|
package/lib/cli/cli.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/cli/cli.ts"],"names":[],"mappings":";;;;;;AAEA,0EAA+C;AAC/C,4EAAiD;AACjD,4CAAmB;AACnB,gDAAuB;AAEvB,sDAA0B;AAC1B,qCAAiF;AACjF,qCAAqC;AACrC,kDAAyB;AACzB,mCAAwC;AACxC,oDAA+C;
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/cli/cli.ts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,CAAC,SAAS,CAAC,EAAE;gBACtB,WAAW,GAAG,OAAO,CAAC,SAAS,CAAC,CAAA;aACjC;YACD,IAAA,mBAAU,EAAC,eAAe,EAAE,WAAW,CAAC,CAAA;SACzC;KACF;SAAM,IAAI,WAAW,CAAC,OAAO,KAAK,OAAO,EAAE;QAC1C,IAAA,sBAAc,EAAC,KAAK,CAAC,CAAA;KACtB;SAAM,IAAI,WAAW,CAAC,OAAO,KAAK,KAAK,EAAE;QACxC,IAAA,sBAAc,EAAC,IAAI,CAAC,CAAA;KACrB;SAAM;QACL,KAAK,EAAE,CAAA;KACR;CACF;AAED,SAAS,KAAK;IACZ,MAAM,KAAK,GAAG,IAAA,4BAAgB,EAAC;QAC7B;YACE,MAAM,EAAE,QAAQ;YAChB,OAAO,EAAE,8CAA8C;SACxD;QACD;YACE,MAAM,EAAE,OAAO;YACf,OAAO,EAAE;gBACP,kEAAkE;gBAClE,qCAAqC;gBACrC,gDAAgD;gBAChD,2DAA2D;gBAC3D,gCAAgC;gBAChC,4CAA4C;gBAC5C,yCAAyC;aAC1C;SACF;KACF,CAAC,CAAA;IACF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;IAClB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport commandLineArgs from 'command-line-args'\nimport commandLineUsage from 'command-line-usage'\nimport fs from 'fs'\nimport path from 'path'\n\nimport yaml from 'js-yaml'\nimport { finalizeHost, FinalizeProjectName, SentioProjectConfig } from './config'\nimport { uploadFile } from './upload'\nimport chalk from 'chalk'\nimport { buildProcessor } from './build'\nimport { runCreate } from './commands/run-create'\nimport { runVersion } from './commands/run-version'\nimport { runLogin } from './commands/run-login'\n\nconst mainDefinitions = [{ name: 'command', defaultOption: true }]\nconst mainOptions = commandLineArgs(mainDefinitions, {\n stopAtFirstUnknown: true,\n})\nconst argv = mainOptions._unknown || []\n\nif (!mainOptions.command) {\n usage()\n}\n\nif (mainOptions.command === 'login') {\n runLogin(argv)\n} else if (mainOptions.command === 'create') {\n runCreate(argv)\n} else if (mainOptions.command === 'version') {\n runVersion(argv)\n} else {\n // For all the commands that need read project configs\n // TODO move them to their own modules\n\n // Process configs\n let processorConfig: SentioProjectConfig = { host: '', project: '', build: true }\n // Fist step, read from project yaml file\n try {\n console.log(chalk.blue('Loading Process config'))\n // TODO correctly located sentio.yaml\n const pwd = process.cwd()\n const packageJson = path.join(pwd, 'package.json')\n if (!fs.existsSync(packageJson)) {\n console.error('package.json not found, please run this command in the root of your project')\n process.exit(1)\n }\n\n const yamlPath = path.join(pwd, 'sentio.yaml')\n if (!fs.existsSync(yamlPath)) {\n console.error('sentio.yaml not found, please create one according to: TODO docs')\n process.exit(1)\n }\n\n processorConfig = yaml.load(fs.readFileSync('sentio.yaml', 'utf8')) as SentioProjectConfig\n if (!processorConfig.project === undefined) {\n console.error('Config yaml must have contain a valid project identifier')\n process.exit(1)\n }\n if (processorConfig.build === undefined) {\n processorConfig.build = true\n }\n if (!processorConfig.host) {\n processorConfig.host = 'prod'\n }\n\n // if (!processorConfig.source) {\n // processorConfig.source = 'src/processor.ts'\n // }\n // if (!processorConfig.targets) {\n // console.warn('targets is not defined, use EVM as the default target')\n // processorConfig.targets = []\n // }\n // if (processorConfig.targets.length === 0) {\n // // By default evm\n // processorConfig.targets.push({ chain: EVM })\n // }\n } catch (e) {\n console.error(e)\n process.exit(1)\n }\n\n if (mainOptions.command === 'upload') {\n const optionDefinitions = [\n {\n name: 'help',\n alias: 'h',\n type: Boolean,\n description: 'Display this usage guide.',\n },\n {\n name: 'api-key',\n type: String,\n description: '(Optional) Manually provide API key rather than use saved credential',\n },\n {\n name: 'host',\n description: '(Optional) Override Sentio Host name',\n type: String,\n },\n {\n name: 'owner',\n description: '(Optional) Override Project owner',\n type: String,\n },\n {\n name: 'nobuild',\n description: '(Optional) Skip build & pack file before uploading, default false',\n type: Boolean,\n },\n ]\n const options = commandLineArgs(optionDefinitions, { argv })\n if (options.help) {\n const usage = commandLineUsage([\n {\n header: 'Sentio upload',\n content: 'sentio upload',\n },\n {\n header: 'Options',\n optionList: optionDefinitions,\n },\n ])\n console.log(usage)\n } else {\n if (options.host) {\n processorConfig.host = options.host\n }\n if (options.nobuild) {\n processorConfig.build = false\n }\n finalizeHost(processorConfig)\n FinalizeProjectName(processorConfig, options.owner)\n console.log(processorConfig)\n\n let apiOverride = undefined\n if (options['api-key']) {\n apiOverride = options['api-key']\n }\n uploadFile(processorConfig, apiOverride)\n }\n } else if (mainOptions.command === 'build') {\n buildProcessor(false)\n } else if (mainOptions.command === 'gen') {\n buildProcessor(true)\n } else {\n usage()\n }\n}\n\nfunction usage() {\n const usage = commandLineUsage([\n {\n header: 'Sentio',\n content: 'Login & Manage your project files to Sentio.',\n },\n {\n header: 'Usage',\n content: [\n 'sentio <command> --help\\t\\tshow detail usage of specific command',\n 'sentio login\\t\\t\\t\\tlogin to sentio',\n 'sentio create\\t\\t\\t\\tcreate a template project',\n 'sentio upload\\t\\t\\t\\tbuild and upload processor to sentio',\n 'sentio gen\\t\\t\\t\\tgenerate abi',\n 'sentio build\\t\\t\\t\\tgenerate abi and build',\n 'sentio version\\t\\t\\tcurrent cli version',\n ],\n },\n ])\n console.log(usage)\n process.exit(1)\n}\n"]}
|
@@ -0,0 +1,134 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
3
|
+
if (k2 === undefined) k2 = k;
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
7
|
+
}
|
8
|
+
Object.defineProperty(o, k2, desc);
|
9
|
+
}) : (function(o, m, k, k2) {
|
10
|
+
if (k2 === undefined) k2 = k;
|
11
|
+
o[k2] = m[k];
|
12
|
+
}));
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
15
|
+
}) : function(o, v) {
|
16
|
+
o["default"] = v;
|
17
|
+
});
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
19
|
+
if (mod && mod.__esModule) return mod;
|
20
|
+
var result = {};
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
22
|
+
__setModuleDefault(result, mod);
|
23
|
+
return result;
|
24
|
+
};
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
27
|
+
};
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
29
|
+
exports.startServer = void 0;
|
30
|
+
const express_1 = __importDefault(require("express"));
|
31
|
+
const config_1 = require("../config");
|
32
|
+
const url_1 = __importStar(require("url"));
|
33
|
+
const node_fetch_1 = __importDefault(require("node-fetch"));
|
34
|
+
const utils_1 = require("../utils");
|
35
|
+
const key_1 = require("../key");
|
36
|
+
const chalk_1 = __importDefault(require("chalk"));
|
37
|
+
const os_1 = __importDefault(require("os"));
|
38
|
+
const crypto = __importStar(require("crypto"));
|
39
|
+
const app = (0, express_1.default)();
|
40
|
+
let server;
|
41
|
+
let authParams;
|
42
|
+
function startServer(params) {
|
43
|
+
authParams = params;
|
44
|
+
server = app.listen(params.serverPort);
|
45
|
+
}
|
46
|
+
exports.startServer = startServer;
|
47
|
+
app.get('/callback', async (req, res) => {
|
48
|
+
res.end('login success, please go back to CLI to continue');
|
49
|
+
const host = authParams.sentioHost;
|
50
|
+
const code = req.query.code;
|
51
|
+
if (!code || code.length == 0) {
|
52
|
+
return;
|
53
|
+
}
|
54
|
+
// exchange token
|
55
|
+
const tokenResRaw = await getToken(host, code);
|
56
|
+
if (!tokenResRaw.ok) {
|
57
|
+
console.error(chalk_1.default.red('request token error, code:', tokenResRaw.status, tokenResRaw.statusText));
|
58
|
+
return;
|
59
|
+
}
|
60
|
+
const tokenRes = await tokenResRaw.json();
|
61
|
+
const accessToken = tokenRes['access_token'];
|
62
|
+
// check if the account is ready
|
63
|
+
const realHost = (0, config_1.getFinalizedHost)(host);
|
64
|
+
const userResRaw = await getUser(realHost, accessToken);
|
65
|
+
if (!userResRaw.ok) {
|
66
|
+
if (userResRaw.status == 401) {
|
67
|
+
console.error(chalk_1.default.red('please sign up on sentio first'));
|
68
|
+
}
|
69
|
+
else {
|
70
|
+
console.error(chalk_1.default.red('get user error, code:', userResRaw.status, userResRaw.statusText));
|
71
|
+
}
|
72
|
+
return;
|
73
|
+
}
|
74
|
+
const userRes = await userResRaw.json();
|
75
|
+
if (!userRes.emailVerified) {
|
76
|
+
console.error(chalk_1.default.red('please verify your email first'));
|
77
|
+
return;
|
78
|
+
}
|
79
|
+
// create API key
|
80
|
+
const apiKeyName = `${os_1.default.hostname()}-${crypto.randomBytes(4).toString('hex')}`;
|
81
|
+
const createApiKeyResRaw = await createApiKey(realHost, apiKeyName, 'sdk_generated', accessToken);
|
82
|
+
if (!createApiKeyResRaw.ok) {
|
83
|
+
console.error(chalk_1.default.red('create api key error, code:', createApiKeyResRaw.status, createApiKeyResRaw.statusText));
|
84
|
+
return;
|
85
|
+
}
|
86
|
+
const createApiKeyRes = await createApiKeyResRaw.json();
|
87
|
+
const apiKey = createApiKeyRes['key'];
|
88
|
+
(0, key_1.WriteKey)(realHost, apiKey);
|
89
|
+
console.log(chalk_1.default.green('login success, new API key: ' + apiKey));
|
90
|
+
server.close();
|
91
|
+
});
|
92
|
+
async function getToken(host, code) {
|
93
|
+
const authConf = (0, config_1.getAuthConfig)(host);
|
94
|
+
const params = new url_1.default.URLSearchParams({
|
95
|
+
grant_type: 'authorization_code',
|
96
|
+
client_id: authConf.clientId,
|
97
|
+
code_verifier: authParams.codeVerifier,
|
98
|
+
code: code,
|
99
|
+
redirect_uri: `http://localhost:${authParams.serverPort}/callback`,
|
100
|
+
});
|
101
|
+
return (0, node_fetch_1.default)(`${authConf.domain}/oauth/token`, {
|
102
|
+
method: 'POST',
|
103
|
+
headers: {
|
104
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
105
|
+
},
|
106
|
+
body: params.toString(),
|
107
|
+
});
|
108
|
+
}
|
109
|
+
async function createApiKey(host, name, source, accessToken) {
|
110
|
+
const createApiKeyUrl = new url_1.URL('/api/v1/keys', host);
|
111
|
+
return (0, node_fetch_1.default)(createApiKeyUrl, {
|
112
|
+
method: 'POST',
|
113
|
+
headers: {
|
114
|
+
Authorization: 'Bearer ' + accessToken,
|
115
|
+
version: (0, utils_1.getCliVersion)(),
|
116
|
+
},
|
117
|
+
body: JSON.stringify({
|
118
|
+
name: name,
|
119
|
+
scopes: ['write:project'],
|
120
|
+
source: source,
|
121
|
+
}),
|
122
|
+
});
|
123
|
+
}
|
124
|
+
async function getUser(host, accessToken) {
|
125
|
+
const getUserUrl = new url_1.URL('/api/v1/users', host);
|
126
|
+
return (0, node_fetch_1.default)(getUserUrl, {
|
127
|
+
method: 'GET',
|
128
|
+
headers: {
|
129
|
+
Authorization: 'Bearer ' + accessToken,
|
130
|
+
version: (0, utils_1.getCliVersion)(),
|
131
|
+
},
|
132
|
+
});
|
133
|
+
}
|
134
|
+
//# sourceMappingURL=login-server.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"login-server.js","sourceRoot":"","sources":["../../../src/cli/commands/login-server.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAA6B;AAC7B,sCAA2D;AAC3D,2CAA8B;AAC9B,4DAA8B;AAC9B,oCAAwC;AACxC,gCAAiC;AACjC,kDAAyB;AAEzB,4CAAmB;AACnB,+CAAgC;AAQhC,MAAM,GAAG,GAAG,IAAA,iBAAO,GAAE,CAAA;AAErB,IAAI,MAAmB,CAAA;AACvB,IAAI,UAAsB,CAAA;AAE1B,SAAgB,WAAW,CAAC,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nimport { getAuthConfig, getFinalizedHost } from '../config'\nimport url, { URL } from 'url'\nimport fetch from 'node-fetch'\nimport { getCliVersion } from '../utils'\nimport { WriteKey } from '../key'\nimport chalk from 'chalk'\nimport http from 'http'\nimport os from 'os'\nimport * as crypto from 'crypto'\n\ninterface AuthParams {\n serverPort: number\n sentioHost: string\n codeVerifier: string\n}\n\nconst app = express()\n\nlet server: http.Server\nlet authParams: AuthParams\n\nexport function startServer(params: AuthParams) {\n authParams = params\n server = app.listen(params.serverPort)\n}\n\napp.get('/callback', async (req, res) => {\n res.end('login success, please go back to CLI to continue')\n const host = authParams.sentioHost\n const code = req.query.code\n if (!code || (code as string).length == 0) {\n return\n }\n\n // exchange token\n const tokenResRaw = await getToken(host, code as string)\n if (!tokenResRaw.ok) {\n console.error(chalk.red('request token error, code:', tokenResRaw.status, tokenResRaw.statusText))\n return\n }\n const tokenRes = await tokenResRaw.json()\n const accessToken = tokenRes['access_token']\n\n // check if the account is ready\n const realHost = getFinalizedHost(host)\n const userResRaw = await getUser(realHost, accessToken)\n if (!userResRaw.ok) {\n if (userResRaw.status == 401) {\n console.error(chalk.red('please sign up on sentio first'))\n } else {\n console.error(chalk.red('get user error, code:', userResRaw.status, userResRaw.statusText))\n }\n return\n }\n const userRes = await userResRaw.json()\n if (!userRes.emailVerified) {\n console.error(chalk.red('please verify your email first'))\n return\n }\n\n // create API key\n const apiKeyName = `${os.hostname()}-${crypto.randomBytes(4).toString('hex')}`\n const createApiKeyResRaw = await createApiKey(realHost, apiKeyName, 'sdk_generated', accessToken)\n if (!createApiKeyResRaw.ok) {\n console.error(chalk.red('create api key error, code:', createApiKeyResRaw.status, createApiKeyResRaw.statusText))\n return\n }\n const createApiKeyRes = await createApiKeyResRaw.json()\n const apiKey = createApiKeyRes['key']\n WriteKey(realHost, apiKey)\n console.log(chalk.green('login success, new API key: ' + apiKey))\n\n server.close()\n})\n\nasync function getToken(host: string, code: string) {\n const authConf = getAuthConfig(host)\n const params = new url.URLSearchParams({\n grant_type: 'authorization_code',\n client_id: authConf.clientId,\n code_verifier: authParams.codeVerifier,\n code: code,\n redirect_uri: `http://localhost:${authParams.serverPort}/callback`,\n })\n return fetch(`${authConf.domain}/oauth/token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: params.toString(),\n })\n}\n\nasync function createApiKey(host: string, name: string, source: string, accessToken: string) {\n const createApiKeyUrl = new URL('/api/v1/keys', host)\n return fetch(createApiKeyUrl, {\n method: 'POST',\n headers: {\n Authorization: 'Bearer ' + accessToken,\n version: getCliVersion(),\n },\n body: JSON.stringify({\n name: name,\n scopes: ['write:project'],\n source: source,\n }),\n })\n}\n\nasync function getUser(host: string, accessToken: string) {\n const getUserUrl = new URL('/api/v1/users', host)\n return fetch(getUserUrl, {\n method: 'GET',\n headers: {\n Authorization: 'Bearer ' + accessToken,\n version: getCliVersion(),\n },\n })\n}\n"]}
|
@@ -1,4 +1,27 @@
|
|
1
1
|
"use strict";
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
3
|
+
if (k2 === undefined) k2 = k;
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
7
|
+
}
|
8
|
+
Object.defineProperty(o, k2, desc);
|
9
|
+
}) : (function(o, m, k, k2) {
|
10
|
+
if (k2 === undefined) k2 = k;
|
11
|
+
o[k2] = m[k];
|
12
|
+
}));
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
15
|
+
}) : function(o, v) {
|
16
|
+
o["default"] = v;
|
17
|
+
});
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
19
|
+
if (mod && mod.__esModule) return mod;
|
20
|
+
var result = {};
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
22
|
+
__setModuleDefault(result, mod);
|
23
|
+
return result;
|
24
|
+
};
|
2
25
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
3
26
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
27
|
};
|
@@ -7,10 +30,13 @@ exports.runLogin = void 0;
|
|
7
30
|
const command_line_args_1 = __importDefault(require("command-line-args"));
|
8
31
|
const command_line_usage_1 = __importDefault(require("command-line-usage"));
|
9
32
|
const config_1 = require("../config");
|
33
|
+
const login_server_1 = require("./login-server");
|
34
|
+
const url_1 = __importStar(require("url"));
|
35
|
+
const crypto = __importStar(require("crypto"));
|
10
36
|
const chalk_1 = __importDefault(require("chalk"));
|
11
|
-
const https_1 = __importDefault(require("https"));
|
12
|
-
const http_1 = __importDefault(require("http"));
|
13
37
|
const key_1 = require("../key");
|
38
|
+
const node_fetch_1 = __importDefault(require("node-fetch"));
|
39
|
+
const port = 20000;
|
14
40
|
function runLogin(argv) {
|
15
41
|
const optionDefinitions = [
|
16
42
|
{
|
@@ -20,22 +46,22 @@ function runLogin(argv) {
|
|
20
46
|
description: 'Display this usage guide.',
|
21
47
|
},
|
22
48
|
{
|
23
|
-
name: '
|
49
|
+
name: 'host',
|
50
|
+
description: '(Optional) Override Sentio Host name',
|
24
51
|
type: String,
|
25
|
-
description: '(Required) Your API key',
|
26
52
|
},
|
27
53
|
{
|
28
|
-
name: '
|
29
|
-
description: '(Optional) Override Sentio Host name',
|
54
|
+
name: 'api-key',
|
30
55
|
type: String,
|
56
|
+
description: '(Optional) Your API key',
|
31
57
|
},
|
32
58
|
];
|
33
59
|
const options = (0, command_line_args_1.default)(optionDefinitions, { argv });
|
34
|
-
if (options.help
|
60
|
+
if (options.help) {
|
35
61
|
const usage = (0, command_line_usage_1.default)([
|
36
62
|
{
|
37
63
|
header: 'Login to Sentio',
|
38
|
-
content: 'sentio login
|
64
|
+
content: 'sentio login',
|
39
65
|
},
|
40
66
|
{
|
41
67
|
header: 'Options',
|
@@ -44,34 +70,58 @@ function runLogin(argv) {
|
|
44
70
|
]);
|
45
71
|
console.log(usage);
|
46
72
|
}
|
47
|
-
else {
|
73
|
+
else if (options['api-key']) {
|
48
74
|
const host = (0, config_1.getFinalizedHost)(options.host);
|
49
75
|
console.log(chalk_1.default.blue('login to ' + host));
|
50
|
-
const
|
51
|
-
|
52
|
-
|
53
|
-
|
54
|
-
path: '/api/v1/processors/check_key',
|
55
|
-
method: 'HEAD',
|
56
|
-
headers: {
|
57
|
-
'api-key': options['api-key'],
|
58
|
-
},
|
59
|
-
};
|
60
|
-
const h = url.protocol == 'https:' ? https_1.default : http_1.default;
|
61
|
-
const req = h.request(reqOptions, (res) => {
|
62
|
-
if (res.statusCode == 200) {
|
63
|
-
(0, key_1.WriteKey)(host, options['api-key']);
|
76
|
+
const apiKey = options['api-key'];
|
77
|
+
checkKey(host, apiKey).then((res) => {
|
78
|
+
if (res.status == 200) {
|
79
|
+
(0, key_1.WriteKey)(host, apiKey);
|
64
80
|
console.log(chalk_1.default.green('login success'));
|
65
81
|
}
|
66
82
|
else {
|
67
|
-
console.error(chalk_1.default.red('login failed, code:', res.
|
83
|
+
console.error(chalk_1.default.red('login failed, code:', res.status, res.statusText));
|
68
84
|
}
|
69
85
|
});
|
70
|
-
|
71
|
-
|
86
|
+
}
|
87
|
+
else {
|
88
|
+
// https://auth0.com/docs/get-started/authentication-and-authorization-flow/call-your-api-using-the-authorization-code-flow-with-pkce
|
89
|
+
const verifier = base64URLEncode(crypto.randomBytes(32));
|
90
|
+
const challenge = base64URLEncode(sha256(verifier));
|
91
|
+
const conf = (0, config_1.getAuthConfig)(options.host);
|
92
|
+
const authURL = new url_1.URL(conf.domain + `/authorize?`);
|
93
|
+
const params = new url_1.default.URLSearchParams({
|
94
|
+
response_type: 'code',
|
95
|
+
code_challenge: challenge,
|
96
|
+
code_challenge_method: 'S256',
|
97
|
+
client_id: conf.clientId,
|
98
|
+
redirect_uri: `http://localhost:${port}/callback`,
|
99
|
+
audience: conf.audience,
|
100
|
+
prompt: 'login',
|
101
|
+
});
|
102
|
+
authURL.search = params.toString();
|
103
|
+
console.log('Continue your authorization here: ' + authURL.toString());
|
104
|
+
(0, login_server_1.startServer)({
|
105
|
+
serverPort: port,
|
106
|
+
sentioHost: options.host,
|
107
|
+
codeVerifier: verifier,
|
72
108
|
});
|
73
|
-
req.end();
|
74
109
|
}
|
75
110
|
}
|
76
111
|
exports.runLogin = runLogin;
|
112
|
+
function base64URLEncode(str) {
|
113
|
+
return str.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
|
114
|
+
}
|
115
|
+
function sha256(str) {
|
116
|
+
return crypto.createHash('sha256').update(str).digest();
|
117
|
+
}
|
118
|
+
async function checkKey(host, apiKey) {
|
119
|
+
const checkApiKeyUrl = new url_1.URL('/api/v1/processors/check_key', host);
|
120
|
+
return (0, node_fetch_1.default)(checkApiKeyUrl, {
|
121
|
+
method: 'HEAD',
|
122
|
+
headers: {
|
123
|
+
'api-key': apiKey,
|
124
|
+
},
|
125
|
+
});
|
126
|
+
}
|
77
127
|
//# sourceMappingURL=run-login.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"run-login.js","sourceRoot":"","sources":["../../../src/cli/commands/run-login.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"run-login.js","sourceRoot":"","sources":["../../../src/cli/commands/run-login.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0EAA+C;AAC/C,4EAAiD;AACjD,sCAA2D;AAC3D,iDAA4C;AAC5C,2CAA8B;AAC9B,+CAAgC;AAChC,kDAAyB;AACzB,gCAAiC;AACjC,4DAA8B;AAE9B,MAAM,IAAI,GAAG,KAAK,CAAA;AAElB,SAAgB,QAAQ,CAAC,IAAc;IACrC,MAAM,iBAAiB,GAAG;QACxB;YACE,IAAI,EAAE,MAAM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,CAAA;AACzF,CAAC;AAED,SAAS,MAAM,CAAC,GAAW;IACzB,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAA;AACzD,CAAC;AAED,KAAK,UAAU,QAAQ,CAAC,IAAY,EAAE,MAAc;IAClD,MAAM,cAAc,GAAG,IAAI,SAAG,CAAC,8BAA8B,EAAE,IAAI,CAAC,CAAA;IACpE,OAAO,IAAA,oBAAK,EAAC,cAAc,EAAE;QAC3B,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACP,SAAS,EAAE,MAAM;SAClB;KACF,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import commandLineArgs from 'command-line-args'\nimport commandLineUsage from 'command-line-usage'\nimport { getAuthConfig, getFinalizedHost } from '../config'\nimport { startServer } from './login-server'\nimport url, { URL } from 'url'\nimport * as crypto from 'crypto'\nimport chalk from 'chalk'\nimport { WriteKey } from '../key'\nimport fetch from 'node-fetch'\n\nconst port = 20000\n\nexport function runLogin(argv: string[]) {\n const optionDefinitions = [\n {\n name: 'help',\n alias: 'h',\n type: Boolean,\n description: 'Display this usage guide.',\n },\n {\n name: 'host',\n description: '(Optional) Override Sentio Host name',\n type: String,\n },\n {\n name: 'api-key',\n type: String,\n description: '(Optional) Your API key',\n },\n ]\n const options = commandLineArgs(optionDefinitions, { argv })\n\n if (options.help) {\n const usage = commandLineUsage([\n {\n header: 'Login to Sentio',\n content: 'sentio login',\n },\n {\n header: 'Options',\n optionList: optionDefinitions,\n },\n ])\n console.log(usage)\n } else if (options['api-key']) {\n const host = getFinalizedHost(options.host)\n console.log(chalk.blue('login to ' + host))\n const apiKey = options['api-key']\n checkKey(host, apiKey).then((res) => {\n if (res.status == 200) {\n WriteKey(host, apiKey)\n console.log(chalk.green('login success'))\n } else {\n console.error(chalk.red('login failed, code:', res.status, res.statusText))\n }\n })\n } else {\n // https://auth0.com/docs/get-started/authentication-and-authorization-flow/call-your-api-using-the-authorization-code-flow-with-pkce\n const verifier = base64URLEncode(crypto.randomBytes(32))\n const challenge = base64URLEncode(sha256(verifier))\n\n const conf = getAuthConfig(options.host)\n const authURL = new URL(conf.domain + `/authorize?`)\n const params = new url.URLSearchParams({\n response_type: 'code',\n code_challenge: challenge,\n code_challenge_method: 'S256',\n client_id: conf.clientId,\n redirect_uri: `http://localhost:${port}/callback`,\n audience: conf.audience,\n prompt: 'login',\n })\n authURL.search = params.toString()\n console.log('Continue your authorization here: ' + authURL.toString())\n\n startServer({\n serverPort: port,\n sentioHost: options.host,\n codeVerifier: verifier,\n })\n }\n}\n\nfunction base64URLEncode(str: Buffer) {\n return str.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n}\n\nfunction sha256(str: string) {\n return crypto.createHash('sha256').update(str).digest()\n}\n\nasync function checkKey(host: string, apiKey: string) {\n const checkApiKeyUrl = new URL('/api/v1/processors/check_key', host)\n return fetch(checkApiKeyUrl, {\n method: 'HEAD',\n headers: {\n 'api-key': apiKey,\n },\n })\n}\n"]}
|
package/lib/cli/config.d.ts
CHANGED
@@ -4,5 +4,10 @@ export interface SentioProjectConfig {
|
|
4
4
|
build: boolean;
|
5
5
|
}
|
6
6
|
export declare function getFinalizedHost(host: string): string;
|
7
|
+
export declare function getAuthConfig(host: string): {
|
8
|
+
domain: string;
|
9
|
+
clientId: string;
|
10
|
+
audience: string;
|
11
|
+
};
|
7
12
|
export declare function finalizeHost(config: SentioProjectConfig): void;
|
8
13
|
export declare function FinalizeProjectName(config: SentioProjectConfig, owner: string | undefined): void;
|
package/lib/cli/config.js
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.FinalizeProjectName = exports.finalizeHost = exports.getFinalizedHost = void 0;
|
3
|
+
exports.FinalizeProjectName = exports.finalizeHost = exports.getAuthConfig = exports.getFinalizedHost = void 0;
|
4
4
|
function getFinalizedHost(host) {
|
5
5
|
switch (host) {
|
6
6
|
case undefined:
|
@@ -17,6 +17,33 @@ function getFinalizedHost(host) {
|
|
17
17
|
return host;
|
18
18
|
}
|
19
19
|
exports.getFinalizedHost = getFinalizedHost;
|
20
|
+
function getAuthConfig(host) {
|
21
|
+
let domain = '', clientId = '', audience = '';
|
22
|
+
switch (host) {
|
23
|
+
case 'local':
|
24
|
+
domain = 'https://sentio-dev.us.auth0.com';
|
25
|
+
clientId = 'qGDisObqQbcPeRA8k02POPZ2Df4KVCna';
|
26
|
+
audience = 'http://localhost:8080/v1';
|
27
|
+
break;
|
28
|
+
case '':
|
29
|
+
case undefined:
|
30
|
+
case 'prod':
|
31
|
+
domain = 'https://auth.sentio.xyz';
|
32
|
+
clientId = 'xd80PeuvuZVHpBFh7yEdlSZdtE5mTpGe';
|
33
|
+
audience = 'https://app.sentio.xyz/api/v1';
|
34
|
+
break;
|
35
|
+
case 'test':
|
36
|
+
case 'staging':
|
37
|
+
domain = 'https://auth.test.sentio.xyz';
|
38
|
+
clientId = 'qXVvovHaOE37SndxTZJxCKgZjw1axPax';
|
39
|
+
audience = 'https://test.sentio.xyz/api/v1';
|
40
|
+
break;
|
41
|
+
default:
|
42
|
+
break;
|
43
|
+
}
|
44
|
+
return { domain, clientId, audience };
|
45
|
+
}
|
46
|
+
exports.getAuthConfig = getAuthConfig;
|
20
47
|
function finalizeHost(config) {
|
21
48
|
config.host = getFinalizedHost(config.host);
|
22
49
|
}
|
package/lib/cli/config.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/cli/config.ts"],"names":[],"mappings":";;;AAQA,SAAgB,gBAAgB,CAAC,IAAY;IAC3C,QAAQ,IAAI,EAAE;QACZ,KAAK,SAAS,CAAC;QACf,KAAK,EAAE,CAAC;QACR,KAAK,MAAM;YACT,OAAO,wBAAwB,CAAA;QACjC,KAAK,MAAM;YACT,OAAO,yBAAyB,CAAA;QAClC,KAAK,SAAS;YACZ,OAAO,4BAA4B,CAAA;QACrC,KAAK,OAAO;YACV,OAAO,wBAAwB,CAAA;KAClC;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAdD,4CAcC;AAED,SAAgB,YAAY,CAAC,MAA2B;IACtD,MAAM,CAAC,IAAI,GAAG,gBAAgB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;AAC7C,CAAC;AAFD,oCAEC;AAED,SAAgB,mBAAmB,CAAC,MAA2B,EAAE,KAAyB;IACxF,IAAI,KAAK,EAAE;QACT,IAAI,IAAI,GAAG,MAAM,CAAC,OAAO,CAAA;QACzB,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YACtB,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;SACpC;QACD,MAAM,CAAC,OAAO,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;KACzC;AACH,CAAC;AARD,kDAQC;AAED,4BAA4B;AAC5B,kBAAkB;AAClB,qBAAqB;AACrB,IAAI;AACJ,EAAE;AACF,wCAAwC;AACxC,2BAA2B;AAC3B,iCAAiC","sourcesContent":["export interface SentioProjectConfig {\n project: string\n host: string\n // source: string\n build: boolean\n // targets: Target[]\n}\n\nexport function getFinalizedHost(host: string): string {\n switch (host) {\n case undefined:\n case '':\n case 'prod':\n return 'https://app.sentio.xyz'\n case 'test':\n return 'https://test.sentio.xyz'\n case 'staging':\n return 'https://staging.sentio.xyz'\n case 'local':\n return 'http://localhost:10000'\n }\n return host\n}\n\nexport function finalizeHost(config: SentioProjectConfig) {\n config.host = getFinalizedHost(config.host)\n}\n\nexport function FinalizeProjectName(config: SentioProjectConfig, owner: string | undefined) {\n if (owner) {\n let name = config.project\n if (name.includes('/')) {\n name = config.project.split('/')[1]\n }\n config.project = [owner, name].join('/')\n }\n}\n\n// export interface Target {\n// chain: string\n// abisDir?: string\n// }\n//\n// // Supported target chain, lower case\n// export const EVM = 'evm'\n// export const SOLANA = 'solana'\n"]}
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/cli/config.ts"],"names":[],"mappings":";;;AAQA,SAAgB,gBAAgB,CAAC,IAAY;IAC3C,QAAQ,IAAI,EAAE;QACZ,KAAK,SAAS,CAAC;QACf,KAAK,EAAE,CAAC;QACR,KAAK,MAAM;YACT,OAAO,wBAAwB,CAAA;QACjC,KAAK,MAAM;YACT,OAAO,yBAAyB,CAAA;QAClC,KAAK,SAAS;YACZ,OAAO,4BAA4B,CAAA;QACrC,KAAK,OAAO;YACV,OAAO,wBAAwB,CAAA;KAClC;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAdD,4CAcC;AAED,SAAgB,aAAa,CAAC,IAAY;IACxC,IAAI,MAAM,GAAG,EAAE,EACb,QAAQ,GAAG,EAAE,EACb,QAAQ,GAAG,EAAE,CAAA;IACf,QAAQ,IAAI,EAAE;QACZ,KAAK,OAAO;YACV,MAAM,GAAG,iCAAiC,CAAA;YAC1C,QAAQ,GAAG,kCAAkC,CAAA;YAC7C,QAAQ,GAAG,0BAA0B,CAAA;YACrC,MAAK;QACP,KAAK,EAAE,CAAC;QACR,KAAK,SAAS,CAAC;QACf,KAAK,MAAM;YACT,MAAM,GAAG,yBAAyB,CAAA;YAClC,QAAQ,GAAG,kCAAkC,CAAA;YAC7C,QAAQ,GAAG,+BAA+B,CAAA;YAC1C,MAAK;QACP,KAAK,MAAM,CAAC;QACZ,KAAK,SAAS;YACZ,MAAM,GAAG,8BAA8B,CAAA;YACvC,QAAQ,GAAG,kCAAkC,CAAA;YAC7C,QAAQ,GAAG,gCAAgC,CAAA;YAC3C,MAAK;QACP;YACE,MAAK;KACR;IACD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAA;AACvC,CAAC;AA3BD,sCA2BC;AAED,SAAgB,YAAY,CAAC,MAA2B;IACtD,MAAM,CAAC,IAAI,GAAG,gBAAgB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;AAC7C,CAAC;AAFD,oCAEC;AAED,SAAgB,mBAAmB,CAAC,MAA2B,EAAE,KAAyB;IACxF,IAAI,KAAK,EAAE;QACT,IAAI,IAAI,GAAG,MAAM,CAAC,OAAO,CAAA;QACzB,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YACtB,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;SACpC;QACD,MAAM,CAAC,OAAO,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;KACzC;AACH,CAAC;AARD,kDAQC;AAED,4BAA4B;AAC5B,kBAAkB;AAClB,qBAAqB;AACrB,IAAI;AACJ,EAAE;AACF,wCAAwC;AACxC,2BAA2B;AAC3B,iCAAiC","sourcesContent":["export interface SentioProjectConfig {\n project: string\n host: string\n // source: string\n build: boolean\n // targets: Target[]\n}\n\nexport function getFinalizedHost(host: string): string {\n switch (host) {\n case undefined:\n case '':\n case 'prod':\n return 'https://app.sentio.xyz'\n case 'test':\n return 'https://test.sentio.xyz'\n case 'staging':\n return 'https://staging.sentio.xyz'\n case 'local':\n return 'http://localhost:10000'\n }\n return host\n}\n\nexport function getAuthConfig(host: string): { domain: string; clientId: string; audience: string } {\n let domain = '',\n clientId = '',\n audience = ''\n switch (host) {\n case 'local':\n domain = 'https://sentio-dev.us.auth0.com'\n clientId = 'qGDisObqQbcPeRA8k02POPZ2Df4KVCna'\n audience = 'http://localhost:8080/v1'\n break\n case '':\n case undefined:\n case 'prod':\n domain = 'https://auth.sentio.xyz'\n clientId = 'xd80PeuvuZVHpBFh7yEdlSZdtE5mTpGe'\n audience = 'https://app.sentio.xyz/api/v1'\n break\n case 'test':\n case 'staging':\n domain = 'https://auth.test.sentio.xyz'\n clientId = 'qXVvovHaOE37SndxTZJxCKgZjw1axPax'\n audience = 'https://test.sentio.xyz/api/v1'\n break\n default:\n break\n }\n return { domain, clientId, audience }\n}\n\nexport function finalizeHost(config: SentioProjectConfig) {\n config.host = getFinalizedHost(config.host)\n}\n\nexport function FinalizeProjectName(config: SentioProjectConfig, owner: string | undefined) {\n if (owner) {\n let name = config.project\n if (name.includes('/')) {\n name = config.project.split('/')[1]\n }\n config.project = [owner, name].join('/')\n }\n}\n\n// export interface Target {\n// chain: string\n// abisDir?: string\n// }\n//\n// // Supported target chain, lower case\n// export const EVM = 'evm'\n// export const SOLANA = 'solana'\n"]}
|
package/package.json
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"name": "@sentio/sdk",
|
3
3
|
"license": "Apache-2.0",
|
4
|
-
"version": "1.
|
4
|
+
"version": "1.27.0",
|
5
5
|
"scripts": {
|
6
6
|
"compile_target": "yarn tsc -b src/target-ethers-sentio/tsconfig.json",
|
7
7
|
"compile": "tsc -p . && cp src/cli/webpack.config.js lib/cli && cp src/utils/*.csv lib/utils",
|
@@ -25,6 +25,7 @@
|
|
25
25
|
"@solana/web3.js": "^1.47.3",
|
26
26
|
"@typechain/ethers-v5": "^10.0.0",
|
27
27
|
"@types/bn.js": "^5.1.0",
|
28
|
+
"@types/express": "^4.17.14",
|
28
29
|
"@types/node-fetch": "^2.6.2",
|
29
30
|
"aptos-sdk": "npm:aptos@^1.3.16",
|
30
31
|
"bignumber.js": "^9.1.0",
|
@@ -34,6 +35,7 @@
|
|
34
35
|
"command-line-usage": "^6.1.3",
|
35
36
|
"csv-parse": "^5.3.0",
|
36
37
|
"ethers": "~5.7.1",
|
38
|
+
"express": "^4.18.2",
|
37
39
|
"form-data": "^4.0.0",
|
38
40
|
"fs-extra": "^10.1.0",
|
39
41
|
"google-protobuf": "^3.15.8",
|
@@ -78,5 +80,8 @@
|
|
78
80
|
"lib/**/*",
|
79
81
|
"src/**/*",
|
80
82
|
"templates/**/*"
|
81
|
-
]
|
83
|
+
],
|
84
|
+
"engines": {
|
85
|
+
"node": ">=16"
|
86
|
+
}
|
82
87
|
}
|
@@ -251,9 +251,9 @@ export class AptosAccountProcessor {
|
|
251
251
|
public onTimeInterval(
|
252
252
|
handler: (resources: MoveResource[], ctx: AptosResourceContext) => void,
|
253
253
|
timeIntervalInMinutes = 60,
|
254
|
-
|
254
|
+
type?: string
|
255
255
|
) {
|
256
|
-
return this.onInterval(handler, timeIntervalInMinutes, undefined,
|
256
|
+
return this.onInterval(handler, timeIntervalInMinutes, undefined, type)
|
257
257
|
}
|
258
258
|
|
259
259
|
public onVersionInterval(
|
package/src/aptos/index.ts
CHANGED
@@ -3,5 +3,5 @@ export type { EventInstance, TypedEventInstance, TypedEntryFunctionPayload } fro
|
|
3
3
|
export { TYPE_REGISTRY, TypeRegistry } from './types'
|
4
4
|
export type { FunctionNameAndCallFilter, EventFilter, CallFilter, ArgumentsFilter } from './aptos-processor'
|
5
5
|
export { AptosBaseProcessor, AptosAccountProcessor } from './aptos-processor'
|
6
|
-
export { AptosContext } from './context'
|
6
|
+
export { AptosContext, AptosResourceContext } from './context'
|
7
7
|
export { AptosBindOptions, AptosNetwork, getRpcClient } from './network'
|
@@ -56,7 +56,7 @@ export async function generateForNetwork(srcDir: string, outputDir: string, netw
|
|
56
56
|
|
57
57
|
while (loader.pendingAccounts.size > 0) {
|
58
58
|
for (const account of loader.pendingAccounts) {
|
59
|
-
console.log(`download
|
59
|
+
console.log(`download dependent module for account ${account} at ${getChainName(network)}`)
|
60
60
|
|
61
61
|
try {
|
62
62
|
const modules = await client.getAccountModules(account)
|
@@ -387,27 +387,6 @@ function getEventStructs(module: MoveModule) {
|
|
387
387
|
return eventMap
|
388
388
|
}
|
389
389
|
|
390
|
-
function isEvent(struct: MoveStruct, module: MoveModule) {
|
391
|
-
const hasAbility = struct.abilities.includes('drop') && struct.abilities.includes('store')
|
392
|
-
|
393
|
-
if (!hasAbility) {
|
394
|
-
return false
|
395
|
-
}
|
396
|
-
if (struct.name.endsWith('Event')) {
|
397
|
-
return true
|
398
|
-
}
|
399
|
-
|
400
|
-
// for (const struct of module.structs) {
|
401
|
-
// for (const field of struct.fields) {
|
402
|
-
// if (field.type.startsWith('0x1::event::EventHandle')
|
403
|
-
// }
|
404
|
-
// }
|
405
|
-
|
406
|
-
return false
|
407
|
-
|
408
|
-
//&&
|
409
|
-
}
|
410
|
-
|
411
390
|
function generateOnEvents(module: MoveModule, struct: MoveStruct): string {
|
412
391
|
// for struct that has drop + store
|
413
392
|
// if (!isEvent(struct, module)) {
|
package/src/cli/cli.ts
CHANGED
@@ -10,9 +10,9 @@ import { finalizeHost, FinalizeProjectName, SentioProjectConfig } from './config
|
|
10
10
|
import { uploadFile } from './upload'
|
11
11
|
import chalk from 'chalk'
|
12
12
|
import { buildProcessor } from './build'
|
13
|
-
import { runLogin } from './commands/run-login'
|
14
13
|
import { runCreate } from './commands/run-create'
|
15
14
|
import { runVersion } from './commands/run-version'
|
15
|
+
import { runLogin } from './commands/run-login'
|
16
16
|
|
17
17
|
const mainDefinitions = [{ name: 'command', defaultOption: true }]
|
18
18
|
const mainOptions = commandLineArgs(mainDefinitions, {
|
@@ -159,12 +159,12 @@ function usage() {
|
|
159
159
|
header: 'Usage',
|
160
160
|
content: [
|
161
161
|
'sentio <command> --help\t\tshow detail usage of specific command',
|
162
|
-
'sentio login
|
162
|
+
'sentio login\t\t\t\tlogin to sentio',
|
163
163
|
'sentio create\t\t\t\tcreate a template project',
|
164
164
|
'sentio upload\t\t\t\tbuild and upload processor to sentio',
|
165
165
|
'sentio gen\t\t\t\tgenerate abi',
|
166
166
|
'sentio build\t\t\t\tgenerate abi and build',
|
167
|
-
'sentio version\t\t\
|
167
|
+
'sentio version\t\t\tcurrent cli version',
|
168
168
|
],
|
169
169
|
},
|
170
170
|
])
|
@@ -0,0 +1,120 @@
|
|
1
|
+
import express from 'express'
|
2
|
+
import { getAuthConfig, getFinalizedHost } from '../config'
|
3
|
+
import url, { URL } from 'url'
|
4
|
+
import fetch from 'node-fetch'
|
5
|
+
import { getCliVersion } from '../utils'
|
6
|
+
import { WriteKey } from '../key'
|
7
|
+
import chalk from 'chalk'
|
8
|
+
import http from 'http'
|
9
|
+
import os from 'os'
|
10
|
+
import * as crypto from 'crypto'
|
11
|
+
|
12
|
+
interface AuthParams {
|
13
|
+
serverPort: number
|
14
|
+
sentioHost: string
|
15
|
+
codeVerifier: string
|
16
|
+
}
|
17
|
+
|
18
|
+
const app = express()
|
19
|
+
|
20
|
+
let server: http.Server
|
21
|
+
let authParams: AuthParams
|
22
|
+
|
23
|
+
export function startServer(params: AuthParams) {
|
24
|
+
authParams = params
|
25
|
+
server = app.listen(params.serverPort)
|
26
|
+
}
|
27
|
+
|
28
|
+
app.get('/callback', async (req, res) => {
|
29
|
+
res.end('login success, please go back to CLI to continue')
|
30
|
+
const host = authParams.sentioHost
|
31
|
+
const code = req.query.code
|
32
|
+
if (!code || (code as string).length == 0) {
|
33
|
+
return
|
34
|
+
}
|
35
|
+
|
36
|
+
// exchange token
|
37
|
+
const tokenResRaw = await getToken(host, code as string)
|
38
|
+
if (!tokenResRaw.ok) {
|
39
|
+
console.error(chalk.red('request token error, code:', tokenResRaw.status, tokenResRaw.statusText))
|
40
|
+
return
|
41
|
+
}
|
42
|
+
const tokenRes = await tokenResRaw.json()
|
43
|
+
const accessToken = tokenRes['access_token']
|
44
|
+
|
45
|
+
// check if the account is ready
|
46
|
+
const realHost = getFinalizedHost(host)
|
47
|
+
const userResRaw = await getUser(realHost, accessToken)
|
48
|
+
if (!userResRaw.ok) {
|
49
|
+
if (userResRaw.status == 401) {
|
50
|
+
console.error(chalk.red('please sign up on sentio first'))
|
51
|
+
} else {
|
52
|
+
console.error(chalk.red('get user error, code:', userResRaw.status, userResRaw.statusText))
|
53
|
+
}
|
54
|
+
return
|
55
|
+
}
|
56
|
+
const userRes = await userResRaw.json()
|
57
|
+
if (!userRes.emailVerified) {
|
58
|
+
console.error(chalk.red('please verify your email first'))
|
59
|
+
return
|
60
|
+
}
|
61
|
+
|
62
|
+
// create API key
|
63
|
+
const apiKeyName = `${os.hostname()}-${crypto.randomBytes(4).toString('hex')}`
|
64
|
+
const createApiKeyResRaw = await createApiKey(realHost, apiKeyName, 'sdk_generated', accessToken)
|
65
|
+
if (!createApiKeyResRaw.ok) {
|
66
|
+
console.error(chalk.red('create api key error, code:', createApiKeyResRaw.status, createApiKeyResRaw.statusText))
|
67
|
+
return
|
68
|
+
}
|
69
|
+
const createApiKeyRes = await createApiKeyResRaw.json()
|
70
|
+
const apiKey = createApiKeyRes['key']
|
71
|
+
WriteKey(realHost, apiKey)
|
72
|
+
console.log(chalk.green('login success, new API key: ' + apiKey))
|
73
|
+
|
74
|
+
server.close()
|
75
|
+
})
|
76
|
+
|
77
|
+
async function getToken(host: string, code: string) {
|
78
|
+
const authConf = getAuthConfig(host)
|
79
|
+
const params = new url.URLSearchParams({
|
80
|
+
grant_type: 'authorization_code',
|
81
|
+
client_id: authConf.clientId,
|
82
|
+
code_verifier: authParams.codeVerifier,
|
83
|
+
code: code,
|
84
|
+
redirect_uri: `http://localhost:${authParams.serverPort}/callback`,
|
85
|
+
})
|
86
|
+
return fetch(`${authConf.domain}/oauth/token`, {
|
87
|
+
method: 'POST',
|
88
|
+
headers: {
|
89
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
90
|
+
},
|
91
|
+
body: params.toString(),
|
92
|
+
})
|
93
|
+
}
|
94
|
+
|
95
|
+
async function createApiKey(host: string, name: string, source: string, accessToken: string) {
|
96
|
+
const createApiKeyUrl = new URL('/api/v1/keys', host)
|
97
|
+
return fetch(createApiKeyUrl, {
|
98
|
+
method: 'POST',
|
99
|
+
headers: {
|
100
|
+
Authorization: 'Bearer ' + accessToken,
|
101
|
+
version: getCliVersion(),
|
102
|
+
},
|
103
|
+
body: JSON.stringify({
|
104
|
+
name: name,
|
105
|
+
scopes: ['write:project'],
|
106
|
+
source: source,
|
107
|
+
}),
|
108
|
+
})
|
109
|
+
}
|
110
|
+
|
111
|
+
async function getUser(host: string, accessToken: string) {
|
112
|
+
const getUserUrl = new URL('/api/v1/users', host)
|
113
|
+
return fetch(getUserUrl, {
|
114
|
+
method: 'GET',
|
115
|
+
headers: {
|
116
|
+
Authorization: 'Bearer ' + accessToken,
|
117
|
+
version: getCliVersion(),
|
118
|
+
},
|
119
|
+
})
|
120
|
+
}
|
@@ -1,10 +1,14 @@
|
|
1
1
|
import commandLineArgs from 'command-line-args'
|
2
2
|
import commandLineUsage from 'command-line-usage'
|
3
|
-
import { getFinalizedHost } from '../config'
|
3
|
+
import { getAuthConfig, getFinalizedHost } from '../config'
|
4
|
+
import { startServer } from './login-server'
|
5
|
+
import url, { URL } from 'url'
|
6
|
+
import * as crypto from 'crypto'
|
4
7
|
import chalk from 'chalk'
|
5
|
-
import https from 'https'
|
6
|
-
import http from 'http'
|
7
8
|
import { WriteKey } from '../key'
|
9
|
+
import fetch from 'node-fetch'
|
10
|
+
|
11
|
+
const port = 20000
|
8
12
|
|
9
13
|
export function runLogin(argv: string[]) {
|
10
14
|
const optionDefinitions = [
|
@@ -15,23 +19,23 @@ export function runLogin(argv: string[]) {
|
|
15
19
|
description: 'Display this usage guide.',
|
16
20
|
},
|
17
21
|
{
|
18
|
-
name: '
|
22
|
+
name: 'host',
|
23
|
+
description: '(Optional) Override Sentio Host name',
|
19
24
|
type: String,
|
20
|
-
description: '(Required) Your API key',
|
21
25
|
},
|
22
26
|
{
|
23
|
-
name: '
|
24
|
-
description: '(Optional) Override Sentio Host name',
|
27
|
+
name: 'api-key',
|
25
28
|
type: String,
|
29
|
+
description: '(Optional) Your API key',
|
26
30
|
},
|
27
31
|
]
|
28
32
|
const options = commandLineArgs(optionDefinitions, { argv })
|
29
33
|
|
30
|
-
if (options.help
|
34
|
+
if (options.help) {
|
31
35
|
const usage = commandLineUsage([
|
32
36
|
{
|
33
37
|
header: 'Login to Sentio',
|
34
|
-
content: 'sentio login
|
38
|
+
content: 'sentio login',
|
35
39
|
},
|
36
40
|
{
|
37
41
|
header: 'Options',
|
@@ -39,32 +43,59 @@ export function runLogin(argv: string[]) {
|
|
39
43
|
},
|
40
44
|
])
|
41
45
|
console.log(usage)
|
42
|
-
} else {
|
46
|
+
} else if (options['api-key']) {
|
43
47
|
const host = getFinalizedHost(options.host)
|
44
48
|
console.log(chalk.blue('login to ' + host))
|
45
|
-
const
|
46
|
-
|
47
|
-
|
48
|
-
|
49
|
-
path: '/api/v1/processors/check_key',
|
50
|
-
method: 'HEAD',
|
51
|
-
headers: {
|
52
|
-
'api-key': options['api-key'],
|
53
|
-
},
|
54
|
-
}
|
55
|
-
const h = url.protocol == 'https:' ? https : http
|
56
|
-
const req = h.request(reqOptions, (res) => {
|
57
|
-
if (res.statusCode == 200) {
|
58
|
-
WriteKey(host, options['api-key'])
|
49
|
+
const apiKey = options['api-key']
|
50
|
+
checkKey(host, apiKey).then((res) => {
|
51
|
+
if (res.status == 200) {
|
52
|
+
WriteKey(host, apiKey)
|
59
53
|
console.log(chalk.green('login success'))
|
60
54
|
} else {
|
61
|
-
console.error(chalk.red('login failed, code:', res.
|
55
|
+
console.error(chalk.red('login failed, code:', res.status, res.statusText))
|
62
56
|
}
|
63
57
|
})
|
58
|
+
} else {
|
59
|
+
// https://auth0.com/docs/get-started/authentication-and-authorization-flow/call-your-api-using-the-authorization-code-flow-with-pkce
|
60
|
+
const verifier = base64URLEncode(crypto.randomBytes(32))
|
61
|
+
const challenge = base64URLEncode(sha256(verifier))
|
64
62
|
|
65
|
-
|
66
|
-
|
63
|
+
const conf = getAuthConfig(options.host)
|
64
|
+
const authURL = new URL(conf.domain + `/authorize?`)
|
65
|
+
const params = new url.URLSearchParams({
|
66
|
+
response_type: 'code',
|
67
|
+
code_challenge: challenge,
|
68
|
+
code_challenge_method: 'S256',
|
69
|
+
client_id: conf.clientId,
|
70
|
+
redirect_uri: `http://localhost:${port}/callback`,
|
71
|
+
audience: conf.audience,
|
72
|
+
prompt: 'login',
|
73
|
+
})
|
74
|
+
authURL.search = params.toString()
|
75
|
+
console.log('Continue your authorization here: ' + authURL.toString())
|
76
|
+
|
77
|
+
startServer({
|
78
|
+
serverPort: port,
|
79
|
+
sentioHost: options.host,
|
80
|
+
codeVerifier: verifier,
|
67
81
|
})
|
68
|
-
req.end()
|
69
82
|
}
|
70
83
|
}
|
84
|
+
|
85
|
+
function base64URLEncode(str: Buffer) {
|
86
|
+
return str.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
|
87
|
+
}
|
88
|
+
|
89
|
+
function sha256(str: string) {
|
90
|
+
return crypto.createHash('sha256').update(str).digest()
|
91
|
+
}
|
92
|
+
|
93
|
+
async function checkKey(host: string, apiKey: string) {
|
94
|
+
const checkApiKeyUrl = new URL('/api/v1/processors/check_key', host)
|
95
|
+
return fetch(checkApiKeyUrl, {
|
96
|
+
method: 'HEAD',
|
97
|
+
headers: {
|
98
|
+
'api-key': apiKey,
|
99
|
+
},
|
100
|
+
})
|
101
|
+
}
|
package/src/cli/config.ts
CHANGED
@@ -22,6 +22,35 @@ export function getFinalizedHost(host: string): string {
|
|
22
22
|
return host
|
23
23
|
}
|
24
24
|
|
25
|
+
export function getAuthConfig(host: string): { domain: string; clientId: string; audience: string } {
|
26
|
+
let domain = '',
|
27
|
+
clientId = '',
|
28
|
+
audience = ''
|
29
|
+
switch (host) {
|
30
|
+
case 'local':
|
31
|
+
domain = 'https://sentio-dev.us.auth0.com'
|
32
|
+
clientId = 'qGDisObqQbcPeRA8k02POPZ2Df4KVCna'
|
33
|
+
audience = 'http://localhost:8080/v1'
|
34
|
+
break
|
35
|
+
case '':
|
36
|
+
case undefined:
|
37
|
+
case 'prod':
|
38
|
+
domain = 'https://auth.sentio.xyz'
|
39
|
+
clientId = 'xd80PeuvuZVHpBFh7yEdlSZdtE5mTpGe'
|
40
|
+
audience = 'https://app.sentio.xyz/api/v1'
|
41
|
+
break
|
42
|
+
case 'test':
|
43
|
+
case 'staging':
|
44
|
+
domain = 'https://auth.test.sentio.xyz'
|
45
|
+
clientId = 'qXVvovHaOE37SndxTZJxCKgZjw1axPax'
|
46
|
+
audience = 'https://test.sentio.xyz/api/v1'
|
47
|
+
break
|
48
|
+
default:
|
49
|
+
break
|
50
|
+
}
|
51
|
+
return { domain, clientId, audience }
|
52
|
+
}
|
53
|
+
|
25
54
|
export function finalizeHost(config: SentioProjectConfig) {
|
26
55
|
config.host = getFinalizedHost(config.host)
|
27
56
|
}
|