Frontend applications, plugin UI and browser contracts

Handbook · Coverage · Code reference

Pulse has two independently built Vue applications. frontend/ is the public/player application. backend/resources/admin/ is the separate control panel served under /admin/. They share a backend and runtime bundle format, but have different routers, HTTP clients, dependencies and startup code. Changing one does not automatically update the other.

Use runtime for backend request flow, plugins for manifests, packages for compiled assets, and communication for server events.

Select the right application

Concern Public/player app Separate admin app
Root frontend/ backend/resources/admin/
Entry src/main.ts src/main.js
Router src/router/index.ts src/router/index.js
API client src/services/api.ts src/services/api.js
Runtime loader src/services/plugin-loader.ts src/services/plugin-runtime.js
Base route / /admin/
Build output frontend/dist backend/public/admin
Default Vite port 5180 5174
Default proxy backend 127.0.0.1:8010, overridden by BACKEND_URL localhost:8001, overridden by VITE_API_URL

These are configuration defaults, not proof of a running service. Check your actual Docker mapping and env values. The admin default proxy differs from the current player backend default; set it deliberately in local admin development. See configuration.

The player app contains some admin-oriented views too. Their presence does not mean they are the deployed separate admin application's implementation. Confirm the URL, entry HTML and bundle before choosing a file to edit.

Player startup

main.ts imports global styles, creates Vue and Pinia, installs i18n and error logging, and registers global auth/error handlers. Bootstrap starts two tasks:

  1. Initialize authentication and, if authenticated, fetch the user profile.
  2. Initialize plugin routes and runtime components.

It waits for those tasks using Promise.allSettled, bounded by an eight-second barrier, then installs the router, waits for readiness and mounts #app. The timeout permits mounting while a slow initialization task may still run; it does not cancel pending requests. Loading and unauthenticated states must therefore be rendered safely without assuming the profile is ready.

The router contains core shell routes, product routes from src/router/product-routes.ts, and plugin routes initialized at startup. Client guards inspect authentication, stored tokens and route role metadata. They improve navigation behavior; backend middleware is the authorization boundary. A manually requested API remains subject to server checks.

Player HTTP client

Import api from @/services/api. Its Axios base URL is import.meta.env.VITE_API_URL ?? ''. Core endpoints should include their path:

import api from '@/services/api'

const response = await api.get('/api/v1/user', { cacheTTL: 0 })
const user = response.data

Expected result after authentication: the controller's user response in response.data. This is an Axios response wrapper, not an automatically unwrapped user object. Inspect each endpoint's JSON envelope.

The client uses JSON headers and withCredentials: true, and adds bearer auth from auth_token or legacy token in localStorage. A 401 removes user, auth_token, token, admin_token, and admin_user, then redirects to /login unless already on a login path. Auth stores and other interceptors also participate; avoid adding a second independent credential store in a plugin.

API method Return / options
get<T>(url, config?): Promise<AxiosResponse<T>> GET with optional cache/deduplication/cancellation
post<T>(url, data?, config?): Promise<AxiosResponse<T>> POST; identical pending bodies can be deduplicated
put<T>(url, data?, config?): Promise<AxiosResponse<T>> PUT, invalidates exact URL cache
patch<T>(url, data?, config?): Promise<AxiosResponse<T>> PATCH, invalidates exact URL cache
delete<T>(url, config?): Promise<AxiosResponse<T>> DELETE, invalidates exact URL cache
cancelAll(tag?: string): void Abort all tracked requests or keys starting with tag
cancel(key: string): void Abort request by internal generated key
clearCache(pattern?: string): void Clear all cached responses or keys containing pattern
getCacheStats(): { size: number; keys: string[] } In-memory cache inspection
getPendingCount(): number Number of tracked deduplicated requests
instance getter Underlying Axios instance for advanced configuration

PUT omits undefined Axios options so the default validateStatus predicate still rejects HTTP errors, including a world-editor revision409. An explicitly supplied custom predicate remains the caller's responsibility. This lets conflict handling distinguish a rejected save from a successful response.

Request config includes Axios options plus skipDeduplication, cacheTTL, forceRefresh, signal, and timeout. GET does not cache by default (cacheTTL is 0): every call reaches the server, except that identical GETs already in flight share one request unless skipDeduplication is set. To cache static, viewer-independent data in memory, pass a positive cacheTTL such as STATIC_CACHE_TTL (five minutes) from @/services/cache-ttl; forceRefresh bypasses an existing entry. A call without cacheTTL never reads the cache. ETags may be sent for cached responses. The core shell opts in only for /api/v1/settings/public.

import api from '@/services/api'
import { STATIC_CACHE_TTL } from '@/services/cache-ttl'

const settings = await api.get('/api/v1/settings/public', { cacheTTL: STATIC_CACHE_TTL })

Current cache/deduplication keys use method, URL and sometimes body, but do not fully encode query params or authenticated identity. For changing query-based views, encode distinct parameters in the URL or use appropriate skip/refresh options. Do not assume mutations invalidate every related collection URL; refresh affected lists explicitly. Repeated identical POSTs can share a pending promise; server-side idempotency and transaction safety remain necessary.

Global authentication interception

The player entry calls setupGlobalAuthInterceptors(): void once. getAuthToken(): string | null reads auth_token, then legacy token; it returns null outside a browser or when storage cannot be read. Setup copies an existing token into either missing legacy key and changes three global clients:

Client Implemented effect
Global Axios singleton Adds bearer auth when Authorization is absent or exactly Bearer, Bearer null or Bearer undefined after trimming; adds Accept when absent and sets withCredentials true. It does not restrict URLs to API paths.
window.fetch For URL strings starting /api or containing /api/, merges supplied/Request headers, fills missing/placeholder bearer auth and Accept, and defaults credentials to include. An explicit credentials option is retained.
XMLHttpRequest prototypes Tracks URL/header state, fills absent/placeholder auth for the same API string match, adds Accept on send and sets withCredentials true.

This matching is not an origin check: https://another-host.example/api/items also matches fetch/XHR. Global Axios interception can attach auth to non-API URLs. Use the intended same-origin API paths and inspect final headers when integrating another origin. Existing non-placeholder Authorization is retained; the underlying player API client has its own interceptor and token policy. Interceptors on the global Axios object do not install its hooks on every axios.create() instance; XHR patching is a separate mechanism.

Setup has no install-once guard, returned disposer or prototype restoration. Calling it repeatedly stacks wrappers/interceptors. It belongs in application boot, not each component mount. A same-origin request such as fetch('/api/v1/user') will receive the stored bearer header and include credentials when available; that is client behavior, not proof of server acceptance. Implementation.

Admin startup and HTTP differences

The admin entry installs Pinia and error logging, calls initializeAdminPluginRoutes(router), installs the router, waits for readiness, and mounts #app. It does not use the player app's i18n installation or eight- second overall bootstrap barrier.

Its normal API client's baseURL is /api/v1. Thus a normal admin service call uses /admin/... relative to that base, not /api/v1/admin/... repeated twice. It reads admin_token, falling back to auth_token or token.

The admin response interceptor handles 401 and 423. Demo mode can request a new guest session and retry after a 401. Outside that recovery path it clears all shared auth keys and redirects to /admin/login. These behaviors are specific to the admin client; do not copy demo renewal logic into arbitrary plugins.

The admin plugin runtime uses its own Axios instance with base / and the admin session cookie (with the XSRF token on same-origin requests). A plugin calls canonical /api/plugins/... URLs through that runtime HTTP object. This prevents the normal admin /api/v1 base from being incorrectly added to a plugin endpoint. Its http object (backend/resources/admin/src/services/plugin-http.js) is a port of the player's plugin-http.ts: the same requestConfig keys, host-owned headers, relative-URL refusal and params encoding. The admin has no GET cache, so cacheTTL, forceRefresh and skipDeduplication are dropped there.

Registry payload and store

GET /api/plugins/enabled returns:

success: boolean
plugins: frontend-safe plugin records
navigation: flattened menu definitions
routes: flattened frontend route definitions
slots: map from slot name to component records

The backend projection service exposes getEnabledPluginsForFrontend(): Collection, getPluginManifest(string $slug): ?array, getPluginRoutes(): array, getNavigationItems(): array, getApiRoutes(): array, getPluginsBySection(): array, and clearCache(): void. The collection cache key is plugins.frontend_manifest, with a 60-second population TTL. Clearing this cache does not clear a browser's API cache or loaded JavaScript registry.

Plugin records include slug/name/version, UI metadata, frontend routes/slots, permissions, route flags and optional runtime descriptor. Internal PHP paths and namespace details are not needed for rendering. PluginManifestService projects the database registry; changing a filesystem manifest alone need not refresh installed frontend metadata.

usePluginsStore() exposes plugin/route/navigation state, loaded, loading, enabled plugins, section grouping and slot component projections. Important methods are:

Method Use
fetchPlugins() Fetch initial registry, with loaded/loading protection
refreshPlugins() Refresh server registry
isEnabled(slug), getPlugin(slug) Local availability / metadata
getPluginByRoute(routeName) Find plugin owning a route name
hasSlot(slug, slotName) Check plugin declaration
getComponentsForSlot(slotName), hasSlotComponents(slotName) Renderable slot metadata
getPluginsWithSlot(slotName) Plugin subset
resolveNavigationTarget(item) Resolve declared navigation to path
disablePlugin(slug), enablePlugin(slug) Local state mutation; does not perform administrative server lifecycle

A local store mutation cannot enable server-side routes. For administrative state changes use the backend manager/API, then refresh the registry.

Runtime host and SDK

Both apps provide window.LFStudioPluginRuntime. Browser bundles use host Vue and router exports instead of shipping a second conflicting Vue instance. The shared format is lfstudio-runtime-v1.

Runtime member Contract
vue Host Vue module exports
router Host Vue Router module exports, not an arbitrary current-router instance
http.get<T>(url, options?) Promise of response with data and status; player host accepts { cacheTTL?: number, forceRefresh?: boolean, skipDeduplication?: boolean } plus the request config below
http.post/put/patch<T>(url, body?, config?) Authenticated mutation methods
http.delete<T>(url, config?) Authenticated DELETE
http.requestConfig? Request config keys the host passes through (headers, params, signal, timeout); absent on hosts without passthrough
register({ format, slug, version, components }) Register exact bundle identity and compiled components
theme Player host theme manager; separate admin host does not currently supply it
ui?.ActivityBrowser Additive player presentation component for plugin-owned activities; feature-detect on older/admin hosts
ui?.ResourceHud Additive player resource renderer; plugins supply authoritative meter/balance props and handle retry

The player host's http.get does not cache by default, so dynamic player reads such as resource balances and action history are fresh without options; identical reads already in flight still share one request. Hosts released before this change cached GETs for five minutes, so a plugin that must also run on them should keep passing { cacheTTL: 0 } for live reads. Opt in with a positive cacheTTL (milliseconds) only for static, viewer-independent data such as rules text or a fixed catalogue; forceRefresh: true bypasses a cached entry. Keep actions locked until the authoritative refresh completes. The shared ActivityBrowser accepts typed items, selection/category, loading/error/busy, result/history and an optional resource balance; it emits select, category, action and retry without fetching data. See frontend/src/components/activity/types.ts and ActivityBrowser.vue for its presentation contract. The canonical Crimes package supplies the first adapter. The shell continues to obtain game-specific resources through plugin slots. The account bar mounts game.header.account, where plugins add buttons such as a mailbox (core names none), and the player menu lists only enabled plugins' entries: core has no /forum, /community or /profile/:id route, and a plugin registers its own pages. The persistent header mounts game.header.stats; Gamekit's canonical header adapter supplies real stats with uncached reads, loading/error states and a 60-second refresh. After a gameplay mutation is confirmed and its resources refreshed, an adapter can dispatch pulse:resources-changed on window to invalidate subscribed resource displays. A settled mutation must still invalidate resources if its originating route has unmounted. These events carry no balances; each owning plugin reads its authoritative API. ResourceHud is presentational and imports no game stores or concrete plugins.

pulse:before-logout {#before-logout-event}

When the player signs out, the auth store's logout() (frontend/src/stores/auth.ts) first calls announceLogout() from frontend/src/services/logout-event.ts. It dispatches a pulse:before-logout CustomEvent on window while the session is still valid, so a listener can still make an authenticated request. event.detail.waitUntil(promise) asks sign-out to wait for that promise. Sign-out waits for all registered promises at most 2 seconds (timeoutMs, default 2000), then continues. A listener that throws, or a promise that rejects, never fails the logout. With no waitUntil call, nothing waits.

window.addEventListener('pulse:before-logout', (event) => {
  // For example, remove this browser's push subscription and tell the server.
  event.detail.waitUntil(unsubscribeThisBrowser())
})

The server side of the same moment is the auth.logout hook.

Player Home groups enabled, authorized registry destinations. Its optional status reports mount on first expansion and keep their state across later collapse/reopen. Raw package descriptions are operator metadata and are not shown as player instructions. The mobile strip exposes all registered destinations with horizontal scrolling and keyboard access; account tools stay in the menu. Saved alternate themes remain supported.

The player host passes an optional request config through on every http verb, restricted to an allow-list: headers (a plain object or a fetch Headers), params, signal and timeout. get also takes cacheTTL, forceRefresh and skipDeduplication. Every other key is dropped, including baseURL, url, method, withCredentials, adapter, transforms and validateStatus. Header values must be strings, and host-owned headers are dropped: Accept, Authorization, Cookie, Host, Origin, Referer, X-CSRF-Token, X-XSRF-Token, X-Requested-With, X-HTTP-Method-Override, X-HTTP-Method and X-Method-Override. URLs must be app-relative (for example /api/plugins/<slug>/...); an absolute or protocol-relative URL rejects with a TypeError and nothing is sent.

params are appended to the URL, so request sharing and the GET cache stay per query, and a write to a path clears cached GETs of that path with any query. A plain object uses Laravel's bracket form: arrays of scalars as ids[]=1&ids[]=2 (a trailing [] on an array's key is dropped first; a scalar keeps its key[] name), objects as filter[rarity]=rare, arrays of objects as rows[0][id]=1, and Dates as ISO strings. null and undefined values are skipped. A URLSearchParams is appended as it is. Any other params value (a Map, a class instance), functions, symbols, bigints, other class instances and nesting deeper than five levels reject with a TypeError. A signal cancels only a request that call started: when an identical GET or POST is already in flight, the call shares it, and aborting the later caller's signal does not cancel the shared request (a signal that is already aborted still rejects the call at once).

This allow-list is an API contract, not a sandbox. A bundle runs in the page with the host's privileges and could call fetch directly. The host's fetch wrapper and its Axios client attach the session cookie and CSRF token only to trusted API URLs (/api on the app's origin or on the configured VITE_API_URL), never to other hosts. The allow-list keeps host.http requests on that path; it does not confine the bundle. Review a bundle's code before installing it.

Routes marked idempotent:required read only the Idempotency-Key header, so send it as a header. Reuse one key for retries of the same action and make a new key for the next action. Two in-flight writes with the same body but different keys are sent as two requests; the same key and body in flight share one. Hosts without passthrough omit http.requestConfig (a frozen array) and ignore the third argument, so feature-detect before relying on it (the admin host passes config through too):

const host = window.LFStudioPluginRuntime
if (!host?.http.requestConfig?.includes('headers')) {
  throw new Error('This host cannot send Idempotency-Key; update Pulse Engine.')
}
const key = crypto.randomUUID() // keep it for retries of this same enhance
const response = await host.http.post<{ level: number }>(
  '/api/plugins/gear/enhance',
  { item_id: itemId },
  { headers: { 'Idempotency-Key': key } },
)

frontend/src/plugin-sdk.ts exports http and theme. Every SDK method resolves the runtime when called and throws if no host exists. With an existing host, theme access is optional: get() falls back to pulse-dark, set(string) calls the available host, and onChange(listener) returns an unsubscribe function or no-op. This fallback differs from the player loader's initial pulse-base theme. Do not claim admin theme integration merely because TypeScript's player host interface declares it.

Example inside a plugin component using the runtime directly:

<script setup lang="ts">
import { onMounted, ref } from 'vue'

const ready = ref(false)
const error = ref('')

onMounted(async () => {
  try {
    const host = window.LFStudioPluginRuntime
    if (!host) throw new Error('Plugin runtime unavailable')
    const response = await host.http.get<{ ready: boolean }>(
      '/api/plugins/journal/status',
    )
    ready.value = response.data.ready
  } catch {
    error.value = 'The journal is unavailable. Please try again.'
  }
})
</script>

<template>
  <p v-if="error" role="alert">{{ error }}</p>
  <p v-else-if="ready">Journal ready</p>
  <p v-else role="status">Loading journal…</p>
</template>

Place the source in the plugin's frontend component source tree, declare its component reference in the manifest, and build/package it. With the Journal status route from plugins, the expected successful UI is “Journal ready”. The example's API typing must match its controller response; it is not a guarantee every endpoint uses that envelope.

Loader APIs and safety rules

The player loader exposes these operations:

API Purpose
loadPluginRuntime(plugin): Promise<void> Load/validate published script and styles, serialized
resolvePluginComponent(slug, reference): Component | null Resolve runtime component or local fallback
getPluginComponentLoader(slug, reference) Async component loader or null
importPluginComponent(slug, reference): Promise<Component | null> Promise wrapper around resolution
createPluginRoutes(slug, definitions): RouteRecordRaw[] Build routes for resolvable components
getActivePlugins(): Promise<string[]> Fetch store and return slugs
loadPluginModule(slug): Promise<PluginModule | null> Load one plugin and cache module
loadAllPlugins(): Promise<PluginModule[]> Initialize available plugins, log per-plugin failures
loadPluginRoutes(): Promise<RouteRecordRaw[]> Load then flatten routes
getPluginRoutes(): RouteRecordRaw[] Flatten already loaded modules
getPluginModule(slug): PluginModule | undefined Read module cache
clearPluginCache(): void Clear registrations/modules/components and remove runtime DOM assets
registerHmrPluginComponent(slug, reference, component): boolean Development component replacement
invalidatePluginHmr(pluginSlug?): void Invalidate component/module lookup caches

Runtime URLs must be same-origin under /plugins/<slug>/<version>/. SRI must be a correctly formed SHA-384 value. Scripts must register matching slug/version and a component map; merely downloading successfully does not initialize a plugin. Script loads have an eight-second timeout in the player loader.

Local eager-glob components are a development/compatibility path, not proof that an arbitrary installed plugin's Vue sources are available in production. Unsafe URLs, unsupported runtime versions, bad integrity and identity mismatch are rejected. Some ordinary load failures can fall back to built-in components. Use published runtime bundles for distribution.

Player route initialization skips /admin/ routes and protects plugin routes through the player shell/auth metadata. Separate admin initialization selects manifest routes starting with /admin/, strips that prefix for its router, adds them under admin-shell, and skips existing paths. Its script timeout is ten seconds. Names/path collisions can prevent registration; choose unique plugin-prefixed route names.

Slots and screen layout

PluginSlot.vue renders registered/resolved components for a slot. Props are slotName, optional containerClass, wrapperTag, pluginId, and limit. It renders nothing when no component resolves. Components receive plugin-id, plugin-name, and slot-name props. A named component slot can override the wrapper rendering and receives item/index/component metadata.

<PluginSlot slot-name="dashboard-widget" :limit="3" />

A declaration such as frontend.slots.dashboard-widget: ['JournalWidget.vue'] provides metadata. It requires a real registered component and a host screen containing the matching PluginSlot. Studio layouts can alter the server slot map; studio covers that configuration. The admin runtime loader currently mounts admin routes, not a complete duplicate of every player slot facility.

State, language, themes and realtime

Keep shared account state in the existing auth/user Pinia stores. Keep local form/loading state in the component. Clear subscriptions and timers on unmount; route changes should not accumulate listeners or repeat background operations.

Player i18n uses Vue I18n composition mode with English fallback and bundled en, es, de, fr locales. setLanguage(locale) persists laravelcp_locale, updates the active locale and document language. For a signed-in player (the auth store's user, so cookie sessions count) it also saves the locale to the account with PATCH /api/v1/user/profile in the background; a refused request logs a warning and the local switch stands. Requests run one at a time and a superseded switch is dropped, so quick changes leave the account on the last choice; Account settings records the locale it just saved, so it sends no second request. registerPluginTranslations(pluginSlug, messages) merges bundles under plugins.<slug>. It is an explicit helper, not automatic PHP translation loading or a guaranteed SDK export. The separate admin entry does not install this player i18n instance. SupportedLocale is the en/es/de/fr union. The initial stored locale is cast, not checked against that union at runtime; an unknown stored string can still reach Vue I18n and fall back for messages. Initial boot does not call setLanguage to synchronize document.lang. In player source code, explicitly register a bundle before using its keys:

import { i18n, registerPluginTranslations, setLanguage } from '@/i18n'

registerPluginTranslations('journal', {
  en: { title: 'Journal', entries: '{n} entries' },
  es: { title: 'Diario', entries: '{n} entradas' },
})
setLanguage('en')
const title = i18n.global.t('plugins.journal.title')

Expected title: Journal. The helper merges locale bundles under plugins.journal; it does not scan a PHP lang directory or register itself through plugin.json. A new application locale requires its JSON import, messages entry, supported locale union and language selector options. Keep plugin keys under their slug. This source-local import is not automatically available in a published bundle.

Player theme state updates the document's data-theme, persists pulse-theme, and loads /themes/<theme>/theme.css. Theme listeners return unsubscribe functions. A browser preference change is separate from server theme activation.

websocketService is a custom WebSocket/Pusher-protocol helper, not simply an Echo object despite dependencies that include Echo. Public methods include connect(authToken?): Promise<void>, disconnect(): void, getState(), isConnected(), subscribe(channel, authToken?), unsubscribe(channel), on(event, callback): () => void, onStateChange(callback): () => void, send(message), subscribeToPlugin(pluginName, channel, callback): () => void, broadcastToPlugin(pluginName, event, data): void, and onAnyPluginEvent(callback): () => void. Plugin subscriptions use <plugin>:<channel> names; browser broadcasts use plugin-<plugin> channels with <plugin>:<event> and an app_prefix field. Those helper conventions must match the actual server event contract; they are not authorization. Default reconnect interval is three seconds, maximum attempts ten, heartbeat thirty seconds. A listening frontend still needs a running compatible server, authorized channels and a backend broadcaster. See communication.

Player stores

These modules require the player's installed Pinia and browser storage where used. Import from the matching application's @/stores/...; they are not properties of the packaged runtime SDK. Pinia unwraps state/getters on the store; use storeToRefs when destructuring reactive values. Use unique IDs when authoring source-local Pinia stores (for example plugin-journal-draft) to avoid collisions with core stores. The runtime bridge does not expose Pinia or register arbitrary stores automatically. Methods below describe normal HTTP failures; unavailable storage or caller misuse can still throw. UI role checks never replace backend authorization.

Auth store

useAuthStore() exposes user: User | null, loading: boolean, error: string | null, and getter isAuthenticated = !!user. User, LoginCredentials and RegisterData are re-exported from types/user.

Action Result and effects
login(credentials): Promise<boolean> Sends login/email fallback and password to /api/v1/login; remember is not sent. Sets loading, clears error, stores user and optional token in user/auth_token/token. Returns false and sets first validation/message error on ordinary failure.
register(data): Promise<boolean> Sends username/email/password/password_confirmation to /api/v1/register; same loading/error and user/token persistence behavior.
logout(): Promise<void> Attempts /api/v1/logout; even on HTTP failure clears auth user and user/auth_token/token/admin_token/admin_user storage. Does not clear other Pinia stores, HTTP response cache or service-worker caches.
fetchUser(): Promise<void> No stored token means user=null without a request. Otherwise GET /api/v1/user, expecting a direct object with id; persists it. Invalid response/failure clears user and player token keys. Does not clear every admin key in this method itself.
init(): Promise<void> Synchronizes missing token aliases; parses stored user and calls fetchUser only when stored user exists. A token by itself does not trigger profile verification here. Malformed stored user clears it.
autoProvisionGuest(): Promise<boolean> Requests /api/v1/demo/guest-session, stores shared player/admin token/user and returned stats. On request/malformed-response failure, installs a synthetic guest with client admin roles and demo-local-token, then returns true. This fallback is not a server session or permission grant; use only in intended demo context.
clearError(): void Sets error=null.

For 2FA, login stores sessionStorage['2fa_challenge'], sets the error “Two-factor authentication required” and returns false. The player LoginView currently has no completion branch. Successful login and registration default to the core /dashboard; the separate demo-host redirect /game still requires a downstream route absent from standalone core. SettingsView's 2FA toggle currently shows a coming-soon message. The separate admin LoginView has a challenge form; backend completion has its own documented limitations.

User profile store

useUserStore() exposes profile/null, roles/string[], permissions/string[], notificationSettings/null, preferences/null, loading/false, error/null and lastFetched/Date|null. Exported UserProfile has id/username/name/email and optional avatar/bio/timezone/locale/createdAt/lastActive. UserNotificationSettings has emailNotifications/pushNotifications/soundEnabled booleans; UserPreferences has theme (light/dark/system), language/string and compactMode/boolean. These preference types are distinct from runtime theme IDs.

Getters: userId (null fallback), username/displayName (name/username then Guest), email/avatar/bio (null fallback), isAdmin (admin or super-admin), isModerator (moderator or isAdmin), hasPermission(permission), hasRole(role), isAuthenticated (truthy profile id), and isLoaded (profile exists).

Action Return / behavior
fetchProfile(): Promise<boolean> Returns false if already loading. GET direct /api/v1/user, maps snake_case times/avatar/name fallbacks; roles/permissions accept strings or objects with name. Sets lastFetched on success; failure sets error and retains prior data. Missing role/permission fields do not clear old arrays.
updateProfile(updates): Promise<boolean> Requires profile. PATCH /api/v1/user/profile; type allows name/bio/timezone/locale only. Updates supplied local fields when success is not false; name/timezone/locale empty strings do not update locally, bio can. Manages loading/error.
updateAvatar(file: File): Promise<boolean> Requires profile. Multipart POST /api/v1/user/avatar with avatar; requires response.avatar to update local state. Manages loading/error.
fetchNotificationSettings(): Promise<boolean> GET /api/v1/user/notification-settings; assigns direct response.
updateNotificationSettings(partial): Promise<boolean> PATCH same path; truthy response merges supplied values.
fetchPreferences(): Promise<boolean> GET /api/v1/user/preferences; assigns direct response.
updatePreferences(partial): Promise<boolean> PATCH same path; truthy response merges supplied values.
can(permission): boolean, has(role): boolean Exact array membership, without implicit server permission checks.
clearUser(): void Clears profile/roles/permissions/settings/preferences/lastFetched/error; does not change loading, auth store, storage or HTTP caches.

The four notification-settings/preferences actions swallow HTTP failures and return false without updating loading/error. Their paths are not registered in the current core route file; they require implementation elsewhere before they can succeed. Their presence does not establish supported persistence. Account settings/profile screens also have their own endpoint/payload behavior; inspect the HTTP user-settings contract.

Inside the player source application:

import { useUserStore } from '@/stores/user'

const user = useUserStore()
const loaded = await user.fetchProfile()
if (loaded && user.can('journal.write')) {
  // Show the editor; its server endpoint must still authorize the request.
}

Expected: false on fetch failure; capability derives from returned permissions. There is no auth.hasPermission method or SDK permission helper.

Notifications store

useNotificationsStore() exposes notifications/Notification[], unreadCount/0, loading/false, error/null and connected/false. Getters are hasUnread, unreadNotifications and readNotifications, split by read_at. Notification has id/type/title/message, optional link/data, read_at and created_at. The store re-exports that type from types/notification; declarations in types/api are not validation of the actual server envelope.

Action Return / effects
fetchNotifications(): Promise<void> GET /api/v1/notifications; accepts an array or notifications property, replaces list and recalculates unread from loaded rows; sets loading/error. It does not unwrap arbitrary nested paginator data.
fetchRecent(): Promise<void> GET /api/v1/notifications/recent; same list/count replacement, silently catches failure.
fetchUnreadCount(): Promise<void> GET /api/v1/notifications/unread-count; uses count or unread_count or 0; silently catches failure.
markAsRead(id): Promise<void> POST /{id}/read; only on success marks a local row with browser time and decrements count, clamped at zero.
markAllAsRead(): Promise<void> POST /mark-all-read; on success marks local rows and zeroes count.
deleteNotification(id): Promise<void> DELETE /{id}; on success removes local row/decrements unread if needed.
clearRead(): Promise<void> DELETE /read/clear; on success filters read rows locally.
addNotification(notification): void Unshifts local row and increments unread if unread; no ID deduplication or server save.
connect(userId): Promise<void> Connects shared WebSocket service, subscribes private-user.{id}, registers notification/unread-count listeners and fetches initial list. Connection failure starts internal 60-second unread-count polling.
disconnect(): void Removes store callbacks/poll intervals and sets connected=false. Does not disconnect shared socket or unsubscribe its channel.
clearAll(): void Calls disconnect; empties list/count/error. Does not reset loading or clear API cache.

All read/delete mutation actions swallow HTTP errors; resolved void is not proof of server success. List and count reads bypass the GET cache and deduplication, so a refresh always reaches the server; call the fetch actions again after a mutation when exact server state matters. Polling is an internal helper, not an exported startPolling API. Repeated connect calls can add duplicate listeners or intervals; the connected field records listener initialization, not a verified socket health check. Incoming notification expects direct id/type/title/message/link/created_at; unread-count expects {count}. See server notification contracts and service channels.

Registry store details

The registry methods belong to the player store. Its complete returned state is plugins, routes, navigation, loaded and loading. Computed enabledPlugins is a slug Map excluding enabled===false; pluginsBySection is ordered navigation grouped by section (main fallback), pluginRoutes aliases routes, and slotComponents uses a nonempty server slot map or projects frontend_slots into SlottedComponent records {plugin_id, plugin_name, component}. Array-form slot names contain no component records. Local disable toggles do not automatically filter every derived route, nav or server slot projection.

fetchPlugins()/refreshPlugins() return Promise<void>. Fetch skips when loaded/loading, sets loaded only for success=true and catches failures with a console error, without an error state. Refresh resets loaded/loading/server slots, clears the registry HTTP cache and fetches again; it does not itself rebuild router registrations. Use initializePluginRoutes(true) for the router-owned refresh workflow, which removes prior plugin routes/cache first. isEnabled, hasSlot and hasSlotComponents return booleans; getPlugin/getPluginByRoute return Plugin|undefined; getComponentsForSlot/getPluginsWithSlot return arrays; resolveNavigationTarget returns string|null (matching route-name, first plugin route, then declared route/path fallback). Enable/disable return void and may create an incomplete local placeholder when slug is unknown.

A plugin's menu icon comes from its manifest's settings.icon when the host's SVG set has that name (resolvePluginIcon in components/navigation/pluginIcons.ts); otherwise the plugin gets a neutral puzzle piece. Only home is fixed. Core keeps no per-plugin icon list, so name the icon in the manifest.

Import actual registry types Plugin, PluginRoute, PluginNavigationItem and PluginRuntimeDescriptor from @/stores/plugins. Plugin has slug/name/version, description/icon/color/route_name, frontend_routes, navigation/order, API/web/admin flags, frontend_slots, optional runtime and permissions. Routes include owning plugin, path, nullable name/component and meta. Navigation includes slug/name, nullable icon/color/route, section/order and optional roles. Runtime descriptor has format/entry_url/integrity and styles {url,integrity}[]. Do not substitute the differently shaped legacy Plugin in types/plugin. Executable helpers in types/plugin-route.ts use local dynamic imports and are separate from the published runtime loader; they do not make arbitrary installed Vue sources available in production.

Player composables

These source-local helpers are not packaged SDK exports. Call Vue lifecycle composables during setup. Browser APIs are required; no SSR or legacy-browser fallback is implemented for Image/IntersectionObserver.

Lazy loading

Export Inputs/defaults Returned contract and limits
useLazyLoad(elementRef, options = {}) Ref<HTMLElement | null>; root=null, rootMargin=100px, threshold=.1 isLoaded/isVisible refs false, error ref null, load():void. Observes current ref on mount; first intersection sets visible/loaded and unobserves. load only changes loaded; it does not fetch an asset or assign error. Null mount ref is not watched later. Disconnects observer on unmount.
useLazyImage(imageRef, src, placeholder?) Ref<HTMLImageElement | null>, fixed source string isLoaded/isLoading/error/currentSrc refs and loadImage():void. Parent binds currentSrc to img src. Null mount ref loads immediately; otherwise observes. Uses Image preload; success swaps currentSrc, error records Error. Guard skips loading/already-loaded; source is not watched. Observer disconnects on unmount; in-flight Image callbacks are not cancelled.
useImagePreloader() preload(urls: string | string[]) loadedImages/ loadingImages Set refs, errors Map ref; preload returns Promise<void[]>; isLoaded/isLoading/hasError(url) booleans. Reuses loaded URLs and waits for in-flight loads. Failures resolve and enter errors; inspect map rather than expecting rejection. No unmount cancellation.
vLazyImage v-lazy-image="source"; optional data-placeholder Directive observes mounted img, assigns src on first intersection and unobserves. Disconnects stored observer on unmount. No updated hook, load/error state or automatic global registration.
<script setup lang="ts">
import { ref } from 'vue'
import { useLazyImage } from '@/composables/useLazyLoad'

const image = ref<HTMLImageElement | null>(null)
const { currentSrc, isLoaded, error } = useLazyImage(image, '/images/banner.webp')
</script>

<template>
  <img ref="image" :src="currentSrc" alt="Game banner" />
  <p v-if="error" role="alert">Banner unavailable.</p>
  <p v-else-if="!isLoaded" role="status">Loading banner…</p>
</template>

Supply an existing source image. This is a setup/mount example, not an executed browser check. Source.

WebSocket composables

useWebSocket(options = {}) accepts autoConnect=false, optional authToken and channels=[]; values are captured at setup, not watched. It returns readonly connectionState and isConnected refs plus these methods:

Method Contract
connect(): Promise<void> Connects shared service with token, then subscribes configured channels. Explicit calls can reject; mount autoConnect catches failures and relies on state.
disconnect(): void Disconnects shared service for every consumer, not only this component.
subscribe(channel): void, unsubscribe(channel): void Manage shared service subscription; subscribe passes setup authToken.
on<T>(event, callback): () => void Callback receives data and full message; registers callback for unmount cleanup and returns early removal function.
send(message): void Passes WebSocketMessage to service, which queues while disconnected.

Mount adds a service-state listener and optionally connects. Unmount removes registered callbacks only; it does not disconnect or unsubscribe channels. The shared connection is not reference-counted. A component owning a channel must coordinate subscription/unsubscription with other consumers.

useWebSocketChannel<T>(channelName, events = []) auto-connects/subscribes and listens to events. It returns connection refs and data: {value: T|null|undefined}; the current implementation copies the initial data.value into a plain object, so later event changes do not update that returned data property. It also calls subscribe on mount in addition to configured-channel subscription. Do not use it as a working reactive event-data abstraction without fixing/verifying it.

useRealtimeNotifications(userId) auto-connects private-user.{id}, returns unreadCount ref (0) and latestNotification ref (null). unread-count assigns data.count; notification assigns data.notification and increments count. This payload differs from notifications store's direct NotificationEvent. It does not fetch durable history, authenticate with a supplied token, or remove the shared channel on unmount.

For a channel exclusively owned by the current component:

import { onMounted, onUnmounted, ref } from 'vue'
import { useWebSocket } from '@/composables/useWebSocket'

const count = ref<number | null>(null)
const failure = ref('')
const socket = useWebSocket()
socket.on<{ count: number }>('unread-count', data => { count.value = data.count })
onMounted(async () => {
  try {
    await socket.connect()
    socket.subscribe('global')
  } catch {
    failure.value = 'Realtime unavailable'
  }
})
onUnmounted(() => socket.unsubscribe('global'))

Requires a compatible server actually broadcasting that event; the example establishes no private-channel authorization and leaves shared socket ownership with the app. Composable source.

Toasts and service-worker status

Player useToast() returns shared toasts ref and show(message, type='info', duration=3000), success/error/info/warning(message, duration?), and remove(id). Creation returns numeric ID; removal returns void. Toast records have id/message/type/duration. Every creation schedules removal, including nonpositive durations; zero does not mean persistent. No clear-all/dispose is exported. Mount ToastContainer once. The service-worker helpers and cache/update limitations are documented below; status has isRegistered, isUpdateAvailable, isOffline and registration (ServiceWorkerRegistration|null).

Separate admin store and composables

@/stores/plugins in the admin app is a different usePluginsStore. Returned state is plugins (initial []), loading (false), and refreshPlugins(): Promise<void>. Refresh calls /admin/plugins, assigns response.plugins or response or [], catches errors with console warning and retains prior data, then clears loading. It has no loaded guard/error ref or player navigation/slot helpers, and refresh does not reinstall runtime routes.

Admin useToast() returns shared toasts plus show(message, type='info', duration=4000), success/error/warning/info(message, duration?) and remove(id). Creation returns numeric ID beginning at 1; records have id/message/type/visible. Only positive durations schedule removal; duration=0 persists until removed. Player and admin state/type/defaults are separate. For an admin source component:

import { useToast } from '@/composables/useToast'
const toast = useToast()
const id = toast.info('Working…', 0)
// After the caller completes its work:
toast.remove(id)

Admin useConfirm() returns shared isOpen/config refs, show(options), and confirm(message, title?), warning(message, title?), info(message, title?). All four methods return Promise<boolean>. show defaults title/message to Confirm Action/Are you sure?, labels to Confirm/Cancel, type to danger; shortcuts select danger/warning/info. options must be an object. Config carries onConfirm/onCancel callbacks; they close and resolve true/false. Overlay cancel resolves false. A second show replaces config and can leave the first promise unresolved; no queue or timeout exists. It controls only confirmation, not API busy/error state. Mount ConfirmModal once. Example:

import { useConfirm } from '@/composables/useConfirm'
const accepted = await useConfirm().warning('Discard this draft?', 'Discard draft')
if (accepted) {
  // Clear the caller-owned draft here.
}

The current renderer's dialog/focus limitations are recorded on its component page. Source helpers confirm and toast are admin-local APIs, not runtime SDK members.

Realtime transport details

The exported WebSocketService class accepts a partial configuration: url/key/cluster (from env helper, falling back to ws://localhost:6001, app-key, mt1), reconnect=true, reconnectInterval=3000ms, maxReconnectAttempts=10 and heartbeatInterval=30000ms. The singleton is websocketService. It builds a Pusher-protocol URL /app/<key>?protocol=7&client=js&version=7.4.0&cluster=<cluster>. ConnectionState is connecting/connected/disconnecting/disconnected/error. Messages have event, data, optional channel and optional timestamp. The service event union lists notification, chat-message, unread-count and system-alert; arbitrary namespaced events require appropriate typing at source call sites. on callbacks receive parsed data and full message; malformed JSON and callback errors are swallowed.

connect resolves on socket open, before private subscription acknowledgement; already-connected calls resolve immediately. Error rejects; close before open has no explicit promise rejection/timeout. Concurrent connects are not deduped. Unexpected close uses fixed-interval reconnect, not exponential backoff; reconnect does not pass the original connect token, though per-subscription auth may remain. subscribe sends a Pusher subscribe message containing auth directly; it does not perform Laravel's broadcast-signature authorization request. A bearer token alone is not a verified private-channel signature. Normal disconnect stops timers and closes socket but leaves subscription/listener/queued-message collections; send queues serialized messages until a later open.

WebSocketService.parsePluginFromEvent(eventName) returns the first colon segment or null; parseEventName(eventName) removes the first prefix, retaining remaining colons. subscribeToPlugin(slug, channel, callback) subscribes and listens to event slug:channel, filtering optional data.app_prefix; returned cleanup removes listener and channel. broadcastToPlugin uses channel plugin-slug and event slug:event. Those conventions differ and require explicit server alignment; these helpers do not establish authenticated server broadcast or standard channel catalogs. onAnyPluginEvent uses wildcard events containing a colon and returns listener removal.

Use server broadcast/polling contracts for actual user/admin/global channels. Do not infer system.announcements, admin.telemetry, forum/gamekit channel contracts or Echo timing from old guides. Service source.

Core error reporting

frontend/src/plugins/errorLogger.ts is a first-party Vue infrastructure plugin, despite its directory name. The player entry installs it, attaches window error/unhandled-rejection handlers, and attaches an Axios interceptor to the global Axios object. This is separate from distributable gameplay plugins.

Public helper Behaviour
errorLogger.logError(error, source = 'unknown', line = 0, column = 0) Posts message, stack, page URL and browser details to /log-frontend-error.
errorLogger.logApiError(endpoint, method, statusCode, errorMessage, requestData = null, responseData = null) Posts API failure context to /log-api-error.
errorLogger.logVueError(error, component, hook = null, info = null) Posts component failure context to /log-vue-error.
setupGlobalErrorHandlers() Adds window listeners; call once during boot.
setupAxiosErrorInterceptor(instance) Installs a response interceptor on that specific Axios instance; reports HTTP 500+ responses.

All three posting methods return Promise<void>, share a limit of ten attempted reports per minute and catch delivery errors. The base URL comes from VITE_API_URL or /api; choose the versioned API base when using the versioned Vue/API error routes. Installing an interceptor on global Axios does not automatically attach it to every axios.create() instance. The interceptor parses truthy request data as JSON without its own parse guard, so non-JSON request bodies need care. These limits and swallowed delivery errors mean a quiet log is not proof of a healthy UI. Do not put credentials into diagnostic payloads. See operations and source.

Service worker and offline boundaries

useServiceWorker() exports reactive status plus register(), update(), activateUpdate(), clearCache() and clearApiCache(). A component using the composable registers /sw.js at root scope on mount, attaches online/offline and controller-change listeners, and removes those online/offline/controller-change listeners on unmount. Registration updatefound/installing-worker listeners are not explicitly removed. register() returns Promise<boolean>; the other helpers return Promise<void>. No current app component calls this composable, so its presence does not mean every player already has a worker installed. It requires browser globals and is not a server-side utility.

The worker in frontend/public/sw.js uses versioned laravelcp-* caches. It precaches /, /index.html and /favicon.ico; a failed precache request can fail installation. It handles GET requests with these strategies:

Request Implemented strategy
API path starting /api/user or /api/settings Network first; successful responses cached for a five-minute network-failure fallback.
Other /api/ paths, including the current /api/v1/user and /api/v1/settings routes Network only; no offline account-data fallback from this allowlist.
Image extension Cache first for 24 hours; an expired entry can still be returned after network failure.
JavaScript, CSS and font extension Cached response first, with background network refresh.

The worker's message handler does not acknowledge the message channel sent by clearCache(), so that helper's returned promise can remain pending. It deletes all same-origin cache names, rather than only Pulse names. clearApiCache() sends a fire-and-forget deletion message; it does not await deletion. Update activation also polls without a timeout and controller changes reload the page. Account sign-out does not call these helpers automatically. Do not promise offline gameplay, completed cache clearing or safe account cache separation from these APIs. See the composable and worker.

Builds, checks and common failures

Run player checks from frontend: npm run type-check and npm run test:unit -- --run. npm run build builds the SPA; build:check combines type checking and build. Run admin npm test / npm run build from backend/resources/admin. Its build writes backend/public/admin and empties that output directory; review generated output rules before running it.

For a blank plugin screen, inspect /api/plugins/enabled, the browser network asset request, console registration error and component name in that order. For 401 loops, inspect all auth keys and the application's actual client. For stale data, inspect GET cache TTL and invalidate related list URLs. For 404 on admin refresh, check the server SPA catchall/build output as well as the Vue route. Successful compilation does not verify keyboard behavior, responsive layout, loading/error states or authenticated browser interactions.

Sources: player entry (frontend/src/main.ts), player services (frontend/src/services), plugin store (frontend/src/stores/plugins.ts), admin app (backend/resources/admin), SDK (frontend/src/plugin-sdk.ts).

Continue with workflows and source contracts

The screen workflow map documents every static player/admin registration and every owned view/layout, including unrouted source and simulated actions. Frontend internals covers the remaining type/data/style/environment/build interfaces. Those source contracts do not claim every application workflow was exercised in a browser.

Playable stage

The optional 3D toolchain extends the existing stage with explicit local practice, physics/navigation, animated GLBs and opt-in positional sound. Its shared room contract uses single-use Laravel tickets and server-owned positions; ordinary plugin/economy state is outside that protocol.