inflekt 0.7.2 → 0.8.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inflekt",
3
- "version": "0.7.2",
3
+ "version": "0.8.1",
4
4
  "description": "Inflection utilities for pluralization and singularization with PostGraphile-compatible Latin suffix handling",
5
5
  "author": "Constructive <developers@constructive.io>",
6
6
  "homepage": "https://github.com/constructive-io/dev-utils",
@@ -19,6 +19,8 @@
19
19
  "build": "makage build",
20
20
  "lint": "eslint . --fix",
21
21
  "test": "jest",
22
+ "audit": "ts-node scripts/audit.ts",
23
+ "generate": "ts-node scripts/generate-exceptions.ts",
22
24
  "test:watch": "jest --watch"
23
25
  },
24
26
  "repository": {
@@ -44,5 +46,5 @@
44
46
  "inflection": "^3.0.0",
45
47
  "komoji": "0.9.1"
46
48
  },
47
- "gitHead": "2985d68020ec7d1eeae9a839bdb7ebb68727dd55"
49
+ "gitHead": "a40381a8025aff405d23c96574555aea990b4cc9"
48
50
  }
package/pluralize.d.ts CHANGED
@@ -4,8 +4,8 @@
4
4
  */
5
5
  export declare function singularize(word: string): string;
6
6
  /**
7
- * Convert a word to its plural form
8
- * @example "User" -> "Users", "Person" -> "People"
7
+ * Convert a word to its plural form. Already-plural input is returned as-is.
8
+ * @example "User" -> "Users", "Person" -> "People", "Users" -> "Users"
9
9
  */
10
10
  export declare function pluralize(word: string): string;
11
11
  /**
package/pluralize.js CHANGED
@@ -1,37 +1,4 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
3
  exports.singularize = singularize;
37
4
  exports.pluralize = pluralize;
@@ -40,14 +7,14 @@ exports.pluralizeLast = pluralizeLast;
40
7
  exports.distinctPluralize = distinctPluralize;
41
8
  exports.distinctPluralizeLast = distinctPluralizeLast;
42
9
  /**
43
- * Pluralization utilities with PostGraphile-compatible Latin suffix handling
10
+ * Inflection with PostGraphile-compatible Latin suffix handling.
44
11
  *
45
- * Uses the 'inflection' package with custom overrides for Latin plural suffixes
46
- * that PostGraphile handles differently than standard English pluralization,
47
- * plus a dictionary-proven exception table for the words where no suffix rule
48
- * is right (see exceptions.ts).
12
+ * Both directions are the same shape: an exception table proven against a
13
+ * system dictionary (exceptions.ts) in front of the suffix rules (rules.ts),
14
+ * so dictionary words are right by construction and coined identifiers fall
15
+ * through to the rules. Both are idempotent — `singularize` of a singular and
16
+ * `pluralize` of a plural return the word unchanged.
49
17
  */
50
- const inflection = __importStar(require("inflection"));
51
18
  const exceptions_1 = require("./exceptions");
52
19
  const rules_1 = require("./rules");
53
20
  const LAST_SEGMENT_REGEX = /([A-Z]|_[a-z0-9])[a-z0-9]*_*$/;
@@ -66,12 +33,29 @@ function splitLastSegment(str) {
66
33
  }
67
34
  return { prefix: str.slice(0, index), word: str.slice(index) };
68
35
  }
69
- function lookupException(word) {
36
+ function lookup(table, word) {
70
37
  const key = word.toLowerCase();
71
- if (!Object.prototype.hasOwnProperty.call(exceptions_1.SINGULAR_EXCEPTIONS, key)) {
38
+ if (!Object.prototype.hasOwnProperty.call(table, key)) {
39
+ return null;
40
+ }
41
+ return (0, rules_1.restoreWordCase)(word, table[key]);
42
+ }
43
+ /**
44
+ * Apply an exception table to a word, or to the final segment of a compound
45
+ * name ("user_cookies" -> "cookies") so compounds inflect like the word they
46
+ * end in.
47
+ */
48
+ function applyTable(table, word) {
49
+ const whole = lookup(table, word);
50
+ if (whole) {
51
+ return whole;
52
+ }
53
+ const segment = splitLastSegment(word);
54
+ if (!segment) {
72
55
  return null;
73
56
  }
74
- return (0, rules_1.restoreWordCase)(word, exceptions_1.SINGULAR_EXCEPTIONS[key]);
57
+ const segmentException = lookup(table, segment.word);
58
+ return segmentException ? segment.prefix + segmentException : null;
75
59
  }
76
60
  /**
77
61
  * Convert a word to its singular form with PostGraphile-compatible Latin handling
@@ -79,44 +63,40 @@ function lookupException(word) {
79
63
  */
80
64
  function singularize(word) {
81
65
  const normalizedWord = (0, rules_1.normalizeMalformedDoubleS)(word);
82
- const exception = lookupException(normalizedWord);
66
+ const exception = applyTable(exceptions_1.SINGULAR_EXCEPTIONS, normalizedWord);
83
67
  if (exception) {
84
68
  return exception;
85
69
  }
86
- const segment = splitLastSegment(normalizedWord);
87
- if (segment) {
88
- const segmentException = lookupException(segment.word);
89
- if (segmentException) {
90
- return segment.prefix + segmentException;
91
- }
92
- }
93
70
  return (0, rules_1.singularizeByRules)(normalizedWord);
94
71
  }
95
- const F_OR_FE_REGEX = /(?:f|fe)$/i;
96
- function pluralizeCanonical(word) {
97
- const normalizedWord = (0, rules_1.normalizeMalformedDoubleS)(word);
98
- // -f/-fe words: only the f-stem nouns take -ves; the rest take a plain "s".
99
- const fStem = (0, rules_1.pluralizeFStem)(normalizedWord);
100
- if (fStem) {
101
- return fStem;
102
- }
103
- if (F_OR_FE_REGEX.test(normalizedWord)) {
104
- return `${normalizedWord}s`;
105
- }
106
- const pluralWord = (0, rules_1.normalizeMalformedDoubleS)(inflection.pluralize(normalizedWord));
107
- // -is nouns the inflection library leaves untouched (iris, chassis) rather
108
- // than treating as Greek/Latin (analysis -> analyses).
109
- if (pluralWord === normalizedWord && /is$/i.test(normalizedWord)) {
110
- return `${normalizedWord}es`;
72
+ /**
73
+ * Whether `word` is already a plural, and so must be returned unchanged.
74
+ *
75
+ * SINGULAR_EXCEPTIONS answers this for the dictionary (its keys are plurals,
76
+ * except the self-mapped singulars it carries to protect them from the rules),
77
+ * and the rules answer it for everything else, coined identifiers included.
78
+ */
79
+ function isPlural(word) {
80
+ const singular = applyTable(exceptions_1.SINGULAR_EXCEPTIONS, word);
81
+ if (singular) {
82
+ return singular !== word;
111
83
  }
112
- return (0, rules_1.enforceDoubleSPlural)(singularize(normalizedWord), pluralWord);
84
+ return (0, rules_1.isRulesPlural)(word);
113
85
  }
114
86
  /**
115
- * Convert a word to its plural form
116
- * @example "User" -> "Users", "Person" -> "People"
87
+ * Convert a word to its plural form. Already-plural input is returned as-is.
88
+ * @example "User" -> "Users", "Person" -> "People", "Users" -> "Users"
117
89
  */
118
90
  function pluralize(word) {
119
- return pluralizeCanonical(word);
91
+ const normalizedWord = (0, rules_1.normalizeMalformedDoubleS)(word);
92
+ if (isPlural(normalizedWord)) {
93
+ return normalizedWord;
94
+ }
95
+ const exception = applyTable(exceptions_1.PLURAL_EXCEPTIONS, normalizedWord);
96
+ if (exception) {
97
+ return exception;
98
+ }
99
+ return (0, rules_1.pluralizeByRules)(normalizedWord);
120
100
  }
121
101
  /**
122
102
  * Pluralize/singularize only the final segment of a compound name.
package/rules.d.ts CHANGED
@@ -34,7 +34,31 @@ export declare function pluralizeFStem(word: string): string | null;
34
34
  */
35
35
  export declare function restoreWordCase(source: string, replacement: string): string;
36
36
  /**
37
- * Singularize using suffix rules only — the fallback for words absent from the
38
- * exception table (including coined identifiers that no dictionary knows).
37
+ * Pluralize using suffix rules only, with no exception table — the fallback for
38
+ * words the dictionary does not know, which is every coined identifier.
39
+ *
40
+ * The inflection library's Latin instincts are wrong for identifiers in three
41
+ * shapes, all of which it leaves *unchanged* (so the "plural" equals the
42
+ * singular, and a schema ends up with `radius` and `radius` fields):
43
+ *
44
+ * radius -> radiuses (not radius)
45
+ * delta -> deltas (not delta)
46
+ * forum -> forums (not fora)
47
+ *
48
+ * The genuine Latin plurals are a closed set of dictionary words, carried by
49
+ * LATIN_SUFFIX_OVERRIDES and by the generated PLURAL_EXCEPTIONS table.
50
+ *
51
+ * Words the inflection library holds uncountable (sheep, series, aircraft) are
52
+ * left alone here: "no plural" is a dictionary fact like any other, and the
53
+ * ones it gets wrong (bias, atlas, aid) are corrected by PLURAL_EXCEPTIONS.
54
+ */
55
+ export declare function pluralizeByRules(word: string): string;
56
+ /**
57
+ * Whether the rules already read `word` as a plural: it singularizes to
58
+ * something else, and that singular pluralizes back to exactly `word`.
59
+ *
60
+ * This is what keeps pluralize idempotent — `pluralize('apis')` must be `apis`,
61
+ * not `apises` — without a table of every plural in the language.
39
62
  */
63
+ export declare function isRulesPlural(word: string): boolean;
40
64
  export declare function singularizeByRules(word: string): string;
package/rules.js CHANGED
@@ -38,13 +38,15 @@ exports.normalizeMalformedDoubleS = normalizeMalformedDoubleS;
38
38
  exports.enforceDoubleSPlural = enforceDoubleSPlural;
39
39
  exports.pluralizeFStem = pluralizeFStem;
40
40
  exports.restoreWordCase = restoreWordCase;
41
+ exports.pluralizeByRules = pluralizeByRules;
42
+ exports.isRulesPlural = isRulesPlural;
41
43
  exports.singularizeByRules = singularizeByRules;
42
44
  /**
43
- * Rule-based singularization: the suffix rules alone, with no exception table.
45
+ * Rule-based inflection: the suffix rules alone, with no exception tables.
44
46
  *
45
47
  * Kept separate from pluralize.ts so that scripts/generate-exceptions.ts can
46
- * diff the rules against a dictionary without the exception table masking the
47
- * very defects it is meant to record. Not part of the public API.
48
+ * diff the rules against a dictionary without the exception tables masking the
49
+ * very defects they are meant to record. Not part of the public API.
48
50
  */
49
51
  const inflection = __importStar(require("inflection"));
50
52
  /**
@@ -57,6 +59,8 @@ const inflection = __importStar(require("inflection"));
57
59
  */
58
60
  const LATIN_SUFFIX_OVERRIDES = [
59
61
  ['schemata', 'schema'],
62
+ ['corpora', 'corpus'],
63
+ ['genera', 'genus'],
60
64
  ['criteria', 'criterion'],
61
65
  ['phenomena', 'phenomenon'],
62
66
  ['media', 'medium'],
@@ -65,6 +69,34 @@ const LATIN_SUFFIX_OVERRIDES = [
65
69
  ['curricula', 'curriculum'],
66
70
  ['data', 'datum'],
67
71
  ];
72
+ /**
73
+ * The `-a` plurals of LATIN_SUFFIX_OVERRIDES, as a set: these are the only
74
+ * words the rules may read as an existing plural rather than pluralizing them.
75
+ *
76
+ * Everything else ending in "a" is treated as a singular that takes "-as"
77
+ * (deltas, betas, quotas, schemas, replicas). The inflection library assumes
78
+ * the opposite — that "-a" is Latin — and so leaves every one of them
79
+ * unchanged, which for an identifier means the plural silently equals the
80
+ * singular.
81
+ */
82
+ const LATIN_A_PLURALS = LATIN_SUFFIX_OVERRIDES.map(([plural]) => plural);
83
+ /** Whether `lowerWord` is (or ends in) one of the Latin `-a` plurals. */
84
+ function isLatinAPlural(lowerWord) {
85
+ return LATIN_A_PLURALS.some((plural) => lowerWord.endsWith(plural));
86
+ }
87
+ /**
88
+ * The Latin plurals to *produce*, the inverse of LATIN_SUFFIX_OVERRIDES minus
89
+ * "schema" (whose plural is "schemas" here, per PostGraphile). Matched as a
90
+ * suffix so compounds follow: metadatum -> metadata.
91
+ *
92
+ * Without this, pluralize and singularize disagree: "criteria" singularizes to
93
+ * "criterion", but "criterion" would pluralize to "criterions".
94
+ *
95
+ * Format: [singularSuffix, pluralSuffix]
96
+ */
97
+ const LATIN_PLURAL_SUFFIXES = LATIN_SUFFIX_OVERRIDES
98
+ .filter(([plural]) => plural !== 'schemata')
99
+ .map(([plural, singular]) => [singular, plural]);
68
100
  /**
69
101
  * Compound words ending in "base" that the inflection library incorrectly
70
102
  * singularizes via its (b)a branch in the ses$ rule (e.g. codebases -> codebasis).
@@ -114,11 +146,26 @@ exports.F_STEM_PLURALS = [
114
146
  ['wolf', 'wolves'],
115
147
  ];
116
148
  /**
117
- * Words that are already singular but look plural to the s$ rule: no English
118
- * plural ends in "is" (iris, analysis, chassis) or "us" (bus, status, virus,
119
- * anxious).
149
+ * Adjectives, never plurals: anxious, various, porous. No noun stem ends in
150
+ * "ou", so nothing here is ever a dropped-s away from a singular.
151
+ *
152
+ * There is no equivalent rule for the rest of "-is"/"-us", because none exists:
153
+ * "apis" and "iris" are both a vowel plus "s" (api + s, iri + s), so no suffix
154
+ * tells the plural from the singular. Whether a word is one or the other is a
155
+ * dictionary fact, and the dictionary-proven singulars live in
156
+ * SINGULAR_EXCEPTIONS as self-mappings (status -> status, analysis -> analysis).
157
+ * Words the dictionary does not know fall through to the generic "drop the s",
158
+ * which is what coined identifiers want: apis -> api, cpus -> cpu, uris -> uri.
159
+ */
160
+ const ADJECTIVE_OUS_REGEX = /ous$/i;
161
+ /**
162
+ * Words ending in "a" are singular (delta, schema, replica, quota, aorta): the
163
+ * only English plurals spelled that way are the Latin ones in
164
+ * LATIN_SUFFIX_OVERRIDES. The inflection library reads the suffix as Latin
165
+ * regardless and rewrites it to "-um", coining "deltum" and "schemum", which
166
+ * then reads back as a plural and leaves pluralize with nothing to do.
120
167
  */
121
- const ALREADY_SINGULAR_REGEX = /(?:is|us)$/i;
168
+ const A_SINGULAR_REGEX = /a$/i;
122
169
  /**
123
170
  * The only -ice plurals. The inflection library's rule is written `([m|l])ice`,
124
171
  * whose character class also matches "|", and it fires on any word ending in
@@ -222,10 +269,105 @@ function applyGenericSingularRules(word) {
222
269
  * Singularize using suffix rules only — the fallback for words absent from the
223
270
  * exception table (including coined identifiers that no dictionary knows).
224
271
  */
272
+ const US_REGEX = /us$/i;
273
+ const A_REGEX = /a$/i;
274
+ const UM_REGEX = /um$/i;
275
+ const F_OR_FE_REGEX = /(?:f|fe)$/i;
276
+ /**
277
+ * Nouns ending in "is" that are not the Greek/Latin `-sis`/`-xis` family: their
278
+ * plural adds "es" (iris -> irises, chassis -> chassises). Only the Greek ones
279
+ * rewrite the "is" itself (analysis -> analyses, axis -> axes), which is the
280
+ * rule the inflection library applies to all of them, coining "chasses".
281
+ */
282
+ const NON_GREEK_IS_REGEX = /(?<![sx])is$/i;
283
+ /**
284
+ * Pluralize using suffix rules only, with no exception table — the fallback for
285
+ * words the dictionary does not know, which is every coined identifier.
286
+ *
287
+ * The inflection library's Latin instincts are wrong for identifiers in three
288
+ * shapes, all of which it leaves *unchanged* (so the "plural" equals the
289
+ * singular, and a schema ends up with `radius` and `radius` fields):
290
+ *
291
+ * radius -> radiuses (not radius)
292
+ * delta -> deltas (not delta)
293
+ * forum -> forums (not fora)
294
+ *
295
+ * The genuine Latin plurals are a closed set of dictionary words, carried by
296
+ * LATIN_SUFFIX_OVERRIDES and by the generated PLURAL_EXCEPTIONS table.
297
+ *
298
+ * Words the inflection library holds uncountable (sheep, series, aircraft) are
299
+ * left alone here: "no plural" is a dictionary fact like any other, and the
300
+ * ones it gets wrong (bias, atlas, aid) are corrected by PLURAL_EXCEPTIONS.
301
+ */
302
+ function pluralizeByRules(word) {
303
+ const normalizedWord = normalizeMalformedDoubleS(word);
304
+ // Adjectives have no plural, so leave them be rather than coining
305
+ // "anxiouses"; see ADJECTIVE_OUS_REGEX.
306
+ if (ADJECTIVE_OUS_REGEX.test(normalizedWord)) {
307
+ return normalizedWord;
308
+ }
309
+ // -f/-fe words: only the f-stem nouns take -ves; the rest take a plain "s".
310
+ const fStem = pluralizeFStem(normalizedWord);
311
+ if (fStem) {
312
+ return fStem;
313
+ }
314
+ if (F_OR_FE_REGEX.test(normalizedWord)) {
315
+ return matchWordCase(normalizedWord, `${normalizedWord}s`);
316
+ }
317
+ const lowerWord = normalizedWord.toLowerCase();
318
+ for (const [singularSuffix, pluralSuffix] of LATIN_PLURAL_SUFFIXES) {
319
+ if (!lowerWord.endsWith(singularSuffix)) {
320
+ continue;
321
+ }
322
+ const stem = normalizedWord.slice(0, -singularSuffix.length);
323
+ const matched = normalizedWord.slice(-singularSuffix.length);
324
+ return stem + matchCase(matched, pluralSuffix);
325
+ }
326
+ if (NON_GREEK_IS_REGEX.test(normalizedWord)) {
327
+ return matchWordCase(normalizedWord, `${normalizedWord}es`);
328
+ }
329
+ const pluralWord = normalizeMalformedDoubleS(inflection.pluralize(normalizedWord));
330
+ if (pluralWord === normalizedWord) {
331
+ // Latin-looking shapes it declines to pluralize, and the uncountable list
332
+ // it applies to countable nouns (bias, atlas, aid, air).
333
+ if (US_REGEX.test(normalizedWord)) {
334
+ return matchWordCase(normalizedWord, `${normalizedWord}es`);
335
+ }
336
+ if (UM_REGEX.test(normalizedWord)) {
337
+ return matchWordCase(normalizedWord, `${normalizedWord}s`);
338
+ }
339
+ if (A_REGEX.test(normalizedWord) && !isLatinAPlural(lowerWord)) {
340
+ return matchWordCase(normalizedWord, `${normalizedWord}s`);
341
+ }
342
+ }
343
+ return matchWordCase(normalizedWord, enforceDoubleSPlural(singularizeByRules(normalizedWord), pluralWord));
344
+ }
345
+ /**
346
+ * Keep an all-caps word all-caps: the suffix rules and the inflection library
347
+ * both append a lowercase "s", turning API_KEY into API_KEYs.
348
+ */
349
+ function matchWordCase(word, plural) {
350
+ const isAllCaps = word === word.toUpperCase() && /[A-Z]/.test(word);
351
+ return isAllCaps ? plural.toUpperCase() : plural;
352
+ }
353
+ /**
354
+ * Whether the rules already read `word` as a plural: it singularizes to
355
+ * something else, and that singular pluralizes back to exactly `word`.
356
+ *
357
+ * This is what keeps pluralize idempotent — `pluralize('apis')` must be `apis`,
358
+ * not `apises` — without a table of every plural in the language.
359
+ */
360
+ function isRulesPlural(word) {
361
+ const singular = singularizeByRules(word);
362
+ return singular !== word && pluralizeByRules(singular) === word;
363
+ }
225
364
  function singularizeByRules(word) {
226
365
  const normalizedWord = normalizeMalformedDoubleS(word);
227
366
  const lowerWord = normalizedWord.toLowerCase();
228
- if (ALREADY_SINGULAR_REGEX.test(normalizedWord)) {
367
+ if (ADJECTIVE_OUS_REGEX.test(normalizedWord)) {
368
+ return normalizedWord;
369
+ }
370
+ if (A_SINGULAR_REGEX.test(normalizedWord) && !isLatinAPlural(lowerWord)) {
229
371
  return normalizedWord;
230
372
  }
231
373
  if (ICE_REGEX.test(normalizedWord)) {