zenodo 2.0.0 → 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 (122) hide show
  1. package/README.md +12 -0
  2. package/lib/Zenodo.d.ts +76 -4
  3. package/lib/Zenodo.d.ts.map +1 -1
  4. package/lib/Zenodo.js +150 -19
  5. package/lib/Zenodo.js.map +1 -1
  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 +2 -38
  11. package/lib/ZenodoFile.d.ts.map +1 -1
  12. package/lib/ZenodoFile.js +3 -18
  13. package/lib/ZenodoFile.js.map +1 -1
  14. package/lib/depositions/Deposition.d.ts +90 -6
  15. package/lib/depositions/Deposition.d.ts.map +1 -1
  16. package/lib/depositions/Deposition.js +198 -29
  17. package/lib/depositions/Deposition.js.map +1 -1
  18. package/lib/depositions/ListDepositionsOptions.d.ts +4 -2
  19. package/lib/depositions/ListDepositionsOptions.d.ts.map +1 -1
  20. package/lib/depositions/ListDepositionsOptions.js +1 -2
  21. package/lib/depositions/Record.d.ts +10 -0
  22. package/lib/depositions/Record.d.ts.map +1 -0
  23. package/lib/depositions/Record.js +19 -0
  24. package/lib/depositions/Record.js.map +1 -0
  25. package/lib/fetchZenodo.d.ts +44 -1
  26. package/lib/fetchZenodo.d.ts.map +1 -1
  27. package/lib/fetchZenodo.js +214 -15
  28. package/lib/fetchZenodo.js.map +1 -1
  29. package/lib/index.d.ts +3 -1
  30. package/lib/index.d.ts.map +1 -1
  31. package/lib/index.js +3 -17
  32. package/lib/index.js.map +1 -1
  33. package/lib/responseStatuses.js +1 -4
  34. package/lib/responseStatuses.js.map +1 -1
  35. package/lib/utilities/ZenodoDepositionSchema.d.ts +473 -0
  36. package/lib/utilities/ZenodoDepositionSchema.d.ts.map +1 -0
  37. package/lib/utilities/ZenodoDepositionSchema.js +80 -0
  38. package/lib/utilities/ZenodoDepositionSchema.js.map +1 -0
  39. package/lib/utilities/ZenodoFileSchema.d.ts +39 -0
  40. package/lib/utilities/ZenodoFileSchema.d.ts.map +1 -0
  41. package/lib/utilities/ZenodoFileSchema.js +37 -0
  42. package/lib/utilities/ZenodoFileSchema.js.map +1 -0
  43. package/lib/utilities/ZenodoMetadataSchema.d.ts +400 -0
  44. package/lib/utilities/ZenodoMetadataSchema.d.ts.map +1 -0
  45. package/lib/utilities/ZenodoMetadataSchema.js +602 -0
  46. package/lib/utilities/ZenodoMetadataSchema.js.map +1 -0
  47. package/lib/utilities/ZenodoRecordSchema.d.ts +544 -0
  48. package/lib/utilities/ZenodoRecordSchema.d.ts.map +1 -0
  49. package/lib/utilities/ZenodoRecordSchema.js +70 -0
  50. package/lib/utilities/ZenodoRecordSchema.js.map +1 -0
  51. package/lib/utilities/ZenodoReviewSchema.d.ts +112 -0
  52. package/lib/utilities/ZenodoReviewSchema.d.ts.map +1 -0
  53. package/lib/utilities/ZenodoReviewSchema.js +80 -0
  54. package/lib/utilities/ZenodoReviewSchema.js.map +1 -0
  55. package/lib/utilities/licensesEnum.d.ts +4 -0
  56. package/lib/utilities/licensesEnum.d.ts.map +1 -0
  57. package/lib/utilities/licensesEnum.js +449 -0
  58. package/lib/utilities/licensesEnum.js.map +1 -0
  59. package/lib/utilities/schemaValidation.d.ts +50 -0
  60. package/lib/utilities/schemaValidation.d.ts.map +1 -0
  61. package/lib/utilities/schemaValidation.js +124 -0
  62. package/lib/utilities/schemaValidation.js.map +1 -0
  63. package/lib/utilities/zipFiles.d.ts +9 -0
  64. package/lib/utilities/zipFiles.d.ts.map +1 -0
  65. package/lib/utilities/zipFiles.js +28 -0
  66. package/lib/utilities/zipFiles.js.map +1 -0
  67. package/package.json +28 -22
  68. package/src/Zenodo.ts +180 -10
  69. package/src/ZenodoAuthenticationStates.ts +22 -0
  70. package/src/ZenodoFile.ts +4 -18
  71. package/src/depositions/Deposition.ts +236 -24
  72. package/src/depositions/ListDepositionsOptions.ts +4 -2
  73. package/src/depositions/Record.ts +25 -0
  74. package/src/fetchZenodo.ts +402 -16
  75. package/src/index.ts +5 -1
  76. package/src/utilities/ZenodoDepositionSchema.ts +90 -0
  77. package/src/utilities/ZenodoFileSchema.ts +40 -0
  78. package/src/utilities/ZenodoMetadataSchema.ts +608 -0
  79. package/src/utilities/ZenodoRecordSchema.ts +75 -0
  80. package/src/utilities/ZenodoReviewSchema.ts +84 -0
  81. package/src/utilities/licensesEnum.ts +448 -0
  82. package/src/utilities/schemaValidation.ts +150 -0
  83. package/src/utilities/zipFiles.ts +36 -0
  84. package/lib/depositions/depositionSchema.d.ts +0 -982
  85. package/lib/depositions/depositionSchema.d.ts.map +0 -1
  86. package/lib/depositions/depositionSchema.js +0 -141
  87. package/lib/depositions/depositionSchema.js.map +0 -1
  88. package/lib-esm/Zenodo.d.ts +0 -19
  89. package/lib-esm/Zenodo.d.ts.map +0 -1
  90. package/lib-esm/Zenodo.js +0 -51
  91. package/lib-esm/Zenodo.js.map +0 -1
  92. package/lib-esm/ZenodoFile.d.ts +0 -45
  93. package/lib-esm/ZenodoFile.d.ts.map +0 -1
  94. package/lib-esm/ZenodoFile.js +0 -33
  95. package/lib-esm/ZenodoFile.js.map +0 -1
  96. package/lib-esm/depositions/Deposition.d.ts +0 -14
  97. package/lib-esm/depositions/Deposition.d.ts.map +0 -1
  98. package/lib-esm/depositions/Deposition.js +0 -51
  99. package/lib-esm/depositions/Deposition.js.map +0 -1
  100. package/lib-esm/depositions/ListDepositionsOptions.d.ts +0 -32
  101. package/lib-esm/depositions/ListDepositionsOptions.d.ts.map +0 -1
  102. package/lib-esm/depositions/ListDepositionsOptions.js +0 -2
  103. package/lib-esm/depositions/ListDepositionsOptions.js.map +0 -1
  104. package/lib-esm/depositions/depositionSchema.d.ts +0 -982
  105. package/lib-esm/depositions/depositionSchema.d.ts.map +0 -1
  106. package/lib-esm/depositions/depositionSchema.js +0 -138
  107. package/lib-esm/depositions/depositionSchema.js.map +0 -1
  108. package/lib-esm/fetchZenodo.d.ts +0 -12
  109. package/lib-esm/fetchZenodo.d.ts.map +0 -1
  110. package/lib-esm/fetchZenodo.js +0 -31
  111. package/lib-esm/fetchZenodo.js.map +0 -1
  112. package/lib-esm/index.d.ts +0 -2
  113. package/lib-esm/index.d.ts.map +0 -1
  114. package/lib-esm/index.js +0 -2
  115. package/lib-esm/index.js.map +0 -1
  116. package/lib-esm/responseStatuses.d.ts +0 -8
  117. package/lib-esm/responseStatuses.d.ts.map +0 -1
  118. package/lib-esm/responseStatuses.js +0 -68
  119. package/lib-esm/responseStatuses.js.map +0 -1
  120. package/src/__tests__/Zenodo.test.ts +0 -79
  121. package/src/__tests__/getConfig.ts +0 -9
  122. package/src/depositions/depositionSchema.ts +0 -154
@@ -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,30 +1,28 @@
1
1
  {
2
2
  "name": "zenodo",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "Node.js library to access the Zenodo API",
5
- "main": "./lib/index.js",
6
- "module": "./lib-esm/index.js",
7
- "types": "./lib/index.d.ts",
5
+ "type": "module",
6
+ "exports": "./lib/index.js",
8
7
  "files": [
9
8
  "src",
10
- "lib",
11
- "lib-esm"
9
+ "lib"
12
10
  ],
13
11
  "scripts": {
14
- "build": "npm run tsc-esm && cheminfo-build --entry lib-esm/index.js --root Zenodo",
12
+ "build": "npm run tsc && cheminfo-build --entry lib/index.js --root Zenodo",
15
13
  "build-watch": "fswatch -o src | xargs -n1 -I{} npm run build",
16
14
  "check-types": "tsc --noEmit",
17
- "clean": "rimraf lib lib-esm",
15
+ "clean": "rimraf lib",
18
16
  "eslint": "eslint src",
19
17
  "eslint-fix": "npm run eslint -- --fix",
20
18
  "prepack": "npm run tsc",
21
19
  "prettier": "prettier --check src",
22
20
  "prettier-write": "prettier --write src",
23
- "test": "npm run test-only && npm run eslint && npm run prettier && npm run check-types",
21
+ "test": "npm run test-only && npm run eslint && npm run prettier && npm run check-types && npm run verify-build",
24
22
  "test-only": "vitest run --coverage",
25
- "tsc": "npm run clean && npm run tsc-cjs && npm run tsc-esm",
26
- "tsc-cjs": "tsc --project tsconfig.cjs.json",
27
- "tsc-esm": "tsc --project tsconfig.esm.json"
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"
28
26
  },
29
27
  "repository": {
30
28
  "type": "git",
@@ -37,18 +35,26 @@
37
35
  "url": "https://github.com/cheminfo/zenodo/issues"
38
36
  },
39
37
  "homepage": "https://github.com/cheminfo/zenodo#readme",
38
+ "dependencies": {
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"
44
+ },
40
45
  "devDependencies": {
41
- "@types/node": "^22.13.4",
42
- "@vitest/coverage-v8": "^3.0.5",
46
+ "@types/node": "^24.0.3",
47
+ "@vitest/coverage-v8": "^3.2.3",
48
+ "@zakodium/tsconfig": "^1.0.2",
43
49
  "cheminfo-build": "^1.2.1",
44
- "dotenv": "^16.4.7",
45
- "eslint": "^9.20.1",
46
- "eslint-config-cheminfo-typescript": "^17.0.0",
47
- "prettier": "^3.5.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",
48
57
  "rimraf": "^6.0.1",
49
- "vitest": "^3.0.5"
50
- },
51
- "dependencies": {
52
- "zod": "^3.24.2"
58
+ "vitest": "^3.2.3"
53
59
  }
54
60
  }
package/src/Zenodo.ts CHANGED
@@ -1,45 +1,138 @@
1
- import { Deposition } from './depositions/Deposition';
2
- import type { ListDepositionsOptions } from './depositions/ListDepositionsOptions';
3
- import type { DepositionMetadata } from './depositions/depositionSchema';
4
- import { fetchZenodo } from './fetchZenodo';
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';
5
11
 
6
12
  interface ZenodoOptions {
7
13
  accessToken: string;
8
14
  host?: string;
15
+ logger?: Logger;
16
+ }
17
+
18
+ interface PublicRecordOptions {
19
+ isPublished?: boolean;
9
20
  }
21
+
10
22
  export class Zenodo {
11
23
  host: string;
12
24
  accessToken: string;
13
25
  baseURL: string;
26
+ logger?: Logger;
27
+ authenticationState: ZenodoAuthenticationStatesType;
14
28
 
15
29
  constructor(options: ZenodoOptions) {
16
- const { accessToken, host = 'sandbox.zenodo.org' } = options;
30
+ const { accessToken, host = 'sandbox.zenodo.org', logger } = options;
17
31
  this.host = host;
18
32
  this.baseURL = `https://${host}/api/`;
19
- if (!accessToken) {
20
- throw new Error('accessToken is required');
21
- }
33
+ this.logger = logger;
22
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
+ }
23
97
  }
24
98
 
99
+ /**
100
+ * List all depositions
101
+ * @param options - options for listing depositions
102
+ * @returns an array of deposition objects
103
+ */
25
104
  async listDepositions(
26
105
  options: ListDepositionsOptions = {},
27
106
  ): Promise<Deposition[]> {
28
107
  // all the values must be string
29
108
  const optionsWithStrings = Object.fromEntries(
30
- Object.entries(options).map(([key, value]) => [key, String(value)]),
109
+ Object.entries(options).map(([key, value]) => {
110
+ if (key === 'allVersions') {
111
+ return ['all_versions', String(value)];
112
+ }
113
+ return [key, String(value)];
114
+ }),
31
115
  );
116
+
32
117
  const response = await fetchZenodo(this, {
33
118
  route: 'deposit/depositions',
34
119
  searchParams: optionsWithStrings,
35
120
  });
36
121
  const depositions = (await response.json()) as unknown[];
122
+ this.logger?.info(`Listed ${depositions.length} depositions`);
37
123
  return depositions.map(
38
124
  (deposition: unknown) => new Deposition(this, deposition),
39
125
  );
40
126
  }
41
127
 
42
- async createDeposition(metadata: DepositionMetadata): Promise<Deposition> {
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> {
43
136
  const response = await fetchZenodo(this, {
44
137
  route: 'deposit/depositions',
45
138
  expectedStatus: 201,
@@ -47,22 +140,99 @@ export class Zenodo {
47
140
  body: JSON.stringify({ metadata }),
48
141
  });
49
142
  const deposition = new Deposition(this, await response.json());
143
+ this.logger?.info(`Created deposition ${deposition.value.id}`);
50
144
  return deposition;
51
145
  }
52
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
+ */
53
153
  async retrieveDeposition(id: number): Promise<Deposition> {
54
154
  const response = await fetchZenodo(this, {
55
155
  route: `deposit/depositions/${id}`,
56
156
  });
57
157
  const deposition = await response.json();
158
+ this.logger?.info(`Retrieved deposition ${id}`);
58
159
  return new Deposition(this, deposition);
59
160
  }
60
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
+ */
61
230
  async deleteDeposition(id: number): Promise<void> {
62
231
  await fetchZenodo(this, {
63
232
  method: 'DELETE',
64
233
  route: `deposit/depositions/${id}`,
65
234
  expectedStatus: 204,
66
235
  });
236
+ this.logger?.info(`Deleted deposition ${id}`);
67
237
  }
68
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];
package/src/ZenodoFile.ts CHANGED
@@ -1,27 +1,13 @@
1
- import { z } from 'zod';
2
-
3
- import type { Zenodo } from './Zenodo';
4
-
5
- // Define the Zod schema
6
- export const zenodoFileSchema = z.object({
7
- id: z.string(),
8
- filename: z.string(),
9
- filesize: z.number(),
10
- checksum: z.string(),
11
- links: z.object({
12
- download: z.string().url(),
13
- self: z.string().url(),
14
- }),
15
- });
16
-
17
- type ZenodoFileType = z.infer<typeof zenodoFileSchema>;
1
+ import type { Zenodo } from './Zenodo.ts';
2
+ import type { ZenodoFileType } from './utilities/ZenodoFileSchema.ts';
3
+ import { validateZenodoFile } from './utilities/schemaValidation.ts';
18
4
 
19
5
  export class ZenodoFile {
20
6
  private zenodo: Zenodo;
21
7
  public value: ZenodoFileType;
22
8
 
23
9
  constructor(zenodo: Zenodo, file: unknown) {
24
- this.value = zenodoFileSchema.parse(file);
10
+ this.value = validateZenodoFile(file);
25
11
  this.zenodo = zenodo;
26
12
  }
27
13
 
@@ -1,9 +1,12 @@
1
- import type { Zenodo } from '../Zenodo';
2
- import { ZenodoFile } from '../ZenodoFile';
3
- import { fetchZenodo } from '../fetchZenodo';
4
-
5
- import { zenodoDepositionSchema } from './depositionSchema';
6
- import type { DepositionMetadata, ZenodoDeposition } from './depositionSchema';
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';
7
10
 
8
11
  export class Deposition {
9
12
  private zenodo: Zenodo;
@@ -11,50 +14,259 @@ export class Deposition {
11
14
 
12
15
  constructor(zenodo: Zenodo, deposition: unknown) {
13
16
  this.zenodo = zenodo;
14
- this.value = zenodoDepositionSchema.parse(deposition);
17
+ this.value = validateZenodoDeposition(deposition, zenodo.logger);
15
18
  }
16
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
+ */
17
26
  async createFile(file: File): Promise<ZenodoFile> {
18
- const formData = new FormData();
19
- formData.append('file', file);
20
- const response = await fetchZenodo(this.zenodo, {
21
- route: `deposit/depositions/${this.value.id}/files`,
22
- method: 'POST',
23
- body: formData,
24
- expectedStatus: 201,
25
- });
26
- return new ZenodoFile(this.zenodo, await response.json());
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);
27
44
  }
28
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
+ */
29
64
  async listFiles(): Promise<ZenodoFile[]> {
30
65
  const response = await fetchZenodo(this.zenodo, {
31
66
  route: `deposit/depositions/${this.value.id}/files`,
32
67
  });
33
- const files = (await response.json()) as any[];
68
+ const files = (await response.json()) as unknown[];
69
+ this.zenodo.logger?.info(
70
+ `Listed ${files.length} files for deposition ${this.value.id}`,
71
+ );
34
72
  return files.map((file) => new ZenodoFile(this.zenodo, file));
35
73
  }
36
74
 
37
- async deleteFile(fileId: string): Promise<void> {
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> {
38
80
  await fetchZenodo(this.zenodo, {
39
- route: `deposit/depositions/${this.value.id}/files/${fileId}`,
81
+ route: `deposit/depositions/${this.value.id}/files/${id}`,
40
82
  method: 'DELETE',
41
83
  expectedStatus: 204,
42
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
+ );
43
101
  }
44
102
 
45
- async retrieveFile(fileId: string): Promise<ZenodoFile> {
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> {
46
109
  const response = await fetchZenodo(this.zenodo, {
47
- route: `deposit/depositions/${this.value.id}/files/${fileId}`,
110
+ route: `deposit/depositions/${this.value.id}/files/${id}`,
48
111
  });
49
- return new ZenodoFile(this.zenodo, await response.json());
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;
50
117
  }
51
118
 
52
- async update(metadata: DepositionMetadata): Promise<Deposition> {
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> {
53
125
  const response = await fetchZenodo(this.zenodo, {
54
126
  route: `deposit/depositions/${this.value.id}`,
55
127
  method: 'PUT',
56
128
  body: JSON.stringify({ metadata }),
57
129
  });
58
- return new Deposition(this.zenodo, await response.json());
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();
59
271
  }
60
272
  }