@flowrunner/cli 0.1.12 → 0.1.13

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.
@@ -6,7 +6,7 @@ import type { SharedExtensionMethod } from '../model/model-types';
6
6
  import { MethodParams } from '../params';
7
7
  import { ResultSpec } from '../result';
8
8
  import type { ProviderPayload } from '../types';
9
- import type { RealtimeTriggerProps } from './types';
9
+ import type { RealtimeInstance, RealtimeTriggerProps } from './types';
10
10
  export declare class RealtimeTriggerMethod extends ExtensionMethod implements LoaderOwner {
11
11
  private readonly props;
12
12
  readonly params: MethodParams;
@@ -21,6 +21,16 @@ export declare class RealtimeTriggerMethod extends ExtensionMethod implements Lo
21
21
  providerEventNames(params?: Record<string, unknown>): string[];
22
22
  claims(providerEventName: string): boolean;
23
23
  extendEventData(requestBody: ProviderPayload, providerEventData: ProviderPayload): Record<string, unknown> | undefined;
24
+ /**
25
+ * Whether `extendMatchData` should run before these instances are matched. Only when something will READ its
26
+ * result — otherwise the API call is pure cost, paid on every event:
27
+ * - no instances, or no `match` → nothing to decide (with no `match` every instance fires);
28
+ * - declarative `match`, and no instance fills any of its params → every instance matches regardless,
29
+ * since an empty param means "any". This is the v1 rule: read the resource only when a flow filters.
30
+ * A predicate `match` is opaque, so the hook runs and receives the instances to make that call itself.
31
+ */
32
+ needsMatchData(instances: RealtimeInstance[]): boolean;
33
+ extendMatchData(providerEventData: ProviderPayload, instances: RealtimeInstance[], ctx: ExecutionContext, webhookData?: ProviderPayload): Promise<Record<string, unknown> | void> | Record<string, unknown> | void;
24
34
  /**
25
35
  * Whether one CONFIGURED INSTANCE of this trigger cares about an event. Declarative form: type-coerced
26
36
  * equality per filled param, where an empty param means "any" — that is what lets a user leave a filter
@@ -30,7 +40,7 @@ export declare class RealtimeTriggerMethod extends ExtensionMethod implements Lo
30
40
  * subscription registered (a tenant id, a resource the webhook was scoped to) has nowhere else to get it.
31
41
  * Returning a new document is not a thing this seam can do; only subscribe/refresh/unsubscribe persist.
32
42
  */
33
- matches(params: Record<string, unknown>, providerEventData: ProviderPayload, webhookData?: ProviderPayload): boolean;
43
+ matches(params: Record<string, unknown>, providerEventData: ProviderPayload, webhookData?: ProviderPayload): Promise<boolean>;
34
44
  extendResult(providerEventData: ProviderPayload, ctx: ExecutionContext, webhookData?: ProviderPayload): Promise<unknown> | unknown;
35
45
  hasExtendResult(): boolean;
36
46
  toModel(): SharedExtensionMethod;
@@ -66,7 +66,7 @@ export interface RealtimeSetupProps<TShape extends ExtensionShape = AnyShape> {
66
66
  verify?: RealtimeVerify<TShape>;
67
67
  handshake?: (bag: InboundBag<TShape> & {
68
68
  requestBody: ProviderPayload;
69
- }) => HandshakeResult | void | Promise<HandshakeResult | void>;
69
+ }) => HandshakeResult | boolean | void | Promise<HandshakeResult | boolean | void>;
70
70
  subscribe: (bag: HandlerBag<TShape> & {
71
71
  callbackUrl: string;
72
72
  triggers: RealtimeSubTrigger[];
@@ -116,11 +116,16 @@ export interface RealtimeTriggerProps<TShape extends ExtensionShape = AnyShape,
116
116
  requestBody: ProviderPayload;
117
117
  providerEventData: ProviderPayload;
118
118
  }) => Record<string, unknown>;
119
+ extendMatchData?: (bag: HandlerBag<TShape> & {
120
+ providerEventData: ProviderPayload;
121
+ webhookData: ProviderPayload;
122
+ instances: RealtimeInstance<Infer<TParams>>[];
123
+ }) => Record<string, unknown> | void | Promise<Record<string, unknown> | void>;
119
124
  match?: Record<string, string> | ((bag: {
120
125
  params: Infer<TParams>;
121
126
  providerEventData: ProviderPayload;
122
127
  webhookData: ProviderPayload;
123
- }) => boolean);
128
+ }) => boolean | Promise<boolean>);
124
129
  extendResult?: (bag: HandlerBag<TShape> & {
125
130
  providerEventData: ProviderPayload;
126
131
  webhookData: ProviderPayload;
@@ -129,6 +134,10 @@ export interface RealtimeTriggerProps<TShape extends ExtensionShape = AnyShape,
129
134
  logo?: string;
130
135
  appearanceColors?: [string, string];
131
136
  }
137
+ export interface RealtimeInstance<TParams = Record<string, unknown>> {
138
+ id: string;
139
+ params: TParams;
140
+ }
132
141
  export interface RealtimeInvocation {
133
142
  callbackUrl?: string;
134
143
  events?: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowrunner/cli",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
package/runtime/index.js CHANGED
@@ -4094,7 +4094,7 @@ var OAuth2 = class {
4094
4094
  {
4095
4095
  name: REFRESH_TOKEN,
4096
4096
  scheme: z.object({ refreshToken: RefreshTokenSchema }),
4097
- run: ({ refreshToken }, ctx) => this.#refresh(refreshToken, anonymous(ctx))
4097
+ run: ({ refreshToken }, ctx) => this.#refresh(refreshToken, ctx)
4098
4098
  }
4099
4099
  ]);
4100
4100
  }
@@ -4532,7 +4532,15 @@ function readExtract(extract, body) {
4532
4532
  return void 0;
4533
4533
  }
4534
4534
  function isEmptyBody(body) {
4535
- return body == null || typeof body === "object" && Object.keys(body).length === 0;
4535
+ return body == null || body === "" || typeof body === "object" && Object.keys(body).length === 0;
4536
+ }
4537
+ function hasHandshakeResponse(result) {
4538
+ return result.responseToExternalService !== void 0 || !!result.responseHeaders || !!result.responseToWebhook;
4539
+ }
4540
+ function handshakeErrorStatus(error) {
4541
+ const { statusCode, status } = error ?? {};
4542
+ const candidate = typeof statusCode === "number" ? statusCode : status;
4543
+ return typeof candidate === "number" && candidate >= 400 && candidate < 500 ? candidate : 400;
4536
4544
  }
4537
4545
  var RealtimeSetup = class {
4538
4546
  constructor(extension, props) {
@@ -4643,19 +4651,9 @@ var RealtimeSetup = class {
4643
4651
  const body = invocation.body;
4644
4652
  const rawBody = invocation.rawBody;
4645
4653
  const webhookData = invocation.webhookData ?? null;
4646
- if (this.props.handshake) {
4647
- const result = await this.props.handshake(ctx.bagWith({ requestBody: body, headers, rawBody, webhookData }));
4648
- if (result && (result.responseToExternalService !== void 0 || result.responseHeaders || result.responseToWebhook)) {
4649
- return {
4650
- handshake: true,
4651
- responseToExternalService: result.responseToExternalService,
4652
- responseHeaders: result.responseHeaders,
4653
- responseToWebhook: result.responseToWebhook
4654
- };
4655
- }
4656
- }
4657
- if (isEmptyBody(body)) {
4658
- return { handshake: true, events: [] };
4654
+ const handshake = await this.#handshake(body, headers, rawBody, webhookData, ctx);
4655
+ if (handshake) {
4656
+ return handshake;
4659
4657
  }
4660
4658
  if (!await this.#verify(rawBody, headers, webhookData, ctx)) {
4661
4659
  ctx.logger.warn(`[flow-extension:${this.extension.id}] webhook signature verification failed \u2014 answering 401`);
@@ -4696,6 +4694,52 @@ var RealtimeSetup = class {
4696
4694
  return { events, eventScopeId, connectionId: invocation.connectionId };
4697
4695
  }
4698
4696
  // The author's own check wins; otherwise the declarative one; otherwise nothing was asked for.
4697
+ /**
4698
+ * Whether this delivery is an endpoint-verification handshake, and if so the answer to it; `null` → proceed.
4699
+ *
4700
+ * Without a `handshake` hook the default applies: an EMPTY body is a handshake, acked with a plain 200 —
4701
+ * the URL-verification ping most providers send. A declared hook REPLACES that default rather than running
4702
+ * before it, so it alone decides: some providers deliver real events with no body at all (Google Drive
4703
+ * puts everything in `X-Goog-*` headers), and a hook that can't overrule the empty-body rule leaves them
4704
+ * no way to reach `resolveEvents`.
4705
+ *
4706
+ * `true` → handshake, plain 200
4707
+ * `{ responseToWebhook, … }` → handshake, answered with that response
4708
+ * nothing / `false` / `{}` → not a handshake, the delivery proceeds
4709
+ * throws → answered with the error, as a 4xx carrying its message
4710
+ *
4711
+ * The throw is turned into a RESPONSE for the same reason a failed signature check is: a throw leaves the
4712
+ * pod as a failed invocation and the provider receives a 500 telling it nothing. The hook runs BEFORE
4713
+ * verification, so the message reaches an unverified caller — throw what the provider may read.
4714
+ */
4715
+ async #handshake(body, headers, rawBody, webhookData, ctx) {
4716
+ if (!this.props.handshake) {
4717
+ return isEmptyBody(body) ? { handshake: true, events: [] } : null;
4718
+ }
4719
+ let result;
4720
+ try {
4721
+ result = await this.props.handshake(ctx.bagWith({ requestBody: body, headers, rawBody, webhookData }));
4722
+ } catch (error) {
4723
+ const message = error?.message ?? String(error);
4724
+ ctx.logger.error(`[flow-extension:${this.extension.id}] handshake failed \u2014 ${message}`);
4725
+ return {
4726
+ events: [],
4727
+ responseToWebhook: { httpStatus: handshakeErrorStatus(error), body: { message } }
4728
+ };
4729
+ }
4730
+ if (result === true) {
4731
+ return { handshake: true, events: [] };
4732
+ }
4733
+ if (result && typeof result === "object" && hasHandshakeResponse(result)) {
4734
+ return {
4735
+ handshake: true,
4736
+ responseToExternalService: result.responseToExternalService,
4737
+ responseHeaders: result.responseHeaders,
4738
+ responseToWebhook: result.responseToWebhook
4739
+ };
4740
+ }
4741
+ return null;
4742
+ }
4699
4743
  async #verify(rawBody, headers, webhookData, ctx) {
4700
4744
  if (this.props.verifyRequest) {
4701
4745
  return !!await this.props.verifyRequest(ctx.bagWith({ rawBody, headers, webhookData, config: ctx.config }));
@@ -4705,6 +4749,26 @@ var RealtimeSetup = class {
4705
4749
  }
4706
4750
  return true;
4707
4751
  }
4752
+ /**
4753
+ * The event data `match` decides on: the delivered data plus whatever `extendMatchData` fetched, read ONCE
4754
+ * for every instance — the case is an id-only webhook (Xero names an invoice, not its type or status) whose
4755
+ * instance filters need the resource itself.
4756
+ *
4757
+ * A failed read is NOT a failed delivery. Select is the data plane: nothing is waiting on it, and a throw
4758
+ * would abort the delivery's other events. So it is logged and the instances are matched against the data
4759
+ * that WAS delivered — an instance filtering on the missing fields declines, an unfiltered one still fires.
4760
+ */
4761
+ async #withMatchData(trigger, eventData, instances, webhookData, ctx) {
4762
+ try {
4763
+ const extra = await trigger.extendMatchData(eventData, instances, ctx, webhookData);
4764
+ return extra && typeof extra === "object" ? { ...eventData, ...extra } : eventData;
4765
+ } catch (error) {
4766
+ ctx.logger.warn(
4767
+ `[flow-extension:${this.extension.id}] extendMatchData of "${trigger.id}" failed \u2014 matching on the delivered data: ${error?.message ?? error}`
4768
+ );
4769
+ return eventData;
4770
+ }
4771
+ }
4708
4772
  // Fan one resolved event out over the configured instances of its trigger. An `eventName` this service
4709
4773
  // does not declare is DECLINED outright — `{ ids: [], enrichedEventData: null }`, no instance offered up
4710
4774
  // and no per-event seam run. That is deliberately not the same case as a trigger which declares no
@@ -4720,15 +4784,22 @@ var RealtimeSetup = class {
4720
4784
  if (!trigger) {
4721
4785
  return { ids: [], enrichedEventData: null };
4722
4786
  }
4723
- const eventData = invocation.eventData;
4724
4787
  const webhookData = invocation.webhookData ?? null;
4725
- const ids = (invocation.triggers ?? []).filter((instance) => trigger.matches(instance.data ?? {}, eventData, webhookData)).map((instance) => instance.id);
4788
+ const instances = (invocation.triggers ?? []).map((instance) => ({ id: instance.id, params: instance.data ?? {} }));
4789
+ const eventData = trigger.needsMatchData(instances) ? await this.#withMatchData(trigger, invocation.eventData, instances, webhookData, ctx) : invocation.eventData;
4790
+ const verdicts = await Promise.all(
4791
+ instances.map((instance) => trigger.matches(instance.params, eventData, webhookData))
4792
+ );
4793
+ const ids = instances.filter((_instance, index) => verdicts[index]).map((instance) => instance.id);
4726
4794
  const enrichedEventData = ids.length && trigger.hasExtendResult() ? await trigger.extendResult(eventData, ctx, webhookData) : null;
4727
4795
  return { ids, enrichedEventData };
4728
4796
  }
4729
4797
  };
4730
4798
 
4731
4799
  // ../../flow-extension-runner/src/v2/realtime-triggers/trigger-method.ts
4800
+ function isFilled(value) {
4801
+ return value != null && value !== "";
4802
+ }
4732
4803
  var RealtimeTriggerMethod = class extends ExtensionMethod {
4733
4804
  constructor(extension, props) {
4734
4805
  super(extension);
@@ -4780,6 +4851,30 @@ var RealtimeTriggerMethod = class extends ExtensionMethod {
4780
4851
  extendEventData(requestBody, providerEventData) {
4781
4852
  return this.props.extendEventData?.({ requestBody, providerEventData });
4782
4853
  }
4854
+ /**
4855
+ * Whether `extendMatchData` should run before these instances are matched. Only when something will READ its
4856
+ * result — otherwise the API call is pure cost, paid on every event:
4857
+ * - no instances, or no `match` → nothing to decide (with no `match` every instance fires);
4858
+ * - declarative `match`, and no instance fills any of its params → every instance matches regardless,
4859
+ * since an empty param means "any". This is the v1 rule: read the resource only when a flow filters.
4860
+ * A predicate `match` is opaque, so the hook runs and receives the instances to make that call itself.
4861
+ */
4862
+ needsMatchData(instances) {
4863
+ const match = this.props.match;
4864
+ if (typeof this.props.extendMatchData !== "function" || !match || !instances.length) {
4865
+ return false;
4866
+ }
4867
+ if (typeof match === "function") {
4868
+ return true;
4869
+ }
4870
+ const filterKeys = Object.keys(match);
4871
+ return instances.some((instance) => filterKeys.some((key) => isFilled(instance.params[key])));
4872
+ }
4873
+ // Runs ONCE per event, before any instance is matched, with the full handler bag (`apiRequest` on the
4874
+ // connection's token) — for an instance filter on data the delivery does not carry.
4875
+ extendMatchData(providerEventData, instances, ctx, webhookData = null) {
4876
+ return this.props.extendMatchData?.(ctx.bagWith({ providerEventData, webhookData, instances }));
4877
+ }
4783
4878
  /**
4784
4879
  * Whether one CONFIGURED INSTANCE of this trigger cares about an event. Declarative form: type-coerced
4785
4880
  * equality per filled param, where an empty param means "any" — that is what lets a user leave a filter
@@ -4789,17 +4884,17 @@ var RealtimeTriggerMethod = class extends ExtensionMethod {
4789
4884
  * subscription registered (a tenant id, a resource the webhook was scoped to) has nowhere else to get it.
4790
4885
  * Returning a new document is not a thing this seam can do; only subscribe/refresh/unsubscribe persist.
4791
4886
  */
4792
- matches(params, providerEventData, webhookData = null) {
4887
+ async matches(params, providerEventData, webhookData = null) {
4793
4888
  const match = this.props.match;
4794
4889
  if (!match) {
4795
4890
  return true;
4796
4891
  }
4797
4892
  if (typeof match === "function") {
4798
- return !!match({ params, providerEventData, webhookData });
4893
+ return !!await match({ params, providerEventData, webhookData });
4799
4894
  }
4800
4895
  for (const [paramKey, path2] of Object.entries(match)) {
4801
4896
  const paramValue = params[paramKey];
4802
- if (paramValue == null || paramValue === "") {
4897
+ if (!isFilled(paramValue)) {
4803
4898
  continue;
4804
4899
  }
4805
4900
  if (`${paramValue}` !== `${getPath(providerEventData, path2)}`) {