@faybl/client 4.3.0 → 4.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faybl/client",
3
- "version": "4.3.0",
3
+ "version": "4.3.1",
4
4
  "description": "Faybl JavaScript Client",
5
5
  "license": "MIT",
6
6
  "author": "Arcturitech",
@@ -45,7 +45,6 @@
45
45
  "openid-client": "^6.8.8",
46
46
  "ramda": "^0.32.0",
47
47
  "sift": "^17.1.4",
48
- "tri-fp": "^4.2.0",
49
48
  "xstate": "^5.33.3"
50
49
  },
51
50
  "devDependencies": {
package/src/dataset.js CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  } from 'xstate';
13
13
 
14
14
  import { applyChange, compileFilter, createRecordMatcher, projectWith } from './datasetRecords.js';
15
+ import { either } from './utils/either.js';
15
16
 
16
17
  const SUBSCRIPTION_ID = 'subscription';
17
18
 
@@ -112,8 +113,9 @@ export const createDatasetMachine = (client, spec, onChange = () => undefined) =
112
113
  const readArgs = readArgsFor({ ...rest, rids, filter, projection: readProjection });
113
114
 
114
115
  const compiled = compileFilter(filter);
116
+ const filterErrorMessage = either(R.prop('message'))(() => undefined)(compiled);
115
117
  const change = applyChange({
116
- matches: compiled.ok ? createRecordMatcher({ rids, test: compiled.value }) : R.F,
118
+ matches: either(() => R.F)((test) => createRecordMatcher({ rids, test }))(compiled),
117
119
  transform: R.pipe(readProjection ? projectWith(readProjection) : R.identity, recordTransform),
118
120
  });
119
121
  const applyAll = (records, changes) =>
@@ -129,7 +131,7 @@ export const createDatasetMachine = (client, spec, onChange = () => undefined) =
129
131
  clearRecords: assign({ records: [], held: [] }),
130
132
  hold: assign({ held: ({ context: { held }, event }) => R.append(event, held) }),
131
133
  setError: assign({ error: ({ event: { error } }) => error }),
132
- setFilterError: assign({ error: () => Error(compiled.message) }),
134
+ setFilterError: assign({ error: () => Error(filterErrorMessage) }),
133
135
  clearError: assign({ error: undefined }),
134
136
  setRecords: assign({
135
137
  records: ({ context: { held }, event: { output } }) =>
@@ -144,7 +146,7 @@ export const createDatasetMachine = (client, spec, onChange = () => undefined) =
144
146
  }),
145
147
  },
146
148
  guards: {
147
- hasInvalidFilter: () => !compiled.ok,
149
+ hasInvalidFilter: () => filterErrorMessage !== undefined,
148
150
  },
149
151
  });
150
152
  };
@@ -1,6 +1,8 @@
1
1
  import * as R from 'ramda';
2
2
  import sift from 'sift';
3
3
 
4
+ import { Left, Right } from './utils/either.js';
5
+
4
6
  const isNonEmpty = R.complement(R.isEmpty);
5
7
  const keysToInclude = R.pipe(R.pickBy(Boolean), R.keys);
6
8
  const keysToExclude = R.pipe(R.pickBy(R.complement(Boolean)), R.keys);
@@ -21,21 +23,20 @@ export const projectWith = (projection) =>
21
23
  // `$where` runs JavaScript; a dataset filter only describes data. sift passes the operation's
22
24
  // name fourth, after its parameters, the query that owns it and the options.
23
25
  const refuseOperation = (...[, , , name]) => {
24
- // eslint-disable-next-line functional/no-throw-statements -- sift's operation API reports an operation it cannot build by throwing; compileFilter turns it into a Result.
26
+ // eslint-disable-next-line functional/no-throw-statements -- sift's operation API reports an operation it cannot build by throwing; compileFilter turns it into a Left.
25
27
  throw Error(`Unsupported operation: ${name}`);
26
28
  };
27
29
 
28
30
  /**
29
31
  * Compiles a MongoDB filter into a test on a record, the same query language conf reads with.
30
- * An operation sift cannot evaluate, such as `$text`, fails the compilation.
32
+ * An operation sift cannot evaluate, such as `$text`, fails the compilation: a Left of
33
+ * `{ kind: 'InvalidFilter', message, cause }` instead of a Right of the test.
31
34
  */
32
- export const compileFilter = (filter = {}) => {
33
- try {
34
- return { ok: true, value: sift(filter, { operations: { $where: refuseOperation } }) };
35
- } catch (error) {
36
- return { ok: false, message: `Invalid dataset filter: ${error.message}` };
37
- }
38
- };
35
+ export const compileFilter = R.tryCatch(
36
+ (filter = {}) => Right(sift(filter, { operations: { $where: refuseOperation } })),
37
+ (cause) =>
38
+ Left({ kind: 'InvalidFilter', message: `Invalid dataset filter: ${cause.message}`, cause }),
39
+ );
39
40
 
40
41
  export const createRecordMatcher =
41
42
  ({ rids, test }) =>
package/src/fetch.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as R from 'ramda';
2
- import { biAsync } from 'tri-fp';
2
+
3
+ import { Left, Right, either, tryCatchAsync } from './utils/either.js';
3
4
 
4
5
  // Every request carries a JSON body, so the content type is set here rather than by each caller.
5
6
  // Asking for JSON makes the login proxy answer an expired session with 401 instead of a redirect
@@ -18,11 +19,16 @@ const withToken = async (options, oidcHandler) =>
18
19
  ? R.assocPath(['headers', 'Authorization'])(`Bearer ${await oidcHandler.getToken()}`)(options)
19
20
  : options;
20
21
 
22
+ const readJson = tryCatchAsync(async (response) => Right(await response.json()))((cause) =>
23
+ Left({ kind: 'InvalidJson', cause }),
24
+ );
25
+
26
+ // A failed response need not carry JSON, say an HTML error page from a proxy; its body is then {}.
21
27
  const requestFailure = async (response) => {
22
28
  const { status, statusText } = response;
23
- const [err, json] = await biAsync(response.json.bind(response))();
29
+ const body = either(() => ({}))(R.identity)(await readJson(response));
24
30
  return Object.assign(Error(`Request failed: ${status} ${statusText}`), {
25
- response: { status, statusText, body: err ? {} : json },
31
+ response: { status, statusText, body },
26
32
  });
27
33
  };
28
34
 
package/src/mqttUtils.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import match from 'mqtt-match';
2
2
  import * as R from 'ramda';
3
- import { bi } from 'tri-fp';
4
3
 
5
- const safeJsonParse = bi(JSON.parse);
4
+ import { Left, Right, either, tryCatchAsync } from './utils/either.js';
5
+
6
+ const parseJson = R.tryCatch(R.pipe(JSON.parse, Right), (cause) =>
7
+ Left({ kind: 'InvalidJson', cause }),
8
+ );
6
9
 
7
10
  // No `Buffer`: it is a Node global, and browsers have none. A Node Buffer is a typed array, so
8
11
  // binary passes through on either side.
@@ -47,26 +50,24 @@ export const getMatchingTopics = (topic) => R.pickBy((_, key) => matchTopic(key)
47
50
 
48
51
  // A subscriber's failure is reported and stays its own: it neither reaches the
49
52
  // other subscribers nor escapes as an unhandled rejection.
50
- const deliver =
51
- (report) =>
52
- async ({ callback, preCallback }, message) => {
53
- try {
54
- const payload = preCallback ? await preCallback(message) : message;
55
- await callback(payload);
56
- } catch (error) {
57
- report(error, { source: 'subscriber', topic: message.topic });
58
- }
59
- };
53
+ const deliver = (report) =>
54
+ tryCatchAsync(async ({ callback, preCallback }, message) => {
55
+ const payload = preCallback ? await preCallback(message) : message;
56
+ await callback(payload);
57
+ })((error, _, { topic }) => report(error, { source: 'subscriber', topic }));
60
58
 
59
+ const deliverAll = (getState, report) => async (topic, data) => {
60
+ const subscribers = R.pipe(getState, getMatchingTopics(topic), R.values, R.flatten)();
61
+ await Promise.all(subscribers.map((subscriber) => deliver(report)(subscriber, { topic, data })));
62
+ };
63
+
64
+ // onError gets the parser's own SyntaxError, as it does any other failure.
61
65
  const messageHandler = (getState, report) => async (topic, jsonData) => {
62
66
  // An empty payload clears a retained message; there is nothing to deliver.
63
67
  if (jsonData.length === 0) return undefined;
64
- const [error, data] = safeJsonParse(jsonData);
65
-
66
- if (error) return report(error, { source: 'message', topic });
67
- const subscribers = R.pipe(getState, getMatchingTopics(topic), R.values, R.flatten)();
68
- await Promise.all(subscribers.map((subscriber) => deliver(report)(subscriber, { topic, data })));
69
- return undefined;
68
+ return either(({ cause }) => report(cause, { source: 'message', topic }))((data) =>
69
+ deliverAll(getState, report)(topic, data),
70
+ )(parseJson(jsonData));
70
71
  };
71
72
 
72
73
  // A SUBACK return code of 0x80 or above refuses the subscription.
package/src/procedure.js CHANGED
@@ -2,6 +2,7 @@ import * as R from 'ramda';
2
2
  import { createId } from '@paralleldrive/cuid2';
3
3
 
4
4
  import { assertTopicSegment, topicSegmentError } from './topicSegment.js';
5
+ import { tryCatchAsync } from './utils/either.js';
5
6
 
6
7
  export const createRequestMessage = (args) => ({
7
8
  args,
@@ -18,13 +19,10 @@ const procedureBaseTopic = 'procedure';
18
19
  const procedureMqttOptions = { qos: 1, retain: false };
19
20
  const maxRememberedReplies = 1024;
20
21
 
21
- const runProcedure = async (callback, args) => {
22
- try {
23
- return createReplyMessage(await callback(args), true);
24
- } catch (error) {
25
- return createReplyMessage(error?.message ?? String(error), false);
26
- }
27
- };
22
+ // A provider's procedure is caller code: whatever it throws or rejects with becomes a failure reply.
23
+ const runProcedure = tryCatchAsync(async (callback, args) =>
24
+ createReplyMessage(await callback(args), true),
25
+ )((error) => createReplyMessage(error?.message ?? String(error), false));
28
26
 
29
27
  // Settles like `promise`, or rejects once `seconds` pass first. The timer is
30
28
  // cleared as soon as `promise` settles.
package/src/report.js CHANGED
@@ -1,16 +1,19 @@
1
+ import * as R from 'ramda';
2
+
1
3
  /**
2
4
  * Turns the caller's `onError` into the function every module reports through. The client writes
3
5
  * nothing to the console; without an `onError`, what it would report is dropped.
4
6
  *
5
7
  * `context.source` says where the error came from: `mqtt`, `credentials`, `message`, `subscriber`
6
8
  * or `procedure`. `context.topic` is set when the error concerns a topic.
9
+ *
10
+ * What a throwing onError throws is dropped too; it would otherwise escape into an MQTT.js event or
11
+ * a subscriber's delivery.
7
12
  */
8
- export const createReporter =
9
- (onError = () => undefined) =>
10
- (error, context) => {
11
- try {
13
+ export const createReporter = (onError = () => undefined) =>
14
+ R.tryCatch(
15
+ (error, context) => {
12
16
  onError(error, context);
13
- } catch {
14
- // A throwing onError would otherwise escape into an MQTT.js event or a subscriber's delivery.
15
- }
16
- };
17
+ },
18
+ () => undefined,
19
+ );
@@ -0,0 +1,35 @@
1
+ import * as R from 'ramda';
2
+
3
+ // Expected failures are values: a step returns Right(value) or Left(error) instead of throwing.
4
+ // Fantasy-land map/chain (non-enumerable) → R.map/R.chain work; toEqual compares { isLeft, value }.
5
+ // The methods come as one object to stay within the max-params lint rule.
6
+ const make = (isLeft, value, { map, chain }) =>
7
+ Object.freeze(
8
+ Object.defineProperties(
9
+ { isLeft, value },
10
+ { 'fantasy-land/map': { value: map }, 'fantasy-land/chain': { value: chain } },
11
+ ),
12
+ );
13
+
14
+ export const Left = (value) =>
15
+ make(true, value, { map: () => Left(value), chain: () => Left(value) });
16
+ export const Right = (value) =>
17
+ make(false, value, { map: (f) => Right(f(value)), chain: (f) => f(value) });
18
+ export const either =
19
+ (onLeft) =>
20
+ (onRight) =>
21
+ ({ isLeft, value }) =>
22
+ isLeft ? onLeft(value) : onRight(value);
23
+
24
+ export const fromNil = (error) => R.ifElse(R.isNil, R.always(Left(error)), Right);
25
+
26
+ export const tryCatchAsync =
27
+ (tryer) =>
28
+ (catcher) =>
29
+ async (...args) => {
30
+ try {
31
+ return await tryer(...args);
32
+ } catch (err) {
33
+ return catcher(err, ...args);
34
+ }
35
+ };