zenodo 1.0.2 → 3.0.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.
Files changed (89) hide show
  1. package/README.md +60 -0
  2. package/lib/Zenodo.d.ts +91 -0
  3. package/lib/Zenodo.d.ts.map +1 -0
  4. package/lib/Zenodo.js +186 -0
  5. package/lib/Zenodo.js.map +1 -0
  6. package/lib/ZenodoAuthenticationStates.d.ts +21 -0
  7. package/lib/ZenodoAuthenticationStates.d.ts.map +1 -0
  8. package/lib/ZenodoAuthenticationStates.js +20 -0
  9. package/lib/ZenodoAuthenticationStates.js.map +1 -0
  10. package/lib/ZenodoFile.d.ts +9 -0
  11. package/lib/ZenodoFile.d.ts.map +1 -0
  12. package/lib/ZenodoFile.js +22 -0
  13. package/lib/ZenodoFile.js.map +1 -0
  14. package/lib/depositions/Deposition.d.ts +98 -0
  15. package/lib/depositions/Deposition.d.ts.map +1 -0
  16. package/lib/depositions/Deposition.js +224 -0
  17. package/lib/depositions/Deposition.js.map +1 -0
  18. package/lib/depositions/ListDepositionsOptions.d.ts +34 -0
  19. package/lib/depositions/ListDepositionsOptions.d.ts.map +1 -0
  20. package/lib/depositions/ListDepositionsOptions.js +2 -0
  21. package/lib/depositions/ListDepositionsOptions.js.map +1 -0
  22. package/lib/depositions/Record.d.ts +10 -0
  23. package/lib/depositions/Record.d.ts.map +1 -0
  24. package/lib/depositions/Record.js +19 -0
  25. package/lib/depositions/Record.js.map +1 -0
  26. package/lib/fetchZenodo.d.ts +55 -0
  27. package/lib/fetchZenodo.d.ts.map +1 -0
  28. package/lib/fetchZenodo.js +233 -0
  29. package/lib/fetchZenodo.js.map +1 -0
  30. package/lib/index.d.ts +4 -0
  31. package/lib/index.d.ts.map +1 -0
  32. package/lib/index.js +4 -0
  33. package/lib/index.js.map +1 -0
  34. package/lib/responseStatuses.d.ts +8 -0
  35. package/lib/responseStatuses.d.ts.map +1 -0
  36. package/lib/responseStatuses.js +68 -0
  37. package/lib/responseStatuses.js.map +1 -0
  38. package/lib/utilities/ZenodoDepositionSchema.d.ts +473 -0
  39. package/lib/utilities/ZenodoDepositionSchema.d.ts.map +1 -0
  40. package/lib/utilities/ZenodoDepositionSchema.js +80 -0
  41. package/lib/utilities/ZenodoDepositionSchema.js.map +1 -0
  42. package/lib/utilities/ZenodoFileSchema.d.ts +39 -0
  43. package/lib/utilities/ZenodoFileSchema.d.ts.map +1 -0
  44. package/lib/utilities/ZenodoFileSchema.js +37 -0
  45. package/lib/utilities/ZenodoFileSchema.js.map +1 -0
  46. package/lib/utilities/ZenodoMetadataSchema.d.ts +400 -0
  47. package/lib/utilities/ZenodoMetadataSchema.d.ts.map +1 -0
  48. package/lib/utilities/ZenodoMetadataSchema.js +602 -0
  49. package/lib/utilities/ZenodoMetadataSchema.js.map +1 -0
  50. package/lib/utilities/ZenodoRecordSchema.d.ts +544 -0
  51. package/lib/utilities/ZenodoRecordSchema.d.ts.map +1 -0
  52. package/lib/utilities/ZenodoRecordSchema.js +70 -0
  53. package/lib/utilities/ZenodoRecordSchema.js.map +1 -0
  54. package/lib/utilities/ZenodoReviewSchema.d.ts +112 -0
  55. package/lib/utilities/ZenodoReviewSchema.d.ts.map +1 -0
  56. package/lib/utilities/ZenodoReviewSchema.js +80 -0
  57. package/lib/utilities/ZenodoReviewSchema.js.map +1 -0
  58. package/lib/utilities/licensesEnum.d.ts +4 -0
  59. package/lib/utilities/licensesEnum.d.ts.map +1 -0
  60. package/lib/utilities/licensesEnum.js +449 -0
  61. package/lib/utilities/licensesEnum.js.map +1 -0
  62. package/lib/utilities/schemaValidation.d.ts +50 -0
  63. package/lib/utilities/schemaValidation.d.ts.map +1 -0
  64. package/lib/utilities/schemaValidation.js +124 -0
  65. package/lib/utilities/schemaValidation.js.map +1 -0
  66. package/lib/utilities/zipFiles.d.ts +9 -0
  67. package/lib/utilities/zipFiles.d.ts.map +1 -0
  68. package/lib/utilities/zipFiles.js +28 -0
  69. package/lib/utilities/zipFiles.js.map +1 -0
  70. package/package.json +41 -8
  71. package/src/Zenodo.ts +238 -0
  72. package/src/ZenodoAuthenticationStates.ts +22 -0
  73. package/src/ZenodoFile.ts +26 -0
  74. package/src/depositions/Deposition.ts +272 -0
  75. package/src/depositions/ListDepositionsOptions.ts +38 -0
  76. package/src/depositions/Record.ts +25 -0
  77. package/src/fetchZenodo.ts +439 -0
  78. package/src/index.ts +5 -0
  79. package/src/responseStatuses.ts +85 -0
  80. package/src/utilities/ZenodoDepositionSchema.ts +90 -0
  81. package/src/utilities/ZenodoFileSchema.ts +40 -0
  82. package/src/utilities/ZenodoMetadataSchema.ts +608 -0
  83. package/src/utilities/ZenodoRecordSchema.ts +75 -0
  84. package/src/utilities/ZenodoReviewSchema.ts +84 -0
  85. package/src/utilities/licensesEnum.ts +448 -0
  86. package/src/utilities/schemaValidation.ts +150 -0
  87. package/src/utilities/zipFiles.ts +36 -0
  88. package/History.md +0 -73
  89. package/src/index.js +0 -171
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zipFiles.js","sourceRoot":"","sources":["../../src/utilities/zipFiles.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEtD,SAAS,CAAC;IACR,oBAAoB,EAAE,IAAI;IAC1B,aAAa,EAAE,KAAK;CACrB,CAAC,CAAC;AAEH;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,KAAa,EAAE,OAAe;IAC3D,MAAM,aAAa,GAAG,IAAI,eAAe,EAAE,CAAC;IAC5C,MAAM,kBAAkB,GAAG,IAAI,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;IACvE,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAExD,MAAM,kBAAkB,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAC5C,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CACxC,CAAC;IAEF,MAAM,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IACtC,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;IAExB,MAAM,WAAW,GAAG,MAAM,kBAAkB,CAAC;IAE7C,IAAI,WAAW,CAAC,IAAI,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACjD,CAAC;IAED,OAAO,IAAI,IAAI,CAAC,CAAC,WAAW,CAAC,EAAE,GAAG,OAAO,MAAM,EAAE;QAC/C,IAAI,EAAE,iBAAiB;KACxB,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,18 +1,33 @@
1
1
  {
2
2
  "name": "zenodo",
3
- "version": "1.0.2",
3
+ "version": "3.0.0",
4
4
  "description": "Node.js library to access the Zenodo API",
5
- "main": "src/index.js",
5
+ "type": "module",
6
+ "exports": "./lib/index.js",
7
+ "files": [
8
+ "src",
9
+ "lib"
10
+ ],
6
11
  "scripts": {
7
- "test": "echo OK"
12
+ "build": "npm run tsc && cheminfo-build --entry lib/index.js --root Zenodo",
13
+ "build-watch": "fswatch -o src | xargs -n1 -I{} npm run build",
14
+ "check-types": "tsc --noEmit",
15
+ "clean": "rimraf lib",
16
+ "eslint": "eslint src",
17
+ "eslint-fix": "npm run eslint -- --fix",
18
+ "prepack": "npm run tsc",
19
+ "prettier": "prettier --check src",
20
+ "prettier-write": "prettier --write src",
21
+ "test": "npm run test-only && npm run eslint && npm run prettier && npm run check-types && npm run verify-build",
22
+ "test-only": "vitest run --coverage",
23
+ "tsc": "npm run clean && npm run tsc-build",
24
+ "tsc-build": "tsc --project tsconfig.build.json",
25
+ "verify-build": "npm run tsc && node lib/index.js"
8
26
  },
9
27
  "repository": {
10
28
  "type": "git",
11
29
  "url": "git+https://github.com/cheminfo/zenodo.git"
12
30
  },
13
- "files": [
14
- "src"
15
- ],
16
31
  "keywords": [],
17
32
  "author": "Michaël Zasso",
18
33
  "license": "MIT",
@@ -21,7 +36,25 @@
21
36
  },
22
37
  "homepage": "https://github.com/cheminfo/zenodo#readme",
23
38
  "dependencies": {
24
- "axios": "^0.21.1"
39
+ "@zip.js/zip.js": "^2.7.62",
40
+ "ajv": "^8.17.1",
41
+ "ajv-formats": "^3.0.1",
42
+ "delay": "^6.0.0",
43
+ "orcid-utils": "^1.2.2"
25
44
  },
26
- "devDependencies": {}
45
+ "devDependencies": {
46
+ "@types/node": "^24.0.3",
47
+ "@vitest/coverage-v8": "^3.2.3",
48
+ "@zakodium/tsconfig": "^1.0.2",
49
+ "cheminfo-build": "^1.2.1",
50
+ "cheminfo-types": "^1.8.1",
51
+ "dotenv": "^16.5.0",
52
+ "eslint": "^9.29.0",
53
+ "eslint-config-cheminfo-typescript": "^18.0.1",
54
+ "fifo-logger": "^1.0.0",
55
+ "json-schema-to-ts": "^3.1.1",
56
+ "prettier": "^3.5.3",
57
+ "rimraf": "^6.0.1",
58
+ "vitest": "^3.2.3"
59
+ }
27
60
  }
package/src/Zenodo.ts ADDED
@@ -0,0 +1,238 @@
1
+ import type { Logger } from 'cheminfo-types';
2
+
3
+ import { ZenodoAuthenticationStates } from './ZenodoAuthenticationStates.ts';
4
+ import type { ZenodoAuthenticationStatesType } from './ZenodoAuthenticationStates.ts';
5
+ import { Deposition } from './depositions/Deposition.ts';
6
+ import type { ListDepositionsOptions } from './depositions/ListDepositionsOptions.ts';
7
+ import { Record } from './depositions/Record.ts';
8
+ import { fetchZenodo } from './fetchZenodo.ts';
9
+ import type { ZenodoMetadata } from './utilities/ZenodoMetadataSchema.ts';
10
+ import type { ZenodoReview } from './utilities/ZenodoReviewSchema.ts';
11
+
12
+ interface ZenodoOptions {
13
+ accessToken: string;
14
+ host?: string;
15
+ logger?: Logger;
16
+ }
17
+
18
+ interface PublicRecordOptions {
19
+ isPublished?: boolean;
20
+ }
21
+
22
+ export class Zenodo {
23
+ host: string;
24
+ accessToken: string;
25
+ baseURL: string;
26
+ logger?: Logger;
27
+ authenticationState: ZenodoAuthenticationStatesType;
28
+
29
+ constructor(options: ZenodoOptions) {
30
+ const { accessToken, host = 'sandbox.zenodo.org', logger } = options;
31
+ this.host = host;
32
+ this.baseURL = `https://${host}/api/`;
33
+ this.logger = logger;
34
+ this.accessToken = accessToken;
35
+ this.authenticationState = ZenodoAuthenticationStates.NOT_TRIED;
36
+ }
37
+
38
+ /**
39
+ * Create a new Zenodo instance.
40
+ * This method authenticates the user and initializes a new Zenodo instance.
41
+ * @param options - the options for creating a Zenodo instance
42
+ * @throws {Error} If the authentication fails
43
+ * @returns a new Zenodo instance
44
+ */
45
+ static async create(options: ZenodoOptions): Promise<Zenodo> {
46
+ const zenodo = new Zenodo(options);
47
+ const response = await fetchZenodo(zenodo, {
48
+ route: 'deposit/depositions',
49
+ expectedStatus: 200,
50
+ });
51
+ if (!response.ok) {
52
+ throw new Error(`Failed to authenticate: ${response.statusText}`);
53
+ }
54
+ zenodo.logger?.info('Authenticated successfully');
55
+ zenodo.authenticationState = ZenodoAuthenticationStates.SUCCEEDED;
56
+ return zenodo;
57
+ }
58
+
59
+ /**
60
+ * Verify the authentication state of the Zenodo instance.
61
+ * This method checks if the access token is valid by making a request to the Zenodo API.
62
+ * @returns true if authentication is successful, false otherwise.
63
+ */
64
+ async verifyAuthentication(): Promise<boolean> {
65
+ const url = `${this.baseURL}deposit/depositions`;
66
+ const headers = new Headers();
67
+
68
+ if (this.accessToken) {
69
+ headers.set('Authorization', `Bearer ${this.accessToken}`);
70
+ }
71
+
72
+ // can't use fetchZenodo to avoid circular dependency
73
+ try {
74
+ const response = await fetch(url, {
75
+ method: 'GET',
76
+ headers,
77
+ });
78
+
79
+ if (response.status === 200) {
80
+ this.authenticationState = ZenodoAuthenticationStates.SUCCEEDED;
81
+ this.logger?.info('Authentication verified successfully');
82
+ return true;
83
+ } else {
84
+ this.authenticationState = ZenodoAuthenticationStates.FAILED;
85
+ this.logger?.warn(
86
+ `Authentication failed with status ${response.status}`,
87
+ );
88
+ return false;
89
+ }
90
+ } catch (error) {
91
+ this.authenticationState = ZenodoAuthenticationStates.FAILED;
92
+ this.logger?.error(
93
+ `Authentication verification failed: ${String(error)}`,
94
+ );
95
+ return false;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * List all depositions
101
+ * @param options - options for listing depositions
102
+ * @returns an array of deposition objects
103
+ */
104
+ async listDepositions(
105
+ options: ListDepositionsOptions = {},
106
+ ): Promise<Deposition[]> {
107
+ // all the values must be string
108
+ const optionsWithStrings = Object.fromEntries(
109
+ Object.entries(options).map(([key, value]) => {
110
+ if (key === 'allVersions') {
111
+ return ['all_versions', String(value)];
112
+ }
113
+ return [key, String(value)];
114
+ }),
115
+ );
116
+
117
+ const response = await fetchZenodo(this, {
118
+ route: 'deposit/depositions',
119
+ searchParams: optionsWithStrings,
120
+ });
121
+ const depositions = (await response.json()) as unknown[];
122
+ this.logger?.info(`Listed ${depositions.length} depositions`);
123
+ return depositions.map(
124
+ (deposition: unknown) => new Deposition(this, deposition),
125
+ );
126
+ }
127
+
128
+ /**
129
+ * Create a new deposition
130
+ * @param metadata - the metadata for the new deposition
131
+ * @throws {Error} If the metadata is invalid or the request fails
132
+ * @description Creates a new deposition with the provided metadata.
133
+ * @returns The created deposition object
134
+ */
135
+ async createDeposition(metadata: ZenodoMetadata): Promise<Deposition> {
136
+ const response = await fetchZenodo(this, {
137
+ route: 'deposit/depositions',
138
+ expectedStatus: 201,
139
+ method: 'POST',
140
+ body: JSON.stringify({ metadata }),
141
+ });
142
+ const deposition = new Deposition(this, await response.json());
143
+ this.logger?.info(`Created deposition ${deposition.value.id}`);
144
+ return deposition;
145
+ }
146
+
147
+ /**
148
+ * Retrieve a deposition by its ID
149
+ * @param id - the deposition id
150
+ * @throws {Error} If the deposition does not exist or the ID is undefined
151
+ * @returns The retrieved deposition object
152
+ */
153
+ async retrieveDeposition(id: number): Promise<Deposition> {
154
+ const response = await fetchZenodo(this, {
155
+ route: `deposit/depositions/${id}`,
156
+ });
157
+ const deposition = await response.json();
158
+ this.logger?.info(`Retrieved deposition ${id}`);
159
+ return new Deposition(this, deposition);
160
+ }
161
+
162
+ /**
163
+ * Retrieve a public deposition record
164
+ * @param id - the deposition id
165
+ * @param options - additional options for the request
166
+ * @throws {Error} If the deposition does not exist or the ID is undefined
167
+ * @returns The public deposition record
168
+ */
169
+ async retrieveRecord(
170
+ id: number,
171
+ options: PublicRecordOptions = {},
172
+ ): Promise<Record> {
173
+ const { isPublished = false } = options;
174
+ const route = isPublished ? `records/${id}` : `records/${id}/draft`;
175
+ const response = await fetchZenodo(this, {
176
+ route,
177
+ });
178
+ const deposition = await response.json();
179
+ this.logger?.info(`Retrieved public deposition ${id}`);
180
+ return new Record(this, deposition);
181
+ }
182
+
183
+ /**
184
+ * List files in a deposition
185
+ * @param depositionId - the deposition id to retrieve requests for
186
+ * @returns An object containing the total number of requests and the list of requests
187
+ */
188
+ async retrieveRequests(
189
+ depositionId?: number,
190
+ ): Promise<{ hits: { total: number; hits: ZenodoReview[] } }> {
191
+ const response = await fetchZenodo(this, {
192
+ route: `requests/`,
193
+ searchParams: {
194
+ q: String(depositionId),
195
+ },
196
+ });
197
+ const requests = (await response.json()) as {
198
+ hits: { total: number; hits: ZenodoReview[] };
199
+ };
200
+ this.logger?.info(
201
+ `Retrieved ${requests.hits.total} requests for deposition ${depositionId}`,
202
+ );
203
+ return requests;
204
+ }
205
+
206
+ /**
207
+ * Retrieve all versions of a deposition
208
+ * @param id - the deposition id
209
+ * @returns unvalidated array of deposition versions
210
+ */
211
+ async retrieveVersions(id: number): Promise<unknown[]> {
212
+ const response = await fetchZenodo(this, {
213
+ route: `records/${id}/versions`,
214
+ });
215
+ const versions = (await response.json()) as {
216
+ hits: { total: number; hits: unknown[] };
217
+ };
218
+ this.logger?.info(
219
+ `Retrieved ${versions?.hits.total} versions for deposition ${id}`,
220
+ );
221
+
222
+ return versions?.hits.hits || [];
223
+ }
224
+
225
+ /**
226
+ * Deletes a deposition.
227
+ * @param id - the deposition id
228
+ * @throws {Error} If the deposition does not exist or the ID is undefined
229
+ */
230
+ async deleteDeposition(id: number): Promise<void> {
231
+ await fetchZenodo(this, {
232
+ method: 'DELETE',
233
+ route: `deposit/depositions/${id}`,
234
+ expectedStatus: 204,
235
+ });
236
+ this.logger?.info(`Deleted deposition ${id}`);
237
+ }
238
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Represents the different states of Zenodo authentication for retry logic.
3
+ *
4
+ * States:
5
+ * - NOT_TRIED: Authentication verification has not been attempted yet
6
+ * - FAILED: Authentication verification has failed
7
+ * - SUCCEEDED: Authentication verification has succeeded
8
+ *
9
+ * Usage in retry mechanism (src/services/zenodoService.ts):
10
+ * The Zenodo API sometimes returns 401 Unauthorized or 403 Forbidden due to temporary issues.
11
+ * - If SUCCEEDED: Access token is valid, safe to retry the request
12
+ * - If FAILED: Access token is invalid/expired, do not retry
13
+ * - If NOT_TRIED: Can attempt authentication once to determine next steps
14
+ */
15
+ export const ZenodoAuthenticationStates = {
16
+ NOT_TRIED: 0,
17
+ FAILED: 1,
18
+ SUCCEEDED: 2,
19
+ } as const;
20
+
21
+ export type ZenodoAuthenticationStatesType =
22
+ (typeof ZenodoAuthenticationStates)[keyof typeof ZenodoAuthenticationStates];
@@ -0,0 +1,26 @@
1
+ import type { Zenodo } from './Zenodo.ts';
2
+ import type { ZenodoFileType } from './utilities/ZenodoFileSchema.ts';
3
+ import { validateZenodoFile } from './utilities/schemaValidation.ts';
4
+
5
+ export class ZenodoFile {
6
+ private zenodo: Zenodo;
7
+ public value: ZenodoFileType;
8
+
9
+ constructor(zenodo: Zenodo, file: unknown) {
10
+ this.value = validateZenodoFile(file);
11
+ this.zenodo = zenodo;
12
+ }
13
+
14
+ async getContentResponse() {
15
+ const link = this.value.links.download;
16
+ const response = await fetch(link, {
17
+ headers: {
18
+ Authorization: `Bearer ${this.zenodo.accessToken}`,
19
+ },
20
+ });
21
+ if (!response.ok) {
22
+ throw new Error(`Failed to fetch ${link}`);
23
+ }
24
+ return response;
25
+ }
26
+ }
@@ -0,0 +1,272 @@
1
+ /* eslint-disable no-await-in-loop */
2
+ import type { Zenodo } from '../Zenodo.ts';
3
+ import { ZenodoFile } from '../ZenodoFile.ts';
4
+ import { fetchZenodo } from '../fetchZenodo.ts';
5
+ import type { ZenodoDeposition } from '../utilities/ZenodoDepositionSchema.ts';
6
+ import type { ZenodoMetadata } from '../utilities/ZenodoMetadataSchema.ts';
7
+ import type { ZenodoReview } from '../utilities/ZenodoReviewSchema.ts';
8
+ import { validateZenodoDeposition } from '../utilities/schemaValidation.ts';
9
+ import { zipFiles } from '../utilities/zipFiles.ts';
10
+
11
+ export class Deposition {
12
+ private zenodo: Zenodo;
13
+ public value: ZenodoDeposition;
14
+
15
+ constructor(zenodo: Zenodo, deposition: unknown) {
16
+ this.zenodo = zenodo;
17
+ this.value = validateZenodoDeposition(deposition, zenodo.logger);
18
+ }
19
+
20
+ /**
21
+ * This method creates a new file in the deposition. If the file is already it will first
22
+ * delete the existing file and then create a new one.
23
+ * @param file - the file to create in the deposition
24
+ * @returns the created file object
25
+ */
26
+ async createFile(file: File): Promise<ZenodoFile> {
27
+ const createdFile = await this.createFiles([file]);
28
+ if (!createdFile[0]) {
29
+ throw new Error('Failed to create file: No status object returned.');
30
+ }
31
+ return createdFile[0];
32
+ }
33
+
34
+ /**
35
+ * Creates multiple files in the deposition. It will attempt to create each file
36
+ * multiple times with delays in between until all files are successfully created or
37
+ * the maximum number of attempts is reached.
38
+ * @param filesAndNames - an array of File objects to be created in the deposition
39
+ * @returns an array of the created ZenodoFile objects
40
+ */
41
+ async createFiles(filesAndNames: File[]): Promise<ZenodoFile[]> {
42
+ const promises = filesAndNames.map((file) => this.uploadFile(file));
43
+ return await Promise.all(promises);
44
+ }
45
+
46
+ /**
47
+ * Creates a zip file from multiple files and uploads it to the deposition.
48
+ * @param filesAndNames - an array of File objects to be created in the deposition
49
+ * @param zipName - the name of the zip file to be created
50
+ * @returns an array of the created ZenodoFile objects
51
+ */
52
+ async createFilesAsZip(
53
+ filesAndNames: File[],
54
+ zipName: string,
55
+ ): Promise<ZenodoFile[]> {
56
+ const zippedFile = await zipFiles(filesAndNames, zipName);
57
+ return this.createFiles([zippedFile]);
58
+ }
59
+
60
+ /**
61
+ * List all files in the deposition
62
+ * @returns an array of ZenodoFile objects
63
+ */
64
+ async listFiles(): Promise<ZenodoFile[]> {
65
+ const response = await fetchZenodo(this.zenodo, {
66
+ route: `deposit/depositions/${this.value.id}/files`,
67
+ });
68
+ const files = (await response.json()) as unknown[];
69
+ this.zenodo.logger?.info(
70
+ `Listed ${files.length} files for deposition ${this.value.id}`,
71
+ );
72
+ return files.map((file) => new ZenodoFile(this.zenodo, file));
73
+ }
74
+
75
+ /**
76
+ * Delete a file from the deposition
77
+ * @param id - the ID or the name of the file to delete
78
+ */
79
+ async deleteFile(id: string): Promise<void> {
80
+ await fetchZenodo(this.zenodo, {
81
+ route: `deposit/depositions/${this.value.id}/files/${id}`,
82
+ method: 'DELETE',
83
+ expectedStatus: 204,
84
+ });
85
+ this.zenodo.logger?.info(
86
+ `Deleted file ${id} for deposition ${this.value.id}`,
87
+ );
88
+ }
89
+
90
+ /**
91
+ * delete all files from the deposition
92
+ */
93
+ async deleteAllFiles(): Promise<void> {
94
+ const files = await this.listFiles();
95
+ for (const file of files) {
96
+ await this.deleteFile(file.value.id);
97
+ }
98
+ this.zenodo.logger?.info(
99
+ `Deleted all files for deposition ${this.value.id}`,
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Retrieve a file from the deposition
105
+ * @param id - the ID or the name of the file to retrieve
106
+ * @returns the file object
107
+ */
108
+ async retrieveFile(id: string): Promise<ZenodoFile> {
109
+ const response = await fetchZenodo(this.zenodo, {
110
+ route: `deposit/depositions/${this.value.id}/files/${id}`,
111
+ });
112
+ const file = new ZenodoFile(this.zenodo, await response.json());
113
+ this.zenodo.logger?.info(
114
+ `Retrieved file ${id} for deposition ${this.value.id}`,
115
+ );
116
+ return file;
117
+ }
118
+
119
+ /**
120
+ * Update the metadata of the deposition
121
+ * @param metadata - the new metadata to update the deposition with
122
+ * @returns the updated deposition object
123
+ */
124
+ async update(metadata: ZenodoMetadata): Promise<Deposition> {
125
+ const response = await fetchZenodo(this.zenodo, {
126
+ route: `deposit/depositions/${this.value.id}`,
127
+ method: 'PUT',
128
+ body: JSON.stringify({ metadata }),
129
+ });
130
+ const deposition = new Deposition(this.zenodo, await response.json());
131
+ this.zenodo.logger?.info(`Updated deposition ${this.value.id}`);
132
+ return deposition;
133
+ }
134
+
135
+ /**
136
+ * Publish the deposition. This will make it publicly available.
137
+ * !!! Note that the deposition cannot be deleted after it is published.
138
+ * @returns the updated deposition object after publishing
139
+ */
140
+ async publish(): Promise<Deposition> {
141
+ const response = await fetchZenodo(this.zenodo, {
142
+ route: `deposit/depositions/${this.value.id}/actions/publish`,
143
+ method: 'POST',
144
+ expectedStatus: 202,
145
+ });
146
+ const deposition = new Deposition(this.zenodo, await response.json());
147
+ this.zenodo.logger?.info(`Published deposition ${this.value.id}`);
148
+ return deposition;
149
+ }
150
+
151
+ /**
152
+ * Creates a new version of a published deposition.
153
+ * This is useful for updating the deposition with new files or metadata.
154
+ * The new version will have a new ID and will not overwrite the existing deposition.
155
+ * @returns a new deposition object that is a new version of the current deposition
156
+ */
157
+ async newVersion(): Promise<Deposition> {
158
+ const response = await fetchZenodo(this.zenodo, {
159
+ route: `deposit/depositions/${this.value.id}/actions/newversion`,
160
+ method: 'POST',
161
+ expectedStatus: 201,
162
+ });
163
+ const deposition = new Deposition(this.zenodo, await response.json());
164
+ if (
165
+ deposition.value.metadata &&
166
+ !deposition.value.metadata?.publication_date
167
+ ) {
168
+ deposition.value.metadata.publication_date = new Date()
169
+ .toISOString()
170
+ .split('T')[0];
171
+ await deposition.update(deposition.value.metadata);
172
+ }
173
+ this.zenodo.logger?.info(
174
+ `Created new version for deposition ${this.value.id}`,
175
+ );
176
+ return deposition;
177
+ }
178
+
179
+ /**
180
+ * Upload a file to the deposition
181
+ * @param file - the file to upload to the deposition
182
+ * @returns the created file object
183
+ */
184
+ async uploadFile(file: File): Promise<ZenodoFile> {
185
+ const formData = new FormData();
186
+ formData.append('file', file);
187
+ const response = await fetchZenodo(this.zenodo, {
188
+ route: `deposit/depositions/${this.value.id}/files`,
189
+ method: 'POST',
190
+ body: formData,
191
+ expectedStatus: 201,
192
+ });
193
+ const zenodoFile = new ZenodoFile(this.zenodo, await response.json());
194
+ this.zenodo.logger?.info(
195
+ `Created file ${zenodoFile.value.id} for deposition ${this.value.id}`,
196
+ );
197
+ this.value.files?.push(zenodoFile.value);
198
+ return zenodoFile;
199
+ }
200
+
201
+ /**
202
+ * Submits the deposition for review via browser.
203
+ * CORS request won't work from the other endpoint when using a browser.
204
+ * If a URL is provided, it will use that URL to submit the request.
205
+ * Otherwise, it will find the request for the current deposition and submit it.
206
+ * This is not the intended endpoint for submitting requests via browser.
207
+ * But the base endpoint is not CORS enabled.
208
+ * You can find the method with the right endpoint at:
209
+ * https://github.com/cheminfo/zenodo/blob/7fbf3e8bb44246b3465b94b68c21cd3f4fee3bf6/src/depositions/Deposition.ts#L286-L301
210
+ * @param url - optional URL to submit the request
211
+ * @returns The submitted Zenodo request object
212
+ */
213
+ async submitForReview(url?: string): Promise<ZenodoReview> {
214
+ if (url) {
215
+ // If a URL is provided, we assume it's a full API endpoint for submitting the request
216
+ url = url.replace(/.*requests\//, 'requests/');
217
+ const response = await fetchZenodo(this.zenodo, {
218
+ route: url,
219
+ method: 'POST',
220
+ });
221
+ this.zenodo.logger?.info(
222
+ `Submitted deposition ${this.value.id} for review via URL ${url}`,
223
+ );
224
+ return (await response.json()) as ZenodoReview;
225
+ } else {
226
+ const response = await fetchZenodo(this.zenodo, {
227
+ route: `requests`,
228
+ });
229
+ const requests = (await response.json()) as {
230
+ hits: {
231
+ total: number;
232
+ hits: ZenodoReview[];
233
+ };
234
+ };
235
+ const request = requests.hits.hits.find(
236
+ (req) => req.topic.record === String(this.value.id),
237
+ );
238
+ await fetchZenodo(this.zenodo, {
239
+ route: request?.links.actions?.submit,
240
+ method: 'POST',
241
+ expectedStatus: 202,
242
+ });
243
+ this.zenodo.logger?.info(
244
+ `Submitted deposition ${this.value.id} for review`,
245
+ );
246
+ return request as ZenodoReview;
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Adds the deposition to a community.
252
+ * This method adds the deposition to a community by creating a review request.
253
+ * @param communityId - the ID of the community to add the deposition to
254
+ * @returns the response from the Zenodo API
255
+ */
256
+ async addToCommunity(communityId: string): Promise<unknown> {
257
+ const body = JSON.stringify({
258
+ receiver: { community: communityId },
259
+ type: 'community-submission',
260
+ });
261
+ const response = await fetchZenodo(this.zenodo, {
262
+ route: `records/${this.value.id}/draft/review`,
263
+ method: 'PUT',
264
+ body,
265
+ expectedStatus: 200,
266
+ });
267
+ this.zenodo.logger?.info(
268
+ `Added deposition ${this.value.id} to community ${communityId}`,
269
+ );
270
+ return await response.json();
271
+ }
272
+ }
@@ -0,0 +1,38 @@
1
+ export interface ListDepositionsOptions {
2
+ /**
3
+ * Search query (using Elasticsearch query string syntax).
4
+ * Some characters have special meaning here, including `/`, which is also present in full DOIs.
5
+ */
6
+ q?: string;
7
+
8
+ /**
9
+ * Filter result based on deposit status.
10
+ * Possible values: 'draft' | 'published'
11
+ */
12
+ status?: 'draft' | 'published';
13
+
14
+ /**
15
+ * Sort order.
16
+ * Possible values: 'bestmatch' | 'mostrecent'
17
+ * Prefix with minus to change from ascending to descending (e.g., '-mostrecent').
18
+ */
19
+ sort?: 'bestmatch' | 'mostrecent' | '-bestmatch' | '-mostrecent';
20
+
21
+ /**
22
+ * Page number for pagination.
23
+ */
24
+ page?: number;
25
+
26
+ /**
27
+ * Number of results to return per page.
28
+ */
29
+ size?: number;
30
+
31
+ /**
32
+ * Show or hide all versions of deposits.
33
+ * the query is not camelCase but for consistency with other options.
34
+ * the query is translated to `all_versions` in this library.
35
+ * Possible values: 'true' | 'false' | 1 | 0
36
+ */
37
+ allVersions?: 'true' | 'false' | 1 | 0;
38
+ }
@@ -0,0 +1,25 @@
1
+ import type { Zenodo } from '../Zenodo.ts';
2
+ import type { ZenodoRecord } from '../utilities/ZenodoRecordSchema.ts';
3
+ import { validateZenodoRecord } from '../utilities/schemaValidation.ts';
4
+
5
+ import type { Deposition } from './Deposition.ts';
6
+
7
+ export class Record {
8
+ public value: ZenodoRecord;
9
+ private zenodo: Zenodo;
10
+
11
+ constructor(zenodo: Zenodo, value: unknown) {
12
+ this.zenodo = zenodo;
13
+ this.value = validateZenodoRecord(value);
14
+ }
15
+
16
+ async getDeposition(): Promise<Deposition> {
17
+ if (this.value.id === undefined) {
18
+ throw new Error('Deposition ID is undefined');
19
+ }
20
+ if (this.zenodo.accessToken === undefined) {
21
+ throw new Error('Access token is required to retrieve a deposition');
22
+ }
23
+ return await this.zenodo.retrieveDeposition(this.value.id);
24
+ }
25
+ }