@openstax/ts-utils 1.31.0 → 1.31.2

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.
@@ -38,7 +38,7 @@ export type ApiClientResponse<Ro> = Ro extends any ? {
38
38
  } : never;
39
39
  export type ExpandRoute<T> = T extends ((...args: infer A) => infer R) & {
40
40
  renderUrl: (...args: infer Ar) => Promise<string>;
41
- } ? (...args: A) => R & {
41
+ } ? ((...args: A) => R) & {
42
42
  renderUrl: (...args: Ar) => Promise<string>;
43
43
  } : never;
44
44
  export type MapRoutesToClient<Ru> = [Ru] extends [AnyRoute<Ru>] ? {
@@ -13,6 +13,18 @@ export declare const isFolderValue: (thing: any) => thing is FolderValue;
13
13
  export interface FileServerAdapter {
14
14
  putFileContent: (source: FileValue, content: string) => Promise<FileValue>;
15
15
  getSignedViewerUrl: (source: FileValue) => Promise<string>;
16
+ getPublicViewerUrl: (source: FileValue) => Promise<string>;
16
17
  getFileContent: (source: FileValue) => Promise<Buffer>;
18
+ getSignedFileUploadConfig: () => Promise<{
19
+ url: string;
20
+ payload: {
21
+ [key: string]: string;
22
+ };
23
+ }>;
24
+ copyFileTo: (source: FileValue, destinationPath: string) => Promise<FileValue>;
25
+ copyFileToDirectory: (source: FileValue, destinationDirectory: string) => Promise<FileValue>;
26
+ isTemporaryUpload: (source: FileValue) => boolean;
27
+ getFileChecksum: (source: FileValue) => Promise<string>;
28
+ filesEqual: (sourceA: FileValue, sourceB: FileValue) => Promise<boolean>;
17
29
  }
18
30
  export declare const isFileOrFolder: (thing: any) => thing is FileValue | FolderValue;
@@ -5,18 +5,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.localFileServer = void 0;
7
7
  /* cspell:ignore originalname */
8
+ const crypto_1 = __importDefault(require("crypto"));
8
9
  const fs_1 = __importDefault(require("fs"));
9
10
  const https_1 = __importDefault(require("https"));
10
11
  const path_1 = __importDefault(require("path"));
11
12
  const cors_1 = __importDefault(require("cors"));
12
13
  const express_1 = __importDefault(require("express"));
13
14
  const multer_1 = __importDefault(require("multer"));
15
+ const uuid_1 = require("uuid");
14
16
  const assertions_1 = require("../../assertions");
15
17
  const config_1 = require("../../config");
16
18
  const guards_1 = require("../../guards");
17
19
  const helpers_1 = require("../../misc/helpers");
18
20
  /* istanbul ignore next */
19
- const startServer = (0, helpers_1.once)((port, uploadDir) => {
21
+ const startServer = (0, helpers_1.memoize)((port, uploadDir) => {
20
22
  // TODO - re-evaluate the `preservePath` behavior to match whatever s3 does
21
23
  const upload = (0, multer_1.default)({ dest: uploadDir, preservePath: true });
22
24
  const fileServerApp = (0, express_1.default)();
@@ -61,6 +63,9 @@ const localFileServer = (initializer) => (configProvider) => {
61
63
  const getSignedViewerUrl = async (source) => {
62
64
  return `https://${await host}:${await port}/${source.path}`;
63
65
  };
66
+ const getPublicViewerUrl = async (source) => {
67
+ return `https://${await host}:${await port}/${source.path}`;
68
+ };
64
69
  const getFileContent = async (source) => {
65
70
  const filePath = path_1.default.join(await fileDir, source.path);
66
71
  return fs_1.default.promises.readFile(filePath);
@@ -72,10 +77,56 @@ const localFileServer = (initializer) => (configProvider) => {
72
77
  await fs_1.default.promises.writeFile(filePath, content);
73
78
  return source;
74
79
  };
80
+ const getSignedFileUploadConfig = async () => {
81
+ const prefix = 'uploads/' + (0, uuid_1.v4)();
82
+ return {
83
+ url: `https://${await host}:${await port}/`,
84
+ payload: {
85
+ key: prefix + '/${filename}',
86
+ }
87
+ };
88
+ };
89
+ const copyFileTo = async (source, destinationPath) => {
90
+ const sourcePath = path_1.default.join(await fileDir, source.path);
91
+ const destPath = path_1.default.join(await fileDir, destinationPath);
92
+ const destDirectory = path_1.default.dirname(destPath);
93
+ await fs_1.default.promises.mkdir(destDirectory, { recursive: true });
94
+ await fs_1.default.promises.copyFile(sourcePath, destPath);
95
+ return {
96
+ ...source,
97
+ path: destinationPath
98
+ };
99
+ };
100
+ const copyFileToDirectory = async (source, destination) => {
101
+ const destinationPath = path_1.default.join(destination, source.label);
102
+ return copyFileTo(source, destinationPath);
103
+ };
104
+ const isTemporaryUpload = (source) => {
105
+ return source.path.indexOf('uploads/') === 0;
106
+ };
107
+ const getFileChecksum = async (source) => {
108
+ const filePath = path_1.default.join(await fileDir, source.path);
109
+ const fileContent = await fs_1.default.promises.readFile(filePath);
110
+ return crypto_1.default.createHash('md5').update(fileContent).digest('hex');
111
+ };
112
+ const filesEqual = async (sourceA, sourceB) => {
113
+ const [aSum, bSum] = await Promise.all([
114
+ getFileChecksum(sourceA),
115
+ getFileChecksum(sourceB)
116
+ ]);
117
+ return aSum === bSum;
118
+ };
75
119
  return {
76
120
  getSignedViewerUrl,
121
+ getPublicViewerUrl,
77
122
  getFileContent,
78
123
  putFileContent,
124
+ getSignedFileUploadConfig,
125
+ copyFileTo,
126
+ copyFileToDirectory,
127
+ isTemporaryUpload,
128
+ getFileChecksum,
129
+ filesEqual,
79
130
  };
80
131
  };
81
132
  exports.localFileServer = localFileServer;
@@ -4,6 +4,7 @@ import { FileServerAdapter } from '.';
4
4
  export type Config = {
5
5
  bucketName: string;
6
6
  bucketRegion: string;
7
+ publicViewerDomain?: string;
7
8
  };
8
9
  interface Initializer<C> {
9
10
  configSpace?: C;
@@ -1,9 +1,15 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.s3FileServer = void 0;
4
7
  /* cspell:ignore presigner */
5
8
  const client_s3_1 = require("@aws-sdk/client-s3");
9
+ const s3_presigned_post_1 = require("@aws-sdk/s3-presigned-post");
6
10
  const s3_request_presigner_1 = require("@aws-sdk/s3-request-presigner");
11
+ const path_1 = __importDefault(require("path"));
12
+ const uuid_1 = require("uuid");
7
13
  const __1 = require("../..");
8
14
  const assertions_1 = require("../../assertions");
9
15
  const config_1 = require("../../config");
@@ -12,6 +18,9 @@ const s3FileServer = (initializer) => (configProvider) => {
12
18
  const config = configProvider[(0, guards_1.ifDefined)(initializer.configSpace, 'deployed')];
13
19
  const bucketName = (0, __1.once)(() => (0, config_1.resolveConfigValue)(config.bucketName));
14
20
  const bucketRegion = (0, __1.once)(() => (0, config_1.resolveConfigValue)(config.bucketRegion));
21
+ const publicViewerDomain = (0, __1.once)(() => 'publicViewerDomain' in config && config.publicViewerDomain
22
+ ? (0, config_1.resolveConfigValue)(config.publicViewerDomain)
23
+ : undefined);
15
24
  const s3Service = (0, __1.once)(async () => {
16
25
  var _a, _b;
17
26
  const args = { apiVersion: '2012-08-10', region: await bucketRegion() };
@@ -27,6 +36,10 @@ const s3FileServer = (initializer) => (configProvider) => {
27
36
  expiresIn: 3600, // 1 hour
28
37
  });
29
38
  };
39
+ const getPublicViewerUrl = async (source) => {
40
+ const host = (0, assertions_1.assertDefined)(await publicViewerDomain(), new Error(`Tried to get public viewer URL for ${source.path} but no publicViewerDomain configured`));
41
+ return `https://${host}/${source.path}`;
42
+ };
30
43
  const getFileContent = async (source) => {
31
44
  const bucket = await bucketName();
32
45
  const command = new client_s3_1.GetObjectCommand({ Bucket: bucket, Key: source.path });
@@ -44,10 +57,75 @@ const s3FileServer = (initializer) => (configProvider) => {
44
57
  await (await s3Service()).send(command);
45
58
  return source;
46
59
  };
60
+ /*
61
+ * https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/modules/_aws_sdk_s3_presigned_post.html
62
+ * https://docs.aws.amazon.com/AmazonS3/latest/userguide/HTTPPOSTExamples.html
63
+ * https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html
64
+ */
65
+ const getSignedFileUploadConfig = async () => {
66
+ const prefix = 'uploads/' + (0, uuid_1.v4)();
67
+ const bucket = (await bucketName());
68
+ const Conditions = [
69
+ { acl: 'private' },
70
+ { bucket },
71
+ ['starts-with', '$key', prefix]
72
+ ];
73
+ const defaultFields = {
74
+ acl: 'private',
75
+ };
76
+ const { url, fields } = await (0, s3_presigned_post_1.createPresignedPost)(await s3Service(), {
77
+ Bucket: bucket,
78
+ Key: prefix + '/${filename}',
79
+ Conditions,
80
+ Fields: defaultFields,
81
+ Expires: 3600, // 1 hour
82
+ });
83
+ return {
84
+ url, payload: fields
85
+ };
86
+ };
87
+ const copyFileTo = async (source, destinationPath) => {
88
+ const bucket = (await bucketName());
89
+ const destinationPathWithoutLeadingSlash = destinationPath.replace(/^\//, '');
90
+ const command = new client_s3_1.CopyObjectCommand({
91
+ Bucket: bucket,
92
+ Key: destinationPathWithoutLeadingSlash,
93
+ CopySource: path_1.default.join(bucket, source.path),
94
+ });
95
+ await (await s3Service()).send(command);
96
+ return {
97
+ ...source,
98
+ path: destinationPathWithoutLeadingSlash
99
+ };
100
+ };
101
+ const copyFileToDirectory = async (source, destination) => {
102
+ const destinationPath = path_1.default.join(destination, source.label);
103
+ return copyFileTo(source, destinationPath);
104
+ };
105
+ const isTemporaryUpload = (source) => {
106
+ return source.path.indexOf('uploads/') === 0;
107
+ };
108
+ const getFileChecksum = async (source) => {
109
+ const bucket = (await bucketName());
110
+ const command = new client_s3_1.HeadObjectCommand({ Bucket: bucket, Key: source.path });
111
+ const response = await (await s3Service()).send(command);
112
+ return (0, assertions_1.assertDefined)(response.ETag);
113
+ };
114
+ const filesEqual = async (sourceA, sourceB) => {
115
+ const [aSum, bSum] = await Promise.all([getFileChecksum(sourceA), getFileChecksum(sourceB)]);
116
+ return aSum === bSum;
117
+ };
47
118
  return {
48
119
  getFileContent,
49
120
  putFileContent,
50
121
  getSignedViewerUrl,
122
+ getPublicViewerUrl,
123
+ getSignedFileUploadConfig,
124
+ copyFileTo,
125
+ copyFileToDirectory,
126
+ isTemporaryUpload,
127
+ getFileChecksum,
128
+ filesEqual,
51
129
  };
52
130
  };
53
131
  exports.s3FileServer = s3FileServer;
@@ -29,10 +29,6 @@ const openSearchService = (initializer = {}) => (configProvider) => {
29
29
  maxRetries: 4, // default is 3
30
30
  requestTimeout: 5000, // default is 30000
31
31
  pingTimeout: 2000, // default is 30000
32
- sniffOnConnectionFault: true,
33
- sniffOnStart: true,
34
- resurrectStrategy: 'ping',
35
- agent: { keepAlive: false },
36
32
  node: await (0, config_1.resolveConfigValue)(config.node),
37
33
  }));
38
34
  return (indexConfig) => {
@@ -68,6 +64,9 @@ const openSearchService = (initializer = {}) => (configProvider) => {
68
64
  body: params.body,
69
65
  id: params.id,
70
66
  refresh: true
67
+ }, {
68
+ requestTimeout: 10000,
69
+ maxRetries: 1,
71
70
  });
72
71
  };
73
72
  const bulkIndex = async (items) => {
@@ -79,6 +78,9 @@ const openSearchService = (initializer = {}) => (configProvider) => {
79
78
  item.body
80
79
  ]),
81
80
  refresh: true
81
+ }, {
82
+ requestTimeout: 10000,
83
+ maxRetries: 1,
82
84
  });
83
85
  };
84
86
  const search = async (options) => {