feat: ws singleton, auth transport and game payload types
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
90c4611f1f
commit
d0176fe67a
|
|
@ -0,0 +1,11 @@
|
||||||
|
import type { GameError } from '~/types/game'
|
||||||
|
|
||||||
|
/** Turns a rejected send (`{ message, code? }`, not an Error) into text for the player. */
|
||||||
|
export function useErrorText() {
|
||||||
|
const { t, te } = useI18n()
|
||||||
|
return (e: unknown) => {
|
||||||
|
const err = (e ?? {}) as Partial<GameError> & { error?: string }
|
||||||
|
if (err.code && te(`errors.${err.code}`)) return t(`errors.${err.code}`)
|
||||||
|
return err.message || err.error || t('errors.unknown')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
export type NoticeType = 'success' | 'error' | 'warning' | 'info'
|
||||||
|
|
||||||
|
export interface Notice {
|
||||||
|
id: number
|
||||||
|
text: string
|
||||||
|
type: NoticeType
|
||||||
|
}
|
||||||
|
|
||||||
|
let nextId = 1
|
||||||
|
|
||||||
|
/** Short-lived messages shown at the top of every page. */
|
||||||
|
export function useNotices() {
|
||||||
|
const list = useState<Notice[]>('notices', () => [])
|
||||||
|
|
||||||
|
function dismiss(id: number) {
|
||||||
|
list.value = list.value.filter((n) => n.id !== id)
|
||||||
|
}
|
||||||
|
|
||||||
|
function push(text: string, type: NoticeType = 'info') {
|
||||||
|
const id = nextId++
|
||||||
|
list.value = [...list.value, { id, text, type }]
|
||||||
|
setTimeout(() => dismiss(id), 6000)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { list, push, dismiss }
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
export default defineNuxtPlugin((nuxtApp) => {
|
||||||
|
const config = useRuntimeConfig().public
|
||||||
|
const notices = useNotices()
|
||||||
|
|
||||||
|
setupNetworking({
|
||||||
|
serverUrl: String(config.SERVER_URL),
|
||||||
|
wsUrl: `${config.WS_PROTOCOL === 'ws' ? 'ws' : 'wss'}://${config.WEBS_URL}/app/${config.PUSHER_APP_KEY}`,
|
||||||
|
appKey: String(config.PUSHER_APP_KEY),
|
||||||
|
mock: String(config.MOCK_SERVER) === 'true',
|
||||||
|
notify: (opts, type) =>
|
||||||
|
typeof opts === 'string' ? notices.push(opts, type ?? 'info') : notices.push(opts.text, opts.type),
|
||||||
|
translate: (key) => nuxtApp.$i18n.t(key),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,135 @@
|
||||||
|
// Payloads exchanged with the server. Every number in here is computed server-side;
|
||||||
|
// the client only projects resources and countdowns forward from the timestamps.
|
||||||
|
|
||||||
|
export type Resource = 'wood' | 'clay' | 'iron' | 'food'
|
||||||
|
export type Resources = Record<Resource, number>
|
||||||
|
export type Cost = Record<Exclude<Resource, 'food'>, number>
|
||||||
|
|
||||||
|
export type BuildingType =
|
||||||
|
| 'headquarters'
|
||||||
|
| 'storage'
|
||||||
|
| 'farm'
|
||||||
|
| 'timber_camp'
|
||||||
|
| 'clay_pit'
|
||||||
|
| 'iron_mine'
|
||||||
|
| 'hiding_place'
|
||||||
|
| 'wall'
|
||||||
|
| 'rally_point'
|
||||||
|
|
||||||
|
/** Why the server refuses an offer. The client shows `village.blocked.<reason>`. */
|
||||||
|
export type BlockedReason = 'max_per_village' | 'no_space' | 'max_level'
|
||||||
|
|
||||||
|
export interface AuthUser {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `POST auth/login` and `POST auth/register`. */
|
||||||
|
export interface AuthResult {
|
||||||
|
token: string
|
||||||
|
user: AuthUser
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One row of `world.index`. */
|
||||||
|
export interface WorldSummary {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
slug: string
|
||||||
|
speed: number
|
||||||
|
village_id: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `village.show`, and the reply to every `village.*` mutation. */
|
||||||
|
export interface VillageState {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
x: number
|
||||||
|
y: number
|
||||||
|
grid: { w: number; h: number }
|
||||||
|
/** Amounts stored at `resources_at`. */
|
||||||
|
resources: Resources
|
||||||
|
resources_at: string
|
||||||
|
/** Net change per hour. Food is farm output minus upkeep, so it can be negative. */
|
||||||
|
rates: Resources
|
||||||
|
storage_cap: number
|
||||||
|
population: Population
|
||||||
|
builders: number
|
||||||
|
buildings: Building[]
|
||||||
|
queue: BuildOrder[]
|
||||||
|
buildable: BuildOption[]
|
||||||
|
/** Lets the client correct for its own clock being off. */
|
||||||
|
server_time: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Population {
|
||||||
|
/** Food per hour the village can feed. */
|
||||||
|
food_budget: number
|
||||||
|
/** Food per hour eaten by villagers and soldiers. */
|
||||||
|
upkeep: number
|
||||||
|
villagers: number
|
||||||
|
/** Villagers assigned to buildings. */
|
||||||
|
workers: number
|
||||||
|
soldiers: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Building {
|
||||||
|
id: number
|
||||||
|
type: BuildingType
|
||||||
|
level: number
|
||||||
|
x: number
|
||||||
|
y: number
|
||||||
|
footprint: [number, number]
|
||||||
|
priority: number
|
||||||
|
workers: { assigned: number; required: number }
|
||||||
|
/** assigned / required, 0..1. */
|
||||||
|
staffing: number
|
||||||
|
production: { resource: Resource; per_hour: number } | null
|
||||||
|
/** Next level after everything already queued; null at max level. */
|
||||||
|
upgrade: Offer | null
|
||||||
|
/** null when the building cannot go lower (core buildings at level 0). */
|
||||||
|
demolish: { refund: Cost; seconds: number } | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether it is affordable is left to the client, which compares the cost to projected resources. */
|
||||||
|
export interface Offer {
|
||||||
|
target_level: number
|
||||||
|
cost: Cost
|
||||||
|
seconds: number
|
||||||
|
blocked: BlockedReason | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BuildOption extends Offer {
|
||||||
|
type: BuildingType
|
||||||
|
footprint: [number, number]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BuildOrder {
|
||||||
|
id: number
|
||||||
|
/** null for a new instance that does not exist yet. */
|
||||||
|
building_id: number | null
|
||||||
|
type: BuildingType
|
||||||
|
action: 'build' | 'upgrade' | 'demolish'
|
||||||
|
/** -1 means the instance is removed. */
|
||||||
|
target_level: number
|
||||||
|
x: number
|
||||||
|
y: number
|
||||||
|
footprint: [number, number]
|
||||||
|
cost: Cost
|
||||||
|
position: number
|
||||||
|
/** Builder slot working on it, or null while it waits. */
|
||||||
|
builder: number | null
|
||||||
|
starts_at: string | null
|
||||||
|
finishes_at: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Push `village:updated` after the server processed an event for this village. */
|
||||||
|
export interface VillageUpdated {
|
||||||
|
village_id: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a rejected `ws.send` carries. */
|
||||||
|
export interface GameError {
|
||||||
|
message: string
|
||||||
|
code?: string
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,75 @@
|
||||||
|
import { createApiClient, type WsClientConfig } from '@blax-software/networking'
|
||||||
|
import { createVueWsClient, type VueWsClient } from '@blax-software/networking/vue'
|
||||||
|
import type { AuthResult } from '~/types/game'
|
||||||
|
import { createMockServer } from '~/mock/server'
|
||||||
|
|
||||||
|
/** The part of the WS client the game uses. The mock server implements the same surface. */
|
||||||
|
export type GameWs = Pick<
|
||||||
|
VueWsClient,
|
||||||
|
'send' | 'listen' | 'listenWhileMounted' | 'is_setup' | 'is_opened' | 'resetConnection'
|
||||||
|
>
|
||||||
|
|
||||||
|
/** HTTP is only for getting the bearer token; everything else goes over `ws`. */
|
||||||
|
export interface GameAuth {
|
||||||
|
token(): string | null
|
||||||
|
login(email: string, password: string): Promise<AuthResult>
|
||||||
|
register(name: string, email: string, password: string): Promise<AuthResult>
|
||||||
|
logout(): void
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NetworkingOptions {
|
||||||
|
serverUrl: string
|
||||||
|
wsUrl: string
|
||||||
|
appKey: string
|
||||||
|
mock: boolean
|
||||||
|
notify?: WsClientConfig['notify']
|
||||||
|
translate?: WsClientConfig['translate']
|
||||||
|
}
|
||||||
|
|
||||||
|
// The app's singletons, assigned once by plugins/networking.ts before any page runs.
|
||||||
|
export let ws: GameWs
|
||||||
|
export let gameAuth: GameAuth
|
||||||
|
export let isMockServer = false
|
||||||
|
|
||||||
|
export function setupNetworking(options: NetworkingOptions) {
|
||||||
|
if (options.mock) {
|
||||||
|
const mock = createMockServer()
|
||||||
|
ws = mock.ws
|
||||||
|
gameAuth = mock.auth
|
||||||
|
isMockServer = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const api = createApiClient({ serverUrl: options.serverUrl, notify: options.notify })
|
||||||
|
api.loadBearerFromStorage()
|
||||||
|
|
||||||
|
const client = createVueWsClient({
|
||||||
|
url: options.wsUrl,
|
||||||
|
appKey: options.appKey,
|
||||||
|
getAuthToken: () => api.bearerToken || null,
|
||||||
|
notify: options.notify,
|
||||||
|
translate: options.translate,
|
||||||
|
sendTimeout: 15000,
|
||||||
|
rejectOnDisconnect: true,
|
||||||
|
})
|
||||||
|
client.setAppReady()
|
||||||
|
ws = client
|
||||||
|
|
||||||
|
const signIn = (result: AuthResult) => {
|
||||||
|
api.setBearer(result.token)
|
||||||
|
client.resetConnection()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
gameAuth = {
|
||||||
|
token: () => api.bearerToken || null,
|
||||||
|
login: async (email, password) =>
|
||||||
|
signIn((await api.post<AuthResult>('auth/login', { email, password })).data),
|
||||||
|
register: async (name, email, password) =>
|
||||||
|
signIn((await api.post<AuthResult>('auth/register', { name, email, password })).data),
|
||||||
|
logout() {
|
||||||
|
api.setBearer(null)
|
||||||
|
client.resetConnection()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue