@openfn/language-collections 0.1.0 → 0.3.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
@@ -50,6 +50,7 @@ var import_stream_chain = __toESM(require("stream-chain"), 1);
50
50
  var import_stream_json = __toESM(require("stream-json"), 1);
51
51
  var import_Pick = __toESM(require("stream-json/filters/Pick"), 1);
52
52
  var import_StreamArray = __toESM(require("stream-json/streamers/StreamArray"), 1);
53
+ var import_StreamValues = __toESM(require("stream-json/streamers/StreamValues"), 1);
53
54
 
54
55
  // src/mock.js
55
56
  var import_undici = require("undici");
@@ -74,27 +75,31 @@ function API() {
74
75
  throw new Error(COLLECTION_NOT_FOUND);
75
76
  }
76
77
  const col = collections[name];
77
- const results = [];
78
+ const items = [];
78
79
  const regex = new RegExp(key.replace("*", "(.*)"));
79
80
  for (const key2 in col) {
80
81
  if (regex.test(key2)) {
81
- results.push({
82
+ items.push({
82
83
  key: key2,
83
84
  value: col[key2]
84
85
  });
85
86
  }
86
87
  }
87
- return { results };
88
+ return { items };
88
89
  };
89
90
  const byKey = (name, key) => {
90
91
  return collections[name][key];
91
92
  };
93
+ const asJSON = (name, key) => {
94
+ return JSON.parse(collections[name][key]);
95
+ };
92
96
  const remove2 = (name, key) => {
93
97
  if (!(name in collections)) {
94
98
  throw new Error(COLLECTION_NOT_FOUND);
95
99
  }
96
100
  const col = collections[name];
97
101
  delete col[key];
102
+ return [key];
98
103
  };
99
104
  const api = {
100
105
  collections,
@@ -103,12 +108,17 @@ function API() {
103
108
  upsert,
104
109
  fetch,
105
110
  remove: remove2,
106
- byKey
111
+ byKey,
112
+ asJSON
107
113
  };
108
114
  return api;
109
115
  }
110
116
  var parsePath = (path) => {
111
- let [_collections, name, key] = path.split("/");
117
+ if (!path.startsWith("/")) {
118
+ path = `/${path}`;
119
+ }
120
+ path = path.split("?")[0];
121
+ let [_, _collections, name, key] = path.split("/");
112
122
  return { name, key };
113
123
  };
114
124
  var assertAuth = (req) => {
@@ -130,12 +140,30 @@ function createServer(url = "https://app.openfn.org") {
130
140
  }
131
141
  try {
132
142
  let { name, key } = parsePath(req.path);
133
- if (!key) {
134
- key = "*";
143
+ let body;
144
+ let statusCode = 200;
145
+ if (key) {
146
+ const result = api.byKey(name, key);
147
+ if (!result) {
148
+ body = {};
149
+ statusCode = 204;
150
+ } else {
151
+ body = {
152
+ key,
153
+ value: result
154
+ };
155
+ }
156
+ } else {
157
+ const params = new URLSearchParams(req.query || req.path.split("?")[1]);
158
+ key = params.get("key") ?? "*";
159
+ const { items } = api.fetch(name, key);
160
+ body = {
161
+ cursor: ["xxx"],
162
+ items
163
+ };
135
164
  }
136
- const body = api.fetch(name, key);
137
165
  return {
138
- statusCode: 200,
166
+ statusCode,
139
167
  data: JSON.stringify(body),
140
168
  responseOptions: {
141
169
  headers: { "Content-Type": "application/json" }
@@ -154,13 +182,22 @@ function createServer(url = "https://app.openfn.org") {
154
182
  } catch (e) {
155
183
  return { statusCode: 403 };
156
184
  }
185
+ let upserted = 0;
186
+ const errors = [];
157
187
  try {
158
188
  const { name, key } = parsePath(req.path);
159
189
  const body = JSON.parse(req.body);
160
- for (const { key: key2, value } of body) {
190
+ for (const { key: key2, value } of body.items) {
161
191
  api.upsert(name, key2, value);
192
+ upserted++;
162
193
  }
163
- return { statusCode: 200 };
194
+ return {
195
+ statusCode: 200,
196
+ responseOptions: {
197
+ headers: { "Content-Type": "application/json" }
198
+ },
199
+ data: JSON.stringify({ upserted, errors })
200
+ };
164
201
  } catch (e) {
165
202
  if (e.message === COLLECTION_NOT_FOUND) {
166
203
  return { statusCode: 404 };
@@ -175,8 +212,14 @@ function createServer(url = "https://app.openfn.org") {
175
212
  }
176
213
  try {
177
214
  const { name, key } = parsePath(req.path);
178
- api.remove(name, key);
179
- return { statusCode: 200 };
215
+ const keys = api.remove(name, key);
216
+ return {
217
+ statusCode: 200,
218
+ responseOptions: {
219
+ headers: { "Content-Type": "application/json" }
220
+ },
221
+ data: JSON.stringify({ deleted: keys.length, keys })
222
+ };
180
223
  } catch (e) {
181
224
  if (e.message === COLLECTION_NOT_FOUND) {
182
225
  return { statusCode: 404 };
@@ -214,8 +257,11 @@ var client;
214
257
  var getClient = (state) => {
215
258
  var _a;
216
259
  if (!client) {
217
- const baseUrl = ((_a = state.configuration) == null ? void 0 : _a.collections_endpoint) ?? "https://app.openfn.org";
218
- client = new import_undici2.default.client(baseUrl);
260
+ if (!((_a = state.configuration) == null ? void 0 : _a.collections_endpoint)) {
261
+ throw new Error("ERROR: collections_endpoint not set");
262
+ }
263
+ const url = new URL(state.configuration.collections_endpoint);
264
+ client = new import_undici2.default.Client(url.origin);
219
265
  }
220
266
  return client;
221
267
  };
@@ -224,25 +270,38 @@ var setMockClient = (mockClient) => {
224
270
  };
225
271
  function get(name, query = {}) {
226
272
  return async (state) => {
227
- const [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
273
+ let [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
274
+ if (typeof resolvedQuery === "string") {
275
+ resolvedQuery = { key: resolvedQuery };
276
+ }
228
277
  const { key, ...rest } = expandQuery(resolvedQuery);
229
- const response = await request(
230
- state,
231
- getClient(state),
232
- `${resolvedName}/${key}`,
233
- { query: rest }
234
- );
235
- let data;
236
- if (!key.match(/\*/) || Object.keys(resolvedQuery).length === 0) {
237
- [data] = (await response.body.json()).results;
238
- console.log(`Fetched "${key}" from collection "${name}"`);
278
+ let q;
279
+ let path = resolvedName;
280
+ if (key.match(/\*/) || Object.keys(rest).length) {
281
+ q = resolvedQuery;
239
282
  } else {
283
+ path = `${resolvedName}/${key}`;
284
+ }
285
+ const response = await request(state, getClient(state), path, { query: q });
286
+ let data;
287
+ if (q) {
240
288
  data = [];
241
289
  console.log(`Downloading data from collection "${name}"...`);
242
- await streamResponse(response, (item) => {
290
+ const cursor = await streamResponse(response, (item) => {
291
+ item.value = JSON.parse(item.value);
243
292
  data.push(item);
244
293
  });
294
+ data.cursor = cursor;
245
295
  console.log(`Fetched "${data.length}" values from collection "${name}"`);
296
+ } else {
297
+ const body = await response.body.json();
298
+ if (body.value) {
299
+ data = JSON.parse(body.value);
300
+ console.log(`Fetched "${key}" from collection "${name}"`);
301
+ } else {
302
+ data = {};
303
+ console.warn(`Key "${key}" not found in collection "${name}"`);
304
+ }
246
305
  }
247
306
  state.data = data;
248
307
  return state;
@@ -257,15 +316,31 @@ function set(name, keyGen, values) {
257
316
  );
258
317
  const dataArray = Array.isArray(resolvedValues) ? resolvedValues : [resolvedValues];
259
318
  const keyGenFn = typeof keyGen === "string" ? () => keyGen : keyGen;
260
- const pairs = dataArray.map((value) => ({ key: keyGenFn(value), value }));
261
- console.log(`Setting ${pairs.length} values in collection "${name}"`);
319
+ const pairs = dataArray.map((value, index) => ({
320
+ key: keyGenFn(value, index),
321
+ value: JSON.stringify(value)
322
+ }));
262
323
  const response = await request(state, getClient(state), resolvedName, {
263
324
  method: "POST",
264
- body: JSON.stringify(pairs),
265
- heeaders: {
325
+ body: JSON.stringify({ items: pairs }),
326
+ headers: {
266
327
  "content-type": "application/json"
267
328
  }
268
329
  });
330
+ if (response.statusCode >= 400) {
331
+ console.log(
332
+ `Error setting ${pairs.length} values in collection "${name}"`
333
+ );
334
+ const text = await response.body.text();
335
+ const e = new Error("ERROR from collections server:" + 400);
336
+ e.body = text;
337
+ throw e;
338
+ }
339
+ const result = await response.body.json();
340
+ console.log(`Set ${result.upserted} values in collection "${name}"`);
341
+ if (result.error) {
342
+ console.log(`Errors reported on set:`, result.error);
343
+ }
269
344
  return state;
270
345
  };
271
346
  }
@@ -282,35 +357,89 @@ function remove(name, query = {}, options = {}) {
282
357
  query: rest
283
358
  }
284
359
  );
360
+ const result = await response.body.json();
361
+ console.log(`Set ${result.upserts} values in collection "${name}"`);
285
362
  return state;
286
363
  };
287
364
  }
288
- function each(name, query = {}, callback = {}) {
365
+ function each(name, query = {}, callback = () => {
366
+ }) {
289
367
  return async (state) => {
290
368
  const [resolvedName, resolvedQuery] = (0, import_util.expandReferences)(state, name, query);
369
+ let q;
370
+ if (typeof resolvedQuery === "string") {
371
+ q = { key: resolvedQuery };
372
+ } else {
373
+ q = resolvedQuery;
374
+ }
291
375
  const { key, ...rest } = expandQuery(resolvedQuery);
292
- const response = await request(
293
- state,
294
- getClient(state),
295
- `${resolvedName}/${key}`,
296
- { query: rest }
297
- );
298
- await streamResponse(response, async ({ key: key2, value }) => {
299
- await callback(state, value, key2);
376
+ const response = await request(state, getClient(state), resolvedName, {
377
+ query: q
300
378
  });
379
+ console.log(`each response`, response.statusCode);
380
+ const cursor = await streamResponse(response, async ({ value, key: key2 }) => {
381
+ await callback(state, JSON.parse(value), key2);
382
+ });
383
+ state.data = {
384
+ cursor
385
+ };
301
386
  return state;
302
387
  };
303
388
  }
304
389
  var streamResponse = async (response, onValue) => {
305
- const pipeline = (0, import_stream_chain.default)([
306
- response.body,
307
- (0, import_stream_json.default)(),
308
- new import_Pick.default({ filter: "results" }),
309
- new import_StreamArray.default()
310
- ]);
311
- for await (const { key, value } of pipeline) {
312
- await onValue(value);
390
+ const pipeline = (0, import_stream_chain.default)([response.body, (0, import_stream_json.default)()]);
391
+ let isInsideItems = false;
392
+ let cursor;
393
+ const it = pipeline.iterator();
394
+ const waitFor = async (...names) => {
395
+ while (true) {
396
+ const next = await it.next();
397
+ if (next.done) {
398
+ return;
399
+ }
400
+ if (names.includes(next.value.name)) {
401
+ return next;
402
+ }
403
+ }
404
+ };
405
+ for await (const token of it) {
406
+ if (!isInsideItems && token.name === "startKey") {
407
+ const next = await waitFor("keyValue");
408
+ if (next.value.value === "cursor") {
409
+ const strValue = await waitFor("stringChunk", "nullValue");
410
+ if (strValue.name === "nullValue") {
411
+ continue;
412
+ }
413
+ cursor = strValue.value.value;
414
+ }
415
+ if (next.value.value === "items") {
416
+ isInsideItems = true;
417
+ await waitFor("startArray");
418
+ }
419
+ }
420
+ if (isInsideItems && token.name === "startObject") {
421
+ let key;
422
+ let value;
423
+ while (!key || !value) {
424
+ const nextKey = await waitFor("keyValue");
425
+ if (nextKey.value.value === "key") {
426
+ key = await waitFor("stringValue");
427
+ }
428
+ if (nextKey.value.value === "value") {
429
+ value = await waitFor("stringValue");
430
+ }
431
+ }
432
+ await onValue({
433
+ key: key.value.value,
434
+ value: value.value.value
435
+ });
436
+ waitFor("endObject");
437
+ }
438
+ if (isInsideItems && token.name === "endArray") {
439
+ isInsideItems = false;
440
+ }
313
441
  }
442
+ return cursor;
314
443
  };
315
444
  var expandQuery = (query) => {
316
445
  let key;
@@ -343,19 +472,21 @@ var request = (state, client2, path, options = {}) => {
343
472
  path
344
473
  });
345
474
  }
475
+ const basePath = new URL(state.configuration.collections_endpoint).pathname;
346
476
  const headers = {
347
477
  Authorization: `Bearer ${state.configuration.collections_token}`
348
478
  };
349
479
  Object.assign(headers, options == null ? void 0 : options.headers);
350
480
  const { headers: _h, query: _q, ...otherOptions } = options;
351
- const query = parseQuery(options.query);
352
- return client2.request({
353
- path: import_node_path.default.join("collections", path),
481
+ const query = parseQuery(options);
482
+ const args = {
483
+ path: import_node_path.default.join(basePath, path),
354
484
  headers,
355
485
  method: "GET",
356
486
  query,
357
487
  ...otherOptions
358
- });
488
+ };
489
+ return client2.request(args);
359
490
  };
360
491
  // Annotate the CommonJS export names for ESM import in node:
361
492
  0 && (module.exports = {
package/dist/index.js CHANGED
@@ -25,6 +25,7 @@ import chain from "stream-chain";
25
25
  import parser from "stream-json";
26
26
  import Pick from "stream-json/filters/Pick";
27
27
  import streamArray from "stream-json/streamers/StreamArray";
28
+ import streamValues from "stream-json/streamers/StreamValues";
28
29
 
29
30
  // src/mock.js
30
31
  import { MockAgent } from "undici";
@@ -49,27 +50,31 @@ function API() {
49
50
  throw new Error(COLLECTION_NOT_FOUND);
50
51
  }
51
52
  const col = collections[name];
52
- const results = [];
53
+ const items = [];
53
54
  const regex = new RegExp(key.replace("*", "(.*)"));
54
55
  for (const key2 in col) {
55
56
  if (regex.test(key2)) {
56
- results.push({
57
+ items.push({
57
58
  key: key2,
58
59
  value: col[key2]
59
60
  });
60
61
  }
61
62
  }
62
- return { results };
63
+ return { items };
63
64
  };
64
65
  const byKey = (name, key) => {
65
66
  return collections[name][key];
66
67
  };
68
+ const asJSON = (name, key) => {
69
+ return JSON.parse(collections[name][key]);
70
+ };
67
71
  const remove2 = (name, key) => {
68
72
  if (!(name in collections)) {
69
73
  throw new Error(COLLECTION_NOT_FOUND);
70
74
  }
71
75
  const col = collections[name];
72
76
  delete col[key];
77
+ return [key];
73
78
  };
74
79
  const api = {
75
80
  collections,
@@ -78,12 +83,17 @@ function API() {
78
83
  upsert,
79
84
  fetch,
80
85
  remove: remove2,
81
- byKey
86
+ byKey,
87
+ asJSON
82
88
  };
83
89
  return api;
84
90
  }
85
91
  var parsePath = (path) => {
86
- let [_collections, name, key] = path.split("/");
92
+ if (!path.startsWith("/")) {
93
+ path = `/${path}`;
94
+ }
95
+ path = path.split("?")[0];
96
+ let [_, _collections, name, key] = path.split("/");
87
97
  return { name, key };
88
98
  };
89
99
  var assertAuth = (req) => {
@@ -105,12 +115,30 @@ function createServer(url = "https://app.openfn.org") {
105
115
  }
106
116
  try {
107
117
  let { name, key } = parsePath(req.path);
108
- if (!key) {
109
- key = "*";
118
+ let body;
119
+ let statusCode = 200;
120
+ if (key) {
121
+ const result = api.byKey(name, key);
122
+ if (!result) {
123
+ body = {};
124
+ statusCode = 204;
125
+ } else {
126
+ body = {
127
+ key,
128
+ value: result
129
+ };
130
+ }
131
+ } else {
132
+ const params = new URLSearchParams(req.query || req.path.split("?")[1]);
133
+ key = params.get("key") ?? "*";
134
+ const { items } = api.fetch(name, key);
135
+ body = {
136
+ cursor: ["xxx"],
137
+ items
138
+ };
110
139
  }
111
- const body = api.fetch(name, key);
112
140
  return {
113
- statusCode: 200,
141
+ statusCode,
114
142
  data: JSON.stringify(body),
115
143
  responseOptions: {
116
144
  headers: { "Content-Type": "application/json" }
@@ -129,13 +157,22 @@ function createServer(url = "https://app.openfn.org") {
129
157
  } catch (e) {
130
158
  return { statusCode: 403 };
131
159
  }
160
+ let upserted = 0;
161
+ const errors = [];
132
162
  try {
133
163
  const { name, key } = parsePath(req.path);
134
164
  const body = JSON.parse(req.body);
135
- for (const { key: key2, value } of body) {
165
+ for (const { key: key2, value } of body.items) {
136
166
  api.upsert(name, key2, value);
167
+ upserted++;
137
168
  }
138
- return { statusCode: 200 };
169
+ return {
170
+ statusCode: 200,
171
+ responseOptions: {
172
+ headers: { "Content-Type": "application/json" }
173
+ },
174
+ data: JSON.stringify({ upserted, errors })
175
+ };
139
176
  } catch (e) {
140
177
  if (e.message === COLLECTION_NOT_FOUND) {
141
178
  return { statusCode: 404 };
@@ -150,8 +187,14 @@ function createServer(url = "https://app.openfn.org") {
150
187
  }
151
188
  try {
152
189
  const { name, key } = parsePath(req.path);
153
- api.remove(name, key);
154
- return { statusCode: 200 };
190
+ const keys = api.remove(name, key);
191
+ return {
192
+ statusCode: 200,
193
+ responseOptions: {
194
+ headers: { "Content-Type": "application/json" }
195
+ },
196
+ data: JSON.stringify({ deleted: keys.length, keys })
197
+ };
155
198
  } catch (e) {
156
199
  if (e.message === COLLECTION_NOT_FOUND) {
157
200
  return { statusCode: 404 };
@@ -189,8 +232,11 @@ var client;
189
232
  var getClient = (state) => {
190
233
  var _a;
191
234
  if (!client) {
192
- const baseUrl = ((_a = state.configuration) == null ? void 0 : _a.collections_endpoint) ?? "https://app.openfn.org";
193
- client = new undici.client(baseUrl);
235
+ if (!((_a = state.configuration) == null ? void 0 : _a.collections_endpoint)) {
236
+ throw new Error("ERROR: collections_endpoint not set");
237
+ }
238
+ const url = new URL(state.configuration.collections_endpoint);
239
+ client = new undici.Client(url.origin);
194
240
  }
195
241
  return client;
196
242
  };
@@ -199,25 +245,38 @@ var setMockClient = (mockClient) => {
199
245
  };
200
246
  function get(name, query = {}) {
201
247
  return async (state) => {
202
- const [resolvedName, resolvedQuery] = expandReferences(state, name, query);
248
+ let [resolvedName, resolvedQuery] = expandReferences(state, name, query);
249
+ if (typeof resolvedQuery === "string") {
250
+ resolvedQuery = { key: resolvedQuery };
251
+ }
203
252
  const { key, ...rest } = expandQuery(resolvedQuery);
204
- const response = await request(
205
- state,
206
- getClient(state),
207
- `${resolvedName}/${key}`,
208
- { query: rest }
209
- );
210
- let data;
211
- if (!key.match(/\*/) || Object.keys(resolvedQuery).length === 0) {
212
- [data] = (await response.body.json()).results;
213
- console.log(`Fetched "${key}" from collection "${name}"`);
253
+ let q;
254
+ let path = resolvedName;
255
+ if (key.match(/\*/) || Object.keys(rest).length) {
256
+ q = resolvedQuery;
214
257
  } else {
258
+ path = `${resolvedName}/${key}`;
259
+ }
260
+ const response = await request(state, getClient(state), path, { query: q });
261
+ let data;
262
+ if (q) {
215
263
  data = [];
216
264
  console.log(`Downloading data from collection "${name}"...`);
217
- await streamResponse(response, (item) => {
265
+ const cursor = await streamResponse(response, (item) => {
266
+ item.value = JSON.parse(item.value);
218
267
  data.push(item);
219
268
  });
269
+ data.cursor = cursor;
220
270
  console.log(`Fetched "${data.length}" values from collection "${name}"`);
271
+ } else {
272
+ const body = await response.body.json();
273
+ if (body.value) {
274
+ data = JSON.parse(body.value);
275
+ console.log(`Fetched "${key}" from collection "${name}"`);
276
+ } else {
277
+ data = {};
278
+ console.warn(`Key "${key}" not found in collection "${name}"`);
279
+ }
221
280
  }
222
281
  state.data = data;
223
282
  return state;
@@ -232,15 +291,31 @@ function set(name, keyGen, values) {
232
291
  );
233
292
  const dataArray = Array.isArray(resolvedValues) ? resolvedValues : [resolvedValues];
234
293
  const keyGenFn = typeof keyGen === "string" ? () => keyGen : keyGen;
235
- const pairs = dataArray.map((value) => ({ key: keyGenFn(value), value }));
236
- console.log(`Setting ${pairs.length} values in collection "${name}"`);
294
+ const pairs = dataArray.map((value, index) => ({
295
+ key: keyGenFn(value, index),
296
+ value: JSON.stringify(value)
297
+ }));
237
298
  const response = await request(state, getClient(state), resolvedName, {
238
299
  method: "POST",
239
- body: JSON.stringify(pairs),
240
- heeaders: {
300
+ body: JSON.stringify({ items: pairs }),
301
+ headers: {
241
302
  "content-type": "application/json"
242
303
  }
243
304
  });
305
+ if (response.statusCode >= 400) {
306
+ console.log(
307
+ `Error setting ${pairs.length} values in collection "${name}"`
308
+ );
309
+ const text = await response.body.text();
310
+ const e = new Error("ERROR from collections server:" + 400);
311
+ e.body = text;
312
+ throw e;
313
+ }
314
+ const result = await response.body.json();
315
+ console.log(`Set ${result.upserted} values in collection "${name}"`);
316
+ if (result.error) {
317
+ console.log(`Errors reported on set:`, result.error);
318
+ }
244
319
  return state;
245
320
  };
246
321
  }
@@ -257,35 +332,89 @@ function remove(name, query = {}, options = {}) {
257
332
  query: rest
258
333
  }
259
334
  );
335
+ const result = await response.body.json();
336
+ console.log(`Set ${result.upserts} values in collection "${name}"`);
260
337
  return state;
261
338
  };
262
339
  }
263
- function each(name, query = {}, callback = {}) {
340
+ function each(name, query = {}, callback = () => {
341
+ }) {
264
342
  return async (state) => {
265
343
  const [resolvedName, resolvedQuery] = expandReferences(state, name, query);
344
+ let q;
345
+ if (typeof resolvedQuery === "string") {
346
+ q = { key: resolvedQuery };
347
+ } else {
348
+ q = resolvedQuery;
349
+ }
266
350
  const { key, ...rest } = expandQuery(resolvedQuery);
267
- const response = await request(
268
- state,
269
- getClient(state),
270
- `${resolvedName}/${key}`,
271
- { query: rest }
272
- );
273
- await streamResponse(response, async ({ key: key2, value }) => {
274
- await callback(state, value, key2);
351
+ const response = await request(state, getClient(state), resolvedName, {
352
+ query: q
275
353
  });
354
+ console.log(`each response`, response.statusCode);
355
+ const cursor = await streamResponse(response, async ({ value, key: key2 }) => {
356
+ await callback(state, JSON.parse(value), key2);
357
+ });
358
+ state.data = {
359
+ cursor
360
+ };
276
361
  return state;
277
362
  };
278
363
  }
279
364
  var streamResponse = async (response, onValue) => {
280
- const pipeline = chain([
281
- response.body,
282
- parser(),
283
- new Pick({ filter: "results" }),
284
- new streamArray()
285
- ]);
286
- for await (const { key, value } of pipeline) {
287
- await onValue(value);
365
+ const pipeline = chain([response.body, parser()]);
366
+ let isInsideItems = false;
367
+ let cursor;
368
+ const it = pipeline.iterator();
369
+ const waitFor = async (...names) => {
370
+ while (true) {
371
+ const next = await it.next();
372
+ if (next.done) {
373
+ return;
374
+ }
375
+ if (names.includes(next.value.name)) {
376
+ return next;
377
+ }
378
+ }
379
+ };
380
+ for await (const token of it) {
381
+ if (!isInsideItems && token.name === "startKey") {
382
+ const next = await waitFor("keyValue");
383
+ if (next.value.value === "cursor") {
384
+ const strValue = await waitFor("stringChunk", "nullValue");
385
+ if (strValue.name === "nullValue") {
386
+ continue;
387
+ }
388
+ cursor = strValue.value.value;
389
+ }
390
+ if (next.value.value === "items") {
391
+ isInsideItems = true;
392
+ await waitFor("startArray");
393
+ }
394
+ }
395
+ if (isInsideItems && token.name === "startObject") {
396
+ let key;
397
+ let value;
398
+ while (!key || !value) {
399
+ const nextKey = await waitFor("keyValue");
400
+ if (nextKey.value.value === "key") {
401
+ key = await waitFor("stringValue");
402
+ }
403
+ if (nextKey.value.value === "value") {
404
+ value = await waitFor("stringValue");
405
+ }
406
+ }
407
+ await onValue({
408
+ key: key.value.value,
409
+ value: value.value.value
410
+ });
411
+ waitFor("endObject");
412
+ }
413
+ if (isInsideItems && token.name === "endArray") {
414
+ isInsideItems = false;
415
+ }
288
416
  }
417
+ return cursor;
289
418
  };
290
419
  var expandQuery = (query) => {
291
420
  let key;
@@ -318,19 +447,21 @@ var request = (state, client2, path, options = {}) => {
318
447
  path
319
448
  });
320
449
  }
450
+ const basePath = new URL(state.configuration.collections_endpoint).pathname;
321
451
  const headers = {
322
452
  Authorization: `Bearer ${state.configuration.collections_token}`
323
453
  };
324
454
  Object.assign(headers, options == null ? void 0 : options.headers);
325
455
  const { headers: _h, query: _q, ...otherOptions } = options;
326
- const query = parseQuery(options.query);
327
- return client2.request({
328
- path: nodepath.join("collections", path),
456
+ const query = parseQuery(options);
457
+ const args = {
458
+ path: nodepath.join(basePath, path),
329
459
  headers,
330
460
  method: "GET",
331
461
  query,
332
462
  ...otherOptions
333
- });
463
+ };
464
+ return client2.request(args);
334
465
  };
335
466
  export {
336
467
  collections_exports as collections
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openfn/language-collections",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "OpenFn collections adaptor",
5
5
  "type": "module",
6
6
  "exports": {
@@ -23,7 +23,7 @@
23
23
  "stream-chain": "^3.3.2",
24
24
  "stream-json": "^1.8.0",
25
25
  "undici": "^5.22.1",
26
- "@openfn/language-common": "2.1.0"
26
+ "@openfn/language-common": "2.1.1"
27
27
  },
28
28
  "devDependencies": {
29
29
  "assertion-error": "2.0.0",
@@ -39,10 +39,9 @@
39
39
  "types": "types/index.d.ts",
40
40
  "main": "dist/index.cjs",
41
41
  "scripts": {
42
- "tmp": "node test.js",
43
42
  "build": "pnpm clean && build-adaptor collections",
44
- "test": "mocha --experimental-specifier-resolution=node --no-warnings **/*.test.js",
45
- "test:watch": "mocha -w --experimental-specifier-resolution=node --no-warnings *.test.js",
43
+ "test": "mocha --experimental-specifier-resolution=node --no-warnings --recursive",
44
+ "test:watch": "mocha -w --experimental-specifier-resolution=node --no-warnings --recursive",
46
45
  "clean": "rimraf dist types docs",
47
46
  "pack": "pnpm pack --pack-destination ../../dist",
48
47
  "lint": "eslint src"
@@ -7,17 +7,20 @@
7
7
  * @property {string} createdAfter - matches values that were created after the end of the provided date
8
8
  * @property {string} updatedBefore - matches values that were updated before the start of the provided date
9
9
  * @property {string} updatedAfter - matches values that were updated after the end of the provided date*
10
+ * @property {number} limit - limit the maximum amount of results. Defaults to 1000.
11
+ * @property {string} cursor - set the cursor position to start searching from a specific index.
10
12
  */
11
13
  /**
12
14
  * Fetch one or more values from a collection.
13
15
  * For large datasets, we recommend using each(), which streams data.
14
16
  * You can pass a specific key as a string to only fetch one item, or pass a query
15
17
  * with a key-pattern or a date filter.
18
+ * If not all matching values are returned, the cursor position is written to state.data
16
19
  * @public
17
20
  * @function
18
21
  * @param {string} name - The name of the collection to fetch from
19
22
  * @param {string|QueryOptions} query - A string key or key pattern (with wildcards '*') to fetch, or a query object
20
- * @state data - the downloaded values as an array unless a specific string was specified
23
+ * @state data - the downloaded values as an array unless a specific key was specified, in which case state.data is the value
21
24
  * @example <caption>Get a specific value from a collection</caption>
22
25
  * collections.get('my-collection', '556e0a62')
23
26
  * @example <caption>Get a range of values from a collection with a key pattern</caption>
@@ -34,7 +37,7 @@ export function get(name: string, query?: string | QueryOptions): (state: any) =
34
37
  * a string key.
35
38
  * @public
36
39
  * @function
37
- * @param keygen - a function which generates a key for each value. Pass a string to set a static key for a single item.
40
+ * @param keygen - a function which generates a key for each value: (value, index) => key. Pass a string to set a static key for a single item.
38
41
  * @param values - an array of values to set, or a single value.
39
42
  * @example <caption>Set a number of values using each value's id property as a key</caption>
40
43
  * collections.set('my-collection', (item) => item.id, $.data)
@@ -71,6 +74,7 @@ export function remove(name: string, query?: string | QueryOptions, options?: {}
71
74
  * @param {string} name - The name of the collection to remove from
72
75
  * @param {string|QueryOptions} query - A string key or key pattern (with wildcards '*') to remove, or a query object
73
76
  * @param {function} callback - A callback invoked for each item `(state, value, key) => void`
77
+ * @state data.cursor - if values are still left on the server, a cursor string will be written to state.data
74
78
  * @example <caption>Iterate over a range of values with wildcards</caption>
75
79
  * collections.each('my-collection', 'record-2024*-appointment-*', (state, value, key) => {
76
80
  * state.cumulativeCost += value.cost;
@@ -83,7 +87,7 @@ export function remove(name: string, query?: string | QueryOptions, options?: {}
83
87
  export function each(name: string, query?: string | QueryOptions, callback?: Function): (state: any) => Promise<any>;
84
88
  export { createServer as createMockServer };
85
89
  export function setMockClient(mockClient: any): void;
86
- export function streamResponse(response: any, onValue: any): Promise<void>;
90
+ export function streamResponse(response: any, onValue: any): Promise<any>;
87
91
  export function expandQuery(query: any): any;
88
92
  export function parseQuery(options?: {}): {};
89
93
  export function request(state: any, client: any, path: any, options?: {}): any;
package/types/mock.d.ts CHANGED
@@ -4,13 +4,14 @@ export function API(): {
4
4
  reset: () => void;
5
5
  upsert: (name: any, key: any, value: any) => void;
6
6
  fetch: (name: any, key: any, query: any) => {
7
- results: {
7
+ items: {
8
8
  key: string;
9
9
  value: any;
10
10
  }[];
11
11
  };
12
- remove: (name: any, key: any) => void;
12
+ remove: (name: any, key: any) => any[];
13
13
  byKey: (name: any, key: any) => any;
14
+ asJSON: (name: any, key: any) => any;
14
15
  };
15
16
  export function createServer(url?: string): {
16
17
  api: any;