@blamejs/core 0.7.4 → 0.7.18

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.
Files changed (180) hide show
  1. package/CHANGELOG.md +423 -395
  2. package/README.md +150 -149
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +308 -284
  5. package/lib/api-key.js +660 -663
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt.js +311 -311
  16. package/lib/auth/lockout.js +436 -436
  17. package/lib/auth/oauth.js +721 -721
  18. package/lib/auth/passkey.js +181 -181
  19. package/lib/auth/password.js +594 -594
  20. package/lib/backup/bundle.js +217 -217
  21. package/lib/backup/crypto.js +176 -176
  22. package/lib/backup/index.js +515 -515
  23. package/lib/backup/manifest.js +282 -282
  24. package/lib/break-glass.js +1338 -1338
  25. package/lib/bundler.js +441 -441
  26. package/lib/cache-redis.js +256 -256
  27. package/lib/cache.js +1206 -1206
  28. package/lib/canonical-json.js +115 -115
  29. package/lib/chain-writer.js +234 -234
  30. package/lib/cli-helpers.js +206 -206
  31. package/lib/cli.js +2334 -2334
  32. package/lib/cluster-provider-db.js +317 -317
  33. package/lib/cluster-storage.js +226 -226
  34. package/lib/cluster.js +703 -703
  35. package/lib/codepoint-class.js +196 -0
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -286
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -421
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/file-upload.js +213 -10
  56. package/lib/forms.js +422 -422
  57. package/lib/framework-error.js +293 -215
  58. package/lib/framework-schema.js +717 -717
  59. package/lib/gate-contract.js +971 -0
  60. package/lib/guard-all.js +405 -0
  61. package/lib/guard-archive.js +739 -0
  62. package/lib/guard-csv.js +816 -0
  63. package/lib/guard-email.js +744 -0
  64. package/lib/guard-filename.js +724 -0
  65. package/lib/guard-html.js +976 -0
  66. package/lib/guard-json.js +729 -0
  67. package/lib/guard-markdown.js +586 -0
  68. package/lib/guard-svg.js +976 -0
  69. package/lib/guard-xml.js +405 -0
  70. package/lib/guard-yaml.js +529 -0
  71. package/lib/handlers.js +350 -350
  72. package/lib/http-client-cookie-jar.js +508 -508
  73. package/lib/http-client.js +1195 -1195
  74. package/lib/i18n.js +878 -878
  75. package/lib/jobs.js +185 -185
  76. package/lib/log-stream-cloudwatch.js +369 -369
  77. package/lib/log-stream-local.js +146 -146
  78. package/lib/log-stream-otlp-grpc.js +410 -410
  79. package/lib/log-stream-otlp.js +286 -286
  80. package/lib/log-stream-syslog.js +302 -302
  81. package/lib/log-stream-webhook.js +199 -199
  82. package/lib/log-stream.js +330 -330
  83. package/lib/log.js +500 -500
  84. package/lib/mail-bounce.js +528 -528
  85. package/lib/mail-dkim.js +369 -362
  86. package/lib/mail.js +981 -962
  87. package/lib/metrics.js +683 -683
  88. package/lib/middleware/api-encrypt.js +936 -936
  89. package/lib/middleware/attach-user.js +157 -157
  90. package/lib/middleware/body-parser.js +1170 -1091
  91. package/lib/middleware/bot-guard.js +178 -178
  92. package/lib/middleware/compression.js +452 -452
  93. package/lib/middleware/cors.js +314 -314
  94. package/lib/middleware/csp-nonce.js +348 -348
  95. package/lib/middleware/csrf-protect.js +316 -316
  96. package/lib/middleware/db-role-for.js +264 -264
  97. package/lib/middleware/health.js +392 -392
  98. package/lib/middleware/index.js +79 -79
  99. package/lib/middleware/rate-limit.js +358 -358
  100. package/lib/middleware/request-id.js +61 -61
  101. package/lib/middleware/request-log.js +168 -168
  102. package/lib/middleware/require-auth.js +104 -104
  103. package/lib/middleware/security-headers.js +116 -116
  104. package/lib/middleware/sse.js +166 -166
  105. package/lib/migrations.js +383 -383
  106. package/lib/mtls-ca.js +518 -518
  107. package/lib/mtls-engine-default.js +481 -481
  108. package/lib/network-dns.js +632 -632
  109. package/lib/network-heartbeat.js +290 -290
  110. package/lib/network-nts.js +574 -574
  111. package/lib/network-proxy.js +265 -265
  112. package/lib/network-tls.js +328 -328
  113. package/lib/network.js +233 -233
  114. package/lib/notify.js +612 -612
  115. package/lib/ntp-check.js +229 -229
  116. package/lib/numeric-bounds.js +111 -91
  117. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  118. package/lib/object-store/azure-blob.js +488 -488
  119. package/lib/object-store/gcs-bucket-ops.js +351 -351
  120. package/lib/object-store/gcs.js +519 -519
  121. package/lib/object-store/http-put.js +153 -153
  122. package/lib/object-store/index.js +197 -197
  123. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  124. package/lib/object-store/sigv4.js +903 -903
  125. package/lib/observability.js +151 -151
  126. package/lib/otel-export.js +269 -269
  127. package/lib/pagination.js +464 -464
  128. package/lib/parsers/index.js +80 -80
  129. package/lib/parsers/safe-env.js +642 -642
  130. package/lib/parsers/safe-ini.js +292 -292
  131. package/lib/parsers/safe-toml.js +784 -784
  132. package/lib/parsers/safe-xml.js +390 -390
  133. package/lib/parsers/safe-yaml.js +1015 -1015
  134. package/lib/permissions.js +708 -708
  135. package/lib/pqc-agent.js +87 -87
  136. package/lib/pqc-gate.js +279 -279
  137. package/lib/protobuf-encoder.js +190 -190
  138. package/lib/protocol-dispatcher.js +161 -161
  139. package/lib/pubsub-redis.js +167 -167
  140. package/lib/pubsub.js +429 -429
  141. package/lib/queue-local.js +476 -476
  142. package/lib/queue-redis.js +745 -745
  143. package/lib/queue-sqs.js +319 -319
  144. package/lib/queue.js +695 -695
  145. package/lib/redis-client.js +519 -519
  146. package/lib/request-helpers.js +340 -340
  147. package/lib/restore-bundle.js +237 -237
  148. package/lib/restore-rollback.js +259 -259
  149. package/lib/restore.js +409 -409
  150. package/lib/retry.js +376 -376
  151. package/lib/router.js +748 -748
  152. package/lib/safe-async.js +735 -735
  153. package/lib/safe-buffer.js +237 -237
  154. package/lib/safe-json.js +541 -541
  155. package/lib/safe-schema.js +1266 -1266
  156. package/lib/safe-url.js +159 -159
  157. package/lib/scheduler.js +706 -706
  158. package/lib/security-assert.js +373 -373
  159. package/lib/seeders.js +618 -618
  160. package/lib/session.js +478 -478
  161. package/lib/slug.js +269 -269
  162. package/lib/ssrf-guard.js +401 -401
  163. package/lib/static.js +184 -4
  164. package/lib/storage.js +471 -471
  165. package/lib/subject.js +281 -281
  166. package/lib/template.js +791 -791
  167. package/lib/testing.js +798 -798
  168. package/lib/time.js +310 -310
  169. package/lib/totp.js +302 -302
  170. package/lib/tracing.js +494 -494
  171. package/lib/uuid.js +132 -132
  172. package/lib/validate-opts.js +340 -319
  173. package/lib/vault/index.js +308 -308
  174. package/lib/vault/rotate.js +784 -784
  175. package/lib/vault/wrap.js +296 -296
  176. package/lib/vendor/noble-ciphers.cjs +9 -9
  177. package/lib/webhook.js +595 -595
  178. package/lib/websocket.js +1048 -1048
  179. package/package.json +77 -77
  180. package/sbom.cyclonedx.json +7 -7
package/lib/csv.js CHANGED
@@ -1,286 +1,275 @@
1
- "use strict";
2
- /**
3
- * csv — RFC 4180 parser + serializer with operator-friendly defaults.
4
- *
5
- * var rows = b.csv.parse(text);
6
- * // header row by default — returns array of objects keyed by header
7
- * // [ { name: "alice", age: "30" }, ... ]
8
- *
9
- * var arrays = b.csv.parse(text, { header: false });
10
- * // returns array of arrays
11
- *
12
- * var out = b.csv.stringify(rows);
13
- * // RFC 4180 + Excel-formula-injection prevention by default
14
- *
15
- * Defaults:
16
- * parse:
17
- * header: true first row is column names
18
- * delimiter: "," single byte; "\t" / ";" supported
19
- * quote: '"'
20
- * trim: false cell whitespace preserved
21
- * maxBytes: 16 MiB
22
- * maxRows: 1,000,000
23
- * maxFieldBytes: 1 MiB
24
- * onBadRow: "throw" "skip" tolerates short/long rows
25
- *
26
- * stringify:
27
- * header: true (or array of explicit columns)
28
- * delimiter: ","
29
- * quote: '"'
30
- * eol: "\r\n" RFC 4180; "\n" via opt
31
- * alwaysQuote: false only quote when needed
32
- * preventFormulaInjection: true prefix '=' / '+' / '-' / '@' / TAB / CR
33
- * cells with "'" so Excel doesn't
34
- * execute them when the CSV is opened
35
- * formulaPrefixChars: ["=","+","-","@","\t","\r"]
36
- *
37
- * SECURITY: stringify defends against CSV-injection (Excel/Sheets execute
38
- * cells starting with "=" / "+" / "-" / "@" / TAB / CR as formulas).
39
- * Operator-controlled cells stay safe; user-supplied cells get the leading
40
- * single-quote so the formula engine sees a literal string.
41
- *
42
- * Throws CsvError (FrameworkError, permanent) on shape violations.
43
- */
44
- var C = require("./constants");
45
- var numericBounds = require("./numeric-bounds");
46
- var { defineClass } = require("./framework-error");
47
-
48
- var CsvError = defineClass("CsvError", { alwaysPermanent: true });
49
-
50
- var DEFAULTS_PARSE = {
51
- header: true,
52
- delimiter: ",",
53
- quote: "\"",
54
- trim: false,
55
- maxBytes: C.BYTES.mib(16),
56
- maxRows: 1_000_000,
57
- maxFieldBytes: C.BYTES.mib(1),
58
- onBadRow: "throw",
59
- };
60
-
61
- var DEFAULTS_STRINGIFY = {
62
- header: true,
63
- delimiter: ",",
64
- quote: "\"",
65
- eol: "\r\n",
66
- alwaysQuote: false,
67
- preventFormulaInjection: true,
68
- formulaPrefixChars: ["=", "+", "-", "@", "\t", "\r"],
69
- columns: null,
70
- };
71
-
72
- function _validateDelim(name, value) {
73
- if (typeof value !== "string" || value.length !== 1) {
74
- throw new CsvError("csv/bad-delimiter",
75
- name + " must be a single character, got " + JSON.stringify(value));
76
- }
77
- if (value === "\r" || value === "\n") {
78
- throw new CsvError("csv/bad-delimiter",
79
- name + " cannot be CR or LF");
80
- }
81
- }
82
-
83
- // ---- parse ----
84
-
85
- function parse(input, opts) {
86
- opts = Object.assign({}, DEFAULTS_PARSE, opts || {});
87
- // maxBytes / maxRows / maxFieldBytes via shared lib/numeric-bounds —
88
- // Infinity / NaN bypass the corresponding caps and let a hostile
89
- // multi-megabyte CSV (or a single hostile row / single hostile field)
90
- // through unbounded.
91
- numericBounds.requirePositiveFiniteIntIfPresent(opts.maxBytes,
92
- "csv.parse: maxBytes", CsvError, "csv/bad-opt");
93
- numericBounds.requirePositiveFiniteIntIfPresent(opts.maxRows,
94
- "csv.parse: maxRows", CsvError, "csv/bad-opt");
95
- numericBounds.requirePositiveFiniteIntIfPresent(opts.maxFieldBytes,
96
- "csv.parse: maxFieldBytes", CsvError, "csv/bad-opt");
97
-
98
- var s;
99
- if (typeof input === "string") s = input;
100
- else if (Buffer.isBuffer(input)) s = input.toString("utf8");
101
- else if (input instanceof Uint8Array) s = Buffer.from(input).toString("utf8");
102
- else {
103
- throw new CsvError("csv/bad-input",
104
- "parse: input must be string, Buffer, or Uint8Array, got " + typeof input);
105
- }
106
- if (s.charCodeAt(0) === 0xFEFF) s = s.slice(1);
107
- if (Buffer.byteLength(s, "utf8") > opts.maxBytes) {
108
- throw new CsvError("csv/too-large",
109
- "parse: input exceeds maxBytes (" + opts.maxBytes + ")");
110
- }
111
-
112
- _validateDelim("delimiter", opts.delimiter);
113
- _validateDelim("quote", opts.quote);
114
- if (opts.delimiter === opts.quote) {
115
- throw new CsvError("csv/bad-delimiter",
116
- "delimiter and quote must differ");
117
- }
118
- if (opts.onBadRow !== "throw" && opts.onBadRow !== "skip") {
119
- throw new CsvError("csv/bad-opt",
120
- "onBadRow must be 'throw' or 'skip'");
121
- }
122
-
123
- var len = s.length;
124
- var pos = 0;
125
- var rows = [];
126
- var row = [];
127
- var field = "";
128
- var inQuote = false;
129
-
130
- function pushField() {
131
- if (Buffer.byteLength(field, "utf8") > opts.maxFieldBytes) {
132
- throw new CsvError("csv/field-too-large",
133
- "field exceeds maxFieldBytes at row " + (rows.length + 1));
134
- }
135
- row.push(opts.trim ? field.trim() : field);
136
- field = "";
137
- }
138
- function pushRow() {
139
- pushField();
140
- rows.push(row);
141
- if (rows.length > opts.maxRows) {
142
- throw new CsvError("csv/too-many-rows",
143
- "row count exceeds maxRows (" + opts.maxRows + ")");
144
- }
145
- row = [];
146
- }
147
-
148
- while (pos < len) {
149
- var ch = s.charAt(pos);
150
- if (inQuote) {
151
- if (ch === opts.quote) {
152
- if (pos + 1 < len && s.charAt(pos + 1) === opts.quote) {
153
- field += opts.quote;
154
- pos += 2;
155
- continue;
156
- }
157
- inQuote = false;
158
- pos += 1;
159
- continue;
160
- }
161
- field += ch;
162
- pos += 1;
163
- } else {
164
- if (ch === opts.delimiter) {
165
- pushField();
166
- pos += 1;
167
- } else if (ch === "\r") {
168
- pushRow();
169
- pos += 1;
170
- if (pos < len && s.charAt(pos) === "\n") pos += 1;
171
- } else if (ch === "\n") {
172
- pushRow();
173
- pos += 1;
174
- } else if (ch === opts.quote && field === "") {
175
- inQuote = true;
176
- pos += 1;
177
- } else {
178
- field += ch;
179
- pos += 1;
180
- }
181
- }
182
- }
183
- if (inQuote) {
184
- throw new CsvError("csv/unterminated-quote",
185
- "unterminated quoted field");
186
- }
187
- if (field.length > 0 || row.length > 0) pushRow();
188
-
189
- if (!opts.header) return rows;
190
- if (rows.length === 0) return [];
191
-
192
- var header = rows[0];
193
- var out = [];
194
- for (var r = 1; r < rows.length; r++) {
195
- var rec = rows[r];
196
- if (rec.length !== header.length) {
197
- if (opts.onBadRow === "skip") continue;
198
- throw new CsvError("csv/row-length-mismatch",
199
- "row " + r + " has " + rec.length + " fields, header has " + header.length);
200
- }
201
- var obj = {};
202
- for (var i = 0; i < header.length; i++) obj[header[i]] = rec[i];
203
- out.push(obj);
204
- }
205
- return out;
206
- }
207
-
208
- // ---- stringify ----
209
-
210
- function stringify(rows, opts) {
211
- opts = Object.assign({}, DEFAULTS_STRINGIFY, opts || {});
212
- if (!Array.isArray(rows)) {
213
- throw new CsvError("csv/bad-input",
214
- "stringify: rows must be an array, got " + typeof rows);
215
- }
216
- _validateDelim("delimiter", opts.delimiter);
217
- _validateDelim("quote", opts.quote);
218
- if (opts.delimiter === opts.quote) {
219
- throw new CsvError("csv/bad-delimiter",
220
- "delimiter and quote must differ");
221
- }
222
- if (opts.eol !== "\r\n" && opts.eol !== "\n") {
223
- throw new CsvError("csv/bad-opt",
224
- "eol must be '\\r\\n' or '\\n'");
225
- }
226
- if (rows.length === 0) return "";
227
-
228
- var first = rows[0];
229
- var asObjects;
230
- var header;
231
- if (Array.isArray(first)) {
232
- asObjects = false;
233
- header = Array.isArray(opts.columns) ? opts.columns : null;
234
- } else if (first !== null && typeof first === "object") {
235
- asObjects = true;
236
- header = Array.isArray(opts.columns) ? opts.columns : Object.keys(first);
237
- } else {
238
- throw new CsvError("csv/bad-input",
239
- "stringify: rows must be arrays or plain objects");
240
- }
241
-
242
- var prefixSet = Object.create(null);
243
- for (var pi = 0; pi < opts.formulaPrefixChars.length; pi++) {
244
- prefixSet[opts.formulaPrefixChars[pi]] = true;
245
- }
246
-
247
- function escapeCell(value) {
248
- var str = value == null ? "" : String(value);
249
- if (opts.preventFormulaInjection && str.length > 0 && prefixSet[str.charAt(0)]) {
250
- str = "'" + str;
251
- }
252
- var needsQuote = opts.alwaysQuote ||
253
- str.indexOf(opts.delimiter) !== -1 ||
254
- str.indexOf(opts.quote) !== -1 ||
255
- str.indexOf("\n") !== -1 ||
256
- str.indexOf("\r") !== -1;
257
- if (needsQuote) {
258
- str = opts.quote + str.split(opts.quote).join(opts.quote + opts.quote) + opts.quote;
259
- }
260
- return str;
261
- }
262
-
263
- var out = [];
264
- if (opts.header && header) {
265
- out.push(header.map(escapeCell).join(opts.delimiter));
266
- }
267
- for (var i = 0; i < rows.length; i++) {
268
- var rec = rows[i];
269
- var cells;
270
- if (asObjects) {
271
- cells = header.map(function (k) { return escapeCell(rec[k]); });
272
- } else {
273
- cells = rec.map(escapeCell);
274
- }
275
- out.push(cells.join(opts.delimiter));
276
- }
277
- return out.join(opts.eol);
278
- }
279
-
280
- module.exports = {
281
- parse: parse,
282
- stringify: stringify,
283
- CsvError: CsvError,
284
- DEFAULTS_PARSE: DEFAULTS_PARSE,
285
- DEFAULTS_STRINGIFY: DEFAULTS_STRINGIFY,
286
- };
1
+ "use strict";
2
+ /**
3
+ * csv — RFC 4180 parser + serializer with operator-friendly defaults.
4
+ *
5
+ * var rows = b.csv.parse(text);
6
+ * // header row by default — returns array of objects keyed by header
7
+ * // [ { name: "alice", age: "30" }, ... ]
8
+ *
9
+ * var arrays = b.csv.parse(text, { header: false });
10
+ * // returns array of arrays
11
+ *
12
+ * var out = b.csv.stringify(rows);
13
+ * // RFC 4180 quoting + anti-DoS bounds. NO threat-catalog handling.
14
+ *
15
+ * Defaults:
16
+ * parse:
17
+ * header: true first row is column names
18
+ * delimiter: "," single byte; "\t" / ";" supported
19
+ * quote: '"'
20
+ * trim: false cell whitespace preserved
21
+ * maxBytes: 16 MiB
22
+ * maxRows: 1,000,000
23
+ * maxFieldBytes: 1 MiB
24
+ * onBadRow: "throw" "skip" tolerates short/long rows
25
+ *
26
+ * stringify:
27
+ * header: true (or array of explicit columns)
28
+ * delimiter: ","
29
+ * quote: '"'
30
+ * eol: "\r\n" RFC 4180; "\n" via opt
31
+ * alwaysQuote: false only quote when needed
32
+ *
33
+ * SCOPE: this module is for trusted-source-only emission. It performs RFC
34
+ * 4180 quote/delimiter escaping but does NOT defend against the broader
35
+ * CSV-injection threat catalog (Excel/Sheets formula triggers, Unicode
36
+ * bidi overrides, dangerous-function denylist, homoglyphs, control-byte
37
+ * injection, BOM mid-stream, dialect ambiguity, CSV-bombs). Any path
38
+ * that emits or accepts user-supplied cells MUST route through
39
+ * `b.guardCsv` its `serialize` / `validate` / `sanitize` / `gate`
40
+ * surface handles every documented threat with a single profile choice
41
+ * (strict / balanced / permissive / email-attachment) or compliance
42
+ * posture (hipaa / pci-dss / gdpr / soc2-cc7).
43
+ *
44
+ * Throws CsvError (FrameworkError, permanent) on shape violations.
45
+ */
46
+ var C = require("./constants");
47
+ var numericBounds = require("./numeric-bounds");
48
+ var { defineClass } = require("./framework-error");
49
+
50
+ var CsvError = defineClass("CsvError", { alwaysPermanent: true });
51
+
52
+ var DEFAULTS_PARSE = {
53
+ header: true,
54
+ delimiter: ",",
55
+ quote: "\"",
56
+ trim: false,
57
+ maxBytes: C.BYTES.mib(16),
58
+ maxRows: 1_000_000,
59
+ maxFieldBytes: C.BYTES.mib(1),
60
+ onBadRow: "throw",
61
+ };
62
+
63
+ var DEFAULTS_STRINGIFY = {
64
+ header: true,
65
+ delimiter: ",",
66
+ quote: "\"",
67
+ eol: "\r\n",
68
+ alwaysQuote: false,
69
+ columns: null,
70
+ };
71
+
72
+ function _validateDelim(name, value) {
73
+ if (typeof value !== "string" || value.length !== 1) {
74
+ throw new CsvError("csv/bad-delimiter",
75
+ name + " must be a single character, got " + JSON.stringify(value));
76
+ }
77
+ if (value === "\r" || value === "\n") {
78
+ throw new CsvError("csv/bad-delimiter",
79
+ name + " cannot be CR or LF");
80
+ }
81
+ }
82
+
83
+ // ---- parse ----
84
+
85
+ function parse(input, opts) {
86
+ opts = Object.assign({}, DEFAULTS_PARSE, opts || {});
87
+ // maxBytes / maxRows / maxFieldBytes via shared lib/numeric-bounds —
88
+ // Infinity / NaN bypass the corresponding caps and let a hostile
89
+ // multi-megabyte CSV (or a single hostile row / single hostile field)
90
+ // through unbounded.
91
+ numericBounds.requireAllPositiveFiniteIntIfPresent(opts,
92
+ ["maxBytes", "maxRows", "maxFieldBytes"],
93
+ "csv.parse", CsvError, "csv/bad-opt");
94
+
95
+ var s;
96
+ if (typeof input === "string") s = input;
97
+ else if (Buffer.isBuffer(input)) s = input.toString("utf8");
98
+ else if (input instanceof Uint8Array) s = Buffer.from(input).toString("utf8");
99
+ else {
100
+ throw new CsvError("csv/bad-input",
101
+ "parse: input must be string, Buffer, or Uint8Array, got " + typeof input);
102
+ }
103
+ if (s.charCodeAt(0) === 0xFEFF) s = s.slice(1);
104
+ if (Buffer.byteLength(s, "utf8") > opts.maxBytes) {
105
+ throw new CsvError("csv/too-large",
106
+ "parse: input exceeds maxBytes (" + opts.maxBytes + ")");
107
+ }
108
+
109
+ _validateDelim("delimiter", opts.delimiter);
110
+ _validateDelim("quote", opts.quote);
111
+ if (opts.delimiter === opts.quote) {
112
+ throw new CsvError("csv/bad-delimiter",
113
+ "delimiter and quote must differ");
114
+ }
115
+ if (opts.onBadRow !== "throw" && opts.onBadRow !== "skip") {
116
+ throw new CsvError("csv/bad-opt",
117
+ "onBadRow must be 'throw' or 'skip'");
118
+ }
119
+
120
+ var len = s.length;
121
+ var pos = 0;
122
+ var rows = [];
123
+ var row = [];
124
+ var field = "";
125
+ var inQuote = false;
126
+
127
+ function pushField() {
128
+ if (Buffer.byteLength(field, "utf8") > opts.maxFieldBytes) {
129
+ throw new CsvError("csv/field-too-large",
130
+ "field exceeds maxFieldBytes at row " + (rows.length + 1));
131
+ }
132
+ row.push(opts.trim ? field.trim() : field);
133
+ field = "";
134
+ }
135
+ function pushRow() {
136
+ pushField();
137
+ rows.push(row);
138
+ if (rows.length > opts.maxRows) {
139
+ throw new CsvError("csv/too-many-rows",
140
+ "row count exceeds maxRows (" + opts.maxRows + ")");
141
+ }
142
+ row = [];
143
+ }
144
+
145
+ while (pos < len) {
146
+ var ch = s.charAt(pos);
147
+ if (inQuote) {
148
+ if (ch === opts.quote) {
149
+ if (pos + 1 < len && s.charAt(pos + 1) === opts.quote) {
150
+ field += opts.quote;
151
+ pos += 2;
152
+ continue;
153
+ }
154
+ inQuote = false;
155
+ pos += 1;
156
+ continue;
157
+ }
158
+ field += ch;
159
+ pos += 1;
160
+ } else {
161
+ if (ch === opts.delimiter) {
162
+ pushField();
163
+ pos += 1;
164
+ } else if (ch === "\r") {
165
+ pushRow();
166
+ pos += 1;
167
+ if (pos < len && s.charAt(pos) === "\n") pos += 1;
168
+ } else if (ch === "\n") {
169
+ pushRow();
170
+ pos += 1;
171
+ } else if (ch === opts.quote && field === "") {
172
+ inQuote = true;
173
+ pos += 1;
174
+ } else {
175
+ field += ch;
176
+ pos += 1;
177
+ }
178
+ }
179
+ }
180
+ if (inQuote) {
181
+ throw new CsvError("csv/unterminated-quote",
182
+ "unterminated quoted field");
183
+ }
184
+ if (field.length > 0 || row.length > 0) pushRow();
185
+
186
+ if (!opts.header) return rows;
187
+ if (rows.length === 0) return [];
188
+
189
+ var header = rows[0];
190
+ var out = [];
191
+ for (var r = 1; r < rows.length; r++) {
192
+ var rec = rows[r];
193
+ if (rec.length !== header.length) {
194
+ if (opts.onBadRow === "skip") continue;
195
+ throw new CsvError("csv/row-length-mismatch",
196
+ "row " + r + " has " + rec.length + " fields, header has " + header.length);
197
+ }
198
+ var obj = {};
199
+ for (var i = 0; i < header.length; i++) obj[header[i]] = rec[i];
200
+ out.push(obj);
201
+ }
202
+ return out;
203
+ }
204
+
205
+ // ---- stringify ----
206
+
207
+ function stringify(rows, opts) {
208
+ opts = Object.assign({}, DEFAULTS_STRINGIFY, opts || {});
209
+ if (!Array.isArray(rows)) {
210
+ throw new CsvError("csv/bad-input",
211
+ "stringify: rows must be an array, got " + typeof rows);
212
+ }
213
+ _validateDelim("delimiter", opts.delimiter);
214
+ _validateDelim("quote", opts.quote);
215
+ if (opts.delimiter === opts.quote) {
216
+ throw new CsvError("csv/bad-delimiter",
217
+ "delimiter and quote must differ");
218
+ }
219
+ if (opts.eol !== "\r\n" && opts.eol !== "\n") {
220
+ throw new CsvError("csv/bad-opt",
221
+ "eol must be '\\r\\n' or '\\n'");
222
+ }
223
+ if (rows.length === 0) return "";
224
+
225
+ var first = rows[0];
226
+ var asObjects;
227
+ var header;
228
+ if (Array.isArray(first)) {
229
+ asObjects = false;
230
+ header = Array.isArray(opts.columns) ? opts.columns : null;
231
+ } else if (first !== null && typeof first === "object") {
232
+ asObjects = true;
233
+ header = Array.isArray(opts.columns) ? opts.columns : Object.keys(first);
234
+ } else {
235
+ throw new CsvError("csv/bad-input",
236
+ "stringify: rows must be arrays or plain objects");
237
+ }
238
+
239
+ function escapeCell(value) {
240
+ var str = value == null ? "" : String(value);
241
+ var needsQuote = opts.alwaysQuote ||
242
+ str.indexOf(opts.delimiter) !== -1 ||
243
+ str.indexOf(opts.quote) !== -1 ||
244
+ str.indexOf("\n") !== -1 ||
245
+ str.indexOf("\r") !== -1;
246
+ if (needsQuote) {
247
+ str = opts.quote + str.split(opts.quote).join(opts.quote + opts.quote) + opts.quote;
248
+ }
249
+ return str;
250
+ }
251
+
252
+ var out = [];
253
+ if (opts.header && header) {
254
+ out.push(header.map(escapeCell).join(opts.delimiter));
255
+ }
256
+ for (var i = 0; i < rows.length; i++) {
257
+ var rec = rows[i];
258
+ var cells;
259
+ if (asObjects) {
260
+ cells = header.map(function (k) { return escapeCell(rec[k]); });
261
+ } else {
262
+ cells = rec.map(escapeCell);
263
+ }
264
+ out.push(cells.join(opts.delimiter));
265
+ }
266
+ return out.join(opts.eol);
267
+ }
268
+
269
+ module.exports = {
270
+ parse: parse,
271
+ stringify: stringify,
272
+ CsvError: CsvError,
273
+ DEFAULTS_PARSE: DEFAULTS_PARSE,
274
+ DEFAULTS_STRINGIFY: DEFAULTS_STRINGIFY,
275
+ };