chore: consolidate platform split checks
This commit is contained in:
@@ -150,11 +150,20 @@ export type PrivacyRetentionPolicyScope = "system" | "tenant" | "user" | "group"
|
||||
export type PolicySourceStep = {
|
||||
scope_type: string;
|
||||
scope_id?: string | null;
|
||||
path: string;
|
||||
label: string;
|
||||
applied_fields?: string[];
|
||||
policy?: PrivacyRetentionPolicyPatch | PrivacyRetentionPolicy | null;
|
||||
};
|
||||
|
||||
export type PolicyDecision = {
|
||||
allowed: boolean;
|
||||
reason?: string | null;
|
||||
source_path: PolicySourceStep[];
|
||||
requirements: string[];
|
||||
details?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type PrivacyRetentionPolicyScopeResponse = {
|
||||
scope_type: PrivacyRetentionPolicyScope;
|
||||
scope_id?: string | null;
|
||||
@@ -165,20 +174,43 @@ export type PrivacyRetentionPolicyScopeResponse = {
|
||||
parent_policy_sources?: PolicySourceStep[];
|
||||
};
|
||||
|
||||
export type PrivacyRetentionPolicyExplainResponse = {
|
||||
scope_type: PrivacyRetentionPolicyScope;
|
||||
scope_id?: string | null;
|
||||
decision: PolicyDecision;
|
||||
effective_policy: PrivacyRetentionPolicy;
|
||||
parent_policy?: PrivacyRetentionPolicy | null;
|
||||
effective_policy_sources?: PolicySourceStep[];
|
||||
parent_policy_sources?: PolicySourceStep[];
|
||||
blocked_fields: PrivacyRetentionPolicyFieldKey[];
|
||||
};
|
||||
|
||||
export type SystemSettingsItem = {
|
||||
default_locale: string;
|
||||
allow_tenant_custom_groups: boolean;
|
||||
allow_tenant_custom_roles: boolean;
|
||||
allow_tenant_api_keys: boolean;
|
||||
privacy_retention_policy: PrivacyRetentionPolicy;
|
||||
maintenance_mode?: { enabled: boolean; message?: string | null };
|
||||
available_languages?: LanguagePackage[];
|
||||
enabled_language_codes?: string[];
|
||||
settings: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type LanguagePackage = {
|
||||
code: string;
|
||||
label: string;
|
||||
native_label?: string | null;
|
||||
};
|
||||
|
||||
export type TenantSettingsItem = {
|
||||
id: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
default_locale: string;
|
||||
available_languages: LanguagePackage[];
|
||||
system_enabled_language_codes: string[];
|
||||
enabled_language_codes: string[];
|
||||
settings: Record<string, unknown>;
|
||||
};
|
||||
|
||||
@@ -192,6 +224,116 @@ export type RetentionRunResponse = {
|
||||
};
|
||||
};
|
||||
|
||||
export type ConfigurationSafetyField = {
|
||||
key: string;
|
||||
label: string;
|
||||
owner_module: string;
|
||||
scope: "system" | "tenant" | "user" | "group" | "campaign";
|
||||
storage: string;
|
||||
ui_managed: boolean;
|
||||
risk: "low" | "medium" | "high" | "destructive";
|
||||
secret_handling: "none" | "reference_only" | "env_only";
|
||||
required_scopes: string[];
|
||||
dry_run_required: boolean;
|
||||
validation_required: boolean;
|
||||
policy_explanation_required: boolean;
|
||||
audit_event?: string | null;
|
||||
maintenance_required: boolean;
|
||||
two_person_approval_required: boolean;
|
||||
rollback_history_required: boolean;
|
||||
notes?: string | null;
|
||||
};
|
||||
|
||||
export type ConfigurationChangeSafetyPlan = {
|
||||
key: string;
|
||||
allowed: boolean;
|
||||
field?: ConfigurationSafetyField | null;
|
||||
risk?: ConfigurationSafetyField["risk"] | null;
|
||||
missing_scopes: string[];
|
||||
dry_run_required: boolean;
|
||||
dry_run_satisfied: boolean;
|
||||
approval_required: boolean;
|
||||
approval_satisfied: boolean;
|
||||
maintenance_required: boolean;
|
||||
maintenance_satisfied: boolean;
|
||||
rollback_history_required: boolean;
|
||||
secret_handling: ConfigurationSafetyField["secret_handling"];
|
||||
audit_event?: string | null;
|
||||
policy_explanation?: string | null;
|
||||
blockers: string[];
|
||||
warnings: string[];
|
||||
};
|
||||
|
||||
export type ConfigurationChangeRequest = {
|
||||
id: string;
|
||||
key: string;
|
||||
label?: string;
|
||||
target?: Record<string, unknown>;
|
||||
dry_run: boolean;
|
||||
requested_by: string;
|
||||
requested_at: string;
|
||||
updated_at: string;
|
||||
status: "pending_approval" | "approved" | "applied" | "rejected" | string;
|
||||
approvals: Array<Record<string, unknown>>;
|
||||
plan: ConfigurationChangeSafetyPlan;
|
||||
value_preview?: unknown;
|
||||
};
|
||||
|
||||
export type ConfigurationChangeRecord = {
|
||||
id: string;
|
||||
version: number;
|
||||
key: string;
|
||||
target?: Record<string, unknown>;
|
||||
actor_user_id: string;
|
||||
approval_request_id?: string | null;
|
||||
approval_user_ids: string[];
|
||||
before?: unknown;
|
||||
after?: unknown;
|
||||
rollback_value?: unknown;
|
||||
status: string;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type ConfigurationPackageDiagnostic = {
|
||||
severity: "blocker" | "warning" | "info";
|
||||
code: string;
|
||||
message: string;
|
||||
module_id?: string | null;
|
||||
object_ref?: string | null;
|
||||
resolution?: string | null;
|
||||
};
|
||||
|
||||
export type ConfigurationPackageRequiredData = {
|
||||
key: string;
|
||||
label: string;
|
||||
data_type: string;
|
||||
required: boolean;
|
||||
secret: boolean;
|
||||
description?: string | null;
|
||||
};
|
||||
|
||||
export type ConfigurationPackagePlanItem = {
|
||||
action: "create" | "update" | "bind" | "skip" | "blocked" | "noop";
|
||||
module_id: string;
|
||||
fragment_type: string;
|
||||
fragment_id?: string | null;
|
||||
summary?: string | null;
|
||||
};
|
||||
|
||||
export type ConfigurationPackageFragment = {
|
||||
module_id: string;
|
||||
fragment_type: string;
|
||||
fragment_id?: string | null;
|
||||
payload: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type ConfigurationPackageRunPayload = {
|
||||
package: Record<string, unknown>;
|
||||
tenant_id?: string | null;
|
||||
supplied_data?: Record<string, unknown>;
|
||||
change_request_id?: string | null;
|
||||
};
|
||||
|
||||
export type GovernanceAssignment = {
|
||||
tenant_id: string;
|
||||
mode: "available" | "required";
|
||||
@@ -289,7 +431,7 @@ export function fetchTenantSettings(settings: ApiSettings): Promise<TenantSettin
|
||||
return apiFetch(settings, "/api/v1/admin/tenant/settings");
|
||||
}
|
||||
|
||||
export function updateTenantSettings(settings: ApiSettings, payload: { default_locale: string }): Promise<TenantSettingsItem> {
|
||||
export function updateTenantSettings(settings: ApiSettings, payload: { default_locale: string; enabled_language_codes?: string[] | null }): Promise<TenantSettingsItem> {
|
||||
return apiFetch(settings, "/api/v1/admin/tenant/settings", { method: "PATCH", body: JSON.stringify(payload) });
|
||||
}
|
||||
|
||||
@@ -502,6 +644,10 @@ export type SystemSettingsUpdatePayload = {
|
||||
allow_tenant_custom_roles: boolean;
|
||||
allow_tenant_api_keys: boolean;
|
||||
privacy_retention_policy?: PrivacyRetentionPolicy | null;
|
||||
maintenance_mode?: { enabled: boolean; message?: string | null } | null;
|
||||
available_languages?: LanguagePackage[] | null;
|
||||
enabled_language_codes?: string[] | null;
|
||||
change_request_id?: string | null;
|
||||
};
|
||||
|
||||
export function updateSystemSettings(settings: ApiSettings, payload: SystemSettingsUpdatePayload): Promise<SystemSettingsItem> {
|
||||
@@ -515,31 +661,127 @@ export function getPrivacyRetentionPolicy(settings: ApiSettings, scope: PrivacyR
|
||||
return apiFetch(settings, `/api/v1/admin/privacy-retention/policies/${encodeURIComponent(scope)}${suffix}`);
|
||||
}
|
||||
|
||||
export function updatePrivacyRetentionPolicy(settings: ApiSettings, scope: PrivacyRetentionPolicyScope, policy: PrivacyRetentionPolicyPatch, scopeId?: string | null): Promise<PrivacyRetentionPolicyScopeResponse> {
|
||||
export function explainPrivacyRetentionPolicy(settings: ApiSettings, scope: PrivacyRetentionPolicyScope, scopeId?: string | null): Promise<PrivacyRetentionPolicyExplainResponse> {
|
||||
const params = new URLSearchParams();
|
||||
if (scopeId) params.set("scope_id", scopeId);
|
||||
const suffix = params.toString() ? `?${params.toString()}` : "";
|
||||
return apiFetch(settings, `/api/v1/admin/privacy-retention/policies/${encodeURIComponent(scope)}${suffix}`, { method: "PUT", body: JSON.stringify({ policy }) });
|
||||
return apiFetch(settings, `/api/v1/admin/privacy-retention/policies/${encodeURIComponent(scope)}/explain${suffix}`);
|
||||
}
|
||||
|
||||
export function updatePrivacyRetentionPolicy(settings: ApiSettings, scope: PrivacyRetentionPolicyScope, policy: PrivacyRetentionPolicyPatch, scopeId?: string | null, changeRequestId?: string | null): Promise<PrivacyRetentionPolicyScopeResponse> {
|
||||
const params = new URLSearchParams();
|
||||
if (scopeId) params.set("scope_id", scopeId);
|
||||
const suffix = params.toString() ? `?${params.toString()}` : "";
|
||||
return apiFetch(settings, `/api/v1/admin/privacy-retention/policies/${encodeURIComponent(scope)}${suffix}`, { method: "PUT", body: JSON.stringify({ policy, change_request_id: changeRequestId ?? null }) });
|
||||
}
|
||||
|
||||
export function runRetentionPolicy(settings: ApiSettings, dryRun = true): Promise<RetentionRunResponse> {
|
||||
return apiFetch(settings, "/api/v1/admin/system/retention/run", { method: "POST", body: JSON.stringify({ dry_run: dryRun }) });
|
||||
}
|
||||
|
||||
export async function fetchConfigurationSafetyCatalog(settings: ApiSettings, includeEnvOnly = false): Promise<ConfigurationSafetyField[]> {
|
||||
const suffix = includeEnvOnly ? "?include_env_only=true" : "";
|
||||
const response = await apiFetch<{ fields: ConfigurationSafetyField[] }>(settings, `/api/v1/admin/configuration-safety${suffix}`);
|
||||
return response.fields;
|
||||
}
|
||||
|
||||
export async function planConfigurationChange(settings: ApiSettings, payload: {
|
||||
key: string;
|
||||
value?: unknown;
|
||||
dry_run?: boolean;
|
||||
maintenance_mode?: boolean;
|
||||
approval_count?: number;
|
||||
}): Promise<ConfigurationChangeSafetyPlan> {
|
||||
const response = await apiFetch<{ plan: ConfigurationChangeSafetyPlan }>(settings, "/api/v1/admin/configuration-safety/plan", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
return response.plan;
|
||||
}
|
||||
|
||||
export function fetchConfigurationChanges(settings: ApiSettings): Promise<{ requests: ConfigurationChangeRequest[]; history: ConfigurationChangeRecord[] }> {
|
||||
return apiFetch(settings, "/api/v1/admin/configuration-changes");
|
||||
}
|
||||
|
||||
export async function createConfigurationChangeRequest(settings: ApiSettings, payload: {
|
||||
key: string;
|
||||
value?: unknown;
|
||||
dry_run?: boolean;
|
||||
target?: Record<string, unknown>;
|
||||
reason?: string | null;
|
||||
}): Promise<ConfigurationChangeRequest> {
|
||||
const response = await apiFetch<{ request: ConfigurationChangeRequest }>(settings, "/api/v1/admin/configuration-change-requests", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
return response.request;
|
||||
}
|
||||
|
||||
export async function approveConfigurationChangeRequest(settings: ApiSettings, requestId: string, reason?: string | null): Promise<ConfigurationChangeRequest> {
|
||||
const response = await apiFetch<{ request: ConfigurationChangeRequest }>(settings, `/api/v1/admin/configuration-change-requests/${encodeURIComponent(requestId)}/approve`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ reason: reason ?? null })
|
||||
});
|
||||
return response.request;
|
||||
}
|
||||
|
||||
export function fetchConfigurationPackageCatalogValidation(settings: ApiSettings): Promise<{ validation: Record<string, unknown> }> {
|
||||
return apiFetch(settings, "/api/v1/admin/configuration-packages/catalog");
|
||||
}
|
||||
|
||||
export function dryRunConfigurationPackage(settings: ApiSettings, payload: ConfigurationPackageRunPayload): Promise<{
|
||||
diagnostics: ConfigurationPackageDiagnostic[];
|
||||
required_data: ConfigurationPackageRequiredData[];
|
||||
plan: ConfigurationPackagePlanItem[];
|
||||
}> {
|
||||
return apiFetch(settings, "/api/v1/admin/configuration-packages/dry-run", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
|
||||
export function applyConfigurationPackage(settings: ApiSettings, payload: ConfigurationPackageRunPayload): Promise<{
|
||||
diagnostics: ConfigurationPackageDiagnostic[];
|
||||
created_refs: Record<string, string>;
|
||||
updated_refs: Record<string, string>;
|
||||
}> {
|
||||
return apiFetch(settings, "/api/v1/admin/configuration-packages/apply", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
|
||||
export function exportConfigurationPackage(settings: ApiSettings, payload: {
|
||||
tenant_id?: string | null;
|
||||
scopes?: string[];
|
||||
module_ids?: string[];
|
||||
object_refs?: string[];
|
||||
}): Promise<{
|
||||
fragments: ConfigurationPackageFragment[];
|
||||
data_requirements: ConfigurationPackageRequiredData[];
|
||||
diagnostics: ConfigurationPackageDiagnostic[];
|
||||
}> {
|
||||
return apiFetch(settings, "/api/v1/admin/configuration-packages/export", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchGovernanceTemplates(settings: ApiSettings, kind?: "group" | "role"): Promise<GovernanceTemplateItem[]> {
|
||||
const suffix = kind ? `?kind=${encodeURIComponent(kind)}` : "";
|
||||
const response = await apiFetch<{ templates: GovernanceTemplateItem[] }>(settings, `/api/v1/admin/system/governance-templates${suffix}`);
|
||||
return response.templates;
|
||||
}
|
||||
|
||||
export function createGovernanceTemplate(settings: ApiSettings, payload: Omit<GovernanceTemplateItem, "id" | "created_at" | "updated_at" | "effective_permission_count">): Promise<GovernanceTemplateItem> {
|
||||
export function createGovernanceTemplate(settings: ApiSettings, payload: Omit<GovernanceTemplateItem, "id" | "created_at" | "updated_at" | "effective_permission_count"> & { change_request_id?: string | null }): Promise<GovernanceTemplateItem> {
|
||||
return apiFetch(settings, "/api/v1/admin/system/governance-templates", { method: "POST", body: JSON.stringify(payload) });
|
||||
}
|
||||
|
||||
export function updateGovernanceTemplate(settings: ApiSettings, templateId: string, payload: Omit<GovernanceTemplateItem, "id" | "kind" | "slug" | "created_at" | "updated_at" | "effective_permission_count">): Promise<GovernanceTemplateItem> {
|
||||
export function updateGovernanceTemplate(settings: ApiSettings, templateId: string, payload: Omit<GovernanceTemplateItem, "id" | "kind" | "slug" | "created_at" | "updated_at" | "effective_permission_count"> & { change_request_id?: string | null }): Promise<GovernanceTemplateItem> {
|
||||
return apiFetch(settings, `/api/v1/admin/system/governance-templates/${templateId}`, { method: "PATCH", body: JSON.stringify(payload) });
|
||||
}
|
||||
|
||||
export function deleteGovernanceTemplate(settings: ApiSettings, templateId: string): Promise<void> {
|
||||
return apiFetch(settings, `/api/v1/admin/system/governance-templates/${templateId}`, { method: "DELETE" });
|
||||
export function deleteGovernanceTemplate(settings: ApiSettings, templateId: string, changeRequestId?: string | null): Promise<void> {
|
||||
const suffix = changeRequestId ? `?change_request_id=${encodeURIComponent(changeRequestId)}` : "";
|
||||
return apiFetch(settings, `/api/v1/admin/system/governance-templates/${templateId}${suffix}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApiSettings, AuthInfo, LoginResponse } from "../types";
|
||||
import type { ApiSettings, AuthInfo, LoginResponse, UserUiPreferences } from "../types";
|
||||
import { apiFetch } from "./client";
|
||||
|
||||
export async function login(
|
||||
@@ -28,7 +28,13 @@ export async function logout(settings: ApiSettings): Promise<void> {
|
||||
|
||||
export async function updateProfile(
|
||||
settings: ApiSettings,
|
||||
payload: { display_name?: string | null; tenant_display_name?: string | null }
|
||||
payload: {
|
||||
display_name?: string | null;
|
||||
tenant_display_name?: string | null;
|
||||
preferred_language?: string | null;
|
||||
enabled_language_codes?: string[] | null;
|
||||
ui_preferences?: Partial<UserUiPreferences> | null;
|
||||
}
|
||||
): Promise<AuthInfo> {
|
||||
return apiFetch<AuthInfo>(settings, "/api/v1/auth/profile", {
|
||||
method: "PATCH",
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { ApiSettings } from "../types";
|
||||
|
||||
const STORAGE_KEY = "multimailer.apiSettings";
|
||||
const LEGACY_STORAGE_KEYS = ["i18n:govoplan-core.multimailer_apisettings.1d1601d4"];
|
||||
const SESSION_STORAGE_KEY = "multimailer.session";
|
||||
const CSRF_COOKIE_NAME = import.meta.env.VITE_CSRF_COOKIE_NAME ?? "msm_csrf";
|
||||
const RECENT_SAFE_REQUEST_TTL_MS = 750;
|
||||
const MAX_RECENT_SAFE_REQUESTS = 100;
|
||||
const MAX_CONDITIONAL_SAFE_REQUESTS = 200;
|
||||
|
||||
export const AUTH_REQUIRED_EVENT = "govoplan:auth-required";
|
||||
|
||||
@@ -19,8 +21,14 @@ type RecentSafeRequest = {
|
||||
expiresAt: number;
|
||||
};
|
||||
|
||||
type ConditionalSafeRequest = {
|
||||
value: unknown;
|
||||
etag: string;
|
||||
};
|
||||
|
||||
const inFlightSafeRequests = new Map<string, Promise<unknown>>();
|
||||
const recentSafeRequests = new Map<string, RecentSafeRequest>();
|
||||
const conditionalSafeRequests = new Map<string, ConditionalSafeRequest>();
|
||||
let safeRequestGeneration = 0;
|
||||
|
||||
export class ApiError extends Error {
|
||||
@@ -47,8 +55,20 @@ export function isApiError(error: unknown, ...statuses: number[]): error is ApiE
|
||||
* API prefix so old localStorage settings cannot produce /api/v1/api/v1 URLs.
|
||||
*/
|
||||
export function normalizeApiBaseUrl(value: string): string {
|
||||
const withoutTrailingSlash = value.trim().replace(/\/+$/, "");
|
||||
return withoutTrailingSlash.replace(/\/api(?:\/v1)?$/i, "");
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed || trimmed === "." || trimmed === "./") return "";
|
||||
|
||||
const withoutTrailingSlash = trimmed.replace(/\/+$/, "");
|
||||
const withoutApiPrefix = withoutTrailingSlash.replace(/\/api(?:\/v1)?$/i, "");
|
||||
|
||||
// API base is an origin, not a frontend route prefix. Path-only values such
|
||||
// as /a or . are stale/invalid local settings and would bypass Vite's /api
|
||||
// proxy by producing /a/api/v1/... requests.
|
||||
if (withoutApiPrefix.startsWith("/") && !withoutApiPrefix.startsWith("//")) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return withoutApiPrefix;
|
||||
}
|
||||
|
||||
export function apiUrl(settings: ApiSettings, path: string): string {
|
||||
@@ -58,7 +78,8 @@ export function apiUrl(settings: ApiSettings, path: string): string {
|
||||
}
|
||||
|
||||
export function loadApiSettings(): ApiSettings {
|
||||
const storedBaseUrl = localStorage.getItem(`${STORAGE_KEY}.baseUrl`);
|
||||
const storedBaseUrl = loadStoredSetting("baseUrl");
|
||||
const storedApiKey = loadStoredSetting("apiKey");
|
||||
const configuredBaseUrl = storedBaseUrl !== null ? storedBaseUrl : import.meta.env.VITE_API_BASE_URL ?? "";
|
||||
const apiBaseUrl = normalizeApiBaseUrl(configuredBaseUrl);
|
||||
|
||||
@@ -66,6 +87,11 @@ export function loadApiSettings(): ApiSettings {
|
||||
if (storedBaseUrl !== null && storedBaseUrl !== apiBaseUrl) {
|
||||
localStorage.setItem(`${STORAGE_KEY}.baseUrl`, apiBaseUrl);
|
||||
}
|
||||
if (storedApiKey !== null) {
|
||||
localStorage.setItem(`${STORAGE_KEY}.apiKey`, storedApiKey);
|
||||
}
|
||||
clearLegacyStoredSetting("baseUrl");
|
||||
clearLegacyStoredSetting("apiKey");
|
||||
|
||||
localStorage.removeItem(`${STORAGE_KEY}.accessToken`);
|
||||
sessionStorage.removeItem(`${SESSION_STORAGE_KEY}.accessToken`);
|
||||
@@ -73,7 +99,7 @@ export function loadApiSettings(): ApiSettings {
|
||||
return {
|
||||
// Empty base URL means "same origin". In Vite dev, /api is proxied to FastAPI.
|
||||
apiBaseUrl,
|
||||
apiKey: localStorage.getItem(`${STORAGE_KEY}.apiKey`) || "",
|
||||
apiKey: storedApiKey || "",
|
||||
accessToken: ""
|
||||
};
|
||||
}
|
||||
@@ -81,6 +107,8 @@ export function loadApiSettings(): ApiSettings {
|
||||
export function saveApiSettings(settings: ApiSettings): void {
|
||||
localStorage.setItem(`${STORAGE_KEY}.baseUrl`, normalizeApiBaseUrl(settings.apiBaseUrl));
|
||||
localStorage.setItem(`${STORAGE_KEY}.apiKey`, settings.apiKey);
|
||||
clearLegacyStoredSetting("baseUrl");
|
||||
clearLegacyStoredSetting("apiKey");
|
||||
localStorage.removeItem(`${STORAGE_KEY}.accessToken`);
|
||||
sessionStorage.removeItem(`${SESSION_STORAGE_KEY}.accessToken`);
|
||||
}
|
||||
@@ -90,14 +118,29 @@ export function clearAccessToken(): void {
|
||||
localStorage.removeItem(`${STORAGE_KEY}.accessToken`);
|
||||
}
|
||||
|
||||
function loadStoredSetting(name: string): string | null {
|
||||
const keys = [STORAGE_KEY, ...LEGACY_STORAGE_KEYS];
|
||||
for (const key of keys) {
|
||||
const value = localStorage.getItem(`${key}.${name}`);
|
||||
if (value !== null) return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function clearLegacyStoredSetting(name: string): void {
|
||||
for (const key of LEGACY_STORAGE_KEYS) {
|
||||
localStorage.removeItem(`${key}.${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function readCookie(name: string): string {
|
||||
const prefix = `${encodeURIComponent(name)}=`;
|
||||
return document.cookie
|
||||
.split(";")
|
||||
.map((part) => part.trim())
|
||||
.find((part) => part.startsWith(prefix))
|
||||
?.slice(prefix.length) ?? "";
|
||||
return document.cookie.
|
||||
split(";").
|
||||
map((part) => part.trim()).
|
||||
find((part) => part.startsWith(prefix))?.
|
||||
slice(prefix.length) ?? "";
|
||||
}
|
||||
|
||||
export function csrfToken(): string {
|
||||
@@ -111,29 +154,29 @@ function isUnsafeMethod(method?: string): boolean {
|
||||
}
|
||||
|
||||
function canReuseSafeRequest(method: string, init?: RequestInit): boolean {
|
||||
return (method === "GET" || method === "HEAD")
|
||||
&& !init?.body
|
||||
&& !init?.signal
|
||||
&& init?.cache !== "no-store"
|
||||
&& init?.cache !== "reload";
|
||||
return (method === "GET" || method === "HEAD") &&
|
||||
!init?.body &&
|
||||
!init?.signal &&
|
||||
init?.cache !== "no-store" &&
|
||||
init?.cache !== "reload";
|
||||
}
|
||||
|
||||
function requestHeadersKey(headers: Headers): string {
|
||||
return [...headers.entries()]
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, value]) => `${key}:${value}`)
|
||||
.join("\n");
|
||||
return [...headers.entries()].
|
||||
sort(([left], [right]) => left.localeCompare(right)).
|
||||
map(([key, value]) => `${key}:${value}`).
|
||||
join("\n");
|
||||
}
|
||||
|
||||
function safeRequestKey(url: string, method: string, headers: Headers, init?: RequestInit): string {
|
||||
return [
|
||||
method,
|
||||
url,
|
||||
init?.credentials ?? "include",
|
||||
init?.mode ?? "",
|
||||
init?.redirect ?? "",
|
||||
requestHeadersKey(headers),
|
||||
].join("\n\n");
|
||||
method,
|
||||
url,
|
||||
init?.credentials ?? "include",
|
||||
init?.mode ?? "",
|
||||
init?.redirect ?? "",
|
||||
requestHeadersKey(headers)].
|
||||
join("\n\n");
|
||||
}
|
||||
|
||||
function pruneRecentSafeRequests(now = Date.now()): void {
|
||||
@@ -167,6 +210,31 @@ function rememberSafeResponse(key: string, value: unknown): void {
|
||||
pruneRecentSafeRequests(now);
|
||||
}
|
||||
|
||||
function conditionalSafeResponse(key: string): ConditionalSafeRequest | undefined {
|
||||
const cached = conditionalSafeRequests.get(key);
|
||||
if (!cached) return undefined;
|
||||
conditionalSafeRequests.delete(key);
|
||||
conditionalSafeRequests.set(key, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
function rememberConditionalSafeResponse(key: string, etag: string, value: unknown): void {
|
||||
conditionalSafeRequests.delete(key);
|
||||
conditionalSafeRequests.set(key, { etag, value });
|
||||
while (conditionalSafeRequests.size > MAX_CONDITIONAL_SAFE_REQUESTS) {
|
||||
const oldestKey = conditionalSafeRequests.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
conditionalSafeRequests.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
|
||||
function clearSafeRequestCaches(): void {
|
||||
safeRequestGeneration += 1;
|
||||
inFlightSafeRequests.clear();
|
||||
recentSafeRequests.clear();
|
||||
conditionalSafeRequests.clear();
|
||||
}
|
||||
|
||||
export function authHeaders(settings: ApiSettings): Headers {
|
||||
const headers = new Headers();
|
||||
if (settings.accessToken) {
|
||||
@@ -187,13 +255,13 @@ function notifyAuthRequired(path: string): void {
|
||||
const detail: AuthRequiredEventDetail = {
|
||||
path,
|
||||
status: 401,
|
||||
message: "Your session has expired. Sign in again to continue."
|
||||
message: "i18n:govoplan-core.your_session_has_expired_sign_in_again_to_contin.4cc6a1b3"
|
||||
};
|
||||
window.dispatchEvent(new CustomEvent<AuthRequiredEventDetail>(AUTH_REQUIRED_EVENT, { detail }));
|
||||
}
|
||||
|
||||
function authExpiredError(statusText: string): ApiError {
|
||||
return new ApiError(401, statusText || "Unauthorized", "Your session has expired. Sign in again to continue.");
|
||||
return new ApiError(401, statusText || "i18n:govoplan-core.unauthorized.740b8315", "i18n:govoplan-core.your_session_has_expired_sign_in_again_to_contin.4cc6a1b3");
|
||||
}
|
||||
|
||||
export async function apiFetch<T>(settings: ApiSettings, path: string, init?: RequestInit): Promise<T> {
|
||||
@@ -214,17 +282,27 @@ export async function apiFetch<T>(settings: ApiSettings, path: string, init?: Re
|
||||
}
|
||||
|
||||
if (isUnsafeMethod(method)) {
|
||||
safeRequestGeneration += 1;
|
||||
inFlightSafeRequests.clear();
|
||||
recentSafeRequests.clear();
|
||||
clearSafeRequestCaches();
|
||||
}
|
||||
|
||||
const url = apiUrl(settings, path);
|
||||
const fetchInit = { ...init, headers, credentials: init?.credentials ?? "include" };
|
||||
const reusableSafeRequest = canReuseSafeRequest(method, init);
|
||||
const cacheKey = reusableSafeRequest ? safeRequestKey(url, method, headers, init) : null;
|
||||
|
||||
async function runFetch(): Promise<T> {
|
||||
const fetchHeaders = new Headers(headers);
|
||||
const conditional = cacheKey ? conditionalSafeResponse(cacheKey) : undefined;
|
||||
if (conditional && !fetchHeaders.has("If-None-Match")) {
|
||||
fetchHeaders.set("If-None-Match", conditional.etag);
|
||||
}
|
||||
const fetchInit = { ...init, headers: fetchHeaders, credentials: init?.credentials ?? "include" };
|
||||
const response = await fetch(url, fetchInit);
|
||||
|
||||
if (response.status === 304 && cacheKey && conditional) {
|
||||
rememberSafeResponse(cacheKey, conditional.value);
|
||||
return conditional.value as T;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
if (response.status === 401 && shouldNotifyAuthRequired(path)) {
|
||||
@@ -235,22 +313,31 @@ export async function apiFetch<T>(settings: ApiSettings, path: string, init?: Re
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
if (cacheKey) conditionalSafeRequests.delete(cacheKey);
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("content-type") || "";
|
||||
let value: T;
|
||||
if (!contentType.includes("application/json")) {
|
||||
return (await response.text()) as T;
|
||||
value = (await response.text()) as T;
|
||||
} else {
|
||||
value = (await response.json()) as T;
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
const etag = response.headers.get("etag");
|
||||
if (cacheKey && etag) {
|
||||
rememberConditionalSafeResponse(cacheKey, etag, value);
|
||||
} else if (cacheKey) {
|
||||
conditionalSafeRequests.delete(cacheKey);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
if (!canReuseSafeRequest(method, init)) {
|
||||
if (!reusableSafeRequest || !cacheKey) {
|
||||
return runFetch();
|
||||
}
|
||||
|
||||
const cacheKey = safeRequestKey(url, method, headers, init);
|
||||
const requestGeneration = safeRequestGeneration;
|
||||
const recent = recentSafeResponse(cacheKey);
|
||||
if (recent !== undefined) {
|
||||
@@ -262,18 +349,18 @@ export async function apiFetch<T>(settings: ApiSettings, path: string, init?: Re
|
||||
return existing as Promise<T>;
|
||||
}
|
||||
|
||||
const request = runFetch()
|
||||
.then((value) => {
|
||||
if (requestGeneration === safeRequestGeneration) {
|
||||
rememberSafeResponse(cacheKey, value);
|
||||
}
|
||||
return value;
|
||||
})
|
||||
.finally(() => {
|
||||
if (inFlightSafeRequests.get(cacheKey) === request) {
|
||||
inFlightSafeRequests.delete(cacheKey);
|
||||
}
|
||||
});
|
||||
const request = runFetch().
|
||||
then((value) => {
|
||||
if (requestGeneration === safeRequestGeneration) {
|
||||
rememberSafeResponse(cacheKey, value);
|
||||
}
|
||||
return value;
|
||||
}).
|
||||
finally(() => {
|
||||
if (inFlightSafeRequests.get(cacheKey) === request) {
|
||||
inFlightSafeRequests.delete(cacheKey);
|
||||
}
|
||||
});
|
||||
inFlightSafeRequests.set(cacheKey, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,15 @@ export type PlatformStatusResponse = {
|
||||
enabled: boolean;
|
||||
message?: string | null;
|
||||
};
|
||||
i18n?: {
|
||||
available_languages: Array<{
|
||||
code: string;
|
||||
label: string;
|
||||
native_label?: string | null;
|
||||
}>;
|
||||
enabled_languages: string[];
|
||||
default_language: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type PlatformPermission = {
|
||||
|
||||
Reference in New Issue
Block a user