@frontierjs/web
Version:
Web modules for FrontierJS
906 lines (893 loc) • 30.7 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __reExport = (target, module, copyDefault, desc) => {
if (module && typeof module === "object" || typeof module === "function") {
for (let key of __getOwnPropNames(module))
if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
__defProp(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable });
}
return target;
};
var __toESM = (module, isNodeMode) => {
return __reExport(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", !isNodeMode && module && module.__esModule ? { get: () => module.default, enumerable: true } : { value: module, enumerable: true })), module);
};
// ../../node_modules/@feathersjs/errors/lib/index.js
var require_lib = __commonJS({
"../../node_modules/@feathersjs/errors/lib/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convert = exports.errors = exports.Unavailable = exports.BadGateway = exports.NotImplemented = exports.GeneralError = exports.TooManyRequests = exports.Unprocessable = exports.LengthRequired = exports.Gone = exports.Conflict = exports.Timeout = exports.NotAcceptable = exports.MethodNotAllowed = exports.NotFound = exports.Forbidden = exports.PaymentError = exports.NotAuthenticated = exports.BadRequest = exports.FeathersError = void 0;
var FeathersError = class extends Error {
constructor(err, name, code, className, _data) {
let msg = typeof err === "string" ? err : "Error";
const properties = {
name,
code,
className,
type: "FeathersError"
};
if (Array.isArray(_data)) {
properties.data = _data;
} else if (typeof err === "object" || _data !== void 0) {
const { message, errors, ...rest } = err !== null && typeof err === "object" ? err : _data;
msg = message || msg;
properties.errors = errors;
properties.data = rest;
}
super(msg);
Object.assign(this, properties);
}
toJSON() {
const result = {
name: this.name,
message: this.message,
code: this.code,
className: this.className
};
if (this.data !== void 0) {
result.data = this.data;
}
if (this.errors !== void 0) {
result.errors = this.errors;
}
return result;
}
};
exports.FeathersError = FeathersError;
var BadRequest = class extends FeathersError {
constructor(message, data) {
super(message, "BadRequest", 400, "bad-request", data);
}
};
exports.BadRequest = BadRequest;
var NotAuthenticated = class extends FeathersError {
constructor(message, data) {
super(message, "NotAuthenticated", 401, "not-authenticated", data);
}
};
exports.NotAuthenticated = NotAuthenticated;
var PaymentError = class extends FeathersError {
constructor(message, data) {
super(message, "PaymentError", 402, "payment-error", data);
}
};
exports.PaymentError = PaymentError;
var Forbidden = class extends FeathersError {
constructor(message, data) {
super(message, "Forbidden", 403, "forbidden", data);
}
};
exports.Forbidden = Forbidden;
var NotFound = class extends FeathersError {
constructor(message, data) {
super(message, "NotFound", 404, "not-found", data);
}
};
exports.NotFound = NotFound;
var MethodNotAllowed = class extends FeathersError {
constructor(message, data) {
super(message, "MethodNotAllowed", 405, "method-not-allowed", data);
}
};
exports.MethodNotAllowed = MethodNotAllowed;
var NotAcceptable = class extends FeathersError {
constructor(message, data) {
super(message, "NotAcceptable", 406, "not-acceptable", data);
}
};
exports.NotAcceptable = NotAcceptable;
var Timeout = class extends FeathersError {
constructor(message, data) {
super(message, "Timeout", 408, "timeout", data);
}
};
exports.Timeout = Timeout;
var Conflict = class extends FeathersError {
constructor(message, data) {
super(message, "Conflict", 409, "conflict", data);
}
};
exports.Conflict = Conflict;
var Gone = class extends FeathersError {
constructor(message, data) {
super(message, "Gone", 410, "gone", data);
}
};
exports.Gone = Gone;
var LengthRequired = class extends FeathersError {
constructor(message, data) {
super(message, "LengthRequired", 411, "length-required", data);
}
};
exports.LengthRequired = LengthRequired;
var Unprocessable = class extends FeathersError {
constructor(message, data) {
super(message, "Unprocessable", 422, "unprocessable", data);
}
};
exports.Unprocessable = Unprocessable;
var TooManyRequests = class extends FeathersError {
constructor(message, data) {
super(message, "TooManyRequests", 429, "too-many-requests", data);
}
};
exports.TooManyRequests = TooManyRequests;
var GeneralError = class extends FeathersError {
constructor(message, data) {
super(message, "GeneralError", 500, "general-error", data);
}
};
exports.GeneralError = GeneralError;
var NotImplemented = class extends FeathersError {
constructor(message, data) {
super(message, "NotImplemented", 501, "not-implemented", data);
}
};
exports.NotImplemented = NotImplemented;
var BadGateway = class extends FeathersError {
constructor(message, data) {
super(message, "BadGateway", 502, "bad-gateway", data);
}
};
exports.BadGateway = BadGateway;
var Unavailable = class extends FeathersError {
constructor(message, data) {
super(message, "Unavailable", 503, "unavailable", data);
}
};
exports.Unavailable = Unavailable;
exports.errors = {
FeathersError,
BadRequest,
NotAuthenticated,
PaymentError,
Forbidden,
NotFound,
MethodNotAllowed,
NotAcceptable,
Timeout,
Conflict,
LengthRequired,
Unprocessable,
TooManyRequests,
GeneralError,
NotImplemented,
BadGateway,
Unavailable,
400: BadRequest,
401: NotAuthenticated,
402: PaymentError,
403: Forbidden,
404: NotFound,
405: MethodNotAllowed,
406: NotAcceptable,
408: Timeout,
409: Conflict,
410: Gone,
411: LengthRequired,
422: Unprocessable,
429: TooManyRequests,
500: GeneralError,
501: NotImplemented,
502: BadGateway,
503: Unavailable
};
function convert(error) {
if (!error) {
return error;
}
const FeathersError2 = exports.errors[error.name];
const result = FeathersError2 ? new FeathersError2(error.message, error.data) : new Error(error.message || error);
if (typeof error === "object") {
Object.assign(result, error);
}
return result;
}
exports.convert = convert;
}
});
// ../../node_modules/@feathersjs/authentication-client/lib/storage.js
var require_storage = __commonJS({
"../../node_modules/@feathersjs/authentication-client/lib/storage.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StorageWrapper = exports.MemoryStorage = void 0;
var MemoryStorage = class {
constructor() {
this.store = {};
}
getItem(key) {
return Promise.resolve(this.store[key]);
}
setItem(key, value) {
return Promise.resolve(this.store[key] = value);
}
removeItem(key) {
const value = this.store[key];
delete this.store[key];
return Promise.resolve(value);
}
};
exports.MemoryStorage = MemoryStorage;
var StorageWrapper = class {
constructor(storage) {
this.storage = storage;
}
getItem(key) {
return Promise.resolve(this.storage.getItem(key));
}
setItem(key, value) {
return Promise.resolve(this.storage.setItem(key, value));
}
removeItem(key) {
return Promise.resolve(this.storage.removeItem(key));
}
};
exports.StorageWrapper = StorageWrapper;
}
});
// ../../node_modules/@feathersjs/authentication-client/lib/core.js
var require_core = __commonJS({
"../../node_modules/@feathersjs/authentication-client/lib/core.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthenticationClient = void 0;
var errors_1 = require_lib();
var storage_1 = require_storage();
var OauthError = class extends errors_1.FeathersError {
constructor(message, data) {
super(message, "OauthError", 401, "oauth-error", data);
}
};
var getMatch = (location, key) => {
const regex = new RegExp(`(?:&?)${key}=([^&]*)`);
const match = location.hash ? location.hash.match(regex) : null;
if (match !== null) {
const [, value] = match;
return [value, regex];
}
return [null, regex];
};
var AuthenticationClient = class {
constructor(app, options) {
const socket = app.io;
const storage = new storage_1.StorageWrapper(app.get("storage") || options.storage);
this.app = app;
this.options = options;
this.authenticated = false;
this.app.set("storage", storage);
if (socket) {
this.handleSocket(socket);
}
}
get service() {
return this.app.service(this.options.path);
}
get storage() {
return this.app.get("storage");
}
handleSocket(socket) {
socket.on("disconnect", () => {
if (this.authenticated) {
this.reAuthenticate(true);
}
});
}
getFromLocation(location) {
const [accessToken, tokenRegex] = getMatch(location, this.options.locationKey);
if (accessToken !== null) {
location.hash = location.hash.replace(tokenRegex, "");
return Promise.resolve(accessToken);
}
const [message, errorRegex] = getMatch(location, this.options.locationErrorKey);
if (message !== null) {
location.hash = location.hash.replace(errorRegex, "");
return Promise.reject(new OauthError(decodeURIComponent(message)));
}
return Promise.resolve(null);
}
setAccessToken(accessToken) {
return this.storage.setItem(this.options.storageKey, accessToken);
}
getAccessToken() {
return this.storage.getItem(this.options.storageKey).then((accessToken) => {
if (!accessToken && typeof window !== "undefined" && window.location) {
return this.getFromLocation(window.location);
}
return accessToken || null;
});
}
removeAccessToken() {
return this.storage.removeItem(this.options.storageKey);
}
reset() {
this.app.set("authentication", null);
this.authenticated = false;
return Promise.resolve(null);
}
handleError(error, type) {
if (error.code > 400 && error.code < 408) {
const promise = this.removeAccessToken().then(() => this.reset());
return type === "logout" ? promise : promise.then(() => Promise.reject(error));
}
return this.reset().then(() => Promise.reject(error));
}
reAuthenticate(force = false, strategy) {
let authPromise = this.app.get("authentication");
if (!authPromise || force === true) {
authPromise = this.getAccessToken().then((accessToken) => {
if (!accessToken) {
return this.handleError(new errors_1.NotAuthenticated("No accessToken found in storage"), "authenticate");
}
return this.authenticate({
strategy: strategy || this.options.jwtStrategy,
accessToken
});
});
this.app.set("authentication", authPromise);
}
return authPromise;
}
authenticate(authentication, params) {
if (!authentication) {
return this.reAuthenticate();
}
const promise = this.service.create(authentication, params).then((authResult) => {
const { accessToken } = authResult;
this.authenticated = true;
this.app.emit("login", authResult);
this.app.emit("authenticated", authResult);
return this.setAccessToken(accessToken).then(() => authResult);
}).catch((error) => this.handleError(error, "authenticate"));
this.app.set("authentication", promise);
return promise;
}
logout() {
return Promise.resolve(this.app.get("authentication")).then(() => this.service.remove(null).then((authResult) => this.removeAccessToken().then(() => this.reset()).then(() => {
this.app.emit("logout", authResult);
return authResult;
}))).catch((error) => this.handleError(error, "logout"));
}
};
exports.AuthenticationClient = AuthenticationClient;
}
});
// ../../node_modules/@feathersjs/commons/lib/debug.js
var require_debug = __commonJS({
"../../node_modules/@feathersjs/commons/lib/debug.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDebug = exports.setDebug = exports.noopDebug = void 0;
var debuggers = {};
function noopDebug() {
return function() {
};
}
exports.noopDebug = noopDebug;
var defaultInitializer = noopDebug;
function setDebug(debug) {
defaultInitializer = debug;
Object.keys(debuggers).forEach((name) => {
debuggers[name] = debug(name);
});
}
exports.setDebug = setDebug;
function createDebug(name) {
if (!debuggers[name]) {
debuggers[name] = defaultInitializer(name);
}
return (...args) => debuggers[name](...args);
}
exports.createDebug = createDebug;
}
});
// ../../node_modules/@feathersjs/commons/lib/index.js
var require_lib2 = __commonJS({
"../../node_modules/@feathersjs/commons/lib/index.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0)
k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0)
k2 = k;
o[k2] = m[k];
});
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m)
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
__createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSymbol = exports.isPromise = exports._ = exports.stripSlashes = void 0;
function stripSlashes(name) {
return name.replace(/^(\/+)|(\/+)$/g, "");
}
exports.stripSlashes = stripSlashes;
exports._ = {
each(obj, callback) {
if (obj && typeof obj.forEach === "function") {
obj.forEach(callback);
} else if (exports._.isObject(obj)) {
Object.keys(obj).forEach((key) => callback(obj[key], key));
}
},
some(value, callback) {
return Object.keys(value).map((key) => [value[key], key]).some(([val, key]) => callback(val, key));
},
every(value, callback) {
return Object.keys(value).map((key) => [value[key], key]).every(([val, key]) => callback(val, key));
},
keys(obj) {
return Object.keys(obj);
},
values(obj) {
return exports._.keys(obj).map((key) => obj[key]);
},
isMatch(obj, item) {
return exports._.keys(item).every((key) => obj[key] === item[key]);
},
isEmpty(obj) {
return exports._.keys(obj).length === 0;
},
isObject(item) {
return typeof item === "object" && !Array.isArray(item) && item !== null;
},
isObjectOrArray(value) {
return typeof value === "object" && value !== null;
},
extend(first, ...rest) {
return Object.assign(first, ...rest);
},
omit(obj, ...keys) {
const result = exports._.extend({}, obj);
keys.forEach((key) => delete result[key]);
return result;
},
pick(source, ...keys) {
return keys.reduce((result, key) => {
if (source[key] !== void 0) {
result[key] = source[key];
}
return result;
}, {});
},
merge(target, source) {
if (exports._.isObject(target) && exports._.isObject(source)) {
Object.keys(source).forEach((key) => {
if (exports._.isObject(source[key])) {
if (!target[key]) {
Object.assign(target, { [key]: {} });
}
exports._.merge(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
});
}
return target;
}
};
function isPromise(result) {
return exports._.isObject(result) && typeof result.then === "function";
}
exports.isPromise = isPromise;
function createSymbol(name) {
return typeof Symbol !== "undefined" ? Symbol(name) : name;
}
exports.createSymbol = createSymbol;
__exportStar(require_debug(), exports);
}
});
// ../../node_modules/@feathersjs/authentication-client/lib/hooks/authentication.js
var require_authentication = __commonJS({
"../../node_modules/@feathersjs/authentication-client/lib/hooks/authentication.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.authentication = void 0;
var commons_1 = require_lib2();
var authentication = () => {
return (context, next) => {
const { app, params, path, method, app: { authentication: service } } = context;
if ((0, commons_1.stripSlashes)(service.options.path) === path && method === "create") {
return next();
}
return Promise.resolve(app.get("authentication")).then((authResult) => {
if (authResult) {
context.params = Object.assign({}, authResult, params);
}
}).then(next);
};
};
exports.authentication = authentication;
}
});
// ../../node_modules/@feathersjs/authentication-client/lib/hooks/populate-header.js
var require_populate_header = __commonJS({
"../../node_modules/@feathersjs/authentication-client/lib/hooks/populate-header.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.populateHeader = void 0;
var populateHeader = () => {
return (context, next) => {
const { app, params: { accessToken } } = context;
const authentication = app.authentication;
if (app.rest && accessToken) {
const { scheme, header } = authentication.options;
const authHeader = `${scheme} ${accessToken}`;
context.params.headers = Object.assign({}, {
[header]: authHeader
}, context.params.headers);
}
return next();
};
};
exports.populateHeader = populateHeader;
}
});
// ../../node_modules/@feathersjs/authentication-client/lib/hooks/index.js
var require_hooks = __commonJS({
"../../node_modules/@feathersjs/authentication-client/lib/hooks/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.populateHeader = exports.authentication = void 0;
var authentication_1 = require_authentication();
Object.defineProperty(exports, "authentication", { enumerable: true, get: function() {
return authentication_1.authentication;
} });
var populate_header_1 = require_populate_header();
Object.defineProperty(exports, "populateHeader", { enumerable: true, get: function() {
return populate_header_1.populateHeader;
} });
}
});
// ../../node_modules/@feathersjs/authentication-client/lib/index.js
var require_lib3 = __commonJS({
"../../node_modules/@feathersjs/authentication-client/lib/index.js"(exports, module) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0)
k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0)
k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__importStar || function(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null) {
for (var k in mod)
if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
__createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaults = exports.defaultStorage = exports.hooks = exports.MemoryStorage = exports.AuthenticationClient = exports.getDefaultStorage = void 0;
var core_1 = require_core();
Object.defineProperty(exports, "AuthenticationClient", { enumerable: true, get: function() {
return core_1.AuthenticationClient;
} });
var hooks = __importStar(require_hooks());
exports.hooks = hooks;
var storage_1 = require_storage();
Object.defineProperty(exports, "MemoryStorage", { enumerable: true, get: function() {
return storage_1.MemoryStorage;
} });
var getDefaultStorage = () => {
try {
return new storage_1.StorageWrapper(window.localStorage);
} catch (error) {
}
return new storage_1.MemoryStorage();
};
exports.getDefaultStorage = getDefaultStorage;
exports.defaultStorage = (0, exports.getDefaultStorage)();
exports.defaults = {
header: "Authorization",
scheme: "Bearer",
storageKey: "feathers-jwt",
locationKey: "access_token",
locationErrorKey: "error",
jwtStrategy: "jwt",
path: "/authentication",
Authentication: core_1.AuthenticationClient,
storage: exports.defaultStorage
};
var init = (_options = {}) => {
const options = Object.assign({}, exports.defaults, _options);
const { Authentication } = options;
return (app) => {
const authentication = new Authentication(app, options);
app.authentication = authentication;
app.authenticate = authentication.authenticate.bind(authentication);
app.reAuthenticate = authentication.reAuthenticate.bind(authentication);
app.logout = authentication.logout.bind(authentication);
app.hooks([hooks.authentication(), hooks.populateHeader()]);
};
};
exports.default = init;
if (typeof module !== "undefined") {
module.exports = Object.assign(init, module.exports);
}
}
});
// ../../node_modules/svelte/internal/index.mjs
function noop() {
}
function run(fn) {
return fn();
}
function run_all(fns) {
fns.forEach(run);
}
function is_function(thing) {
return typeof thing === "function";
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || (a && typeof a === "object" || typeof a === "function");
}
function is_empty(obj) {
return Object.keys(obj).length === 0;
}
var render_callbacks = [];
function flush_render_callbacks(fns) {
const filtered = [];
const targets = [];
render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c));
targets.forEach((c) => c());
render_callbacks = filtered;
}
var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : global;
var _boolean_attributes = [
"allowfullscreen",
"allowpaymentrequest",
"async",
"autofocus",
"autoplay",
"checked",
"controls",
"default",
"defer",
"disabled",
"formnovalidate",
"hidden",
"inert",
"ismap",
"itemscope",
"loop",
"multiple",
"muted",
"nomodule",
"novalidate",
"open",
"playsinline",
"readonly",
"required",
"reversed",
"selected"
];
var boolean_attributes = /* @__PURE__ */ new Set([..._boolean_attributes]);
function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
flush_render_callbacks($$.after_update);
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);
$$.on_destroy = $$.fragment = null;
$$.ctx = [];
}
}
var SvelteElement;
if (typeof HTMLElement === "function") {
SvelteElement = class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
connectedCallback() {
const { on_mount } = this.$$;
this.$$.on_disconnect = on_mount.map(run).filter(is_function);
for (const key in this.$$.slotted) {
this.appendChild(this.$$.slotted[key]);
}
}
attributeChangedCallback(attr, _oldValue, newValue) {
this[attr] = newValue;
}
disconnectedCallback() {
run_all(this.$$.on_disconnect);
}
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(type, callback) {
if (!is_function(callback)) {
return noop;
}
const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set($$props) {
if (this.$$set && !is_empty($$props)) {
this.$$.skip_bound = true;
this.$$set($$props);
this.$$.skip_bound = false;
}
}
};
}
// ../../node_modules/svelte/store/index.mjs
var subscriber_queue = [];
function writable(value, start = noop) {
let stop;
const subscribers = /* @__PURE__ */ new Set();
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) {
const run_queue = !subscriber_queue.length;
for (const subscriber of subscribers) {
subscriber[1]();
subscriber_queue.push(subscriber, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn) {
set(fn(value));
}
function subscribe2(run2, invalidate = noop) {
const subscriber = [run2, invalidate];
subscribers.add(subscriber);
if (subscribers.size === 1) {
stop = start(set) || noop;
}
run2(value);
return () => {
subscribers.delete(subscriber);
if (subscribers.size === 0 && stop) {
stop();
stop = null;
}
};
}
return { set, update, subscribe: subscribe2 };
}
// src/auth.js
var import_authentication_client = __toESM(require_lib3());
function Auth(spec = {}) {
const { client, currentUser, currentAccount } = spec;
client.configure((0, import_authentication_client.default)());
const authenticating = writable(true);
const register = async (account, callback) => {
authenticating.set(true);
await client.service("registration").create(account);
authenticating.set(false);
await login(account, callback);
};
const login = async (credentials, goto) => {
authenticating.set(true);
if (!credentials) {
const res = await client.reAuthenticate();
currentUser.set(res.user);
currentAccount.set(await client.service("/accounts").get(res.user.currentAccountId));
} else {
const res = await client.authenticate({
strategy: "local",
...credentials
});
currentUser.set(res.user);
currentAccount.set(await client.service("/accounts").get(res.user.currentAccountId));
}
if (goto)
goto();
authenticating.set(false);
};
const authenticate = async (credentials) => {
authenticating.set(true);
try {
if (!credentials) {
const res = await client.reAuthenticate();
currentUser.set(res.user);
currentAccount.set(await client.service("/accounts").get(res.user.currentAccountId));
authenticating.set(false);
return res.user;
} else {
const res = await client.authenticate({
strategy: "local",
...credentials
});
currentUser.set(res.user);
currentAccount.set(await client.service("/accounts").get(res.user.currentAccountId));
authenticating.set(false);
return res.user;
}
} catch (error) {
console.log({ error });
authenticating.set(false);
}
};
const logout = async (callback) => {
await client.logout();
currentUser.set(null);
currentAccount.set(null);
if (callback) {
callback();
} else {
window.location = "/";
}
};
return {
authenticating,
register,
login,
logout,
authenticate
};
}
export {
Auth
};