dsh-molbio-tools 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-molbio-tools",
3
- "version": "0.24.0",
4
- "description": "Zero-dependency molecular-biology plugin bundle for the DeepSeek Harness: sequence analysis, primer design (incl. cross-intron qPCR primers, TaqMan hydrolysis/MGB probes with ordering CSV and multiplex compatibility), in-silico PCR, cloning simulation, SnapGene .dna parsing and plasmid maps, Sanger verification, protein tools (incl. helical wheel, hydropathy and charge-pH plots), methylation-aware restriction analysis with double-digest buffer checks, qPCR analysis and plotting, multiple sequence alignment that conserves every input residue, conservation analysis, sequence logos, codon-usage analysis, phylogenetic trees with bootstrap support, Newick I/O and long-name label wrapping, CpG-island/GC-skew composition analysis, k-mer dotplots, read-level FASTQ QC, vector/adapter contamination screening, FASTQ trimming/filtering, batch file analysis with CSV export, silent restriction-site mutagenesis, family-aware CRISPR gRNA design (SpCas9/SaCas9/Cas12a/Cas13) with off-target search, an opt-in hand-off that shows a generated plot to the model as an attached image, plus a browser-side right-sidebar panel (plasmid maps and sequence logos drawn in the Web GUI) and a literature/protocol/experiment record system.",
3
+ "version": "0.25.0",
4
+ "description": "Zero-dependency molecular-biology plugin bundle for the DeepSeek Harness: sequence analysis, primer design (incl. cross-intron qPCR primers, TaqMan hydrolysis/MGB probes with ordering CSV and multiplex compatibility), in-silico PCR, cloning simulation, SnapGene .dna parsing and plasmid maps, Sanger verification, protein tools (incl. helical wheel, hydropathy and charge-pH plots), methylation-aware restriction analysis with double-digest buffer checks, qPCR analysis and plotting, multiple sequence alignment that conserves every input residue, conservation analysis, sequence logos, codon-usage analysis, phylogenetic trees with bootstrap support, Newick I/O and long-name label wrapping, CpG-island/GC-skew composition analysis, k-mer dotplots, read-level FASTQ QC, vector/adapter contamination screening, FASTQ trimming/filtering, batch file analysis with CSV export, silent restriction-site mutagenesis, family-aware CRISPR gRNA design (SpCas9/SaCas9/Cas12a/Cas13) with off-target search, an opt-in hand-off that shows a generated plot to the model as an attached image, plus a browser-side right-sidebar panel (plasmid maps, sequence logos, and a rotatable realistic 3D ball-and-stick/space-filling preview of PDB/mmCIF/SDF structures drawn in the Web GUI) and a literature/protocol/experiment record system.",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
7
7
  "engines": {
@@ -18,7 +18,7 @@
18
18
  "scripts": {
19
19
  "build:client": "node build/client-bundle.mjs",
20
20
  "test": "node --run test:unit && node test/contract.mjs && node test/drift-probe.mjs && node test/preset-health.mjs && node test/release.mjs && node test/benchmark-profile.mjs && node test/benchmark-score.mjs && node test/benchmark-coverage.mjs && node test/benchmark-changed.mjs && node --run bench:offline",
21
- "test:unit": "node test/smoke.mjs && node test/svgpng.mjs && node test/svgio.mjs && node test/charts.mjs && node test/client.mjs && node test/panel-render.mjs && node test/map-card.mjs && node test/client-mount.mjs",
21
+ "test:unit": "node test/smoke.mjs && node test/svgpng.mjs && node test/svgio.mjs && node test/charts.mjs && node test/structure.mjs && node test/client.mjs && node test/panel-render.mjs && node test/map-card.mjs && node test/client-mount.mjs",
22
22
  "test:smoke": "node test/smoke.mjs",
23
23
  "test:svgpng": "node test/svgpng.mjs",
24
24
  "test:charts": "node test/charts.mjs",
@@ -59,6 +59,8 @@
59
59
  "sanger.mjs",
60
60
  "protein.mjs",
61
61
  "protein-structure.mjs",
62
+ "structure-preview.mjs",
63
+ "structure-render.mjs",
62
64
  "protein-charge.mjs",
63
65
  "dotplot.mjs",
64
66
  "contamination.mjs",
package/papers.mjs CHANGED
@@ -51,6 +51,12 @@ export async function loadLibrary(fs, path) {
51
51
  if (typeof parsed !== 'object' || parsed === null || !Array.isArray(parsed.papers)) {
52
52
  throw new Error('expected an object with a "papers" array');
53
53
  }
54
+ // A hand-edited library can contain a null or scalar entry. Without this
55
+ // check, paperKey()/render() would throw a raw TypeError; a clear input
56
+ // error names the file instead.
57
+ if (!parsed.papers.every((paper) => typeof paper === 'object' && paper !== null && !Array.isArray(paper))) {
58
+ throw new Error('every entry in "papers" must be an object');
59
+ }
54
60
  return parsed;
55
61
  } catch (error) {
56
62
  throw new MolbioInputError(`the paper library at ${path} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
@@ -115,6 +121,10 @@ export function updatePaper(library, id, changes) {
115
121
  if (Array.isArray(changes.tags)) {
116
122
  paper.tags = changes.tags.filter((tag) => typeof tag === 'string').map((tag) => tag.trim()).filter((tag) => tag !== '');
117
123
  }
124
+ // The id is DERIVED from pmid, then url, then title+year. Recompute it after
125
+ // an update: leaving the old title-based id in place means adding the renamed
126
+ // paper later is not recognised as a duplicate.
127
+ paper.id = paperKey(paper);
118
128
  return paper;
119
129
  }
120
130
 
package/plot.mjs CHANGED
@@ -70,6 +70,20 @@ function validateNumbers(values, label) {
70
70
  return values;
71
71
  }
72
72
 
73
+ /** Smallest datum, by loop: spreading a long series into Math.min overflows the argument limit. */
74
+ function minValue(values) {
75
+ let min = Infinity;
76
+ for (const value of values) if (value < min) min = value;
77
+ return min;
78
+ }
79
+
80
+ /** Largest datum, by loop (same reason as {@link minValue}). */
81
+ function maxValue(values) {
82
+ let max = -Infinity;
83
+ for (const value of values) if (value > max) max = value;
84
+ return max;
85
+ }
86
+
73
87
  function frameParts(title, xLabel, yLabel) {
74
88
  const parts = [];
75
89
  parts.push(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${WIDTH} ${HEIGHT}" font-family="${FIGURE_FONT}" role="img">`);
@@ -110,11 +124,13 @@ export function renderBarChart({ title, x_label, y_label, labels, values, errors
110
124
  }
111
125
  errs = errors;
112
126
  }
113
- let min = Math.min(0, ...vals);
114
- let max = Math.max(0, ...vals);
127
+ let min = Math.min(0, minValue(vals));
128
+ let max = Math.max(0, maxValue(vals));
115
129
  if (errs !== undefined) {
116
- min = Math.min(min, ...vals.map((v, i) => v - errs[i]));
117
- max = Math.max(max, ...vals.map((v, i) => v + errs[i]));
130
+ for (let index = 0; index < vals.length; index++) {
131
+ min = Math.min(min, vals[index] - errs[index]);
132
+ max = Math.max(max, vals[index] + errs[index]);
133
+ }
118
134
  }
119
135
  if (max === min) max = min + 1;
120
136
  const parts = frameParts(title, x_label, y_label);
@@ -158,15 +174,15 @@ export function renderScatterChart({ title, x_label, y_label, x, y, fit }) {
158
174
  }
159
175
  fitLine = fit;
160
176
  }
161
- let xMin = Math.min(...xs);
162
- let xMax = Math.max(...xs);
177
+ let xMin = minValue(xs);
178
+ let xMax = maxValue(xs);
163
179
  if (xMax === xMin) {
164
180
  const pad = Math.abs(xMax) * 0.1 + 1;
165
181
  xMin -= pad;
166
182
  xMax += pad;
167
183
  }
168
- let yMin = Math.min(...ys);
169
- let yMax = Math.max(...ys);
184
+ let yMin = minValue(ys);
185
+ let yMax = maxValue(ys);
170
186
  if (fitLine !== undefined) {
171
187
  yMin = Math.min(yMin, fitLine.intercept + fitLine.slope * xMin, fitLine.intercept + fitLine.slope * xMax);
172
188
  yMax = Math.max(yMax, fitLine.intercept + fitLine.slope * xMin, fitLine.intercept + fitLine.slope * xMax);
@@ -55,6 +55,14 @@ function flag(name) {
55
55
  }
56
56
 
57
57
  const profile = flag('profile') === undefined ? 'web' : String(flag('profile'));
58
+ // DSH profile names are directory names under <dshHome>/profiles. Reject
59
+ // separators/control characters before the value can reach a child process:
60
+ // on Windows this script runs through a shell, where an unquoted metacharacter
61
+ // (for example "web & calc") would be a command injection.
62
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(profile) || profile === '.' || profile === '..') {
63
+ console.error(`invalid --profile ${JSON.stringify(profile)}: start with a letter or digit, then letters, digits, ".", "_" or "-"`);
64
+ process.exit(2);
65
+ }
58
66
  const checkOnly = flag('check') === true;
59
67
  const dshHomeFlag = flag('dsh-home');
60
68
  const dshHome = resolve(
@@ -278,14 +278,22 @@ export function hydropathyProfile(rawSequence, options = {}) {
278
278
  }
279
279
  if (current !== null) peaks.push(current);
280
280
  const total = points.reduce((sum, point) => sum + point.hydropathy, 0);
281
+ // Loop rather than Math.min(...points): the protein length is not capped and
282
+ // a long input would overflow the argument limit with a RangeError.
283
+ let minimumHydropathy = Infinity;
284
+ let maximumHydropathy = -Infinity;
285
+ for (const point of points) {
286
+ if (point.hydropathy < minimumHydropathy) minimumHydropathy = point.hydropathy;
287
+ if (point.hydropathy > maximumHydropathy) maximumHydropathy = point.hydropathy;
288
+ }
281
289
  return {
282
290
  length: sequence.length,
283
291
  window,
284
292
  threshold,
285
293
  gravy: sequence.length === 0 ? 0 : round2([...sequence].reduce((sum, aa) => sum + KYTE_DOOLITTLE[aa], 0) / sequence.length),
286
294
  mean_profile: round3(total / points.length),
287
- minimum_hydropathy: round3(Math.min(...points.map((point) => point.hydropathy))),
288
- maximum_hydropathy: round3(Math.max(...points.map((point) => point.hydropathy))),
295
+ minimum_hydropathy: round3(minimumHydropathy),
296
+ maximum_hydropathy: round3(maximumHydropathy),
289
297
  peaks: peaks.map((peak) => ({ ...peak, maximum: round3(peak.maximum), length: peak.end - peak.start + 1 })),
290
298
  points,
291
299
  };
package/records.mjs CHANGED
@@ -27,6 +27,11 @@ export async function loadRecords(fs, path, key) {
27
27
  if (typeof parsed !== 'object' || parsed === null || !Array.isArray(parsed[key])) {
28
28
  throw new Error(`expected an object with a "${key}" array`);
29
29
  }
30
+ // See papers.mjs: a null/scalar entry would otherwise reach
31
+ // record.name.trim() (protocols) as a raw TypeError.
32
+ if (!parsed[key].every((record) => typeof record === 'object' && record !== null && !Array.isArray(record))) {
33
+ throw new Error(`every entry in "${key}" must be an object`);
34
+ }
30
35
  return parsed;
31
36
  } catch (error) {
32
37
  throw new MolbioInputError(`${path} is not a valid record file: ${error instanceof Error ? error.message : String(error)}`);
@@ -54,7 +59,7 @@ export function addProtocol(records, entry) {
54
59
  if (typeof entry !== 'object' || entry === null || typeof entry.name !== 'string' || entry.name.trim() === '') {
55
60
  throw new MolbioInputError('each protocol needs a non-empty "name"');
56
61
  }
57
- if (records.some((record) => record.name.trim().toLowerCase() === entry.name.trim().toLowerCase())) {
62
+ if (records.some((record) => typeof record?.name === 'string' && record.name.trim().toLowerCase() === entry.name.trim().toLowerCase())) {
58
63
  throw new MolbioInputError(`a protocol named ${JSON.stringify(entry.name)} already exists`);
59
64
  }
60
65
  const protocol = {
@@ -78,7 +83,17 @@ export function addProtocol(records, entry) {
78
83
  export function updateProtocol(records, id, changes) {
79
84
  const protocol = records.find((record) => record.id === id);
80
85
  if (protocol === undefined) return undefined;
81
- if (typeof changes.name === 'string' && changes.name.trim() !== '') protocol.name = changes.name.trim();
86
+ if (typeof changes.name === 'string' && changes.name.trim() !== '') {
87
+ const nextName = changes.name.trim();
88
+ // addProtocol enforces unique names; update must too, or a rename can
89
+ // create a duplicate the next add refuses to explain.
90
+ if (records.some((record) => record !== protocol
91
+ && typeof record?.name === 'string'
92
+ && record.name.trim().toLowerCase() === nextName.toLowerCase())) {
93
+ throw new MolbioInputError(`a protocol named ${JSON.stringify(nextName)} already exists`);
94
+ }
95
+ protocol.name = nextName;
96
+ }
82
97
  if (typeof changes.category === 'string' && changes.category.trim() !== '') protocol.category = changes.category.trim();
83
98
  if (Array.isArray(changes.steps)) {
84
99
  protocol.steps = changes.steps.filter((step) => typeof step === 'string').map((step) => step.trim()).filter((step) => step !== '');
package/seqio.mjs CHANGED
@@ -96,10 +96,23 @@ export function toFastq(entries) {
96
96
 
97
97
  /** Summary statistics over parsed entries. */
98
98
  export function entryStats(entries, qualityMode = false) {
99
- const lengths = entries.map((entry) => entry.sequence.length);
99
+ // Count in a loop instead of spreading into Math.min/Math.max: a large FASTQ
100
+ // can hold hundreds of thousands of reads (and millions of quality
101
+ // characters), and spreading such an array overflows the engine's argument
102
+ // limit with a RangeError. The numbers are identical; only the failure mode
103
+ // changes.
104
+ let totalBases = 0;
105
+ let minLength = entries.length === 0 ? 0 : Infinity;
106
+ let maxLength = 0;
107
+ let longest = 0;
100
108
  let gc = 0;
101
109
  let at = 0;
102
110
  for (const entry of entries) {
111
+ const length = entry.sequence.length;
112
+ totalBases += length;
113
+ if (length < minLength) minLength = length;
114
+ if (length > maxLength) maxLength = length;
115
+ if (length > longest) longest = length;
103
116
  for (const base of entry.sequence) {
104
117
  if (base === 'G' || base === 'C') gc++;
105
118
  else if (base === 'A' || base === 'T') at++;
@@ -107,22 +120,34 @@ export function entryStats(entries, qualityMode = false) {
107
120
  }
108
121
  const stats = {
109
122
  entries: entries.length,
110
- total_bases: lengths.reduce((sum, len) => sum + len, 0),
111
- min_length: Math.min(...lengths),
112
- max_length: Math.max(...lengths),
113
- mean_length: Math.round((lengths.reduce((sum, len) => sum + len, 0) / lengths.length) * 100) / 100,
123
+ total_bases: totalBases,
124
+ min_length: minLength,
125
+ max_length: maxLength,
126
+ mean_length: entries.length === 0 ? 0 : Math.round((totalBases / entries.length) * 100) / 100,
114
127
  gc_percent: gc + at === 0 ? 0 : Math.round((gc / (gc + at)) * 1000) / 10,
115
128
  };
116
129
  if (qualityMode) {
117
- const allQ = entries.flatMap((entry) => [...entry.quality].map((ch) => ch.charCodeAt(0) - 33));
118
- if (allQ.length > 0) {
119
- const mean = allQ.reduce((sum, q) => sum + q, 0) / allQ.length;
120
- const low = allQ.filter((q) => q < 20).length / allQ.length;
121
- stats.quality_mean = Math.round(mean * 100) / 100;
122
- stats.quality_min = Math.min(...allQ);
123
- stats.quality_max = Math.max(...allQ);
124
- stats.low_quality_fraction = Math.round(low * 1000) / 1000;
125
- const maxLen = Math.min(150, Math.max(...entries.map((e) => e.sequence.length)));
130
+ let qualitySum = 0;
131
+ let qualityCount = 0;
132
+ let lowCount = 0;
133
+ let qualityMin = Infinity;
134
+ let qualityMax = -Infinity;
135
+ for (const entry of entries) {
136
+ for (const ch of entry.quality) {
137
+ const q = ch.charCodeAt(0) - 33;
138
+ qualitySum += q;
139
+ qualityCount++;
140
+ if (q < 20) lowCount++;
141
+ if (q < qualityMin) qualityMin = q;
142
+ if (q > qualityMax) qualityMax = q;
143
+ }
144
+ }
145
+ if (qualityCount > 0) {
146
+ stats.quality_mean = Math.round((qualitySum / qualityCount) * 100) / 100;
147
+ stats.quality_min = qualityMin;
148
+ stats.quality_max = qualityMax;
149
+ stats.low_quality_fraction = Math.round((lowCount / qualityCount) * 1000) / 1000;
150
+ const maxLen = Math.min(150, longest);
126
151
  const perPosition = [];
127
152
  for (let pos = 0; pos < maxLen; pos++) {
128
153
  const values = entries.filter((e) => e.sequence.length > pos).map((e) => e.quality.charCodeAt(pos) - 33);
@@ -0,0 +1,395 @@
1
+ /**
2
+ * dsh-molbio-tools/structure-preview.mjs
3
+ *
4
+ * Pure parsing for structure files shown in the browser panel: PDB, mmCIF and
5
+ * MDL SDF/MOL V2000. Rendering lives in structure-render.mjs, which turns this
6
+ * record into a realistic ball-and-stick or space-filling RGB frame.
7
+ *
8
+ * WHAT THIS IS
9
+ * ------------
10
+ * A compact, dependency-free reader for the coordinates, elements, chains and
11
+ * bonds a preview needs. It does not interpret secondary structure, surfaces,
12
+ * symmetry or multiple models; a failed/unsupported file throws a
13
+ * MolbioInputError naming the file kind, and the panel turns that into a notice.
14
+ *
15
+ * The module is browser-safe on purpose: it imports only MolbioInputError from
16
+ * lib.mjs. It must not import node:fs, node:path or node:zlib.
17
+ */
18
+ import { MolbioInputError } from './lib.mjs';
19
+
20
+ /** Extension to parser kind. The keys are lowercase. */
21
+ export const STRUCTURE_EXTENSIONS = {
22
+ pdb: 'pdb',
23
+ ent: 'pdb',
24
+ cif: 'mmcif',
25
+ mmcif: 'mmcif',
26
+ sdf: 'sdf',
27
+ mol: 'sdf',
28
+ };
29
+
30
+ /** Upper bound on atoms read from one file. */
31
+ export const MAX_STRUCTURE_ATOMS = 20000;
32
+
33
+ /** Upper bound on bonds read from one file. */
34
+ export const MAX_STRUCTURE_BONDS = 40000;
35
+
36
+ /** The format label for a filename, or undefined when it is not a structure. */
37
+ export function structureFormatOf(name) {
38
+ const match = /\.([A-Za-z0-9]+)$/.exec(String(name));
39
+ if (match === null) return undefined;
40
+ return STRUCTURE_EXTENSIONS[match[1].toLowerCase()];
41
+ }
42
+
43
+ /**
44
+ * Parse one structure file.
45
+ * @param {string} format 'pdb' | 'mmcif' | 'sdf'
46
+ * @param {string} text file content (UTF-8 decoded).
47
+ * @param {string} [name] display name, used for the title fallback.
48
+ * @returns {object} the parsed record consumed by structure-render.mjs.
49
+ */
50
+ export function parseStructureText(format, text, name = 'structure') {
51
+ const kind = String(format).toLowerCase();
52
+ if (kind === 'pdb') return withSummary(parsePdb(text, name));
53
+ if (kind === 'mmcif') return withSummary(parseMmcif(text, name));
54
+ if (kind === 'sdf') return withSummary(parseSdf(text, name));
55
+ throw new MolbioInputError('the structure parser accepts pdb, mmcif or sdf/mol files');
56
+ }
57
+
58
+ // ── shared atom helpers ─────────────────────────────────────────────────────
59
+
60
+ const ELEMENTS = new Set(['H', 'C', 'N', 'O', 'S', 'P', 'F', 'CL', 'BR', 'I', 'B', 'SI', 'SE', 'FE', 'ZN', 'MG', 'CA', 'NA', 'K']);
61
+
62
+ /** Element symbol from an atom name, when the file does not carry one. */
63
+ function guessElement(atomName) {
64
+ const cleaned = String(atomName ?? '').toUpperCase().replace(/[^A-Z]/g, '');
65
+ if (cleaned === '') return 'C';
66
+ const two = cleaned.slice(0, 2);
67
+ if (ELEMENTS.has(two)) return two;
68
+ return cleaned.slice(0, 1);
69
+ }
70
+
71
+ /** Element symbol, normalised to upper case and at most two characters. */
72
+ function normalizeElement(value, fallbackName) {
73
+ const element = String(value ?? '').trim().toUpperCase();
74
+ if (element !== '' && element !== '?' && element !== '.') return element.slice(0, 2);
75
+ return guessElement(fallbackName);
76
+ }
77
+
78
+ /** One atom record; all coordinates are finite numbers. */
79
+ function atomRecord({ serial, name, element, residue, chain, residueNumber, x, y, z, hetatm }) {
80
+ return {
81
+ serial,
82
+ name: String(name ?? '').trim(),
83
+ element: normalizeElement(element, name),
84
+ residue: String(residue ?? '').trim(),
85
+ chain: String(chain ?? '').trim(),
86
+ residue_number: String(residueNumber ?? '').trim(),
87
+ x,
88
+ y,
89
+ z,
90
+ hetatm: hetatm === true,
91
+ };
92
+ }
93
+
94
+ /** Reject a file that produced no usable coordinates. */
95
+ function requireAtoms(atoms, format) {
96
+ if (atoms.length === 0) {
97
+ throw new MolbioInputError(`the ${format} file contains no usable atom coordinates`);
98
+ }
99
+ if (atoms.length > MAX_STRUCTURE_ATOMS) {
100
+ throw new MolbioInputError(`the file has ${atoms.length} atoms; the panel reads at most ${MAX_STRUCTURE_ATOMS}`);
101
+ }
102
+ }
103
+
104
+ /** Attach the derived facts the panel shows, without copying the arrays. */
105
+ function withSummary(record) {
106
+ const chains = [...new Set(record.atoms.map((atom) => atom.chain).filter((chain) => chain !== ''))];
107
+ const residues = new Set(record.atoms.map((atom) => `${atom.chain}:${atom.residue_number}:${atom.residue}`));
108
+ return {
109
+ ...record,
110
+ chains,
111
+ chain_count: chains.length,
112
+ residue_count: residues.size,
113
+ hetatm_count: record.atoms.filter((atom) => atom.hetatm).length,
114
+ };
115
+ }
116
+
117
+ // ── PDB ─────────────────────────────────────────────────────────────────────
118
+
119
+ /** Parse PDB ATOM/HETATM records from the first model. */
120
+ export function parsePdb(text, name = 'structure') {
121
+ const atoms = [];
122
+ const serials = new Map();
123
+ const conect = [];
124
+ const titleParts = [];
125
+ let model = 0;
126
+ let sawModel = false;
127
+
128
+ for (const rawLine of String(text).split(/\r?\n/)) {
129
+ const lineText = rawLine.padEnd(80, ' ');
130
+ const recordName = lineText.slice(0, 6).trim().toUpperCase();
131
+ if (recordName === 'TITLE') {
132
+ titleParts.push(lineText.slice(10).trim());
133
+ continue;
134
+ }
135
+ if (recordName === 'MODEL') {
136
+ sawModel = true;
137
+ model += 1;
138
+ continue;
139
+ }
140
+ if (recordName === 'ENDMDL') {
141
+ if (atoms.length > 0) break;
142
+ continue;
143
+ }
144
+ if (recordName !== 'ATOM' && recordName !== 'HETATM') {
145
+ if (recordName === 'CONECT') {
146
+ const numbers = lineText.slice(6).trim().split(/\s+/).map((value) => Number(value)).filter((value) => Number.isInteger(value));
147
+ if (numbers.length > 1) conect.push(numbers);
148
+ }
149
+ continue;
150
+ }
151
+ if (sawModel && model > 1) continue;
152
+ const altLocation = lineText.slice(16, 17);
153
+ if (altLocation !== ' ' && altLocation !== 'A') continue;
154
+ const x = Number(lineText.slice(30, 38));
155
+ const y = Number(lineText.slice(38, 46));
156
+ const z = Number(lineText.slice(46, 54));
157
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) continue;
158
+ const serial = Number(lineText.slice(6, 11).trim());
159
+ const atom = atomRecord({
160
+ serial: Number.isInteger(serial) ? serial : atoms.length + 1,
161
+ name: lineText.slice(12, 16),
162
+ element: lineText.slice(76, 78),
163
+ residue: lineText.slice(17, 20),
164
+ chain: lineText.slice(21, 22),
165
+ residueNumber: lineText.slice(22, 26),
166
+ x,
167
+ y,
168
+ z,
169
+ hetatm: recordName === 'HETATM',
170
+ });
171
+ if (Number.isInteger(atom.serial)) serials.set(atom.serial, atoms.length);
172
+ atoms.push(atom);
173
+ }
174
+
175
+ requireAtoms(atoms, 'PDB');
176
+ const bonds = [];
177
+ for (const numbers of conect) {
178
+ const from = serials.get(numbers[0]);
179
+ if (from === undefined) continue;
180
+ for (const target of numbers.slice(1)) {
181
+ const to = serials.get(target);
182
+ if (to !== undefined) bonds.push({ a: from, b: to, order: 1 });
183
+ }
184
+ }
185
+ return {
186
+ kind: 'structure',
187
+ format: 'pdb',
188
+ name,
189
+ title: titleParts.join(' ').replace(/\s+/g, ' ').trim(),
190
+ atoms,
191
+ bonds: bonds.slice(0, MAX_STRUCTURE_BONDS),
192
+ };
193
+ }
194
+
195
+ // ── mmCIF ───────────────────────────────────────────────────────────────────
196
+
197
+ /** Split a CIF document into tokens, honouring quotes and ; text blocks. */
198
+ function cifTokens(text) {
199
+ const tokens = [];
200
+ const lines = String(text).split(/\r?\n/);
201
+ let index = 0;
202
+ while (index < lines.length) {
203
+ const lineText = lines[index];
204
+ if (lineText.startsWith(';')) {
205
+ const parts = [];
206
+ index += 1;
207
+ while (index < lines.length && !lines[index].startsWith(';')) {
208
+ parts.push(lines[index]);
209
+ index += 1;
210
+ }
211
+ index += 1;
212
+ tokens.push(parts.join('\n'));
213
+ continue;
214
+ }
215
+ let position = 0;
216
+ while (position < lineText.length) {
217
+ while (position < lineText.length && /\s/.test(lineText[position])) position += 1;
218
+ if (position >= lineText.length) break;
219
+ if (lineText[position] === '#') break;
220
+ const quote = lineText[position];
221
+ if (quote === "'" || quote === '"') {
222
+ position += 1;
223
+ const start = position;
224
+ while (position < lineText.length && lineText[position] !== quote) position += 1;
225
+ tokens.push(lineText.slice(start, position));
226
+ if (position < lineText.length) position += 1;
227
+ continue;
228
+ }
229
+ const start = position;
230
+ while (position < lineText.length && !/\s/.test(lineText[position])) position += 1;
231
+ tokens.push(lineText.slice(start, position));
232
+ }
233
+ index += 1;
234
+ }
235
+ return tokens;
236
+ }
237
+
238
+ /** Index of the first tag matching one of the candidate names. */
239
+ function firstTagIndex(tags, candidates) {
240
+ for (const candidate of candidates) {
241
+ const index = tags.indexOf(candidate);
242
+ if (index !== -1) return index;
243
+ }
244
+ return -1;
245
+ }
246
+
247
+ /** Parse the _atom_site loop of an mmCIF document. */
248
+ export function parseMmcif(text, name = 'structure') {
249
+ const tokens = cifTokens(text);
250
+ let atoms = [];
251
+ for (let index = 0; index < tokens.length; index++) {
252
+ if (tokens[index].toLowerCase() !== 'loop_') continue;
253
+ const tags = [];
254
+ let cursor = index + 1;
255
+ while (cursor < tokens.length && tokens[cursor].startsWith('_')) {
256
+ tags.push(tokens[cursor]);
257
+ cursor += 1;
258
+ }
259
+ if (!tags.some((tag) => tag.startsWith('_atom_site.'))) {
260
+ index = cursor - 1;
261
+ continue;
262
+ }
263
+ const values = [];
264
+ while (cursor < tokens.length) {
265
+ const token = tokens[cursor];
266
+ if (token.startsWith('_') || token.toLowerCase() === 'loop_' || token.toLowerCase() === 'stop_' || token.toLowerCase().startsWith('data_')) break;
267
+ values.push(token);
268
+ cursor += 1;
269
+ }
270
+ const rowWidth = tags.length;
271
+ if (rowWidth === 0) continue;
272
+ const column = (candidates) => firstTagIndex(tags, candidates);
273
+ const groupColumn = column(['_atom_site.group_PDB']);
274
+ const atomColumn = column(['_atom_site.label_atom_id', '_atom_site.auth_atom_id']);
275
+ const residueColumn = column(['_atom_site.label_comp_id', '_atom_site.auth_comp_id']);
276
+ const chainColumn = column(['_atom_site.auth_asym_id', '_atom_site.label_asym_id']);
277
+ const residueNumberColumn = column(['_atom_site.auth_seq_id', '_atom_site.label_seq_id']);
278
+ const xColumn = column(['_atom_site.Cartn_x']);
279
+ const yColumn = column(['_atom_site.Cartn_y']);
280
+ const zColumn = column(['_atom_site.Cartn_z']);
281
+ const elementColumn = column(['_atom_site.type_symbol']);
282
+ const modelColumn = column(['_atom_site.pdbx_PDB_model_num']);
283
+ const altColumn = column(['_atom_site.label_alt_id']);
284
+ if (xColumn === -1 || yColumn === -1 || zColumn === -1) continue;
285
+ const rows = [];
286
+ for (let start = 0; start + rowWidth <= values.length; start += rowWidth) {
287
+ rows.push(values.slice(start, start + rowWidth));
288
+ }
289
+ let firstModel;
290
+ const parsed = [];
291
+ for (const row of rows) {
292
+ const cell = (position) => (position === -1 ? '' : row[position]);
293
+ const modelValue = cell(modelColumn);
294
+ if (firstModel === undefined && modelValue !== '' && modelValue !== '.' && modelValue !== '?') firstModel = modelValue;
295
+ if (firstModel !== undefined && modelValue !== '' && modelValue !== '.' && modelValue !== '?' && modelValue !== firstModel) continue;
296
+ const alt = cell(altColumn);
297
+ if (alt !== '' && alt !== '.' && alt !== '?' && alt !== 'A') continue;
298
+ const x = Number(cell(xColumn));
299
+ const y = Number(cell(yColumn));
300
+ const z = Number(cell(zColumn));
301
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) continue;
302
+ const group = cell(groupColumn).toUpperCase();
303
+ parsed.push(atomRecord({
304
+ serial: parsed.length + 1,
305
+ name: cell(atomColumn),
306
+ element: cell(elementColumn),
307
+ residue: cell(residueColumn),
308
+ chain: cell(chainColumn),
309
+ residueNumber: cell(residueNumberColumn),
310
+ x,
311
+ y,
312
+ z,
313
+ hetatm: group === 'HETATM',
314
+ }));
315
+ }
316
+ atoms = parsed;
317
+ break;
318
+ }
319
+
320
+ requireAtoms(atoms, 'mmCIF');
321
+ return {
322
+ kind: 'structure',
323
+ format: 'mmcif',
324
+ name,
325
+ title: '',
326
+ atoms,
327
+ bonds: [],
328
+ };
329
+ }
330
+
331
+ // ── SDF / MOL V2000 ─────────────────────────────────────────────────────────
332
+
333
+ /** Parse the first molecule of an SDF/MOL V2000 file. */
334
+ export function parseSdf(text, name = 'structure') {
335
+ // The first record ends at $$$$; later records are deliberately ignored.
336
+ const first = String(text).split(/^\$\$\$\$/m)[0];
337
+ const lines = first.split(/\r?\n/);
338
+ const title = (lines[0] ?? '').trim();
339
+ let countsIndex = -1;
340
+ for (let index = 0; index < Math.min(lines.length, 8); index++) {
341
+ if (/V2000|V3000/.test(lines[index])) {
342
+ countsIndex = index;
343
+ break;
344
+ }
345
+ }
346
+ if (countsIndex === -1) throw new MolbioInputError('the SDF/MOL file has no V2000 counts line');
347
+ if (/V3000/.test(lines[countsIndex])) {
348
+ throw new MolbioInputError('MDL V3000 is not supported; export the molecule as V2000 SDF or MOL');
349
+ }
350
+ const counts = lines[countsIndex] ?? '';
351
+ const atomCount = Number.parseInt(counts.slice(0, 3), 10);
352
+ const bondCount = Number.parseInt(counts.slice(3, 6), 10);
353
+ if (!Number.isInteger(atomCount) || atomCount <= 0) throw new MolbioInputError('the SDF/MOL counts line declares no atoms');
354
+ if (atomCount > MAX_STRUCTURE_ATOMS) throw new MolbioInputError(`the file has ${atomCount} atoms; the panel reads at most ${MAX_STRUCTURE_ATOMS}`);
355
+ const atoms = [];
356
+ for (let offset = 0; offset < atomCount; offset++) {
357
+ const lineText = lines[countsIndex + 1 + offset] ?? '';
358
+ const x = Number(lineText.slice(0, 10));
359
+ const y = Number(lineText.slice(10, 20));
360
+ const z = Number(lineText.slice(20, 30));
361
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) continue;
362
+ const symbol = lineText.slice(31, 34).trim() || lineText.trim().split(/\s+/)[3] || 'C';
363
+ atoms.push(atomRecord({
364
+ serial: offset + 1,
365
+ name: symbol,
366
+ element: symbol,
367
+ residue: '',
368
+ chain: '',
369
+ residueNumber: '',
370
+ x,
371
+ y,
372
+ z,
373
+ hetatm: false,
374
+ }));
375
+ }
376
+ requireAtoms(atoms, 'SDF/MOL');
377
+ const bonds = [];
378
+ const bondStart = countsIndex + 1 + atomCount;
379
+ for (let offset = 0; offset < bondCount; offset++) {
380
+ const lineText = lines[bondStart + offset] ?? '';
381
+ const from = Number.parseInt(lineText.slice(0, 3), 10) - 1;
382
+ const to = Number.parseInt(lineText.slice(3, 6), 10) - 1;
383
+ const order = Number.parseInt(lineText.slice(6, 9), 10);
384
+ if (from < 0 || to < 0 || from >= atoms.length || to >= atoms.length) continue;
385
+ bonds.push({ a: from, b: to, order: Number.isInteger(order) && order > 0 ? order : 1 });
386
+ }
387
+ return {
388
+ kind: 'structure',
389
+ format: 'sdf',
390
+ name,
391
+ title,
392
+ atoms,
393
+ bonds: bonds.slice(0, MAX_STRUCTURE_BONDS),
394
+ };
395
+ }