@openfn/language-common 1.10.2 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -56,7 +56,8 @@ __export(src_exports, {
56
56
  source: () => source,
57
57
  sourceValue: () => sourceValue,
58
58
  splitKeys: () => splitKeys,
59
- toArray: () => toArray
59
+ toArray: () => toArray,
60
+ validate: () => validate
60
61
  });
61
62
  module.exports = __toCommonJS(src_exports);
62
63
 
@@ -93,22 +94,37 @@ __export(Adaptor_exports, {
93
94
  source: () => source,
94
95
  sourceValue: () => sourceValue,
95
96
  splitKeys: () => splitKeys,
96
- toArray: () => toArray
97
+ toArray: () => toArray,
98
+ validate: () => validate
97
99
  });
98
100
  var import_curry = __toESM(require("lodash/fp/curry.js"), 1);
99
101
  var import_fromPairs = __toESM(require("lodash/fp/fromPairs.js"), 1);
100
102
  var import_jsonpath_plus = require("jsonpath-plus");
101
103
  var import_csv_parse = require("csv-parse");
104
+ var import_node_stream2 = require("stream");
105
+ var import_undici = require("undici");
102
106
 
103
107
  // src/util.js
108
+ var import_node_stream = require("stream");
104
109
  function expandReferences(state, ...args) {
105
110
  return args.map((value) => expandReference(state, value));
106
111
  }
112
+ var isStream = (value) => {
113
+ if (value && typeof value == "object") {
114
+ if (value instanceof import_node_stream.Readable || value instanceof import_node_stream.Writable) {
115
+ return true;
116
+ }
117
+ if (value.pipeTo || value.pipe) {
118
+ return true;
119
+ }
120
+ }
121
+ return false;
122
+ };
107
123
  function expandReference(state, value) {
108
124
  if (Array.isArray(value)) {
109
125
  return value.map((v) => expandReference(state, v));
110
126
  }
111
- if (typeof value == "object" && !!value) {
127
+ if (typeof value == "object" && !!value && !isStream(value)) {
112
128
  return Object.keys(value).reduce((acc, key) => {
113
129
  return { ...acc, [key]: expandReference(state, value[key]) };
114
130
  }, {});
@@ -248,6 +264,7 @@ __export(dateFns_exports, {
248
264
  var import_date_fns = require("date-fns");
249
265
 
250
266
  // src/Adaptor.js
267
+ var schemaCache = {};
251
268
  function execute(...operations) {
252
269
  return (state) => {
253
270
  const start = Promise.resolve(state);
@@ -444,6 +461,16 @@ function chunk(array, chunkSize) {
444
461
  output.push(array.slice(i, i + chunkSize));
445
462
  return output;
446
463
  }
464
+ var getParser = (csvData, options2) => {
465
+ if (typeof csvData === "string") {
466
+ return (0, import_csv_parse.parse)(csvData, options2);
467
+ }
468
+ let stream = csvData;
469
+ if (csvData instanceof ReadableStream) {
470
+ stream = import_node_stream2.Readable.from(csvData);
471
+ }
472
+ return stream.pipe((0, import_csv_parse.parse)(options2));
473
+ };
447
474
  function parseCsv(csvData, parsingOptions = {}, callback) {
448
475
  const defaultOptions = {
449
476
  delimiter: ",",
@@ -473,22 +500,94 @@ function parseCsv(csvData, parsingOptions = {}, callback) {
473
500
  throw new Error("chunkSize must be at least 1");
474
501
  }
475
502
  let buffer = [];
476
- const parser = typeof resolvedCsvData === "string" ? (0, import_csv_parse.parse)(resolvedCsvData, options2) : resolvedCsvData.pipe((0, import_csv_parse.parse)(options2));
503
+ const parser = getParser(resolvedCsvData, options2);
477
504
  const flushBuffer = async (currentState) => {
478
505
  const nextState = callback ? await callback(currentState, buffer) : composeNextState(currentState, buffer);
479
506
  buffer = [];
480
507
  return [nextState, buffer];
481
508
  };
509
+ let result = state;
482
510
  for await (const record of parser) {
483
511
  buffer.push(record);
484
512
  if (buffer.length === options2.chunkSize) {
485
- const [nextState, nextBuffer] = await flushBuffer(state);
486
- state = nextState;
513
+ const [nextState, nextBuffer] = await flushBuffer(result);
514
+ result = nextState;
487
515
  buffer = nextBuffer;
488
516
  }
489
517
  }
490
- const [finalState] = await flushBuffer(state);
491
- return finalState;
518
+ if (buffer.length) {
519
+ [result] = await flushBuffer(result);
520
+ }
521
+ return result;
522
+ };
523
+ }
524
+ var ajvVersions = {};
525
+ var getAjvVersion = async (schema) => {
526
+ if (/^https?:\/\/json-schema.org\/draft\/2019/.test(schema)) {
527
+ if (!ajvVersions["2019"]) {
528
+ const Ajv = (await import("ajv/dist/2019.js")).default;
529
+ ajvVersions["2019"] = new Ajv();
530
+ }
531
+ return ajvVersions["2019"];
532
+ }
533
+ if (/^https?:\/\/json-schema.org\/draft\/2020/.test(schema)) {
534
+ if (!ajvVersions["2020"]) {
535
+ const Ajv = (await import("ajv/dist/2020.js")).default;
536
+ ajvVersions["2020"] = new Ajv();
537
+ }
538
+ return ajvVersions["2020"];
539
+ }
540
+ if (!ajvVersions["default"]) {
541
+ const Ajv = (await import("ajv")).default;
542
+ ajvVersions["default"] = new Ajv();
543
+ }
544
+ return ajvVersions["default"];
545
+ };
546
+ function validate(schema = "schema", data = "data") {
547
+ return async (state) => {
548
+ if (!state.validationErrors) {
549
+ state.validationErrors = [];
550
+ }
551
+ const resolvedData = resolveData();
552
+ const resolvedSchema = await resolveSchema();
553
+ const schemaId = resolvedSchema.$id || "schema";
554
+ if (!schemaCache[schemaId]) {
555
+ const ajv = await getAjvVersion(resolvedSchema.$schema);
556
+ schemaCache[schemaId] = ajv.compile(resolvedSchema);
557
+ }
558
+ const validate2 = schemaCache[schemaId];
559
+ if (!validate2(resolvedData)) {
560
+ state.validationErrors.push({
561
+ data: state.data,
562
+ errors: validate2.errors
563
+ });
564
+ }
565
+ return state;
566
+ async function resolveSchema() {
567
+ const [schemaOrUrl] = expandReferences(state, schema);
568
+ if (typeof schemaOrUrl === "string") {
569
+ try {
570
+ const url = new URL(schemaOrUrl);
571
+ const response = await (0, import_undici.request)(url);
572
+ return response.body.json();
573
+ } catch (e) {
574
+ if (e instanceof TypeError) {
575
+ return (0, import_jsonpath_plus.JSONPath)({ path: schemaOrUrl, json: state })[0];
576
+ } else {
577
+ console.error("Error fetching schema from ", schemaOrUrl);
578
+ console.error(e);
579
+ }
580
+ }
581
+ }
582
+ return schemaOrUrl;
583
+ }
584
+ function resolveData() {
585
+ const [d] = expandReferences(state, data);
586
+ if (typeof d === "string") {
587
+ return (0, import_jsonpath_plus.JSONPath)({ path: d, json: state })[0];
588
+ }
589
+ return d;
590
+ }
492
591
  };
493
592
  }
494
593
 
@@ -526,5 +625,6 @@ var src_default = Adaptor_exports;
526
625
  source,
527
626
  sourceValue,
528
627
  splitKeys,
529
- toArray
628
+ toArray,
629
+ validate
530
630
  });
package/dist/index.js CHANGED
@@ -37,22 +37,37 @@ __export(Adaptor_exports, {
37
37
  source: () => source,
38
38
  sourceValue: () => sourceValue,
39
39
  splitKeys: () => splitKeys,
40
- toArray: () => toArray
40
+ toArray: () => toArray,
41
+ validate: () => validate
41
42
  });
42
43
  import curry from "lodash/fp/curry.js";
43
44
  import fromPairs from "lodash/fp/fromPairs.js";
44
45
  import { JSONPath } from "jsonpath-plus";
45
46
  import { parse as parse2 } from "csv-parse";
47
+ import { Readable as Readable2 } from "stream";
48
+ import { request } from "undici";
46
49
 
47
50
  // src/util.js
51
+ import { Readable, Writable } from "stream";
48
52
  function expandReferences(state, ...args) {
49
53
  return args.map((value) => expandReference(state, value));
50
54
  }
55
+ var isStream = (value) => {
56
+ if (value && typeof value == "object") {
57
+ if (value instanceof Readable || value instanceof Writable) {
58
+ return true;
59
+ }
60
+ if (value.pipeTo || value.pipe) {
61
+ return true;
62
+ }
63
+ }
64
+ return false;
65
+ };
51
66
  function expandReference(state, value) {
52
67
  if (Array.isArray(value)) {
53
68
  return value.map((v) => expandReference(state, v));
54
69
  }
55
- if (typeof value == "object" && !!value) {
70
+ if (typeof value == "object" && !!value && !isStream(value)) {
56
71
  return Object.keys(value).reduce((acc, key) => {
57
72
  return { ...acc, [key]: expandReference(state, value[key]) };
58
73
  }, {});
@@ -192,6 +207,7 @@ __export(dateFns_exports, {
192
207
  import { parse, format } from "date-fns";
193
208
 
194
209
  // src/Adaptor.js
210
+ var schemaCache = {};
195
211
  function execute(...operations) {
196
212
  return (state) => {
197
213
  const start = Promise.resolve(state);
@@ -388,6 +404,16 @@ function chunk(array, chunkSize) {
388
404
  output.push(array.slice(i, i + chunkSize));
389
405
  return output;
390
406
  }
407
+ var getParser = (csvData, options2) => {
408
+ if (typeof csvData === "string") {
409
+ return parse2(csvData, options2);
410
+ }
411
+ let stream = csvData;
412
+ if (csvData instanceof ReadableStream) {
413
+ stream = Readable2.from(csvData);
414
+ }
415
+ return stream.pipe(parse2(options2));
416
+ };
391
417
  function parseCsv(csvData, parsingOptions = {}, callback) {
392
418
  const defaultOptions = {
393
419
  delimiter: ",",
@@ -417,22 +443,94 @@ function parseCsv(csvData, parsingOptions = {}, callback) {
417
443
  throw new Error("chunkSize must be at least 1");
418
444
  }
419
445
  let buffer = [];
420
- const parser = typeof resolvedCsvData === "string" ? parse2(resolvedCsvData, options2) : resolvedCsvData.pipe(parse2(options2));
446
+ const parser = getParser(resolvedCsvData, options2);
421
447
  const flushBuffer = async (currentState) => {
422
448
  const nextState = callback ? await callback(currentState, buffer) : composeNextState(currentState, buffer);
423
449
  buffer = [];
424
450
  return [nextState, buffer];
425
451
  };
452
+ let result = state;
426
453
  for await (const record of parser) {
427
454
  buffer.push(record);
428
455
  if (buffer.length === options2.chunkSize) {
429
- const [nextState, nextBuffer] = await flushBuffer(state);
430
- state = nextState;
456
+ const [nextState, nextBuffer] = await flushBuffer(result);
457
+ result = nextState;
431
458
  buffer = nextBuffer;
432
459
  }
433
460
  }
434
- const [finalState] = await flushBuffer(state);
435
- return finalState;
461
+ if (buffer.length) {
462
+ [result] = await flushBuffer(result);
463
+ }
464
+ return result;
465
+ };
466
+ }
467
+ var ajvVersions = {};
468
+ var getAjvVersion = async (schema) => {
469
+ if (/^https?:\/\/json-schema.org\/draft\/2019/.test(schema)) {
470
+ if (!ajvVersions["2019"]) {
471
+ const Ajv = (await import("ajv/dist/2019.js")).default;
472
+ ajvVersions["2019"] = new Ajv();
473
+ }
474
+ return ajvVersions["2019"];
475
+ }
476
+ if (/^https?:\/\/json-schema.org\/draft\/2020/.test(schema)) {
477
+ if (!ajvVersions["2020"]) {
478
+ const Ajv = (await import("ajv/dist/2020.js")).default;
479
+ ajvVersions["2020"] = new Ajv();
480
+ }
481
+ return ajvVersions["2020"];
482
+ }
483
+ if (!ajvVersions["default"]) {
484
+ const Ajv = (await import("ajv")).default;
485
+ ajvVersions["default"] = new Ajv();
486
+ }
487
+ return ajvVersions["default"];
488
+ };
489
+ function validate(schema = "schema", data = "data") {
490
+ return async (state) => {
491
+ if (!state.validationErrors) {
492
+ state.validationErrors = [];
493
+ }
494
+ const resolvedData = resolveData();
495
+ const resolvedSchema = await resolveSchema();
496
+ const schemaId = resolvedSchema.$id || "schema";
497
+ if (!schemaCache[schemaId]) {
498
+ const ajv = await getAjvVersion(resolvedSchema.$schema);
499
+ schemaCache[schemaId] = ajv.compile(resolvedSchema);
500
+ }
501
+ const validate2 = schemaCache[schemaId];
502
+ if (!validate2(resolvedData)) {
503
+ state.validationErrors.push({
504
+ data: state.data,
505
+ errors: validate2.errors
506
+ });
507
+ }
508
+ return state;
509
+ async function resolveSchema() {
510
+ const [schemaOrUrl] = expandReferences(state, schema);
511
+ if (typeof schemaOrUrl === "string") {
512
+ try {
513
+ const url = new URL(schemaOrUrl);
514
+ const response = await request(url);
515
+ return response.body.json();
516
+ } catch (e) {
517
+ if (e instanceof TypeError) {
518
+ return JSONPath({ path: schemaOrUrl, json: state })[0];
519
+ } else {
520
+ console.error("Error fetching schema from ", schemaOrUrl);
521
+ console.error(e);
522
+ }
523
+ }
524
+ }
525
+ return schemaOrUrl;
526
+ }
527
+ function resolveData() {
528
+ const [d] = expandReferences(state, data);
529
+ if (typeof d === "string") {
530
+ return JSONPath({ path: d, json: state })[0];
531
+ }
532
+ return d;
533
+ }
436
534
  };
437
535
  }
438
536
 
@@ -470,5 +568,6 @@ export {
470
568
  source,
471
569
  sourceValue,
472
570
  splitKeys,
473
- toArray
571
+ toArray,
572
+ validate
474
573
  };
package/dist/util.cjs CHANGED
@@ -23,14 +23,26 @@ __export(util_exports, {
23
23
  normalizeOauthConfig: () => normalizeOauthConfig
24
24
  });
25
25
  module.exports = __toCommonJS(util_exports);
26
+ var import_node_stream = require("stream");
26
27
  function expandReferences(state, ...args) {
27
28
  return args.map((value) => expandReference(state, value));
28
29
  }
30
+ var isStream = (value) => {
31
+ if (value && typeof value == "object") {
32
+ if (value instanceof import_node_stream.Readable || value instanceof import_node_stream.Writable) {
33
+ return true;
34
+ }
35
+ if (value.pipeTo || value.pipe) {
36
+ return true;
37
+ }
38
+ }
39
+ return false;
40
+ };
29
41
  function expandReference(state, value) {
30
42
  if (Array.isArray(value)) {
31
43
  return value.map((v) => expandReference(state, v));
32
44
  }
33
- if (typeof value == "object" && !!value) {
45
+ if (typeof value == "object" && !!value && !isStream(value)) {
34
46
  return Object.keys(value).reduce((acc, key) => {
35
47
  return { ...acc, [key]: expandReference(state, value[key]) };
36
48
  }, {});
package/dist/util.js CHANGED
@@ -1,12 +1,24 @@
1
1
  // src/util.js
2
+ import { Readable, Writable } from "stream";
2
3
  function expandReferences(state, ...args) {
3
4
  return args.map((value) => expandReference(state, value));
4
5
  }
6
+ var isStream = (value) => {
7
+ if (value && typeof value == "object") {
8
+ if (value instanceof Readable || value instanceof Writable) {
9
+ return true;
10
+ }
11
+ if (value.pipeTo || value.pipe) {
12
+ return true;
13
+ }
14
+ }
15
+ return false;
16
+ };
5
17
  function expandReference(state, value) {
6
18
  if (Array.isArray(value)) {
7
19
  return value.map((v) => expandReference(state, v));
8
20
  }
9
- if (typeof value == "object" && !!value) {
21
+ if (typeof value == "object" && !!value && !isStream(value)) {
10
22
  return Object.keys(value).reduce((acc, key) => {
11
23
  return { ...acc, [key]: expandReference(state, value[key]) };
12
24
  }, {});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-common",
3
- "version": "1.10.2",
3
+ "version": "1.11.0",
4
4
  "description": "Common Expressions for OpenFn",
5
5
  "homepage": "https://docs.openfn.org",
6
6
  "repository": {
@@ -33,12 +33,14 @@
33
33
  "type": "module",
34
34
  "types": "types/index.d.ts",
35
35
  "dependencies": {
36
+ "ajv": "^8.12.0",
36
37
  "axios": "1.1.3",
37
38
  "csv-parse": "^5.4.0",
38
39
  "csvtojson": "^2.0.10",
39
40
  "date-fns": "^2.25.0",
40
41
  "jsonpath-plus": "^4.0.0",
41
- "lodash": "^4.17.19"
42
+ "lodash": "^4.17.19",
43
+ "undici": "^5.22.1"
42
44
  },
43
45
  "devDependencies": {
44
46
  "@openfn/buildtools": "^1.0.2",
@@ -331,6 +331,22 @@ export function chunk(array: any, chunkSize: Integer): any;
331
331
  * @returns {Operation} The function returns a Promise that resolves to the result of parsing a CSV `stringOrStream`.
332
332
  */
333
333
  export function parseCsv(csvData: string | Stream, parsingOptions?: any, callback?: Function): Operation;
334
+ /**
335
+ * Validate against a JSON schema. Any erors are written to an array at `state.validationErrors`.
336
+ * Schema can be passed directly, loaded as a JSON path from state, or loaded from a URL
337
+ * Data can be passed directly or loaded as a JSON path from state.
338
+ * By default, schema is loaded from `state.schema` and data from `state.data`.
339
+ * @param {string|object} schema - The schema, path or URL to validate against
340
+ * @param {string|object} data - The data or path to validate
341
+ * @example <caption>Validate `state.data` with `state.schema`</caption>
342
+ * validate()
343
+ * @example <caption>Validate form data at `state.form` with a schema from a URL</caption>
344
+ * validate("https://www.example.com/schema/record", "form")
345
+ * @example <caption>Validate the each item in `state.records` with a schema from a URL</caption>
346
+ * each("records[*]", validate("https://www.example.com/schema/record"))
347
+ * @returns {Operation}
348
+ */
349
+ export function validate(schema?: string | object, data?: string | object): Operation;
334
350
  export * as beta from "./beta";
335
351
  export * as http from "./http";
336
352
  export * as dateFns from "./dateFns";