diff --git a/README.md b/README.md
index 942d1b6c..ab97dad2 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ This package can be used in both browser and Node.js environments.
- [Quick Start](#quick-start)
- [Examples](#examples)
- [Modules](#modules)
- - [Auth](#auth)
+ - [Auth](#authentication)
- [Vault](#vault)
- [Membership](#membership)
- [Memo](#memo)
@@ -38,13 +38,10 @@ const { Akord } = require("@akord/akord-js");
### Quick start
#### Init Akord
-##### with email & password
```js
-const { akord, wallet, jwtToken } = await Akord.auth.signIn(email, password);
-```
-##### with Akord Wallet & JWT
-```js
-const akord = await Akord.init(wallet, jwtToken);
+import { Akord, Auth } from "@akord/akord-js";
+const { wallet } = await Auth.signIn(email, password);
+const akord = await Akord.init(wallet);
```
#### Create vault
@@ -64,29 +61,59 @@ const { data: fileBuffer, name: fileName } = await akord.stack.getVersion(stackI
#### Query user vaults
```js
-const vaults = await akord.vault.list();
+const vaults = await akord.vault.listAll();
```
### Examples
-See our [demo app tutorial](https://akord-js-tutorial.akord.com) and learn how to create,
-contribute and access an Akord Vault.\
-We also have some example flows in our [tests](src/__tests__) repository.
+- See our [demo app tutorial](https://akord-js-tutorial.akord.com) and learn how to create,
+contribute and access an Akord Vault from .\
-## Modules
+- See example flows in our [tests repo](src/__tests__).
+
+- See different setups on [recipes repo](https://github.com/Akord-com/recipes).
+
+## Authentication
+Use `Auth` module to handle authentication.
-### auth
+```js
+import { Auth } from "@akord/akord-js";
+```
+
+- By default `Auth` is using SRP authentication
+- `Auth` stores tokens in `Storage` implementation
+- `Storage` defaults to localStorage on web & memoryStorage on nodeJs
+- `Storage` implementation can be configured with `Auth.configure({ storage: window.sessionStorage })`
+- `Auth` is automatically refreshing tokens in SRP mode
+- On server side it is recommended to use API keys: `Auth.configure({ apiKey: 'your_api_key' })`
+- API key: can be generated over web app & over CLI
+
+##### use short living token with refresh
+```js
+import { Auth } from "@akord/akord-js";
+Auth.configure({ storage: window.sessionStorage }); // optionally - configure tokens store
+```
+##### use API key
+```js
+import { Auth } from "@akord/akord-js";
+Auth.configure({ apiKey: "api_key" });
+```
+##### use self-managed auth token
+```js
+import { Akord, Auth } from "@akord/akord-js";
+Auth.configure({ authToken: "auth_token" });
+```
#### `signIn(email, password)`
- `email` (`string`, required)
- `password` (`string`, required)
-- returns `Promise<{ akord, wallet, jwtToken }>` - Promise with Akord Client instance, JWT token & Akord Wallet
+- returns `Promise<{ wallet, jwt }>` - Promise with JWT token & Akord Wallet
example
```js
-const { akord, wallet, jwtToken } = await Akord.auth.signIn("winston@gmail.com", "1984");
+const { wallet } = await Auth.signIn("winston@gmail.com", "1984");
```
@@ -95,13 +122,13 @@ const { akord, wallet, jwtToken } = await Akord.auth.signIn("winston@gmail.com",
- `email` (`string`, required)
- `password` (`string`, required)
- `clientMetadata` (`any`, optional) - JSON client metadata, ex: { clientType: "CLI" }
-- returns `Promise` - Promise with Akord Wallet
+- returns `Promise<{ wallet }>` - Promise with Akord Wallet
example
```js
-const wallet = await Akord.auth.signUp("winston@gmail.com", "1984");
+const { wallet } = await Auth.signUp("winston@gmail.com", "1984");
```
@@ -115,24 +142,33 @@ const wallet = await Akord.auth.signUp("winston@gmail.com", "1984");
example
```js
-await Akord.auth.verifyAccount("winston@gmail.com", 123456);
+await Auth.verifyAccount("winston@gmail.com", 123456);
```
+
+## Modules
+
### vault
-#### `create(name, termsOfAccess, isPublic)`
+#### `create(name, options)`
- `name` (`string`, required) - new vault name
-- `termsOfAccess` (`string`, optional) - if the vault is intended for professional or legal use, you can add terms of access and they must be digitally signed before accessing the vault
-- `isPublic` (`boolean`, optional)
+- `options` (`VaultCreateOptions`, optional) - public/private, terms of access, etc.
- returns `Promise<{ vaultId, membershipId, transactionId }>` - Promise with new vault id, owner membership id & corresponding transaction id
example
```js
-const { vaultId, membershipId } = await akord.vault.create("my first vault", "terms of access");
+// create a private vault
+const { vaultId, membershipId } = await akord.vault.create("my first private vault");
+
+// create a public vault with terms of access
+const { vaultId, membershipId } = await akord.vault.create(
+ "my first public vault",
+ { public: true, termsOfAccess: "terms of access here - if the vault is intended for professional or legal use, you can add terms of access and they must be digitally signed before accessing the vault" }
+);
```
@@ -189,10 +225,10 @@ const { transactionId } = await akord.vault.delete(vaultId);
```
-#### `get(vaultId, shouldDecrypt)`
+#### `get(vaultId, options)`
- `vaultId` (`string`, required)
-- `shouldDecrypt` (`boolean`, optional) - default to true
+- `options` ([`VaultGetOptions`][vault-get-options], optional)
- returns `Promise` - Promise with the vault object
@@ -203,16 +239,42 @@ const vault = await akord.vault.get(vaultId);
```
-#### `list(listOptions)`
+#### `listAll(options)`
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise>` - Promise with currently authenticated user vaults
example
```js
-const vaults = await akord.vault.list();
+const vaults = await akord.vault.listAll();
+```
+
+
+#### `list(listOptions)`
+
+- `options` ([`ListOptions`][list-options], optional)
+- returns `Promise<{ items, nextToken }>` - Promise with paginated user vaults
+
+
+ example
+
+```js
+// retrieve first 100 user vaults
+const { items } = await akord.vault.list();
+
+// retrieve first 20 user vaults
+const { items } = await akord.vault.list({ limit: 20 });
+
+// iterate through all user vaults
+let token = null;
+let vaults = [];
+do {
+ const { items, nextToken } = await akord.vault.list({ nextToken: token });
+ vaults = vaults.concat(items);
+ token = nextToken;
+} while (token);
```
@@ -224,7 +286,8 @@ Invite user with an Akord account
- `vaultId` (`string`, required)
- `email` (`string`, required) - invitee's email
-- `role` (`string`, required) - CONTRIBUTOR or VIEWER
+- `role` ([`RoleType`][role-type], required) - CONTRIBUTOR or VIEWER
+- `options` (`MembershipCreateOptions`, optional) - invitation email message, etc.
- returns `Promise<{ membershipId, transactionId }>` - Promise with new membership id & corresponding transaction id
@@ -241,7 +304,8 @@ Invite user without an Akord account
- `vaultId` (`string`, required)
- `email` (`string`, required) - invitee's email
-- `role` (`string`, required) - CONTRIBUTOR or VIEWER
+- `role` ([`RoleType`][role-type], required) - CONTRIBUTOR or VIEWER
+- `options` (`MembershipCreateOptions`, optional) - invitation email message, etc.
- returns `Promise<{ transactionId }>` - Promise with new membership id & corresponding transaction id
@@ -326,7 +390,7 @@ const { transactionId } = await akord.membership.revoke(membershipId);
#### `changeRole(membershipId, role)`
- `membershipId` (`string`, required)
-- `role` (`string`, required) - CONTRIBUTOR or VIEWER
+- `role` ([`RoleType`][role-type], required) - CONTRIBUTOR or VIEWER
- returns `Promise<{ transactionId }>` - Promise with corresponding transaction id
@@ -352,10 +416,10 @@ const { transactionId } = await akord.membership.inviteResend(membershipId);
```
-#### `get(membershipId, shouldDecrypt)`
+#### `get(membershipId, options)`
- `membershipId` (`string`, required)
-- `shouldDecrypt` (`boolean`, optional) - default to true
+- `options` ([`GetOptions`][get-options], optional)
- returns `Promise` - Promise with the membership object
@@ -366,10 +430,10 @@ const membership = await akord.membership.get(membershipId);
```
-#### `listAll(vaultId, listOptions)`
+#### `listAll(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise>` - Promise with all memberships within given vault
@@ -380,10 +444,10 @@ const memberships = await akord.membership.listAll(vaultId);
```
-#### `list(vaultId, listOptions)`
+#### `list(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise<{ items, nextToken }>` - Promise with paginated memberships within given vault
@@ -413,7 +477,7 @@ do {
- `vaultId` (`string`, required)
- `message` (`string`, required) - memo content
-- `parentId` (`string`, optional) - parent folder id
+- `options` (`NodeCreateOptions`, optional) - parent id, etc.
- returns `Promise<{ memoId, transactionId }>` - Promise with new memo id & corresponding transaction id
@@ -456,10 +520,10 @@ const { transactionId } = await akord.memo.removeReaction(memoId, Akord.reaction
```
-#### `get(memoId, shouldDecrypt)`
+#### `get(memoId, options)`
- `memoId` (`string`, required)
-- `shouldDecrypt` (`boolean`, optional) - default to true
+- `options` ([`GetOptions`][get-options], optional)
- returns `Promise` - Promise with the memo object
@@ -470,10 +534,10 @@ const memo = await akord.memo.get(memoId);
```
-#### `listAll(vaultId, listOptions)`
+#### `listAll(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise>` - Promise with all memos within given vault
@@ -484,10 +548,10 @@ const memos = await akord.memo.listAll(vaultId);
```
-#### `list(vaultId, listOptions)`
+#### `list(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise<{ items, nextToken }>` - Promise with paginated memos within given vault
@@ -513,31 +577,32 @@ do {
### stack
-#### `create(vaultId, file, name, parentId, progressHook, cancelHook)`
+#### `create(vaultId, file, name)`
- `vaultId` (`string`, required)
-- `file` ([`FileLike`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/file.ts#L8), required) - file object - web: File, node: NodeJs.File (Blob implementation; web like File)
+- `file` ([`FileLike`][file-like], required) - file object - web: File, node: NodeJs.File (Blob implementation; web like File)
- `name` (`string`, required) - stack name
-- `parentId` (`string`, optional) - parent folder id
-- `progressHook` (`(progress:number)=>void`, optional)
-- `cancelHook` (`AbortController`, optional)
+- `options` (`StackCreateOptions`, optional)
- returns `Promise<{ stackId, transactionId }>` - Promise with new stack id & corresponding transaction id
example
```js
+import { NodeJs } from "@akord/akord-js/lib/types/file";
+const file = await NodeJs.File.fromPath("path to your file");
const { stackId } = await akord.stack.create(vaultId, file, "your stack name");
```
+> [See Next.js file upload showcase here][file-upload-example]
-#### `import(vaultId, fileTxId, parentId)`
+#### `import(vaultId, fileTxId)`
Create new stack from an existing arweave file transaction
- `vaultId` (`string`, required)
- `fileTxId` (`string`, required) - arweave file transaction id reference
-- `parentId` (`string`, optional) - parent folder id
+- `options` (`NodeCreateOptions`, optional) - parent id, etc.
- returns `Promise<{ stackId, transactionId }>` - Promise with new stack id & corresponding transaction id
@@ -562,17 +627,19 @@ const { transactionId } = await akord.stack.rename(stackId, "new name for your s
```
-#### `uploadRevision(stackId, file, progressHook)`
+#### `uploadRevision(stackId, file)`
- `stackId` (`string`, required)
-- `file` ([`FileLike`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/file.ts#L8), required) - file object
-- `progressHook` (`(progress:number)=>void`, optional)
+- `file` ([`FileLike`][file-like], required) - file object
+- `options` (`FileUploadOptions`, optional)
- returns `Promise<{ transactionId }>` - Promise with corresponding transaction id
example
```js
+import { NodeJs } from "@akord/akord-js/lib/types/file";
+const file = await NodeJs.File.fromPath("path to your file");
const { transactionId } = await akord.stack.uploadRevision(stackId, file);
```
@@ -633,10 +700,10 @@ const { transactionId } = await akord.stack.delete(stackId);
```
-#### `get(stackId, shouldDecrypt)`
+#### `get(stackId, options)`
- `stackId` (`string`, required)
-- `shouldDecrypt` (`boolean`, optional) - default to true
+- `options` ([`GetOptions`][get-options], optional)
- returns `Promise` - Promise with the stack object
@@ -647,10 +714,10 @@ const stack = await akord.stack.get(stackId);
```
-#### `listAll(vaultId, listOptions)`
+#### `listAll(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise>` - Promise with all stacks within given vault
@@ -661,10 +728,10 @@ const stacks = await akord.stack.listAll(vaultId);
```
-#### `list(vaultId, listOptions)`
+#### `list(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise<{ items, nextToken }>` - Promise with paginated stacks within given vault
@@ -713,7 +780,7 @@ const { name: fileName, data: fileBuffer } = await akord.stack.getVersion(stackI
Get stack file uri by index, return the latest arweave uri by default
- `stackId` (`string`, required)
-- `type` ([`StorageType`](https://github.com/Akord-com/akord-js/blob/26d1945bee727a1af45f0f9cc44c7fa9b68c5d75/src/types/node.ts#L149), optional) - storage type, default to arweave
+- `type` ([`StorageType`][storage-type], optional) - storage type, default to arweave
- `index` (`number`, optional) - file version index, default to latest
- returns `Promise` - Promise with stack file uri
@@ -760,11 +827,11 @@ See: https://github.com/jimmywarting/StreamSaver.js#configuration
### folder
-#### `create(vaultId, name, parentId)`
+#### `create(vaultId, name)`
- `vaultId` (`string`, required)
- `name` (`string`, required) - folder name
-- `parentId` (`string`, optional) - parent folder id
+- `options` (`NodeCreateOptions`, optional) - parent id, etc.
- returns `Promise<{ folderId, transactionId }>` - Promise with new folder id & corresponding transaction id
@@ -853,10 +920,10 @@ const { transactionId } = await akord.folder.delete(folderId);
```
-#### `get(folderId, shouldDecrypt)`
+#### `get(folderId, options)`
- `folderId` (`string`, required)
-- `shouldDecrypt` (`boolean`, optional) - default to true
+- `options` ([`GetOptions`][get-options], optional)
- returns `Promise` - Promise with the folder object
@@ -867,10 +934,10 @@ const folder = await akord.folder.get(folderId);
```
-#### `listAll(vaultId, listOptions)`
+#### `listAll(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise>` - Promise with all folders within given vault
@@ -881,10 +948,10 @@ const folders = await akord.folder.listAll(vaultId);
```
-#### `list(vaultId, listOptions)`
+#### `list(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise<{ items, nextToken }>` - Promise with paginated folders within given vault
@@ -910,13 +977,12 @@ do {
### note
-#### `create(vaultId, content, name, parentId)`
+#### `create(vaultId, content, name)`
- `vaultId` (`string`, required)
- `content` (`string`, required) - note text content, ex: stringified JSON
- `name` (`string`, required) - note name
-- `parentId` (`string`, optional) - parent folder id
-- `mimeType` (`string`, optional) - MIME type for the note text file, default: text/markdown
+- `options` (`NoteCreateOptions`, optional) - parent id, mime type, etc.
- returns `Promise<{ noteId, transactionId }>` - Promise with new note id & corresponding transaction id
@@ -929,8 +995,7 @@ const { noteId } = await akord.note.create(
vaultId,
JSON.stringify({ name: "My first JSON note" }),
"My first JSON note",
- parentId,
- "application/json"
+ { parentId: parentId, mimeType: "application/json" }
);
```
@@ -940,14 +1005,14 @@ const { noteId } = await akord.note.create(
- `noteId` (`string`, required)
- `content` (`string`, required) - note text content, ex: stringified JSON
- `name` (`string`, required) - note name
-- `mimeType` (`string`, optional) - MIME type for the note text file, default: text/markdown
+- `options` (`NoteOptions`, optional) - mime type, etc.
- returns `Promise<{ transactionId }>` - Promise with corresponding transaction id
example
```js
-const { transactionId } = await akord.note.uploadRevision(vaultId, "# Hello World bis", "Hello World note bis");
+const { transactionId } = await akord.note.uploadRevision(noteId, "# Hello World bis", "Hello World note bis");
```
@@ -1007,10 +1072,10 @@ const { transactionId } = await akord.note.delete(noteId);
```
-#### `get(noteId, shouldDecrypt)`
+#### `get(noteId, options)`
- `noteId` (`string`, required)
-- `shouldDecrypt` (`boolean`, optional) - default to true
+- `options` ([`GetOptions`][get-options], optional)
- returns `Promise` - Promise with the note object
@@ -1021,10 +1086,10 @@ const note = await akord.note.get(noteId);
```
-#### `listAll(vaultId, listOptions)`
+#### `listAll(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise>` - Promise with all notes within given vault
@@ -1035,10 +1100,10 @@ const notes = await akord.note.listAll(vaultId);
```
-#### `list(vaultId, listOptions)`
+#### `list(vaultId, options)`
- `vaultId` (`string`, required)
-- `listOptions` ([`ListOptions`](https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/list-options.ts#L1), optional)
+- `options` ([`ListOptions`][list-options], optional)
- returns `Promise<{ items, nextToken }>` - Promise with paginated notes within given vault
@@ -1172,44 +1237,43 @@ Update user profile along with all active memberships
#### `revoke(items)`
-- `items` (`Array<{ id: string, type: string }>`, required)
+- `items` (`Array<{ id: string, type: `[`NodeType`][node-type]` }>`, required)
- returns `Promise>` - Promise with corresponding transaction ids
#### `restore(items)`
-- `items` (`Array<{ id: string, type: string }>`, required)
+- `items` (`Array<{ id: string, type: `[`NodeType`][node-type]` }>`, required)
- returns `Promise>` - Promise with corresponding transaction ids
#### `delete(items)`
-- `items` (`Array<{ id: string, type: string }>`, required)
+- `items` (`Array<{ id: string, type: `[`NodeType`][node-type]` }>`, required)
- returns `Promise>` - Promise with corresponding transaction ids
#### `move(items, parentId)`
-- `items` (`Array<{ transactionId }>`, required)
+- `items` (`Array<{ id: string, type: `[`NodeType`][node-type]` }>`, required)
- `parentId` (`string`, optional)
- returns `Promise>` - Promise with corresponding transaction ids
#### `membershipChangeRole(items)`
-- `items` (`Array<{ transactionId }>`, required)
+- `items` (`Array<{ id: string, role: `[`RoleType`][role-type]` }>`, required)
- returns `Promise>` - Promise with corresponding transaction ids
-#### `stackCreate(vaultId, items, parentId, progressHook, cancelHook)`
+#### `stackCreate(vaultId, items)`
- `vaultId` (`string`, required)
-- `items` (`Array<{ transactionId }>`, required)
-- `parentId` (`string`, optional)
-- `progressHook` (`(progress:number)=>void`, optional)
-- `cancelHook` (`AbortController`, optional)
-- returns `Promise>` - Promise with new stack ids & their corresponding transaction ids
+- `items` (`Array<{ file: `[`FileLike`][file-like]`, name: string }>`, required)
+- `options` (`BatchStackCreateOptions`, optional)
+- returns `Promise<`[`BatchStackCreateResponse`][batch-stack-create-response]`>` - Promise with new stack ids & their corresponding transaction ids
#### `membershipInvite(vaultId, items)`
- `vaultId` (`string`, required)
-- `items` (`Array<{ transactionId }>`, required)
-- returns `Promise>` - Promise with new membership ids & their corresponding transaction ids
+- `items` (`Array<{ email: string, role: `[`RoleType`][role-type]` }>`, required)
+- `options` (`MembershipCreateOptions`, optional) - invitation email message, etc.
+- returns `Promise<`[`BatchMembershipInviteResponse`][batch-membership-invite-response]`>` - Promise with new membership ids & their corresponding transaction ids
### Development
> requires Node.js 16
@@ -1247,3 +1311,14 @@ After merging your PR to `main`:
- it will update package version
- will create a release
- will build and publish it to NPM
+
+[list-options]: https://github.com/Akord-com/akord-js/blob/193062c541ad06c186d5b872ecf9066d15806b43/src/types/query-options.ts#L1
+[get-options]: https://github.com/Akord-com/akord-js/blob/193062c541ad06c186d5b872ecf9066d15806b43/src/types/query-options.ts#L9
+[vault-get-options]: https://github.com/Akord-com/akord-js/blob/193062c541ad06c186d5b872ecf9066d15806b43/src/types/query-options.ts#L14
+[file-like]: https://github.com/Akord-com/akord-js/blob/ab9bb814fa9cf73d9ed01052738c8b84a86040b2/src/types/file.ts#L8
+[storage-type]: https://github.com/Akord-com/akord-js/blob/26d1945bee727a1af45f0f9cc44c7fa9b68c5d75/src/types/node.ts#L149
+[role-type]: https://github.com/Akord-com/akord-js/blob/03e28ffd95224dbfd0a8d891a06a154298619378/src/types/membership.ts#L4
+[node-type]: https://github.com/Akord-com/akord-js/blob/03e28ffd95224dbfd0a8d891a06a154298619378/src/types/node.ts#L11
+[batch-stack-create-response]: https://github.com/Akord-com/akord-js/blob/03e28ffd95224dbfd0a8d891a06a154298619378/src/types/batch-response.ts#L1
+[batch-membership-invite-response]: https://github.com/Akord-com/akord-js/blob/03e28ffd95224dbfd0a8d891a06a154298619378/src/types/batch-response.ts#L7
+[file-upload-example]:https://github.com/Akord-com/recipes/blob/a2dbc847097973ef08586f32b0ce3192f0581ed4/nextjs-starter/src/pages/index.tsx#L66
diff --git a/babel.config.js b/babel.config.js
deleted file mode 100644
index a1db3ce9..00000000
--- a/babel.config.js
+++ /dev/null
@@ -1,3 +0,0 @@
-module.exports = {
- presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
-};
\ No newline at end of file
diff --git a/package.json b/package.json
index a7a06e6d..3399ea1c 100644
--- a/package.json
+++ b/package.json
@@ -31,12 +31,11 @@
"node": ">=16.0.0"
},
"dependencies": {
- "@akord/crypto": "0.10.1",
+ "@akord/akord-auth": "0.25.0",
+ "@akord/crypto": "0.10.6",
"@akord/ts-cacheable": "1.0.11",
- "amazon-cognito-identity-js": "^5.2.8",
"axios": "^0.24.0",
"blueimp-load-image": "^5.16.0",
- "cross-fetch": "^3.1.5",
"lodash": "^4.17.21",
"mime-types": "^2.1.35",
"pdfjs-dist": "^2.16.105",
@@ -46,7 +45,6 @@
"web-streams-polyfill": "^3.2.1"
},
"devDependencies": {
- "@babel/preset-env": "^7.12.1",
"@faker-js/faker": "^6.2.0",
"@types/blueimp-load-image": "^5.16.0",
"@types/jest": "^27.4.0",
diff --git a/src/__tests__/batch.test.ts b/src/__tests__/batch.test.ts
index bf3e82aa..ce8513c4 100644
--- a/src/__tests__/batch.test.ts
+++ b/src/__tests__/batch.test.ts
@@ -1,34 +1,20 @@
import { Akord } from "../index";
import faker from '@faker-js/faker';
-import { initInstance } from './helpers';
+import { initInstance, folderCreate, noteCreate, testDataPath, vaultCreate } from './common';
import { email, email2, email3, password } from './data/test-credentials';
import { NodeJs } from "../types/file";
+import { firstFileName } from "./data/content";
let akord: Akord;
jest.setTimeout(3000000);
-async function vaultCreate() {
- const name = faker.random.words();
- const termsOfAccess = faker.lorem.sentences();
- const { vaultId, membershipId } = await akord.vault.create(name, termsOfAccess);
-
- const membership = await akord.membership.get(membershipId);
- expect(membership.status).toEqual("ACCEPTED");
- expect(membership.role).toEqual("OWNER");
-
- const vault = await akord.vault.get(vaultId);
- expect(vault.status).toEqual("ACTIVE");
- expect(vault.name).toEqual(name);
- return { vaultId };
-}
-
describe("Testing batch actions", () => {
let vaultId: string;
let folderId: string;
let noteId: string;
- let membershipId1: string;
- let membershipId2: string;
+ let viewerId: string;
+ let contributorId: string;
beforeEach(async () => {
akord = await initInstance(email, password);
@@ -36,28 +22,16 @@ describe("Testing batch actions", () => {
beforeAll(async () => {
akord = await initInstance(email, password);
- vaultId = (await vaultCreate()).vaultId;
+ vaultId = (await vaultCreate(akord)).vaultId;
});
describe("Batch revoke/restore actions", () => {
it("should create folder", async () => {
- const name = faker.random.words();
- folderId = (await akord.folder.create(vaultId, name)).folderId;
-
- const folder = await akord.folder.get(folderId);
- expect(folder.status).toEqual("ACTIVE");
- expect(folder.parentId).toBeFalsy();
- expect(folder.name).toEqual(name);
+ folderId = await folderCreate(akord, vaultId);
});
it("should create note", async () => {
- const name = faker.random.words();
- const content = faker.lorem.sentences();
-
- noteId = (await akord.note.create(vaultId, content, name)).noteId;
-
- const note = await akord.note.get(noteId);
- expect(note.versions.length).toEqual(1);
+ noteId = await noteCreate(akord, vaultId);
});
it("should revoke all items in a batch", async () => {
@@ -89,22 +63,23 @@ describe("Testing batch actions", () => {
describe("Batch upload", () => {
it("should upload a batch of 10 files", async () => {
- const file = NodeJs.File.fromPath("./src/__tests__/data/logo.png");
+ const file = await NodeJs.File.fromPath(testDataPath + firstFileName);
const items = [] as { file: any, name: string }[];
- for (let i = 0; i < 10; i++) {
+ for (let i = 0; i < 2; i++) {
const name = faker.random.words();
items.push({ file, name });
}
- const response = await akord.batch.stackCreate(vaultId, items);
+ const response = (await akord.batch.stackCreate(vaultId, items)).data;
for (let index in items) {
const stack = await akord.stack.get(response[index].stackId);
expect(stack.status).toEqual("ACTIVE");
+ expect(stack.name).toEqual(response[index].object.name);
expect(stack.versions.length).toEqual(1);
- expect(stack.versions[0].title).toEqual("logo.png");
+ expect(stack.versions[0].name).toEqual(firstFileName);
}
});
});
@@ -120,11 +95,11 @@ describe("Testing batch actions", () => {
for (let item of response) {
const membership = await akord.membership.get(item.membershipId);
if (membership.email === email2) {
- membershipId1 = item.membershipId;
+ contributorId = item.membershipId;
expect(membership.status).toEqual("PENDING");
expect(membership.role).toEqual("CONTRIBUTOR");
} else {
- membershipId2 = item.membershipId;
+ viewerId = item.membershipId;
expect(membership.status).toEqual("PENDING");
expect(membership.role).toEqual("VIEWER");
}
@@ -133,14 +108,14 @@ describe("Testing batch actions", () => {
it("should change access", async () => {
await akord.batch.membershipChangeRole([
- { id: membershipId1, role: "VIEWER" },
- { id: membershipId2, role: "CONTRIBUTOR" }
+ { id: contributorId, role: "VIEWER" },
+ { id: viewerId, role: "CONTRIBUTOR" }
])
- const membership1 = await akord.membership.get(membershipId1);
+ const membership1 = await akord.membership.get(contributorId);
expect(membership1.role).toEqual("VIEWER");
- const membership2 = await akord.membership.get(membershipId2);
+ const membership2 = await akord.membership.get(viewerId);
expect(membership2.role).toEqual("CONTRIBUTOR");
});
});
diff --git a/src/__tests__/common.ts b/src/__tests__/common.ts
new file mode 100644
index 00000000..203158ad
--- /dev/null
+++ b/src/__tests__/common.ts
@@ -0,0 +1,53 @@
+import { Akord, Auth } from "../index";
+import faker from '@faker-js/faker';
+
+export async function initInstance(email: string, password: string): Promise {
+ const { wallet } = await Auth.signIn(email, password);
+ return new Akord(wallet, { debug: true });
+}
+
+export const vaultCreate = async (akord: Akord) => {
+ const name = faker.random.words();
+ const termsOfAccess = faker.lorem.sentences();
+ const { vaultId, membershipId } = await akord.vault.create(name, { termsOfAccess });
+
+ const membership = await akord.membership.get(membershipId);
+ expect(membership.status).toEqual("ACCEPTED");
+ expect(membership.role).toEqual("OWNER");
+
+ const vault = await akord.vault.get(vaultId);
+ expect(vault.status).toEqual("ACTIVE");
+ expect(vault.name).toEqual(name);
+ return { vaultId, membershipId };
+}
+
+export const folderCreate = async (akord: Akord, vaultId: string, parentId?: string) => {
+ const name = faker.random.words();
+ const { folderId } = await akord.folder.create(vaultId, name, { parentId: parentId });
+
+ const folder = await akord.folder.get(folderId);
+ expect(folder.status).toEqual("ACTIVE");
+ if (parentId) {
+ expect(folder.parentId).toEqual(parentId);
+ } else {
+ expect(folder.parentId).toBeFalsy();
+ }
+ expect(folder.name).toEqual(name);
+ return folderId;
+}
+
+export const noteCreate = async (akord: Akord, vaultId: string) => {
+ const name = faker.random.words();
+ const content = faker.lorem.sentences();
+
+ const { noteId } = await akord.note.create(vaultId, content, name);
+
+ const note = await akord.note.get(noteId);
+ expect(note.versions.length).toEqual(1);
+ const { name: fileName, data } = await akord.note.getVersion(noteId);
+ expect(data).toEqual(content);
+ expect(fileName).toEqual(name);
+ return noteId;
+}
+
+export const testDataPath = "./src/__tests__/data/";
diff --git a/src/__tests__/data/content.ts b/src/__tests__/data/content.ts
index 433a9887..9e0df597 100644
--- a/src/__tests__/data/content.ts
+++ b/src/__tests__/data/content.ts
@@ -16,4 +16,8 @@ export const publicVaultId = "RNACU80_GqwUBS0annCpcaD7evriSU9mid_s-K0yvvA";
export const parentId = "33408770-f188-4586-a9ac-e50297a85eb5";
export const privateVaultId = 'j8C-RDy0F5zwQvrzesL0QaaKk7bjnLhYBFp8xpqV37k';
export const fileId = 'efb8ed89-3221-48e7-b1e5-9b94eef41319';
-export const message = 'Quae vel nemo dolorum recusandae temporibus temporibus. Hic id eum quo sint atque voluptates voluptatum. Vero sit aliquid. Nam omnis repudiandae. Corporis quasi ex id incidunt suscipit non. In ea impedit. Consequatur voluptatem et nihil ut debitis similique. Eligendi ut voluptatum fuga eos a ab iure alias molestiae. Sed reiciendis aut sapiente natus inventore iure nesciunt architecto veritatis. Ea omnis similique incidunt voluptas sit pariatur officia nihil cupiditate. Voluptas nobis molestias quia voluptas saepe labore quia consequatur dolorem. Ut quia quis ut iste inventore excepturi. Dolores incidunt eum quia aspernatur et architecto cumque provident architecto. Maiores occaecati suscipit repellat. Quia illum ex doloribus porro. Ipsa doloribus atque et aut molestiae quam magnam enim. Laborum totam adipisci non dolor neque quos saepe. Qui consequuntur sapiente quis non sit explicabo expedita. Odio voluptatibus neque maxime autem harum facilis optio. Eum esse ipsam itaque minima quia repudiandae. Cum eveniet voluptatum consequatur. Dolor mollitia perferendis fuga impedit quia enim consectetur non. Quibusdam nostrum sit at quae sit ducimus blanditiis a deserunt. Qui aperiam id est architecto ut. Ut dolores soluta consequatur at expedita. Et blanditiis nam quam cumque. Similique aut animi voluptas id quam. Id rerum est architecto dolorem quae rerum autem voluptatem. Id cum impedit est cumque quod dolores aut. Qui quo autem vel. Autem sapiente voluptates rerum architecto necessitatibus doloremque consequatur iure quo. Veritatis tenetur voluptatem praesentium. Et sit architecto veritatis modi voluptatem iusto voluptates neque. Soluta explicabo qui provident velit sunt. Quia nisi deleniti perferendis quo et enim explicabo eos. Tempore amet quisquam itaque et corrupti inventore quia illo deserunt. Voluptatum animi et. Earum in vitae nemo officia qui necessitatibus animi totam. Totam amet beatae ex totam quia est labore. Id voluptates voluptatibus. Beatae eos corporis sed ratione ipsa eum vel placeat. Voluptas est quam atque non iure necessitatibus. Ab et numquam excepturi rem vel hic delectus voluptatem. Ut et hic animi minus sint et. Commodi explicabo est quo veniam ratione quisquam iure ducimus sit. Molestias cum voluptas consectetur necessitatibus nobis eveniet veritatis reiciendis illo. Ex est officia eveniet eveniet enim voluptatum iusto labore vitae. Quam eum vero ratione veritatis ex voluptatibus. Vel repellendus voluptatum autem doloremque cupiditate cumque. Delectus aut esse occaecati.'
\ No newline at end of file
+export const message = 'Quae vel nemo dolorum recusandae temporibus temporibus. Hic id eum quo sint atque voluptates voluptatum. Vero sit aliquid. Nam omnis repudiandae. Corporis quasi ex id incidunt suscipit non. In ea impedit. Consequatur voluptatem et nihil ut debitis similique. Eligendi ut voluptatum fuga eos a ab iure alias molestiae. Sed reiciendis aut sapiente natus inventore iure nesciunt architecto veritatis. Ea omnis similique incidunt voluptas sit pariatur officia nihil cupiditate. Voluptas nobis molestias quia voluptas saepe labore quia consequatur dolorem. Ut quia quis ut iste inventore excepturi. Dolores incidunt eum quia aspernatur et architecto cumque provident architecto. Maiores occaecati suscipit repellat. Quia illum ex doloribus porro. Ipsa doloribus atque et aut molestiae quam magnam enim. Laborum totam adipisci non dolor neque quos saepe. Qui consequuntur sapiente quis non sit explicabo expedita. Odio voluptatibus neque maxime autem harum facilis optio. Eum esse ipsam itaque minima quia repudiandae. Cum eveniet voluptatum consequatur. Dolor mollitia perferendis fuga impedit quia enim consectetur non. Quibusdam nostrum sit at quae sit ducimus blanditiis a deserunt. Qui aperiam id est architecto ut. Ut dolores soluta consequatur at expedita. Et blanditiis nam quam cumque. Similique aut animi voluptas id quam. Id rerum est architecto dolorem quae rerum autem voluptatem. Id cum impedit est cumque quod dolores aut. Qui quo autem vel. Autem sapiente voluptates rerum architecto necessitatibus doloremque consequatur iure quo. Veritatis tenetur voluptatem praesentium. Et sit architecto veritatis modi voluptatem iusto voluptates neque. Soluta explicabo qui provident velit sunt. Quia nisi deleniti perferendis quo et enim explicabo eos. Tempore amet quisquam itaque et corrupti inventore quia illo deserunt. Voluptatum animi et. Earum in vitae nemo officia qui necessitatibus animi totam. Totam amet beatae ex totam quia est labore. Id voluptates voluptatibus. Beatae eos corporis sed ratione ipsa eum vel placeat. Voluptas est quam atque non iure necessitatibus. Ab et numquam excepturi rem vel hic delectus voluptatem. Ut et hic animi minus sint et. Commodi explicabo est quo veniam ratione quisquam iure ducimus sit. Molestias cum voluptas consectetur necessitatibus nobis eveniet veritatis reiciendis illo. Ex est officia eveniet eveniet enim voluptatum iusto labore vitae. Quam eum vero ratione veritatis ex voluptatibus. Vel repellendus voluptatum autem doloremque cupiditate cumque. Delectus aut esse occaecati.'
+
+export const firstFileName = "logo.png";
+export const secondFileName = "avatar.jpeg";
+export const arweaveImportFileTx = "kzGxbFW_oJ3PyYneRs9cPrChQ-k-8Fym5k9PCZNJ_HA";
\ No newline at end of file
diff --git a/src/__tests__/folder.test.ts b/src/__tests__/folder.test.ts
index b3f66472..885d1a61 100644
--- a/src/__tests__/folder.test.ts
+++ b/src/__tests__/folder.test.ts
@@ -1,27 +1,12 @@
import { Akord } from "../index";
import faker from '@faker-js/faker';
-import { initInstance } from './helpers';
+import { initInstance, folderCreate, vaultCreate } from './common';
import { email, password } from './data/test-credentials';
let akord: Akord;
jest.setTimeout(3000000);
-async function vaultCreate() {
- const name = faker.random.words();
- const termsOfAccess = faker.lorem.sentences();
- const { vaultId, membershipId } = await akord.vault.create(name, termsOfAccess);
-
- const membership = await akord.membership.get(membershipId);
- expect(membership.status).toEqual("ACCEPTED");
- expect(membership.role).toEqual("OWNER");
-
- const vault = await akord.vault.get(vaultId);
- expect(vault.status).toEqual("ACTIVE");
- expect(vault.name).toEqual(name);
- return { vaultId };
-}
-
describe("Testing folder functions", () => {
let vaultId: string;
let rootFolderId: string;
@@ -33,31 +18,15 @@ describe("Testing folder functions", () => {
beforeAll(async () => {
akord = await initInstance(email, password);
- vaultId = (await vaultCreate()).vaultId;
+ vaultId = (await vaultCreate(akord)).vaultId;
});
it("should create root folder", async () => {
- const name = faker.random.words();
- const { folderId } = await akord.folder.create(vaultId, name);
-
- rootFolderId = folderId;
-
- const rootFolder = await akord.folder.get(rootFolderId);
- expect(rootFolder.status).toEqual("ACTIVE");
- expect(rootFolder.parentId).toBeFalsy();
- expect(rootFolder.name).toEqual(name);
+ rootFolderId = await folderCreate(akord, vaultId);
});
it("should create a sub folder", async () => {
- const name = faker.random.words();
- const { folderId } = await akord.folder.create(vaultId, name, rootFolderId);
-
- subFolderId = folderId;
-
- const subFolder = await akord.folder.get(subFolderId);
- expect(subFolder.status).toEqual("ACTIVE");
- expect(subFolder.parentId).toEqual(rootFolderId);
- expect(subFolder.name).toEqual(name);
+ subFolderId = await folderCreate(akord, vaultId, rootFolderId);
});
it("should revoke root folder", async () => {
@@ -73,7 +42,7 @@ describe("Testing folder functions", () => {
it("should fail adding new sub-folder to the revoked root folder", async () => {
const name = faker.random.words();
await expect(async () =>
- await akord.folder.create(vaultId, name, rootFolderId)
+ await akord.folder.create(vaultId, name, { parentId: rootFolderId })
).rejects.toThrow(Error);
});
diff --git a/src/__tests__/helpers.ts b/src/__tests__/helpers.ts
deleted file mode 100644
index b5312318..00000000
--- a/src/__tests__/helpers.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { Akord } from "../index";
-
-export async function initInstance(email: string, password: string): Promise {
- const { wallet, jwtToken } = await Akord.auth.signIn(email, password);
- return new Akord(wallet, jwtToken, { debug: true });
-}
\ No newline at end of file
diff --git a/src/__tests__/manifest.test.ts b/src/__tests__/manifest.test.ts
index 460470a0..05703b85 100644
--- a/src/__tests__/manifest.test.ts
+++ b/src/__tests__/manifest.test.ts
@@ -1,6 +1,5 @@
import { Akord } from "../index";
-import faker from '@faker-js/faker';
-import { initInstance } from './helpers';
+import { initInstance, vaultCreate } from './common';
import { email, password } from './data/test-credentials';
import { createFileLike } from "../core/file";
@@ -36,30 +35,6 @@ const manifest = {
}
};
-async function vaultCreate() {
- const name = faker.random.words();
- const termsOfAccess = faker.lorem.sentences();
- const { vaultId, membershipId } = await akord.vault.create(name, termsOfAccess, true);
- console.log("created vault", name);
-
- const membership = await akord.membership.get(membershipId);
- expect(membership.status).toEqual("ACCEPTED");
- expect(membership.role).toEqual("OWNER");
-
- const htmlSrc = "Hello World";
- const htmlFile = await createFileLike([htmlSrc], "index.html", "text/html");
- const { stackId } = await akord.stack.create(vaultId, htmlFile, "index.html");
- console.log("uploaded index.html", stackId);
-
- const vault = await akord.vault.get(vaultId);
- expect(vault.status).toEqual("ACTIVE");
- expect(vault.name).toEqual(name);
-
- console.log(vaultId, name);
-
- return { vaultId };
-}
-
describe("Testing manifest functions", () => {
let vaultId: string;
@@ -69,7 +44,13 @@ describe("Testing manifest functions", () => {
beforeAll(async () => {
akord = await initInstance(email, password);
- vaultId = (await vaultCreate()).vaultId;
+ vaultId = (await vaultCreate(akord)).vaultId;
+
+ // upload html file
+ const htmlSrc = "Hello World
";
+ const htmlFile = await createFileLike([htmlSrc], "index.html", "text/html");
+ const { stackId } = await akord.stack.create(vaultId, htmlFile, "index.html");
+ console.log("uploaded index.html", stackId);
});
// it("should create new manifest", async () => {
diff --git a/src/__tests__/membership.test.ts b/src/__tests__/membership.test.ts
index 7fc811a1..60e4e602 100644
--- a/src/__tests__/membership.test.ts
+++ b/src/__tests__/membership.test.ts
@@ -1,78 +1,108 @@
import { Akord } from "../index";
-import faker from '@faker-js/faker';
-import { initInstance } from './helpers';
import { email, email2, password, password2 } from './data/test-credentials';
+import { initInstance, vaultCreate } from './common';
+import { Membership } from "../types/membership";
-let akord1: Akord;
-let akord2: Akord;
+let ownerAkordInstance: Akord;
+let inviteeAkordInstance: Akord;
jest.setTimeout(3000000);
-async function vaultCreate() {
- const name = faker.random.words();
- const termsOfAccess = faker.lorem.sentences();
- const { vaultId, membershipId } = await akord1.vault.create(name, termsOfAccess);
-
- const membership = await akord1.membership.get(membershipId);
- expect(membership.status).toEqual("ACCEPTED");
- expect(membership.role).toEqual("OWNER");
-
- const vault = await akord1.vault.get(vaultId);
- expect(vault.status).toEqual("ACTIVE");
- expect(vault.name).toEqual(name);
- return { vaultId };
+type Member = {
+ publicSigningKey: string,
+ address: string,
+ name?: string,
+ membershipId: string,
+ membership?: Membership
}
describe("Testing membership functions", () => {
let vaultId: string;
- let membershipId: string;
-
- beforeEach(async () => {
- akord1 = await initInstance(email, password);
- akord2 = await initInstance(email2, password2);
- });
+ let owner: Member;
+ let invitee: Member;
beforeAll(async () => {
- akord1 = await initInstance(email, password);
- akord2 = await initInstance(email2, password2);
- vaultId = (await vaultCreate()).vaultId;
+ inviteeAkordInstance = await initInstance(email2, password2);
+ const inviteeProfileDetails = await inviteeAkordInstance.profile.get();
+ invitee = {
+ publicSigningKey: inviteeAkordInstance.vault.wallet.signingPublicKey(),
+ address: await inviteeAkordInstance.vault.wallet.getAddress(),
+ name: inviteeProfileDetails.name,
+ membershipId: ""
+ };
+ ownerAkordInstance = await initInstance(email, password);
+ const ownerProfileDetails = await ownerAkordInstance.profile.get();
+ owner = {
+ publicSigningKey: ownerAkordInstance.vault.wallet.signingPublicKey(),
+ address: await ownerAkordInstance.vault.wallet.getAddress(),
+ name: ownerProfileDetails.name,
+ membershipId: ""
+ };
+ const vaultResult = await vaultCreate(ownerAkordInstance);
+ vaultId = vaultResult.vaultId;
+ owner.membershipId = vaultResult.membershipId;
});
it("should invite new member", async () => {
- membershipId = (await akord1.membership.invite(vaultId, email2, "CONTRIBUTOR")).membershipId;
-
- const membership = await akord1.membership.get(membershipId);
- expect(membership.status).toEqual("PENDING");
- expect(membership.role).toEqual("CONTRIBUTOR");
+ ownerAkordInstance = await initInstance(email, password);
+
+ invitee.membershipId = (await ownerAkordInstance.membership.invite(vaultId, email2, "CONTRIBUTOR")).membershipId;
+
+ invitee.membership = await ownerAkordInstance.membership.get(invitee.membershipId);
+ expect(invitee.membership.status).toEqual("PENDING");
+ expect(invitee.membership.role).toEqual("CONTRIBUTOR");
+ expect(invitee.membership.memberDetails.name).toBeFalsy();
+ expect(invitee.membership.memberPublicSigningKey).toEqual(invitee.publicSigningKey);
+ expect(invitee.membership.address).toEqual(invitee.address);
+ expect(invitee.membership.owner).toEqual(owner.address);
+
+ owner.membership = await ownerAkordInstance.membership.get(owner.membershipId);
+ expect(owner.membership.status).toEqual("ACCEPTED");
+ expect(owner.membership.role).toEqual("OWNER");
+ expect(owner.membership.memberDetails.name).toEqual(owner.name);
+ expect(owner.membership.memberPublicSigningKey).toEqual(owner.publicSigningKey);
+ expect(owner.membership.address).toEqual(owner.address);
+ expect(owner.membership.owner).toEqual(owner.address);
});
it("should accept the invite", async () => {
- await akord2.membership.accept(membershipId);
+ inviteeAkordInstance = await initInstance(email2, password2);
+ await inviteeAkordInstance.membership.accept(invitee.membershipId);
- const membership = await akord2.membership.get(membershipId);
- expect(membership.status).toEqual("ACCEPTED");
+ invitee.membership = await inviteeAkordInstance.membership.get(invitee.membershipId);
+ expect(invitee.membership.status).toEqual("ACCEPTED");
+ expect(invitee.membership.memberDetails.name).toEqual(invitee.name);
+ expect(invitee.membership.memberPublicSigningKey).toEqual(invitee.publicSigningKey);
+ expect(invitee.membership.address).toEqual(invitee.address);
+ expect(invitee.membership.owner).toEqual(owner.address);
// should be able to decrypt the vault name by the new member
- await akord2.vault.get(vaultId);
+ await inviteeAkordInstance.vault.get(vaultId);
});
it("should fail inviting the same member twice", async () => {
+ ownerAkordInstance = await initInstance(email, password);
await expect(async () =>
- akord1.membership.invite(vaultId, email2, "VIEWER")
+ ownerAkordInstance.membership.invite(vaultId, email2, "VIEWER")
).rejects.toThrow(Error);
});
it("should change access", async () => {
- await akord1.membership.changeRole(membershipId, "VIEWER");
+ ownerAkordInstance = await initInstance(email, password);
+ await ownerAkordInstance.membership.changeRole(invitee.membershipId, "VIEWER");
- const membership = await akord1.membership.get(membershipId);
+ const membership = await ownerAkordInstance.membership.get(invitee.membershipId);
expect(membership.role).toEqual("VIEWER");
});
it("should revoke the invite", async () => {
- await akord1.membership.revoke(membershipId);
+ ownerAkordInstance = await initInstance(email, password);
+ await ownerAkordInstance.membership.revoke(invitee.membershipId);
- const membership = await akord1.membership.get(membershipId);
+ const membership = await ownerAkordInstance.membership.get(invitee.membershipId);
expect(membership.status).toEqual("REVOKED");
+
+ // should be able to decrypt the vault by the owner
+ await ownerAkordInstance.vault.get(vaultId);
});
});
\ No newline at end of file
diff --git a/src/__tests__/memo.test.ts b/src/__tests__/memo.test.ts
index 1f9a9ab5..5585f644 100644
--- a/src/__tests__/memo.test.ts
+++ b/src/__tests__/memo.test.ts
@@ -1,6 +1,6 @@
import { Akord } from "../index";
import faker from '@faker-js/faker';
-import { initInstance } from './helpers';
+import { initInstance, vaultCreate } from './common';
import { reactionEmoji } from '../constants';
import { email, password } from './data/test-credentials';
@@ -8,21 +8,6 @@ let akord: Akord;
jest.setTimeout(3000000);
-async function vaultCreate() {
- const name = faker.random.words();
- const termsOfAccess = faker.lorem.sentences();
- const { vaultId, membershipId } = await akord.vault.create(name, termsOfAccess);
-
- const membership = await akord.membership.get(membershipId);
- expect(membership.status).toEqual("ACCEPTED");
- expect(membership.role).toEqual("OWNER");
-
- const vault = await akord.vault.get(vaultId);
- expect(vault.status).toEqual("ACTIVE");
- expect(vault.name).toEqual(name);
- return { vaultId };
-}
-
describe("Testing memo functions", () => {
let vaultId: string;
let memoId: string;
@@ -33,7 +18,7 @@ describe("Testing memo functions", () => {
beforeAll(async () => {
akord = await initInstance(email, password);
- vaultId = (await vaultCreate()).vaultId;
+ vaultId = (await vaultCreate(akord)).vaultId;
});
it("should create new memo", async () => {
diff --git a/src/__tests__/note.test.ts b/src/__tests__/note.test.ts
index 0f5c67eb..f199d498 100644
--- a/src/__tests__/note.test.ts
+++ b/src/__tests__/note.test.ts
@@ -1,27 +1,12 @@
import { Akord } from "../index";
import faker from '@faker-js/faker';
-import { initInstance } from './helpers';
+import { initInstance, noteCreate, vaultCreate } from './common';
import { email, password } from './data/test-credentials';
let akord: Akord;
jest.setTimeout(3000000);
-async function vaultCreate() {
- const name = faker.random.words();
- const termsOfAccess = faker.lorem.sentences();
- const { vaultId, membershipId } = await akord.vault.create(name, termsOfAccess);
-
- const membership = await akord.membership.get(membershipId);
- expect(membership.status).toEqual("ACCEPTED");
- expect(membership.role).toEqual("OWNER");
-
- const vault = await akord.vault.get(vaultId);
- expect(vault.status).toEqual("ACTIVE");
- expect(vault.name).toEqual(name);
- return { vaultId };
-}
-
describe("Testing note functions", () => {
let vaultId: string;
let noteId: string;
@@ -32,20 +17,11 @@ describe("Testing note functions", () => {
beforeAll(async () => {
akord = await initInstance(email, password);
- vaultId = (await vaultCreate()).vaultId;
+ vaultId = (await vaultCreate(akord)).vaultId;
});
it("should create new note", async () => {
- const name = faker.random.words();
- const content = faker.lorem.sentences();
-
- noteId = (await akord.note.create(vaultId, content, name)).noteId;
-
- const note = await akord.note.get(noteId);
- expect(note.versions.length).toEqual(1);
- const { name: fileName, data } = await akord.note.getVersion(noteId);
- expect(data).toEqual(content);
- expect(fileName).toEqual(name);
+ noteId = await noteCreate(akord, vaultId);
});
it("should upload new revision", async () => {
@@ -56,7 +32,7 @@ describe("Testing note functions", () => {
noteId,
JSON.stringify({ content: content }),
name,
- "application/json"
+ { mimeType: "application/json" }
);
const note = await akord.note.get(noteId);
diff --git a/src/__tests__/profile.test.ts b/src/__tests__/profile.test.ts
index f39693e1..d011b96f 100644
--- a/src/__tests__/profile.test.ts
+++ b/src/__tests__/profile.test.ts
@@ -1,8 +1,9 @@
import { Akord } from "../index";
import faker from '@faker-js/faker';
-import { initInstance } from './helpers';
+import { initInstance, testDataPath } from './common';
import { email, password } from './data/test-credentials';
import { NodeJs } from "../types/file";
+import { firstFileName } from "./data/content";
let akord: Akord;
@@ -16,13 +17,12 @@ describe("Testing profile functions", () => {
it("should update the profile", async () => {
const name = faker.random.words();
- const file = NodeJs.File.fromPath("./src/__tests__/data/logo.png");
+ const file = await NodeJs.File.fromPath(testDataPath + firstFileName);
const fileBuffer = await file.arrayBuffer();
await akord.profile.update(name, fileBuffer);
const profileDetails = await akord.profile.get();
expect(profileDetails.name).toEqual(name);
- expect(profileDetails.avatar).not.toBeNull();
- expect(Buffer.from(profileDetails.avatar || new ArrayBuffer(1))).toEqual(fileBuffer);
+ expect(profileDetails.avatar).toEqual(fileBuffer);
});
});
\ No newline at end of file
diff --git a/src/__tests__/queries.test.ts b/src/__tests__/queries.test.ts
index 7ebeab39..a2582798 100644
--- a/src/__tests__/queries.test.ts
+++ b/src/__tests__/queries.test.ts
@@ -1,4 +1,4 @@
-import { Akord } from "../index";
+import { Akord, Auth } from "../index";
import { email, password } from './data/test-credentials';
import { vaults, fileId, message, publicVaultId, privateVaultId, parentId } from './data/content';
import { NodeJs } from "../types/file";
@@ -10,15 +10,15 @@ jest.setTimeout(3000000);
describe("Testing querying directly from permaweb", () => {
beforeAll(async () => {
- const { jwtToken, wallet } = await Akord.auth.signIn(email, password);
- privateClient = new Akord(wallet, jwtToken);
+ const { wallet } = await Auth.signIn(email, password);
+ privateClient = new Akord(wallet);
publicClient = new Akord();
});
- // it("Query all vaults from Akord API", async () => {
- // const result = await privateClient.vault.list();
- // expect(result).toEqual(vaults);
- // });
+ it("Query all vaults from Akord API", async () => {
+ const result = await privateClient.vault.listAll();
+ expect(result).toBeTruthy();
+ });
it("Should query public vault - contract state from Akord API", async () => {
const contract = await publicClient.contract.getState(publicVaultId);
@@ -34,7 +34,7 @@ describe("Testing querying directly from permaweb", () => {
});
it("Query stacks by parent id", async () => {
- const stacks = await publicClient.stack.listAll(publicVaultId, parentId);
+ const stacks = await publicClient.stack.listAll(publicVaultId, { parentId });
expect(stacks.length).toEqual(2);
expect(stacks[0].parentId).toEqual(parentId);
expect(stacks[1].parentId).toEqual(parentId);
@@ -42,13 +42,13 @@ describe("Testing querying directly from permaweb", () => {
// it("Query chunked file from Akord API", async () => {
// const decryptedFile = await privateClient.file.get(fileId, vaults[0].id, { isChunked: true, numberOfChunks: 3 });
- // const file = NodeJs.File.fromPath("./src/__tests__/data/chunked-file.test");
+ // const file = await NodeJs.File.fromPath("./src/__tests__/data/chunked-file.test");
// expect(Buffer.from(decryptedFile)).toEqual(await file.arrayBuffer());
// });
// it("Query chunked file from Akord API", async () => {
// const decryptedFile = await privateClient.file.get(fileId, vaults[0].id, { isChunked: true, numberOfChunks: 3 });
- // const file = NodeJs.File.fromPath("./src/__tests__/data/chunked-file.test");
+ // const file = await NodeJs.File.fromPath("./src/__tests__/data/chunked-file.test");
// expect(Buffer.from(decryptedFile)).toEqual(await file.arrayBuffer());
// });
});
diff --git a/src/__tests__/stack.test.ts b/src/__tests__/stack.test.ts
index 2a59fb03..76f626ab 100644
--- a/src/__tests__/stack.test.ts
+++ b/src/__tests__/stack.test.ts
@@ -1,30 +1,16 @@
import { Akord } from "../index";
import faker from '@faker-js/faker';
-import { initInstance } from './helpers';
+import { initInstance, testDataPath, vaultCreate } from './common';
import { email, password } from './data/test-credentials';
import { NodeJs } from "../types/file";
import { StorageType } from "../types/node";
import { getTxData } from "../arweave";
+import { firstFileName, secondFileName, arweaveImportFileTx } from './data/content';
let akord: Akord;
jest.setTimeout(3000000);
-async function vaultCreate() {
- const name = faker.random.words();
- const termsOfAccess = faker.lorem.sentences();
- const { vaultId, membershipId } = await akord.vault.create(name, termsOfAccess);
-
- const membership = await akord.membership.get(membershipId);
- expect(membership.status).toEqual("ACCEPTED");
- expect(membership.role).toEqual("OWNER");
-
- const vault = await akord.vault.get(vaultId);
- expect(vault.status).toEqual("ACTIVE");
- expect(vault.name).toEqual(name);
- return { vaultId };
-}
-
describe("Testing stack functions", () => {
let vaultId: string;
let stackId: string;
@@ -35,88 +21,113 @@ describe("Testing stack functions", () => {
beforeAll(async () => {
akord = await initInstance(email, password);
- vaultId = (await vaultCreate()).vaultId;
+ vaultId = (await vaultCreate(akord)).vaultId;
});
it("should create new stack", async () => {
- const name = faker.random.words();
+ stackId = await stackCreate(vaultId);
+ });
- const file = NodeJs.File.fromPath("./src/__tests__/data/logo.png");
+ it("should upload new revision", async () => {
+ await stackUploadRevision(stackId);
+ });
- stackId = (await akord.stack.create(vaultId, file, name)).stackId;
+ it("should rename the stack", async () => {
+ await stackRename(stackId);
+ });
- const stack = await akord.stack.get(stackId);
- expect(stack.status).toEqual("ACTIVE");
- expect(stack.name).toEqual(name);
- expect(stack.versions.length).toEqual(1);
- expect(stack.versions[0].name).toEqual("logo.png");
+ it("should revoke the stack", async () => {
+ await stackRevoke(stackId);
+ });
- const binary = await akord.file.get(stack.getUri(StorageType.S3, 0), vaultId);
- expect(binary).toEqual(await file.arrayBuffer());
+ it("should restore the stack", async () => {
+ await stackRestore(stackId);
});
- it("should upload new revision", async () => {
- const file = NodeJs.File.fromPath("./src/__tests__/data/avatar.jpeg");
+ it("should import new stack from arweave tx", async () => {
+ await stackImport(vaultId);
+ });
+});
- await akord.stack.uploadRevision(stackId, file);
+export const stackCreate = async (vaultId: string) => {
+ const name = faker.random.words();
- const stack = await akord.stack.get(stackId);
- expect(stack.versions.length).toEqual(2);
- expect(stack.versions[0].name).toEqual("logo.png");
- expect(stack.versions[1].name).toEqual("avatar.jpeg");
+ const file = await NodeJs.File.fromPath(testDataPath + firstFileName);
- const { data } = await akord.stack.getVersion(stackId);
- expect(data).toEqual(await file.arrayBuffer());
+ const { stackId } = await akord.stack.create(vaultId, file, name);
- const firstFile = NodeJs.File.fromPath("./src/__tests__/data/logo.png");
- const { data: firstFileData } = await akord.stack.getVersion(stackId, 0);
- expect(firstFileData).toEqual(await firstFile.arrayBuffer());
- });
+ const stack = await akord.stack.get(stackId);
+ expect(stack.status).toEqual("ACTIVE");
+ expect(stack.name).toEqual(name);
+ expect(stack.versions.length).toEqual(1);
+ expect(stack.versions[0].name).toEqual(firstFileName);
- it("should rename the stack", async () => {
- const name = faker.random.words();
+ const binary = await akord.file.get(stack.getUri(StorageType.S3, 0), vaultId);
+ expect(binary).toEqual(await file.arrayBuffer());
+ return stackId;
+}
- await akord.stack.rename(stackId, name);
+export const stackUploadRevision = async (stackId: string) => {
+ const file = await NodeJs.File.fromPath(testDataPath + secondFileName);
- const stack = await akord.stack.get(stackId);
- expect(stack.name).toEqual(name);
- expect(stack.versions.length).toEqual(2);
- expect(stack.versions[0].name).toEqual("logo.png");
- expect(stack.versions[1].name).toEqual("avatar.jpeg");
+ await akord.stack.uploadRevision(stackId, file);
- const firstFile = NodeJs.File.fromPath("./src/__tests__/data/logo.png");
- const { data: firstFileData } = await akord.stack.getVersion(stackId, 0);
- expect(firstFileData).toEqual(await firstFile.arrayBuffer());
+ const stack = await akord.stack.get(stackId);
+ expect(stack.versions.length).toEqual(2);
+ expect(stack.versions[0].name).toEqual(firstFileName);
+ expect(stack.versions[1].name).toEqual(secondFileName);
- const secondFile = NodeJs.File.fromPath("./src/__tests__/data/avatar.jpeg");
+ const { data } = await akord.stack.getVersion(stackId);
+ expect(data).toEqual(await file.arrayBuffer());
- const { data: secondFileData } = await akord.stack.getVersion(stackId);
- expect(secondFileData).toEqual(await secondFile.arrayBuffer());
- });
+ const firstFile = await NodeJs.File.fromPath(testDataPath + firstFileName);
+ const { data: firstFileData } = await akord.stack.getVersion(stackId, 0);
+ expect(firstFileData).toEqual(await firstFile.arrayBuffer());
+}
- it("should revoke the stack", async () => {
- await akord.stack.revoke(stackId)
- const stack = await akord.stack.get(stackId);
- expect(stack.status).toEqual("REVOKED");
- });
+export const stackRename = async (stackId: string) => {
+ const name = faker.random.words();
- it("should restore the stack", async () => {
- await akord.stack.restore(stackId)
- const stack = await akord.stack.get(stackId);
- expect(stack.status).toEqual("ACTIVE");
- });
+ await akord.stack.rename(stackId, name);
- it("should import new stack from arweave tx", async () => {
- const fileTxId = "kzGxbFW_oJ3PyYneRs9cPrChQ-k-8Fym5k9PCZNJ_HA";
- const fileName = fileTxId + ".jpeg";
- const { stackId } = await akord.stack.import(vaultId, fileTxId);
+ const stack = await akord.stack.get(stackId);
+ expect(stack.name).toEqual(name);
+ expect(stack.versions.length).toEqual(2);
+ expect(stack.versions[0].name).toEqual(firstFileName);
+ expect(stack.versions[1].name).toEqual(secondFileName);
- const stack = await akord.stack.get(stackId);
- expect(stack.name).toEqual(fileName);
- expect(stack.versions.length).toEqual(1);
- expect(stack.versions[0].name).toEqual(fileName);
+ const firstFile = await NodeJs.File.fromPath(testDataPath + firstFileName);
+ const { data: firstFileData } = await akord.stack.getVersion(stackId, 0);
+ expect(firstFileData).toEqual(await firstFile.arrayBuffer());
- const { data } = await akord.stack.getVersion(stackId);
- expect(data).toEqual(await getTxData(fileTxId));
- });
-});
+ const secondFile = await NodeJs.File.fromPath(testDataPath + secondFileName);
+
+ const { data: secondFileData } = await akord.stack.getVersion(stackId);
+ expect(secondFileData).toEqual(await secondFile.arrayBuffer());
+}
+
+export const stackRevoke = async (stackId: string) => {
+ await akord.stack.revoke(stackId)
+ const stack = await akord.stack.get(stackId);
+ expect(stack.status).toEqual("REVOKED");
+}
+
+export const stackRestore = async (stackId: string) => {
+ await akord.stack.restore(stackId)
+ const stack = await akord.stack.get(stackId);
+ expect(stack.status).toEqual("ACTIVE");
+}
+
+export const stackImport = async (vaultId: string) => {
+ const fileName = arweaveImportFileTx + ".jpeg";
+ const { stackId } = await akord.stack.import(vaultId, arweaveImportFileTx);
+
+ const stack = await akord.stack.get(stackId);
+ expect(stack.name).toEqual(fileName);
+ expect(stack.versions.length).toEqual(1);
+ expect(stack.versions[0].name).toEqual(fileName);
+
+ const { data } = await akord.stack.getVersion(stackId);
+ expect(data).toEqual(await getTxData(arweaveImportFileTx));
+ return stackId;
+}
diff --git a/src/__tests__/vault.test.ts b/src/__tests__/vault.test.ts
index f5f12146..24fbbcb2 100644
--- a/src/__tests__/vault.test.ts
+++ b/src/__tests__/vault.test.ts
@@ -1,29 +1,14 @@
import { Akord } from "../index";
import faker from '@faker-js/faker';
-import { initInstance } from './helpers';
+import { initInstance, vaultCreate } from './common';
import { email, password } from './data/test-credentials';
let akord: Akord;
jest.setTimeout(3000000);
-async function vaultCreate() {
- const name = faker.random.words();
- const termsOfAccess = faker.lorem.sentences();
- const { vaultId, membershipId } = await akord.vault.create(name, termsOfAccess);
-
- const membership = await akord.membership.get(membershipId);
- expect(membership.status).toEqual("ACCEPTED");
- expect(membership.role).toEqual("OWNER");
-
- const vault = await akord.vault.get(vaultId);
- expect(vault.status).toEqual("ACTIVE");
- expect(vault.name).toEqual(name);
- return { vaultId };
-}
-
describe("Testing vault functions", () => {
- let vaultId: any
+ let vaultId: string;
beforeEach(async () => {
akord = await initInstance(email, password);
@@ -31,7 +16,7 @@ describe("Testing vault functions", () => {
beforeAll(async () => {
akord = await initInstance(email, password);
- vaultId = (await vaultCreate()).vaultId;
+ vaultId = (await vaultCreate(akord)).vaultId;
});
it("should rename the vault", async () => {
diff --git a/src/akord.ts b/src/akord.ts
index e5f3b6ef..dac06c6f 100644
--- a/src/akord.ts
+++ b/src/akord.ts
@@ -12,7 +12,6 @@ import { StackService } from "./core/stack";
import { NoteService } from "./core/note";
import { ManifestService } from "./core/manifest";
import { ProfileService } from "./core/profile";
-import { Auth } from "./auth";
import { CacheBusters } from "./types/cacheable";
import { FileService } from "./core/file";
import { BatchService } from "./core/batch";
@@ -34,20 +33,17 @@ export class Akord {
public batch: BatchService;
public contract: ContractService;
- public static init: (wallet: Wallet, jwtToken?: string, config?: ClientConfig) => Promise;
- public static auth = new Auth();
+ public static init: (wallet: Wallet, config?: ClientConfig) => Promise;
- // TODO: JWT token provider
/**
* @param {ClientConfig} config
* @param {Wallet} [wallet]
- * @param {string} [jwtToken]
*/
- constructor(wallet?: Wallet, jwtToken?: string, config: ClientConfig = {}) {
+ constructor(wallet?: Wallet, config: ClientConfig = {}) {
Logger.debug = config.debug;
CacheBusters.cache = config.cache;
Crypto.configure({ wallet: wallet });
- this.api = config.api ? config.api : new AkordApi(config, jwtToken);
+ this.api = config.api ? config.api : new AkordApi(config);
this.vault = new VaultService(wallet, this.api);
this.memo = new MemoService(wallet, this.api);
this.folder = new FolderService(wallet, this.api);
diff --git a/src/api/akord-api.ts b/src/api/akord-api.ts
index ab15b789..893efd25 100644
--- a/src/api/akord-api.ts
+++ b/src/api/akord-api.ts
@@ -7,56 +7,58 @@ import { Membership, MembershipKeys, RoleType } from "../types/membership";
import { ContractInput, ContractState, Tags } from "../types/contract";
import { NodeType } from "../types/node";
import { Vault } from "../types/vault";
+import { Transaction } from "../types/transaction";
import { Paginated } from "../types/paginated";
+import { ListOptions, VaultApiGetOptions } from "../types/query-options";
+import { User, UserPublicInfo } from "../types/user";
+import { FileDownloadOptions, FileUploadOptions } from "../core/file";
+import { AxiosResponseHeaders } from "axios";
+
+export const defaultFileUploadOptions = {
+ shouldBundleTransaction: true,
+ public: false
+};
export default class AkordApi extends Api {
public config!: ApiConfig;
- public jwtToken: string;
- constructor(config: ClientConfig, jwtToken: string) {
+ constructor(config: ClientConfig) {
super();
this.config = apiConfig(config.env);
- this.jwtToken = jwtToken;
}
- public async uploadData(items: { data: any, tags: Tags, metadata?: any }[], shouldBundleTransaction?: boolean)
- : Promise> {
-
+ public async uploadData(items: { data: any, tags: Tags }[], options: FileUploadOptions = defaultFileUploadOptions)
+ : Promise> {
const resources = [];
await Promise.all(items.map(async (item, index) => {
const resource = await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
- .data(item.data)
- .tags(item.tags)
- .bundle(shouldBundleTransaction)
- .metadata(item.metadata)
+ .data({ data: item.data, tags: item.tags })
+ .bundle(options.shouldBundleTransaction)
.uploadState()
- Logger.log("Uploaded state with id: " + resource.id);
+ Logger.log("Uploaded state with id: " + resource);
resources[index] = resource;
}));
return resources;
};
- public async postContractTransaction(contractId: string, input: ContractInput, tags: Tags, metadata?: any): Promise {
- const txId = await new ApiClient()
+ public async postContractTransaction(contractId: string, input: ContractInput, tags: Tags, metadata?: any): Promise<{ id: string, object: T }> {
+ const { id, object } = await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.vaultId(contractId)
+ .metadata(metadata)
.input(input)
- .metadata(metadata ? metadata : {})
.tags(tags)
- .transaction()
- Logger.log("Uploaded contract interaction with id: " + txId);
- return txId;
+ .transaction()
+ Logger.log("Uploaded contract interaction with id: " + id);
+ return { id, object };
};
public async getMembers(vaultId: string): Promise> {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.vaultId(vaultId)
.getMembers();
};
@@ -64,102 +66,107 @@ export default class AkordApi extends Api {
public async initContractId(tags: Tags, state?: any): Promise {
const contractId = await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.data({ tags, state })
.contract()
Logger.log("Created contract with id: " + contractId);
return contractId;
};
- public async getUserFromEmail(email: string): Promise {
- return await new ApiClient()
- .env(this.config)
- .auth(this.jwtToken)
- .resourceId(email)
- .getUser();
- };
-
- public async uploadFile(file: any, tags: Tags, isPublic?: boolean, shouldBundleTransaction?: boolean, progressHook?: (progress: number, data?: any) => void, cancelHook?: AbortController): Promise<{ resourceUrl: string, resourceTx: string }> {
+ public async uploadFile(file: ArrayBuffer, tags: Tags, options: FileUploadOptions = defaultFileUploadOptions): Promise<{ resourceUrl: string, resourceTx: string }> {
+ const uploadOptions = {
+ ...defaultFileUploadOptions,
+ ...options
+ }
const resource = await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.data(file)
.tags(tags)
- .public(isPublic)
- .bundle(shouldBundleTransaction)
- .progressHook(progressHook)
- .cancelHook(cancelHook)
+ .public(uploadOptions.public)
+ .bundle(uploadOptions.shouldBundleTransaction)
+ .progressHook(uploadOptions.progressHook)
+ .cancelHook(uploadOptions.cancelHook)
.uploadFile()
Logger.log("Uploaded file with id: " + resource.id);
return resource;
};
- public async downloadFile(id: string, isPublic?: boolean, progressHook?: (progress: number, data?: any) => void, cancelHook?: AbortController, numberOfChunks?: number, loadedSize?: number, resourceSize?: number): Promise {
+ public async downloadFile(id: string, options: FileDownloadOptions = {}): Promise<{ fileData: ArrayBuffer, headers: AxiosResponseHeaders }> {
const { response } = await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.resourceId(id)
- .public(isPublic)
- .numberOfChunks(numberOfChunks)
- .progressHook(progressHook, loadedSize, resourceSize)
- .cancelHook(cancelHook)
+ .public(options.public)
+ .numberOfChunks(options.numberOfChunks)
+ .progressHook(options.progressHook, options.loadedSize, options.resourceSize)
+ .cancelHook(options.cancelHook)
.asArrayBuffer()
.downloadFile();
- let fileData: any;
- if (response.headers['x-amz-meta-encryptedkey']) {
- fileData = response.data;
- } else {
- fileData = Buffer.from(response.data).toJSON();
- }
+ const fileData = response.data;
return { fileData: fileData, headers: response.headers };
};
- public async getProfile(): Promise {
+ public async existsUser(email: string): Promise {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
- .getProfile();
+ .resourceId(email)
+ .existsUser();
+ }
+
+ public async getUserPublicData(email: string): Promise {
+ return await new ApiClient()
+ .env(this.config)
+ .resourceId(email)
+ .getUserPublicData();
+ };
+
+ public async getUser(): Promise {
+ return await new ApiClient()
+ .env(this.config)
+ .getUser();
};
- public async updateProfile(name: string, avatarUri: string): Promise {
+ public async updateUser(name: string, avatarUri: string[]): Promise {
await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.data({
name: name,
avatarUri: avatarUri
})
- .updateProfile();
+ .updateUser();
};
public async deleteVault(vaultId: string): Promise {
await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.vaultId(vaultId)
.deleteVault();
}
- public async inviteNewUser(vaultId: string, email: string, role: RoleType): Promise<{ id: string }> {
+ public async inviteNewUser(vaultId: string, email: string, role: RoleType, message?: string): Promise<{ id: string }> {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.vaultId(vaultId)
.data({
email: email,
role: role
})
+ .metadata({ message })
.invite();
}
+ public async revokeInvite(vaultId: string, membershipId: string): Promise<{ id: string }> {
+ return await new ApiClient()
+ .env(this.config)
+ .vaultId(vaultId)
+ .resourceId(membershipId)
+ .revokeInvite();
+ }
public async inviteResend(vaultId: string, membershipId: string): Promise<{ id: string }> {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.vaultId(vaultId)
.resourceId(membershipId)
.inviteResend();
@@ -168,7 +175,6 @@ export default class AkordApi extends Api {
public async getNode(id: string, type: NodeType): Promise {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.resourceId(id)
.queryParams({ type })
.getNode();
@@ -177,23 +183,27 @@ export default class AkordApi extends Api {
public async getMembership(id: string): Promise {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.resourceId(id)
.getMembership();
};
- public async getVault(id: string): Promise {
+ public async getVault(id: string, options?: VaultApiGetOptions): Promise {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.resourceId(id)
+ .queryParams({
+ withNodes: options?.withNodes,
+ withMemberships: options?.deep,
+ withMemos: options?.deep,
+ withStacks: options?.deep,
+ withFolders: options?.deep,
+ })
.getVault();
};
public async getMembershipKeys(vaultId: string): Promise {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.vaultId(vaultId)
.getMembershipKeys();
};
@@ -201,7 +211,6 @@ export default class AkordApi extends Api {
public async getNodeState(stateId: string): Promise {
const { response } = await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.resourceId(stateId)
.downloadState()
@@ -211,7 +220,6 @@ export default class AkordApi extends Api {
public async getNotifications(): Promise> {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.getNotifications()
};
@@ -223,7 +231,6 @@ export default class AkordApi extends Api {
}): Promise {
await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.queryParams(options)
.patchNotifications()
};
@@ -231,56 +238,63 @@ export default class AkordApi extends Api {
public async getContractState(objectId: string): Promise {
const contract = await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.vaultId(objectId)
.getContract();
return contract.state;
};
- public async getMemberships(): Promise> {
+ public async getMemberships(limit?: number, nextToken?: string): Promise> {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
+ .queryParams({
+ limit,
+ nextToken
+ })
.getMemberships();
};
- public async getVaults(): Promise> {
+ public async getVaults(filter = {}, limit?: number, nextToken?: string): Promise> {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
+ .queryParams({
+ filter: JSON.stringify(filter),
+ limit,
+ nextToken
+ })
.getVaults();
};
- public async getNodesByVaultId(vaultId: string, type: NodeType, parentId?: string, filter = {}, limit?: number, nextToken?: string): Promise> {
+ public async getNodesByVaultId(vaultId: string, type: NodeType, options: ListOptions): Promise> {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.vaultId(vaultId)
.queryParams({
type,
- parentId,
- filter: JSON.stringify(filter),
- limit,
- nextToken
+ parentId: options.parentId,
+ filter: JSON.stringify(options.filter ? options.filter : {}),
+ limit: options.limit,
+ nextToken: options.nextToken
})
.getNodesByVaultId();
};
- public async getMembershipsByVaultId(vaultId: string, filter = {}, limit?: number, nextToken?: string): Promise> {
+ public async getMembershipsByVaultId(vaultId: string, options: ListOptions): Promise> {
return await new ApiClient()
.env(this.config)
- .auth(this.jwtToken)
.vaultId(vaultId)
.queryParams({
- filter: JSON.stringify(filter),
- limit,
- nextToken
+ filter: JSON.stringify(options.filter ? options.filter : {}),
+ limit: options.limit,
+ nextToken: options.nextToken
})
.getMembershipsByVaultId();
};
- public async getTransactions(vaultId: string): Promise> {
- throw new Error("Method not implemented");
+ public async getTransactions(vaultId: string): Promise> {
+ return await new ApiClient()
+ .env(this.config)
+ .vaultId(vaultId)
+ .getTransactions();
}
}
diff --git a/src/api/api-authenticator.ts b/src/api/api-authenticator.ts
deleted file mode 100644
index 6d183189..00000000
--- a/src/api/api-authenticator.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import "cross-fetch/polyfill";
-import * as AmazonCognitoIdentity from "amazon-cognito-identity-js";
-import { EnvType } from "../config";
-import { apiConfig, ApiConfig } from "./config";
-import { Logger } from "../logger";
-
-export default class ApiAuthenticator {
- public config!: ApiConfig;
-
- constructor(config?: EnvType) {
- this.config = apiConfig(config);
- }
-
- public getCognitoUser(username: string): AmazonCognitoIdentity.CognitoUser {
- const userPool = this.getCognitoUserPool();
- const userData = {
- Username: username,
- Pool: userPool
- };
- const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
- return cognitoUser;
- }
-
- public getCognitoUserPool(): AmazonCognitoIdentity.CognitoUserPool {
- const poolData = {
- UserPoolId: this.config.aws_user_pools_id,
- ClientId: this.config.aws_user_pools_web_client_id
- };
- const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
- return userPool;
- }
-
- public async getJWTToken(username: string, password: string): Promise {
- const { session } = await this.authenticateUser(username, password);
- return session.getIdToken().getJwtToken();
- }
-
- public async authenticateUser(username: string, password: string): Promise<{
- user: AmazonCognitoIdentity.CognitoUser,
- session: AmazonCognitoIdentity.CognitoUserSession
- }> {
- const cognitoUser = this.getCognitoUser(username);
- const authenticationData = {
- Username: username,
- Password: password,
- };
- const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
- return new Promise((resolve, reject) => {
- cognitoUser.authenticateUser(authenticationDetails, {
- onSuccess: function (result) {
- resolve({ user: cognitoUser, session: result })
- },
- onFailure: function (err) {
- Logger.log(err.message);
- Logger.log(JSON.stringify(err));
- return reject(err.message);
- }
- })
- }
- );
- }
-
- public async getUserAttributes(email: string, password: string): Promise