@adminide-stack/yantra-mobile 12.0.178-alpha.2 → 12.0.179-alpha.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.
@@ -23,14 +23,10 @@ async function waitForToken(read, timeoutMs = TOKEN_WAIT_MS, intervalMs = TOKEN_
23
23
  }
24
24
  return token;
25
25
  }
26
- function createCubeforgeFriends(deps) {
26
+ function createGamesRequest(deps) {
27
27
  const {
28
28
  graphqlUrl,
29
29
  getToken,
30
- playerName,
31
- listChats,
32
- sendToChat,
33
- recentChatMessages,
34
30
  fetchImpl = fetch
35
31
  } = deps;
36
32
  const post = async (query, variables, token) => {
@@ -64,7 +60,7 @@ function createCubeforgeFriends(deps) {
64
60
  return ((_a2 = e.extensions) == null ? void 0 : _a2.code) === "UNAUTHENTICATED";
65
61
  }));
66
62
  };
67
- const request = async (query, variables = {}) => {
63
+ return async (query, variables = {}) => {
68
64
  var _a, _b;
69
65
  const token = await getToken(false);
70
66
  if (!token) throw new Error(SIGN_IN);
@@ -80,6 +76,17 @@ function createCubeforgeFriends(deps) {
80
76
  if (!result.data) throw new Error(UNREACHABLE);
81
77
  return result.data;
82
78
  };
79
+ }
80
+ function createCubeforgeFriends(deps) {
81
+ const {
82
+ graphqlUrl,
83
+ getToken,
84
+ playerName,
85
+ listChats,
86
+ sendToChat,
87
+ recentChatMessages
88
+ } = deps;
89
+ const request = createGamesRequest(deps);
83
90
  return {
84
91
  listWorlds: async () => {
85
92
  const data = await request(`query { myGameWorlds { ${WORLD_FIELDS} } }`);
@@ -146,4 +153,4 @@ function createCubeforgeFriends(deps) {
146
153
  };
147
154
  }
148
155
  };
149
- }export{createCubeforgeFriends,waitForToken};//# sourceMappingURL=cubeforgeFriends.js.map
156
+ }export{createCubeforgeFriends,createGamesRequest,waitForToken};//# sourceMappingURL=cubeforgeFriends.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cubeforgeFriends.js","sources":["../../../src/features/games/cubeforgeFriends.ts"],"sourcesContent":["/**\n * Shared Cubeforge worlds over the games subgraph, and invites over chat.\n * Everything that touches the app (tokens, chat) comes in through `FriendsDeps`,\n * so this file can be tested without a running app.\n */\nimport type { CubeforgeFriends, InviteChat, SharedWorld } from './vendored';\nimport { inviteMessage, parseInviteMessage } from './gameInvite';\n\n/**\n * The terrain new shared worlds are made with. Only raise this in the same change\n * that vendors an engine able to draw it: the server refuses older engines from such\n * a world, so a mismatch would lock this app out of the worlds it creates.\n */\nconst TERRAIN_GENERATION = 2;\n\n/** A chat message that may be an invite. */\nexport interface RecentChatMessage {\n body: string;\n /** Who sent it, or null when this player did. */\n from: string | null;\n chatTitle: string;\n sentAt: number;\n}\n\nexport interface FriendsDeps {\n /** `https://host/graphql`. */\n graphqlUrl: string;\n /** A bearer token; `renew` asks for a new one. Null when signed out. */\n getToken: (renew: boolean) => Promise<string | null>;\n playerName: () => string;\n listChats: () => Promise<InviteChat[]>;\n sendToChat: (chatId: string, text: string) => Promise<void>;\n recentChatMessages: () => Promise<RecentChatMessage[]>;\n fetchImpl?: typeof fetch;\n}\n\ninterface WireWorld {\n id: string;\n name: string;\n seed: number;\n memberIds: string[];\n inviteCode: string | null;\n viewerIsOwner: boolean;\n}\n\ninterface GraphQLResponse<T> {\n data?: T | null;\n errors?: { message?: string; extensions?: { code?: string } }[];\n}\n\nconst WORLD_FIELDS = 'id name seed memberIds inviteCode viewerIsOwner';\nconst UNREACHABLE = 'Could not reach the game server. Check your connection and try again.';\nconst SIGN_IN = 'Please sign in again.';\n/** Longer than the session's own two quick retries, 3s then 10s after a failed mint. */\nconst TOKEN_WAIT_MS = 15_000;\nconst TOKEN_POLL_MS = 250;\n\nconst toWorld = (w: WireWorld): SharedWorld => ({\n id: w.id,\n name: w.name,\n seed: w.seed,\n memberCount: w.memberIds.length,\n inviteCode: w.inviteCode,\n ownedByMe: w.viewerIsOwner,\n});\n\n/**\n * Waits for a token that is still on its way. The app opens Games from a chat\n * card as soon as it is tapped, which can be before the signed-in session exists.\n */\nexport async function waitForToken(\n read: () => string | null,\n timeoutMs = TOKEN_WAIT_MS,\n intervalMs = TOKEN_POLL_MS,\n): Promise<string | null> {\n const deadline = Date.now() + timeoutMs;\n let token = read();\n while (!token && Date.now() < deadline) {\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => {\n setTimeout(resolve, intervalMs);\n });\n token = read();\n }\n return token;\n}\n\nexport function createCubeforgeFriends(deps: FriendsDeps): CubeforgeFriends {\n const { graphqlUrl, getToken, playerName, listChats, sendToChat, recentChatMessages, fetchImpl = fetch } = deps;\n\n const post = async <T>(query: string, variables: object, token: string): Promise<GraphQLResponse<T> | 401> => {\n let response: Response;\n try {\n response = await fetchImpl(graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },\n body: JSON.stringify({ query, variables }),\n });\n } catch {\n throw new Error(UNREACHABLE);\n }\n if (response.status === 401) return 401;\n try {\n return (await response.json()) as GraphQLResponse<T>;\n } catch {\n throw new Error(UNREACHABLE);\n }\n };\n\n const isUnauthenticated = <T>(result: GraphQLResponse<T> | 401): boolean =>\n result === 401 || Boolean(result.errors?.some((e) => e.extensions?.code === 'UNAUTHENTICATED'));\n\n const request = async <T>(query: string, variables: object = {}): Promise<T> => {\n const token = await getToken(false);\n if (!token) throw new Error(SIGN_IN);\n let result = await post<T>(query, variables, token);\n if (isUnauthenticated(result)) {\n const fresh = await getToken(true);\n if (!fresh) throw new Error(SIGN_IN);\n result = await post<T>(query, variables, fresh);\n }\n if (result === 401 || isUnauthenticated(result)) throw new Error(SIGN_IN);\n const message = result.errors?.[0]?.message;\n if (message) throw new Error(message);\n if (!result.data) throw new Error(UNREACHABLE);\n return result.data;\n };\n\n return {\n listWorlds: async () => {\n const data = await request<{ myGameWorlds: WireWorld[] }>(`query { myGameWorlds { ${WORLD_FIELDS} } }`);\n return data.myGameWorlds.map(toWorld);\n },\n createWorld: async (name, chatId) => {\n const data = await request<{ createGameWorld: WireWorld }>(\n `mutation($name: String!, $channelId: String, $gen: Int) { createGameWorld(name: $name, channelId: $channelId, gen: $gen) { ${WORLD_FIELDS} } }`,\n { name, channelId: chatId, gen: TERRAIN_GENERATION },\n );\n return toWorld(data.createGameWorld);\n },\n joinWorld: async (inviteCode) => {\n const data = await request<{ joinGameWorld: WireWorld }>(\n `mutation($inviteCode: String!) { joinGameWorld(inviteCode: $inviteCode) { ${WORLD_FIELDS} } }`,\n { inviteCode },\n );\n return toWorld(data.joinGameWorld);\n },\n leaveWorld: async (world) => {\n await request('mutation($id: ID!) { leaveGameWorld(id: $id) }', { id: world.id });\n },\n renameWorld: async (world, name) => {\n await request('mutation($id: ID!, $name: String!) { renameGameWorld(id: $id, name: $name) { id } }', {\n id: world.id,\n name,\n });\n },\n deleteWorld: async (world) => {\n await request('mutation($id: ID!) { deleteGameWorld(id: $id) }', { id: world.id });\n },\n listChats,\n listInvites: async () =>\n (await recentChatMessages()).flatMap(({ body, from, chatTitle, sentAt }) => {\n const invite = parseInviteMessage(body);\n return invite ? [{ code: invite.code, worldName: invite.worldName, from, chatTitle, sentAt }] : [];\n }),\n inviteToChat: async (world, chatId) => {\n if (!world.inviteCode) throw new Error('This world has no invite code.');\n await sendToChat(chatId, inviteMessage(world.name, world.inviteCode));\n },\n roomAccess: async (world, options) => {\n const token = await getToken(Boolean(options?.renewToken));\n if (!token) throw new Error(SIGN_IN);\n const base = graphqlUrl.replace(/^http/, 'ws').replace(/\\/graphql\\/?$/, '');\n return { url: `${base}/rooms/${encodeURIComponent(world.id)}`, token, playerName: playerName() };\n },\n };\n}\n"],"names":["_a"],"mappings":"+DAaA,MAAM,kBAAqB,GAAA,CAAA;AAsC3B,MAAM,YAAe,GAAA,iDAAA;AACrB,MAAM,WAAc,GAAA,uEAAA;AACpB,MAAM,OAAU,GAAA,uBAAA;AAEhB,MAAM,aAAgB,GAAA,IAAA;AACtB,MAAM,aAAgB,GAAA,GAAA;AACtB,MAAM,OAAA,GAAU,CAAC,CAA+B,MA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,OAAO,KAAA,EAAO,OAAY,KAAA;AACpC,MAAA,MAAM,QAAQ,MAAM,QAAA,CAAS,OAAQ,CAAA,OAAA,IAAA,IAAA,GAAA,MAAA,GAAA,OAAA,CAAS,UAAU,CAAC,CAAA;AACzD,MAAA,IAAI,CAAC,KAAA,EAAa,MAAA,IAAI,MAAM,OAAO,CAAA;AACnC,MAAM,MAAA,IAAA,GAAO,WAAW,OAAQ,CAAA,OAAA,EAAS,IAAI,CAAE,CAAA,OAAA,CAAQ,iBAAiB,EAAE,CAAA;AAC1E,MAAO,OAAA;AAAA,QACL,KAAK,CAAG,EAAA,IAAI,UAAU,kBAAmB,CAAA,KAAA,CAAM,EAAE,CAAC,CAAA,CAAA;AAAA,QAClD,KAAA;AAAA,QACA,YAAY,UAAW;AAAA,OACzB;AAAA;AACF,GACF;AACF"}
1
+ {"version":3,"file":"cubeforgeFriends.js","sources":["../../../src/features/games/cubeforgeFriends.ts"],"sourcesContent":["/**\n * Shared Cubeforge worlds over the games subgraph, and invites over chat.\n * Everything that touches the app (tokens, chat) comes in through `FriendsDeps`,\n * so this file can be tested without a running app.\n */\nimport type { CubeforgeFriends, InviteChat, SharedWorld } from './vendored';\nimport { inviteMessage, parseInviteMessage } from './gameInvite';\n\n/**\n * The terrain new shared worlds are made with. Only raise this in the same change\n * that vendors an engine able to draw it: the server refuses older engines from such\n * a world, so a mismatch would lock this app out of the worlds it creates.\n */\nconst TERRAIN_GENERATION = 2;\n\n/** A chat message that may be an invite. */\nexport interface RecentChatMessage {\n body: string;\n /** Who sent it, or null when this player did. */\n from: string | null;\n chatTitle: string;\n sentAt: number;\n}\n\nexport interface FriendsDeps {\n /** `https://host/graphql`. */\n graphqlUrl: string;\n /** A bearer token; `renew` asks for a new one. Null when signed out. */\n getToken: (renew: boolean) => Promise<string | null>;\n playerName: () => string;\n listChats: () => Promise<InviteChat[]>;\n sendToChat: (chatId: string, text: string) => Promise<void>;\n recentChatMessages: () => Promise<RecentChatMessage[]>;\n fetchImpl?: typeof fetch;\n}\n\ninterface WireWorld {\n id: string;\n name: string;\n seed: number;\n memberIds: string[];\n inviteCode: string | null;\n viewerIsOwner: boolean;\n}\n\ninterface GraphQLResponse<T> {\n data?: T | null;\n errors?: { message?: string; extensions?: { code?: string } }[];\n}\n\nconst WORLD_FIELDS = 'id name seed memberIds inviteCode viewerIsOwner';\nconst UNREACHABLE = 'Could not reach the game server. Check your connection and try again.';\nconst SIGN_IN = 'Please sign in again.';\n/** Longer than the session's own two quick retries, 3s then 10s after a failed mint. */\nconst TOKEN_WAIT_MS = 15_000;\nconst TOKEN_POLL_MS = 250;\n\nconst toWorld = (w: WireWorld): SharedWorld => ({\n id: w.id,\n name: w.name,\n seed: w.seed,\n memberCount: w.memberIds.length,\n inviteCode: w.inviteCode,\n ownedByMe: w.viewerIsOwner,\n});\n\n/**\n * Waits for a token that is still on its way. The app opens Games from a chat\n * card as soon as it is tapped, which can be before the signed-in session exists.\n */\nexport async function waitForToken(\n read: () => string | null,\n timeoutMs = TOKEN_WAIT_MS,\n intervalMs = TOKEN_POLL_MS,\n): Promise<string | null> {\n const deadline = Date.now() + timeoutMs;\n let token = read();\n while (!token && Date.now() < deadline) {\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => {\n setTimeout(resolve, intervalMs);\n });\n token = read();\n }\n return token;\n}\n\n/** One call to the games subgraph, renewing the token once when it is refused. */\nexport type GamesRequest = <T>(query: string, variables?: object) => Promise<T>;\n\nexport function createGamesRequest(deps: Pick<FriendsDeps, 'graphqlUrl' | 'getToken' | 'fetchImpl'>): GamesRequest {\n const { graphqlUrl, getToken, fetchImpl = fetch } = deps;\n\n const post = async <T>(query: string, variables: object, token: string): Promise<GraphQLResponse<T> | 401> => {\n let response: Response;\n try {\n response = await fetchImpl(graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },\n body: JSON.stringify({ query, variables }),\n });\n } catch {\n throw new Error(UNREACHABLE);\n }\n if (response.status === 401) return 401;\n try {\n return (await response.json()) as GraphQLResponse<T>;\n } catch {\n throw new Error(UNREACHABLE);\n }\n };\n\n const isUnauthenticated = <T>(result: GraphQLResponse<T> | 401): boolean =>\n result === 401 || Boolean(result.errors?.some((e) => e.extensions?.code === 'UNAUTHENTICATED'));\n\n return async <T>(query: string, variables: object = {}): Promise<T> => {\n const token = await getToken(false);\n if (!token) throw new Error(SIGN_IN);\n let result = await post<T>(query, variables, token);\n if (isUnauthenticated(result)) {\n const fresh = await getToken(true);\n if (!fresh) throw new Error(SIGN_IN);\n result = await post<T>(query, variables, fresh);\n }\n if (result === 401 || isUnauthenticated(result)) throw new Error(SIGN_IN);\n const message = result.errors?.[0]?.message;\n if (message) throw new Error(message);\n if (!result.data) throw new Error(UNREACHABLE);\n return result.data;\n };\n}\n\nexport function createCubeforgeFriends(deps: FriendsDeps): CubeforgeFriends {\n const { graphqlUrl, getToken, playerName, listChats, sendToChat, recentChatMessages } = deps;\n const request = createGamesRequest(deps);\n\n return {\n listWorlds: async () => {\n const data = await request<{ myGameWorlds: WireWorld[] }>(`query { myGameWorlds { ${WORLD_FIELDS} } }`);\n return data.myGameWorlds.map(toWorld);\n },\n createWorld: async (name, chatId) => {\n const data = await request<{ createGameWorld: WireWorld }>(\n `mutation($name: String!, $channelId: String, $gen: Int) { createGameWorld(name: $name, channelId: $channelId, gen: $gen) { ${WORLD_FIELDS} } }`,\n { name, channelId: chatId, gen: TERRAIN_GENERATION },\n );\n return toWorld(data.createGameWorld);\n },\n joinWorld: async (inviteCode) => {\n const data = await request<{ joinGameWorld: WireWorld }>(\n `mutation($inviteCode: String!) { joinGameWorld(inviteCode: $inviteCode) { ${WORLD_FIELDS} } }`,\n { inviteCode },\n );\n return toWorld(data.joinGameWorld);\n },\n leaveWorld: async (world) => {\n await request('mutation($id: ID!) { leaveGameWorld(id: $id) }', { id: world.id });\n },\n renameWorld: async (world, name) => {\n await request('mutation($id: ID!, $name: String!) { renameGameWorld(id: $id, name: $name) { id } }', {\n id: world.id,\n name,\n });\n },\n deleteWorld: async (world) => {\n await request('mutation($id: ID!) { deleteGameWorld(id: $id) }', { id: world.id });\n },\n listChats,\n listInvites: async () =>\n (await recentChatMessages()).flatMap(({ body, from, chatTitle, sentAt }) => {\n const invite = parseInviteMessage(body);\n return invite ? [{ code: invite.code, worldName: invite.worldName, from, chatTitle, sentAt }] : [];\n }),\n inviteToChat: async (world, chatId) => {\n if (!world.inviteCode) throw new Error('This world has no invite code.');\n await sendToChat(chatId, inviteMessage(world.name, world.inviteCode));\n },\n roomAccess: async (world, options) => {\n const token = await getToken(Boolean(options?.renewToken));\n if (!token) throw new Error(SIGN_IN);\n const base = graphqlUrl.replace(/^http/, 'ws').replace(/\\/graphql\\/?$/, '');\n return { url: `${base}/rooms/${encodeURIComponent(world.id)}`, token, playerName: playerName() };\n },\n };\n}\n"],"names":["_a"],"mappings":"+DAaA,MAAM,kBAAqB,GAAA,CAAA;AAsC3B,MAAM,YAAe,GAAA,iDAAA;AACrB,MAAM,WAAc,GAAA,uEAAA;AACpB,MAAM,OAAU,GAAA,uBAAA;AAEhB,MAAM,aAAgB,GAAA,IAAA;AACtB,MAAM,aAAgB,GAAA,GAAA;AACtB,MAAM,OAAA,GAAU,CAAC,CAA+B,MAAA;AAAA,EAC9C,IAAI,CAAE,CAAA,EAAA;AAAA,EACN,MAAM,CAAE,CAAA,IAAA;AAAA,EACR,MAAM,CAAE,CAAA,IAAA;AAAA,EACR,WAAA,EAAa,EAAE,SAAU,CAAA,MAAA;AAAA,EACzB,YAAY,CAAE,CAAA,UAAA;AAAA,EACd,WAAW,CAAE,CAAA;AACf,CAAA,CAAA;AAMA,eAAsB,YAAa,CAAA,IAAA,EAA2B,SAAY,GAAA,aAAA,EAAe,aAAa,aAAuC,EAAA;AAC3I,EAAM,MAAA,QAAA,GAAW,IAAK,CAAA,GAAA,EAAQ,GAAA,SAAA;AAC9B,EAAA,IAAI,QAAQ,IAAK,EAAA;AACjB,EAAA,OAAO,CAAC,KA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CAAQ,iBAAiB,EAAE,CAAA;AAC1E,MAAO,OAAA;AAAA,QACL,KAAK,CAAG,EAAA,IAAI,UAAU,kBAAmB,CAAA,KAAA,CAAM,EAAE,CAAC,CAAA,CAAA;AAAA,QAClD,KAAA;AAAA,QACA,YAAY,UAAW;AAAA,OACzB;AAAA;AACF,GACF;AACF"}
@@ -1,12 +1,33 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1
20
  const HELPER_CONNECTOR = "yantra-games";
2
21
  const HELPER_ACTION = "YANTRA_GAMES_HELPER";
3
22
  const HELPER_TIMEOUT_MS = 9e4;
4
23
  const NAME_TIMEOUT_MS = 3e4;
5
- const DAILY_HELPER_LIMIT = 20;
24
+ const DAILY_HELPER_LIMIT = 100;
6
25
  const MAX_NAME_CHARS = 24;
7
26
  const LIMIT_REPLY = "That is all the help I can give today. Come back tomorrow!";
8
27
  const UNAVAILABLE_REPLY = "I cannot reach my workshop right now. Please try again soon.";
9
28
  const TOO_TIGHT_REPLY = "That one did not come together. Tap ASK and say a size, like a small house or two floors.";
29
+ const LOCKED_REPLY = "This world cannot be changed, so I cannot build here.";
30
+ const PLAN_LOCKED = -2;
10
31
  const DID_NOT_FIT = "Your last plan placed nothing, so build right next to the player, starting on the ground at their feet.";
11
32
  const CONSENT_KEY = "yantra.cubeforge.helperConsent.v1";
12
33
  const USAGE_KEY = "yantra.cubeforge.helperUsage.v1";
@@ -48,21 +69,33 @@ async function askAndPreview(game, helper, message) {
48
69
  const snapshot = await game.helperSnapshot();
49
70
  if (!snapshot) return null;
50
71
  await game.helperSay("Let me take a look...");
51
- const shown = async (answer2) => answer2.plan !== null && await game.helperPropose(JSON.stringify(answer2.plan)) > 0;
72
+ const place = async (answer2) => {
73
+ const plan = asRecord(answer2.plan);
74
+ return plan ? game.helperPropose(JSON.stringify(__spreadProps(__spreadValues({}, plan), {
75
+ auto: true
76
+ }))) : 0;
77
+ };
78
+ const say = async (text) => {
79
+ if (text) await game.helperSay(text);
80
+ return text || null;
81
+ };
52
82
  let answer = await helper.ask(message, snapshot);
53
- if (answer.plan !== null && !await shown(answer)) {
83
+ if (answer.plan === null) return say(answer.reply);
84
+ let placed = await place(answer);
85
+ if (placed <= 0 && placed !== PLAN_LOCKED) {
54
86
  const fresh = await game.helperSnapshot();
55
87
  answer = fresh ? await helper.ask(`${DID_NOT_FIT} ${message}`, fresh) : {
56
88
  reply: "",
57
89
  plan: null
58
90
  };
59
- if (!await shown(answer)) {
60
- await game.helperSay(TOO_TIGHT_REPLY);
61
- return null;
62
- }
91
+ if (answer.plan === null && answer.reply) return say(answer.reply);
92
+ placed = await place(answer);
93
+ }
94
+ if (placed <= 0) {
95
+ await say(placed === PLAN_LOCKED ? LOCKED_REPLY : TOO_TIGHT_REPLY);
96
+ return null;
63
97
  }
64
- if (answer.reply) await game.helperSay(answer.reply);
65
- return answer.reply || null;
98
+ return say(answer.reply);
66
99
  }
67
100
  function createCubeforgeHelper(deps) {
68
101
  var _a;
@@ -75,7 +108,8 @@ function createCubeforgeHelper(deps) {
75
108
  ask: async (message, snapshot) => {
76
109
  var _a2;
77
110
  const today = await usedToday(storage, now());
78
- if (today >= DAILY_HELPER_LIMIT) return {
111
+ const again = message.startsWith(DID_NOT_FIT);
112
+ if (!again && today >= DAILY_HELPER_LIMIT) return {
79
113
  reply: LIMIT_REPLY,
80
114
  plan: null
81
115
  };
@@ -92,10 +126,12 @@ function createCubeforgeHelper(deps) {
92
126
  reply: UNAVAILABLE_REPLY,
93
127
  plan: null
94
128
  };
95
- await storage.setItem(USAGE_KEY, JSON.stringify({
96
- day: dayOf(now()),
97
- used: today + 1
98
- })).catch(() => void 0);
129
+ if (!again) {
130
+ await storage.setItem(USAGE_KEY, JSON.stringify({
131
+ day: dayOf(now()),
132
+ used: today + 1
133
+ })).catch(() => void 0);
134
+ }
99
135
  return {
100
136
  reply: typeof layer.reply === "string" ? layer.reply : "",
101
137
  plan: (_a2 = layer.plan) != null ? _a2 : null
@@ -124,4 +160,4 @@ function createCubeforgeHelper(deps) {
124
160
  }
125
161
  }
126
162
  };
127
- }export{DAILY_HELPER_LIMIT,HELPER_ACTION,HELPER_CONNECTOR,LIMIT_REPLY,TOO_TIGHT_REPLY,UNAVAILABLE_REPLY,askAndPreview,createCubeforgeHelper,helperConsentGiven,rememberHelperConsent};//# sourceMappingURL=cubeforgeHelper.js.map
163
+ }export{DAILY_HELPER_LIMIT,HELPER_ACTION,HELPER_CONNECTOR,LIMIT_REPLY,LOCKED_REPLY,PLAN_LOCKED,TOO_TIGHT_REPLY,UNAVAILABLE_REPLY,askAndPreview,createCubeforgeHelper,helperConsentGiven,rememberHelperConsent};//# sourceMappingURL=cubeforgeHelper.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cubeforgeHelper.js","sources":["../../../src/features/games/cubeforgeHelper.ts"],"sourcesContent":["/**\n * The game's build helper, reached through a connector the way Dictate reaches\n * its AI. What goes out is the blocks around the player and what they typed; no\n * name, chat or friend is ever part of it.\n */\nimport type { RemoteConnectorExec } from '../canvas/videoEditor/remoteMediaClient';\nimport type { CubeforgeHelper, HelperAnswer } from './vendored';\n\nexport const HELPER_CONNECTOR = 'yantra-games';\nexport const HELPER_ACTION = 'YANTRA_GAMES_HELPER';\nconst HELPER_TIMEOUT_MS = 90_000;\nconst NAME_TIMEOUT_MS = 30_000;\n/** A day's worth of asking, kept on this device. */\nexport const DAILY_HELPER_LIMIT = 20;\nconst MAX_NAME_CHARS = 24;\n\nexport const LIMIT_REPLY = 'That is all the help I can give today. Come back tomorrow!';\nexport const UNAVAILABLE_REPLY = 'I cannot reach my workshop right now. Please try again soon.';\n\n/** Only after two plans placed nothing at all, which a game that clears its own way rarely sees. */\nexport const TOO_TIGHT_REPLY =\n 'That one did not come together. Tap ASK and say a size, like a small house or two floors.';\n/**\n * Goes first, because the connector keeps only so much of a message. Older games\n * only build into empty air; newer ones clear their own way and take a level pad.\n */\nconst DID_NOT_FIT =\n 'Your last plan placed nothing, so build right next to the player, starting on the ground at their feet.';\n\nconst CONSENT_KEY = 'yantra.cubeforge.helperConsent.v1';\nconst USAGE_KEY = 'yantra.cubeforge.helperUsage.v1';\n\nexport interface HelperStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\ntype Json = Record<string, unknown>;\n\nfunction asRecord(value: unknown): Json | null {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : null;\n}\n\n/** The first layer of the reply (itself, its `data`, its `result`...) holding `key`. */\nfunction findLayer(raw: unknown, key: string): Json | null {\n let layer = asRecord(raw);\n for (let depth = 0; layer && depth < 6; depth += 1) {\n if (key in layer) return layer;\n layer = asRecord(layer.data) ?? asRecord(layer.result);\n }\n return null;\n}\n\nfunction dayOf(now: number): string {\n return new Date(now).toISOString().slice(0, 10);\n}\n\nasync function usedToday(storage: HelperStorage, now: number): Promise<number> {\n try {\n const saved = JSON.parse((await storage.getItem(USAGE_KEY)) ?? '{}') as { day?: string; used?: number };\n return saved.day === dayOf(now) ? Number(saved.used) || 0 : 0;\n } catch {\n return 0;\n }\n}\n\nexport async function helperConsentGiven(storage: HelperStorage): Promise<boolean> {\n try {\n return (await storage.getItem(CONSENT_KEY)) === '1';\n } catch {\n return false;\n }\n}\n\nexport async function rememberHelperConsent(storage: HelperStorage): Promise<void> {\n await storage.setItem(CONSENT_KEY, '1');\n}\n\n/** What the helper needs from the running game. */\nexport interface HelperGame {\n helperSnapshot(): Promise<string | null>;\n helperPropose(plan: string): Promise<number>;\n helperSay(text: string): Promise<boolean>;\n}\n\n/**\n * One request from the player, start to finish. A plan that does not fit gets\n * one more try before the player hears anything, and a reply is only shown once\n * what it describes is really on screen.\n */\nexport async function askAndPreview(\n game: HelperGame,\n helper: CubeforgeHelper,\n message: string,\n): Promise<string | null> {\n const snapshot = await game.helperSnapshot();\n if (!snapshot) return null;\n await game.helperSay('Let me take a look...');\n const shown = async (answer: HelperAnswer) =>\n answer.plan !== null && (await game.helperPropose(JSON.stringify(answer.plan))) > 0;\n\n let answer = await helper.ask(message, snapshot);\n if (answer.plan !== null && !(await shown(answer))) {\n const fresh = await game.helperSnapshot();\n answer = fresh ? await helper.ask(`${DID_NOT_FIT} ${message}`, fresh) : { reply: '', plan: null };\n if (!(await shown(answer))) {\n await game.helperSay(TOO_TIGHT_REPLY);\n return null;\n }\n }\n if (answer.reply) await game.helperSay(answer.reply);\n return answer.reply || null;\n}\n\nexport function createCubeforgeHelper(deps: {\n exec: RemoteConnectorExec;\n storage: HelperStorage;\n now?: () => number;\n}): CubeforgeHelper {\n const { exec, storage } = deps;\n const now = deps.now ?? Date.now;\n return {\n ask: async (message, snapshot): Promise<HelperAnswer> => {\n const today = await usedToday(storage, now());\n if (today >= DAILY_HELPER_LIMIT) return { reply: LIMIT_REPLY, plan: null };\n try {\n const raw = await exec(\n HELPER_CONNECTOR,\n HELPER_ACTION,\n { mode: 'build', message, snapshot: JSON.parse(snapshot) as unknown },\n { timeoutMs: HELPER_TIMEOUT_MS },\n );\n const layer = findLayer(raw, 'reply');\n if (!layer) return { reply: UNAVAILABLE_REPLY, plan: null };\n await storage\n .setItem(USAGE_KEY, JSON.stringify({ day: dayOf(now()), used: today + 1 }))\n .catch(() => undefined);\n return { reply: typeof layer.reply === 'string' ? layer.reply : '', plan: layer.plan ?? null };\n } catch {\n return { reply: UNAVAILABLE_REPLY, plan: null };\n }\n },\n nameWorld: async (summary) => {\n try {\n const raw = await exec(\n HELPER_CONNECTOR,\n HELPER_ACTION,\n { mode: 'name', summary: JSON.parse(summary) as unknown },\n { timeoutMs: NAME_TIMEOUT_MS },\n );\n const name = findLayer(raw, 'name')?.name;\n const clean = typeof name === 'string' ? name.trim().slice(0, MAX_NAME_CHARS) : '';\n return clean || null;\n } catch {\n return null;\n }\n },\n };\n}\n"],"names":["answer","_a"],"mappings":"AAOO,MAAM,gBAAmB,GAAA;AACzB,MAAM,aAAgB,GAAA;AAC7B,MAAM,iBAAoB,GAAA,GAAA;AAC1B,MAAM,eAAkB,GAAA,GAAA;AAEjB,MAAM,kBAAqB,GAAA;AAClC,MAAM,cAAiB,GAAA,EAAA;AAChB,MAAM,WAAc,GAAA;AACpB,MAAM,iBAAoB,GAAA;AAG1B,MAAM,eAAkB,GAAA;AAK/B,MAAM,WAAc,GAAA,yGAAA;AACpB,MAAM,WAAc,GAAA,mCAAA;AACpB,MAAM,SAAY,GAAA,iCAAA;AAMlB,SAAS,SAAS,KAA6B,EAAA;AAC7C,EAAO,OAAA,KAAA,IAAS,OAAO,KAAU,KAAA,QAAA,IAAY,CAAC,KAAM,CAAA,OAAA,CAAQ,KAAK,CAAA,GAAI,KAAgB,GAAA,IAAA;AACvF;AAGA,SAAS,SAAA,CAAU,KAAc,GAA0B,EAAA;AApC3D,EAAA,IAAA,EAAA;AAqCE,EAAI,IAAA,KAAA,GAAQ,SAAS,GAAG,CAAA;AACxB,EAAA,KAAA,IAAS,QAAQ,CAAG,EAAA,KAAA,IAAS,KAAQ,GAAA,CAAA,EAAG,SAAS,CAAG,EAAA;AAClD,IAAI,IAAA,GAAA,IAAO,OAAc,OAAA,KAAA;AACzB,IAAA,KAAA,GAAA,CAAQ,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;AAmJM,MAAI,IAAA;AACF,QAAA,MAAM,GAAM,GAAA,MAAM,IAAK,CAAA,gBAAA,EAAkB,aAAe,EAAA;AAAA,UACtD,IAAM,EAAA,MAAA;AAAA,UACN,OAAA,EAAS,IAAK,CAAA,KAAA,CAAM,OAAO;AAAA,SAC1B,EAAA;AAAA,UACD,SAAW,EAAA;AAAA,SACZ,CAAA;AACD,QAAA,MAAM,QAAOA,GAAA,GAAA,SAAA,CAAU,KAAK,MAAM,CAAA,KAArB,gBAAAA,GAAwB,CAAA,IAAA;AACrC,QAAM,MAAA,KAAA,GAAQ,OAAO,IAAA,KAAS,QAAW,GAAA,IAAA,CAAK,MAAO,CAAA,KAAA,CAAM,CAAG,EAAA,cAAc,CAAI,GAAA,EAAA;AAChF,QAAA,OAAO,KAAS,IAAA,IAAA;AAAA,OACV,CAAA,OAAA,CAAA,EAAA;AACN,QAAO,OAAA,IAAA;AAAA;AACT;AACF,GACF;AACF"}
1
+ {"version":3,"file":"cubeforgeHelper.js","sources":["../../../src/features/games/cubeforgeHelper.ts"],"sourcesContent":["/**\n * The game's build helper, reached through a connector the way Dictate reaches\n * its AI. What goes out is the blocks around the player and what they typed; no\n * name, chat or friend is ever part of it.\n */\nimport type { RemoteConnectorExec } from '../canvas/videoEditor/remoteMediaClient';\nimport type { CubeforgeHelper, HelperAnswer } from './vendored';\n\nexport const HELPER_CONNECTOR = 'yantra-games';\nexport const HELPER_ACTION = 'YANTRA_GAMES_HELPER';\nconst HELPER_TIMEOUT_MS = 90_000;\nconst NAME_TIMEOUT_MS = 30_000;\n/** A day's worth of asking, kept on this device. A second try at the same request is not counted. */\nexport const DAILY_HELPER_LIMIT = 100;\nconst MAX_NAME_CHARS = 24;\n\nexport const LIMIT_REPLY = 'That is all the help I can give today. Come back tomorrow!';\nexport const UNAVAILABLE_REPLY = 'I cannot reach my workshop right now. Please try again soon.';\n\n/** Only after two plans placed nothing at all, which a game that clears its own way rarely sees. */\nexport const TOO_TIGHT_REPLY =\n 'That one did not come together. Tap ASK and say a size, like a small house or two floors.';\nexport const LOCKED_REPLY = 'This world cannot be changed, so I cannot build here.';\n\n/**\n * Why the game could not take a plan, from games that say: -1 is any reason on\n * an older game (or no game), -2 the world cannot be changed, -3 no snapshot,\n * -4 unreadable, -5 no steps, -6 nothing in it could be built.\n */\nexport const PLAN_LOCKED = -2;\n/**\n * Goes first, because the connector keeps only so much of a message. Older games\n * only build into empty air; newer ones clear their own way and take a level pad.\n */\nconst DID_NOT_FIT =\n 'Your last plan placed nothing, so build right next to the player, starting on the ground at their feet.';\n\nconst CONSENT_KEY = 'yantra.cubeforge.helperConsent.v1';\nconst USAGE_KEY = 'yantra.cubeforge.helperUsage.v1';\n\nexport interface HelperStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\ntype Json = Record<string, unknown>;\n\nfunction asRecord(value: unknown): Json | null {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : null;\n}\n\n/** The first layer of the reply (itself, its `data`, its `result`...) holding `key`. */\nfunction findLayer(raw: unknown, key: string): Json | null {\n let layer = asRecord(raw);\n for (let depth = 0; layer && depth < 6; depth += 1) {\n if (key in layer) return layer;\n layer = asRecord(layer.data) ?? asRecord(layer.result);\n }\n return null;\n}\n\nfunction dayOf(now: number): string {\n return new Date(now).toISOString().slice(0, 10);\n}\n\nasync function usedToday(storage: HelperStorage, now: number): Promise<number> {\n try {\n const saved = JSON.parse((await storage.getItem(USAGE_KEY)) ?? '{}') as { day?: string; used?: number };\n return saved.day === dayOf(now) ? Number(saved.used) || 0 : 0;\n } catch {\n return 0;\n }\n}\n\nexport async function helperConsentGiven(storage: HelperStorage): Promise<boolean> {\n try {\n return (await storage.getItem(CONSENT_KEY)) === '1';\n } catch {\n return false;\n }\n}\n\nexport async function rememberHelperConsent(storage: HelperStorage): Promise<void> {\n await storage.setItem(CONSENT_KEY, '1');\n}\n\n/** What the helper needs from the running game. */\nexport interface HelperGame {\n helperSnapshot(): Promise<string | null>;\n helperPropose(plan: string): Promise<number>;\n helperSay(text: string): Promise<boolean>;\n}\n\n/**\n * One request from the player, start to finish. The plan starts building at once\n * (`auto`), so the player can keep playing or walk off and come back to it; UNDO\n * takes it away. A plan that does not fit gets one more try before the player\n * hears anything, and a reply is only shown once what it describes is really\n * going up. Older games ignore `auto` and show a preview to accept.\n */\nexport async function askAndPreview(\n game: HelperGame,\n helper: CubeforgeHelper,\n message: string,\n): Promise<string | null> {\n const snapshot = await game.helperSnapshot();\n if (!snapshot) return null;\n await game.helperSay('Let me take a look...');\n const place = async (answer: HelperAnswer): Promise<number> => {\n const plan = asRecord(answer.plan);\n return plan ? game.helperPropose(JSON.stringify({ ...plan, auto: true })) : 0;\n };\n\n const say = async (text: string) => {\n if (text) await game.helperSay(text);\n return text || null;\n };\n\n let answer = await helper.ask(message, snapshot);\n // A plain answer, such as how to light a cave, has nothing to build.\n if (answer.plan === null) return say(answer.reply);\n let placed = await place(answer);\n if (placed <= 0 && placed !== PLAN_LOCKED) {\n const fresh = await game.helperSnapshot();\n answer = fresh ? await helper.ask(`${DID_NOT_FIT} ${message}`, fresh) : { reply: '', plan: null };\n // Out of reach of the workshop this time: say so rather than blame the plan.\n if (answer.plan === null && answer.reply) return say(answer.reply);\n placed = await place(answer);\n }\n if (placed <= 0) {\n await say(placed === PLAN_LOCKED ? LOCKED_REPLY : TOO_TIGHT_REPLY);\n return null;\n }\n return say(answer.reply);\n}\n\nexport function createCubeforgeHelper(deps: {\n exec: RemoteConnectorExec;\n storage: HelperStorage;\n now?: () => number;\n}): CubeforgeHelper {\n const { exec, storage } = deps;\n const now = deps.now ?? Date.now;\n return {\n ask: async (message, snapshot): Promise<HelperAnswer> => {\n const today = await usedToday(storage, now());\n // The second try at a plan that did not fit is the same request.\n const again = message.startsWith(DID_NOT_FIT);\n if (!again && today >= DAILY_HELPER_LIMIT) return { reply: LIMIT_REPLY, plan: null };\n try {\n const raw = await exec(\n HELPER_CONNECTOR,\n HELPER_ACTION,\n { mode: 'build', message, snapshot: JSON.parse(snapshot) as unknown },\n { timeoutMs: HELPER_TIMEOUT_MS },\n );\n const layer = findLayer(raw, 'reply');\n if (!layer) return { reply: UNAVAILABLE_REPLY, plan: null };\n if (!again) {\n await storage\n .setItem(USAGE_KEY, JSON.stringify({ day: dayOf(now()), used: today + 1 }))\n .catch(() => undefined);\n }\n return { reply: typeof layer.reply === 'string' ? layer.reply : '', plan: layer.plan ?? null };\n } catch {\n return { reply: UNAVAILABLE_REPLY, plan: null };\n }\n },\n nameWorld: async (summary) => {\n try {\n const raw = await exec(\n HELPER_CONNECTOR,\n HELPER_ACTION,\n { mode: 'name', summary: JSON.parse(summary) as unknown },\n { timeoutMs: NAME_TIMEOUT_MS },\n );\n const name = findLayer(raw, 'name')?.name;\n const clean = typeof name === 'string' ? name.trim().slice(0, MAX_NAME_CHARS) : '';\n return clean || null;\n } catch {\n return null;\n }\n },\n };\n}\n"],"names":["answer","_a"],"mappings":";;;;;;;;;;;;;;;;;;;AAOO,MAAM,gBAAmB,GAAA;AACzB,MAAM,aAAgB,GAAA;AAC7B,MAAM,iBAAoB,GAAA,GAAA;AAC1B,MAAM,eAAkB,GAAA,GAAA;AAEjB,MAAM,kBAAqB,GAAA;AAClC,MAAM,cAAiB,GAAA,EAAA;AAChB,MAAM,WAAc,GAAA;AACpB,MAAM,iBAAoB,GAAA;AAG1B,MAAM,eAAkB,GAAA;AACxB,MAAM,YAAe,GAAA;AAOrB,MAAM,WAAc,GAAA;AAK3B,MAAM,WAAc,GAAA,yGAAA;AACpB,MAAM,WAAc,GAAA,mCAAA;AACpB,MAAM,SAAY,GAAA,iCAAA;AAMlB,SAAS,SAAS,KAA6B,EAAA;AAC7C,EAAO,OAAA,KAAA,IAAS,OAAO,KAAU,KAAA,QAAA,IAAY,CAAC,KAAM,CAAA,OAAA,CAAQ,KAAK,CAAA,GAAI,KAAgB,GAAA,IAAA;AACvF;AAGA,SAAS,SAAA,CAAU,KAAc,GAA0B,EAAA;A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AA,GAAQ,OAAO,IAAA,KAAS,QAAW,GAAA,IAAA,CAAK,MAAO,CAAA,KAAA,CAAM,CAAG,EAAA,cAAc,CAAI,GAAA,EAAA;AAChF,QAAA,OAAO,KAAS,IAAA,IAAA;AAAA,OACV,CAAA,OAAA,CAAA,EAAA;AACN,QAAO,OAAA,IAAA;AAAA;AACT;AACF,GACF;AACF"}
@@ -0,0 +1,71 @@
1
+ import'./vendored/core/engine/palette.js';import'./vendored/core/lessons/lessons.js';import'./vendored/core/cubeforge/items.js';import'./vendored/core/cubeforge/recipes.js';import {lookPrice}from'./vendored/core/cubeforge/looks.js';import'./vendored/ui/GamesRoot.js';const CACHE_KEY = "yantra.cubeforge.ownedLooks.v1";
2
+ function createCubeforgeLooks(deps) {
3
+ const {
4
+ request,
5
+ storage,
6
+ playerKey
7
+ } = deps;
8
+ const key = `${CACHE_KEY}:${playerKey}`;
9
+ const remember = async (ids) => {
10
+ if (playerKey) await storage.setItem(key, JSON.stringify(ids)).catch(() => void 0);
11
+ };
12
+ return {
13
+ /** What this phone last knew, for a quick first look. */
14
+ cached: async () => {
15
+ var _a;
16
+ if (!playerKey) return [];
17
+ try {
18
+ const ids = JSON.parse((_a = await storage.getItem(key)) != null ? _a : "[]");
19
+ return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
20
+ } catch (e) {
21
+ return [];
22
+ }
23
+ },
24
+ /** The server's list, which replaces the cached one. */
25
+ refresh: async () => {
26
+ const {
27
+ myLooks
28
+ } = await request("query { myLooks }");
29
+ await remember(myLooks);
30
+ return myLooks;
31
+ },
32
+ unlock: async (lookId) => {
33
+ const {
34
+ unlockLook
35
+ } = await request("mutation($lookId: String!) { unlockLook(lookId: $lookId) { ok lookId owned credits reason } }", {
36
+ lookId
37
+ });
38
+ return unlockLook;
39
+ },
40
+ remember
41
+ };
42
+ }
43
+ const COULD_NOT = "Could not unlock";
44
+ async function unlockLookFlow(look, looks, prompts) {
45
+ const price = lookPrice(look);
46
+ const balance = await prompts.balance().catch(() => null);
47
+ const have = balance === null ? "" : `
48
+
49
+ You have ${Math.max(0, Math.floor(balance)).toLocaleString()} credits.`;
50
+ const yes = await prompts.confirm(`Unlock ${look.name}?`, `Uses ${price.toLocaleString()} Yantra credits. It stays yours.${have}`, `Use ${price.toLocaleString()} credits`);
51
+ if (!yes) return false;
52
+ let result;
53
+ try {
54
+ result = await looks.unlock(look.id);
55
+ } catch (error) {
56
+ prompts.tell(COULD_NOT, error instanceof Error ? error.message : "Please try again.");
57
+ return false;
58
+ }
59
+ if (result.ok) return true;
60
+ switch (result.reason) {
61
+ case "not_enough_credits":
62
+ prompts.offerCredits(`${look.name} needs ${price.toLocaleString()} credits. Add credits or upgrade to unlock it.`);
63
+ break;
64
+ case "charge_failed":
65
+ prompts.tell(COULD_NOT, `${look.name} did not go through. Please try again in a moment. You are never charged twice for the same look.`);
66
+ break;
67
+ default:
68
+ prompts.tell(COULD_NOT, "Looks cannot be bought right now. Please try again later.");
69
+ }
70
+ return false;
71
+ }export{createCubeforgeLooks,unlockLookFlow};//# sourceMappingURL=cubeforgeLooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cubeforgeLooks.js","sources":["../../../src/features/games/cubeforgeLooks.ts"],"sourcesContent":["/**\n * Rare and legendary Cubeforge looks: which ones this player owns, and buying\n * one with Yantra credits. The games server prices and charges; the app only\n * asks first and says how it went. Owned ids are kept on the phone too, so the\n * avatar screen shows them at once, but the server's list is the one that counts.\n */\nimport type { GamesRequest } from './cubeforgeFriends';\nimport { lookPrice, type Look } from './vendored';\n\nexport type UnlockReason = 'not_found' | 'free' | 'not_enough_credits' | 'charge_failed' | 'unavailable';\n\nexport interface LookUnlock {\n ok: boolean;\n lookId: string;\n owned: boolean;\n credits: number;\n reason: UnlockReason | null;\n}\n\nexport interface LooksStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\nconst CACHE_KEY = 'yantra.cubeforge.ownedLooks.v1';\n\n/** `playerKey` names whose looks the phone keeps; empty keeps none, rather than risk showing another person's. */\nexport function createCubeforgeLooks(deps: { request: GamesRequest; storage: LooksStorage; playerKey: string }) {\n const { request, storage, playerKey } = deps;\n const key = `${CACHE_KEY}:${playerKey}`;\n const remember = async (ids: string[]) => {\n if (playerKey) await storage.setItem(key, JSON.stringify(ids)).catch(() => undefined);\n };\n return {\n /** What this phone last knew, for a quick first look. */\n cached: async (): Promise<string[]> => {\n if (!playerKey) return [];\n try {\n const ids: unknown = JSON.parse((await storage.getItem(key)) ?? '[]');\n return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === 'string') : [];\n } catch {\n return [];\n }\n },\n /** The server's list, which replaces the cached one. */\n refresh: async (): Promise<string[]> => {\n const { myLooks } = await request<{ myLooks: string[] }>('query { myLooks }');\n await remember(myLooks);\n return myLooks;\n },\n unlock: async (lookId: string): Promise<LookUnlock> => {\n const { unlockLook } = await request<{ unlockLook: LookUnlock }>(\n 'mutation($lookId: String!) { unlockLook(lookId: $lookId) { ok lookId owned credits reason } }',\n { lookId },\n );\n return unlockLook;\n },\n remember,\n };\n}\n\nexport type CubeforgeLooks = ReturnType<typeof createCubeforgeLooks>;\n\n/** What the player sees and taps along the way, so the flow can be tested without a phone. */\nexport interface UnlockPrompts {\n /** Asks before spending; true to go ahead. */\n confirm: (title: string, message: string, spend: string) => Promise<boolean>;\n /** Credits this organisation can spend now, or null when they could not be read. */\n balance: () => Promise<number | null>;\n /** The way to more credits, after a refusal for credits. */\n offerCredits: (message: string) => void;\n tell: (title: string, message: string) => void;\n}\n\nconst COULD_NOT = 'Could not unlock';\n\n/**\n * Asks the player, then buys the look. True once it is theirs, so the avatar\n * screen can put it on.\n */\nexport async function unlockLookFlow(\n look: Pick<Look, 'id' | 'name' | 'tier'>,\n looks: Pick<CubeforgeLooks, 'unlock'>,\n prompts: UnlockPrompts,\n): Promise<boolean> {\n const price = lookPrice(look);\n const balance = await prompts.balance().catch(() => null);\n const have = balance === null ? '' : `\\n\\nYou have ${Math.max(0, Math.floor(balance)).toLocaleString()} credits.`;\n const yes = await prompts.confirm(\n `Unlock ${look.name}?`,\n `Uses ${price.toLocaleString()} Yantra credits. It stays yours.${have}`,\n `Use ${price.toLocaleString()} credits`,\n );\n if (!yes) return false;\n let result: LookUnlock;\n try {\n result = await looks.unlock(look.id);\n } catch (error) {\n prompts.tell(COULD_NOT, error instanceof Error ? error.message : 'Please try again.');\n return false;\n }\n if (result.ok) return true;\n switch (result.reason) {\n case 'not_enough_credits':\n prompts.offerCredits(\n `${look.name} needs ${price.toLocaleString()} credits. Add credits or upgrade to unlock it.`,\n );\n break;\n case 'charge_failed':\n prompts.tell(\n COULD_NOT,\n `${look.name} did not go through. Please try again in a moment. You are never charged twice for the same look.`,\n );\n break;\n default:\n prompts.tell(COULD_NOT, 'Looks cannot be bought right now. Please try again later.');\n }\n return false;\n}\n"],"names":[],"mappings":"2QAoBA,MAAM,SAAY,GAAA,gCAAA;AAGX,SAAS,qBAAqB,IAIlC,EAAA;AACD,EAAM,MAAA;AAAA,IACJ,OAAA;AAAA,IACA,OAAA;AAAA,IACA;AAAA,GACE,GAAA,IAAA;AACJ,EAAA,MAAM,GAAM,GAAA,CAAA,EAAG,SAAS,CAAA,CAAA,EAAI,SAAS,CAAA,CAAA;AACrC,EAAM,MAAA,QAAA,GAAW,OAAO,GAAkB,KAAA;AACxC,IAAA,IAAI,SAAW,EAAA,MAAM,OAAQ,CAAA,OAAA,CAAQ,GAAK,EAAA,IAAA,CAAK,SAAU,CAAA,GAAG,CAAC,CAAA,CAAE,KAAM,CAAA,MAAM,MAAS,CAAA;AAAA,GACtF;AACA,EAAO,OAAA;AAAA;AAAA,IAEL,QAAQ,YAA+B;AAvC3C,MAAA,IAAA,EAAA;AAwCM,MAAI,IAAA,CAAC,SAAW,EAAA,OAAO,EAAC;AACxB,MAAI,IAAA;AACF,QAAM,MAAA,GAAA,GAAe,KAAK,KAAO,CAAA,CAAA,EAAA,GAAA,MAAM,QAAQ,OAAQ,CA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M,cAAe,EAAC,mCAAmC,IAAI,CAAA,CAAA,EAAI,OAAO,KAAM,CAAA,cAAA,EAAgB,CAAU,QAAA,CAAA,CAAA;AAC1K,EAAI,IAAA,CAAC,KAAY,OAAA,KAAA;AACjB,EAAI,IAAA,MAAA;AACJ,EAAI,IAAA;AACF,IAAA,MAAA,GAAS,MAAM,KAAA,CAAM,MAAO,CAAA,IAAA,CAAK,EAAE,CAAA;AAAA,WAC5B,KAAO,EAAA;AACd,IAAA,OAAA,CAAQ,KAAK,SAAW,EAAA,KAAA,YAAiB,KAAQ,GAAA,KAAA,CAAM,UAAU,mBAAmB,CAAA;AACpF,IAAO,OAAA,KAAA;AAAA;AAET,EAAI,IAAA,MAAA,CAAO,IAAW,OAAA,IAAA;AACtB,EAAA,QAAQ,OAAO,MAAQ;AAAA,IACrB,KAAK,oBAAA;AACH,MAAQ,OAAA,CAAA,YAAA,CAAa,GAAG,IAAK,CAAA,IAAI,UAAU,KAAM,CAAA,cAAA,EAAgB,CAAgD,8CAAA,CAAA,CAAA;AACjH,MAAA;AAAA,IACF,KAAK,eAAA;AACH,MAAA,OAAA,CAAQ,IAAK,CAAA,SAAA,EAAW,CAAG,EAAA,IAAA,CAAK,IAAI,CAAmG,iGAAA,CAAA,CAAA;AACvI,MAAA;AAAA,IACF;AACE,MAAQ,OAAA,CAAA,IAAA,CAAK,WAAW,2DAA2D,CAAA;AAAA;AAEvF,EAAO,OAAA,KAAA;AACT"}
@@ -1,10 +1,17 @@
1
- import {requireOptionalNativeModule}from'expo-modules-core';const UPRIGHT = 3;
1
+ import {AppState}from'react-native';import {requireOptionalNativeModule}from'expo-modules-core';const UPRIGHT = 3;
2
2
  const SIDEWAYS = 5;
3
3
  function holdGameScreen(orientation) {
4
4
  const native = requireOptionalNativeModule("ExpoScreenOrientation");
5
5
  if (!native) return () => void 0;
6
- native.lockAsync(orientation === "portrait" ? UPRIGHT : SIDEWAYS).catch(() => void 0);
6
+ const turn = () => {
7
+ native.lockAsync(orientation === "portrait" ? UPRIGHT : SIDEWAYS).catch(() => void 0);
8
+ };
9
+ turn();
10
+ const returning = AppState.addEventListener("change", (state) => {
11
+ if (state === "active") turn();
12
+ });
7
13
  return () => {
14
+ returning.remove();
8
15
  native.lockAsync(UPRIGHT).catch(() => void 0);
9
16
  };
10
17
  }export{holdGameScreen};//# sourceMappingURL=gameOrientation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"gameOrientation.js","sources":["../../../src/features/games/gameOrientation.ts"],"sourcesContent":["/**\n * Turning the screen for Cubeforge; the rest of the app stays upright. The native\n * module is absent on a binary built before this shipped, which an over-the-air\n * update can reach, and then the game simply stays upright.\n *\n * The game asks for a definite orientation. \"Default\" would not do: on iOS it means\n * the app's own default, which is upright, so the game could never turn.\n */\nimport { requireOptionalNativeModule } from 'expo-modules-core';\nimport type { GameOrientation } from './vendored';\n\n/** `OrientationLock.PORTRAIT_UP` and `.LANDSCAPE` (either side) in expo-screen-orientation. */\nconst UPRIGHT = 3;\nconst SIDEWAYS = 5;\n\ninterface NativeOrientation {\n lockAsync(lock: number): Promise<void>;\n}\n\n/** Turns the screen for the game, and returns the function that puts it back upright. */\nexport function holdGameScreen(orientation: GameOrientation): () => void {\n const native = requireOptionalNativeModule<NativeOrientation>('ExpoScreenOrientation');\n if (!native) return () => undefined;\n native.lockAsync(orientation === 'portrait' ? UPRIGHT : SIDEWAYS).catch(() => undefined);\n return () => {\n native.lockAsync(UPRIGHT).catch(() => undefined);\n };\n}\n"],"names":[],"mappings":"4DAYA,MAAM,OAAU,GAAA,CAAA;AAChB,MAAM,QAAW,GAAA,CAAA;AAMV,SAAS,eAAe,WAA0C,EAAA;AACvE,EAAM,MAAA,MAAA,GAAS,4BAA+C,uBAAuB,CAAA;AACrF,EAAI,IAAA,CAAC,MAAQ,EAAA,OAAO,MAAM,MAAA;AAC1B,EAAO,MAAA,CAAA,SAAA,CAAU,gBAAgB,UAAa,GAAA,OAAA,GAAU,QAAQ,CAAE,CAAA,KAAA,CAAM,MAAM,MAAS,CAAA;AACvF,EAAA,OAAO,MAAM;AACX,IAAA,MAAA,CAAO,SAAU,CAAA,OAAO,CAAE,CAAA,KAAA,CAAM,MAAM,MAAS,CAAA;AAAA,GACjD;AACF"}
1
+ {"version":3,"file":"gameOrientation.js","sources":["../../../src/features/games/gameOrientation.ts"],"sourcesContent":["/**\n * Turning the screen for Cubeforge; the rest of the app stays upright. The native\n * module is absent on a binary built before this shipped, which an over-the-air\n * update can reach, and then the game simply stays upright.\n *\n * The game asks for a definite orientation. \"Default\" would not do: on iOS it means\n * the app's own default, which is upright, so the game could never turn.\n *\n * On iOS the module forgets the lock whenever the app goes to the background (it\n * drops its controller's mask then and does not put it back), so after switching\n * apps the game came back upright. The lock is asked for again on every return.\n */\nimport { AppState } from 'react-native';\nimport { requireOptionalNativeModule } from 'expo-modules-core';\nimport type { GameOrientation } from './vendored';\n\n/** `OrientationLock.PORTRAIT_UP` and `.LANDSCAPE` (either side) in expo-screen-orientation. */\nconst UPRIGHT = 3;\nconst SIDEWAYS = 5;\n\ninterface NativeOrientation {\n lockAsync(lock: number): Promise<void>;\n}\n\n/** Turns the screen for the game, and returns the function that puts it back upright. */\nexport function holdGameScreen(orientation: GameOrientation): () => void {\n const native = requireOptionalNativeModule<NativeOrientation>('ExpoScreenOrientation');\n if (!native) return () => undefined;\n const turn = () => {\n native.lockAsync(orientation === 'portrait' ? UPRIGHT : SIDEWAYS).catch(() => undefined);\n };\n turn();\n const returning = AppState.addEventListener('change', (state) => {\n if (state === 'active') turn();\n });\n return () => {\n returning.remove();\n native.lockAsync(UPRIGHT).catch(() => undefined);\n };\n}\n"],"names":[],"mappings":"gGAiBA,MAAM,OAAU,GAAA,CAAA;AAChB,MAAM,QAAW,GAAA,CAAA;AAMV,SAAS,eAAe,WAA0C,EAAA;AACvE,EAAM,MAAA,MAAA,GAAS,4BAA+C,uBAAuB,CAAA;AACrF,EAAI,IAAA,CAAC,MAAQ,EAAA,OAAO,MAAM,MAAA;AAC1B,EAAA,MAAM,OAAO,MAAM;AACjB,IAAO,MAAA,CAAA,SAAA,CAAU,gBAAgB,UAAa,GAAA,OAAA,GAAU,QAAQ,CAAE,CAAA,KAAA,CAAM,MAAM,MAAS,CAAA;AAAA,GACzF;AACA,EAAK,IAAA,EAAA;AACL,EAAA,MAAM,SAAY,GAAA,QAAA,CAAS,gBAAiB,CAAA,QAAA,EAAU,CAAS,KAAA,KAAA;AAC7D,IAAI,IAAA,KAAA,KAAU,UAAe,IAAA,EAAA;AAAA,GAC9B,CAAA;AACD,EAAA,OAAO,MAAM;AACX,IAAA,SAAA,CAAU,MAAO,EAAA;AACjB,IAAA,MAAA,CAAO,SAAU,CAAA,OAAO,CAAE,CAAA,KAAA,CAAM,MAAM,MAAS,CAAA;AAAA,GACjD;AACF"}
@@ -1,6 +1,18 @@
1
1
  import {useRef,useMemo}from'react';import {useApolloClient,gql}from'@apollo/client/index.js';import {config}from'../../config/env-config.js';import {useCanvasSession}from'../canvas/useCanvasSession.js';import {pickAuthor,displayNameOf,toEpoch,toConversation}from'../messaging/chatModel.js';import {SEND_MESSAGE_MUTATION,MESSAGES_QUERY,CHANNELS_QUERY}from'../messaging/chatOperations.js';import {NATIVE_CHAT_CHANNELS_QUERY_VARS,isNativeMessengerChannel}from'../messaging/nativeChatChannelQuery.js';import {useChatViewer}from'../messaging/useChatViewer.js';import {createCubeforgeFriends,waitForToken}from'./cubeforgeFriends.js';const FALLBACK_PLAYER_NAME = "Player";
2
2
  const INVITE_CHATS_SCANNED = 10;
3
3
  const INVITE_MESSAGES_SCANNED = 30;
4
+ function gamesTokenGetter(read) {
5
+ return async (forceNew) => {
6
+ const {
7
+ token: current,
8
+ renew: mint
9
+ } = read();
10
+ if (current && !forceNew) return current;
11
+ const minted = await mint();
12
+ if (minted || forceNew) return minted;
13
+ return waitForToken(() => read().token);
14
+ };
15
+ }
4
16
  function useCubeforgeFriends() {
5
17
  const client = useApolloClient();
6
18
  const {
@@ -34,16 +46,7 @@ function useCubeforgeFriends() {
34
46
  };
35
47
  return createCubeforgeFriends({
36
48
  graphqlUrl: config.GAMES_SUBGRAPH_URL,
37
- getToken: async (forceNew) => {
38
- const {
39
- token: current,
40
- renew: mint
41
- } = latest.current;
42
- if (current && !forceNew) return current;
43
- const minted = await mint();
44
- if (minted || forceNew) return minted;
45
- return waitForToken(() => latest.current.token);
46
- },
49
+ getToken: gamesTokenGetter(() => latest.current),
47
50
  playerName: () => {
48
51
  var _a, _b;
49
52
  return ((_b = (_a = latest.current.viewer) == null ? void 0 : _a.displayName) == null ? void 0 : _b.trim()) || FALLBACK_PLAYER_NAME;
@@ -111,4 +114,4 @@ function useCubeforgeFriends() {
111
114
  }
112
115
  });
113
116
  }, [client]);
114
- }export{useCubeforgeFriends};//# sourceMappingURL=useCubeforgeFriends.js.map
117
+ }export{gamesTokenGetter,useCubeforgeFriends};//# sourceMappingURL=useCubeforgeFriends.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useCubeforgeFriends.js","sources":["../../../src/features/games/useCubeforgeFriends.ts"],"sourcesContent":["/** Shared Cubeforge worlds and chat invites for the signed-in person. */\nimport { useMemo, useRef } from 'react';\nimport { gql, useApolloClient } from '@apollo/client';\nimport { config } from '../../config/env-config';\nimport { useCanvasSession } from '../canvas/useCanvasSession';\nimport {\n displayNameOf,\n pickAuthor,\n toConversation,\n toEpoch,\n type WireChannel,\n type WirePost,\n} from '../messaging/chatModel';\nimport { CHANNELS_QUERY, MESSAGES_QUERY, SEND_MESSAGE_MUTATION } from '../messaging/chatOperations';\nimport { isNativeMessengerChannel, NATIVE_CHAT_CHANNELS_QUERY_VARS } from '../messaging/nativeChatChannelQuery';\nimport { useChatViewer } from '../messaging/useChatViewer';\nimport { createCubeforgeFriends, waitForToken } from './cubeforgeFriends';\nimport type { CubeforgeFriends, InviteChat } from './vendored';\n\nconst FALLBACK_PLAYER_NAME = 'Player';\n/** How far back to look for invites: the most recent chats, and the latest messages in each. */\nconst INVITE_CHATS_SCANNED = 10;\nconst INVITE_MESSAGES_SCANNED = 30;\n\nexport function useCubeforgeFriends(): CubeforgeFriends {\n const client = useApolloClient();\n const { viewer } = useChatViewer();\n const { token, renew } = useCanvasSession();\n const latest = useRef({ viewer, token, renew });\n latest.current = { viewer, token, renew };\n\n return useMemo(() => {\n const loadChats = async (viewerId: string) => {\n const { data } = await client.query<{ channelsByUser?: (WireChannel | null)[] | null }>({\n query: gql(CHANNELS_QUERY),\n variables: NATIVE_CHAT_CHANNELS_QUERY_VARS,\n fetchPolicy: 'network-only',\n });\n return (data.channelsByUser ?? [])\n .filter((c): c is WireChannel => isNativeMessengerChannel(c))\n .map((c) => toConversation(c, viewerId));\n };\n\n return createCubeforgeFriends({\n graphqlUrl: config.GAMES_SUBGRAPH_URL,\n getToken: async (forceNew) => {\n const { token: current, renew: mint } = latest.current;\n if (current && !forceNew) return current;\n const minted = await mint();\n if (minted || forceNew) return minted;\n // Null is \"not yet\": the session mints by itself once the org and project load.\n return waitForToken(() => latest.current.token);\n },\n playerName: () => latest.current.viewer?.displayName?.trim() || FALLBACK_PLAYER_NAME,\n listChats: async (): Promise<InviteChat[]> => {\n const viewerId = latest.current.viewer?.userId;\n if (!viewerId) return [];\n return (await loadChats(viewerId)).map((c) => ({\n id: c.id,\n title: c.title,\n detail: c.isDirect ? 'Person' : `Group, ${c.members.length} members`,\n }));\n },\n recentChatMessages: async () => {\n // Games can open before the person's profile has loaded.\n const viewerId = await waitForToken(() => latest.current.viewer?.userId ?? null);\n if (!viewerId) return [];\n const chats = (await loadChats(viewerId)).slice(0, INVITE_CHATS_SCANNED);\n const pages = await Promise.all(\n chats.map(async (chat) => {\n try {\n const { data } = await client.query<{\n messages?: { data?: (WirePost | null)[] | null } | null;\n }>({\n query: gql(MESSAGES_QUERY),\n variables: { channelId: chat.id, limit: INVITE_MESSAGES_SCANNED, skip: 0 },\n // Reading for invites must not disturb the chat screen's own copy.\n fetchPolicy: 'no-cache',\n });\n return (data.messages?.data ?? [])\n .filter((post): post is WirePost => Boolean(post) && !post?.deletedAt)\n .map((post) => {\n const author = pickAuthor(post);\n const mine = Boolean(author?.id) && String(author?.id) === viewerId;\n // A person's own chat already carries the name this player knows them by.\n const sender = chat.isDirect ? chat.title : displayNameOf(author);\n return {\n body: post.message ?? '',\n from: mine ? null : sender,\n chatTitle: chat.title,\n sentAt: toEpoch(post.createdAt),\n };\n });\n } catch {\n return [];\n }\n }),\n );\n return pages.flat();\n },\n sendToChat: async (chatId, text) => {\n await client.mutate({\n mutation: gql(SEND_MESSAGE_MUTATION),\n variables: { channelId: chatId, messageInput: { content: text } },\n });\n },\n });\n }, [client]);\n}\n"],"names":["_a"],"mappings":"mnBAWA,MAAM,oBAAuB,GAAA,QAAA;AAE7B,MAAM,oBAAuB,GAAA,EAAA;AAC7B,MAAM,uBAA0B,GAAA,EAAA;AACzB,SAAS,mBAAwC,GAAA;AACtD,EAAA,MAAM,SAAS,eAAgB,EAAA;AAC/B,EAAM,MAAA;AAAA,IACJ;AAAA,MACE,aAAc,EAAA;AAClB,EAAM,MAAA;AAAA,IACJ,KAAA;AAAA,IACA;AAAA,MACE,gBAAiB,EAAA;AACrB,EAAA,MAAM,SAAS,MAAO,CAAA;AAAA,IACpB,MAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACD,CAAA;AACD,EAAA,MAAA,CAAO,OAAU,GAAA;AAAA,IACf,MAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACF;AACA,EAAA,OAAO,QAAQ,MAAM;AACnB,IAAM,MAAA,SAAA,GAAY,OAAO,QAAqB,KAAA;AAnClD,MAAA,IAAA,EAAA;AAoCM,MAAM,MAAA;AAAA,QACJ;AAAA,OACF,GAAI,MAAM,MAAA,CAAO,KAEd,CAAA;AAAA,QACD,KAAA,EAAO,IAAI,cAAc,CAAA;AAAA,QACzB,SAAW,EAAA,+BAAA;AAAA,QACX,WAAa,EAAA;AAAA,OACd,CAAA;AACD,MAAA,OAAA,CAAA,CAAQ,UAAK,cAAL,KAA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
1
+ {"version":3,"file":"useCubeforgeFriends.js","sources":["../../../src/features/games/useCubeforgeFriends.ts"],"sourcesContent":["/** Shared Cubeforge worlds and chat invites for the signed-in person. */\nimport { useMemo, useRef } from 'react';\nimport { gql, useApolloClient } from '@apollo/client';\nimport { config } from '../../config/env-config';\nimport { useCanvasSession } from '../canvas/useCanvasSession';\nimport {\n displayNameOf,\n pickAuthor,\n toConversation,\n toEpoch,\n type WireChannel,\n type WirePost,\n} from '../messaging/chatModel';\nimport { CHANNELS_QUERY, MESSAGES_QUERY, SEND_MESSAGE_MUTATION } from '../messaging/chatOperations';\nimport { isNativeMessengerChannel, NATIVE_CHAT_CHANNELS_QUERY_VARS } from '../messaging/nativeChatChannelQuery';\nimport { useChatViewer } from '../messaging/useChatViewer';\nimport { createCubeforgeFriends, waitForToken } from './cubeforgeFriends';\nimport type { CubeforgeFriends, InviteChat } from './vendored';\n\nconst FALLBACK_PLAYER_NAME = 'Player';\n/** How far back to look for invites: the most recent chats, and the latest messages in each. */\nconst INVITE_CHATS_SCANNED = 10;\nconst INVITE_MESSAGES_SCANNED = 30;\n\n/**\n * The bearer for the games subgraph: the canvas session's token, a fresh one\n * when asked, and a short wait while the session is still minting its first.\n */\nexport function gamesTokenGetter(\n read: () => { token: string | null; renew: () => Promise<string | null> },\n): (forceNew: boolean) => Promise<string | null> {\n return async (forceNew) => {\n const { token: current, renew: mint } = read();\n if (current && !forceNew) return current;\n const minted = await mint();\n if (minted || forceNew) return minted;\n // Null is \"not yet\": the session mints by itself once the org and project load.\n return waitForToken(() => read().token);\n };\n}\n\nexport function useCubeforgeFriends(): CubeforgeFriends {\n const client = useApolloClient();\n const { viewer } = useChatViewer();\n const { token, renew } = useCanvasSession();\n const latest = useRef({ viewer, token, renew });\n latest.current = { viewer, token, renew };\n\n return useMemo(() => {\n const loadChats = async (viewerId: string) => {\n const { data } = await client.query<{ channelsByUser?: (WireChannel | null)[] | null }>({\n query: gql(CHANNELS_QUERY),\n variables: NATIVE_CHAT_CHANNELS_QUERY_VARS,\n fetchPolicy: 'network-only',\n });\n return (data.channelsByUser ?? [])\n .filter((c): c is WireChannel => isNativeMessengerChannel(c))\n .map((c) => toConversation(c, viewerId));\n };\n\n return createCubeforgeFriends({\n graphqlUrl: config.GAMES_SUBGRAPH_URL,\n getToken: gamesTokenGetter(() => latest.current),\n playerName: () => latest.current.viewer?.displayName?.trim() || FALLBACK_PLAYER_NAME,\n listChats: async (): Promise<InviteChat[]> => {\n const viewerId = latest.current.viewer?.userId;\n if (!viewerId) return [];\n return (await loadChats(viewerId)).map((c) => ({\n id: c.id,\n title: c.title,\n detail: c.isDirect ? 'Person' : `Group, ${c.members.length} members`,\n }));\n },\n recentChatMessages: async () => {\n // Games can open before the person's profile has loaded.\n const viewerId = await waitForToken(() => latest.current.viewer?.userId ?? null);\n if (!viewerId) return [];\n const chats = (await loadChats(viewerId)).slice(0, INVITE_CHATS_SCANNED);\n const pages = await Promise.all(\n chats.map(async (chat) => {\n try {\n const { data } = await client.query<{\n messages?: { data?: (WirePost | null)[] | null } | null;\n }>({\n query: gql(MESSAGES_QUERY),\n variables: { channelId: chat.id, limit: INVITE_MESSAGES_SCANNED, skip: 0 },\n // Reading for invites must not disturb the chat screen's own copy.\n fetchPolicy: 'no-cache',\n });\n return (data.messages?.data ?? [])\n .filter((post): post is WirePost => Boolean(post) && !post?.deletedAt)\n .map((post) => {\n const author = pickAuthor(post);\n const mine = Boolean(author?.id) && String(author?.id) === viewerId;\n // A person's own chat already carries the name this player knows them by.\n const sender = chat.isDirect ? chat.title : displayNameOf(author);\n return {\n body: post.message ?? '',\n from: mine ? null : sender,\n chatTitle: chat.title,\n sentAt: toEpoch(post.createdAt),\n };\n });\n } catch {\n return [];\n }\n }),\n );\n return pages.flat();\n },\n sendToChat: async (chatId, text) => {\n await client.mutate({\n mutation: gql(SEND_MESSAGE_MUTATION),\n variables: { channelId: chatId, messageInput: { content: text } },\n });\n },\n });\n }, [client]);\n}\n"],"names":["_a"],"mappings":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IAAA,GAAA,KAAA,CAAA,GAAA,MAAA,CAAQ,EAAE,CAAM,KAAA,QAAA;AAE3D,cAAA,MAAM,SAAS,IAAK,CAAA,QAAA,GAAW,IAAK,CAAA,KAAA,GAAQ,cAAc,MAAM,CAAA;AAChE,cAAO,OAAA;AAAA,gBACL,IAAMA,EAAAA,CAAAA,GAAAA,GAAA,IAAK,CAAA,OAAA,KAAL,OAAAA,GAAgB,GAAA,EAAA;AAAA,gBACtB,IAAA,EAAM,OAAO,IAAO,GAAA,MAAA;AAAA,gBACpB,WAAW,IAAK,CAAA,KAAA;AAAA,gBAChB,MAAA,EAAQ,OAAQ,CAAA,IAAA,CAAK,SAAS;AAAA,eAChC;AAAA,aACD,CAAA;AAAA,WACK,CAAA,OAAA,CAAA,EAAA;AACN,YAAA,OAAO,EAAC;AAAA;AACV,SACD,CAAC,CAAA;AACF,QAAA,OAAO,MAAM,IAAK,EAAA;AAAA,OACpB;AAAA,MACA,UAAA,EAAY,OAAO,MAAA,EAAQ,IAAS,KAAA;AAClC,QAAA,MAAM,OAAO,MAAO,CAAA;AAAA,UAClB,QAAA,EAAU,IAAI,qBAAqB,CAAA;AAAA,UACnC,SAAW,EAAA;AAAA,YACT,SAAW,EAAA,MAAA;AAAA,YACX,YAAc,EAAA;AAAA,cACZ,OAAS,EAAA;AAAA;AACX;AACF,SACD,CAAA;AAAA;AACH,KACD,CAAA;AAAA,GACH,EAAG,CAAC,MAAM,CAAC,CAAA;AACb"}
@@ -0,0 +1,110 @@
1
+ import {useRef,useMemo,useState,useEffect,useCallback}from'react';import {Alert}from'react-native';import {useApolloClient,gql}from'@apollo/client/index.js';import AsyncStorage from'@react-native-async-storage/async-storage';import {config}from'../../config/env-config.js';import {offerCredits}from'../canvas/creditsOffer.js';import {useCanvasSession}from'../canvas/useCanvasSession.js';import {useChatViewer}from'../messaging/useChatViewer.js';import {createGamesRequest}from'./cubeforgeFriends.js';import {createCubeforgeLooks,unlockLookFlow}from'./cubeforgeLooks.js';import {gamesTokenGetter}from'./useCubeforgeFriends.js';const NONE = /* @__PURE__ */ new Set();
2
+ const BALANCE_WAIT_MS = 4e3;
3
+ const CREDITS_BALANCE = gql`
4
+ query CubeforgeCreditsBalance {
5
+ checkLLMSpend {
6
+ availableUsd
7
+ }
8
+ creditRate {
9
+ creditsPerUsd
10
+ }
11
+ }
12
+ `;
13
+ async function readBalance(client, orgName) {
14
+ if (!orgName) return null;
15
+ const read = client.query({
16
+ query: CREDITS_BALANCE,
17
+ context: {
18
+ headers: {
19
+ orgname: orgName
20
+ }
21
+ },
22
+ fetchPolicy: "network-only"
23
+ }).then(({
24
+ data
25
+ }) => {
26
+ var _a, _b;
27
+ const usd = (_a = data.checkLLMSpend) == null ? void 0 : _a.availableUsd;
28
+ const rate = (_b = data.creditRate) == null ? void 0 : _b.creditsPerUsd;
29
+ return typeof usd === "number" && typeof rate === "number" && rate > 0 ? usd * rate : null;
30
+ }).catch(() => null);
31
+ const late = new Promise((resolve) => {
32
+ setTimeout(() => resolve(null), BALANCE_WAIT_MS);
33
+ });
34
+ return Promise.race([read, late]);
35
+ }
36
+ const confirmSpend = (title, message, spend) => new Promise((resolve) => {
37
+ Alert.alert(title, message, [{
38
+ text: "Cancel",
39
+ style: "cancel",
40
+ onPress: () => resolve(false)
41
+ }, {
42
+ text: spend,
43
+ onPress: () => resolve(true)
44
+ }], {
45
+ cancelable: true,
46
+ onDismiss: () => resolve(false)
47
+ });
48
+ });
49
+ function useCubeforgeLooks(orgName) {
50
+ var _a;
51
+ const client = useApolloClient();
52
+ const {
53
+ viewer
54
+ } = useChatViewer();
55
+ const {
56
+ token,
57
+ renew
58
+ } = useCanvasSession();
59
+ const latest = useRef({
60
+ token,
61
+ renew
62
+ });
63
+ latest.current = {
64
+ token,
65
+ renew
66
+ };
67
+ const playerKey = (_a = viewer == null ? void 0 : viewer.userId) != null ? _a : "";
68
+ const looks = useMemo(() => createCubeforgeLooks({
69
+ request: createGamesRequest({
70
+ graphqlUrl: config.GAMES_SUBGRAPH_URL,
71
+ getToken: gamesTokenGetter(() => latest.current)
72
+ }),
73
+ storage: AsyncStorage,
74
+ playerKey
75
+ }), [playerKey]);
76
+ const [owned, setOwned] = useState(NONE);
77
+ useEffect(() => {
78
+ let live = true;
79
+ void looks.cached().then((ids) => {
80
+ if (live && ids.length) setOwned(new Set(ids));
81
+ });
82
+ looks.refresh().then((ids) => {
83
+ if (live) setOwned(new Set(ids));
84
+ }).catch(() => void 0);
85
+ return () => {
86
+ live = false;
87
+ };
88
+ }, [looks]);
89
+ const onUnlockLook = useCallback(async (look) => {
90
+ const ok = await unlockLookFlow(look, looks, {
91
+ confirm: confirmSpend,
92
+ balance: () => readBalance(client, orgName),
93
+ offerCredits: (message) => offerCredits(message, ""),
94
+ tell: (title, message) => Alert.alert(title, message)
95
+ });
96
+ if (ok) {
97
+ setOwned((prev) => {
98
+ const next = new Set(prev);
99
+ next.add(look.id);
100
+ void looks.remember([...next]);
101
+ return next;
102
+ });
103
+ }
104
+ return ok;
105
+ }, [client, looks, orgName]);
106
+ return {
107
+ ownedLooks: owned,
108
+ onUnlockLook
109
+ };
110
+ }export{useCubeforgeLooks};//# sourceMappingURL=useCubeforgeLooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCubeforgeLooks.js","sources":["../../../src/features/games/useCubeforgeLooks.ts"],"sourcesContent":["/** The signed-in player's rare and legendary looks, and buying one, for the avatar screen. */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Alert } from 'react-native';\nimport { gql, useApolloClient, type ApolloClient } from '@apollo/client';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport { config } from '../../config/env-config';\nimport { offerCredits } from '../canvas/creditsOffer';\nimport { useCanvasSession } from '../canvas/useCanvasSession';\nimport { useChatViewer } from '../messaging/useChatViewer';\nimport { createGamesRequest } from './cubeforgeFriends';\nimport { createCubeforgeLooks, unlockLookFlow } from './cubeforgeLooks';\nimport { gamesTokenGetter } from './useCubeforgeFriends';\nimport type { Look } from './vendored';\n\nconst NONE: ReadonlySet<string> = new Set();\nconst BALANCE_WAIT_MS = 4000;\n\nconst CREDITS_BALANCE = gql`\n query CubeforgeCreditsBalance {\n checkLLMSpend {\n availableUsd\n }\n creditRate {\n creditsPerUsd\n }\n }\n`;\n\n/** Credits the organisation can spend now, or null when they could not be read in time. */\nasync function readBalance(client: ApolloClient<unknown>, orgName: string): Promise<number | null> {\n if (!orgName) return null;\n const read = client\n .query<{\n checkLLMSpend?: { availableUsd?: number | null } | null;\n creditRate?: { creditsPerUsd?: number | null };\n }>({\n query: CREDITS_BALANCE,\n context: { headers: { orgname: orgName } },\n fetchPolicy: 'network-only',\n })\n .then(({ data }) => {\n const usd = data.checkLLMSpend?.availableUsd;\n const rate = data.creditRate?.creditsPerUsd;\n return typeof usd === 'number' && typeof rate === 'number' && rate > 0 ? usd * rate : null;\n })\n .catch(() => null);\n const late = new Promise<null>((resolve) => {\n setTimeout(() => resolve(null), BALANCE_WAIT_MS);\n });\n return Promise.race([read, late]);\n}\n\nconst confirmSpend = (title: string, message: string, spend: string) =>\n new Promise<boolean>((resolve) => {\n Alert.alert(\n title,\n message,\n [\n { text: 'Cancel', style: 'cancel', onPress: () => resolve(false) },\n { text: spend, onPress: () => resolve(true) },\n ],\n { cancelable: true, onDismiss: () => resolve(false) },\n );\n });\n\nexport function useCubeforgeLooks(orgName: string): {\n ownedLooks: ReadonlySet<string>;\n onUnlockLook: (look: Look) => Promise<boolean>;\n} {\n const client = useApolloClient();\n const { viewer } = useChatViewer();\n const { token, renew } = useCanvasSession();\n const latest = useRef({ token, renew });\n latest.current = { token, renew };\n const playerKey = viewer?.userId ?? '';\n\n const looks = useMemo(\n () =>\n createCubeforgeLooks({\n request: createGamesRequest({\n graphqlUrl: config.GAMES_SUBGRAPH_URL,\n getToken: gamesTokenGetter(() => latest.current),\n }),\n storage: AsyncStorage,\n playerKey,\n }),\n [playerKey],\n );\n const [owned, setOwned] = useState<ReadonlySet<string>>(NONE);\n\n useEffect(() => {\n let live = true;\n void looks.cached().then((ids) => {\n if (live && ids.length) setOwned(new Set(ids));\n });\n looks\n .refresh()\n .then((ids) => {\n if (live) setOwned(new Set(ids));\n })\n .catch(() => undefined);\n return () => {\n live = false;\n };\n }, [looks]);\n\n const onUnlockLook = useCallback(\n async (look: Look): Promise<boolean> => {\n const ok = await unlockLookFlow(look, looks, {\n confirm: confirmSpend,\n balance: () => readBalance(client, orgName),\n offerCredits: (message) => offerCredits(message, ''),\n tell: (title, message) => Alert.alert(title, message),\n });\n if (ok) {\n setOwned((prev) => {\n const next = new Set(prev);\n next.add(look.id);\n void looks.remember([...next]);\n return next;\n });\n }\n return ok;\n },\n [client, looks, orgName],\n );\n\n return { ownedLooks: owned, onUnlockLook };\n}\n"],"names":[],"mappings":"knBAaA,MAAM,IAAA,uBAAgC,GAAI,EAAA;AAC1C,MAAM,eAAkB,GAAA,GAAA;AACxB,MAAM,eAAkB,GAAA,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAYxB,eAAe,WAAA,CAAY,QAA+B,OAAyC,EAAA;AACjG,EAAI,IAAA,CAAC,SAAgB,OAAA,IAAA;AACrB,EAAM,MAAA,IAAA,GAAO,OAAO,KAOjB,CAAA;AAAA,IACD,KAAO,EAAA,eAAA;AAAA,IACP,OAAS,EAAA;AAAA,MACP,OAAS,EAAA;AAAA,QACP,OAAS,EAAA;AAAA;AACX,KACF;AAAA,IACA,WAAa,EAAA;AAAA,GACd,CAAE,CAAA,IAAA,CAAK,CAAC;AAAA,IACP;AAAA,GACI,KAAA;AA9CR,IAAA,IAAA,EAAA,EAAA,EAAA;AA+CI,IAAM,MAAA,GAAA,GAAA,CAAM,EAAK,GAAA,IAAA,CAAA,aAAA,KAAL,IAAoB,GAAA,MAAA,GAAA,EAAA,CAAA,YAAA;AAChC,IAAM,MAAA,IAAA,GAAA,CAAO,EAAK,GAAA,IAAA,CAAA,UAAA,KAAL,IAAiB,GA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