chemweave 0.1.340 → 0.1.341

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/chemweave.mjs CHANGED
@@ -1728,7 +1728,7 @@ function pinSymbol(doc, s) {
1728
1728
  let best = null, bestD = 0.7 * doc.style.bondLength;
1729
1729
  for (const a2 of doc.atomsNear(c2, bestD)) {
1730
1730
  const d2 = dist(a2, c2);
1731
- if (d2 < bestD && !a2.multi) {
1731
+ if (d2 < bestD && !a2.multi && !a2.attach) {
1732
1732
  bestD = d2;
1733
1733
  best = a2.id;
1734
1734
  }
@@ -2086,16 +2086,19 @@ const MAX_VALENCE = {
2086
2086
  80: 2,
2087
2087
  82: 4
2088
2088
  };
2089
- function valenceOfBonds(orders, z2 = 6) {
2089
+ function valenceOfBonds(orders, z2 = 6, charge = 0) {
2090
2090
  let sum2 = 0, arom = 0;
2091
2091
  for (const o of orders) {
2092
2092
  if (o === 1.5) arom++;
2093
2093
  else sum2 += o;
2094
2094
  }
2095
2095
  if (!arom) return sum2;
2096
- return sum2 + arom + (LONE_PAIR_DONORS.has(z2) ? 0 : 1);
2096
+ return sum2 + arom + (LONE_PAIR_DONORS.has(z2) || aromaticCarbonIon(z2, charge, arom) ? 0 : 1);
2097
+ }
2098
+ const LONE_PAIR_DONORS = /* @__PURE__ */ new Set([5, 7, 8, 15, 16, 34, 52]);
2099
+ function aromaticCarbonIon(z2, charge, aromaticBonds) {
2100
+ return z2 === 6 && Math.abs(charge) === 1 && aromaticBonds >= 2;
2097
2101
  }
2098
- const LONE_PAIR_DONORS = /* @__PURE__ */ new Set([5, 7, 8, 15, 16, 34]);
2099
2102
  function tablePosition(z2) {
2100
2103
  if (z2 < 1 || z2 > 118) return null;
2101
2104
  const ends = [2, 10, 18, 36, 54, 86, 118];
@@ -2507,10 +2510,19 @@ for (const lig of LIGANDS$1) {
2507
2510
  NICK_NAMES = nickNames();
2508
2511
  const BUILT_IN = new Set(Object.keys(NICKNAMES));
2509
2512
  const SAME_READING = /* @__PURE__ */ new Map();
2510
- function addNicknames(more) {
2511
- const added = [];
2513
+ const FROM_FILE = /* @__PURE__ */ new Set();
2514
+ function addFileNicknames(more) {
2515
+ return putNicknames(more);
2516
+ }
2517
+ function putNicknames(more, fromFile) {
2518
+ const added = [], kept2 = [];
2512
2519
  for (const [name, smi] of Object.entries(more)) {
2513
2520
  if (!name || BUILT_IN.has(name) || typeof smi !== "string" || !smi) continue;
2521
+ if (name in NICKNAMES && !FROM_FILE.has(name)) {
2522
+ if (!sameNicknameSmiles(NICKNAMES[name], smi)) kept2.push(name);
2523
+ continue;
2524
+ }
2525
+ FROM_FILE.add(name);
2514
2526
  NICKNAMES[name] = smi;
2515
2527
  nickCache.delete(name);
2516
2528
  added.push(name);
@@ -2520,7 +2532,7 @@ function addNicknames(more) {
2520
2532
  graphCache.clear();
2521
2533
  SAME_READING.clear();
2522
2534
  }
2523
- return added;
2535
+ return { added, kept: kept2 };
2524
2536
  }
2525
2537
  function tokenize$1(label) {
2526
2538
  const out = [];
@@ -3012,18 +3024,24 @@ function kekulize(g2) {
3012
3024
  const arom = g2.bonds.map((b, i2) => b.order === 1.5 ? i2 : -1).filter((i2) => i2 >= 0);
3013
3025
  if (!arom.length) return g2.bonds;
3014
3026
  const degree = g2.atoms.map(() => 0);
3027
+ const used = g2.atoms.map(() => 0);
3015
3028
  for (const b of g2.bonds) {
3016
3029
  degree[b.a]++;
3017
3030
  degree[b.b]++;
3031
+ const order = b.order === 1.5 ? 1 : b.order;
3032
+ used[b.a] += order;
3033
+ used[b.b] += order;
3018
3034
  }
3019
3035
  const needs = (i2) => {
3020
3036
  const a2 = g2.atoms[i2];
3021
- if (a2.z === 6 || a2.z === 5) return true;
3037
+ if (a2.z === 6) return used[i2] + (a2.hCount ?? 0) < (maxValence(a2.z, a2.charge) ?? Infinity);
3038
+ if (a2.z === 5) return true;
3022
3039
  if (a2.z !== 7 && a2.z !== 15) return false;
3023
3040
  const n2 = degree[i2] + (a2.hCount ?? 0);
3024
3041
  return a2.charge === 1 ? n2 === 3 : a2.charge === 0 && !a2.hCount && n2 < 3;
3025
3042
  };
3026
3043
  const atoms = [...new Set(arom.flatMap((i2) => [g2.bonds[i2].a, g2.bonds[i2].b]))].filter(needs);
3044
+ const needed = new Set(atoms);
3027
3045
  const mate = /* @__PURE__ */ new Map();
3028
3046
  let steps = 0;
3029
3047
  const solve = (k2) => {
@@ -3034,7 +3052,7 @@ function kekulize(g2) {
3034
3052
  for (const bi of arom) {
3035
3053
  const b = g2.bonds[bi];
3036
3054
  const y2 = b.a === x2 ? b.b : b.b === x2 ? b.a : -1;
3037
- if (y2 < 0 || mate.has(y2) || !atoms.includes(y2)) continue;
3055
+ if (y2 < 0 || mate.has(y2) || !needed.has(y2)) continue;
3038
3056
  mate.set(x2, bi);
3039
3057
  mate.set(y2, bi);
3040
3058
  if (solve(k2 + 1)) return true;
@@ -3047,6 +3065,177 @@ function kekulize(g2) {
3047
3065
  const doubles = new Set(mate.values());
3048
3066
  return g2.bonds.map((b, i2) => b.order === 1.5 ? { ...b, order: doubles.has(i2) ? 2 : 1 } : b);
3049
3067
  }
3068
+ function ringBonds$2(n2, bonds) {
3069
+ const adj = Array.from({ length: n2 }, () => []);
3070
+ bonds.forEach((b, i2) => {
3071
+ if (b.a !== b.b && adj[b.a] && adj[b.b]) {
3072
+ adj[b.a].push(i2);
3073
+ adj[b.b].push(i2);
3074
+ }
3075
+ });
3076
+ const ring2 = bonds.map(() => false);
3077
+ const order = Array(n2).fill(-1), low = Array(n2).fill(0);
3078
+ let time = 0;
3079
+ for (let root2 = 0; root2 < n2; root2++) {
3080
+ if (order[root2] >= 0) continue;
3081
+ const stack2 = [[root2, -1, 0]];
3082
+ order[root2] = low[root2] = time++;
3083
+ while (stack2.length) {
3084
+ const top = stack2[stack2.length - 1];
3085
+ const [x2, via] = top;
3086
+ if (top[2] < adj[x2].length) {
3087
+ const bi = adj[x2][top[2]++];
3088
+ if (bi === via) continue;
3089
+ const y2 = bonds[bi].a === x2 ? bonds[bi].b : bonds[bi].a;
3090
+ if (order[y2] < 0) {
3091
+ order[y2] = low[y2] = time++;
3092
+ stack2.push([y2, bi, 0]);
3093
+ } else {
3094
+ low[x2] = Math.min(low[x2], order[y2]);
3095
+ ring2[bi] = true;
3096
+ }
3097
+ continue;
3098
+ }
3099
+ stack2.pop();
3100
+ if (via >= 0) {
3101
+ const parent = stack2[stack2.length - 1][0];
3102
+ low[parent] = Math.min(low[parent], low[x2]);
3103
+ if (low[x2] <= order[parent]) ring2[via] = true;
3104
+ }
3105
+ }
3106
+ }
3107
+ return ring2;
3108
+ }
3109
+ function kekuleForms(g2, attachment, limit = 64) {
3110
+ const n2 = g2.atoms.length;
3111
+ const out = attachment !== void 0 && attachment < n2;
3112
+ const withOut = out ? { atoms: [...g2.atoms, { z: 0, charge: 0, aromatic: false, dummy: true }], bonds: [...g2.bonds, { a: attachment, b: n2, order: 1 }] } : g2;
3113
+ let start2 = kekulize(withOut);
3114
+ if (out) start2 = start2.slice(0, g2.bonds.length);
3115
+ if (start2.some((b) => b.order === 1.5)) return [start2];
3116
+ const ring2 = ringBonds$2(n2, start2).map((r, i2) => r && (start2[i2].order === 1 || start2[i2].order === 2));
3117
+ const doubles = Array(n2).fill(0);
3118
+ const other = Array(n2).fill(false);
3119
+ start2.forEach((b, i2) => {
3120
+ if (b.order !== 2) {
3121
+ if (b.order !== 1) {
3122
+ other[b.a] = true;
3123
+ other[b.b] = true;
3124
+ }
3125
+ return;
3126
+ }
3127
+ doubles[b.a]++;
3128
+ doubles[b.b]++;
3129
+ if (!ring2[i2]) {
3130
+ other[b.a] = true;
3131
+ other[b.b] = true;
3132
+ }
3133
+ });
3134
+ const movable = g2.atoms.map((_2, i2) => doubles[i2] === 1 && !other[i2]);
3135
+ const usable = start2.map((b, i2) => ring2[i2] && movable[b.a] && movable[b.b]);
3136
+ if (!usable.some((u2) => u2)) return [start2];
3137
+ const atoms = movable.map((m2, i2) => m2 ? i2 : -1).filter((i2) => i2 >= 0);
3138
+ const mate = /* @__PURE__ */ new Map();
3139
+ const forms2 = [];
3140
+ const byAtom = g2.atoms.map(() => []);
3141
+ start2.forEach((b, bi) => {
3142
+ if (usable[bi]) {
3143
+ byAtom[b.a]?.push(bi);
3144
+ if (b.b !== b.a) byAtom[b.b]?.push(bi);
3145
+ }
3146
+ });
3147
+ let steps = 0;
3148
+ const solve = (k2) => {
3149
+ if (forms2.length >= limit || ++steps > 2e4) return;
3150
+ if (k2 === atoms.length) {
3151
+ const set2 = new Set(mate.values());
3152
+ forms2.push(start2.map((b, i2) => usable[i2] ? { ...b, order: set2.has(i2) ? 2 : 1 } : b));
3153
+ return;
3154
+ }
3155
+ const x2 = atoms[k2];
3156
+ if (mate.has(x2)) {
3157
+ solve(k2 + 1);
3158
+ return;
3159
+ }
3160
+ for (const bi of byAtom[x2]) {
3161
+ const b = start2[bi];
3162
+ const y2 = b.a === x2 ? b.b : b.a;
3163
+ if (mate.has(y2)) continue;
3164
+ mate.set(x2, bi);
3165
+ mate.set(y2, bi);
3166
+ solve(k2 + 1);
3167
+ mate.delete(x2);
3168
+ mate.delete(y2);
3169
+ }
3170
+ };
3171
+ solve(0);
3172
+ return forms2.length ? forms2 : [start2];
3173
+ }
3174
+ function sameGroupGraph(a2, b, attachment, forms2) {
3175
+ const count = a2.atoms.length;
3176
+ if (!count || count > MAX_LABEL_ATOMS || count !== b.atoms.length || a2.bonds.length !== b.bonds.length) return false;
3177
+ const adjacency = (bonds) => {
3178
+ const edges = Array.from({ length: count }, () => /* @__PURE__ */ new Map());
3179
+ for (const { a: a22, b: b2, order } of bonds) {
3180
+ if (!edges[a22] || !edges[b2] || a22 === b2 || edges[a22].has(b2)) return null;
3181
+ edges[a22].set(b2, order);
3182
+ edges[b2].set(a22, order);
3183
+ }
3184
+ return edges;
3185
+ };
3186
+ const keys = (g2, edges, head) => g2.atoms.map((at2, i2) => `${i2 === head}:${at2.dummy ? "*" : at2.z}:${at2.charge}:${at2.iso ?? 0}:${at2.hCount ?? "?"}:${[...edges[i2].values()].sort().join(",")}`);
3187
+ const matches = (ab, bb) => {
3188
+ const left = adjacency(ab), right = adjacency(bb);
3189
+ if (!left || !right) return false;
3190
+ const buckets = /* @__PURE__ */ new Map();
3191
+ keys(b, right, attachment).forEach((key2, i2) => {
3192
+ const bucket = buckets.get(key2);
3193
+ if (bucket) bucket.push(i2);
3194
+ else buckets.set(key2, [i2]);
3195
+ });
3196
+ const choices = keys(a2, left, attachment === void 0 ? void 0 : 0).map((key2) => buckets.get(key2) ?? []);
3197
+ if (choices.some((c2) => !c2.length)) return false;
3198
+ const order = choices.map((_2, i2) => i2).sort((u2, v) => choices[u2].length - choices[v].length || left[v].size - left[u2].size);
3199
+ const paired = Array(count).fill(-1);
3200
+ const taken = Array(count).fill(false);
3201
+ let tried = 0;
3202
+ const walk = (depth) => {
3203
+ if (depth === count) return true;
3204
+ const u2 = order[depth];
3205
+ for (const v of choices[u2]) {
3206
+ if (taken[v]) continue;
3207
+ if (++tried > 2e4) return false;
3208
+ const agrees = [...left[u2]].every(([n2, bond]) => paired[n2] < 0 || right[v].get(paired[n2]) === bond);
3209
+ if (!agrees) continue;
3210
+ paired[u2] = v;
3211
+ taken[v] = true;
3212
+ if (walk(depth + 1)) return true;
3213
+ paired[u2] = -1;
3214
+ taken[v] = false;
3215
+ }
3216
+ return false;
3217
+ };
3218
+ return walk(0);
3219
+ };
3220
+ if (matches(a2.bonds, b.bonds)) return true;
3221
+ const bk = kekuleForms(b, attachment, 1)[0];
3222
+ return (forms2 ?? kekuleForms(a2, attachment === void 0 ? void 0 : 0)).some((ak) => matches(ak, bk));
3223
+ }
3224
+ function sameNicknameSmiles(a2, b) {
3225
+ if (a2 === b) return true;
3226
+ if (/[@\/\\]/.test(a2) || /[@\/\\]/.test(b)) return false;
3227
+ const ga = parseSmiles(a2), gb = parseSmiles(b);
3228
+ if (ga.atoms.length !== gb.atoms.length || ga.bonds.length !== gb.bonds.length || ga.atoms.length > MAX_LABEL_ATOMS) return false;
3229
+ const graph = (g2) => {
3230
+ const used = g2.atoms.map((_2, i2) => i2 === 0 ? 1 : 0);
3231
+ for (const { a: a22, b: b2, order } of kekuleForms(g2, 0, 1)[0]) {
3232
+ used[a22] += order;
3233
+ used[b2] += order;
3234
+ }
3235
+ return { ...g2, atoms: g2.atoms.map((at2, i2) => ({ ...at2, hCount: at2.hCount ?? implicitHydrogens(at2.z, used[i2], at2.charge) })) };
3236
+ };
3237
+ return sameGroupGraph(graph(ga), graph(gb), 0);
3238
+ }
3050
3239
  const nickCache = /* @__PURE__ */ new Map();
3051
3240
  function nickGraph(name) {
3052
3241
  let g2 = nickCache.get(name);
@@ -3170,6 +3359,27 @@ class LabelBuilder {
3170
3359
  });
3171
3360
  return out;
3172
3361
  }
3362
+ /**
3363
+ * Is a single I right after an aryl group (atom `b`, its head) a hypervalent centre holding the
3364
+ * rest of the label, as in PhICl2, PhIO2, PhI(OAc)2, PhIO and ArI(OAc)2? Only when the aryl has
3365
+ * no room left and everything after the I is its ligands (see hypervalentLigands). Not after a
3366
+ * metal, B, Si, Sn or a C written out (PdIPh, Bu3SnIPh, CHICl2, CH2IPh): there the I is the
3367
+ * atom before's, as before.
3368
+ */
3369
+ hypervalentAfter(b, z2, rest, aryl) {
3370
+ if (z2 !== 53 || !hypervalentLigands(rest, 1) || !this.heads.has(b) || this.body.has(b)) return false;
3371
+ if (this.open(b) - 1 >= ligandBonds(rest[0])) return false;
3372
+ this.hyper = this.g.atoms.length;
3373
+ if (b === 0) {
3374
+ const smiles = "tok" in aryl && aryl.tok.kind === "nick" ? NICKNAMES[aryl.tok.text] : void 0;
3375
+ this.arylAttachment = smiles === NICKNAMES.Ph ? 3 : 0;
3376
+ }
3377
+ return true;
3378
+ }
3379
+ /** The hypervalent I a label's ligands go on (PhICl2), or −1. */
3380
+ hyper = -1;
3381
+ /** The aryl atom a PhICl2-type label bonds to the structure by, when it has one bond (or 0). */
3382
+ arylAttachment = 0;
3173
3383
  setCharge(i2, text2) {
3174
3384
  if (i2 >= 0 && text2) this.g.atoms[i2].charge = signedCharge(text2);
3175
3385
  }
@@ -3265,7 +3475,7 @@ class LabelBuilder {
3265
3475
  if (b >= 0) this.bond(b, last);
3266
3476
  else if (r === 0) this.backbone = last;
3267
3477
  }
3268
- } else if (oneBond(z2) && z2 !== 1 && n2 === 1 && b >= 0 && order === 1 && !oneBond(this.g.atoms[b].z) && !(oxoNext && this.g.atoms[b].z === 8) && !twiceNext) {
3478
+ } else if (oneBond(z2) && z2 !== 1 && n2 === 1 && b >= 0 && order === 1 && (!oneBond(this.g.atoms[b].z) || b === this.hyper) && !(oxoNext && this.g.atoms[b].z === 8) && !twiceNext && !(prev && isArylItem(prev) && this.hypervalentAfter(b, z2, items.slice(k2 + 1), prev))) {
3269
3479
  last = this.add(z2, { ...extra });
3270
3480
  this.bond(b, last);
3271
3481
  } else if (z2 === 1 && n2 === 1 && b >= 0 && order === 1) {
@@ -3285,6 +3495,7 @@ class LabelBuilder {
3285
3495
  group(it) {
3286
3496
  const sub2 = new LabelBuilder(0);
3287
3497
  sub2.seq(it.group);
3498
+ sub2.attachAryl(this.backbone >= 0 ? 1 : this.ext);
3288
3499
  const n2 = sub2.g.atoms.length;
3289
3500
  if (!n2) return;
3290
3501
  const b = this.backbone, only = sub2.g.atoms[0];
@@ -3302,7 +3513,7 @@ class LabelBuilder {
3302
3513
  open += o;
3303
3514
  if (o > 0) tail = i2;
3304
3515
  }
3305
- const chain = !it.hang && (open >= 2 || this.backbone < 0);
3516
+ const chain = !it.hang && (b < 0 || open >= 2 && !(n2 === 1 && oneBond(only.z)));
3306
3517
  if (this.g.atoms.length + n2 * it.count > MAX_LABEL_ATOMS) throw new TooBig();
3307
3518
  for (let r = 0; r < it.count; r++) {
3308
3519
  const off = this.g.atoms.length;
@@ -3315,7 +3526,23 @@ class LabelBuilder {
3315
3526
  }
3316
3527
  this.setCharge(this.backbone, it.charge);
3317
3528
  }
3529
+ /**
3530
+ * PhICl2 with one bond to the structure bonds by its para carbon (atom 3 moved to atom 0); with
3531
+ * none, or with more than its one H allows, it keeps atom 0, as other aryls do.
3532
+ */
3533
+ attachAryl(ext) {
3534
+ const at2 = this.arylAttachment;
3535
+ if (ext !== 1 || !at2) return;
3536
+ [this.g.atoms[0], this.g.atoms[at2]] = [this.g.atoms[at2], this.g.atoms[0]];
3537
+ const swap = (i2) => i2 === 0 ? at2 : i2 === at2 ? 0 : i2;
3538
+ for (const b of this.g.bonds) {
3539
+ b.a = swap(b.a);
3540
+ b.b = swap(b.b);
3541
+ }
3542
+ this.body.delete(at2);
3543
+ }
3318
3544
  finish() {
3545
+ this.attachAryl(this.ext);
3319
3546
  if (!this.g.atoms.length && this.pendingH) {
3320
3547
  const n2 = this.pendingH, q = this.pendingCharge;
3321
3548
  this.pendingH = 0;
@@ -3332,6 +3559,7 @@ function terminal(it) {
3332
3559
  if (!("tok" in it)) {
3333
3560
  const b = new LabelBuilder(0);
3334
3561
  b.seq(it.group);
3562
+ if (b.g.atoms.length === 1 && oneBond(b.g.atoms[0].z)) return true;
3335
3563
  let open = 0;
3336
3564
  for (let i2 = 0; i2 < b.g.atoms.length; i2++) open += b.open(i2);
3337
3565
  return open <= 1;
@@ -3340,6 +3568,43 @@ function terminal(it) {
3340
3568
  if (t.kind === "nick" || t.kind === "generic") return true;
3341
3569
  return t.kind === "el" && t.text !== "H" && oneBond(elementNumber(t.text) ?? 0);
3342
3570
  }
3571
+ function ligandBonds(it) {
3572
+ if (!it) return 0;
3573
+ if (isBond(it)) return it.bond;
3574
+ return Math.max(1, "group" in it ? it.count : it.tok.count);
3575
+ }
3576
+ function isArylItem(it) {
3577
+ if (!("tok" in it) || it.tok.count > 1 || it.tok.charge) return false;
3578
+ const t = it.tok;
3579
+ if (t.kind === "generic") return /^Ar\d*$/.test(t.text);
3580
+ const a2 = t.kind === "nick" ? nickGraph(t.text).atoms[0] : void 0;
3581
+ return !!a2 && (a2.aromatic || !!a2.dummy && /^Ar\d*$/.test(a2.generic ?? ""));
3582
+ }
3583
+ function ligandGroup(g2) {
3584
+ const f4 = g2.group[0];
3585
+ if (!f4 || !("tok" in f4) || f4.tok.kind !== "el" || f4.tok.count > 1 || !["O", "F", "Cl", "Br", "I"].includes(f4.tok.text)) return false;
3586
+ const second = g2.group[1];
3587
+ if (f4.tok.text === "O" && second && "tok" in second && second.tok.kind === "nick" && nickGraph(second.tok.text).atoms[0]?.z === 8) return false;
3588
+ return g2.group.length > 1 || f4.tok.text !== "O";
3589
+ }
3590
+ function hypervalentLigands(rest, before) {
3591
+ if (!rest.length) return false;
3592
+ let bonds = before;
3593
+ const ok = rest.every((it, i2) => {
3594
+ if (isBond(it)) {
3595
+ const o = rest[i2 + 1];
3596
+ return it.bond === 2 && !!o && "tok" in o && o.tok.text === "O" && o.tok.count <= 1;
3597
+ }
3598
+ if ("group" in it) {
3599
+ bonds += it.count;
3600
+ return !it.charge && ligandGroup(it);
3601
+ }
3602
+ const t = it.tok;
3603
+ bonds += Math.max(1, t.count) * (t.text === "O" ? 2 : 1);
3604
+ return t.kind === "el" && !t.charge && (t.text === "O" || t.text === "F" || t.text === "Cl" || t.text === "Br");
3605
+ });
3606
+ return ok && bonds % 2 === 1 && bonds <= 5;
3607
+ }
3343
3608
  function oneBond(z2) {
3344
3609
  return z2 === 1 || z2 === 9 || z2 === 17 || z2 === 35 || z2 === 53 || z2 === 85 || (maxValence(z2) ?? 2) <= 1;
3345
3610
  }
@@ -3378,6 +3643,14 @@ function reversedItems(items, ext) {
3378
3643
  if (!units2 || units2.length < 2) return null;
3379
3644
  const first = units2[0][0];
3380
3645
  const el = (u2, sym, count = 1) => !!u2 && u2.length === 1 && "tok" in u2[0] && u2[0].tok.kind === "el" && u2[0].tok.text === sym && u2[0].tok.count <= count && !u2[0].tok.charge;
3646
+ const hal = ["Cl", "Br", "I"].find((x2) => el(units2[0], x2));
3647
+ const second = units2.length === 2 && units2[1].length === 1 ? units2[1][0] : null;
3648
+ if (hal && second && "tok" in second && second.tok.kind === "el" && second.tok.text === "O" && (second.tok.count === 3 || second.tok.count === 4) && !second.tok.charge) {
3649
+ const o = (count) => ({ tok: { ...second.tok, count, explicit: false } });
3650
+ return [o(1), units2[0][0], o(second.tok.count - 1)];
3651
+ }
3652
+ if (hal === "I" && second && !isBond(second) && ("group" in second ? second.count > 1 : second.tok.count > 1) && hypervalentLigands([second], 1)) return items;
3653
+ if (units2.length >= 3 && units2[0].length === 1 && isArylItem(first) && el(units2[1], "I") && hypervalentLigands(units2.slice(2).flat(), 1)) return items;
3381
3654
  if ("tok" in first && first.tok.kind === "el" && (first.tok.text === "O" || first.tok.text === "S") && first.tok.count > 1 && !first.tok.charge && units2[0].length === 1) {
3382
3655
  const mid = units2[1];
3383
3656
  const centre2 = mid[0];
@@ -3426,6 +3699,8 @@ function leadingGroupsFirst(items) {
3426
3699
  const atom = items[k2];
3427
3700
  if (!atom || !("tok" in atom) || atom.tok.kind !== "el" || atom.tok.text === "H" || atom.tok.count > 1) return null;
3428
3701
  if (groups2 < 1 || groups2 < 2 && !DONOR_ATOMS.has(atom.tok.text)) return null;
3702
+ const last = items[k2 - 1], lead = items[0];
3703
+ if (k2 === 2 && atom.tok.text === "O" && !atom.tok.charge && k2 + 1 === items.length && "tok" in last && last.tok.kind === "el" && last.tok.text === "I" && last.tok.count <= 1 && !last.tok.charge && isArylItem(lead)) return null;
3429
3704
  const front = items.slice(0, k2).map((it) => {
3430
3705
  if (!("tok" in it)) return it;
3431
3706
  const t = it.tok;
@@ -3553,6 +3828,711 @@ const CARBONYL_AS_DRAWN = parseSmiles("C#O");
3553
3828
  function labelOverValent(label, ext = 1, charge = 0) {
3554
3829
  return buildLabel(label, ext, charge).over;
3555
3830
  }
3831
+ function labelCharge(label) {
3832
+ if (!label) return 0;
3833
+ const toks = tokenize$1(label);
3834
+ const text2 = toks[toks.length - 1]?.charge ?? "";
3835
+ const m2 = /^(\d*)([+\-−]+)$/.exec(text2);
3836
+ if (!m2) return 0;
3837
+ const sign = m2[2][0] === "+" ? 1 : -1;
3838
+ return sign * (m2[1] ? Number(m2[1]) : m2[2].length);
3839
+ }
3840
+ function atomCharge(a2) {
3841
+ return a2.charge || labelCharge(a2.label);
3842
+ }
3843
+ const key$2 = (ring2) => [...ring2].sort((a2, b) => a2 - b).join(",");
3844
+ function ringAvoiding(doc, bondId, avoid, maxSize = 8) {
3845
+ const b = doc.bonds.get(bondId);
3846
+ if (!b) return null;
3847
+ const prev = /* @__PURE__ */ new Map([[b.a2, -1]]);
3848
+ let frontier = [b.a2];
3849
+ for (let depth = 1; depth < maxSize && frontier.length; depth++) {
3850
+ const next = [];
3851
+ for (const id of frontier) {
3852
+ for (const bid of doc.adj.get(id) ?? []) {
3853
+ if (bid === bondId) continue;
3854
+ const bb = doc.bonds.get(bid);
3855
+ const o = bb.a1 === id ? bb.a2 : bb.a1;
3856
+ if (prev.has(o) || avoid.has(o)) continue;
3857
+ prev.set(o, id);
3858
+ if (o === b.a1) {
3859
+ const path = [o];
3860
+ let cur = id;
3861
+ while (cur !== -1) {
3862
+ path.push(cur);
3863
+ cur = prev.get(cur);
3864
+ }
3865
+ return path;
3866
+ }
3867
+ next.push(o);
3868
+ }
3869
+ }
3870
+ frontier = next;
3871
+ }
3872
+ return null;
3873
+ }
3874
+ function ringsThroughBond(doc, bondId, maxSize = 8) {
3875
+ const first = ringAvoiding(doc, bondId, /* @__PURE__ */ new Set(), maxSize);
3876
+ if (!first) return [];
3877
+ const b = doc.bonds.get(bondId);
3878
+ const inner = new Set(first.filter((a2) => a2 !== b.a1 && a2 !== b.a2));
3879
+ const second = ringAvoiding(doc, bondId, inner, maxSize);
3880
+ return second && key$2(second) !== key$2(first) ? [first, second] : [first];
3881
+ }
3882
+ function bondBetween(doc, a2, c2) {
3883
+ for (const bid of doc.adj.get(a2) ?? []) {
3884
+ const b = doc.bonds.get(bid);
3885
+ if (b.a1 === c2 || b.a2 === c2) return bid;
3886
+ }
3887
+ return void 0;
3888
+ }
3889
+ function ringBonds$1(doc, ring2) {
3890
+ const out = [];
3891
+ for (let i2 = 0; i2 < ring2.length; i2++) {
3892
+ const b = bondBetween(doc, ring2[i2], ring2[(i2 + 1) % ring2.length]);
3893
+ if (b !== void 0) out.push(b);
3894
+ }
3895
+ return out;
3896
+ }
3897
+ function isCircleRing(doc, ring2) {
3898
+ const bs = ringBonds$1(doc, ring2);
3899
+ return bs.length === ring2.length && bs.every((id) => {
3900
+ const b = doc.bonds.get(id);
3901
+ return b.order === 1.5 && !!b.circle;
3902
+ });
3903
+ }
3904
+ function ringCircle(doc, ring2) {
3905
+ return circleIn(ring2.map((id) => doc.atoms.get(id)));
3906
+ }
3907
+ function circleIn(pts2) {
3908
+ const n2 = pts2.length;
3909
+ let x2 = 0, y2 = 0;
3910
+ for (const p2 of pts2) {
3911
+ x2 += p2.x;
3912
+ y2 += p2.y;
3913
+ }
3914
+ const center = { x: x2 / n2, y: y2 / n2 };
3915
+ let apothem = Infinity;
3916
+ for (let i2 = 0; i2 < n2; i2++) {
3917
+ const p2 = pts2[i2], q = pts2[(i2 + 1) % n2];
3918
+ apothem = Math.min(apothem, Math.hypot((p2.x + q.x) / 2 - center.x, (p2.y + q.y) / 2 - center.y));
3919
+ }
3920
+ const plain = { center, radius: 0.62 * apothem };
3921
+ if (n2 < 3) return plain;
3922
+ let a2 = 0, b = 0, c2 = 0, d2 = 0;
3923
+ pts2.forEach((p2, k2) => {
3924
+ const u2 = Math.cos(2 * Math.PI * k2 / n2), v = Math.sin(2 * Math.PI * k2 / n2);
3925
+ a2 += (p2.x - center.x) * u2;
3926
+ b += (p2.x - center.x) * v;
3927
+ c2 += (p2.y - center.y) * u2;
3928
+ d2 += (p2.y - center.y) * v;
3929
+ });
3930
+ const m2 = [2 * a2 / n2, 2 * b / n2, 2 * c2 / n2, 2 * d2 / n2];
3931
+ let miss = 0, size = 0;
3932
+ pts2.forEach((p2, k2) => {
3933
+ const u2 = Math.cos(2 * Math.PI * k2 / n2), v = Math.sin(2 * Math.PI * k2 / n2);
3934
+ miss = Math.max(miss, Math.hypot(center.x + m2[0] * u2 + m2[1] * v - p2.x, center.y + m2[2] * u2 + m2[3] * v - p2.y));
3935
+ size += Math.hypot(p2.x - center.x, p2.y - center.y) / n2;
3936
+ });
3937
+ if (miss > 0.12 * size) return plain;
3938
+ const [s1, s2] = singularValues(m2);
3939
+ if (s2 > 0.96 * s1) return plain;
3940
+ return { center, radius: plain.radius, ellipse: { m: m2, r: 0.62 * Math.cos(Math.PI / n2) } };
3941
+ }
3942
+ function singularValues([a2, b, c2, d2]) {
3943
+ const s = a2 * a2 + b * b + c2 * c2 + d2 * d2, det = a2 * d2 - b * c2;
3944
+ const root2 = Math.sqrt(Math.max(0, s * s - 4 * det * det));
3945
+ return [Math.sqrt((s + root2) / 2), Math.sqrt(Math.max(0, (s - root2) / 2))];
3946
+ }
3947
+ function ellipseAxes(e) {
3948
+ const [a2, b, c2, d2] = e.m;
3949
+ const phi = 0.5 * Math.atan2(2 * (a2 * b + c2 * d2), a2 * a2 + c2 * c2 - b * b - d2 * d2);
3950
+ const at2 = (f4) => ({ x: (a2 * Math.cos(f4) + b * Math.sin(f4)) * e.r, y: (c2 * Math.cos(f4) + d2 * Math.sin(f4)) * e.r });
3951
+ const p2 = at2(phi), q = at2(phi + Math.PI / 2);
3952
+ return Math.hypot(p2.x, p2.y) >= Math.hypot(q.x, q.y) ? { major: p2, minor: q } : { major: q, minor: p2 };
3953
+ }
3954
+ function ellipseArc(center, e, p2, q, steps = 14) {
3955
+ const [a2, b, c2, d2] = e.m;
3956
+ const det = a2 * d2 - b * c2 || 1e-12;
3957
+ const phiOf = (v) => {
3958
+ const dx = v.x - center.x, dy = v.y - center.y;
3959
+ return Math.atan2((-c2 * dx + a2 * dy) / det, (d2 * dx - b * dy) / det);
3960
+ };
3961
+ const f1 = phiOf(p2);
3962
+ let df = phiOf(q) - f1;
3963
+ while (df > Math.PI) df -= 2 * Math.PI;
3964
+ while (df < -Math.PI) df += 2 * Math.PI;
3965
+ const out = [];
3966
+ for (let k2 = 0; k2 <= steps; k2++) {
3967
+ const f4 = f1 + df * k2 / steps;
3968
+ out.push({ x: center.x + (a2 * Math.cos(f4) + b * Math.sin(f4)) * e.r, y: center.y + (c2 * Math.cos(f4) + d2 * Math.sin(f4)) * e.r });
3969
+ }
3970
+ return out;
3971
+ }
3972
+ function ringsAmong(doc, bonds, maxSize = 8) {
3973
+ const seen = /* @__PURE__ */ new Map();
3974
+ const ids = [...bonds];
3975
+ for (const id of ids.length ? ids : doc.bonds.keys()) for (const r of ringsThroughBond(doc, id, maxSize)) seen.set(key$2(r), r);
3976
+ return [...seen.values()];
3977
+ }
3978
+ function kekuleDoubles(doc, todo, strict = false) {
3979
+ const atoms = [...new Set([...todo].flatMap((id) => {
3980
+ const b = doc.bonds.get(id);
3981
+ return [b.a1, b.a2];
3982
+ }))];
3983
+ const optional = (id) => {
3984
+ const a2 = doc.atoms.get(id);
3985
+ if (a2.z !== 6 || a2.charge !== 0 || strict && a2.label) return true;
3986
+ return [...doc.adj.get(id) ?? []].some((bid) => !todo.has(bid) && doc.bonds.get(bid).order === 2);
3987
+ };
3988
+ const room = (id) => {
3989
+ if (!strict) return true;
3990
+ const a2 = doc.atoms.get(id);
3991
+ if (isMetalAtom(a2)) return true;
3992
+ let used = 0;
3993
+ for (const bid of doc.adj.get(id) ?? []) {
3994
+ const b = doc.bonds.get(bid);
3995
+ if (todo.has(bid)) {
3996
+ used += 1;
3997
+ continue;
3998
+ }
3999
+ if (outsideValence(b) || isMetalAtom(doc.atoms.get(b.a1 === id ? b.a2 : b.a1))) continue;
4000
+ used += b.order === 1.5 ? 1 : b.order;
4001
+ }
4002
+ if (a2.label) return !!a2.group || labelOverValent(a2.label, used + 1, a2.charge).length === 0;
4003
+ const max2 = maxValence(a2.z, a2.charge);
4004
+ return max2 === void 0 || used + 1 <= max2;
4005
+ };
4006
+ const paired = /* @__PURE__ */ new Map();
4007
+ const chosen = /* @__PURE__ */ new Set();
4008
+ const comp = /* @__PURE__ */ new Map();
4009
+ const comps = [];
4010
+ for (const start2 of atoms) {
4011
+ if (comp.has(start2)) continue;
4012
+ const list2 = [start2];
4013
+ comp.set(start2, comps.length);
4014
+ for (let k2 = 0; k2 < list2.length; k2++) for (const bid of doc.adj.get(list2[k2]) ?? []) {
4015
+ if (!todo.has(bid)) continue;
4016
+ const b = doc.bonds.get(bid);
4017
+ const o = b.a1 === list2[k2] ? b.a2 : b.a1;
4018
+ if (!comp.has(o)) {
4019
+ comp.set(o, comps.length);
4020
+ list2.push(o);
4021
+ }
4022
+ }
4023
+ comps.push(list2);
4024
+ }
4025
+ if (comps.some((c2) => c2.length % 2 === 1 && !c2.some(optional))) return null;
4026
+ let part2 = [];
4027
+ let steps = 0;
4028
+ const STEPS = 2e4;
4029
+ const solve = (i2) => {
4030
+ if (++steps > STEPS) return null;
4031
+ if (i2 === part2.length) return true;
4032
+ const a2 = part2[i2];
4033
+ if (paired.has(a2)) return solve(i2 + 1);
4034
+ for (const bid of doc.adj.get(a2) ?? []) {
4035
+ if (!todo.has(bid)) continue;
4036
+ const b = doc.bonds.get(bid);
4037
+ const o = b.a1 === a2 ? b.a2 : b.a1;
4038
+ if (paired.has(o) || !room(a2) || !room(o)) continue;
4039
+ paired.set(a2, o);
4040
+ paired.set(o, a2);
4041
+ chosen.add(bid);
4042
+ const r = solve(i2 + 1);
4043
+ if (r !== false) return r;
4044
+ paired.delete(a2);
4045
+ paired.delete(o);
4046
+ chosen.delete(bid);
4047
+ }
4048
+ return optional(a2) ? solve(i2 + 1) : false;
4049
+ };
4050
+ for (let k2 = 0; k2 < comps.length; k2++) {
4051
+ part2 = atoms.filter((a2) => comp.get(a2) === k2);
4052
+ const sys = systemKekule(doc, todo, part2);
4053
+ if (sys) {
4054
+ for (const bid of sys.doubles) {
4055
+ const b = doc.bonds.get(bid);
4056
+ chosen.add(bid);
4057
+ paired.set(b.a1, b.a2);
4058
+ paired.set(b.a2, b.a1);
4059
+ }
4060
+ continue;
4061
+ }
4062
+ steps = 0;
4063
+ const r = solve(0);
4064
+ if (r === false) return null;
4065
+ if (r === true) continue;
4066
+ for (const a2 of part2) paired.delete(a2);
4067
+ for (const bid of [...chosen]) {
4068
+ const b = doc.bonds.get(bid);
4069
+ if (comp.get(b.a1) === k2) chosen.delete(bid);
4070
+ }
4071
+ const found = matchedBonds(doc, todo, part2, optional, room);
4072
+ if (!found) return null;
4073
+ for (const bid of found) {
4074
+ const b = doc.bonds.get(bid);
4075
+ chosen.add(bid);
4076
+ paired.set(b.a1, b.a2);
4077
+ paired.set(b.a2, b.a1);
4078
+ }
4079
+ }
4080
+ return chosen;
4081
+ }
4082
+ function matchedBonds(doc, todo, part2, optional, room) {
4083
+ const n2 = part2.length;
4084
+ const index2 = new Map(part2.map((a2, i2) => [a2, i2]));
4085
+ const adj = Array.from({ length: 2 * n2 }, () => []);
4086
+ const bondOf2 = /* @__PURE__ */ new Map();
4087
+ for (let i2 = 0; i2 < n2; i2++) {
4088
+ const a2 = part2[i2];
4089
+ if (!room(a2) && !optional(a2)) return null;
4090
+ if (optional(a2)) {
4091
+ adj[i2].push(i2 + n2);
4092
+ adj[i2 + n2].push(i2);
4093
+ }
4094
+ if (!room(a2)) continue;
4095
+ for (const bid of doc.adj.get(a2) ?? []) {
4096
+ if (!todo.has(bid)) continue;
4097
+ const b = doc.bonds.get(bid);
4098
+ const j = index2.get(b.a1 === a2 ? b.a2 : b.a1);
4099
+ if (j === void 0 || j <= i2 || !room(part2[j])) continue;
4100
+ adj[i2].push(j);
4101
+ adj[j].push(i2);
4102
+ adj[i2 + n2].push(j + n2);
4103
+ adj[j + n2].push(i2 + n2);
4104
+ bondOf2.set(i2 * n2 + j, bid);
4105
+ }
4106
+ }
4107
+ const match = maximumMatching(adj);
4108
+ if (match.some((m2) => m2 < 0)) return null;
4109
+ const out = [];
4110
+ for (let i2 = 0; i2 < n2; i2++) if (match[i2] >= 0 && match[i2] < n2 && match[i2] > i2) out.push(bondOf2.get(i2 * n2 + match[i2]));
4111
+ return out;
4112
+ }
4113
+ function maximumMatching(adj) {
4114
+ const n2 = adj.length;
4115
+ const match = new Array(n2).fill(-1), p2 = new Array(n2).fill(-1), base = new Array(n2).fill(0);
4116
+ const used = new Array(n2).fill(false), blossom = new Array(n2).fill(false);
4117
+ const lca = (a2, b) => {
4118
+ const seen = new Array(n2).fill(false);
4119
+ for (; ; ) {
4120
+ a2 = base[a2];
4121
+ seen[a2] = true;
4122
+ if (match[a2] < 0) break;
4123
+ a2 = p2[match[a2]];
4124
+ }
4125
+ for (; ; ) {
4126
+ b = base[b];
4127
+ if (seen[b]) return b;
4128
+ b = p2[match[b]];
4129
+ }
4130
+ };
4131
+ const markPath = (v, b, child) => {
4132
+ while (base[v] !== b) {
4133
+ blossom[base[v]] = blossom[base[match[v]]] = true;
4134
+ p2[v] = child;
4135
+ child = match[v];
4136
+ v = p2[match[v]];
4137
+ }
4138
+ };
4139
+ const findPath = (root2) => {
4140
+ used.fill(false);
4141
+ p2.fill(-1);
4142
+ for (let i2 = 0; i2 < n2; i2++) base[i2] = i2;
4143
+ used[root2] = true;
4144
+ const q = [root2];
4145
+ for (let h = 0; h < q.length; h++) {
4146
+ const v = q[h];
4147
+ for (const to of adj[v]) {
4148
+ if (base[v] === base[to] || match[v] === to) continue;
4149
+ if (to === root2 || match[to] >= 0 && p2[match[to]] >= 0) {
4150
+ const cur = lca(v, to);
4151
+ blossom.fill(false);
4152
+ markPath(v, cur, to);
4153
+ markPath(to, cur, v);
4154
+ for (let i2 = 0; i2 < n2; i2++) if (blossom[base[i2]]) {
4155
+ base[i2] = cur;
4156
+ if (!used[i2]) {
4157
+ used[i2] = true;
4158
+ q.push(i2);
4159
+ }
4160
+ }
4161
+ } else if (p2[to] < 0) {
4162
+ p2[to] = v;
4163
+ if (match[to] < 0) return to;
4164
+ used[match[to]] = true;
4165
+ q.push(match[to]);
4166
+ }
4167
+ }
4168
+ }
4169
+ return -1;
4170
+ };
4171
+ for (let v = 0; v < n2; v++) if (match[v] < 0) {
4172
+ for (const to of adj[v]) if (match[to] < 0) {
4173
+ match[v] = to;
4174
+ match[to] = v;
4175
+ break;
4176
+ }
4177
+ }
4178
+ for (let v = 0; v < n2; v++) {
4179
+ if (match[v] >= 0) continue;
4180
+ let u2 = findPath(v);
4181
+ while (u2 >= 0) {
4182
+ const pv = p2[u2], ppv = match[pv];
4183
+ match[u2] = pv;
4184
+ match[pv] = u2;
4185
+ u2 = ppv;
4186
+ }
4187
+ }
4188
+ return match;
4189
+ }
4190
+ function kekuleRoles(doc, todo, atoms) {
4191
+ const roles = /* @__PURE__ */ new Map();
4192
+ for (const id of atoms) {
4193
+ const a2 = doc.atoms.get(id);
4194
+ let k2 = 0, other = 0, extra = false, double = false;
4195
+ for (const bid of doc.adj.get(id) ?? []) {
4196
+ const b = doc.bonds.get(bid);
4197
+ if (todo.has(bid)) k2++;
4198
+ else if (b.display === "dative") extra = true;
4199
+ else if (outsideValence(b)) continue;
4200
+ else if (isMetalAtom(doc.atoms.get(b.a1 === id ? b.a2 : b.a1))) extra = true;
4201
+ else {
4202
+ other += b.order === 1.5 ? 1 : b.order;
4203
+ if (b.order >= 2) double = true;
4204
+ }
4205
+ }
4206
+ let role = "free";
4207
+ if (double && a2.z === 6) role = "none";
4208
+ else if (a2.z === 6 && !a2.group) {
4209
+ const room = other + k2 < 4 && (!a2.label || !labelOverValent(a2.label, other + k2 + 1, a2.charge).length);
4210
+ role = !a2.charge && room ? "must" : "none";
4211
+ } else if (a2.label && a2.label !== SYMBOLS$2[a2.z]) {
4212
+ const cation = atomCharge(a2) > 0 && (a2.z === 7 || a2.z === 15);
4213
+ role = cation && other + k2 < 4 && !labelOverValent(a2.label, other + k2 + 1, a2.charge).length ? "must" : "none";
4214
+ } else if (a2.radical) role = "free";
4215
+ else if (a2.z === 7 || a2.z === 15) {
4216
+ if (a2.charge > 0) role = 4 - other - k2 >= 1 ? "must" : "none";
4217
+ else if (a2.charge < 0) role = "none";
4218
+ else if (k2 === 2 && other === 0) role = extra || a2.label ? "pair" : "nh";
4219
+ else role = 3 - other - k2 >= 1 ? "free" : "none";
4220
+ } else if (a2.z === 8 || a2.z === 16 || a2.z === 34 || a2.z === 52) {
4221
+ if (a2.charge > 0) role = 3 - other - k2 >= 1 ? "must" : "none";
4222
+ else role = !a2.charge && k2 === 2 && other === 0 ? "none" : "free";
4223
+ } else if (a2.z === 5) role = "none";
4224
+ roles.set(id, role);
4225
+ }
4226
+ return roles;
4227
+ }
4228
+ function ringPath(doc, todo, from, to, avoid) {
4229
+ const prev = /* @__PURE__ */ new Map([[from, -1]]);
4230
+ const q = [from];
4231
+ for (let h = 0; h < q.length; h++) {
4232
+ const x2 = q[h];
4233
+ if (x2 === to) {
4234
+ const path = [];
4235
+ for (let c2 = x2; c2 !== -1; c2 = prev.get(c2)) path.push(c2);
4236
+ return path.reverse();
4237
+ }
4238
+ for (const bid of doc.adj.get(x2) ?? []) {
4239
+ if (!todo.has(bid)) continue;
4240
+ const b = doc.bonds.get(bid);
4241
+ const o = b.a1 === x2 ? b.a2 : b.a1;
4242
+ if (o === avoid || prev.has(o)) continue;
4243
+ prev.set(o, x2);
4244
+ q.push(o);
4245
+ }
4246
+ }
4247
+ return null;
4248
+ }
4249
+ function blossomMatcher(adj) {
4250
+ const n2 = adj.length;
4251
+ const match = maximumMatching(adj);
4252
+ const gone = /* @__PURE__ */ new Set(), dropped = new Array(n2).fill(false);
4253
+ const edge = (a2, b) => a2 < b ? a2 + "," + b : b + "," + a2;
4254
+ const ok = (a2, b) => !dropped[a2] && !dropped[b] && !gone.has(edge(a2, b));
4255
+ const p2 = new Array(n2).fill(-1), base = new Array(n2).fill(0);
4256
+ const used = new Array(n2).fill(false), blossom = new Array(n2).fill(false);
4257
+ const lca = (a2, b) => {
4258
+ const seen = new Array(n2).fill(false);
4259
+ for (; ; ) {
4260
+ a2 = base[a2];
4261
+ seen[a2] = true;
4262
+ if (match[a2] < 0) break;
4263
+ a2 = p2[match[a2]];
4264
+ }
4265
+ for (; ; ) {
4266
+ b = base[b];
4267
+ if (seen[b]) return b;
4268
+ b = p2[match[b]];
4269
+ }
4270
+ };
4271
+ const markPath = (v, b, child) => {
4272
+ while (base[v] !== b) {
4273
+ blossom[base[v]] = blossom[base[match[v]]] = true;
4274
+ p2[v] = child;
4275
+ child = match[v];
4276
+ v = p2[match[v]];
4277
+ }
4278
+ };
4279
+ const augment = (root2) => {
4280
+ used.fill(false);
4281
+ p2.fill(-1);
4282
+ for (let i2 = 0; i2 < n2; i2++) base[i2] = i2;
4283
+ used[root2] = true;
4284
+ const q = [root2];
4285
+ for (let h = 0; h < q.length; h++) {
4286
+ const v = q[h];
4287
+ for (const to of adj[v]) {
4288
+ if (!ok(v, to) || base[v] === base[to] || match[v] === to) continue;
4289
+ if (to === root2 || match[to] >= 0 && p2[match[to]] >= 0) {
4290
+ const cur = lca(v, to);
4291
+ blossom.fill(false);
4292
+ markPath(v, cur, to);
4293
+ markPath(to, cur, v);
4294
+ for (let i2 = 0; i2 < n2; i2++) if (blossom[base[i2]]) {
4295
+ base[i2] = cur;
4296
+ if (!used[i2]) {
4297
+ used[i2] = true;
4298
+ q.push(i2);
4299
+ }
4300
+ }
4301
+ } else if (p2[to] < 0) {
4302
+ p2[to] = v;
4303
+ if (match[to] < 0) {
4304
+ for (let u2 = to; u2 >= 0; ) {
4305
+ const pv = p2[u2], ppv = match[pv];
4306
+ match[u2] = pv;
4307
+ match[pv] = u2;
4308
+ u2 = ppv;
4309
+ }
4310
+ return true;
4311
+ }
4312
+ used[match[to]] = true;
4313
+ q.push(match[to]);
4314
+ }
4315
+ }
4316
+ }
4317
+ return false;
4318
+ };
4319
+ const saved = () => match.slice();
4320
+ const restore = (m2) => {
4321
+ for (let i2 = 0; i2 < n2; i2++) match[i2] = m2[i2];
4322
+ };
4323
+ return {
4324
+ match,
4325
+ perfect: () => match.every((m2, i2) => m2 >= 0 || dropped[i2]),
4326
+ cut(a2, b) {
4327
+ gone.add(edge(a2, b));
4328
+ if (match[a2] !== b) return true;
4329
+ const before = saved();
4330
+ match[a2] = match[b] = -1;
4331
+ if (augment(a2)) return true;
4332
+ gone.delete(edge(a2, b));
4333
+ restore(before);
4334
+ return false;
4335
+ },
4336
+ drop(a2, b) {
4337
+ const before = saved();
4338
+ dropped[a2] = dropped[b] = true;
4339
+ const loose = [match[a2], match[b]].filter((w2) => w2 >= 0 && w2 !== a2 && w2 !== b);
4340
+ match[a2] = match[b] = -1;
4341
+ for (const w2 of loose) match[w2] = -1;
4342
+ if (!loose.length || augment(loose[0]) && match[loose[1]] >= 0) return true;
4343
+ dropped[a2] = dropped[b] = false;
4344
+ restore(before);
4345
+ return false;
4346
+ }
4347
+ };
4348
+ }
4349
+ function systemKekule(doc, todo, atoms) {
4350
+ const roles = kekuleRoles(doc, todo, atoms);
4351
+ const near2 = (id) => (doc.adj.get(id) ?? []).filter((bid) => todo.has(bid)).map((bid) => {
4352
+ const b = doc.bonds.get(bid);
4353
+ return b.a1 === id ? b.a2 : b.a1;
4354
+ });
4355
+ const ring2 = /* @__PURE__ */ new Map();
4356
+ for (const id of atoms) {
4357
+ if (roles.get(id) !== "nh") continue;
4358
+ const ends = near2(id);
4359
+ const path = ends.length === 2 ? ringPath(doc, todo, ends[0], ends[1], id) : null;
4360
+ if (!path) roles.set(id, "free");
4361
+ else ring2.set(id, path);
4362
+ }
4363
+ if (!ring2.size) return void 0;
4364
+ const verts = atoms.filter((id) => roles.get(id) !== "none");
4365
+ const n2 = verts.length;
4366
+ const index2 = new Map(verts.map((a2, i2) => [a2, i2]));
4367
+ const adj = Array.from({ length: 2 * n2 }, () => []);
4368
+ const bondOf2 = /* @__PURE__ */ new Map();
4369
+ for (let i2 = 0; i2 < n2; i2++) {
4370
+ for (const bid of doc.adj.get(verts[i2]) ?? []) {
4371
+ if (!todo.has(bid)) continue;
4372
+ const b = doc.bonds.get(bid);
4373
+ const j = index2.get(b.a1 === verts[i2] ? b.a2 : b.a1);
4374
+ if (j === void 0 || j <= i2) continue;
4375
+ adj[i2].push(j);
4376
+ adj[j].push(i2);
4377
+ adj[i2 + n2].push(j + n2);
4378
+ adj[j + n2].push(i2 + n2);
4379
+ bondOf2.set(i2 + "," + j, bid);
4380
+ }
4381
+ if (roles.get(verts[i2]) !== "must") {
4382
+ adj[i2].push(i2 + n2);
4383
+ adj[i2 + n2].push(i2);
4384
+ }
4385
+ }
4386
+ const m2 = blossomMatcher(adj);
4387
+ if (!m2.perfect()) return null;
4388
+ const fusion = (id) => near2(id).length >= 3;
4389
+ const key2 = (id) => {
4390
+ const ns = near2(id);
4391
+ const z2 = ns.map((x2) => doc.atoms.get(x2).z);
4392
+ const n22 = new Set(ns.flatMap((x2) => near2(x2)).filter((y2) => y2 !== id && !ns.includes(y2) && doc.atoms.get(y2).z === 7)).size;
4393
+ return [ring2.get(id).length + 1 <= 5 ? 0 : 1, ns.some(fusion) ? 0 : 1, z2.includes(7) && z2.includes(6) ? 0 : 1, -n22, id];
4394
+ };
4395
+ const keys = new Map([...ring2.keys()].map((id) => [id, key2(id)]));
4396
+ const suited = [...ring2.keys()].sort((x2, y2) => {
4397
+ const p2 = keys.get(x2), q = keys.get(y2);
4398
+ for (let i2 = 0; i2 < p2.length; i2++) if (p2[i2] !== q[i2]) return p2[i2] - q[i2];
4399
+ return 0;
4400
+ });
4401
+ const nh = /* @__PURE__ */ new Set();
4402
+ const oxo = (id) => doc.atoms.get(id).z === 6 && (doc.adj.get(id) ?? []).some((bid) => {
4403
+ const b = doc.bonds.get(bid);
4404
+ const o = doc.atoms.get(b.a1 === id ? b.a2 : b.a1);
4405
+ return !todo.has(bid) && b.order === 2 && (o.z === 8 || o.z === 16) && (!o.label || o.label === SYMBOLS$2[o.z]);
4406
+ });
4407
+ const fusedOnly = (members) => members.every((r) => near2(r).every((x2) => {
4408
+ if (members.includes(x2)) return true;
4409
+ let front = [x2];
4410
+ const seen = /* @__PURE__ */ new Set([r, x2]);
4411
+ for (let d2 = 0; d2 < 3; d2++) {
4412
+ const next = [];
4413
+ for (const y2 of front) for (const w2 of near2(y2)) {
4414
+ if (members.includes(w2) && w2 !== r) return true;
4415
+ if (!seen.has(w2) && !members.includes(w2)) {
4416
+ seen.add(w2);
4417
+ next.push(w2);
4418
+ }
4419
+ }
4420
+ front = next;
4421
+ }
4422
+ return front.some((y2) => near2(y2).some((w2) => members.includes(w2) && w2 !== r));
4423
+ }));
4424
+ const kept2 = [];
4425
+ const nextToKept = (members) => kept2.some((k2) => members.some((a2) => near2(a2).some((b) => k2.includes(b) || near2(b).some((c2) => c2 !== a2 && k2.includes(c2)))));
4426
+ const keeps = (id) => {
4427
+ if (near2(id).some(oxo)) return true;
4428
+ const members = [id, ...ring2.get(id)];
4429
+ if (members.length !== 5 || !members.slice(1).every((x2) => doc.atoms.get(x2).z === 6)) return false;
4430
+ if (fusedOnly(members)) return true;
4431
+ if (nextToKept(members)) return false;
4432
+ kept2.push(members);
4433
+ return true;
4434
+ };
4435
+ for (const id of suited) {
4436
+ if (!keeps(id)) continue;
4437
+ if (m2.drop(index2.get(id), index2.get(id) + n2)) nh.add(id);
4438
+ else if (kept2.length && kept2[kept2.length - 1][0] === id) kept2.pop();
4439
+ }
4440
+ const order = [
4441
+ ...verts.filter((id) => roles.get(id) === "pair"),
4442
+ ...[...suited].reverse().filter((id) => !nh.has(id)),
4443
+ ...verts.filter((id) => roles.get(id) === "free")
4444
+ ];
4445
+ for (const id of order) {
4446
+ const i2 = index2.get(id);
4447
+ m2.cut(i2, i2 + n2);
4448
+ }
4449
+ const doubles = /* @__PURE__ */ new Set();
4450
+ for (let i2 = 0; i2 < n2; i2++) {
4451
+ const j = m2.match[i2];
4452
+ if (j > i2 && j < n2) doubles.add(bondOf2.get(i2 + "," + j));
4453
+ if (roles.get(verts[i2]) === "nh" && (nh.has(verts[i2]) || j === i2 + n2)) nh.add(verts[i2]);
4454
+ }
4455
+ return { doubles, nh };
4456
+ }
4457
+ function ringAromatic(doc, o) {
4458
+ return o.order === 1.5 && !outsideValence(o) && !isMetalAtom(doc.atoms.get(o.a1)) && !isMetalAtom(doc.atoms.get(o.a2));
4459
+ }
4460
+ const aromaticRings = /* @__PURE__ */ new WeakMap();
4461
+ function forgetAromaticRings(doc) {
4462
+ aromaticRings.delete(doc);
4463
+ }
4464
+ function aromaticBondInRing(doc, bondId) {
4465
+ const b = doc.bonds.get(bondId);
4466
+ if (!b || !ringAromatic(doc, b)) return false;
4467
+ let memo2 = aromaticRings.get(doc);
4468
+ if (memo2?.version !== doc.version) {
4469
+ memo2 = { version: doc.version, inRing: /* @__PURE__ */ new Map() };
4470
+ aromaticRings.set(doc, memo2);
4471
+ }
4472
+ if (!memo2.inRing.has(bondId)) for (const [id, ring2] of systemRingBonds(doc, b.a1)) memo2.inRing.set(id, ring2);
4473
+ return memo2.inRing.get(bondId) ?? false;
4474
+ }
4475
+ function systemRingBonds(doc, root2) {
4476
+ const out = /* @__PURE__ */ new Map();
4477
+ const order = /* @__PURE__ */ new Map([[root2, 0]]), low = /* @__PURE__ */ new Map([[root2, 0]]);
4478
+ let t = 1;
4479
+ const stack2 = [{ atom: root2, via: -1, bonds: doc.adj.get(root2) ?? [], k: 0 }];
4480
+ while (stack2.length) {
4481
+ const top = stack2[stack2.length - 1];
4482
+ if (top.k < top.bonds.length) {
4483
+ const bid = top.bonds[top.k++];
4484
+ if (bid === top.via) continue;
4485
+ const o = doc.bonds.get(bid);
4486
+ if (!o || !ringAromatic(doc, o)) continue;
4487
+ if (!out.has(bid)) out.set(bid, true);
4488
+ const w2 = o.a1 === top.atom ? o.a2 : o.a1;
4489
+ if (order.has(w2)) {
4490
+ low.set(top.atom, Math.min(low.get(top.atom), order.get(w2)));
4491
+ continue;
4492
+ }
4493
+ order.set(w2, t);
4494
+ low.set(w2, t);
4495
+ t++;
4496
+ stack2.push({ atom: w2, via: bid, bonds: doc.adj.get(w2) ?? [], k: 0 });
4497
+ continue;
4498
+ }
4499
+ stack2.pop();
4500
+ const up = stack2[stack2.length - 1];
4501
+ if (!up) continue;
4502
+ low.set(up.atom, Math.min(low.get(up.atom), low.get(top.atom)));
4503
+ if (low.get(top.atom) > order.get(up.atom)) out.set(top.via, false);
4504
+ }
4505
+ return out;
4506
+ }
4507
+ function aromaticAsSingle(doc, bonds) {
4508
+ const out = /* @__PURE__ */ new Set();
4509
+ const ring2 = /* @__PURE__ */ new Set();
4510
+ for (const id of bonds) {
4511
+ if (doc.bonds.get(id)?.order !== 1.5 || out.has(id) || ring2.has(id)) continue;
4512
+ if (!aromaticBondInRing(doc, id)) {
4513
+ out.add(id);
4514
+ continue;
4515
+ }
4516
+ const part2 = /* @__PURE__ */ new Set();
4517
+ const stack2 = [id];
4518
+ while (stack2.length) {
4519
+ const bid = stack2.pop();
4520
+ if (part2.has(bid)) continue;
4521
+ part2.add(bid);
4522
+ const b = doc.bonds.get(bid);
4523
+ for (const a2 of [b.a1, b.a2]) {
4524
+ for (const n2 of doc.adj.get(a2) ?? []) {
4525
+ if (part2.has(n2) || out.has(n2) || doc.bonds.get(n2).order !== 1.5) continue;
4526
+ if (aromaticBondInRing(doc, n2)) stack2.push(n2);
4527
+ else out.add(n2);
4528
+ }
4529
+ }
4530
+ }
4531
+ if (kekuleDoubles(doc, part2, true)) for (const bid of part2) ring2.add(bid);
4532
+ else for (const bid of part2) out.add(bid);
4533
+ }
4534
+ return out;
4535
+ }
3556
4536
  const TEXT_FX_KEYS = ["noKern", "noFill", "transparency", "outline", "outlineW", "shadow"];
3557
4537
  function textFx(r) {
3558
4538
  let fx2;
@@ -4023,10 +5003,10 @@ function splitParagraphs(runs) {
4023
5003
  }
4024
5004
  const hints = /* @__PURE__ */ new Map();
4025
5005
  const stacks = /* @__PURE__ */ new Map();
4026
- const key$2 = (name) => name.trim().replace(/^['"]|['"]$/g, "").toLowerCase();
5006
+ const key$1 = (name) => name.trim().replace(/^['"]|['"]$/g, "").toLowerCase();
4027
5007
  const embedded = /* @__PURE__ */ new Map();
4028
5008
  function fontClass(family) {
4029
- const f4 = key$2(family);
5009
+ const f4 = key$1(family);
4030
5010
  const h = hints.get(f4);
4031
5011
  if (h) return h;
4032
5012
  if (/courier|consolas|mono/.test(f4)) return "mono";
@@ -4034,14 +5014,14 @@ function fontClass(family) {
4034
5014
  return "sans";
4035
5015
  }
4036
5016
  function standInFont(family) {
4037
- const f4 = key$2(family);
5017
+ const f4 = key$1(family);
4038
5018
  if (f4 === "calibri") return "Carlito";
4039
5019
  if (f4 === "cambria") return "Caladea";
4040
5020
  const c2 = fontClass(family);
4041
5021
  return c2 === "mono" ? "Cousine" : c2 === "serif" ? "Tinos" : "Arimo";
4042
5022
  }
4043
5023
  function fallbackFonts(family) {
4044
- const f4 = key$2(family);
5024
+ const f4 = key$1(family);
4045
5025
  let s = stacks.get(f4);
4046
5026
  if (s) return s;
4047
5027
  const c2 = fontClass(family);
@@ -4053,7 +5033,7 @@ function fallbackFonts(family) {
4053
5033
  return s;
4054
5034
  }
4055
5035
  function lineFactor(family) {
4056
- const first = key$2(family.split(",")[0] ?? "");
5036
+ const first = key$1(family.split(",")[0] ?? "");
4057
5037
  return LINE_FACTORS[first] ?? 1.15;
4058
5038
  }
4059
5039
  const LINE_FACTORS = { calibri: 2500 / 2048, carlito: 2500 / 2048, "courier new": 2320 / 2048, cousine: 2320 / 2048, "liberation mono": 2320 / 2048 };
@@ -5297,6 +6277,25 @@ function isMetalAtom(a2) {
5297
6277
  if (!a2 || a2.multi || a2.attach) return false;
5298
6278
  return a2.label ? !NICKNAMES[a2.label] && metalLabel(a2.label) : isMetal(a2.z);
5299
6279
  }
6280
+ function ringNH(doc, start2) {
6281
+ const atoms = [start2];
6282
+ const seen = new Set(atoms);
6283
+ const todo = /* @__PURE__ */ new Set();
6284
+ for (let k2 = 0; k2 < atoms.length; k2++) for (const bid of doc.adj.get(atoms[k2]) ?? []) {
6285
+ if (!aromaticBondInRing(doc, bid)) continue;
6286
+ todo.add(bid);
6287
+ const b = doc.bonds.get(bid);
6288
+ const o = b.a1 === atoms[k2] ? b.a2 : b.a1;
6289
+ if (!seen.has(o)) {
6290
+ seen.add(o);
6291
+ atoms.push(o);
6292
+ }
6293
+ }
6294
+ const sys = systemKekule(doc, todo, atoms);
6295
+ const out = /* @__PURE__ */ new Map();
6296
+ for (const id of atoms) out.set(id, !!sys?.nh.has(id));
6297
+ return out;
6298
+ }
5300
6299
  function metalLabel(label) {
5301
6300
  if (GROUP_LIKE.has(label.trim()) || startsAsGroup(label)) return false;
5302
6301
  const g2 = labelGraph(label, 1), head = g2?.atoms[0];
@@ -5424,7 +6423,7 @@ const KEPT_ENTRY = 3;
5424
6423
  const copyKept = (k2) => k2.map((x2) => ({ xml: x2.xml, refs: { ...x2.refs } }));
5425
6424
  const copyGuides = (g2) => g2 && { ...g2, list: g2.list.map((x2) => ({ ...x2 })) };
5426
6425
  const CELL = 12;
5427
- function cellKey(cx, cy) {
6426
+ function cellKey$1(cx, cy) {
5428
6427
  return cx * 100003 + cy;
5429
6428
  }
5430
6429
  function clone(e) {
@@ -5593,6 +6592,8 @@ class Doc {
5593
6592
  restoreVersion(version2) {
5594
6593
  this.version = version2;
5595
6594
  this.boundsMemo = null;
6595
+ this.nhMemo = null;
6596
+ forgetAromaticRings(this);
5596
6597
  }
5597
6598
  /** Give up the step being made: what it changed goes back as it was, with nothing to undo or redo. */
5598
6599
  abandon() {
@@ -5989,7 +6990,7 @@ class Doc {
5989
6990
  }
5990
6991
  // ---------------------------------------------------------------- spatial index
5991
6992
  indexAtom(a2) {
5992
- const key2 = cellKey(Math.floor(a2.x / CELL), Math.floor(a2.y / CELL));
6993
+ const key2 = cellKey$1(Math.floor(a2.x / CELL), Math.floor(a2.y / CELL));
5993
6994
  const old = this.atomCell.get(a2.id);
5994
6995
  if (old === key2) return;
5995
6996
  if (old !== void 0) this.removeFromCell(old, a2.id);
@@ -6030,7 +7031,7 @@ class Doc {
6030
7031
  const r2 = r * r;
6031
7032
  for (let cx = c0x; cx <= c1x; cx++) {
6032
7033
  for (let cy = c0y; cy <= c1y; cy++) {
6033
- const l = this.grid.get(cellKey(cx, cy));
7034
+ const l = this.grid.get(cellKey$1(cx, cy));
6034
7035
  if (!l) continue;
6035
7036
  for (const id of l) {
6036
7037
  const a2 = this.atoms.get(id);
@@ -6052,7 +7053,7 @@ class Doc {
6052
7053
  }
6053
7054
  for (let cx = c0x; cx <= c1x; cx++) {
6054
7055
  for (let cy = c0y; cy <= c1y; cy++) {
6055
- const l = this.grid.get(cellKey(cx, cy));
7056
+ const l = this.grid.get(cellKey$1(cx, cy));
6056
7057
  if (!l) continue;
6057
7058
  for (const id of l) {
6058
7059
  const a2 = this.atoms.get(id);
@@ -6089,6 +7090,7 @@ class Doc {
6089
7090
  if (!a2) return;
6090
7091
  this.touch("a", id);
6091
7092
  const n2 = { ...a2, ...patch, id };
7093
+ if (n2.label !== a2.label && !("ringH" in patch)) delete n2.ringH;
6092
7094
  if ("label" in patch && n2.label !== a2.label && !("group" in patch)) {
6093
7095
  if (a2.group && !("isotope" in patch)) n2.isotope = 0;
6094
7096
  delete n2.group;
@@ -6418,7 +7420,8 @@ class Doc {
6418
7420
  if (b.order === 1.5) aromatic++;
6419
7421
  }
6420
7422
  }
6421
- if (a2 && aromatic === 2 && !a2.label && !a2.charge && AROMATIC_CHALCOGENS.has(a2.z)) own -= 1;
7423
+ if (a2 && !a2.label && (aromaticCarbonIon(a2.z, a2.charge, aromatic) && this.inOddAromaticRing(atomId) || aromatic === 2 && !a2.charge && AROMATIC_CHALCOGENS.has(a2.z))) own -= aromatic / 2;
7424
+ else if (a2 && aromatic === 2 && own === 3 && !toMetal && !rad && !a2.label && !a2.charge && (a2.z === 7 || a2.z === 15) && this.hasRingNH(atomId)) own -= 1;
6422
7425
  if (toMetal && a2 && !a2.label && !isMetalAtom(a2)) {
6423
7426
  const room = metalBondRoom(a2.z, own, a2.charge, rad);
6424
7427
  if (room !== void 0) toMetal = Math.min(toMetal, room);
@@ -6426,6 +7429,21 @@ class Doc {
6426
7429
  }
6427
7430
  return own + toMetal + rad;
6428
7431
  }
7432
+ /**
7433
+ * Does this unlabeled ring N (or P) between two aromatic bonds carry an H, as pyrrole's does and
7434
+ * pyridine's doesn't (see systemKekule)? Worked out once per ring system for each version of the drawing.
7435
+ */
7436
+ hasRingNH(atomId) {
7437
+ if (this.nhMemo?.version !== this.version) this.nhMemo = { version: this.version, nh: /* @__PURE__ */ new Map() };
7438
+ const memo2 = this.nhMemo.nh;
7439
+ if (!memo2.has(atomId)) {
7440
+ const found = ringNH(this, atomId);
7441
+ memo2.set(atomId, false);
7442
+ for (const [id, h] of found) memo2.set(id, h);
7443
+ }
7444
+ return memo2.get(atomId);
7445
+ }
7446
+ nhMemo = null;
6429
7447
  /** An atom's bonds that count (not dative, ionic or partial): to whom, their order, and whether to a metal. */
6430
7448
  countedBonds(atomId) {
6431
7449
  return (this.adj.get(atomId) ?? []).map((bid) => this.bonds.get(bid)).filter((b) => !outsideValence(b)).map((b) => {
@@ -6488,6 +7506,29 @@ class Doc {
6488
7506
  }
6489
7507
  return out;
6490
7508
  }
7509
+ /**
7510
+ * Whether an atom's smallest ring through one of its aromatic (1.5) bonds has an odd number of
7511
+ * atoms and no other π-donor: a carbocyclic ion like cyclopentadienide or tropylium, where the
7512
+ * charged carbon brings the ring's lone pair or empty orbital. In a ring with another donor (a
7513
+ * thiophene's S, a furan's O, a pyrrole's or N-methylimidazole's N–R, a B, or another charged
7514
+ * atom) that atom brings it instead, and the charged carbon keeps its place in a double bond.
7515
+ */
7516
+ inOddAromaticRing(atomId) {
7517
+ for (const bid of this.adj.get(atomId) ?? []) {
7518
+ if (this.bonds.get(bid).order !== 1.5) continue;
7519
+ const ring2 = this.ringThroughBond(bid);
7520
+ if (ring2) return ring2.length % 2 === 1 && !ring2.some((id) => id !== atomId && this.ringDonor(id));
7521
+ }
7522
+ return false;
7523
+ }
7524
+ /** Whether a ring atom can give an aromatic ring two π electrons or an empty orbital (see inOddAromaticRing). */
7525
+ ringDonor(id) {
7526
+ const a2 = this.atoms.get(id);
7527
+ if (!a2) return false;
7528
+ if (a2.label || a2.charge || a2.z === 5) return true;
7529
+ if (AROMATIC_CHALCOGENS.has(a2.z)) return true;
7530
+ return (a2.z === 7 || a2.z === 15) && this.countedBonds(id).length >= 3;
7531
+ }
6491
7532
  /** Smallest ring through a bond (atom ids in order), or null. Used to place double bonds. */
6492
7533
  ringThroughBond(bondId, maxSize = 8) {
6493
7534
  const b = this.bonds.get(bondId);
@@ -7375,26 +8416,45 @@ try {
7375
8416
  } catch (e) {
7376
8417
  }
7377
8418
  const MOST_UNPACKED = 32 * 1024 * 1024;
8419
+ const MOST_UNPACKED_IN_ALL = 128 * 1024 * 1024;
8420
+ const unpackBudget = (most2 = MOST_UNPACKED_IN_ALL) => ({ left: most2, over: 0 });
7378
8421
  const SLICE = 1024;
7379
8422
  function inflateCapped(data2, opts = {}) {
7380
- const most2 = opts.most ?? MOST_UNPACKED;
8423
+ const own = opts.most ?? MOST_UNPACKED;
8424
+ const budget = opts.budget;
8425
+ if (budget && budget.left <= 0) {
8426
+ budget.over++;
8427
+ return null;
8428
+ }
8429
+ const most2 = budget ? Math.max(0, Math.min(own, budget.left)) : own;
8430
+ const made2 = { bytes: 0 };
8431
+ const out = inflateUpTo(data2, most2, !!opts.raw, made2);
8432
+ if (budget) {
8433
+ if (out === "over" && most2 < own) budget.over++;
8434
+ budget.left = Math.max(0, budget.left - made2.bytes);
8435
+ }
8436
+ return out instanceof Uint8Array ? out : null;
8437
+ }
8438
+ function inflateUpTo(data2, most2, raw, made2) {
7381
8439
  const parts = [];
7382
8440
  let total2 = 0, done = false;
7383
8441
  const take = (chunk, final) => {
7384
8442
  total2 += chunk.length;
8443
+ made2.bytes = total2;
7385
8444
  if (total2 <= most2) parts.push(chunk);
7386
8445
  if (final) done = true;
7387
8446
  };
7388
8447
  try {
7389
- const s = opts.raw ? new Inflate(take) : new Unzlib(take);
8448
+ const s = raw ? new Inflate(take) : new Unzlib(take);
7390
8449
  for (let at22 = 0; at22 < data2.length; at22 += SLICE) {
7391
8450
  s.push(data2.subarray(at22, at22 + SLICE), at22 + SLICE >= data2.length);
7392
- if (total2 > most2) return null;
8451
+ if (total2 > most2) return "over";
7393
8452
  }
7394
8453
  } catch {
7395
8454
  return null;
7396
8455
  }
7397
- if (!done || total2 > most2) return null;
8456
+ if (total2 > most2) return "over";
8457
+ if (!done) return null;
7398
8458
  const out = new Uint8Array(total2);
7399
8459
  let at2 = 0;
7400
8460
  for (const p2 of parts) {
@@ -7534,393 +8594,6 @@ function openDirection(dirs) {
7534
8594
  }
7535
8595
  return { x: Math.cos(best), y: Math.sin(best) };
7536
8596
  }
7537
- const key$1 = (ring2) => [...ring2].sort((a2, b) => a2 - b).join(",");
7538
- function ringAvoiding(doc, bondId, avoid, maxSize = 8) {
7539
- const b = doc.bonds.get(bondId);
7540
- if (!b) return null;
7541
- const prev = /* @__PURE__ */ new Map([[b.a2, -1]]);
7542
- let frontier = [b.a2];
7543
- for (let depth = 1; depth < maxSize && frontier.length; depth++) {
7544
- const next = [];
7545
- for (const id of frontier) {
7546
- for (const bid of doc.adj.get(id) ?? []) {
7547
- if (bid === bondId) continue;
7548
- const bb = doc.bonds.get(bid);
7549
- const o = bb.a1 === id ? bb.a2 : bb.a1;
7550
- if (prev.has(o) || avoid.has(o)) continue;
7551
- prev.set(o, id);
7552
- if (o === b.a1) {
7553
- const path = [o];
7554
- let cur = id;
7555
- while (cur !== -1) {
7556
- path.push(cur);
7557
- cur = prev.get(cur);
7558
- }
7559
- return path;
7560
- }
7561
- next.push(o);
7562
- }
7563
- }
7564
- frontier = next;
7565
- }
7566
- return null;
7567
- }
7568
- function ringsThroughBond(doc, bondId, maxSize = 8) {
7569
- const first = ringAvoiding(doc, bondId, /* @__PURE__ */ new Set(), maxSize);
7570
- if (!first) return [];
7571
- const b = doc.bonds.get(bondId);
7572
- const inner = new Set(first.filter((a2) => a2 !== b.a1 && a2 !== b.a2));
7573
- const second = ringAvoiding(doc, bondId, inner, maxSize);
7574
- return second && key$1(second) !== key$1(first) ? [first, second] : [first];
7575
- }
7576
- function bondBetween(doc, a2, c2) {
7577
- for (const bid of doc.adj.get(a2) ?? []) {
7578
- const b = doc.bonds.get(bid);
7579
- if (b.a1 === c2 || b.a2 === c2) return bid;
7580
- }
7581
- return void 0;
7582
- }
7583
- function ringBonds$1(doc, ring2) {
7584
- const out = [];
7585
- for (let i2 = 0; i2 < ring2.length; i2++) {
7586
- const b = bondBetween(doc, ring2[i2], ring2[(i2 + 1) % ring2.length]);
7587
- if (b !== void 0) out.push(b);
7588
- }
7589
- return out;
7590
- }
7591
- function isCircleRing(doc, ring2) {
7592
- const bs = ringBonds$1(doc, ring2);
7593
- return bs.length === ring2.length && bs.every((id) => {
7594
- const b = doc.bonds.get(id);
7595
- return b.order === 1.5 && !!b.circle;
7596
- });
7597
- }
7598
- function ringCircle(doc, ring2) {
7599
- return circleIn(ring2.map((id) => doc.atoms.get(id)));
7600
- }
7601
- function circleIn(pts2) {
7602
- const n2 = pts2.length;
7603
- let x2 = 0, y2 = 0;
7604
- for (const p2 of pts2) {
7605
- x2 += p2.x;
7606
- y2 += p2.y;
7607
- }
7608
- const center = { x: x2 / n2, y: y2 / n2 };
7609
- let apothem = Infinity;
7610
- for (let i2 = 0; i2 < n2; i2++) {
7611
- const p2 = pts2[i2], q = pts2[(i2 + 1) % n2];
7612
- apothem = Math.min(apothem, Math.hypot((p2.x + q.x) / 2 - center.x, (p2.y + q.y) / 2 - center.y));
7613
- }
7614
- const plain = { center, radius: 0.62 * apothem };
7615
- if (n2 < 3) return plain;
7616
- let a2 = 0, b = 0, c2 = 0, d2 = 0;
7617
- pts2.forEach((p2, k2) => {
7618
- const u2 = Math.cos(2 * Math.PI * k2 / n2), v = Math.sin(2 * Math.PI * k2 / n2);
7619
- a2 += (p2.x - center.x) * u2;
7620
- b += (p2.x - center.x) * v;
7621
- c2 += (p2.y - center.y) * u2;
7622
- d2 += (p2.y - center.y) * v;
7623
- });
7624
- const m2 = [2 * a2 / n2, 2 * b / n2, 2 * c2 / n2, 2 * d2 / n2];
7625
- let miss = 0, size = 0;
7626
- pts2.forEach((p2, k2) => {
7627
- const u2 = Math.cos(2 * Math.PI * k2 / n2), v = Math.sin(2 * Math.PI * k2 / n2);
7628
- miss = Math.max(miss, Math.hypot(center.x + m2[0] * u2 + m2[1] * v - p2.x, center.y + m2[2] * u2 + m2[3] * v - p2.y));
7629
- size += Math.hypot(p2.x - center.x, p2.y - center.y) / n2;
7630
- });
7631
- if (miss > 0.12 * size) return plain;
7632
- const [s1, s2] = singularValues(m2);
7633
- if (s2 > 0.96 * s1) return plain;
7634
- return { center, radius: plain.radius, ellipse: { m: m2, r: 0.62 * Math.cos(Math.PI / n2) } };
7635
- }
7636
- function singularValues([a2, b, c2, d2]) {
7637
- const s = a2 * a2 + b * b + c2 * c2 + d2 * d2, det = a2 * d2 - b * c2;
7638
- const root2 = Math.sqrt(Math.max(0, s * s - 4 * det * det));
7639
- return [Math.sqrt((s + root2) / 2), Math.sqrt(Math.max(0, (s - root2) / 2))];
7640
- }
7641
- function ellipseAxes(e) {
7642
- const [a2, b, c2, d2] = e.m;
7643
- const phi = 0.5 * Math.atan2(2 * (a2 * b + c2 * d2), a2 * a2 + c2 * c2 - b * b - d2 * d2);
7644
- const at2 = (f4) => ({ x: (a2 * Math.cos(f4) + b * Math.sin(f4)) * e.r, y: (c2 * Math.cos(f4) + d2 * Math.sin(f4)) * e.r });
7645
- const p2 = at2(phi), q = at2(phi + Math.PI / 2);
7646
- return Math.hypot(p2.x, p2.y) >= Math.hypot(q.x, q.y) ? { major: p2, minor: q } : { major: q, minor: p2 };
7647
- }
7648
- function ellipseArc(center, e, p2, q, steps = 14) {
7649
- const [a2, b, c2, d2] = e.m;
7650
- const det = a2 * d2 - b * c2 || 1e-12;
7651
- const phiOf = (v) => {
7652
- const dx = v.x - center.x, dy = v.y - center.y;
7653
- return Math.atan2((-c2 * dx + a2 * dy) / det, (d2 * dx - b * dy) / det);
7654
- };
7655
- const f1 = phiOf(p2);
7656
- let df = phiOf(q) - f1;
7657
- while (df > Math.PI) df -= 2 * Math.PI;
7658
- while (df < -Math.PI) df += 2 * Math.PI;
7659
- const out = [];
7660
- for (let k2 = 0; k2 <= steps; k2++) {
7661
- const f4 = f1 + df * k2 / steps;
7662
- out.push({ x: center.x + (a2 * Math.cos(f4) + b * Math.sin(f4)) * e.r, y: center.y + (c2 * Math.cos(f4) + d2 * Math.sin(f4)) * e.r });
7663
- }
7664
- return out;
7665
- }
7666
- function ringsAmong(doc, bonds, maxSize = 8) {
7667
- const seen = /* @__PURE__ */ new Map();
7668
- const ids = [...bonds];
7669
- for (const id of ids.length ? ids : doc.bonds.keys()) for (const r of ringsThroughBond(doc, id, maxSize)) seen.set(key$1(r), r);
7670
- return [...seen.values()];
7671
- }
7672
- function kekuleDoubles(doc, todo, strict = false) {
7673
- const atoms = [...new Set([...todo].flatMap((id) => {
7674
- const b = doc.bonds.get(id);
7675
- return [b.a1, b.a2];
7676
- }))];
7677
- const optional = (id) => {
7678
- const a2 = doc.atoms.get(id);
7679
- if (a2.z !== 6 || a2.charge !== 0 || strict && a2.label) return true;
7680
- return [...doc.adj.get(id) ?? []].some((bid) => !todo.has(bid) && doc.bonds.get(bid).order === 2);
7681
- };
7682
- const room = (id) => {
7683
- if (!strict) return true;
7684
- const a2 = doc.atoms.get(id);
7685
- if (isMetalAtom(a2)) return true;
7686
- let used = 0;
7687
- for (const bid of doc.adj.get(id) ?? []) {
7688
- const b = doc.bonds.get(bid);
7689
- if (todo.has(bid)) {
7690
- used += 1;
7691
- continue;
7692
- }
7693
- if (outsideValence(b) || isMetalAtom(doc.atoms.get(b.a1 === id ? b.a2 : b.a1))) continue;
7694
- used += b.order === 1.5 ? 1 : b.order;
7695
- }
7696
- if (a2.label) return !!a2.group || labelOverValent(a2.label, used + 1, a2.charge).length === 0;
7697
- const max2 = maxValence(a2.z, a2.charge);
7698
- return max2 === void 0 || used + 1 <= max2;
7699
- };
7700
- const paired = /* @__PURE__ */ new Map();
7701
- const chosen = /* @__PURE__ */ new Set();
7702
- const comp = /* @__PURE__ */ new Map();
7703
- const comps = [];
7704
- for (const start2 of atoms) {
7705
- if (comp.has(start2)) continue;
7706
- const list2 = [start2];
7707
- comp.set(start2, comps.length);
7708
- for (let k2 = 0; k2 < list2.length; k2++) for (const bid of doc.adj.get(list2[k2]) ?? []) {
7709
- if (!todo.has(bid)) continue;
7710
- const b = doc.bonds.get(bid);
7711
- const o = b.a1 === list2[k2] ? b.a2 : b.a1;
7712
- if (!comp.has(o)) {
7713
- comp.set(o, comps.length);
7714
- list2.push(o);
7715
- }
7716
- }
7717
- comps.push(list2);
7718
- }
7719
- if (comps.some((c2) => c2.length % 2 === 1 && !c2.some(optional))) return null;
7720
- let part2 = [];
7721
- let steps = 0;
7722
- const STEPS = 2e4;
7723
- const solve = (i2) => {
7724
- if (++steps > STEPS) return null;
7725
- if (i2 === part2.length) return true;
7726
- const a2 = part2[i2];
7727
- if (paired.has(a2)) return solve(i2 + 1);
7728
- for (const bid of doc.adj.get(a2) ?? []) {
7729
- if (!todo.has(bid)) continue;
7730
- const b = doc.bonds.get(bid);
7731
- const o = b.a1 === a2 ? b.a2 : b.a1;
7732
- if (paired.has(o) || !room(a2) || !room(o)) continue;
7733
- paired.set(a2, o);
7734
- paired.set(o, a2);
7735
- chosen.add(bid);
7736
- const r = solve(i2 + 1);
7737
- if (r !== false) return r;
7738
- paired.delete(a2);
7739
- paired.delete(o);
7740
- chosen.delete(bid);
7741
- }
7742
- return optional(a2) ? solve(i2 + 1) : false;
7743
- };
7744
- for (let k2 = 0; k2 < comps.length; k2++) {
7745
- part2 = atoms.filter((a2) => comp.get(a2) === k2);
7746
- steps = 0;
7747
- const r = solve(0);
7748
- if (r === false) return null;
7749
- if (r === true) continue;
7750
- for (const a2 of part2) paired.delete(a2);
7751
- for (const bid of [...chosen]) {
7752
- const b = doc.bonds.get(bid);
7753
- if (comp.get(b.a1) === k2) chosen.delete(bid);
7754
- }
7755
- const found = matchedBonds(doc, todo, part2, optional, room);
7756
- if (!found) return null;
7757
- for (const bid of found) {
7758
- const b = doc.bonds.get(bid);
7759
- chosen.add(bid);
7760
- paired.set(b.a1, b.a2);
7761
- paired.set(b.a2, b.a1);
7762
- }
7763
- }
7764
- return chosen;
7765
- }
7766
- function matchedBonds(doc, todo, part2, optional, room) {
7767
- const n2 = part2.length;
7768
- const index2 = new Map(part2.map((a2, i2) => [a2, i2]));
7769
- const adj = Array.from({ length: 2 * n2 }, () => []);
7770
- const bondOf2 = /* @__PURE__ */ new Map();
7771
- for (let i2 = 0; i2 < n2; i2++) {
7772
- const a2 = part2[i2];
7773
- if (!room(a2) && !optional(a2)) return null;
7774
- if (optional(a2)) {
7775
- adj[i2].push(i2 + n2);
7776
- adj[i2 + n2].push(i2);
7777
- }
7778
- if (!room(a2)) continue;
7779
- for (const bid of doc.adj.get(a2) ?? []) {
7780
- if (!todo.has(bid)) continue;
7781
- const b = doc.bonds.get(bid);
7782
- const j = index2.get(b.a1 === a2 ? b.a2 : b.a1);
7783
- if (j === void 0 || j <= i2 || !room(part2[j])) continue;
7784
- adj[i2].push(j);
7785
- adj[j].push(i2);
7786
- adj[i2 + n2].push(j + n2);
7787
- adj[j + n2].push(i2 + n2);
7788
- bondOf2.set(i2 * n2 + j, bid);
7789
- }
7790
- }
7791
- const match = maximumMatching(adj);
7792
- if (match.some((m2) => m2 < 0)) return null;
7793
- const out = [];
7794
- for (let i2 = 0; i2 < n2; i2++) if (match[i2] >= 0 && match[i2] < n2 && match[i2] > i2) out.push(bondOf2.get(i2 * n2 + match[i2]));
7795
- return out;
7796
- }
7797
- function maximumMatching(adj) {
7798
- const n2 = adj.length;
7799
- const match = new Array(n2).fill(-1), p2 = new Array(n2).fill(-1), base = new Array(n2).fill(0);
7800
- const used = new Array(n2).fill(false), blossom = new Array(n2).fill(false);
7801
- const lca = (a2, b) => {
7802
- const seen = new Array(n2).fill(false);
7803
- for (; ; ) {
7804
- a2 = base[a2];
7805
- seen[a2] = true;
7806
- if (match[a2] < 0) break;
7807
- a2 = p2[match[a2]];
7808
- }
7809
- for (; ; ) {
7810
- b = base[b];
7811
- if (seen[b]) return b;
7812
- b = p2[match[b]];
7813
- }
7814
- };
7815
- const markPath = (v, b, child) => {
7816
- while (base[v] !== b) {
7817
- blossom[base[v]] = blossom[base[match[v]]] = true;
7818
- p2[v] = child;
7819
- child = match[v];
7820
- v = p2[match[v]];
7821
- }
7822
- };
7823
- const findPath = (root2) => {
7824
- used.fill(false);
7825
- p2.fill(-1);
7826
- for (let i2 = 0; i2 < n2; i2++) base[i2] = i2;
7827
- used[root2] = true;
7828
- const q = [root2];
7829
- for (let h = 0; h < q.length; h++) {
7830
- const v = q[h];
7831
- for (const to of adj[v]) {
7832
- if (base[v] === base[to] || match[v] === to) continue;
7833
- if (to === root2 || match[to] >= 0 && p2[match[to]] >= 0) {
7834
- const cur = lca(v, to);
7835
- blossom.fill(false);
7836
- markPath(v, cur, to);
7837
- markPath(to, cur, v);
7838
- for (let i2 = 0; i2 < n2; i2++) if (blossom[base[i2]]) {
7839
- base[i2] = cur;
7840
- if (!used[i2]) {
7841
- used[i2] = true;
7842
- q.push(i2);
7843
- }
7844
- }
7845
- } else if (p2[to] < 0) {
7846
- p2[to] = v;
7847
- if (match[to] < 0) return to;
7848
- used[match[to]] = true;
7849
- q.push(match[to]);
7850
- }
7851
- }
7852
- }
7853
- return -1;
7854
- };
7855
- for (let v = 0; v < n2; v++) if (match[v] < 0) {
7856
- for (const to of adj[v]) if (match[to] < 0) {
7857
- match[v] = to;
7858
- match[to] = v;
7859
- break;
7860
- }
7861
- }
7862
- for (let v = 0; v < n2; v++) {
7863
- if (match[v] >= 0) continue;
7864
- let u2 = findPath(v);
7865
- while (u2 >= 0) {
7866
- const pv = p2[u2], ppv = match[pv];
7867
- match[u2] = pv;
7868
- match[pv] = u2;
7869
- u2 = ppv;
7870
- }
7871
- }
7872
- return match;
7873
- }
7874
- function aromaticBondInRing(doc, bondId) {
7875
- const b = doc.bonds.get(bondId);
7876
- if (!b || b.order !== 1.5) return false;
7877
- const seen = /* @__PURE__ */ new Set([b.a2]);
7878
- const stack2 = [b.a2];
7879
- while (stack2.length) {
7880
- const id = stack2.pop();
7881
- for (const bid of doc.adj.get(id) ?? []) {
7882
- if (bid === bondId) continue;
7883
- const o = doc.bonds.get(bid);
7884
- if (o.order !== 1.5) continue;
7885
- const n2 = o.a1 === id ? o.a2 : o.a1;
7886
- if (n2 === b.a1) return true;
7887
- if (!seen.has(n2)) {
7888
- seen.add(n2);
7889
- stack2.push(n2);
7890
- }
7891
- }
7892
- }
7893
- return false;
7894
- }
7895
- function aromaticAsSingle(doc, bonds) {
7896
- const out = /* @__PURE__ */ new Set();
7897
- const ring2 = /* @__PURE__ */ new Set();
7898
- for (const id of bonds) {
7899
- if (doc.bonds.get(id)?.order !== 1.5 || out.has(id) || ring2.has(id)) continue;
7900
- if (!aromaticBondInRing(doc, id)) {
7901
- out.add(id);
7902
- continue;
7903
- }
7904
- const part2 = /* @__PURE__ */ new Set();
7905
- const stack2 = [id];
7906
- while (stack2.length) {
7907
- const bid = stack2.pop();
7908
- if (part2.has(bid)) continue;
7909
- part2.add(bid);
7910
- const b = doc.bonds.get(bid);
7911
- for (const a2 of [b.a1, b.a2]) {
7912
- for (const n2 of doc.adj.get(a2) ?? []) {
7913
- if (part2.has(n2) || out.has(n2) || doc.bonds.get(n2).order !== 1.5) continue;
7914
- if (aromaticBondInRing(doc, n2)) stack2.push(n2);
7915
- else out.add(n2);
7916
- }
7917
- }
7918
- }
7919
- if (kekuleDoubles(doc, part2, true)) for (const bid of part2) ring2.add(bid);
7920
- else for (const bid of part2) out.add(bid);
7921
- }
7922
- return out;
7923
- }
7924
8597
  let dflt = "box";
7925
8598
  const focalDefault = () => dflt;
7926
8599
  function focalAtoms(doc, atoms) {
@@ -8120,13 +8793,63 @@ function sanitizeEcount(v) {
8120
8793
  }
8121
8794
  const place$1 = (lf) => Math.round((0.55 + 0.7 * lf) * 1e3) / 1e3;
8122
8795
  const D_GEOMETRIES = [
8123
- { id: "oh", name: "Octahedral", delta: "Δ_{o}", sets: [{ label: "t_{2g}", n: 3, lf: -0.4, at: place$1(-0.4) }, { label: "e_{g}", n: 2, lf: 0.6, at: place$1(0.6) }] },
8124
- { id: "td", name: "Tetrahedral", delta: "Δ_{t}", sets: [{ label: "e", n: 2, lf: -0.6, at: place$1(-0.6) }, { label: "t_{2}", n: 3, lf: 0.4, at: place$1(0.4) }] },
8796
+ { id: "oh", name: "Octahedral", pointGroup: "O_{h}", cn: 6, delta: "Δ_{o}", sets: [{ label: "t_{2g}", n: 3, lf: -0.4, at: place$1(-0.4) }, { label: "e_{g}", n: 2, lf: 0.6, at: place$1(0.6) }] },
8797
+ { id: "td", name: "Tetrahedral", pointGroup: "T_{d}", cn: 4, delta: "Δ_{t}", sets: [{ label: "e", n: 2, lf: -0.6, at: place$1(-0.6) }, { label: "t_{2}", n: 3, lf: 0.4, at: place$1(0.4) }] },
8125
8798
  {
8126
8799
  id: "sq",
8127
8800
  name: "Square Planar",
8801
+ pointGroup: "D_{4h}",
8802
+ cn: 4,
8128
8803
  delta: "Δ_{1}",
8129
8804
  sets: [{ label: "b_{2g}", n: 1, at: 0.06 }, { label: "e_{g}", n: 2, at: 0.2 }, { label: "a_{1g}", n: 1, at: 0.36 }, { label: "b_{1g}", n: 1, at: 0.97 }]
8805
+ },
8806
+ {
8807
+ id: "tbp",
8808
+ name: "Trigonal Bipyramidal",
8809
+ pointGroup: "D_{3h}",
8810
+ cn: 5,
8811
+ delta: "Δ",
8812
+ sets: [{ label: "e″", n: 2, at: 0.14 }, { label: "e′", n: 2, at: 0.4 }, { label: "a_{1}′", n: 1, at: 0.95 }]
8813
+ },
8814
+ {
8815
+ id: "spy",
8816
+ name: "Square Pyramidal",
8817
+ pointGroup: "C_{4v}",
8818
+ cn: 5,
8819
+ delta: "Δ",
8820
+ sets: [{ label: "e", n: 2, at: 0.08 }, { label: "b_{2}", n: 1, at: 0.3 }, { label: "a_{1}", n: 1, at: 0.5 }, { label: "b_{1}", n: 1, at: 0.95 }]
8821
+ },
8822
+ {
8823
+ id: "jt",
8824
+ name: "Tetragonal Elongated",
8825
+ pointGroup: "D_{4h}",
8826
+ cn: 6,
8827
+ delta: "Δ",
8828
+ sets: [{ label: "e_{g}", n: 2, at: 0.1 }, { label: "b_{2g}", n: 1, at: 0.3 }, { label: "a_{1g}", n: 1, at: 0.72 }, { label: "b_{1g}", n: 1, at: 0.95 }]
8829
+ },
8830
+ {
8831
+ id: "lin",
8832
+ name: "Linear",
8833
+ pointGroup: "D_{∞h}",
8834
+ cn: 2,
8835
+ delta: "Δ",
8836
+ sets: [{ label: "δ_{g}", n: 2, at: 0.1 }, { label: "π_{g}", n: 2, at: 0.48 }, { label: "σ_{g}^{+}", n: 1, at: 0.95 }]
8837
+ },
8838
+ {
8839
+ id: "tpl",
8840
+ name: "Trigonal Planar",
8841
+ pointGroup: "D_{3h}",
8842
+ cn: 3,
8843
+ delta: "Δ",
8844
+ sets: [{ label: "e″", n: 2, at: 0.12 }, { label: "a_{1}′", n: 1, at: 0.34 }, { label: "e′", n: 2, at: 0.95 }]
8845
+ },
8846
+ {
8847
+ id: "pbp",
8848
+ name: "Pentagonal Bipyramidal",
8849
+ pointGroup: "D_{5h}",
8850
+ cn: 7,
8851
+ delta: "Δ",
8852
+ sets: [{ label: "e_{1}″", n: 2, at: 0.1 }, { label: "e_{2}′", n: 2, at: 0.68 }, { label: "a_{1}′", n: 1, at: 0.95 }]
8130
8853
  }
8131
8854
  ];
8132
8855
  const dGeometry = (id) => D_GEOMETRIES.find((g2) => g2.id === id) ?? D_GEOMETRIES[0];
@@ -8159,9 +8882,11 @@ function parseIon(text2) {
8159
8882
  if (!z2 || SYMBOLS$2[z2] !== symbol) return null;
8160
8883
  return { symbol, z: z2, charge };
8161
8884
  }
8885
+ const POST_TRANSITION_Z = /* @__PURE__ */ new Set([31, 32, 49, 50, 51, 81, 82, 83]);
8162
8886
  function dShell(z2) {
8163
8887
  const p2 = tablePosition(z2);
8164
- return p2 && p2.row >= 4 && p2.row <= 6 && p2.col >= 3 && p2.col <= 12 ? `${p2.row - 1}d` : null;
8888
+ if (!p2 || p2.row < 4 || p2.row > 6) return null;
8889
+ return p2.col >= 3 && p2.col <= 12 || POST_TRANSITION_Z.has(z2) ? `${p2.row - 1}d` : null;
8165
8890
  }
8166
8891
  function dFill(levels, d2, spin) {
8167
8892
  const room = levels.reduce((t, l) => t + 2 * l.n, 0);
@@ -8215,6 +8940,7 @@ function sanitizeDSplit(v) {
8215
8940
  readouts: typeof o.readouts === "boolean" ? o.readouts : base.readouts
8216
8941
  };
8217
8942
  if (typeof o.barycenter === "boolean") out.barycenter = o.barycenter;
8943
+ if (typeof o.mirrored === "boolean" && o.mirrored) out.mirrored = true;
8218
8944
  return out;
8219
8945
  }
8220
8946
  function soundPlateDSplit(plate) {
@@ -8606,9 +9332,9 @@ function possibleStereocentres(doc, atoms) {
8606
9332
  if (j !== void 0) nb[i2].push([j, b.order]);
8607
9333
  }
8608
9334
  });
8609
- const hs = ids.map((id, i2) => {
9335
+ const hs = ids.map((id) => {
8610
9336
  const a2 = doc.atoms.get(id);
8611
- return a2.label ? -1 : implicitHydrogens(a2.z, nb[i2].reduce((t2, [, o]) => t2 + o, 0), a2.charge ?? 0);
9337
+ return a2.label ? -1 : implicitHydrogens(a2.z, doc.valenceSum(id), a2.charge ?? 0);
8612
9338
  });
8613
9339
  const relabel2 = (keys) => {
8614
9340
  const u2 = [...new Set(keys)].sort();
@@ -8816,7 +9542,7 @@ function readV3000(lines) {
8816
9542
  atoms,
8817
9543
  bonds,
8818
9544
  write(sym, added) {
8819
- const atomRows = body.slice(a0 + 1, a1).map((t, k2) => {
9545
+ const atomRows2 = body.slice(a0 + 1, a1).map((t, k2) => {
8820
9546
  const e = sym.get(k2);
8821
9547
  if (!e) return t;
8822
9548
  const w2 = words(t);
@@ -8825,14 +9551,14 @@ function readV3000(lines) {
8825
9551
  });
8826
9552
  const bondOut = [...bondRows];
8827
9553
  for (const p2 of added) {
8828
- atomRows.push(`${atomRows.length + 1} ${p2.sym} ${p2.x.toFixed(4)} ${p2.y.toFixed(4)} 0 0`);
8829
- bondOut.push(`${bondOut.length + 1} 1 ${p2.to + 1} ${atomRows.length}`);
9554
+ atomRows2.push(`${atomRows2.length + 1} ${p2.sym} ${p2.x.toFixed(4)} ${p2.y.toFixed(4)} 0 0`);
9555
+ bondOut.push(`${bondOut.length + 1} 1 ${p2.to + 1} ${atomRows2.length}`);
8830
9556
  }
8831
9557
  const cw = words(body[ci]);
8832
- cw[1] = String(atomRows.length);
9558
+ cw[1] = String(atomRows2.length);
8833
9559
  cw[2] = String(bondOut.length);
8834
9560
  const out = body.slice(0, a0 + 1).map((t, k2) => k2 === ci ? cw.join(" ") : t);
8835
- out.push(...atomRows, "END ATOM");
9561
+ out.push(...atomRows2, "END ATOM");
8836
9562
  if (b0 >= 0) out.push(...body.slice(a1 + 1, b0));
8837
9563
  if (bondOut.length) out.push("BEGIN BOND", ...bondOut, "END BOND");
8838
9564
  out.push(...body.slice(b0 >= 0 ? b1 + 1 : a1 + 1));
@@ -10131,22 +10857,24 @@ function reactionSteps(doc, items) {
10131
10857
  return all.filter(({ arrow, roles }) => isStep(roles) || arrow.step);
10132
10858
  }
10133
10859
  function linkRows(steps, items, bond = 30) {
10134
- const boxOf2 = new Map(items.map((it) => [it.ref, it.box]));
10135
- const startsOf = new Set(steps.flatMap(({ roles }) => roles.reactants));
10860
+ const find2 = itemFinder(items);
10861
+ const boxOf2 = (ref) => find2(ref)?.box;
10862
+ const startsOf = new Set(steps.flatMap(({ roles }) => roles.reactants.map((ref) => find2(ref) ?? ref)));
10136
10863
  const y2 = (r) => (r.tail.y + r.head.y) / 2;
10137
10864
  const across2 = (r) => Math.abs(r.head.x - r.tail.x) > 2 * Math.abs(r.head.y - r.tail.y);
10138
10865
  for (const st of steps) {
10139
10866
  const { arrow, roles } = st;
10140
10867
  if (roles.manual || roles.reactants.length || !roles.products.length || !across2(arrow)) continue;
10141
- const top = Math.min(...roles.products.map((ref) => boxOf2.get(ref)?.y1 ?? Infinity), Math.min(arrow.tail.y, arrow.head.y));
10868
+ const top = Math.min(...roles.products.map((ref) => boxOf2(ref)?.y1 ?? Infinity), Math.min(arrow.tail.y, arrow.head.y));
10869
+ const mine = new Set(roles.products.map((ref) => find2(ref) ?? ref));
10142
10870
  let best = null;
10143
10871
  for (const o of steps) {
10144
10872
  if (o === st || !across2(o.arrow) || !o.roles.products.length) continue;
10145
10873
  const dy = y2(arrow) - y2(o.arrow);
10146
10874
  if (dy <= 0 || y2(o.arrow) >= top) continue;
10147
10875
  for (const ref of o.roles.products) {
10148
- const b = boxOf2.get(ref);
10149
- if (!b || startsOf.has(ref) || roles.products.includes(ref)) continue;
10876
+ const it = find2(ref), b = it?.box;
10877
+ if (!it || !b || startsOf.has(it) || mine.has(it)) continue;
10150
10878
  if (!best || dy < best.dy - 1 || Math.abs(dy - best.dy) <= 1 && b.x2 > best.x) best = { ref, dy, x: b.x2, h: b.y2 - b.y1 };
10151
10879
  }
10152
10880
  }
@@ -10154,7 +10882,7 @@ function linkRows(steps, items, bond = 30) {
10154
10882
  if (best.dy > Math.max(6 * bond, 2.5 * best.h + 3 * bond)) continue;
10155
10883
  if (best.x <= Math.min(arrow.tail.x, arrow.head.x)) continue;
10156
10884
  st.roles = { ...roles, reactants: [best.ref] };
10157
- startsOf.add(best.ref);
10885
+ startsOf.add(find2(best.ref) ?? best.ref);
10158
10886
  }
10159
10887
  }
10160
10888
  function plainMeasure(doc) {
@@ -10207,9 +10935,9 @@ function splitCharge(raw) {
10207
10935
  const q = chargeOf(m2[2]);
10208
10936
  return Number.isNaN(q) ? null : { body: m2[1], charge: q };
10209
10937
  }
10210
- m2 = /^(.*?\S)(?:\s+\^?|\^|\()(\d*[+-]+\d*)\)?$/.exec(t);
10211
- if (m2 && (!m2[0].includes("(") || m2[0].endsWith(")"))) {
10212
- const q = chargeOf(m2[2]);
10938
+ m2 = /^(.*?\S)(\s+\^?|\^|\()(\d*[+-]+\d*)(\)?)$/.exec(t);
10939
+ if (m2 && m2[2] === "(" === (m2[4] === ")")) {
10940
+ const q = chargeOf(m2[3]);
10213
10941
  if (!Number.isNaN(q)) return { body: unbracket(m2[1]), charge: q };
10214
10942
  }
10215
10943
  m2 = /^([A-Z][a-z]?)(\d+)([+-])$/.exec(t);
@@ -10284,7 +11012,8 @@ function readSalt(body) {
10284
11012
  if (!rest) continue;
10285
11013
  if (n2 > MAX_SALT_COUNT || m2 > MAX_SALT_COUNT || n2 < 1 || m2 < 1) continue;
10286
11014
  const halide = HALIDES.has(rest) ? { smiles: `[${rest}-]`, name: `${rest === "F" ? "fluor" : rest === "Cl" ? "chlor" : rest === "Br" ? "brom" : "iod"}ide`, kind: "anion" } : null;
10287
- const anion = halide ?? lookUp(rest, 0) ?? lookUp(rest, -1);
11015
+ const plain = lookUp(rest, 0);
11016
+ const anion = halide ?? (plain?.kind === "anion" ? plain : null) ?? lookUp(rest, -1);
10288
11017
  const cat = FIXED_CATIONS[c2] ? null : lookUp(c2, 1);
10289
11018
  if (!anion || anion.kind !== "anion" || !FIXED_CATIONS[c2] && !cat) continue;
10290
11019
  const ga = entryGraph(anion);
@@ -11111,7 +11840,7 @@ function shapeOf(v) {
11111
11840
  }
11112
11841
  const viewOfShape = (k2) => k2 === "boat-flip" ? "boat" : k2;
11113
11842
  const HEXAGON = [0, 1, 2, 3, 4, 5].map((k2) => ({ x: Math.cos((-90 + 60 * k2) * Math.PI / 180), y: Math.sin((-90 + 60 * k2) * Math.PI / 180) }));
11114
- function viewRingOf(doc, atoms) {
11843
+ function viewRingOf(doc, atoms, { allowVariableAttachment = false } = {}) {
11115
11844
  const sel = new Set(atoms);
11116
11845
  if (!sel.size) return { why: "Select a cyclohexane ring first." };
11117
11846
  const sixRings = (bonds, into) => {
@@ -11147,7 +11876,10 @@ function viewRingOf(doc, atoms) {
11147
11876
  return !!b && b.order === 1;
11148
11877
  });
11149
11878
  if (!ringBondsOk) return { why: "Only a ring of single bonds can be drawn as a chair or a boat." };
11150
- if (picked2.some((id) => doc.atoms.get(id).multi)) return { why: "This ring is bonded to a metal through its middle." };
11879
+ const inPicked = new Set(picked2);
11880
+ const over = picked2.flatMap((id) => (doc.centresOf.get(id) ?? []).map((c2) => doc.atoms.get(c2)).filter((c2) => !!c2?.multi && c2.multi.every((x2) => inPicked.has(x2))));
11881
+ if (over.some((c2) => !c2.variable)) return { why: "This ring is bonded to a metal through its middle." };
11882
+ if (!allowVariableAttachment && over.length) return { why: "A ring with a variable attachment keeps its shape: only a ring on its own can be redrawn." };
11151
11883
  const start2 = picked2.indexOf(Math.min(...picked2));
11152
11884
  let ring2 = [...picked2.slice(start2), ...picked2.slice(0, start2)];
11153
11885
  if (ring2[5] < ring2[1]) ring2 = [ring2[0], ...ring2.slice(1).reverse()];
@@ -11419,7 +12151,7 @@ function applyLayout(doc, lay) {
11419
12151
  }
11420
12152
  }
11421
12153
  }
11422
- function nearestPlaces(doc, vr, view2) {
12154
+ function nearestPlaces(doc, vr, view2, allowed) {
11423
12155
  const model = HEXAGON;
11424
12156
  if (!model) return [0, 1, 2, 3, 4, 5];
11425
12157
  const drawn = vr.ring.map((id) => doc.atoms.get(id));
@@ -11471,7 +12203,7 @@ function flatStandIn(doc, atoms) {
11471
12203
  if (!ringBonds$1(doc, r).every((x2) => doc.bonds.get(x2).order === 1) || nearlyHexagon(doc, r)) continue;
11472
12204
  const rough = fitView(doc, { ring: r });
11473
12205
  if (rough.view === "flat" || rough.misfit >= FITS) continue;
11474
- const got = viewRingOf(doc, r);
12206
+ const got = viewRingOf(doc, r, { allowVariableAttachment: true });
11475
12207
  if (!("ring" in got)) {
11476
12208
  kept2.push(r);
11477
12209
  continue;
@@ -11671,7 +12403,8 @@ const DEFAULT_ANALYSIS = {
11671
12403
  { key: "hrms", on: false, label: "", dp: null }
11672
12404
  ],
11673
12405
  autoName: true,
11674
- autoPubchem: false
12406
+ autoPubchem: false,
12407
+ labCalcLook: "guided"
11675
12408
  };
11676
12409
  const copy = (p2) => structuredClone(p2);
11677
12410
  let current = copy(DEFAULT_ANALYSIS);
@@ -12785,6 +13518,53 @@ function readPageTag(v) {
12785
13518
  return null;
12786
13519
  }
12787
13520
  }
13521
+ const NUMS = ["speciesSize", "textSize", "arrowWidth", "headLength", "arrowLength", "structGap", "textGap"];
13522
+ const NONZERO_FORMAT = /* @__PURE__ */ new Set(["speciesSize", "textSize", "arrowWidth"]);
13523
+ const HEADS = /* @__PURE__ */ new Set(["solid", "hollow", "angle"]);
13524
+ function cleanFormat(raw) {
13525
+ if (!raw || typeof raw !== "object") return void 0;
13526
+ const r = raw;
13527
+ const out = {};
13528
+ if (typeof r.font === "string" && r.font.trim() && r.font.length < 120) out.font = r.font.trim();
13529
+ for (const k2 of NUMS) {
13530
+ const v = r[k2];
13531
+ if (typeof v === "number" && isFinite(v) && (NONZERO_FORMAT.has(k2) ? v > 0 : v >= 0) && v <= 500) out[k2] = v;
13532
+ }
13533
+ if (typeof r.headType === "string" && HEADS.has(r.headType)) out.headType = r.headType;
13534
+ return Object.keys(out).length ? out : void 0;
13535
+ }
13536
+ const SHORT = {
13537
+ "oxidative addition": "OA",
13538
+ "reductive elimination": "RE",
13539
+ transmetalation: "TM",
13540
+ "migratory insertion": "MI",
13541
+ "β-hydride elimination": "β-H",
13542
+ "single-electron transfer": "SET",
13543
+ "ligand exchange": "LE"
13544
+ };
13545
+ Object.fromEntries(Object.entries(SHORT).map(([full, short2]) => [short2, full]));
13546
+ const SMART_LAYOUTS = [
13547
+ { id: "line", name: "Line", tip: "Every step in one line, left to right. Branches run below and above it" },
13548
+ { id: "rows", name: "Rows", tip: "Steps in rows, each row starting again on the left" },
13549
+ { id: "snake", name: "Snake", tip: "Steps in rows, every other row running back" },
13550
+ { id: "down", name: "Down", tip: "Every step down the page. Branches run beside it" },
13551
+ { id: "tree", name: "Tree", tip: "Branches fan out in columns: one species leading to several, or several coming together" },
13552
+ { id: "cycle", name: "Cycle", tip: "Around a catalytic cycle, the last step back to the first species. A cycle can have several loops and species off it" }
13553
+ ];
13554
+ const LAYOUT_IDS = new Set(SMART_LAYOUTS.map((l) => l.id));
13555
+ function cleanSmart(raw) {
13556
+ if (!raw || typeof raw !== "object") return null;
13557
+ const r = raw;
13558
+ if (typeof r.layout !== "string" || !LAYOUT_IDS.has(r.layout)) return null;
13559
+ const out = { layout: r.layout };
13560
+ if (typeof r.perRow === "number" && r.perRow >= 1 && r.perRow <= 20) out.perRow = Math.round(r.perRow);
13561
+ if (r.anticlockwise === true) out.anticlockwise = true;
13562
+ if (r.reagentArrows === true) out.reagentArrows = true;
13563
+ if (r.free === true) out.free = true;
13564
+ const fmt2 = cleanFormat(r.fmt);
13565
+ if (fmt2) out.fmt = fmt2;
13566
+ return out;
13567
+ }
12788
13568
  const chiralPrefs = { unflagged: "racemic" };
12789
13569
  const isChiralFlag = (s) => s.kind === "symbol" && !!s.symbol && !!CHIRAL_FLAGS[s.symbol];
12790
13570
  const LOOSE_REACH = 3;
@@ -28639,6 +29419,10 @@ function atomMore(a2, seen, look, stereo, packed = false, just) {
28639
29419
  l.asTyped = true;
28640
29420
  l.label = a2.label;
28641
29421
  }
29422
+ if (a2.ringH && a2.label) {
29423
+ l.ringH = a2.ringH;
29424
+ l.label = a2.label;
29425
+ }
28642
29426
  if (a2.labelMarks !== void 0 && a2.labelMarks !== look.marks) l.marks = a2.labelMarks;
28643
29427
  if (a2.supDigits !== void 0 && a2.supDigits !== look.supDigits) l.supDigits = a2.supDigits;
28644
29428
  if (just) l.just = just;
@@ -28659,6 +29443,12 @@ function atomMoreIn(a2, v, seen, bonded) {
28659
29443
  a2.label = l.label;
28660
29444
  delete a2.fileLabel;
28661
29445
  }
29446
+ if (bonded && (l.ringH === "circle" || l.ringH === "explicit") && typeof l.label === "string") {
29447
+ a2.ringH = l.ringH;
29448
+ a2.label = l.label;
29449
+ delete a2.fileLabel;
29450
+ delete a2.hByRule;
29451
+ }
28662
29452
  }
28663
29453
  stereoIn(a2, v.stereo);
28664
29454
  }
@@ -29083,6 +29873,7 @@ function readCdxml(text2, opts = {}) {
29083
29873
  const skip = (what) => {
29084
29874
  stats.skipped[what] = (stats.skipped[what] ?? 0) + 1;
29085
29875
  };
29876
+ const pictureBudget = unpackBudget();
29086
29877
  const frameTexts2 = /* @__PURE__ */ new Map();
29087
29878
  const flagHomes = [];
29088
29879
  const st = { ...doc.style, name: "From file" };
@@ -30312,7 +31103,7 @@ function readCdxml(text2, opts = {}) {
30312
31103
  case "embeddedobject": {
30313
31104
  const bb = pts$1(ch.getAttribute("BoundingBox"));
30314
31105
  if (bb.length === 4) {
30315
- const pic = pictureOf(ch);
31106
+ const pic = pictureOf(ch, pictureBudget);
30316
31107
  let extra = {};
30317
31108
  let trusted = true;
30318
31109
  try {
@@ -30492,6 +31283,7 @@ function readCdxml(text2, opts = {}) {
30492
31283
  readRepeats();
30493
31284
  for (const el of keepLater) keepXml(el);
30494
31285
  for (const c2 of pendingCircles) if (!ringOfCircle(doc, c2)) c2.oval();
31286
+ const keptNicknames = /* @__PURE__ */ new Set();
30495
31287
  for (const { atom, text: text22, hShown, groupName } of pendingLabels) {
30496
31288
  const auto = hShown !== null && hShown >= 0 && isAutoLabel(atom.z, text22, hShown);
30497
31289
  const bos = doc.valenceSum(atom.id);
@@ -30506,7 +31298,7 @@ function readCdxml(text2, opts = {}) {
30506
31298
  const turned = drawn(text22);
30507
31299
  if (turned !== text22 && drawn(turned) === text22) atom.label = turned;
30508
31300
  }
30509
- if (atom.group) addNicknames({ [groupName ?? atom.label ?? text22]: atom.group });
31301
+ if (atom.group) for (const k2 of addFileNicknames({ [groupName ?? atom.label ?? text22]: atom.group }).kept) keptNicknames.add(k2);
30510
31302
  if (hShown === null && atom.z === 6 && /^[A-Z][a-z]?$/.test(text22) && elementNumber(text22) !== void 0) {
30511
31303
  atom.z = elementNumber(text22);
30512
31304
  atom.label = null;
@@ -30521,6 +31313,8 @@ function readCdxml(text2, opts = {}) {
30521
31313
  }
30522
31314
  }
30523
31315
  }
31316
+ if (pictureBudget.over) (stats.notes ??= []).push(`${pictureBudget.over === 1 ? "A picture" : `${pictureBudget.over} pictures`} in this file ${pictureBudget.over === 1 ? "was" : "were"} not unpacked: the file's pictures together unpack to more than ${MOST_UNPACKED_IN_ALL / 1024 / 1024} MB. A smaller copy is shown where the file has one.`);
31317
+ for (const k2 of keptNicknames) (stats.notes ??= []).push(`This file uses “${k2}” for a different group from your abbreviation “${k2}”. The file's labels keep the file's group; “${k2}” typed as a label is still yours.`);
30524
31318
  for (const { atom, nh } of pendingStatedH) {
30525
31319
  const label = statedHLabel(atom.z, nh, doc.valenceSum(atom.id) - radicalElectrons(atom.radical), atom.charge, atom.radical);
30526
31320
  if (label) atom.label = label;
@@ -30800,7 +31594,13 @@ function readSteps(all, refs, doc) {
30800
31594
  }
30801
31595
  const own = kids$2(st).find((k2) => k2.nodeName === "objecttag" && k2.getAttribute("Name") === STEP_TAG)?.getAttribute("Value");
30802
31596
  try {
30803
- if (own && JSON.parse(own).manual === true) roles.manual = true;
31597
+ if (own) {
31598
+ const parsed = JSON.parse(own);
31599
+ if (parsed && typeof parsed === "object") {
31600
+ if (parsed.manual === true) roles.manual = true;
31601
+ if (typeof parsed.reagentArrows === "boolean") roles.reagentArrows = parsed.reagentArrows;
31602
+ }
31603
+ }
30804
31604
  } catch {
30805
31605
  }
30806
31606
  r.step = roles;
@@ -31112,6 +31912,11 @@ function geoFromTag(saved) {
31112
31912
  const out = {};
31113
31913
  for (const [k2, v] of Object.entries(saved)) {
31114
31914
  if (k2 === "id") continue;
31915
+ if (k2 === "smart") {
31916
+ const smart = cleanSmart(v);
31917
+ if (smart) out.smart = smart;
31918
+ continue;
31919
+ }
31115
31920
  const want = GEO_KINDS[k2];
31116
31921
  if (want && (typeof v !== want || want === "number" && !Number.isFinite(v))) continue;
31117
31922
  if (k2 === "poly" && !(Array.isArray(v) && v.every((p2) => p2 && typeof p2.x === "number" && typeof p2.y === "number"))) continue;
@@ -31372,7 +32177,7 @@ const HEX = (() => {
31372
32177
  }
31373
32178
  return t;
31374
32179
  })();
31375
- function pictureOf(el) {
32180
+ function pictureOf(el, budget) {
31376
32181
  const own = el.getAttribute(OWN_PICTURE);
31377
32182
  const c2 = pts$1(el.getAttribute(OWN_CROP));
31378
32183
  const crop = c2.length === 4 && c2.every(Number.isFinite) ? { l: c2[0], t: c2[1], r: c2[2], b: c2[3] } : null;
@@ -31383,21 +32188,29 @@ function pictureOf(el) {
31383
32188
  } catch {
31384
32189
  }
31385
32190
  }
31386
- const hexBytes2 = (name) => {
32191
+ const hexBytes2 = (name, compressed = false) => {
31387
32192
  const hex2 = el.getAttribute(name);
31388
32193
  if (!hex2 || hex2.length < 48 || !/^[0-9a-f]+$/i.test(hex2.slice(0, 64))) return null;
32194
+ if (compressed && budget.left <= 0) {
32195
+ budget.over++;
32196
+ return null;
32197
+ }
31389
32198
  const bytes = new Uint8Array(hex2.length >> 1);
31390
32199
  for (let i2 = 0, j = 0; i2 < bytes.length; i2++, j += 2) bytes[i2] = HEX[hex2.charCodeAt(j)] << 4 | HEX[hex2.charCodeAt(j + 1)];
31391
32200
  return bytes;
31392
32201
  };
31393
32202
  const picture = (bytes, mime) => ({ src: dataUrl(bytes, mime), px: imageSize(bytes, mime) ?? { w: 100, h: 100 }, crop });
31394
32203
  const unpack = (name) => {
31395
- const packed = hexBytes2(name);
32204
+ const packed = hexBytes2(name, true);
31396
32205
  if (!packed) return null;
31397
- return inflateCapped(packed);
32206
+ return inflateCapped(packed, { budget });
31398
32207
  };
31399
- const wmf = hexBytes2("WindowsMetafile") ?? unpack("CompressedWindowsMetafile");
31400
- const emf = hexBytes2("EnhancedMetafile") ?? unpack("CompressedEnhancedMetafile") ?? (wmf ? emfInWmf(wmf) : null);
32208
+ const over = budget.over;
32209
+ let emf = hexBytes2("EnhancedMetafile") ?? unpack("CompressedEnhancedMetafile");
32210
+ if (!emf) {
32211
+ const wmf = hexBytes2("WindowsMetafile") ?? (budget.over === over ? unpack("CompressedWindowsMetafile") : null);
32212
+ emf = wmf ? emfInWmf(wmf) : null;
32213
+ }
31401
32214
  const drawn = emf ? emfToSvg(emf) : null;
31402
32215
  if (emf && drawn && drawn.vectors > 0) return picture(emf, "image/x-emf");
31403
32216
  for (const [name, mime] of [["PNG", "image/png"], ["JPEG", "image/jpeg"], ["GIF", "image/gif"], ["BMP", "image/bmp"]]) {
@@ -36205,7 +37018,8 @@ class CdxmlWriter {
36205
37018
  n2.setAttribute("GenericNickname", label);
36206
37019
  return;
36207
37020
  }
36208
- const g2 = labelGraph(label);
37021
+ const ext = valenceOfBonds((this.doc.adj.get(a2.id) ?? []).map((bid) => this.doc.bonds.get(bid)).filter((b) => !outsideValence(b)).map((b) => b.order));
37022
+ const g2 = labelGraph(label, ext);
36209
37023
  if (!g2) {
36210
37024
  n2.setAttribute("NodeType", "Unspecified");
36211
37025
  return;
@@ -37842,7 +38656,10 @@ class CdxmlWriter {
37842
38656
  this.changed = true;
37843
38657
  }
37844
38658
  this.fillAtomMap(st, roles);
37845
- const own = [[INSIDE_TAG, ids(roles.inside)], [STEP_TAG, roles.manual ? JSON.stringify({ manual: true }) : ""]];
38659
+ const stepMeta = {};
38660
+ if (roles.manual) stepMeta.manual = true;
38661
+ if (roles.reagentArrows !== void 0) stepMeta.reagentArrows = roles.reagentArrows;
38662
+ const own = [[INSIDE_TAG, ids(roles.inside)], [STEP_TAG, Object.keys(stepMeta).length ? JSON.stringify(stepMeta) : ""]];
37846
38663
  for (const [name, value] of own) {
37847
38664
  const tag = kids$2(st).find((c2) => c2.nodeName === "objecttag" && c2.getAttribute("Name") === name);
37848
38665
  if ((tag?.getAttribute("Value") ?? "") === value) continue;
@@ -39554,49 +40371,195 @@ function placeComponent(g2, orig, keep, labelled2, comp, L10, systems, ringBonds
39554
40371
  }
39555
40372
  return pos;
39556
40373
  }
40374
+ const cellKey = (x2, y2) => x2 + "," + y2;
40375
+ function cellSpan(p2, q, size) {
40376
+ return [
40377
+ Math.floor(Math.min(p2.x, q.x) / size),
40378
+ Math.floor(Math.min(p2.y, q.y) / size),
40379
+ Math.floor(Math.max(p2.x, q.x) / size),
40380
+ Math.floor(Math.max(p2.y, q.y) / size)
40381
+ ];
40382
+ }
40383
+ function visitCells(span, visit) {
40384
+ const [x1, y1, x2, y2] = span;
40385
+ if (!span.every(Number.isSafeInteger) || x2 - x1 > 2 || y2 - y1 > 2) return false;
40386
+ for (let x3 = x1; x3 <= x2; x3++) for (let y3 = y1; y3 <= y2; y3++) visit(cellKey(x3, y3));
40387
+ return true;
40388
+ }
39557
40389
  function crowding(g2, pos, ids, labelled2, L10, ringBonds2) {
39558
40390
  const reach = L10 * 1.15;
39559
- let score2 = 0;
39560
- const pairs2 = [];
40391
+ const found = [];
39561
40392
  if (ringBonds2) {
39562
40393
  const inSet = new Set(ids);
39563
40394
  const edges = [];
39564
40395
  for (const a2 of ids) for (const b of g2.nbr[a2]) if (a2 < b && inSet.has(b)) edges.push([a2, b]);
39565
- for (let i2 = 0; i2 < edges.length; i2++) {
39566
- const [a2, b] = edges[i2];
39567
- const pa = pos.get(a2), pb = pos.get(b);
39568
- for (let j = i2 + 1; j < edges.length; j++) {
39569
- const [c2, d2] = edges[j];
40396
+ let size = reach;
40397
+ for (const [a2, b] of edges) {
40398
+ const p2 = pos.get(a2), q = pos.get(b);
40399
+ size = Math.max(size, Math.abs(p2.x - q.x), Math.abs(p2.y - q.y));
40400
+ }
40401
+ const span = edges.map(([a2, b]) => cellSpan(pos.get(a2), pos.get(b), size));
40402
+ const cells = /* @__PURE__ */ new Map();
40403
+ for (const [i2, bounds2] of span.entries()) {
40404
+ const ok = visitCells(bounds2, (k2) => {
40405
+ const l = cells.get(k2);
40406
+ if (l) l.push(i2);
40407
+ else cells.set(k2, [i2]);
40408
+ });
40409
+ if (!ok) return { score: 0, pairs: [] };
40410
+ }
40411
+ for (const [k2, list2] of cells) {
40412
+ if (list2.length < 2) continue;
40413
+ const [cx, cy] = k2.split(",").map(Number);
40414
+ for (let u2 = 0; u2 < list2.length; u2++) for (let w2 = u2 + 1; w2 < list2.length; w2++) {
40415
+ const i2 = Math.min(list2[u2], list2[w2]), j = Math.max(list2[u2], list2[w2]);
40416
+ if (Math.max(span[i2][0], span[j][0]) !== cx || Math.max(span[i2][1], span[j][1]) !== cy) continue;
40417
+ const [a2, b] = edges[i2], [c2, d2] = edges[j];
39570
40418
  if (a2 === c2 || a2 === d2 || b === c2 || b === d2) continue;
39571
40419
  if (ringBonds2.has(key(a2, b)) && ringBonds2.has(key(c2, d2))) continue;
39572
- if (segmentsCross(pa, pb, pos.get(c2), pos.get(d2))) {
39573
- score2 += L10;
39574
- pairs2.push(ringBonds2.has(key(a2, b)) ? [c2, a2] : [a2, c2]);
39575
- }
40420
+ if (segmentsCross(pos.get(a2), pos.get(b), pos.get(c2), pos.get(d2))) found.push({ i: i2, j, add: L10, pair: ringBonds2.has(key(a2, b)) ? [c2, a2] : [a2, c2] });
39576
40421
  }
39577
40422
  }
39578
40423
  }
40424
+ const crossings = found.length;
40425
+ const where = /* @__PURE__ */ new Map();
40426
+ const cellOf = (p2) => [Math.floor(p2.x / reach), Math.floor(p2.y / reach)];
40427
+ ids.forEach((id, i2) => {
40428
+ const [x2, y2] = cellOf(pos.get(id));
40429
+ const k2 = x2 + "," + y2;
40430
+ const l = where.get(k2);
40431
+ if (l) l.push(i2);
40432
+ else where.set(k2, [i2]);
40433
+ });
39579
40434
  for (let i2 = 0; i2 < ids.length; i2++) {
39580
40435
  const p2 = pos.get(ids[i2]);
39581
- for (let j = i2 + 1; j < ids.length; j++) {
39582
- const q = pos.get(ids[j]);
39583
- if (Math.abs(p2.x - q.x) >= reach || Math.abs(p2.y - q.y) >= reach) continue;
39584
- const near2 = labelled2[ids[i2]] && labelled2[ids[j]] ? reach : L10 * 0.8;
39585
- const d2 = dist(p2, q);
39586
- if (d2 < near2 && !g2.nbr[ids[i2]].includes(ids[j])) {
39587
- score2 += near2 - d2;
39588
- pairs2.push([ids[i2], ids[j]]);
40436
+ const [x2, y2] = cellOf(p2);
40437
+ for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) {
40438
+ for (const j of where.get(x2 + dx + "," + (y2 + dy)) ?? []) {
40439
+ if (j <= i2) continue;
40440
+ const q = pos.get(ids[j]);
40441
+ if (Math.abs(p2.x - q.x) >= reach || Math.abs(p2.y - q.y) >= reach) continue;
40442
+ const near2 = labelled2[ids[i2]] && labelled2[ids[j]] ? reach : L10 * 0.8;
40443
+ const d2 = dist(p2, q);
40444
+ if (d2 < near2 && !g2.nbr[ids[i2]].includes(ids[j])) found.push({ i: i2, j, add: near2 - d2, pair: [ids[i2], ids[j]] });
39589
40445
  }
39590
40446
  }
39591
40447
  }
39592
- return { score: score2, pairs: pairs2 };
40448
+ const order = (x2, y2) => x2.i - y2.i || x2.j - y2.j;
40449
+ const sorted2 = [...found.slice(0, crossings).sort(order), ...found.slice(crossings).sort(order)];
40450
+ let score2 = 0;
40451
+ for (const f4 of sorted2) score2 += f4.add;
40452
+ return { score: score2, pairs: sorted2.map((f4) => f4.pair) };
39593
40453
  }
39594
40454
  function untangle(g2, pos, keep, labelled2, ringBonds2, L10) {
39595
40455
  const ids = [...pos.keys()];
39596
40456
  if (ids.length > 600) return;
40457
+ const reach = L10 * 1.15;
40458
+ const inSet = new Set(ids);
40459
+ const edges = [];
40460
+ for (const a2 of ids) for (const b of g2.nbr[a2]) if (a2 < b && inSet.has(b)) edges.push([a2, b]);
40461
+ const edgesAt = /* @__PURE__ */ new Map();
40462
+ edges.forEach(([a2, b], i2) => {
40463
+ for (const x2 of [a2, b]) {
40464
+ const l = edgesAt.get(x2);
40465
+ if (l) l.push(i2);
40466
+ else edgesAt.set(x2, [i2]);
40467
+ }
40468
+ });
40469
+ const ringEdge = edges.map(([a2, b]) => ringBonds2.has(key(a2, b)));
40470
+ let size = reach;
40471
+ for (const [a2, b] of edges) {
40472
+ const p2 = pos.get(a2), q = pos.get(b);
40473
+ size = Math.max(size, Math.abs(p2.x - q.x), Math.abs(p2.y - q.y));
40474
+ }
40475
+ const indexable = (p2) => Math.abs(p2.x / reach) < Number.MAX_SAFE_INTEGER && Math.abs(p2.y / reach) < Number.MAX_SAFE_INTEGER;
40476
+ if (!Number.isFinite(size) || !ids.every((id) => indexable(pos.get(id)))) return;
39597
40477
  for (let round2 = 0; round2 < 6; round2++) {
39598
40478
  const now = crowding(g2, pos, ids, labelled2, L10, ringBonds2);
39599
40479
  if (!now.pairs.length) return;
40480
+ const atomGrid = /* @__PURE__ */ new Map();
40481
+ for (const id of ids) {
40482
+ const p2 = pos.get(id);
40483
+ const k2 = cellKey(Math.floor(p2.x / reach), Math.floor(p2.y / reach));
40484
+ const l = atomGrid.get(k2);
40485
+ if (l) l.push(id);
40486
+ else atomGrid.set(k2, [id]);
40487
+ }
40488
+ const edgeGrid = /* @__PURE__ */ new Map();
40489
+ const edgeCells = (p2, q, visit) => visitCells(cellSpan(p2, q, size), visit);
40490
+ for (const [i2, [a2, b]] of edges.entries()) {
40491
+ const ok = edgeCells(pos.get(a2), pos.get(b), (k2) => {
40492
+ const l = edgeGrid.get(k2);
40493
+ if (l) l.push(i2);
40494
+ else edgeGrid.set(k2, [i2]);
40495
+ });
40496
+ if (!ok) return;
40497
+ }
40498
+ const within2 = (sideEdges, at2) => {
40499
+ if (sideEdges.length < 2) return 0;
40500
+ const ends = sideEdges.map((i2) => [at2(edges[i2][0]), at2(edges[i2][1])]);
40501
+ const span = ends.map(([p2, q]) => cellSpan(p2, q, size));
40502
+ const cells = /* @__PURE__ */ new Map();
40503
+ for (const [k2, bounds2] of span.entries()) {
40504
+ const ok = visitCells(bounds2, (c2) => {
40505
+ const l = cells.get(c2);
40506
+ if (l) l.push(k2);
40507
+ else cells.set(c2, [k2]);
40508
+ });
40509
+ if (!ok) return Infinity;
40510
+ }
40511
+ let sc = 0;
40512
+ for (const [c2, list2] of cells) {
40513
+ if (list2.length < 2) continue;
40514
+ const [cx, cy] = c2.split(",").map(Number);
40515
+ for (let u2 = 0; u2 < list2.length; u2++) for (let w2 = u2 + 1; w2 < list2.length; w2++) {
40516
+ const k1 = list2[u2], k2 = list2[w2];
40517
+ if (Math.max(span[k1][0], span[k2][0]) !== cx || Math.max(span[k1][1], span[k2][1]) !== cy) continue;
40518
+ const i2 = sideEdges[k1], j = sideEdges[k2];
40519
+ const [a2, b] = edges[i2], [cc, d2] = edges[j];
40520
+ if (a2 === cc || a2 === d2 || b === cc || b === d2) continue;
40521
+ if (ringEdge[i2] && ringEdge[j]) continue;
40522
+ const [f4, g22] = i2 < j ? [k1, k2] : [k2, k1];
40523
+ if (segmentsCross(ends[f4][0], ends[f4][1], ends[g22][0], ends[g22][1])) sc += L10;
40524
+ }
40525
+ }
40526
+ return sc;
40527
+ };
40528
+ const across2 = (inSide, sideEdges, at2) => {
40529
+ let sc = 0;
40530
+ for (const a2 of inSide) {
40531
+ const p2 = at2(a2);
40532
+ const cx = Math.floor(p2.x / reach), cy = Math.floor(p2.y / reach);
40533
+ for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) {
40534
+ for (const b of atomGrid.get(cellKey(cx + dx, cy + dy)) ?? []) {
40535
+ if (inSide.has(b)) continue;
40536
+ const q = pos.get(b);
40537
+ if (Math.abs(p2.x - q.x) >= reach || Math.abs(p2.y - q.y) >= reach) continue;
40538
+ const near2 = labelled2[a2] && labelled2[b] ? reach : L10 * 0.8;
40539
+ const d2 = dist(p2, q);
40540
+ if (d2 < near2 && !g2.nbr[a2].includes(b)) sc += near2 - d2;
40541
+ }
40542
+ }
40543
+ }
40544
+ for (const i2 of sideEdges) {
40545
+ const [a2, b] = edges[i2];
40546
+ const p2 = inSide.has(a2) ? at2(a2) : pos.get(a2), q = inSide.has(b) ? at2(b) : pos.get(b);
40547
+ const seen = /* @__PURE__ */ new Set();
40548
+ const ok = edgeCells(p2, q, (k2) => {
40549
+ for (const j of edgeGrid.get(k2) ?? []) {
40550
+ if (seen.has(j)) continue;
40551
+ seen.add(j);
40552
+ const [c2, d2] = edges[j];
40553
+ if (inSide.has(c2) || inSide.has(d2) || a2 === c2 || a2 === d2 || b === c2 || b === d2) continue;
40554
+ if (ringEdge[i2] && ringEdge[j]) continue;
40555
+ const r = pos.get(c2), t = pos.get(d2);
40556
+ if (i2 < j ? segmentsCross(p2, q, r, t) : segmentsCross(r, t, p2, q)) sc += L10;
40557
+ }
40558
+ });
40559
+ if (!ok) return Infinity;
40560
+ }
40561
+ return sc;
40562
+ };
39600
40563
  let best = null, bestScore = now.score - 1e-6;
39601
40564
  for (const [u2, v] of now.pairs.slice(0, 4)) {
39602
40565
  for (const [x2, y2] of pathBonds(g2, u2, v)) {
@@ -39614,20 +40577,32 @@ function untangle(g2, pos, keep, labelled2, ringBonds2, L10) {
39614
40577
  });
39615
40578
  if (g2.order(from, to) !== 2 && !side.some((a2) => keep[a2])) {
39616
40579
  const axis = sub$1(pos.get(to), pf);
39617
- const k2 = 1 / (axis.x * axis.x + axis.y * axis.y);
39618
- tries.push([(p2) => {
39619
- const d2 = sub$1(p2, pf);
39620
- const t = (d2.x * axis.x + d2.y * axis.y) * k2;
39621
- return add(pf, sub$1(mul$2(axis, 2 * t), d2));
39622
- }, 0]);
40580
+ const length2 = Math.hypot(axis.x, axis.y);
40581
+ if (length2 > 0 && Number.isFinite(length2)) {
40582
+ const unit2 = { x: axis.x / length2, y: axis.y / length2 };
40583
+ tries.push([(p2) => {
40584
+ const d2 = sub$1(p2, pf);
40585
+ return add(pf, sub$1(mul$2(unit2, 2 * dot$1(d2, unit2)), d2));
40586
+ }, 0]);
40587
+ }
39623
40588
  }
40589
+ const inSide = new Set(side);
40590
+ const sideEdges = [...new Set(side.flatMap((a2) => edgesAt.get(a2) ?? []))];
40591
+ const here2 = (a2) => pos.get(a2);
40592
+ const before = across2(inSide, sideEdges, here2) + within2(sideEdges, here2);
39624
40593
  for (const [f4, cost] of tries) {
39625
- const moved = new Map(pos);
39626
- for (const a2 of side) moved.set(a2, f4(pos.get(a2)));
39627
- const sc = crowding(g2, moved, ids, labelled2, L10, ringBonds2).score + cost;
39628
- if (sc < bestScore) {
39629
- bestScore = sc;
39630
- best = moved;
40594
+ const to2 = new Map(side.map((a2) => [a2, f4(pos.get(a2))]));
40595
+ if (side.some((a2) => !indexable(to2.get(a2)))) continue;
40596
+ const there = (a2) => to2.get(a2) ?? pos.get(a2);
40597
+ const sc = now.score - before + across2(inSide, sideEdges, there) + within2(sideEdges, there) + cost;
40598
+ if (sc < bestScore + 1e-6 * L10) {
40599
+ const moved = new Map(pos);
40600
+ for (const [a2, p2] of to2) moved.set(a2, p2);
40601
+ const whole2 = crowding(g2, moved, ids, labelled2, L10, ringBonds2).score + cost;
40602
+ if (whole2 < bestScore) {
40603
+ bestScore = whole2;
40604
+ best = moved;
40605
+ }
39631
40606
  }
39632
40607
  }
39633
40608
  }
@@ -39923,7 +40898,8 @@ function toMolfile(doc, atomIds, name = "", opts = {}) {
39923
40898
  const seen15 = /* @__PURE__ */ new Set();
39924
40899
  for (const id of ids) {
39925
40900
  const a2 = doc.atoms.get(id);
39926
- if (!a2.charge || a2.label || charged.has(id)) continue;
40901
+ const needsKekule = a2.label ? !a2.group && (a2.z === 6 || labelHydrogens(a2.label, 7) === 1 || labelHydrogens(a2.label, 15) === 1) : a2.charge || (a2.z === 7 || a2.z === 15) && doc.hasRingNH(id);
40902
+ if (charged.has(id) || !needsKekule) continue;
39927
40903
  const start2 = (doc.adj.get(id) ?? []).filter((bid) => doc.bonds.get(bid).order === 1.5 && !kekule.has(bid) && !seen15.has(bid));
39928
40904
  if (!start2.length) continue;
39929
40905
  const part2 = /* @__PURE__ */ new Set();
@@ -40004,7 +40980,7 @@ function toMolfile(doc, atomIds, name = "", opts = {}) {
40004
40980
  const at2 = stand?.moves.get(id) ?? a2;
40005
40981
  const x2 = (at2.x - first.x) / L10, y2 = -(at2.y - first.y) / L10;
40006
40982
  let g2 = null;
40007
- const lone = a2.label && !a2.charge && !a2.isotope && !a2.radical && !doc.adj.get(id)?.length ? readSpecies(a2.label, { fragments: true }) : null;
40983
+ const lone = a2.label && !a2.group && !a2.charge && !a2.isotope && !a2.radical && !doc.adj.get(id)?.length ? readSpecies(a2.label, { fragments: true }) : null;
40008
40984
  if (lone && !lone.expected && !lone.graph.atoms.some((ga) => ga.dummy)) {
40009
40985
  attach.set(id, atoms.length);
40010
40986
  pushWritten(lone.graph, x2, y2, id, opts.maps ? a2.mapNo : void 0, a2.label);
@@ -40012,7 +40988,7 @@ function toMolfile(doc, atomIds, name = "", opts = {}) {
40012
40988
  }
40013
40989
  let own = 0;
40014
40990
  if (a2.label) {
40015
- own = valenceOfBonds((doc.adj.get(id) ?? []).map((bid) => doc.bonds.get(bid)).filter((b) => !outsideValence(b) && !dative.has(b.id)).map((b) => b.order));
40991
+ own = valenceOfBonds((doc.adj.get(id) ?? []).map((bid) => doc.bonds.get(bid)).filter((b) => !outsideValence(b) && !dative.has(b.id)).map((b) => kekule.get(b.id) ?? b.order));
40016
40992
  const carbonyl = !a2.group && isCarbonylLabel(a2.label) && toMetal(id);
40017
40993
  g2 = carbonyl && files ? CARBONYL_AS_DRAWN : carbonyl && !own ? CARBONYL_LIGAND : atomLabelGraph(a2, own);
40018
40994
  if (!g2) unknown.push(a2.label);
@@ -40290,6 +41266,17 @@ function hydrogensLast(atoms, bonds, map, inLabel, generic, sgroups = []) {
40290
41266
  for (const g2 of generic) g2[0] = to[g2[0]];
40291
41267
  for (const g2 of sgroups) g2.atoms = g2.atoms.map((k2) => to[k2]);
40292
41268
  }
41269
+ const SMILES_CHARS = /^[A-Za-z0-9@+\-[\]()=#$%/\\.:*~]+$/;
41270
+ function cxSmiles(text2) {
41271
+ const m2 = /^(\S+)\s+\|(.*)\|$/.exec(text2.trim());
41272
+ return m2 && SMILES_CHARS.test(m2[1]) && !m2[1].includes(">") ? { smiles: m2[1], extras: m2[2] } : null;
41273
+ }
41274
+ function rxnV2000Counts(counts) {
41275
+ const nr = parseInt(counts.slice(0, 3), 10), np = parseInt(counts.slice(3, 6), 10);
41276
+ const na = parseInt(counts.slice(6, 9), 10) || 0;
41277
+ if (!Number.isFinite(nr) || !Number.isFinite(np) || nr < 0 || np < 0 || na < 0) return null;
41278
+ return { nr, np, na };
41279
+ }
40293
41280
  function chemFormatOf(name, text2) {
40294
41281
  const ext = (/\.([^.\\/]+)$/.exec(name)?.[1] ?? "").toLowerCase();
40295
41282
  const t = text2.trimStart();
@@ -40605,11 +41592,15 @@ function contract(mol, groups2, ours = false) {
40605
41592
  const crossing = mol.bonds.filter((b) => inG.has(b.a) !== inG.has(b.b));
40606
41593
  const heads = new Set(crossing.map((b) => inG.has(b.a) ? b.a : b.b));
40607
41594
  if (heads.size > 1) continue;
40608
- if (!ours && !sameAtoms(g2.label, g2.atoms.map((k2) => mol.atoms[k2]?.sym ?? ""), crossing.reduce((t, b) => t + Math.round(b.order), 0))) continue;
40609
- if (!ours && !sameMarks(g2.label, g2.atoms.map((k2) => mol.atoms[k2]), crossing.reduce((t, b) => t + Math.round(b.order), 0))) continue;
40610
41595
  const head = crossing.length ? [...heads][0] : g2.atoms[0];
41596
+ const ext = crossing.reduce((t, b) => t + Math.round(b.order), 0);
41597
+ const outside = crossing.map((b) => mol.atoms[b.a === head ? b.b : b.a]);
41598
+ const reading = labelAsWritten(g2.label, ext, outside);
41599
+ if (!reading && (!ours || g2.atoms.length !== 1)) continue;
41600
+ if (reading && !sameGroupBonds(reading, mol, g2.atoms, crossing.length ? head : void 0)) continue;
41601
+ if (reading && !sameMarks(reading, g2.atoms.map((k2) => mol.atoms[k2]), ext)) continue;
40611
41602
  const was = mol.atoms[head];
40612
- const own = (labelAsWritten(g2.label, crossing.reduce((t, b) => t + Math.round(b.order), 0))?.atoms ?? []).reduce((t, a2) => t + (a2.charge ?? 0), 0);
41603
+ const own = reading?.atoms.reduce((t, a2) => t + a2.charge, 0) ?? 0;
40613
41604
  const charge = g2.atoms.reduce((t, k2) => t + (mol.atoms[k2]?.charge ?? 0), 0) - own;
40614
41605
  for (const k2 of g2.atoms) headOf.set(k2, head);
40615
41606
  mol.atoms[head] = { sym: g2.label, x: was.x, y: was.y, label: true, ...charge ? { charge } : {}, ...was.map ? { map: was.map } : {}, ...was.enh ? { enh: was.enh } : {} };
@@ -40632,7 +41623,8 @@ function contract(mol, groups2, ours = false) {
40632
41623
  }));
40633
41624
  return { ...mol, atoms, bonds };
40634
41625
  }
40635
- function labelAsWritten(label, ext) {
41626
+ function labelAsWritten(label, ext, outside) {
41627
+ if (isCarbonylLabel(label) && outside.some((a2) => a2 && !a2.label && isMetal(elementNumber(a2.sym) ?? 0))) return CARBONYL_AS_DRAWN;
40636
41628
  let g2 = null;
40637
41629
  if (!ext) {
40638
41630
  const sp = readSpecies(label, { fragments: true });
@@ -40640,18 +41632,49 @@ function labelAsWritten(label, ext) {
40640
41632
  }
40641
41633
  return g2 ?? labelGraph(label, ext) ?? (ext ? null : labelGraph(label, 1));
40642
41634
  }
40643
- function sameAtoms(label, syms, ext) {
40644
- const g2 = labelAsWritten(label, ext);
40645
- if (!g2) return false;
40646
- const key2 = (zs2) => zs2.filter((z2) => z2 !== 1).sort((p2, q) => p2 - q).join(",");
40647
- const zs = syms.map((t) => /^(\*|R#?|R\d*|A|Q|X|Du)$/.test(t) ? 0 : elementNumber(t));
40648
- if (zs.some((z2) => z2 === void 0)) return false;
40649
- return key2(zs) === key2(g2.atoms.map((a2) => a2.dummy ? 0 : a2.z));
40650
- }
40651
- function sameMarks(label, atoms, ext) {
40652
- if (!atoms.some((a2) => a2?.iso || a2?.rad)) return true;
40653
- const g2 = labelAsWritten(label, ext);
40654
- if (!g2) return false;
41635
+ function sameGroupBonds(g2, mol, ids, head) {
41636
+ if (ids.length > MAX_LABEL_ATOMS * 4 || new Set(ids).size !== ids.length) return false;
41637
+ return [false, true].some((noH) => sameGroupAtoms(g2, mol, ids, head, noH));
41638
+ }
41639
+ function sameGroupAtoms(g2, mol, ids, head, noH) {
41640
+ const generic = (sym) => /^(\*|R#?|R\d*|A|Q|X|Du)$/.test(sym);
41641
+ const keep = g2.atoms.map((a2, k2) => !noH || k2 === 0 || !(a2.z === 1 && !a2.iso && !a2.dummy));
41642
+ const at2 = /* @__PURE__ */ new Map();
41643
+ keep.forEach((y2, k2) => {
41644
+ if (y2) at2.set(k2, at2.size);
41645
+ });
41646
+ const kept2 = noH ? ids.filter((k2) => k2 === head || !(mol.atoms[k2]?.sym === "H" && !mol.atoms[k2]?.iso)) : ids;
41647
+ if (kept2.length !== at2.size) return false;
41648
+ const charged = g2.atoms.some((a2) => a2.charge);
41649
+ const indices = new Map(kept2.map((k2, i2) => [k2, i2]));
41650
+ const atoms = [];
41651
+ for (const k2 of kept2) {
41652
+ const a2 = mol.atoms[k2];
41653
+ if (!a2 || a2.label && !generic(a2.sym)) return false;
41654
+ const z2 = generic(a2.sym) ? 0 : elementNumber(a2.sym);
41655
+ if (z2 === void 0) return false;
41656
+ atoms.push({ z: z2, dummy: z2 === 0, charge: charged ? a2.charge ?? 0 : 0, aromatic: false, ...a2.iso ? { iso: a2.iso } : {} });
41657
+ }
41658
+ const label = { atoms: g2.atoms.filter((_2, k2) => keep[k2]).map(({ z: z2, dummy, charge, iso }) => ({ z: z2, dummy, charge, aromatic: false, ...iso ? { iso } : {} })), bonds: [] };
41659
+ const elements = (xs) => xs.map((a2) => a2.dummy ? 0 : a2.z).sort((u2, v) => u2 - v).join(",");
41660
+ if (elements(atoms) !== elements(label.atoms)) return false;
41661
+ const inGroup = new Set(ids);
41662
+ const bonds = [];
41663
+ for (const b of mol.bonds) {
41664
+ if (!inGroup.has(b.a) || !inGroup.has(b.b)) continue;
41665
+ if (b.dative || b.hbond || b.endpts?.length || b.order === 1 && b.stereo) return false;
41666
+ const a2 = indices.get(b.a), c2 = indices.get(b.b);
41667
+ if (a2 === void 0 || c2 === void 0) continue;
41668
+ bonds.push({ a: a2, b: c2, order: b.order });
41669
+ }
41670
+ const strip = (bs) => bs.filter((b) => at2.has(b.a) && at2.has(b.b)).map((b) => ({ a: at2.get(b.a), b: at2.get(b.b), order: b.order }));
41671
+ label.bonds = strip(g2.bonds);
41672
+ if (label.bonds.length !== bonds.length) return false;
41673
+ const forms2 = kekuleForms(g2, head === void 0 ? void 0 : 0).map(strip);
41674
+ return sameGroupGraph(label, { atoms, bonds }, head === void 0 ? void 0 : indices.get(head), forms2);
41675
+ }
41676
+ function sameMarks(g2, atoms, ext) {
41677
+ if (!atoms.some((a2) => a2?.iso || a2?.rad)) return !g2.atoms.some((a2) => a2.iso);
40655
41678
  const used = g2.atoms.map((_2, k2) => k2 === 0 ? ext : 0);
40656
41679
  for (const b of kekulize(g2)) {
40657
41680
  used[b.a] += b.order;
@@ -40708,10 +41731,9 @@ function readRxnFile(text2) {
40708
41731
  }
40709
41732
  }
40710
41733
  } else {
40711
- const counts = lines[head + 4] ?? "";
40712
- const nr = parseInt(counts.slice(0, 3), 10), np = parseInt(counts.slice(3, 6), 10);
40713
- const na = parseInt(counts.slice(6, 9), 10) || 0;
40714
- if (!Number.isFinite(nr) || !Number.isFinite(np)) return null;
41734
+ const counts = rxnV2000Counts(lines[head + 4] ?? "");
41735
+ if (!counts) return null;
41736
+ const { nr, np, na } = counts;
40715
41737
  let i2 = head + 5, k2 = 0;
40716
41738
  while (i2 < lines.length) {
40717
41739
  if (!lines[i2].startsWith("$MOL")) {
@@ -40725,7 +41747,7 @@ function readRxnFile(text2) {
40725
41747
  k2++;
40726
41748
  i2 = got.end;
40727
41749
  }
40728
- if (k2 < nr + np) return null;
41750
+ if (k2 < nr + np + na) return null;
40729
41751
  }
40730
41752
  return { mols, arrows: [], pluses: [], texts: [], keepPlaces: true };
40731
41753
  }
@@ -40744,8 +41766,11 @@ const num$1 = (s) => {
40744
41766
  const v = parseFloat(s ?? "");
40745
41767
  return Number.isFinite(v) ? v : 0;
40746
41768
  };
40747
- function cmlMolecule(m2, mrv, byId) {
41769
+ const MAX_GROUP_ATOMS = 2e4;
41770
+ const MAX_GROUP_DEPTH = 32;
41771
+ function cmlMolecule(m2, mrv, byId, ctx = { left: MAX_GROUP_ATOMS, depth: 0, memo: /* @__PURE__ */ new Map() }) {
40748
41772
  const atoms = [];
41773
+ const idOf = [];
40749
41774
  const bonds = [];
40750
41775
  const index2 = /* @__PURE__ */ new Map();
40751
41776
  const groupTitle = /* @__PURE__ */ new Map();
@@ -40759,7 +41784,7 @@ function cmlMolecule(m2, mrv, byId) {
40759
41784
  const addAtoms = (owner) => {
40760
41785
  for (const arr of kids(owner, "atomArray")) {
40761
41786
  const list2 = kids(arr, "atom");
40762
- const rows = list2.length ? list2.map((a2) => Object.fromEntries(Array.from(a2.attributes).map((x2) => [x2.localName, x2.value]))) : arrayRows(arr);
41787
+ const rows = atomRows(arr, list2);
40763
41788
  for (const r of rows) {
40764
41789
  const xs = r.x2 ?? r.x3, ys = r.y2 ?? r.y3;
40765
41790
  if (xs === void 0 || ys === void 0 || !Number.isFinite(parseFloat(xs)) || !Number.isFinite(parseFloat(ys))) {
@@ -40773,7 +41798,7 @@ function cmlMolecule(m2, mrv, byId) {
40773
41798
  sym = groupTitle.get(r.sgroupRef).title || "R";
40774
41799
  label = sym !== "R";
40775
41800
  contracted.add(r.sgroupRef);
40776
- if (label) groupOf.set(atoms.length, r.sgroupRef);
41801
+ groupOf.set(atoms.length, r.sgroupRef);
40777
41802
  } else if (sym === "R" && r.rgroupRef && r.rgroupRef !== "0") sym = "R" + r.rgroupRef;
40778
41803
  else if (sym === "Du" || sym === "R") sym = sym === "Du" ? "*" : "R";
40779
41804
  const alias = r.mrvAlias || (list2.length ? kids(list2[rows.indexOf(r)], "label")[0]?.getAttribute("value") : "");
@@ -40799,6 +41824,7 @@ function cmlMolecule(m2, mrv, byId) {
40799
41824
  const mv = parseInt(r.mrvValence ?? "", 10);
40800
41825
  if (mv >= 0) vals.set(atoms.length, mv);
40801
41826
  index2.set(id, atoms.length);
41827
+ idOf[atoms.length] = id;
40802
41828
  byId?.set(id, a2);
40803
41829
  atoms.push(a2);
40804
41830
  }
@@ -40824,16 +41850,67 @@ function cmlMolecule(m2, mrv, byId) {
40824
41850
  };
40825
41851
  addAtoms(m2);
40826
41852
  addBonds(m2);
41853
+ const keepLabel = (i2, el) => {
41854
+ const net = kids(el, "atomArray").flatMap((arr) => atomRows(arr)).reduce((t, r) => t + (parseInt(r.formalCharge ?? "", 10) || 0), 0);
41855
+ const ext = bonds.reduce((t, b) => t + (b.a === i2 || b.b === i2 ? Math.round(b.order) : 0), 0);
41856
+ const own = (labelAsWritten(atoms[i2].sym, ext, [])?.atoms ?? []).reduce((t, a2) => t + (a2.charge ?? 0), 0);
41857
+ if (net - own) atoms[i2].charge = (atoms[i2].charge ?? 0) + net - own;
41858
+ };
40827
41859
  for (const [i2, ref] of groupOf) {
40828
41860
  const el = groupTitle.get(ref).el;
40829
- const charges = kids(el, "atomArray").flatMap((arr) => {
40830
- const list2 = kids(arr, "atom");
40831
- return list2.length ? list2.map((a2) => a2.getAttribute("formalCharge") ?? "") : arrayRows(arr).map((r) => r.formalCharge ?? "");
41861
+ const rows = kids(el, "atomArray").flatMap((arr) => atomRows(arr));
41862
+ const listed = kids(el, "AttachmentPointArray").flatMap((arr) => kids(arr, "attachmentPoint"));
41863
+ const points = Math.max(listed.length, rows.reduce((t, r) => t + (r.sgroupAttachmentPoint === "both" ? 2 : Number(r.sgroupAttachmentPoint) > 0 ? 1 : 0), 0));
41864
+ if (points > 1 || ctx.depth >= MAX_GROUP_DEPTH) {
41865
+ keepLabel(i2, el);
41866
+ continue;
41867
+ }
41868
+ let read2 = ctx.memo.get(el);
41869
+ if (!read2) {
41870
+ const ids = /* @__PURE__ */ new Map();
41871
+ ctx.depth++;
41872
+ read2 = { child: cmlMolecule(el, mrv, ids, ctx), ids };
41873
+ ctx.depth--;
41874
+ ctx.memo.set(el, read2);
41875
+ placeless += read2.child.leftOut ?? 0;
41876
+ }
41877
+ const { child, ids: childIds } = read2;
41878
+ if (!child.atoms.length) continue;
41879
+ const attachment = rows.find((r) => Number(r.sgroupAttachmentPoint) > 0) ?? rows.find((r) => listed.some((p2) => p2.getAttribute("atom") === (r.id ?? r.atomID))) ?? rows[0];
41880
+ const first = childIds.get(attachment?.id ?? attachment?.atomID ?? "") ?? child.atoms[0];
41881
+ const head = child.atoms.indexOf(first);
41882
+ const placeholder = atoms[i2];
41883
+ const crossing = bonds.filter((b) => b.a === i2 || b.b === i2);
41884
+ const ext = crossing.reduce((t, b) => t + Math.round(b.order), 0);
41885
+ const outside = crossing.map((b) => atoms[b.a === i2 ? b.b : b.a]);
41886
+ const reading = labelAsWritten(placeholder.sym, ext, outside);
41887
+ if (reading && !child.leftOut && sameGroupBonds(reading, child, child.atoms.map((_2, k2) => k2), crossing.length ? head : void 0) && sameMarks(reading, child.atoms, ext)) {
41888
+ const net = child.atoms.reduce((t, a2) => t + (a2.charge ?? 0), 0);
41889
+ const own = reading.atoms.reduce((t, a2) => t + a2.charge, 0);
41890
+ if (net - own) placeholder.charge = (placeholder.charge ?? 0) + net - own;
41891
+ continue;
41892
+ }
41893
+ if (head < 0 || child.atoms.length - 1 > ctx.left) {
41894
+ keepLabel(i2, el);
41895
+ continue;
41896
+ }
41897
+ ctx.left -= child.atoms.length - 1;
41898
+ const base = atoms.length;
41899
+ const indexOf = (k2) => k2 === head ? i2 : base + k2 - (k2 > head ? 1 : 0);
41900
+ atoms[i2] = { ...first, x: placeholder.x, y: placeholder.y, ...placeholder.map ? { map: placeholder.map } : {} };
41901
+ if (placeholder.charge) atoms[i2].charge = (first.charge ?? 0) + placeholder.charge;
41902
+ byId?.set(idOf[i2], atoms[i2]);
41903
+ const valence = parseInt(attachment?.mrvValence ?? "", 10);
41904
+ if (valence >= 0 && !(parseInt(attachment?.hydrogenCount ?? "", 10) >= 0)) {
41905
+ const used = bondSum(child.bonds, head) + bondSum(crossing, i2);
41906
+ atoms[i2].hCount = Math.max(0, valence - Math.ceil(used - 1e-6));
41907
+ }
41908
+ vals.delete(i2);
41909
+ hTotal.delete(i2);
41910
+ child.atoms.forEach((a2, k2) => {
41911
+ if (k2 !== head) atoms.push({ ...a2, x: a2.x + placeholder.x - first.x, y: a2.y + placeholder.y - first.y });
40832
41912
  });
40833
- const net = charges.reduce((t, c2) => t + (parseInt(c2, 10) || 0), 0);
40834
- const ext = bonds.reduce((t, b) => t + (b.a === i2 || b.b === i2 ? Math.round(b.order) : 0), 0);
40835
- const own = (labelAsWritten(atoms[i2].sym, ext)?.atoms ?? []).reduce((t, a2) => t + (a2.charge ?? 0), 0);
40836
- if (net - own) atoms[i2].charge = (atoms[i2].charge ?? 0) + net - own;
41913
+ for (const b of child.bonds) bonds.push({ ...b, a: indexOf(b.a), b: indexOf(b.b) });
40837
41914
  }
40838
41915
  for (const s of kids(m2, "molecule")) {
40839
41916
  const id = s.getAttribute("id") ?? "";
@@ -40854,6 +41931,9 @@ function cmlMolecule(m2, mrv, byId) {
40854
41931
  const mol = { atoms, bonds, ...m2.getAttribute("title") ? { name: m2.getAttribute("title") } : {}, ...placeless ? { leftOut: placeless } : {} };
40855
41932
  return expanded.length ? contract(mol, expanded) : mol;
40856
41933
  }
41934
+ function atomRows(arr, list2 = kids(arr, "atom")) {
41935
+ return list2.length ? list2.map((a2) => Object.fromEntries(Array.from(a2.attributes).map((x2) => [x2.localName, x2.value]))) : arrayRows(arr);
41936
+ }
40857
41937
  function arrayRows(arr) {
40858
41938
  const cols = Array.from(arr.attributes).map((x2) => [x2.localName, x2.value.trim().split(/\s+/)]);
40859
41939
  const n2 = Math.max(0, maxOf(cols.map(([, v]) => v.length)));
@@ -45382,6 +46462,11 @@ class Renderer {
45382
46462
  frontier = next;
45383
46463
  }
45384
46464
  for (const id of seen) {
46465
+ for (const bid of doc.adj.get(id) ?? []) {
46466
+ const b = doc.bonds.get(bid);
46467
+ this.bondCache.delete(bid);
46468
+ if (b.order === 1.5) seen.add(b.a1 === id ? b.a2 : b.a1);
46469
+ }
45385
46470
  this.atomCache.delete(id);
45386
46471
  const a2 = doc.atoms.get(id);
45387
46472
  if (a2) rects.push({ x1: a2.x, y1: a2.y, x2: a2.x, y2: a2.y });
@@ -49230,11 +50315,6 @@ function cxNotes(smiles) {
49230
50315
  if (layers.some((l) => l.startsWith("Sg:"))) notes.push("Polymer brackets are not drawn yet; the repeat unit's ends are shown as R.");
49231
50316
  return notes;
49232
50317
  }
49233
- const SMILES_CHARS = /^[A-Za-z0-9@+\-[\]()=#$%/\\.:*~]+$/;
49234
- function cxSmiles(text2) {
49235
- const m2 = /^(\S+)\s+\|(.*)\|$/.exec(text2.trim());
49236
- return m2 && SMILES_CHARS.test(m2[1]) && !m2[1].includes(">") ? { smiles: m2[1], extras: m2[2] } : null;
49237
- }
49238
50318
  var wasm$1;
49239
50319
  var heap = new Array(128).fill(void 0);
49240
50320
  heap.push(void 0, null, true, false);
@@ -52332,7 +53412,7 @@ function pngOptions(dpi, background) {
52332
53412
  function pngOnly(format, o) {
52333
53413
  if (format !== "png" && (o.png.dpi !== void 0 || o.png.background)) log(`Note: --dpi and --background change only PNG pictures, not ${format} files.`);
52334
53414
  }
52335
- const VERSION = "0.1.340";
53415
+ const VERSION = "0.1.341";
52336
53416
  const HELP = `Chemweave ${VERSION}: chemistry drawings from the command line
52337
53417
 
52338
53418
  Usage: