@overpunch/vf-clamp 2.3.0 → 2.4.0

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/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
- import { createRequire as $ } from "node:module";
2
- const M = $(import.meta.url), { preparePyodide: d, PyodideFile: x } = M("@web-alchemy/fonttools/src/pyodide.js");
3
- let A = null;
4
- async function L() {
5
- return A || (A = d().then(
6
- (e) => e.runPythonAsync(`
1
+ import { createRequire as j } from "node:module";
2
+ import { findInstance as F, rangeName as E } from "./naming.js";
3
+ import { compactName as st, numberKey as rt, planOutputs as lt, unboughtInstances as ft } from "./naming.js";
4
+ const P = j(import.meta.url), { preparePyodide: f, PyodideFile: p } = P("@web-alchemy/fonttools/src/pyodide.js");
5
+ let y = null;
6
+ async function M() {
7
+ return y || (y = f().then(
8
+ (t) => t.runPythonAsync(`
7
9
  from fontTools.ttLib import TTFont
8
10
 
9
11
  def vf_convert_flavor(file_options):
@@ -13,39 +15,39 @@ def vf_convert_flavor(file_options):
13
15
 
14
16
  vf_convert_flavor
15
17
  `)
16
- )), A;
18
+ )), y;
17
19
  }
18
- async function R(e, a) {
19
- const t = await d(), n = new x({ pyodide: t }), i = new x({ pyodide: t });
20
+ async function O(t, o) {
21
+ const a = await f(), n = new p({ pyodide: a }), e = new p({ pyodide: a });
20
22
  try {
21
- await n.upload(e);
22
- const o = /* @__PURE__ */ new Map([
23
+ await n.upload(t);
24
+ const i = /* @__PURE__ */ new Map([
23
25
  ["input-file", n.filename],
24
- ["output-file", i.filename],
25
- ["flavor", a]
26
+ ["output-file", e.filename],
27
+ ["flavor", o]
26
28
  ]);
27
- return (await L())(o), i.download();
29
+ return (await M())(i), e.download();
28
30
  } finally {
29
31
  try {
30
32
  n.delete();
31
33
  } catch {
32
34
  }
33
35
  try {
34
- i.delete();
36
+ e.delete();
35
37
  } catch {
36
38
  }
37
39
  }
38
40
  }
39
- async function k(e) {
40
- return R(e, "woff");
41
+ async function U(t) {
42
+ return O(t, "woff");
41
43
  }
42
- async function C(e) {
43
- return R(e, "woff2");
44
+ async function q(t) {
45
+ return O(t, "woff2");
44
46
  }
45
- let I = null;
46
- async function E() {
47
- return I || (I = d().then(
48
- (e) => e.runPythonAsync(`
47
+ let v = null;
48
+ async function W() {
49
+ return v || (v = f().then(
50
+ (t) => t.runPythonAsync(`
49
51
  import json
50
52
  from fontTools.ttLib import TTFont
51
53
 
@@ -78,18 +80,28 @@ def get_instances_fn(input_file):
78
80
  for i, inst in enumerate(fvar.instances)
79
81
  ]
80
82
 
81
- return json.dumps({'axes': axes, 'instances': instances, 'family': family})
83
+ labels = {}
84
+ if 'STAT' in font and font['STAT'].table.AxisValueArray:
85
+ stat = font['STAT'].table
86
+ tags = [a.AxisTag for a in stat.DesignAxisRecord.Axis]
87
+ for av in stat.AxisValueArray.AxisValue:
88
+ if av.Format in (1, 2, 3) and av.AxisIndex < len(tags):
89
+ value = av.NominalValue if av.Format == 2 else av.Value
90
+ key = ('%f' % float(value)).rstrip('0').rstrip('.')
91
+ labels.setdefault(tags[av.AxisIndex], {})[key] = name_table.getDebugName(av.ValueNameID) or ''
92
+
93
+ return json.dumps({'axes': axes, 'instances': instances, 'family': family, 'labels': labels})
82
94
 
83
95
  get_instances_fn
84
96
  `)
85
- )), I;
97
+ )), v;
86
98
  }
87
- async function B(e) {
88
- const a = await d(), t = e instanceof ArrayBuffer ? new Uint8Array(e) : e, n = new x({ pyodide: a });
99
+ async function z(t) {
100
+ const o = await f(), a = t instanceof ArrayBuffer ? new Uint8Array(t) : t, n = new p({ pyodide: o });
89
101
  try {
90
- await n.upload(t);
91
- const o = (await E())(n.filename);
92
- return JSON.parse(o);
102
+ await n.upload(a);
103
+ const i = (await W())(n.filename);
104
+ return JSON.parse(i);
93
105
  } finally {
94
106
  try {
95
107
  n.delete();
@@ -97,125 +109,414 @@ async function B(e) {
97
109
  }
98
110
  }
99
111
  }
100
- function U(e, a) {
101
- if (e === a) return e;
102
- const t = e.split(" "), n = a.split(" ");
103
- let i = 0;
104
- for (; i < t.length && i < n.length && t[i] === n[i]; )
105
- i++;
106
- let o = 0;
107
- for (; o < t.length - i && o < n.length - i && t[t.length - 1 - o] === n[n.length - 1 - o]; )
108
- o++;
109
- const r = t.slice(0, i).join(" "), s = t.slice(i, t.length - (o || 0)).join(" "), h = n.slice(i, n.length - (o || 0)).join(" "), y = o > 0 ? t.slice(t.length - o).join(" ") : "", f = s && h ? `${s}-${h}` : s || h;
110
- return [r, f, y].filter(Boolean).join(" ");
112
+ const $ = `# vfclamp_naming.py — the single implementation of vf-clamp's naming, style-bit and STAT clean-up rules (docs/NAMING.md), shared by the npm package (run in Pyodide), the Glyphs plugin and the RoboFont extension.
113
+ #
114
+ # Canonical copy: vfClamp/shared/plugin-views/vfclamp_naming.py. The plugins get byte-identical copies via
115
+ # \`npm run sync-plugin-views\`; the npm package imports this file's text at build time. Never edit a copy.
116
+ # Pure fontTools: no Glyphs, RoboFont or AppKit imports.
117
+
118
+ import re
119
+ import unicodedata
120
+
121
+ #: OS/2.fsSelection bits this module owns.
122
+ FS_ITALIC = 0x01
123
+ FS_BOLD = 0x20
124
+ FS_REGULAR = 0x40
125
+ FS_OBLIQUE = 0x200
126
+ #: head.macStyle bits this module owns.
127
+ MAC_BOLD = 0x01
128
+ MAC_ITALIC = 0x02
129
+
130
+ #: Label for an axis value that has no word in the font's style names (e.g. wdth 100 in "Light").
131
+ DEFAULT_AXIS_WORDS = {'wght': 'Regular', 'wdth': 'Normal', 'ital': 'Upright', 'slnt': 'Upright'}
132
+
133
+ #: The four style-linking (RIBBI) subfamily names.
134
+ RIBBI = ('Regular', 'Italic', 'Bold', 'Bold Italic')
135
+
136
+
137
+ def short_hash(text):
138
+ """Six-character FNV-1a hash of a string, base 36; identical to shortHash() in the npm package."""
139
+ h = 0x811c9dc5
140
+ for ch in text:
141
+ h ^= ord(ch)
142
+ h = (h * 0x01000193) & 0xFFFFFFFF
143
+ digits = '0123456789abcdefghijklmnopqrstuvwxyz'
144
+ out = ''
145
+ while h:
146
+ h, rem = divmod(h, 36)
147
+ out = digits[rem] + out
148
+ return (out or '0').rjust(6, '0')[-6:]
149
+
150
+
151
+ def ps_name(text, max_len=63):
152
+ """PostScript name (nameID 6): accents transliterated, [A-Za-z0-9-] only, at most 63 characters.
153
+
154
+ Over 63 characters, a readable prefix plus a hash of the full text keeps names unique. Text with
155
+ letters in another script becomes 'Font-<hash>' (never the source font's name); text with no
156
+ letters at all becomes 'Font'.
157
+ """
158
+ ascii_text = unicodedata.normalize('NFKD', text or '').encode('ascii', 'ignore').decode('ascii')
159
+ s = re.sub(r'[^A-Za-z0-9 -]', '', ascii_text).strip()
160
+ s = re.sub(r'\\s+', '-', s)
161
+ s = re.sub(r'-+', '-', s).strip('-')
162
+ if not s:
163
+ return f'Font-{short_hash(text)}' if any(c.isalpha() for c in (text or '')) else 'Font'
164
+ if len(s) > max_len:
165
+ s = f'{s[:max_len - 7].rstrip("-")}-{short_hash(text)}'
166
+ return s
167
+
168
+
169
+ def vf_prefix(ps, family):
170
+ """Variations PostScript Name Prefix (nameID 25): ASCII letters and digits only (OpenType spec), at most 27."""
171
+ alnum = re.sub(r'[^A-Za-z0-9]', '', ps)
172
+ if not alnum:
173
+ return 'Font'
174
+ if len(alnum) > 27:
175
+ return alnum[:21] + short_hash(family)
176
+ return alnum
177
+
178
+
179
+ def full_name(family, style):
180
+ """Full name (nameID 4): family plus style, leaving out 'Regular' and a style the family name already ends with."""
181
+ if not style or style == 'Regular' or family.lower().endswith(style.lower()):
182
+ return family
183
+ return f'{family} {style}'
184
+
185
+
186
+ def number_key(value):
187
+ """Stable text key for an axis value, identical in Python and JavaScript ('100', '87.5')."""
188
+ return ('%f' % float(value)).rstrip('0').rstrip('.')
189
+
190
+
191
+ # ---------------------------------------------------------------------------
192
+ # Inputs read from the source font (before instancing)
193
+ # ---------------------------------------------------------------------------
194
+
195
+ def source_style_info(font):
196
+ """What the style rules need to know about the source: its italic/oblique bits and whether ital/slnt exist."""
197
+ fs = font['OS/2'].fsSelection if 'OS/2' in font else 0
198
+ tags = {ax.axisTag for ax in font['fvar'].axes} if 'fvar' in font else set()
199
+ return {'italic': bool(fs & FS_ITALIC), 'oblique': bool(fs & FS_OBLIQUE), 'has_ital_slnt': bool(tags & {'ital', 'slnt'})}
200
+
201
+
202
+ def naming_inputs(font):
203
+ """Instances, axes and STAT labels of a source font, in the shape range_name() takes."""
204
+ name = font['name']
205
+ axes = [{'tag': ax.axisTag, 'default': ax.defaultValue} for ax in font['fvar'].axes] if 'fvar' in font else []
206
+ instances = [
207
+ {'name': name.getDebugName(inst.subfamilyNameID) or '', 'coordinates': dict(inst.coordinates)}
208
+ for inst in (font['fvar'].instances if 'fvar' in font else [])
209
+ ]
210
+ labels = {}
211
+ if 'STAT' in font and font['STAT'].table.AxisValueArray:
212
+ stat = font['STAT'].table
213
+ tags = [a.AxisTag for a in stat.DesignAxisRecord.Axis]
214
+ for av in stat.AxisValueArray.AxisValue:
215
+ if av.Format in (1, 2, 3) and av.AxisIndex < len(tags):
216
+ value = av.NominalValue if av.Format == 2 else av.Value
217
+ labels.setdefault(tags[av.AxisIndex], {})[number_key(value)] = name.getDebugName(av.ValueNameID) or ''
218
+ return {'instances': instances, 'axes': axes, 'labels': labels}
219
+
220
+
221
+ # ---------------------------------------------------------------------------
222
+ # Default output name for a selection
223
+ # ---------------------------------------------------------------------------
224
+
225
+ def _words(text):
226
+ """Whitespace-separated words of a style name."""
227
+ return [w for w in (text or '').split() if w]
228
+
229
+
230
+ def range_name(selected, instances, axes, labels=None):
231
+ """Default name for a selection of named instances: one range per axis, in the font's own style words.
232
+
233
+ Each word in the font's style names is attributed to the one axis that is constant wherever the word
234
+ appears and varies across the font ("SemiCondensed" -> wdth, "Thin" -> wght). An axis that varies in
235
+ the selection becomes "low-high" ("SemiCondensed-Normal", "Thin-Light"); an axis that doesn't shows
236
+ its word once, or nothing when that value has no word. A value with no word (wdth 100 in "Light")
237
+ takes its STAT name ("Normal"), else a default word, else "<tag><value>". Parts follow the order the
238
+ words appear in the font's names; words shared by every selected name and owned by no axis (a family prefix,
239
+ "Italic" in an italic-only font) stay in place before or after them.
240
+
241
+ \`\`selected\`\`/\`\`instances\`\`: dicts with 'name' and 'coordinates'; \`\`axes\`\`: dicts with 'tag' and
242
+ 'default'; \`\`labels\`\`: {tag: {number_key(value): name}} from STAT. Mirrored by rangeName() in
243
+ TypeScript; both are checked against shared/naming-cases.json.
244
+ """
245
+ if not selected:
246
+ return ''
247
+ if len(selected) == 1:
248
+ return selected[0]['name']
249
+ labels = labels or {}
250
+ defaults = {a['tag']: a['default'] for a in axes}
251
+ tags = [a['tag'] for a in axes]
252
+
253
+ def coord(inst, tag):
254
+ return inst['coordinates'].get(tag, defaults.get(tag))
255
+
256
+ varying = [t for t in tags if len({coord(i, t) for i in instances}) > 1]
257
+
258
+ owner_cache = {}
259
+
260
+ def owner(word):
261
+ if word not in owner_cache:
262
+ having = [i for i in instances if word in _words(i['name'])]
263
+ cands = [t for t in varying if len({coord(i, t) for i in having}) == 1] if having else []
264
+ owner_cache[word] = cands[0] if len(cands) == 1 else None
265
+ return owner_cache[word]
266
+
267
+ def label(tag, value):
268
+ at = [i for i in instances if coord(i, tag) == value]
269
+ if not at:
270
+ return ''
271
+ common = [w for w in _words(at[0]['name']) if owner(w) == tag and all(w in _words(i['name']) for i in at)]
272
+ return ' '.join(common)
273
+
274
+ def fallback(tag, value):
275
+ stat = labels.get(tag, {}).get(number_key(value))
276
+ if stat:
277
+ return stat
278
+ return DEFAULT_AXIS_WORDS.get(tag) or f'{tag}{number_key(value)}'
279
+
280
+ # Axis order follows the font's own names: positions come from names carrying words for two or more
281
+ # axes ("SemiCondensed Thin" puts width before weight); a plain "Thin" says nothing about order.
282
+ def owned_axes(inst):
283
+ return {owner(w) for w in _words(inst['name'])} - {None}
284
+
285
+ rich = [i for i in instances if len(owned_axes(i)) > 1] or instances
286
+
287
+ def axis_position(tag):
288
+ found = [k for i in rich for k, w in enumerate(_words(i['name'])) if owner(w) == tag]
289
+ return min(found) if found else 10_000
290
+
291
+ parts = []
292
+ for order, tag in enumerate(tags):
293
+ values = sorted({coord(i, tag) for i in selected})
294
+ lo, hi = values[0], values[-1]
295
+ if lo == hi:
296
+ text = label(tag, lo)
297
+ if not text:
298
+ continue
299
+ else:
300
+ a = label(tag, lo) or fallback(tag, lo)
301
+ b = label(tag, hi) or fallback(tag, hi)
302
+ text = a if a == b else f'{a}-{b}'
303
+ parts.append((axis_position(tag), order, text))
304
+ parts.sort()
305
+
306
+ first_words = _words(selected[0]['name'])
307
+ shared = [w for w in first_words if owner(w) is None and all(w in _words(i['name']) for i in selected)]
308
+ owned_positions = [k for k, w in enumerate(first_words) if owner(w) is not None]
309
+ first_owned = min(owned_positions) if owned_positions else len(first_words)
310
+ before = [w for w in shared if first_words.index(w) < first_owned]
311
+ after = [w for w in shared if first_words.index(w) >= first_owned]
312
+ name = ' '.join(before + [p[2] for p in parts] + after).strip()
313
+ return name or f'{selected[0]["name"]}-{selected[-1]["name"]}'
314
+
315
+
316
+ # ---------------------------------------------------------------------------
317
+ # Rules applied to the clamped font (after instancing)
318
+ # ---------------------------------------------------------------------------
319
+
320
+ _WIDTH_CLASSES = ((62.5, 1), (75.0, 2), (87.5, 3), (100.0, 4), (112.5, 5), (125.0, 6), (150.0, 7), (200.0, 8))
321
+
322
+
323
+ def location_after(font, pinned):
324
+ """The clamped font's default location: remaining fvar defaults plus the values of pinned axes."""
325
+ loc = {ax.axisTag: ax.defaultValue for ax in font['fvar'].axes} if 'fvar' in font else {}
326
+ for tag, value in (pinned or {}).items():
327
+ loc.setdefault(tag, value)
328
+ return loc
329
+
330
+
331
+ def unlink_out_of_range_stat(font, location):
332
+ """Turn STAT Format 3 values whose LinkedValue the clamped font can't reach into Format 1 (same name, no link)."""
333
+ if 'STAT' not in font or not font['STAT'].table.AxisValueArray:
334
+ return
335
+ stat = font['STAT'].table
336
+ tags = [a.AxisTag for a in stat.DesignAxisRecord.Axis]
337
+ ranges = {ax.axisTag: (ax.minValue, ax.maxValue) for ax in font['fvar'].axes} if 'fvar' in font else {}
338
+ for av in stat.AxisValueArray.AxisValue:
339
+ if av.Format != 3 or av.AxisIndex >= len(tags):
340
+ continue
341
+ tag = tags[av.AxisIndex]
342
+ if tag in ranges:
343
+ lo, hi = ranges[tag]
344
+ reachable = lo <= av.LinkedValue <= hi
345
+ elif tag in location:
346
+ reachable = av.LinkedValue == location[tag]
347
+ else:
348
+ continue
349
+ if not reachable:
350
+ av.Format = 1
351
+ del av.LinkedValue
352
+
353
+
354
+ def apply_style_bits(font, location, source):
355
+ """Set usWeightClass/usWidthClass, fsSelection and macStyle from the clamped font's default location.
356
+
357
+ BOLD from weight 700; ITALIC from ital >= 0.5 or slnt < 0 (OBLIQUE as well for a slant without ital);
358
+ with neither axis in the source, the source's italic/oblique bits are kept. REGULAR only when none of
359
+ BOLD, ITALIC or OBLIQUE is set. Returns (is_bold, is_italic).
360
+ """
361
+ if 'OS/2' not in font:
362
+ return False, False
363
+ os2 = font['OS/2']
364
+ wght, wdth = location.get('wght'), location.get('wdth')
365
+ if wght is not None:
366
+ os2.usWeightClass = max(1, min(1000, int(round(wght))))
367
+ if wdth is not None:
368
+ os2.usWidthClass = next((cls for edge, cls in _WIDTH_CLASSES if wdth < edge), 9)
369
+ if source.get('has_ital_slnt'):
370
+ ital, slnt = location.get('ital'), location.get('slnt')
371
+ is_italic = (ital is not None and ital >= 0.5) or (slnt is not None and slnt < 0)
372
+ is_oblique = slnt is not None and slnt < 0 and not (ital is not None and ital >= 0.5)
373
+ else:
374
+ is_italic, is_oblique = source.get('italic', False), source.get('oblique', False)
375
+ is_bold = os2.usWeightClass >= 700
376
+ fs = os2.fsSelection & ~(FS_ITALIC | FS_BOLD | FS_REGULAR | FS_OBLIQUE)
377
+ if is_italic or is_oblique:
378
+ fs |= FS_ITALIC
379
+ if is_oblique:
380
+ fs |= FS_OBLIQUE
381
+ if is_bold:
382
+ fs |= FS_BOLD
383
+ if not (is_bold or is_italic or is_oblique):
384
+ fs |= FS_REGULAR
385
+ os2.fsSelection = fs
386
+ if 'head' in font:
387
+ mac = font['head'].macStyle & ~(MAC_BOLD | MAC_ITALIC)
388
+ font['head'].macStyle = mac | (MAC_BOLD if is_bold else 0) | (MAC_ITALIC if (is_italic or is_oblique) else 0)
389
+ return is_bold, (is_italic or is_oblique)
390
+
391
+
392
+ def default_instance_style(font):
393
+ """Subfamily name of the named instance at the clamped font's default location, or None."""
394
+ if 'fvar' not in font:
395
+ return None
396
+ defaults = {ax.axisTag: ax.defaultValue for ax in font['fvar'].axes}
397
+ for inst in font['fvar'].instances:
398
+ if all(abs(inst.coordinates.get(t, v) - v) < 0.01 for t, v in defaults.items()):
399
+ return font['name'].getDebugName(inst.subfamilyNameID)
400
+ return None
401
+
402
+
403
+ def apply_names(font, family, style=None, keep_mac=True, version=None):
404
+ """Write name IDs 1, 2, 3, 4, 6, 16/17, 25 and the named instances' PostScript names. Run after apply_style_bits.
405
+
406
+ \`\`family\`\` is the output name; blank raises ValueError. \`\`style\`\` is the picked instance's name for a
407
+ single-style output; for a range it defaults to the instance at the new default location. nameID 2 is
408
+ the RIBBI style matching OS/2; a non-RIBBI style (SemiBold) goes into 16/17, and for a static file
409
+ into nameID 1 too ("Family SemiBold" + "Regular"), as the OpenType spec describes. A static file's
410
+ PostScript name includes its style so two pins never collide.
411
+ """
412
+ family = (family or '').strip()
413
+ if not family:
414
+ raise ValueError('vf-clamp: the output name is empty')
415
+ name_table = font['name']
416
+ existing = {r.nameID for r in name_table.names}
417
+ static = 'fvar' not in font
418
+ fs = font['OS/2'].fsSelection if 'OS/2' in font else FS_REGULAR
419
+ is_bold, is_italic = bool(fs & FS_BOLD), bool(fs & FS_ITALIC)
420
+ ribbi = ('Bold Italic' if is_italic else 'Bold') if is_bold else ('Italic' if is_italic else 'Regular')
421
+
422
+ typo = (style or '').strip() or default_instance_style(font) or ribbi
423
+ if is_italic and 'Italic' not in typo and 'Oblique' not in typo:
424
+ typo = 'Italic' if typo == 'Regular' else f'{typo} Italic'
425
+ core = ' '.join(w for w in typo.split() if w not in ('Italic', 'Oblique'))
426
+ non_ribbi = core not in ('', 'Regular', 'Bold')
427
+
428
+ name1 = family
429
+ if static and non_ribbi and not family.lower().endswith(core.lower()):
430
+ name1 = f'{family} {core}'
431
+ ps_base = family if not static or typo == 'Regular' or family.lower().endswith(typo.lower()) else f'{family} {typo}'
432
+ ps = ps_name(ps_base)
433
+ prefix = vf_prefix(ps, family)
434
+ if version is None:
435
+ try:
436
+ version = '%.3f' % font['head'].fontRevision
437
+ except Exception:
438
+ version = '1.000'
439
+
440
+ updates = {
441
+ 1: name1,
442
+ 2: ribbi,
443
+ 3: f'{version};{ps};{family}',
444
+ 4: full_name(family, typo if static else ribbi),
445
+ 6: ps,
446
+ }
447
+ if 16 in existing or 17 in existing or non_ribbi:
448
+ updates[16] = family
449
+ updates[17] = typo
450
+ if 25 in existing:
451
+ updates[25] = prefix
452
+ if 'fvar' in font:
453
+ for inst in font['fvar'].instances:
454
+ pid = getattr(inst, 'postscriptNameID', 0xFFFF)
455
+ if pid in (None, 0xFFFF) or pid in updates:
456
+ continue
457
+ inst_style = re.sub(r'[^A-Za-z0-9-]', '', (name_table.getDebugName(inst.subfamilyNameID) or '').replace(' ', ''))
458
+ updates[pid] = f'{prefix}-{inst_style}'[:63]
459
+
460
+ english = {0, 0x0409}
461
+ kept = []
462
+ written = set()
463
+ for record in name_table.names:
464
+ if record.nameID not in updates:
465
+ kept.append(record)
466
+ continue
467
+ if record.platformID in (1, 3) and record.langID not in english:
468
+ continue # stale localised name for an ID we're rewriting
469
+ value = updates[record.nameID]
470
+ if record.platformID in (0, 3):
471
+ record.string = value.encode('utf-16-be')
472
+ elif record.platformID == 1:
473
+ if not keep_mac:
474
+ continue
475
+ try:
476
+ record.string = value.encode('mac_roman')
477
+ except (UnicodeEncodeError, LookupError):
478
+ continue # drop rather than write '?'
479
+ kept.append(record)
480
+ written.add((record.nameID, record.platformID))
481
+ name_table.names = kept
482
+ for name_id, value in updates.items():
483
+ if (name_id, 3) not in written:
484
+ name_table.setName(value, name_id, 3, 1, 0x0409)
485
+ return updates
486
+
487
+
488
+ def finish(font, family, style, pinned, source, keep_mac=True):
489
+ """Everything after instancing, in order: STAT links, style bits, names. Returns the name updates."""
490
+ location = location_after(font, pinned)
491
+ unlink_out_of_range_stat(font, location)
492
+ apply_style_bits(font, location, source)
493
+ return apply_names(font, family, style, keep_mac=keep_mac)
494
+ `;
495
+ let b = null, A = null, T = null, I = null;
496
+ function C() {
497
+ return b || (b = f().then(async (t) => {
498
+ await t.runPythonAsync($);
499
+ })), b;
111
500
  }
112
- function T(e, a) {
113
- const t = a.filter((n) => n.name === e);
114
- if (!t.length) throw new Error(`Named instance "${e}" not found in font`);
115
- if (t.length > 1) throw new Error(`Named instance "${e}" is ambiguous: ${t.length} instances share that name`);
116
- return t[0];
117
- }
118
- let S = null, V = null, D = null, N = null;
119
- async function z() {
120
- return S || (S = d().then(
121
- (e) => e.runPythonAsync(`
122
- from fontTools import ttLib
123
-
124
- def patch_font_names_fn(file_options):
125
- font = ttLib.TTFont(file_options['input-file'])
126
- name_table = font['name']
127
- family_name = file_options['family-name']
128
- ps_name = file_options['postscript-name']
129
-
130
- existing_ids = {r.nameID for r in name_table.names}
131
-
132
- # A family name with no ASCII letters gives an empty PostScript name: fall back to the
133
- # source PostScript name plus a short hash of the family name (passed in from JS).
134
- if not ps_name:
135
- source_ps = name_table.getDebugName(6) or 'Font'
136
- ps_name = ('%s-%s' % (source_ps[:52], file_options['postscript-suffix']))[:63]
137
-
138
- # nameID 2 must be a RIBBI style that matches OS/2 (already updated): Regular, Italic, Bold or Bold Italic.
139
- fs = font['OS/2'].fsSelection if 'OS/2' in font else 0x40
140
- is_italic = bool(fs & 0x01)
141
- is_bold = bool(fs & 0x20)
142
- ribbi = ('Bold Italic' if is_italic else 'Bold') if is_bold else ('Italic' if is_italic else 'Regular')
143
-
144
- # nameID 17 (typographic subfamily): the name of the named instance at the new default, if any.
145
- default_style = None
146
- if 'fvar' in font:
147
- defaults = {ax.axisTag: ax.defaultValue for ax in font['fvar'].axes}
148
- for inst in font['fvar'].instances:
149
- if all(abs(inst.coordinates.get(t, v) - v) < 0.01 for t, v in defaults.items()):
150
- default_style = name_table.getDebugName(inst.subfamilyNameID)
151
- break
152
-
153
- # nameID 1 = Family, 4 = Full name, 6 = PostScript name
154
- # nameID 2 = Subfamily — reset to 'Regular' so the restricted file does not
155
- # collide with the source font's Subfamily in OS font caches.
156
- # nameID 3 = Unique ID — regenerate so it is distinct from the source font.
157
- # nameID 16 = Preferred family (update only if present)
158
- # nameID 25 = Variations PS Name Prefix (update only if present)
159
- #
160
- # head.fontRevision is a Fixed value (e.g. 1.000). Fall back to '1.000' if
161
- # the head table is unreadable.
162
- try:
163
- version = '%.3f' % font['head'].fontRevision
164
- except Exception:
165
- version = '1.000'
166
- unique_id = '%s;%s;%s' % (version, ps_name, family_name)
167
-
168
- updates = {
169
- 1: family_name,
170
- 2: ribbi,
171
- 3: unique_id,
172
- 4: family_name if ribbi == 'Regular' else '%s %s' % (family_name, ribbi),
173
- 6: ps_name,
174
- }
175
- if 16 in existing_ids:
176
- updates[16] = family_name
177
- if 17 in existing_ids and default_style:
178
- updates[17] = default_style
179
- if 25 in existing_ids:
180
- updates[25] = ps_name
181
-
182
- # Named instances' PostScript names must follow the new prefix, e.g. Inter-Regular-Bold-Medium.
183
- if 'fvar' in font:
184
- for inst in font['fvar'].instances:
185
- pid = getattr(inst, 'postscriptNameID', 0xFFFF)
186
- if pid in (None, 0xFFFF):
187
- continue
188
- style = (name_table.getDebugName(inst.subfamilyNameID) or '').replace(' ', '')
189
- style = ''.join(c for c in style if c.isascii() and (c.isalnum() or c == '-'))
190
- updates[pid] = ('%s-%s' % (ps_name, style))[:63]
191
-
192
- # Rewrite every platform. A Mac (platform 1) record that can't be encoded in Mac Roman is dropped
193
- # rather than filled with '?'; Windows and Unicode records always carry the full name.
194
- keep = []
195
- for record in name_table.names:
196
- if record.nameID not in updates:
197
- keep.append(record)
198
- continue
199
- value = updates[record.nameID]
200
- if record.platformID in (0, 3):
201
- record.string = value.encode('utf-16-be')
202
- elif record.platformID == 1:
203
- try:
204
- record.string = value.encode('mac_roman')
205
- except Exception:
206
- continue
207
- keep.append(record)
208
- name_table.names = keep
501
+ async function G() {
502
+ return A || (A = C().then(() => f()).then(
503
+ (t) => t.runPythonAsync(`
504
+ import json
505
+ from fontTools.ttLib import TTFont
209
506
 
507
+ def vf_clamp_finish(file_options, opts_json):
508
+ opts = json.loads(opts_json)
509
+ font = TTFont(file_options['input-file'])
510
+ finish(font, opts['family'], opts.get('style'), opts.get('pinned') or {}, opts['source'])
210
511
  font.save(file_options['output-file'])
211
512
 
212
- patch_font_names_fn
513
+ vf_clamp_finish
213
514
  `)
214
- )), S;
515
+ )), A;
215
516
  }
216
- async function W() {
217
- return V || (V = d().then(
218
- (e) => e.runPythonAsync(`
517
+ async function Q() {
518
+ return T || (T = C().then(() => f()).then(
519
+ (t) => t.runPythonAsync(`
219
520
  from fontTools.ttLib import TTFont
220
521
  from fontTools.varLib import instancer
221
522
  import json
@@ -246,16 +547,20 @@ def vf_clamp_instantiate(file_options, axes_json):
246
547
  else:
247
548
  limits[tag] = float(spec)
248
549
 
550
+ # The style rules need the source's italic bits and which axes were pinned (they leave fvar).
551
+ source = source_style_info(font)
552
+ pinned = {tag: value for tag, value in limits.items() if isinstance(value, float)}
249
553
  partial = instancer.instantiateVariableFont(font, limits)
250
554
  partial.save(file_options['output-file'])
555
+ return json.dumps({'source': source, 'pinned': pinned})
251
556
 
252
557
  vf_clamp_instantiate
253
558
  `)
254
- )), V;
559
+ )), T;
255
560
  }
256
- async function q() {
257
- return D || (D = d().then(
258
- (e) => e.runPythonAsync(`
561
+ async function J() {
562
+ return I || (I = f().then(
563
+ (t) => t.runPythonAsync(`
259
564
  from fontTools.ttLib import TTFont
260
565
 
261
566
  def vf_clamp_normalize_wght(file_options, new_min_str):
@@ -322,276 +627,135 @@ def vf_clamp_normalize_wght(file_options, new_min_str):
322
627
 
323
628
  vf_clamp_normalize_wght
324
629
  `)
325
- )), D;
326
- }
327
- async function H() {
328
- return N || (N = d().then(
329
- (e) => e.runPythonAsync(`
330
- from fontTools.ttLib import TTFont
331
-
332
- def vf_clamp_update_os2(file_options):
333
- font = TTFont(file_options['input-file'])
334
-
335
- if 'fvar' not in font:
336
- font.save(file_options['output-file'])
337
- return
338
-
339
- wght_axis = next((ax for ax in font['fvar'].axes if ax.axisTag == 'wght'), None)
340
- if wght_axis is not None:
341
- # OS/2.usWeightClass valid range is 1..1000.
342
- weight_class = int(round(max(1, min(1000, wght_axis.defaultValue))))
343
- elif 'OS/2' in font:
344
- # wght was pinned: fontTools has already set usWeightClass to the pinned weight.
345
- weight_class = font['OS/2'].usWeightClass
346
- else:
347
- font.save(file_options['output-file'])
348
- return
349
-
350
- if 'OS/2' in font:
351
- os2 = font['OS/2']
352
- os2.usWeightClass = weight_class
353
- # fsSelection: 0x01 ITALIC (kept), 0x20 BOLD, 0x40 REGULAR. REGULAR only when neither ITALIC nor BOLD.
354
- fs = os2.fsSelection
355
- fs &= ~(0x20 | 0x40)
356
- if weight_class >= 700:
357
- fs |= 0x20
358
- elif not fs & 0x01:
359
- fs |= 0x40
360
- os2.fsSelection = fs
361
-
362
- if 'head' in font:
363
- head = font['head']
364
- # macStyle bit 0 = bold.
365
- ms = head.macStyle
366
- if weight_class >= 700:
367
- ms |= 0x01
368
- else:
369
- ms &= ~0x01
370
- head.macStyle = ms
371
-
372
- font.save(file_options['output-file'])
373
-
374
- vf_clamp_update_os2
375
- `)
376
- )), N;
377
- }
378
- function J(e) {
379
- const a = e.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/[^A-Za-z0-9 -]/g, "").trim().split(/\s+/).join("-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
380
- return a.length <= 63 ? a : `${a.slice(0, 56).replace(/-+$/, "")}-${P(e)}`;
381
- }
382
- function P(e) {
383
- let a = 2166136261;
384
- for (const t of e)
385
- a ^= t.codePointAt(0), a = Math.imul(a, 16777619) >>> 0;
386
- return a.toString(36).padStart(6, "0").slice(-6);
630
+ )), I;
387
631
  }
388
- async function G(e, a) {
389
- if (!a) return e;
390
- const t = await d(), n = new x({ pyodide: t }), i = new x({ pyodide: t });
632
+ async function H(t, o) {
633
+ const a = await f(), n = new p({ pyodide: a }), e = new p({ pyodide: a });
391
634
  try {
392
- const o = J(a);
393
- await n.upload(e);
394
- const r = /* @__PURE__ */ new Map([
635
+ await n.upload(t);
636
+ const i = /* @__PURE__ */ new Map([
395
637
  ["input-file", n.filename],
396
- ["output-file", i.filename],
397
- ["family-name", a],
398
- ["postscript-name", o],
399
- ["postscript-suffix", P(a)]
638
+ ["output-file", e.filename]
400
639
  ]);
401
- return (await z())(r), i.download();
402
- } catch (o) {
403
- throw Object.assign(new Error(`vf-clamp: name table patching failed for "${a}"`), { cause: o });
640
+ return (await G())(i, JSON.stringify(o)), e.download();
641
+ } catch (i) {
642
+ throw Object.assign(new Error(`vf-clamp: name table patching failed for "${o.family}"`), { cause: i });
404
643
  } finally {
405
644
  try {
406
645
  n.delete();
407
646
  } catch {
408
647
  }
409
648
  try {
410
- i.delete();
649
+ e.delete();
411
650
  } catch {
412
651
  }
413
652
  }
414
653
  }
415
- function K(e) {
416
- return typeof e == "number" ? e : e === null ? null : [e.min, e.max];
654
+ function Z(t) {
655
+ return typeof t == "number" ? t : t === null ? null : [t.min, t.max];
417
656
  }
418
- async function Z(e, a) {
419
- const t = await d(), n = new x({ pyodide: t }), i = new x({ pyodide: t });
657
+ async function K(t, o) {
658
+ const a = await f(), n = new p({ pyodide: a }), e = new p({ pyodide: a });
420
659
  try {
421
- await n.upload(e);
422
- const o = /* @__PURE__ */ new Map([
660
+ await n.upload(t);
661
+ const i = /* @__PURE__ */ new Map([
423
662
  ["input-file", n.filename],
424
- ["output-file", i.filename]
425
- ]);
426
- return (await W())(o, JSON.stringify(a)), i.download();
663
+ ["output-file", e.filename]
664
+ ]), s = await Q(), d = JSON.parse(s(i, JSON.stringify(o)));
665
+ return { buffer: e.download(), info: d };
427
666
  } finally {
428
667
  try {
429
668
  n.delete();
430
669
  } catch {
431
670
  }
432
671
  try {
433
- i.delete();
672
+ e.delete();
434
673
  } catch {
435
674
  }
436
675
  }
437
676
  }
438
- async function Q(e) {
439
- const a = await d(), t = new x({ pyodide: a }), n = new x({ pyodide: a });
677
+ async function X(t, o) {
678
+ const a = await f(), n = new p({ pyodide: a }), e = new p({ pyodide: a });
440
679
  try {
441
- await t.upload(e);
680
+ await n.upload(t);
442
681
  const i = /* @__PURE__ */ new Map([
443
- ["input-file", t.filename],
444
- ["output-file", n.filename]
445
- ]);
446
- return (await H())(i), n.download();
447
- } catch (i) {
448
- throw Object.assign(new Error("vf-clamp: OS/2 and macStyle update failed"), { cause: i });
449
- } finally {
450
- try {
451
- t.delete();
452
- } catch {
453
- }
454
- try {
455
- n.delete();
456
- } catch {
457
- }
458
- }
459
- }
460
- async function X(e, a) {
461
- const t = await d(), n = new x({ pyodide: t }), i = new x({ pyodide: t });
462
- try {
463
- await n.upload(e);
464
- const o = /* @__PURE__ */ new Map([
465
682
  ["input-file", n.filename],
466
- ["output-file", i.filename]
683
+ ["output-file", e.filename]
467
684
  ]);
468
- return (await q())(o, String(a)) === "skipped" && console.warn("vf-clamp: normalizeWeightAxis skipped: the weight default is the axis minimum, so there is no lower range to remap"), i.download();
469
- } catch (o) {
470
- throw Object.assign(new Error("vf-clamp: wght normalisation failed"), { cause: o });
685
+ return (await J())(i, String(o)) === "skipped" && console.warn("vf-clamp: normalizeWeightAxis skipped: the weight default is the axis minimum, so there is no lower range to remap"), e.download();
686
+ } catch (i) {
687
+ throw Object.assign(new Error("vf-clamp: wght normalisation failed"), { cause: i });
471
688
  } finally {
472
689
  try {
473
690
  n.delete();
474
691
  } catch {
475
692
  }
476
693
  try {
477
- i.delete();
694
+ e.delete();
478
695
  } catch {
479
696
  }
480
697
  }
481
698
  }
482
- function Y(e, a) {
483
- const t = {};
484
- for (const i of e) {
485
- const o = T(i, a);
486
- for (const [r, s] of Object.entries(o.coordinates))
487
- t[r] ? (t[r].min = Math.min(t[r].min, s), t[r].max = Math.max(t[r].max, s)) : t[r] = { min: s, max: s };
699
+ function Y(t, o) {
700
+ const a = {};
701
+ for (const e of t) {
702
+ const i = F(e, o);
703
+ for (const [s, d] of Object.entries(i.coordinates))
704
+ a[s] ? (a[s].min = Math.min(a[s].min, d), a[s].max = Math.max(a[s].max, d)) : a[s] = { min: d, max: d };
488
705
  }
489
706
  const n = {};
490
- for (const [i, { min: o, max: r }] of Object.entries(t))
491
- n[i] = o === r ? o : { min: o, max: r };
707
+ for (const [e, { min: i, max: s }] of Object.entries(a))
708
+ n[e] = i === s ? i : { min: i, max: s };
492
709
  return n;
493
710
  }
494
- function ee(e) {
495
- return e.length >= 4 && e[0] === 79 && e[1] === 84 && e[2] === 84 && e[3] === 79;
711
+ function tt(t) {
712
+ return t.length >= 4 && t[0] === 79 && t[1] === 84 && t[2] === 84 && t[3] === 79;
496
713
  }
497
- async function ae(e, a) {
498
- var h, y;
499
- if (a.outputs.length === 0) return [];
500
- const t = e instanceof ArrayBuffer ? new Uint8Array(e) : e, n = a.format ?? "ttf", { instances: i, axes: o, family: r } = await B(t), s = [];
501
- for (const f of a.outputs) {
502
- let l = {};
503
- if ((h = f.instances) != null && h.length && (l = Y(f.instances, i)), f.axes && (l = { ...l, ...f.axes }), a.strict) {
504
- const _ = new Set((f.instances ?? []).map((p) => T(p, i))), w = i.filter((p) => !_.has(p) && o.every((b) => {
505
- const F = p.coordinates[b.tag] ?? b.default, v = l[b.tag];
506
- return v == null ? !0 : typeof v == "number" ? F === v : F >= v.min && F <= v.max;
507
- })).map((p) => p.name);
508
- if (w.length)
509
- throw new Error(`vf-clamp: output "${f.name || (f.instances ?? []).join(", ") || "axes-only"}" would include unselected instances (${w.join(", ")}); use planOutputs() to split the selection`);
714
+ async function at(t, o) {
715
+ var N, V;
716
+ if (o.outputs.length === 0) return [];
717
+ const a = t instanceof ArrayBuffer ? new Uint8Array(t) : t, n = o.format ?? "ttf", { instances: e, axes: i, family: s, labels: d } = await z(a), S = [];
718
+ for (const m of o.outputs) {
719
+ let h = {};
720
+ if ((N = m.instances) != null && N.length && (h = Y(m.instances, e)), m.axes && (h = { ...h, ...m.axes }), o.strict) {
721
+ const l = new Set((m.instances ?? []).map((r) => F(r, e))), u = e.filter((r) => !l.has(r) && i.every((_) => {
722
+ const w = r.coordinates[_.tag] ?? _.default, g = h[_.tag];
723
+ return g == null ? !0 : typeof g == "number" ? w === g : w >= g.min && w <= g.max;
724
+ })).map((r) => r.name);
725
+ if (u.length)
726
+ throw new Error(`vf-clamp: output "${m.name || (m.instances ?? []).join(", ") || "axes-only"}" would include unselected instances (${u.join(", ")}); use planOutputs() to split the selection`);
510
727
  }
511
- for (const _ of o) {
512
- const w = l[_.tag];
513
- if (w != null && typeof w == "object") {
514
- const p = w;
515
- if (_.default < p.min || _.default > p.max) {
516
- const b = Math.max(p.min, Math.min(p.max, _.default));
728
+ for (const l of i) {
729
+ const u = h[l.tag];
730
+ if (u != null && typeof u == "object") {
731
+ const r = u;
732
+ if (l.default < r.min || l.default > r.max) {
733
+ const _ = Math.max(r.min, Math.min(r.max, l.default));
517
734
  console.warn(
518
- `vf-clamp: axis "${_.tag}" default (${_.default}) is outside restricted range [${p.min}, ${p.max}] — will be clamped to ${b}`
735
+ `vf-clamp: axis "${l.tag}" default (${l.default}) is outside restricted range [${r.min}, ${r.max}] — will be clamped to ${_}`
519
736
  );
520
737
  }
521
738
  }
522
739
  }
523
- const c = {};
524
- for (const [_, w] of Object.entries(l))
525
- w !== null && (c[_] = K(w));
526
- const u = (y = f.instances) != null && y.length ? f.instances.length === 1 ? f.instances[0] : `${f.instances[0]}-${f.instances[f.instances.length - 1]}` : "Clamped", g = f.name || (r ? `${r} ${u}` : u);
527
- let m = await Z(t, c);
528
- if (n === "otf" && !ee(m))
740
+ const D = {};
741
+ for (const [l, u] of Object.entries(h))
742
+ u !== null && (D[l] = Z(u));
743
+ const x = (m.instances ?? []).map((l) => F(l, e)), k = x.length ? E(x, e, i, d ?? {}) : "Clamped", L = ((V = m.name) == null ? void 0 : V.trim()) || (s ? `${s} ${k}` : k), { buffer: B, info: R } = await K(a, D);
744
+ let c = B;
745
+ if (n === "otf" && !tt(c))
529
746
  throw new Error("vf-clamp: format 'otf' needs a CFF/CFF2 source font; this font has TrueType outlines — use 'ttf'");
530
- a.normalizeWeightAxis && (m = await X(m, 100)), m = await Q(m), m = await G(m, g), n === "woff2" ? m = await C(m) : n === "woff" && (m = await k(m)), s.push({ name: g, buffer: m, format: n });
531
- }
532
- return s;
533
- }
534
- function O(e, a) {
535
- const t = {};
536
- for (const n of a) {
537
- const i = e.map((o) => o.coordinates[n.tag] ?? n.default);
538
- t[n.tag] = { min: Math.min(...i), max: Math.max(...i) };
747
+ o.normalizeWeightAxis && (c = await X(c, 100)), c = await H(c, { family: L, style: x.length === 1 ? x[0].name : null, pinned: R.pinned, source: R.source }), n === "woff2" ? c = await q(c) : n === "woff" && (c = await U(c)), S.push({ name: L, buffer: c, format: n });
539
748
  }
540
- return t;
541
- }
542
- function j(e, a, t, n) {
543
- return a.filter((i) => t.has(i) ? !1 : n.every((o) => {
544
- const r = i.coordinates[o.tag] ?? o.default, s = e[o.tag];
545
- return !s || r >= s.min && r <= s.max;
546
- }));
547
- }
548
- function te(e) {
549
- return e.reduce((a, t) => !a || t.maximum - t.minimum > a.maximum - a.minimum ? t : a, void 0);
550
- }
551
- function ie(e, a, t) {
552
- const { axes: n, instances: i } = e, o = [...new Set(a)].map((l) => T(l, i));
553
- if (!o.length) return [];
554
- const r = new Set(o);
555
- let s;
556
- if (!j(O(o, n), i, r, n).length)
557
- s = [o];
558
- else {
559
- s = o.map((c) => [c]);
560
- let l = !0;
561
- for (; l; ) {
562
- l = !1;
563
- e: for (let c = 0; c < s.length; c++)
564
- for (let u = c + 1; u < s.length; u++) {
565
- const g = [...s[c], ...s[u]];
566
- if (!j(O(g, n), i, r, n).length) {
567
- s[c] = g, s.splice(u, 1), l = !0;
568
- break e;
569
- }
570
- }
571
- }
572
- }
573
- const h = te(n), y = h ? [h, ...n.filter((l) => l.tag !== h.tag)] : n, f = (l, c) => {
574
- for (const u of y) {
575
- const g = (l.coordinates[u.tag] ?? u.default) - (c.coordinates[u.tag] ?? u.default);
576
- if (g) return g;
577
- }
578
- return 0;
579
- };
580
- return s = s.map((l) => [...l].sort(f)).sort((l, c) => f(l[0], c[0])), s.map((l) => {
581
- const c = l[0], u = l[l.length - 1], g = l.length === 1 ? c.name : U(c.name, u.name);
582
- return { name: t ? `${t} ${g}` : g, instances: l.map((m) => m.name) };
583
- });
584
- }
585
- function oe(e, a) {
586
- const t = a.map((n) => T(n, e.instances));
587
- return t.length ? j(O(t, e.axes), e.instances, new Set(t), e.axes).map((n) => n.name) : [];
749
+ return S;
588
750
  }
589
751
  export {
590
- ae as clampFont,
591
- U as compactName,
592
- k as convertToWoff,
593
- C as convertToWoff2,
594
- B as getInstances,
595
- ie as planOutputs,
596
- oe as unboughtInstances
752
+ at as clampFont,
753
+ st as compactName,
754
+ U as convertToWoff,
755
+ q as convertToWoff2,
756
+ z as getInstances,
757
+ rt as numberKey,
758
+ lt as planOutputs,
759
+ E as rangeName,
760
+ ft as unboughtInstances
597
761
  };