@playcademy/sandbox 0.3.17-beta.4 → 0.3.17-beta.6

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.
Files changed (3) hide show
  1. package/dist/cli.js +478 -391
  2. package/dist/server.js +478 -391
  3. package/package.json +1 -1
package/dist/server.js CHANGED
@@ -1309,7 +1309,7 @@ var package_default;
1309
1309
  var init_package = __esm(() => {
1310
1310
  package_default = {
1311
1311
  name: "@playcademy/sandbox",
1312
- version: "0.3.17-beta.4",
1312
+ version: "0.3.17-beta.6",
1313
1313
  description: "Local development server for Playcademy game development",
1314
1314
  type: "module",
1315
1315
  exports: {
@@ -26646,447 +26646,533 @@ var init_developer_service = __esm(() => {
26646
26646
  logger4 = log.scope("DeveloperService");
26647
26647
  });
26648
26648
 
26649
- // ../api-core/src/services/game.service.ts
26650
- class GameService {
26651
- deps;
26652
- static MANIFEST_FETCH_TIMEOUT_MS = 5000;
26653
- static MAX_FETCH_ERROR_MESSAGE_LENGTH = 512;
26654
- constructor(deps) {
26655
- this.deps = deps;
26656
- }
26657
- static getManifestHost(manifestUrl) {
26658
- try {
26659
- return new URL(manifestUrl).host;
26660
- } catch {
26661
- return manifestUrl;
26662
- }
26649
+ // ../utils/src/fns.ts
26650
+ function sleep(ms) {
26651
+ if (ms <= 0) {
26652
+ return Promise.resolve();
26663
26653
  }
26664
- static getFetchErrorMessage(error) {
26665
- let raw;
26666
- if (error instanceof Error) {
26667
- raw = error.message;
26668
- } else if (typeof error === "string") {
26669
- raw = error;
26670
- }
26671
- if (!raw) {
26672
- return;
26654
+ return new Promise((resolve) => setTimeout(resolve, ms));
26655
+ }
26656
+
26657
+ // ../api-core/src/services/game.service.ts
26658
+ var logger5, inFlightManifestFetches, GameService;
26659
+ var init_game_service = __esm(() => {
26660
+ init_drizzle_orm();
26661
+ init_tables_index();
26662
+ init_src2();
26663
+ init_errors();
26664
+ init_deployment_util();
26665
+ logger5 = log.scope("GameService");
26666
+ inFlightManifestFetches = new Map;
26667
+ GameService = class GameService {
26668
+ deps;
26669
+ static MANIFEST_FETCH_ATTEMPT_TIMEOUT_MS = 1e4;
26670
+ static MANIFEST_FETCH_MAX_RETRIES = 2;
26671
+ static MANIFEST_FETCH_RETRY_BACKOFF_MS = [250, 750];
26672
+ static MANIFEST_CACHE_TTL_SECONDS = 60;
26673
+ static MANIFEST_CACHE_KEY_PREFIX = "game:manifest";
26674
+ static MAX_FETCH_ERROR_MESSAGE_LENGTH = 512;
26675
+ constructor(deps) {
26676
+ this.deps = deps;
26677
+ }
26678
+ static getManifestHost(manifestUrl) {
26679
+ try {
26680
+ return new URL(manifestUrl).host;
26681
+ } catch {
26682
+ return manifestUrl;
26683
+ }
26673
26684
  }
26674
- const normalized = raw.replace(/\s+/g, " ").trim();
26675
- if (!normalized) {
26676
- return;
26685
+ static getFetchErrorMessage(error) {
26686
+ let raw;
26687
+ if (error instanceof Error) {
26688
+ raw = error.message;
26689
+ } else if (typeof error === "string") {
26690
+ raw = error;
26691
+ }
26692
+ if (!raw) {
26693
+ return;
26694
+ }
26695
+ const normalized = raw.replace(/\s+/g, " ").trim();
26696
+ if (!normalized) {
26697
+ return;
26698
+ }
26699
+ return normalized.slice(0, GameService.MAX_FETCH_ERROR_MESSAGE_LENGTH);
26677
26700
  }
26678
- return normalized.slice(0, GameService.MAX_FETCH_ERROR_MESSAGE_LENGTH);
26679
- }
26680
- static isRetryableStatus(status) {
26681
- return status === 429 || status >= 500;
26682
- }
26683
- async list(caller) {
26684
- const db2 = this.deps.db;
26685
- const isAdmin = caller?.role === "admin";
26686
- const isDeveloper = caller?.role === "developer";
26687
- let whereClause;
26688
- if (isAdmin) {
26689
- whereClause = undefined;
26690
- } else if (isDeveloper && caller?.id) {
26691
- whereClause = or(ne(games.visibility, "internal"), eq(games.developerId, caller.id));
26692
- } else {
26693
- whereClause = ne(games.visibility, "internal");
26701
+ static isRetryableStatus(status) {
26702
+ return status === 429 || status >= 500;
26694
26703
  }
26695
- return db2.query.games.findMany({
26696
- where: whereClause,
26697
- orderBy: [desc(games.createdAt)]
26698
- });
26699
- }
26700
- async listManageable(user) {
26701
- this.validateDeveloperStatus(user);
26702
- const db2 = this.deps.db;
26703
- return db2.query.games.findMany({
26704
- where: user.role === "admin" ? undefined : eq(games.developerId, user.id),
26705
- orderBy: [desc(games.createdAt)]
26706
- });
26707
- }
26708
- async getSubjects() {
26709
- const db2 = this.deps.db;
26710
- const integrations = await db2.query.gameTimebackIntegrations.findMany({
26711
- columns: { gameId: true, subject: true },
26712
- orderBy: [asc(gameTimebackIntegrations.createdAt)]
26713
- });
26714
- const subjectMap = {};
26715
- for (const integration of integrations) {
26716
- if (!(integration.gameId in subjectMap)) {
26717
- subjectMap[integration.gameId] = integration.subject;
26704
+ static getRetryBackoffMs(attemptIndex) {
26705
+ const backoff = GameService.MANIFEST_FETCH_RETRY_BACKOFF_MS;
26706
+ if (backoff.length === 0) {
26707
+ return 0;
26718
26708
  }
26709
+ return backoff[Math.min(attemptIndex, backoff.length - 1)] ?? 0;
26719
26710
  }
26720
- return subjectMap;
26721
- }
26722
- async getById(gameId, caller) {
26723
- const db2 = this.deps.db;
26724
- const game = await db2.query.games.findFirst({
26725
- where: eq(games.id, gameId)
26726
- });
26727
- if (!game) {
26728
- throw new NotFoundError("Game", gameId);
26711
+ static normalizeDeploymentUrl(deploymentUrl) {
26712
+ return deploymentUrl.replace(/\/$/, "");
26729
26713
  }
26730
- this.enforceVisibility(game, caller, gameId);
26731
- return game;
26732
- }
26733
- async getBySlug(slug, caller) {
26734
- const db2 = this.deps.db;
26735
- const game = await db2.query.games.findFirst({
26736
- where: eq(games.slug, slug)
26737
- });
26738
- if (!game) {
26739
- throw new NotFoundError("Game", slug);
26740
- }
26741
- this.enforceVisibility(game, caller, slug);
26742
- return game;
26743
- }
26744
- async getManifest(gameId, caller) {
26745
- const game = await this.getById(gameId, caller);
26746
- if (game.gameType !== "hosted" || !game.deploymentUrl) {
26747
- throw new BadRequestError("Game does not have a deployment manifest");
26714
+ static getManifestCacheKey(deploymentUrl) {
26715
+ return `${GameService.MANIFEST_CACHE_KEY_PREFIX}:${deploymentUrl}`;
26748
26716
  }
26749
- const deploymentUrl = game.deploymentUrl;
26750
- const manifestUrl = `${deploymentUrl.replace(/\/$/, "")}/playcademy.manifest.json`;
26751
- const manifestHost = GameService.getManifestHost(manifestUrl);
26752
- const startedAt = Date.now();
26753
- const controller = new AbortController;
26754
- const timeout = setTimeout(() => controller.abort(), GameService.MANIFEST_FETCH_TIMEOUT_MS);
26755
- function buildDetails(fetchOutcome, manifestErrorKind, extra = {}) {
26756
- return {
26757
- manifestUrl,
26758
- manifestHost,
26759
- deploymentUrl,
26760
- fetchOutcome,
26761
- retryCount: 0,
26762
- durationMs: Date.now() - startedAt,
26763
- manifestErrorKind,
26764
- ...extra
26765
- };
26717
+ async list(caller) {
26718
+ const db2 = this.deps.db;
26719
+ const isAdmin = caller?.role === "admin";
26720
+ const isDeveloper = caller?.role === "developer";
26721
+ let whereClause;
26722
+ if (isAdmin) {
26723
+ whereClause = undefined;
26724
+ } else if (isDeveloper && caller?.id) {
26725
+ whereClause = or(ne(games.visibility, "internal"), eq(games.developerId, caller.id));
26726
+ } else {
26727
+ whereClause = ne(games.visibility, "internal");
26728
+ }
26729
+ return db2.query.games.findMany({
26730
+ where: whereClause,
26731
+ orderBy: [desc(games.createdAt)]
26732
+ });
26766
26733
  }
26767
- let response;
26768
- try {
26769
- response = await fetch(manifestUrl, {
26770
- method: "GET",
26771
- headers: {
26772
- Accept: "application/json"
26773
- },
26774
- signal: controller.signal
26734
+ async listManageable(user) {
26735
+ this.validateDeveloperStatus(user);
26736
+ const db2 = this.deps.db;
26737
+ return db2.query.games.findMany({
26738
+ where: user.role === "admin" ? undefined : eq(games.developerId, user.id),
26739
+ orderBy: [desc(games.createdAt)]
26775
26740
  });
26776
- } catch (error) {
26777
- clearTimeout(timeout);
26778
- const fetchErrorMessage = GameService.getFetchErrorMessage(error);
26779
- const details = buildDetails("network_error", "temporary", fetchErrorMessage ? { fetchErrorMessage } : {});
26780
- logger5.error("Failed to fetch game manifest", {
26781
- gameId,
26782
- manifestUrl,
26783
- error,
26784
- details
26741
+ }
26742
+ async getSubjects() {
26743
+ const db2 = this.deps.db;
26744
+ const integrations = await db2.query.gameTimebackIntegrations.findMany({
26745
+ columns: { gameId: true, subject: true },
26746
+ orderBy: [asc(gameTimebackIntegrations.createdAt)]
26785
26747
  });
26786
- if (error instanceof Error && error.name === "AbortError") {
26787
- throw new TimeoutError("Timed out loading game manifest", details);
26748
+ const subjectMap = {};
26749
+ for (const integration of integrations) {
26750
+ if (!(integration.gameId in subjectMap)) {
26751
+ subjectMap[integration.gameId] = integration.subject;
26752
+ }
26788
26753
  }
26789
- throw new ServiceUnavailableError("Failed to load game manifest", details);
26790
- } finally {
26791
- clearTimeout(timeout);
26754
+ return subjectMap;
26792
26755
  }
26793
- if (!response.ok) {
26794
- const resolvedManifestUrl = response.url || manifestUrl;
26795
- const resolvedManifestHost = GameService.getManifestHost(resolvedManifestUrl);
26796
- const manifestErrorKind = GameService.isRetryableStatus(response.status) ? "temporary" : "permanent";
26797
- const details = buildDetails("bad_status", manifestErrorKind, {
26798
- manifestUrl: resolvedManifestUrl,
26799
- manifestHost: resolvedManifestHost,
26800
- status: response.status,
26801
- contentType: response.headers.get("content-type") ?? undefined,
26802
- cfRay: response.headers.get("cf-ray") ?? undefined,
26803
- redirected: response.redirected,
26804
- ...response.redirected ? {
26805
- originalManifestUrl: manifestUrl,
26806
- originalManifestHost: manifestHost
26807
- } : {}
26808
- });
26809
- const message = `Failed to fetch manifest: ${response.status} ${response.statusText}`;
26810
- logger5.error("Game manifest returned non-ok response", {
26811
- gameId,
26812
- manifestUrl,
26813
- status: response.status,
26814
- details
26756
+ async getById(gameId, caller) {
26757
+ const db2 = this.deps.db;
26758
+ const game = await db2.query.games.findFirst({
26759
+ where: eq(games.id, gameId)
26815
26760
  });
26816
- if (manifestErrorKind === "temporary") {
26817
- throw new ServiceUnavailableError(message, details);
26761
+ if (!game) {
26762
+ throw new NotFoundError("Game", gameId);
26818
26763
  }
26819
- throw new BadRequestError(message, details);
26764
+ this.enforceVisibility(game, caller, gameId);
26765
+ return game;
26820
26766
  }
26821
- try {
26822
- return await response.json();
26823
- } catch (error) {
26824
- const resolvedManifestUrl = response.url || manifestUrl;
26825
- const resolvedManifestHost = GameService.getManifestHost(resolvedManifestUrl);
26826
- const details = buildDetails("invalid_body", "permanent", {
26827
- manifestUrl: resolvedManifestUrl,
26828
- manifestHost: resolvedManifestHost,
26829
- status: response.status,
26830
- contentType: response.headers.get("content-type") ?? undefined,
26831
- cfRay: response.headers.get("cf-ray") ?? undefined,
26832
- redirected: response.redirected,
26833
- ...response.redirected ? {
26834
- originalManifestUrl: manifestUrl,
26835
- originalManifestHost: manifestHost
26836
- } : {}
26837
- });
26838
- logger5.error("Failed to parse game manifest", {
26839
- gameId,
26840
- manifestUrl,
26841
- error,
26842
- details
26767
+ async getBySlug(slug, caller) {
26768
+ const db2 = this.deps.db;
26769
+ const game = await db2.query.games.findFirst({
26770
+ where: eq(games.slug, slug)
26843
26771
  });
26844
- throw new BadRequestError("Failed to parse game manifest", details);
26845
- }
26846
- }
26847
- enforceVisibility(game, caller, lookupIdentifier) {
26848
- if (game.visibility !== "internal") {
26849
- return;
26850
- }
26851
- const isAdmin = caller?.role === "admin";
26852
- const isOwner = caller?.id != null && caller.id === game.developerId;
26853
- if (!isAdmin && !isOwner) {
26854
- throw new NotFoundError("Game", lookupIdentifier);
26855
- }
26856
- }
26857
- async upsertBySlug(slug, data, user) {
26858
- const db2 = this.deps.db;
26859
- const existingGame = await db2.query.games.findFirst({
26860
- where: eq(games.slug, slug)
26861
- });
26862
- const isUpdate = Boolean(existingGame);
26863
- const gameId = existingGame?.id ?? crypto.randomUUID();
26864
- if (isUpdate) {
26865
- await this.validateDeveloperAccess(user, gameId);
26866
- } else {
26867
- this.validateDeveloperStatus(user);
26868
- }
26869
- const gameDataForDb = {
26870
- displayName: data.displayName,
26871
- platform: data.platform,
26872
- metadata: data.metadata,
26873
- mapElementId: data.mapElementId,
26874
- gameType: data.gameType,
26875
- ...data.visibility && { visibility: data.visibility },
26876
- externalUrl: data.externalUrl || null,
26877
- updatedAt: new Date
26878
- };
26879
- let gameResponse;
26880
- if (isUpdate) {
26881
- const [updatedGame] = await db2.update(games).set(gameDataForDb).where(eq(games.id, gameId)).returning();
26882
- if (!updatedGame) {
26883
- logger5.error("Game update returned no rows", { gameId, slug });
26884
- throw new InternalError("DB update failed to return result for existing game");
26885
- }
26886
- gameResponse = updatedGame;
26887
- } else {
26888
- const insertData = {
26889
- ...gameDataForDb,
26890
- id: gameId,
26891
- slug,
26892
- developerId: user.id,
26893
- metadata: data.metadata || {},
26894
- version: data.gameType === "external" ? "external" : "",
26895
- deploymentUrl: null,
26896
- createdAt: new Date
26897
- };
26898
- const [createdGame] = await db2.insert(games).values(insertData).returning();
26899
- if (!createdGame) {
26900
- logger5.error("Game insert returned no rows", { slug, developerId: user.id });
26901
- throw new InternalError("DB insert failed to return result for new game");
26772
+ if (!game) {
26773
+ throw new NotFoundError("Game", slug);
26902
26774
  }
26903
- gameResponse = createdGame;
26775
+ this.enforceVisibility(game, caller, slug);
26776
+ return game;
26904
26777
  }
26905
- if (data.mapElementId) {
26906
- try {
26907
- await db2.update(mapElements).set({
26908
- interactionType: "game_entry",
26909
- gameId: gameResponse.id
26910
- }).where(eq(mapElements.id, data.mapElementId));
26911
- } catch (mapError) {
26912
- logger5.warn("Failed to update map element", {
26913
- mapElementId: data.mapElementId,
26914
- error: mapError
26778
+ async getManifest(gameId, caller) {
26779
+ const game = await this.getById(gameId, caller);
26780
+ if (game.gameType !== "hosted" || !game.deploymentUrl) {
26781
+ throw new BadRequestError("Game does not have a deployment manifest");
26782
+ }
26783
+ const deploymentUrl = GameService.normalizeDeploymentUrl(game.deploymentUrl);
26784
+ const cacheKey2 = GameService.getManifestCacheKey(deploymentUrl);
26785
+ const cached = await this.deps.cache.get(cacheKey2);
26786
+ if (cached) {
26787
+ return cached;
26788
+ }
26789
+ const inFlight = inFlightManifestFetches.get(deploymentUrl);
26790
+ if (inFlight) {
26791
+ return inFlight;
26792
+ }
26793
+ const promise = this.fetchManifestFromOrigin({ gameId, deploymentUrl }).then(async (manifest) => {
26794
+ try {
26795
+ await this.deps.cache.set(cacheKey2, manifest, GameService.MANIFEST_CACHE_TTL_SECONDS);
26796
+ } catch (cacheError) {
26797
+ logger5.warn("Failed to cache game manifest", {
26798
+ gameId,
26799
+ deploymentUrl,
26800
+ cacheKey: cacheKey2,
26801
+ error: cacheError
26802
+ });
26803
+ }
26804
+ return manifest;
26805
+ }).finally(() => {
26806
+ inFlightManifestFetches.delete(deploymentUrl);
26807
+ });
26808
+ inFlightManifestFetches.set(deploymentUrl, promise);
26809
+ return promise;
26810
+ }
26811
+ async fetchManifestFromOrigin(args2) {
26812
+ const { gameId, deploymentUrl } = args2;
26813
+ const manifestUrl = `${deploymentUrl}/playcademy.manifest.json`;
26814
+ const manifestHost = GameService.getManifestHost(manifestUrl);
26815
+ const startedAt = Date.now();
26816
+ const maxAttempts = GameService.MANIFEST_FETCH_MAX_RETRIES + 1;
26817
+ for (let attempt = 0;attempt < maxAttempts; attempt++) {
26818
+ const isLastAttempt = attempt === maxAttempts - 1;
26819
+ const outcome = await this.attemptManifestFetch({
26820
+ manifestUrl,
26821
+ manifestHost,
26822
+ deploymentUrl,
26823
+ startedAt,
26824
+ retryCount: attempt
26825
+ });
26826
+ if (outcome.kind === "success") {
26827
+ return outcome.manifest;
26828
+ }
26829
+ if (!outcome.retryable || isLastAttempt) {
26830
+ logger5.error("Failed to fetch game manifest", {
26831
+ gameId,
26832
+ manifestUrl,
26833
+ attempt: attempt + 1,
26834
+ maxAttempts,
26835
+ retryable: outcome.retryable,
26836
+ details: outcome.details,
26837
+ throwable: outcome.throwable,
26838
+ cause: outcome.cause
26839
+ });
26840
+ throw outcome.throwable;
26841
+ }
26842
+ const backoffMs = GameService.getRetryBackoffMs(attempt);
26843
+ logger5.warn("Retrying game manifest fetch after transient failure", {
26844
+ gameId,
26845
+ manifestUrl,
26846
+ attempt: attempt + 1,
26847
+ maxAttempts,
26848
+ backoffMs,
26849
+ details: outcome.details,
26850
+ cause: outcome.cause
26915
26851
  });
26852
+ await sleep(backoffMs);
26916
26853
  }
26854
+ throw new InternalError("Exhausted manifest fetch retries without result");
26917
26855
  }
26918
- logger5.info("Upserted game", {
26919
- gameId: gameResponse.id,
26920
- slug: gameResponse.slug,
26921
- operation: isUpdate ? "update" : "create",
26922
- displayName: gameResponse.displayName
26923
- });
26924
- return gameResponse;
26925
- }
26926
- async delete(gameId, user) {
26927
- await this.validateDeveloperAccess(user, gameId);
26928
- const db2 = this.deps.db;
26929
- const gameToDelete = await db2.query.games.findFirst({
26930
- where: eq(games.id, gameId),
26931
- columns: { id: true, slug: true, displayName: true }
26932
- });
26933
- if (!gameToDelete?.slug) {
26934
- throw new NotFoundError("Game", gameId);
26935
- }
26936
- const activeDeployment = await db2.query.gameDeployments.findFirst({
26937
- where: and(eq(gameDeployments.gameId, gameId), eq(gameDeployments.isActive, true)),
26938
- columns: { deploymentId: true, provider: true, resources: true }
26939
- });
26940
- const customHostnames = await db2.select({
26941
- hostname: gameCustomHostnames.hostname,
26942
- cloudflareId: gameCustomHostnames.cloudflareId,
26943
- environment: gameCustomHostnames.environment
26944
- }).from(gameCustomHostnames).where(eq(gameCustomHostnames.gameId, gameId));
26945
- const result = await db2.delete(games).where(eq(games.id, gameId)).returning({ id: games.id });
26946
- if (result.length === 0) {
26947
- throw new NotFoundError("Game", gameId);
26948
- }
26949
- logger5.info("Deleted game", {
26950
- gameId: result[0].id,
26951
- slug: gameToDelete.slug,
26952
- hadActiveDeployment: Boolean(activeDeployment),
26953
- customDomainsCount: customHostnames.length
26954
- });
26955
- this.deps.alerts.notifyGameDeletion({
26956
- slug: gameToDelete.slug,
26957
- displayName: gameToDelete.displayName,
26958
- developer: { id: user.id, email: user.email }
26959
- }).catch((error) => {
26960
- logger5.warn("Failed to send deletion alert", { error });
26961
- });
26962
- if (activeDeployment?.provider === "cloudflare" && this.deps.cloudflare) {
26856
+ async attemptManifestFetch(args2) {
26857
+ const { manifestUrl, manifestHost, deploymentUrl, startedAt, retryCount } = args2;
26858
+ function buildDetails(fetchOutcome, manifestErrorKind, extra = {}) {
26859
+ return {
26860
+ manifestUrl,
26861
+ manifestHost,
26862
+ deploymentUrl,
26863
+ fetchOutcome,
26864
+ retryCount,
26865
+ durationMs: Date.now() - startedAt,
26866
+ manifestErrorKind,
26867
+ ...extra
26868
+ };
26869
+ }
26870
+ const controller = new AbortController;
26871
+ const timeout = setTimeout(() => controller.abort(), GameService.MANIFEST_FETCH_ATTEMPT_TIMEOUT_MS);
26872
+ let response;
26963
26873
  try {
26964
- await this.deps.cloudflare.delete(activeDeployment.deploymentId, {
26965
- deleteBindings: true,
26966
- resources: activeDeployment.resources ?? undefined,
26967
- customDomains: customHostnames.length > 0 ? customHostnames : undefined,
26968
- gameSlug: gameToDelete.slug
26969
- });
26970
- logger5.info("Cleaned up Cloudflare resources", {
26971
- gameId,
26972
- deploymentId: activeDeployment.deploymentId,
26973
- customDomainsDeleted: customHostnames.length
26874
+ response = await fetch(manifestUrl, {
26875
+ method: "GET",
26876
+ headers: {
26877
+ Accept: "application/json"
26878
+ },
26879
+ signal: controller.signal
26974
26880
  });
26975
- } catch (cfError) {
26976
- logger5.warn("Failed to cleanup Cloudflare resources", {
26977
- gameId,
26978
- deploymentId: activeDeployment.deploymentId,
26979
- error: cfError
26881
+ } catch (error) {
26882
+ const fetchErrorMessage = GameService.getFetchErrorMessage(error);
26883
+ const details = buildDetails("network_error", "temporary", fetchErrorMessage ? { fetchErrorMessage } : {});
26884
+ const throwable = error instanceof Error && error.name === "AbortError" ? new TimeoutError("Timed out loading game manifest", details) : new ServiceUnavailableError("Failed to load game manifest", details);
26885
+ return { kind: "failure", retryable: true, throwable, details, cause: error };
26886
+ } finally {
26887
+ clearTimeout(timeout);
26888
+ }
26889
+ if (!response.ok) {
26890
+ const resolvedManifestUrl = response.url || manifestUrl;
26891
+ const resolvedManifestHost = GameService.getManifestHost(resolvedManifestUrl);
26892
+ const manifestErrorKind = GameService.isRetryableStatus(response.status) ? "temporary" : "permanent";
26893
+ const details = buildDetails("bad_status", manifestErrorKind, {
26894
+ manifestUrl: resolvedManifestUrl,
26895
+ manifestHost: resolvedManifestHost,
26896
+ status: response.status,
26897
+ contentType: response.headers.get("content-type") ?? undefined,
26898
+ cfRay: response.headers.get("cf-ray") ?? undefined,
26899
+ redirected: response.redirected,
26900
+ ...response.redirected ? {
26901
+ originalManifestUrl: manifestUrl,
26902
+ originalManifestHost: manifestHost
26903
+ } : {}
26980
26904
  });
26905
+ const message = `Failed to fetch manifest: ${response.status} ${response.statusText}`;
26906
+ const throwable = manifestErrorKind === "temporary" ? new ServiceUnavailableError(message, details) : new BadRequestError(message, details);
26907
+ return {
26908
+ kind: "failure",
26909
+ retryable: manifestErrorKind === "temporary",
26910
+ throwable,
26911
+ details
26912
+ };
26981
26913
  }
26982
26914
  try {
26983
- const deletedKeyId = await this.deps.deleteApiKeyByName(getGameWorkerApiKeyName(gameToDelete.slug), user.id);
26984
- if (deletedKeyId) {
26985
- logger5.info("Cleaned up API key for deleted game", {
26986
- gameId,
26987
- slug: gameToDelete.slug,
26988
- keyId: deletedKeyId
26915
+ const manifest = await response.json();
26916
+ return { kind: "success", manifest };
26917
+ } catch (error) {
26918
+ const resolvedManifestUrl = response.url || manifestUrl;
26919
+ const resolvedManifestHost = GameService.getManifestHost(resolvedManifestUrl);
26920
+ const details = buildDetails("invalid_body", "permanent", {
26921
+ manifestUrl: resolvedManifestUrl,
26922
+ manifestHost: resolvedManifestHost,
26923
+ status: response.status,
26924
+ contentType: response.headers.get("content-type") ?? undefined,
26925
+ cfRay: response.headers.get("cf-ray") ?? undefined,
26926
+ redirected: response.redirected,
26927
+ ...response.redirected ? {
26928
+ originalManifestUrl: manifestUrl,
26929
+ originalManifestHost: manifestHost
26930
+ } : {}
26931
+ });
26932
+ return {
26933
+ kind: "failure",
26934
+ retryable: false,
26935
+ throwable: new BadRequestError("Failed to parse game manifest", details),
26936
+ details,
26937
+ cause: error
26938
+ };
26939
+ }
26940
+ }
26941
+ enforceVisibility(game, caller, lookupIdentifier) {
26942
+ if (game.visibility !== "internal") {
26943
+ return;
26944
+ }
26945
+ const isAdmin = caller?.role === "admin";
26946
+ const isOwner = caller?.id != null && caller.id === game.developerId;
26947
+ if (!isAdmin && !isOwner) {
26948
+ throw new NotFoundError("Game", lookupIdentifier);
26949
+ }
26950
+ }
26951
+ async upsertBySlug(slug, data, user) {
26952
+ const db2 = this.deps.db;
26953
+ const existingGame = await db2.query.games.findFirst({
26954
+ where: eq(games.slug, slug)
26955
+ });
26956
+ const isUpdate = Boolean(existingGame);
26957
+ const gameId = existingGame?.id ?? crypto.randomUUID();
26958
+ if (isUpdate) {
26959
+ await this.validateDeveloperAccess(user, gameId);
26960
+ } else {
26961
+ this.validateDeveloperStatus(user);
26962
+ }
26963
+ const gameDataForDb = {
26964
+ displayName: data.displayName,
26965
+ platform: data.platform,
26966
+ metadata: data.metadata,
26967
+ mapElementId: data.mapElementId,
26968
+ gameType: data.gameType,
26969
+ ...data.visibility && { visibility: data.visibility },
26970
+ externalUrl: data.externalUrl || null,
26971
+ updatedAt: new Date
26972
+ };
26973
+ let gameResponse;
26974
+ if (isUpdate) {
26975
+ const [updatedGame] = await db2.update(games).set(gameDataForDb).where(eq(games.id, gameId)).returning();
26976
+ if (!updatedGame) {
26977
+ logger5.error("Game update returned no rows", { gameId, slug });
26978
+ throw new InternalError("DB update failed to return result for existing game");
26979
+ }
26980
+ gameResponse = updatedGame;
26981
+ } else {
26982
+ const insertData = {
26983
+ ...gameDataForDb,
26984
+ id: gameId,
26985
+ slug,
26986
+ developerId: user.id,
26987
+ metadata: data.metadata || {},
26988
+ version: data.gameType === "external" ? "external" : "",
26989
+ deploymentUrl: null,
26990
+ createdAt: new Date
26991
+ };
26992
+ const [createdGame] = await db2.insert(games).values(insertData).returning();
26993
+ if (!createdGame) {
26994
+ logger5.error("Game insert returned no rows", { slug, developerId: user.id });
26995
+ throw new InternalError("DB insert failed to return result for new game");
26996
+ }
26997
+ gameResponse = createdGame;
26998
+ }
26999
+ if (data.mapElementId) {
27000
+ try {
27001
+ await db2.update(mapElements).set({
27002
+ interactionType: "game_entry",
27003
+ gameId: gameResponse.id
27004
+ }).where(eq(mapElements.id, data.mapElementId));
27005
+ } catch (mapError) {
27006
+ logger5.warn("Failed to update map element", {
27007
+ mapElementId: data.mapElementId,
27008
+ error: mapError
26989
27009
  });
26990
27010
  }
26991
- } catch (keyError) {
26992
- logger5.warn("Failed to cleanup API key", { gameId, error: keyError });
26993
27011
  }
27012
+ logger5.info("Upserted game", {
27013
+ gameId: gameResponse.id,
27014
+ slug: gameResponse.slug,
27015
+ operation: isUpdate ? "update" : "create",
27016
+ displayName: gameResponse.displayName
27017
+ });
27018
+ return gameResponse;
26994
27019
  }
26995
- return {
26996
- slug: gameToDelete.slug,
26997
- displayName: gameToDelete.displayName
26998
- };
26999
- }
27000
- async validateOwnership(user, gameId) {
27001
- if (user.role === "admin") {
27002
- const gameExists = await this.deps.db.query.games.findFirst({
27020
+ async delete(gameId, user) {
27021
+ await this.validateDeveloperAccess(user, gameId);
27022
+ const db2 = this.deps.db;
27023
+ const gameToDelete = await db2.query.games.findFirst({
27003
27024
  where: eq(games.id, gameId),
27004
- columns: { id: true }
27025
+ columns: { id: true, slug: true, displayName: true }
27005
27026
  });
27006
- if (!gameExists) {
27027
+ if (!gameToDelete?.slug) {
27007
27028
  throw new NotFoundError("Game", gameId);
27008
27029
  }
27009
- return;
27030
+ const activeDeployment = await db2.query.gameDeployments.findFirst({
27031
+ where: and(eq(gameDeployments.gameId, gameId), eq(gameDeployments.isActive, true)),
27032
+ columns: { deploymentId: true, provider: true, resources: true }
27033
+ });
27034
+ const customHostnames = await db2.select({
27035
+ hostname: gameCustomHostnames.hostname,
27036
+ cloudflareId: gameCustomHostnames.cloudflareId,
27037
+ environment: gameCustomHostnames.environment
27038
+ }).from(gameCustomHostnames).where(eq(gameCustomHostnames.gameId, gameId));
27039
+ const result = await db2.delete(games).where(eq(games.id, gameId)).returning({ id: games.id });
27040
+ if (result.length === 0) {
27041
+ throw new NotFoundError("Game", gameId);
27042
+ }
27043
+ logger5.info("Deleted game", {
27044
+ gameId: result[0].id,
27045
+ slug: gameToDelete.slug,
27046
+ hadActiveDeployment: Boolean(activeDeployment),
27047
+ customDomainsCount: customHostnames.length
27048
+ });
27049
+ this.deps.alerts.notifyGameDeletion({
27050
+ slug: gameToDelete.slug,
27051
+ displayName: gameToDelete.displayName,
27052
+ developer: { id: user.id, email: user.email }
27053
+ }).catch((error) => {
27054
+ logger5.warn("Failed to send deletion alert", { error });
27055
+ });
27056
+ if (activeDeployment?.provider === "cloudflare" && this.deps.cloudflare) {
27057
+ try {
27058
+ await this.deps.cloudflare.delete(activeDeployment.deploymentId, {
27059
+ deleteBindings: true,
27060
+ resources: activeDeployment.resources ?? undefined,
27061
+ customDomains: customHostnames.length > 0 ? customHostnames : undefined,
27062
+ gameSlug: gameToDelete.slug
27063
+ });
27064
+ logger5.info("Cleaned up Cloudflare resources", {
27065
+ gameId,
27066
+ deploymentId: activeDeployment.deploymentId,
27067
+ customDomainsDeleted: customHostnames.length
27068
+ });
27069
+ } catch (cfError) {
27070
+ logger5.warn("Failed to cleanup Cloudflare resources", {
27071
+ gameId,
27072
+ deploymentId: activeDeployment.deploymentId,
27073
+ error: cfError
27074
+ });
27075
+ }
27076
+ try {
27077
+ const deletedKeyId = await this.deps.deleteApiKeyByName(getGameWorkerApiKeyName(gameToDelete.slug), user.id);
27078
+ if (deletedKeyId) {
27079
+ logger5.info("Cleaned up API key for deleted game", {
27080
+ gameId,
27081
+ slug: gameToDelete.slug,
27082
+ keyId: deletedKeyId
27083
+ });
27084
+ }
27085
+ } catch (keyError) {
27086
+ logger5.warn("Failed to cleanup API key", { gameId, error: keyError });
27087
+ }
27088
+ }
27089
+ return {
27090
+ slug: gameToDelete.slug,
27091
+ displayName: gameToDelete.displayName
27092
+ };
27010
27093
  }
27011
- const db2 = this.deps.db;
27012
- const gameOwnership = await db2.query.games.findFirst({
27013
- where: and(eq(games.id, gameId), eq(games.developerId, user.id)),
27014
- columns: { id: true }
27015
- });
27016
- if (!gameOwnership) {
27017
- const gameExists = await db2.query.games.findFirst({
27018
- where: eq(games.id, gameId),
27094
+ async validateOwnership(user, gameId) {
27095
+ if (user.role === "admin") {
27096
+ const gameExists = await this.deps.db.query.games.findFirst({
27097
+ where: eq(games.id, gameId),
27098
+ columns: { id: true }
27099
+ });
27100
+ if (!gameExists) {
27101
+ throw new NotFoundError("Game", gameId);
27102
+ }
27103
+ return;
27104
+ }
27105
+ const db2 = this.deps.db;
27106
+ const gameOwnership = await db2.query.games.findFirst({
27107
+ where: and(eq(games.id, gameId), eq(games.developerId, user.id)),
27019
27108
  columns: { id: true }
27020
27109
  });
27021
- if (!gameExists) {
27022
- throw new NotFoundError("Game", gameId);
27110
+ if (!gameOwnership) {
27111
+ const gameExists = await db2.query.games.findFirst({
27112
+ where: eq(games.id, gameId),
27113
+ columns: { id: true }
27114
+ });
27115
+ if (!gameExists) {
27116
+ throw new NotFoundError("Game", gameId);
27117
+ }
27118
+ throw new AccessDeniedError("You do not own this game");
27023
27119
  }
27024
- throw new AccessDeniedError("You do not own this game");
27025
27120
  }
27026
- }
27027
- async validateDeveloperAccess(user, gameId) {
27028
- this.validateDeveloperStatus(user);
27029
- if (user.role === "admin") {
27030
- const gameExists = await this.deps.db.query.games.findFirst({
27031
- where: eq(games.id, gameId),
27121
+ async validateDeveloperAccess(user, gameId) {
27122
+ this.validateDeveloperStatus(user);
27123
+ if (user.role === "admin") {
27124
+ const gameExists = await this.deps.db.query.games.findFirst({
27125
+ where: eq(games.id, gameId),
27126
+ columns: { id: true }
27127
+ });
27128
+ if (!gameExists) {
27129
+ throw new NotFoundError("Game", gameId);
27130
+ }
27131
+ return;
27132
+ }
27133
+ const db2 = this.deps.db;
27134
+ const existingGame = await db2.query.games.findFirst({
27135
+ where: and(eq(games.id, gameId), eq(games.developerId, user.id)),
27032
27136
  columns: { id: true }
27033
27137
  });
27034
- if (!gameExists) {
27138
+ if (!existingGame) {
27035
27139
  throw new NotFoundError("Game", gameId);
27036
27140
  }
27037
- return;
27038
- }
27039
- const db2 = this.deps.db;
27040
- const existingGame = await db2.query.games.findFirst({
27041
- where: and(eq(games.id, gameId), eq(games.developerId, user.id)),
27042
- columns: { id: true }
27043
- });
27044
- if (!existingGame) {
27045
- throw new NotFoundError("Game", gameId);
27046
27141
  }
27047
- }
27048
- async validateDeveloperAccessBySlug(user, slug) {
27049
- this.validateDeveloperStatus(user);
27050
- const db2 = this.deps.db;
27051
- if (user.role === "admin") {
27052
- const game2 = await db2.query.games.findFirst({
27053
- where: eq(games.slug, slug)
27142
+ async validateDeveloperAccessBySlug(user, slug) {
27143
+ this.validateDeveloperStatus(user);
27144
+ const db2 = this.deps.db;
27145
+ if (user.role === "admin") {
27146
+ const game2 = await db2.query.games.findFirst({
27147
+ where: eq(games.slug, slug)
27148
+ });
27149
+ if (!game2) {
27150
+ throw new NotFoundError("Game", slug);
27151
+ }
27152
+ return game2;
27153
+ }
27154
+ const game = await db2.query.games.findFirst({
27155
+ where: and(eq(games.slug, slug), eq(games.developerId, user.id))
27054
27156
  });
27055
- if (!game2) {
27157
+ if (!game) {
27056
27158
  throw new NotFoundError("Game", slug);
27057
27159
  }
27058
- return game2;
27059
- }
27060
- const game = await db2.query.games.findFirst({
27061
- where: and(eq(games.slug, slug), eq(games.developerId, user.id))
27062
- });
27063
- if (!game) {
27064
- throw new NotFoundError("Game", slug);
27065
- }
27066
- return game;
27067
- }
27068
- validateDeveloperStatus(user) {
27069
- if (user.role === "admin") {
27070
- return;
27160
+ return game;
27071
27161
  }
27072
- if (user.developerStatus !== "approved") {
27073
- const status = user.developerStatus || "none";
27074
- if (status === "pending") {
27075
- throw new AccessDeniedError("Developer application is pending approval. You will be notified when approved.");
27076
- } else {
27077
- throw new AccessDeniedError("Developer status required. Apply for developer access to create and manage games.");
27162
+ validateDeveloperStatus(user) {
27163
+ if (user.role === "admin") {
27164
+ return;
27165
+ }
27166
+ if (user.developerStatus !== "approved") {
27167
+ const status = user.developerStatus || "none";
27168
+ if (status === "pending") {
27169
+ throw new AccessDeniedError("Developer application is pending approval. You will be notified when approved.");
27170
+ } else {
27171
+ throw new AccessDeniedError("Developer status required. Apply for developer access to create and manage games.");
27172
+ }
27078
27173
  }
27079
27174
  }
27080
- }
27081
- }
27082
- var logger5;
27083
- var init_game_service = __esm(() => {
27084
- init_drizzle_orm();
27085
- init_tables_index();
27086
- init_src2();
27087
- init_errors();
27088
- init_deployment_util();
27089
- logger5 = log.scope("GameService");
27175
+ };
27090
27176
  });
27091
27177
 
27092
27178
  // ../api-core/src/services/factory/game.ts
@@ -27095,6 +27181,7 @@ function createGameServices(deps) {
27095
27181
  const game = new GameService({
27096
27182
  db: db2,
27097
27183
  alerts,
27184
+ cache,
27098
27185
  cloudflare,
27099
27186
  deleteApiKeyByName: auth2.deleteApiKeyByName.bind(auth2)
27100
27187
  });