@idosgames/mcp 0.1.28 → 0.1.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/package.json +1 -1
- package/registry/host.json +11 -71
- package/registry/index.json +109 -109
- package/registry/modules/ai.json +4 -4
- package/registry/modules/board-game.json +3 -3
- package/registry/modules/boosts.json +6 -6
- package/registry/modules/character.json +33 -5
- package/registry/modules/chat.json +25 -5
- package/registry/modules/collections.json +22 -6
- package/registry/modules/coop-events.json +6 -6
- package/registry/modules/craft.json +6 -6
- package/registry/modules/deals.json +2 -2
- package/registry/modules/events.json +5 -5
- package/registry/modules/friends.json +25 -5
- package/registry/modules/idle-rpg.json +2 -2
- package/registry/modules/inventory.json +2 -2
- package/registry/modules/invite.json +5 -5
- package/registry/modules/leaderboard.json +21 -5
- package/registry/modules/lootboxes.json +6 -6
- package/registry/modules/mailbox.json +33 -5
- package/registry/modules/marketplace.json +34 -6
- package/registry/modules/mini-game.json +2 -2
- package/registry/modules/multiplayer.json +34 -10
- package/registry/modules/premium.json +6 -6
- package/registry/modules/profile.json +4 -4
- package/registry/modules/pvp.json +33 -5
- package/registry/modules/quests.json +5 -5
- package/registry/modules/rewards.json +6 -6
- package/registry/modules/season.json +5 -5
- package/registry/modules/store.json +4 -4
- package/registry/modules/tutorials.json +2 -2
- package/registry/modules/voxelcraft.json +264 -12
- package/registry/modules/workshop.json +49 -5
- package/registry/skills/authentication.json +1 -1
- package/registry/skills/blockchain-system.json +1 -1
- package/registry/skills/checkout-system.json +1 -1
- package/registry/skills/cloud-code.json +2 -2
- package/registry/skills/currency-system.json +1 -1
- package/registry/skills/idosgames-compose-modules.json +1 -1
- package/registry/skills/idosgames-getting-started.json +1 -1
- package/registry/skills/idosgames-module-contract.json +2 -2
- package/registry/skills/idosgames-project-structure.json +1 -1
- package/registry/skills/idosgames-ui-kit.json +2 -2
- package/registry/skills/marketplace-system.json +1 -1
- package/registry/skills/match-system.json +1 -1
- package/registry/skills/multiplayer-realtime.json +2 -2
- package/registry/skills/voxelcraft-worlds.json +2 -2
- package/registry/skills/workshop-system.json +2 -2
|
@@ -39,28 +39,72 @@
|
|
|
39
39
|
"version": "0.1.2"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@idosgames/core": "0.21.
|
|
42
|
+
"@idosgames/core": "0.21.3",
|
|
43
43
|
"@idosgames/module-sdk": "0.10.0",
|
|
44
|
-
"@idosgames/react": "0.4.
|
|
44
|
+
"@idosgames/react": "0.4.5",
|
|
45
45
|
"react": "19.2.7"
|
|
46
46
|
},
|
|
47
|
-
"contentHash": "
|
|
47
|
+
"contentHash": "71dc68c0348e58d7fd757b3f17cd5f49c32ac81a6a7f51f43cf738a440da9b9f",
|
|
48
48
|
"files": [
|
|
49
|
+
{
|
|
50
|
+
"path": "components/Catalog.tsx",
|
|
51
|
+
"content": "import { useCallback, useEffect, useState, type ReactNode } from \"react\";\nimport {\n type WorkshopBrowseQuery,\n type WorkshopContentView,\n type WorkshopDefinitionsResponse,\n} from \"@idosgames/core\";\nimport { ContentCard } from \"./ContentCard\";\nimport { errorText } from \"../errors\";\nimport { useContentTypes } from \"../hooks\";\nimport {\n checkLabel,\n chip,\n chipActive,\n chipsRow,\n errorBox,\n filtersRow,\n grid,\n input,\n muted,\n secondaryBtn,\n} from \"../styles\";\nimport { type WorkshopHost } from \"../types\";\n\nexport function Catalog({\n host,\n defs,\n onOpen,\n}: {\n host: WorkshopHost;\n defs: WorkshopDefinitionsResponse;\n onOpen(id: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content);\n const [query, setQuery] = useState<WorkshopBrowseQuery>({ sort: \"New\" });\n const [collection, setCollection] = useState<string | null>(null);\n const [items, setItems] = useState<WorkshopContentView[]>([]);\n const [cursor, setCursor] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const load = useCallback(\n async (more: boolean) => {\n setBusy(true);\n setError(null);\n if (collection) {\n const r = await host.client.workshop.getCollection(collection);\n if (r.ok) {\n setItems(r.data.Items ?? []);\n setCursor(null);\n } else setError(errorText(r.error));\n } else {\n const r = await host.client.workshop.browse({\n ...query,\n pageSize: 24,\n continuationToken: more ? (cursor ?? undefined) : undefined,\n });\n if (r.ok) {\n setItems((prev) =>\n more ? [...prev, ...(r.data.Items ?? [])] : (r.data.Items ?? []),\n );\n setCursor(r.data.ContinuationToken ?? null);\n } else setError(errorText(r.error));\n }\n setBusy(false);\n },\n [host, query, collection, cursor],\n );\n\n // Reload from the first page whenever the filter changes (not when the cursor does).\n useEffect(() => {\n void load(false);\n }, [query, collection]);\n\n const types = Object.entries(defs.Definitions?.ContentTypes ?? {}).filter(\n ([, t]) => t.Enabled !== false,\n );\n\n return (\n <div>\n {(defs.Collections?.length ?? 0) > 0 && (\n <div style={chipsRow}>\n <button\n style={collection === null ? chipActive : chip}\n onClick={() => setCollection(null)}\n >\n All\n </button>\n {defs.Collections?.map((c) => (\n <button\n key={c.CollectionID ?? \"\"}\n style={collection === c.CollectionID ? chipActive : chip}\n onClick={() => setCollection(c.CollectionID ?? null)}\n >\n ★ {c.Name ?? c.CollectionID}\n </button>\n ))}\n </div>\n )}\n {!collection && (\n <div style={filtersRow}>\n <select\n style={input}\n value={query.contentType ?? \"\"}\n onChange={(e) =>\n setQuery({ ...query, contentType: e.target.value || undefined })\n }\n >\n <option value=\"\">All types</option>\n {types.map(([id, t]) => (\n <option key={id} value={id}>\n {handlers.find((h) => h.type === id)?.label ??\n t.DisplayName ??\n id}\n </option>\n ))}\n </select>\n <select\n style={input}\n value={query.sort ?? \"New\"}\n onChange={(e) =>\n setQuery({\n ...query,\n sort: e.target.value as WorkshopBrowseQuery[\"sort\"],\n })\n }\n >\n <option value=\"New\">Newest</option>\n <option value=\"Popular\">Most acquired</option>\n <option value=\"MostLiked\">Most liked</option>\n </select>\n <input\n style={input}\n placeholder=\"Tag\"\n defaultValue={query.tag ?? \"\"}\n onKeyDown={(e) => {\n if (e.key === \"Enter\")\n setQuery({\n ...query,\n tag: (e.target as HTMLInputElement).value.trim() || undefined,\n });\n }}\n />\n <label style={checkLabel}>\n <input\n type=\"checkbox\"\n checked={query.fromFollowing === true}\n onChange={(e) =>\n setQuery({\n ...query,\n fromFollowing: e.target.checked || undefined,\n })\n }\n />\n From authors I follow\n </label>\n </div>\n )}\n {error && <div style={errorBox}>{error}</div>}\n {items.length === 0 && !busy && (\n <div style={muted}>Nothing here yet.</div>\n )}\n <div style={grid}>\n {items.map((item) => (\n <ContentCard\n key={item.ContentID ?? \"\"}\n item={item}\n handlers={handlers}\n onClick={() => item.ContentID && onOpen(item.ContentID)}\n />\n ))}\n </div>\n {cursor && (\n <button\n style={secondaryBtn}\n disabled={busy}\n onClick={() => void load(true)}\n >\n {busy ? \"Loading…\" : \"Show more\"}\n </button>\n )}\n </div>\n );\n}\n"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"path": "components/ContentCard.tsx",
|
|
55
|
+
"content": "import { type ReactNode } from \"react\";\nimport { type WorkshopContentView } from \"@idosgames/core\";\nimport { type ContentTypeHandler } from \"@idosgames/module-sdk\";\nimport { accessLabel } from \"../labels\";\nimport {\n badge,\n badgeOwned,\n badgeWarn,\n badgesRow,\n card,\n cardMeta,\n cardTitle,\n thumbBox,\n thumbImg,\n} from \"../styles\";\n\nexport function ContentCard({\n item,\n handlers,\n onClick,\n}: {\n item: WorkshopContentView;\n handlers: ContentTypeHandler[];\n onClick(): void;\n}): ReactNode {\n const handler = handlers.find((h) => h.type === item.ContentType);\n return (\n <button style={card} onClick={onClick}>\n <div style={thumbBox}>\n {item.ThumbnailUrl ? (\n <img src={item.ThumbnailUrl} alt=\"\" style={thumbImg} />\n ) : (\n <span style={{ fontSize: 34 }}>{handler?.icon ?? \"📦\"}</span>\n )}\n </div>\n <div style={cardTitle}>\n {item.Title ||\n (item.Status === \"Uploading\" ? \"Unfinished upload\" : \"Untitled\")}\n </div>\n <div style={cardMeta}>\n {item.IsOfficial\n ? \"Official\"\n : (item.CreatorPublicData?.Username ?? \"Player\")}{\" \"}\n · ♥ {item.Stats?.Likes ?? 0}\n </div>\n <div style={badgesRow}>\n {item.IsMine ? (\n <span style={badgeOwned}>Yours</span>\n ) : item.Owned ? (\n <span style={badgeOwned}>In library</span>\n ) : (\n (item.Access ?? []).map((o) => (\n <span key={o.OptionID ?? \"\"} style={badge}>\n {accessLabel(o)}\n </span>\n ))\n )}\n {item.Status && item.Status !== \"Published\" && (\n <span style={badgeWarn}>{item.Status}</span>\n )}\n </div>\n </button>\n );\n}\n\n// ────────────────────────────── Details ──────────────────────────────\n"
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"path": "components/ContentDetails.tsx",
|
|
59
|
+
"content": "import { useCallback, useEffect, useState, type ReactNode } from \"react\";\nimport {\n type WorkshopAccessOption,\n type WorkshopContentResponse,\n type SocialReportReason,\n} from \"@idosgames/core\";\nimport { Modal } from \"./Frame\";\nimport { errorText } from \"../errors\";\nimport { accessLabel, formatBytes } from \"../labels\";\nimport {\n actionsCol,\n badge,\n badgesRow,\n dangerBtn,\n detailsHead,\n detailsThumb,\n disabledBtn,\n errorBox,\n filtersRow,\n input,\n muted,\n noticeBox,\n primaryBtn,\n secondaryBtn,\n thumbImg,\n} from \"../styles\";\nimport { type WorkshopHost } from \"../types\";\n\nconst REPORT_REASONS: SocialReportReason[] = [\n \"Inappropriate\",\n \"Spam\",\n \"Stolen\",\n \"Broken\",\n \"Harassment\",\n \"Other\",\n];\n\nexport function ContentDetails({\n host,\n contentID,\n onClose,\n}: {\n host: WorkshopHost;\n contentID: string;\n onClose(): void;\n}): ReactNode {\n const [data, setData] = useState<WorkshopContentResponse | null>(null);\n const [busy, setBusy] = useState<string | null>(null);\n const [message, setMessage] = useState<string | null>(null);\n const [following, setFollowing] = useState<boolean | null>(null);\n const [reportReason, setReportReason] =\n useState<SocialReportReason>(\"Inappropriate\");\n\n const reload = useCallback(async () => {\n const r = await host.client.workshop.getContent(contentID);\n if (!r.ok) {\n setMessage(errorText(r.error));\n return;\n }\n setData(r.data);\n // Following the author is a social-layer edge on the PLAYER, not part of the card.\n const creator = r.data.Content?.CreatorUserID;\n if (creator && !r.data.Content?.IsMine) {\n const s = await host.client.social.getEntityStates(\"User\", [creator]);\n if (s.ok) setFollowing(s.data.Items?.[0]?.Following === true);\n }\n }, [host, contentID]);\n\n useEffect(() => {\n void reload();\n }, [reload]);\n\n const view = data?.Content;\n const handler = view?.ContentType\n ? host.content.getType(view.ContentType)\n : undefined;\n\n const run = async (\n label: string,\n work: () => Promise<string | null>,\n ): Promise<void> => {\n setBusy(label);\n setMessage(null);\n try {\n setMessage(await work());\n } catch (e) {\n setMessage(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(null);\n }\n };\n\n const open = (): Promise<void> =>\n run(\"open\", async () => {\n if (!view?.ContentID) return null;\n if (!handler?.open)\n return \"This game can't open this type of content here.\";\n const r = await host.client.workshop.downloadFiles(view.ContentID);\n if (!r.ok) return errorText(r.error);\n await handler.open({\n contentID: view.ContentID,\n title: view.Title,\n revision: view.Revision,\n files: r.data.files,\n });\n if (handler.modeId) host.navigate(handler.modeId);\n return null;\n });\n\n const acquire = (option: WorkshopAccessOption): Promise<void> =>\n run(`get:${option.OptionID}`, async () => {\n const r = await host.client.workshop.acquire(contentID, option);\n if (!r.ok) return errorText(r.error);\n await reload();\n return r.data.AlreadyOwned\n ? \"Already in your library.\"\n : \"Added to your library.\";\n });\n\n if (!view) return <Modal onClose={onClose}>{message ?? \"Loading…\"}</Modal>;\n\n const states = new Map(\n (data?.AccessState ?? []).map((s) => [\n s.OptionID ?? \"\",\n s.Available !== false,\n ]),\n );\n const canOpen = Boolean(data?.CanDownload);\n\n return (\n <Modal onClose={onClose}>\n <div style={detailsHead}>\n <div style={detailsThumb}>\n {view.ThumbnailUrl ? (\n <img src={view.ThumbnailUrl} alt=\"\" style={thumbImg} />\n ) : (\n <span style={{ fontSize: 48 }}>{handler?.icon ?? \"📦\"}</span>\n )}\n </div>\n <div style={{ minWidth: 0 }}>\n <h2 style={{ margin: \"0 0 6px\" }}>{view.Title}</h2>\n <div style={muted}>\n {view.IsOfficial\n ? \"Official content\"\n : `by ${view.CreatorPublicData?.Username ?? \"a player\"}`}{\" \"}\n · {handler?.label ?? view.ContentType} · rev. {view.Revision}\n </div>\n <div style={muted}>\n ♥ {view.Stats?.Likes ?? 0} · ★ {view.Stats?.Favorites ?? 0} · ⬇{\" \"}\n {view.Stats?.Acquisitions ?? 0}\n {view.TotalBytes ? ` · ${formatBytes(view.TotalBytes)}` : \"\"}\n </div>\n {(view.Tags?.length ?? 0) > 0 && (\n <div style={badgesRow}>\n {view.Tags?.map((t) => (\n <span key={t} style={badge}>\n #{t}\n </span>\n ))}\n </div>\n )}\n </div>\n </div>\n\n {view.Description && (\n <p style={{ whiteSpace: \"pre-wrap\" }}>{view.Description}</p>\n )}\n {view.IsMine && view.ModerationNote && (\n <div style={errorBox}>Moderation: {view.ModerationNote}</div>\n )}\n {view.IsMine && (view.Access?.length ?? 0) > 0 && (\n <div style={muted}>\n Others get it: {(view.Access ?? []).map(accessLabel).join(\" · \")}\n </div>\n )}\n\n <div style={actionsCol}>\n {canOpen ? (\n <button\n style={primaryBtn}\n disabled={busy !== null || !handler?.open}\n onClick={() => void open()}\n >\n {busy === \"open\"\n ? \"Opening…\"\n : handler?.open\n ? \"Open\"\n : \"Owned (open it in the game)\"}\n </button>\n ) : (\n (view.Access ?? []).map((o) => {\n const available = states.get(o.OptionID ?? \"\") ?? true;\n return (\n <button\n key={o.OptionID ?? \"\"}\n style={available ? primaryBtn : disabledBtn}\n disabled={!available || busy !== null}\n title={\n available\n ? undefined\n : \"You don't meet this option's requirements\"\n }\n onClick={() => void acquire(o)}\n >\n {busy === `get:${o.OptionID}` ? \"…\" : `Get — ${accessLabel(o)}`}\n </button>\n );\n })\n )}\n </div>\n\n <div style={filtersRow}>\n {!view.IsMine && (\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"like\", async () => {\n const r = view.Liked\n ? await host.client.social.unlike(\"WorkshopItem\", contentID)\n : await host.client.social.like(\"WorkshopItem\", contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return null;\n })\n }\n >\n {view.Liked ? \"♥ Liked\" : \"♡ Like\"}\n </button>\n )}\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"fav\", async () => {\n const r = view.Favorited\n ? await host.client.social.unfavorite(\"WorkshopItem\", contentID)\n : await host.client.social.favorite(\"WorkshopItem\", contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return null;\n })\n }\n >\n {view.Favorited ? \"★ In favorites\" : \"☆ Favorite\"}\n </button>\n {!view.IsMine && view.CreatorUserID && (\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"follow\", async () => {\n const creator = view.CreatorUserID ?? \"\";\n const r = following\n ? await host.client.social.unfollow(\"User\", creator)\n : await host.client.social.follow(\"User\", creator);\n if (!r.ok) return errorText(r.error);\n setFollowing(r.data.Following === true);\n return r.data.Following ? \"You follow this author.\" : null;\n })\n }\n >\n {following ? \"Following ✓\" : \"Follow author\"}\n </button>\n )}\n {view.IsMine && view.Status !== \"Removed\" && (\n <button\n style={dangerBtn}\n disabled={busy !== null}\n onClick={() => {\n if (\n !confirm(\n \"Unpublish for good? Players who already have it keep it.\",\n )\n )\n return;\n void run(\"unpublish\", async () => {\n const r = await host.client.workshop.unpublish(contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return \"Unpublished.\";\n });\n }}\n >\n Unpublish\n </button>\n )}\n </div>\n\n {!view.IsMine && (\n <div style={filtersRow}>\n <select\n style={input}\n value={reportReason}\n onChange={(e) =>\n setReportReason(e.target.value as SocialReportReason)\n }\n >\n {REPORT_REASONS.map((r) => (\n <option key={r} value={r}>\n {r}\n </option>\n ))}\n </select>\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"report\", async () => {\n const r = await host.client.social.report(\n \"WorkshopItem\",\n contentID,\n reportReason,\n );\n if (!r.ok) return errorText(r.error);\n return r.data.AlreadyReported\n ? \"You already reported this.\"\n : \"Thanks — the publisher will review it.\";\n })\n }\n >\n Report\n </button>\n </div>\n )}\n\n {message && <div style={noticeBox}>{message}</div>}\n </Modal>\n );\n}\n\n// ────────────────────────────── Publish ──────────────────────────────\n"
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
"path": "components/Frame.tsx",
|
|
63
|
+
"content": "import { type ReactNode } from \"react\";\nimport { backdrop, closeBtn, frame, modal } from \"../styles\";\n\nexport function Frame({ children }: { children: ReactNode }): ReactNode {\n return <div style={frame}>{children}</div>;\n}\n\nexport function Modal({\n children,\n onClose,\n}: {\n children: ReactNode;\n onClose(): void;\n}): ReactNode {\n return (\n <div style={backdrop} onClick={onClose}>\n <div style={modal} onClick={(e) => e.stopPropagation()}>\n <button style={closeBtn} onClick={onClose} aria-label=\"Close\">\n ✕\n </button>\n {children}\n </div>\n </div>\n );\n}\n\n// ────────────────────────────── styles ──────────────────────────────\n// Every colour is a theme token of the UI kit (the project's src/ui.config.ts), like every other\n// system — the workshop must not be a dark island in a light app. Change the theme, not these.\n"
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"path": "components/MyList.tsx",
|
|
67
|
+
"content": "import { useEffect, useState, type ReactNode } from \"react\";\nimport { type WorkshopContentView } from \"@idosgames/core\";\nimport { ContentCard } from \"./ContentCard\";\nimport { errorText } from \"../errors\";\nimport { useContentTypes } from \"../hooks\";\nimport { errorBox, grid, muted } from \"../styles\";\nimport { type WorkshopHost } from \"../types\";\n\nexport function MyList({\n host,\n kind,\n onOpen,\n}: {\n host: WorkshopHost;\n kind: \"mine\" | \"licenses\" | \"favorites\";\n onOpen(id: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content);\n const [items, setItems] = useState<WorkshopContentView[] | null>(null);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n let alive = true;\n const load = async (): Promise<void> => {\n const w = host.client.workshop;\n if (kind === \"licenses\") {\n const r = await w.getMyLicenses();\n if (!alive) return;\n if (r.ok)\n setItems(\n (r.data.Licenses ?? [])\n .map((l) => l.Content)\n .filter((c): c is WorkshopContentView => Boolean(c)),\n );\n else setError(errorText(r.error));\n return;\n }\n const r =\n kind === \"mine\" ? await w.getMyContent() : await w.getMyFavorites();\n if (!alive) return;\n if (r.ok) setItems(r.data.Items ?? []);\n else setError(errorText(r.error));\n };\n void load();\n return () => {\n alive = false;\n };\n }, [host, kind]);\n\n if (error) return <div style={errorBox}>{error}</div>;\n if (!items) return <div style={muted}>Loading…</div>;\n if (items.length === 0) return <div style={muted}>Empty.</div>;\n return (\n <div style={grid}>\n {items.map((item) => (\n <ContentCard\n key={item.ContentID ?? \"\"}\n item={item}\n handlers={handlers}\n onClick={() => item.ContentID && onOpen(item.ContentID)}\n />\n ))}\n </div>\n );\n}\n\n// ────────────────────────────── helpers ──────────────────────────────\n"
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"path": "components/PublishWizard.tsx",
|
|
71
|
+
"content": "import { useEffect, useState, type ReactNode } from \"react\";\nimport {\n type WorkshopAccessOptionInput,\n type WorkshopDefinitionsResponse,\n type WorkshopVisibility,\n} from \"@idosgames/core\";\nimport { errorText } from \"../errors\";\nimport { useContentTypes, useResourceOptions } from \"../hooks\";\nimport { bundleLabel } from \"../labels\";\nimport {\n checkLabel,\n chip,\n chipActive,\n chipsRow,\n errorBox,\n fieldLabel,\n filtersRow,\n formCol,\n input,\n muted,\n primaryBtn,\n secondaryBtn,\n} from \"../styles\";\nimport { type WorkshopHost } from \"../types\";\n\ninterface AccessDraft {\n mode: \"Free\" | \"Price\" | \"Holding\";\n resource: string; // \"vc:GOLD\" | \"cc:USDT\" | \"item:<catalog>/<item>\"\n amount: number;\n holdMode: \"WhileHeld\" | \"UnlockOnce\";\n}\n\nexport function PublishWizard({\n host,\n defs,\n onDone,\n}: {\n host: WorkshopHost;\n defs: WorkshopDefinitionsResponse;\n onDone(contentID: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content).filter(\n (h) => h.listLocal && h.capture && defs.CanPublish?.[h.type] === true,\n );\n const [type, setType] = useState<string | null>(null);\n const [locals, setLocals] = useState<Array<{\n id: string;\n name: string;\n subtitle?: string;\n }> | null>(null);\n const [localId, setLocalId] = useState<string | null>(null);\n const [title, setTitle] = useState(\"\");\n const [description, setDescription] = useState(\"\");\n const [tags, setTags] = useState(\"\");\n const [visibility, setVisibility] = useState<WorkshopVisibility>(\"Public\");\n const [access, setAccess] = useState<AccessDraft[]>([\n { mode: \"Free\", resource: \"\", amount: 1, holdMode: \"UnlockOnce\" },\n ]);\n const [busy, setBusy] = useState(false);\n const [message, setMessage] = useState<string | null>(null);\n\n const handler = handlers.find((h) => h.type === type);\n const typeDef = type ? defs.Definitions?.ContentTypes?.[type] : undefined;\n const allowedModes = typeDef?.AllowedAccessModes?.length\n ? typeDef.AllowedAccessModes\n : [\"Free\", \"Price\", \"Holding\"];\n const resources = useResourceOptions(host.client);\n // Плата за публикацию берётся только ресурсами: вариант с оплатой в сторе сервер отвергнет.\n const fee = Object.entries(typeDef?.PublishFeeOptions ?? {}).find(\n ([, option]) =>\n !(option?.Cost?.Standard?.Entries ?? []).some(\n (e) => e?.Type === \"Purchase\",\n ),\n );\n\n useEffect(() => {\n setLocals(null);\n setLocalId(null);\n if (!handler?.listLocal) return;\n void handler\n .listLocal()\n .then(setLocals, (e: unknown) =>\n setMessage(e instanceof Error ? e.message : String(e)),\n );\n }, [handler]);\n\n if (handlers.length === 0)\n return (\n <div style={muted}>\n Nothing to publish from here: the games in this project either do not\n register their content, or you can't publish it yet.\n </div>\n );\n\n const publish = async (): Promise<void> => {\n if (!handler?.capture || !type || !localId) return;\n // Опция без ресурса молча выпала бы из списка, и публикация ушла бы не с теми способами получить.\n if (access.some((a) => a.mode !== \"Free\" && !a.resource)) {\n setMessage(\"Pick a resource for every paid or hold-to-unlock option.\");\n return;\n }\n setBusy(true);\n setMessage(null);\n try {\n const captured = await handler.capture(localId);\n const r = await host.client.workshop.publish({\n contentType: type,\n files: captured.files,\n thumbnail: captured.thumbnail,\n title: title.trim() || captured.suggestedTitle || \"Untitled\",\n description: description.trim() || captured.suggestedDescription,\n tags: tags\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean)\n .concat(captured.tags ?? []),\n metadata: captured.metadata,\n visibility,\n access: access\n .map(toAccessInput)\n .filter((a): a is WorkshopAccessOptionInput => a !== null),\n selectedFeeOptionID: fee?.[0],\n });\n if (!r.ok) setMessage(errorText(r.error));\n else if (r.data.Content?.ContentID) onDone(r.data.Content.ContentID);\n } catch (e) {\n setMessage(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n return (\n <div style={formCol}>\n <label style={fieldLabel}>What</label>\n <div style={chipsRow}>\n {handlers.map((h) => (\n <button\n key={h.type}\n style={type === h.type ? chipActive : chip}\n onClick={() => setType(h.type)}\n >\n {h.icon} {h.label}\n </button>\n ))}\n </div>\n\n {handler && (\n <>\n <label style={fieldLabel}>Which one</label>\n {!locals ? (\n <div style={muted}>Loading…</div>\n ) : locals.length === 0 ? (\n <div style={muted}>You have nothing of this type yet.</div>\n ) : (\n <div style={formCol}>\n {locals.map((l) => (\n <label key={l.id} style={checkLabel}>\n <input\n type=\"radio\"\n name=\"wsLocal\"\n checked={localId === l.id}\n onChange={() => {\n setLocalId(l.id);\n if (!title) setTitle(l.name);\n }}\n />\n {l.name}{\" \"}\n {l.subtitle && <span style={muted}>· {l.subtitle}</span>}\n </label>\n ))}\n </div>\n )}\n </>\n )}\n\n {localId && (\n <>\n <label style={fieldLabel}>Title</label>\n <input\n style={input}\n value={title}\n maxLength={defs.Definitions?.Limits?.MaxTitleLength ?? 60}\n onChange={(e) => setTitle(e.target.value)}\n />\n <label style={fieldLabel}>Description</label>\n <textarea\n style={{ ...input, minHeight: 70 }}\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n />\n <label style={fieldLabel}>\n Tags (comma separated\n {typeDef?.TagVocabulary?.length\n ? `: ${typeDef.TagVocabulary.join(\", \")}`\n : \"\"}\n )\n </label>\n <input\n style={input}\n value={tags}\n onChange={(e) => setTags(e.target.value)}\n />\n <label style={fieldLabel}>Who can see it</label>\n <select\n style={input}\n value={visibility}\n onChange={(e) =>\n setVisibility(e.target.value as WorkshopVisibility)\n }\n >\n <option value=\"Public\">Everyone (in the catalog)</option>\n <option value=\"Unlisted\">Anyone with the link</option>\n <option value=\"Friends\">Only my friends</option>\n </select>\n\n <label style={fieldLabel}>How others get it — any option works</label>\n {access.map((a, i) => (\n <div key={i} style={filtersRow}>\n <select\n style={input}\n value={a.mode}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n mode: e.target.value as AccessDraft[\"mode\"],\n }),\n )\n }\n >\n {allowedModes.map((m) => (\n <option key={m} value={m}>\n {m === \"Free\"\n ? \"Free\"\n : m === \"Price\"\n ? \"For resources\"\n : \"Hold to unlock\"}\n </option>\n ))}\n </select>\n {a.mode !== \"Free\" && (\n <>\n <select\n style={input}\n value={a.resource}\n onChange={(e) =>\n setAccess(patch(access, i, { resource: e.target.value }))\n }\n >\n <option value=\"\">— resource —</option>\n {resources\n .filter((r) =>\n // A price: an in-game currency or crypto (the author gets it minus the developer's trade\n // fee). Holding: currencies and items — crypto is not a \"hold to unlock\" resource.\n a.mode === \"Holding\"\n ? !r.startsWith(\"cc:\")\n : r.startsWith(\"vc:\") || r.startsWith(\"cc:\"),\n )\n .map((r) => (\n <option key={r} value={r}>\n {r\n .replace(/^vc:/, \"\")\n .replace(/^cc:/, \"crypto \")\n .replace(/^item:/, \"item \")}\n </option>\n ))}\n </select>\n <input\n style={{ ...input, width: 90 }}\n type=\"number\"\n min={1}\n value={a.amount}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n amount: Math.max(1, Number(e.target.value) || 1),\n }),\n )\n }\n />\n </>\n )}\n {a.mode === \"Holding\" && (\n <select\n style={input}\n value={a.holdMode}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n holdMode: e.target.value as AccessDraft[\"holdMode\"],\n }),\n )\n }\n >\n <option value=\"UnlockOnce\">Checked once, then forever</option>\n <option value=\"WhileHeld\">Only while they hold it</option>\n </select>\n )}\n {access.length > 1 && (\n <button\n style={secondaryBtn}\n onClick={() => setAccess(access.filter((_, j) => j !== i))}\n >\n ✕\n </button>\n )}\n </div>\n ))}\n <button\n style={secondaryBtn}\n onClick={() =>\n setAccess([\n ...access,\n {\n mode: allowedModes.includes(\"Price\") ? \"Price\" : \"Free\",\n resource: \"\",\n amount: 10,\n holdMode: \"UnlockOnce\",\n },\n ])\n }\n >\n + Add an option\n </button>\n\n {fee && (\n <div style={muted}>\n Publishing costs {bundleLabel(fee[1].Cost?.Standard)} (charged\n once).\n </div>\n )}\n <button\n style={primaryBtn}\n disabled={busy}\n onClick={() => void publish()}\n >\n {busy ? \"Publishing…\" : \"Publish\"}\n </button>\n </>\n )}\n {message && <div style={errorBox}>{message}</div>}\n </div>\n );\n}\n\nfunction patch<T>(list: T[], index: number, change: Partial<T>): T[] {\n return list.map((item, i) => (i === index ? { ...item, ...change } : item));\n}\n\nfunction toAccessInput(a: AccessDraft): WorkshopAccessOptionInput | null {\n if (a.mode === \"Free\") return { Mode: \"Free\" };\n if (!a.resource) return null;\n const [kind, id = \"\"] = a.resource.split(\":\", 2);\n if (a.mode === \"Price\") {\n return {\n Mode: \"Price\",\n Price: {\n Entries: [\n {\n Type: kind === \"cc\" ? \"CryptoCurrency\" : \"VirtualCurrency\",\n CurrencyID: id,\n Amount: a.amount,\n },\n ],\n },\n };\n }\n const [catalogID, itemID] = id.split(\"/\", 2);\n return {\n Mode: \"Holding\",\n Holding: {\n Mode: a.holdMode,\n Match: \"All\",\n Requirements: [\n kind === \"vc\"\n ? { Type: \"VirtualCurrency\", CurrencyID: id, Amount: a.amount }\n : {\n Type: \"Item\",\n CatalogID: catalogID,\n ItemID: itemID ?? \"\",\n Amount: a.amount,\n },\n ],\n },\n };\n}\n\n// ────────────────────────────── Lists ──────────────────────────────\n"
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
"path": "errors.ts",
|
|
75
|
+
"content": "/** Server error codes → words. Anything else is shown as is (it is already a sentence). */\nconst ERRORS: Record<string, string> = {\n WORKSHOP_DISABLED: \"The Workshop is turned off.\",\n WORKSHOP_NOT_CONFIGURED: \"The Workshop is not set up in this game yet.\",\n WORKSHOP_NOT_AVAILABLE: \"The Workshop is not available to you.\",\n WORKSHOP_CLOSED: \"The Workshop is closed right now.\",\n PRICE_CHANGED: \"The author changed the price — look at it again.\",\n HOLDING_REQUIREMENTS_NOT_MET: \"You don't hold what this option requires.\",\n ACCESS_DENIED: \"You don't have access to this yet.\",\n CONTENT_NOT_FOUND: \"Not found (or not shared with you).\",\n CONTENT_NOT_AVAILABLE: \"This publication is not available now.\",\n CONTENT_TEXT_REJECTED:\n \"The title or description contains words that are not allowed.\",\n PUBLISH_LIMIT_REACHED:\n \"You have reached the limit of publications of this type.\",\n DAILY_PUBLISH_LIMIT_REACHED: \"You have reached today's publishing limit.\",\n PUBLISH_NOT_ALLOWED: \"You can't publish this type of content yet.\",\n CANNOT_LIKE_OWN_CONTENT: \"You can't like your own publication.\",\n WORKSHOP_STORAGE_NOT_CONFIGURED:\n \"File storage is not configured for this game.\",\n TOO_MANY_PENDING_UPLOADS:\n \"You have too many unfinished uploads — try again a bit later.\",\n ACCESS_REQUIRED: \"Add at least one way for others to get it.\",\n OPTION_REQUIRED: \"Choose how you want to get it.\",\n PRICE_NO_LONGER_ALLOWED: \"This price is no longer allowed in this game.\",\n TITLE_REQUIRED: \"Give it a title.\",\n TITLE_TOO_LONG: \"The title is too long.\",\n THUMBNAIL_REQUIRED: \"This type of content needs a preview image.\",\n FILE_TOO_LARGE: \"The file is too large for this type of content.\",\n FILE_TYPE_MISMATCH: \"The file does not match its declared format.\",\n CONTENT_TYPE_NOT_ALLOWED:\n \"This type of content can't be published in this game.\",\n CANNOT_REPORT_OWN_CONTENT: \"You can't report your own publication.\",\n CANNOT_FOLLOW_SELF: \"You can't follow yourself.\",\n};\n\nexport const errorText = (e: string): string => ERRORS[e] ?? e;\n"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"path": "hooks.ts",
|
|
79
|
+
"content": "import { useEffect, useState } from \"react\";\nimport {\n type ContentRegistry,\n type ContentTypeHandler,\n type IDosGamesClient,\n} from \"@idosgames/module-sdk\";\n\n/**\n * Registered content types, re-read on every registry change. ⚠ Not keyed by the NUMBER of types: a game\n * re-installed after re-login registers the same type again with a new handler, the count stays the\n * same, and a count-based snapshot kept the handler of the destroyed game.\n */\nexport function useContentTypes(\n content: ContentRegistry,\n): ContentTypeHandler[] {\n const [types, setTypes] = useState(() => content.listTypes());\n useEffect(() => {\n setTypes(content.listTypes());\n return content.subscribe(() => setTypes(content.listTypes()));\n }, [content]);\n return types;\n}\n\n/**\n * \"vc:GOLD\", \"cc:USDT\" and \"item:<catalog>/<item>\" for every currency, crypto currency and item the title defines\n * (the engine still checks the Workshop price policy — crypto needs `AllowCryptoCurrency`).\n */\nexport function useResourceOptions(client: IDosGamesClient): string[] {\n const [list] = useState(() => {\n const out: string[] = [];\n for (const id of Object.keys(\n client.data.config.currencyDefinitions?.VirtualCurrencies ?? {},\n ))\n out.push(`vc:${id}`);\n for (const id of Object.keys(\n client.data.config.currencyDefinitions?.CryptoCurrencies ?? {},\n ))\n out.push(`cc:${id}`);\n for (const [catalogID, catalog] of Object.entries(\n client.data.config.itemDefinitions?.Catalogs ?? {},\n ))\n for (const itemID of Object.keys(catalog?.Items ?? {}))\n out.push(`item:${catalogID}/${itemID}`);\n return out;\n });\n return list;\n}\n"
|
|
80
|
+
},
|
|
49
81
|
{
|
|
50
82
|
"path": "i18n.ts",
|
|
51
83
|
"content": "import { makeT } from \"@idosgames/react/ui\";\n\n// The Workshop's name in the lobby. The screen itself speaks English for now.\n\nconst EN = {\n title: \"Workshop\",\n} as const;\n\nexport type StringKey = keyof typeof EN;\n\nexport const t = makeT<StringKey>(EN, {\n title: \"Мастерская\",\n});\n"
|
|
52
84
|
},
|
|
53
85
|
{
|
|
54
86
|
"path": "index.ts",
|
|
55
|
-
"content": "// @idosgames/mod-workshop — the Workshop: player & publisher content and licenses, for any game.\n//\n// Primary export is the module manifest; the React screen is exported too so a project can place it\n// elsewhere (a modal, a mode of its own) after copying this into src/modules/.\n\nexport { workshopModule } from \"./module\";\nexport {
|
|
87
|
+
"content": "// @idosgames/mod-workshop — the Workshop: player & publisher content and licenses, for any game.\n//\n// Primary export is the module manifest; the React screen is exported too so a project can place it\n// elsewhere (a modal, a mode of its own) after copying this into src/modules/.\n\nexport { workshopModule } from \"./module\";\nexport { makeWorkshopScreen, WorkshopApp } from \"./WorkshopApp\";\nexport type { WorkshopHost } from \"./types\";\n"
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
"path": "labels.ts",
|
|
91
|
+
"content": "import { type WorkshopAccessOption } from \"@idosgames/core\";\n\ntype BundleLike =\n | {\n Entries?: Array<{\n CurrencyID?: string | null;\n ItemID?: string | null;\n Amount?: number | null;\n } | null> | null;\n }\n | null\n | undefined;\n\nexport function bundleLabel(bundle: BundleLike): string {\n const parts = (bundle?.Entries ?? [])\n .filter((e): e is NonNullable<typeof e> => Boolean(e))\n .map((e) => `${e.Amount ?? 0} ${e.CurrencyID ?? e.ItemID ?? \"\"}`.trim());\n return parts.length ? parts.join(\" + \") : \"free\";\n}\n\nexport function accessLabel(o: WorkshopAccessOption): string {\n if (o.Mode === \"Free\") return \"Free\";\n if (o.Mode === \"Price\") return bundleLabel(o.Price);\n const reqs = (o.Holding?.Requirements ?? []).map(\n (r) =>\n `${r.Amount ?? 0} ${r.CurrencyID ?? r.ItemID ?? \"\"}${r.MinLevel ? ` (lvl ${r.MinLevel}+)` : \"\"}`,\n );\n const joined = reqs.join(o.Holding?.Match === \"Any\" ? \" or \" : \" + \");\n return `🔑 hold ${joined}${o.Holding?.Mode === \"WhileHeld\" ? \" (while held)\" : \"\"}`;\n}\n\nexport function formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;\n return `${(n / 1024 / 1024).toFixed(1)} MB`;\n}\n"
|
|
56
92
|
},
|
|
57
93
|
{
|
|
58
94
|
"path": "module.ts",
|
|
59
95
|
"content": "import { defineModule, type Module } from \"@idosgames/module-sdk\";\nimport { makeWorkshopScreen } from \"./WorkshopApp\";\nimport { t } from \"./i18n\";\n\n// The Workshop system: a tab of the lobby (ctx.features) with the catalog of player & publisher\n// content. It works for any game — what a content type IS (how to list, capture and open it) comes\n// from the handlers games register in `ctx.content`; the Workshop never imports a game. With no game\n// that registers a content type there is nothing to share, and the tab stays hidden.\nexport const workshopModule: Module = defineModule({\n id: \"workshop\",\n meta: {\n name: \"Workshop\",\n type: \"app\",\n engine: \"dom\",\n },\n setup(ctx) {\n ctx.features.register({\n id: \"workshop\",\n label: t(\"title\"),\n icon: \"globe\",\n group: \"social\",\n order: 88,\n available: false,\n Screen: makeWorkshopScreen({\n client: ctx.client,\n content: ctx.content,\n navigate: (modeId) => ctx.navigate(modeId),\n }),\n });\n\n // Games register their content types in their own setup() — before or after this one — so the\n // tab follows the registry instead of looking once.\n const sync = (): void =>\n ctx.features.setAvailable(\n \"workshop\",\n ctx.content.listTypes().length > 0,\n \"no installed game registers a content type (ctx.content.registerType)\",\n );\n sync();\n ctx.content.subscribe(sync);\n\n ctx.exposeToAgent({\n state: () => ({\n contentTypes: ctx.content.listTypes().map((type) => ({\n type: type.type,\n canPublish: Boolean(type.listLocal && type.capture),\n canOpen: Boolean(type.open),\n })),\n }),\n describeActions: {},\n });\n },\n});\n"
|
|
60
96
|
},
|
|
97
|
+
{
|
|
98
|
+
"path": "styles.ts",
|
|
99
|
+
"content": "import { type CSSProperties } from \"react\";\nimport { buttonStyle, panel, v } from \"@idosgames/react/ui\";\n\nexport const frame: CSSProperties = {\n // A tab of the lobby: the lobby scrolls it and gives it the width.\n minHeight: 360,\n borderRadius: 16,\n padding: \"16px 20px 40px\",\n ...panel,\n color: v.text,\n fontFamily: v.font,\n pointerEvents: \"auto\",\n};\n\nexport const tabsRow: CSSProperties = {\n display: \"flex\",\n gap: 6,\n flexWrap: \"wrap\",\n marginBottom: 14,\n};\n\nexport const tabBtn: CSSProperties = {\n background: \"transparent\",\n color: v.textDim,\n border: `1px solid ${v.line}`,\n borderRadius: 8,\n padding: \"6px 12px\",\n cursor: \"pointer\",\n};\n\nexport const tabActive: CSSProperties = {\n ...tabBtn,\n background: `linear-gradient(180deg, ${v.blue}, ${v.blueDeep})`,\n color: v.onBlue,\n border: \"1px solid transparent\",\n};\n\nexport const chipsRow: CSSProperties = {\n display: \"flex\",\n gap: 6,\n flexWrap: \"wrap\",\n margin: \"8px 0\",\n};\n\nexport const chip: CSSProperties = {\n ...tabBtn,\n borderRadius: 999,\n padding: \"4px 10px\",\n fontSize: 13,\n};\n\nexport const chipActive: CSSProperties = {\n ...chip,\n background: `color-mix(in srgb, ${v.blue} 30%, transparent)`,\n color: v.text,\n};\n\nexport const filtersRow: CSSProperties = {\n display: \"flex\",\n gap: 8,\n flexWrap: \"wrap\",\n alignItems: \"center\",\n margin: \"8px 0\",\n};\n\nexport const input: CSSProperties = {\n background: v.well,\n color: v.text,\n border: `1px solid ${v.line}`,\n boxShadow: v.wellShadow,\n borderRadius: 6,\n padding: \"6px 8px\",\n font: \"inherit\",\n};\n\nexport const checkLabel: CSSProperties = {\n display: \"flex\",\n gap: 6,\n alignItems: \"center\",\n fontSize: 14,\n};\n\nexport const grid: CSSProperties = {\n display: \"grid\",\n gridTemplateColumns: \"repeat(auto-fill, minmax(170px, 1fr))\",\n gap: 12,\n};\n\nexport const card: CSSProperties = {\n textAlign: \"left\",\n background: v.panelDeep,\n border: `1px solid ${v.panelEdge}`,\n borderRadius: 10,\n padding: 8,\n color: \"inherit\",\n cursor: \"pointer\",\n font: \"inherit\",\n};\n\nexport const thumbBox: CSSProperties = {\n aspectRatio: \"1 / 1\",\n borderRadius: 8,\n background: v.wellSoft,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n};\n\nexport const thumbImg: CSSProperties = {\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n imageRendering: \"pixelated\",\n};\n\nexport const cardTitle: CSSProperties = {\n fontWeight: 600,\n margin: \"6px 0 2px\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n};\n\nexport const cardMeta: CSSProperties = { fontSize: 12, color: v.textDim };\n\nexport const badgesRow: CSSProperties = {\n display: \"flex\",\n gap: 4,\n flexWrap: \"wrap\",\n marginTop: 6,\n};\n\nexport const badge: CSSProperties = {\n fontSize: 11,\n background: v.wellSoft,\n color: v.text,\n borderRadius: 4,\n padding: \"2px 6px\",\n};\n\nexport const badgeOwned: CSSProperties = {\n ...badge,\n background: `color-mix(in srgb, ${v.green} 35%, transparent)`,\n};\n\nexport const badgeWarn: CSSProperties = {\n ...badge,\n background: `color-mix(in srgb, ${v.gold} 35%, transparent)`,\n};\n\nexport const muted: CSSProperties = { color: v.textDim, fontSize: 13 };\n\nexport const errorBox: CSSProperties = {\n background: `color-mix(in srgb, ${v.red} 18%, transparent)`,\n border: `1px solid color-mix(in srgb, ${v.red} 45%, transparent)`,\n color: v.text,\n borderRadius: 6,\n padding: \"8px 10px\",\n margin: \"8px 0\",\n};\n\nexport const noticeBox: CSSProperties = {\n background: `color-mix(in srgb, ${v.blue} 16%, transparent)`,\n borderRadius: 6,\n padding: \"8px 10px\",\n marginTop: 10,\n};\n\nexport const primaryBtn: CSSProperties = {\n ...buttonStyle(\"blue\", false, \"sm\"),\n font: \"inherit\",\n fontWeight: 800,\n};\n\nexport const disabledBtn: CSSProperties = {\n ...buttonStyle(\"blue\", true, \"sm\"),\n font: \"inherit\",\n fontWeight: 800,\n cursor: \"not-allowed\",\n};\n\nexport const secondaryBtn: CSSProperties = { ...tabBtn, color: v.text };\n\nexport const dangerBtn: CSSProperties = {\n ...tabBtn,\n color: v.red,\n border: `1px solid color-mix(in srgb, ${v.red} 50%, transparent)`,\n};\n\nexport const actionsCol: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n gap: 8,\n margin: \"12px 0\",\n};\n\nexport const formCol: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n gap: 6,\n maxWidth: 640,\n};\n\nexport const fieldLabel: CSSProperties = {\n fontSize: 13,\n color: v.textDim,\n marginTop: 8,\n};\n\nexport const backdrop: CSSProperties = {\n position: \"fixed\",\n inset: 0,\n background: v.backdrop,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n zIndex: 50,\n};\n\nexport const modal: CSSProperties = {\n position: \"relative\",\n ...panel,\n color: v.text,\n padding: 20,\n width: \"min(640px, 94vw)\",\n maxHeight: \"90vh\",\n overflow: \"auto\",\n};\n\nexport const closeBtn: CSSProperties = {\n position: \"absolute\",\n top: 10,\n right: 10,\n background: \"transparent\",\n color: v.textDim,\n border: 0,\n fontSize: 18,\n cursor: \"pointer\",\n};\n\nexport const detailsHead: CSSProperties = {\n display: \"flex\",\n gap: 14,\n alignItems: \"flex-start\",\n marginRight: 24,\n};\n\nexport const detailsThumb: CSSProperties = {\n ...thumbBox,\n width: 120,\n flex: \"0 0 120px\",\n};\n"
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
"path": "types.ts",
|
|
103
|
+
"content": "import {\n type ContentRegistry,\n type IDosGamesClient,\n} from \"@idosgames/module-sdk\";\n\n/** What the panel needs from the host — the module passes it in at setup(). */\nexport interface WorkshopHost {\n client: IDosGamesClient;\n content: ContentRegistry;\n navigate(modeId: string): void;\n}\n"
|
|
104
|
+
},
|
|
61
105
|
{
|
|
62
106
|
"path": "WorkshopApp.tsx",
|
|
63
|
-
"content": "import {\n useCallback,\n useEffect,\n useState,\n type ComponentType,\n type CSSProperties,\n type ReactNode,\n} from \"react\";\nimport type {\n WorkshopAccessOption,\n WorkshopAccessOptionInput,\n WorkshopBrowseQuery,\n WorkshopContentResponse,\n WorkshopContentView,\n WorkshopDefinitionsResponse,\n SocialReportReason,\n WorkshopVisibility,\n} from \"@idosgames/core\";\nimport type {\n ContentRegistry,\n ContentTypeHandler,\n FeatureScreenProps,\n IDosGamesClient,\n} from \"@idosgames/module-sdk\";\nimport { buttonStyle, panel, v } from \"@idosgames/react/ui\";\n\n// The Workshop screen: catalog, content card, publish wizard, \"mine / licenses / favorites\".\n//\n// It is the same for every game. Everything game-specific comes from two places: the title's Workshop\n// config (which types exist, formats, access modes — read via client.workshop.getDefinitions()) and the\n// handlers games register in ctx.content (how to list, capture and open their content). This file is\n// plain editable React with inline styles — restyle or replace it like any other module source.\n\n/** What the panel needs from the host — the module passes it in at setup(). */\nexport interface WorkshopHost {\n client: IDosGamesClient;\n content: ContentRegistry;\n navigate(modeId: string): void;\n}\n\n/** The Workshop as a tab of the lobby (a feature screen); `navigate` hands the screen to a game. */\nexport function makeWorkshopScreen(\n host: WorkshopHost,\n): ComponentType<FeatureScreenProps> {\n return function WorkshopScreen(): ReactNode {\n return <WorkshopApp host={host} />;\n };\n}\n\ntype Tab = \"catalog\" | \"publish\" | \"mine\" | \"licenses\" | \"favorites\";\n\nconst TABS: Array<[Tab, string]> = [\n [\"catalog\", \"Catalog\"],\n [\"publish\", \"Publish\"],\n [\"mine\", \"My content\"],\n [\"licenses\", \"My library\"],\n [\"favorites\", \"Favorites\"],\n];\n\n/** Server error codes → words. Anything else is shown as is (it is already a sentence). */\nconst ERRORS: Record<string, string> = {\n WORKSHOP_DISABLED: \"The Workshop is turned off.\",\n WORKSHOP_NOT_CONFIGURED: \"The Workshop is not set up in this game yet.\",\n WORKSHOP_NOT_AVAILABLE: \"The Workshop is not available to you.\",\n WORKSHOP_CLOSED: \"The Workshop is closed right now.\",\n PRICE_CHANGED: \"The author changed the price — look at it again.\",\n HOLDING_REQUIREMENTS_NOT_MET: \"You don't hold what this option requires.\",\n ACCESS_DENIED: \"You don't have access to this yet.\",\n CONTENT_NOT_FOUND: \"Not found (or not shared with you).\",\n CONTENT_NOT_AVAILABLE: \"This publication is not available now.\",\n CONTENT_TEXT_REJECTED:\n \"The title or description contains words that are not allowed.\",\n PUBLISH_LIMIT_REACHED:\n \"You have reached the limit of publications of this type.\",\n DAILY_PUBLISH_LIMIT_REACHED: \"You have reached today's publishing limit.\",\n PUBLISH_NOT_ALLOWED: \"You can't publish this type of content yet.\",\n CANNOT_LIKE_OWN_CONTENT: \"You can't like your own publication.\",\n WORKSHOP_STORAGE_NOT_CONFIGURED:\n \"File storage is not configured for this game.\",\n TOO_MANY_PENDING_UPLOADS:\n \"You have too many unfinished uploads — try again a bit later.\",\n ACCESS_REQUIRED: \"Add at least one way for others to get it.\",\n OPTION_REQUIRED: \"Choose how you want to get it.\",\n PRICE_NO_LONGER_ALLOWED: \"This price is no longer allowed in this game.\",\n TITLE_REQUIRED: \"Give it a title.\",\n TITLE_TOO_LONG: \"The title is too long.\",\n THUMBNAIL_REQUIRED: \"This type of content needs a preview image.\",\n FILE_TOO_LARGE: \"The file is too large for this type of content.\",\n FILE_TYPE_MISMATCH: \"The file does not match its declared format.\",\n CONTENT_TYPE_NOT_ALLOWED:\n \"This type of content can't be published in this game.\",\n CANNOT_REPORT_OWN_CONTENT: \"You can't report your own publication.\",\n CANNOT_FOLLOW_SELF: \"You can't follow yourself.\",\n};\nconst errorText = (e: string): string => ERRORS[e] ?? e;\n\nexport function WorkshopApp({ host }: { host: WorkshopHost }): ReactNode {\n const [defs, setDefs] = useState<WorkshopDefinitionsResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [tab, setTab] = useState<Tab>(\"catalog\");\n const [openID, setOpenID] = useState<string | null>(null);\n\n useEffect(() => {\n let alive = true;\n void host.client.workshop.getDefinitions().then((r) => {\n if (!alive) return;\n if (r.ok) setDefs(r.data);\n else setError(errorText(r.error));\n });\n return () => {\n alive = false;\n };\n }, [host]);\n\n if (!defs) return <Frame>{error ?? \"Loading the Workshop…\"}</Frame>;\n if (!defs.Definitions?.Enabled || !defs.GatePassed)\n return <Frame>The Workshop is not available in this game right now.</Frame>;\n\n return (\n <Frame>\n <div style={tabsRow}>\n {TABS.map(([id, label]) => (\n <button\n key={id}\n style={id === tab ? tabActive : tabBtn}\n onClick={() => setTab(id)}\n >\n {label}\n </button>\n ))}\n </div>\n {tab === \"catalog\" && (\n <Catalog host={host} defs={defs} onOpen={setOpenID} />\n )}\n {tab === \"publish\" && (\n <PublishWizard\n host={host}\n defs={defs}\n onDone={(id) => {\n setTab(\"mine\");\n setOpenID(id);\n }}\n />\n )}\n {tab === \"mine\" && <MyList host={host} kind=\"mine\" onOpen={setOpenID} />}\n {tab === \"licenses\" && (\n <MyList host={host} kind=\"licenses\" onOpen={setOpenID} />\n )}\n {tab === \"favorites\" && (\n <MyList host={host} kind=\"favorites\" onOpen={setOpenID} />\n )}\n {openID && (\n <ContentDetails\n host={host}\n contentID={openID}\n onClose={() => setOpenID(null)}\n />\n )}\n </Frame>\n );\n}\n\n// ────────────────────────────── Catalog ──────────────────────────────\n\nfunction Catalog({\n host,\n defs,\n onOpen,\n}: {\n host: WorkshopHost;\n defs: WorkshopDefinitionsResponse;\n onOpen(id: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content);\n const [query, setQuery] = useState<WorkshopBrowseQuery>({ sort: \"New\" });\n const [collection, setCollection] = useState<string | null>(null);\n const [items, setItems] = useState<WorkshopContentView[]>([]);\n const [cursor, setCursor] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const load = useCallback(\n async (more: boolean) => {\n setBusy(true);\n setError(null);\n if (collection) {\n const r = await host.client.workshop.getCollection(collection);\n if (r.ok) {\n setItems(r.data.Items ?? []);\n setCursor(null);\n } else setError(errorText(r.error));\n } else {\n const r = await host.client.workshop.browse({\n ...query,\n pageSize: 24,\n continuationToken: more ? (cursor ?? undefined) : undefined,\n });\n if (r.ok) {\n setItems((prev) =>\n more ? [...prev, ...(r.data.Items ?? [])] : (r.data.Items ?? []),\n );\n setCursor(r.data.ContinuationToken ?? null);\n } else setError(errorText(r.error));\n }\n setBusy(false);\n },\n [host, query, collection, cursor],\n );\n\n // Reload from the first page whenever the filter changes (not when the cursor does).\n useEffect(() => {\n void load(false);\n }, [query, collection]);\n\n const types = Object.entries(defs.Definitions?.ContentTypes ?? {}).filter(\n ([, t]) => t.Enabled !== false,\n );\n\n return (\n <div>\n {(defs.Collections?.length ?? 0) > 0 && (\n <div style={chipsRow}>\n <button\n style={collection === null ? chipActive : chip}\n onClick={() => setCollection(null)}\n >\n All\n </button>\n {defs.Collections?.map((c) => (\n <button\n key={c.CollectionID ?? \"\"}\n style={collection === c.CollectionID ? chipActive : chip}\n onClick={() => setCollection(c.CollectionID ?? null)}\n >\n ★ {c.Name ?? c.CollectionID}\n </button>\n ))}\n </div>\n )}\n {!collection && (\n <div style={filtersRow}>\n <select\n style={input}\n value={query.contentType ?? \"\"}\n onChange={(e) =>\n setQuery({ ...query, contentType: e.target.value || undefined })\n }\n >\n <option value=\"\">All types</option>\n {types.map(([id, t]) => (\n <option key={id} value={id}>\n {handlers.find((h) => h.type === id)?.label ??\n t.DisplayName ??\n id}\n </option>\n ))}\n </select>\n <select\n style={input}\n value={query.sort ?? \"New\"}\n onChange={(e) =>\n setQuery({\n ...query,\n sort: e.target.value as WorkshopBrowseQuery[\"sort\"],\n })\n }\n >\n <option value=\"New\">Newest</option>\n <option value=\"Popular\">Most acquired</option>\n <option value=\"MostLiked\">Most liked</option>\n </select>\n <input\n style={input}\n placeholder=\"Tag\"\n defaultValue={query.tag ?? \"\"}\n onKeyDown={(e) => {\n if (e.key === \"Enter\")\n setQuery({\n ...query,\n tag: (e.target as HTMLInputElement).value.trim() || undefined,\n });\n }}\n />\n <label style={checkLabel}>\n <input\n type=\"checkbox\"\n checked={query.fromFollowing === true}\n onChange={(e) =>\n setQuery({\n ...query,\n fromFollowing: e.target.checked || undefined,\n })\n }\n />\n From authors I follow\n </label>\n </div>\n )}\n {error && <div style={errorBox}>{error}</div>}\n {items.length === 0 && !busy && (\n <div style={muted}>Nothing here yet.</div>\n )}\n <div style={grid}>\n {items.map((item) => (\n <ContentCard\n key={item.ContentID ?? \"\"}\n item={item}\n handlers={handlers}\n onClick={() => item.ContentID && onOpen(item.ContentID)}\n />\n ))}\n </div>\n {cursor && (\n <button\n style={secondaryBtn}\n disabled={busy}\n onClick={() => void load(true)}\n >\n {busy ? \"Loading…\" : \"Show more\"}\n </button>\n )}\n </div>\n );\n}\n\nfunction ContentCard({\n item,\n handlers,\n onClick,\n}: {\n item: WorkshopContentView;\n handlers: ContentTypeHandler[];\n onClick(): void;\n}): ReactNode {\n const handler = handlers.find((h) => h.type === item.ContentType);\n return (\n <button style={card} onClick={onClick}>\n <div style={thumbBox}>\n {item.ThumbnailUrl ? (\n <img src={item.ThumbnailUrl} alt=\"\" style={thumbImg} />\n ) : (\n <span style={{ fontSize: 34 }}>{handler?.icon ?? \"📦\"}</span>\n )}\n </div>\n <div style={cardTitle}>\n {item.Title ||\n (item.Status === \"Uploading\" ? \"Unfinished upload\" : \"Untitled\")}\n </div>\n <div style={cardMeta}>\n {item.IsOfficial\n ? \"Official\"\n : (item.CreatorPublicData?.Username ?? \"Player\")}{\" \"}\n · ♥ {item.Stats?.Likes ?? 0}\n </div>\n <div style={badgesRow}>\n {item.IsMine ? (\n <span style={badgeOwned}>Yours</span>\n ) : item.Owned ? (\n <span style={badgeOwned}>In library</span>\n ) : (\n (item.Access ?? []).map((o) => (\n <span key={o.OptionID ?? \"\"} style={badge}>\n {accessLabel(o)}\n </span>\n ))\n )}\n {item.Status && item.Status !== \"Published\" && (\n <span style={badgeWarn}>{item.Status}</span>\n )}\n </div>\n </button>\n );\n}\n\n// ────────────────────────────── Details ──────────────────────────────\n\nconst REPORT_REASONS: SocialReportReason[] = [\n \"Inappropriate\",\n \"Spam\",\n \"Stolen\",\n \"Broken\",\n \"Harassment\",\n \"Other\",\n];\n\nfunction ContentDetails({\n host,\n contentID,\n onClose,\n}: {\n host: WorkshopHost;\n contentID: string;\n onClose(): void;\n}): ReactNode {\n const [data, setData] = useState<WorkshopContentResponse | null>(null);\n const [busy, setBusy] = useState<string | null>(null);\n const [message, setMessage] = useState<string | null>(null);\n const [following, setFollowing] = useState<boolean | null>(null);\n const [reportReason, setReportReason] =\n useState<SocialReportReason>(\"Inappropriate\");\n\n const reload = useCallback(async () => {\n const r = await host.client.workshop.getContent(contentID);\n if (!r.ok) {\n setMessage(errorText(r.error));\n return;\n }\n setData(r.data);\n // Following the author is a social-layer edge on the PLAYER, not part of the card.\n const creator = r.data.Content?.CreatorUserID;\n if (creator && !r.data.Content?.IsMine) {\n const s = await host.client.social.getEntityStates(\"User\", [creator]);\n if (s.ok) setFollowing(s.data.Items?.[0]?.Following === true);\n }\n }, [host, contentID]);\n\n useEffect(() => {\n void reload();\n }, [reload]);\n\n const view = data?.Content;\n const handler = view?.ContentType\n ? host.content.getType(view.ContentType)\n : undefined;\n\n const run = async (\n label: string,\n work: () => Promise<string | null>,\n ): Promise<void> => {\n setBusy(label);\n setMessage(null);\n try {\n setMessage(await work());\n } catch (e) {\n setMessage(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(null);\n }\n };\n\n const open = (): Promise<void> =>\n run(\"open\", async () => {\n if (!view?.ContentID) return null;\n if (!handler?.open)\n return \"This game can't open this type of content here.\";\n const r = await host.client.workshop.downloadFiles(view.ContentID);\n if (!r.ok) return errorText(r.error);\n await handler.open({\n contentID: view.ContentID,\n title: view.Title,\n revision: view.Revision,\n files: r.data.files,\n });\n if (handler.modeId) host.navigate(handler.modeId);\n return null;\n });\n\n const acquire = (option: WorkshopAccessOption): Promise<void> =>\n run(`get:${option.OptionID}`, async () => {\n const r = await host.client.workshop.acquire(contentID, option);\n if (!r.ok) return errorText(r.error);\n await reload();\n return r.data.AlreadyOwned\n ? \"Already in your library.\"\n : \"Added to your library.\";\n });\n\n if (!view) return <Modal onClose={onClose}>{message ?? \"Loading…\"}</Modal>;\n\n const states = new Map(\n (data?.AccessState ?? []).map((s) => [\n s.OptionID ?? \"\",\n s.Available !== false,\n ]),\n );\n const canOpen = Boolean(data?.CanDownload);\n\n return (\n <Modal onClose={onClose}>\n <div style={detailsHead}>\n <div style={detailsThumb}>\n {view.ThumbnailUrl ? (\n <img src={view.ThumbnailUrl} alt=\"\" style={thumbImg} />\n ) : (\n <span style={{ fontSize: 48 }}>{handler?.icon ?? \"📦\"}</span>\n )}\n </div>\n <div style={{ minWidth: 0 }}>\n <h2 style={{ margin: \"0 0 6px\" }}>{view.Title}</h2>\n <div style={muted}>\n {view.IsOfficial\n ? \"Official content\"\n : `by ${view.CreatorPublicData?.Username ?? \"a player\"}`}{\" \"}\n · {handler?.label ?? view.ContentType} · rev. {view.Revision}\n </div>\n <div style={muted}>\n ♥ {view.Stats?.Likes ?? 0} · ★ {view.Stats?.Favorites ?? 0} · ⬇{\" \"}\n {view.Stats?.Acquisitions ?? 0}\n {view.TotalBytes ? ` · ${formatBytes(view.TotalBytes)}` : \"\"}\n </div>\n {(view.Tags?.length ?? 0) > 0 && (\n <div style={badgesRow}>\n {view.Tags?.map((t) => (\n <span key={t} style={badge}>\n #{t}\n </span>\n ))}\n </div>\n )}\n </div>\n </div>\n\n {view.Description && (\n <p style={{ whiteSpace: \"pre-wrap\" }}>{view.Description}</p>\n )}\n {view.IsMine && view.ModerationNote && (\n <div style={errorBox}>Moderation: {view.ModerationNote}</div>\n )}\n {view.IsMine && (view.Access?.length ?? 0) > 0 && (\n <div style={muted}>\n Others get it: {(view.Access ?? []).map(accessLabel).join(\" · \")}\n </div>\n )}\n\n <div style={actionsCol}>\n {canOpen ? (\n <button\n style={primaryBtn}\n disabled={busy !== null || !handler?.open}\n onClick={() => void open()}\n >\n {busy === \"open\"\n ? \"Opening…\"\n : handler?.open\n ? \"Open\"\n : \"Owned (open it in the game)\"}\n </button>\n ) : (\n (view.Access ?? []).map((o) => {\n const available = states.get(o.OptionID ?? \"\") ?? true;\n return (\n <button\n key={o.OptionID ?? \"\"}\n style={available ? primaryBtn : disabledBtn}\n disabled={!available || busy !== null}\n title={\n available\n ? undefined\n : \"You don't meet this option's requirements\"\n }\n onClick={() => void acquire(o)}\n >\n {busy === `get:${o.OptionID}` ? \"…\" : `Get — ${accessLabel(o)}`}\n </button>\n );\n })\n )}\n </div>\n\n <div style={filtersRow}>\n {!view.IsMine && (\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"like\", async () => {\n const r = view.Liked\n ? await host.client.social.unlike(\"WorkshopItem\", contentID)\n : await host.client.social.like(\"WorkshopItem\", contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return null;\n })\n }\n >\n {view.Liked ? \"♥ Liked\" : \"♡ Like\"}\n </button>\n )}\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"fav\", async () => {\n const r = view.Favorited\n ? await host.client.social.unfavorite(\"WorkshopItem\", contentID)\n : await host.client.social.favorite(\"WorkshopItem\", contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return null;\n })\n }\n >\n {view.Favorited ? \"★ In favorites\" : \"☆ Favorite\"}\n </button>\n {!view.IsMine && view.CreatorUserID && (\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"follow\", async () => {\n const creator = view.CreatorUserID ?? \"\";\n const r = following\n ? await host.client.social.unfollow(\"User\", creator)\n : await host.client.social.follow(\"User\", creator);\n if (!r.ok) return errorText(r.error);\n setFollowing(r.data.Following === true);\n return r.data.Following ? \"You follow this author.\" : null;\n })\n }\n >\n {following ? \"Following ✓\" : \"Follow author\"}\n </button>\n )}\n {view.IsMine && view.Status !== \"Removed\" && (\n <button\n style={dangerBtn}\n disabled={busy !== null}\n onClick={() => {\n if (\n !confirm(\n \"Unpublish for good? Players who already have it keep it.\",\n )\n )\n return;\n void run(\"unpublish\", async () => {\n const r = await host.client.workshop.unpublish(contentID);\n if (!r.ok) return errorText(r.error);\n await reload();\n return \"Unpublished.\";\n });\n }}\n >\n Unpublish\n </button>\n )}\n </div>\n\n {!view.IsMine && (\n <div style={filtersRow}>\n <select\n style={input}\n value={reportReason}\n onChange={(e) =>\n setReportReason(e.target.value as SocialReportReason)\n }\n >\n {REPORT_REASONS.map((r) => (\n <option key={r} value={r}>\n {r}\n </option>\n ))}\n </select>\n <button\n style={secondaryBtn}\n disabled={busy !== null}\n onClick={() =>\n void run(\"report\", async () => {\n const r = await host.client.social.report(\n \"WorkshopItem\",\n contentID,\n reportReason,\n );\n if (!r.ok) return errorText(r.error);\n return r.data.AlreadyReported\n ? \"You already reported this.\"\n : \"Thanks — the publisher will review it.\";\n })\n }\n >\n Report\n </button>\n </div>\n )}\n\n {message && <div style={noticeBox}>{message}</div>}\n </Modal>\n );\n}\n\n// ────────────────────────────── Publish ──────────────────────────────\n\ninterface AccessDraft {\n mode: \"Free\" | \"Price\" | \"Holding\";\n resource: string; // \"vc:GOLD\" | \"item:<catalog>/<item>\"\n amount: number;\n holdMode: \"WhileHeld\" | \"UnlockOnce\";\n}\n\nfunction PublishWizard({\n host,\n defs,\n onDone,\n}: {\n host: WorkshopHost;\n defs: WorkshopDefinitionsResponse;\n onDone(contentID: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content).filter(\n (h) => h.listLocal && h.capture && defs.CanPublish?.[h.type] === true,\n );\n const [type, setType] = useState<string | null>(null);\n const [locals, setLocals] = useState<Array<{\n id: string;\n name: string;\n subtitle?: string;\n }> | null>(null);\n const [localId, setLocalId] = useState<string | null>(null);\n const [title, setTitle] = useState(\"\");\n const [description, setDescription] = useState(\"\");\n const [tags, setTags] = useState(\"\");\n const [visibility, setVisibility] = useState<WorkshopVisibility>(\"Public\");\n const [access, setAccess] = useState<AccessDraft[]>([\n { mode: \"Free\", resource: \"\", amount: 1, holdMode: \"UnlockOnce\" },\n ]);\n const [busy, setBusy] = useState(false);\n const [message, setMessage] = useState<string | null>(null);\n\n const handler = handlers.find((h) => h.type === type);\n const typeDef = type ? defs.Definitions?.ContentTypes?.[type] : undefined;\n const allowedModes = typeDef?.AllowedAccessModes?.length\n ? typeDef.AllowedAccessModes\n : [\"Free\", \"Price\", \"Holding\"];\n const resources = useResourceOptions(host.client);\n // Плата за публикацию берётся только ресурсами: вариант с оплатой в сторе сервер отвергнет.\n const fee = Object.entries(typeDef?.PublishFeeOptions ?? {}).find(\n ([, option]) =>\n !(option?.Cost?.Standard?.Entries ?? []).some(\n (e) => e?.Type === \"Purchase\",\n ),\n );\n\n useEffect(() => {\n setLocals(null);\n setLocalId(null);\n if (!handler?.listLocal) return;\n void handler\n .listLocal()\n .then(setLocals, (e: unknown) =>\n setMessage(e instanceof Error ? e.message : String(e)),\n );\n }, [handler]);\n\n if (handlers.length === 0)\n return (\n <div style={muted}>\n Nothing to publish from here: the games in this project either do not\n register their content, or you can't publish it yet.\n </div>\n );\n\n const publish = async (): Promise<void> => {\n if (!handler?.capture || !type || !localId) return;\n // Опция без ресурса молча выпала бы из списка, и публикация ушла бы не с теми способами получить.\n if (access.some((a) => a.mode !== \"Free\" && !a.resource)) {\n setMessage(\"Pick a resource for every paid or hold-to-unlock option.\");\n return;\n }\n setBusy(true);\n setMessage(null);\n try {\n const captured = await handler.capture(localId);\n const r = await host.client.workshop.publish({\n contentType: type,\n files: captured.files,\n thumbnail: captured.thumbnail,\n title: title.trim() || captured.suggestedTitle || \"Untitled\",\n description: description.trim() || captured.suggestedDescription,\n tags: tags\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean)\n .concat(captured.tags ?? []),\n metadata: captured.metadata,\n visibility,\n access: access\n .map(toAccessInput)\n .filter((a): a is WorkshopAccessOptionInput => a !== null),\n selectedFeeOptionID: fee?.[0],\n });\n if (!r.ok) setMessage(errorText(r.error));\n else if (r.data.Content?.ContentID) onDone(r.data.Content.ContentID);\n } catch (e) {\n setMessage(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n return (\n <div style={formCol}>\n <label style={fieldLabel}>What</label>\n <div style={chipsRow}>\n {handlers.map((h) => (\n <button\n key={h.type}\n style={type === h.type ? chipActive : chip}\n onClick={() => setType(h.type)}\n >\n {h.icon} {h.label}\n </button>\n ))}\n </div>\n\n {handler && (\n <>\n <label style={fieldLabel}>Which one</label>\n {!locals ? (\n <div style={muted}>Loading…</div>\n ) : locals.length === 0 ? (\n <div style={muted}>You have nothing of this type yet.</div>\n ) : (\n <div style={formCol}>\n {locals.map((l) => (\n <label key={l.id} style={checkLabel}>\n <input\n type=\"radio\"\n name=\"wsLocal\"\n checked={localId === l.id}\n onChange={() => {\n setLocalId(l.id);\n if (!title) setTitle(l.name);\n }}\n />\n {l.name}{\" \"}\n {l.subtitle && <span style={muted}>· {l.subtitle}</span>}\n </label>\n ))}\n </div>\n )}\n </>\n )}\n\n {localId && (\n <>\n <label style={fieldLabel}>Title</label>\n <input\n style={input}\n value={title}\n maxLength={defs.Definitions?.Limits?.MaxTitleLength ?? 60}\n onChange={(e) => setTitle(e.target.value)}\n />\n <label style={fieldLabel}>Description</label>\n <textarea\n style={{ ...input, minHeight: 70 }}\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n />\n <label style={fieldLabel}>\n Tags (comma separated\n {typeDef?.TagVocabulary?.length\n ? `: ${typeDef.TagVocabulary.join(\", \")}`\n : \"\"}\n )\n </label>\n <input\n style={input}\n value={tags}\n onChange={(e) => setTags(e.target.value)}\n />\n <label style={fieldLabel}>Who can see it</label>\n <select\n style={input}\n value={visibility}\n onChange={(e) =>\n setVisibility(e.target.value as WorkshopVisibility)\n }\n >\n <option value=\"Public\">Everyone (in the catalog)</option>\n <option value=\"Unlisted\">Anyone with the link</option>\n <option value=\"Friends\">Only my friends</option>\n </select>\n\n <label style={fieldLabel}>How others get it — any option works</label>\n {access.map((a, i) => (\n <div key={i} style={filtersRow}>\n <select\n style={input}\n value={a.mode}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n mode: e.target.value as AccessDraft[\"mode\"],\n }),\n )\n }\n >\n {allowedModes.map((m) => (\n <option key={m} value={m}>\n {m === \"Free\"\n ? \"Free\"\n : m === \"Price\"\n ? \"For resources\"\n : \"Hold to unlock\"}\n </option>\n ))}\n </select>\n {a.mode !== \"Free\" && (\n <>\n <select\n style={input}\n value={a.resource}\n onChange={(e) =>\n setAccess(patch(access, i, { resource: e.target.value }))\n }\n >\n <option value=\"\">— resource —</option>\n {resources\n .filter(\n (r) => a.mode === \"Holding\" || r.startsWith(\"vc:\"),\n )\n .map((r) => (\n <option key={r} value={r}>\n {r.replace(/^vc:/, \"\").replace(/^item:/, \"item \")}\n </option>\n ))}\n </select>\n <input\n style={{ ...input, width: 90 }}\n type=\"number\"\n min={1}\n value={a.amount}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n amount: Math.max(1, Number(e.target.value) || 1),\n }),\n )\n }\n />\n </>\n )}\n {a.mode === \"Holding\" && (\n <select\n style={input}\n value={a.holdMode}\n onChange={(e) =>\n setAccess(\n patch(access, i, {\n holdMode: e.target.value as AccessDraft[\"holdMode\"],\n }),\n )\n }\n >\n <option value=\"UnlockOnce\">Checked once, then forever</option>\n <option value=\"WhileHeld\">Only while they hold it</option>\n </select>\n )}\n {access.length > 1 && (\n <button\n style={secondaryBtn}\n onClick={() => setAccess(access.filter((_, j) => j !== i))}\n >\n ✕\n </button>\n )}\n </div>\n ))}\n <button\n style={secondaryBtn}\n onClick={() =>\n setAccess([\n ...access,\n {\n mode: allowedModes.includes(\"Price\") ? \"Price\" : \"Free\",\n resource: \"\",\n amount: 10,\n holdMode: \"UnlockOnce\",\n },\n ])\n }\n >\n + Add an option\n </button>\n\n {fee && (\n <div style={muted}>\n Publishing costs {bundleLabel(fee[1].Cost?.Standard)} (charged\n once).\n </div>\n )}\n <button\n style={primaryBtn}\n disabled={busy}\n onClick={() => void publish()}\n >\n {busy ? \"Publishing…\" : \"Publish\"}\n </button>\n </>\n )}\n {message && <div style={errorBox}>{message}</div>}\n </div>\n );\n}\n\nfunction patch<T>(list: T[], index: number, change: Partial<T>): T[] {\n return list.map((item, i) => (i === index ? { ...item, ...change } : item));\n}\n\nfunction toAccessInput(a: AccessDraft): WorkshopAccessOptionInput | null {\n if (a.mode === \"Free\") return { Mode: \"Free\" };\n if (!a.resource) return null;\n const [kind, id = \"\"] = a.resource.split(\":\", 2);\n if (a.mode === \"Price\") {\n return {\n Mode: \"Price\",\n Price: {\n Entries: [\n { Type: \"VirtualCurrency\", CurrencyID: id, Amount: a.amount },\n ],\n },\n };\n }\n const [catalogID, itemID] = id.split(\"/\", 2);\n return {\n Mode: \"Holding\",\n Holding: {\n Mode: a.holdMode,\n Match: \"All\",\n Requirements: [\n kind === \"vc\"\n ? { Type: \"VirtualCurrency\", CurrencyID: id, Amount: a.amount }\n : {\n Type: \"Item\",\n CatalogID: catalogID,\n ItemID: itemID ?? \"\",\n Amount: a.amount,\n },\n ],\n },\n };\n}\n\n// ────────────────────────────── Lists ──────────────────────────────\n\nfunction MyList({\n host,\n kind,\n onOpen,\n}: {\n host: WorkshopHost;\n kind: \"mine\" | \"licenses\" | \"favorites\";\n onOpen(id: string): void;\n}): ReactNode {\n const handlers = useContentTypes(host.content);\n const [items, setItems] = useState<WorkshopContentView[] | null>(null);\n const [error, setError] = useState<string | null>(null);\n\n useEffect(() => {\n let alive = true;\n const load = async (): Promise<void> => {\n const w = host.client.workshop;\n if (kind === \"licenses\") {\n const r = await w.getMyLicenses();\n if (!alive) return;\n if (r.ok)\n setItems(\n (r.data.Licenses ?? [])\n .map((l) => l.Content)\n .filter((c): c is WorkshopContentView => Boolean(c)),\n );\n else setError(errorText(r.error));\n return;\n }\n const r =\n kind === \"mine\" ? await w.getMyContent() : await w.getMyFavorites();\n if (!alive) return;\n if (r.ok) setItems(r.data.Items ?? []);\n else setError(errorText(r.error));\n };\n void load();\n return () => {\n alive = false;\n };\n }, [host, kind]);\n\n if (error) return <div style={errorBox}>{error}</div>;\n if (!items) return <div style={muted}>Loading…</div>;\n if (items.length === 0) return <div style={muted}>Empty.</div>;\n return (\n <div style={grid}>\n {items.map((item) => (\n <ContentCard\n key={item.ContentID ?? \"\"}\n item={item}\n handlers={handlers}\n onClick={() => item.ContentID && onOpen(item.ContentID)}\n />\n ))}\n </div>\n );\n}\n\n// ────────────────────────────── helpers ──────────────────────────────\n\n/**\n * Registered content types, re-read on every registry change. ⚠ Not keyed by the NUMBER of types: a game\n * re-installed after re-login registers the same type again with a new handler, the count stays the\n * same, and a count-based snapshot kept the handler of the destroyed game.\n */\nfunction useContentTypes(content: ContentRegistry): ContentTypeHandler[] {\n const [types, setTypes] = useState(() => content.listTypes());\n useEffect(() => {\n setTypes(content.listTypes());\n return content.subscribe(() => setTypes(content.listTypes()));\n }, [content]);\n return types;\n}\n\n/** \"vc:GOLD\" and \"item:<catalog>/<item>\" for every currency and item the title defines. */\nfunction useResourceOptions(client: IDosGamesClient): string[] {\n const [list] = useState(() => {\n const out: string[] = [];\n for (const id of Object.keys(\n client.data.config.currencyDefinitions?.VirtualCurrencies ?? {},\n ))\n out.push(`vc:${id}`);\n for (const [catalogID, catalog] of Object.entries(\n client.data.config.itemDefinitions?.Catalogs ?? {},\n ))\n for (const itemID of Object.keys(catalog?.Items ?? {}))\n out.push(`item:${catalogID}/${itemID}`);\n return out;\n });\n return list;\n}\n\ntype BundleLike =\n | {\n Entries?: Array<{\n CurrencyID?: string | null;\n ItemID?: string | null;\n Amount?: number | null;\n } | null> | null;\n }\n | null\n | undefined;\n\nfunction bundleLabel(bundle: BundleLike): string {\n const parts = (bundle?.Entries ?? [])\n .filter((e): e is NonNullable<typeof e> => Boolean(e))\n .map((e) => `${e.Amount ?? 0} ${e.CurrencyID ?? e.ItemID ?? \"\"}`.trim());\n return parts.length ? parts.join(\" + \") : \"free\";\n}\n\nfunction accessLabel(o: WorkshopAccessOption): string {\n if (o.Mode === \"Free\") return \"Free\";\n if (o.Mode === \"Price\") return bundleLabel(o.Price);\n const reqs = (o.Holding?.Requirements ?? []).map(\n (r) =>\n `${r.Amount ?? 0} ${r.CurrencyID ?? r.ItemID ?? \"\"}${r.MinLevel ? ` (lvl ${r.MinLevel}+)` : \"\"}`,\n );\n const joined = reqs.join(o.Holding?.Match === \"Any\" ? \" or \" : \" + \");\n return `🔑 hold ${joined}${o.Holding?.Mode === \"WhileHeld\" ? \" (while held)\" : \"\"}`;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;\n return `${(n / 1024 / 1024).toFixed(1)} MB`;\n}\n\nfunction Frame({ children }: { children: ReactNode }): ReactNode {\n return <div style={frame}>{children}</div>;\n}\n\nfunction Modal({\n children,\n onClose,\n}: {\n children: ReactNode;\n onClose(): void;\n}): ReactNode {\n return (\n <div style={backdrop} onClick={onClose}>\n <div style={modal} onClick={(e) => e.stopPropagation()}>\n <button style={closeBtn} onClick={onClose} aria-label=\"Close\">\n ✕\n </button>\n {children}\n </div>\n </div>\n );\n}\n\n// ────────────────────────────── styles ──────────────────────────────\n// Every colour is a theme token of the UI kit (the project's src/ui.config.ts), like every other\n// system — the workshop must not be a dark island in a light app. Change the theme, not these.\n\nconst frame: CSSProperties = {\n // A tab of the lobby: the lobby scrolls it and gives it the width.\n minHeight: 360,\n borderRadius: 16,\n padding: \"16px 20px 40px\",\n ...panel,\n color: v.text,\n fontFamily: v.font,\n pointerEvents: \"auto\",\n};\nconst tabsRow: CSSProperties = {\n display: \"flex\",\n gap: 6,\n flexWrap: \"wrap\",\n marginBottom: 14,\n};\nconst tabBtn: CSSProperties = {\n background: \"transparent\",\n color: v.textDim,\n border: `1px solid ${v.line}`,\n borderRadius: 8,\n padding: \"6px 12px\",\n cursor: \"pointer\",\n};\nconst tabActive: CSSProperties = {\n ...tabBtn,\n background: `linear-gradient(180deg, ${v.blue}, ${v.blueDeep})`,\n color: v.onBlue,\n border: \"1px solid transparent\",\n};\nconst chipsRow: CSSProperties = {\n display: \"flex\",\n gap: 6,\n flexWrap: \"wrap\",\n margin: \"8px 0\",\n};\nconst chip: CSSProperties = {\n ...tabBtn,\n borderRadius: 999,\n padding: \"4px 10px\",\n fontSize: 13,\n};\nconst chipActive: CSSProperties = {\n ...chip,\n background: `color-mix(in srgb, ${v.blue} 30%, transparent)`,\n color: v.text,\n};\nconst filtersRow: CSSProperties = {\n display: \"flex\",\n gap: 8,\n flexWrap: \"wrap\",\n alignItems: \"center\",\n margin: \"8px 0\",\n};\nconst input: CSSProperties = {\n background: v.well,\n color: v.text,\n border: `1px solid ${v.line}`,\n boxShadow: v.wellShadow,\n borderRadius: 6,\n padding: \"6px 8px\",\n font: \"inherit\",\n};\nconst checkLabel: CSSProperties = {\n display: \"flex\",\n gap: 6,\n alignItems: \"center\",\n fontSize: 14,\n};\nconst grid: CSSProperties = {\n display: \"grid\",\n gridTemplateColumns: \"repeat(auto-fill, minmax(170px, 1fr))\",\n gap: 12,\n};\nconst card: CSSProperties = {\n textAlign: \"left\",\n background: v.panelDeep,\n border: `1px solid ${v.panelEdge}`,\n borderRadius: 10,\n padding: 8,\n color: \"inherit\",\n cursor: \"pointer\",\n font: \"inherit\",\n};\nconst thumbBox: CSSProperties = {\n aspectRatio: \"1 / 1\",\n borderRadius: 8,\n background: v.wellSoft,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n};\nconst thumbImg: CSSProperties = {\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n imageRendering: \"pixelated\",\n};\nconst cardTitle: CSSProperties = {\n fontWeight: 600,\n margin: \"6px 0 2px\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n};\nconst cardMeta: CSSProperties = { fontSize: 12, color: v.textDim };\nconst badgesRow: CSSProperties = {\n display: \"flex\",\n gap: 4,\n flexWrap: \"wrap\",\n marginTop: 6,\n};\nconst badge: CSSProperties = {\n fontSize: 11,\n background: v.wellSoft,\n color: v.text,\n borderRadius: 4,\n padding: \"2px 6px\",\n};\nconst badgeOwned: CSSProperties = {\n ...badge,\n background: `color-mix(in srgb, ${v.green} 35%, transparent)`,\n};\nconst badgeWarn: CSSProperties = {\n ...badge,\n background: `color-mix(in srgb, ${v.gold} 35%, transparent)`,\n};\nconst muted: CSSProperties = { color: v.textDim, fontSize: 13 };\nconst errorBox: CSSProperties = {\n background: `color-mix(in srgb, ${v.red} 18%, transparent)`,\n border: `1px solid color-mix(in srgb, ${v.red} 45%, transparent)`,\n color: v.text,\n borderRadius: 6,\n padding: \"8px 10px\",\n margin: \"8px 0\",\n};\nconst noticeBox: CSSProperties = {\n background: `color-mix(in srgb, ${v.blue} 16%, transparent)`,\n borderRadius: 6,\n padding: \"8px 10px\",\n marginTop: 10,\n};\nconst primaryBtn: CSSProperties = {\n ...buttonStyle(\"blue\", false, \"sm\"),\n font: \"inherit\",\n fontWeight: 800,\n};\nconst disabledBtn: CSSProperties = {\n ...buttonStyle(\"blue\", true, \"sm\"),\n font: \"inherit\",\n fontWeight: 800,\n cursor: \"not-allowed\",\n};\nconst secondaryBtn: CSSProperties = { ...tabBtn, color: v.text };\nconst dangerBtn: CSSProperties = {\n ...tabBtn,\n color: v.red,\n border: `1px solid color-mix(in srgb, ${v.red} 50%, transparent)`,\n};\nconst actionsCol: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n gap: 8,\n margin: \"12px 0\",\n};\nconst formCol: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n gap: 6,\n maxWidth: 640,\n};\nconst fieldLabel: CSSProperties = {\n fontSize: 13,\n color: v.textDim,\n marginTop: 8,\n};\nconst backdrop: CSSProperties = {\n position: \"fixed\",\n inset: 0,\n background: v.backdrop,\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n zIndex: 50,\n};\nconst modal: CSSProperties = {\n position: \"relative\",\n ...panel,\n color: v.text,\n padding: 20,\n width: \"min(640px, 94vw)\",\n maxHeight: \"90vh\",\n overflow: \"auto\",\n};\nconst closeBtn: CSSProperties = {\n position: \"absolute\",\n top: 10,\n right: 10,\n background: \"transparent\",\n color: v.textDim,\n border: 0,\n fontSize: 18,\n cursor: \"pointer\",\n};\nconst detailsHead: CSSProperties = {\n display: \"flex\",\n gap: 14,\n alignItems: \"flex-start\",\n marginRight: 24,\n};\nconst detailsThumb: CSSProperties = {\n ...thumbBox,\n width: 120,\n flex: \"0 0 120px\",\n};\n"
|
|
107
|
+
"content": "import { useEffect, useState, type ComponentType, type ReactNode } from \"react\";\nimport { type WorkshopDefinitionsResponse } from \"@idosgames/core\";\nimport { type FeatureScreenProps } from \"@idosgames/module-sdk\";\nimport { Catalog } from \"./components/Catalog\";\nimport { ContentDetails } from \"./components/ContentDetails\";\nimport { Frame } from \"./components/Frame\";\nimport { MyList } from \"./components/MyList\";\nimport { PublishWizard } from \"./components/PublishWizard\";\nimport { errorText } from \"./errors\";\nimport { tabActive, tabBtn, tabsRow } from \"./styles\";\nimport { type WorkshopHost } from \"./types\";\n\n// The Workshop screen: catalog, content card, publish wizard, \"mine / licenses / favorites\".\n//\n// It is the same for every game. Everything game-specific comes from two places: the title's Workshop\n// config (which types exist, formats, access modes — read via client.workshop.getDefinitions()) and the\n// handlers games register in ctx.content (how to list, capture and open their content). This file is\n// plain editable React with inline styles — restyle or replace it like any other module source.\n\n/** The Workshop as a tab of the lobby (a feature screen); `navigate` hands the screen to a game. */\nexport function makeWorkshopScreen(\n host: WorkshopHost,\n): ComponentType<FeatureScreenProps> {\n return function WorkshopScreen(): ReactNode {\n return <WorkshopApp host={host} />;\n };\n}\n\ntype Tab = \"catalog\" | \"publish\" | \"mine\" | \"licenses\" | \"favorites\";\n\nconst TABS: Array<[Tab, string]> = [\n [\"catalog\", \"Catalog\"],\n [\"publish\", \"Publish\"],\n [\"mine\", \"My content\"],\n [\"licenses\", \"My library\"],\n [\"favorites\", \"Favorites\"],\n];\n\nexport function WorkshopApp({ host }: { host: WorkshopHost }): ReactNode {\n const [defs, setDefs] = useState<WorkshopDefinitionsResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [tab, setTab] = useState<Tab>(\"catalog\");\n const [openID, setOpenID] = useState<string | null>(null);\n\n useEffect(() => {\n let alive = true;\n void host.client.workshop.getDefinitions().then((r) => {\n if (!alive) return;\n if (r.ok) setDefs(r.data);\n else setError(errorText(r.error));\n });\n return () => {\n alive = false;\n };\n }, [host]);\n\n if (!defs) return <Frame>{error ?? \"Loading the Workshop…\"}</Frame>;\n if (!defs.Definitions?.Enabled || !defs.GatePassed)\n return <Frame>The Workshop is not available in this game right now.</Frame>;\n\n return (\n <Frame>\n <div style={tabsRow}>\n {TABS.map(([id, label]) => (\n <button\n key={id}\n style={id === tab ? tabActive : tabBtn}\n onClick={() => setTab(id)}\n >\n {label}\n </button>\n ))}\n </div>\n {tab === \"catalog\" && (\n <Catalog host={host} defs={defs} onOpen={setOpenID} />\n )}\n {tab === \"publish\" && (\n <PublishWizard\n host={host}\n defs={defs}\n onDone={(id) => {\n setTab(\"mine\");\n setOpenID(id);\n }}\n />\n )}\n {tab === \"mine\" && <MyList host={host} kind=\"mine\" onOpen={setOpenID} />}\n {tab === \"licenses\" && (\n <MyList host={host} kind=\"licenses\" onOpen={setOpenID} />\n )}\n {tab === \"favorites\" && (\n <MyList host={host} kind=\"favorites\" onOpen={setOpenID} />\n )}\n {openID && (\n <ContentDetails\n host={host}\n contentID={openID}\n onClose={() => setOpenID(null)}\n />\n )}\n </Frame>\n );\n}\n\n// ────────────────────────────── Catalog ──────────────────────────────\n"
|
|
64
108
|
},
|
|
65
109
|
{
|
|
66
110
|
"path": "module.meta.json",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "authentication",
|
|
3
3
|
"description": "Log players into a game on the iDosGames TypeScript SDK (@idosgames/core) via client.auth (AuthenticationService): guest/device-id login, two-step email registration with a confirmation code, email login, Google/Telegram login, SSO-code login from idosgames.com, wallet login, password reset, auto login on relaunch, session refresh, logout, and client-side email/password validation. Use this whenever the user is working in the iDosGames TS SDK or its game templates (board-game, idle-rpg) and asks about logging a player in, sessions, registration, email confirmation codes, resending a code, guest accounts, device-id login, Telegram login, Google login, SSO login, wallet login, forgot/reset password, auto-login, isLoggedIn, or otherwise touches client.auth, AuthenticationService, or AuthContext — even if they don't name the module explicitly.",
|
|
4
|
-
"content": "---\nname: authentication\ndescription: >-\n Log players into a game on the iDosGames TypeScript SDK (@idosgames/core)\n via client.auth (AuthenticationService): guest/device-id login, two-step\n email registration with a confirmation code, email login, Google/Telegram\n login, SSO-code login from idosgames.com, wallet login, password reset, auto\n login on relaunch, session refresh, logout, and client-side email/password\n validation. Use this whenever the user is working in the iDosGames TS SDK or\n its game templates (board-game, idle-rpg) and asks about logging a player\n in, sessions, registration, email confirmation codes, resending a code,\n guest accounts, device-id login, Telegram login, Google login, SSO login,\n wallet login, forgot/reset password, auto-login, isLoggedIn, or otherwise\n touches client.auth, AuthenticationService, or AuthContext — even if they\n don't name the module explicitly.\n---\n\n# Authentication (iDosGames TS SDK)\n\nThe Authentication module is how a player gets a session. It's the one module\nevery other feature depends on: nothing else on `client` works until a login\nmethod has succeeded. Unlike feature modules, most of its methods don't return\na narrow per-feature payload — they return the **entire post-login bootstrap\nstate** (`ClientState`: title config + the player's full `User` state),\nbecause a successful login is also \"give me everything the client needs to\nrender.\"\n\nThis skill is for **using** production login flows, not for porting or\nextending the service. If a login is rejected, that's the backend enforcing a\nrule (bad credentials, duplicate email, banned account) — surface the error,\ndon't try to reproduce the check client-side.\n\n## Remember me\n\n`setRememberSession(remember)` decides whether a successful login is written to storage. Call it\n**before** a `login*` method — it is read when that login completes, and it applies to whichever\nprovider runs next.\n\n```ts\nclient.auth.setRememberSession(rememberCheckbox); // default: true\nconst result = await client.auth.loginWithDeviceID();\n```\n\n- **On** (the default, and how every release before core 0.1.3 behaved) — the session is persisted,\n so `autoLogin()` signs the player back in on the next launch.\n- **Off** — nothing is persisted and any previously remembered session is dropped, so the next\n launch opens on the login screen. The current session is NOT weakened: the credentials stay in\n memory for this tab, so the transport's automatic 401 re-login still works.\n\n`logout()` ends the session and clears the persisted one, so a reload does not walk back into the\naccount the player just left. (Before core 0.1.3 it left storage untouched and a reload silently\nsigned them back in.)\n\nSessions are extended by the **refresh token** (`Authentication/RefreshSession`, core ≥ 0.18): every\nlogin returns one, it is kept in memory and — when remembering — in storage, and rotated on every\nrefresh. A 401 and a cold-start `autoLogin()` use it first, so ANY method comes back, wallet and\nGoogle included; replaying the login method is only the fallback for a missing/expired token. On a\ntitle whose login mode needs a token balance the server re-checks it on that refresh; a balance\nthat dropped closes the game (`client.auth.playAccess.Granted === false`), it does not end the session.\n\n## Mental model\n\n- **Guest login** (`loginWithDeviceID`) — anonymous account keyed off a\n per-device ID the platform adapter generates/stores. Zero-friction first\n launch; no credentials to lose, but also nothing to recover if the device ID\n is gone (reinstall, new device).\n- **Linked login methods** — `loginWithEmail` / `registerWithEmail`,\n `loginWithGoogle`, `loginWithTelegram`, `loginWithSsoCode`. These tie\n the account to a real identity so the player can resume it elsewhere.\n- **`autoLogin()`** picks up where the player left off. It first extends the\n remembered session by its **refresh token** (works for every method). Only\n without a usable token does it fall back to replaying — and that fallback\n covers just the methods that don't need a fresh externally-issued token: it replays `loginWithEmail`\n if the last successful login was Email (saved password), `loginWithDeviceID`\n if it was Device/None, and `loginWithTelegram` if it was Telegram (its\n `initData` is re-read live from the Telegram WebApp bridge each time, not\n stored). For Google/Facebook/GooglePlay/platform-token, there's no stored\n credential to replay — `autoLogin()` returns `reason: \"client\"` instead of\n guessing, because DeviceID and email/platform logins hash to **different\n backend UserIDs** (see Gotchas), so silently falling back to a guest login\n would strand the player on an unrelated empty account. What `autoLogin()`\n has to replay is controlled by **\"remember me\"** — see below. Call this on app\n start instead of hand-rolling \"which method did they use last,\" but be ready\n to handle its failure by re-running the platform's sign-in flow.\n- **Session refresh is automatic.** The HTTP transport calls\n `refreshSession()` itself when a request comes back 401 — it calls the\n server's `RefreshSession` with the refresh token (falling back to replaying\n the login method only without a usable token) and retries once. You almost never call\n `refreshSession()` directly; it's documented here for completeness, not as a\n method you wire up in app code.\n- **Static validators** (`AuthenticationService.isValidEmail`,\n `AuthenticationService.isValidPasswordLength`) are plain synchronous\n functions, not calls to the backend — use them to validate a form before\n spending a network round-trip on a login/register call that will fail\n server-side anyway. They mirror, but do not replace, the server's own\n checks — the server always re-validates.\n\n## Setup\n\n```ts\nimport { createIDosGamesClient } from \"@idosgames/core\";\n\nconst client = createIDosGamesClient({ titleID: \"your-title-id\" });\nawait client.auth.loginWithDeviceID(); // or any other auth.* login method\n\nclient.auth.isLoggedIn; // true once a login call has succeeded\n```\n\nEvery other module's methods require this to have succeeded first — without a\nsession they return `{ ok: false, reason: \"unauthorized\" }` rather than\nthrowing. There is one `client` per player; don't share it across sessions.\nAuthentication requests carry no Bearer ticket at all — login/register/reset\nare the one family of calls that work before you have a session.\n\n## Methods\n\nAll login/register/reset methods return `Promise<OperationResult<T>>`: either\n`{ ok: true, data }` or `{ ok: false, reason, error }`. Always branch on\n`result.ok` before touching `result.data`. `reason` is one of `\"client\"` (bad\nlocal args, e.g. missing Telegram initData or empty platform token),\n`\"unauthorized\"`, `\"throttled\"` (fired the same endpoint again inside the\nthrottle window), `\"connection\"` (transient, offer Retry), `\"validation\"`\n(response/schema drift), or `\"server\"` (backend rejected it — `error` carries\nthe reason code the backend returned, e.g. `\"INCORRECT_EMAIL_OR_PASSWORD\"`,\n`\"INVALID_VERIFICATION_CODE\"` — see Gotchas for the verbatim set).\n\n| Method | Purpose | `data` on success |\n| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |\n| `loginWithDeviceID()` | Anonymous/guest login keyed off the device ID. | `ClientState` |\n| `loginWithTelegram()` | Login using the Telegram Mini App's init data. | `ClientState` |\n| `loginWithEmail(email, password)` | Login with email + password. | `ClientState` |\n| `registerWithEmail(email, password)` | **Start** a registration. Only mails a code — never returns a session, see below. | `EmailRegistrationOutcome` |\n| `confirmEmailRegistration(email, code)` | Finish the registration with the code from the email, creating the player. | `ClientState` |\n| `resendVerificationCode(email)` | Mail a fresh code. Resolves successfully whatever happened — except when there is no usable sender at all (`EMAIL_SENDER_NOT_CONFIGURED`). | `void` |\n| `requestWalletChallenge(networkID, address)` | Ask for the message the player's wallet must sign. Step one of wallet login. | `WalletChallengeResponse` |\n| `loginWithWallet(networkID, address, signature)` | Exchange the signed challenge for a title session. | `ClientState` |\n| `loginWithGoogle(googleIDToken)` | Login with a Google ID token. | `ClientState` |\n| `loginWithSsoCode(code)` | Exchange a one-time code from idosgames.com for a title session. **Web only** — see below. | `ClientState` |\n| `forgotPassword(email)` | Trigger a password-reset email (a 6-digit code). | `SuccessResponse` |\n| `resetPassword(email, resetToken, password)` | Complete a password reset using the emailed code. | `SuccessResponse` |\n| `autoLogin()` | Replay the last-used auth method (Email/Device/None/Telegram only — fails with `reason: \"client\"` for Google/Facebook/GooglePlay/platform-token). | `ClientState` |\n| `refreshSession()` | Re-authenticate and return a fresh session ticket; used internally by the transport on 401. | `string \\| null` (not an `OperationResult`) |\n| `logout()` | Clear the session, forget the saved login method, and reset the local cache. Synchronous, no network call. | `void` |\n| `setRememberSession(remember)` | \"Remember me\" — whether the NEXT login is persisted for `autoLogin()`. Default `true`. Call before a `login*` method. | `void` |\n| `AuthenticationService.isValidEmail(email)` | Static, synchronous client-side format check. | `boolean` |\n| `AuthenticationService.isValidPasswordLength(pw)` | Static, synchronous length check (8–100 chars). | `boolean` |\n\n⚠ **Each title has its OWN password.** The same address in two games means two independent\npasswords: resetting in one game does not change the login for the other. The reason is that the\nreset e-mail goes out through the PUBLISHER's SMTP — with one shared password, one publisher's mail\nserver would control access to every other publisher's game. So don't tell the player \"the same\npassword as in your other game\", and don't reuse stored credentials across titles.\nThe IDENTITY is still shared: Google, Apple and the idosgames.com sign-in recognise the same person\nin every game. Identity answers \"who is this\", not \"what proves they may sign in\".\n\n⚠ **Signing in through idosgames.com from a NATIVE build is not in this SDK.** `beginSsoRedirect` /\n`loginWithSsoCode` are the web half: the browser comes back to the same page with the code in the\nURL fragment. In a packaged Android/iOS build the browser is a separate program that tells the app\nnothing, so that flow uses a request the game polls for instead (`BeginNativeSsoRequest` /\n`PollNativeSsoRequest`), and it is implemented in the Unity SDK. Don't reach for `loginWithSsoCode`\nfrom a native wrapper — it has no way to receive the code.\n\n⚠ **That native flow now has a SHORT CODE, and a native client should use it.** `BeginNativeSsoRequest`\naccepts `UseUserCode: true` and then answers with `UserCode` (`WDJB-MJHT`) plus `VerificationUri`.\nThe game displays the code; the player opens the plain URL and types it there. The older shape — the\ngame opening `…/sso?title=X&request=<handle>` and the page confirming on its own — still works for\nalready-shipped builds, but **a request created with a code refuses that path**, so a build must do\none or the other, never a mix.\n\nThe reason is not convenience. In the older shape the handle travels IN THE ADDRESS, so the link can\nbe sent to somebody else: the attacker creates the request on their own device, the victim opens the\nlink and confirms, and the attacker's game gets a session as the victim. PKCE does not help (the\nverifier belongs to whoever created the request). With a code there is nothing in the URL to forward\n— the request is named only by what is on the device's own screen. `GetAuthOptions` reports\n`NativeSso.UserCodeSupported` and `NativeSso.PollIntervalSeconds`; ask before assuming, and follow\nthe interval or the poll quota will refuse you.\n\n⚠ **The code is shown, the secret is not.** Players read codes off screens, over shoulders and out\nof screenshots — so the code alone must never buy a session. Polling keeps requiring the request\nsecret, which never leaves the game.\n\nNon-Promise instance getters (read directly, no `await`):\n\n| Getter | Returns |\n| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `client.auth.context` | `AuthContext \\| null` — `{ userID, clientSessionTicket, clientSessionTicketExpiration, platformUserID?, platformAuthToken?, platformAuthTokenExpiration? }`, or `null` if never logged in. |\n| `client.auth.isLoggedIn` | `true` once `context` has a non-empty `userID` and `clientSessionTicket`. |\n| `client.auth.lastAuthType` | The persisted `AuthType` (`\"None\" \\| \"Device\" \\| \"Email\" \\| \"iDosGames\" \\| \"Facebook\" \\| \"Google\" \\| \"GooglePlay\" \\| \"Telegram\"`) from the previous successful login, read from local storage. |\n\nOn a successful login/register call, the SDK mirrors the full `ClientState`\ninto `client.data` (title config + user state) — same cache every other\nmodule reads from — and emits events. `email`/`password` are persisted to\nlocal storage **only** after a successful `loginWithEmail` or\n`confirmEmailRegistration` call, so `autoLogin()` has something to replay.\n⚠ Note it is the CONFIRMATION, not `registerWithEmail`, that persists them:\nregistration alone creates no account, so there is nothing to replay yet (the\npassword is carried over from the first step internally). A leftover\nusername you pass in is only a fallback — Google logins use the Google\nprofile name, platform-token logins use the platform profile name, and if\nnone is available anywhere the backend assigns a generated one (see Gotchas).\n\n## Events\n\nSubscribe with `client.on(...)`; each returns an unsubscribe fn.\n\n- `auth:requestSent` → `void` — fired at the start of every login/reset call (before the network round-trip). One exception: `loginWithSsoCode` validates its argument first, so an empty-code `reason: \"client\"` failure doesn't fire it.\n- `auth:loggedIn` → `void` — fired after a login/register call succeeds and `ClientState` has been applied to the cache.\n- `auth:loggedOut` → `void` — fired synchronously by `logout()`.\n- `auth:unauthorized` → `void` — transport-level, fired by the HTTP layer only when a 401 could **not** be transparently recovered (the automatic refresh was unavailable, already attempted, or failed). A 401 that the refresh-and-retry rescues never emits it. Not emitted by `AuthenticationService` itself.\n- `user:clientStateReceived` → `ClientState` — fired whenever a full client state is applied (login, or any other flow that re-fetches it).\n- `user:stateUpdated` → `void` — fired whenever the cached `User` half of `ClientState` is replaced, which includes every successful login.\n- `user:anyUpdated` → `void` — coarsest \"something in the user cache changed\" signal; also fires on login.\n\n```ts\nconst off = client.on(\"auth:loggedIn\", () => {\n console.log(\"logged in as\", client.auth.context?.userID);\n});\n// later: off();\n```\n\n## Recipes\n\n### Guest login on first launch\n\n```ts\nconst result = await client.auth.loginWithDeviceID();\nif (!result.ok) return showError(result.error ?? result.reason);\n// client.data now has the full ClientState; render the game.\n```\n\n### Try auto-login first, fall back appropriately\n\n```ts\nasync function bootstrap() {\n const result = await client.auth.autoLogin();\n if (result.ok) return; // resumed the last session\n if (result.reason === \"client\" && client.auth.lastAuthType !== \"None\") {\n // Last session used Google/Facebook/GooglePlay/a platform token — autoLogin\n // can't replay that silently. Re-run that platform's sign-in flow and call\n // the matching login method (e.g. loginWithGoogle) with a fresh token.\n return reauthenticateViaPlatformSDK(client.auth.lastAuthType);\n }\n showError(result.error ?? result.reason);\n}\n```\n\n`autoLogin()` safely self-replays Email, Device/None, and Telegram — call it\nonce on app start for those. For anything else it deliberately does **not**\nfall back to a guest login (see Gotchas) — treat its `reason: \"client\"`\nfailure as \"go get a fresh token,\" not as a generic error to toast.\n\n### Register a new account with email\n\n```ts\nif (!AuthenticationService.isValidEmail(email)) {\n return showFieldError(\"email\", \"Enter a valid email address.\");\n}\nif (!AuthenticationService.isValidPasswordLength(password)) {\n return showFieldError(\"password\", \"Password must be 8–100 characters.\");\n}\n\nconst started = await client.auth.registerWithEmail(email, password);\nif (!started.ok) return showError(started.error ?? started.reason);\n\n// No account yet — a code was mailed. Show a code screen; the session arrives from confirm.\nconst done = await client.auth.confirmEmailRegistration(email, codeFromPlayer);\nif (!done.ok) return showError(done.error ?? done.reason);\n```\n\n⚠ **`registerWithEmail` never creates an account, and success does not mean the address was\nfree.**\n\nRegistration always stores the attempt and mails a 6-digit code; the player is created by\n`confirmEmailRegistration`. Building a screen that assumes an immediate session will leave players\nstaring at a spinner that never resolves.\n\nConfirmation is **platform behaviour, not a title setting** — there is no flag to switch it off,\nand no `verificationRequired` branch to write. Only the numbers are configurable (code lifetime,\nattempt cap, resend cooldown).\n\nThe answer is also deliberately **identical for a free and for a taken address** — there is no\n`EMAIL_ALREADY_EXISTS` on this path any more. Telling them apart would turn the registration form\ninto a way of checking whether a given person has an account here, which is exactly what the\npassword-recovery form goes out of its way to avoid. The owner of a taken address gets a \"you\nalready have an account\" e-mail instead, without a code.\n\nOne failure on this path **is** reported: `EMAIL_SENDER_NOT_CONFIGURED`, when the server has no\nusable mail sender at all. It says nothing about the address — the same answer comes back for a\nfree one, a taken one and a typo — and it exists because confirmation cannot be switched off: with\nno sender, e-mail registration does not work at all, and answering \"code sent\" would hide a broken\ndeployment behind a normal-looking screen. Show it as a server-side problem, not as the player's\nmistake, and do not offer a \"resend\" — the resend refuses the same way. A letter that merely fails\nto leave is a different case and still answers success.\n\nEvery way of getting the code wrong — no such registration, expired, mismatched — answers with the\nsame `INVALID_VERIFICATION_CODE`, for the same reason. Do not branch on it.\n\n`resendVerificationCode` mails a **new** code: only its hash is stored, so the previous one cannot\nbe re-sent and stops working. Rate-limit the button in the UI (the server's cooldown is reported as\n`resendCooldownSeconds`) — the server answers successfully even when it sent nothing.\n\nEmail is matched case-insensitively — the backend trims and lowercases it\nbefore every lookup and write, so `Player@Mail.com` and `player@mail.com`\ncollide on the same account.\n\n### Upgrade a guest account to an email account\n\nThe SDK has no dedicated \"link email to this guest\" call — `registerWithEmail`\nalways mints its **own** account (a fresh UserID derived from the email, via a\ndifferent hash than the device-id account uses). To move a guest forward\nwithout losing their progress, do it through your own game-side flow (e.g. a\ncloud script that copies/merges state) rather than assuming registration\ncarries the guest's inventory along; don't build a UI that implies it will.\n\n### Forgot / reset password\n\n```ts\nconst sent = await client.auth.forgotPassword(email);\nif (!sent.ok) return showError(sent.error ?? sent.reason);\n// If an account exists for this email, a 6-digit reset code was emailed,\n// valid for 5 minutes. The response looks identical whether or not the\n// email is registered (see Gotchas) — don't tell the player \"no such account.\"\n\nconst reset = await client.auth.resetPassword(email, resetToken, newPassword);\nif (!reset.ok) return showError(reset.error ?? reset.reason);\n// password changed; call loginWithEmail with the new password next\n```\n\n### Handle a rejected login\n\n```ts\nconst result = await client.auth.loginWithEmail(email, password);\nif (!result.ok) {\n switch (result.reason) {\n case \"connection\":\n return offerRetry();\n case \"throttled\":\n return; // ignore — same call already in flight/just ran\n case \"client\":\n case \"server\":\n default:\n return showError(result.error ?? \"Login failed.\");\n }\n}\n```\n\n### Log out\n\n```ts\nclient.auth.logout(); // synchronous — clears context + resets client.data cache\n// route to login screen; no network call is made\n```\n\n## Gotchas\n\n- **A title's login mode can refuse methods** (`cfg.Blockchain.PlayAccess`). `WalletOnly` accepts\n only wallet login (others fail with `PLAY_ACCESS_WALLET_LOGIN_ONLY`); `AnyWithLinkedWallet` refuses\n guests (`PLAY_ACCESS_GUEST_DISABLED`) and lets other logins in with `client.auth.playAccess.Granted\n=== false` until a wallet is linked and holds enough tokens. Read the mode BEFORE login with\n `client.auth.getAuthOptions()` (`PlayAccessMode`) to hide dead buttons. The host template does all\n of this already — see the `blockchain-system` skill, \"Login mode and play access\".\n- **`autoLogin()` deliberately refuses to guess for federated/platform\n logins.** The backend derives DeviceID UserIDs from\n `SHA256(platform + device + deviceID)` and email/platform-linked UserIDs\n from `SHA256(email + titleID)` — two different hashes with no server-side\n link between them. Falling back to `loginWithDeviceID()` for a\n Google/Facebook/GooglePlay/platform-token session would silently resolve to\n a different, empty account, not \"safely resume as a guest.\" If\n `lastAuthType` is one of those, `autoLogin()` returns\n `{ ok: false, reason: \"client\" }` instead; the app must obtain a fresh token\n from that platform's SDK and call the matching `login*` method itself.\n- **The exact `error` strings on `reason: \"server\"` are backend-defined\n codes/messages**, not prose meant for direct display — surface them through\n your own copy/localization layer rather than showing them raw. Verified\n values from the backend for the flows above: `\"INVALID_INPUT_DATA\"`\n (missing/blank required field) and `\"INCORRECT_EMAIL_OR_PASSWORD\"` (bad\n credentials **or** unknown email — the backend intentionally doesn't\n distinguish the two, so don't tell the player \"no such account\") and\n `\"INVALID_VERIFICATION_CODE\"` (every way of getting the confirmation code\n wrong, collapsed into one) are shared\n `MessageCode` enum values also used elsewhere in the backend;\n `\"EMAIL_ALREADY_EXISTS\"` is **no longer returned by registration** — the form\n answers identically for a free and for a taken address, on purpose;\n `\"RATE_LIMIT_EXCEEDED\"` / `\"OPERATION_IN_PROGRESS\"` (per-account login lock\n — see below) are the same enum family. Google/platform-token logins instead\n return ad-hoc string literals specific to that flow, e.g. `\"BANNED_GLOBAL\"`\n (platform account is banned), `\"GOOGLE_ACCOUNT_CONFLICT\"` (email already\n linked to a _different_ Google account), `\"INVALID_GOOGLE_TOKEN\"`\n (bad/expired Google ID token) — see\n [references/data-model.md](references/data-model.md) for the full list.\n Telegram login instead surfaces plain sentences like `\"Invalid Telegram\ndata\"` / an internal `\"Telegram auth_date is stale\"` condition (initData\n older than 24h or timestamped implausibly in the future) — treat any\n non-uppercase-code string as an opaque message, not something to\n pattern-match on.\n- **Per-account login is rate-limited server-side, independent of the SDK's\n own 600 ms throttle.** Repeated `loginWithEmail` attempts for the same\n account inside a ~1-second window come back `\"RATE_LIMIT_EXCEEDED\"`; a login\n already being processed for that account comes back\n `\"OPERATION_IN_PROGRESS\"`. This is a brute-force guard, not a bug — don't\n retry-loop past it.\n- **Telegram login needs the platform adapter's init data.** `loginWithTelegram()`\n calls `platform.getTelegramInitDataRaw()` first; if that returns falsy (not\n running inside Telegram, or the adapter doesn't support it), the call fails\n client-side with `reason: \"client\"` before any network request — no point\n retrying without fixing the environment. Server-side, the init data is\n rejected if its `auth_date` is missing, more than 24 hours old, or more than\n 5 minutes in the future — a Telegram Mini App that's been idle a long time\n may need a fresh WebApp launch, not just a retry. On success it's recorded\n under its own `AuthType.Telegram` (not `Device`) precisely so `autoLogin()`\n replays `loginWithTelegram()` again rather than a device-id login.\n- **`loginWithPlatformToken` no longer exists.** The site used to hand games the\n platform auth token — a 24-hour string that also authorizes the whole\n management API. It was replaced by the one-time SSO code\n (`loginWithSsoCode`), and the endpoint has since been removed as unreachable.\n A session opened by that code is still recorded under `AuthType.iDosGames`,\n which is what `lastAuthType` reports afterward.\n- **A username you pass in is a last resort, not a guarantee.** For Google and\n platform-token logins, the backend prefers the identity provider's own\n profile name over any client-supplied username on every login (not just the\n first) — so a locally cached display name can be silently overwritten by the\n linked account's name. If no name is available from any source at\n registration time, the backend assigns a generated one\n (`\"BraveTiger482\"`-style: adjective + noun + 2–4 digit number) rather than\n leaving it blank.\n- **`forgotPassword` never reveals whether an email is registered.** Unknown\n emails and known emails both return `{ ok: true }` with no email actually\n sent for the unknown case — this is a deliberate anti-enumeration measure,\n not a bug to work around. The emailed reset code is a 6-digit number valid\n for 5 minutes; requesting again inside a 60-second cooldown silently\n no-ops (still returns `ok: true`, no second email). `resetPassword` allows\n at most 5 wrong-code attempts before the code is invalidated server-side and\n a fresh `forgotPassword` call is required.\n ⚠ **The remaining-attempt count is NOT in the response any more**, and neither\n is \"no such account\": every outcome of `resetPassword` — unknown address, no\n code requested, expired code, wrong code — answers `\"INVALID_RESET_CODE\"`, and\n an exhausted code answers `\"RESET_CODE_ATTEMPTS_EXCEEDED\"`. Reporting the\n remaining count both confirmed the account existed and told an attacker how\n much room was left. Don't parse a number out of `error`.\n- **Email credentials are only saved on success.** `loginWithEmail` and\n `confirmEmailRegistration` persist email+password to local storage (scoped by\n `titleID`) only after `fetchAndApplyClientState` succeeds — a failed login\n doesn't overwrite previously saved credentials, and a fresh install has\n nothing saved until the first successful email login. `registerWithEmail` on\n its own saves nothing: at that point the account does not exist yet.\n- **`refreshSession()` has a re-entrancy guard.** If it's already running\n (e.g. two requests 401 at nearly the same time), a second call returns `null`\n immediately instead of recursing — this exists to avoid deadlocking the\n retry, so don't assume a `null` result means the session is actually dead.\n- **`logout()` forgets the saved login method too (changed in core 0.1.3).** It\n nulls the auth context, wipes the cached user state and title-config bundle,\n clears `lastAuthType` and any saved email/password, and emits\n `auth:loggedOut` — so a later `autoLogin()` has nothing to resume. Before\n 0.1.3 storage survived a logout and the next launch silently signed the\n player back into the account they had just left. If you want a sign-out the\n player is remembered through, don't call `logout()`.\n- **Never reload the page after `logout()`** (or after deleting the account). The host shell\n (`AuthGate`) returns to the sign-in screen by itself on `auth:loggedOut`. A `location.reload()`\n restarts the whole app for nothing and, in the AI Coder's live preview, left a dark empty frame:\n the preview's files arrive by message and do not survive a reload.\n- **`refreshSession()` and `logout()` don't return `OperationResult`.**\n `refreshSession()` resolves to `string | null` (the fresh session ticket, or\n `null` on failure/no saved method); `logout()` is synchronous `void`. Don't\n branch on `.ok` for these two.\n- **`GameLoop` is excluded from the login `ClientState`.** Board/stage state\n and its definitions are fetched separately per-stage by the GameLoop\n feature, not bundled into every login response.\n- **Guard against double-submit.** Each call fires a real request; a\n double-tapped \"Log in\" button can fire twice. Firing the same auth endpoint\n again inside the SDK's own throttle window (default 600 ms) comes back\n `reason: \"throttled\"` rather than duplicating the call, but disable the\n control while a call is in flight rather than relying on that — and note the\n server has its own, stricter per-account lock on top (see above).\n\n## Full reference\n\n[references/data-model.md](references/data-model.md) — request/response wire\nshapes, the exact backend validation and error-code rules for each login/reset\npath, UserID derivation, and the default-username generator. Read it when you\nneed to reason about _why_ a specific `error` string came back, or when\nbuilding a password-reset or registration UI that needs to match the backend's\ntiming/attempt rules exactly.\n",
|
|
4
|
+
"content": "---\nname: authentication\ndescription: >-\n Log players into a game on the iDosGames TypeScript SDK (@idosgames/core)\n via client.auth (AuthenticationService): guest/device-id login, two-step\n email registration with a confirmation code, email login, Google/Telegram\n login, SSO-code login from idosgames.com, wallet login, password reset, auto\n login on relaunch, session refresh, logout, and client-side email/password\n validation. Use this whenever the user is working in the iDosGames TS SDK or\n its game templates (board-game, idle-rpg) and asks about logging a player\n in, sessions, registration, email confirmation codes, resending a code,\n guest accounts, device-id login, Telegram login, Google login, SSO login,\n wallet login, forgot/reset password, auto-login, isLoggedIn, or otherwise\n touches client.auth, AuthenticationService, or AuthContext — even if they\n don't name the module explicitly.\n---\n\n# Authentication (iDosGames TS SDK)\n\nThe Authentication module is how a player gets a session. It's the one module\nevery other feature depends on: nothing else on `client` works until a login\nmethod has succeeded. Unlike feature modules, most of its methods don't return\na narrow per-feature payload — they return the **entire post-login bootstrap\nstate** (`ClientState`: title config + the player's full `User` state),\nbecause a successful login is also \"give me everything the client needs to\nrender.\"\n\nThis skill is for **using** production login flows, not for porting or\nextending the service. If a login is rejected, that's the backend enforcing a\nrule (bad credentials, duplicate email, banned account) — surface the error,\ndon't try to reproduce the check client-side.\n\n## Remember me\n\n`setRememberSession(remember)` decides whether a successful login is written to storage. Call it\n**before** a `login*` method — it is read when that login completes, and it applies to whichever\nprovider runs next.\n\n```ts\nclient.auth.setRememberSession(rememberCheckbox); // default: true\nconst result = await client.auth.loginWithDeviceID();\n```\n\n- **On** (the default, and how every release before core 0.1.3 behaved) — the session is persisted,\n so `autoLogin()` signs the player back in on the next launch.\n- **Off** — nothing is persisted and any previously remembered session is dropped, so the next\n launch opens on the login screen. The current session is NOT weakened: the credentials stay in\n memory for this tab, so the transport's automatic 401 re-login still works.\n\n`logout()` ends the session and clears the persisted one, so a reload does not walk back into the\naccount the player just left. (Before core 0.1.3 it left storage untouched and a reload silently\nsigned them back in.)\n\nSessions are extended by the **refresh token** (`Authentication/RefreshSession`, core ≥ 0.18): every\nlogin returns one, it is kept in memory and — when remembering — in storage, and rotated on every\nrefresh. A 401 and a cold-start `autoLogin()` use it first, so ANY method comes back, wallet and\nGoogle included; replaying the login method is only the fallback for a missing/expired token. On a\ntitle whose login mode needs a token balance the server re-checks it on that refresh; a balance\nthat dropped closes the game (`client.auth.playAccess.Granted === false`), it does not end the session.\n\n## Mental model\n\n- **Guest login** (`loginWithDeviceID`) — anonymous account keyed off a\n per-device ID the platform adapter generates/stores. Zero-friction first\n launch; no credentials to lose, but also nothing to recover if the device ID\n is gone (reinstall, new device).\n- **Linked login methods** — `loginWithEmail` / `registerWithEmail`,\n `loginWithGoogle`, `loginWithTelegram`, `loginWithSsoCode`. These tie\n the account to a real identity so the player can resume it elsewhere.\n- **`autoLogin()`** picks up where the player left off. It first extends the\n remembered session by its **refresh token** (works for every method). Only\n without a usable token does it fall back to replaying — and that fallback\n covers just the methods that don't need a fresh externally-issued token: it replays `loginWithEmail`\n if the last successful login was Email (saved password), `loginWithDeviceID`\n if it was Device/None, and `loginWithTelegram` if it was Telegram (its\n `initData` is re-read live from the Telegram WebApp bridge each time, not\n stored). For Google/Facebook/GooglePlay/platform-token, there's no stored\n credential to replay — `autoLogin()` returns `reason: \"client\"` instead of\n guessing, because DeviceID and email/platform logins hash to **different\n backend UserIDs** (see Gotchas), so silently falling back to a guest login\n would strand the player on an unrelated empty account. What `autoLogin()`\n has to replay is controlled by **\"remember me\"** — see below. Call this on app\n start instead of hand-rolling \"which method did they use last,\" but be ready\n to handle its failure by re-running the platform's sign-in flow.\n- **Session refresh is automatic.** The HTTP transport calls\n `refreshSession()` itself when a request comes back 401 — it calls the\n server's `RefreshSession` with the refresh token (falling back to replaying\n the login method only without a usable token) and retries once. You almost never call\n `refreshSession()` directly; it's documented here for completeness, not as a\n method you wire up in app code.\n- **Static validators** (`AuthenticationService.isValidEmail`,\n `AuthenticationService.isValidPasswordLength`) are plain synchronous\n functions, not calls to the backend — use them to validate a form before\n spending a network round-trip on a login/register call that will fail\n server-side anyway. They mirror, but do not replace, the server's own\n checks — the server always re-validates.\n\n## Setup\n\n```ts\nimport { createIDosGamesClient } from \"@idosgames/core\";\n\nconst client = createIDosGamesClient({ titleID: \"your-title-id\" });\nawait client.auth.loginWithDeviceID(); // or any other auth.* login method\n\nclient.auth.isLoggedIn; // true once a login call has succeeded\n```\n\nEvery other module's methods require this to have succeeded first — without a\nsession they return `{ ok: false, reason: \"unauthorized\" }` rather than\nthrowing. There is one `client` per player; don't share it across sessions.\nAuthentication requests carry no Bearer ticket at all — login/register/reset\nare the one family of calls that work before you have a session.\n\n## Methods\n\nAll login/register/reset methods return `Promise<OperationResult<T>>`: either\n`{ ok: true, data }` or `{ ok: false, reason, error }`. Always branch on\n`result.ok` before touching `result.data`. `reason` is one of `\"client\"` (bad\nlocal args, e.g. missing Telegram initData or empty platform token),\n`\"unauthorized\"`, `\"throttled\"` (fired the same endpoint again inside the\nthrottle window), `\"connection\"` (transient, offer Retry), `\"validation\"`\n(response/schema drift), or `\"server\"` (backend rejected it — `error` carries\nthe reason code the backend returned, e.g. `\"INCORRECT_EMAIL_OR_PASSWORD\"`,\n`\"INVALID_VERIFICATION_CODE\"` — see Gotchas for the verbatim set).\n\n| Method | Purpose | `data` on success |\n| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |\n| `loginWithDeviceID()` | Anonymous/guest login keyed off the device ID. | `ClientState` |\n| `loginWithTelegram()` | Login using the Telegram Mini App's init data. | `ClientState` |\n| `loginWithEmail(email, password)` | Login with email + password. | `ClientState` |\n| `registerWithEmail(email, password)` | **Start** a registration. Only mails a code — never returns a session, see below. | `EmailRegistrationOutcome` |\n| `confirmEmailRegistration(email, code)` | Finish the registration with the code from the email, creating the player. | `ClientState` |\n| `resendVerificationCode(email)` | Mail a fresh code. Resolves successfully whatever happened — except when there is no usable sender at all (`EMAIL_SENDER_NOT_CONFIGURED`). | `void` |\n| `requestWalletChallenge(networkID, address)` | Ask for the message the player's wallet must sign. Step one of wallet login. | `WalletChallengeResponse` |\n| `loginWithWallet(networkID, address, signature)` | Exchange the signed challenge for a title session. | `ClientState` |\n| `loginWithGoogle(googleIDToken)` | Login with a Google ID token. | `ClientState` |\n| `loginWithSsoCode(code)` | Exchange a one-time code from idosgames.com for a title session. **Web only** — see below. | `ClientState` |\n| `forgotPassword(email)` | Trigger a password-reset email (a 6-digit code). | `SuccessResponse` |\n| `resetPassword(email, resetToken, password)` | Complete a password reset using the emailed code. | `SuccessResponse` |\n| `autoLogin()` | Replay the last-used auth method (Email/Device/None/Telegram only — fails with `reason: \"client\"` for Google/Facebook/GooglePlay/platform-token). | `ClientState` |\n| `refreshSession()` | Re-authenticate and return a fresh session ticket; used internally by the transport on 401. | `string \\| null` (not an `OperationResult`) |\n| `logout()` | Clear the session, forget the saved login method, and reset the local cache. Synchronous, no network call. | `void` |\n| `setRememberSession(remember)` | \"Remember me\" — whether the NEXT login is persisted for `autoLogin()`. Default `true`. Call before a `login*` method. | `void` |\n| `AuthenticationService.isValidEmail(email)` | Static, synchronous client-side format check. | `boolean` |\n| `AuthenticationService.isValidPasswordLength(pw)` | Static, synchronous length check (8–100 chars). | `boolean` |\n\n⚠ **Each title has its OWN password.** The same address in two games means two independent\npasswords: resetting in one game does not change the login for the other. The reason is that the\nreset e-mail goes out through the PUBLISHER's SMTP — with one shared password, one publisher's mail\nserver would control access to every other publisher's game. So don't tell the player \"the same\npassword as in your other game\", and don't reuse stored credentials across titles.\nThe IDENTITY is still shared: Google, Apple and the idosgames.com sign-in recognise the same person\nin every game. Identity answers \"who is this\", not \"what proves they may sign in\".\n\n⚠ **Signing in through idosgames.com from a NATIVE build is not in this SDK.** `beginSsoRedirect` /\n`loginWithSsoCode` are the web half: the browser comes back to the same page with the code in the\nURL fragment. In a packaged Android/iOS build the browser is a separate program that tells the app\nnothing, so that flow uses a request the game polls for instead (`BeginNativeSsoRequest` /\n`PollNativeSsoRequest`), and it is implemented in the Unity SDK. Don't reach for `loginWithSsoCode`\nfrom a native wrapper — it has no way to receive the code.\n\n⚠ **That native flow now has a SHORT CODE, and a native client should use it.** `BeginNativeSsoRequest`\naccepts `UseUserCode: true` and then answers with `UserCode` (`WDJB-MJHT`) plus `VerificationUri`.\nThe game displays the code; the player opens the plain URL and types it there. The older shape — the\ngame opening `…/sso?title=X&request=<handle>` and the page confirming on its own — still works for\nalready-shipped builds, but **a request created with a code refuses that path**, so a build must do\none or the other, never a mix.\n\nThe reason is not convenience. In the older shape the handle travels IN THE ADDRESS, so the link can\nbe sent to somebody else: the attacker creates the request on their own device, the victim opens the\nlink and confirms, and the attacker's game gets a session as the victim. PKCE does not help (the\nverifier belongs to whoever created the request). With a code there is nothing in the URL to forward\n— the request is named only by what is on the device's own screen. `GetAuthOptions` reports\n`NativeSso.UserCodeSupported` and `NativeSso.PollIntervalSeconds`; ask before assuming, and follow\nthe interval or the poll quota will refuse you.\n\n⚠ **The code is shown, the secret is not.** Players read codes off screens, over shoulders and out\nof screenshots — so the code alone must never buy a session. Polling keeps requiring the request\nsecret, which never leaves the game.\n\nNon-Promise instance getters (read directly, no `await`):\n\n| Getter | Returns |\n| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `client.auth.context` | `AuthContext \\| null` — `{ userID, clientSessionTicket, clientSessionTicketExpiration, platformUserID?, platformAuthToken?, platformAuthTokenExpiration? }`, or `null` if never logged in. |\n| `client.auth.isLoggedIn` | `true` once `context` has a non-empty `userID` and `clientSessionTicket`. |\n| `client.auth.lastAuthType` | The persisted `AuthType` (`\"None\" \\| \"Device\" \\| \"Email\" \\| \"iDosGames\" \\| \"Facebook\" \\| \"Google\" \\| \"GooglePlay\" \\| \"Telegram\"`) from the previous successful login, read from local storage. |\n\nOn a successful login/register call, the SDK mirrors the full `ClientState`\ninto `client.data` (title config + user state) — same cache every other\nmodule reads from — and emits events. `email`/`password` are persisted to\nlocal storage **only** after a successful `loginWithEmail` or\n`confirmEmailRegistration` call, so `autoLogin()` has something to replay.\n⚠ Note it is the CONFIRMATION, not `registerWithEmail`, that persists them:\nregistration alone creates no account, so there is nothing to replay yet (the\npassword is carried over from the first step internally). A leftover\nusername you pass in is only a fallback — Google logins use the Google\nprofile name, platform-token logins use the platform profile name, and if\nnone is available anywhere the backend assigns a generated one (see Gotchas).\n\n## Events\n\nSubscribe with `client.on(...)`; each returns an unsubscribe fn.\n\n- `auth:requestSent` → `void` — fired at the start of every login/reset call (before the network round-trip). One exception: `loginWithSsoCode` validates its argument first, so an empty-code `reason: \"client\"` failure doesn't fire it.\n- `auth:loggedIn` → `void` — fired after a login/register call succeeds and `ClientState` has been applied to the cache.\n- `auth:loggedOut` → `void` — fired synchronously by `logout()`.\n- `auth:unauthorized` → `void` — transport-level, fired by the HTTP layer only when a 401 could **not** be transparently recovered (the automatic refresh was unavailable, already attempted, or failed). A 401 that the refresh-and-retry rescues never emits it. Not emitted by `AuthenticationService` itself.\n- `user:clientStateReceived` → `ClientState` — fired whenever a full client state is applied (login, or any other flow that re-fetches it).\n- `user:stateUpdated` → `void` — fired whenever the cached `User` half of `ClientState` is replaced, which includes every successful login.\n- `user:anyUpdated` → `void` — coarsest \"something in the user cache changed\" signal; also fires on login.\n\n```ts\nconst off = client.on(\"auth:loggedIn\", () => {\n console.log(\"logged in as\", client.auth.context?.userID);\n});\n// later: off();\n```\n\n## Recipes\n\n### Guest login on first launch\n\nIn the base template the \"Play as guest\" button is OFF by default; a project turns it on with\n`auth: { guest: true }` in `src/app.config.ts`. The Google button shows only when the title has its\nOWN Google client (`getAuthOptions()` → `Google.Enabled` and not `Google.PlatformFallback`).\n\n```ts\nconst result = await client.auth.loginWithDeviceID();\nif (!result.ok) return showError(result.error ?? result.reason);\n// client.data now has the full ClientState; render the game.\n```\n\n### Try auto-login first, fall back appropriately\n\n```ts\nasync function bootstrap() {\n const result = await client.auth.autoLogin();\n if (result.ok) return; // resumed the last session\n if (result.reason === \"client\" && client.auth.lastAuthType !== \"None\") {\n // Last session used Google/Facebook/GooglePlay/a platform token — autoLogin\n // can't replay that silently. Re-run that platform's sign-in flow and call\n // the matching login method (e.g. loginWithGoogle) with a fresh token.\n return reauthenticateViaPlatformSDK(client.auth.lastAuthType);\n }\n showError(result.error ?? result.reason);\n}\n```\n\n`autoLogin()` safely self-replays Email, Device/None, and Telegram — call it\nonce on app start for those. For anything else it deliberately does **not**\nfall back to a guest login (see Gotchas) — treat its `reason: \"client\"`\nfailure as \"go get a fresh token,\" not as a generic error to toast.\n\n### Register a new account with email\n\n```ts\nif (!AuthenticationService.isValidEmail(email)) {\n return showFieldError(\"email\", \"Enter a valid email address.\");\n}\nif (!AuthenticationService.isValidPasswordLength(password)) {\n return showFieldError(\"password\", \"Password must be 8–100 characters.\");\n}\n\nconst started = await client.auth.registerWithEmail(email, password);\nif (!started.ok) return showError(started.error ?? started.reason);\n\n// No account yet — a code was mailed. Show a code screen; the session arrives from confirm.\nconst done = await client.auth.confirmEmailRegistration(email, codeFromPlayer);\nif (!done.ok) return showError(done.error ?? done.reason);\n```\n\n⚠ **`registerWithEmail` never creates an account, and success does not mean the address was\nfree.**\n\nRegistration always stores the attempt and mails a 6-digit code; the player is created by\n`confirmEmailRegistration`. Building a screen that assumes an immediate session will leave players\nstaring at a spinner that never resolves.\n\nConfirmation is **platform behaviour, not a title setting** — there is no flag to switch it off,\nand no `verificationRequired` branch to write. Only the numbers are configurable (code lifetime,\nattempt cap, resend cooldown).\n\nThe answer is also deliberately **identical for a free and for a taken address** — there is no\n`EMAIL_ALREADY_EXISTS` on this path any more. Telling them apart would turn the registration form\ninto a way of checking whether a given person has an account here, which is exactly what the\npassword-recovery form goes out of its way to avoid. The owner of a taken address gets a \"you\nalready have an account\" e-mail instead, without a code.\n\nOne failure on this path **is** reported: `EMAIL_SENDER_NOT_CONFIGURED`, when the server has no\nusable mail sender at all. It says nothing about the address — the same answer comes back for a\nfree one, a taken one and a typo — and it exists because confirmation cannot be switched off: with\nno sender, e-mail registration does not work at all, and answering \"code sent\" would hide a broken\ndeployment behind a normal-looking screen. Show it as a server-side problem, not as the player's\nmistake, and do not offer a \"resend\" — the resend refuses the same way. A letter that merely fails\nto leave is a different case and still answers success.\n\nEvery way of getting the code wrong — no such registration, expired, mismatched — answers with the\nsame `INVALID_VERIFICATION_CODE`, for the same reason. Do not branch on it.\n\n`resendVerificationCode` mails a **new** code: only its hash is stored, so the previous one cannot\nbe re-sent and stops working. Rate-limit the button in the UI (the server's cooldown is reported as\n`resendCooldownSeconds`) — the server answers successfully even when it sent nothing.\n\nEmail is matched case-insensitively — the backend trims and lowercases it\nbefore every lookup and write, so `Player@Mail.com` and `player@mail.com`\ncollide on the same account.\n\n### Upgrade a guest account to an email account\n\nThe SDK has no dedicated \"link email to this guest\" call — `registerWithEmail`\nalways mints its **own** account (a fresh UserID derived from the email, via a\ndifferent hash than the device-id account uses). To move a guest forward\nwithout losing their progress, do it through your own game-side flow (e.g. a\ncloud script that copies/merges state) rather than assuming registration\ncarries the guest's inventory along; don't build a UI that implies it will.\n\n### Forgot / reset password\n\n```ts\nconst sent = await client.auth.forgotPassword(email);\nif (!sent.ok) return showError(sent.error ?? sent.reason);\n// If an account exists for this email, a 6-digit reset code was emailed,\n// valid for 5 minutes. The response looks identical whether or not the\n// email is registered (see Gotchas) — don't tell the player \"no such account.\"\n\nconst reset = await client.auth.resetPassword(email, resetToken, newPassword);\nif (!reset.ok) return showError(reset.error ?? reset.reason);\n// password changed; call loginWithEmail with the new password next\n```\n\n### Handle a rejected login\n\n```ts\nconst result = await client.auth.loginWithEmail(email, password);\nif (!result.ok) {\n switch (result.reason) {\n case \"connection\":\n return offerRetry();\n case \"throttled\":\n return; // ignore — same call already in flight/just ran\n case \"client\":\n case \"server\":\n default:\n return showError(result.error ?? \"Login failed.\");\n }\n}\n```\n\n### Log out\n\n```ts\nclient.auth.logout(); // synchronous — clears context + resets client.data cache\n// route to login screen; no network call is made\n```\n\n## Gotchas\n\n- **A title's login mode can refuse methods** (`cfg.Blockchain.PlayAccess`). `WalletOnly` accepts\n only wallet login (others fail with `PLAY_ACCESS_WALLET_LOGIN_ONLY`); `AnyWithLinkedWallet` refuses\n guests (`PLAY_ACCESS_GUEST_DISABLED`) and lets other logins in with `client.auth.playAccess.Granted\n=== false` until a wallet is linked and holds enough tokens. Read the mode BEFORE login with\n `client.auth.getAuthOptions()` (`PlayAccessMode`) to hide dead buttons. The host template does all\n of this already — see the `blockchain-system` skill, \"Login mode and play access\".\n- **`autoLogin()` deliberately refuses to guess for federated/platform\n logins.** The backend derives DeviceID UserIDs from\n `SHA256(platform + device + deviceID)` and email/platform-linked UserIDs\n from `SHA256(email + titleID)` — two different hashes with no server-side\n link between them. Falling back to `loginWithDeviceID()` for a\n Google/Facebook/GooglePlay/platform-token session would silently resolve to\n a different, empty account, not \"safely resume as a guest.\" If\n `lastAuthType` is one of those, `autoLogin()` returns\n `{ ok: false, reason: \"client\" }` instead; the app must obtain a fresh token\n from that platform's SDK and call the matching `login*` method itself.\n- **The exact `error` strings on `reason: \"server\"` are backend-defined\n codes/messages**, not prose meant for direct display — surface them through\n your own copy/localization layer rather than showing them raw. Verified\n values from the backend for the flows above: `\"INVALID_INPUT_DATA\"`\n (missing/blank required field) and `\"INCORRECT_EMAIL_OR_PASSWORD\"` (bad\n credentials **or** unknown email — the backend intentionally doesn't\n distinguish the two, so don't tell the player \"no such account\") and\n `\"INVALID_VERIFICATION_CODE\"` (every way of getting the confirmation code\n wrong, collapsed into one) are shared\n `MessageCode` enum values also used elsewhere in the backend;\n `\"EMAIL_ALREADY_EXISTS\"` is **no longer returned by registration** — the form\n answers identically for a free and for a taken address, on purpose;\n `\"RATE_LIMIT_EXCEEDED\"` / `\"OPERATION_IN_PROGRESS\"` (per-account login lock\n — see below) are the same enum family. Google/platform-token logins instead\n return ad-hoc string literals specific to that flow, e.g. `\"BANNED_GLOBAL\"`\n (platform account is banned), `\"GOOGLE_ACCOUNT_CONFLICT\"` (email already\n linked to a _different_ Google account), `\"INVALID_GOOGLE_TOKEN\"`\n (bad/expired Google ID token) — see\n [references/data-model.md](references/data-model.md) for the full list.\n Telegram login instead surfaces plain sentences like `\"Invalid Telegram\ndata\"` / an internal `\"Telegram auth_date is stale\"` condition (initData\n older than 24h or timestamped implausibly in the future) — treat any\n non-uppercase-code string as an opaque message, not something to\n pattern-match on.\n- **Per-account login is rate-limited server-side, independent of the SDK's\n own 600 ms throttle.** Repeated `loginWithEmail` attempts for the same\n account inside a ~1-second window come back `\"RATE_LIMIT_EXCEEDED\"`; a login\n already being processed for that account comes back\n `\"OPERATION_IN_PROGRESS\"`. This is a brute-force guard, not a bug — don't\n retry-loop past it.\n- **Telegram login needs the platform adapter's init data.** `loginWithTelegram()`\n calls `platform.getTelegramInitDataRaw()` first; if that returns falsy (not\n running inside Telegram, or the adapter doesn't support it), the call fails\n client-side with `reason: \"client\"` before any network request — no point\n retrying without fixing the environment. Server-side, the init data is\n rejected if its `auth_date` is missing, more than 24 hours old, or more than\n 5 minutes in the future — a Telegram Mini App that's been idle a long time\n may need a fresh WebApp launch, not just a retry. On success it's recorded\n under its own `AuthType.Telegram` (not `Device`) precisely so `autoLogin()`\n replays `loginWithTelegram()` again rather than a device-id login.\n- **`loginWithPlatformToken` no longer exists.** The site used to hand games the\n platform auth token — a 24-hour string that also authorizes the whole\n management API. It was replaced by the one-time SSO code\n (`loginWithSsoCode`), and the endpoint has since been removed as unreachable.\n A session opened by that code is still recorded under `AuthType.iDosGames`,\n which is what `lastAuthType` reports afterward.\n- **A username you pass in is a last resort, not a guarantee.** For Google and\n platform-token logins, the backend prefers the identity provider's own\n profile name over any client-supplied username on every login (not just the\n first) — so a locally cached display name can be silently overwritten by the\n linked account's name. If no name is available from any source at\n registration time, the backend assigns a generated one\n (`\"BraveTiger482\"`-style: adjective + noun + 2–4 digit number) rather than\n leaving it blank.\n- **`forgotPassword` never reveals whether an email is registered.** Unknown\n emails and known emails both return `{ ok: true }` with no email actually\n sent for the unknown case — this is a deliberate anti-enumeration measure,\n not a bug to work around. The emailed reset code is a 6-digit number valid\n for 5 minutes; requesting again inside a 60-second cooldown silently\n no-ops (still returns `ok: true`, no second email). `resetPassword` allows\n at most 5 wrong-code attempts before the code is invalidated server-side and\n a fresh `forgotPassword` call is required.\n ⚠ **The remaining-attempt count is NOT in the response any more**, and neither\n is \"no such account\": every outcome of `resetPassword` — unknown address, no\n code requested, expired code, wrong code — answers `\"INVALID_RESET_CODE\"`, and\n an exhausted code answers `\"RESET_CODE_ATTEMPTS_EXCEEDED\"`. Reporting the\n remaining count both confirmed the account existed and told an attacker how\n much room was left. Don't parse a number out of `error`.\n- **Email credentials are only saved on success.** `loginWithEmail` and\n `confirmEmailRegistration` persist email+password to local storage (scoped by\n `titleID`) only after `fetchAndApplyClientState` succeeds — a failed login\n doesn't overwrite previously saved credentials, and a fresh install has\n nothing saved until the first successful email login. `registerWithEmail` on\n its own saves nothing: at that point the account does not exist yet.\n- **`refreshSession()` has a re-entrancy guard.** If it's already running\n (e.g. two requests 401 at nearly the same time), a second call returns `null`\n immediately instead of recursing — this exists to avoid deadlocking the\n retry, so don't assume a `null` result means the session is actually dead.\n- **`logout()` forgets the saved login method too (changed in core 0.1.3).** It\n nulls the auth context, wipes the cached user state and title-config bundle,\n clears `lastAuthType` and any saved email/password, and emits\n `auth:loggedOut` — so a later `autoLogin()` has nothing to resume. Before\n 0.1.3 storage survived a logout and the next launch silently signed the\n player back into the account they had just left. If you want a sign-out the\n player is remembered through, don't call `logout()`.\n- **Never reload the page after `logout()`** (or after deleting the account). The host shell\n (`AuthGate`) returns to the sign-in screen by itself on `auth:loggedOut`. A `location.reload()`\n restarts the whole app for nothing and, in the AI Coder's live preview, left a dark empty frame:\n the preview's files arrive by message and do not survive a reload.\n- **`refreshSession()` and `logout()` don't return `OperationResult`.**\n `refreshSession()` resolves to `string | null` (the fresh session ticket, or\n `null` on failure/no saved method); `logout()` is synchronous `void`. Don't\n branch on `.ok` for these two.\n- **`GameLoop` is excluded from the login `ClientState`.** Board/stage state\n and its definitions are fetched separately per-stage by the GameLoop\n feature, not bundled into every login response.\n- **Guard against double-submit.** Each call fires a real request; a\n double-tapped \"Log in\" button can fire twice. Firing the same auth endpoint\n again inside the SDK's own throttle window (default 600 ms) comes back\n `reason: \"throttled\"` rather than duplicating the call, but disable the\n control while a call is in flight rather than relying on that — and note the\n server has its own, stricter per-account lock on top (see above).\n\n## Full reference\n\n[references/data-model.md](references/data-model.md) — request/response wire\nshapes, the exact backend validation and error-code rules for each login/reset\npath, UserID derivation, and the default-username generator. Read it when you\nneed to reason about _why_ a specific `error` string came back, or when\nbuilding a password-reset or registration UI that needs to match the backend's\ntiming/attempt rules exactly.\n",
|
|
5
5
|
"references": [
|
|
6
6
|
{
|
|
7
7
|
"path": "data-model.md",
|