sim 2.2.31-preview.310.1 → 2.2.32-preview.312.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/dist/runtime.js CHANGED
@@ -4029,6 +4029,40 @@ class EmbeddedOutput {
4029
4029
  }
4030
4030
  }
4031
4031
 
4032
+ // ../utils/src/retry.ts
4033
+ var DEFAULT_BACKOFF_BASE_MS = 500;
4034
+ var DEFAULT_BACKOFF_MAX_MS = 30000;
4035
+ function backoffWithJitter(attempt, retryAfterMs, options = {}) {
4036
+ const baseMs = options.baseMs ?? DEFAULT_BACKOFF_BASE_MS;
4037
+ const maxMs = options.maxMs ?? DEFAULT_BACKOFF_MAX_MS;
4038
+ if (retryAfterMs !== null) {
4039
+ return Math.min(Math.max(retryAfterMs, baseMs), maxMs);
4040
+ }
4041
+ const exponential = Math.min(baseMs * 2 ** (attempt - 1), maxMs);
4042
+ const jitter = crypto.getRandomValues(new Uint32Array(1))[0] / 4294967296;
4043
+ return exponential * (0.8 + jitter * 0.4);
4044
+ }
4045
+ var RETRY_AFTER_MAX_MS = 30000;
4046
+ function parseRetryAfter(header, maxMs = RETRY_AFTER_MAX_MS) {
4047
+ if (!header)
4048
+ return null;
4049
+ const trimmed = header.trim();
4050
+ if (trimmed.length === 0)
4051
+ return null;
4052
+ const seconds = Number(trimmed);
4053
+ if (Number.isFinite(seconds) && seconds >= 0) {
4054
+ return Math.min(Math.floor(seconds * 1000), maxMs);
4055
+ }
4056
+ const dateMs = Date.parse(trimmed);
4057
+ if (!Number.isNaN(dateMs)) {
4058
+ const delta = dateMs - Date.now();
4059
+ if (delta <= 0)
4060
+ return 0;
4061
+ return Math.min(delta, maxMs);
4062
+ }
4063
+ return null;
4064
+ }
4065
+
4032
4066
  // src/output/io.ts
4033
4067
  import { format } from "node:util";
4034
4068
  function printLine(...args) {
@@ -4931,6 +4965,7 @@ class SimApiError extends Error {
4931
4965
  details;
4932
4966
  exitCode;
4933
4967
  requestId;
4968
+ retryAfterMs = null;
4934
4969
  constructor(message, status, code = null, details, exitCode = 1, requestId = null) {
4935
4970
  super(message);
4936
4971
  this.status = status;
@@ -5015,7 +5050,9 @@ async function readResponseText(response) {
5015
5050
  try {
5016
5051
  return await response.text();
5017
5052
  } catch (error) {
5018
- throw new SimApiError(`Unable to read the response: ${transportErrorMessage(error)}`, response.status, "RESPONSE_READ_FAILED", undefined, 1, responseRequestId(response));
5053
+ const failure = new SimApiError(`Unable to read the response: ${transportErrorMessage(error)}`, response.status, "RESPONSE_READ_FAILED", undefined, 1, responseRequestId(response));
5054
+ failure.retryAfterMs = parseRetryAfter(response.headers.get("retry-after"), 300000);
5055
+ throw failure;
5019
5056
  }
5020
5057
  }
5021
5058
  function refusalCode(error) {
@@ -5262,6 +5299,7 @@ class SimClient {
5262
5299
  if (!response.ok) {
5263
5300
  const raw = await readResponseText(response);
5264
5301
  const error = toApiError(url, response, raw);
5302
+ error.retryAfterMs = parseRetryAfter(response.headers.get("retry-after"), 300000);
5265
5303
  if (response.status === 401) {
5266
5304
  error.message = `${error.message} — run: sim login --profile ${this.profile.authProfile}`;
5267
5305
  }
@@ -10987,6 +11025,40 @@ var V2_OPERATIONS = {
10987
11025
  }
10988
11026
  }
10989
11027
  },
11028
+ createSearchSource: {
11029
+ method: "POST",
11030
+ path: "/api/v2/organizations/[organizationId]/search/sources",
11031
+ pathParams: ["organizationId"],
11032
+ pathParamDocs: { organizationId: "Organization identifier." },
11033
+ responseMode: "json",
11034
+ summary: "Create Search source",
11035
+ body: {
11036
+ connectorType: { kind: "string", required: true, describe: "Registered connector type." },
11037
+ credentialId: {
11038
+ kind: "string",
11039
+ describe: "OAuth credential identifier for connector types whose `auth.mode` is `oauth` (see connector types), or a saved credential for an `apiKey` connector type that declares `auth.savedCredential` (such as Amazon S3 with a saved AWS credential); otherwise omit it for `apiKey` connectors."
11040
+ },
11041
+ apiKey: {
11042
+ kind: "string",
11043
+ describe: "Write-only API key for connector types whose `auth.mode` is `apiKey` (see connector types), or a personal access token for an OAuth connector that also accepts one, such as GitHub. Send it instead of `credentialId`. Pass a raw key, or a secret reference written as the whole value `{{SECRET_NAME}}`, which the server resolves; `$SECRET_NAME` is not a reference."
11044
+ },
11045
+ sourceConfig: {
11046
+ kind: "object",
11047
+ required: true,
11048
+ describe: "Connector-specific source selection and filtering configuration."
11049
+ },
11050
+ accessMode: {
11051
+ kind: "enum",
11052
+ values: ["admin", "members"],
11053
+ default: "admin",
11054
+ describe: "Source-managed permissions (admin), or individually connected member accounts (members)."
11055
+ },
11056
+ permissionConfig: {
11057
+ kind: "object",
11058
+ describe: "Provider-specific permissions for initial setup. Large CSV snapshots use permission imports after creation."
11059
+ }
11060
+ }
11061
+ },
10990
11062
  createServiceAccountCredential: {
10991
11063
  method: "POST",
10992
11064
  path: "/api/v2/credentials",
@@ -11625,6 +11697,17 @@ var V2_OPERATIONS = {
11625
11697
  workspaceId: { kind: "string", required: true, describe: "Workspace that owns the sandbox." }
11626
11698
  }
11627
11699
  },
11700
+ deleteSearchSource: {
11701
+ method: "DELETE",
11702
+ path: "/api/v2/organizations/[organizationId]/search/sources/[sourceId]",
11703
+ pathParams: ["organizationId", "sourceId"],
11704
+ pathParamDocs: {
11705
+ organizationId: "Organization identifier.",
11706
+ sourceId: "Search source identifier, also used by permission uploads."
11707
+ },
11708
+ responseMode: "json",
11709
+ summary: "Delete Search source"
11710
+ },
11628
11711
  deleteSecret: {
11629
11712
  method: "DELETE",
11630
11713
  path: "/api/v2/secrets/[name]",
@@ -12849,6 +12932,17 @@ var V2_OPERATIONS = {
12849
12932
  workspaceId: { kind: "string", required: true, describe: "Workspace that owns the sandbox." }
12850
12933
  }
12851
12934
  },
12935
+ getSearchSource: {
12936
+ method: "GET",
12937
+ path: "/api/v2/organizations/[organizationId]/search/sources/[sourceId]",
12938
+ pathParams: ["organizationId", "sourceId"],
12939
+ pathParamDocs: {
12940
+ organizationId: "Organization identifier.",
12941
+ sourceId: "Search source identifier, also used by permission uploads."
12942
+ },
12943
+ responseMode: "json",
12944
+ summary: "Get Search source"
12945
+ },
12852
12946
  getSearchSourcePermissions: {
12853
12947
  method: "GET",
12854
12948
  path: "/api/v2/organizations/[organizationId]/search/sources/[sourceId]/permissions",
@@ -15098,6 +15192,38 @@ var V2_OPERATIONS = {
15098
15192
  }
15099
15193
  }
15100
15194
  },
15195
+ listSearchSources: {
15196
+ method: "GET",
15197
+ path: "/api/v2/organizations/[organizationId]/search/sources",
15198
+ pathParams: ["organizationId"],
15199
+ pathParamDocs: { organizationId: "Organization identifier." },
15200
+ responseMode: "json",
15201
+ summary: "List Search sources",
15202
+ query: {
15203
+ sortBy: {
15204
+ kind: "enum",
15205
+ values: ["connectorType", "createdAt", "updatedAt"],
15206
+ default: "createdAt",
15207
+ describe: "Field used to sort the result."
15208
+ },
15209
+ sortOrder: {
15210
+ kind: "enum",
15211
+ values: ["asc", "desc"],
15212
+ default: "desc",
15213
+ describe: "Sort direction."
15214
+ },
15215
+ limit: {
15216
+ kind: "integer",
15217
+ default: 50,
15218
+ maximum: 100,
15219
+ describe: "Maximum connectors to return per page. Must be a whole number from 1 to 100. Defaults to 50."
15220
+ },
15221
+ cursor: {
15222
+ kind: "string",
15223
+ describe: "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor."
15224
+ }
15225
+ }
15226
+ },
15101
15227
  listSecrets: {
15102
15228
  method: "GET",
15103
15229
  path: "/api/v2/secrets",
@@ -16080,6 +16206,23 @@ var V2_OPERATIONS = {
16080
16206
  }
16081
16207
  }
16082
16208
  },
16209
+ prepareSearchSources: {
16210
+ method: "POST",
16211
+ path: "/api/v2/organizations/[organizationId]/search/sources/prepare",
16212
+ pathParams: ["organizationId"],
16213
+ pathParamDocs: { organizationId: "Organization identifier." },
16214
+ responseMode: "json",
16215
+ summary: "Prepare Search sources",
16216
+ body: {
16217
+ connectorType: { kind: "string", required: true, describe: "Registered connector type." },
16218
+ accessMode: {
16219
+ kind: "enum",
16220
+ values: ["admin", "members"],
16221
+ default: "admin",
16222
+ describe: "Source-managed permissions (admin), or individually connected member accounts (members)."
16223
+ }
16224
+ }
16225
+ },
16083
16226
  previewOrganizationAccessRequest: {
16084
16227
  method: "GET",
16085
16228
  path: "/api/v2/organizations/[organizationId]/access-requests/[requestId]/preview",
@@ -18218,6 +18361,36 @@ var V2_OPERATIONS = {
18218
18361
  }
18219
18362
  }
18220
18363
  },
18364
+ updateSearchSource: {
18365
+ method: "PATCH",
18366
+ path: "/api/v2/organizations/[organizationId]/search/sources/[sourceId]",
18367
+ pathParams: ["organizationId", "sourceId"],
18368
+ pathParamDocs: {
18369
+ organizationId: "Organization identifier.",
18370
+ sourceId: "Search source identifier, also used by permission uploads."
18371
+ },
18372
+ responseMode: "json",
18373
+ summary: "Update Search source",
18374
+ body: {
18375
+ apiKey: {
18376
+ kind: "string",
18377
+ describe: "Replacement token for providers supporting credential updates (currently GitLab). For GitLab, supply permissionConfig with the current expectedRevision; omitted CSVs retain grants. Omit to keep the saved token."
18378
+ },
18379
+ sourceConfig: {
18380
+ kind: "object",
18381
+ describe: "Complete replacement source configuration. Read the existing configuration before editing it."
18382
+ },
18383
+ permissionConfig: {
18384
+ kind: "object",
18385
+ describe: "Provider-specific permission update, using the current expectedRevision. Omit to retain permissions."
18386
+ },
18387
+ status: {
18388
+ kind: "enum",
18389
+ values: ["active", "paused"],
18390
+ describe: "Pause or resume this source without changing its ID or stored permissions."
18391
+ }
18392
+ }
18393
+ },
18221
18394
  updateSkill: {
18222
18395
  method: "PATCH",
18223
18396
  path: "/api/v2/skills/[skillId]",
@@ -20563,6 +20736,37 @@ var CLI_CONTRACT = {
20563
20736
  columns: [{ header: "id" }, { header: "name" }, { header: "role" }]
20564
20737
  },
20565
20738
  getOrganization: { command: "organizations get" },
20739
+ prepareSearchSources: {
20740
+ command: "organizations search sources prepare",
20741
+ pathFlags: ORGANIZATION_FLAG
20742
+ },
20743
+ listSearchSources: {
20744
+ command: "organizations search sources list",
20745
+ pathFlags: ORGANIZATION_FLAG,
20746
+ columns: [
20747
+ { header: "id" },
20748
+ { header: "provider", path: "connectorType" },
20749
+ { header: "status" },
20750
+ { header: "approved", format: "bool" }
20751
+ ]
20752
+ },
20753
+ getSearchSource: { command: "organizations search sources get", pathFlags: ORGANIZATION_FLAG },
20754
+ createSearchSource: {
20755
+ command: "organizations search sources create",
20756
+ pathFlags: ORGANIZATION_FLAG,
20757
+ flags: { apiKey: { textSource: true } }
20758
+ },
20759
+ updateSearchSource: {
20760
+ command: "organizations search sources update",
20761
+ pathFlags: ORGANIZATION_FLAG,
20762
+ flags: { apiKey: { textSource: true } },
20763
+ confirm: "This updates source settings and may replace its permission grants."
20764
+ },
20765
+ deleteSearchSource: {
20766
+ command: "organizations search sources delete",
20767
+ pathFlags: ORGANIZATION_FLAG,
20768
+ confirm: "This removes the source and its permission grants."
20769
+ },
20566
20770
  getSearchSourcePermissions: {
20567
20771
  command: "organizations search sources permissions get",
20568
20772
  pathFlags: ORGANIZATION_FLAG
@@ -26905,6 +27109,1743 @@ function attachSecretCommands(program) {
26905
27109
  set.argument("<name>", "Secret name, as referenced in workflows").description(describeOperation(V2_OPERATIONS.setSecret, "Create or replace a named secret, such as an API key or environment variable")).addOption(new Option("--scope <scope>", "Secret ownership scope (required)").choices([...SECRET_SCOPES]).makeOptionMandatory()).option("--value <value|@file>", "Secret value. Passing it inline exposes it to shell history and process listings; @path reads it from a file and @- from stdin, verbatim — a trailing newline is part of the value, so write the file with printf rather than echo. Prefix a literal leading @ with a second one").option("--description <description>", "What the secret is for, shown to teammates; workspace scope only. Omit to leave an existing description unchanged").option("--unredacted", `${V2_OPERATIONS.setSecret.body.unredacted.describe} Pass --no-unredacted to restore redaction`).option("--no-unredacted", "Send --unredacted as false").addHelpText("after", "Omit --value to enter it privately in a terminal. For an existing workspace secret, passing only --description or a redaction flag keeps the stored value and does not prompt. Personal secrets always require a value; they accept no writable metadata. In scripts, pass --value @path or --value @-.").on("option:unredacted", () => redactionSpellings.add("--unredacted")).on("option:no-unredacted", () => redactionSpellings.add("--no-unredacted")).action((name, options) => setSecret(name, options, connectSet, redactionSpellings));
26906
27110
  }
26907
27111
 
27112
+ // src/commands/source-permissions.ts
27113
+ import { readFile } from "node:fs/promises";
27114
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
27115
+
27116
+ // src/transfer/permission-csv.ts
27117
+ import { constants as constants3 } from "node:fs";
27118
+ import { mkdtemp as mkdtemp2, open, rm as rm2, writeFile } from "node:fs/promises";
27119
+ import { tmpdir } from "node:os";
27120
+ import { basename as basename3, join as join4 } from "node:path";
27121
+ import { addAbortSignal, Readable as Readable2 } from "node:stream";
27122
+
27123
+ // ../../node_modules/csv-parse/lib/index.js
27124
+ import { Transform } from "stream";
27125
+
27126
+ // ../../node_modules/csv-parse/lib/utils/is_object.js
27127
+ var is_object = function(obj) {
27128
+ return typeof obj === "object" && obj !== null && !Array.isArray(obj);
27129
+ };
27130
+
27131
+ // ../../node_modules/csv-parse/lib/api/CsvError.js
27132
+ class CsvError extends Error {
27133
+ constructor(code, message, options, ...contexts) {
27134
+ if (Array.isArray(message))
27135
+ message = message.join(" ").trim();
27136
+ super(message);
27137
+ if (Error.captureStackTrace !== undefined) {
27138
+ Error.captureStackTrace(this, CsvError);
27139
+ }
27140
+ this.code = code;
27141
+ for (const context of contexts) {
27142
+ for (const key in context) {
27143
+ const value = context[key];
27144
+ this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value));
27145
+ }
27146
+ }
27147
+ }
27148
+ }
27149
+
27150
+ // ../../node_modules/csv-parse/lib/api/normalize_columns_array.js
27151
+ var normalize_columns_array = function(columns) {
27152
+ const normalizedColumns = [];
27153
+ for (let i = 0, l = columns.length;i < l; i++) {
27154
+ const column = columns[i];
27155
+ if (column === undefined || column === null || column === false) {
27156
+ normalizedColumns[i] = { disabled: true };
27157
+ } else if (typeof column === "string" || typeof column === "number") {
27158
+ normalizedColumns[i] = { name: `${column}` };
27159
+ } else if (is_object(column)) {
27160
+ if (typeof column.name !== "string") {
27161
+ throw new CsvError("CSV_OPTION_COLUMNS_MISSING_NAME", [
27162
+ "Option columns missing name:",
27163
+ `property "name" is required at position ${i}`,
27164
+ "when column is an object literal"
27165
+ ]);
27166
+ }
27167
+ normalizedColumns[i] = column;
27168
+ } else {
27169
+ throw new CsvError("CSV_INVALID_COLUMN_DEFINITION", [
27170
+ "Invalid column definition:",
27171
+ "expect a string or a literal object,",
27172
+ `got ${JSON.stringify(column)} at position ${i}`
27173
+ ]);
27174
+ }
27175
+ }
27176
+ return normalizedColumns;
27177
+ };
27178
+
27179
+ // ../../node_modules/csv-parse/lib/utils/ResizeableBuffer.js
27180
+ class ResizeableBuffer {
27181
+ constructor(size = 100) {
27182
+ this.size = size;
27183
+ this.length = 0;
27184
+ this.buf = Buffer.allocUnsafe(size);
27185
+ }
27186
+ prepend(val) {
27187
+ if (Buffer.isBuffer(val)) {
27188
+ const length = this.length + val.length;
27189
+ if (length >= this.size) {
27190
+ this.resize();
27191
+ if (length >= this.size) {
27192
+ throw Error("INVALID_BUFFER_STATE");
27193
+ }
27194
+ }
27195
+ const buf = this.buf;
27196
+ this.buf = Buffer.allocUnsafe(this.size);
27197
+ val.copy(this.buf, 0);
27198
+ buf.copy(this.buf, val.length);
27199
+ this.length += val.length;
27200
+ } else {
27201
+ const length = this.length++;
27202
+ if (length === this.size) {
27203
+ this.resize();
27204
+ }
27205
+ const buf = this.clone();
27206
+ this.buf[0] = val;
27207
+ buf.copy(this.buf, 1, 0, length);
27208
+ }
27209
+ }
27210
+ append(val) {
27211
+ const length = this.length++;
27212
+ if (length === this.size) {
27213
+ this.resize();
27214
+ }
27215
+ this.buf[length] = val;
27216
+ }
27217
+ clone() {
27218
+ return Buffer.from(this.buf.slice(0, this.length));
27219
+ }
27220
+ resize() {
27221
+ const length = this.length;
27222
+ this.size = this.size * 2;
27223
+ const buf = Buffer.allocUnsafe(this.size);
27224
+ this.buf.copy(buf, 0, 0, length);
27225
+ this.buf = buf;
27226
+ }
27227
+ toString(encoding) {
27228
+ if (encoding) {
27229
+ return this.buf.toString(encoding, 0, this.length);
27230
+ } else {
27231
+ return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length));
27232
+ }
27233
+ }
27234
+ toJSON() {
27235
+ return this.toString("utf8");
27236
+ }
27237
+ reset() {
27238
+ this.length = 0;
27239
+ }
27240
+ }
27241
+ var ResizeableBuffer_default = ResizeableBuffer;
27242
+
27243
+ // ../../node_modules/csv-parse/lib/api/init_state.js
27244
+ var init_state = function(options) {
27245
+ const timchars = [
27246
+ 32,
27247
+ 9,
27248
+ 10,
27249
+ 13,
27250
+ 12,
27251
+ 11,
27252
+ 160,
27253
+ 5760,
27254
+ 8192,
27255
+ 8193,
27256
+ 8194,
27257
+ 8195,
27258
+ 8196,
27259
+ 8197,
27260
+ 8198,
27261
+ 8199,
27262
+ 8200,
27263
+ 8201,
27264
+ 8202,
27265
+ 8232,
27266
+ 8233,
27267
+ 8239,
27268
+ 8287,
27269
+ 12288,
27270
+ 65279
27271
+ ].reduce((acc, codepoint) => {
27272
+ const encoded = Buffer.from(String.fromCharCode(codepoint), options.encoding);
27273
+ if (codepoint !== 63 && encoded.length === 1 && encoded[0] === 63) {
27274
+ return acc;
27275
+ }
27276
+ acc.push(encoded);
27277
+ return acc;
27278
+ }, []);
27279
+ const timcharFirstBytes = new Uint8Array(256);
27280
+ for (const t of timchars)
27281
+ timcharFirstBytes[t[0]] = 1;
27282
+ return {
27283
+ bomSkipped: false,
27284
+ bufBytesStart: 0,
27285
+ castField: options.cast_function,
27286
+ commenting: false,
27287
+ delimiterBufPrevious: undefined,
27288
+ delimiterDiscovered: false,
27289
+ error: undefined,
27290
+ enabled: options.from_line === 1,
27291
+ escaping: false,
27292
+ escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0,
27293
+ expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined,
27294
+ field: new ResizeableBuffer_default(20),
27295
+ firstLineToHeaders: options.cast_first_line_to_header,
27296
+ needMoreDataSize: Math.max(options.comment !== null ? options.comment.length : 0, ...options.delimiter ? options.delimiter.map((delimiter) => delimiter.length) : [], options.delimiter_auto ? 1 : 0, options.quote !== null ? options.quote.length : 0, ...timchars.map((t) => t.length)),
27297
+ previousBuf: undefined,
27298
+ quoting: false,
27299
+ stop: false,
27300
+ rawBuffer: new ResizeableBuffer_default(100),
27301
+ record: [],
27302
+ recordHasError: false,
27303
+ record_length: 0,
27304
+ recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)),
27305
+ trimChars: [
27306
+ Buffer.from(" ", options.encoding)[0],
27307
+ Buffer.from("\t", options.encoding)[0]
27308
+ ],
27309
+ wasQuoting: false,
27310
+ wasRowDelimiter: false,
27311
+ timchars,
27312
+ timcharFirstBytes
27313
+ };
27314
+ };
27315
+
27316
+ // ../../node_modules/csv-parse/lib/utils/underscore.js
27317
+ var underscore = function(str) {
27318
+ return str.replace(/([A-Z])/g, function(_, match) {
27319
+ return "_" + match.toLowerCase();
27320
+ });
27321
+ };
27322
+
27323
+ // ../../node_modules/csv-parse/lib/api/normalize_options.js
27324
+ var normalize_options = function(opts) {
27325
+ const options = {};
27326
+ for (const opt in opts) {
27327
+ options[underscore(opt)] = opts[opt];
27328
+ }
27329
+ if (options.encoding === undefined || options.encoding === true) {
27330
+ options.encoding = "utf8";
27331
+ } else if (options.encoding === null || options.encoding === false) {
27332
+ options.encoding = null;
27333
+ } else if (typeof options.encoding !== "string" && options.encoding !== null) {
27334
+ throw new CsvError("CSV_INVALID_OPTION_ENCODING", [
27335
+ "Invalid option encoding:",
27336
+ "encoding must be a string or null to return a buffer,",
27337
+ `got ${JSON.stringify(options.encoding)}`
27338
+ ], options);
27339
+ }
27340
+ if (options.bom === undefined || options.bom === null || options.bom === false) {
27341
+ options.bom = false;
27342
+ } else if (options.bom !== true) {
27343
+ throw new CsvError("CSV_INVALID_OPTION_BOM", [
27344
+ "Invalid option bom:",
27345
+ "bom must be true,",
27346
+ `got ${JSON.stringify(options.bom)}`
27347
+ ], options);
27348
+ }
27349
+ options.cast_function = null;
27350
+ if (options.cast === undefined || options.cast === null || options.cast === false || options.cast === "") {
27351
+ options.cast = undefined;
27352
+ } else if (typeof options.cast === "function") {
27353
+ options.cast_function = options.cast;
27354
+ options.cast = true;
27355
+ } else if (options.cast !== true) {
27356
+ throw new CsvError("CSV_INVALID_OPTION_CAST", [
27357
+ "Invalid option cast:",
27358
+ "cast must be true or a function,",
27359
+ `got ${JSON.stringify(options.cast)}`
27360
+ ], options);
27361
+ }
27362
+ if (options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === "") {
27363
+ options.cast_date = false;
27364
+ } else if (options.cast_date === true) {
27365
+ options.cast_date = function(value) {
27366
+ const date = Date.parse(value);
27367
+ return !isNaN(date) ? new Date(date) : value;
27368
+ };
27369
+ } else if (typeof options.cast_date !== "function") {
27370
+ throw new CsvError("CSV_INVALID_OPTION_CAST_DATE", [
27371
+ "Invalid option cast_date:",
27372
+ "cast_date must be true or a function,",
27373
+ `got ${JSON.stringify(options.cast_date)}`
27374
+ ], options);
27375
+ }
27376
+ options.cast_first_line_to_header = undefined;
27377
+ if (options.columns === true) {
27378
+ options.cast_first_line_to_header = undefined;
27379
+ } else if (typeof options.columns === "function") {
27380
+ options.cast_first_line_to_header = options.columns;
27381
+ options.columns = true;
27382
+ } else if (Array.isArray(options.columns)) {
27383
+ options.columns = normalize_columns_array(options.columns);
27384
+ } else if (options.columns === undefined || options.columns === null || options.columns === false) {
27385
+ options.columns = false;
27386
+ } else {
27387
+ throw new CsvError("CSV_INVALID_OPTION_COLUMNS", [
27388
+ "Invalid option columns:",
27389
+ "expect an array, a function or true,",
27390
+ `got ${JSON.stringify(options.columns)}`
27391
+ ], options);
27392
+ }
27393
+ if (options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false) {
27394
+ options.group_columns_by_name = false;
27395
+ } else if (options.group_columns_by_name !== true) {
27396
+ throw new CsvError("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME", [
27397
+ "Invalid option group_columns_by_name:",
27398
+ "expect an boolean,",
27399
+ `got ${JSON.stringify(options.group_columns_by_name)}`
27400
+ ], options);
27401
+ } else if (options.columns === false) {
27402
+ throw new CsvError("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME", [
27403
+ "Invalid option group_columns_by_name:",
27404
+ "the `columns` mode must be activated."
27405
+ ], options);
27406
+ }
27407
+ if (options.comment === undefined || options.comment === null || options.comment === false || options.comment === "") {
27408
+ options.comment = null;
27409
+ } else {
27410
+ if (typeof options.comment === "string") {
27411
+ options.comment = Buffer.from(options.comment, options.encoding);
27412
+ }
27413
+ if (!Buffer.isBuffer(options.comment)) {
27414
+ throw new CsvError("CSV_INVALID_OPTION_COMMENT", [
27415
+ "Invalid option comment:",
27416
+ "comment must be a buffer or a string,",
27417
+ `got ${JSON.stringify(options.comment)}`
27418
+ ], options);
27419
+ }
27420
+ }
27421
+ if (options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false) {
27422
+ options.comment_no_infix = false;
27423
+ } else if (options.comment_no_infix !== true) {
27424
+ throw new CsvError("CSV_INVALID_OPTION_COMMENT", [
27425
+ "Invalid option comment_no_infix:",
27426
+ "value must be a boolean,",
27427
+ `got ${JSON.stringify(options.comment_no_infix)}`
27428
+ ], options);
27429
+ }
27430
+ if (options.delimiter_auto === undefined || options.delimiter_auto === null || options.delimiter_auto === false) {
27431
+ options.delimiter_auto = false;
27432
+ } else if (options.delimiter_auto === true) {
27433
+ options.delimiter_auto = {};
27434
+ } else if (!is_object(options.delimiter_auto)) {
27435
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER_AUTO", [
27436
+ "Invalid option delimiter_auto:",
27437
+ "delimiter_auto must be a boolean or a configuration object,",
27438
+ `got ${JSON.stringify(options.delimiter_auto)}`
27439
+ ], options);
27440
+ }
27441
+ if (options.delimiter_auto) {
27442
+ if (options.delimiter_auto.preferred === undefined)
27443
+ options.delimiter_auto.preferred = {
27444
+ [44]: 1.8,
27445
+ [9]: 1.8,
27446
+ [59]: 1.6,
27447
+ [32]: 1.6,
27448
+ [58]: 1.5,
27449
+ [46]: 1.4,
27450
+ [47]: 1.4
27451
+ };
27452
+ else if (!is_object(options.delimiter_auto.preferred)) {
27453
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER_AUTO", [
27454
+ "Invalid option delimiter_auto:",
27455
+ "preferred must be an object,",
27456
+ `got ${JSON.stringify(options.delimiter_auto.preferred)}`
27457
+ ], options);
27458
+ }
27459
+ if (options.delimiter_auto.score === undefined)
27460
+ options.delimiter_auto.score = (info, options) => {
27461
+ return (info.total - info.std) * (options.preferred[info.char_code] || 1);
27462
+ };
27463
+ else if (typeof options.delimiter_auto.score !== "function") {
27464
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER_AUTO", [
27465
+ "Invalid option delimiter_auto:",
27466
+ "score must be a function,",
27467
+ `got ${JSON.stringify(options.delimiter_auto.score)}`
27468
+ ], options);
27469
+ }
27470
+ if (options.delimiter_auto.size === undefined)
27471
+ options.delimiter_auto.size = 2048;
27472
+ else if (typeof options.delimiter_auto.size !== "number") {
27473
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER_AUTO", [
27474
+ "Invalid option delimiter_auto:",
27475
+ "size must be a number,",
27476
+ `got ${JSON.stringify(options.delimiter_auto.size)}`
27477
+ ], options);
27478
+ }
27479
+ }
27480
+ const delimiter_json = JSON.stringify(options.delimiter);
27481
+ if (options.delimiter_auto !== false) {
27482
+ options.delimiter = [];
27483
+ }
27484
+ if (!Array.isArray(options.delimiter)) {
27485
+ if (options.delimiter === undefined || options.delimiter === null || options.delimiter === false) {
27486
+ options.delimiter = Buffer.from(",", options.encoding);
27487
+ }
27488
+ options.delimiter = [options.delimiter];
27489
+ }
27490
+ options.delimiter = options.delimiter.map(function(delimiter) {
27491
+ if (typeof delimiter === "string") {
27492
+ delimiter = Buffer.from(delimiter, options.encoding);
27493
+ }
27494
+ if (!Buffer.isBuffer(delimiter) || delimiter.length === 0) {
27495
+ throw new CsvError("CSV_INVALID_OPTION_DELIMITER", [
27496
+ "Invalid option delimiter:",
27497
+ "delimiter must be a non empty string or buffer or array of string|buffer,",
27498
+ `got ${delimiter_json}`
27499
+ ], options);
27500
+ }
27501
+ return delimiter;
27502
+ });
27503
+ if (options.escape === undefined || options.escape === true) {
27504
+ options.escape = Buffer.from('"', options.encoding);
27505
+ } else if (typeof options.escape === "string") {
27506
+ options.escape = Buffer.from(options.escape, options.encoding);
27507
+ } else if (options.escape === null || options.escape === false) {
27508
+ options.escape = null;
27509
+ }
27510
+ if (options.escape !== null) {
27511
+ if (!Buffer.isBuffer(options.escape)) {
27512
+ throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`);
27513
+ }
27514
+ }
27515
+ if (options.from === undefined || options.from === null) {
27516
+ options.from = 1;
27517
+ } else {
27518
+ if (typeof options.from === "string" && /\d+/.test(options.from)) {
27519
+ options.from = parseInt(options.from);
27520
+ }
27521
+ if (Number.isInteger(options.from)) {
27522
+ if (options.from < 0) {
27523
+ throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`);
27524
+ }
27525
+ } else {
27526
+ throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`);
27527
+ }
27528
+ }
27529
+ if (options.from_line === undefined || options.from_line === null) {
27530
+ options.from_line = 1;
27531
+ } else {
27532
+ if (typeof options.from_line === "string" && /\d+/.test(options.from_line)) {
27533
+ options.from_line = parseInt(options.from_line);
27534
+ }
27535
+ if (Number.isInteger(options.from_line)) {
27536
+ if (options.from_line <= 0) {
27537
+ throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`);
27538
+ }
27539
+ } else {
27540
+ throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`);
27541
+ }
27542
+ }
27543
+ if (options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null) {
27544
+ options.ignore_last_delimiters = false;
27545
+ } else if (typeof options.ignore_last_delimiters === "number") {
27546
+ options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters);
27547
+ if (options.ignore_last_delimiters === 0) {
27548
+ options.ignore_last_delimiters = false;
27549
+ }
27550
+ } else if (typeof options.ignore_last_delimiters !== "boolean") {
27551
+ throw new CsvError("CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS", [
27552
+ "Invalid option `ignore_last_delimiters`:",
27553
+ "the value must be a boolean value or an integer,",
27554
+ `got ${JSON.stringify(options.ignore_last_delimiters)}`
27555
+ ], options);
27556
+ }
27557
+ if (options.ignore_last_delimiters === true && options.columns === false) {
27558
+ throw new CsvError("CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS", [
27559
+ "The option `ignore_last_delimiters`",
27560
+ "requires the activation of the `columns` option"
27561
+ ], options);
27562
+ }
27563
+ if (options.info === undefined || options.info === null || options.info === false) {
27564
+ options.info = false;
27565
+ } else if (options.info !== true) {
27566
+ throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`);
27567
+ }
27568
+ if (options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false) {
27569
+ options.max_record_size = 0;
27570
+ } else if (Number.isInteger(options.max_record_size) && options.max_record_size >= 0) {} else if (typeof options.max_record_size === "string" && /\d+/.test(options.max_record_size)) {
27571
+ options.max_record_size = parseInt(options.max_record_size);
27572
+ } else {
27573
+ throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`);
27574
+ }
27575
+ if (options.objname === undefined || options.objname === null || options.objname === false) {
27576
+ options.objname = undefined;
27577
+ } else if (Buffer.isBuffer(options.objname)) {
27578
+ if (options.objname.length === 0) {
27579
+ throw new Error(`Invalid Option: objname must be a non empty buffer`);
27580
+ }
27581
+ if (options.encoding === null) {} else {
27582
+ options.objname = options.objname.toString(options.encoding);
27583
+ }
27584
+ } else if (typeof options.objname === "string") {
27585
+ if (options.objname.length === 0) {
27586
+ throw new Error(`Invalid Option: objname must be a non empty string`);
27587
+ }
27588
+ } else if (typeof options.objname === "number") {} else {
27589
+ throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`);
27590
+ }
27591
+ if (options.objname !== undefined) {
27592
+ if (typeof options.objname === "number") {
27593
+ if (options.columns !== false) {
27594
+ throw Error("Invalid Option: objname index cannot be combined with columns or be defined as a field");
27595
+ }
27596
+ } else {
27597
+ if (options.columns === false) {
27598
+ throw Error("Invalid Option: objname field must be combined with columns or be defined as an index");
27599
+ }
27600
+ }
27601
+ }
27602
+ if (options.on_record === undefined || options.on_record === null) {
27603
+ options.on_record = undefined;
27604
+ } else if (typeof options.on_record !== "function") {
27605
+ throw new CsvError("CSV_INVALID_OPTION_ON_RECORD", [
27606
+ "Invalid option `on_record`:",
27607
+ "expect a function,",
27608
+ `got ${JSON.stringify(options.on_record)}`
27609
+ ], options);
27610
+ }
27611
+ if (options.on_skip !== undefined && options.on_skip !== null && typeof options.on_skip !== "function") {
27612
+ throw new Error(`Invalid Option: on_skip must be a function, got ${JSON.stringify(options.on_skip)}`);
27613
+ }
27614
+ if (options.quote === null || options.quote === false || options.quote === "") {
27615
+ options.quote = null;
27616
+ } else {
27617
+ if (options.quote === undefined || options.quote === true) {
27618
+ options.quote = Buffer.from('"', options.encoding);
27619
+ } else if (typeof options.quote === "string") {
27620
+ options.quote = Buffer.from(options.quote, options.encoding);
27621
+ }
27622
+ if (!Buffer.isBuffer(options.quote)) {
27623
+ throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`);
27624
+ }
27625
+ }
27626
+ if (options.raw === undefined || options.raw === null || options.raw === false) {
27627
+ options.raw = false;
27628
+ } else if (options.raw !== true) {
27629
+ throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`);
27630
+ }
27631
+ if (options.record_delimiter === undefined) {
27632
+ options.record_delimiter = [];
27633
+ } else if (typeof options.record_delimiter === "string" || Buffer.isBuffer(options.record_delimiter)) {
27634
+ if (options.record_delimiter.length === 0) {
27635
+ throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
27636
+ "Invalid option `record_delimiter`:",
27637
+ "value must be a non empty string or buffer,",
27638
+ `got ${JSON.stringify(options.record_delimiter)}`
27639
+ ], options);
27640
+ }
27641
+ options.record_delimiter = [options.record_delimiter];
27642
+ } else if (!Array.isArray(options.record_delimiter)) {
27643
+ throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
27644
+ "Invalid option `record_delimiter`:",
27645
+ "value must be a string, a buffer or array of string|buffer,",
27646
+ `got ${JSON.stringify(options.record_delimiter)}`
27647
+ ], options);
27648
+ }
27649
+ options.record_delimiter = options.record_delimiter.map(function(rd, i) {
27650
+ if (typeof rd !== "string" && !Buffer.isBuffer(rd)) {
27651
+ throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
27652
+ "Invalid option `record_delimiter`:",
27653
+ "value must be a string, a buffer or array of string|buffer",
27654
+ `at index ${i},`,
27655
+ `got ${JSON.stringify(rd)}`
27656
+ ], options);
27657
+ } else if (rd.length === 0) {
27658
+ throw new CsvError("CSV_INVALID_OPTION_RECORD_DELIMITER", [
27659
+ "Invalid option `record_delimiter`:",
27660
+ "value must be a non empty string or buffer",
27661
+ `at index ${i},`,
27662
+ `got ${JSON.stringify(rd)}`
27663
+ ], options);
27664
+ }
27665
+ if (typeof rd === "string") {
27666
+ rd = Buffer.from(rd, options.encoding);
27667
+ }
27668
+ return rd;
27669
+ });
27670
+ if (typeof options.relax_column_count === "boolean") {} else if (options.relax_column_count === undefined || options.relax_column_count === null) {
27671
+ options.relax_column_count = false;
27672
+ } else {
27673
+ throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`);
27674
+ }
27675
+ if (typeof options.relax_column_count_less === "boolean") {} else if (options.relax_column_count_less === undefined || options.relax_column_count_less === null) {
27676
+ options.relax_column_count_less = false;
27677
+ } else {
27678
+ throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`);
27679
+ }
27680
+ if (typeof options.relax_column_count_more === "boolean") {} else if (options.relax_column_count_more === undefined || options.relax_column_count_more === null) {
27681
+ options.relax_column_count_more = false;
27682
+ } else {
27683
+ throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`);
27684
+ }
27685
+ if (typeof options.relax_quotes === "boolean") {} else if (options.relax_quotes === undefined || options.relax_quotes === null) {
27686
+ options.relax_quotes = false;
27687
+ } else {
27688
+ throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`);
27689
+ }
27690
+ if (typeof options.skip_empty_lines === "boolean") {} else if (options.skip_empty_lines === undefined || options.skip_empty_lines === null) {
27691
+ options.skip_empty_lines = false;
27692
+ } else {
27693
+ throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`);
27694
+ }
27695
+ if (typeof options.skip_records_with_empty_values === "boolean") {} else if (options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null) {
27696
+ options.skip_records_with_empty_values = false;
27697
+ } else {
27698
+ throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`);
27699
+ }
27700
+ if (typeof options.skip_records_with_error === "boolean") {} else if (options.skip_records_with_error === undefined || options.skip_records_with_error === null) {
27701
+ options.skip_records_with_error = false;
27702
+ } else {
27703
+ throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`);
27704
+ }
27705
+ if (options.rtrim === undefined || options.rtrim === null || options.rtrim === false) {
27706
+ options.rtrim = false;
27707
+ } else if (options.rtrim !== true) {
27708
+ throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`);
27709
+ }
27710
+ if (options.ltrim === undefined || options.ltrim === null || options.ltrim === false) {
27711
+ options.ltrim = false;
27712
+ } else if (options.ltrim !== true) {
27713
+ throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`);
27714
+ }
27715
+ if (options.trim === undefined || options.trim === null || options.trim === false) {
27716
+ options.trim = false;
27717
+ } else if (options.trim !== true) {
27718
+ throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`);
27719
+ }
27720
+ if (options.trim === true && opts.ltrim !== false) {
27721
+ options.ltrim = true;
27722
+ } else if (options.ltrim !== true) {
27723
+ options.ltrim = false;
27724
+ }
27725
+ if (options.trim === true && opts.rtrim !== false) {
27726
+ options.rtrim = true;
27727
+ } else if (options.rtrim !== true) {
27728
+ options.rtrim = false;
27729
+ }
27730
+ if (options.to === undefined || options.to === null) {
27731
+ options.to = -1;
27732
+ } else if (options.to !== -1) {
27733
+ if (typeof options.to === "string" && /\d+/.test(options.to)) {
27734
+ options.to = parseInt(options.to);
27735
+ }
27736
+ if (Number.isInteger(options.to)) {
27737
+ if (options.to <= 0) {
27738
+ throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`);
27739
+ }
27740
+ } else {
27741
+ throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`);
27742
+ }
27743
+ }
27744
+ if (options.to_line === undefined || options.to_line === null) {
27745
+ options.to_line = -1;
27746
+ } else if (options.to_line !== -1) {
27747
+ if (typeof options.to_line === "string" && /\d+/.test(options.to_line)) {
27748
+ options.to_line = parseInt(options.to_line);
27749
+ }
27750
+ if (Number.isInteger(options.to_line)) {
27751
+ if (options.to_line <= 0) {
27752
+ throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`);
27753
+ }
27754
+ } else {
27755
+ throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`);
27756
+ }
27757
+ }
27758
+ return options;
27759
+ };
27760
+
27761
+ // ../../node_modules/csv-parse/lib/utils/delimiter_discover.js
27762
+ var delimiter_discover = function(records, options) {
27763
+ if (!options) {
27764
+ ({ delimiter_auto: options } = normalize_options({ delimiter_auto: true }));
27765
+ }
27766
+ if (typeof records === "string") {
27767
+ records = Buffer.from(records);
27768
+ }
27769
+ if (Buffer.isBuffer(records)) {
27770
+ records = ((data) => {
27771
+ const records = [];
27772
+ const parser = transform({ delimiter: [] });
27773
+ const push = (record) => records.push(record);
27774
+ const close = () => {};
27775
+ const error = parser.parse(data, true, push, close);
27776
+ if (error !== undefined)
27777
+ throw error;
27778
+ return records;
27779
+ })(records);
27780
+ }
27781
+ const info = Array(127).fill().map(() => ({ lines: [] }));
27782
+ records.map(([record], line) => {
27783
+ for (let i = 0, l = record.length;i < l; i++) {
27784
+ const code = record.charCodeAt(i);
27785
+ if (info[code].lines[line] === undefined)
27786
+ info[code].lines[line] = 0;
27787
+ info[code].lines[line]++;
27788
+ }
27789
+ });
27790
+ info.map((info, i) => {
27791
+ info.char_code = i;
27792
+ info.std = std(info.lines);
27793
+ info.total = info.lines.reduce((acc, val) => acc + val, 0);
27794
+ info.preferred = !!options.preferred[i];
27795
+ info.score = options.score(info, options);
27796
+ });
27797
+ const result = info.reduce((acc, info) => acc.score > info.score ? acc : info, {});
27798
+ return String.fromCharCode(result.char_code);
27799
+ };
27800
+ var std = function(array) {
27801
+ const n = array.length;
27802
+ if (n === 0)
27803
+ return 0;
27804
+ const mean = array.reduce((a, b) => a + b) / n;
27805
+ return Math.sqrt(array.map((x) => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n);
27806
+ };
27807
+
27808
+ // ../../node_modules/csv-parse/lib/api/index.js
27809
+ var isRecordEmpty = function(record) {
27810
+ return record.every((field) => field == null || field.toString && field.toString().trim() === "");
27811
+ };
27812
+ var cr = 13;
27813
+ var nl = 10;
27814
+ var boms = {
27815
+ utf8: Buffer.from([239, 187, 191]),
27816
+ utf16le: Buffer.from([255, 254])
27817
+ };
27818
+ var transform = function(original_options = {}) {
27819
+ const info = {
27820
+ bytes: 0,
27821
+ bytes_records: 0,
27822
+ comment_lines: 0,
27823
+ empty_lines: 0,
27824
+ invalid_field_length: 0,
27825
+ lines: 1,
27826
+ records: 0
27827
+ };
27828
+ const options = normalize_options(original_options);
27829
+ return {
27830
+ info,
27831
+ original_options,
27832
+ options,
27833
+ state: init_state(options),
27834
+ __needMoreData: function(i, bufLen, end) {
27835
+ if (end)
27836
+ return false;
27837
+ const { encoding, escape, quote } = this.options;
27838
+ const { quoting, needMoreDataSize, recordDelimiterMaxLength } = this.state;
27839
+ const numOfCharLeft = bufLen - i - 1;
27840
+ const requiredLength = Math.max(needMoreDataSize, recordDelimiterMaxLength === 0 ? Buffer.from(`\r
27841
+ `, encoding).length : recordDelimiterMaxLength, quoting ? (escape === null ? 0 : escape.length) + quote.length : 0, quoting ? quote.length + recordDelimiterMaxLength : 0);
27842
+ return numOfCharLeft < requiredLength;
27843
+ },
27844
+ parse: function(nextBuf, end, push, close) {
27845
+ const {
27846
+ bom,
27847
+ comment_no_infix,
27848
+ delimiter_auto,
27849
+ encoding,
27850
+ from_line,
27851
+ ltrim,
27852
+ max_record_size,
27853
+ raw,
27854
+ relax_quotes,
27855
+ rtrim,
27856
+ skip_empty_lines,
27857
+ to,
27858
+ to_line
27859
+ } = this.options;
27860
+ let { comment, escape, quote, record_delimiter } = this.options;
27861
+ const {
27862
+ bomSkipped,
27863
+ delimiterDiscovered,
27864
+ delimiterBufPrevious,
27865
+ rawBuffer,
27866
+ escapeIsQuote
27867
+ } = this.state;
27868
+ if (!delimiterDiscovered && delimiter_auto) {
27869
+ let delimiterBuf;
27870
+ if (delimiterBufPrevious === undefined) {
27871
+ delimiterBuf = nextBuf;
27872
+ } else if (delimiterBufPrevious !== undefined && nextBuf === undefined) {
27873
+ delimiterBuf = delimiterBufPrevious;
27874
+ } else {
27875
+ delimiterBuf = Buffer.concat([delimiterBufPrevious, nextBuf]);
27876
+ }
27877
+ nextBuf = undefined;
27878
+ if (end || delimiterBuf.length > delimiter_auto.size) {
27879
+ this.options.delimiter = [
27880
+ Buffer.from(delimiter_discover(delimiterBuf, this.options.delimiter_auto))
27881
+ ];
27882
+ this.state.previousBuf = delimiterBuf;
27883
+ this.state.delimiterBufPrevious = undefined;
27884
+ this.state.delimiterDiscovered = true;
27885
+ } else {
27886
+ this.state.delimiterBufPrevious = delimiterBuf;
27887
+ return;
27888
+ }
27889
+ }
27890
+ const { previousBuf } = this.state;
27891
+ let buf;
27892
+ if (previousBuf === undefined) {
27893
+ if (nextBuf === undefined) {
27894
+ close();
27895
+ return;
27896
+ } else {
27897
+ buf = nextBuf;
27898
+ }
27899
+ } else if (previousBuf !== undefined && nextBuf === undefined) {
27900
+ buf = previousBuf;
27901
+ } else {
27902
+ buf = Buffer.concat([previousBuf, nextBuf]);
27903
+ }
27904
+ if (bomSkipped === false) {
27905
+ if (bom === false) {
27906
+ this.state.bomSkipped = true;
27907
+ } else if (buf.length < 3) {
27908
+ if (end === false) {
27909
+ this.state.previousBuf = buf;
27910
+ return;
27911
+ }
27912
+ } else {
27913
+ for (const encoding in boms) {
27914
+ if (boms[encoding].compare(buf, 0, boms[encoding].length) === 0) {
27915
+ const bomLength = boms[encoding].length;
27916
+ this.state.bufBytesStart += bomLength;
27917
+ buf = buf.slice(bomLength);
27918
+ const options = normalize_options({
27919
+ ...this.original_options,
27920
+ encoding
27921
+ });
27922
+ for (const key in options) {
27923
+ this.options[key] = options[key];
27924
+ }
27925
+ ({ comment, escape, quote } = this.options);
27926
+ break;
27927
+ }
27928
+ }
27929
+ this.state.bomSkipped = true;
27930
+ }
27931
+ }
27932
+ const bufLen = buf.length;
27933
+ let pos;
27934
+ for (pos = 0;pos < bufLen; pos++) {
27935
+ if (this.__needMoreData(pos, bufLen, end)) {
27936
+ break;
27937
+ }
27938
+ if (this.state.wasRowDelimiter === true) {
27939
+ this.info.lines++;
27940
+ this.state.wasRowDelimiter = false;
27941
+ }
27942
+ if (to_line !== -1 && this.info.lines > to_line) {
27943
+ this.state.stop = true;
27944
+ close();
27945
+ return;
27946
+ }
27947
+ if (this.state.quoting === false && record_delimiter.length === 0) {
27948
+ const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos);
27949
+ if (record_delimiterCount) {
27950
+ record_delimiter = this.options.record_delimiter;
27951
+ }
27952
+ }
27953
+ const chr = buf[pos];
27954
+ if (raw === true) {
27955
+ rawBuffer.append(chr);
27956
+ }
27957
+ if ((chr === cr || chr === nl) && this.state.wasRowDelimiter === false) {
27958
+ this.state.wasRowDelimiter = true;
27959
+ }
27960
+ if (this.state.escaping === true) {
27961
+ this.state.escaping = false;
27962
+ } else {
27963
+ if (escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen) {
27964
+ if (escapeIsQuote) {
27965
+ if (this.__isQuote(buf, pos + escape.length)) {
27966
+ this.state.escaping = true;
27967
+ pos += escape.length - 1;
27968
+ continue;
27969
+ }
27970
+ } else {
27971
+ this.state.escaping = true;
27972
+ pos += escape.length - 1;
27973
+ continue;
27974
+ }
27975
+ }
27976
+ if (this.state.commenting === false && this.__isQuote(buf, pos)) {
27977
+ if (this.state.quoting === true) {
27978
+ const nextChr = buf[pos + quote.length];
27979
+ const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos + quote.length);
27980
+ const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + quote.length, nextChr);
27981
+ const isNextChrDelimiter = this.__isDelimiter(buf, pos + quote.length, nextChr);
27982
+ const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos + quote.length) : this.__isRecordDelimiter(nextChr, buf, pos + quote.length);
27983
+ if (escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)) {
27984
+ pos += escape.length - 1;
27985
+ } else if (!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable) {
27986
+ this.state.quoting = false;
27987
+ this.state.wasQuoting = true;
27988
+ pos += quote.length - 1;
27989
+ continue;
27990
+ } else if (relax_quotes === false) {
27991
+ const err = this.__error(new CsvError("CSV_INVALID_CLOSING_QUOTE", [
27992
+ "Invalid Closing Quote:",
27993
+ `got "${String.fromCharCode(nextChr)}"`,
27994
+ `at line ${this.info.lines}`,
27995
+ "instead of delimiter, record delimiter, trimable character",
27996
+ "(if activated) or comment"
27997
+ ], this.options, this.__infoField()));
27998
+ if (err !== undefined)
27999
+ return err;
28000
+ } else {
28001
+ this.state.quoting = false;
28002
+ this.state.wasQuoting = true;
28003
+ this.state.field.prepend(quote);
28004
+ pos += quote.length - 1;
28005
+ }
28006
+ } else {
28007
+ if (this.state.field.length !== 0) {
28008
+ if (relax_quotes === false) {
28009
+ const info = this.__infoField();
28010
+ const bom = Object.keys(boms).map((b) => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0];
28011
+ const err = this.__error(new CsvError("INVALID_OPENING_QUOTE", [
28012
+ "Invalid Opening Quote:",
28013
+ `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`,
28014
+ bom ? `(${bom} bom)` : undefined
28015
+ ], this.options, info, {
28016
+ field: this.state.field
28017
+ }));
28018
+ if (err !== undefined)
28019
+ return err;
28020
+ }
28021
+ } else {
28022
+ this.state.quoting = true;
28023
+ pos += quote.length - 1;
28024
+ continue;
28025
+ }
28026
+ }
28027
+ }
28028
+ if (this.state.quoting === false) {
28029
+ const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos);
28030
+ if (recordDelimiterLength !== 0) {
28031
+ const skipCommentLine = this.state.commenting && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0;
28032
+ if (skipCommentLine) {
28033
+ this.info.comment_lines++;
28034
+ } else {
28035
+ if (this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1 : 0) >= from_line) {
28036
+ this.state.enabled = true;
28037
+ this.__resetField();
28038
+ this.__resetRecord();
28039
+ pos += recordDelimiterLength - 1;
28040
+ continue;
28041
+ }
28042
+ if (skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) {
28043
+ this.info.empty_lines++;
28044
+ pos += recordDelimiterLength - 1;
28045
+ continue;
28046
+ }
28047
+ this.info.bytes = this.state.bufBytesStart + pos;
28048
+ const errField = this.__onField();
28049
+ if (errField !== undefined)
28050
+ return errField;
28051
+ this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength;
28052
+ const errRecord = this.__onRecord(push);
28053
+ if (errRecord !== undefined)
28054
+ return errRecord;
28055
+ if (to !== -1 && this.info.records >= to) {
28056
+ this.state.stop = true;
28057
+ close();
28058
+ return;
28059
+ }
28060
+ }
28061
+ this.state.commenting = false;
28062
+ pos += recordDelimiterLength - 1;
28063
+ continue;
28064
+ }
28065
+ if (this.state.commenting) {
28066
+ continue;
28067
+ }
28068
+ if (comment !== null && (comment_no_infix === false || this.state.record.length === 0 && this.state.field.length === 0)) {
28069
+ const commentCount = this.__compareBytes(comment, buf, pos, chr);
28070
+ if (commentCount !== 0) {
28071
+ this.state.commenting = true;
28072
+ continue;
28073
+ }
28074
+ }
28075
+ const delimiterLength = this.__isDelimiter(buf, pos, chr);
28076
+ if (delimiterLength !== 0) {
28077
+ this.info.bytes = this.state.bufBytesStart + pos;
28078
+ const errField = this.__onField();
28079
+ if (errField !== undefined)
28080
+ return errField;
28081
+ pos += delimiterLength - 1;
28082
+ continue;
28083
+ }
28084
+ }
28085
+ }
28086
+ if (this.state.commenting === false) {
28087
+ if (max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size) {
28088
+ return this.__error(new CsvError("CSV_MAX_RECORD_SIZE", [
28089
+ "Max Record Size:",
28090
+ "record exceed the maximum number of tolerated bytes",
28091
+ `of ${max_record_size}`,
28092
+ `at line ${this.info.lines}`
28093
+ ], this.options, this.__infoField()));
28094
+ }
28095
+ }
28096
+ const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos);
28097
+ const rappend = rtrim === false || this.state.wasQuoting === false;
28098
+ if (lappend === true && rappend === true) {
28099
+ this.state.field.append(chr);
28100
+ } else if (rtrim === true && !this.__isCharTrimable(buf, pos)) {
28101
+ return this.__error(new CsvError("CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE", [
28102
+ "Invalid Closing Quote:",
28103
+ "found non trimable byte after quote",
28104
+ `at line ${this.info.lines}`
28105
+ ], this.options, this.__infoField()));
28106
+ } else {
28107
+ if (lappend === false) {
28108
+ pos += this.__isCharTrimable(buf, pos) - 1;
28109
+ }
28110
+ continue;
28111
+ }
28112
+ }
28113
+ if (end === true) {
28114
+ if (this.state.quoting === true) {
28115
+ const err = this.__error(new CsvError("CSV_QUOTE_NOT_CLOSED", [
28116
+ "Quote Not Closed:",
28117
+ `the parsing is finished with an opening quote at line ${this.info.lines}`
28118
+ ], this.options, this.__infoField()));
28119
+ if (err !== undefined)
28120
+ return err;
28121
+ } else {
28122
+ if (this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0) {
28123
+ this.info.bytes = this.state.bufBytesStart + pos;
28124
+ const errField = this.__onField();
28125
+ if (errField !== undefined)
28126
+ return errField;
28127
+ const errRecord = this.__onRecord(push);
28128
+ if (errRecord !== undefined)
28129
+ return errRecord;
28130
+ } else if (this.state.wasRowDelimiter === true) {
28131
+ this.info.empty_lines++;
28132
+ } else if (this.state.commenting === true) {
28133
+ this.info.comment_lines++;
28134
+ }
28135
+ }
28136
+ } else {
28137
+ this.state.bufBytesStart += pos;
28138
+ this.state.previousBuf = buf.slice(pos);
28139
+ }
28140
+ if (this.state.wasRowDelimiter === true) {
28141
+ this.info.lines++;
28142
+ this.state.wasRowDelimiter = false;
28143
+ }
28144
+ },
28145
+ __onRecord: function(push) {
28146
+ const {
28147
+ columns,
28148
+ group_columns_by_name,
28149
+ encoding,
28150
+ info,
28151
+ from,
28152
+ relax_column_count,
28153
+ relax_column_count_less,
28154
+ relax_column_count_more,
28155
+ raw,
28156
+ skip_records_with_empty_values
28157
+ } = this.options;
28158
+ const { enabled, record } = this.state;
28159
+ if (enabled === false) {
28160
+ return this.__resetRecord();
28161
+ }
28162
+ const recordLength = record.length;
28163
+ if (columns === true) {
28164
+ if (skip_records_with_empty_values === true && isRecordEmpty(record)) {
28165
+ this.__resetRecord();
28166
+ return;
28167
+ }
28168
+ return this.__firstLineToColumns(record);
28169
+ }
28170
+ if (columns === false && this.info.records === 0) {
28171
+ this.state.expectedRecordLength = recordLength;
28172
+ }
28173
+ if (recordLength !== this.state.expectedRecordLength) {
28174
+ const err = columns === false ? new CsvError("CSV_RECORD_INCONSISTENT_FIELDS_LENGTH", [
28175
+ "Invalid Record Length:",
28176
+ `expect ${this.state.expectedRecordLength},`,
28177
+ `got ${recordLength} on line ${this.info.lines}`
28178
+ ], this.options, this.__infoField(), {
28179
+ record
28180
+ }) : new CsvError("CSV_RECORD_INCONSISTENT_COLUMNS", [
28181
+ "Invalid Record Length:",
28182
+ `columns length is ${columns.length},`,
28183
+ `got ${recordLength} on line ${this.info.lines}`
28184
+ ], this.options, this.__infoField(), {
28185
+ record
28186
+ });
28187
+ if (relax_column_count === true || relax_column_count_less === true && recordLength < this.state.expectedRecordLength || relax_column_count_more === true && recordLength > this.state.expectedRecordLength) {
28188
+ this.info.invalid_field_length++;
28189
+ this.state.error = err;
28190
+ } else {
28191
+ const finalErr = this.__error(err);
28192
+ if (finalErr)
28193
+ return finalErr;
28194
+ }
28195
+ }
28196
+ if (skip_records_with_empty_values === true && isRecordEmpty(record)) {
28197
+ this.__resetRecord();
28198
+ return;
28199
+ }
28200
+ if (this.state.recordHasError === true) {
28201
+ this.__resetRecord();
28202
+ this.state.recordHasError = false;
28203
+ return;
28204
+ }
28205
+ this.info.records++;
28206
+ if (from === 1 || this.info.records >= from) {
28207
+ const { objname } = this.options;
28208
+ if (columns !== false) {
28209
+ const obj = {};
28210
+ for (let i = 0, l = record.length;i < l; i++) {
28211
+ if (columns[i] === undefined || columns[i].disabled)
28212
+ continue;
28213
+ if (group_columns_by_name === true && Object.hasOwn(obj, columns[i].name)) {
28214
+ if (Array.isArray(obj[columns[i].name])) {
28215
+ obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
28216
+ } else {
28217
+ obj[columns[i].name] = [obj[columns[i].name], record[i]];
28218
+ }
28219
+ } else {
28220
+ Object.defineProperty(obj, columns[i].name, {
28221
+ value: record[i],
28222
+ enumerable: true,
28223
+ writable: true,
28224
+ configurable: true
28225
+ });
28226
+ }
28227
+ }
28228
+ if (raw === true || info === true) {
28229
+ const extRecord = Object.assign({ record: obj }, raw === true ? { raw: this.state.rawBuffer.toString(encoding) } : {}, info === true ? { info: this.__infoRecord() } : {});
28230
+ const err = this.__push(objname === undefined ? extRecord : [obj[objname], extRecord], push);
28231
+ if (err) {
28232
+ return err;
28233
+ }
28234
+ } else {
28235
+ const err = this.__push(objname === undefined ? obj : [obj[objname], obj], push);
28236
+ if (err) {
28237
+ return err;
28238
+ }
28239
+ }
28240
+ } else {
28241
+ if (raw === true || info === true) {
28242
+ const extRecord = Object.assign({ record }, raw === true ? { raw: this.state.rawBuffer.toString(encoding) } : {}, info === true ? { info: this.__infoRecord() } : {});
28243
+ const err = this.__push(objname === undefined ? extRecord : [record[objname], extRecord], push);
28244
+ if (err) {
28245
+ return err;
28246
+ }
28247
+ } else {
28248
+ const err = this.__push(objname === undefined ? record : [record[objname], record], push);
28249
+ if (err) {
28250
+ return err;
28251
+ }
28252
+ }
28253
+ }
28254
+ }
28255
+ this.__resetRecord();
28256
+ },
28257
+ __firstLineToColumns: function(record) {
28258
+ const { firstLineToHeaders } = this.state;
28259
+ try {
28260
+ const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record);
28261
+ if (!Array.isArray(headers)) {
28262
+ return this.__error(new CsvError("CSV_INVALID_COLUMN_MAPPING", [
28263
+ "Invalid Column Mapping:",
28264
+ "expect an array from column function,",
28265
+ `got ${JSON.stringify(headers)}`
28266
+ ], this.options, this.__infoField(), {
28267
+ headers
28268
+ }));
28269
+ }
28270
+ const normalizedHeaders = normalize_columns_array(headers);
28271
+ this.state.expectedRecordLength = normalizedHeaders.length;
28272
+ this.options.columns = normalizedHeaders;
28273
+ this.__resetRecord();
28274
+ return;
28275
+ } catch (err) {
28276
+ return err;
28277
+ }
28278
+ },
28279
+ __resetRecord: function() {
28280
+ if (this.options.raw === true) {
28281
+ this.state.rawBuffer.reset();
28282
+ }
28283
+ this.state.error = undefined;
28284
+ this.state.record = [];
28285
+ this.state.record_length = 0;
28286
+ },
28287
+ __onField: function() {
28288
+ const { cast, encoding, rtrim, max_record_size } = this.options;
28289
+ const { enabled, wasQuoting } = this.state;
28290
+ if (enabled === false) {
28291
+ return this.__resetField();
28292
+ }
28293
+ let field = this.state.field.toString(encoding);
28294
+ if (rtrim === true && wasQuoting === false) {
28295
+ field = field.trimRight();
28296
+ }
28297
+ if (cast === true) {
28298
+ const [err, f] = this.__cast(field);
28299
+ if (err !== undefined)
28300
+ return err;
28301
+ field = f;
28302
+ }
28303
+ this.state.record.push(field);
28304
+ if (max_record_size !== 0 && typeof field === "string") {
28305
+ this.state.record_length += field.length;
28306
+ }
28307
+ this.__resetField();
28308
+ },
28309
+ __resetField: function() {
28310
+ this.state.field.reset();
28311
+ this.state.wasQuoting = false;
28312
+ },
28313
+ __push: function(record, push) {
28314
+ const { on_record } = this.options;
28315
+ if (on_record !== undefined) {
28316
+ const info = this.__infoRecord();
28317
+ try {
28318
+ record = on_record.call(null, record, info);
28319
+ } catch (err) {
28320
+ return err;
28321
+ }
28322
+ if (record === undefined || record === null) {
28323
+ return;
28324
+ }
28325
+ }
28326
+ this.info.bytes_records += this.info.bytes;
28327
+ push(record);
28328
+ },
28329
+ __cast: function(field) {
28330
+ const { columns, relax_column_count } = this.options;
28331
+ const isColumns = Array.isArray(columns);
28332
+ if (isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length) {
28333
+ return [undefined, undefined];
28334
+ }
28335
+ if (this.state.castField !== null) {
28336
+ try {
28337
+ const info = this.__infoField();
28338
+ return [undefined, this.state.castField.call(null, field, info)];
28339
+ } catch (err) {
28340
+ return [err];
28341
+ }
28342
+ }
28343
+ if (this.__isFloat(field)) {
28344
+ return [undefined, parseFloat(field)];
28345
+ } else if (this.options.cast_date !== false) {
28346
+ const info = this.__infoField();
28347
+ return [undefined, this.options.cast_date.call(null, field, info)];
28348
+ }
28349
+ return [undefined, field];
28350
+ },
28351
+ __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte) {
28352
+ if (sourceBuf[0] !== firstByte)
28353
+ return 0;
28354
+ const sourceLength = sourceBuf.length;
28355
+ for (let i = 1;i < sourceLength; i++) {
28356
+ if (sourceBuf[i] !== targetBuf[targetPos + i])
28357
+ return 0;
28358
+ }
28359
+ return sourceLength;
28360
+ },
28361
+ __isCharTrimable: function(buf, pos) {
28362
+ const { timchars, timcharFirstBytes } = this.state;
28363
+ const first = buf[pos];
28364
+ if (first === undefined || timcharFirstBytes[first] === 0)
28365
+ return 0;
28366
+ loop1:
28367
+ for (let i = 0;i < timchars.length; i++) {
28368
+ const timchar = timchars[i];
28369
+ for (let j = 0;j < timchar.length; j++) {
28370
+ if (timchar[j] !== buf[pos + j])
28371
+ continue loop1;
28372
+ }
28373
+ return timchar.length;
28374
+ }
28375
+ return 0;
28376
+ },
28377
+ __isDelimiter: function(buf, pos, chr) {
28378
+ const { delimiter, ignore_last_delimiters } = this.options;
28379
+ if (ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1) {
28380
+ return 0;
28381
+ } else if (ignore_last_delimiters !== false && typeof ignore_last_delimiters === "number" && this.state.record.length === ignore_last_delimiters - 1) {
28382
+ return 0;
28383
+ }
28384
+ loop1:
28385
+ for (let i = 0;i < delimiter.length; i++) {
28386
+ const del = delimiter[i];
28387
+ if (del[0] === chr) {
28388
+ for (let j = 1;j < del.length; j++) {
28389
+ if (del[j] !== buf[pos + j])
28390
+ continue loop1;
28391
+ }
28392
+ return del.length;
28393
+ }
28394
+ }
28395
+ return 0;
28396
+ },
28397
+ __isEscape: function(buf, pos, chr) {
28398
+ const { escape } = this.options;
28399
+ if (escape === null)
28400
+ return false;
28401
+ const l = escape.length;
28402
+ if (escape[0] === chr) {
28403
+ for (let i = 0;i < l; i++) {
28404
+ if (escape[i] !== buf[pos + i]) {
28405
+ return false;
28406
+ }
28407
+ }
28408
+ return true;
28409
+ }
28410
+ return false;
28411
+ },
28412
+ __isFloat: function(value) {
28413
+ return value - parseFloat(value) + 1 >= 0;
28414
+ },
28415
+ __isQuote: function(buf, pos) {
28416
+ const { quote } = this.options;
28417
+ if (quote === null)
28418
+ return false;
28419
+ const l = quote.length;
28420
+ for (let i = 0;i < l; i++) {
28421
+ if (quote[i] !== buf[pos + i]) {
28422
+ return false;
28423
+ }
28424
+ }
28425
+ return true;
28426
+ },
28427
+ __isRecordDelimiter: function(chr, buf, pos) {
28428
+ const { record_delimiter } = this.options;
28429
+ const recordDelimiterLength = record_delimiter.length;
28430
+ loop1:
28431
+ for (let i = 0;i < recordDelimiterLength; i++) {
28432
+ const rd = record_delimiter[i];
28433
+ const rdLength = rd.length;
28434
+ if (rd[0] !== chr) {
28435
+ continue;
28436
+ }
28437
+ for (let j = 1;j < rdLength; j++) {
28438
+ if (rd[j] !== buf[pos + j]) {
28439
+ continue loop1;
28440
+ }
28441
+ }
28442
+ return rd.length;
28443
+ }
28444
+ return 0;
28445
+ },
28446
+ __autoDiscoverRecordDelimiter: function(buf, pos) {
28447
+ const { encoding } = this.options;
28448
+ const rds = [
28449
+ Buffer.from(`\r
28450
+ `, encoding),
28451
+ Buffer.from(`
28452
+ `, encoding),
28453
+ Buffer.from("\r", encoding)
28454
+ ];
28455
+ loop:
28456
+ for (let i = 0;i < rds.length; i++) {
28457
+ const l = rds[i].length;
28458
+ for (let j = 0;j < l; j++) {
28459
+ if (rds[i][j] !== buf[pos + j]) {
28460
+ continue loop;
28461
+ }
28462
+ }
28463
+ this.options.record_delimiter.push(rds[i]);
28464
+ this.state.recordDelimiterMaxLength = rds[i].length;
28465
+ return rds[i].length;
28466
+ }
28467
+ return 0;
28468
+ },
28469
+ __error: function(msg) {
28470
+ const { encoding, raw, skip_records_with_error } = this.options;
28471
+ const err = typeof msg === "string" ? new Error(msg) : msg;
28472
+ if (skip_records_with_error) {
28473
+ this.state.recordHasError = true;
28474
+ if (this.options.on_skip !== undefined) {
28475
+ try {
28476
+ this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
28477
+ } catch (err) {
28478
+ return err;
28479
+ }
28480
+ }
28481
+ return;
28482
+ } else {
28483
+ return err;
28484
+ }
28485
+ },
28486
+ __infoDataSet: function() {
28487
+ return {
28488
+ ...this.info,
28489
+ columns: this.options.columns
28490
+ };
28491
+ },
28492
+ __infoRecord: function() {
28493
+ const { columns, raw, encoding } = this.options;
28494
+ return {
28495
+ ...this.__infoDataSet(),
28496
+ bytes_records: this.info.bytes,
28497
+ error: this.state.error,
28498
+ header: columns === true,
28499
+ index: this.state.record.length,
28500
+ raw: raw ? this.state.rawBuffer.toString(encoding) : undefined
28501
+ };
28502
+ },
28503
+ __infoField: function() {
28504
+ const { columns } = this.options;
28505
+ const isColumns = Array.isArray(columns);
28506
+ const bytes_records = this.info.bytes_records;
28507
+ return {
28508
+ ...this.__infoRecord(),
28509
+ bytes_records,
28510
+ column: isColumns === true ? columns.length > this.state.record.length ? columns[this.state.record.length].name : null : this.state.record.length,
28511
+ quoting: this.state.wasQuoting
28512
+ };
28513
+ }
28514
+ };
28515
+ };
28516
+
28517
+ // ../../node_modules/csv-parse/lib/index.js
28518
+ class Parser extends Transform {
28519
+ constructor(opts = {}) {
28520
+ super({ ...{ readableObjectMode: true }, ...opts, encoding: null });
28521
+ this.api = transform({
28522
+ on_skip: (err, chunk) => {
28523
+ this.emit("skip", err, chunk);
28524
+ },
28525
+ ...opts
28526
+ });
28527
+ this.state = this.api.state;
28528
+ this.options = this.api.options;
28529
+ this.info = this.api.info;
28530
+ }
28531
+ _transform(buf, _, callback) {
28532
+ if (this.state.stop === true) {
28533
+ return;
28534
+ }
28535
+ const err = this.api.parse(buf, false, (record) => {
28536
+ this.push(record);
28537
+ }, () => {
28538
+ this.push(null);
28539
+ this.end();
28540
+ this.on("end", this.destroy);
28541
+ });
28542
+ if (err !== undefined) {
28543
+ this.state.stop = true;
28544
+ }
28545
+ callback(err);
28546
+ }
28547
+ _flush(callback) {
28548
+ if (this.state.stop === true) {
28549
+ return;
28550
+ }
28551
+ const err = this.api.parse(undefined, true, (record) => {
28552
+ this.push(record);
28553
+ }, () => {
28554
+ this.push(null);
28555
+ this.on("end", this.destroy);
28556
+ });
28557
+ callback(err);
28558
+ }
28559
+ }
28560
+ var parse = function() {
28561
+ let data, options, callback;
28562
+ for (const i in arguments) {
28563
+ const argument = arguments[i];
28564
+ const type = typeof argument;
28565
+ if (data === undefined && (typeof argument === "string" || Buffer.isBuffer(argument))) {
28566
+ data = argument;
28567
+ } else if (options === undefined && is_object(argument)) {
28568
+ options = argument;
28569
+ } else if (callback === undefined && type === "function") {
28570
+ callback = argument;
28571
+ } else {
28572
+ throw new CsvError("CSV_INVALID_ARGUMENT", ["Invalid argument:", `got ${JSON.stringify(argument)} at index ${i}`], options || {});
28573
+ }
28574
+ }
28575
+ const parser = new Parser(options);
28576
+ if (callback) {
28577
+ const records = options === undefined || options.objname === undefined ? [] : Object.create(null);
28578
+ parser.on("readable", function() {
28579
+ let record;
28580
+ while ((record = this.read()) !== null) {
28581
+ if (options === undefined || options.objname === undefined) {
28582
+ records.push(record);
28583
+ } else {
28584
+ Object.assign(records, {
28585
+ [record[0]]: record[1]
28586
+ });
28587
+ }
28588
+ }
28589
+ });
28590
+ parser.on("error", function(err) {
28591
+ callback(err, undefined, parser.api.__infoDataSet());
28592
+ });
28593
+ parser.on("end", function() {
28594
+ callback(undefined, records, parser.api.__infoDataSet());
28595
+ });
28596
+ }
28597
+ if (data !== undefined) {
28598
+ const writer = function() {
28599
+ parser.write(data);
28600
+ parser.end();
28601
+ };
28602
+ if (typeof setImmediate === "function") {
28603
+ setImmediate(writer);
28604
+ } else {
28605
+ setTimeout(writer, 0);
28606
+ }
28607
+ }
28608
+ return parser;
28609
+ };
28610
+
28611
+ // src/transfer/permission-csv.ts
28612
+ var PART_BYTES = 1024 * 1024;
28613
+ var PART_ROWS = 5000;
28614
+ var MAX_BYTES = 1024 * 1024 * 1024;
28615
+ var MAX_PARTS = 4096;
28616
+ var CSV_PROVIDERS = {
28617
+ gitlab: {
28618
+ userMapping: { header: ["user_id", "email"], maxRows: 500000 },
28619
+ projectPermissions: { header: ["project_path", "user_id"], maxRows: 5000000 }
28620
+ }
28621
+ };
28622
+ async function* snapshotChunks(stream, signal) {
28623
+ const reader = stream.getReader();
28624
+ const cancel = () => {
28625
+ reader.cancel(signal?.reason).catch(() => {});
28626
+ };
28627
+ signal?.addEventListener("abort", cancel, { once: true });
28628
+ try {
28629
+ while (true) {
28630
+ signal?.throwIfAborted();
28631
+ const chunk = await reader.read();
28632
+ signal?.throwIfAborted();
28633
+ if (chunk.done)
28634
+ return;
28635
+ yield chunk.value;
28636
+ }
28637
+ } finally {
28638
+ signal?.removeEventListener("abort", cancel);
28639
+ await reader.cancel();
28640
+ reader.releaseLock();
28641
+ }
28642
+ }
28643
+ async function stagePermissionCsvs(provider, paths, signal) {
28644
+ const directory = await mkdtemp2(join4(tmpdir(), "sim-permissions-")).catch((error) => {
28645
+ throw new SimApiError(`Cannot stage permission CSVs: ${getErrorMessage(error)}`, 0);
28646
+ });
28647
+ const parts = [];
28648
+ const manifest = {};
28649
+ let totalBytes = 0;
28650
+ let inputBytes = 0;
28651
+ const dispose = () => rm2(directory, { recursive: true, force: true });
28652
+ try {
28653
+ for (const field of ["userMapping", "projectPermissions"]) {
28654
+ signal?.throwIfAborted();
28655
+ const path = paths[field];
28656
+ const filename = basename3(embeddedFileKey(path));
28657
+ if (!filename.trim() || filename.length > 255 || /[\p{Cc}/\\]/u.test(filename))
28658
+ throw new SimApiError("Use CSV filenames of 1–255 characters without control characters.", 0);
28659
+ const embedded = embedStore.getStore();
28660
+ if (embedded && !embedded.openFile)
28661
+ throw new SimApiError("This invocation has no machine to read from", 0);
28662
+ const snapshot = await embedded?.openFile?.(embeddedFileKey(path));
28663
+ const handle = embedded ? undefined : await open(path, constants3.O_RDONLY | constants3.O_NONBLOCK);
28664
+ let stream;
28665
+ let snapshotStream;
28666
+ try {
28667
+ const before = await handle?.stat();
28668
+ if (before && !before.isFile())
28669
+ throw new SimApiError(`${field}: use a regular CSV file.`, 0);
28670
+ const size = snapshot?.size ?? before?.size;
28671
+ if (size === undefined || !Number.isSafeInteger(size) || size <= 0 || size > MAX_BYTES - inputBytes)
28672
+ throw new SimApiError("CSV files must be nonempty and total at most 1 GiB.", 0);
28673
+ inputBytes += size;
28674
+ const readSignal = combineSignals(snapshot?.signal, signal);
28675
+ snapshotStream = await snapshot?.stream();
28676
+ stream = snapshotStream ? Readable2.from(snapshotChunks(snapshotStream, readSignal)) : handle?.createReadStream({ autoClose: false });
28677
+ if (!stream)
28678
+ throw new SimApiError(`Cannot read ${field}.`, 0);
28679
+ if (readSignal)
28680
+ addAbortSignal(readSignal, stream);
28681
+ const source = stream;
28682
+ const decode = async function* () {
28683
+ const decoder = new TextDecoder("utf-8", { fatal: true });
28684
+ const decodeText = (chunk) => {
28685
+ try {
28686
+ return decoder.decode(chunk, { stream: chunk !== undefined });
28687
+ } catch {
28688
+ throw new SimApiError(`${field}: CSV must contain valid UTF-8.`, 0);
28689
+ }
28690
+ };
28691
+ let bytes = 0;
28692
+ for await (const chunk of source) {
28693
+ signal?.throwIfAborted();
28694
+ snapshot?.signal?.throwIfAborted();
28695
+ bytes += chunk.length;
28696
+ if (bytes > size)
28697
+ throw new SimApiError(`${field}: input changed during staging.`, 0);
28698
+ for (let offset = 0;offset < chunk.length; offset += 65536) {
28699
+ readSignal?.throwIfAborted();
28700
+ yield decodeText(chunk.subarray(offset, offset + 65536));
28701
+ }
28702
+ }
28703
+ if (bytes !== size)
28704
+ throw new SimApiError(`${field}: input changed during staging.`, 0);
28705
+ yield decodeText();
28706
+ };
28707
+ const definition = CSV_PROVIDERS[provider][field];
28708
+ const header = `${definition.header.join(",")}
28709
+ `;
28710
+ let content = header;
28711
+ let partBytes = Buffer.byteLength(header);
28712
+ let partRows = 0;
28713
+ let rowCount = 0;
28714
+ const startPart = parts.length;
28715
+ const save = async () => {
28716
+ if (parts.length >= MAX_PARTS || totalBytes + partBytes > MAX_BYTES)
28717
+ throw new SimApiError("Permission import exceeds 4,096 parts or 1 GiB.", 0);
28718
+ const partPath = join4(directory, String(parts.length));
28719
+ await writeFile(partPath, content, { mode: 384, flag: "wx" });
28720
+ parts.push({ field, path: partPath });
28721
+ totalBytes += partBytes;
28722
+ };
28723
+ const parser = parse({ bom: true, skip_empty_lines: true, max_record_size: 8192 });
28724
+ const decoded = Readable2.from(decode());
28725
+ decoded.on("error", (error) => parser.destroy(error));
28726
+ decoded.pipe(parser);
28727
+ let first = true;
28728
+ try {
28729
+ const records = parser;
28730
+ for await (const row of records) {
28731
+ if (row.length !== 2 || row.some((cell) => cell.length > 4096))
28732
+ throw new SimApiError(`${field}: expected two CSV columns of at most 4,096 characters.`, 0);
28733
+ if (first && row.every((cell, index) => cell.trim() === definition.header[index])) {
28734
+ first = false;
28735
+ continue;
28736
+ }
28737
+ first = false;
28738
+ rowCount++;
28739
+ if (rowCount > definition.maxRows)
28740
+ throw new SimApiError(`${field}: exceeds ${definition.maxRows} data records.`, 0);
28741
+ const record = `${row.map((cell) => /[",\r\n]/.test(cell) ? `"${cell.replaceAll('"', '""')}"` : cell).join(",")}
28742
+ `;
28743
+ const bytes = Buffer.byteLength(record);
28744
+ if (partRows === PART_ROWS || partBytes + bytes > PART_BYTES) {
28745
+ await save();
28746
+ content = header;
28747
+ partBytes = Buffer.byteLength(header);
28748
+ partRows = 0;
28749
+ }
28750
+ content += record;
28751
+ partBytes += bytes;
28752
+ partRows++;
28753
+ }
28754
+ } finally {
28755
+ decoded.destroy();
28756
+ parser.destroy();
28757
+ }
28758
+ const after = await handle?.stat();
28759
+ if (before && after && (before.size !== after.size || before.mtimeMs !== after.mtimeMs))
28760
+ throw new SimApiError(`${field}: input changed during staging. Rerun the export.`, 0);
28761
+ if (!rowCount)
28762
+ throw new SimApiError(`${field}: at least one data record is required.`, 0);
28763
+ await save();
28764
+ manifest[field] = { filename, rowCount, parts: parts.length - startPart };
28765
+ } catch (error) {
28766
+ if (signal?.aborted || snapshot?.signal?.aborted)
28767
+ throw new SimApiError("Permission CSV upload cancelled.", 0);
28768
+ if (error instanceof CsvError)
28769
+ throw new SimApiError(`${field}: invalid CSV quoting or record length.`, 0);
28770
+ throw error;
28771
+ } finally {
28772
+ stream?.destroy();
28773
+ if (snapshotStream && !snapshotStream.locked)
28774
+ await snapshotStream.cancel();
28775
+ await handle?.close();
28776
+ await snapshot?.dispose();
28777
+ }
28778
+ }
28779
+ return { manifest, parts, dispose };
28780
+ } catch (error) {
28781
+ await dispose();
28782
+ if (error instanceof SimApiError)
28783
+ throw error;
28784
+ if (error instanceof Error && "code" in error && typeof error.code === "string")
28785
+ throw new SimApiError(`Cannot stage permission CSVs: ${error.message}`, 0);
28786
+ throw error;
28787
+ }
28788
+ }
28789
+
28790
+ // src/commands/source-permissions.ts
28791
+ function attachSourcePermissionCommands(program) {
28792
+ let parent = program;
28793
+ for (const name of ["organizations", "search", "sources", "permissions"]) {
28794
+ const child = parent.commands.find((command) => command.name() === name);
28795
+ if (!child)
28796
+ throw new Error(`Missing generated command group: ${name}`);
28797
+ parent = child;
28798
+ }
28799
+ const [command, connect] = apiCommand(parent, "upload", [
28800
+ "createSourcePermissionImport",
28801
+ "putSourcePermissionImportPart",
28802
+ "completeSourcePermissionImport"
28803
+ ]);
28804
+ command.argument("<sourceId>", "Search source identifier").description("Replace source permissions from two CSV files, uploaded in bounded parts").allowExcessArguments(false).requiredOption("--organization <id>", "Organization identifier").addOption(new Option("--provider <provider>", "Permission provider").choices(["gitlab"]).makeOptionMandatory()).requiredOption("--expected-revision <number>", "Revision read before exporting the CSVs").requiredOption("--user-mapping <path>", "Complete user mapping CSV").requiredOption("--project-permissions <path>", "Complete project permissions CSV").option("-y, --yes", "Confirm replacement of all source permissions (required)").action(async (sourceId, options) => {
28805
+ if (!options.yes)
28806
+ throw new SimApiError("This replaces all source permissions. Re-run with --yes to confirm.", 0);
28807
+ const expectedRevision = Number(options.expectedRevision);
28808
+ if (!Number.isInteger(expectedRevision) || expectedRevision <= 0 || expectedRevision >= 2147483647)
28809
+ throw new SimApiError("--expected-revision must be an integer from 1 to 2147483646.", 0);
28810
+ const { client, profile } = connect();
28811
+ const signal = profile.signal;
28812
+ const staged = await stagePermissionCsvs(options.provider, options, signal);
28813
+ const params = { organizationId: options.organization, sourceId };
28814
+ const retry = async (request) => {
28815
+ for (let attempt = 1;; attempt++) {
28816
+ signal?.throwIfAborted();
28817
+ try {
28818
+ return await request();
28819
+ } catch (error) {
28820
+ if (!(error instanceof SimApiError) || attempt >= 5 || error.code !== "RESPONSE_READ_FAILED" && error.status !== 0 && error.status !== 429 && error.status < 500)
28821
+ throw error;
28822
+ await setTimeout2(backoffWithJitter(attempt, error.retryAfterMs, { maxMs: 300000 }), undefined, { signal });
28823
+ }
28824
+ }
28825
+ };
28826
+ try {
28827
+ const started = await client.request("createSourcePermissionImport", {
28828
+ params,
28829
+ body: { provider: options.provider, expectedRevision, ...staged.manifest }
28830
+ });
28831
+ const importParams = { ...params, importId: started.data.id };
28832
+ for (const [partNumber, part] of staged.parts.entries()) {
28833
+ const content = await readFile(part.path, "utf8");
28834
+ const result = await retry(() => client.request("putSourcePermissionImportPart", {
28835
+ params: { ...importParams, partNumber: String(partNumber) },
28836
+ body: { field: part.field, content }
28837
+ }));
28838
+ if (result.data.nextPart !== partNumber + 1)
28839
+ throw new SimApiError("The server returned an unexpected upload position. Permissions were not activated.", 0);
28840
+ }
28841
+ const result = await retry(() => client.request("completeSourcePermissionImport", { params: importParams, body: {} }));
28842
+ printProtocolResult(profile.output, { sourceId, revision: result.data.revision });
28843
+ } finally {
28844
+ await staged.dispose();
28845
+ }
28846
+ });
28847
+ }
28848
+
26908
28849
  // src/telemetry/transport.ts
26909
28850
  import { spawn as spawn4 } from "node:child_process";
26910
28851
  var CAPTURE_PATH = "/i/v0/e/";
@@ -27233,6 +29174,7 @@ function buildProgram(options = {}) {
27233
29174
  attachCredentialCommands(program);
27234
29175
  attachProtocolCommands(program);
27235
29176
  attachSecretCommands(program);
29177
+ attachSourcePermissionCommands(program);
27236
29178
  program.addHelpText("after", options.helpText ?? HELP_EPILOGUE);
27237
29179
  program.addHelpText("beforeAll", ({ command }) => detectCodingAgent(env) !== undefined && command.commands.length > 0 ? AGENT_DISCOVERY_NOTE : "");
27238
29180
  refuseHelpAfterUnknownCommand(program);