@jacebenson/jsn 5.5.3-dev.182.1 → 5.5.3-dev.184.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.3-dev.182.1",
3
+ "version": "5.5.3-dev.184.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -28,6 +28,7 @@
28
28
  "@inquirer/core": "^10.3.2",
29
29
  "@inquirer/prompts": "^7.10.1",
30
30
  "better-sqlite3": "^13.1.1",
31
+ "commonmark": "^0.31.2",
31
32
  "js-yaml": "^5.5.0",
32
33
  "saxes": "^6.0.0",
33
34
  "turndown": "^7.2.5"
package/src/cli.js CHANGED
@@ -100,10 +100,11 @@ import { graphqlCmd } from './commands/graphql.js';
100
100
  *
101
101
  * Precedence is the middleware's, unchanged: the shortcut flags beat `--format`,
102
102
  * and among the shortcuts the one applied last wins
103
- * (csv > markdown > styled > quiet > json).
103
+ * (tsv > csv > markdown > styled > quiet > json).
104
104
  */
105
105
  export function resolveRequestedFormat(argv) {
106
106
  if (!argv) return '';
107
+ if (argv.tsv) return 'tsv';
107
108
  if (argv.csv) return 'csv';
108
109
  if (argv.markdown) return 'markdown';
109
110
  if (argv.styled) return 'styled';
@@ -175,8 +176,8 @@ export function buildCLI() {
175
176
  },
176
177
  format: {
177
178
  type: 'string',
178
- description: 'Output format: auto, json, markdown, styled, quiet, csv',
179
- choices: ['auto', 'json', 'markdown', 'styled', 'quiet', 'csv'],
179
+ description: 'Output format: auto, json, markdown, styled, quiet, csv, tsv',
180
+ choices: ['auto', 'json', 'markdown', 'styled', 'quiet', 'csv', 'tsv'],
180
181
  },
181
182
  json: {
182
183
  type: 'boolean',
@@ -184,7 +185,11 @@ export function buildCLI() {
184
185
  },
185
186
  csv: {
186
187
  type: 'boolean',
187
- description: 'Output in CSV format (shortcut for --format=csv)',
188
+ description: 'CSV output for compact, flat record lists',
189
+ },
190
+ tsv: {
191
+ type: 'boolean',
192
+ description: 'TSV output for compact, tab-separated record lists',
188
193
  },
189
194
  get: {
190
195
  alias: 'select',
@@ -1,5 +1,6 @@
1
1
  // Public documentation service. Deliberately independent of instance credentials.
2
2
  import { AppError } from '../../errors.js';
3
+ import { selectDocument, SECTION_PROTOCOL } from './sections.js';
3
4
 
4
5
  export const DEFAULT_DOCS_URL = 'https://jsn.jace.pro';
5
6
  const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
@@ -73,12 +74,27 @@ export async function searchHostedDocs(options = {}) {
73
74
  export async function getHostedDoc(idOrPath, options = {}) {
74
75
  const identifier = String(idOrPath || '');
75
76
  if (!identifier) throw new AppError('usage_error', 'Provide a document ID or exact path.');
77
+ if ((options.outline && options.section !== undefined) || (options.section !== undefined && !String(options.section).trim())) throw new AppError('usage_error', 'Use either --outline or one nonempty --section.');
76
78
  const numeric = /^\d+$/.test(identifier);
77
79
  const { data, service } = await request(numeric ? `api/docs/${identifier}` : 'api/docs/document', {
78
80
  ...(numeric ? {} : { path: identifier }), revision: options.revision, release: options.release,
81
+ outline: options.outline || undefined, section: options.section,
79
82
  }, options);
80
- if (!data || !data.document || typeof data.document.body !== 'string' || typeof data.document.path !== 'string' || typeof data.revision !== 'string') throw invalidResponse();
81
- return { ...data.document, release: options.release ?? data.release, revision: data.revision, service };
83
+ const targeted = options.outline || options.section !== undefined;
84
+ const native = data?.section_protocol === SECTION_PROTOCOL;
85
+ if (!data?.document || typeof data.document.path !== 'string' || typeof data.revision !== 'string' ||
86
+ (!(targeted && native && options.outline) && typeof data.document.body !== 'string')) throw invalidResponse();
87
+ if (options.revision && data.revision !== options.revision) throw new AppError('api_error', 'Documentation revision mismatch. Refresh the outline.');
88
+ if (options.release && data.document.release && data.document.release !== options.release) throw new AppError('api_error', `Documentation service returned release ${data.document.release}, expected ${options.release}.`);
89
+ let row = { ...data.document, release: options.release ?? data.release ?? data.document.release, revision: data.revision, service };
90
+ if (targeted) {
91
+ if (!native) row = selectDocument(row, options);
92
+ const mode = options.outline ? 'outline' : 'section';
93
+ if (row.retrieval?.protocol !== SECTION_PROTOCOL || row.retrieval?.mode !== mode ||
94
+ (options.outline ? !Array.isArray(row.outline) : !row.section || row.retrieval.subtree_complete !== true)) throw invalidResponse();
95
+ row.retrieval = { ...row.retrieval, execution: native ? 'service' : 'client-fallback', full_document_transferred: !native };
96
+ }
97
+ return row;
82
98
  }
83
99
  export async function getHostedDocsStatus(options = {}) {
84
100
  const { data, service } = await request('api/docs/status', { release: options.release }, options);
@@ -9,6 +9,10 @@ import { listDocsReleases } from './releases.js';
9
9
 
10
10
  declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
11
11
 
12
+ function presented(data, text) {
13
+ return Object.defineProperty(data, '_formatted', { value: text, enumerable: false });
14
+ }
15
+
12
16
  async function search(argv, app) {
13
17
  const query = Array.isArray(argv.query) ? argv.query.join(' ') : argv.query;
14
18
  const result = await searchHostedDocs({ query, limit: argv.limit, offset: argv.offset, bundle: argv.bundle, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
@@ -29,11 +33,18 @@ async function search(argv, app) {
29
33
  async function read(argv, app) {
30
34
  const maxLines = argv.lines ?? 80;
31
35
  if (!Number.isInteger(maxLines) || maxLines < 1 || maxLines > 10000) throw new AppError('usage_error', 'Use --lines 1–10000.');
32
- const row = await getHostedDoc(argv.path || argv['id-or-path'], { revision: argv.revision, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
36
+ const row = await getHostedDoc(argv.path || argv['id-or-path'], { outline: argv.outline, section: argv.section, revision: argv.revision, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
33
37
  const title = row.title || row.path;
38
+ const provenance = `${row.path}\nRelease: ${row.release} | Revision: ${row.revision}\nService: ${row.service}`;
39
+ if (row.outline) {
40
+ const text = row.outline.map(h => `${' '.repeat(h.ancestors.length)}${h.title} [lines ${h.start_line}–${h.end_line}]\n${' '.repeat(h.ancestors.length)} ${h.id}`).join('\n');
41
+ return app.ok(presented(row, `${title}\n${provenance}\n\n${text || 'No selectable headings.'}\n\nUse --section '<ID>' with this --path. Selection includes preamble and ancestor introductions.\nOther sections and linked prerequisites may still matter.\nRetrieval: ${row.retrieval.execution}; full document transferred: ${row.retrieval.full_document_transferred}\n`));
42
+ }
34
43
  const lines = row.body.split('\n');
35
44
  const hint = lines.length > maxLines ? `\n\n… ${lines.length - maxLines} more lines (use --lines ${Math.min(lines.length, 10000)} or --json for full content)` : '';
36
- app.ok({ ...row, _formatted: `Doc ${row.id}: ${title} in ${row.release}\n${'─'.repeat(Math.min(title.length, 80))}\n\n${lines.slice(0, maxLines).join('\n')}${hint}\n` }, { summary: `Doc ${row.id}: ${title} in ${row.release}` });
45
+ const content = row.section ? row.body : lines.slice(0, maxLines).join('\n') + hint;
46
+ const context = row.section ? `\nComplete selected subtree: ${row.section.title}\n${row.retrieval.context_policy}\nOther sections to check: ${row.retrieval.context_sections.map(h => h.title).join('; ') || 'none'}.\nUse --outline to retrieve their IDs.\nSemantic answer completeness: unknown. Retrieval: ${row.retrieval.execution}.\n` : '';
47
+ app.ok(presented(row, `Doc ${row.id}: ${title} in ${row.release}\n${provenance}${context}\n${content}\n`), { summary: `Doc ${row.id}: ${title} in ${row.release}` });
37
48
  }
38
49
 
39
50
  export function docsCmd(wrap) {
@@ -53,7 +64,9 @@ export function docsCmd(wrap) {
53
64
  .option('bundle', { type: 'string', describe: 'Filter by documentation bundle' })
54
65
  .option('path', { type: 'string', describe: 'Read an exact document path or ID from search results' })
55
66
  .option('revision', { type: 'string', describe: 'Require the revision returned by search (recommended with IDs)' })
56
- .option('lines', { type: 'number', default: 80, describe: 'Preview lines; JSON contains the full Markdown body' })
67
+ .option('outline', { type: 'boolean', describe: 'List revision-bound section IDs for --path, without document body' })
68
+ .option('section', { type: 'string', describe: 'Read a complete subtree by outline ID or exact unique heading; includes ancestor introductions' })
69
+ .option('lines', { type: 'number', default: 80, describe: 'Full-document human preview lines; JSON and selected sections are not truncated' })
57
70
  .command({ command: 'releases', describe: 'List locally installed documentation families', handler: wrap(async (_argv, app) => {
58
71
  const releases = listDocsReleases();
59
72
  app.ok({ releases, _formatted: releases.length ? releases.map(row => `${row.release}${row.default ? ' (default)' : ''} ${row.revision || 'unknown'} ${row.documents} documents ${row.indexPath}`).join('\n') + '\n' : 'No local documentation families installed.\n' }, { summary: `${releases.length} local documentation release(s)` });
@@ -90,6 +103,7 @@ export function docsCmd(wrap) {
90
103
  for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
91
104
  return;
92
105
  }
106
+ if ((argv.outline || argv.section !== undefined) && !argv.path) throw new AppError('usage_error', 'Use --path with --outline or --section.');
93
107
  if (argv.path) return read(argv, app);
94
108
  if (argv.query?.length) return search(argv, app);
95
109
  const service = await documentationService(app.config, resolveDocsRelease(argv.release, app.config));
@@ -1,5 +1,6 @@
1
1
  // One search engine for the hosted website and the optional local service.
2
2
  import fs from 'node:fs';
3
+ import { selectDocument } from './sections.js';
3
4
  import path from 'node:path';
4
5
  import Database from 'better-sqlite3';
5
6
  import { resolveDocsDbPath } from './db.js';
@@ -72,11 +73,11 @@ export class DocumentationIndex {
72
73
  .all(...binds, text, text, text, limit, offset).map(documentationSummary);
73
74
  return { query: text, revision: this.revision(), total, count: results.length, limit, offset, results };
74
75
  }
75
- document({ id, path: docPath } = {}) {
76
+ document({ id, path: docPath, outline = false, section } = {}) {
76
77
  const select = 'SELECT id, path, title, bundle, doc_type, release, body FROM docs WHERE';
77
78
  const row = docPath ? this.db.prepare(`${select} path = ?`).get(docPath)
78
79
  : /^\d{1,18}$/.test(String(id)) ? this.db.prepare(`${select} id = ?`).get(String(id)) : null;
79
80
  if (!row) throw new DocumentationError('Document not found.', 404);
80
- return row;
81
+ return outline || section !== undefined ? selectDocument({ ...row, revision: this.revision() }, { outline, section }) : row;
81
82
  }
82
83
  }
@@ -0,0 +1,59 @@
1
+ // CommonMark source positions let us slice original text, never reserialize tables/code.
2
+ import * as commonmark from 'commonmark';
3
+ import { createHash } from 'node:crypto';
4
+ import { AppError } from '../../errors.js';
5
+
6
+ export const SECTION_PROTOCOL = 'sections-v1';
7
+ function failure(message) { return new AppError('usage_error', message, 'Use --outline for exact titles and revision-bound IDs.', 400); }
8
+ export function selectDocument(row, { outline = false, section } = {}) {
9
+ if (outline && section !== undefined) throw failure('Use either --outline or --section, not both.');
10
+ if (section !== undefined && !String(section).trim()) throw failure('Section must not be empty.');
11
+ if (!outline && section === undefined) return row;
12
+ const body = row.body;
13
+ const starts = [0];
14
+ for (const match of body.matchAll(/\r\n|\n|\r/g)) starts.push(match.index + match[0].length);
15
+ const ast = new commonmark.Parser().parse(body);
16
+ const headings = [];
17
+ for (let node = ast.firstChild; node; node = node.next) {
18
+ if (node.type !== 'heading') continue; // Never split lists, blockquotes or HTML blocks.
19
+ let title = '', walker = node.walker(), event;
20
+ while ((event = walker.next())) {
21
+ if (event.entering && ['text', 'code'].includes(event.node.type)) title += event.node.literal;
22
+ if (event.entering && ['softbreak', 'linebreak'].includes(event.node.type)) title += ' ';
23
+ }
24
+ headings.push({ title, depth: node.level, start_line: node.sourcepos[0][0], start: starts[node.sourcepos[0][0] - 1] });
25
+ }
26
+ const identity = createHash('sha256').update(JSON.stringify([SECTION_PROTOCOL, row.path, row.release, row.revision, body])).digest('hex').slice(0, 24);
27
+ const stack = [];
28
+ for (let i = 0; i < headings.length; i++) {
29
+ const h = headings[i];
30
+ while (stack.length && headings[stack.at(-1)].depth >= h.depth) stack.pop();
31
+ h.ancestors = stack.map(n => headings[n].id);
32
+ h.id = `s1:${identity}:${i + 1}`;
33
+ const next = headings.slice(i + 1).find(n => n.depth <= h.depth);
34
+ h.end = next?.start ?? body.length;
35
+ h.end_line = next ? next.start_line - 1 : starts.length;
36
+ h.introEnd = headings[i + 1]?.start ?? body.length;
37
+ stack.push(i);
38
+ }
39
+ const publicHeading = ({ start: _start, end: _end, introEnd: _introEnd, ...h }) => h; // Offsets remain an implementation detail.
40
+ const metadata = { protocol: SECTION_PROTOCOL, document_complete: false, semantic_completeness: 'unknown', truncated: false,
41
+ heading_policy: 'CommonMark top-level ATX/setext; container and HTML headings are not boundaries' };
42
+ const { body: _body, ...identityRow } = row;
43
+ if (outline) return { ...identityRow, outline: headings.map(publicHeading), retrieval: { ...metadata, mode: 'outline', total_lines: starts.length, context_policy: 'Selection includes preamble and ancestor introductions; other sections may contain relevant context.' } };
44
+ const matches = headings.filter(h => h.id === section || h.title === section);
45
+ if (!matches.length) throw failure('No matching section. IDs are document- and revision-bound; refresh the outline.');
46
+ if (matches.length !== 1) throw failure(`Ambiguous section ${JSON.stringify(section)}. Choose an ID: ${matches.map(h => `${h.id} (${h.title}, line ${h.start_line})`).join('; ')}`);
47
+ const h = matches[0];
48
+ const spans = [];
49
+ const add = (start, end, kind) => { if (end > start) spans.push({ start, end, kind }); };
50
+ add(0, headings[0]?.start ?? body.length, 'preamble');
51
+ for (const id of h.ancestors) { const a = headings.find(n => n.id === id); add(a.start, a.introEnd, 'ancestor-introduction'); }
52
+ add(h.start, h.end, 'section-subtree');
53
+ return { ...identityRow, body: spans.map(s => body.slice(s.start, s.end)).join(''), section: publicHeading(h), retrieval: {
54
+ ...metadata, mode: 'section', subtree_complete: true, document_complete: spans.reduce((n, s) => n + s.end - s.start, 0) === body.length,
55
+ context_policy: 'Preamble and ancestor introductions included. Sibling sections and linked prerequisites are not automatically included; read the full document when needed.',
56
+ context_sections: headings.filter(n => !spans.some(s => n.start >= s.start && n.start < s.end)).map(n => ({ id: n.id, title: n.title })),
57
+ included_spans: spans.map(s => ({ start_offset: s.start, end_offset: s.end, kind: s.kind })),
58
+ } };
59
+ }
@@ -1,4 +1,5 @@
1
1
  import http from 'node:http';
2
+ import { SECTION_PROTOCOL } from './sections.js';
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import os from 'node:os';
@@ -27,7 +28,9 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
27
28
  if (url.pathname === '/api/docs/search') return send(200, { ...index.search({ query: params.q, limit: params.limit ?? 20, offset: params.offset ?? 0, bundle: params.bundle }), release });
28
29
  const revision = index.revision();
29
30
  if (params.revision && params.revision !== revision) return send(409, { error: 'Documentation has changed. Search again or retrieve by exact path.' });
30
- return send(200, { release, revision, document: index.document({ path: params.path, id: url.pathname.split('/').at(-1) }) });
31
+ if (params.outline !== undefined && params.outline !== 'true') return send(400, { error: 'outline must be true.' });
32
+ const document = index.document({ path: params.path, id: url.pathname.split('/').at(-1), outline: params.outline === 'true', section: params.section });
33
+ return send(200, { release, revision, section_protocol: SECTION_PROTOCOL, document });
31
34
  } catch (error) { send(error.status || 503, { error: error.status ? error.message : 'Documentation search is temporarily unavailable.' }); }
32
35
  finally { index?.close(); }
33
36
  });
package/src/help.js CHANGED
@@ -14,11 +14,11 @@ const COMMON_COMMANDS = [
14
14
  'incidents', 'requests', 'tasks', 'changes', 'approvals', 'knowledge', 'records', 'setup', 'discover',
15
15
  ];
16
16
 
17
- const CONCISE_FLAGS = ['instance', 'profile', 'json'];
17
+ const CONCISE_FLAGS = ['instance', 'profile', 'json', 'csv', 'tsv'];
18
18
 
19
19
  const CONCISE_EXAMPLES = [
20
20
  'jsn incidents list --query "active=true" --limit 5',
21
- 'jsn records list --table incident --limit 5 --json',
21
+ 'jsn records list --table incident --columns sys_id,number,state --limit 5 --csv',
22
22
  'jsn discover catalog',
23
23
  ];
24
24
 
@@ -242,6 +242,8 @@ function renderFlags(options, { full = false, width = helpWidth() } = {}) {
242
242
  * examples, and pointers to the exhaustive reference and local discovery.
243
243
  */
244
244
  function renderConciseHelp(config, registry, width) {
245
+ // Keep the short page consistent between ordinary 80-column terminals and pipes.
246
+ width = Math.min(width, 80);
245
247
  const commands = Array.isArray(registry?.commands) ? registry.commands : [];
246
248
  const byName = new Map(commands.map((command) => [command.name, command]));
247
249
  const common = COMMON_COMMANDS
@@ -259,9 +261,16 @@ function renderConciseHelp(config, registry, width) {
259
261
  renderGroup('COMMON COMMANDS', common, width),
260
262
  '',
261
263
  'EXAMPLES',
262
- ...CONCISE_EXAMPLES.map((example) => ` ${example}`),
264
+ ...CONCISE_EXAMPLES.map((example) => wrapText(example, { width: width - 2, firstIndent: 2 }).join(' \\\n')),
263
265
  renderFlags(Array.isArray(registry?.options) ? registry.options : [], { width }),
264
266
  '',
267
+ 'OUTPUT',
268
+ ...[
269
+ 'For smaller list responses, select fields with --columns and bound rows with --limit.',
270
+ 'CSV and TSV avoid repeated field names; JSON preserves metadata and nested structure.',
271
+ 'Use JSON for pagination metadata or both reference IDs and display labels.',
272
+ ].flatMap(text => wrapText(text, { width, firstIndent: 2 })),
273
+ '',
265
274
  'MORE',
266
275
  renderRows(CONCISE_MORE, { width, indent: 2 }),
267
276
  '',
package/src/output.js CHANGED
@@ -9,6 +9,7 @@ export const FormatMarkdown = 'markdown';
9
9
  export const FormatStyled = 'styled';
10
10
  export const FormatQuiet = 'quiet';
11
11
  export const FormatCSV = 'csv';
12
+ export const FormatTSV = 'tsv';
12
13
 
13
14
  /**
14
15
  * Resolve a dotpath (`.data[0].number`, `data.records.0.sys_id`) against an
@@ -154,6 +155,8 @@ export class OutputWriter {
154
155
  return this.writeQuiet(data);
155
156
  case FormatCSV:
156
157
  return this.writeCSV(data, opts);
158
+ case FormatTSV:
159
+ return this.writeDelimited(data, '\t', tsvEscape, 'TSV');
157
160
  case FormatStyled:
158
161
  return this.writeStyled(data, opts);
159
162
  default:
@@ -291,12 +294,16 @@ export class OutputWriter {
291
294
  }
292
295
 
293
296
  writeCSV(data, _opts) {
294
- // CSV stdout contains only the table, even on a terminal. Pagination is
297
+ return this.writeDelimited(data, ',', csvEscape, 'CSV');
298
+ }
299
+
300
+ writeDelimited(data, delimiter, escape, label) {
301
+ // Delimited stdout contains only the table, even on a terminal. Pagination is
295
302
  // diagnostic output, not an extra row that spreadsheet readers must skip.
296
303
  if (Array.isArray(data)) {
297
- this.writeCSVTable(data);
304
+ this.writeDelimitedTable(data, delimiter, escape);
298
305
  } else if (data && typeof data === 'object' && Array.isArray(data.records)) {
299
- this.writeCSVTable(data.records);
306
+ this.writeDelimitedTable(data.records, delimiter, escape);
300
307
  const page = data.pagination;
301
308
  if (page?.hasMore === true) {
302
309
  const count = data.records.length;
@@ -309,32 +316,36 @@ export class OutputWriter {
309
316
  && Number.isSafeInteger(page.limit) && page.limit > 0
310
317
  && Number.isSafeInteger(page.offset + page.limit)
311
318
  ? `; next offset ${page.offset + page.limit}` : '';
312
- this.errorWriter.write(`CSV pagination: returned ${count}${total} records${unknown}; more available${nextOffset}.\n`);
319
+ this.errorWriter.write(`${label} pagination: returned ${count}${total} records${unknown}; more available${nextOffset}.\n`);
313
320
  }
314
321
  } else {
315
- this.writeCSVTable([data]);
322
+ this.writeDelimitedTable([data], delimiter, escape);
316
323
  }
317
324
  }
318
325
 
319
326
  writeCSVTable(rows) {
327
+ return this.writeDelimitedTable(rows, ',', csvEscape);
328
+ }
329
+
330
+ writeDelimitedTable(rows, delimiter, escape) {
320
331
  if (!Array.isArray(rows) || rows.length === 0) {
321
332
  this.writer.write('');
322
333
  return;
323
334
  }
324
335
  const columns = Object.keys(rows[0]);
325
- this.writer.write(columns.map(csvEscape).join(',') + '\n');
336
+ this.writer.write(columns.map(escape).join(delimiter) + '\n');
326
337
  for (const row of rows) {
327
338
  const cells = columns.map((col) => {
328
339
  const val = row[col];
329
340
  if (val == null) return '';
330
341
  if (typeof val === 'object') {
331
- if (val.display_value != null) return csvEscape(val.display_value);
332
- if (val.value != null) return csvEscape(val.value);
333
- return csvEscape(JSON.stringify(val));
342
+ if (val.display_value != null) return escape(val.display_value);
343
+ if (val.value != null) return escape(val.value);
344
+ return escape(JSON.stringify(val));
334
345
  }
335
- return csvEscape(val);
346
+ return escape(val);
336
347
  });
337
- this.writer.write(cells.join(',') + '\n');
348
+ this.writer.write(cells.join(delimiter) + '\n');
338
349
  }
339
350
  }
340
351
 
@@ -700,6 +711,11 @@ export function getDisplayValue(val) {
700
711
  return String(val);
701
712
  }
702
713
 
714
+ // Backslash escapes keep each TSV record on one physical line, including headers.
715
+ export function tsvEscape(val) {
716
+ return String(val ?? '').replace(/[\\\t\n\r]/g, ch => ({ '\\': '\\\\', '\t': '\\t', '\n': '\\n', '\r': '\\r' })[ch]);
717
+ }
718
+
703
719
  /** Escape a single CSV field: quote when it contains a delimiter, quote, or newline. */
704
720
  export function csvEscape(val) {
705
721
  if (val == null) return '';