@willwade/aac-processors 0.3.1 → 0.3.3

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.
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Vocabulary Dump (counts-only)
3
+ *
4
+ * Inventory of the vocabulary available in an AAC pageset, aggregated by
5
+ * source and part of speech. Only counts are emitted — never word lists —
6
+ * so the output is safe to embed in privacy-preserving reports.
7
+ *
8
+ * Sources counted:
9
+ * buttons — labelled buttons (the static on-board vocabulary)
10
+ * wordLists — page WordLists feeding dynamic AutoContent cells
11
+ * (Grid 3 `<WordList>`; absent in other formats)
12
+ * predictionDictionaries — prediction wordlists attached to prediction cells
13
+ * (Grid 3 `Prediction.PredictThis` dictionaries)
14
+ * wordForms — smart-grammar inflections generated by
15
+ * MetricsCalculator (only when a MetricsResult is
16
+ * supplied)
17
+ *
18
+ * Non-Grid 3 formats simply report zeros for the Grid 3-specific sources.
19
+ */
20
+ /** Normalise an entry: trim, lowercase, collapse internal whitespace. */
21
+ function normalize(text) {
22
+ return text.trim().toLowerCase().replace(/\s+/g, ' ');
23
+ }
24
+ const UNTAGGED = 'Unknown';
25
+ /** Per-source tally accumulated while walking the tree. */
26
+ class SourceTally {
27
+ constructor() {
28
+ this.entries = 0;
29
+ this.words = new Set();
30
+ this.phrases = new Set();
31
+ this.byPos = new Map();
32
+ }
33
+ add(text, pos) {
34
+ const norm = normalize(text);
35
+ if (!norm)
36
+ return;
37
+ this.entries++;
38
+ if (/\s/.test(norm))
39
+ this.phrases.add(norm);
40
+ else
41
+ this.words.add(norm);
42
+ const tag = pos && pos.trim() ? pos.trim() : UNTAGGED;
43
+ let set = this.byPos.get(tag);
44
+ if (!set) {
45
+ set = new Set();
46
+ this.byPos.set(tag, set);
47
+ }
48
+ set.add(norm);
49
+ }
50
+ counts() {
51
+ const byPartOfSpeech = {};
52
+ for (const tag of Array.from(this.byPos.keys()).sort((a, b) => a.localeCompare(b))) {
53
+ byPartOfSpeech[tag] = this.byPos.get(tag).size;
54
+ }
55
+ return {
56
+ entries: this.entries,
57
+ uniqueWords: this.words.size,
58
+ uniquePhrases: this.phrases.size,
59
+ byPartOfSpeech,
60
+ };
61
+ }
62
+ get wordSet() {
63
+ return this.words;
64
+ }
65
+ get phraseSet() {
66
+ return this.phrases;
67
+ }
68
+ }
69
+ /**
70
+ * Count the vocabulary available in a pageset, by source and part of speech.
71
+ * Emits counts only — no word lists.
72
+ *
73
+ * @example
74
+ * const processor = new GridsetProcessor();
75
+ * const tree = await processor.loadIntoTree('my.gridset');
76
+ * const metrics = new MetricsCalculator().analyze(tree);
77
+ * const dump = dumpVocabulary(tree, { metrics });
78
+ * console.log(dump.summary.wordLists.lists, 'wordlists');
79
+ */
80
+ export function dumpVocabulary(tree, options) {
81
+ const pages = Object.values(tree.pages);
82
+ const buttonTally = new SourceTally();
83
+ const wordListTally = new SourceTally();
84
+ const predictionTally = new SourceTally();
85
+ let wordListCount = 0;
86
+ let buttonsWithDictionaries = 0;
87
+ let totalButtons = 0;
88
+ for (const page of pages) {
89
+ totalButtons += page.buttons.length;
90
+ if (page.wordListItems && page.wordListItems.length > 0) {
91
+ wordListCount++;
92
+ for (const item of page.wordListItems) {
93
+ wordListTally.add(item.text, item.partOfSpeech);
94
+ }
95
+ }
96
+ for (const btn of page.buttons) {
97
+ const label = btn.label?.trim();
98
+ if (label) {
99
+ buttonTally.add(label, btn.pos);
100
+ }
101
+ // Prediction dictionaries: parameters.predictions keeps the original
102
+ // Prediction.PredictThis words even after analyze() expands
103
+ // btn.predictions with morphological forms.
104
+ const dict = btn.parameters?.predictions;
105
+ if (Array.isArray(dict) && dict.length > 0) {
106
+ buttonsWithDictionaries++;
107
+ for (const w of dict) {
108
+ if (typeof w === 'string') {
109
+ predictionTally.add(w, btn.pos);
110
+ }
111
+ }
112
+ }
113
+ }
114
+ }
115
+ // Smart-grammar word forms: inflected forms generated by MetricsCalculator
116
+ // (is_word_form buttons), excluding the original dictionary words they
117
+ // were generated from.
118
+ let wordForms = null;
119
+ let formTally = null;
120
+ if (options?.metrics) {
121
+ const originals = new Set();
122
+ for (const page of pages) {
123
+ for (const btn of page.buttons) {
124
+ const dict = btn.parameters?.predictions;
125
+ if (Array.isArray(dict)) {
126
+ for (const w of dict) {
127
+ if (typeof w === 'string') {
128
+ const norm = normalize(w);
129
+ if (norm)
130
+ originals.add(norm);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ formTally = new SourceTally();
137
+ const parents = new Set();
138
+ const seen = new Set();
139
+ for (const b of options.metrics.buttons) {
140
+ if (!b.is_word_form)
141
+ continue;
142
+ const norm = normalize(b.label);
143
+ if (!norm || seen.has(norm) || originals.has(norm))
144
+ continue;
145
+ seen.add(norm);
146
+ formTally.add(b.label, b.pos);
147
+ if (b.parent_button_id)
148
+ parents.add(b.parent_button_id);
149
+ }
150
+ wordForms = { ...formTally.counts(), parentButtons: parents.size };
151
+ }
152
+ const combinedWords = new Set([
153
+ ...buttonTally.wordSet,
154
+ ...wordListTally.wordSet,
155
+ ...predictionTally.wordSet,
156
+ ...(formTally ? formTally.wordSet : []),
157
+ ]);
158
+ const combinedPhrases = new Set([
159
+ ...buttonTally.phraseSet,
160
+ ...wordListTally.phraseSet,
161
+ ...predictionTally.phraseSet,
162
+ ]);
163
+ return {
164
+ schema: 'aac-vocabulary-dump/v1',
165
+ generatedAt: new Date().toISOString(),
166
+ source: {
167
+ format: tree.metadata?.format,
168
+ name: tree.metadata?.name,
169
+ locale: tree.metadata?.locale,
170
+ },
171
+ summary: {
172
+ totalBoards: pages.length,
173
+ totalButtons,
174
+ buttons: buttonTally.counts(),
175
+ wordLists: { ...wordListTally.counts(), lists: wordListCount },
176
+ predictionDictionaries: {
177
+ ...predictionTally.counts(),
178
+ buttonsWithDictionaries,
179
+ },
180
+ wordForms,
181
+ combined: {
182
+ uniqueEntries: combinedWords.size + combinedPhrases.size,
183
+ uniqueWords: combinedWords.size,
184
+ uniquePhrases: combinedPhrases.size,
185
+ },
186
+ },
187
+ };
188
+ }
package/dist/cli/index.js CHANGED
@@ -6,6 +6,7 @@ const prettyPrint_1 = require("./prettyPrint");
6
6
  const analyze_1 = require("../core/analyze");
7
7
  const history_1 = require("../utilities/analytics/history");
8
8
  const analytics_1 = require("../utilities/analytics");
9
+ const zip_1 = require("../utils/zip");
9
10
  const aac_1 = require("../types/aac");
10
11
  const io_1 = require("../utils/io");
11
12
  const node_fs_1 = require("node:fs");
@@ -28,6 +29,26 @@ async function detectFormat(filePath) {
28
29
  if (filePath.endsWith('.gtbz')) {
29
30
  return 'gotalknow';
30
31
  }
32
+ // GoTalk NOW share exports keep their book suffix before the archive
33
+ // extension ("MyBook.gotalk-book.zip") — route on the book suffix.
34
+ if (/\.gotalk-book(\.|$)/i.test(filePath)) {
35
+ return 'gotalknow';
36
+ }
37
+ // Bare .zip: sniff the archive for GoTalk NOW plists (root or nested
38
+ // <BookName>.gotalk-book/ folder). Other zip-based formats (.obz, .spb,
39
+ // .gridset) always arrive with their own extension.
40
+ if (filePath.toLowerCase().endsWith('.zip')) {
41
+ try {
42
+ const zip = await (0, zip_1.getZipAdapter)(filePath, io_1.defaultFileAdapter);
43
+ const files = zip.listFiles();
44
+ const hasGoTalkPlists = files.some((f) => !f.startsWith('__MACOSX/') && /(^|\/)PageData\.plist$/.test(f.replace(/\\/g, '/')));
45
+ if (hasGoTalkPlists)
46
+ return 'gotalknow';
47
+ }
48
+ catch {
49
+ /* not a readable zip — fall through to extension-based detection */
50
+ }
51
+ }
31
52
  // Otherwise use file extension
32
53
  return (0, io_1.extname)(filePath).slice(1);
33
54
  }
@@ -438,6 +459,64 @@ commander_1.program
438
459
  process.exit(1);
439
460
  }
440
461
  });
462
+ commander_1.program
463
+ .command('vocabulary <file>')
464
+ .description('Counts-only vocabulary inventory: buttons, wordlists, prediction dictionaries and word forms (no word lists are emitted)')
465
+ .option('--format <format>', 'Format type (auto-detected if not specified)')
466
+ .option('--out <path>', 'Write output to a file instead of stdout')
467
+ .option('--preserve-all-buttons', 'Preserve all buttons including navigation/system buttons')
468
+ .option('--no-exclude-navigation', "Don't exclude navigation buttons (Home, Back)")
469
+ .option('--no-exclude-system', "Don't exclude system buttons (Delete, Clear, etc.)")
470
+ .option('--exclude-buttons <list>', 'Comma-separated list of button labels/terms to exclude')
471
+ .option('--gridset-password <password>', 'Password for encrypted Grid3 archives (.gridsetx)')
472
+ .option('--no-smart-grammar', 'Skip smart-grammar word-form counts')
473
+ .action(async (file, options) => {
474
+ try {
475
+ const filteringOptions = parseFilteringOptions(options);
476
+ const format = options.format || (await detectFormat(file));
477
+ const processor = (0, analyze_1.getProcessor)(format, filteringOptions);
478
+ // The gridset loader logs debug chatter to stdout; silence it so the
479
+ // command's stdout is exactly one JSON document.
480
+ const silenced = Object.entries(console).reduce((acc, [k, fn]) => {
481
+ acc[k] = fn;
482
+ return acc;
483
+ }, {});
484
+ for (const k of ['log', 'info', 'debug', 'warn']) {
485
+ console[k] = () => { };
486
+ }
487
+ let dump;
488
+ try {
489
+ const tree = await processor.loadIntoTree(file);
490
+ // analyze() first: it expands morphological predictions on the tree,
491
+ // which dumpVocabulary() needs for the word-form counts.
492
+ const metrics = new analytics_1.MetricsCalculator().analyze(tree, {
493
+ useSmartGrammar: options.smartGrammar,
494
+ });
495
+ dump = (0, analytics_1.dumpVocabulary)(tree, { metrics });
496
+ }
497
+ finally {
498
+ for (const [k, fn] of Object.entries(silenced)) {
499
+ console[k] = fn;
500
+ }
501
+ }
502
+ const result = {
503
+ format,
504
+ filtering: filteringOptions,
505
+ vocabulary: dump,
506
+ };
507
+ const output = JSON.stringify(result, null, 2);
508
+ if (options.out) {
509
+ await writeTextToPath(options.out, output);
510
+ }
511
+ else {
512
+ console.log(output);
513
+ }
514
+ }
515
+ catch (error) {
516
+ console.error('Error dumping vocabulary:', error instanceof Error ? error.message : String(error));
517
+ process.exit(1);
518
+ }
519
+ });
441
520
  // Show help if no command provided
442
521
  if (process.argv.length <= 2) {
443
522
  commander_1.program.help();
@@ -49,6 +49,7 @@ function getProcessor(format, options) {
49
49
  case 'gotalknow':
50
50
  case 'gotalk':
51
51
  case 'gtbz': // GoTalk NOW file extension
52
+ case 'gotalk-book': // GoTalk NOW share export (e.g. "MyBook.gotalk-book.zip")
52
53
  return new gotalkNowProcessor_1.GotalkNowProcessor(options);
53
54
  default:
54
55
  throw new Error('Unknown format: ' + format);
@@ -96,6 +96,12 @@ function getProcessor(filePathOrExtension, options) {
96
96
  const extension = filePathOrExtension.includes('.')
97
97
  ? filePathOrExtension.substring(filePathOrExtension.lastIndexOf('.'))
98
98
  : filePathOrExtension;
99
+ // GoTalk NOW share exports keep their book suffix before the archive
100
+ // extension (e.g. "MyBook.gotalk-book.zip"), so match on the name, not the
101
+ // final extension.
102
+ if (/\.gotalk-book(\.|$)/i.test(filePathOrExtension)) {
103
+ return new gotalkNowProcessor_2.GotalkNowProcessor(options);
104
+ }
99
105
  switch (extension.toLowerCase()) {
100
106
  case '.dot':
101
107
  return new dotProcessor_2.DotProcessor(options);
@@ -138,6 +144,7 @@ function getSupportedExtensions() {
138
144
  '.plist',
139
145
  '.grd',
140
146
  '.gtbz',
147
+ '.gotalk-book',
141
148
  ];
142
149
  }
143
150
  /**
@@ -102,6 +102,12 @@ function getProcessor(filePathOrExtension, options) {
102
102
  const extension = filePathOrExtension.includes('.')
103
103
  ? filePathOrExtension.substring(filePathOrExtension.lastIndexOf('.'))
104
104
  : filePathOrExtension;
105
+ // GoTalk NOW share exports keep their book suffix before the archive
106
+ // extension (e.g. "MyBook.gotalk-book.zip"), so match on the name, not the
107
+ // final extension.
108
+ if (/\.gotalk-book(\.|$)/i.test(filePathOrExtension)) {
109
+ return new gotalkNowProcessor_1.GotalkNowProcessor(options);
110
+ }
105
111
  switch (extension.toLowerCase()) {
106
112
  case '.dot':
107
113
  return new dotProcessor_1.DotProcessor(options);
@@ -152,6 +158,7 @@ function getSupportedExtensions() {
152
158
  '.plist',
153
159
  '.grd',
154
160
  '.gtbz',
161
+ '.gotalk-book',
155
162
  ];
156
163
  }
157
164
  /**
package/dist/metrics.d.ts CHANGED
@@ -10,6 +10,8 @@ export * from './utilities/analytics/metrics/obl-types';
10
10
  export { OblUtil, OblAnonymizer } from './utilities/analytics/metrics/obl';
11
11
  export { MetricsCalculator } from './utilities/analytics/metrics/core';
12
12
  export { VocabularyAnalyzer } from './utilities/analytics/metrics/vocabulary';
13
+ export { dumpVocabulary } from './utilities/analytics/metrics/vocabularyDump';
14
+ export type { VocabularyDump, VocabularyDumpOptions, VocabularySourceCounts, VocabularySummary, } from './utilities/analytics/metrics/vocabularyDump';
13
15
  export { SentenceAnalyzer } from './utilities/analytics/metrics/sentence';
14
16
  export { ComparisonAnalyzer } from './utilities/analytics/metrics/comparison';
15
17
  export { MorphologyEngine } from './utilities/analytics/morphology';
package/dist/metrics.js CHANGED
@@ -20,7 +20,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
20
20
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
21
21
  };
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.loadReferenceDataFromUrl = exports.createBrowserReferenceLoader = exports.InMemoryReferenceLoader = exports.ReferenceLoader = exports.WordFormGenerator = exports.MorphologyEngine = exports.ComparisonAnalyzer = exports.SentenceAnalyzer = exports.VocabularyAnalyzer = exports.MetricsCalculator = exports.OblAnonymizer = exports.OblUtil = void 0;
23
+ exports.loadReferenceDataFromUrl = exports.createBrowserReferenceLoader = exports.InMemoryReferenceLoader = exports.ReferenceLoader = exports.WordFormGenerator = exports.MorphologyEngine = exports.ComparisonAnalyzer = exports.SentenceAnalyzer = exports.dumpVocabulary = exports.VocabularyAnalyzer = exports.MetricsCalculator = exports.OblAnonymizer = exports.OblUtil = void 0;
24
24
  __exportStar(require("./utilities/analytics/metrics/types"), exports);
25
25
  __exportStar(require("./utilities/analytics/metrics/effort"), exports);
26
26
  __exportStar(require("./utilities/analytics/metrics/obl-types"), exports);
@@ -31,6 +31,8 @@ var core_1 = require("./utilities/analytics/metrics/core");
31
31
  Object.defineProperty(exports, "MetricsCalculator", { enumerable: true, get: function () { return core_1.MetricsCalculator; } });
32
32
  var vocabulary_1 = require("./utilities/analytics/metrics/vocabulary");
33
33
  Object.defineProperty(exports, "VocabularyAnalyzer", { enumerable: true, get: function () { return vocabulary_1.VocabularyAnalyzer; } });
34
+ var vocabularyDump_1 = require("./utilities/analytics/metrics/vocabularyDump");
35
+ Object.defineProperty(exports, "dumpVocabulary", { enumerable: true, get: function () { return vocabularyDump_1.dumpVocabulary; } });
34
36
  var sentence_1 = require("./utilities/analytics/metrics/sentence");
35
37
  Object.defineProperty(exports, "SentenceAnalyzer", { enumerable: true, get: function () { return sentence_1.SentenceAnalyzer; } });
36
38
  var comparison_1 = require("./utilities/analytics/metrics/comparison");
@@ -17,6 +17,13 @@
17
17
  * - Backup-<n>.zip – rolling backups
18
18
  * - REQUIRESREGEN – marker file
19
19
  *
20
+ * Two on-disk variants exist and both are accepted:
21
+ * - `.gtbz` app backups: plists at the ZIP root.
22
+ * - `.gotalk-book` share exports (often `.zip`-suffixed): everything nested
23
+ * under a `<BookName>.gotalk-book/` folder, possibly alongside `__MACOSX/`
24
+ * resource-fork entries (ignored). Button images are pre-rendered
25
+ * snapshots named `<page>-<button>-<buttonCount>.png`.
26
+ *
20
27
  * Colours and fonts in PageData are NSKeyedArchiver-encoded binary plists
21
28
  * carried inside `<data>` tags. They are treated as opaque blobs and preserved
22
29
  * verbatim so that only text fields are touched during translation.
@@ -32,6 +39,13 @@ declare class GotalkNowProcessor extends BaseProcessor {
32
39
  };
33
40
  constructor(options?: ProcessorOptions);
34
41
  private openZip;
42
+ /**
43
+ * Resolve a plist entry name inside the archive, tolerating both layout
44
+ * variants: `.gtbz` (plists at ZIP root) and `.gotalk-book` share exports
45
+ * (plists nested under a `<BookName>.gotalk-book/` folder). `__MACOSX`
46
+ * resource-fork entries are ignored. Returns the full entry name, or null.
47
+ */
48
+ private resolveEntryName;
35
49
  private readPlistFromZip;
36
50
  extractTexts(filePathOrBuffer: ProcessorInput): Promise<string[]>;
37
51
  loadIntoTree(filePathOrBuffer: ProcessorInput): Promise<AACTree>;
@@ -18,6 +18,13 @@
18
18
  * - Backup-<n>.zip – rolling backups
19
19
  * - REQUIRESREGEN – marker file
20
20
  *
21
+ * Two on-disk variants exist and both are accepted:
22
+ * - `.gtbz` app backups: plists at the ZIP root.
23
+ * - `.gotalk-book` share exports (often `.zip`-suffixed): everything nested
24
+ * under a `<BookName>.gotalk-book/` folder, possibly alongside `__MACOSX/`
25
+ * resource-fork entries (ignored). Button images are pre-rendered
26
+ * snapshots named `<page>-<button>-<buttonCount>.png`.
27
+ *
21
28
  * Colours and fonts in PageData are NSKeyedArchiver-encoded binary plists
22
29
  * carried inside `<data>` tags. They are treated as opaque blobs and preserved
23
30
  * verbatim so that only text fields are touched during translation.
@@ -45,7 +52,8 @@ function buildSemanticAction(rawButton, pageId, buttonIndex) {
45
52
  switch (buttonType) {
46
53
  case 'Jump': {
47
54
  const jumpTo = actionData.JumpTo;
48
- const target = jumpTo !== undefined ? String(jumpTo) : undefined;
55
+ // GoTalk treats 0 / -1 / "" as "no jump configured".
56
+ const target = !isNoJumpTarget(jumpTo) ? String(jumpTo) : undefined;
49
57
  return {
50
58
  semanticAction: {
51
59
  category: treeStructure_1.AACSemanticCategory.NAVIGATION,
@@ -54,7 +62,7 @@ function buildSemanticAction(rawButton, pageId, buttonIndex) {
54
62
  platformData: {
55
63
  gotalkNow: { buttonType: 'Jump', jumpTo, jumpBook: actionData.JumpBook },
56
64
  },
57
- fallback: { type: 'NAVIGATE', targetPageId: target },
65
+ fallback: target ? { type: 'NAVIGATE', targetPageId: target } : { type: 'ACTION' },
58
66
  },
59
67
  message: '',
60
68
  targetPageId: target,
@@ -163,12 +171,62 @@ function buildSemanticAction(rawButton, pageId, buttonIndex) {
163
171
  }
164
172
  }
165
173
  /**
166
- * Derive a square-ish grid layout from the declared button count.
167
- * GoTalk NOW uses fixed layouts (1, 4, 9, 16, 25, 36 …).
174
+ * Derive a GoTalk NOW layout from the declared button count.
175
+ * GoTalk NOW uses fixed square layouts (1, 4, 9, 16, 25, 36 …); when the
176
+ * count is not a perfect square (alternate/custom layouts), fall back to a
177
+ * near-square rectangle: cols = ceil(sqrt(n)), rows = ceil(n / cols).
168
178
  */
169
179
  function gridDimensionsFromButtonCount(count) {
170
- const side = Math.max(1, Math.ceil(Math.sqrt(Math.max(count, 1))));
171
- return { rows: side, cols: side };
180
+ const n = Math.max(count, 1);
181
+ const side = Math.ceil(Math.sqrt(n));
182
+ return { rows: Math.ceil(n / side), cols: side };
183
+ }
184
+ /** GoTalk treats JumpTo 0 / -1 / "" as "no jump". */
185
+ function isNoJumpTarget(value) {
186
+ return (value === undefined ||
187
+ value === null ||
188
+ value === 0 ||
189
+ value === -1 ||
190
+ value === '' ||
191
+ value === '0' ||
192
+ value === '-1');
193
+ }
194
+ /** Normalise a zip or iOS-container path to a lowercase basename. */
195
+ function basenameLower(p) {
196
+ if (!p)
197
+ return null;
198
+ const base = p.replace(/\\/g, '/').split('/').pop() || '';
199
+ const trimmed = base.trim().toLowerCase();
200
+ return trimmed.length > 0 ? trimmed : null;
201
+ }
202
+ /**
203
+ * Resolve a bundled image for a button against the archive's file list.
204
+ *
205
+ * `Location`/`QuickRecoveryPath` values are iOS app-container paths that never
206
+ * match archive entry names verbatim, so candidates are matched by basename
207
+ * (case-insensitive), with extension guessing when the name has none.
208
+ */
209
+ function findZipImageEntry(zipBasenames, candidates) {
210
+ const tried = new Set();
211
+ for (const candidate of candidates) {
212
+ const base = basenameLower(candidate);
213
+ if (!base || tried.has(base))
214
+ continue;
215
+ tried.add(base);
216
+ // 1. Exact basename match.
217
+ const direct = zipBasenames.get(base);
218
+ if (direct) {
219
+ const ext = base.includes('.') ? base.slice(base.lastIndexOf('.')) : '.png';
220
+ return { entry: direct, ext };
221
+ }
222
+ // 2. Try common image extensions.
223
+ for (const ext of ['.png', '.jpg', '.jpeg', '.bmp']) {
224
+ const hit = zipBasenames.get(base + ext);
225
+ if (hit)
226
+ return { entry: hit, ext };
227
+ }
228
+ }
229
+ return null;
172
230
  }
173
231
  // ---------------------------------------------------------------------------
174
232
  // Processor
@@ -187,14 +245,27 @@ class GotalkNowProcessor extends baseProcessor_1.BaseProcessor {
187
245
  const zip = await this.options.zipAdapter(filePathOrBuffer, this.options.fileAdapter);
188
246
  return zip;
189
247
  }
190
- async readPlistFromZip(zip, name, fallback) {
191
- const files = zip.listFiles();
192
- if (!files.includes(name)) {
248
+ /**
249
+ * Resolve a plist entry name inside the archive, tolerating both layout
250
+ * variants: `.gtbz` (plists at ZIP root) and `.gotalk-book` share exports
251
+ * (plists nested under a `<BookName>.gotalk-book/` folder). `__MACOSX`
252
+ * resource-fork entries are ignored. Returns the full entry name, or null.
253
+ */
254
+ resolveEntryName(files, basename, prefix) {
255
+ const rooted = `${prefix}${basename}`;
256
+ if (files.includes(rooted))
257
+ return rooted;
258
+ // Nested variant: find the (non-__MACOSX) entry ending in /<basename>.
259
+ const matches = files.filter((f) => f !== `__MACOSX` && !f.startsWith('__MACOSX/') && f.endsWith(`/${basename}`));
260
+ return matches.length > 0 ? matches[0] : null;
261
+ }
262
+ async readPlistFromZip(zip, name, resolvedName, fallback) {
263
+ if (!resolvedName) {
193
264
  if (fallback)
194
265
  return fallback();
195
266
  throw new Error(`GoTalk NOW archive is missing ${name}`);
196
267
  }
197
- const bytes = await zip.readFile(name);
268
+ const bytes = await zip.readFile(resolvedName);
198
269
  const text = typeof Buffer !== 'undefined' && Buffer.isBuffer(bytes)
199
270
  ? bytes.toString('utf8')
200
271
  : new TextDecoder().decode(bytes);
@@ -227,9 +298,13 @@ class GotalkNowProcessor extends baseProcessor_1.BaseProcessor {
227
298
  let bookInfoValue;
228
299
  try {
229
300
  zip = await this.openZip(filePathOrBuffer);
230
- pageDataValue = await this.readPlistFromZip(zip, 'PageData.plist');
231
- pageOrderValue = await this.readPlistFromZip(zip, 'PageOrder.plist', () => []);
232
- bookInfoValue = await this.readPlistFromZip(zip, 'BookInfo.plist', () => ({}));
301
+ // Resolve plist locations once; shared by load/processTexts round-trip.
302
+ const files = zip.listFiles();
303
+ const pdEntry = this.resolveEntryName(files, 'PageData.plist', '');
304
+ const prefix = pdEntry ? pdEntry.slice(0, -'PageData.plist'.length) : '';
305
+ pageDataValue = await this.readPlistFromZip(zip, 'PageData.plist', pdEntry);
306
+ pageOrderValue = await this.readPlistFromZip(zip, 'PageOrder.plist', this.resolveEntryName(files, 'PageOrder.plist', prefix), () => []);
307
+ bookInfoValue = await this.readPlistFromZip(zip, 'BookInfo.plist', this.resolveEntryName(files, 'BookInfo.plist', prefix), () => ({}));
233
308
  }
234
309
  catch (err) {
235
310
  if (err instanceof validationTypes_1.ValidationFailureError)
@@ -268,6 +343,16 @@ class GotalkNowProcessor extends baseProcessor_1.BaseProcessor {
268
343
  }
269
344
  // Track available image files so we can resolve ButtonImages locations.
270
345
  const zipFiles = new Set(zip.listFiles());
346
+ // Basename (lowercase, non-__MACOSX) -> full entry name, for tolerant
347
+ // matching of bundled images in .gotalk-book share exports.
348
+ const zipBasenames = new Map();
349
+ for (const f of zipFiles) {
350
+ if (f.startsWith('__MACOSX/') || f.endsWith('/'))
351
+ continue;
352
+ const base = basenameLower(f);
353
+ if (base && !zipBasenames.has(base))
354
+ zipBasenames.set(base, f);
355
+ }
271
356
  // Build pages. Use the union of PageData keys and PageOrder ids.
272
357
  const allPageIds = new Set([...Object.keys(pageData), ...orderedPageIds]);
273
358
  // Deterministic ordering: ordered pages first (in order), then any extras sorted numerically.
@@ -317,7 +402,10 @@ class GotalkNowProcessor extends baseProcessor_1.BaseProcessor {
317
402
  const buttonsById = rawPage.Buttons || {};
318
403
  // Numeric sort of button indices ("0","1",…,"10",…)
319
404
  const buttonIndices = Object.keys(buttonsById).sort((a, b) => Number(a) - Number(b));
320
- const buttonCount = rawPage.ButtonCount ?? buttonIndices.length;
405
+ // Sparse button maps: the grid size is max(index)+1, not the number of
406
+ // keys (GoTalk snapshots and layouts are sized by the highest slot).
407
+ const buttonCount = rawPage.ButtonCount ??
408
+ (buttonIndices.length > 0 ? Math.max(...buttonIndices.map(Number)) + 1 : 0);
321
409
  const { rows, cols } = gridDimensionsFromButtonCount(buttonCount);
322
410
  const gridLayout = Array.from({ length: rows }, () => Array.from({ length: cols }, () => null));
323
411
  buttonIndices.forEach((btnIndex, i) => {
@@ -347,19 +435,47 @@ class GotalkNowProcessor extends baseProcessor_1.BaseProcessor {
347
435
  };
348
436
  }
349
437
  // Resolve image metadata.
350
- const images = rawButton.ButtonImages;
351
- if (Array.isArray(images) && images.length > 0) {
352
- const first = images[0];
353
- if (first?.Location) {
354
- button.image = first.Location;
355
- if (zipFiles.has(first.Location)) {
356
- button.resolvedImageEntry = first.Location;
438
+ // Heuristics (from real .gotalk-book share exports):
439
+ // - entries sourced from the app's bundled "GoTalk Image Library"
440
+ // are clip-art, not user content — skip them;
441
+ // - prefer the entry carrying QuickRecoveryPath; with multiple
442
+ // entries the second one is the user's image;
443
+ // - bundled files are matched by basename (Location/QRP are iOS
444
+ // container paths, never archive entry names);
445
+ // - last resort: the pre-rendered snapshot <page>-<btn>-<count>.png.
446
+ const imagesAll = rawButton.ButtonImages;
447
+ const images = Array.isArray(imagesAll)
448
+ ? imagesAll.filter((im) => (im?.SourceLibrary || '') !== 'GoTalk Image Library')
449
+ : [];
450
+ if (images.length > 0) {
451
+ const selected = images.find((im) => im.QuickRecoveryPath !== undefined) ??
452
+ (images.length >= 2 ? images[1] : images[0]);
453
+ if (selected) {
454
+ const sourceLibrary = (selected.SourceLibrary || '').toLowerCase();
455
+ const sourceImageName = selected.SourceImageName || '';
456
+ const isLibrarySymbol = /metacom|pcs|symbolstix|widgit/.test(sourceLibrary) && sourceImageName.length > 0;
457
+ if (selected.Location)
458
+ button.image = selected.Location;
459
+ if (selected.SourceLibrary)
460
+ button.symbolLibrary = selected.SourceLibrary;
461
+ if (sourceImageName)
462
+ button.symbolPath = sourceImageName;
463
+ if (!isLibrarySymbol) {
464
+ const bundled = findZipImageEntry(zipBasenames, [
465
+ selected.QuickRecoveryPath,
466
+ selected.Location,
467
+ selected.SourceImageName,
468
+ `${pageId}-${btnIndex}-${buttonCount}.png`,
469
+ ]);
470
+ if (bundled) {
471
+ button.image = bundled.entry;
472
+ button.resolvedImageEntry = bundled.entry;
473
+ }
474
+ }
475
+ else if (zipFiles.has(selected.Location || '')) {
476
+ button.resolvedImageEntry = selected.Location;
357
477
  }
358
478
  }
359
- if (first?.SourceLibrary)
360
- button.symbolLibrary = first.SourceLibrary;
361
- if (first?.SourceImageName)
362
- button.symbolPath = first.SourceImageName;
363
479
  }
364
480
  // Visibility: GoTalk buttons can be disabled via either field.
365
481
  if (rawButton.Enabled === false || rawButton.Disabled === true) {
@@ -413,8 +529,12 @@ class GotalkNowProcessor extends baseProcessor_1.BaseProcessor {
413
529
  async processTexts(filePathOrBuffer, translations, outputPath) {
414
530
  const { writeBinaryToPath } = this.options.fileAdapter;
415
531
  const originalZip = await this.openZip(filePathOrBuffer);
416
- // Parse PageData and apply translations in place.
417
- const pageDataBytes = await originalZip.readFile('PageData.plist');
532
+ // Parse PageData and apply translations in place. Locate the plist the
533
+ // same tolerant way loadIntoTree does (root or nested .gotalk-book folder)
534
+ // and write it back under its original entry name so the layout survives.
535
+ const files = originalZip.listFiles();
536
+ const pdEntry = this.resolveEntryName(files, 'PageData.plist', '') ?? 'PageData.plist';
537
+ const pageDataBytes = await originalZip.readFile(pdEntry);
418
538
  const pageDataText = typeof Buffer !== 'undefined' && Buffer.isBuffer(pageDataBytes)
419
539
  ? pageDataBytes.toString('utf8')
420
540
  : new TextDecoder().decode(pageDataBytes);
@@ -441,14 +561,14 @@ class GotalkNowProcessor extends baseProcessor_1.BaseProcessor {
441
561
  const rebuiltPageData = plist_1.default.build(pageData);
442
562
  // Repack: copy every original entry verbatim, replacing only PageData.plist.
443
563
  const outputZip = await this.options.zipAdapter(undefined, this.options.fileAdapter);
444
- const files = [];
564
+ const filesOut = [];
445
565
  for (const name of originalZip.listFiles()) {
446
- if (name === 'PageData.plist')
566
+ if (name === pdEntry)
447
567
  continue;
448
- files.push({ name, data: await originalZip.readFile(name) });
568
+ filesOut.push({ name, data: await originalZip.readFile(name) });
449
569
  }
450
- files.push({ name: 'PageData.plist', data: rebuiltPageData });
451
- const outputBuffer = await outputZip.writeFiles(files);
570
+ filesOut.push({ name: pdEntry, data: rebuiltPageData });
571
+ const outputBuffer = await outputZip.writeFiles(filesOut);
452
572
  await writeBinaryToPath(outputPath, outputBuffer);
453
573
  return outputBuffer;
454
574
  }