Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,15 @@ export function apiResponseError (status: number, body: unknown, headers: Header
const retrySafe = method === 'GET' || request.retrySafe === true
const transient = status === 408 || status === 429 || status >= 500
const redirect = status >= 300 && status < 400
const unknownGameEngine = method === 'PATCH' && /^\/games\/[^/]+$/.test(request.path) &&
status === 403 && firstErrorCode === 'forbidden' && firstErrorTitle === 'only admins can add new game engines; select an existing engine'
return new CliError(code, message, status === 401 && !payloadValidationFailed ? 3 : status >= 500 ? 5 : 4, {
status,
...(Object.keys(safeDetails).length === 0 ? {} : { details: safeDetails }),
retryable: transient && retrySafe,
requestId: headers.get('x-request-id') ?? headers.get('x-cloud-trace-context') ?? undefined,
retryAfter: headers.get('retry-after') ?? undefined,
...(unknownGameEngine ? { hint: 'Run `poki games engines` and use an exact name from the list in your update.' } : {}),
...(status === 403 && firstErrorCode === 'content-moderation-required'
? { hint: 'This operation requires content moderation to pass for an unapproved game. Inspect content_moderation_status with `poki games get GAME_ID`. Pending, fail, defer, and missing status block restricted operations. Wait for moderation or address the review feedback before retrying; ordinary version uploads remain available.' }
: status === 400 && firstErrorCode === 'invalid-lobby-filter' && /^\/games\/[^/]+\/netlib\/lobbies$/.test(request.path)
Expand Down
14 changes: 11 additions & 3 deletions src/commands/games.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import type { Argv } from 'yargs'

import { ApiClient } from '../api'
import { gamesDocumentation } from '../docs/resources'
import { gameEngineInput, gamesDocumentation } from '../docs/resources'
import { CliError, inputError } from '../errors'
import { requireChanges } from '../input'
import { isRecord } from '../json'
import { jsonApiDocument, unreadableFields, unreadableFieldsReport } from '../jsonapi'
import { listCapabilities } from '../list-capabilities'
import { getProjectGameId, projectConfigError } from '../project'
Expand Down Expand Up @@ -130,7 +131,7 @@ function withGameFieldOptions (yargs: Argv): Argv {
.option('archived', { describe: 'Archive the game; use --no-archived to restore it', type: 'boolean' })
.option('favorite', { describe: 'Favorite the game for the current user; use --no-favorite to remove it', type: 'boolean' })
.option('engine', {
describe: 'Developer-editable engine annotation: 2-32 lowercase letters, digits, or hyphens; the server preserves every other annotation',
describe: gameEngineInput,
type: 'string'
})
.option('privacy-policy-url', {
Expand Down Expand Up @@ -178,6 +179,13 @@ export function registerGameCommands (yargs: Argv, api: ApiClient): Argv {
const result = await listResources(api, '/games', argv, listCapabilities.games, [], argv.team === undefined ? [] : [['team_id', argv.team]])
renderList(result, argv, 'games')
})
.command('engines', 'List existing game engine names', engines => withRequestOptions(engines), async argv => {
const { body } = await api.request({ path: '/_annotations/engine', accept: 'application/json', timeoutMs: requestTimeout(argv) })
if (!isRecord(body) || !Array.isArray(body.engine) || !body.engine.every(name => typeof name === 'string')) {
throw new CliError('INVALID_API_RESPONSE', 'Expected a list of engine names from the Poki API.', 5)
}
render({ data: body.engine, meta: { total: body.engine.length } }, argv)
})
.command('get [game-id]', 'Get one game; defaults to the configured project game', get => gameFlag(withOutputOptions(get))
.positional('game-id', { describe: 'Poki for Developers game ID; defaults to project game_id', type: 'string' }), async argv => {
const gameID = selectedGame(argv)
Expand Down Expand Up @@ -236,5 +244,5 @@ export function registerGameCommands (yargs: Argv, api: ApiClient): Argv {
const body = jsonApiDocument('games', data, gameID)
await renderMutation(api, argv, { method: 'PATCH', path, body, expected: { type: 'games', id: gameID }, behavior: { sideEffects: ['May create audit or notification activity.'] } })
})
.demandCommand(1, 'Choose games list, games get, games readiness, or games update.'), () => {})
.demandCommand(1, 'Choose games list, games engines, games get, games readiness, or games update.'), () => {})
}
1 change: 1 addition & 0 deletions src/developer-permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const developerPermissionCatalog = [
{ code: 'can_edit_owned_reviews', description: 'Update or close reviews for a game belonging to the current user or team.' },
{ code: 'can_edit_owned_versions', description: 'Update, archive, or restore versions belonging to the current user or team.' },
{ code: 'can_query_clickhouse', description: 'Run analytics queries; backend table and row scoping still applies.' },
{ code: 'can_read_distinct_engine_annotations', description: 'List the existing game engine names.' },
{ code: 'can_read_owned_game_change_requests', description: 'List or read game-change requests for a game belonging to the current user or team.' },
{ code: 'can_read_owned_game_events', description: 'List event definitions and funnels for a game belonging to the current user or team.' },
{ code: 'can_read_owned_games', description: 'List or read games belonging to the current user or team.' },
Expand Down
9 changes: 8 additions & 1 deletion src/docs/command-groups/games.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
import { listCapabilities } from '../../list-capabilities'
import { gameEngineInput } from '../resources'
import type { CommandSpecBuilder } from './types'

export function addGameCommandSpecs ({ add, apiAction, argument, categoryNameDiscovery, dataOption, example, formatOption, gameOption, group, listOptionsFor, mutationOptions, option, outputOptions, requestOptions }: CommandSpecBuilder): void {
group('games', 'List, inspect, assess readiness, and update games.')
const gameFieldOptions = [
option('--archived', 'boolean', 'Archive the game; --no-archived restores it. Archiving is blocked during a requested or running Web Fit test.'),
option('--favorite', 'boolean', 'Favorite for the current user only; --no-favorite removes it.'),
option('--engine', 'string', 'Developer-editable engine annotation: 2-32 lowercase letters, digits, or hyphens; the server preserves every other annotation.'),
option('--engine', 'string', gameEngineInput),
option('--privacy-policy-url', 'string', 'Public privacy-policy URL with a supported network scheme and no whitespace.'),
option('--suggested-description', 'string', 'Developer-suggested public game description, at most 65535 UTF-8 bytes.'),
option('--suggested-category', 'string', `Suggested Poki content-category name; combined comma-separated value at most 65535 UTF-8 bytes; repeatable. ${categoryNameDiscovery}`, { repeatable: true })
]
const gameDataShapeBehavior = '--data is a flat attribute object, not a JSON:API envelope, and replaces all field flags. Run poki games fields for the editable field reference.'
apiAction(['games', 'list'], 'List games for one team with bounded pagination.', { method: 'GET', path: '/games', contacts_api: true }, ['can_read_owned_games'], { options: [option('--team', 'string', 'Select an exact team ID; without it the API uses the authenticated user\'s first team.'), ...listOptionsFor(listCapabilities.games)], scope: '--team or the authenticated user\'s first team', behavior: ['This endpoint supports --team, sorting, and pagination. It does not support the generic --filter option or combine all of a user\'s teams.'], examples: [example('poki games list --team TEAM_ID --page 2 --page-size 50', 'Read one bounded page; meta.has_next reports whether more pages exist.'), example('poki games list --all --fields id,title,public_version --format csv', 'Select three developer-visible fields and export the complete list as CSV; a single page is refused unless it proves it is the last one.')] })
apiAction(['games', 'get'], 'Get one game; positional ID defaults to project game_id.', { method: 'GET', path: '/games/:gameID', contacts_api: true }, ['can_read_owned_games'], { arguments: [argument('game-id', 'Game ID; defaults to project game_id.', false)], options: [option('--game', 'string', 'Game ID; alternative to the positional game-id.'), ...outputOptions] })
apiAction(['games', 'engines'], 'List existing game engine names for games update.', { method: 'GET', path: '/_annotations/engine', contacts_api: true }, ['can_read_distinct_engine_annotations'], {
options: requestOptions,
scope: 'All non-deleted games across teams.',
output: { shape: '{data: string[], meta: {total}}' },
examples: [example('poki games engines --format json', 'Look up the exact name to pass to poki games update --engine.')]
})
add({
path: ['games', 'readiness'],
summary: 'Report visible CLI and backend readiness for activation, Playtest requests, and Player Fit tests.',
Expand Down
6 changes: 4 additions & 2 deletions src/docs/resources.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { mediaKitAssetTypes } from '../media-kit'
import { RESOURCE_API_TIME_ZONE } from '../timezones'

export const gameEngineInput = 'For a non-empty engine, select an exact name from poki games engines (2-32 lowercase letters, digits, or hyphens).'

export type RelationshipResourceApiType =
'games' |
'game_versions' |
Expand Down Expand Up @@ -48,7 +50,7 @@ const supplementalDetails: Record<string, {
'media-kit.status': { enum_values: ['uploading', 'ready', 'error'] },
'media-kit.size': { unit: 'bytes' },
'games.public_version': { input_behavior: 'Not editable through games update; versions activate changes the public version. tracks remain the authoritative traffic allocation.' },
'games.annotations': { input_behavior: 'Developer mutations accept only engine. The server preserves existing annotation keys and never removes them.' },
'games.annotations': { input_behavior: `Developer mutations accept only engine. ${gameEngineInput} The server preserves other annotation keys.` },
'games.tracks': { input_behavior: 'Not editable through games update. versions activate replaces the allocation with one public track, and the backend rejects activation while multiple tracks already exist. Weights within each track must total 100.' },
'games.cached_median_download_size': { unit: 'bytes' },
'games.content_moderation_status': { enum_values: ['pending', 'pass', 'fail', 'defer'] },
Expand Down Expand Up @@ -132,7 +134,7 @@ export const gamesDocumentation: ResourceDocumentation = {
field('privacy_policy_url', 'string', 'editable', 'Public URL of the game privacy policy, at most 255 UTF-8 bytes; use an absolute network URL without whitespace, or an empty string to clear it. Supported schemes: http, https, ftp, tcp, udp, ws, wss.'),
field('custom_content_security_policy', 'string', 'read-only', 'Server-managed Content Security Policy for the game build.'),
field('thumbnail_url', 'string', 'read-only', 'Public URL of the current processed thumbnail.'),
field('annotations', 'object', 'editable', 'Game metadata map. Developer mutations accept only engine, containing 2 through 32 lowercase letters, digits, or hyphens; the server preserves all existing keys and never removes annotations.'),
field('annotations', 'object', 'editable', `Game metadata map. Only engine is editable. ${gameEngineInput} The server preserves other annotation keys.`),
field('suggested_description', 'string', 'editable', 'Developer-proposed public description, at most 65535 UTF-8 bytes.'),
field('suggested_categories', 'string', 'editable', 'Comma-separated Poki content-category names proposed by the developer, at most 65535 UTF-8 bytes total; use the title values from poki categories list. Playtest and Player Fit targeting use numeric IDs instead.'),
field('tracks', 'array<object>', 'read-only', 'Traffic allocation entries containing track, version_id, and weight. versions activate supports games with at most one existing track and replaces the allocation with one public track.'),
Expand Down
38 changes: 38 additions & 0 deletions test/resources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,44 @@ import test from 'node:test'

import { apiHarness, authEnvironment, jsonApi, listen, requestBody, runCli, temporaryDirectory } from './helpers'

void test('games engines reads the live list and rejects malformed names', async t => {
let body: unknown
const { env } = await apiHarness(t, (req, res) => {
assert.equal(req.method, 'GET')
assert.equal(req.url, '/_annotations/engine')
assert.equal(req.headers.authorization, 'Bearer test-token')
assert.equal(req.headers.accept, 'application/json')
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(body))
}, 'game-engines')
for (const engines of [['phaser-3', 'studio-engine'], []]) {
body = { engine: engines, internal: 'hidden' }
const result = await runCli(['games', 'engines', '--format', 'json'], { env })
assert.equal(result.code, 0, result.stderr)
assert.deepEqual(JSON.parse(result.stdout), { data: engines, meta: { total: engines.length } })
}
for (body of [{ engines: [] }, { engine: ['unity', null] }]) {
const result = await runCli(['games', 'engines', '--format', 'json'], { env })
assert.equal(result.code, 5, result.stderr)
assert.equal(JSON.parse(result.stderr).error.code, 'INVALID_API_RESPONSE')
}
})

void test('games update points rejected engine names to the live list', async t => {
const title = 'only admins can add new game engines; select an existing engine'
const { env } = await apiHarness(t, (req, res) => {
assert.equal(req.method, 'PATCH')
assert.equal(req.url, '/games/g')
jsonApi(res, { errors: [{ status: '403', code: 'forbidden', title }] }, 403)
}, 'game-engine-update')
const result = await runCli(['games', 'update', 'g', '--engine', 'new-engine', '--format', 'json'], { env })
assert.equal(result.code, 4, result.stderr)
const { error } = JSON.parse(result.stderr)
assert.equal(error.message, title)
assert.equal(error.retryable, false)
assert.match(error.hint, /poki games engines/)
})

void test('resource lists default to operational summaries and support full and selected views', async t => {
const { env } = await apiHarness(t, (req, res) => {
jsonApi(res, {
Expand Down
Loading