@openfn/language-common 1.11.1 → 1.13.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/ast.json CHANGED
@@ -1312,6 +1312,83 @@
1312
1312
  },
1313
1313
  "valid": true
1314
1314
  },
1315
+ {
1316
+ "name": "cursor",
1317
+ "params": [
1318
+ "value",
1319
+ "options"
1320
+ ],
1321
+ "docs": {
1322
+ "description": "Sets a cursor property on state.\nSupports natural language dates like `now`, `today`, `yesterday`, `n hours ago`, `n days ago`, and `start`,\nwhich will be converted relative to the environment (ie, the Lightning or CLI locale). Custom timezones \nare not yet supported.\nSee the usage guide at @{link https://docs.openfn.org/documentation/jobs/job-writing-guide#using-cursors}",
1323
+ "tags": [
1324
+ {
1325
+ "title": "public",
1326
+ "description": null,
1327
+ "type": null
1328
+ },
1329
+ {
1330
+ "title": "example",
1331
+ "description": "cursor($.cursor, { defaultValue: 'today' })",
1332
+ "caption": "Use a cursor from state if present, or else use the default value"
1333
+ },
1334
+ {
1335
+ "title": "example",
1336
+ "description": "cursor(22)",
1337
+ "caption": "Use a pagination cursor"
1338
+ },
1339
+ {
1340
+ "title": "function",
1341
+ "description": null,
1342
+ "name": null
1343
+ },
1344
+ {
1345
+ "title": "param",
1346
+ "description": "the cursor value. Usually an ISO date, natural language date, or page number",
1347
+ "type": {
1348
+ "type": "NameExpression",
1349
+ "name": "any"
1350
+ },
1351
+ "name": "value"
1352
+ },
1353
+ {
1354
+ "title": "param",
1355
+ "description": "options to control the cursor.",
1356
+ "type": {
1357
+ "type": "NameExpression",
1358
+ "name": "object"
1359
+ },
1360
+ "name": "options"
1361
+ },
1362
+ {
1363
+ "title": "param",
1364
+ "description": "set the cursor key. Will persist through the whole run.",
1365
+ "type": {
1366
+ "type": "NameExpression",
1367
+ "name": "string"
1368
+ },
1369
+ "name": "options.key"
1370
+ },
1371
+ {
1372
+ "title": "param",
1373
+ "description": "the value to use if value is falsy",
1374
+ "type": {
1375
+ "type": "NameExpression",
1376
+ "name": "any"
1377
+ },
1378
+ "name": "options.defaultValue"
1379
+ },
1380
+ {
1381
+ "title": "returns",
1382
+ "description": null,
1383
+ "type": {
1384
+ "type": "NameExpression",
1385
+ "name": "Operation"
1386
+ }
1387
+ }
1388
+ ]
1389
+ },
1390
+ "valid": false
1391
+ },
1315
1392
  {
1316
1393
  "name": "map",
1317
1394
  "params": [
package/dist/index.cjs CHANGED
@@ -32,6 +32,7 @@ __export(src_exports, {
32
32
  chunk: () => chunk,
33
33
  combine: () => combine,
34
34
  composeNextState: () => composeNextState,
35
+ cursor: () => cursor,
35
36
  dataPath: () => dataPath,
36
37
  dataValue: () => dataValue,
37
38
  dateFns: () => dateFns_exports,
@@ -42,7 +43,7 @@ __export(src_exports, {
42
43
  field: () => field,
43
44
  fields: () => fields,
44
45
  fn: () => fn,
45
- http: () => http_exports,
46
+ http: () => http_deprecated_exports,
46
47
  humanProper: () => humanProper,
47
48
  index: () => index,
48
49
  join: () => join,
@@ -71,6 +72,7 @@ __export(Adaptor_exports, {
71
72
  chunk: () => chunk,
72
73
  combine: () => combine,
73
74
  composeNextState: () => composeNextState,
75
+ cursor: () => cursor,
74
76
  dataPath: () => dataPath,
75
77
  dataValue: () => dataValue,
76
78
  dateFns: () => dateFns_exports,
@@ -80,7 +82,7 @@ __export(Adaptor_exports, {
80
82
  field: () => field,
81
83
  fields: () => fields,
82
84
  fn: () => fn,
83
- http: () => http_exports,
85
+ http: () => http_deprecated_exports,
84
86
  humanProper: () => humanProper,
85
87
  index: () => index,
86
88
  join: () => join,
@@ -101,17 +103,23 @@ var import_curry = __toESM(require("lodash/fp/curry.js"), 1);
101
103
  var import_fromPairs = __toESM(require("lodash/fp/fromPairs.js"), 1);
102
104
  var import_jsonpath_plus = require("jsonpath-plus");
103
105
  var import_csv_parse = require("csv-parse");
104
- var import_node_stream2 = require("stream");
105
- var import_undici = require("undici");
106
+ var import_node_stream3 = require("stream");
107
+ var import_undici2 = require("undici");
108
+ var import_date_fns3 = require("date-fns");
106
109
 
107
- // src/util.js
110
+ // src/util/http.js
111
+ var import_undici = require("undici");
112
+ var import_http_status_codes = require("http-status-codes");
108
113
  var import_node_stream = require("stream");
114
+
115
+ // src/util/references.js
116
+ var import_node_stream2 = require("stream");
109
117
  function expandReferences(state, ...args) {
110
118
  return args.map((value) => expandReference(state, value));
111
119
  }
112
120
  var isStream = (value) => {
113
121
  if (value && typeof value == "object") {
114
- if (value instanceof import_node_stream.Readable || value instanceof import_node_stream.Writable) {
122
+ if (value instanceof import_node_stream2.Readable || value instanceof import_node_stream2.Writable) {
115
123
  return true;
116
124
  }
117
125
  if (value.pipeTo || value.pipe) {
@@ -138,6 +146,32 @@ function expandReference(state, value) {
138
146
  return value;
139
147
  }
140
148
 
149
+ // src/util/parse-date.js
150
+ var import_date_fns = require("date-fns");
151
+ var parse_date_default = (d, startDate) => {
152
+ try {
153
+ if (d === "start") {
154
+ return startDate;
155
+ } else if (d === "now" || d === "end") {
156
+ return new Date();
157
+ } else if (d === "today") {
158
+ return (0, import_date_fns.startOfToday)();
159
+ } else if (d === "yesterday") {
160
+ return (0, import_date_fns.startOfYesterday)();
161
+ } else if (/(hours? ago)$/.test(d)) {
162
+ const [diff] = d.match(/\d+/);
163
+ return (0, import_date_fns.subHours)(new Date(), diff);
164
+ } else if (/(days? ago)$/.test(d)) {
165
+ const [diff] = d.match(/\d+/);
166
+ return (0, import_date_fns.startOfDay)((0, import_date_fns.subDays)(new Date(), diff));
167
+ }
168
+ } catch (e) {
169
+ console.log(`Error converting ${d} into a date`);
170
+ console.log(e);
171
+ }
172
+ return d;
173
+ };
174
+
141
175
  // src/beta.js
142
176
  var beta_exports = {};
143
177
  __export(beta_exports, {
@@ -169,9 +203,9 @@ function each(dataSource, operation) {
169
203
  };
170
204
  }
171
205
 
172
- // src/http.js
173
- var http_exports = {};
174
- __export(http_exports, {
206
+ // src/http.deprecated.js
207
+ var http_deprecated_exports = {};
208
+ __export(http_deprecated_exports, {
175
209
  axios: () => import_axios.default,
176
210
  delete: () => del,
177
211
  expandRequestReferences: () => expandRequestReferences,
@@ -184,6 +218,13 @@ __export(http_exports, {
184
218
  });
185
219
  var import_axios = __toESM(require("axios"), 1);
186
220
  var import_https = __toESM(require("https"), 1);
221
+ var printDeprecationNotice = (name) => {
222
+ if (process.env.NODE_ENV !== "production") {
223
+ console.warn(
224
+ `The common.http.${name} function has been deprecated. This adaptor should migrate to use common.util.http instead.`
225
+ );
226
+ }
227
+ };
187
228
  function expandRequestReferences(params) {
188
229
  const [toKeep, toExpand] = splitKeys(params || {}, [
189
230
  "agentOptions",
@@ -217,42 +258,49 @@ function withAgent(params) {
217
258
  }
218
259
  function get(requestParams) {
219
260
  return (state) => {
261
+ printDeprecationNotice("get");
220
262
  const params = expandRequestReferences(requestParams)(state);
221
263
  return (0, import_axios.default)({ method: "get", ...withAgent(params) });
222
264
  };
223
265
  }
224
266
  function post(requestParams) {
225
267
  return (state) => {
268
+ printDeprecationNotice("post");
226
269
  const params = expandRequestReferences(requestParams)(state);
227
270
  return (0, import_axios.default)({ method: "post", ...withAgent(params) });
228
271
  };
229
272
  }
230
273
  function del(requestParams) {
231
274
  return (state) => {
275
+ printDeprecationNotice("del");
232
276
  const params = expandRequestReferences(requestParams)(state);
233
277
  return (0, import_axios.default)({ method: "delete", ...withAgent(params) });
234
278
  };
235
279
  }
236
280
  function head(requestParams) {
237
281
  return (state) => {
282
+ printDeprecationNotice("head");
238
283
  const params = expandRequestReferences(requestParams)(state);
239
284
  return (0, import_axios.default)({ method: "head", ...withAgent(params) });
240
285
  };
241
286
  }
242
287
  function put(requestParams) {
243
288
  return (state) => {
289
+ printDeprecationNotice("put");
244
290
  const params = expandRequestReferences(requestParams)(state);
245
291
  return (0, import_axios.default)({ method: "put", ...withAgent(params) });
246
292
  };
247
293
  }
248
294
  function patch(requestParams) {
249
295
  return (state) => {
296
+ printDeprecationNotice("patch");
250
297
  const params = expandRequestReferences(requestParams)(state);
251
298
  return (0, import_axios.default)({ method: "patch", ...withAgent(params) });
252
299
  };
253
300
  }
254
301
  function options(requestParams) {
255
302
  return (state) => {
303
+ printDeprecationNotice("options");
256
304
  const params = expandRequestReferences(requestParams)(state);
257
305
  return (0, import_axios.default)({ method: "options", ...withAgent(params) });
258
306
  };
@@ -261,10 +309,10 @@ function options(requestParams) {
261
309
  // src/dateFns.js
262
310
  var dateFns_exports = {};
263
311
  __export(dateFns_exports, {
264
- format: () => import_date_fns.format,
265
- parse: () => import_date_fns.parse
312
+ format: () => import_date_fns2.format,
313
+ parse: () => import_date_fns2.parse
266
314
  });
267
- var import_date_fns = require("date-fns");
315
+ var import_date_fns2 = require("date-fns");
268
316
 
269
317
  // src/Adaptor.js
270
318
  var schemaCache = {};
@@ -470,7 +518,7 @@ var getParser = (csvData, options2) => {
470
518
  }
471
519
  let stream = csvData;
472
520
  if (csvData instanceof ReadableStream) {
473
- stream = import_node_stream2.Readable.from(csvData);
521
+ stream = import_node_stream3.Readable.from(csvData);
474
522
  }
475
523
  return stream.pipe((0, import_csv_parse.parse)(options2));
476
524
  };
@@ -571,7 +619,7 @@ function validate(schema = "schema", data = "data") {
571
619
  if (typeof schemaOrUrl === "string") {
572
620
  try {
573
621
  const url = new URL(schemaOrUrl);
574
- const response = await (0, import_undici.request)(url);
622
+ const response = await (0, import_undici2.request)(url);
575
623
  return response.body.json();
576
624
  } catch (e) {
577
625
  if (e instanceof TypeError) {
@@ -593,6 +641,36 @@ function validate(schema = "schema", data = "data") {
593
641
  }
594
642
  };
595
643
  }
644
+ var cursorStart = void 0;
645
+ var cursorKey = "cursor";
646
+ function cursor(value, options2 = {}) {
647
+ return (state) => {
648
+ const [resolvedValue, resolvedOptions] = expandReferences(state, value, options2);
649
+ const {
650
+ defaultValue,
651
+ key
652
+ } = resolvedOptions;
653
+ if (key) {
654
+ cursorKey = key;
655
+ }
656
+ if (!cursorStart) {
657
+ cursorStart = new Date();
658
+ }
659
+ const cursor2 = resolvedValue ?? defaultValue;
660
+ if (typeof cursor2 === "string") {
661
+ const date = parse_date_default(cursor2, cursorStart);
662
+ if (date instanceof Date && date.toString !== "Invalid Date") {
663
+ state[cursorKey] = date.toISOString();
664
+ const formatted = (0, import_date_fns3.format)(date, "HH:MM d MMM yyyy (OOO)");
665
+ console.log(`Setting cursor "${cursor2}" to: ${formatted}`);
666
+ return state;
667
+ }
668
+ }
669
+ state[cursorKey] = cursor2;
670
+ console.log("Setting cursor to:", cursor2);
671
+ return state;
672
+ };
673
+ }
596
674
 
597
675
  // src/index.js
598
676
  var src_default = Adaptor_exports;
@@ -605,6 +683,7 @@ var src_default = Adaptor_exports;
605
683
  chunk,
606
684
  combine,
607
685
  composeNextState,
686
+ cursor,
608
687
  dataPath,
609
688
  dataValue,
610
689
  dateFns,
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ __export(Adaptor_exports, {
14
14
  chunk: () => chunk,
15
15
  combine: () => combine,
16
16
  composeNextState: () => composeNextState,
17
+ cursor: () => cursor,
17
18
  dataPath: () => dataPath,
18
19
  dataValue: () => dataValue,
19
20
  dateFns: () => dateFns_exports,
@@ -23,7 +24,7 @@ __export(Adaptor_exports, {
23
24
  field: () => field,
24
25
  fields: () => fields,
25
26
  fn: () => fn,
26
- http: () => http_exports,
27
+ http: () => http_deprecated_exports,
27
28
  humanProper: () => humanProper,
28
29
  index: () => index,
29
30
  join: () => join,
@@ -46,8 +47,13 @@ import { JSONPath } from "jsonpath-plus";
46
47
  import { parse as parse2 } from "csv-parse";
47
48
  import { Readable as Readable2 } from "stream";
48
49
  import { request } from "undici";
50
+ import { format as format2 } from "date-fns";
49
51
 
50
- // src/util.js
52
+ // src/util/http.js
53
+ import { Client, MockAgent } from "undici";
54
+ import { getReasonPhrase } from "http-status-codes";
55
+
56
+ // src/util/references.js
51
57
  import { Readable, Writable } from "stream";
52
58
  function expandReferences(state, ...args) {
53
59
  return args.map((value) => expandReference(state, value));
@@ -81,6 +87,32 @@ function expandReference(state, value) {
81
87
  return value;
82
88
  }
83
89
 
90
+ // src/util/parse-date.js
91
+ import { startOfToday, startOfYesterday, subHours, subDays, startOfDay } from "date-fns";
92
+ var parse_date_default = (d, startDate) => {
93
+ try {
94
+ if (d === "start") {
95
+ return startDate;
96
+ } else if (d === "now" || d === "end") {
97
+ return new Date();
98
+ } else if (d === "today") {
99
+ return startOfToday();
100
+ } else if (d === "yesterday") {
101
+ return startOfYesterday();
102
+ } else if (/(hours? ago)$/.test(d)) {
103
+ const [diff] = d.match(/\d+/);
104
+ return subHours(new Date(), diff);
105
+ } else if (/(days? ago)$/.test(d)) {
106
+ const [diff] = d.match(/\d+/);
107
+ return startOfDay(subDays(new Date(), diff));
108
+ }
109
+ } catch (e) {
110
+ console.log(`Error converting ${d} into a date`);
111
+ console.log(e);
112
+ }
113
+ return d;
114
+ };
115
+
84
116
  // src/beta.js
85
117
  var beta_exports = {};
86
118
  __export(beta_exports, {
@@ -112,9 +144,9 @@ function each(dataSource, operation) {
112
144
  };
113
145
  }
114
146
 
115
- // src/http.js
116
- var http_exports = {};
117
- __export(http_exports, {
147
+ // src/http.deprecated.js
148
+ var http_deprecated_exports = {};
149
+ __export(http_deprecated_exports, {
118
150
  axios: () => axios,
119
151
  delete: () => del,
120
152
  expandRequestReferences: () => expandRequestReferences,
@@ -127,6 +159,13 @@ __export(http_exports, {
127
159
  });
128
160
  import axios from "axios";
129
161
  import https from "https";
162
+ var printDeprecationNotice = (name) => {
163
+ if (process.env.NODE_ENV !== "production") {
164
+ console.warn(
165
+ `The common.http.${name} function has been deprecated. This adaptor should migrate to use common.util.http instead.`
166
+ );
167
+ }
168
+ };
130
169
  function expandRequestReferences(params) {
131
170
  const [toKeep, toExpand] = splitKeys(params || {}, [
132
171
  "agentOptions",
@@ -160,42 +199,49 @@ function withAgent(params) {
160
199
  }
161
200
  function get(requestParams) {
162
201
  return (state) => {
202
+ printDeprecationNotice("get");
163
203
  const params = expandRequestReferences(requestParams)(state);
164
204
  return axios({ method: "get", ...withAgent(params) });
165
205
  };
166
206
  }
167
207
  function post(requestParams) {
168
208
  return (state) => {
209
+ printDeprecationNotice("post");
169
210
  const params = expandRequestReferences(requestParams)(state);
170
211
  return axios({ method: "post", ...withAgent(params) });
171
212
  };
172
213
  }
173
214
  function del(requestParams) {
174
215
  return (state) => {
216
+ printDeprecationNotice("del");
175
217
  const params = expandRequestReferences(requestParams)(state);
176
218
  return axios({ method: "delete", ...withAgent(params) });
177
219
  };
178
220
  }
179
221
  function head(requestParams) {
180
222
  return (state) => {
223
+ printDeprecationNotice("head");
181
224
  const params = expandRequestReferences(requestParams)(state);
182
225
  return axios({ method: "head", ...withAgent(params) });
183
226
  };
184
227
  }
185
228
  function put(requestParams) {
186
229
  return (state) => {
230
+ printDeprecationNotice("put");
187
231
  const params = expandRequestReferences(requestParams)(state);
188
232
  return axios({ method: "put", ...withAgent(params) });
189
233
  };
190
234
  }
191
235
  function patch(requestParams) {
192
236
  return (state) => {
237
+ printDeprecationNotice("patch");
193
238
  const params = expandRequestReferences(requestParams)(state);
194
239
  return axios({ method: "patch", ...withAgent(params) });
195
240
  };
196
241
  }
197
242
  function options(requestParams) {
198
243
  return (state) => {
244
+ printDeprecationNotice("options");
199
245
  const params = expandRequestReferences(requestParams)(state);
200
246
  return axios({ method: "options", ...withAgent(params) });
201
247
  };
@@ -536,6 +582,36 @@ function validate(schema = "schema", data = "data") {
536
582
  }
537
583
  };
538
584
  }
585
+ var cursorStart = void 0;
586
+ var cursorKey = "cursor";
587
+ function cursor(value, options2 = {}) {
588
+ return (state) => {
589
+ const [resolvedValue, resolvedOptions] = expandReferences(state, value, options2);
590
+ const {
591
+ defaultValue,
592
+ key
593
+ } = resolvedOptions;
594
+ if (key) {
595
+ cursorKey = key;
596
+ }
597
+ if (!cursorStart) {
598
+ cursorStart = new Date();
599
+ }
600
+ const cursor2 = resolvedValue ?? defaultValue;
601
+ if (typeof cursor2 === "string") {
602
+ const date = parse_date_default(cursor2, cursorStart);
603
+ if (date instanceof Date && date.toString !== "Invalid Date") {
604
+ state[cursorKey] = date.toISOString();
605
+ const formatted = format2(date, "HH:MM d MMM yyyy (OOO)");
606
+ console.log(`Setting cursor "${cursor2}" to: ${formatted}`);
607
+ return state;
608
+ }
609
+ }
610
+ state[cursorKey] = cursor2;
611
+ console.log("Setting cursor to:", cursor2);
612
+ return state;
613
+ };
614
+ }
539
615
 
540
616
  // src/index.js
541
617
  var src_default = Adaptor_exports;
@@ -547,6 +623,7 @@ export {
547
623
  chunk,
548
624
  combine,
549
625
  composeNextState,
626
+ cursor,
550
627
  dataPath,
551
628
  dataValue,
552
629
  dateFns_exports as dateFns,
@@ -557,7 +634,7 @@ export {
557
634
  field,
558
635
  fields,
559
636
  fn,
560
- http_exports as http,
637
+ http_deprecated_exports as http,
561
638
  humanProper,
562
639
  index,
563
640
  join,
package/dist/metadata.cjs CHANGED
@@ -32,7 +32,7 @@ var createEntity = (name, type, props = {}, children) => {
32
32
  this.children = name2 ? {} : [];
33
33
  }
34
34
  if (name2) {
35
- if (isArray(this.children)) {
35
+ if (Array.isArray(this.children)) {
36
36
  throw new Error("Cannot add a named entity to child array");
37
37
  }
38
38
  this.children[name2] = e2;
package/dist/metadata.js CHANGED
@@ -9,7 +9,7 @@ var createEntity = (name, type, props = {}, children) => {
9
9
  this.children = name2 ? {} : [];
10
10
  }
11
11
  if (name2) {
12
- if (isArray(this.children)) {
12
+ if (Array.isArray(this.children)) {
13
13
  throw new Error("Cannot add a named entity to child array");
14
14
  }
15
15
  this.children[name2] = e2;
package/dist/util.cjs CHANGED
@@ -16,20 +16,182 @@ var __copyProps = (to, from, except, desc) => {
16
16
  };
17
17
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
18
 
19
- // src/util.js
19
+ // src/util/index.js
20
20
  var util_exports = {};
21
21
  __export(util_exports, {
22
+ del: () => del,
23
+ enableMockClient: () => enableMockClient,
22
24
  expandReferences: () => expandReferences,
23
- normalizeOauthConfig: () => normalizeOauthConfig
25
+ get: () => get,
26
+ logResponse: () => logResponse,
27
+ makeBasicAuthHeader: () => makeBasicAuthHeader,
28
+ normalizeOauthConfig: () => normalizeOauthConfig,
29
+ parseDate: () => parse_date_default,
30
+ parseUrl: () => parseUrl,
31
+ post: () => post,
32
+ put: () => put,
33
+ request: () => request
24
34
  });
25
35
  module.exports = __toCommonJS(util_exports);
36
+
37
+ // src/util/http.js
38
+ var import_undici = require("undici");
39
+ var import_http_status_codes = require("http-status-codes");
26
40
  var import_node_stream = require("stream");
41
+ var clients = /* @__PURE__ */ new Map();
42
+ var makeBasicAuthHeader = (username, password) => {
43
+ const buff = Buffer.from(`${username}:${password}`);
44
+ const credentials = buff.toString("base64");
45
+ return { Authorization: `Basic ${credentials}` };
46
+ };
47
+ var logResponse = (response) => {
48
+ const { method, url, statusCode, duration } = response;
49
+ if (method && url && duration && statusCode) {
50
+ const message = `${method} ${url} - ${statusCode} in ${duration}ms`;
51
+ if (response instanceof Error) {
52
+ console.error(message);
53
+ console.error("response body: ");
54
+ console.error(response.body || "[no body]");
55
+ } else {
56
+ console.log(message);
57
+ }
58
+ }
59
+ return response;
60
+ };
61
+ var getClient = (baseUrl, options) => {
62
+ const { tls } = options;
63
+ if (!clients.has(baseUrl)) {
64
+ clients.set(baseUrl, new import_undici.Client(baseUrl, { connect: tls }));
65
+ }
66
+ return clients.get(baseUrl);
67
+ };
68
+ var enableMockClient = (baseUrl) => {
69
+ const mockAgent = new import_undici.MockAgent({ connections: 1 });
70
+ const client = mockAgent.get(baseUrl);
71
+ if (!clients.has(baseUrl)) {
72
+ clients.set(baseUrl, client);
73
+ }
74
+ return client;
75
+ };
76
+ var assertOK = async (response, errorMap, fullUrl, method, startTime) => {
77
+ const errMapMessage = errorMap[response.statusCode];
78
+ const isError = typeof errMapMessage === "boolean" ? errMapMessage : errMapMessage || response.statusCode >= 400;
79
+ if (isError) {
80
+ const body = await readResponseBody(response);
81
+ const statusText = (0, import_http_status_codes.getReasonPhrase)(response.statusCode);
82
+ const defaultErrorMesssage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
83
+ const duration = Date.now() - startTime;
84
+ const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMesssage;
85
+ const error = new Error(errMessage);
86
+ error.statusCode = response.statusCode;
87
+ error.statusMessage = statusText;
88
+ error.url = fullUrl;
89
+ error.duration = duration;
90
+ error.method = method;
91
+ error.body = body;
92
+ error.headers = response.headers;
93
+ throw error;
94
+ }
95
+ };
96
+ var parseUrl = (pathOrUrl = "", baseUrl) => {
97
+ let fullUrl;
98
+ if (/https?:\/\//.test(pathOrUrl)) {
99
+ fullUrl = pathOrUrl;
100
+ } else if (baseUrl) {
101
+ const base = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
102
+ const path = pathOrUrl.startsWith("/") ? pathOrUrl.substring(1) : pathOrUrl;
103
+ fullUrl = base + path;
104
+ } else {
105
+ new URL(pathOrUrl);
106
+ }
107
+ const url = new URL(fullUrl);
108
+ return {
109
+ url: url.toString(),
110
+ baseUrl: url.origin,
111
+ path: url.pathname
112
+ };
113
+ };
114
+ async function request(method, fullUrlOrPath, options = {}) {
115
+ const startTime = Date.now();
116
+ const { url, baseUrl, path } = parseUrl(fullUrlOrPath, options.baseUrl);
117
+ const {
118
+ headers = {},
119
+ query = {},
120
+ body,
121
+ errors = {},
122
+ timeout = 3e5,
123
+ tls = {},
124
+ parseAs = "auto",
125
+ maxRedirections
126
+ } = options;
127
+ const client = getClient(baseUrl, { tls });
128
+ const response = await client.request({
129
+ path,
130
+ query,
131
+ method,
132
+ headers,
133
+ body: encodeRequestBody(body),
134
+ throwOnError: false,
135
+ maxRedirections,
136
+ bodyTimeout: timeout,
137
+ headersTimeout: timeout
138
+ });
139
+ const statusText = (0, import_http_status_codes.getReasonPhrase)(response.statusCode);
140
+ await assertOK(response, errors, url, method, startTime);
141
+ const responseBody = await readResponseBody(response, parseAs);
142
+ const endTime = Date.now();
143
+ const duration = endTime - startTime;
144
+ return {
145
+ url,
146
+ method,
147
+ statusCode: response.statusCode,
148
+ statusMessage: statusText,
149
+ headers: response.headers,
150
+ body: responseBody,
151
+ duration
152
+ };
153
+ }
154
+ function encodeRequestBody(body) {
155
+ if (!body) {
156
+ return void 0;
157
+ }
158
+ if (Buffer.isBuffer(body) || body instanceof import_node_stream.Readable || typeof body === "string") {
159
+ return body;
160
+ }
161
+ if (typeof body === "object") {
162
+ if (Symbol.asyncIterator in Object(body) || Symbol.iterator in Object(body) || body instanceof FormData) {
163
+ return body;
164
+ }
165
+ return JSON.stringify(body);
166
+ }
167
+ throw new Error("Unsupported body type");
168
+ }
169
+ async function readResponseBody(response, parseAs) {
170
+ const contentType = response.headers["content-type"];
171
+ switch (parseAs) {
172
+ case "json":
173
+ return response.body.json();
174
+ case "text":
175
+ return response.body.text();
176
+ case "stream":
177
+ return response.body;
178
+ default:
179
+ return contentType && contentType.includes("application/json") ? response.body.json() : response.body.text();
180
+ }
181
+ }
182
+ var get = (url, options) => request("GET", url, options);
183
+ var post = (url, body, options) => request("POST", url, { body, ...options });
184
+ var put = (url, body, options) => request("PUT", url, { body, ...options });
185
+ var del = (url, body, options) => request("DELETE", url, { body, ...options });
186
+
187
+ // src/util/references.js
188
+ var import_node_stream2 = require("stream");
27
189
  function expandReferences(state, ...args) {
28
190
  return args.map((value) => expandReference(state, value));
29
191
  }
30
192
  var isStream = (value) => {
31
193
  if (value && typeof value == "object") {
32
- if (value instanceof import_node_stream.Readable || value instanceof import_node_stream.Writable) {
194
+ if (value instanceof import_node_stream2.Readable || value instanceof import_node_stream2.Writable) {
33
195
  return true;
34
196
  }
35
197
  if (value.pipeTo || value.pipe) {
@@ -71,8 +233,44 @@ function normalizeOauthConfig(configuration) {
71
233
  console.log('Using "accessToken" from state.configuration');
72
234
  return configuration;
73
235
  }
236
+
237
+ // src/util/parse-date.js
238
+ var import_date_fns = require("date-fns");
239
+ var parse_date_default = (d, startDate) => {
240
+ try {
241
+ if (d === "start") {
242
+ return startDate;
243
+ } else if (d === "now" || d === "end") {
244
+ return new Date();
245
+ } else if (d === "today") {
246
+ return (0, import_date_fns.startOfToday)();
247
+ } else if (d === "yesterday") {
248
+ return (0, import_date_fns.startOfYesterday)();
249
+ } else if (/(hours? ago)$/.test(d)) {
250
+ const [diff] = d.match(/\d+/);
251
+ return (0, import_date_fns.subHours)(new Date(), diff);
252
+ } else if (/(days? ago)$/.test(d)) {
253
+ const [diff] = d.match(/\d+/);
254
+ return (0, import_date_fns.startOfDay)((0, import_date_fns.subDays)(new Date(), diff));
255
+ }
256
+ } catch (e) {
257
+ console.log(`Error converting ${d} into a date`);
258
+ console.log(e);
259
+ }
260
+ return d;
261
+ };
74
262
  // Annotate the CommonJS export names for ESM import in node:
75
263
  0 && (module.exports = {
264
+ del,
265
+ enableMockClient,
76
266
  expandReferences,
77
- normalizeOauthConfig
267
+ get,
268
+ logResponse,
269
+ makeBasicAuthHeader,
270
+ normalizeOauthConfig,
271
+ parseDate,
272
+ parseUrl,
273
+ post,
274
+ put,
275
+ request
78
276
  });
package/dist/util.js CHANGED
@@ -1,11 +1,161 @@
1
- // src/util.js
2
- import { Readable, Writable } from "stream";
1
+ // src/util/http.js
2
+ import { Client, MockAgent } from "undici";
3
+ import { getReasonPhrase } from "http-status-codes";
4
+ import { Readable } from "stream";
5
+ var clients = /* @__PURE__ */ new Map();
6
+ var makeBasicAuthHeader = (username, password) => {
7
+ const buff = Buffer.from(`${username}:${password}`);
8
+ const credentials = buff.toString("base64");
9
+ return { Authorization: `Basic ${credentials}` };
10
+ };
11
+ var logResponse = (response) => {
12
+ const { method, url, statusCode, duration } = response;
13
+ if (method && url && duration && statusCode) {
14
+ const message = `${method} ${url} - ${statusCode} in ${duration}ms`;
15
+ if (response instanceof Error) {
16
+ console.error(message);
17
+ console.error("response body: ");
18
+ console.error(response.body || "[no body]");
19
+ } else {
20
+ console.log(message);
21
+ }
22
+ }
23
+ return response;
24
+ };
25
+ var getClient = (baseUrl, options) => {
26
+ const { tls } = options;
27
+ if (!clients.has(baseUrl)) {
28
+ clients.set(baseUrl, new Client(baseUrl, { connect: tls }));
29
+ }
30
+ return clients.get(baseUrl);
31
+ };
32
+ var enableMockClient = (baseUrl) => {
33
+ const mockAgent = new MockAgent({ connections: 1 });
34
+ const client = mockAgent.get(baseUrl);
35
+ if (!clients.has(baseUrl)) {
36
+ clients.set(baseUrl, client);
37
+ }
38
+ return client;
39
+ };
40
+ var assertOK = async (response, errorMap, fullUrl, method, startTime) => {
41
+ const errMapMessage = errorMap[response.statusCode];
42
+ const isError = typeof errMapMessage === "boolean" ? errMapMessage : errMapMessage || response.statusCode >= 400;
43
+ if (isError) {
44
+ const body = await readResponseBody(response);
45
+ const statusText = getReasonPhrase(response.statusCode);
46
+ const defaultErrorMesssage = `${method} to ${fullUrl} returned ${response.statusCode}: ${statusText}`;
47
+ const duration = Date.now() - startTime;
48
+ const errMessage = typeof errMapMessage === "function" ? errMapMessage(response) : errMapMessage || defaultErrorMesssage;
49
+ const error = new Error(errMessage);
50
+ error.statusCode = response.statusCode;
51
+ error.statusMessage = statusText;
52
+ error.url = fullUrl;
53
+ error.duration = duration;
54
+ error.method = method;
55
+ error.body = body;
56
+ error.headers = response.headers;
57
+ throw error;
58
+ }
59
+ };
60
+ var parseUrl = (pathOrUrl = "", baseUrl) => {
61
+ let fullUrl;
62
+ if (/https?:\/\//.test(pathOrUrl)) {
63
+ fullUrl = pathOrUrl;
64
+ } else if (baseUrl) {
65
+ const base = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
66
+ const path = pathOrUrl.startsWith("/") ? pathOrUrl.substring(1) : pathOrUrl;
67
+ fullUrl = base + path;
68
+ } else {
69
+ new URL(pathOrUrl);
70
+ }
71
+ const url = new URL(fullUrl);
72
+ return {
73
+ url: url.toString(),
74
+ baseUrl: url.origin,
75
+ path: url.pathname
76
+ };
77
+ };
78
+ async function request(method, fullUrlOrPath, options = {}) {
79
+ const startTime = Date.now();
80
+ const { url, baseUrl, path } = parseUrl(fullUrlOrPath, options.baseUrl);
81
+ const {
82
+ headers = {},
83
+ query = {},
84
+ body,
85
+ errors = {},
86
+ timeout = 3e5,
87
+ tls = {},
88
+ parseAs = "auto",
89
+ maxRedirections
90
+ } = options;
91
+ const client = getClient(baseUrl, { tls });
92
+ const response = await client.request({
93
+ path,
94
+ query,
95
+ method,
96
+ headers,
97
+ body: encodeRequestBody(body),
98
+ throwOnError: false,
99
+ maxRedirections,
100
+ bodyTimeout: timeout,
101
+ headersTimeout: timeout
102
+ });
103
+ const statusText = getReasonPhrase(response.statusCode);
104
+ await assertOK(response, errors, url, method, startTime);
105
+ const responseBody = await readResponseBody(response, parseAs);
106
+ const endTime = Date.now();
107
+ const duration = endTime - startTime;
108
+ return {
109
+ url,
110
+ method,
111
+ statusCode: response.statusCode,
112
+ statusMessage: statusText,
113
+ headers: response.headers,
114
+ body: responseBody,
115
+ duration
116
+ };
117
+ }
118
+ function encodeRequestBody(body) {
119
+ if (!body) {
120
+ return void 0;
121
+ }
122
+ if (Buffer.isBuffer(body) || body instanceof Readable || typeof body === "string") {
123
+ return body;
124
+ }
125
+ if (typeof body === "object") {
126
+ if (Symbol.asyncIterator in Object(body) || Symbol.iterator in Object(body) || body instanceof FormData) {
127
+ return body;
128
+ }
129
+ return JSON.stringify(body);
130
+ }
131
+ throw new Error("Unsupported body type");
132
+ }
133
+ async function readResponseBody(response, parseAs) {
134
+ const contentType = response.headers["content-type"];
135
+ switch (parseAs) {
136
+ case "json":
137
+ return response.body.json();
138
+ case "text":
139
+ return response.body.text();
140
+ case "stream":
141
+ return response.body;
142
+ default:
143
+ return contentType && contentType.includes("application/json") ? response.body.json() : response.body.text();
144
+ }
145
+ }
146
+ var get = (url, options) => request("GET", url, options);
147
+ var post = (url, body, options) => request("POST", url, { body, ...options });
148
+ var put = (url, body, options) => request("PUT", url, { body, ...options });
149
+ var del = (url, body, options) => request("DELETE", url, { body, ...options });
150
+
151
+ // src/util/references.js
152
+ import { Readable as Readable2, Writable } from "stream";
3
153
  function expandReferences(state, ...args) {
4
154
  return args.map((value) => expandReference(state, value));
5
155
  }
6
156
  var isStream = (value) => {
7
157
  if (value && typeof value == "object") {
8
- if (value instanceof Readable || value instanceof Writable) {
158
+ if (value instanceof Readable2 || value instanceof Writable) {
9
159
  return true;
10
160
  }
11
161
  if (value.pipeTo || value.pipe) {
@@ -47,7 +197,43 @@ function normalizeOauthConfig(configuration) {
47
197
  console.log('Using "accessToken" from state.configuration');
48
198
  return configuration;
49
199
  }
200
+
201
+ // src/util/parse-date.js
202
+ import { startOfToday, startOfYesterday, subHours, subDays, startOfDay } from "date-fns";
203
+ var parse_date_default = (d, startDate) => {
204
+ try {
205
+ if (d === "start") {
206
+ return startDate;
207
+ } else if (d === "now" || d === "end") {
208
+ return new Date();
209
+ } else if (d === "today") {
210
+ return startOfToday();
211
+ } else if (d === "yesterday") {
212
+ return startOfYesterday();
213
+ } else if (/(hours? ago)$/.test(d)) {
214
+ const [diff] = d.match(/\d+/);
215
+ return subHours(new Date(), diff);
216
+ } else if (/(days? ago)$/.test(d)) {
217
+ const [diff] = d.match(/\d+/);
218
+ return startOfDay(subDays(new Date(), diff));
219
+ }
220
+ } catch (e) {
221
+ console.log(`Error converting ${d} into a date`);
222
+ console.log(e);
223
+ }
224
+ return d;
225
+ };
50
226
  export {
227
+ del,
228
+ enableMockClient,
51
229
  expandReferences,
52
- normalizeOauthConfig
230
+ get,
231
+ logResponse,
232
+ makeBasicAuthHeader,
233
+ normalizeOauthConfig,
234
+ parse_date_default as parseDate,
235
+ parseUrl,
236
+ post,
237
+ put,
238
+ request
53
239
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-common",
3
- "version": "1.11.1",
3
+ "version": "1.13.0",
4
4
  "description": "Common Expressions for OpenFn",
5
5
  "homepage": "https://docs.openfn.org",
6
6
  "repository": {
@@ -38,12 +38,12 @@
38
38
  "csv-parse": "^5.4.0",
39
39
  "csvtojson": "^2.0.10",
40
40
  "date-fns": "^2.25.0",
41
+ "http-status-codes": "^2.3.0",
41
42
  "jsonpath-plus": "^4.0.0",
42
43
  "lodash": "^4.17.19",
43
- "undici": "^5.22.1"
44
+ "undici": "^5.23.0"
44
45
  },
45
46
  "devDependencies": {
46
- "@openfn/buildtools": "^1.0.2",
47
47
  "@openfn/simple-ast": "0.4.1",
48
48
  "chai": "4.3.6",
49
49
  "deep-eql": "4.1.1",
@@ -55,8 +55,8 @@
55
55
  "main": "dist/index.cjs",
56
56
  "scripts": {
57
57
  "build": "pnpm clean && build-adaptor common",
58
- "test": "mocha --experimental-specifier-resolution=node --no-warnings",
59
- "test:watch": "mocha -w --experimental-specifier-resolution=node --no-warnings",
58
+ "test": "mocha --experimental-specifier-resolution=node --no-warnings --recursive",
59
+ "test:watch": "mocha -w --experimental-specifier-resolution=node --no-warnings --recursive",
60
60
  "clean": "rimraf dist types docs",
61
61
  "pack": "pnpm pack --pack-destination ../../dist",
62
62
  "lint": "eslint src"
@@ -347,8 +347,30 @@ export function parseCsv(csvData: string | Stream, parsingOptions?: any, callbac
347
347
  * @returns {Operation}
348
348
  */
349
349
  export function validate(schema?: string | object, data?: string | object): Operation;
350
+ /**
351
+ * Sets a cursor property on state.
352
+ * Supports natural language dates like `now`, `today`, `yesterday`, `n hours ago`, `n days ago`, and `start`,
353
+ * which will be converted relative to the environment (ie, the Lightning or CLI locale). Custom timezones
354
+ * are not yet supported.
355
+ * See the usage guide at @{link https://docs.openfn.org/documentation/jobs/job-writing-guide#using-cursors}
356
+ * @public
357
+ * @example <caption>Use a cursor from state if present, or else use the default value</caption>
358
+ * cursor($.cursor, { defaultValue: 'today' })
359
+ * @example <caption>Use a pagination cursor</caption>
360
+ * cursor(22)
361
+ * @function
362
+ * @param {any} value - the cursor value. Usually an ISO date, natural language date, or page number
363
+ * @param {object} options - options to control the cursor.
364
+ * @param {string} options.key - set the cursor key. Will persist through the whole run.
365
+ * @param {any} options.defaultValue - the value to use if value is falsy
366
+ * @returns {Operation}
367
+ */
368
+ export function cursor(value: any, options?: {
369
+ key: string;
370
+ defaultValue: any;
371
+ }): Operation;
350
372
  export * as beta from "./beta";
351
- export * as http from "./http";
373
+ export * as http from "./http.deprecated";
352
374
  export * as dateFns from "./dateFns";
353
375
  /**
354
376
  * Scopes an array of data based on a JSONPath.
@@ -0,0 +1,72 @@
1
+ /**
2
+ * `request` is a helper function that sends HTTP requests and returns the response
3
+ * body, headers, and status code.
4
+ * Use the error map to provide custom error messages or get hold of the response in case of errors.
5
+ * @param method - The HTTP method to use for the request (e.g., "GET", "POST", "PUT", "DELETE", etc.).
6
+ * @param fullUrlOrPath - The full or partial URL for the request.
7
+ * @param [options] - The `options` parameter is an object that contains additional configuration
8
+ * options for the request.
9
+ * @returns an object with the following properties:
10
+ * - method: the request method
11
+ * - url: the request url
12
+ * - code: the status code of the response
13
+ * - headers: the headers of the response
14
+ * - body: the body of the response
15
+ * - message: the status text of the response
16
+ * - duration: the response time
17
+ */
18
+ export function request(method: any, fullUrlOrPath: any, options?: {}): Promise<{
19
+ url: string;
20
+ method: any;
21
+ statusCode: any;
22
+ statusMessage: string;
23
+ headers: any;
24
+ body: any;
25
+ duration: number;
26
+ }>;
27
+ export function makeBasicAuthHeader(username: any, password: any): {
28
+ Authorization: string;
29
+ };
30
+ export function logResponse(response: any): any;
31
+ export function enableMockClient(baseUrl: any): import("undici/types/mock-interceptor").Interceptable;
32
+ export function parseUrl(pathOrUrl: string, baseUrl: any): {
33
+ url: string;
34
+ baseUrl: string;
35
+ path: string;
36
+ };
37
+ export function get(url: any, options: any): Promise<{
38
+ url: string;
39
+ method: any;
40
+ statusCode: any;
41
+ statusMessage: string;
42
+ headers: any;
43
+ body: any;
44
+ duration: number;
45
+ }>;
46
+ export function post(url: any, body: any, options: any): Promise<{
47
+ url: string;
48
+ method: any;
49
+ statusCode: any;
50
+ statusMessage: string;
51
+ headers: any;
52
+ body: any;
53
+ duration: number;
54
+ }>;
55
+ export function put(url: any, body: any, options: any): Promise<{
56
+ url: string;
57
+ method: any;
58
+ statusCode: any;
59
+ statusMessage: string;
60
+ headers: any;
61
+ body: any;
62
+ duration: number;
63
+ }>;
64
+ export function del(url: any, body: any, options: any): Promise<{
65
+ url: string;
66
+ method: any;
67
+ statusCode: any;
68
+ statusMessage: string;
69
+ headers: any;
70
+ body: any;
71
+ duration: number;
72
+ }>;
@@ -0,0 +1,4 @@
1
+ export * from "./http";
2
+ export * from "./references";
3
+ export { parseDate };
4
+ import parseDate from "./parse-date";
@@ -0,0 +1,2 @@
1
+ declare function _default(d: any, startDate: any): any;
2
+ export default _default;
@@ -0,0 +1,2 @@
1
+ export function expandReferences(state: any, ...args: any[]): any[];
2
+ export function normalizeOauthConfig(configuration: any): any;
package/types/util.d.ts DELETED
@@ -1,10 +0,0 @@
1
- /**
2
- * General-purpose utility functions
3
- *
4
- * These are designed more for use in adaptor code than job code
5
- * (but we could choose to export util from common)
6
- *
7
- * None of these functions are operation factories
8
- */
9
- export function expandReferences(state: any, ...args: any[]): any[];
10
- export function normalizeOauthConfig(configuration: any): any;
File without changes