UNPKG

shomix-testing-b-u

Version:

Typescript library for uploading files or directory from the Browser to IPFS, Filecoin or Arweave via Spheron

272 lines (268 loc) 9.38 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // src/index.ts var src_exports = {}; __export(src_exports, { ProtocolEnum: () => import_shomix_testing_core.ProtocolEnum, UploadResult: () => import_shomix_testing_core.UploadResult, decryptUpload: () => decryptUpload, encryptUpload: () => encryptUpload, upload: () => upload }); module.exports = __toCommonJS(src_exports); var import_shomix_testing_core = require("shomix-testing-core"); // src/file-payload-creator.ts var import_form_data = __toESM(require("form-data")); var createPayloads = (files, payloadSize) => __async(void 0, null, function* () { const uploadContext = { payloads: new Array(), currentPayload: null, currentPayloadSize: 0, totalSize: 0 }; files.forEach((file) => { if (file.size > payloadSize) { const chunks = splitFileIntoChunks(file, payloadSize); chunks.forEach((chunk, index) => { const form = new import_form_data.default(); form.append( `chunk-${index}-${chunks.length}`, new File([chunk], file.name), file.name ); uploadContext.payloads.push(form); }); } else { uploadContext.totalSize += file.size; if (!uploadContext.currentPayload) { uploadContext.currentPayload = new import_form_data.default(); } uploadContext.currentPayload.append("files", file, file.name); uploadContext.currentPayloadSize += file.size; if (uploadContext.currentPayloadSize > payloadSize) { uploadContext.payloads.push(uploadContext.currentPayload); uploadContext.currentPayload = null; uploadContext.currentPayloadSize = 0; } } }); if (uploadContext.currentPayload) { uploadContext.payloads.push(uploadContext.currentPayload); } return { payloads: uploadContext.payloads, totalSize: uploadContext.totalSize }; }); function splitFileIntoChunks(file, chunkSize) { const chunks = []; let start = 0; let end = chunkSize; while (start < file.size) { const chunk = file.slice(start, end); chunks.push(chunk); start += chunkSize; end += chunkSize; } return chunks; } // src/index.ts var import_jwt_decode = __toESM(require("jwt-decode")); var import_encryption = require("@spheron/encryption"); function upload(files, configuration) { return __async(this, null, function* () { var _a, _b, _c; let fileList = []; if (files instanceof FileList) { fileList = Array.from(files); } else if (Array.isArray(files)) { fileList = files; } if (!fileList || fileList.length === 0) { throw new Error("No files to upload."); } if (!configuration.token) { throw new Error("No token provided."); } const jwtPayload = (0, import_jwt_decode.default)(configuration.token); const uploadId = (_a = jwtPayload == null ? void 0 : jwtPayload.uploadId) != null ? _a : ""; if (!uploadId) { throw new Error("The provided token is invalid."); } const payloadSize = (_b = jwtPayload == null ? void 0 : jwtPayload.payloadSize) != null ? _b : 5 * 5 * 1024; const parallelUploadCount = (_c = jwtPayload == null ? void 0 : jwtPayload.parallelUploadCount) != null ? _c : 3; const { payloads, totalSize } = yield createPayloads(fileList, payloadSize); let success = true; let caughtError = void 0; const uploadManager = new import_shomix_testing_core.UploadManager(configuration.apiUrl); try { const uploadPayloadsResult = yield uploadManager.uploadPayloads(payloads, { uploadId, token: configuration.token, parallelUploadCount, onChunkUploaded: (uploadedSize) => configuration.onChunkUploaded && configuration.onChunkUploaded(uploadedSize, totalSize) }); if (!uploadPayloadsResult.success) { throw new Error(uploadPayloadsResult.errorMessage); } } catch (error) { success = false; caughtError = error; } const result = yield uploadManager.finalizeUpload( uploadId, success, configuration.token ); if (caughtError) { throw caughtError; } if (!result.success) { throw new Error(`Upload failed. ${result.message}`); } return { uploadId: result.uploadId, bucketId: result.bucketId, protocolLink: result.protocolLink, dynamicLinks: result.dynamicLinks, cid: result.cid }; }); } function encryptUpload(_0) { return __async(this, arguments, function* ({ authSig, sessionSigs, accessControlConditions, evmContractConditions, solRpcConditions, unifiedAccessControlConditions, chain, string, file, litNodeClient, configuration }) { if (!string && !file) throw new Error(`Either string or file must be provided`); if (!(configuration == null ? void 0 : configuration.token)) { throw new Error(`Token must be provided`); } let dataToEncrypt = null; if (string && file) { throw new Error(`Provide only either a string or file to encrypt`); } else if (string) { dataToEncrypt = (0, import_encryption.uint8arrayFromString)(string, "utf8"); } else if (file) { dataToEncrypt = new Uint8Array(yield file.arrayBuffer()); } if (dataToEncrypt === null) throw new Error(`Failed to encrypt data`); const { symmetricKey, encryptedData } = yield (0, import_encryption.encryptData)(dataToEncrypt); const encryptedSymmetricKey = yield litNodeClient.saveEncryptionKey({ accessControlConditions, evmContractConditions, solRpcConditions, unifiedAccessControlConditions, symmetricKey, authSig, sessionSigs, chain }); const encryptedSymmetricKeyString = (0, import_encryption.uint8arrayToString)( encryptedSymmetricKey, "base16" ); const encryptedDataJson = Buffer.from(yield encryptedData).toJSON(); const uploadJson = JSON.stringify({ encryptedData: encryptedDataJson, encryptedSymmetricKeyString, accessControlConditions, evmContractConditions, solRpcConditions, unifiedAccessControlConditions, chain }); const uploadFile = (0, import_encryption.convertJsonToFile)(uploadJson, "data.json"); return yield upload([uploadFile], configuration); }); } function decryptUpload(_0) { return __async(this, arguments, function* ({ authSig, sessionSigs, ipfsCid, litNodeClient }) { const metadataRes = yield (yield fetch(`https://${ipfsCid}.ipfs.sphn.link/data.json`).catch(() => { throw new Error("Error finding metadata from IPFS CID"); })).json(); const metadata = JSON.parse(metadataRes); const symmetricKey = yield litNodeClient.getEncryptionKey({ accessControlConditions: metadata.accessControlConditions, evmContractConditions: metadata.evmContractConditions, solRpcConditions: metadata.solRpcConditions, unifiedAccessControlConditions: metadata.unifiedAccessControlConditions, toDecrypt: metadata.encryptedSymmetricKeyString, chain: metadata.chain, authSig, sessionSigs }); const encrypted = new Uint8Array(Buffer.from(metadata.encryptedData)); return (0, import_encryption.decryptData)(encrypted, symmetricKey); }); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { ProtocolEnum, UploadResult, decryptUpload, encryptUpload, upload });