Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

skynet-js

Package Overview
Dependencies
Maintainers
2
Versions
68
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

skynet-js - npm Package Compare versions

Comparing version 2.9.0 to 3.0.0-beta

35

CHANGELOG.md
# Changelog
## [3.0.0-beta]
[Updating Guide](https://siasky.net/docs/v3-beta/#updating-from-v2)
_This beta version is released on the `beta` stream. It can be installed with `npm install skynet-js@beta`._
### Added
- `getFileContent` and `getFileContentHns` methods have been added for getting the content of a file from a skylink or Handshake domain without downloading the file in-browser.
### Changed
- **[Breaking change]** Entry revisions are now `bigint` instead of `number`.
- **[Breaking change]** Upload methods return full objects instead of just a skylink string.
- **[Breaking change]** Upload request methods were removed.
- **[Breaking change]** `getMetadata` returns a full object containing the metadata in a subfield.
- **[Breaking change]** The registry timeout has changed to take seconds instead of milliseconds.
- **[Breaking change]** `db.getJSON` can return destructured nulls instead of null
- **[Breaking change]** `registry.getEntry` only returns `null` on entry-not-found.
- Almost every API method now has the potential to throw. A common cause would be wrongly-typed inputs to a method, which are now checked.
### Removed
- **[Breaking change]** `executeRequest` was removed.
## [2.9.0]

@@ -32,3 +57,3 @@

- Fix `deriveChildSeed` bugs. It will now return hex-encoded strings. Note that it will now return different values than before these bugs were fixed.
- **[Breaking change]** Fix `deriveChildSeed` bugs. It will now return hex-encoded strings. Note that it will now return different values than before these bugs were fixed.
- Fix `setJSON` function not using hex-encoded publickeys when making its request.

@@ -54,6 +79,6 @@ - Do not use a timeout for `setEntry` by default (was 5s previously).

- Rename `keyPairFromSeed` to `genKeyPairFromSeed` and have it return keys in the form of hex strings.
- Rename `generateKeyPairAndSeed` to `genKeyPairAndSeed` and have it return keys in the form of hex strings.
- Use hex strings as keys as inputs to `getJSON`, `setJSON`, `getEntry`, and `setEntry`.
- `setEntry` no longer takes a `datakey` argument as it is already in `entry`.
- **[Breaking change]** Rename `keyPairFromSeed` to `genKeyPairFromSeed` and have it return keys in the form of hex strings.
- **[Breaking change]** Rename `generateKeyPairAndSeed` to `genKeyPairAndSeed` and have it return keys in the form of hex strings.
- **[Breaking change]** Use hex strings as keys as inputs to `getJSON`, `setJSON`, `getEntry`, and `setEntry`.
- **[Breaking change]** `setEntry` no longer takes a `datakey` argument as it is already in `entry`.

@@ -60,0 +85,0 @@ ## [2.4.0]

74

dist/client.d.ts
import { AxiosResponse } from "axios";
import type { Method } from "axios";
import { uploadFile, uploadDirectory, uploadDirectoryRequest, uploadFileRequest } from "./upload";
import { addSkykey, createSkykey, getSkykeyById, getSkykeyByName, getSkykeys } from "./encryption";
import { downloadFile, downloadFileHns, getSkylinkUrl, getHnsUrl, getHnsresUrl, getMetadata, openFile, openFileHns, resolveHns } from "./download";
import { downloadFile, downloadFileHns, getSkylinkUrl, getHnsUrl, getHnsresUrl, getMetadata, getFileContent, getFileContentHns, getFileContentRequest, openFile, openFileHns, resolveHns } from "./download";
/**
* Custom client options.
*
* @property [APIKey] - Authentication password to use.
* @property [customUserAgent] - Custom user agent header to set.
* @property [onUploadProgress] -Optional callback to track upload progress.
*/
export declare type CustomClientOptions = {
/** authentication password to use */
APIKey?: string;
/** custom user agent header to set */
customUserAgent?: string;
/** optional callback to track upload progress */
onUploadProgress?: (progress: number, event: ProgressEvent) => void;
};
/**
* Config options for a single request.
*
* @property [data] - The data for a POST request.
* @property [url] - The full url to contact. Will be computed from the portalUrl and endpointPath if not provided.
* @property [method] - The request method.
* @property [query] - Query parameters.
* @property [timeout] - Request timeout. May be deprecated.
* @property [extraPath] - An additional path to append to the URL, e.g. a 46-character skylink.
*/
export declare type RequestConfig = CustomClientOptions & {
endpointPath: string;
data?: FormData | Record<string, unknown>;
url?: string;
method?: Method;
query?: Record<string, unknown>;
timeout?: number;
extraPath?: string;
skykeyName?: string;
skykeyId?: string;
headers?: Record<string, unknown>;
transformRequest?: (data: unknown) => string;
transformResponse?: (data: string) => Record<string, unknown>;
};
/**
* The Skynet Client which can be used to access Skynet.
*/
export declare class SkynetClient {
portalUrl: string;
customOptions: CustomClientOptions;
/**
* The Skynet Client which can be used to access Skynet.
* @param [portalUrl] The portal URL to use to access Skynet, if specified. To use the default portal while passing custom options, use ""
* @param [customOptions] Configuration for the client
*/
constructor(portalUrl?: string, customOptions?: CustomClientOptions);
uploadFile: typeof uploadFile;
protected uploadFileRequest: typeof uploadFileRequest;
uploadDirectory: typeof uploadDirectory;
uploadDirectoryRequest: typeof uploadDirectoryRequest;
uploadFileRequest: typeof uploadFileRequest;
addSkykey: typeof addSkykey;
createSkykey: typeof createSkykey;
getSkykeyById: typeof getSkykeyById;
getSkykeyByName: typeof getSkykeyByName;
getSkykeys: typeof getSkykeys;
protected uploadDirectoryRequest: typeof uploadDirectoryRequest;
downloadFile: typeof downloadFile;

@@ -37,2 +57,5 @@ downloadFileHns: typeof downloadFileHns;

getMetadata: typeof getMetadata;
getFileContent: typeof getFileContent;
getFileContentHns: typeof getFileContentHns;
protected getFileContentRequest: typeof getFileContentRequest;
openFile: typeof openFile;

@@ -51,7 +74,18 @@ openFileHns: typeof openFileHns;

/**
* The Skynet Client which can be used to access Skynet.
*
* @class
* @param [portalUrl] The portal URL to use to access Skynet, if specified. To use the default portal while passing custom options, use ""
* @param [customOptions] Configuration for the client.
*/
constructor(portalUrl?: string, customOptions?: CustomClientOptions);
/**
* Creates and executes a request.
* @param {Object} config - Configuration for the request. See docs for constructor for the full list of options.
*
* @param config - Configuration for the request.
* @returns - The response from axios.
* @throws - Will throw if unimplemented options have been passed in.
*/
executeRequest(config: any): Promise<AxiosResponse>;
protected executeRequest(config: RequestConfig): Promise<AxiosResponse>;
}
//# sourceMappingURL=client.d.ts.map
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -9,3 +20,2 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

var upload_1 = require("./upload");
var encryption_1 = require("./encryption");
var download_1 = require("./download");

@@ -15,7 +25,12 @@ var skydb_1 = require("./skydb");

var utils_1 = require("./utils");
/**
* The Skynet Client which can be used to access Skynet.
*/
var SkynetClient = /** @class */ (function () {
/**
* The Skynet Client which can be used to access Skynet.
*
* @class
* @param [portalUrl] The portal URL to use to access Skynet, if specified. To use the default portal while passing custom options, use ""
* @param [customOptions] Configuration for the client
* @param [customOptions] Configuration for the client.
*/

@@ -25,11 +40,9 @@ function SkynetClient(portalUrl, customOptions) {

if (customOptions === void 0) { customOptions = {}; }
// Set methods (defined in other files).
// Upload
this.uploadFile = upload_1.uploadFile;
this.uploadFileRequest = upload_1.uploadFileRequest;
this.uploadDirectory = upload_1.uploadDirectory;
this.uploadDirectoryRequest = upload_1.uploadDirectoryRequest;
this.uploadFileRequest = upload_1.uploadFileRequest;
this.addSkykey = encryption_1.addSkykey;
this.createSkykey = encryption_1.createSkykey;
this.getSkykeyById = encryption_1.getSkykeyById;
this.getSkykeyByName = encryption_1.getSkykeyByName;
this.getSkykeys = encryption_1.getSkykeys;
// Download
this.downloadFile = download_1.downloadFile;

@@ -41,2 +54,5 @@ this.downloadFileHns = download_1.downloadFileHns;

this.getMetadata = download_1.getMetadata;
this.getFileContent = download_1.getFileContent;
this.getFileContentHns = download_1.getFileContentHns;
this.getFileContentRequest = download_1.getFileContentRequest;
this.openFile = download_1.openFile;

@@ -61,3 +77,6 @@ this.openFileHns = download_1.openFileHns;

* Creates and executes a request.
* @param {Object} config - Configuration for the request. See docs for constructor for the full list of options.
*
* @param config - Configuration for the request.
* @returns - The response from axios.
* @throws - Will throw if unimplemented options have been passed in.
*/

@@ -69,2 +88,3 @@ SkynetClient.prototype.executeRequest = function (config) {

}
// Build the URL.
var url = config.url;

@@ -77,4 +97,16 @@ if (!url) {

}
// No other headers.
var headers = config.customUserAgent && { "User-Agent": config.customUserAgent };
// Build headers.
var headers = __assign({}, config.headers);
if (config.customUserAgent) {
headers["User-Agent"] = config.customUserAgent;
}
var auth = config.APIKey ? { username: "", password: config.APIKey } : undefined;
/* istanbul ignore next */
var onUploadProgress = config.onUploadProgress &&
function (event) {
var progress = event.loaded / event.total;
// Need the if-statement or TS complains.
if (config.onUploadProgress)
config.onUploadProgress(progress, event);
};
return axios_1["default"]({

@@ -85,9 +117,6 @@ url: url,

headers: headers,
auth: config.APIKey && { username: "", password: config.APIKey },
onUploadProgress: config.onUploadProgress &&
function (event) {
var progress = event.loaded / event.total;
config.onUploadProgress(progress, event);
},
timeout: config.timeout,
auth: auth,
onUploadProgress: onUploadProgress,
transformRequest: config.transformRequest,
transformResponse: config.transformResponse,
maxContentLength: Infinity,

@@ -94,0 +123,0 @@ maxBodyLength: Infinity

@@ -6,23 +6,71 @@ import { pki } from "node-forge";

export declare type Signature = pki.ed25519.NativeBuffer;
/**
* Key pair.
*
* @property publicKey - The public key.
* @property privateKey - The private key.
*/
export declare type KeyPair = {
publicKey: string;
privateKey: string;
};
/**
* Key pair and seed.
*
* @property seed - The secure seed.
*/
export declare type KeyPairAndSeed = KeyPair & {
seed: string;
};
/**
* Takes all given arguments and hashes them.
*
* @param args - Byte arrays to hash.
* @returns - The final hash as a byte array.
*/
export declare function hashAll(...args: Uint8Array[]): Uint8Array;
/**
* Hash the given data key.
*
* @param datakey - Datakey to hash.
* @returns - Hash of the datakey.
*/
export declare function hashDataKey(datakey: string): Uint8Array;
/**
* Hashes the given registry entry.
*
* @param registryEntry - Registry entry to hash.
* @returns - Hash of the registry entry.
*/
export declare function hashRegistryEntry(registryEntry: RegistryEntry): Uint8Array;
/**
* Converts the given bigint into a uint8 array.
*
* @param int - Bigint to encode.
* @returns - Bigint encoded as a byte array.
* @throws - Will throw if the int does not fit in 64 bits.
*/
export declare function encodeBigintAsUint64(int: bigint): Uint8Array;
/**
* Derives a child seed from the given master seed and sub seed.
*
* @param masterSeed - The master seed to derive from.
* @param seed - The sub seed for the derivation.
* @returns - The child seed derived from `masterSeed` using `seed`.
*/
export declare function deriveChildSeed(masterSeed: string, seed: string): string;
/**
* Generates a master key pair and seed.
*
* @param [length=64] - The number of random bytes for the seed. Note that the string seed will be converted to hex representation, making it twice this length.
* @returns -The generated key pair and seed.
*/
export declare function genKeyPairAndSeed(length?: number): {
publicKey: string;
privateKey: string;
seed: string;
};
export declare function genKeyPairAndSeed(length?: number): KeyPairAndSeed;
/**
* Generates a public and private key from a provided, secure seed.
*
* @param seed - A secure seed.
* @returns - The generated key pair.
*/
export declare function genKeyPairFromSeed(seed: string): {
publicKey: string;
privateKey: string;
};
export declare function genKeyPairFromSeed(seed: string): KeyPair;
//# sourceMappingURL=crypto.d.ts.map

@@ -17,3 +17,3 @@ "use strict";

exports.__esModule = true;
exports.genKeyPairFromSeed = exports.genKeyPairAndSeed = exports.deriveChildSeed = exports.hashRegistryEntry = exports.hashDataKey = exports.hashAll = void 0;
exports.genKeyPairFromSeed = exports.genKeyPairAndSeed = exports.deriveChildSeed = exports.encodeBigintAsUint64 = exports.hashRegistryEntry = exports.hashDataKey = exports.hashAll = void 0;
var node_forge_1 = require("node-forge");

@@ -23,7 +23,16 @@ var blakejs_1 = __importDefault(require("blakejs"));

var randombytes_1 = __importDefault(require("randombytes"));
// Returns a blake2b 256bit hasher. See `NewHash` in Sia.
/**
* Returns a blake2b 256bit hasher. See `NewHash` in Sia.
*
* @returns - blake2b 256bit hasher.
*/
function newHash() {
return blakejs_1["default"].blake2bInit(32, null);
}
// Takes all given arguments and hashes them.
/**
* Takes all given arguments and hashes them.
*
* @param args - Byte arrays to hash.
* @returns - The final hash as a byte array.
*/
function hashAll() {

@@ -41,3 +50,8 @@ var args = [];

exports.hashAll = hashAll;
// Hash the given data key.
/**
* Hash the given data key.
*
* @param datakey - Datakey to hash.
* @returns - Hash of the datakey.
*/
function hashDataKey(datakey) {

@@ -47,8 +61,18 @@ return hashAll(encodeString(datakey));

exports.hashDataKey = hashDataKey;
// Hashes the given registry entry.
/**
* Hashes the given registry entry.
*
* @param registryEntry - Registry entry to hash.
* @returns - Hash of the registry entry.
*/
function hashRegistryEntry(registryEntry) {
return hashAll(hashDataKey(registryEntry.datakey), encodeString(registryEntry.data), encodeNumber(registryEntry.revision));
return hashAll(hashDataKey(registryEntry.datakey), encodeString(registryEntry.data), encodeBigintAsUint64(registryEntry.revision));
}
exports.hashRegistryEntry = hashRegistryEntry;
// Converts the given number into a uint8 array
/**
* Converts the given number into a uint8 array
*
* @param num - Number to encode.
* @returns - Number encoded as a byte array.
*/
function encodeNumber(num) {

@@ -63,3 +87,27 @@ var encoded = new Uint8Array(8);

}
// Converts the given string into a uint8 array
/**
* Converts the given bigint into a uint8 array.
*
* @param int - Bigint to encode.
* @returns - Bigint encoded as a byte array.
* @throws - Will throw if the int does not fit in 64 bits.
*/
function encodeBigintAsUint64(int) {
// Assert the input is 64 bits.
utils_1.assertUint64(int);
var encoded = new Uint8Array(8);
for (var index = 0; index < encoded.length; index++) {
var byte = int & BigInt(0xff);
encoded[index] = Number(byte);
int = int >> BigInt(8);
}
return encoded;
}
exports.encodeBigintAsUint64 = encodeBigintAsUint64;
/**
* Converts the given string into a uint8 array.
*
* @param str - String to encode.
* @returns - String encoded as a byte array.
*/
function encodeString(str) {

@@ -71,3 +119,18 @@ var encoded = new Uint8Array(8 + str.length);

}
/**
* Derives a child seed from the given master seed and sub seed.
*
* @param masterSeed - The master seed to derive from.
* @param seed - The sub seed for the derivation.
* @returns - The child seed derived from `masterSeed` using `seed`.
*/
function deriveChildSeed(masterSeed, seed) {
/* istanbul ignore next */
if (typeof masterSeed !== "string") {
throw new Error("Expected parameter masterSeed to be type string, was type " + typeof masterSeed);
}
/* istanbul ignore next */
if (typeof seed !== "string") {
throw new Error("Expected parameter seed to be type string, was type " + typeof seed);
}
return utils_1.toHexString(hashAll(encodeString(masterSeed), encodeString(seed)));

@@ -78,3 +141,5 @@ }

* Generates a master key pair and seed.
*
* @param [length=64] - The number of random bytes for the seed. Note that the string seed will be converted to hex representation, making it twice this length.
* @returns -The generated key pair and seed.
*/

@@ -89,5 +154,11 @@ function genKeyPairAndSeed(length) {

* Generates a public and private key from a provided, secure seed.
*
* @param seed - A secure seed.
* @returns - The generated key pair.
*/
function genKeyPairFromSeed(seed) {
/* istanbul ignore next */
if (typeof seed !== "string") {
throw new Error("Expected parameter seed to be type string, was type " + typeof seed);
}
// Get a 32-byte seed.

@@ -99,2 +170,8 @@ seed = node_forge_1.pkcs5.pbkdf2(seed, "", 1000, 32, node_forge_1.md.sha256.create());

exports.genKeyPairFromSeed = genKeyPairFromSeed;
/**
* Generates a random seed of the given length in bytes.
*
* @param length - Length of the seed in bytes.
* @returns - The generated seed.
*/
function makeSeed(length) {

@@ -101,0 +178,0 @@ // Cryptographically-secure random number generator. It should use the

import { SkynetClient } from "./client";
import { BaseCustomOptions } from "./utils";
/**
* Custom download options.
*
* @property [download=false] - Indicates to `getSkylinkUrl` whether the file should be downloaded (true) or opened in the browser (false). `downloadFile` and `openFile` override this value.
* @property [path=""] - A path to append to the skylink, e.g. `dir1/dir2/file`. A Unix-style path is expected. Each path component will be URL-encoded.
* @property [query={}] - A query object to convert to a query parameter string and append to the URL.
* @property [subdomain=false] - Whether to return the final skylink in subdomain format.
*/
export declare type CustomDownloadOptions = BaseCustomOptions & {
download?: boolean;
path?: string;
query?: Record<string, unknown>;
subdomain?: boolean;
};
/**
* Custom HNS download options.
*
* @property [hnsSubdomain="hns"] - The name of the hns subdomain on the portal.
*/
export declare type CustomHnsDownloadOptions = CustomDownloadOptions & {
hnsSubdomain?: string;
};
/**
* The response for a get file content request.
*
* @property data - The returned file content. Its type is stored in contentType.
* @property contentType - The type of the content.
* @property metadata - The metadata in JSON format.
* @property skylink - 46-character skylink.
*/
export declare type GetFileContentResponse<T = unknown> = {
data: T;
contentType: string;
metadata: Record<string, unknown>;
skylink: string;
};
/**
* The response for a get metadata request.
*
* @property contentType - The type of the content.
* @property metadata - The metadata in JSON format.
* @property skylink - 46-character skylink.
*/
export declare type GetMetadataResponse = {
contentType: string;
metadata: Record<string, unknown>;
skylink: string;
};
/**
* The response for a resolve HNS request.
*
* @property skylink - 46-character skylink.
*/
export declare type ResolveHnsResponse = {
skylink: string;
};
/**
* Initiates a download of the content of the skylink within the browser.
* @param skylink - 46 character skylink, possibly followed by a path or query parameters. Note that the skylink will not be encoded, so if your path might contain special characters, consider using `customOptions.path`.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param {string} [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @param {string} [customOptions.path=""] - A path to append to the skylink, e.g. `dir1/dir2/file`. A Unix-style path is expected. Each path component will be URL-encoded.
* @param {Object} [customOptions.query={}] - A query object to convert to a query parameter string and append to the URL.
* @param {boolean} [customOptions.subdomain=false] - Whether to return the final skylink in subdomain format.
* @returns {string} - The full URL that was used.
*
* @param this - SkynetClient
* @param skylinkUrl - 46-character skylink, or a valid skylink URL. Can be followed by a path. Note that the skylink will not be encoded, so if your path might contain special characters, consider using `customOptions.path`.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL that was used.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
export declare function downloadFile(this: SkynetClient, skylink: string, customOptions?: any): string;
export declare function downloadFile(this: SkynetClient, skylinkUrl: string, customOptions?: CustomDownloadOptions): string;
/**
* Initiates a download of the content of the skylink at the Handshake domain.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL that was used.
*/
export declare function downloadFileHns(this: SkynetClient, domain: string, customOptions?: CustomDownloadOptions): Promise<string>;
/**
* Constructs the full URL for the given skylink.
*
* @param this - SkynetClient
* @param skylinkUrl - Skylink string. See `downloadFile`.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL for the skylink.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
export declare function getSkylinkUrl(this: SkynetClient, skylinkUrl: string, customOptions?: CustomDownloadOptions): string;
/**
* Constructs the full URL for the given HNS domain.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param {string} [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @param {Object} [customOptions.query] - A query object to convert to a query parameter string and append to the URL.
* @param {boolean} [customOptions.subdomain=false] - Whether to return the final URL with the HNS domain as a subdomain.
* @returns {string} - The full URL that was used.
* @param [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL for the HNS domain.
*/
export declare function downloadFileHns(this: SkynetClient, domain: string, customOptions?: any): Promise<string>;
export declare function getSkylinkUrl(this: SkynetClient, skylinkStr: string, customOptions?: any): string;
export declare function getHnsUrl(this: SkynetClient, domain: string, customOptions?: any): string;
export declare function getHnsresUrl(this: SkynetClient, domain: string, customOptions?: any): string;
export declare function getMetadata(this: SkynetClient, skylink: string, customOptions?: any): Promise<any>;
export declare function getHnsUrl(this: SkynetClient, domain: string, customOptions?: CustomHnsDownloadOptions): string;
/**
* Constructs the full URL for the resolver for the given HNS domain.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/hnsres"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL for the resolver for the HNS domain.
*/
export declare function getHnsresUrl(this: SkynetClient, domain: string, customOptions?: BaseCustomOptions): string;
/**
* Gets only the metadata for the given skylink without the contents.
*
* @param this - SkynetClient
* @param skylinkUrl - Skylink string. See `downloadFile`.
* @param [customOptions] - Additional settings that can optionally be set. See `downloadFile` for the full list.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - The metadata in JSON format. Empty if no metadata was found.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
export declare function getMetadata(this: SkynetClient, skylinkUrl: string, customOptions?: CustomDownloadOptions): Promise<GetMetadataResponse>;
/**
* Gets the contents of the file at the given skylink.
*
* @param this - SkynetClient
* @param skylinkUrl - Skylink string. See `downloadFile`.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - An object containing the data of the file, the content-type, metadata, and the file's skylink.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
export declare function getFileContent<T = unknown>(this: SkynetClient, skylinkUrl: string, customOptions?: CustomDownloadOptions): Promise<GetFileContentResponse<T>>;
/**
* Gets the contents of the file at the given Handshake domain.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns - An object containing the data of the file, the content-type, metadata, and the file's skylink.
* @throws - Will throw if the domain does not contain a skylink.
*/
export declare function getFileContentHns<T = unknown>(this: SkynetClient, domain: string, customOptions?: CustomHnsDownloadOptions): Promise<GetFileContentResponse<T>>;
/**
* Does a GET request of the skylink, returning the data property of the response.
*
* @param this - SkynetClient
* @param url - URL.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - An object containing the data of the file, the content-type, metadata, and the file's skylink.
* @throws - Will throw if the request does not succeed or the response is missing data.
*/
export declare function getFileContentRequest<T = unknown>(this: SkynetClient, url: string, customOptions?: CustomDownloadOptions): Promise<GetFileContentResponse<T>>;
/**
* Opens the content of the skylink within the browser.
* @param skylink - 46 character skylink.
* @param [customOptions={}] - Additional settings that can optionally be set.. See `downloadFile` for the full list.
* @param {string} [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
*
* @param this - SkynetClient
* @param skylinkUrl - Skylink string. See `downloadFile`.
* @param [customOptions] - Additional settings that can optionally be set. See `downloadFile` for the full list.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL that was used.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
export declare function openFile(this: SkynetClient, skylink: string, customOptions?: {}): string;
export declare function openFile(this: SkynetClient, skylinkUrl: string, customOptions?: CustomDownloadOptions): string;
/**
* Opens the content of the skylink from the given Handshake domain within the browser.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions={}] - Additional settings that can optionally be set. See `downloadFileHns` for the full list.
* @param {string} [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns {string} - The full URL that was used.
* @param [customOptions] - Additional settings that can optionally be set. See `downloadFileHns` for the full list.
* @param [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL that was used.
*/
export declare function openFileHns(this: SkynetClient, domain: string, customOptions?: {}): Promise<string>;
export declare function openFileHns(this: SkynetClient, domain: string, customOptions?: CustomHnsDownloadOptions): Promise<string>;
/**
* Resolves the given HNS domain to its TXT record and returns the data.
*
* @param this - SkynetClient
* @param domain - Handshake resolver domain.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param {string} [customOptions.endpointPath="/hnsres"] - The relative URL path of the portal endpoint to contact.
* @param {Object} [customOptions.query] - A query object to convert to a query parameter string and append to the URL.
* @param [customOptions.endpointPath="/hnsres"] - The relative URL path of the portal endpoint to contact.
* @returns - The data for the TXT record.
*/
export declare function resolveHns(this: SkynetClient, domain: string, customOptions?: {}): Promise<any>;
export declare function resolveHns(this: SkynetClient, domain: string, customOptions?: BaseCustomOptions): Promise<ResolveHnsResponse>;
//# sourceMappingURL=download.d.ts.map

@@ -50,3 +50,3 @@ "use strict";

exports.__esModule = true;
exports.resolveHns = exports.openFileHns = exports.openFile = exports.getMetadata = exports.getHnsresUrl = exports.getHnsUrl = exports.getSkylinkUrl = exports.downloadFileHns = exports.downloadFile = void 0;
exports.resolveHns = exports.openFileHns = exports.openFile = exports.getFileContentRequest = exports.getFileContentHns = exports.getFileContent = exports.getMetadata = exports.getHnsresUrl = exports.getHnsUrl = exports.getSkylinkUrl = exports.downloadFileHns = exports.downloadFile = void 0;
var utils_1 = require("./utils");

@@ -58,14 +58,17 @@ var defaultDownloadOptions = __assign({}, utils_1.defaultOptions("/"));

* Initiates a download of the content of the skylink within the browser.
* @param skylink - 46 character skylink, possibly followed by a path or query parameters. Note that the skylink will not be encoded, so if your path might contain special characters, consider using `customOptions.path`.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param {string} [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @param {string} [customOptions.path=""] - A path to append to the skylink, e.g. `dir1/dir2/file`. A Unix-style path is expected. Each path component will be URL-encoded.
* @param {Object} [customOptions.query={}] - A query object to convert to a query parameter string and append to the URL.
* @param {boolean} [customOptions.subdomain=false] - Whether to return the final skylink in subdomain format.
* @returns {string} - The full URL that was used.
*
* @param this - SkynetClient
* @param skylinkUrl - 46-character skylink, or a valid skylink URL. Can be followed by a path. Note that the skylink will not be encoded, so if your path might contain special characters, consider using `customOptions.path`.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL that was used.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
function downloadFile(skylink, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
function downloadFile(skylinkUrl, customOptions) {
/* istanbul ignore next */
if (typeof skylinkUrl !== "string") {
throw new Error("Expected parameter skylinkUrl to be type string, was type " + typeof skylinkUrl);
}
var opts = __assign(__assign(__assign(__assign({}, defaultDownloadOptions), this.customOptions), customOptions), { download: true });
var url = this.getSkylinkUrl(skylink, opts);
var url = this.getSkylinkUrl(skylinkUrl, opts);
// Download the url.

@@ -78,14 +81,17 @@ window.location.assign(url);

* Initiates a download of the content of the skylink at the Handshake domain.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param {string} [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @param {Object} [customOptions.query] - A query object to convert to a query parameter string and append to the URL.
* @param {boolean} [customOptions.subdomain=false] - Whether to return the final URL with the HNS domain as a subdomain.
* @returns {string} - The full URL that was used.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL that was used.
*/
function downloadFileHns(domain, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
return __awaiter(this, void 0, void 0, function () {
var opts, url;
return __generator(this, function (_a) {
/* istanbul ignore next */
if (typeof domain !== "string") {
throw new Error("Expected parameter domain to be type string, was type " + typeof domain);
}
opts = __assign(__assign(__assign(__assign({}, defaultDownloadHnsOptions), this.customOptions), customOptions), { download: true });

@@ -100,5 +106,18 @@ url = this.getHnsUrl(domain, opts);

exports.downloadFileHns = downloadFileHns;
function getSkylinkUrl(skylinkStr, customOptions) {
var _a;
if (customOptions === void 0) { customOptions = {}; }
/**
* Constructs the full URL for the given skylink.
*
* @param this - SkynetClient
* @param skylinkUrl - Skylink string. See `downloadFile`.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL for the skylink.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
function getSkylinkUrl(skylinkUrl, customOptions) {
var _a, _b;
/* istanbul ignore next */
if (typeof skylinkUrl !== "string") {
throw new Error("Expected parameter skylinkUrl to be type string, was type " + typeof skylinkUrl);
}
var opts = __assign(__assign(__assign({}, defaultDownloadOptions), this.customOptions), customOptions);

@@ -125,11 +144,10 @@ var query = (_a = opts.query) !== null && _a !== void 0 ? _a : {};

}
// TODO: fix subdomain + includePath
var url;
if (opts.subdomain) {
// Get the path from the skylink.
var skylinkPath = utils_1.parseSkylink(skylinkStr, { onlyPath: true });
// Get the path from the skylink. Use the empty string if not found.
var skylinkPath = (_b = utils_1.parseSkylink(skylinkUrl, { onlyPath: true })) !== null && _b !== void 0 ? _b : "";
// Get just the skylink.
var skylink = utils_1.parseSkylink(skylinkStr);
var skylink = utils_1.parseSkylink(skylinkUrl);
if (skylink === null) {
throw new Error("Could not get skylink out of input '" + skylinkStr + "'");
throw new Error("Could not get skylink out of input '" + skylinkUrl + "'");
}

@@ -143,5 +161,5 @@ // Convert the skylink (without the path) to base32.

// Get the skylink including the path.
var skylink = utils_1.parseSkylink(skylinkStr, { includePath: true });
var skylink = utils_1.parseSkylink(skylinkUrl, { includePath: true });
if (skylink === null) {
throw new Error("Could not get skylink out of input '" + skylinkStr + "'");
throw new Error("Could not get skylink with path out of input '" + skylinkUrl + "'");
}

@@ -154,5 +172,17 @@ // Add additional path if passed in.

exports.getSkylinkUrl = getSkylinkUrl;
/**
* Constructs the full URL for the given HNS domain.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL for the HNS domain.
*/
function getHnsUrl(domain, customOptions) {
var _a;
if (customOptions === void 0) { customOptions = {}; }
/* istanbul ignore next */
if (typeof domain !== "string") {
throw new Error("Expected parameter domain to be type string, was type " + typeof domain);
}
var opts = __assign(__assign(__assign({}, defaultDownloadHnsOptions), this.customOptions), customOptions);

@@ -170,4 +200,16 @@ var query = (_a = opts.query) !== null && _a !== void 0 ? _a : {};

exports.getHnsUrl = getHnsUrl;
/**
* Constructs the full URL for the resolver for the given HNS domain.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/hnsres"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL for the resolver for the HNS domain.
*/
function getHnsresUrl(domain, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
/* istanbul ignore next */
if (typeof domain !== "string") {
throw new Error("Expected parameter domain to be type string, was type " + typeof domain);
}
var opts = __assign(__assign(__assign({}, defaultResolveHnsOptions), this.customOptions), customOptions);

@@ -178,22 +220,35 @@ domain = utils_1.trimUriPrefix(domain, utils_1.uriHandshakeResolverPrefix);

exports.getHnsresUrl = getHnsresUrl;
function getMetadata(skylink, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
/**
* Gets only the metadata for the given skylink without the contents.
*
* @param this - SkynetClient
* @param skylinkUrl - Skylink string. See `downloadFile`.
* @param [customOptions] - Additional settings that can optionally be set. See `downloadFile` for the full list.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - The metadata in JSON format. Empty if no metadata was found.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
function getMetadata(skylinkUrl, customOptions) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var opts, url, response, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
var opts, url, response, contentType, metadata, skylink;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
/* istanbul ignore next */
if (typeof skylinkUrl !== "string") {
throw new Error("Expected parameter skylinkUrl to be type string, was type " + typeof skylinkUrl);
}
opts = __assign(__assign(__assign({}, defaultDownloadOptions), this.customOptions), customOptions);
url = this.getSkylinkUrl(skylink, opts);
_a.label = 1;
url = this.getSkylinkUrl(skylinkUrl, opts);
return [4 /*yield*/, this.executeRequest(__assign(__assign({}, opts), { method: "head", url: url }))];
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.executeRequest(__assign(__assign({}, opts), { method: "head", url: url }))];
case 2:
response = _a.sent();
return [2 /*return*/, response.headers["skynet-file-metadata"] ? JSON.parse(response.headers["skynet-file-metadata"]) : {}];
case 3:
error_1 = _a.sent();
throw new Error("Error getting skynet-file-metadata from skylink");
case 4: return [2 /*return*/];
response = _b.sent();
if (typeof response.headers === "undefined") {
throw new Error("Did not get 'headers' in response despite a successful request. Please try again and report this issue to the devs if it persists.");
}
contentType = (_a = response.headers["content-type"]) !== null && _a !== void 0 ? _a : "";
metadata = response.headers["skynet-file-metadata"] ? JSON.parse(response.headers["skynet-file-metadata"]) : {};
skylink = response.headers["skynet-skylink"] ? utils_1.formatSkylink(response.headers["skynet-skylink"]) : "";
return [2 /*return*/, { contentType: contentType, metadata: metadata, skylink: skylink }];
}

@@ -205,12 +260,99 @@ });

/**
* Gets the contents of the file at the given skylink.
*
* @param this - SkynetClient
* @param skylinkUrl - Skylink string. See `downloadFile`.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - An object containing the data of the file, the content-type, metadata, and the file's skylink.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
function getFileContent(skylinkUrl, customOptions) {
return __awaiter(this, void 0, void 0, function () {
var opts, url;
return __generator(this, function (_a) {
/* istanbul ignore next */
if (typeof skylinkUrl !== "string") {
throw new Error("Expected parameter skylinkUrl to be type string, was type " + typeof skylinkUrl);
}
opts = __assign(__assign(__assign({}, defaultDownloadOptions), this.customOptions), customOptions);
url = this.getSkylinkUrl(skylinkUrl, opts);
return [2 /*return*/, this.getFileContentRequest(url, opts)];
});
});
}
exports.getFileContent = getFileContent;
/**
* Gets the contents of the file at the given Handshake domain.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns - An object containing the data of the file, the content-type, metadata, and the file's skylink.
* @throws - Will throw if the domain does not contain a skylink.
*/
function getFileContentHns(domain, customOptions) {
return __awaiter(this, void 0, void 0, function () {
var opts, url;
return __generator(this, function (_a) {
opts = __assign(__assign(__assign({}, defaultDownloadHnsOptions), this.customOptions), customOptions);
url = this.getHnsUrl(domain, opts);
return [2 /*return*/, this.getFileContentRequest(url, opts)];
});
});
}
exports.getFileContentHns = getFileContentHns;
/**
* Does a GET request of the skylink, returning the data property of the response.
*
* @param this - SkynetClient
* @param url - URL.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - An object containing the data of the file, the content-type, metadata, and the file's skylink.
* @throws - Will throw if the request does not succeed or the response is missing data.
*/
function getFileContentRequest(url, customOptions) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var opts, response, contentType, metadata, skylink;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
opts = __assign(__assign(__assign({}, defaultDownloadOptions), this.customOptions), customOptions);
return [4 /*yield*/, this.executeRequest(__assign(__assign({}, opts), { method: "get", url: url }))];
case 1:
response = _b.sent();
if (typeof response.data === "undefined") {
throw new Error("Did not get 'data' in response despite a successful request. Please try again and report this issue to the devs if it persists.");
}
if (typeof response.headers === "undefined") {
throw new Error("Did not get 'headers' in response despite a successful request. Please try again and report this issue to the devs if it persists.");
}
contentType = (_a = response.headers["content-type"]) !== null && _a !== void 0 ? _a : "";
metadata = response.headers["skynet-file-metadata"] ? JSON.parse(response.headers["skynet-file-metadata"]) : {};
skylink = response.headers["skynet-skylink"] ? utils_1.formatSkylink(response.headers["skynet-skylink"]) : "";
return [2 /*return*/, { data: response.data, contentType: contentType, metadata: metadata, skylink: skylink }];
}
});
});
}
exports.getFileContentRequest = getFileContentRequest;
/**
* Opens the content of the skylink within the browser.
* @param skylink - 46 character skylink.
* @param [customOptions={}] - Additional settings that can optionally be set.. See `downloadFile` for the full list.
* @param {string} [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
*
* @param this - SkynetClient
* @param skylinkUrl - Skylink string. See `downloadFile`.
* @param [customOptions] - Additional settings that can optionally be set. See `downloadFile` for the full list.
* @param [customOptions.endpointPath="/"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL that was used.
* @throws - Will throw if the skylinkUrl does not contain a skylink or if the path option is not a string.
*/
function openFile(skylink, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
function openFile(skylinkUrl, customOptions) {
/* istanbul ignore next */
if (typeof skylinkUrl !== "string") {
throw new Error("Expected parameter skylinkUrl to be type string, was type " + typeof skylinkUrl);
}
var opts = __assign(__assign(__assign({}, defaultDownloadOptions), this.customOptions), customOptions);
var url = this.getSkylinkUrl(skylink, opts);
var url = this.getSkylinkUrl(skylinkUrl, opts);
window.open(url, "_blank");

@@ -222,12 +364,17 @@ return url;

* Opens the content of the skylink from the given Handshake domain within the browser.
*
* @param this - SkynetClient
* @param domain - Handshake domain.
* @param [customOptions={}] - Additional settings that can optionally be set. See `downloadFileHns` for the full list.
* @param {string} [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns {string} - The full URL that was used.
* @param [customOptions] - Additional settings that can optionally be set. See `downloadFileHns` for the full list.
* @param [customOptions.endpointPath="/hns"] - The relative URL path of the portal endpoint to contact.
* @returns - The full URL that was used.
*/
function openFileHns(domain, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
return __awaiter(this, void 0, void 0, function () {
var opts, url;
return __generator(this, function (_a) {
/* istanbul ignore next */
if (typeof domain !== "string") {
throw new Error("Expected parameter domain to be type string, was type " + typeof domain);
}
opts = __assign(__assign(__assign({}, defaultDownloadHnsOptions), this.customOptions), customOptions);

@@ -243,9 +390,11 @@ url = this.getHnsUrl(domain, opts);

/**
* Resolves the given HNS domain to its TXT record and returns the data.
*
* @param this - SkynetClient
* @param domain - Handshake resolver domain.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param {string} [customOptions.endpointPath="/hnsres"] - The relative URL path of the portal endpoint to contact.
* @param {Object} [customOptions.query] - A query object to convert to a query parameter string and append to the URL.
* @param [customOptions.endpointPath="/hnsres"] - The relative URL path of the portal endpoint to contact.
* @returns - The data for the TXT record.
*/
function resolveHns(domain, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
return __awaiter(this, void 0, void 0, function () {

@@ -256,2 +405,6 @@ var opts, url, response;

case 0:
/* istanbul ignore next */
if (typeof domain !== "string") {
throw new Error("Expected parameter domain to be type string, was type " + typeof domain);
}
opts = __assign(__assign(__assign({}, defaultResolveHnsOptions), this.customOptions), customOptions);

@@ -258,0 +411,0 @@ url = this.getHnsresUrl(domain, opts);

export { SkynetClient } from "./client";
export { deriveChildSeed, genKeyPairAndSeed, genKeyPairFromSeed } from "./crypto";
export { MAX_REVISION, defaultPortalUrl, defaultSkynetPortalUrl, getRelativeFilePath, getRootDirectory, parseSkylink, uriHandshakePrefix, uriHandshakeResolverPrefix, uriSkynetPrefix, } from "./utils";
export type { CustomClientOptions, RequestConfig } from "./client";
export type { PublicKey, SecretKey, Signature } from "./crypto";
export type { SignedRegistryEntry, RegistryEntry } from "./registry";
export { defaultPortalUrl, defaultSkynetPortalUrl, getRelativeFilePath, getRootDirectory, parseSkylink, uriHandshakePrefix, uriHandshakeResolverPrefix, uriSkynetPrefix, } from "./utils";
export type { CustomDownloadOptions, ResolveHnsResponse } from "./download";
export type { CustomGetEntryOptions, CustomSetEntryOptions, SignedRegistryEntry, RegistryEntry } from "./registry";
export type { CustomGetJSONOptions, CustomSetJSONOptions, VersionedEntryData } from "./skydb";
export type { CustomUploadOptions, UploadRequestResponse } from "./upload";
export type { ParseSkylinkOptions } from "./utils";
//# sourceMappingURL=index.d.ts.map

@@ -10,3 +10,3 @@ "use strict";

exports.__esModule = true;
exports.uriSkynetPrefix = exports.uriHandshakeResolverPrefix = exports.uriHandshakePrefix = exports.parseSkylink = exports.getRootDirectory = exports.getRelativeFilePath = exports.defaultSkynetPortalUrl = exports.defaultPortalUrl = exports.genKeyPairFromSeed = exports.genKeyPairAndSeed = exports.deriveChildSeed = exports.SkynetClient = void 0;
exports.uriSkynetPrefix = exports.uriHandshakeResolverPrefix = exports.uriHandshakePrefix = exports.parseSkylink = exports.getRootDirectory = exports.getRelativeFilePath = exports.defaultSkynetPortalUrl = exports.defaultPortalUrl = exports.MAX_REVISION = exports.genKeyPairFromSeed = exports.genKeyPairAndSeed = exports.deriveChildSeed = exports.SkynetClient = void 0;
var client_1 = require("./client");

@@ -19,2 +19,3 @@ __createBinding(exports, client_1, "SkynetClient");

var utils_1 = require("./utils");
__createBinding(exports, utils_1, "MAX_REVISION");
__createBinding(exports, utils_1, "defaultPortalUrl");

@@ -21,0 +22,0 @@ __createBinding(exports, utils_1, "defaultSkynetPortalUrl");

import { SkynetClient } from "./client";
import { BaseCustomOptions } from "./utils";
import { Signature } from "./crypto";
/**
* Custom get entry options.
*
* @property [timeout=5] - The custom timeout for getting an entry, in seconds. The maximum value allowed is 300.
*/
export declare type CustomGetEntryOptions = BaseCustomOptions & {
timeout?: number;
};
/**
* Custom set entry options.
*/
export declare type CustomSetEntryOptions = BaseCustomOptions;
export declare const MAX_GET_ENTRY_TIMEOUT = 300;
/**
* Regex for JSON revision value without quotes.
*/
export declare const regexRevisionNoQuotes: RegExp;
/**
* Registry entry.
*
* @property datakey - The key of the data for the given entry.
* @property data - The data stored in the entry.
* @property revision - The revision number for the entry.
*/
export declare type RegistryEntry = {
datakey: string;
data: string;
revision: number;
revision: bigint;
};
/**
* Signed registry entry.
*
* @property entry - The registry entry.
* @property signature - The signature of the registry entry.
*/
export declare type SignedRegistryEntry = {
entry: RegistryEntry;
signature: Signature;
entry: RegistryEntry | null;
signature: Signature | null;
};
/**
* Gets the registry entry corresponding to the publicKey and dataKey.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param [customOptions.timeout=5000] - Timeout in ms for the registry lookup.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The signed registry entry.
* @throws - Will throw if the returned signature does not match the returned entry or the provided timeout is invalid or the given key is not valid.
*/
export declare function getEntry(this: SkynetClient, publicKey: string, dataKey: string, customOptions?: {}): Promise<SignedRegistryEntry | null>;
export declare function getEntryUrl(this: SkynetClient, publicKey: string, dataKey: string, customOptions?: {}): string;
export declare function setEntry(this: SkynetClient, privateKey: string, entry: RegistryEntry, customOptions?: {}): Promise<void>;
export declare function getEntry(this: SkynetClient, publicKey: string, dataKey: string, customOptions?: CustomGetEntryOptions): Promise<SignedRegistryEntry>;
/**
* Gets the registry entry URL corresponding to the publicKey and dataKey.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The full get entry URL.
* @throws - Will throw if the provided timeout is invalid or the given key is not valid.
*/
export declare function getEntryUrl(this: SkynetClient, publicKey: string, dataKey: string, customOptions?: CustomGetEntryOptions): string;
/**
* Sets the registry entry.
*
* @param this - SkynetClient
* @param privateKey - The user private key.
* @param entry - The entry to set.
* @param [customOptions] - Additional settings that can optionally be set.
* @throws - Will throw if the entry revision does not fit in 64 bits or the given key is not valid.
*/
export declare function setEntry(this: SkynetClient, privateKey: string, entry: RegistryEntry, customOptions?: CustomSetEntryOptions): Promise<void>;
//# sourceMappingURL=registry.d.ts.map

@@ -50,3 +50,3 @@ "use strict";

exports.__esModule = true;
exports.setEntry = exports.getEntryUrl = exports.getEntry = void 0;
exports.setEntry = exports.getEntryUrl = exports.getEntry = exports.regexRevisionNoQuotes = exports.MAX_GET_ENTRY_TIMEOUT = void 0;
var node_forge_1 = require("node-forge");

@@ -56,15 +56,26 @@ var utils_1 = require("./utils");

var crypto_1 = require("./crypto");
var defaultGetEntryOptions = __assign(__assign({}, utils_1.defaultOptions("/skynet/registry")), { timeout: 5000 });
var defaultGetEntryOptions = __assign(__assign({}, utils_1.defaultOptions("/skynet/registry")), { timeout: 5 });
var defaultSetEntryOptions = __assign({}, utils_1.defaultOptions("/skynet/registry"));
exports.MAX_GET_ENTRY_TIMEOUT = 300; // 5 minutes
/**
* Regex for JSON revision value without quotes.
*/
exports.regexRevisionNoQuotes = /"revision":\s*([0-9]+)/;
/**
* Regex for JSON revision value with quotes.
*/
var regexRevisionWithQuotes = /"revision":\s*"([0-9]+)"/;
/**
* Gets the registry entry corresponding to the publicKey and dataKey.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param [customOptions.timeout=5000] - Timeout in ms for the registry lookup.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The signed registry entry.
* @throws - Will throw if the returned signature does not match the returned entry or the provided timeout is invalid or the given key is not valid.
*/
function getEntry(publicKey, dataKey, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
return __awaiter(this, void 0, void 0, function () {
var opts, publicKeyBuffer, response, err_1, signedEntry;
var opts, url, publicKeyBuffer, response, err_1, signedEntry;
return __generator(this, function (_a) {

@@ -74,2 +85,3 @@ switch (_a.label) {

opts = __assign(__assign(__assign({}, defaultGetEntryOptions), this.customOptions), customOptions);
url = this.registry.getEntryUrl(publicKey, dataKey, opts);
publicKeyBuffer = buffer_1.Buffer.from(publicKey, "hex");

@@ -79,6 +91,14 @@ _a.label = 1;

_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.executeRequest(__assign(__assign({}, opts), { method: "get", query: {
publickey: "ed25519:" + publicKey,
datakey: utils_1.toHexString(crypto_1.hashDataKey(dataKey))
}, timeout: opts.timeout }))];
return [4 /*yield*/, this.executeRequest(__assign(__assign({}, opts), { url: url, method: "get",
// Transform the response to add quotes, since uint64 cannot be accurately
// read by JS so the revision needs to be parsed as a string.
transformResponse: function (data) {
if (data === undefined) {
return {};
}
// Change the revision value from a JSON integer to a string.
data = data.replace(exports.regexRevisionNoQuotes, '"revision":"$1"');
// Convert the JSON data to an object.
return JSON.parse(data);
} }))];
case 2:

@@ -89,8 +109,15 @@ response = _a.sent();

err_1 = _a.sent();
// unfortunately axios rejects anything that's not >= 200 and < 300
return [2 /*return*/, { entry: null, signature: null }];
case 4:
if (response.status !== 200) {
// @ts-expect-error TS complains about err.response
if (err_1.response.status === 404) {
return [2 /*return*/, { entry: null, signature: null }];
}
// @ts-expect-error TS complains about err.response
throw new Error(err_1.response.data.message);
case 4:
// Sanity check.
if (typeof response.data.data !== "string" ||
typeof response.data.revision !== "string" ||
typeof response.data.signature !== "string") {
throw new Error("Did not get a complete entry response despite a successful request. Please try again and report this issue to the devs if it persists.");
}
signedEntry = {

@@ -100,4 +127,4 @@ entry: {

data: buffer_1.Buffer.from(utils_1.hexToUint8Array(response.data.data)).toString(),
// TODO: Handle uint64 properly.
revision: parseInt(response.data.revision, 10)
// Convert the revision from a string to bigint.
revision: BigInt(response.data.revision)
},

@@ -120,8 +147,35 @@ signature: buffer_1.Buffer.from(utils_1.hexToUint8Array(response.data.signature))

exports.getEntry = getEntry;
/**
* Gets the registry entry URL corresponding to the publicKey and dataKey.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The full get entry URL.
* @throws - Will throw if the provided timeout is invalid or the given key is not valid.
*/
function getEntryUrl(publicKey, dataKey, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
/* istanbul ignore next */
if (typeof publicKey !== "string") {
throw new Error("Expected parameter publicKey to be type string, was type " + typeof publicKey);
}
/* istanbul ignore next */
if (typeof dataKey !== "string") {
throw new Error("Expected parameter dataKey to be type string, was type " + typeof dataKey);
}
var opts = __assign(__assign(__assign({}, defaultGetEntryOptions), this.customOptions), customOptions);
var timeout = opts.timeout;
if (!Number.isInteger(timeout) || timeout > exports.MAX_GET_ENTRY_TIMEOUT || timeout < 1) {
throw new Error("Invalid 'timeout' parameter '" + timeout + "', needs to be an integer between 1s and " + exports.MAX_GET_ENTRY_TIMEOUT + "s");
}
// Trim the prefix if it was passed in.
publicKey = utils_1.trimPrefix(publicKey, "ed25519:");
if (!utils_1.isHexString(publicKey)) {
throw new Error("Given public key '" + publicKey + "' is not a valid hex-encoded string or contains an invalid prefix");
}
var query = {
publickey: "ed25519:" + publicKey,
datakey: utils_1.toHexString(crypto_1.hashDataKey(dataKey))
datakey: utils_1.toHexString(crypto_1.hashDataKey(dataKey)),
timeout: timeout
};

@@ -133,4 +187,12 @@ var url = utils_1.makeUrl(this.portalUrl, opts.endpointPath);

exports.getEntryUrl = getEntryUrl;
/**
* Sets the registry entry.
*
* @param this - SkynetClient
* @param privateKey - The user private key.
* @param entry - The entry to set.
* @param [customOptions] - Additional settings that can optionally be set.
* @throws - Will throw if the entry revision does not fit in 64 bits or the given key is not valid.
*/
function setEntry(privateKey, entry, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
return __awaiter(this, void 0, void 0, function () {

@@ -141,2 +203,14 @@ var opts, privateKeyBuffer, signature, publicKeyBuffer, data;

case 0:
/* istanbul ignore next */
if (typeof privateKey !== "string") {
throw new Error("Expected parameter privateKey to be type string, was type " + typeof privateKey);
}
if (!utils_1.isHexString(privateKey)) {
throw new Error("Expected parameter privateKey to be a hex-encoded string");
}
if (typeof entry !== "object" || entry === null) {
throw new Error("Expected parameter entry to be an object");
}
// Assert the input is 64 bits.
utils_1.assertUint64(entry.revision);
opts = __assign(__assign(__assign({}, defaultSetEntryOptions), this.customOptions), customOptions);

@@ -155,7 +229,17 @@ privateKeyBuffer = buffer_1.Buffer.from(privateKey, "hex");

datakey: utils_1.toHexString(crypto_1.hashDataKey(entry.datakey)),
revision: entry.revision,
// Set the revision as a string here since the value may be up to 64 bits.
// We remove the quotes later in transformRequest.
revision: entry.revision.toString(),
data: Array.from(buffer_1.Buffer.from(entry.data)),
signature: Array.from(signature)
};
return [4 /*yield*/, this.executeRequest(__assign(__assign({}, opts), { method: "post", data: data }))];
return [4 /*yield*/, this.executeRequest(__assign(__assign({}, opts), { method: "post", data: data,
// Transform the request to remove quotes, since the revision needs to be
// parsed as a uint64 on the Go side.
transformRequest: function (data) {
// Convert the object data to JSON.
var json = JSON.stringify(data);
// Change the revision value from a string to a JSON integer.
return json.replace(regexRevisionWithQuotes, '"revision":$1');
} }))];
case 1:

@@ -162,0 +246,0 @@ _a.sent();

import { SkynetClient } from "./client";
import { CustomGetEntryOptions, CustomSetEntryOptions } from "./registry";
import { BaseCustomOptions } from "./utils";
import { CustomUploadOptions } from "./upload";
import { CustomDownloadOptions } from "./download";
/**
* Custom get JSON options.
*/
export declare type CustomGetJSONOptions = BaseCustomOptions & CustomGetEntryOptions & CustomDownloadOptions;
/**
* Custom set JSON options.
*/
export declare type CustomSetJSONOptions = BaseCustomOptions & CustomSetEntryOptions & CustomUploadOptions;
export declare type VersionedEntryData = {
data: Record<string, unknown> | null;
revision: bigint | null;
};
/**
* Gets the JSON object corresponding to the publicKey and dataKey.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param [customOptions.timeout=5000] - Timeout in ms for the registry lookup.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The returned JSON and revision number.
* @throws - Will throw if the returned signature does not match the returned entry, or if the skylink in the entry is invalid.
*/
export declare function getJSON(this: SkynetClient, publicKey: string, dataKey: string, customOptions?: {}): Promise<{
data: Record<string, unknown>;
revision: number;
} | null>;
export declare function getJSON(this: SkynetClient, publicKey: string, dataKey: string, customOptions?: CustomGetJSONOptions): Promise<VersionedEntryData>;
/**
* Sets a JSON object at the registry entry corresponding to the publicKey and dataKey.
*
* @param this - SkynetClient
* @param privateKey - The user private key.
* @param dataKey - The key of the data to fetch for the given user.
* @param json - The JSON data to set.
* @param [revision] - The revision number for the data entry.
* @param [customOptions] - Additional settings that can optionally be set.
* @throws - Will throw if the given entry revision does not fit in 64 bits, or if the revision was not given, if the latest revision of the entry is the maximum revision allowed.
*/
export declare function setJSON(this: SkynetClient, privateKey: string, dataKey: string, json: Record<string, unknown>, revision?: number, customOptions?: {}): Promise<void>;
export declare function setJSON(this: SkynetClient, privateKey: string, dataKey: string, json: Record<string, unknown>, revision?: bigint, customOptions?: CustomSetJSONOptions): Promise<void>;
//# sourceMappingURL=skydb.d.ts.map

@@ -56,11 +56,13 @@ "use strict";

* Gets the JSON object corresponding to the publicKey and dataKey.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param [customOptions.timeout=5000] - Timeout in ms for the registry lookup.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The returned JSON and revision number.
* @throws - Will throw if the returned signature does not match the returned entry, or if the skylink in the entry is invalid.
*/
function getJSON(publicKey, dataKey, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
return __awaiter(this, void 0, void 0, function () {
var opts, entry, skylink, response;
var opts, entry, skylink, data;
return __generator(this, function (_a) {

@@ -74,9 +76,12 @@ switch (_a.label) {

if (entry === null) {
return [2 /*return*/, null];
return [2 /*return*/, { data: null, revision: null }];
}
skylink = utils_1.parseSkylink(entry.data);
return [4 /*yield*/, this.executeRequest(__assign(__assign({}, opts), { method: "get", url: this.getSkylinkUrl(skylink) }))];
skylink = entry.data;
return [4 /*yield*/, this.getFileContent(skylink, opts)];
case 2:
response = _a.sent();
return [2 /*return*/, { data: response.data, revision: entry.revision }];
data = (_a.sent()).data;
if (typeof data !== "object" || data === null) {
throw new Error("File data for the entry at data key '" + dataKey + "' is not JSON.");
}
return [2 /*return*/, { data: data, revision: entry.revision }];
}

@@ -89,31 +94,58 @@ });

* Sets a JSON object at the registry entry corresponding to the publicKey and dataKey.
*
* @param this - SkynetClient
* @param privateKey - The user private key.
* @param dataKey - The key of the data to fetch for the given user.
* @param json - The JSON data to set.
* @param [revision] - The revision number for the data entry.
* @param [customOptions] - Additional settings that can optionally be set.
* @throws - Will throw if the given entry revision does not fit in 64 bits, or if the revision was not given, if the latest revision of the entry is the maximum revision allowed.
*/
function setJSON(privateKey, dataKey, json, revision, customOptions) {
if (customOptions === void 0) { customOptions = {}; }
return __awaiter(this, void 0, void 0, function () {
var opts, privateKeyBuffer, file, skylink, entry_1, publicKey, err_1, entry;
var opts, privateKeyBuffer, publicKey, entry_1, file, skylink, entry;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
/* istanbul ignore next */
if (typeof privateKey !== "string") {
throw new Error("Expected parameter privateKey to be type string, was type " + typeof privateKey);
}
/* istanbul ignore next */
if (typeof dataKey !== "string") {
throw new Error("Expected parameter dataKey to be type string, was type " + typeof dataKey);
}
if (!utils_1.isHexString(privateKey)) {
throw new Error("Expected parameter privateKey to be a hex-encoded string");
}
if (typeof json !== "object" || json === null) {
throw new Error("Expected parameter json to be an object");
}
opts = __assign(__assign({}, this.customOptions), customOptions);
privateKeyBuffer = buffer_1.Buffer.from(privateKey, "hex");
file = new File([JSON.stringify(json)], dataKey, { type: "application/json" });
return [4 /*yield*/, this.uploadFileRequest(file, opts)];
if (!(revision === undefined)) return [3 /*break*/, 2];
publicKey = node_forge_1.pki.ed25519.publicKeyFromPrivateKey({ privateKey: privateKeyBuffer });
return [4 /*yield*/, this.registry.getEntry(utils_1.toHexString(publicKey), dataKey, opts)];
case 1:
skylink = (_a.sent()).skylink;
if (!(revision === undefined)) return [3 /*break*/, 5];
_a.label = 2;
entry_1 = _a.sent();
if (entry_1.entry === null) {
revision = BigInt(0);
}
else {
revision = entry_1.entry.revision + BigInt(1);
}
// Throw if the revision is already the maximum value.
if (revision > utils_1.MAX_REVISION) {
throw new Error("Current entry already has maximum allowed revision, could not update the entry");
}
return [3 /*break*/, 3];
case 2:
_a.trys.push([2, 4, , 5]);
publicKey = node_forge_1.pki.ed25519.publicKeyFromPrivateKey({ privateKey: privateKeyBuffer });
return [4 /*yield*/, this.registry.getEntry(utils_1.toHexString(publicKey), dataKey, opts)];
// Assert the input is 64 bits.
utils_1.assertUint64(revision);
_a.label = 3;
case 3:
entry_1 = _a.sent();
revision = entry_1.entry.revision + 1;
return [3 /*break*/, 5];
file = new File([JSON.stringify(json)], dataKey, { type: "application/json" });
return [4 /*yield*/, this.uploadFile(file, opts)];
case 4:
err_1 = _a.sent();
revision = 0;
return [3 /*break*/, 5];
case 5:
skylink = (_a.sent()).skylink;
entry = {

@@ -124,6 +156,6 @@ datakey: dataKey,

};
// update the registry
// Update the registry.
return [4 /*yield*/, this.registry.setEntry(privateKey, entry)];
case 6:
// update the registry
case 5:
// Update the registry.
_a.sent();

@@ -130,0 +162,0 @@ return [2 /*return*/];

@@ -1,3 +0,13 @@

import { SkynetClient, CustomClientOptions } from "./client";
declare type CustomUploadOptions = {
import { BaseCustomOptions } from "./utils";
import { SkynetClient } from "./client";
import { AxiosResponse } from "axios";
/**
* Custom upload options.
*
* @property [portalFileFieldname="file"] - The file fieldname for uploading files on this portal.
* @property [portalDirectoryfilefieldname="files[]"] - The file fieldname for uploading directories on this portal.
* @property [customFilename] - The custom filename to use when uploading files.
* @property [query] - Query parameters.
*/
export declare type CustomUploadOptions = BaseCustomOptions & {
portalFileFieldname?: string;

@@ -7,20 +17,58 @@ portalDirectoryFileFieldname?: string;

query?: Record<string, unknown>;
} & CustomClientOptions;
export declare function uploadFile(this: SkynetClient, file: File, customOptions?: CustomUploadOptions): Promise<string>;
export declare function uploadFileRequest(this: SkynetClient, file: File, customOptions?: CustomUploadOptions): Promise<any>;
};
/**
* Uploads a local directory to Skynet.
* The response to an upload request.
*
* @property skylink - 46-character skylink.
* @property merkleroot - The hash that is encoded into the skylink.
* @property bitfield - The bitfield that gets encoded into the skylink. The bitfield contains a version, an offset and a length in a heavily compressed and optimized format.
* @property metadata -
*/
export declare type UploadRequestResponse = {
skylink: string;
merkleroot: string;
bitfield: number;
};
/**
* Uploads a file to Skynet.
*
* @param this - SkynetClient
* @param file - The file to upload.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @returns - The returned skylink.
*/
export declare function uploadFile(this: SkynetClient, file: File, customOptions?: CustomUploadOptions): Promise<UploadRequestResponse>;
/**
* Makes a request to upload a file to Skynet.
*
* @param this - SkynetClient
* @param file - The file to upload.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @returns - The upload response.
*/
export declare function uploadFileRequest(this: SkynetClient, file: File, customOptions?: CustomUploadOptions): Promise<AxiosResponse>;
/**
* Uploads a directory to Skynet.
*
* @param this - SkynetClient
* @param directory - File objects to upload, indexed by their path strings.
* @param filename - The name of the directory.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param {string} [config.APIKey] - Authentication password to use.
* @param {string} [config.customUserAgent=""] - Custom user agent header to set.
* @param {string} [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @param {Function} [config.onUploadProgress] - Optional callback to track progress.
* @param {string} [customOptions.portalDirectoryfilefieldname="files[]"] - The fieldName for directory files on the portal.
* @returns skylink - The returned skylink.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @returns - The returned skylink.
*/
export declare function uploadDirectory(this: SkynetClient, directory: any, filename: string, customOptions?: CustomUploadOptions): Promise<string>;
export declare function uploadDirectoryRequest(this: SkynetClient, directory: any, filename: string, customOptions?: CustomUploadOptions): Promise<any>;
export {};
export declare function uploadDirectory(this: SkynetClient, directory: Record<string, File>, filename: string, customOptions?: CustomUploadOptions): Promise<UploadRequestResponse>;
/**
* Makes a request to upload a directory to Skynet.
*
* @param this - SkynetClient
* @param directory - File objects to upload, indexed by their path strings.
* @param filename - The name of the directory.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @returns - The upload response.
*/
export declare function uploadDirectoryRequest(this: SkynetClient, directory: Record<string, File>, filename: string, customOptions?: CustomUploadOptions): Promise<AxiosResponse>;
//# sourceMappingURL=upload.d.ts.map

@@ -53,5 +53,14 @@ "use strict";

var defaultUploadOptions = __assign(__assign({}, utils_1.defaultOptions("/skynet/skyfile")), { portalFileFieldname: "file", portalDirectoryFileFieldname: "files[]", customFilename: "" });
/**
* Uploads a file to Skynet.
*
* @param this - SkynetClient
* @param file - The file to upload.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @returns - The returned skylink.
*/
function uploadFile(file, customOptions) {
return __awaiter(this, void 0, void 0, function () {
var response;
var response, skylink, merkleroot, bitfield;
return __generator(this, function (_a) {

@@ -62,3 +71,11 @@ switch (_a.label) {

response = _a.sent();
return [2 /*return*/, "" + utils_1.uriSkynetPrefix + response.skylink];
if (typeof response.data.skylink !== "string" ||
typeof response.data.merkleroot !== "string" ||
typeof response.data.bitfield !== "number") {
throw new Error("Did not get a complete upload response despite a successful request. Please try again and report this issue to the devs if it persists.");
}
skylink = utils_1.formatSkylink(response.data.skylink);
merkleroot = response.data.merkleroot;
bitfield = response.data.bitfield;
return [2 /*return*/, { skylink: skylink, merkleroot: merkleroot, bitfield: bitfield }];
}

@@ -69,5 +86,14 @@ });

exports.uploadFile = uploadFile;
/**
* Makes a request to upload a file to Skynet.
*
* @param this - SkynetClient
* @param file - The file to upload.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @returns - The upload response.
*/
function uploadFileRequest(file, customOptions) {
return __awaiter(this, void 0, void 0, function () {
var opts, formData, data;
var opts, formData, response;
return __generator(this, function (_a) {

@@ -87,4 +113,4 @@ switch (_a.label) {

case 1:
data = (_a.sent()).data;
return [2 /*return*/, data];
response = _a.sent();
return [2 /*return*/, response];
}

@@ -96,16 +122,14 @@ });

/**
* Uploads a local directory to Skynet.
* Uploads a directory to Skynet.
*
* @param this - SkynetClient
* @param directory - File objects to upload, indexed by their path strings.
* @param filename - The name of the directory.
* @param [customOptions={}] - Additional settings that can optionally be set.
* @param {string} [config.APIKey] - Authentication password to use.
* @param {string} [config.customUserAgent=""] - Custom user agent header to set.
* @param {string} [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @param {Function} [config.onUploadProgress] - Optional callback to track progress.
* @param {string} [customOptions.portalDirectoryfilefieldname="files[]"] - The fieldName for directory files on the portal.
* @returns skylink - The returned skylink.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @returns - The returned skylink.
*/
function uploadDirectory(directory, filename, customOptions) {
return __awaiter(this, void 0, void 0, function () {
var response;
var response, skylink, merkleroot, bitfield;
return __generator(this, function (_a) {

@@ -116,3 +140,11 @@ switch (_a.label) {

response = _a.sent();
return [2 /*return*/, "" + utils_1.uriSkynetPrefix + response.skylink];
if (typeof response.data.skylink !== "string" ||
typeof response.data.merkleroot !== "string" ||
typeof response.data.bitfield !== "number") {
throw new Error("Did not get a complete upload response despite a successful request. Please try again and report this issue to the devs if it persists.");
}
skylink = utils_1.formatSkylink(response.data.skylink);
merkleroot = response.data.merkleroot;
bitfield = response.data.bitfield;
return [2 /*return*/, { skylink: skylink, merkleroot: merkleroot, bitfield: bitfield }];
}

@@ -123,8 +155,22 @@ });

exports.uploadDirectory = uploadDirectory;
/**
* Makes a request to upload a directory to Skynet.
*
* @param this - SkynetClient
* @param directory - File objects to upload, indexed by their path strings.
* @param filename - The name of the directory.
* @param [customOptions] - Additional settings that can optionally be set.
* @param [customOptions.endpointPath="/skynet/skyfile"] - The relative URL path of the portal endpoint to contact.
* @returns - The upload response.
*/
function uploadDirectoryRequest(directory, filename, customOptions) {
return __awaiter(this, void 0, void 0, function () {
var opts, formData, data;
var opts, formData, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
/* istanbul ignore next */
if (typeof filename !== "string") {
throw new Error("Expected parameter filename to be type string, was type " + typeof filename);
}
opts = __assign(__assign(__assign({}, defaultUploadOptions), this.customOptions), customOptions);

@@ -139,4 +185,4 @@ formData = new FormData();

case 1:
data = (_a.sent()).data;
return [2 /*return*/, data];
response = _a.sent();
return [2 /*return*/, response];
}

@@ -153,3 +199,6 @@ });

* as a constructor argument.
* Related issue: https://github.com/NebulousLabs/skynet-webportal/issues/290
*
* @param file - The input file.
* @returns - The processed file.
* @see {@link https://github.com/NebulousLabs/skynet-webportal/issues/290| Related Issue}
*/

@@ -156,0 +205,0 @@ function ensureFileObjectConsistency(file) {

@@ -0,1 +1,25 @@

import { CustomClientOptions } from "./client";
/**
* Base custom options for methods hitting the API.
*
* @property [endpointPath] - The relative URL path of the portal endpoint to contact.
*/
export declare type BaseCustomOptions = CustomClientOptions & {
endpointPath?: string;
};
/**
* Parse skylink options.
*
* @property [fromSubdomain] - Whether to parse the skylink as a base32 subdomain in a URL.
* @property [includePath] - Whether to include the path after the skylink, e.g. /<skylink>/foo/bar.
* @property [onlyPath] - Whether to parse out just the path, e.g. /foo/bar. Will still return null if the string does not contain a skylink.
*/
export declare type ParseSkylinkOptions = {
fromSubdomain?: boolean;
includePath?: boolean;
onlyPath?: boolean;
};
declare type ParseSkylinkBase32Options = {
onlyPath?: boolean;
};
export declare const defaultSkynetPortalUrl = "https://siasky.net";

@@ -5,12 +29,72 @@ export declare const uriHandshakePrefix = "hns:";

export declare const uriSkynetPrefix = "sia:";
/**
* The maximum allowed value for an entry revision. Setting an entry revision to this value prevents it from being updated further.
*/
export declare const MAX_REVISION: bigint;
/**
* Adds a subdomain to the given URL.
*
* @param url - The URL.
* @param subdomain - The subdomain to add.
* @returns - The final URL.
*/
export declare function addSubdomain(url: string, subdomain: string): string;
/**
* Adds a query to the given URL.
*
* @param url - The URL.
* @param query - The query parameters.
* @returns - The final URL.
*/
export declare function addUrlQuery(url: string, query: Record<string, unknown>): string;
export declare function convertSkylinkToBase32(input: string): string;
export declare function defaultOptions(endpointPath: string): {
/**
* Checks if the provided bigint can fit in a 64-bit unsigned integer.
*
* @param int - The provided integer.
* @throws - Will throw if the int does not fit in 64 bits.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/asUintN | MDN Demo}
*/
export declare function assertUint64(int: bigint): void;
/**
* Converts the given base64 skylink to base32.
*
* @param skylink - The base64 skylink.
* @returns - The converted base32 skylink.
*/
export declare function convertSkylinkToBase32(skylink: string): string;
/**
* Returns the default base custom options for the given endpoint path.
*
* @param endpointPath - The endpoint path.
* @returns - The base custom options.
*/
export declare function defaultOptions(endpointPath: string): CustomClientOptions & {
endpointPath: string;
APIKey: string;
customUserAgent: string;
};
/**
* Returns the default portal URL.
*
* @returns - The portal URL.
*/
export declare function defaultPortalUrl(): string;
/**
* Formats the skylink by adding the sia: prefix.
*
* @param skylink - The skylink.
* @returns - The formatted skylink.
*/
export declare function formatSkylink(skylink: string): string;
/**
* Gets the file path relative to the root directory of the path, e.g. `bar` in `/foo/bar`.
*
* @param file - The input file.
* @returns - The relative file path.
*/
export declare function getRelativeFilePath(file: File): string;
/**
* Gets the root directory of the file path, e.g. `foo` in `/foo/bar`.
*
* @param file - The input file.
* @returns - The root directory.
*/
export declare function getRootDirectory(file: File): string;

@@ -20,2 +104,5 @@ /**

* arguments.
*
* @param args - Array of URL parts to join.
* @returns - Final URL constructed from the input parts.
*/

@@ -25,25 +112,79 @@ export declare function makeUrl(...args: string[]): string;

* Parses the given string for a base64 skylink, or base32 if opts.fromSubdomain is given.
* @param skylinkStr - plain skylink, skylink with URI prefix, or URL with skylink as the first path element.
* @param [opts={}] - Additional settings that can optionally be set.
* @param [opts.onlyPath=false] - Whether to parse out just the path, e.g. /foo/bar. Will still return null if the string does not contain a skylink.
* @param [opts.includePath=false] - Whether to include the path after the skylink.
* @param [opts.fromSubdomain=false] - Whether to parse the skylink as a base32 subdomain in a URL.
*
* @param skylinkUrl - Plain skylink, skylink with URI prefix, or URL with skylink as the first path element.
* @param [opts] - Additional settings that can optionally be set.
* @returns - The base64 (or base32) skylink, optionally with the path included.
* @throws - Will throw on invalid combination of options.
*/
export declare function parseSkylink(skylinkStr: string, opts?: any): string;
export declare function parseSkylink(skylinkUrl: string, opts?: ParseSkylinkOptions): string | null;
/**
* Parses the given string for a base32 skylink.
*
* @param skylinkUrl - Base32 skylink.
* @param [opts] - Additional settings that can optionally be set.
* @returns - The base32 skylink.
*/
export declare function parseSkylinkBase32(skylinkUrl: string, opts?: ParseSkylinkBase32Options): string | null;
/**
* Removes a prefix from the beginning of the string.
*
* @param str - The string to process.
* @returns - The processed string.
*/
export declare function trimForwardSlash(str: string): string;
/**
* Removes a prefix from the beginning of the string.
*
* @param str - The string to process.
* @param prefix - The prefix to remove.
* @returns - The processed string.
*/
export declare function trimPrefix(str: string, prefix: string): string;
/**
* Removes a URI prefix from the beginning of the string.
*
* @param str - The string to process.
* @param prefix - The prefix to remove.
* @returns - The processed string.
*/
export declare function trimUriPrefix(str: string, prefix: string): string;
export declare function randomNumber(low: number, high: number): number;
/**
* Converts a string to a uint8 array.
*
* @param str - The string to convert.
* @returns - The uint8 array.
*/
export declare function stringToUint8Array(str: string): Uint8Array;
/**
* Converts a hex encoded string to a uint8 array
*
* @param str - The string to convert.
* @returns - The uint8 array.
* @throws - Will throw if the input is not a valid hex-encoded string.
*/
export declare function hexToUint8Array(str: string): Uint8Array;
/**
* Returns true if the input is a valid hex-encoded string.
*
* @param str - The input string.
* @returns - True if the input is hex-encoded.
*/
export declare function isHexString(str: string): boolean;
/**
* Convert a byte array to a hex string.
* From https://stackoverflow.com/a/44608819.
*
* @param byteArray - The byte array to convert.
* @returns - The hex string.
* @see {@link https://stackoverflow.com/a/44608819|Stack Overflow}
*/
export declare function toHexString(byteArray: Uint8Array): string;
export declare function readData(file: File): Promise<string | ArrayBuffer>;
/**
* Get the file mime type. In case the type is not provided, use mime-db and try
* to guess the file type based on the extension.
*
* @param file - The file.
* @returns - The mime type.
*/
export declare function getFileMimeType(file: File): string;
export {};
//# sourceMappingURL=utils.d.ts.map

@@ -24,3 +24,3 @@ "use strict";

exports.__esModule = true;
exports.getFileMimeType = exports.readData = exports.toHexString = exports.hexToUint8Array = exports.stringToUint8Array = exports.randomNumber = exports.trimUriPrefix = exports.trimForwardSlash = exports.parseSkylink = exports.makeUrl = exports.getRootDirectory = exports.getRelativeFilePath = exports.defaultPortalUrl = exports.defaultOptions = exports.convertSkylinkToBase32 = exports.addUrlQuery = exports.addSubdomain = exports.uriSkynetPrefix = exports.uriHandshakeResolverPrefix = exports.uriHandshakePrefix = exports.defaultSkynetPortalUrl = void 0;
exports.getFileMimeType = exports.toHexString = exports.isHexString = exports.hexToUint8Array = exports.stringToUint8Array = exports.trimUriPrefix = exports.trimPrefix = exports.trimForwardSlash = exports.parseSkylinkBase32 = exports.parseSkylink = exports.makeUrl = exports.getRootDirectory = exports.getRelativeFilePath = exports.formatSkylink = exports.defaultPortalUrl = exports.defaultOptions = exports.convertSkylinkToBase32 = exports.assertUint64 = exports.addUrlQuery = exports.addSubdomain = exports.MAX_REVISION = exports.uriSkynetPrefix = exports.uriHandshakeResolverPrefix = exports.uriHandshakePrefix = exports.defaultSkynetPortalUrl = void 0;
var base64_js_1 = __importDefault(require("base64-js"));

@@ -37,3 +37,13 @@ var base32_encode_1 = __importDefault(require("base32-encode"));

exports.uriSkynetPrefix = "sia:";
// TODO: Use a third-party library to make this more robust.
/**
* The maximum allowed value for an entry revision. Setting an entry revision to this value prevents it from being updated further.
*/
exports.MAX_REVISION = BigInt("18446744073709551615"); // max uint64
/**
* Adds a subdomain to the given URL.
*
* @param url - The URL.
* @param subdomain - The subdomain to add.
* @returns - The final URL.
*/
function addSubdomain(url, subdomain) {

@@ -43,14 +53,16 @@ var urlObj = new URL(url);

var str = urlObj.toString();
if (str.endsWith("/")) {
return str.substring(0, str.length - 1);
}
return str;
return trimSuffix(str, "/");
}
exports.addSubdomain = addSubdomain;
/**
* Adds a query to the given URL.
*
* @param url - The URL.
* @param query - The query parameters.
* @returns - The final URL.
*/
function addUrlQuery(url, query) {
var parsed = url_parse_1["default"](url, true);
if (parsed.query) {
// Combine the desired query params with the already existing ones.
query = __assign(__assign({}, parsed.query), query);
}
// Combine the desired query params with the already existing ones.
query = __assign(__assign({}, parsed.query), query);
parsed.set("query", query);

@@ -60,7 +72,39 @@ return parsed.toString();

exports.addUrlQuery = addUrlQuery;
function convertSkylinkToBase32(input) {
var decoded = base64_js_1["default"].toByteArray(input.padEnd(input.length + 4 - (input.length % 4), "="));
/**
* Checks if the provided bigint can fit in a 64-bit unsigned integer.
*
* @param int - The provided integer.
* @throws - Will throw if the int does not fit in 64 bits.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/asUintN | MDN Demo}
*/
function assertUint64(int) {
/* istanbul ignore next */
if (typeof int !== "bigint") {
throw new Error("Expected parameter int to be type bigint, was type " + typeof int);
}
if (int < BigInt(0)) {
throw new Error("Argument " + int + " must be an unsigned 64-bit integer; was negative");
}
if (int > exports.MAX_REVISION) {
throw new Error("Argument " + int + " does not fit in a 64-bit unsigned integer; exceeds 2^64-1");
}
}
exports.assertUint64 = assertUint64;
/**
* Converts the given base64 skylink to base32.
*
* @param skylink - The base64 skylink.
* @returns - The converted base32 skylink.
*/
function convertSkylinkToBase32(skylink) {
var decoded = base64_js_1["default"].toByteArray(skylink.padEnd(skylink.length + 4 - (skylink.length % 4), "="));
return base32_encode_1["default"](decoded, "RFC4648-HEX", { padding: false }).toLowerCase();
}
exports.convertSkylinkToBase32 = convertSkylinkToBase32;
/**
* Returns the default base custom options for the given endpoint path.
*
* @param endpointPath - The endpoint path.
* @returns - The base custom options.
*/
function defaultOptions(endpointPath) {

@@ -76,3 +120,9 @@ return {

// https://github.com/NebulousLabs/skynet-docs/issues/21.
/**
* Returns the default portal URL.
*
* @returns - The portal URL.
*/
function defaultPortalUrl() {
/* istanbul ignore next */
if (typeof window === "undefined")

@@ -83,5 +133,34 @@ return "/"; // default to path root on ssr

exports.defaultPortalUrl = defaultPortalUrl;
/**
* Formats the skylink by adding the sia: prefix.
*
* @param skylink - The skylink.
* @returns - The formatted skylink.
*/
function formatSkylink(skylink) {
if (skylink == "") {
return skylink;
}
if (!skylink.startsWith(exports.uriSkynetPrefix)) {
skylink = "" + exports.uriSkynetPrefix + skylink;
}
return skylink;
}
exports.formatSkylink = formatSkylink;
/**
* Gets the path for the file.
*
* @param file - The file.
* @returns - The path.
*/
function getFilePath(file) {
/* istanbul ignore next */
return file.webkitRelativePath || file.path || file.name;
}
/**
* Gets the file path relative to the root directory of the path, e.g. `bar` in `/foo/bar`.
*
* @param file - The input file.
* @returns - The relative file path.
*/
function getRelativeFilePath(file) {

@@ -94,2 +173,8 @@ var filePath = getFilePath(file);

exports.getRelativeFilePath = getRelativeFilePath;
/**
* Gets the root directory of the file path, e.g. `foo` in `/foo/bar`.
*
* @param file - The input file.
* @returns - The root directory.
*/
function getRootDirectory(file) {

@@ -104,2 +189,5 @@ var filePath = getFilePath(file);

* arguments.
*
* @param args - Array of URL parts to join.
* @returns - Final URL constructed from the input parts.
*/

@@ -123,18 +211,20 @@ function makeUrl() {

* Parses the given string for a base64 skylink, or base32 if opts.fromSubdomain is given.
* @param skylinkStr - plain skylink, skylink with URI prefix, or URL with skylink as the first path element.
* @param [opts={}] - Additional settings that can optionally be set.
* @param [opts.onlyPath=false] - Whether to parse out just the path, e.g. /foo/bar. Will still return null if the string does not contain a skylink.
* @param [opts.includePath=false] - Whether to include the path after the skylink.
* @param [opts.fromSubdomain=false] - Whether to parse the skylink as a base32 subdomain in a URL.
*
* @param skylinkUrl - Plain skylink, skylink with URI prefix, or URL with skylink as the first path element.
* @param [opts] - Additional settings that can optionally be set.
* @returns - The base64 (or base32) skylink, optionally with the path included.
* @throws - Will throw on invalid combination of options.
*/
function parseSkylink(skylinkStr, opts) {
function parseSkylink(skylinkUrl, opts) {
if (opts === void 0) { opts = {}; }
if (typeof skylinkStr !== "string")
throw new Error("Skylink has to be a string, " + typeof skylinkStr + " provided");
if (opts.includePath && opts.onlyPath)
if (typeof skylinkUrl !== "string")
throw new Error("Skylink has to be a string, " + typeof skylinkUrl + " provided");
if (opts.includePath && opts.onlyPath) {
throw new Error("The includePath and onlyPath options cannot both be set");
if (opts.includePath && opts.fromSubdomain)
}
if (opts.includePath && opts.fromSubdomain) {
throw new Error("The includePath and fromSubdomain options cannot both be set");
}
if (opts.fromSubdomain) {
return parseSkylinkBase32(skylinkStr, opts);
return parseSkylinkBase32(skylinkUrl, opts);
}

@@ -144,5 +234,5 @@ // Check for skylink prefixed with sia: or sia:// and extract it.

// Example: sia://XABvi7JtJbQSMAcDwnUnmp2FKDPjg8_tTTFP4BwMSxVdEg
skylinkStr = trimUriPrefix(skylinkStr, exports.uriSkynetPrefix);
skylinkUrl = trimUriPrefix(skylinkUrl, exports.uriSkynetPrefix);
// Check for direct base64 skylink match.
var matchDirect = skylinkStr.match(SKYLINK_DIRECT_REGEX);
var matchDirect = skylinkUrl.match(SKYLINK_DIRECT_REGEX);
if (matchDirect) {

@@ -159,3 +249,3 @@ if (opts.onlyPath) {

// when parsing in browser.
var parsed = url_parse_1["default"](skylinkStr, {});
var parsed = url_parse_1["default"](skylinkUrl, {});
var skylinkAndPath = trimSuffix(parsed.pathname, "/");

@@ -166,4 +256,2 @@ var matchPathname = skylinkAndPath.match(SKYLINK_PATHNAME_REGEX);

var path = matchPathname[SKYLINK_PATH_MATCH_POSITION];
if (path == "/")
path = "";
if (opts.includePath)

@@ -177,7 +265,14 @@ return trimForwardSlash(skylinkAndPath);

exports.parseSkylink = parseSkylink;
function parseSkylinkBase32(skylinkStr, opts) {
/**
* Parses the given string for a base32 skylink.
*
* @param skylinkUrl - Base32 skylink.
* @param [opts] - Additional settings that can optionally be set.
* @returns - The base32 skylink.
*/
function parseSkylinkBase32(skylinkUrl, opts) {
if (opts === void 0) { opts = {}; }
// Pass empty object as second param to disable using location as base url
// when parsing in browser.
var parsed = url_parse_1["default"](skylinkStr, {});
var parsed = url_parse_1["default"](skylinkUrl, {});
// Check if the hostname contains a skylink subdomain.

@@ -187,3 +282,3 @@ var matchHostname = parsed.hostname.match(SKYLINK_SUBDOMAIN_REGEX);

if (opts.onlyPath) {
return parsed.pathname;
return trimSuffix(parsed.pathname, "/");
}

@@ -194,2 +289,9 @@ return matchHostname[SKYLINK_DIRECT_MATCH_POSITION];

}
exports.parseSkylinkBase32 = parseSkylinkBase32;
/**
* Removes a prefix from the beginning of the string.
*
* @param str - The string to process.
* @returns - The processed string.
*/
function trimForwardSlash(str) {

@@ -199,2 +301,9 @@ return trimPrefix(trimSuffix(str, "/"), "/");

exports.trimForwardSlash = trimForwardSlash;
/**
* Removes a prefix from the beginning of the string.
*
* @param str - The string to process.
* @param prefix - The prefix to remove.
* @returns - The processed string.
*/
function trimPrefix(str, prefix) {

@@ -206,2 +315,10 @@ while (str.startsWith(prefix)) {

}
exports.trimPrefix = trimPrefix;
/**
* Removes a suffix from the end of the string.
*
* @param str - The string to process.
* @param suffix - The suffix to remove.
* @returns - The processed string.
*/
function trimSuffix(str, suffix) {

@@ -213,2 +330,9 @@ while (str.endsWith(suffix)) {

}
/**
* Removes a URI prefix from the beginning of the string.
*
* @param str - The string to process.
* @param prefix - The prefix to remove.
* @returns - The processed string.
*/
function trimUriPrefix(str, prefix) {

@@ -227,19 +351,54 @@ var longPrefix = prefix + "//";

exports.trimUriPrefix = trimUriPrefix;
function randomNumber(low, high) {
return Math.random() * (high - low) + low;
}
exports.randomNumber = randomNumber;
// Converts a string to a uint8 array
/**
* Converts a string to a uint8 array.
*
* @param str - The string to convert.
* @returns - The uint8 array.
*/
function stringToUint8Array(str) {
/* istanbul ignore next */
if (typeof str !== "string") {
throw new Error("Expected parameter str to be type string, was type " + typeof str);
}
return Uint8Array.from(buffer_1.Buffer.from(str));
}
exports.stringToUint8Array = stringToUint8Array;
// Converts a hex encoded string to a uint8 array
/**
* Converts a hex encoded string to a uint8 array
*
* @param str - The string to convert.
* @returns - The uint8 array.
* @throws - Will throw if the input is not a valid hex-encoded string.
*/
function hexToUint8Array(str) {
return new Uint8Array(str.match(/.{1,2}/g).map(function (byte) { return parseInt(byte, 16); }));
if (!isHexString(str)) {
throw new Error("Input string '" + str + "' is not a valid hex-encoded string");
}
var matches = str.match(/.{1,2}/g);
if (matches === null) {
throw new Error("Input string '" + str + "' is not a valid hex-encoded string");
}
return new Uint8Array(matches.map(function (byte) { return parseInt(byte, 16); }));
}
exports.hexToUint8Array = hexToUint8Array;
/**
* Returns true if the input is a valid hex-encoded string.
*
* @param str - The input string.
* @returns - True if the input is hex-encoded.
*/
function isHexString(str) {
/* istanbul ignore next */
if (typeof str !== "string") {
throw new Error("Expected parameter str to be type string, was type " + typeof str);
}
return /^[0-9A-Fa-f]*$/g.test(str);
}
exports.isHexString = isHexString;
/**
* Convert a byte array to a hex string.
* From https://stackoverflow.com/a/44608819.
*
* @param byteArray - The byte array to convert.
* @returns - The hex string.
* @see {@link https://stackoverflow.com/a/44608819|Stack Overflow}
*/

@@ -254,16 +413,8 @@ function toHexString(byteArray) {

exports.toHexString = toHexString;
// A helper function that uses a FileReader to read the contents of the given
// file
function readData(file) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () { return resolve(reader.result); };
reader.onerror = function (error) { return reject(error); };
});
}
exports.readData = readData;
/**
* Get the file mime type. In case the type is not provided, use mime-db and try
* to guess the file type based on the extension.
*
* @param file - The file.
* @returns - The mime type.
*/

@@ -274,6 +425,7 @@ function getFileMimeType(file) {

return file.type;
var extension = file.name.slice(file.name.lastIndexOf(".") + 1);
if (extension) {
var ext = path_browserify_1["default"].parse(file.name).ext;
ext = trimPrefix(ext, ".");
if (ext !== "") {
for (var type in mime_db_1["default"]) {
if ((_b = (_a = mime_db_1["default"][type]) === null || _a === void 0 ? void 0 : _a.extensions) === null || _b === void 0 ? void 0 : _b.includes(extension)) {
if ((_b = (_a = mime_db_1["default"][type]) === null || _a === void 0 ? void 0 : _a.extensions) === null || _b === void 0 ? void 0 : _b.includes(ext)) {
return type;

@@ -280,0 +432,0 @@ }

{
"name": "skynet-js",
"version": "2.9.0",
"version": "3.0.0-beta",
"description": "Sia Skynet Javascript Client",

@@ -15,3 +15,3 @@ "main": "dist/index.js",

"scripts": {
"test": "jest",
"test": "jest --coverage --coverageDirectory ../coverage",
"build": "rimraf dist && babel src --out-dir dist --extensions .ts --ignore src/**/*.test.ts && tsc --project tsconfig.build.json",

@@ -25,2 +25,13 @@ "lint:eslint": "eslint --ext .ts utils src",

"clearMocks": true,
"collectCoverageFrom": [
"**/*.ts"
],
"coverageThreshold": {
"global": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 100
}
},
"rootDir": "src"

@@ -92,2 +103,3 @@ },

"eslint-plugin-compat": "^3.8.0",
"eslint-plugin-jsdoc": "^30.7.8",
"husky": "^4.3.0",

@@ -94,0 +106,0 @@ "jest": "^26.4.2",

@@ -47,4 +47,14 @@ # skynet-js - Javascript Sia Skynet Client

- Clone the repository
- Run `yarn`
- Run `yarn test` to run the tests
1. Clone the repository
1. Run `yarn`
1. Run `yarn test` to run the tests
### Requirements
We have some automated checks that must pass in order for code to be accepted. These include:
- Type-checking and other code lints must pass.
- Every function must have a complete JSDoc-style docstring.
- 100% code coverage is enforced. Every statement and conditional branch must be tested.
Note that the 100% coverage requirement is a _minimum_. Just because a line of code is tested does not mean it is tested _well_, that is, with different values and combinations of values. Tests should be as thorough as possible, within reason.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc