@keymanapp/kmc-model 17.0.299-beta → 17.0.301-beta

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.
@@ -1,377 +1,378 @@
1
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c66d9ba3-d3be-5f6f-acdc-2b7f248aaddd")}catch(e){}}();
2
- import { ModelCompilerError, ModelCompilerMessageContext, ModelCompilerMessages } from "./model-compiler-messages.js";
3
- import { callbacks } from "./compiler-callbacks.js";
4
- // Supports LF or CRLF line terminators.
5
- const NEWLINE_SEPARATOR = /\u000d?\u000a/;
6
- /**
7
- * Returns a data structure that can be loaded by the TrieModel.
8
- *
9
- * It implements a **weighted** trie, whose indices (paths down the trie) are
10
- * generated by a search key, and not concrete wordforms themselves.
11
- *
12
- * @param sourceFiles an array of source files that will be read to generate the trie.
13
- */
14
- export function createTrieDataStructure(filenames, searchTermToKey) {
15
- if (typeof searchTermToKey !== "function") {
16
- throw new ModelCompilerError(ModelCompilerMessages.Error_SearchTermToKeyMustBeExplicitlySpecified());
17
- }
18
- // Make one big word list out of all of the filenames provided.
19
- let wordlist = {};
20
- filenames.forEach(filename => parseWordListFromFilename(wordlist, filename));
21
- let trie = Trie.buildTrie(wordlist, searchTermToKey);
22
- return JSON.stringify(trie);
23
- }
24
- /**
25
- * Parses a word list from a file, merging duplicate entries.
26
- *
27
- * The word list may be encoded in:
28
- *
29
- * - UTF-8, with or without BOM [exported by most software]
30
- * - UTF-16, little endian, with BOM [exported by Microsoft Excel]
31
- *
32
- * @param wordlist word list to merge entries into (may have existing entries)
33
- * @param filename filename of the word list
34
- */
35
- export function parseWordListFromFilename(wordlist, filename) {
36
- ModelCompilerMessageContext.filename = filename;
37
- _parseWordList(wordlist, new WordListFromFilename(filename));
38
- }
39
- /**
40
- * Parses a word list from a string. The string should have multiple lines
41
- * with LF or CRLF line terminators.
42
- *
43
- * @param wordlist word list to merge entries into (may have existing entries)
44
- * @param filename filename of the word list
45
- */
46
- export function parseWordListFromContents(wordlist, contents) {
47
- ModelCompilerMessageContext.filename = undefined;
48
- _parseWordList(wordlist, new WordListFromMemory(contents));
49
- }
50
- /**
51
- * Reads a tab-separated values file into a word list. This function converts all
52
- * entries into NFC and merges duplicate entries across wordlists. Duplication is
53
- * on the basis of character-for-character equality after normalisation to NFC.
54
- *
55
- * Format specification:
56
- *
57
- * - the file is a UTF-8 encoded text file.
58
- * - new lines are either LF or CRLF.
59
- * - the file MAY start with the UTF-8 byte-order mark (BOM); that is, if the
60
- * first three bytes of the file are EF BB BF, these will be interepreted as
61
- * the BOM and will be ignored.
62
- * - the file either consists of a comment or an entry.
63
- * - comment lines MUST start with the '#' character on the very first column.
64
- * - entries are one to three columns, separated by the (horizontal) tab
65
- * character.
66
- * - column 1 (REQUIRED): the wordform: can have any character except tab, CR,
67
- * LF. Surrounding whitespace characters are trimmed.
68
- * - column 2 (optional): the count: a non-negative integer specifying how many
69
- * times this entry has appeared in the corpus. Blank means 'indeterminate';
70
- * commas are permissible in the digits.
71
- * - column 3 (optional): comment: an informative comment, ignored by the tool.
72
- *
73
- * @param wordlist word list to merge entries into (may have existing entries)
74
- * @param contents contents of the file to import
75
- */
76
- function _parseWordList(wordlist, source) {
77
- const TAB = "\t";
78
- let wordsSeenInThisFile = new Set();
79
- for (let [lineno, line] of source.lines()) {
80
- ModelCompilerMessageContext.line = lineno;
81
- // Remove the byte-order mark (BOM) from the beginning of the string.
82
- // Because `contents` can be the concatenation of several files, we have to remove
83
- // the BOM from every possible start of file -- i.e., beginning of every line.
84
- line = line.replace(/^\uFEFF/, '').trim();
85
- if (line.startsWith('#') || line === "") {
86
- continue; // skip comments and empty lines
87
- }
88
- // The third column is the comment. Always ignored!
89
- let [wordform, countText] = line.split(TAB);
90
- // Clean the word form.
91
- let original = wordform;
92
- wordform = wordform.normalize('NFC');
93
- if (original !== wordform) {
94
- // Mixed normalization forms are yucky! Hint about it, because it may
95
- // result in unexpected counts where multiple normalization forms for one
96
- // word
97
- callbacks.reportMessage(ModelCompilerMessages.Hint_MixedNormalizationForms({ wordform: wordform }));
98
- }
99
- wordform = wordform.trim();
100
- countText = (countText || '').trim().replace(/,/g, '');
101
- let count = parseInt(countText, 10);
102
- // When parsing a decimal integer fails (e.g., blank or something else):
103
- if (!isFinite(count) || count < 0) {
104
- // TODO: is this the right thing to do?
105
- // Treat it like a hapax legonmenom -- it exist, but only once.
106
- count = 1;
107
- }
108
- if (wordsSeenInThisFile.has(wordform)) {
109
- // The same word seen across multiple files is fine, but a word seen
110
- // multiple times in one file may be a problem
111
- callbacks.reportMessage(ModelCompilerMessages.Hint_DuplicateWordInSameFile({ wordform: wordform }));
112
- }
113
- wordsSeenInThisFile.add(wordform);
114
- wordlist[wordform] = (isNaN(wordlist[wordform]) ? 0 : wordlist[wordform] || 0) + count;
115
- }
116
- }
117
- class WordListFromMemory {
118
- name = '<memory>';
119
- _contents;
120
- constructor(contents) {
121
- this._contents = contents;
122
- }
123
- *lines() {
124
- yield* enumerateLines(this._contents.split(NEWLINE_SEPARATOR));
125
- }
126
- }
127
- class WordListFromFilename {
128
- name;
129
- constructor(filename) {
130
- this.name = filename;
131
- }
132
- *lines() {
133
- const data = callbacks.loadFile(this.name);
134
- const contents = new TextDecoder(detectEncoding(data)).decode(data);
135
- yield* enumerateLines(contents.split(NEWLINE_SEPARATOR));
136
- }
137
- }
138
- /**
139
- * Yields pairs of [lineno, line], given an Array of lines.
140
- */
141
- function* enumerateLines(lines) {
142
- let i = 1;
143
- for (let line of lines) {
144
- yield [i, line];
145
- i++;
146
- }
147
- }
148
- var Trie;
149
- (function (Trie_1) {
150
- /**
151
- * A sentinel value for when an internal node has contents and requires an
152
- * "internal" leaf. That is, this internal node has content. Instead of placing
153
- * entries as children in an internal node, a "fake" leaf is created, and its
154
- * key is this special internal value.
155
- *
156
- * The value is a valid Unicode BMP code point, but it is a "non-character".
157
- * Unicode will never assign semantics to these characters, as they are
158
- * intended to be used internally as sentinel values.
159
- */
160
- const INTERNAL_VALUE = '\uFDD0';
161
- /**
162
- * Builds a trie from a word list.
163
- *
164
- * @param wordlist The wordlist with non-negative weights.
165
- * @param keyFunction Function that converts word forms into indexed search keys
166
- * @returns A JSON-serialiable object that can be given to the TrieModel constructor.
167
- */
168
- function buildTrie(wordlist, keyFunction) {
169
- let root = new Trie(keyFunction).buildFromWordList(wordlist).root;
170
- return {
171
- totalWeight: sumWeights(root),
172
- root: root
173
- };
174
- }
175
- Trie_1.buildTrie = buildTrie;
176
- /**
177
- * Wrapper class for the trie and its nodes and wordform to search
178
- */
179
- class Trie {
180
- root = createRootNode();
181
- toKey;
182
- constructor(wordform2key) {
183
- this.toKey = wordform2key;
184
- }
185
- /**
186
- * Populates the trie with the contents of an entire wordlist.
187
- * @param words a list of word and count pairs.
188
- */
189
- buildFromWordList(words) {
190
- for (let [wordform, weight] of Object.entries(words)) {
191
- let key = this.toKey(wordform);
192
- addUnsorted(this.root, { key, weight, content: wordform }, 0);
193
- }
194
- sortTrie(this.root);
195
- return this;
196
- }
197
- }
198
- // "Constructors"
199
- function createRootNode() {
200
- return {
201
- type: 'leaf',
202
- weight: 0,
203
- entries: []
204
- };
205
- }
206
- // Implement Trie creation.
207
- /**
208
- * Adds an entry to the trie.
209
- *
210
- * Note that the trie will likely be unsorted after the add occurs. Before
211
- * performing a lookup on the trie, use call sortTrie() on the root note!
212
- *
213
- * @param node Which node should the entry be added to?
214
- * @param entry the wordform/weight/key to add to the trie
215
- * @param index the index in the key and also the trie depth. Should be set to
216
- * zero when adding onto the root node of the trie.
217
- */
218
- function addUnsorted(node, entry, index = 0) {
219
- // Each node stores the MAXIMUM weight out of all of its decesdents, to
220
- // enable a greedy search through the trie.
221
- node.weight = Math.max(node.weight, entry.weight);
222
- // When should a leaf become an interior node?
223
- // When it already has a value, but the key of the current value is longer
224
- // than the prefix.
225
- if (node.type === 'leaf' && index < entry.key.length && node.entries.length >= 1) {
226
- convertLeafToInternalNode(node, index);
227
- }
228
- if (node.type === 'leaf') {
229
- // The key matches this leaf node, so add yet another entry.
230
- addItemToLeaf(node, entry);
231
- }
232
- else {
233
- // Push the node down to a lower node.
234
- addItemToInternalNode(node, entry, index);
235
- }
236
- node.unsorted = true;
237
- }
238
- /**
239
- * Adds an item to the internal node at a given depth.
240
- * @param item
241
- * @param index
242
- */
243
- function addItemToInternalNode(node, item, index) {
244
- let char = item.key[index];
245
- // If an internal node is the proper site for item, it belongs under the
246
- // corresponding (sentinel, internal-use) child node signifying this.
247
- if (char == undefined) {
248
- char = INTERNAL_VALUE;
249
- }
250
- if (!node.children[char]) {
251
- node.children[char] = createRootNode();
252
- node.values.push(char);
253
- }
254
- addUnsorted(node.children[char], item, index + 1);
255
- }
256
- function addItemToLeaf(leaf, item) {
257
- leaf.entries.push(item);
258
- }
259
- /**
260
- * Mutates the given Leaf to turn it into an InternalNode.
261
- *
262
- * NOTE: the node passed in will be DESTRUCTIVELY CHANGED into a different
263
- * type when passed into this function!
264
- *
265
- * @param depth depth of the trie at this level.
266
- */
267
- function convertLeafToInternalNode(leaf, depth) {
268
- let entries = leaf.entries;
269
- // Alias the current node, as the desired type.
270
- let internal = leaf;
271
- internal.type = 'internal';
272
- delete leaf.entries;
273
- internal.values = [];
274
- internal.children = {};
275
- // Convert the old values array into the format for interior nodes.
276
- for (let item of entries) {
277
- let char;
278
- if (depth < item.key.length) {
279
- char = item.key[depth];
280
- }
281
- else {
282
- char = INTERNAL_VALUE;
283
- }
284
- if (!internal.children[char]) {
285
- internal.children[char] = createRootNode();
286
- internal.values.push(char);
287
- }
288
- addUnsorted(internal.children[char], item, depth + 1);
289
- }
290
- internal.unsorted = true;
291
- }
292
- /**
293
- * Recursively sort the trie, in descending order of weight.
294
- * @param node any node in the trie
295
- */
296
- function sortTrie(node) {
297
- if (node.type === 'leaf') {
298
- if (!node.unsorted) {
299
- return;
300
- }
301
- node.entries.sort(function (a, b) { return b.weight - a.weight; });
302
- }
303
- else {
304
- // We MUST recurse and sort children before returning.
305
- for (let char of node.values) {
306
- sortTrie(node.children[char]);
307
- }
308
- if (!node.unsorted) {
309
- return;
310
- }
311
- node.values.sort((a, b) => {
312
- return node.children[b].weight - node.children[a].weight;
313
- });
314
- }
315
- delete node.unsorted;
316
- }
317
- /**
318
- * O(n) recursive traversal to sum the total weight of all leaves in the
319
- * trie, starting at the provided node.
320
- *
321
- * @param node The node to start summing weights.
322
- */
323
- function sumWeights(node) {
324
- let val;
325
- if (node.type === 'leaf') {
326
- val = node.entries
327
- .map(entry => entry.weight)
328
- //.map(entry => isNaN(entry.weight) ? 1 : entry.weight)
329
- .reduce((acc, count) => acc + count, 0);
330
- }
331
- else {
332
- val = Object.keys(node.children)
333
- .map((key) => sumWeights(node.children[key]))
334
- .reduce((acc, count) => acc + count, 0);
335
- }
336
- if (isNaN(val)) {
337
- throw new Error("Unexpected NaN has appeared!");
338
- }
339
- return val;
340
- }
341
- })(Trie || (Trie = {}));
342
- /**
343
- * Detects the encoding of a text file.
344
- *
345
- * Supported encodings are:
346
- *
347
- * - UTF-8, with or without BOM
348
- * - UTF-16, little endian, with BOM
349
- *
350
- * UTF-16 in big endian is explicitly NOT supported! The reason is two-fold:
351
- * 1) Node does not support it without resorting to an external library (or
352
- * swapping every byte in the file!); and 2) I'm not sure anything actually
353
- * outputs in this format anyway!
354
- *
355
- * @param filename filename of the file to detect encoding
356
- */
357
- function detectEncoding(buffer) {
358
- if (buffer.length < 2) {
359
- return 'utf-8';
360
- }
361
- // Note: BOM is U+FEFF
362
- // In little endian, this is 0xFF 0xFE
363
- if (buffer[0] == 0xFF && buffer[1] == 0xFE) {
364
- return 'utf-16le';
365
- }
366
- else if (buffer[0] == 0xFE && buffer[1] == 0xFF) {
367
- // Big Endian, is NOT supported because Node does not support it (???)
368
- // See: https://stackoverflow.com/a/14551669/6626414
369
- throw new ModelCompilerError(ModelCompilerMessages.Error_UTF16BEUnsupported());
370
- }
371
- else {
372
- // Assume its in UTF-8, with or without a BOM.
373
- return 'utf-8';
374
- }
375
- }
376
- //# debugId=c66d9ba3-d3be-5f6f-acdc-2b7f248aaddd
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8cd6afc4-7847-5c28-9696-377ec3527897")}catch(e){}}();
3
+ import { ModelCompilerError, ModelCompilerMessageContext, ModelCompilerMessages } from "./model-compiler-messages.js";
4
+ import { callbacks } from "./compiler-callbacks.js";
5
+ // Supports LF or CRLF line terminators.
6
+ const NEWLINE_SEPARATOR = /\u000d?\u000a/;
7
+ /**
8
+ * Returns a data structure that can be loaded by the TrieModel.
9
+ *
10
+ * It implements a **weighted** trie, whose indices (paths down the trie) are
11
+ * generated by a search key, and not concrete wordforms themselves.
12
+ *
13
+ * @param sourceFiles an array of source files that will be read to generate the trie.
14
+ */
15
+ export function createTrieDataStructure(filenames, searchTermToKey) {
16
+ if (typeof searchTermToKey !== "function") {
17
+ throw new ModelCompilerError(ModelCompilerMessages.Error_SearchTermToKeyMustBeExplicitlySpecified());
18
+ }
19
+ // Make one big word list out of all of the filenames provided.
20
+ let wordlist = {};
21
+ filenames.forEach(filename => parseWordListFromFilename(wordlist, filename));
22
+ let trie = Trie.buildTrie(wordlist, searchTermToKey);
23
+ return JSON.stringify(trie);
24
+ }
25
+ /**
26
+ * Parses a word list from a file, merging duplicate entries.
27
+ *
28
+ * The word list may be encoded in:
29
+ *
30
+ * - UTF-8, with or without BOM [exported by most software]
31
+ * - UTF-16, little endian, with BOM [exported by Microsoft Excel]
32
+ *
33
+ * @param wordlist word list to merge entries into (may have existing entries)
34
+ * @param filename filename of the word list
35
+ */
36
+ export function parseWordListFromFilename(wordlist, filename) {
37
+ ModelCompilerMessageContext.filename = filename;
38
+ _parseWordList(wordlist, new WordListFromFilename(filename));
39
+ }
40
+ /**
41
+ * Parses a word list from a string. The string should have multiple lines
42
+ * with LF or CRLF line terminators.
43
+ *
44
+ * @param wordlist word list to merge entries into (may have existing entries)
45
+ * @param filename filename of the word list
46
+ */
47
+ export function parseWordListFromContents(wordlist, contents) {
48
+ ModelCompilerMessageContext.filename = undefined;
49
+ _parseWordList(wordlist, new WordListFromMemory(contents));
50
+ }
51
+ /**
52
+ * Reads a tab-separated values file into a word list. This function converts all
53
+ * entries into NFC and merges duplicate entries across wordlists. Duplication is
54
+ * on the basis of character-for-character equality after normalisation to NFC.
55
+ *
56
+ * Format specification:
57
+ *
58
+ * - the file is a UTF-8 encoded text file.
59
+ * - new lines are either LF or CRLF.
60
+ * - the file MAY start with the UTF-8 byte-order mark (BOM); that is, if the
61
+ * first three bytes of the file are EF BB BF, these will be interepreted as
62
+ * the BOM and will be ignored.
63
+ * - the file either consists of a comment or an entry.
64
+ * - comment lines MUST start with the '#' character on the very first column.
65
+ * - entries are one to three columns, separated by the (horizontal) tab
66
+ * character.
67
+ * - column 1 (REQUIRED): the wordform: can have any character except tab, CR,
68
+ * LF. Surrounding whitespace characters are trimmed.
69
+ * - column 2 (optional): the count: a non-negative integer specifying how many
70
+ * times this entry has appeared in the corpus. Blank means 'indeterminate';
71
+ * commas are permissible in the digits.
72
+ * - column 3 (optional): comment: an informative comment, ignored by the tool.
73
+ *
74
+ * @param wordlist word list to merge entries into (may have existing entries)
75
+ * @param contents contents of the file to import
76
+ */
77
+ function _parseWordList(wordlist, source) {
78
+ const TAB = "\t";
79
+ let wordsSeenInThisFile = new Set();
80
+ for (let [lineno, line] of source.lines()) {
81
+ ModelCompilerMessageContext.line = lineno;
82
+ // Remove the byte-order mark (BOM) from the beginning of the string.
83
+ // Because `contents` can be the concatenation of several files, we have to remove
84
+ // the BOM from every possible start of file -- i.e., beginning of every line.
85
+ line = line.replace(/^\uFEFF/, '').trim();
86
+ if (line.startsWith('#') || line === "") {
87
+ continue; // skip comments and empty lines
88
+ }
89
+ // The third column is the comment. Always ignored!
90
+ let [wordform, countText] = line.split(TAB);
91
+ // Clean the word form.
92
+ let original = wordform;
93
+ wordform = wordform.normalize('NFC');
94
+ if (original !== wordform) {
95
+ // Mixed normalization forms are yucky! Hint about it, because it may
96
+ // result in unexpected counts where multiple normalization forms for one
97
+ // word
98
+ callbacks.reportMessage(ModelCompilerMessages.Hint_MixedNormalizationForms({ wordform: wordform }));
99
+ }
100
+ wordform = wordform.trim();
101
+ countText = (countText || '').trim().replace(/,/g, '');
102
+ let count = parseInt(countText, 10);
103
+ // When parsing a decimal integer fails (e.g., blank or something else):
104
+ if (!isFinite(count) || count < 0) {
105
+ // TODO: is this the right thing to do?
106
+ // Treat it like a hapax legonmenom -- it exist, but only once.
107
+ count = 1;
108
+ }
109
+ if (wordsSeenInThisFile.has(wordform)) {
110
+ // The same word seen across multiple files is fine, but a word seen
111
+ // multiple times in one file may be a problem
112
+ callbacks.reportMessage(ModelCompilerMessages.Hint_DuplicateWordInSameFile({ wordform: wordform }));
113
+ }
114
+ wordsSeenInThisFile.add(wordform);
115
+ wordlist[wordform] = (isNaN(wordlist[wordform]) ? 0 : wordlist[wordform] || 0) + count;
116
+ }
117
+ }
118
+ class WordListFromMemory {
119
+ name = '<memory>';
120
+ _contents;
121
+ constructor(contents) {
122
+ this._contents = contents;
123
+ }
124
+ *lines() {
125
+ yield* enumerateLines(this._contents.split(NEWLINE_SEPARATOR));
126
+ }
127
+ }
128
+ class WordListFromFilename {
129
+ name;
130
+ constructor(filename) {
131
+ this.name = filename;
132
+ }
133
+ *lines() {
134
+ const data = callbacks.loadFile(this.name);
135
+ const contents = new TextDecoder(detectEncoding(data)).decode(data);
136
+ yield* enumerateLines(contents.split(NEWLINE_SEPARATOR));
137
+ }
138
+ }
139
+ /**
140
+ * Yields pairs of [lineno, line], given an Array of lines.
141
+ */
142
+ function* enumerateLines(lines) {
143
+ let i = 1;
144
+ for (let line of lines) {
145
+ yield [i, line];
146
+ i++;
147
+ }
148
+ }
149
+ var Trie;
150
+ (function (Trie_1) {
151
+ /**
152
+ * A sentinel value for when an internal node has contents and requires an
153
+ * "internal" leaf. That is, this internal node has content. Instead of placing
154
+ * entries as children in an internal node, a "fake" leaf is created, and its
155
+ * key is this special internal value.
156
+ *
157
+ * The value is a valid Unicode BMP code point, but it is a "non-character".
158
+ * Unicode will never assign semantics to these characters, as they are
159
+ * intended to be used internally as sentinel values.
160
+ */
161
+ const INTERNAL_VALUE = '\uFDD0';
162
+ /**
163
+ * Builds a trie from a word list.
164
+ *
165
+ * @param wordlist The wordlist with non-negative weights.
166
+ * @param keyFunction Function that converts word forms into indexed search keys
167
+ * @returns A JSON-serialiable object that can be given to the TrieModel constructor.
168
+ */
169
+ function buildTrie(wordlist, keyFunction) {
170
+ let root = new Trie(keyFunction).buildFromWordList(wordlist).root;
171
+ return {
172
+ totalWeight: sumWeights(root),
173
+ root: root
174
+ };
175
+ }
176
+ Trie_1.buildTrie = buildTrie;
177
+ /**
178
+ * Wrapper class for the trie and its nodes and wordform to search
179
+ */
180
+ class Trie {
181
+ root = createRootNode();
182
+ toKey;
183
+ constructor(wordform2key) {
184
+ this.toKey = wordform2key;
185
+ }
186
+ /**
187
+ * Populates the trie with the contents of an entire wordlist.
188
+ * @param words a list of word and count pairs.
189
+ */
190
+ buildFromWordList(words) {
191
+ for (let [wordform, weight] of Object.entries(words)) {
192
+ let key = this.toKey(wordform);
193
+ addUnsorted(this.root, { key, weight, content: wordform }, 0);
194
+ }
195
+ sortTrie(this.root);
196
+ return this;
197
+ }
198
+ }
199
+ // "Constructors"
200
+ function createRootNode() {
201
+ return {
202
+ type: 'leaf',
203
+ weight: 0,
204
+ entries: []
205
+ };
206
+ }
207
+ // Implement Trie creation.
208
+ /**
209
+ * Adds an entry to the trie.
210
+ *
211
+ * Note that the trie will likely be unsorted after the add occurs. Before
212
+ * performing a lookup on the trie, use call sortTrie() on the root note!
213
+ *
214
+ * @param node Which node should the entry be added to?
215
+ * @param entry the wordform/weight/key to add to the trie
216
+ * @param index the index in the key and also the trie depth. Should be set to
217
+ * zero when adding onto the root node of the trie.
218
+ */
219
+ function addUnsorted(node, entry, index = 0) {
220
+ // Each node stores the MAXIMUM weight out of all of its decesdents, to
221
+ // enable a greedy search through the trie.
222
+ node.weight = Math.max(node.weight, entry.weight);
223
+ // When should a leaf become an interior node?
224
+ // When it already has a value, but the key of the current value is longer
225
+ // than the prefix.
226
+ if (node.type === 'leaf' && index < entry.key.length && node.entries.length >= 1) {
227
+ convertLeafToInternalNode(node, index);
228
+ }
229
+ if (node.type === 'leaf') {
230
+ // The key matches this leaf node, so add yet another entry.
231
+ addItemToLeaf(node, entry);
232
+ }
233
+ else {
234
+ // Push the node down to a lower node.
235
+ addItemToInternalNode(node, entry, index);
236
+ }
237
+ node.unsorted = true;
238
+ }
239
+ /**
240
+ * Adds an item to the internal node at a given depth.
241
+ * @param item
242
+ * @param index
243
+ */
244
+ function addItemToInternalNode(node, item, index) {
245
+ let char = item.key[index];
246
+ // If an internal node is the proper site for item, it belongs under the
247
+ // corresponding (sentinel, internal-use) child node signifying this.
248
+ if (char == undefined) {
249
+ char = INTERNAL_VALUE;
250
+ }
251
+ if (!node.children[char]) {
252
+ node.children[char] = createRootNode();
253
+ node.values.push(char);
254
+ }
255
+ addUnsorted(node.children[char], item, index + 1);
256
+ }
257
+ function addItemToLeaf(leaf, item) {
258
+ leaf.entries.push(item);
259
+ }
260
+ /**
261
+ * Mutates the given Leaf to turn it into an InternalNode.
262
+ *
263
+ * NOTE: the node passed in will be DESTRUCTIVELY CHANGED into a different
264
+ * type when passed into this function!
265
+ *
266
+ * @param depth depth of the trie at this level.
267
+ */
268
+ function convertLeafToInternalNode(leaf, depth) {
269
+ let entries = leaf.entries;
270
+ // Alias the current node, as the desired type.
271
+ let internal = leaf;
272
+ internal.type = 'internal';
273
+ delete leaf.entries;
274
+ internal.values = [];
275
+ internal.children = {};
276
+ // Convert the old values array into the format for interior nodes.
277
+ for (let item of entries) {
278
+ let char;
279
+ if (depth < item.key.length) {
280
+ char = item.key[depth];
281
+ }
282
+ else {
283
+ char = INTERNAL_VALUE;
284
+ }
285
+ if (!internal.children[char]) {
286
+ internal.children[char] = createRootNode();
287
+ internal.values.push(char);
288
+ }
289
+ addUnsorted(internal.children[char], item, depth + 1);
290
+ }
291
+ internal.unsorted = true;
292
+ }
293
+ /**
294
+ * Recursively sort the trie, in descending order of weight.
295
+ * @param node any node in the trie
296
+ */
297
+ function sortTrie(node) {
298
+ if (node.type === 'leaf') {
299
+ if (!node.unsorted) {
300
+ return;
301
+ }
302
+ node.entries.sort(function (a, b) { return b.weight - a.weight; });
303
+ }
304
+ else {
305
+ // We MUST recurse and sort children before returning.
306
+ for (let char of node.values) {
307
+ sortTrie(node.children[char]);
308
+ }
309
+ if (!node.unsorted) {
310
+ return;
311
+ }
312
+ node.values.sort((a, b) => {
313
+ return node.children[b].weight - node.children[a].weight;
314
+ });
315
+ }
316
+ delete node.unsorted;
317
+ }
318
+ /**
319
+ * O(n) recursive traversal to sum the total weight of all leaves in the
320
+ * trie, starting at the provided node.
321
+ *
322
+ * @param node The node to start summing weights.
323
+ */
324
+ function sumWeights(node) {
325
+ let val;
326
+ if (node.type === 'leaf') {
327
+ val = node.entries
328
+ .map(entry => entry.weight)
329
+ //.map(entry => isNaN(entry.weight) ? 1 : entry.weight)
330
+ .reduce((acc, count) => acc + count, 0);
331
+ }
332
+ else {
333
+ val = Object.keys(node.children)
334
+ .map((key) => sumWeights(node.children[key]))
335
+ .reduce((acc, count) => acc + count, 0);
336
+ }
337
+ if (isNaN(val)) {
338
+ throw new Error("Unexpected NaN has appeared!");
339
+ }
340
+ return val;
341
+ }
342
+ })(Trie || (Trie = {}));
343
+ /**
344
+ * Detects the encoding of a text file.
345
+ *
346
+ * Supported encodings are:
347
+ *
348
+ * - UTF-8, with or without BOM
349
+ * - UTF-16, little endian, with BOM
350
+ *
351
+ * UTF-16 in big endian is explicitly NOT supported! The reason is two-fold:
352
+ * 1) Node does not support it without resorting to an external library (or
353
+ * swapping every byte in the file!); and 2) I'm not sure anything actually
354
+ * outputs in this format anyway!
355
+ *
356
+ * @param filename filename of the file to detect encoding
357
+ */
358
+ function detectEncoding(buffer) {
359
+ if (buffer.length < 2) {
360
+ return 'utf-8';
361
+ }
362
+ // Note: BOM is U+FEFF
363
+ // In little endian, this is 0xFF 0xFE
364
+ if (buffer[0] == 0xFF && buffer[1] == 0xFE) {
365
+ return 'utf-16le';
366
+ }
367
+ else if (buffer[0] == 0xFE && buffer[1] == 0xFF) {
368
+ // Big Endian, is NOT supported because Node does not support it (???)
369
+ // See: https://stackoverflow.com/a/14551669/6626414
370
+ throw new ModelCompilerError(ModelCompilerMessages.Error_UTF16BEUnsupported());
371
+ }
372
+ else {
373
+ // Assume its in UTF-8, with or without a BOM.
374
+ return 'utf-8';
375
+ }
376
+ }
377
377
  //# sourceMappingURL=build-trie.js.map
378
+ //# debugId=8cd6afc4-7847-5c28-9696-377ec3527897