connectbase-client 6.26.0 → 6.27.0

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/index.mjs CHANGED
@@ -6013,6 +6013,622 @@ var GameConfigAPI = class {
6013
6013
  }
6014
6014
  };
6015
6015
 
6016
+ // src/api/game-units.ts
6017
+ var GAME_MESSAGE = {
6018
+ ready: "cb:game:ready",
6019
+ token: "cb:game:token",
6020
+ refresh: "cb:game:token:refresh"
6021
+ };
6022
+ var DEFAULT_REFRESH_BEFORE_MS = 12e4;
6023
+ var MIN_REFRESH_DELAY_MS = 5e3;
6024
+ function decodeJwtPayload2(token) {
6025
+ const part = token.split(".")[1];
6026
+ if (!part) return null;
6027
+ try {
6028
+ const b64 = part.replace(/-/g, "+").replace(/_/g, "/");
6029
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
6030
+ const json = typeof atob === "function" ? decodeURIComponent(
6031
+ Array.from(atob(padded)).map((c) => `%${c.charCodeAt(0).toString(16).padStart(2, "0")}`).join("")
6032
+ ) : "";
6033
+ const parsed = JSON.parse(json);
6034
+ return parsed && typeof parsed === "object" ? parsed : null;
6035
+ } catch {
6036
+ return null;
6037
+ }
6038
+ }
6039
+ function normalizeGameTokenGrant(raw) {
6040
+ let g = raw;
6041
+ if (g && typeof g === "object" && !g.token && !g.access_token && g.result && typeof g.result === "object") {
6042
+ g = g.result;
6043
+ }
6044
+ const token = g?.token ?? g?.access_token;
6045
+ if (!g || typeof token !== "string" || token === "") {
6046
+ throw new Error(
6047
+ "\uAC8C\uC784 \uD1A0\uD070 \uBB36\uC74C\uC5D0 token(\uB610\uB294 access_token) \uC774 \uC5C6\uC2B5\uB2C8\uB2E4. getToken \uC774 \uBC1C\uAE09 \uC751\uB2F5\uC744 \uB3CC\uB824\uC8FC\uB294\uC9C0 \uD655\uC778\uD558\uC138\uC694."
6048
+ );
6049
+ }
6050
+ let expiresAt = g.expiresAt;
6051
+ if (expiresAt === void 0 && typeof g.expires_in === "number") {
6052
+ expiresAt = Date.now() + g.expires_in * 1e3;
6053
+ }
6054
+ return {
6055
+ token,
6056
+ playerId: g.playerId ?? g.player_id,
6057
+ playerIdMode: g.playerIdMode ?? g.player_id_mode,
6058
+ expiresAt,
6059
+ gameId: g.game_id
6060
+ };
6061
+ }
6062
+ function encodeSeg(v) {
6063
+ return encodeURIComponent(v);
6064
+ }
6065
+ function isExactOrigin(origin) {
6066
+ if (typeof origin !== "string" || origin === "" || origin.includes("*"))
6067
+ return false;
6068
+ try {
6069
+ const u = new URL(origin);
6070
+ return (u.protocol === "https:" || u.protocol === "http:") && u.origin === origin;
6071
+ } catch {
6072
+ return false;
6073
+ }
6074
+ }
6075
+ function unrefTimer(t) {
6076
+ t.unref?.();
6077
+ }
6078
+ var GameScope = class {
6079
+ constructor(deps, gameId, options) {
6080
+ this.refreshTimer = null;
6081
+ this.rooms = /* @__PURE__ */ new Set();
6082
+ this.disposers = [];
6083
+ this.disposed = false;
6084
+ if (!gameId) throw new Error("cb.game.forGame: gameId \uAC00 \uD544\uC694\uD569\uB2C8\uB2E4.");
6085
+ if (!options?.token)
6086
+ throw new Error("cb.game.forGame: \uAC8C\uC784 \uD1A0\uD070(token) \uC774 \uD544\uC694\uD569\uB2C8\uB2E4.");
6087
+ const appId = options.appId ?? deps.defaultAppId;
6088
+ if (!appId)
6089
+ throw new Error(
6090
+ "cb.game.forGame: appId \uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. new ConnectBase({ appId }) \uB098 options.appId \uB85C \uB118\uAE30\uC138\uC694."
6091
+ );
6092
+ this.deps = deps;
6093
+ this.options = options;
6094
+ this.gameId = gameId;
6095
+ this.appId = appId;
6096
+ this.token = options.token;
6097
+ this._playerId = "";
6098
+ this._playerIdMode = void 0;
6099
+ this._expiresAt = 0;
6100
+ this.applyGrant({
6101
+ token: options.token,
6102
+ playerId: options.playerId,
6103
+ playerIdMode: options.playerIdMode,
6104
+ expiresAt: options.expiresAt
6105
+ });
6106
+ const lb = (key) => `/v1/game/${encodeSeg(this.appId)}/leaderboards/${encodeSeg(key)}`;
6107
+ this.leaderboard = {
6108
+ submit: (key, score, opts) => this.request("POST", `${lb(key)}/scores`, {
6109
+ member: this.requirePlayerId(),
6110
+ score,
6111
+ mode: opts?.mode ?? "set"
6112
+ }),
6113
+ top: (key, n = 10) => this.request("GET", `${lb(key)}/top?n=${n}`),
6114
+ rank: (key) => this.request(
6115
+ "GET",
6116
+ `${lb(key)}/members/${encodeSeg(this.requirePlayerId())}`
6117
+ ),
6118
+ around: (key, above = 5, below = 5) => this.request(
6119
+ "GET",
6120
+ `${lb(key)}/around/${encodeSeg(this.requirePlayerId())}?above=${above}&below=${below}`
6121
+ ),
6122
+ removeMe: (key) => this.request(
6123
+ "DELETE",
6124
+ `${lb(key)}/members/${encodeSeg(this.requirePlayerId())}`
6125
+ )
6126
+ };
6127
+ const mq = (key) => `/v1/game/${encodeSeg(this.appId)}/matchqueue/${encodeSeg(key)}`;
6128
+ this.matchqueue = {
6129
+ enqueue: (queueKey, attributes, ttlSec, ticketId) => this.request("POST", `${mq(queueKey)}/tickets`, {
6130
+ ticket_id: ticketId ?? this.requirePlayerId(),
6131
+ attributes,
6132
+ ttl_sec: ttlSec ?? 0
6133
+ }),
6134
+ list: (queueKey) => this.request("GET", mq(queueKey)),
6135
+ cancel: (queueKey, ticketId) => this.request(
6136
+ "DELETE",
6137
+ `${mq(queueKey)}/tickets/${encodeSeg(ticketId ?? this.requirePlayerId())}`
6138
+ )
6139
+ };
6140
+ const ent = (name) => `/v1/game/${encodeSeg(this.appId)}/entities/${encodeSeg(name)}`;
6141
+ this.entities = {
6142
+ list: (name, opts) => {
6143
+ const q = new URLSearchParams();
6144
+ if (opts?.limit) q.set("limit", String(opts.limit));
6145
+ if (opts?.cursor) q.set("cursor", opts.cursor);
6146
+ const qs = q.toString();
6147
+ return this.request(
6148
+ "GET",
6149
+ qs ? `${ent(name)}?${qs}` : ent(name)
6150
+ );
6151
+ },
6152
+ get: (name, id) => this.request("GET", `${ent(name)}/${encodeSeg(id)}`)
6153
+ };
6154
+ const kv = (key) => key === void 0 ? `/v1/game/${encodeSeg(this.appId)}/kv` : `/v1/game/${encodeSeg(this.appId)}/kv/${encodeSeg(key)}`;
6155
+ this.kv = {
6156
+ list: () => this.request("GET", kv()),
6157
+ get: (key) => this.request("GET", kv(key)),
6158
+ set: (key, value, opts) => {
6159
+ const body = { value };
6160
+ if (opts?.expectedRevision !== void 0)
6161
+ body.expected_revision = opts.expectedRevision;
6162
+ return this.request("PUT", kv(key), body);
6163
+ },
6164
+ delete: (key) => this.request("DELETE", kv(key))
6165
+ };
6166
+ }
6167
+ /** 이 게임에서 내 식별자(리더보드 member, 매치큐 ticket id). */
6168
+ get playerId() {
6169
+ return this._playerId;
6170
+ }
6171
+ /** `playerId` 의 방식(`anonymous` / `member`). 발급 응답이나 옵션으로 받지 못했으면 undefined. */
6172
+ get playerIdMode() {
6173
+ return this._playerIdMode;
6174
+ }
6175
+ /** 토큰 만료 시각(ms). 모르면 0. */
6176
+ get expiresAt() {
6177
+ return this._expiresAt;
6178
+ }
6179
+ /** 지금 쓰는 게임 토큰. 다른 곳에 저장하지 마세요(메모리에만 두는 것이 원칙). */
6180
+ getToken() {
6181
+ return this.token;
6182
+ }
6183
+ /**
6184
+ * 게임 룸(WebSocket) 클라이언트. 토큰은 이 게임 토큰으로 고정한다. 토큰이 바뀌면 다음 연결,
6185
+ * 재연결부터 새 토큰을 쓴다.
6186
+ */
6187
+ createClient(config) {
6188
+ const room = this.deps.createRoom({
6189
+ ...config,
6190
+ appId: this.appId,
6191
+ accessToken: this.token
6192
+ });
6193
+ this.rooms.add(room);
6194
+ return room;
6195
+ }
6196
+ /** 토큰을 바꾼다(갱신). 문자열 또는 발급 응답 모양을 받는다. */
6197
+ setToken(grant) {
6198
+ const n = typeof grant === "string" ? { token: grant } : normalizeGameTokenGrant(grant);
6199
+ if (n.gameId && n.gameId !== this.gameId) {
6200
+ throw new Error(
6201
+ `\uB2E4\uB978 \uAC8C\uC784(${n.gameId}) \uC758 \uD1A0\uD070\uC785\uB2C8\uB2E4. \uC774 \uD074\uB77C\uC774\uC5B8\uD2B8\uB294 ${this.gameId} \uC804\uC6A9\uC785\uB2C8\uB2E4.`
6202
+ );
6203
+ }
6204
+ this.applyGrant(n);
6205
+ for (const room of this.rooms) room.setAccessToken(this.token);
6206
+ }
6207
+ /** 갱신 타이머를 멈추고 붙은 리스너(fromHost)를 뗀다. */
6208
+ dispose() {
6209
+ this.disposed = true;
6210
+ if (this.refreshTimer) clearTimeout(this.refreshTimer);
6211
+ this.refreshTimer = null;
6212
+ for (const d of this.disposers.splice(0)) d();
6213
+ }
6214
+ /** @internal fromHost 가 리스너 정리를 맡긴다. */
6215
+ _onDispose(fn) {
6216
+ this.disposers.push(fn);
6217
+ }
6218
+ applyGrant(g) {
6219
+ this.token = g.token;
6220
+ if (g.playerIdMode) this._playerIdMode = g.playerIdMode;
6221
+ const claims = decodeJwtPayload2(g.token);
6222
+ const fromClaims = this._playerIdMode === "member" ? "" : typeof claims?.gpid === "string" && claims.gpid || (typeof claims?.sub === "string" && claims.sub.startsWith("gp_") ? claims.sub : "");
6223
+ this._playerId = g.playerId || this._playerId || fromClaims || "";
6224
+ if (g.expiresAt !== void 0) {
6225
+ this._expiresAt = g.expiresAt;
6226
+ } else if (typeof claims?.exp === "number") {
6227
+ this._expiresAt = claims.exp * 1e3;
6228
+ }
6229
+ this.scheduleRefresh();
6230
+ }
6231
+ scheduleRefresh() {
6232
+ if (this.refreshTimer) clearTimeout(this.refreshTimer);
6233
+ this.refreshTimer = null;
6234
+ const cb = this.options.onTokenExpiring;
6235
+ if (!cb || !this._expiresAt || this.disposed) return;
6236
+ const before = this.options.refreshBeforeMs ?? DEFAULT_REFRESH_BEFORE_MS;
6237
+ const delay = Math.max(
6238
+ MIN_REFRESH_DELAY_MS,
6239
+ this._expiresAt - before - Date.now()
6240
+ );
6241
+ this.refreshTimer = setTimeout(async () => {
6242
+ this.refreshTimer = null;
6243
+ try {
6244
+ const next = await cb({
6245
+ gameId: this.gameId,
6246
+ expiresAt: this._expiresAt
6247
+ });
6248
+ if (next) this.setToken(next);
6249
+ } catch {
6250
+ }
6251
+ }, delay);
6252
+ unrefTimer(this.refreshTimer);
6253
+ }
6254
+ requirePlayerId() {
6255
+ if (!this._playerId) {
6256
+ throw new Error(
6257
+ this._playerIdMode === "member" ? "member \uBC29\uC2DD \uAC8C\uC784\uC740 playerId(\uBC1C\uAE09 \uC751\uB2F5\uC758 player_id = \uD68C\uC6D0 id) \uB97C \uB118\uACA8\uC57C \uD569\uB2C8\uB2E4. forGame(gameId, { token, playerId, playerIdMode }) \uB85C \uB118\uAE30\uC138\uC694." : "\uC774 \uAC8C\uC784\uC758 playerId \uB97C \uBAA8\uB985\uB2C8\uB2E4. forGame(gameId, { token, playerId }) \uB85C \uB118\uAE30\uC138\uC694."
6258
+ );
6259
+ }
6260
+ return this._playerId;
6261
+ }
6262
+ async request(method, path, body) {
6263
+ const headers = {
6264
+ Authorization: `Bearer ${this.token}`
6265
+ };
6266
+ if (this.deps.publicKey) headers["X-Public-Key"] = this.deps.publicKey;
6267
+ const init = { method, headers };
6268
+ if (body !== void 0) {
6269
+ headers["Content-Type"] = "application/json";
6270
+ init.body = JSON.stringify(body);
6271
+ }
6272
+ const response = await fetch(`${this.deps.gameServerUrl}${path}`, init);
6273
+ if (!response.ok) {
6274
+ let code = "GAME_REQUEST_FAILED";
6275
+ let message = `${method} ${path} failed: ${response.status}`;
6276
+ let details;
6277
+ try {
6278
+ const data = await response.json();
6279
+ details = data;
6280
+ if (typeof data.code === "string") code = data.code;
6281
+ else if (typeof data.error === "string") code = data.error;
6282
+ if (typeof data.message === "string") message = data.message;
6283
+ else if (typeof data.reason === "string") message = data.reason;
6284
+ else if (typeof data.error === "string") message = data.error;
6285
+ } catch {
6286
+ }
6287
+ throw new ApiError(response.status, message, code, details);
6288
+ }
6289
+ if (response.status === 204) return void 0;
6290
+ const ct = response.headers.get("content-type") || "";
6291
+ if (!ct.includes("application/json")) return void 0;
6292
+ return await response.json();
6293
+ }
6294
+ };
6295
+ var GameHubAPI = class {
6296
+ /**
6297
+ * iframe 게임에 게임 토큰을 넘긴다.
6298
+ *
6299
+ * 게임이 `cb:game:ready` 나 `cb:game:token:refresh` 를 보내면 `getToken()` 으로 토큰을 받아
6300
+ * `{type:'cb:game:token', gameId, token, playerId, playerIdMode, expiresAt}` 를 **게임 origin 으로만**
6301
+ * 보낸다. 만료 2분 전에는 게임이 묻지 않아도 새 토큰을 보낸다. 다른 origin 이나 다른 창에서 온
6302
+ * 메시지는 무시한다.
6303
+ *
6304
+ * @example
6305
+ * ```ts
6306
+ * const handle = cb.game.hub.mount(iframeEl, {
6307
+ * gameId: 'space-shooter',
6308
+ * origin: 'https://abc.web.connectbase.world',
6309
+ * getToken: async () => (await cb.functions.invoke('issue-game-token', { gameId: 'space-shooter' })).result,
6310
+ * })
6311
+ * // 화면을 떠날 때
6312
+ * handle.destroy()
6313
+ * ```
6314
+ */
6315
+ mount(iframe, options) {
6316
+ if (!options?.gameId)
6317
+ throw new Error("cb.game.hub.mount: gameId \uAC00 \uD544\uC694\uD569\uB2C8\uB2E4.");
6318
+ if (!isExactOrigin(options.origin)) {
6319
+ throw new Error(
6320
+ "cb.game.hub.mount: origin \uC740 'https://host[:port]' \uCC98\uB7FC \uC815\uD655\uD55C origin \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4('*', \uACBD\uB85C \uBD88\uAC00)."
6321
+ );
6322
+ }
6323
+ if (typeof options.getToken !== "function")
6324
+ throw new Error("cb.game.hub.mount: getToken \uD568\uC218\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4.");
6325
+ const doc = iframe.ownerDocument;
6326
+ const host = doc?.defaultView ?? (typeof window !== "undefined" ? window : void 0);
6327
+ if (!host)
6328
+ throw new Error("cb.game.hub.mount: \uBE0C\uB77C\uC6B0\uC800 \uCC3D\uC5D0\uC11C\uB9CC \uC4F8 \uC218 \uC788\uC2B5\uB2C8\uB2E4.");
6329
+ const refreshBefore = options.refreshBeforeMs ?? DEFAULT_REFRESH_BEFORE_MS;
6330
+ let timer = null;
6331
+ let inflight = null;
6332
+ let destroyed = false;
6333
+ const send = () => {
6334
+ if (destroyed) return Promise.resolve();
6335
+ if (inflight) return inflight;
6336
+ inflight = (async () => {
6337
+ try {
6338
+ const g = normalizeGameTokenGrant(await options.getToken());
6339
+ if (g.gameId && g.gameId !== options.gameId) {
6340
+ throw new Error(
6341
+ `getToken \uC774 \uB2E4\uB978 \uAC8C\uC784(${g.gameId}) \uC758 \uD1A0\uD070\uC744 \uB3CC\uB824\uC92C\uC2B5\uB2C8\uB2E4.`
6342
+ );
6343
+ }
6344
+ const expiresAt = g.expiresAt ?? (() => {
6345
+ const exp = decodeJwtPayload2(g.token)?.exp;
6346
+ return typeof exp === "number" ? exp * 1e3 : void 0;
6347
+ })();
6348
+ const target = iframe.contentWindow;
6349
+ if (destroyed || !target) return;
6350
+ target.postMessage(
6351
+ {
6352
+ type: GAME_MESSAGE.token,
6353
+ gameId: options.gameId,
6354
+ token: g.token,
6355
+ playerId: g.playerId,
6356
+ playerIdMode: g.playerIdMode,
6357
+ expiresAt
6358
+ },
6359
+ options.origin
6360
+ );
6361
+ if (timer) clearTimeout(timer);
6362
+ timer = null;
6363
+ if (expiresAt) {
6364
+ timer = setTimeout(
6365
+ () => {
6366
+ void send();
6367
+ },
6368
+ Math.max(
6369
+ MIN_REFRESH_DELAY_MS,
6370
+ expiresAt - refreshBefore - Date.now()
6371
+ )
6372
+ );
6373
+ unrefTimer(timer);
6374
+ }
6375
+ } catch (err) {
6376
+ options.onError?.(err);
6377
+ } finally {
6378
+ inflight = null;
6379
+ }
6380
+ })();
6381
+ return inflight;
6382
+ };
6383
+ const onMessage = (e) => {
6384
+ if (e.origin !== options.origin) return;
6385
+ if (!iframe.contentWindow || e.source !== iframe.contentWindow) return;
6386
+ const data = e.data;
6387
+ if (!data || typeof data !== "object") return;
6388
+ if (data.gameId !== void 0 && data.gameId !== options.gameId) return;
6389
+ if (data.type === GAME_MESSAGE.ready || data.type === GAME_MESSAGE.refresh) {
6390
+ void send();
6391
+ }
6392
+ };
6393
+ host.addEventListener("message", onMessage);
6394
+ return {
6395
+ refresh: () => send(),
6396
+ destroy: () => {
6397
+ destroyed = true;
6398
+ host.removeEventListener("message", onMessage);
6399
+ if (timer) clearTimeout(timer);
6400
+ timer = null;
6401
+ }
6402
+ };
6403
+ }
6404
+ };
6405
+ function receiveGameTokenFromHost(options, makeScope) {
6406
+ const allowed = options?.allowedParentOrigins ?? [];
6407
+ if (!Array.isArray(allowed) || allowed.length === 0) {
6408
+ return Promise.reject(
6409
+ new Error(
6410
+ "cb.game.fromHost: allowedParentOrigins \uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. \uD5C8\uBE0C origin \uC744 \uC815\uD655\uD788 \uC801\uC73C\uC138\uC694."
6411
+ )
6412
+ );
6413
+ }
6414
+ for (const o of allowed) {
6415
+ if (!isExactOrigin(o)) {
6416
+ return Promise.reject(
6417
+ new Error(
6418
+ `cb.game.fromHost: '${o}' \uB294 \uC815\uD655\uD55C origin \uC774 \uC544\uB2D9\uB2C8\uB2E4('*', \uACBD\uB85C \uBD88\uAC00).`
6419
+ )
6420
+ );
6421
+ }
6422
+ }
6423
+ if (typeof window === "undefined") {
6424
+ return Promise.reject(
6425
+ new Error("cb.game.fromHost: \uBE0C\uB77C\uC6B0\uC800 iframe \uC548\uC5D0\uC11C\uB9CC \uC4F8 \uC218 \uC788\uC2B5\uB2C8\uB2E4.")
6426
+ );
6427
+ }
6428
+ const self = window;
6429
+ const parent = self.parent;
6430
+ if (!parent || parent === self) {
6431
+ return Promise.reject(
6432
+ new Error("cb.game.fromHost: iframe \uC548\uC774 \uC544\uB2D9\uB2C8\uB2E4(\uBD80\uBAA8 \uCC3D\uC774 \uC5C6\uC2B5\uB2C8\uB2E4).")
6433
+ );
6434
+ }
6435
+ return new Promise((resolve, reject) => {
6436
+ let scope = null;
6437
+ let hostOrigin = "";
6438
+ let settled = false;
6439
+ let readyTimer;
6440
+ let timeout;
6441
+ const sendToParent = (type, origins) => {
6442
+ for (const o of origins) {
6443
+ try {
6444
+ parent.postMessage({ type, gameId: options.gameId }, o);
6445
+ } catch {
6446
+ }
6447
+ }
6448
+ };
6449
+ const cleanup = () => {
6450
+ self.removeEventListener("message", onMessage);
6451
+ clearInterval(readyTimer);
6452
+ clearTimeout(timeout);
6453
+ };
6454
+ const onMessage = (e) => {
6455
+ if (e.source !== parent) return;
6456
+ if (!allowed.includes(e.origin)) return;
6457
+ if (hostOrigin && e.origin !== hostOrigin) return;
6458
+ const d = e.data;
6459
+ if (!d || typeof d !== "object" || d.type !== GAME_MESSAGE.token) return;
6460
+ if (typeof d.token !== "string" || d.token === "") return;
6461
+ if (typeof d.gameId !== "string" || d.gameId === "") return;
6462
+ if (options.gameId && d.gameId !== options.gameId) return;
6463
+ const grant = {
6464
+ token: d.token,
6465
+ playerId: typeof d.playerId === "string" ? d.playerId : void 0,
6466
+ playerIdMode: d.playerIdMode === "anonymous" || d.playerIdMode === "member" ? d.playerIdMode : void 0,
6467
+ expiresAt: typeof d.expiresAt === "number" ? d.expiresAt : void 0
6468
+ };
6469
+ if (scope) {
6470
+ if (d.gameId !== scope.gameId) return;
6471
+ scope.setToken(grant);
6472
+ return;
6473
+ }
6474
+ hostOrigin = e.origin;
6475
+ try {
6476
+ scope = makeScope(d.gameId, {
6477
+ token: grant.token,
6478
+ playerId: grant.playerId,
6479
+ playerIdMode: grant.playerIdMode,
6480
+ expiresAt: grant.expiresAt,
6481
+ onTokenExpiring: () => {
6482
+ sendToParent(GAME_MESSAGE.refresh, [hostOrigin]);
6483
+ return void 0;
6484
+ }
6485
+ });
6486
+ } catch (err) {
6487
+ settled = true;
6488
+ cleanup();
6489
+ reject(err);
6490
+ return;
6491
+ }
6492
+ settled = true;
6493
+ clearInterval(readyTimer);
6494
+ clearTimeout(timeout);
6495
+ scope._onDispose(() => self.removeEventListener("message", onMessage));
6496
+ resolve(scope);
6497
+ };
6498
+ self.addEventListener("message", onMessage);
6499
+ sendToParent(GAME_MESSAGE.ready, allowed);
6500
+ readyTimer = setInterval(() => {
6501
+ if (!settled) sendToParent(GAME_MESSAGE.ready, allowed);
6502
+ }, 1e3);
6503
+ timeout = setTimeout(() => {
6504
+ if (settled) return;
6505
+ settled = true;
6506
+ cleanup();
6507
+ reject(
6508
+ new Error(
6509
+ "cb.game.fromHost: \uD5C8\uBE0C\uC5D0\uC11C \uAC8C\uC784 \uD1A0\uD070\uC744 \uBC1B\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. \uD5C8\uBE0C\uAC00 cb.game.hub.mount \uB97C \uBD88\uB800\uB294\uC9C0, origin \uC774 \uB9DE\uB294\uC9C0 \uD655\uC778\uD558\uC138\uC694."
6510
+ )
6511
+ );
6512
+ }, options.timeoutMs ?? 15e3);
6513
+ });
6514
+ }
6515
+ function requireServerCredential(http, method) {
6516
+ if (!http.hasJWT() && !http.hasSecretKey()) {
6517
+ throw new Error(
6518
+ `${method} \uB294 \uC2DC\uD06C\uB9BF \uD0A4(cb_sk_) \uB610\uB294 \uD568\uC218\uC758 ctx.cbAdmin(management_scopes: ["game:manage"]) \uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 \uD5C8\uBE0C \uC11C\uBC84\uB098 \uD568\uC218\uC5D0\uC11C \uC4F0\uC138\uC694.`
6519
+ );
6520
+ }
6521
+ }
6522
+ async function issueGameToken(http, options) {
6523
+ requireServerCredential(http, "cb.game.issueToken()");
6524
+ if (!options?.accessToken)
6525
+ throw new Error(
6526
+ "cb.game.issueToken: accessToken(\uD68C\uC6D0 \uD1A0\uD070) \uC774 \uD544\uC694\uD569\uB2C8\uB2E4."
6527
+ );
6528
+ if (!options.gameId)
6529
+ throw new Error("cb.game.issueToken: gameId \uAC00 \uD544\uC694\uD569\uB2C8\uB2E4.");
6530
+ const body = {
6531
+ access_token: options.accessToken,
6532
+ game_id: options.gameId
6533
+ };
6534
+ if (options.ttlSeconds !== void 0) body.ttl_seconds = options.ttlSeconds;
6535
+ return http.post("/v1/public/game/tokens", body);
6536
+ }
6537
+ var GamesAPI = class {
6538
+ constructor(http) {
6539
+ this.http = http;
6540
+ this.creatorTokens = {
6541
+ list: async (gameKey) => {
6542
+ this.guard("cb.games.creatorTokens.list()");
6543
+ const res = await this.http.get(
6544
+ `${this.path(gameKey)}/creator-tokens`
6545
+ );
6546
+ return res?.tokens ?? [];
6547
+ },
6548
+ issue: async (gameKey, request) => {
6549
+ this.guard("cb.games.creatorTokens.issue()");
6550
+ return this.http.post(
6551
+ `${this.path(gameKey)}/creator-tokens`,
6552
+ request ?? {}
6553
+ );
6554
+ },
6555
+ revoke: async (gameKey, tokenId) => {
6556
+ this.guard("cb.games.creatorTokens.revoke()");
6557
+ await this.http.delete(
6558
+ `${this.path(gameKey)}/creator-tokens/${encodeSeg(tokenId)}`
6559
+ );
6560
+ }
6561
+ };
6562
+ }
6563
+ /** 게임 목록(삭제 중 포함, 최근 순). */
6564
+ async list() {
6565
+ this.guard("cb.games.list()");
6566
+ const res = await this.http.get("/v1/public/games");
6567
+ return res?.games ?? [];
6568
+ }
6569
+ /** 게임 하나. 없으면 404 `game_not_found`. */
6570
+ async get(gameKey) {
6571
+ this.guard("cb.games.get()");
6572
+ return this.http.get(this.path(gameKey));
6573
+ }
6574
+ /** 게임 등록. game_key = Lua 스크립트 이름. */
6575
+ async create(request) {
6576
+ this.guard("cb.games.create()");
6577
+ return this.http.post("/v1/public/games", request);
6578
+ }
6579
+ /** 게임 수정. 스토리지를 바꾸거나 떼면 그 게임의 제작자 토큰이 모두 회수된다. */
6580
+ async update(gameKey, request) {
6581
+ this.guard("cb.games.update()");
6582
+ return this.http.patch(this.path(gameKey), request);
6583
+ }
6584
+ /** 강제 비활성화. 게임 토큰, 연결, 룸, 사이트, 제작자 토큰이 한 번에 막힌다. */
6585
+ async disable(gameKey, reason) {
6586
+ this.guard("cb.games.disable()");
6587
+ return this.http.post(
6588
+ `${this.path(gameKey)}/disable`,
6589
+ reason === void 0 ? {} : { reason }
6590
+ );
6591
+ }
6592
+ /** 다시 켜기. 데이터와 스크립트는 그대로 돌아온다. */
6593
+ async enable(gameKey) {
6594
+ this.guard("cb.games.enable()");
6595
+ return this.http.post(`${this.path(gameKey)}/enable`, {});
6596
+ }
6597
+ /**
6598
+ * 회원 id 와 player id 를 서로 찾는다(최대 100개). 허브 화면에 닉네임을 보여 줄 때 쓴다.
6599
+ *
6600
+ * @example
6601
+ * const { members } = await ctx.cbAdmin.games.resolvePlayers('space-shooter', { playerIds: top.entries.map(e => e.member) })
6602
+ */
6603
+ async resolvePlayers(gameKey, ids) {
6604
+ this.guard("cb.games.resolvePlayers()");
6605
+ const body = "memberIds" in ids ? { member_ids: ids.memberIds } : { player_ids: ids.playerIds };
6606
+ return this.http.post(
6607
+ `${this.path(gameKey)}/players/resolve`,
6608
+ body
6609
+ );
6610
+ }
6611
+ /**
6612
+ * 스크립트 버전 활성화(제작자 초안 승인). 스크립트 이름은 game_key 와 같아야 한다.
6613
+ * version 을 생략하면 최신 버전.
6614
+ */
6615
+ async activateScript(gameKey, options) {
6616
+ this.guard("cb.games.activateScript()");
6617
+ const name = options?.name ?? gameKey;
6618
+ return this.http.post(
6619
+ `${this.path(gameKey)}/scripts/${encodeSeg(name)}/activate`,
6620
+ options?.version === void 0 ? {} : { version: options.version }
6621
+ );
6622
+ }
6623
+ path(gameKey) {
6624
+ if (!gameKey) throw new Error("cb.games: gameKey \uAC00 \uD544\uC694\uD569\uB2C8\uB2E4.");
6625
+ return `/v1/public/games/${encodeSeg(gameKey)}`;
6626
+ }
6627
+ guard(method) {
6628
+ requireServerCredential(this.http, method);
6629
+ }
6630
+ };
6631
+
6016
6632
  // src/api/game.ts
6017
6633
  function parseGameError(msg) {
6018
6634
  const payload = msg.data ?? msg;
@@ -6218,6 +6834,12 @@ var GameRoom = class {
6218
6834
  this.ws.addEventListener("message", onMessage);
6219
6835
  });
6220
6836
  }
6837
+ /**
6838
+ * 다음 연결과 재연결부터 쓸 액세스 토큰을 바꾼다(게임 토큰 갱신용). 이미 열린 연결은 그대로 둔다.
6839
+ */
6840
+ setAccessToken(token) {
6841
+ this.config.accessToken = token;
6842
+ }
6221
6843
  /**
6222
6844
  * 연결 해제
6223
6845
  */
@@ -6720,6 +7342,69 @@ var GameAPI = class {
6720
7342
  this.gameServerUrl = gameServerUrl || getDefaultGameServerUrl().replace(/^ws/, "http");
6721
7343
  this.appId = appId;
6722
7344
  this.config = new GameConfigAPI(http, appId);
7345
+ this.hub = new GameHubAPI();
7346
+ }
7347
+ /**
7348
+ * 게임 하나로 범위를 고정한 클라이언트를 만든다(앱 안의 게임 단위).
7349
+ *
7350
+ * 모든 요청에 `Authorization: Bearer <게임 토큰>` 을 고정해서 보내고, 리더보드 member 와
7351
+ * 매치큐 ticket id 는 `playerId` 로 자동으로 채운다. SDK 로그인 토큰으로 바꿔 끼우지 않는다.
7352
+ *
7353
+ * @example
7354
+ * ```ts
7355
+ * const game = cb.game.forGame('space-shooter', { token, playerId, expiresAt,
7356
+ * onTokenExpiring: () => fetchNewTokenFromHub() })
7357
+ * await game.leaderboard.submit('ranking', 120, { mode: 'incr' })
7358
+ * const room = game.createClient({ clientId: game.playerId })
7359
+ * ```
7360
+ */
7361
+ forGame(gameId, options) {
7362
+ return new GameScope(
7363
+ {
7364
+ gameServerUrl: this.gameServerUrl,
7365
+ publicKey: this.http.getPublicKey(),
7366
+ defaultAppId: this.appId,
7367
+ createRoom: (cfg) => this.createClient(cfg)
7368
+ },
7369
+ gameId,
7370
+ options
7371
+ );
7372
+ }
7373
+ /**
7374
+ * iframe 안 게임이 허브(부모 창)에서 게임 토큰을 받아 게임 범위 클라이언트를 만든다.
7375
+ *
7376
+ * `allowedParentOrigins` 에 없는 origin 이나 부모가 아닌 창에서 온 메시지는 받지 않는다. 토큰은
7377
+ * 메모리에만 두고, 만료 2분 전에 허브에 새 토큰을 요청한다.
7378
+ *
7379
+ * @example
7380
+ * ```ts
7381
+ * const game = await cb.game.fromHost({ allowedParentOrigins: ['https://hub.example.com'] })
7382
+ * await game.kv.set('save', { stage: 3 })
7383
+ * ```
7384
+ */
7385
+ fromHost(options) {
7386
+ return receiveGameTokenFromHost(
7387
+ options,
7388
+ (gameId, opts) => this.forGame(gameId, opts)
7389
+ );
7390
+ }
7391
+ /**
7392
+ * 회원 토큰을 게임 하나로 축소한 게임 토큰을 발급한다(서버 전용).
7393
+ *
7394
+ * 시크릿 키 SDK 또는 함수의 `ctx.cbAdmin`(management_scopes `game:manage`) 에서만 부른다.
7395
+ * 응답의 `app_member_id` 는 게임에 넘기지 않는다.
7396
+ *
7397
+ * @example
7398
+ * ```ts
7399
+ * export default async (payload, ctx) => {
7400
+ * const accessToken = await ctx.cb.auth.getAccessToken()
7401
+ * const t = await ctx.cbAdmin.game.issueToken({ accessToken, gameId: payload.gameId, ttlSeconds: 3600 })
7402
+ * return { access_token: t.access_token, player_id: t.player_id, player_id_mode: t.player_id_mode, expires_in: t.expires_in, game_id: t.game_id }
7403
+ * }
7404
+ * ```
7405
+ */
7406
+ issueToken(options) {
7407
+ return issueGameToken(this.http, options);
6723
7408
  }
6724
7409
  /**
6725
7410
  * 게임 룸 클라이언트 생성.
@@ -6736,7 +7421,10 @@ var GameAPI = class {
6736
7421
  // config.appId 를 무조건 덮어써서 호출별 지정이 불가능했다.
6737
7422
  appId: config.appId ?? this.appId,
6738
7423
  publicKey: this.http.getPublicKey(),
6739
- accessToken: this.http.getAccessToken()
7424
+ // 호출자가 준 토큰이 먼저다. 게임 하나로 축소한 멤버 토큰(POST /v1/public/game/tokens)을
7425
+ // 이 룸 연결에만 쓰려면 여기로 넘긴다. 예전엔 타입에 있는 이 값을 SDK 로그인 토큰이
7426
+ // 조용히 덮어써서 축소 토큰을 SDK 로 쓸 수 없었다.
7427
+ accessToken: config.accessToken ?? this.http.getAccessToken()
6740
7428
  });
6741
7429
  }
6742
7430
  /**
@@ -7036,6 +7724,9 @@ var GameAPI = class {
7036
7724
  }
7037
7725
  /**
7038
7726
  * 매칭 큐에서 ticket 제거 (예: 사용자가 매칭 취소).
7727
+ *
7728
+ * 자기 티켓만 취소된다 (등록 때 서버가 박은 `attributes.member_id` 로 가림). 남의 티켓은 403
7729
+ * `forbidden_member` 이다.
7039
7730
  */
7040
7731
  async cancelMatch(appId, queueKey, ticketId) {
7041
7732
  await this.gameFetch(
@@ -7100,6 +7791,10 @@ var GameAPI = class {
7100
7791
  }
7101
7792
  /**
7102
7793
  * leaderboard 전체 reset (시즌 종료 시).
7794
+ *
7795
+ * 앱 소유자 동작이다. 회원 토큰과 공개키로는 403 `forbidden` 이다 (회원 하나가 앱 전체 랭킹을
7796
+ * 지울 수 있었기 때문). 서버 Lua 의 `leaderboard.reset` 이나 콘솔에서 하고, 새 시즌은 key
7797
+ * 접미사(`ranks:2026q3`)로 시작한다.
7103
7798
  */
7104
7799
  async resetLeaderboard(appId, leaderboardKey) {
7105
7800
  await this.gameFetch(
@@ -7110,7 +7805,8 @@ var GameAPI = class {
7110
7805
  );
7111
7806
  }
7112
7807
  /**
7113
- * 특정 member 만 제거 (계정 삭제 등).
7808
+ * 자기 기록 제거 (탈퇴 등). 회원은 자기 member id 만 지울 수 있고, 남의 기록은 403
7809
+ * `forbidden_member` 이다. 남의 기록은 서버 Lua 의 `leaderboard.remove` 로 지운다.
7114
7810
  */
7115
7811
  async removeFromLeaderboard(appId, leaderboardKey, member) {
7116
7812
  await this.gameFetch(
@@ -9739,11 +10435,37 @@ var PaymentAPI = class {
9739
10435
  params.set("limit", String(options.limit));
9740
10436
  if (options?.offset !== void 0)
9741
10437
  params.set("offset", String(options.offset));
10438
+ if (options?.gameKey) params.set("game_key", options.gameKey);
9742
10439
  const qs = params.toString();
9743
10440
  return this.http.get(
9744
10441
  `/v1/apps/${appId}/payments${qs ? `?${qs}` : ""}`
9745
10442
  );
9746
10443
  }
10444
+ /**
10445
+ * 결제 합계를 게임(game_key)별로 묶어 돌려준다(통화별, 테스트 결제 제외).
10446
+ *
10447
+ * 서버사이드 전용 — service_role(ctx.cbAdmin, management_scopes=["payment:read"]) 또는 콘솔 JWT.
10448
+ * 대상은 `approved_at` 이 기간 안이고 상태가 done, partial_canceled, canceled 인 결제다.
10449
+ *
10450
+ * @example
10451
+ * ```typescript
10452
+ * const { groups } = await ctx.cbAdmin.payment.summary(ctx.appId, { groupBy: 'game_key', from: '2026-11-01', to: '2026-11-30' })
10453
+ * ```
10454
+ */
10455
+ async summary(appId, options) {
10456
+ if (this.http.hasPublicKey() && !this.http.hasJWT()) {
10457
+ throw new Error(
10458
+ 'cb.payment.summary() \uB294 \uCF58\uC194 JWT \uB610\uB294 service_role(ctx.cbAdmin, management_scopes: ["payment:read"]) \uC778\uC99D\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. Public Key(cb_pk_) \uB2E8\uB3C5 SDK \uC778\uC2A4\uD134\uC2A4\uB85C\uB294 \uD638\uCD9C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 Functions \uD658\uACBD\uC5D0\uC11C \uC0AC\uC6A9\uD558\uC138\uC694.'
10459
+ );
10460
+ }
10461
+ const params = new URLSearchParams();
10462
+ params.set("group_by", options?.groupBy ?? "game_key");
10463
+ if (options?.from) params.set("from", options.from);
10464
+ if (options?.to) params.set("to", options.to);
10465
+ return this.http.get(
10466
+ `/v1/apps/${appId}/payments/summary?${params.toString()}`
10467
+ );
10468
+ }
9747
10469
  };
9748
10470
 
9749
10471
  // src/api/public-key.ts
@@ -13833,8 +14555,8 @@ var SupportAPI = class {
13833
14555
  }
13834
14556
  };
13835
14557
  function detectSdkVersion() {
13836
- if ("6.26.0") {
13837
- return "6.26.0";
14558
+ if ("6.27.0") {
14559
+ return "6.27.0";
13838
14560
  }
13839
14561
  return "unknown";
13840
14562
  }
@@ -16352,6 +17074,7 @@ var ConnectBase = class {
16352
17074
  config.gameUrl || env("CB_GAME_URL") || DEFAULT_GAME_URL,
16353
17075
  config.appId
16354
17076
  );
17077
+ this.games = new GamesAPI(this.http);
16355
17078
  this.ads = new AdsAPI(this.http);
16356
17079
  this.native = new NativeAPI();
16357
17080
  this.knowledge = new KnowledgeAPI(this.http);
@@ -16432,11 +17155,15 @@ export {
16432
17155
  AuthError,
16433
17156
  ConnectBase,
16434
17157
  EndpointAPI,
17158
+ GAME_MESSAGE,
16435
17159
  GameAPI,
16436
17160
  GameConfigAPI,
16437
17161
  GameError,
17162
+ GameHubAPI,
16438
17163
  GameRoom,
16439
17164
  GameRoomTransport,
17165
+ GameScope,
17166
+ GamesAPI,
16440
17167
  NativeAPI,
16441
17168
  OrganizationsAPI,
16442
17169
  RealtimeConnectionError,