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

masto

Package Overview
Dependencies
Maintainers
1
Versions
242
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

masto - npm Package Compare versions

Comparing version 6.0.0-alpha.3 to 6.0.0-alpha.4

1501

dist/index.js

@@ -0,11 +1,702 @@

import { snakeCase, camelCase } from 'change-case';
import { CustomError } from 'ts-custom-error';
import { snakeCase, camelCase } from 'change-case';
import parseLinkHeader from 'parse-link-header';
import WebSocket from 'ws';
import { on } from 'events-to-async';
import WebSocket from 'ws';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
const sleep = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
function noop() {
//
}
class ExponentialBackoffError extends CustomError {
constructor(attempts, options) {
super(`Maximum number of attempts reached: ${attempts}`, options);
}
}
// https://en.wikipedia.org/wiki/Exponential_backoff
class ExponentialBackoff {
constructor(props = {}) {
this.props = props;
this.attempts = 0;
}
sleep() {
return __awaiter(this, void 0, void 0, function* () {
if (this.attempts >= this.maxAttempts) {
throw new ExponentialBackoffError(this.attempts);
}
yield sleep(this.getTimeout());
this.attempts++;
});
}
clear() {
this.attempts = 0;
}
get factor() {
var _a;
return (_a = this.props.factor) !== null && _a !== void 0 ? _a : 1000;
}
get base() {
var _a;
return (_a = this.props.base) !== null && _a !== void 0 ? _a : 2;
}
get maxAttempts() {
var _a;
return (_a = this.props.maxAttempts) !== null && _a !== void 0 ? _a : Number.POSITIVE_INFINITY;
}
getTimeout() {
return this.factor * Math.pow(this.base, this.attempts);
}
values() {
return __asyncGenerator(this, arguments, function* values_1() {
while (this.attempts < this.maxAttempts) {
yield yield __await(this.sleep());
}
});
}
[Symbol.asyncIterator]() {
return this.values();
}
}
// https://github.com/tc39/proposal-promise-with-resolvers
const createPromiseWithResolvers = () => {
let resolve;
let reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
class MastoUnexpectedError extends CustomError {
}
class MastoDeserializeError extends CustomError {
constructor(message, contentType, data, options) {
super(message, options);
this.contentType = contentType;
this.data = data;
}
}
class MastoHttpError extends CustomError {
constructor(statusCode, message, description, details, options) {
super(message, options);
this.statusCode = statusCode;
this.message = message;
this.description = description;
this.details = details;
}
}
class MastoTimeoutError extends CustomError {
}
class MastoWebSocketError extends CustomError {
constructor(message, options) {
super(message, options);
this.message = message;
}
}
class PaginatorHttp {
constructor(http, nextPath, nextParams, meta) {
this.http = http;
this.nextPath = nextPath;
this.nextParams = nextParams;
this.meta = meta;
const hasMinId = nextParams && typeof nextParams === "object" && "minId" in nextParams;
this.rel = hasMinId ? "prev" : "next";
}
next() {
return __awaiter(this, void 0, void 0, function* () {
if (this.nextPath == undefined) {
return { done: true, value: undefined };
}
const response = yield this.http.request(Object.assign({ method: "GET", path: this.nextPath, search: this.nextParams }, this.meta));
const nextUrl = this.getLink(response.headers.get("link"));
this.nextPath = nextUrl === null || nextUrl === void 0 ? void 0 : nextUrl.pathname;
this.nextParams = nextUrl === null || nextUrl === void 0 ? void 0 : nextUrl.search.replace(/^\?/, "");
const data = response.data;
const value = this.rel === "prev" && Array.isArray(data)
? data.reverse()
: response.data;
return {
done: false,
value: value,
};
});
}
return(value) {
return __awaiter(this, void 0, void 0, function* () {
this.clear();
return {
done: true,
value: yield value,
};
});
}
throw(e) {
return __awaiter(this, void 0, void 0, function* () {
this.clear();
throw e;
});
}
then(onfulfilled = Promise.resolve.bind(Promise), onrejected = Promise.reject.bind(Promise)) {
// we assume the first item won't be undefined
return this.next().then((value) => onfulfilled(value.value), onrejected);
}
values() {
return this[Symbol.asyncIterator]();
}
[Symbol.asyncIterator]() {
return this;
}
getLink(value) {
var _a, _b;
if (value == undefined) {
return;
}
const parsed = (_b = (_a = parseLinkHeader(value)) === null || _a === void 0 ? void 0 : _a[this.rel]) === null || _b === void 0 ? void 0 : _b.url;
if (parsed == undefined) {
return;
}
return new URL(parsed);
}
clear() {
this.nextPath = undefined;
this.nextParams = undefined;
}
clone() {
return new PaginatorHttp(this.http, this.nextPath, this.nextParams, this.meta);
}
}
class HttpActionDispatcher {
constructor(http, params = {}) {
this.http = http;
this.params = params;
this.waitForMediaAttachment = (id) => __awaiter(this, void 0, void 0, function* () {
let media;
const signal = AbortSignal.timeout(this.mediaTimeout);
while (media == undefined) {
if (signal.aborted) {
throw new MastoTimeoutError(`Media processing timed out of ${this.mediaTimeout}ms`);
}
try {
yield sleep(1000);
const processing = yield this.http.get(`/api/v1/media/${id}`);
if (processing.url != undefined) {
media = processing;
}
}
catch (error) {
if (error instanceof MastoHttpError && error.statusCode === 404) {
continue;
}
throw error;
}
}
return media;
});
}
dispatch(action) {
return __awaiter(this, void 0, void 0, function* () {
const actionType = this.toPrimitiveAction(action.type);
const path = this.isPrimitiveAction(action.type)
? action.path
: action.path + "/" + snakeCase(action.type);
const encoding = this.inferEncoding(actionType, path);
const meta = Object.assign(Object.assign({}, action.meta), { encoding });
switch (actionType) {
case "fetch": {
return this.http.get(path, action.data, meta);
}
case "create": {
if (path === "/api/v2/media") {
const media = yield this.http.post(path, action.data, meta);
return this.waitForMediaAttachment(media.id);
}
return this.http.post(path, action.data, meta);
}
case "update": {
return this.http.patch(path, action.data, meta);
}
case "remove": {
return this.http.delete(path, action.data, meta);
}
case "list": {
return new PaginatorHttp(this.http, path, action.data);
}
}
});
}
isPrimitiveAction(action) {
switch (action) {
case "fetch":
case "create":
case "update":
case "remove":
case "list": {
return true;
}
default: {
return false;
}
}
}
toPrimitiveAction(action) {
if (this.isPrimitiveAction(action)) {
return action;
}
switch (action) {
case "lookup":
case "verifyCredentials": {
return "fetch";
}
case "updateCredentials": {
return "update";
}
default: {
return "create";
}
}
}
inferEncoding(action, path) {
if ((action === "create" && path === "/api/v1/accounts") ||
(action === "update" && path === "/api/v1/update_credentials") ||
(action === "create" && path === "/api/v1/email") ||
(action === "create" && path === "/api/v1/featured_tag") ||
(action === "create" && path === "/api/v1/media") ||
(action === "create" && path === "/api/v2/media")) {
return "multipart-form";
}
return "json";
}
get mediaTimeout() {
var _a;
return (_a = this.params.mediaTimeout) !== null && _a !== void 0 ? _a : 60 * 1000;
}
}
function waitForOpen(ws) {
if (ws.readyState === WebSocket.OPEN) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
const handleError = (error) => {
reject(error);
};
const handleClose = () => {
reject(new Error("WebSocket closed"));
};
const handleOpen = () => {
resolve();
};
ws.addEventListener("error", handleError, { once: true });
ws.addEventListener("close", handleClose, { once: true });
ws.addEventListener("open", handleOpen, { once: true });
});
}
function waitForClose(ws) {
if (ws.readyState === WebSocket.CLOSED) {
return Promise.resolve();
}
return new Promise((resolve) => {
const handleClose = () => {
resolve();
};
ws.addEventListener("error", handleClose, { once: true });
ws.addEventListener("close", handleClose, { once: true });
});
}
class WebSocketConnectorImpl {
constructor(params, logger, maxAttempts) {
this.params = params;
this.logger = logger;
this.maxAttempts = maxAttempts;
this.queue = [];
this.disableRetry = false;
this.initialized = false;
this.init = () => __awaiter(this, void 0, void 0, function* () {
var _a, e_1, _b, _c;
var _d, _e, _f, _g, _h;
if (this.initialized) {
return;
}
this.initialized = true;
try {
for (var _j = true, _k = __asyncValues(this.backoff), _l; _l = yield _k.next(), _a = _l.done, !_a; _j = true) {
_c = _l.value;
_j = false;
const _ = _c;
(_d = this.ws) === null || _d === void 0 ? void 0 : _d.close();
try {
(_e = this.logger) === null || _e === void 0 ? void 0 : _e.info("Connecting to WebSocket...");
{
const ws = new WebSocket(...this.params);
yield waitForOpen(ws);
this.ws = ws;
}
(_f = this.logger) === null || _f === void 0 ? void 0 : _f.info("Connected to WebSocket");
for (const { resolve } of this.queue) {
resolve(this.ws);
}
this.queue = [];
yield waitForClose(this.ws);
(_g = this.logger) === null || _g === void 0 ? void 0 : _g.info("WebSocket closed");
this.backoff.clear();
}
catch (error) {
(_h = this.logger) === null || _h === void 0 ? void 0 : _h.error("WebSocket error:", error);
}
if (this.disableRetry) {
break;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_j && !_a && (_b = _k.return)) yield _b.call(_k);
}
finally { if (e_1) throw e_1.error; }
}
for (const { reject } of this.queue) {
reject(new MastoWebSocketError(`Failed to connect to WebSocket after ${this.maxAttempts} attempts`));
}
this.queue = [];
});
this.backoff = new ExponentialBackoff({
maxAttempts: this.maxAttempts,
});
}
canAcquire() {
return !this.disableRetry;
}
acquire() {
return __awaiter(this, void 0, void 0, function* () {
this.init();
if (this.ws != undefined) {
return this.ws;
}
const promiseWithResolvers = createPromiseWithResolvers();
this.queue.push(promiseWithResolvers);
return yield promiseWithResolvers.promise;
});
}
close() {
var _a;
this.disableRetry = true;
(_a = this.ws) === null || _a === void 0 ? void 0 : _a.close();
this.backoff.clear();
for (const { reject } of this.queue) {
reject(new MastoWebSocketError("WebSocket closed"));
}
this.queue = [];
}
}
function toAsyncIterable(ws) {
return __asyncGenerator(this, arguments, function* toAsyncIterable_1() {
var _a, e_1, _b, _c;
const handleClose = (e) => __awaiter(this, void 0, void 0, function* () {
/* istanbul ignore next */
if (events.return == undefined) {
throw new MastoUnexpectedError("events.return is undefined");
}
yield events.return(e);
});
const handleError = (e) => __awaiter(this, void 0, void 0, function* () {
/* istanbul ignore next */
if (events.return == undefined) {
throw new MastoUnexpectedError("events.return is undefined");
}
yield events.return(e);
});
const events = on((handler) => {
ws.addEventListener("message", handler);
ws.addEventListener("error", handleError);
ws.addEventListener("close", handleClose);
return () => {
ws.removeEventListener("message", handler);
ws.removeEventListener("error", handleError);
ws.removeEventListener("close", handleClose);
};
});
try {
for (var _d = true, events_1 = __asyncValues(events), events_1_1; events_1_1 = yield __await(events_1.next()), _a = events_1_1.done, !_a; _d = true) {
_c = events_1_1.value;
_d = false;
const [event] = _c;
yield yield __await(event);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = events_1.return)) yield __await(_b.call(events_1));
}
finally { if (e_1) throw e_1.error; }
}
});
}
class WebSocketSubscription {
constructor(connector, serializer, stream, logger, params) {
this.connector = connector;
this.serializer = serializer;
this.stream = stream;
this.logger = logger;
this.params = params;
}
values() {
var _a, _b, _c;
return __asyncGenerator(this, arguments, function* values_1() {
var _d, e_1, _e, _f;
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.info("Subscribing to stream", this.stream);
while (this.connector.canAcquire()) {
this.connection = yield __await(this.connector.acquire());
const messages = toAsyncIterable(this.connection);
const data = this.serializer.serialize("json", Object.assign({ type: "subscribe", stream: this.stream }, this.params));
(_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug("↑ WEBSOCKET", data);
this.connection.send(data);
try {
for (var _g = true, _h = (e_1 = void 0, __asyncValues(this.mapEvents(messages))), _j; _j = yield __await(_h.next()), _d = _j.done, !_d; _g = true) {
_f = _j.value;
_g = false;
const event = _f;
if (!this.matches(event))
continue;
(_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug("↓ WEBSOCKET", event);
yield yield __await(event);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_g && !_d && (_e = _h.return)) yield __await(_e.call(_h));
}
finally { if (e_1) throw e_1.error; }
}
}
});
}
unsubscribe() {
if (this.connection == undefined) {
return;
}
const data = this.serializer.serialize("json", Object.assign({ type: "unsubscribe", stream: this.stream }, this.params));
this.connection.send(data);
}
matches(event) {
var _a;
// subscribe("hashtag", { tag: "foo" }) -> ["hashtag", "foo"]
// subscribe("list", { list: "foo" }) -> ["list", "foo"]
const params = (_a = this.params) !== null && _a !== void 0 ? _a : {};
const extra = Object.values(params);
const stream = [this.stream, ...extra];
return stream.every((s) => event.stream.includes(s));
}
[Symbol.asyncIterator]() {
return this.values();
}
mapEvents(messages) {
return __asyncGenerator(this, arguments, function* mapEvents_1() {
var _a, e_2, _b, _c;
try {
for (var _d = true, messages_1 = __asyncValues(messages), messages_1_1; messages_1_1 = yield __await(messages_1.next()), _a = messages_1_1.done, !_a; _d = true) {
_c = messages_1_1.value;
_d = false;
const message = _c;
const event = yield __await(this.parseMessage(message.data));
yield yield __await(event);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (!_d && !_a && (_b = messages_1.return)) yield __await(_b.call(messages_1));
}
finally { if (e_2) throw e_2.error; }
}
});
}
parseMessage(rawEvent) {
return __awaiter(this, void 0, void 0, function* () {
const data = this.serializer.deserialize("json", rawEvent);
if ("error" in data) {
throw new MastoUnexpectedError(data.error);
}
const payload = data.event === "delete" || data.payload == undefined
? data.payload
: this.serializer.deserialize("json", data.payload);
return {
stream: data.stream,
event: data.event,
payload: payload,
};
});
}
}
class WebSocketActionDispatcher {
constructor(connector, serializer, logger) {
this.connector = connector;
this.serializer = serializer;
this.logger = logger;
}
dispatch(action) {
var _a;
if (action.type === "close") {
this.connector.close();
return {};
}
if (action.type !== "subscribe") {
throw new MastoUnexpectedError("Unknown action type");
}
const data = (_a = action.data) !== null && _a !== void 0 ? _a : {};
const stream = action.path.replace(/^\//, "").replaceAll("/", ":");
return new WebSocketSubscription(this.connector, this.serializer, stream, this.logger, Object.assign({}, data));
}
}
const createActionProxy = (actionDispatcher, context = []) => {
return new Proxy(noop, {
get: get(actionDispatcher, context),
apply: apply(actionDispatcher, context),
});
};
const SPECIAL_PROPERTIES = new Set([
"then",
"catch",
"finally",
"inspect",
"toString",
"valueOf",
"toJSON",
"constructor",
"prototype",
"length",
"name",
"caller",
"callee",
"arguments",
"bind",
"apply",
"call",
]);
const get = (actionDispatcher, context) => (_, property) => {
if (typeof property === "string" && SPECIAL_PROPERTIES.has(property)) {
return;
}
if (typeof property === "symbol") {
return;
}
return createActionProxy(actionDispatcher, [...context, property]);
};
const apply = (actionDispatcher, context) => (_1, _2, args) => {
const action = context.pop();
if (action == undefined) {
throw new Error("No action specified");
}
if (action === "$select") {
return createActionProxy(actionDispatcher, [
...context,
...args,
]);
}
const path = "/" + context.map((name) => snakeCase(name)).join("/");
const [data, meta] = args;
return actionDispatcher.dispatch({
type: action,
path,
data,
meta: meta,
});
};
const mergeAbortSignals = (signals) => {
const abortController = new AbortController();
for (const signal of signals) {
signal.addEventListener('abort', () => abortController.abort(), {
signal.addEventListener("abort", () => abortController.abort(), {
once: true,

@@ -33,22 +724,21 @@ });

}
mergeHeadersWithDefaults(override = {}) {
var _a, _b;
const headersInit = mergeHeadersInit([
(_b = (_a = this.props.defaultRequestInit) === null || _a === void 0 ? void 0 : _a.headers) !== null && _b !== void 0 ? _b : {},
override,
]);
const headers = new Headers(headersInit);
if (this.props.accessToken) {
headers.set('Authorization', `Bearer ${this.props.accessToken}`);
mergeRequestInitWithDefaults(override = {}) {
const requestInit = Object.assign({}, this.props.requestInit);
// Merge
{
const { headers, signal } = override, rest = __rest(override, ["headers", "signal"]);
Object.assign(requestInit, rest);
requestInit.headers = this.mergeHeadersWithDefaults(headers);
requestInit.signal = this.mergeAbortSignalWithDefaults(signal);
}
return new Headers(headers);
return requestInit;
}
resolvePath(path, params) {
const url = new URL(path, this.props.url);
if (params != undefined) {
url.search =
typeof params === 'string'
? params
: this.serializer.serialize('querystring', params);
if (typeof params === "string") {
url.search = params;
}
else if (params != undefined) {
url.search = this.serializer.serialize("querystring", params);
}
return url;

@@ -60,2 +750,14 @@ }

}
mergeHeadersWithDefaults(override = {}) {
var _a, _b;
const headersInit = mergeHeadersInit([
(_b = (_a = this.props.requestInit) === null || _a === void 0 ? void 0 : _a.headers) !== null && _b !== void 0 ? _b : {},
override,
]);
const headers = new Headers(headersInit);
if (this.props.accessToken) {
headers.set("Authorization", `Bearer ${this.props.accessToken}`);
}
return new Headers(headers);
}
mergeAbortSignalWithDefaults(signal) {

@@ -65,4 +767,4 @@ var _a;

const signals = [timeout];
if ((_a = this.props.defaultRequestInit) === null || _a === void 0 ? void 0 : _a.signal) {
signals.push(this.props.defaultRequestInit.signal);
if ((_a = this.props.requestInit) === null || _a === void 0 ? void 0 : _a.signal) {
signals.push(this.props.requestInit.signal);
}

@@ -93,3 +795,3 @@ if (signal != undefined) {

}
url.search = this.serializer.serialize('querystring', params);
url.search = this.serializer.serialize("querystring", params);
return url;

@@ -110,127 +812,32 @@ }

get(path, data, meta = {}) {
return this.request(Object.assign({ method: 'GET', path, search: data }, meta)).then((response) => response.data);
return this.request(Object.assign({ method: "GET", path, search: data }, meta)).then((response) => response.data);
}
post(path, data, meta = {}) {
return this.request(Object.assign({ method: 'POST', path, body: data }, meta)).then((response) => response.data);
return this.request(Object.assign({ method: "POST", path, body: data }, meta)).then((response) => response.data);
}
delete(path, data, meta = {}) {
return this.request(Object.assign({ method: 'DELETE', path, body: data }, meta)).then((response) => response.data);
return this.request(Object.assign({ method: "DELETE", path, body: data }, meta)).then((response) => response.data);
}
/* istanbul ignore next */
put(path, data, meta = {}) {
return this.request(Object.assign({ method: 'PUT', path, body: data }, meta)).then((response) => response.data);
return this.request(Object.assign({ method: "PUT", path, body: data }, meta)).then((response) => response.data);
}
patch(path, data, meta = {}) {
return this.request(Object.assign({ method: 'PATCH', path, body: data }, meta)).then((response) => response.data);
return this.request(Object.assign({ method: "PATCH", path, body: data }, meta)).then((response) => response.data);
}
}
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
class MastoUnexpectedError extends CustomError {
constructor(message, options) {
super(message, options);
}
}
class MastoDeserializeError extends CustomError {
constructor(message, contentType, data, options) {
super(message, options);
this.contentType = contentType;
this.data = data;
}
}
class MastoHttpError extends CustomError {
constructor(statusCode, message, description, details, options) {
super(message, options);
this.statusCode = statusCode;
this.message = message;
this.description = description;
this.details = details;
}
}
class MastoTimeoutError extends CustomError {
constructor(message, options) {
super(message, options);
}
}
const getEncoding = (headers) => {
var _a;
const contentType = (_a = headers.get('Content-Type')) === null || _a === void 0 ? void 0 : _a.replace(/\s*;.*$/, '');
if (typeof contentType !== 'string') {
const contentType = (_a = headers.get("Content-Type")) === null || _a === void 0 ? void 0 : _a.replace(/\s*;.*$/, "");
if (typeof contentType !== "string") {
return;
}
switch (contentType) {
case 'application/json': {
return 'json';
case "application/json": {
return "json";
}
case 'application/x-www-form-urlencoded': {
return 'form-url-encoded';
case "multipart/form-data": {
return "multipart-form";
}
case 'multipart/form-data': {
return 'multipart-form';
}
default: {

@@ -255,5 +862,6 @@ return;

(_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`↑ ${request.method} ${request.url}`);
(_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug('\tbody', request.body);
(_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug("\tbody", request.body);
const response = yield fetch(request);
if (!response.ok) {
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw response;

@@ -264,7 +872,7 @@ }

if (encoding == undefined) {
throw new MastoUnexpectedError('Unknown encoding is returned from the server');
throw new MastoUnexpectedError("The server returned data with an unknown encoding.");
}
const data = this.serializer.deserialize(encoding, text);
(_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(`↓ ${request.method} ${request.url}`);
(_d = this.logger) === null || _d === void 0 ? void 0 : _d.debug('\tbody', text);
(_d = this.logger) === null || _d === void 0 ? void 0 : _d.debug("\tbody", text);
return {

@@ -282,32 +890,27 @@ headers: response.headers,

createRequest(params) {
const { method, path, search, encoding = 'json' } = params;
const { method, path, search, encoding = "json", requestInit = {}, } = params;
const url = this.config.resolvePath(path, search);
const headers = this.config.mergeHeadersWithDefaults(params.headers);
const signal = this.config.mergeAbortSignalWithDefaults(params === null || params === void 0 ? void 0 : params.signal);
const body = this.serializer.serialize(encoding, params.body);
const requestInit = {
method,
headers,
body,
signal,
};
if (typeof body === 'string' && encoding === 'json') {
headers.set('Content-Type', 'application/json');
const init = this.config.mergeRequestInitWithDefaults(requestInit);
const request = new Request(url, Object.assign({ method,
body }, init));
if (typeof body === "string" && encoding === "json") {
request.headers.set("Content-Type", "application/json");
}
if (typeof body === 'string' && encoding === 'form-url-encoded') {
headers.set('Content-Type', 'application/x-www-form-urlencoded');
}
return new Request(url, requestInit);
return request;
}
createError(error) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (error instanceof Response) {
const data = this.serializer.deserialize((_a = getEncoding(error.headers)) !== null && _a !== void 0 ? _a : 'json', yield error.text());
return new MastoHttpError(error.status, data === null || data === void 0 ? void 0 : data.error, data === null || data === void 0 ? void 0 : data.description, data === null || data === void 0 ? void 0 : data.details, { cause: error });
const encoding = getEncoding(error.headers);
if (encoding == undefined) {
throw new MastoUnexpectedError("The server returned data with an unknown encoding. The server may be down.");
}
const data = this.serializer.deserialize(encoding, yield error.text());
return new MastoHttpError(error.status, data.error, data.errorDescription, data.details, { cause: error });
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (error != undefined && error.name === 'AbortError') {
if (error != undefined && error.name === "AbortError") {
return new MastoTimeoutError(`Request timed out`, { cause: error });
}
/* istanbul ignore next */
return error;

@@ -323,19 +926,19 @@ });

debug(message, meta) {
if (this.logLevel.satisfies('debug')) {
this.log('debug', message, meta);
if (this.logLevel.satisfies("debug")) {
this.log("debug", message, meta);
}
}
info(message, meta) {
if (this.logLevel.satisfies('info')) {
this.log('info', message, meta);
if (this.logLevel.satisfies("info")) {
this.log("info", message, meta);
}
}
warn(message, meta) {
if (this.logLevel.satisfies('warn')) {
this.log('warn', message, meta);
if (this.logLevel.satisfies("warn")) {
this.log("warn", message, meta);
}
}
error(message, meta) {
if (this.logLevel.satisfies('error')) {
this.log('error', message, meta);
if (this.logLevel.satisfies("error")) {
this.log("error", message, meta);
}

@@ -346,21 +949,18 @@ }

class LoggerConsoleImpl extends BaseLogger {
constructor(logLevel) {
super(logLevel);
}
log(type, message, meta) {
const args = meta == undefined ? [message] : [message, meta];
switch (type) {
case 'debug': {
case "debug": {
console.debug(...args);
return;
}
case 'info': {
case "info": {
console.info(...args);
return;
}
case 'warn': {
case "warn": {
console.warn(...args);
return;
}
case 'error': {
case "error": {
console.error(...args);

@@ -386,12 +986,12 @@ return;

switch (type) {
case 'debug': {
case "debug": {
return Boolean(this.level & LOG_TYPES.DEBUG);
}
case 'info': {
case "info": {
return Boolean(this.level & LOG_TYPES.INFO);
}
case 'warn': {
case "warn": {
return Boolean(this.level & LOG_TYPES.WARN);
}
case 'error': {
case "error": {
return Boolean(this.level & LOG_TYPES.ERROR);

@@ -403,12 +1003,12 @@ }

switch (type) {
case 'debug': {
case "debug": {
return new LogLevel(LOG_TYPES.DEBUG | LOG_TYPES.INFO | LOG_TYPES.WARN | LOG_TYPES.ERROR);
}
case 'info': {
case "info": {
return new LogLevel(LOG_TYPES.INFO | LOG_TYPES.WARN | LOG_TYPES.ERROR);
}
case 'warn': {
case "warn": {
return new LogLevel(LOG_TYPES.WARN | LOG_TYPES.ERROR);
}
case 'error': {
case "error": {
return new LogLevel(LOG_TYPES.ERROR);

@@ -421,219 +1021,21 @@ }

const createLogger = (type) => {
const level = LogLevel.from(type !== null && type !== void 0 ? type : 'warn');
const level = LogLevel.from(type !== null && type !== void 0 ? type : "warn");
return new LoggerConsoleImpl(level);
};
function noop() {
//
}
const isRecord = (x) => typeof x === "object" && x !== null && x.constructor.name === "Object";
const inferEncoding = (action, path) => {
if ((action === 'create' && path === '/api/v1/accounts') ||
(action === 'update' && path === '/api/v1/update_credentials') ||
(action === 'create' && path === '/api/v1/email') ||
(action === 'create' && path === '/api/v1/featured_tag') ||
(action === 'create' && path === '/api/v1/media') ||
(action === 'create' && path === '/api/v2/media')) {
return 'multipart-form';
}
return 'json';
};
class PaginatorHttp {
constructor(http, nextPath, nextParams, meta) {
this.http = http;
this.nextPath = nextPath;
this.nextParams = nextParams;
this.meta = meta;
const hasMinId = nextParams && typeof nextParams === 'object' && 'minId' in nextParams;
this.rel = hasMinId ? 'prev' : 'next';
}
next() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (this.nextPath == undefined) {
return { done: true, value: undefined };
}
const response = yield this.http.request(Object.assign({ method: 'GET', path: this.nextPath, search: this.nextParams }, this.meta));
const nextUrl = this.getLink(response.headers.get('link'));
this.nextPath = nextUrl === null || nextUrl === void 0 ? void 0 : nextUrl.pathname;
this.nextParams = (_a = nextUrl === null || nextUrl === void 0 ? void 0 : nextUrl.search) === null || _a === void 0 ? void 0 : _a.replace(/^\?/, '');
const data = response.data;
const value = this.rel === 'prev' && Array.isArray(data)
? data === null || data === void 0 ? void 0 : data.reverse()
: response.data;
return {
done: false,
value: value,
};
});
}
return(value) {
return __awaiter(this, void 0, void 0, function* () {
this.clear();
return {
done: true,
value: yield value,
};
});
}
throw(e) {
return __awaiter(this, void 0, void 0, function* () {
this.clear();
throw e;
});
}
then(onfulfilled = Promise.resolve, onrejected = Promise.reject) {
// we assume the first item won't be undefined
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.next().then((value) => onfulfilled(value.value), onrejected);
}
values() {
return this[Symbol.asyncIterator]();
}
[Symbol.asyncIterator]() {
// TODO: Use polyfill on demand
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return this;
}
getLink(value) {
var _a, _b;
if (value == undefined) {
return;
}
const parsed = (_b = (_a = parseLinkHeader(value)) === null || _a === void 0 ? void 0 : _a[this.rel]) === null || _b === void 0 ? void 0 : _b.url;
if (parsed == undefined) {
return;
}
return new URL(parsed);
}
clear() {
this.nextPath = undefined;
this.nextParams = undefined;
}
clone() {
return new PaginatorHttp(this.http, this.nextPath, this.nextParams, this.meta);
}
}
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms));
// https://en.wikipedia.org/wiki/Exponential_backoff
class ExponentialBackoff {
constructor(base = 2, factor = 1000) {
this.base = base;
this.factor = factor;
this._attempts = 0;
}
get timeout() {
return this.factor * Math.pow(this.base, this._attempts);
}
get attempts() {
return this._attempts;
}
clear() {
this._attempts = 0;
}
sleep() {
return __awaiter(this, void 0, void 0, function* () {
yield delay(this.timeout);
this._attempts++;
});
}
}
const waitForMediaAttachment = (http, id, timeoutMs = 60 * 1000) => __awaiter(void 0, void 0, void 0, function* () {
let media;
const signal = AbortSignal.timeout(timeoutMs);
while (media == undefined) {
try {
signal.throwIfAborted();
yield delay(1000);
const processing = yield http.get(`/api/v1/media/${id}`);
if (processing.url != undefined) {
media = processing;
}
}
catch (error) {
if (error instanceof MastoHttpError && error.statusCode === 404) {
continue;
}
if (typeof error === 'string') {
throw new MastoTimeoutError(error);
}
throw error;
}
}
return media;
});
const createRequestBuilder = (http, context = []) => {
return new Proxy(noop, {
get: get(http, context),
apply: apply(http, context),
});
};
const get = (http, context) => (_, key) => {
// Promise not permitted
if (key === 'then') {
return;
}
return createRequestBuilder(http, [...context, key]);
};
const apply = (http, context) => (_1, _2, args) => {
const action = context.pop();
if (action == undefined) {
throw new Error('No action specified');
}
if (action === 'select') {
return createRequestBuilder(http, [...context, ...args]);
}
const data = args[0];
const path = '/' + context.map((name) => snakeCase(name)).join('/');
const meta = Object.assign({ encoding: inferEncoding(action, path) }, args[1]);
switch (action) {
case 'fetch': {
return http.get(path, data, meta);
}
case 'create': {
if (path === '/api/v2/media') {
return http
.post(path, data, meta)
.then((media) => {
return waitForMediaAttachment(http, media.id);
});
}
return http.post(path, data, meta);
}
case 'update': {
return http.patch(path, data, meta);
}
case 'remove': {
return http.delete(path, data, meta);
}
case 'list': {
return new PaginatorHttp(http, path, data);
}
default: {
const customAction = [path, snakeCase(action)].join('/');
return http.post(customAction, data);
}
}
};
const isObject = (x) => typeof x === 'object' && x !== null && x.constructor.name === 'Object';
const flattenObject = (object, parent = '') => {
const flattenRecord = (object, parent = "") => {
if (Array.isArray(object)) {
return object
.map((value, i) => flattenObject(value, parent == '' ? i.toString() : `${parent}[${i}]`))
.map((value, i) => flattenRecord(value, parent == "" ? i.toString() : `${parent}[${i}]`))
.reduce((prev, curr) => Object.assign(prev, curr), {});
}
if (isObject(object)) {
if (isRecord(object)) {
return Object.entries(object)
.map(([key, value]) => flattenObject(value, parent === '' ? key : `${parent}[${key}]`))
.map(([key, value]) => flattenRecord(value, parent === "" ? key : `${parent}[${key}]`))
.reduce((prev, curr) => Object.assign(prev, curr), {});
}
// Unit of the monoid is always an object
return parent === ''
return parent === ""
? object

@@ -643,8 +1045,8 @@ : { [parent]: object };

const flatten = (object, parent = '') => {
const flatten = (object, parent = "") => {
if (Array.isArray(object)) {
return object.flatMap((value, i) => flatten(value, parent == '' ? i.toString() : `${parent}[]`));
return object.flatMap((value, i) => flatten(value, parent == "" ? i.toString() : `${parent}[]`));
}
if (isObject(object)) {
return Object.entries(object).flatMap(([key, value]) => flatten(value, parent === '' ? key : `${parent}[${key}]`));
if (isRecord(object)) {
return Object.entries(object).flatMap(([key, value]) => flatten(value, parent === "" ? key : `${parent}[${key}]`));
}

@@ -657,3 +1059,3 @@ return [[parent, object]];

.map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
.join('&');
.join("&");
};

@@ -666,3 +1068,3 @@ const railsQueryString = { stringify };

}
if (isObject(data)) {
if (isRecord(data)) {
return Object.fromEntries(Object.entries(data).map(([key, value]) => [

@@ -678,6 +1080,6 @@ transform(key),

// `PATCH /v1/preferences` uses `:` as a delimiter
if (key.includes(':'))
if (key.includes(":"))
return key;
// `PATCH /v2/filters` uses _destroy as a special key
if (key.startsWith('_'))
if (key.startsWith("_"))
return key;

@@ -691,13 +1093,10 @@ return transform(key);

serialize(type, rawData) {
if (rawData == undefined) {
return;
}
const data = transformKeys(rawData, snakeCase);
switch (type) {
case 'json': {
case "json": {
return JSON.stringify(data);
}
case 'multipart-form': {
case "multipart-form": {
const formData = new FormData();
for (const [key, value] of Object.entries(flattenObject(data))) {
for (const [key, value] of Object.entries(flattenRecord(data))) {
formData.append(key, value);

@@ -707,8 +1106,7 @@ }

}
case 'form-url-encoded':
case 'querystring': {
case "querystring": {
return railsQueryString.stringify(data);
}
default: {
return;
throw new MastoUnexpectedError(`Unknown content type ${type} to serialize.`);
}

@@ -719,3 +1117,3 @@ }

switch (type) {
case 'json': {
case "json": {
try {

@@ -725,3 +1123,3 @@ return transformKeys(JSON.parse(data), camelCase);

catch (_a) {
return undefined;
throw new MastoDeserializeError(`Malformed JSON ${data} returned from the server.`, type, data);
}

@@ -736,254 +1134,2 @@ }

function toAsyncIterable(ws) {
return __asyncGenerator(this, arguments, function* toAsyncIterable_1() {
var _a, e_1, _b, _c;
const handleClose = (e) => {
if (events.return == undefined) {
throw new MastoUnexpectedError('events.return is undefined');
}
events.return(e);
};
const handleError = (e) => {
if (events.throw == undefined) {
throw new MastoUnexpectedError('events.return is undefined');
}
events.throw(e);
};
const events = on((handler) => {
ws.addEventListener('message', handler);
ws.addEventListener('error', handleError);
ws.addEventListener('close', handleClose);
return () => {
ws.removeEventListener('message', handler);
ws.removeEventListener('error', handleError);
ws.removeEventListener('close', handleClose);
};
});
try {
for (var _d = true, events_1 = __asyncValues(events), events_1_1; events_1_1 = yield __await(events_1.next()), _a = events_1_1.done, !_a; _d = true) {
_c = events_1_1.value;
_d = false;
const [event] = _c;
yield yield __await(event);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = events_1.return)) yield __await(_b.call(events_1));
}
finally { if (e_1) throw e_1.error; }
}
});
}
function connect(params) {
return __awaiter(this, void 0, void 0, function* () {
const ws = new WebSocket(...params);
return new Promise((resolve, reject) => {
const handleError = (error) => {
reject(error);
};
const handleOpen = () => {
resolve(ws);
};
ws.addEventListener('error', handleError, { once: true });
ws.addEventListener('open', handleOpen, { once: true });
});
});
}
/* eslint-disable @typescript-eslint/no-unused-vars */
function waitForAsyncIterableToEnd(subject) {
var _a, subject_1, subject_1_1;
var _b, e_1, _c, _d;
return __awaiter(this, void 0, void 0, function* () {
try {
for (_a = true, subject_1 = __asyncValues(subject); subject_1_1 = yield subject_1.next(), _b = subject_1_1.done, !_b; _a = true) {
_d = subject_1_1.value;
_a = false;
const _ = _d;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_a && !_b && (_c = subject_1.return)) yield _c.call(subject_1);
}
finally { if (e_1) throw e_1.error; }
}
return;
});
}
class WebSocketConnector {
constructor(params, logger, config) {
this.params = params;
this.logger = logger;
this.config = config;
this.disableRetry = false;
}
getConnections() {
return __asyncGenerator(this, arguments, function* getConnections_1() {
const backoff = new ExponentialBackoff(2);
while (this.shouldRetry(backoff)) {
try {
this.ws = yield __await(connect(this.params));
this.logger.info('WebSocket connection established');
const messages = toAsyncIterable(this.ws);
yield yield __await({
messages,
readyState: this.ws.readyState,
send: this.ws.send.bind(this.ws),
close: this.close.bind(this),
});
yield __await(waitForAsyncIterableToEnd(messages));
this.logger.info('WebSocket connection closed');
backoff.clear();
}
catch (error) {
this.logger.warn('WebSocket error occurred', error);
}
finally {
this.logger.info(`Reconnecting in ${backoff.timeout}ms...`);
yield __await(backoff.sleep());
}
}
});
}
close() {
// It can be undefined if client is closed before connection is established
if (this.ws == undefined) {
return;
}
this.disableRetry = true;
this.ws.close();
}
shouldRetry(backoff) {
if (this.disableRetry) {
return false;
}
return backoff.attempts < this.config.getMaxAttempts();
}
}
class WebSocketSubscription {
constructor(connections, serializer, stream, params) {
this.connections = connections;
this.serializer = serializer;
this.stream = stream;
this.params = params;
}
values() {
return __asyncGenerator(this, arguments, function* values_1() {
var _a, e_1, _b, _c, _d, e_2, _e, _f;
try {
for (var _g = true, _h = __asyncValues(this.connections), _j; _j = yield __await(_h.next()), _a = _j.done, !_a; _g = true) {
_c = _j.value;
_g = false;
this.connection = _c;
const data = this.serializer.serialize('json', Object.assign({ type: 'subscribe', stream: this.stream }, this.params));
if (data == undefined) {
throw new MastoUnexpectedError('Failed to serialize data');
}
this.connection.send(data);
try {
for (var _k = true, _l = (e_2 = void 0, __asyncValues(this.mapEvents(this.connection.messages))), _m; _m = yield __await(_l.next()), _d = _m.done, !_d; _k = true) {
_f = _m.value;
_k = false;
const event = _f;
if (!event.stream.includes(this.stream)) {
continue;
}
yield yield __await(event);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (!_k && !_d && (_e = _l.return)) yield __await(_e.call(_l));
}
finally { if (e_2) throw e_2.error; }
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_g && !_a && (_b = _h.return)) yield __await(_b.call(_h));
}
finally { if (e_1) throw e_1.error; }
}
});
}
unsubscribe() {
const data = this.serializer.serialize('json', Object.assign({ type: 'unsubscribe', stream: this.stream }, this.params));
if (this.connection == undefined) {
throw new MastoUnexpectedError('No connection established');
}
if (data == undefined) {
throw new MastoUnexpectedError('Failed to serialize data');
}
this.connection.send(data);
}
[Symbol.asyncIterator]() {
return this.values();
}
mapEvents(messages) {
return __asyncGenerator(this, arguments, function* mapEvents_1() {
var _a, e_3, _b, _c;
try {
for (var _d = true, messages_1 = __asyncValues(messages), messages_1_1; messages_1_1 = yield __await(messages_1.next()), _a = messages_1_1.done, !_a; _d = true) {
_c = messages_1_1.value;
_d = false;
const message = _c;
const event = yield __await(this.parseMessage(message.data));
yield yield __await(event);
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (!_d && !_a && (_b = messages_1.return)) yield __await(_b.call(messages_1));
}
finally { if (e_3) throw e_3.error; }
}
});
}
parseMessage(rawEvent) {
return __awaiter(this, void 0, void 0, function* () {
const data = this.serializer.deserialize('json', rawEvent);
if ('error' in data) {
throw new MastoUnexpectedError(data.error);
}
const payload = data.event === 'delete'
? data.payload
: this.serializer.deserialize('json', data.payload);
return {
stream: data.stream,
event: data.event,
payload: payload,
};
});
}
}
class WebSocketClientNativeImpl {
constructor(connections, serializer, onClose) {
this.connections = connections;
this.serializer = serializer;
this.onClose = onClose;
}
get readyState() {
var _a, _b;
return (_b = (_a = this.connection) === null || _a === void 0 ? void 0 : _a.readyState) !== null && _b !== void 0 ? _b : WebSocket.CLOSED;
}
subscribe(stream, params) {
return new WebSocketSubscription(this.connections, this.serializer, stream, params);
}
close() {
this.onClose();
}
}
const createRestClient = (props) => {

@@ -994,4 +1140,7 @@ const serializer = new SerializerNativeImpl();

const http = new HttpNativeImpl(serializer, config, logger);
const builder = createRequestBuilder(http, ['api']);
return builder;
const actionDispatcher = new HttpActionDispatcher(http);
const actionProxy = createActionProxy(actionDispatcher, [
"api",
]);
return actionProxy;
};

@@ -1003,6 +1152,7 @@ const createOAuthClient = (props) => {

const http = new HttpNativeImpl(serializer, config, logger);
const builder = createRequestBuilder(http, [
'oauth',
const actionDispatcher = new HttpActionDispatcher(http);
const actionProxy = createActionProxy(actionDispatcher, [
"oauth",
]);
return builder;
return actionProxy;
};

@@ -1013,51 +1163,52 @@ function createStreamingClient(props) {

const logger = createLogger(props.logLevel);
const connector = new WebSocketConnector([config.resolvePath('/api/v1/streaming').toString(), config.getProtocols()], logger, config);
const connections = connector.getConnections();
return new WebSocketClientNativeImpl(connections, serializer, connector.close.bind(connector));
const connector = new WebSocketConnectorImpl([config.resolvePath("/api/v1/streaming"), config.getProtocols()], logger, config.getMaxAttempts());
const actionDispatcher = new WebSocketActionDispatcher(connector, serializer, logger);
const actionProxy = createActionProxy(actionDispatcher);
return actionProxy;
}
var index$7 = /*#__PURE__*/Object.freeze({
__proto__: null
__proto__: null
});
var index$6 = /*#__PURE__*/Object.freeze({
__proto__: null,
Admin: index$7
__proto__: null,
Admin: index$7
});
var index$5 = /*#__PURE__*/Object.freeze({
__proto__: null
__proto__: null
});
var index$4 = /*#__PURE__*/Object.freeze({
__proto__: null
__proto__: null
});
var index$3 = /*#__PURE__*/Object.freeze({
__proto__: null
__proto__: null
});
var index$2 = /*#__PURE__*/Object.freeze({
__proto__: null,
v1: index$4,
v2: index$3
__proto__: null,
v1: index$4,
v2: index$3
});
var index$1 = /*#__PURE__*/Object.freeze({
__proto__: null
__proto__: null
});
var index = /*#__PURE__*/Object.freeze({
__proto__: null
__proto__: null
});
var mastodon = /*#__PURE__*/Object.freeze({
__proto__: null,
oauth: index,
rest: index$2,
streaming: index$1,
v1: index$6,
v2: index$5
__proto__: null,
oauth: index,
rest: index$2,
streaming: index$1,
v1: index$6,
v2: index$5
});
export { createOAuthClient, createRestClient, createStreamingClient, mastodon };

@@ -5,6 +5,7 @@ {

"private": false,
"version": "6.0.0-alpha.3",
"version": "6.0.0-alpha.4",
"author": "Ryo Igarashi <n33t5hin@gmail.com>",
"license": "MIT",
"type": "module",
"sideEffects": false,
"types": "./dist/index.d.ts",

@@ -25,4 +26,4 @@ "main": "./dist/index.cjs",

"lint": "npm-run-all lint:*",
"lint:eslint": "eslint --ext ts --report-unused-disable-directives --cache '{src,examples,tests,test-utils}/**/*'",
"lint:spellcheck": "cspell '{src,examples}/**/*.{ts,tsx,js,json,md}'",
"lint:eslint": "eslint --ext ts --report-unused-disable-directives --cache '{src,tests,test-utils}/**/*'",
"lint:spellcheck": "cspell '{src,test,test-utils}/**/*.{ts,tsx,js,json,md}'",
"build": "rollup -c rollup.config.cjs",

@@ -62,2 +63,3 @@ "prepublishOnly": "yarn run build",

"eslint-plugin-unicorn": "^47.0.0",
"get-port": "^5.1.1",
"iterator-helpers-polyfill": "^2.3.1",

@@ -64,0 +66,0 @@ "jest": "^29.5.0",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

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