dsh-molbio-tools 0.28.0 → 0.28.2

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/test/smoke.mjs CHANGED
@@ -36,7 +36,8 @@ const lib = await import('../lib.mjs');
36
36
  const view = await import('../view.mjs');
37
37
  const snapgene = await import('../snapgene.mjs');
38
38
  const { fastqQcReport } = await import('../fastq-qc.mjs');
39
- const { entryStats } = await import('../seqio.mjs');
39
+ const { entryStats, parseFasta } = await import('../seqio.mjs');
40
+ const { analyzeSequenceFile, globMatches } = await import('../batch.mjs');
40
41
  const { reverseComplement: reverseComplementOf } = lib;
41
42
 
42
43
  // The auto-view opener would spawn real viewer processes on the machine
@@ -228,6 +229,35 @@ async function run(toolName, args) {
228
229
  return value;
229
230
  }
230
231
 
232
+ // ── FASTA comment lines ──────────────────────────────────────────────────────
233
+ {
234
+ // FASTA's "a line starting with ; is a comment" convention. Such a line used to
235
+ // be appended to the sequence (letters survive cleanSequence), so a commented
236
+ // file reported a longer sequence and a wrong GC% with no warning.
237
+ const parsed = parseFasta('>a first\nACGT\n; a comment line\n; another\nTTTT\n');
238
+ assert.equal(parsed.length, 1);
239
+ assert.equal(parsed[0].sequence, 'ACGTTTTT', 'a ";" line is a comment, not sequence');
240
+ assert.equal(parsed[0].id, 'a');
241
+ assert.equal(parsed[0].description, 'first');
242
+ }
243
+
244
+ // ── argument validation: an undeclared key is an ERROR, never a silent default ─
245
+ {
246
+ const gc = registered.find((tool) => tool.name === 'molbio_gc_content');
247
+ await assert.rejects(
248
+ () => gc.execute({ sequence: 'ACGT', window_size: 10 }, fakeExec),
249
+ /unknown argument "window_size"/,
250
+ 'a misspelled argument must fail loudly instead of running with the default',
251
+ );
252
+ await assert.rejects(() => gc.execute({ sequence: 'ACGT', window: 1.5 }, fakeExec), /expected an integer/);
253
+ const map = registered.find((tool) => tool.name === 'molbio_plasmid_map');
254
+ await assert.rejects(
255
+ () => map.execute({ sequence: 'ACGT', features: [{ label: 'x', start: 1, end: 2, strand: 7 }] }, fakeExec),
256
+ /must be one of 1, -1/,
257
+ 'a numeric enum is enforced like a string one',
258
+ );
259
+ }
260
+
231
261
  /** Deterministic pseudo-random DNA for fixtures. */
232
262
  function makeTemplate(n, seed = 42) {
233
263
  let s = seed;
@@ -266,6 +296,12 @@ function makeTemplate(n, seed = 42) {
266
296
  calls.length = 0;
267
297
  assert.equal(await view.openDefaultViewer('/tmp/map.svg', { platform: 'linux', env: {}, run: fakeRun }), false, 'headless Linux never spawns a viewer');
268
298
  assert.equal(calls.length, 0);
299
+ // Only a rendered document may reach the OS opener. `output_path: "x.cmd"` used
300
+ // to write SVG text into a .cmd and then Invoke-Item EXECUTED it — the one way
301
+ // out of the tool sandbox.
302
+ assert.equal(await view.openDefaultViewer(at('evil.cmd'), { platform: 'win32', env: {}, run: fakeRun }), false, 'a script extension is never handed to the OS');
303
+ assert.equal(await view.openDefaultViewer(at('evil.ps1'), { platform: 'win32', env: {}, run: fakeRun }), false);
304
+ assert.equal(calls.length, 0, 'and no opener process starts');
269
305
  }
270
306
 
271
307
  {
@@ -312,8 +348,15 @@ function makeTemplate(n, seed = 42) {
312
348
  }
313
349
 
314
350
  {
315
- const out = await run('molbio_restriction_sites', { sequence: 'G' + 'AATT'.repeat(0) + 'AATTCAAGCTTA', enzymes: ['common'] });
316
- assert.ok(out.enzymes.length > 50);
351
+ // ["common"] means the WHOLE table, but the default answer is the enzymes that
352
+ // actually cut: printing 100+ "no sites" lines buries the one line that matters.
353
+ const sequence = 'G' + 'AATT'.repeat(0) + 'AATTCAAGCTTA';
354
+ const all = await run('molbio_restriction_sites', { sequence, enzymes: ['common'], only_cutting: false });
355
+ assert.ok(all.enzymes.length > 50);
356
+ const cutting = await run('molbio_restriction_sites', { sequence, enzymes: ['common'] });
357
+ assert.equal(cutting.checked, all.enzymes.length);
358
+ assert.ok(cutting.enzymes.every((entry) => entry.cut_positions.length > 0));
359
+ assert.ok(cutting.enzymes.length < all.enzymes.length);
317
360
  }
318
361
 
319
362
  {
@@ -565,6 +608,29 @@ function makeTemplate(n, seed = 42) {
565
608
  assert.deepEqual([junction.features[0].start, junction.features[0].end], [123, 124], 'a ^ junction reads as 123..124');
566
609
  assert.equal(junction.features[0].location, '123^124', 'and its original spelling is kept');
567
610
  assert.equal(junction.features[0].multi_part, false, 'a junction is one point, not several parts');
611
+
612
+ // A join() wider than the column wraps onto 21-space continuation lines. Those
613
+ // are LOCATION continuations: reading them as qualifier continuations silently
614
+ // dropped every part after the first line (1..100 came out as 1..60).
615
+ const folded = [
616
+ 'LOCUS TESTREC 200 bp DNA circular SYN 01-JAN-2020',
617
+ 'FEATURES Location/Qualifiers',
618
+ ' misc_feature join(1..10,50..60,',
619
+ ' 70..80,90..100)',
620
+ ' /label="folded"',
621
+ 'ORIGIN',
622
+ ' 1 acgtacgtac gtacgtacgt acgtacgtac gtgtacgtac gtacgtacgt acgtacgtac',
623
+ '//',
624
+ ].join('\n');
625
+ const foldedOut = await run('molbio_parse_genbank', { genbank: folded });
626
+ assert.deepEqual([foldedOut.features[0].start, foldedOut.features[0].end], [1, 100], 'a wrapped join() keeps every part');
627
+ assert.equal(foldedOut.features[0].label, 'folded', 'and its qualifier still attaches to the feature');
628
+
629
+ // The span is reduced with a loop, never Math.max(...numbers): a 130k-part
630
+ // join() threw RangeError instead of returning a coordinate.
631
+ const manyParts = Array.from({ length: 130000 }, (_, index) => `${index + 1}..${index + 2}`).join(',');
632
+ const bigJoin = await run('molbio_parse_genbank', { genbank: record(`join(${manyParts})`, 'big') });
633
+ assert.deepEqual([bigJoin.features[0].start, bigJoin.features[0].end], [1, 130001], 'a very large join() is still a span');
568
634
  }
569
635
 
570
636
  // ── plasmid map ─────────────────────────────────────────────────────────────
@@ -2829,6 +2895,23 @@ if (savedNcbiEnv.MOLBIO_NCBI_API_KEY !== undefined) process.env.MOLBIO_NCBI_API_
2829
2895
  const nested = await run('molbio_batch_analyze', { directory: 'batch', pattern: '*.fa', recursive: true, output_path: at('nested.csv') });
2830
2896
  assert.ok(nested.files.some((row) => row.path === 'batch/sub/nested.fa'));
2831
2897
 
2898
+ // Glob matching is linear. Translating `*` to `.*` backtracked exponentially
2899
+ // (measured ~1.4 s for this pattern on a 28-character name); the two-pointer
2900
+ // matcher answers immediately and keeps the same `*`/`?` semantics.
2901
+ const globStarted = Date.now();
2902
+ assert.equal(globMatches('*a*a*a*a*a*a*a*a*a*a*b', 'a'.repeat(28) + 'c'), false);
2903
+ assert.ok(Date.now() - globStarted < 100, 'a pathological glob pattern stays linear');
2904
+ assert.equal(globMatches('*.fa', 'x.fa'), true);
2905
+ assert.equal(globMatches('?', 'ab'), false);
2906
+
2907
+ // A 1 Mb genome at a 1 aa minimum yields ~166k ORFs. Reducing their lengths
2908
+ // must be a loop: Math.max(...lengths) threw RangeError and turned the row into
2909
+ // an "error" for a perfectly valid file.
2910
+ const genome = 'ATGTAA'.repeat(166666);
2911
+ const bigOrf = analyzeSequenceFile({ path: 'genome.fa', text: `>genome\n${genome}`, orfMinAa: 1 });
2912
+ assert.ok(bigOrf.orf_count > 0, 'ORF scanning still runs on a 1 Mb sequence');
2913
+ assert.equal(bigOrf.error, '');
2914
+
2832
2915
  // A limit is reported, not silently applied.
2833
2916
  const limited = await run('molbio_batch_analyze', { directory: 'batch', pattern: '*.fa', max_files: 1, output_path: at('limited.csv') });
2834
2917
  assert.equal(limited.file_count, 1);
@@ -3576,7 +3659,10 @@ if (savedNcbiEnv.MOLBIO_NCBI_API_KEY !== undefined) process.env.MOLBIO_NCBI_API_
3576
3659
  '@rna_r', 'ACGT' + reverseComplementOf(smallRna) + 'ACGT', '+', 'I'.repeat(8 + smallRna.length),
3577
3660
  '',
3578
3661
  ].join('\n');
3579
- const qcRna = await run('molbio_fastq_qc', { fastq: smallRnaFastq, adapter_scan_reads: 10, max_plot_bases: 100 });
3662
+ // No `adapter_scan_reads` here: that is an internal FASTQ_QC_DEFAULTS knob, not a
3663
+ // tool parameter. It used to be accepted-and-ignored; the argument validator now
3664
+ // rejects an undeclared key, which is how this test found the lie.
3665
+ const qcRna = await run('molbio_fastq_qc', { fastq: smallRnaFastq, max_plot_bases: 100 });
3580
3666
  assert.deepEqual(
3581
3667
  qcRna.adapter.hits.map((hit) => [hit.name, hit.reads, hit.percent]),
3582
3668
  [["Illumina Small RNA 5'", 2, 100]],
@@ -4174,6 +4260,45 @@ if (savedNcbiEnv.MOLBIO_NCBI_API_KEY !== undefined) process.env.MOLBIO_NCBI_API_
4174
4260
  assert.equal(circular.pairs[0].amplicons[0].wraps_origin, true);
4175
4261
  assert.equal(circular.pairs[0].amplicons[0].sequence, TEMPLATE.slice(150) + TEMPLATE.slice(0, 30), 'the slice wraps as template[151..200] + template[1..30]');
4176
4262
 
4263
+ // 6b. A circular template has exactly `length` start positions. Scanning the
4264
+ // extra one reported position 0 a second time (start=61 on a 60 bp
4265
+ // template) and drew the same amplicon twice.
4266
+ const dupe = await run('molbio_pcr_simulate', {
4267
+ template: 'ACGTACGT' + 'T'.repeat(52),
4268
+ primer_pairs: [{ name: 'dupe', forward: 'ACGTACGT', reverse: rc('ACGTACGT') }],
4269
+ circular: true,
4270
+ min_size: 8,
4271
+ max_size: 100,
4272
+ gel_path: at('pcr-dupe.svg'),
4273
+ });
4274
+ assert.equal(dupe.pairs[0].forward_sites.length, 1, 'no duplicate site at the wrap');
4275
+ assert.deepEqual(dupe.pairs[0].forward_sites.map((site) => site.start), [1]);
4276
+
4277
+ // 6c. A product as long as the template must come back whole: tiling to
4278
+ // `length` instead of `start + length` truncated a full-turn product.
4279
+ const fullTurn = 'ACGTTGCAAGTCCTAGGATCCGATATCGGCTAACGTTAACCGG';
4280
+ const fullTurnOut = await run('molbio_pcr_simulate', {
4281
+ template: fullTurn,
4282
+ primer_pairs: [{ name: 'turn', forward: fullTurn.slice(10, 18), reverse: rc(fullTurn.slice(2, 10)) }],
4283
+ circular: true,
4284
+ min_size: 8,
4285
+ max_size: 100,
4286
+ gel_path: at('pcr-turn.svg'),
4287
+ });
4288
+ assert.equal(fullTurnOut.pairs[0].amplicons[0].size, 43);
4289
+ assert.equal(fullTurnOut.pairs[0].amplicons[0].sequence, fullTurn.slice(10) + fullTurn.slice(0, 10), 'a full-turn product is not truncated');
4290
+
4291
+ // 6d. A poly-A template yields ~n²/2 candidate pairs. The evaluation budget
4292
+ // must stop that before it allocates millions of amplicons, and SAY so.
4293
+ const poly = await run('molbio_pcr_simulate', {
4294
+ template: 'A'.repeat(1200),
4295
+ primer_pairs: [{ name: 'poly', forward: 'AAAAAAAA', reverse: 'TTTTTTTT' }],
4296
+ max_size: 100000,
4297
+ gel_path: at('pcr-poly.svg'),
4298
+ });
4299
+ assert.equal(poly.pairs[0].truncated, true, 'the pair budget reports a partial answer');
4300
+ assert.ok(poly.pairs[0].amplicon_count <= 200);
4301
+
4177
4302
  // 7. Screening a different template (a vector) answers "does this pair also
4178
4303
  // amplify the backbone".
4179
4304
  const screened = await run('molbio_pcr_simulate', {
package/view.mjs CHANGED
@@ -15,8 +15,19 @@ import { spawn } from 'node:child_process';
15
15
  import { release as osRelease } from 'node:os';
16
16
  import { extname } from 'node:path';
17
17
 
18
+ /**
19
+ * The ONLY extensions this opener will hand to the operating system.
20
+ *
21
+ * Auto-view writes a caller-named file and then asks the desktop to OPEN it, so
22
+ * the extension decides what the OS runs. Without this whitelist, a call with
23
+ * `output_path: "x.cmd"` wrote SVG text into a .cmd and `Invoke-Item` executed
24
+ * it — the one path out of the tool sandbox. Everything this package generates
25
+ * is SVG (the document set below), so a narrower whitelist costs nothing.
26
+ */
27
+ const VIEWABLE_EXTENSIONS = new Set(['.html', '.htm', '.xhtml', '.svg']);
28
+
18
29
  /** Documents a browser renders, opened with the default browser when one can be named. */
19
- const BROWSER_DOCUMENTS = new Set(['.html', '.htm', '.xhtml', '.svg']);
30
+ const BROWSER_DOCUMENTS = VIEWABLE_EXTENSIONS;
20
31
 
21
32
  function present(value) {
22
33
  return value !== undefined && value !== '';
@@ -128,6 +139,7 @@ export async function openDefaultViewer(path, internals = {}) {
128
139
  const env = internals.env ?? process.env;
129
140
  const wsl = platform === 'linux' && isWsl(internals);
130
141
  const ext = extname(path).toLowerCase();
142
+ if (!VIEWABLE_EXTENSIONS.has(ext)) return false;
131
143
  if (!wsl && BROWSER_DOCUMENTS.has(ext) && await openInBrowser(path, internals)) return true;
132
144
  if (platform === 'darwin') {
133
145
  await runCommand('open', [path], internals);