@terrafirmagreg-team/recipe 1.2.27 → 1.2.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/package.json +6 -6
  2. package/src/components/cards/card/index.tsx +17 -13
  3. package/src/components/cards/scroll-card/index.tsx +5 -1
  4. package/src/components/cards/slot-hitbox.tsx +22 -4
  5. package/src/components/mdx/recipe.tsx +2 -2
  6. package/src/components/tree.tsx +7 -6
  7. package/src/components/views/alloy/list.tsx +1 -0
  8. package/src/components/views/browser/axis-switcher.tsx +6 -7
  9. package/src/components/views/browser/card-grid.tsx +14 -7
  10. package/src/components/views/browser/index.tsx +23 -9
  11. package/src/components/views/browser/item-panel/index.tsx +125 -70
  12. package/src/components/views/browser/item-panel-grid/index.tsx +10 -2
  13. package/src/components/views/browser/item-view/tags.tsx +2 -0
  14. package/src/components/views/browser/type-view.tsx +5 -4
  15. package/src/components/views/calc/calculator/index.tsx +2 -0
  16. package/src/components/views/calc/sidebar.tsx +4 -1
  17. package/src/components/views/forge/list.tsx +1 -0
  18. package/src/components/views/landing.tsx +39 -11
  19. package/src/hooks/alloy/use-fluid-colors.ts +2 -3
  20. package/src/hooks/alloy/use-mix-state.ts +2 -0
  21. package/src/hooks/calc/use-actions.ts +6 -4
  22. package/src/hooks/calc/use-data.ts +1 -0
  23. package/src/hooks/calc/use-share.ts +6 -4
  24. package/src/hooks/use-add-to-calc.ts +2 -1
  25. package/src/hooks/use-index.ts +29 -8
  26. package/src/hooks/use-mount-limit.ts +9 -3
  27. package/src/hooks/use-panel-page.ts +8 -50
  28. package/src/hooks/use-panel-warmup.ts +129 -0
  29. package/src/hooks/use-query.ts +8 -2
  30. package/src/hooks/use-session.ts +47 -7
  31. package/src/lib/browser/fluid-outputs.ts +2 -3
  32. package/src/lib/cards/model.ts +5 -1
  33. package/src/lib/client/recipe.ts +24 -30
  34. package/src/lib/client-index/catalog.ts +2 -3
  35. package/src/lib/client-index/chrome.test.ts +87 -0
  36. package/src/lib/client-index/chrome.ts +27 -134
  37. package/src/lib/client-index/prepared-catalog.ts +80 -0
  38. package/src/lib/client-index/registry.ts +3 -4
  39. package/src/lib/client-index/rows.test.ts +127 -0
  40. package/src/lib/client-index/rows.ts +51 -194
  41. package/src/lib/client-index/store.ts +2 -3
  42. package/src/lib/client-index/tooltips.ts +4 -5
  43. package/src/lib/links.ts +10 -3
  44. package/src/lib/og.ts +39 -7
  45. package/src/lib/preview.ts +2 -2
  46. package/src/types/catalog.ts +18 -0
  47. package/src/types/index.ts +1 -0
@@ -1,5 +1,5 @@
1
1
  'use client';
2
- import type { DatasetRef } from '@terrafirmagreg-team/sites/location';
2
+ import { datasetCacheKey, type DatasetRef } from '@terrafirmagreg-team/sites/location';
3
3
 
4
4
  import { startTransition, useMemo, useState } from 'react';
5
5
  import { useLang } from '@terrafirmagreg-team/translate/provider';
@@ -37,17 +37,29 @@ export function useRecipeIndex(dataset: DatasetRef | undefined, lang: string) {
37
37
  () => items?.map((item) => item.locale) ?? [lang],
38
38
  [items, lang],
39
39
  );
40
- const key = `${dataset ? `${dataset.id}/${dataset.version ?? ''}` : ''} ${lang}`;
40
+ const key = dataset ? datasetCacheKey(dataset, lang) : '';
41
41
 
42
42
  useAsyncEffect(async (isCancelled) => {
43
43
  if (!dataset) return;
44
- const skeleton = await loadRecipeSkeletonIndex(dataset);
45
- if (isCancelled()) return;
44
+ const skeleton = await loadRecipeSkeletonIndex(dataset).catch(
45
+ () => undefined,
46
+ );
47
+ if (!skeleton || isCancelled()) {
48
+ if (!isCancelled()) setComplete(key);
49
+ return;
50
+ }
46
51
  setLoaded({ key, index: skeleton });
47
52
  publishRecipeIndex(dataset, lang, skeleton);
48
- const chrome = await loadRecipeChromeClient(dataset, lang);
49
- const index = await loadRecipeCompactIndex(dataset, chrome);
50
- if (isCancelled()) return;
53
+ const chrome = await loadRecipeChromeClient(dataset, lang).catch(
54
+ () => undefined,
55
+ );
56
+ const index = chrome
57
+ ? await loadRecipeCompactIndex(dataset, chrome).catch(() => undefined)
58
+ : undefined;
59
+ if (!chrome || !index || isCancelled()) {
60
+ if (!isCancelled()) setComplete(key);
61
+ return;
62
+ }
51
63
  startTransition(() => {
52
64
  setLoaded({ key, index });
53
65
  setComplete(key);
@@ -74,6 +86,16 @@ export function useRecipeIndex(dataset: DatasetRef | undefined, lang: string) {
74
86
 
75
87
  useAsyncEffect(async (isCancelled) => {
76
88
  if (!dataset || warmKey !== key) return;
89
+ const conn = (
90
+ navigator as Navigator & {
91
+ connection?: { effectiveType?: string; saveData?: boolean };
92
+ }
93
+ ).connection;
94
+ if (
95
+ conn?.saveData ||
96
+ (conn?.effectiveType && conn.effectiveType !== '4g')
97
+ )
98
+ return;
77
99
  for (const entry of locales.filter((item) => item !== lang)) {
78
100
  await idle();
79
101
  if (isCancelled()) return;
@@ -90,4 +112,3 @@ export function useRecipeIndex(dataset: DatasetRef | undefined, lang: string) {
90
112
  const index = active?.items.length ? active : (lastFull ?? active);
91
113
  return { index, indexLoading: complete !== key };
92
114
  }
93
-
@@ -2,12 +2,18 @@
2
2
 
3
3
  import { useEffect, useState } from 'react';
4
4
 
5
- export function useMountLimit(length: number, resetKey: unknown): number {
6
- const [limit, setLimit] = useState(40);
5
+ export function useMountLimit(
6
+ length: number,
7
+ resetKey: unknown,
8
+ eager = false,
9
+ ): number {
10
+ const [limit, setLimit] = useState(() => (eager ? length : 40));
7
11
  const [lastKey, setLastKey] = useState(resetKey);
8
12
  if (lastKey !== resetKey) {
9
13
  setLastKey(resetKey);
10
- setLimit(40);
14
+ setLimit(eager ? length : 40);
15
+ } else if (eager && limit < length) {
16
+ setLimit(length);
11
17
  }
12
18
  useEffect(() => {
13
19
  if (limit >= length) return;
@@ -1,54 +1,12 @@
1
1
  'use client';
2
2
  import type { DatasetRef } from '@terrafirmagreg-team/sites/location';
3
3
 
4
- import { useCallback } from 'react';
5
- import {
6
- createStoredValue,
7
- type StoredCodec,
8
- } from '@terrafirmagreg-team/ui/lib/utils/stored-value';
9
-
10
- const codec: StoredCodec<Record<string, number>> = {
11
- read: (raw) => {
12
- if (!raw) return {};
13
- try {
14
- const parsed: unknown = JSON.parse(raw);
15
- if (!parsed || typeof parsed !== 'object') return {};
16
- const out: Record<string, number> = {};
17
- for (const [key, value] of Object.entries(
18
- parsed as Record<string, unknown>,
19
- )) {
20
- const page = Math.floor(Number(value));
21
- if (Number.isFinite(page) && page > 0) out[key] = page;
22
- }
23
- return out;
24
- } catch {
25
- return {};
26
- }
27
- },
28
- write: (value) => JSON.stringify(value),
29
- };
30
-
31
- const useStoredPanelPages = createStoredValue(
32
- 'wiki.recipe.panelPage',
33
- codec,
34
- );
35
-
36
- export function usePanelPage(dataset: DatasetRef) {
37
- const [pages, setPages] = useStoredPanelPages();
38
- const refKey = `${dataset.id}/${dataset.version ?? ''}`;
39
- const setPage = useCallback(
40
- (page: number) => {
41
- setPages((prev) => {
42
- const next = page > 0 ? page : 0;
43
- if ((prev[refKey] ?? 0) === next) return prev;
44
- const copy = { ...prev };
45
- if (next > 0) copy[refKey] = next;
46
- else delete copy[refKey];
47
- return copy;
48
- });
49
- },
50
- [refKey, setPages],
51
- );
52
- return { page: pages[refKey] ?? 0, setPage };
4
+ import { useCallback, useState } from 'react';
5
+
6
+ export function usePanelPage(_dataset: DatasetRef) {
7
+ const [page, setPageState] = useState(0);
8
+ const setPage = useCallback((next: number) => {
9
+ setPageState(Math.max(0, Math.floor(next)));
10
+ }, []);
11
+ return { page, setPage };
53
12
  }
54
-
@@ -0,0 +1,129 @@
1
+ 'use client';
2
+ import { datasetCacheKey, type DatasetRef } from '@terrafirmagreg-team/sites/location';
3
+
4
+ import { useEffect } from 'react';
5
+ import { parseStackId } from '@terrafirmagreg-team/dump/lib/dump/contract/ref';
6
+ import { loadClientModAtlases } from '@terrafirmagreg-team/dump/lib/dump/client/atlases';
7
+ import {
8
+ atlasPagePublicUrl,
9
+ lookupSpriteInBundle,
10
+ } from '@terrafirmagreg-team/dump/lib/dump/assets/atlas/lookup';
11
+ import type {
12
+ AtlasBundle,
13
+ SpriteQuery,
14
+ } from '@terrafirmagreg-team/dump/lib/dump/assets/atlas/dto';
15
+ import { loadStackDisplay } from '@terrafirmagreg-team/game/lib/entry/tooltip';
16
+ import type { ItemPanelCell } from '@terrafirmagreg-team/recipe/types';
17
+
18
+ const BATCH = 160;
19
+ const MAX_PAGES_CACHE = 6;
20
+
21
+ const prefetched = new Map<string, Set<string>>();
22
+
23
+ function idleStep(step: () => void) {
24
+ if (typeof requestIdleCallback === 'function') {
25
+ requestIdleCallback(step, { timeout: 900 });
26
+ } else {
27
+ window.setTimeout(step, 32);
28
+ }
29
+ }
30
+
31
+ function stackQuery(id: string, kind: SpriteQuery['kind']): SpriteQuery {
32
+ const parsed = parseStackId(id);
33
+ return {
34
+ id: parsed.id,
35
+ kind,
36
+ ...(parsed.nbt !== undefined ? { tag: parsed.nbt } : {}),
37
+ };
38
+ }
39
+
40
+ function cellQueries(cell: ItemPanelCell): SpriteQuery[] {
41
+ switch (cell.kind) {
42
+ case 'stack':
43
+ return [stackQuery(cell.id, cell.ref === 'fluid' ? 'fluid' : 'item')];
44
+ case 'group':
45
+ return cell.members.map((id) => stackQuery(id, 'item'));
46
+ case 'recipe': {
47
+ const icon = cell.fav.icon;
48
+ return icon ? [stackQuery(icon, 'item')] : [];
49
+ }
50
+ }
51
+ }
52
+
53
+ async function warmCells(
54
+ dataset: DatasetRef,
55
+ cells: ItemPanelCell[],
56
+ seen: Set<string>,
57
+ ) {
58
+ const bundles = new Map<string, AtlasBundle | null>();
59
+ for (const cell of cells) {
60
+ for (const query of cellQueries(cell)) {
61
+ const spriteId = query.id;
62
+ if (!spriteId || spriteId.startsWith('#')) continue;
63
+ const ns = spriteId.includes(':')
64
+ ? spriteId.slice(0, spriteId.indexOf(':'))
65
+ : '';
66
+ if (!ns) continue;
67
+ let bundle = bundles.get(ns);
68
+ if (bundle === undefined) {
69
+ bundle = await loadClientModAtlases(dataset, ns);
70
+ bundles.set(ns, bundle);
71
+ }
72
+ const hit = lookupSpriteInBundle(bundle, query);
73
+ const url = hit
74
+ ? atlasPagePublicUrl(dataset, hit.atlas, hit.page)
75
+ : undefined;
76
+ if (url && !seen.has(url)) {
77
+ seen.add(url);
78
+ const img = new Image();
79
+ img.decoding = 'async';
80
+ img.src = url;
81
+ }
82
+ void loadStackDisplay(dataset, spriteId, query.kind).catch(() => {});
83
+ }
84
+ }
85
+ }
86
+
87
+ export function usePanelWarmup(
88
+ dataset: DatasetRef,
89
+ cells: ItemPanelCell[],
90
+ page: number,
91
+ pageSize: number,
92
+ ) {
93
+ useEffect(() => {
94
+ if (!cells.length || pageSize <= 0) return;
95
+ const key = datasetCacheKey(dataset);
96
+ let seen = prefetched.get(key);
97
+ if (!seen) {
98
+ if (prefetched.size >= MAX_PAGES_CACHE) {
99
+ prefetched.delete(prefetched.keys().next().value!);
100
+ }
101
+ seen = new Set();
102
+ prefetched.set(key, seen);
103
+ }
104
+ let cancelled = false;
105
+ const order = cells.map((_, i) => i);
106
+ order.sort(
107
+ (a, b) =>
108
+ Math.abs(Math.floor(a / pageSize) - page) -
109
+ Math.abs(Math.floor(b / pageSize) - page),
110
+ );
111
+ let cursor = 0;
112
+ const step = () => {
113
+ if (cancelled) return;
114
+ const batch = order.slice(cursor, cursor + BATCH);
115
+ cursor += BATCH;
116
+ void warmCells(
117
+ dataset,
118
+ batch.map((i) => cells[i]!),
119
+ seen,
120
+ ).then(() => {
121
+ if (!cancelled && cursor < order.length) idleStep(step);
122
+ });
123
+ };
124
+ step();
125
+ return () => {
126
+ cancelled = true;
127
+ };
128
+ }, [dataset, cells, page, pageSize]);
129
+ }
@@ -25,7 +25,7 @@ function urlRelation(
25
25
  return value === 'uses' || value === 'tags' ? value : undefined;
26
26
  }
27
27
 
28
- export function useRecipeQuery(dataset: DatasetRef) {
28
+ export function useRecipeQuery(dataset: DatasetRef, version?: string) {
29
29
  const params = useLocationSearchParams();
30
30
  const resolved = useResolvedLang();
31
31
 
@@ -80,13 +80,14 @@ export function useRecipeQuery(dataset: DatasetRef) {
80
80
  if (!stray) return;
81
81
  replaceUrlState(
82
82
  isCalc
83
- ? recipeCalcHref(dataset, resolved, tree || undefined)
83
+ ? recipeCalcHref(dataset, resolved, tree || undefined, version)
84
84
  : recipeHref(dataset, resolved, {
85
85
  tool: place.kind,
86
86
  id: recipeId,
87
87
  unit: alloyUnit,
88
88
  mix: alloyMix,
89
89
  tab,
90
+ version,
90
91
  }),
91
92
  );
92
93
  }, [
@@ -95,6 +96,7 @@ export function useRecipeQuery(dataset: DatasetRef) {
95
96
  place.kind,
96
97
  resolved,
97
98
  dataset,
99
+ version,
98
100
  params,
99
101
  tree,
100
102
  recipeId,
@@ -117,6 +119,7 @@ export function useRecipeQuery(dataset: DatasetRef) {
117
119
  tab,
118
120
  search: searchParam || undefined,
119
121
  rpage: rpageValue + 1,
122
+ version,
120
123
  }),
121
124
  );
122
125
  }
@@ -124,6 +127,7 @@ export function useRecipeQuery(dataset: DatasetRef) {
124
127
  isTool,
125
128
  resolved,
126
129
  dataset,
130
+ version,
127
131
  params,
128
132
  rawItem,
129
133
  rawFluid,
@@ -151,12 +155,14 @@ export function useRecipeQuery(dataset: DatasetRef) {
151
155
  tab,
152
156
  search: searchParam || undefined,
153
157
  rpage: rpageValue + 1,
158
+ version,
154
159
  }),
155
160
  );
156
161
  }, [
157
162
  isTool,
158
163
  resolved,
159
164
  dataset,
165
+ version,
160
166
  params,
161
167
  rawItem,
162
168
  rawFluid,
@@ -2,11 +2,15 @@
2
2
 
3
3
  import { useEffect, useMemo } from 'react';
4
4
  import { useVersionedDataset } from '@terrafirmagreg-team/kit/hooks/use-versioned-dataset';
5
+ import { useActiveDatasetSnapshot } from '@terrafirmagreg-team/kit/hooks/use-dataset-snapshot';
5
6
  import { useRecipeIndex } from '@terrafirmagreg-team/recipe/hooks/use-index';
6
7
  import { useRecipeQuery } from '@terrafirmagreg-team/recipe/hooks/use-query';
7
8
  import { useAsyncValue } from '@terrafirmagreg-team/ui/hooks/use-async-value';
8
9
  import { useResolvedLang } from '@terrafirmagreg-team/translate/hooks/use-resolved-lang';
9
- import { clientDumpLang } from '@terrafirmagreg-team/dump/lib/dump/client/dump';
10
+ import {
11
+ clientDumpLangNames,
12
+ clientDumpLangRecipe,
13
+ } from '@terrafirmagreg-team/dump/lib/dump/client/dump';
10
14
  import { useRecipeIndexNames } from '@terrafirmagreg-team/recipe/lib/client-index/store';
11
15
  import {
12
16
  RECIPE_ALL_TYPE,
@@ -21,11 +25,42 @@ import type {
21
25
  RecipeSession,
22
26
  } from '@terrafirmagreg-team/recipe/types';
23
27
 
28
+ let langMapMemo:
29
+ | {
30
+ names: Record<string, Record<string, string>>;
31
+ langRaw: Record<string, string> | undefined;
32
+ lang: string;
33
+ map: Record<string, string>;
34
+ }
35
+ | undefined;
36
+
37
+ function mergeLangMap(
38
+ names: Record<string, Record<string, string>>,
39
+ langRaw: Record<string, string> | undefined,
40
+ lang: string,
41
+ ): Record<string, string> {
42
+ if (
43
+ langMapMemo?.names === names &&
44
+ langMapMemo.langRaw === langRaw &&
45
+ langMapMemo.lang === lang
46
+ ) {
47
+ return langMapMemo.map;
48
+ }
49
+ const map = { ...names.en_us, ...langRaw, ...names[lang] };
50
+ langMapMemo = { names, langRaw, lang, map };
51
+ return map;
52
+ }
53
+
24
54
  export function useRecipeSession(page: RecipePageData): RecipeSession {
25
55
  const { dataset: id, lang } = page;
26
- const dataset =
27
- useVersionedDataset(id.id, { versions: page.versions }) ?? id;
28
- const query = useRecipeQuery(dataset);
56
+ const selection = useVersionedDataset(id.id, { versions: page.versions });
57
+ const active = useActiveDatasetSnapshot(selection);
58
+ const snapshot = id.revision ? id : active ?? selection ?? id;
59
+ const dataset = useMemo(
60
+ () => ({ ...snapshot, pin: selection?.version }),
61
+ [snapshot, selection?.version],
62
+ );
63
+ const query = useRecipeQuery(dataset, selection?.version);
29
64
  const { index, indexLoading } = useRecipeIndex(dataset, lang);
30
65
  const placeOpts = recipePlaceOpts(query.place);
31
66
 
@@ -35,11 +70,15 @@ export function useRecipeSession(page: RecipePageData): RecipeSession {
35
70
  [indexNames, index],
36
71
  );
37
72
  const langRaw = useAsyncValue(
38
- () => clientDumpLang(dataset, lang),
73
+ () =>
74
+ Promise.all([
75
+ clientDumpLangNames(dataset, lang),
76
+ clientDumpLangRecipe(dataset, lang),
77
+ ]).then(([names, recipe]) => ({ ...names, ...recipe })),
39
78
  [dataset, lang],
40
79
  );
41
80
  const langMap = useMemo(
42
- () => ({ ...names.en_us, ...langRaw, ...names[lang] }),
81
+ () => mergeLangMap(names, langRaw, lang),
43
82
  [langRaw, names, lang],
44
83
  );
45
84
  const used = useMemo(() => recipeUsedItems(index), [index]);
@@ -55,6 +94,7 @@ export function useRecipeSession(page: RecipePageData): RecipeSession {
55
94
  relation: query.relation,
56
95
  search: query.query || undefined,
57
96
  rpage: query.rpage + 1,
97
+ version: selection?.version,
58
98
  }),
59
99
  [
60
100
  navType,
@@ -66,6 +106,7 @@ export function useRecipeSession(page: RecipePageData): RecipeSession {
66
106
  query.relation,
67
107
  query.query,
68
108
  query.rpage,
109
+ selection?.version,
69
110
  ],
70
111
  );
71
112
 
@@ -104,4 +145,3 @@ export function useRecipeSession(page: RecipePageData): RecipeSession {
104
145
  used,
105
146
  };
106
147
  }
107
-
@@ -1,4 +1,4 @@
1
- import type { DatasetRef } from '@terrafirmagreg-team/sites/location';
1
+ import { datasetCacheKey, type DatasetRef } from '@terrafirmagreg-team/sites/location';
2
2
  import type { RecipeCompactIndex } from '@terrafirmagreg-team/recipe/types';
3
3
  import { outputBoundary } from '@terrafirmagreg-team/recipe/lib/data/slot-io';
4
4
  import { loadTypeRows } from '@terrafirmagreg-team/recipe/lib/client-index';
@@ -11,7 +11,7 @@ export type FluidIoIndex = {
11
11
 
12
12
  const cache = createDatasetCache(
13
13
  build,
14
- (dataset) => `${dataset.id}/${dataset.version ?? ''}`,
14
+ (dataset) => datasetCacheKey(dataset),
15
15
  );
16
16
 
17
17
  function tankCategories(index: RecipeCompactIndex, role: 'input' | 'output') {
@@ -67,4 +67,3 @@ export function loadFluidIoIndex(
67
67
  ): Promise<FluidIoIndex> {
68
68
  return cache(dataset, index);
69
69
  }
70
-
@@ -72,7 +72,11 @@ export function countCoveredText(
72
72
  return slots.some(
73
73
  (slot) =>
74
74
  slot.count !== undefined &&
75
- scales.some((scale) => Math.round(num * scale) === slot.count) &&
75
+ scales.some(
76
+ (scale) =>
77
+ Math.abs(num * scale - slot.count!) <=
78
+ Math.max(1, num * scale * 0.01),
79
+ ) &&
76
80
  widget.x + widget.w > slot.x &&
77
81
  widget.x < slot.x + slot.w,
78
82
  );
@@ -1,6 +1,6 @@
1
- import type { DatasetRef } from '@terrafirmagreg-team/sites/location';
1
+ import { datasetCacheKey, type DatasetRef } from '@terrafirmagreg-team/sites/location';
2
2
  import { asRecord, asString } from '@terrafirmagreg-team/dump/lib/dump/contract/read';
3
- import { parseRecipe } from '@terrafirmagreg-team/recipe/lib/data/parse';
3
+ import { parseRecipe } from '@terrafirmagreg-team/recipe/lib/data/parse/index';
4
4
  import type { Recipe } from '@terrafirmagreg-team/recipe/lib/data/dto';
5
5
  import { dumpRelPublicUrl } from '@terrafirmagreg-team/dump/lib/dump/paths';
6
6
  import {
@@ -9,41 +9,36 @@ import {
9
9
  } from '@terrafirmagreg-team/dump/lib/dump/client/dump';
10
10
  import { clientRecipeLayout } from '@terrafirmagreg-team/recipe/lib/client/recipe-categories';
11
11
  import { createDatasetCache } from '@terrafirmagreg-team/dump/lib/dump/reader';
12
+ import type {
13
+ PreparedRecipeRow,
14
+ RegistryRecipes,
15
+ } from '@terrafirmagreg-team/dump/lib/dump/gen';
12
16
 
13
- const recipeIndex = createDatasetCache(async (dataset: DatasetRef, ns: string) => {
17
+ const recipeIndex = createDatasetCache(async (dataset: DatasetRef) => {
14
18
  const manifest = await loadClientManifest(dataset);
15
- const listed = manifest?.namespaces[ns];
16
- if (!listed || !listed.registry.includes('recipes')) return undefined;
19
+ if (!manifest || !Object.values(manifest.namespaces).some(
20
+ (namespace) => namespace?.registry.includes('recipes'),
21
+ )) return undefined;
17
22
  return asRecord(
18
- await clientDumpJson(dataset, 'registry/recipes.json', 'high'),
19
- ) as Record<string, string | string[]> | undefined;
23
+ await clientDumpJson(dataset, 'registry/recipes.ndjson', 'high'),
24
+ ) as RegistryRecipes | undefined;
20
25
  });
21
26
 
27
+ export async function clientPreparedRecipeRows(
28
+ dataset: DatasetRef,
29
+ recipeIds: Iterable<string>,
30
+ ): Promise<PreparedRecipeRow[]> {
31
+ const index = await recipeIndex(dataset);
32
+ return [...new Set(recipeIds)].flatMap((id) => index?.[id] ?? []);
33
+ }
34
+
22
35
  export async function clientRecipeFileRels(
23
36
  dataset: DatasetRef,
24
37
  recipeId: string,
25
38
  ): Promise<string[]> {
26
- const ns = recipeId.split(':', 1)[0];
27
- if (!ns) return [];
28
- const index = await recipeIndex(dataset, ns);
29
- const value = index?.[recipeId];
30
- const categories = Array.isArray(value)
31
- ? value
32
- : typeof value === 'string'
33
- ? [value]
34
- : [];
35
- return categories
36
- .filter(
37
- (category): category is string =>
38
- typeof category === 'string' && !!category,
39
- )
40
- .map((category) =>
41
- category.includes(':')
42
- ? category.slice(category.indexOf(':') + 1)
43
- : category,
44
- )
45
- .filter((path) => !!path)
46
- .map((path) => `data/${ns}/recipes/${path}.json`);
39
+ return [...new Set(
40
+ (await clientPreparedRecipeRows(dataset, [recipeId])).map((row) => row.bucket),
41
+ )];
47
42
  }
48
43
 
49
44
  async function clientRecipeFileRel(
@@ -80,6 +75,5 @@ export const loadClientRecipe: (
80
75
  ...(layout ? { layout } : {}),
81
76
  });
82
77
  },
83
- (dataset, id, bucket) => JSON.stringify([dataset, id, bucket ?? '']),
78
+ (dataset, id, bucket) => datasetCacheKey(dataset, id, bucket ?? ''),
84
79
  );
85
-
@@ -1,4 +1,4 @@
1
- import type { DatasetRef } from '@terrafirmagreg-team/sites/location';
1
+ import { datasetCacheKey, type DatasetRef } from '@terrafirmagreg-team/sites/location';
2
2
  import type { RecipeChrome, RecipeCompactIndex } from '@terrafirmagreg-team/recipe/types';
3
3
  import { loadDatasetRecipeCategories } from '@terrafirmagreg-team/recipe/lib/data/category/load';
4
4
  import { stackDisplayName } from '@terrafirmagreg-team/game/lib/entry/display';
@@ -44,7 +44,7 @@ const indexCache = createDatasetCache(
44
44
  return loadRecipeStructureFromDump(dataset, chrome);
45
45
  },
46
46
  (dataset, chrome) =>
47
- `${dataset.id}/${dataset.version ?? ''} ${chrome ? (Object.keys(chrome.names)[0] ?? '') : ''}`,
47
+ datasetCacheKey(dataset, chrome ? (Object.keys(chrome.names)[0] ?? '') : ''),
48
48
  );
49
49
 
50
50
  const skeletonCache = createDatasetCache(
@@ -88,4 +88,3 @@ export function recipeItemName(
88
88
  ): string {
89
89
  return stackDisplayName(names[lang] ?? names.en_us, id);
90
90
  }
91
-
@@ -0,0 +1,87 @@
1
+ import assert from 'node:assert/strict';
2
+ import { mock, test } from 'node:test';
3
+ import { datasetCacheKey, type DatasetRef } from '@terrafirmagreg-team/sites/location';
4
+ import { createAsyncCache } from '@terrafirmagreg-team/data/lib/async-cache';
5
+ import type { PreparedCatalog } from '../../types/catalog';
6
+ import { parseCatalogLabels, parsePreparedCatalog } from './prepared-catalog';
7
+
8
+ const catalog: PreparedCatalog = {
9
+ items: ['test:item{mode:1}'],
10
+ fluids: [],
11
+ usedIds: ['#test:ores'],
12
+ tabs: [{ id: 'test:tab', order: 0, display: {} }],
13
+ tabItems: { 'test:tab': ['test:item{mode:1}'] },
14
+ categories: [{ id: 'test:craft', order: 0, workstations: [] }],
15
+ groups: [{ id: 'test:group', members: ['test:item{mode:1}'] }],
16
+ };
17
+ const requests: string[] = [];
18
+ const names = { 'test:item{mode:1}': 'Item' };
19
+
20
+ mock.module('@terrafirmagreg-team/dump/lib/dump/client/dump', {
21
+ namedExports: {
22
+ clientDumpJson: async (_dataset: DatasetRef, path: string) => {
23
+ requests.push(path);
24
+ if (path === 'registry/catalog.json') return catalog;
25
+ if (path === 'lang/fr_fr.catalog.json') {
26
+ return { mods: { test: 'Test' }, names: { 'test:tab': 'Outils' }, groups: { 'test:group': 'Groupe' } };
27
+ }
28
+ if (path === 'lang/en_us.catalog.json') {
29
+ return { mods: { test: 'Test' }, names: { 'test:tab': 'Tools' }, groups: { 'test:group': 'Group' } };
30
+ }
31
+ throw new Error(`Unexpected request ${path}`);
32
+ },
33
+ clientDumpNames: async (_dataset: DatasetRef, lang: string) => {
34
+ requests.push(`names/${lang}.ndjson`);
35
+ return names;
36
+ },
37
+ },
38
+ });
39
+ mock.module('@terrafirmagreg-team/dump/lib/dump/reader', {
40
+ namedExports: {
41
+ createDatasetCache: <A extends unknown[], V>(
42
+ loader: (dataset: DatasetRef, ...args: A) => Promise<V>,
43
+ key = (dataset: DatasetRef, ...args: A) => datasetCacheKey(dataset, ...args),
44
+ ) => createAsyncCache(loader, key),
45
+ },
46
+ });
47
+
48
+ test('chrome requests only prepared projections and shares neutral arrays across locales', async () => {
49
+ const { loadRecipeChromeClient, loadRecipeEntityNames } = await import('./chrome');
50
+ const dataset = { id: 'fixture', version: '1', revision: 'a' };
51
+ const en = await loadRecipeChromeClient(dataset, 'en_us');
52
+ assert.deepEqual(requests, ['registry/catalog.json', 'lang/en_us.catalog.json']);
53
+ assert.equal(en.items, catalog.items);
54
+ assert.equal(en.names.en_us['test:tab'], 'Tools');
55
+ assert.equal(en.groups?.[0].name, 'Group');
56
+ const fr = await loadRecipeChromeClient(dataset, 'fr_fr');
57
+ assert.deepEqual(requests, [
58
+ 'registry/catalog.json', 'lang/en_us.catalog.json', 'lang/fr_fr.catalog.json',
59
+ ]);
60
+ assert.equal(fr.items, en.items);
61
+ assert.equal(fr.fluids, en.fluids);
62
+ assert.equal(fr.usedIds, en.usedIds);
63
+ assert.equal(fr.tabs, en.tabs);
64
+ assert.equal(fr.categories, en.categories);
65
+ assert.equal(fr.tabItems, en.tabItems);
66
+ assert.equal(fr.groups?.[0].members, en.groups?.[0].members);
67
+ assert.equal(fr.groups?.[0].name, 'Groupe');
68
+ assert.equal(await loadRecipeChromeClient(dataset, 'en_us'), en);
69
+ assert.equal(await loadRecipeEntityNames(dataset, en, 'en_us'), names);
70
+ assert.equal(await loadRecipeEntityNames(dataset, fr, 'en_us'), names);
71
+ assert.equal(requests.filter((path) => path.startsWith('names/')).length, 1);
72
+ });
73
+
74
+ test('required projections reject missing fields, old shapes and malformed rows', () => {
75
+ assert.throws(() => parsePreparedCatalog(undefined));
76
+ for (const field of Object.keys(catalog)) {
77
+ const invalid: Record<string, unknown> = { ...catalog };
78
+ delete invalid[field];
79
+ assert.throws(() => parsePreparedCatalog(invalid));
80
+ }
81
+ assert.throws(() => parsePreparedCatalog({ ...catalog, tabs: {} }));
82
+ assert.throws(() => parsePreparedCatalog({ ...catalog, categories: [{ id: 'test:craft' }] }));
83
+ assert.throws(() => parseCatalogLabels({ mods: {}, names: {} }));
84
+ assert.throws(() => parseCatalogLabels({ mods: {}, names: {}, groups: { bad: 1 } }));
85
+ const empty = { items: [], fluids: [], usedIds: [], tabs: [], tabItems: {}, categories: [], groups: [] };
86
+ assert.deepEqual(parsePreparedCatalog(empty), empty);
87
+ });