Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

refactor(cloudcp): add Pulse Account api client

rcourtman890fd1ef834f
diff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.json
index f4493e9405..59df8cd3bf 100644
--- a/internal/cloudcp/portal/dist/build_manifest.json
+++ b/internal/cloudcp/portal/dist/build_manifest.json
@@ -1,5 +1,5 @@
{
- "source_hash": "a60b0c0002a91c72c4127150533ff4570e3cd5448a3394b281f7fa79832f8c8c",
+ "source_hash": "efb5c65245004ede19f36d87be063a2c2ed5e9904c765b1e94d6cadd7f88fc6c",
"build_inputs": [
"package.json",
"tsconfig.json",
diff --git a/internal/cloudcp/portal/dist/portal_app.js b/internal/cloudcp/portal/dist/portal_app.js
index ce1016057d..0e8790e49e 100644
--- a/internal/cloudcp/portal/dist/portal_app.js
+++ b/internal/cloudcp/portal/dist/portal_app.js
@@ -167,6 +167,151 @@
});
}
+ // src/api.ts
+ var PortalAPIError = class extends Error {
+ constructor(message, status = 0, payload = null) {
+ super(message);
+ this.name = "PortalAPIError";
+ this.status = status;
+ this.payload = payload;
+ }
+ };
+ function createPortalAPI(context) {
+ function bootstrap() {
+ return context.getBootstrap();
+ }
+ async function readPayload(response) {
+ var contentType = response.headers && typeof response.headers.get === "function" ? response.headers.get("content-type") || "" : "";
+ if (typeof response.json === "function") {
+ try {
+ return await response.json();
+ } catch {
+ }
+ }
+ if (contentType.includes("application/json")) {
+ try {
+ return await response.json();
+ } catch {
+ return null;
+ }
+ }
+ try {
+ var text = await response.text();
+ return text || null;
+ } catch {
+ return null;
+ }
+ }
+ function messageFromPayload(payload, fallback) {
+ if (payload && typeof payload === "object") {
+ var errorMessage = payload.error;
+ if (typeof errorMessage === "string" && errorMessage.trim()) {
+ return errorMessage;
+ }
+ var message = payload.message;
+ if (typeof message === "string" && message.trim()) {
+ return message;
+ }
+ }
+ if (typeof payload === "string" && payload.trim()) {
+ return payload;
+ }
+ return fallback;
+ }
+ async function request(input, init, fallbackMessage) {
+ var response;
+ try {
+ if (Object.keys(init).length > 0) {
+ response = await fetch(input, init);
+ } else {
+ response = await fetch(input);
+ }
+ } catch {
+ throw new PortalAPIError("Network error.", 0, null);
+ }
+ var payload = await readPayload(response);
+ if (!response.ok) {
+ throw new PortalAPIError(messageFromPayload(payload, fallbackMessage), response.status, payload);
+ }
+ return payload;
+ }
+ function accountURL(accountID, suffix = "") {
+ return bootstrap().account_api_base_path + "/" + encodeURIComponent(accountID) + suffix;
+ }
+ return {
+ fetchBootstrap: function() {
+ return request(bootstrap().bootstrap_path, {
+ headers: { Accept: "application/json" }
+ }, "Failed to refresh account state.");
+ },
+ requestMagicLink: function(email) {
+ return request(bootstrap().magic_link_request_path, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email })
+ }, "Failed to send magic link.");
+ },
+ logout: function() {
+ return request(bootstrap().logout_path, {
+ method: "POST"
+ }, "Failed to sign out.");
+ },
+ postCommercialJSON: function(path, body) {
+ return request(bootstrap().commercial_api_base_url + path, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }, "Commercial request failed.");
+ },
+ createWorkspace: function(accountID, body) {
+ return request(accountURL(accountID, "/tenants"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }, "Failed to create workspace.");
+ },
+ suspendWorkspace: function(accountID, tenantID) {
+ return request(accountURL(accountID, "/tenants/" + encodeURIComponent(tenantID)), {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ state: "suspended" })
+ }, "Failed to suspend workspace.");
+ },
+ deleteWorkspace: function(accountID, tenantID) {
+ return request(accountURL(accountID, "/tenants/" + encodeURIComponent(tenantID)), {
+ method: "DELETE"
+ }, "Failed to delete workspace.");
+ },
+ openBilling: function(accountID) {
+ return request(bootstrap().portal_api_base_path + "/billing?account_id=" + encodeURIComponent(accountID), {
+ method: "POST"
+ }, "Failed to open billing portal.");
+ },
+ listMembers: function(accountID) {
+ return request(accountURL(accountID, "/members"), {}, "Failed to load team.");
+ },
+ inviteMember: function(accountID, body) {
+ return request(accountURL(accountID, "/members"), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }, "Failed to invite member.");
+ },
+ updateMemberRole: function(accountID, userID, body) {
+ return request(accountURL(accountID, "/members/" + encodeURIComponent(userID)), {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body)
+ }, "Failed to update role.");
+ },
+ removeMember: function(accountID, userID) {
+ return request(accountURL(accountID, "/members/" + encodeURIComponent(userID)), {
+ method: "DELETE"
+ }, "Failed to remove member.");
+ }
+ };
+ }
+
// src/state.ts
function emptyStatus() {
return {
@@ -309,12 +454,6 @@
// src/account_runtime.ts
function installAccountRuntime(deps) {
- var getAccountAPIBasePath = function() {
- return deps.store.getBootstrap().account_api_base_path;
- };
- var getPortalAPIBasePath = function() {
- return deps.store.getBootstrap().portal_api_base_path;
- };
var getPortalPath = function() {
return deps.store.getBootstrap().portal_path;
};
@@ -339,27 +478,18 @@
entry.teamMembers = [];
});
try {
- var r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members");
- if (!r.ok) {
- deps.store.updateAccountState(function(accountState) {
- var entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.teamLoading = false;
- entry.teamError = "Failed to load team.";
- });
- return;
- }
- var members = await r.json();
+ var members = await deps.api.listMembers(accountID);
deps.store.updateAccountState(function(accountState) {
var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamLoading = false;
entry.teamError = "";
entry.teamMembers = Array.isArray(members) ? members : [];
});
- } catch {
+ } catch (error) {
deps.store.updateAccountState(function(accountState) {
var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamLoading = false;
- entry.teamError = "Network error.";
+ entry.teamError = error instanceof Error ? error.message : "Network error.";
});
}
};
@@ -400,18 +530,7 @@
var spinner = getElement("ws-spinner-" + accountID);
if (spinner) spinner.style.display = "block";
try {
- var resp = await fetch(getAccountAPIBasePath() + "/" + accountID + "/tenants", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ display_name: name })
- });
- if (!resp.ok) {
- var err = await resp.json().catch(function() {
- return {};
- });
- deps.showToast(err && err.error || "Failed to create workspace", true);
- return;
- }
+ await deps.api.createWorkspace(accountID, { display_name: name });
if (!await refreshOrRedirect()) {
return;
}
@@ -420,8 +539,8 @@
entry.addWorkspaceOpen = false;
});
deps.showToast("Workspace created!");
- } catch {
- deps.showToast("Network error. Please try again.", true);
+ } catch (error) {
+ deps.showToast(error instanceof Error ? error.message : "Failed to create workspace.", true);
} finally {
if (spinner) spinner.style.display = "none";
}
@@ -430,44 +549,30 @@
evt.stopPropagation();
var action = state === "active" ? "Suspend" : "Delete";
if (!window.confirm(action + ' workspace "' + name + '"?')) return;
- var method = state === "active" ? "PATCH" : "DELETE";
- var body = state === "active" ? JSON.stringify({ state: "suspended" }) : void 0;
try {
- var response = await fetch(getAccountAPIBasePath() + "/" + accountID + "/tenants/" + tenantID, {
- method,
- headers: body ? { "Content-Type": "application/json" } : {},
- body
- });
- if (!response.ok) {
- deps.showToast("Failed to " + action.toLowerCase() + " workspace.", true);
- return;
+ if (state === "active") {
+ await deps.api.suspendWorkspace(accountID, tenantID);
+ } else {
+ await deps.api.deleteWorkspace(accountID, tenantID);
}
if (!await refreshOrRedirect()) {
return;
}
deps.showToast(action + "d workspace.");
- } catch {
- deps.showToast("Network error.", true);
+ } catch (error) {
+ deps.showToast(error instanceof Error ? error.message : "Failed to " + action.toLowerCase() + " workspace.", true);
}
};
var openBilling = async function(accountID) {
try {
- var r = await fetch(getPortalAPIBasePath() + "/billing?account_id=" + encodeURIComponent(accountID), { method: "POST" });
- if (!r.ok) {
- var err = await r.json().catch(function() {
- return {};
- });
- deps.showToast(err && err.error || "Failed to open billing portal.", true);
- return;
- }
- var data = await r.json();
+ var data = await deps.api.openBilling(accountID);
if (data && data.url) {
window.location.href = data.url;
} else {
deps.showToast("Failed to open billing portal.", true);
}
- } catch {
- deps.showToast("Network error.", true);
+ } catch (error) {
+ deps.showToast(error instanceof Error ? error.message : "Failed to open billing portal.", true);
}
};
var toggleTeam = function(accountID) {
@@ -491,75 +596,51 @@
return;
}
try {
- var r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ email, role: roleEl.value })
- });
- if (r.status === 409) {
- deps.showToast("Member already exists.", true);
- return;
- }
- if (!r.ok) {
- var err = await r.text();
- deps.showToast(err || "Failed to invite member.", true);
- return;
- }
+ await deps.api.inviteMember(accountID, { email, role: roleEl.value });
emailEl.value = "";
if (!await refreshAccountTeamSection(accountID)) {
return;
}
deps.showToast("Member invited!");
- } catch {
- deps.showToast("Network error.", true);
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 409) {
+ deps.showToast("Member already exists.", true);
+ return;
+ }
+ deps.showToast(error instanceof Error ? error.message : "Failed to invite member.", true);
}
};
var changeRole = async function(accountID, userID, newRole) {
try {
- var r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ role: newRole })
- });
- if (r.status === 409) {
- deps.showToast("Cannot demote last owner.", true);
- await loadTeam(accountID);
+ await deps.api.updateMemberRole(accountID, userID, { role: newRole });
+ if (!await refreshAccountTeamSection(accountID)) {
return;
}
- if (!r.ok) {
- deps.showToast("Failed to update role.", true);
+ deps.showToast("Role updated.");
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 409) {
+ deps.showToast("Cannot demote last owner.", true);
await loadTeam(accountID);
return;
}
- if (!await refreshAccountTeamSection(accountID)) {
- return;
- }
- deps.showToast("Role updated.");
- } catch {
- deps.showToast("Network error.", true);
+ deps.showToast(error instanceof Error ? error.message : "Failed to update role.", true);
await loadTeam(accountID);
}
};
var removeMember = async function(accountID, userID, email) {
if (!window.confirm("Remove " + email + " from this account?")) return;
try {
- var r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
- method: "DELETE"
- });
- if (r.status === 409) {
- deps.showToast("Cannot remove last owner.", true);
- return;
- }
- if (!r.ok) {
- deps.showToast("Failed to remove member.", true);
- return;
- }
+ await deps.api.removeMember(accountID, userID);
if (!await refreshAccountTeamSection(accountID)) {
return;
}
deps.showToast("Member removed.");
- } catch {
- deps.showToast("Network error.", true);
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 409) {
+ deps.showToast("Cannot remove last owner.", true);
+ return;
+ }
+ deps.showToast(error instanceof Error ? error.message : "Failed to remove member.", true);
}
};
deps.store.subscribeAccount(renderAccountRuntime);
@@ -602,12 +683,14 @@
nextState.success = false;
});
try {
- var response = await fetch(deps.store.getBootstrap().magic_link_request_path, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ email })
+ await deps.api.requestMagicLink(email);
+ deps.store.updateLoginState(function(nextState) {
+ nextState.sending = false;
+ nextState.success = true;
});
- if (response.ok || response.status === 404) {
+ return;
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 404) {
deps.store.updateLoginState(function(nextState) {
nextState.sending = false;
nextState.success = true;
@@ -615,12 +698,8 @@
return;
}
deps.store.updateLoginState(function(nextState) {
- nextState.error = response.status === 429 ? "Too many requests. Please wait a moment and try again." : "Something went wrong. Please try again.";
+ nextState.error = error instanceof PortalAPIError && error.status === 429 ? "Too many requests. Please wait a moment and try again." : "Network error. Please check your connection and try again.";
});
- } catch (_) {
- deps.store.updateLoginState(function(nextState) {
- nextState.error = "Network error. Please check your connection and try again.";
- }, { notify: false });
}
deps.store.updateLoginState(function(nextState) {
nextState.sending = false;
@@ -656,7 +735,7 @@
logoutBtn.textContent = "Signing out\u2026";
(async function() {
try {
- await fetch(deps.store.getBootstrap().logout_path, { method: "POST" });
+ await deps.api.logout();
} catch (_) {
}
window.location.href = deps.store.getBootstrap().portal_path;
@@ -857,6 +936,7 @@
// src/services.ts
function installServicesRuntime(deps) {
+ var api = deps.api;
var store = deps.store;
store.updateServiceState(function(serviceState) {
if (!serviceState.flows) {
@@ -872,13 +952,6 @@
function updateServiceState(mutator, notify = true) {
return store.updateServiceState(mutator, { notify });
}
- function serviceFetch(path, body) {
- return fetch(store.getBootstrap().commercial_api_base_url + path, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body)
- });
- }
function toggleServicePanel(panelID) {
updateServiceState(function(serviceState) {
toggleServicePanelState(serviceState, panelID);
@@ -1104,9 +1177,7 @@
clearFlowStatus(serviceState, flowID);
});
try {
- var res = await serviceFetch(flow.requestPath, { email });
- var data = await res.json();
- if (!res.ok) throw new Error(data.error || flow.requestErrorMessage);
+ await api.postCommercialJSON(flow.requestPath, { email });
updateServiceState(function(serviceState) {
serviceState.flows[flowID].pendingEmail = email;
serviceState.flows[flowID].step2Visible = !!flow.step2ID;
@@ -1114,7 +1185,7 @@
});
} catch (err) {
updateServiceState(function(serviceState) {
- setFlowStatus(serviceState, flowID, err.message, true);
+ setFlowStatus(serviceState, flowID, err instanceof Error ? err.message : flow.requestErrorMessage, true);
});
} finally {
updateServiceState(function(serviceState) {
@@ -1129,15 +1200,13 @@
var email = getServiceState().flows[flowID].pendingEmail;
if (!email) return;
try {
- var res = await serviceFetch(flow.requestPath, { email });
- var data = await res.json();
- if (!res.ok) throw new Error(data.error || flow.requestErrorMessage);
+ await api.postCommercialJSON(flow.requestPath, { email });
updateServiceState(function(serviceState) {
setFlowStatus(serviceState, flowID, flow.resendSuccessMessage, false);
});
} catch (err) {
updateServiceState(function(serviceState) {
- setFlowStatus(serviceState, flowID, err.message, true);
+ setFlowStatus(serviceState, flowID, err instanceof Error ? err.message : flow.requestErrorMessage, true);
});
}
}
@@ -1154,13 +1223,11 @@
serviceState.flows[flowID].confirming = true;
});
try {
- var res = await serviceFetch(flow.confirmPath, { email, code });
- var data = await res.json();
- if (!res.ok) throw new Error(data.error || flow.confirmErrorMessage);
+ var data = await api.postCommercialJSON(flow.confirmPath, { email, code });
flow.onConfirmSuccess(data, email);
} catch (err) {
updateServiceState(function(serviceState) {
- setFlowStatus(serviceState, flowID, err.message, true);
+ setFlowStatus(serviceState, flowID, err instanceof Error ? err.message : flow.confirmErrorMessage, true);
});
} finally {
updateServiceState(function(serviceState) {
@@ -1193,16 +1260,14 @@
serviceState.refund.status = emptyStatus();
});
try {
- var res = await serviceFetch("/v1/self-refund", { email, token });
- var data = await res.json();
- if (!res.ok) throw new Error(data.error || "Refund failed");
+ await api.postCommercialJSON("/v1/self-refund", { email, token });
updateServiceState(function(serviceState) {
serviceState.refund.tokenValue = "";
setRefundStatus(serviceState, "Success! Your refund has been processed. Stripe will follow up by email.", false);
});
} catch (err) {
updateServiceState(function(serviceState) {
- setRefundStatus(serviceState, err.message, true);
+ setRefundStatus(serviceState, err instanceof Error ? err.message : "Refund failed", true);
});
} finally {
updateServiceState(function(serviceState) {
@@ -1506,6 +1571,11 @@
// src/app.ts
function installPortalApp(deps) {
+ var api = createPortalAPI({
+ getBootstrap: function() {
+ return deps.store.getBootstrap();
+ }
+ });
function applyBootstrap(data) {
return deps.store.setBootstrap(data || createAnonymousBootstrap(deps.bootstrapDefaults));
}
@@ -1513,18 +1583,14 @@
var bootstrap = deps.store.getBootstrap();
if (!bootstrap.bootstrap_path) return false;
try {
- var response = await fetch(bootstrap.bootstrap_path, {
- headers: { Accept: "application/json" }
- });
- if (response.status === 401) {
+ var data = await api.fetchBootstrap();
+ applyBootstrap(data);
+ return true;
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 401) {
applyBootstrap(createAnonymousBootstrap(deps.bootstrapDefaults));
return true;
}
- if (!response.ok) return false;
- var data = await response.json();
- applyBootstrap(data);
- return true;
- } catch (_) {
}
return false;
}
@@ -1542,12 +1608,15 @@
store: deps.store
});
installServicesRuntime({
+ api,
store: deps.store
});
installAuthController({
+ api,
store: deps.store
});
var accountRuntime = installAccountRuntime({
+ api,
store: deps.store,
refreshBootstrap,
showToast
diff --git a/internal/cloudcp/portal/frontend/src/account_runtime.test.ts b/internal/cloudcp/portal/frontend/src/account_runtime.test.ts
index 97ea3f378d..5bdf8d5267 100644
--- a/internal/cloudcp/portal/frontend/src/account_runtime.test.ts
+++ b/internal/cloudcp/portal/frontend/src/account_runtime.test.ts
@@ -1,5 +1,6 @@
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createPortalAPI } from './api';
import { installAccountRuntime } from './account_runtime';
import { createPortalStore } from './store';
import type { PortalBootstrapData } from './types';
@@ -8,6 +9,7 @@ function jsonResponse(payload: unknown, ok = true, status = ok ? 200 : 500) {
return {
ok,
status,
+ headers: new Headers({ 'content-type': 'application/json' }),
json: vi.fn().mockResolvedValue(payload),
text: vi.fn().mockResolvedValue(typeof payload === 'string' ? payload : JSON.stringify(payload)),
};
@@ -37,6 +39,7 @@ const bootstrapDefaults: Omit<PortalBootstrapData, 'authenticated' | 'email' | '
};
const deps = {
+ api: null as any,
store: createPortalStore(bootstrapDefaults, {
authenticated: true,
@@ -49,6 +52,11 @@ describe('account runtime', function() {
var runtime: ReturnType<typeof installAccountRuntime>;
beforeAll(function() {
+ deps.api = createPortalAPI({
+ getBootstrap: function() {
+ return deps.store.getBootstrap();
+ },
+ });
runtime = installAccountRuntime(deps);
});
diff --git a/internal/cloudcp/portal/frontend/src/account_runtime.ts b/internal/cloudcp/portal/frontend/src/account_runtime.ts
index 618a4bca99..37fa703b43 100644
--- a/internal/cloudcp/portal/frontend/src/account_runtime.ts
+++ b/internal/cloudcp/portal/frontend/src/account_runtime.ts
@@ -1,9 +1,12 @@
+import { PortalAPIError } from './api';
+import type { PortalAPI } from './api';
import { focusElement, getElement, renderAccountUI as renderAccountUIState } from './account_view';
import { ensurePortalAccountUIEntry } from './state';
import type { PortalStore } from './store';
import type { PortalTeamMember } from './types';
export interface AccountRuntimeDeps {
+ api: PortalAPI;
store: PortalStore;
refreshBootstrap(): Promise<boolean>;
showToast(message: string, isError?: boolean): void;
@@ -21,14 +24,6 @@ export interface AccountRuntime {
}
export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime {
- var getAccountAPIBasePath = function(): string {
- return deps.store.getBootstrap().account_api_base_path;
- };
-
- var getPortalAPIBasePath = function(): string {
- return deps.store.getBootstrap().portal_api_base_path;
- };
-
var getPortalPath = function(): string {
return deps.store.getBootstrap().portal_path;
};
@@ -56,27 +51,18 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime
entry.teamMembers = [];
});
try {
- var r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members');
- if (!r.ok) {
- deps.store.updateAccountState(function(accountState) {
- var entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.teamLoading = false;
- entry.teamError = 'Failed to load team.';
- });
- return;
- }
- var members = await r.json() as PortalTeamMember[];
+ var members = await deps.api.listMembers(accountID) as PortalTeamMember[];
deps.store.updateAccountState(function(accountState) {
var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamLoading = false;
entry.teamError = '';
entry.teamMembers = Array.isArray(members) ? members : [];
});
- } catch {
+ } catch (error) {
deps.store.updateAccountState(function(accountState) {
var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamLoading = false;
- entry.teamError = 'Network error.';
+ entry.teamError = error instanceof Error ? error.message : 'Network error.';
});
}
};
@@ -120,16 +106,7 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime
var spinner = getElement<HTMLElement>('ws-spinner-' + accountID);
if (spinner) spinner.style.display = 'block';
try {
- var resp = await fetch(getAccountAPIBasePath() + '/' + accountID + '/tenants', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ display_name: name }),
- });
- if (!resp.ok) {
- var err = await resp.json().catch(function() { return {}; });
- deps.showToast((err && err.error) || 'Failed to create workspace', true);
- return;
- }
+ await deps.api.createWorkspace(accountID, { display_name: name });
if (!await refreshOrRedirect()) {
return;
}
@@ -138,8 +115,8 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime
entry.addWorkspaceOpen = false;
});
deps.showToast('Workspace created!');
- } catch {
- deps.showToast('Network error. Please try again.', true);
+ } catch (error) {
+ deps.showToast(error instanceof Error ? error.message : 'Failed to create workspace.', true);
} finally {
if (spinner) spinner.style.display = 'none';
}
@@ -149,43 +126,31 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime
evt.stopPropagation();
var action = state === 'active' ? 'Suspend' : 'Delete';
if (!window.confirm(action + ' workspace "' + name + '"?')) return;
- var method = state === 'active' ? 'PATCH' : 'DELETE';
- var body = state === 'active' ? JSON.stringify({ state: 'suspended' }) : undefined;
try {
- var response = await fetch(getAccountAPIBasePath() + '/' + accountID + '/tenants/' + tenantID, {
- method: method,
- headers: body ? { 'Content-Type': 'application/json' } : {},
- body: body,
- });
- if (!response.ok) {
- deps.showToast('Failed to ' + action.toLowerCase() + ' workspace.', true);
- return;
+ if (state === 'active') {
+ await deps.api.suspendWorkspace(accountID, tenantID);
+ } else {
+ await deps.api.deleteWorkspace(accountID, tenantID);
}
if (!await refreshOrRedirect()) {
return;
}
deps.showToast(action + 'd workspace.');
- } catch {
- deps.showToast('Network error.', true);
+ } catch (error) {
+ deps.showToast(error instanceof Error ? error.message : 'Failed to ' + action.toLowerCase() + ' workspace.', true);
}
};
var openBilling = async function(accountID: string): Promise<void> {
try {
- var r = await fetch(getPortalAPIBasePath() + '/billing?account_id=' + encodeURIComponent(accountID), { method: 'POST' });
- if (!r.ok) {
- var err = await r.json().catch(function() { return {}; });
- deps.showToast((err && err.error) || 'Failed to open billing portal.', true);
- return;
- }
- var data = await r.json();
+ var data = await deps.api.openBilling(accountID);
if (data && data.url) {
window.location.href = data.url;
} else {
deps.showToast('Failed to open billing portal.', true);
}
- } catch {
- deps.showToast('Network error.', true);
+ } catch (error) {
+ deps.showToast(error instanceof Error ? error.message : 'Failed to open billing portal.', true);
}
};
@@ -211,53 +176,35 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime
return;
}
try {
- var r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ email: email, role: roleEl.value }),
- });
- if (r.status === 409) {
- deps.showToast('Member already exists.', true);
- return;
- }
- if (!r.ok) {
- var err = await r.text();
- deps.showToast(err || 'Failed to invite member.', true);
- return;
- }
+ await deps.api.inviteMember(accountID, { email: email, role: roleEl.value });
emailEl.value = '';
if (!await refreshAccountTeamSection(accountID)) {
return;
}
deps.showToast('Member invited!');
- } catch {
- deps.showToast('Network error.', true);
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 409) {
+ deps.showToast('Member already exists.', true);
+ return;
+ }
+ deps.showToast(error instanceof Error ? error.message : 'Failed to invite member.', true);
}
};
var changeRole = async function(accountID: string, userID: string, newRole: string): Promise<void> {
try {
- var r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ role: newRole }),
- });
- if (r.status === 409) {
- deps.showToast('Cannot demote last owner.', true);
- await loadTeam(accountID);
+ await deps.api.updateMemberRole(accountID, userID, { role: newRole });
+ if (!await refreshAccountTeamSection(accountID)) {
return;
}
- if (!r.ok) {
- deps.showToast('Failed to update role.', true);
+ deps.showToast('Role updated.');
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 409) {
+ deps.showToast('Cannot demote last owner.', true);
await loadTeam(accountID);
return;
}
- if (!await refreshAccountTeamSection(accountID)) {
- return;
- }
- deps.showToast('Role updated.');
- } catch {
- deps.showToast('Network error.', true);
+ deps.showToast(error instanceof Error ? error.message : 'Failed to update role.', true);
await loadTeam(accountID);
}
};
@@ -265,23 +212,17 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime
var removeMember = async function(accountID: string, userID: string, email: string): Promise<void> {
if (!window.confirm('Remove ' + email + ' from this account?')) return;
try {
- var r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
- method: 'DELETE',
- });
- if (r.status === 409) {
- deps.showToast('Cannot remove last owner.', true);
- return;
- }
- if (!r.ok) {
- deps.showToast('Failed to remove member.', true);
- return;
- }
+ await deps.api.removeMember(accountID, userID);
if (!await refreshAccountTeamSection(accountID)) {
return;
}
deps.showToast('Member removed.');
- } catch {
- deps.showToast('Network error.', true);
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 409) {
+ deps.showToast('Cannot remove last owner.', true);
+ return;
+ }
+ deps.showToast(error instanceof Error ? error.message : 'Failed to remove member.', true);
}
};
diff --git a/internal/cloudcp/portal/frontend/src/api.test.ts b/internal/cloudcp/portal/frontend/src/api.test.ts
new file mode 100644
index 0000000000..7314a77122
--- /dev/null
+++ b/internal/cloudcp/portal/frontend/src/api.test.ts
@@ -0,0 +1,72 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createPortalAPI } from './api';
+import type { PortalBootstrapData } from './types';
+
+const bootstrap: PortalBootstrapData = {
+ authenticated: true,
+ email: '[email protected]',
+ public_site_url: 'https://pulserelay.pro',
+ support_email: '[email protected]',
+ commercial_api_base_url: 'https://license.pulserelay.pro',
+ portal_path: '/portal',
+ bootstrap_path: '/api/portal/bootstrap',
+ magic_link_request_path: '/api/public/magic-link/request',
+ signup_path: '/signup',
+ logout_path: '/auth/logout',
+ account_api_base_path: '/api/accounts',
+ portal_api_base_path: '/api/portal',
+ accounts: [],
+};
+
+describe('portal api', function() {
+ beforeEach(function() {
+ vi.restoreAllMocks();
+ });
+
+ it('parses bootstrap JSON through the shared api client', async function() {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ headers: new Headers({ 'content-type': 'application/json' }),
+ json: async function() {
+ return {
+ authenticated: true,
+ email: '[email protected]',
+ accounts: [],
+ };
+ },
+ }));
+
+ var api = createPortalAPI({
+ getBootstrap: function() {
+ return bootstrap;
+ },
+ });
+
+ var result = await api.fetchBootstrap();
+ expect(result.email).toBe('[email protected]');
+ });
+
+ it('raises typed api errors with payload-derived messages', async function() {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: false,
+ status: 409,
+ headers: new Headers({ 'content-type': 'application/json' }),
+ json: async function() {
+ return { error: 'Member already exists.' };
+ },
+ }));
+
+ var api = createPortalAPI({
+ getBootstrap: function() {
+ return bootstrap;
+ },
+ });
+
+ await expect(api.inviteMember('acct_1', { email: '[email protected]', role: 'admin' })).rejects.toMatchObject({
+ name: 'PortalAPIError',
+ status: 409,
+ message: 'Member already exists.',
+ });
+ });
+});
diff --git a/internal/cloudcp/portal/frontend/src/api.ts b/internal/cloudcp/portal/frontend/src/api.ts
new file mode 100644
index 0000000000..ae2b7311b6
--- /dev/null
+++ b/internal/cloudcp/portal/frontend/src/api.ts
@@ -0,0 +1,193 @@
+import type { PortalBootstrapData, PortalTeamMember } from './types';
+
+interface PortalAPIContext {
+ getBootstrap(): PortalBootstrapData;
+}
+
+export class PortalAPIError extends Error {
+ status: number;
+ payload: unknown;
+
+ constructor(message: string, status = 0, payload: unknown = null) {
+ super(message);
+ this.name = 'PortalAPIError';
+ this.status = status;
+ this.payload = payload;
+ }
+}
+
+export interface PortalBillingResponse {
+ url?: string;
+}
+
+export interface PortalWorkspaceCreateRequest {
+ display_name: string;
+}
+
+export interface PortalMemberInviteRequest {
+ email: string;
+ role: string;
+}
+
+export interface PortalMemberRoleRequest {
+ role: string;
+}
+
+export interface PortalAPI {
+ fetchBootstrap(): Promise<PortalBootstrapData>;
+ requestMagicLink(email: string): Promise<void>;
+ logout(): Promise<void>;
+ postCommercialJSON<T>(path: string, body: Record<string, unknown>): Promise<T>;
+ createWorkspace(accountID: string, body: PortalWorkspaceCreateRequest): Promise<void>;
+ suspendWorkspace(accountID: string, tenantID: string): Promise<void>;
+ deleteWorkspace(accountID: string, tenantID: string): Promise<void>;
+ openBilling(accountID: string): Promise<PortalBillingResponse>;
+ listMembers(accountID: string): Promise<PortalTeamMember[]>;
+ inviteMember(accountID: string, body: PortalMemberInviteRequest): Promise<void>;
+ updateMemberRole(accountID: string, userID: string, body: PortalMemberRoleRequest): Promise<void>;
+ removeMember(accountID: string, userID: string): Promise<void>;
+}
+
+export function createPortalAPI(context: PortalAPIContext): PortalAPI {
+ function bootstrap() {
+ return context.getBootstrap();
+ }
+
+ async function readPayload(response: Response): Promise<unknown> {
+ var contentType = response.headers && typeof response.headers.get === 'function'
+ ? response.headers.get('content-type') || ''
+ : '';
+ if (typeof response.json === 'function') {
+ try {
+ return await response.json();
+ } catch {
+ // Fall through to text/null handling.
+ }
+ }
+ if (contentType.includes('application/json')) {
+ try {
+ return await response.json();
+ } catch {
+ return null;
+ }
+ }
+ try {
+ var text = await response.text();
+ return text || null;
+ } catch {
+ return null;
+ }
+ }
+
+ function messageFromPayload(payload: unknown, fallback: string): string {
+ if (payload && typeof payload === 'object') {
+ var errorMessage = (payload as { error?: unknown }).error;
+ if (typeof errorMessage === 'string' && errorMessage.trim()) {
+ return errorMessage;
+ }
+ var message = (payload as { message?: unknown }).message;
+ if (typeof message === 'string' && message.trim()) {
+ return message;
+ }
+ }
+ if (typeof payload === 'string' && payload.trim()) {
+ return payload;
+ }
+ return fallback;
+ }
+
+ async function request<T>(input: string, init: RequestInit, fallbackMessage: string): Promise<T> {
+ var response: Response;
+ try {
+ if (Object.keys(init).length > 0) {
+ response = await fetch(input, init);
+ } else {
+ response = await fetch(input);
+ }
+ } catch {
+ throw new PortalAPIError('Network error.', 0, null);
+ }
+ var payload = await readPayload(response);
+ if (!response.ok) {
+ throw new PortalAPIError(messageFromPayload(payload, fallbackMessage), response.status, payload);
+ }
+ return payload as T;
+ }
+
+ function accountURL(accountID: string, suffix = ''): string {
+ return bootstrap().account_api_base_path + '/' + encodeURIComponent(accountID) + suffix;
+ }
+
+ return {
+ fetchBootstrap: function() {
+ return request<PortalBootstrapData>(bootstrap().bootstrap_path, {
+ headers: { Accept: 'application/json' },
+ }, 'Failed to refresh account state.');
+ },
+ requestMagicLink: function(email: string) {
+ return request<void>(bootstrap().magic_link_request_path, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ email: email }),
+ }, 'Failed to send magic link.');
+ },
+ logout: function() {
+ return request<void>(bootstrap().logout_path, {
+ method: 'POST',
+ }, 'Failed to sign out.');
+ },
+ postCommercialJSON: function<T>(path: string, body: Record<string, unknown>) {
+ return request<T>(bootstrap().commercial_api_base_url + path, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ }, 'Commercial request failed.');
+ },
+ createWorkspace: function(accountID: string, body: PortalWorkspaceCreateRequest) {
+ return request<void>(accountURL(accountID, '/tenants'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ }, 'Failed to create workspace.');
+ },
+ suspendWorkspace: function(accountID: string, tenantID: string) {
+ return request<void>(accountURL(accountID, '/tenants/' + encodeURIComponent(tenantID)), {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ state: 'suspended' }),
+ }, 'Failed to suspend workspace.');
+ },
+ deleteWorkspace: function(accountID: string, tenantID: string) {
+ return request<void>(accountURL(accountID, '/tenants/' + encodeURIComponent(tenantID)), {
+ method: 'DELETE',
+ }, 'Failed to delete workspace.');
+ },
+ openBilling: function(accountID: string) {
+ return request<PortalBillingResponse>(bootstrap().portal_api_base_path + '/billing?account_id=' + encodeURIComponent(accountID), {
+ method: 'POST',
+ }, 'Failed to open billing portal.');
+ },
+ listMembers: function(accountID: string) {
+ return request<PortalTeamMember[]>(accountURL(accountID, '/members'), {}, 'Failed to load team.');
+ },
+ inviteMember: function(accountID: string, body: PortalMemberInviteRequest) {
+ return request<void>(accountURL(accountID, '/members'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ }, 'Failed to invite member.');
+ },
+ updateMemberRole: function(accountID: string, userID: string, body: PortalMemberRoleRequest) {
+ return request<void>(accountURL(accountID, '/members/' + encodeURIComponent(userID)), {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ }, 'Failed to update role.');
+ },
+ removeMember: function(accountID: string, userID: string) {
+ return request<void>(accountURL(accountID, '/members/' + encodeURIComponent(userID)), {
+ method: 'DELETE',
+ }, 'Failed to remove member.');
+ },
+ };
+}
diff --git a/internal/cloudcp/portal/frontend/src/app.ts b/internal/cloudcp/portal/frontend/src/app.ts
index c9475e8dc8..95c5a259e6 100644
--- a/internal/cloudcp/portal/frontend/src/app.ts
+++ b/internal/cloudcp/portal/frontend/src/app.ts
@@ -1,5 +1,6 @@
import { installAccountController } from './account_controller';
import { installAccountRuntime } from './account_runtime';
+import { createPortalAPI, PortalAPIError } from './api';
import { installAuthController } from './auth_controller';
import { installServicesRuntime } from './services';
import { installShell } from './shell';
@@ -23,6 +24,12 @@ export interface PortalApp {
}
export function installPortalApp(deps: PortalAppDeps): PortalApp {
+ var api = createPortalAPI({
+ getBootstrap: function() {
+ return deps.store.getBootstrap();
+ },
+ });
+
function applyBootstrap(data: Partial<PortalBootstrapData> | PortalBootstrapData | null | undefined): PortalBootstrapData {
return deps.store.setBootstrap(data || createAnonymousBootstrap(deps.bootstrapDefaults));
}
@@ -31,18 +38,15 @@ export function installPortalApp(deps: PortalAppDeps): PortalApp {
var bootstrap = deps.store.getBootstrap();
if (!bootstrap.bootstrap_path) return false;
try {
- var response = await fetch(bootstrap.bootstrap_path, {
- headers: { Accept: 'application/json' },
- });
- if (response.status === 401) {
+ var data = await api.fetchBootstrap();
+ applyBootstrap(data);
+ return true;
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 401) {
applyBootstrap(createAnonymousBootstrap(deps.bootstrapDefaults));
return true;
}
- if (!response.ok) return false;
- var data = await response.json();
- applyBootstrap(data);
- return true;
- } catch (_) {}
+ }
return false;
}
@@ -62,14 +66,17 @@ export function installPortalApp(deps: PortalAppDeps): PortalApp {
});
installServicesRuntime({
+ api: api,
store: deps.store,
});
installAuthController({
+ api: api,
store: deps.store,
});
var accountRuntime = installAccountRuntime({
+ api: api,
store: deps.store,
refreshBootstrap: refreshBootstrap,
showToast: showToast,
diff --git a/internal/cloudcp/portal/frontend/src/auth_controller.test.ts b/internal/cloudcp/portal/frontend/src/auth_controller.test.ts
index 4651002a13..7069f11492 100644
--- a/internal/cloudcp/portal/frontend/src/auth_controller.test.ts
+++ b/internal/cloudcp/portal/frontend/src/auth_controller.test.ts
@@ -1,9 +1,19 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createPortalAPI } from './api';
import { installAuthController } from './auth_controller';
import { createPortalStore } from './store';
import type { PortalBootstrapData } from './types';
+async function flushAsync() {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ await new Promise(function(resolve) {
+ setTimeout(resolve, 0);
+ });
+}
+
const bootstrapDefaults: Omit<PortalBootstrapData, 'authenticated' | 'email' | 'accounts'> = {
public_site_url: 'https://pulserelay.pro',
support_email: '[email protected]',
@@ -28,6 +38,7 @@ describe('auth controller', function() {
});
var controller = installAuthController({
+ api: createPortalAPI({ getBootstrap: function() { return store.getBootstrap(); } }),
store,
});
@@ -51,6 +62,7 @@ describe('auth controller', function() {
);
var controller = installAuthController({
+ api: createPortalAPI({ getBootstrap: function() { return store.getBootstrap(); } }),
store,
});
@@ -65,8 +77,7 @@ describe('auth controller', function() {
document.getElementById('send')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- await Promise.resolve();
- await Promise.resolve();
+ await flushAsync();
expect(controller.getLoginState().sending).toBe(false);
expect(controller.getLoginState().success).toBe(true);
expect(fetch).toHaveBeenCalledWith(
diff --git a/internal/cloudcp/portal/frontend/src/auth_controller.ts b/internal/cloudcp/portal/frontend/src/auth_controller.ts
index 7d693f3417..3673ec931e 100644
--- a/internal/cloudcp/portal/frontend/src/auth_controller.ts
+++ b/internal/cloudcp/portal/frontend/src/auth_controller.ts
@@ -1,3 +1,5 @@
+import { PortalAPIError } from './api';
+import type { PortalAPI } from './api';
import { createPortalLoginState, syncLoginStateBootstrapEmail } from './state';
import type { PortalLoginState } from './types';
import type { PortalStore } from './store';
@@ -5,6 +7,7 @@ import type { PortalStore } from './store';
type FormValueElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
export interface AuthControllerDeps {
+ api: PortalAPI;
store: PortalStore;
}
@@ -40,12 +43,14 @@ export function installAuthController(deps: AuthControllerDeps): AuthController
nextState.success = false;
});
try {
- var response = await fetch(deps.store.getBootstrap().magic_link_request_path, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ email: email })
+ await deps.api.requestMagicLink(email);
+ deps.store.updateLoginState(function(nextState) {
+ nextState.sending = false;
+ nextState.success = true;
});
- if (response.ok || response.status === 404) {
+ return;
+ } catch (error) {
+ if (error instanceof PortalAPIError && error.status === 404) {
deps.store.updateLoginState(function(nextState) {
nextState.sending = false;
nextState.success = true;
@@ -53,14 +58,10 @@ export function installAuthController(deps: AuthControllerDeps): AuthController
return;
}
deps.store.updateLoginState(function(nextState) {
- nextState.error = response.status === 429
+ nextState.error = error instanceof PortalAPIError && error.status === 429
? 'Too many requests. Please wait a moment and try again.'
- : 'Something went wrong. Please try again.';
+ : 'Network error. Please check your connection and try again.';
});
- } catch (_) {
- deps.store.updateLoginState(function(nextState) {
- nextState.error = 'Network error. Please check your connection and try again.';
- }, { notify: false });
}
deps.store.updateLoginState(function(nextState) {
nextState.sending = false;
@@ -98,7 +99,7 @@ export function installAuthController(deps: AuthControllerDeps): AuthController
logoutBtn.textContent = 'Signing out…';
(async function() {
try {
- await fetch(deps.store.getBootstrap().logout_path, { method: 'POST' });
+ await deps.api.logout();
} catch (_) {}
window.location.href = deps.store.getBootstrap().portal_path;
})();
diff --git a/internal/cloudcp/portal/frontend/src/services.ts b/internal/cloudcp/portal/frontend/src/services.ts
index 0ac41f6f37..62acf97d8c 100644
--- a/internal/cloudcp/portal/frontend/src/services.ts
+++ b/internal/cloudcp/portal/frontend/src/services.ts
@@ -1,3 +1,4 @@
+import type { PortalAPI } from './api';
import { installServicesController } from './services_controller';
import {
clearFlowStatus,
@@ -57,10 +58,12 @@ interface VerificationFlowDefinition {
}
export interface ServicesRuntimeDeps {
+ api: PortalAPI;
store: PortalStore;
}
export function installServicesRuntime(deps: ServicesRuntimeDeps): void {
+ var api = deps.api;
var store = deps.store;
store.updateServiceState(function(serviceState) {
@@ -80,14 +83,6 @@ export function installServicesRuntime(deps: ServicesRuntimeDeps): void {
return store.updateServiceState(mutator, { notify: notify });
}
- function serviceFetch(path, body) {
- return fetch(store.getBootstrap().commercial_api_base_url + path, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- });
- }
-
function toggleServicePanel(panelID) {
updateServiceState(function(serviceState) {
toggleServicePanelState(serviceState, panelID);
@@ -318,9 +313,7 @@ export function installServicesRuntime(deps: ServicesRuntimeDeps): void {
clearFlowStatus(serviceState, flowID);
});
try {
- var res = await serviceFetch(flow.requestPath, { email: email });
- var data = await res.json();
- if (!res.ok) throw new Error(data.error || flow.requestErrorMessage);
+ await api.postCommercialJSON(flow.requestPath, { email: email });
updateServiceState(function(serviceState) {
serviceState.flows[flowID].pendingEmail = email;
serviceState.flows[flowID].step2Visible = !!flow.step2ID;
@@ -328,7 +321,7 @@ export function installServicesRuntime(deps: ServicesRuntimeDeps): void {
});
} catch (err) {
updateServiceState(function(serviceState) {
- setFlowStatus(serviceState, flowID, err.message, true);
+ setFlowStatus(serviceState, flowID, err instanceof Error ? err.message : flow.requestErrorMessage, true);
});
} finally {
updateServiceState(function(serviceState) {
@@ -344,15 +337,13 @@ export function installServicesRuntime(deps: ServicesRuntimeDeps): void {
var email = getServiceState().flows[flowID].pendingEmail;
if (!email) return;
try {
- var res = await serviceFetch(flow.requestPath, { email: email });
- var data = await res.json();
- if (!res.ok) throw new Error(data.error || flow.requestErrorMessage);
+ await api.postCommercialJSON(flow.requestPath, { email: email });
updateServiceState(function(serviceState) {
setFlowStatus(serviceState, flowID, flow.resendSuccessMessage, false);
});
} catch (err) {
updateServiceState(function(serviceState) {
- setFlowStatus(serviceState, flowID, err.message, true);
+ setFlowStatus(serviceState, flowID, err instanceof Error ? err.message : flow.requestErrorMessage, true);
});
}
}
@@ -370,13 +361,11 @@ export function installServicesRuntime(deps: ServicesRuntimeDeps): void {
serviceState.flows[flowID].confirming = true;
});
try {
- var res = await serviceFetch(flow.confirmPath, { email: email, code: code });
- var data = await res.json();
- if (!res.ok) throw new Error(data.error || flow.confirmErrorMessage);
+ var data = await api.postCommercialJSON(flow.confirmPath, { email: email, code: code });
flow.onConfirmSuccess(data, email);
} catch (err) {
updateServiceState(function(serviceState) {
- setFlowStatus(serviceState, flowID, err.message, true);
+ setFlowStatus(serviceState, flowID, err instanceof Error ? err.message : flow.confirmErrorMessage, true);
});
} finally {
updateServiceState(function(serviceState) {
@@ -411,16 +400,14 @@ export function installServicesRuntime(deps: ServicesRuntimeDeps): void {
serviceState.refund.status = emptyStatus();
});
try {
- var res = await serviceFetch('/v1/self-refund', { email: email, token: token });
- var data = await res.json();
- if (!res.ok) throw new Error(data.error || 'Refund failed');
+ await api.postCommercialJSON('/v1/self-refund', { email: email, token: token });
updateServiceState(function(serviceState) {
serviceState.refund.tokenValue = '';
setRefundStatus(serviceState, 'Success! Your refund has been processed. Stripe will follow up by email.', false);
});
} catch (err) {
updateServiceState(function(serviceState) {
- setRefundStatus(serviceState, err.message, true);
+ setRefundStatus(serviceState, err instanceof Error ? err.message : 'Refund failed', true);
});
} finally {
updateServiceState(function(serviceState) {