@middag-io/n8n-nodes-middag 0.3.1 → 0.4.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/README.md CHANGED
@@ -33,8 +33,9 @@ For each request the node does this, in order:
33
33
  (for example `{}`, which n8n leaves for a content type it does not parse), the node answers
34
34
  400 `missing_body`.
35
35
  2. Checks the CloudEvent envelope. If the body is not a CloudEvent, it answers 400.
36
- 3. Filters by **Event Types** (catalog `<entity>.<action>`, e.g. `form.submitted`) and
37
- **Providers** (e.g. `hubspot`). Empty means all. Other events get 200 `{ignored: true}`.
36
+ 3. Filters by **Event Types** (catalog `<entity>.<action>`, e.g. `form.submitted`),
37
+ **Providers** (`hubspot`, `activecampaign`) and **Sources** (CloudEvent `source`).
38
+ Empty means all. Other events get 200 `{ignored: true}`.
38
39
  4. Dedupes on `X-Middag-Delivery-Id`. A repeat gets 200 `{duplicate: true}`. The dedupe is
39
40
  best effort: it lives in the workflow static data and keeps the last 500 ids.
40
41
  5. Answers 200 and emits one item:
@@ -54,11 +55,31 @@ For each request the node does this, in order:
54
55
 
55
56
  `event` is the CloudEvent exactly as received. Read the payload from `event.data`. Its shape per
56
57
  type is in the Connector contracts (`@middag-io/connector-contracts`, `schema/data/*`).
58
+ `data` also depends on `provider`: an `activecampaign` `form.submitted` has no `portalId` and
59
+ no `action`. It names the account in `externalAccountId` and the person in `contact`. Check
60
+ `event.provider` before you read provider-specific fields.
57
61
 
58
62
  The trigger always answers the request itself. If the workflow fails later, call
59
63
  **MIDDAG Connector > Delivery > Retry** with the event. The Connector then redelivers it with a
60
64
  new `X-Middag-Delivery-Id`.
61
65
 
66
+ #### Options from the instance catalog
67
+
68
+ **Instance ID** (optional) is the ULID (e.g. `01M85RX3YKFDDRBNWZ0HJCWA56`) of an ActiveCampaign instance in the Connector. Find it
69
+ in the Connector admin, in the instance list of the tenant. When it is filled, the editor loads
70
+ **Event Types** and **Sources** from `GET /internal/catalog/<instanceId>/options`, with the
71
+ credential's Cloudflare Access service token. When it is empty, **Event Types** shows the static
72
+ list and **Sources** is empty. Workflows saved without it keep working unchanged.
73
+
74
+ - An event type appears once, and its description lists its canais.
75
+ - A source shows as `name (cloudeventSource)`. Its value is the CloudEvent `source`.
76
+ - Disabled entries still appear, with the suffix " (desativado)", after the enabled ones.
77
+ - The catalog serves only ActiveCampaign instances. A HubSpot or unknown instance gives
78
+ "Instância não encontrada", an inactive one "Instância inativa". A 401/403 means the
79
+ Cloudflare Access application does not cover `/internal/catalog/*` for the service token.
80
+ - Only the editor calls the catalog. The webhook never does, so a catalog outage does not stop
81
+ deliveries.
82
+
62
83
  ### Version 1 (legacy)
63
84
 
64
85
  Version 1 is unchanged and is kept for existing workflows of the legacy HubSpot Worker
@@ -69,12 +90,13 @@ with `No Webhook node found in the workflow`, and v1 answers an empty 200.
69
90
  ## MIDDAG Connector
70
91
 
71
92
  The node builds its operations from a catalog (`nodes/MiddagConnector/operations.ts`). There is
72
- one node for all providers.
93
+ one node for all providers, but not every operation fits every provider: **Event > Record** is
94
+ HubSpot only, **Delivery > Retry** works for any provider (for example `activecampaign`).
73
95
 
74
96
  | Resource | Operation | Route |
75
97
  | --- | --- | --- |
76
- | Event | Record | `POST /internal/events` (`events.record`: `order_created`, `order_paid`, ...) |
77
- | Delivery | Retry | `POST /internal/deliveries/retry` (`event`, `attempt`, `reason`) |
98
+ | Event | Record | `POST /internal/events` (`events.record`: `order_created`, `order_paid`, ...). HubSpot only: it writes a HubSpot timeline event. Do not call it for `activecampaign` events. |
99
+ | Delivery | Retry | `POST /internal/deliveries/retry` (`event`, `attempt`, `reason`). Any provider. |
78
100
 
79
101
  The node returns the `data` of the Connector response. If the Connector answers 4xx or 5xx, the
80
102
  node fails with `MIDDAG Connector returned <status> <code>: <message>`. If **Continue on Fail**
@@ -5,8 +5,9 @@ import type { ICredentialType, INodeProperties } from 'n8n-workflow';
5
5
  * - `signingSecret`: the account's destination signing secret, used by MiddagTrigger to verify
6
6
  * `X-Middag-Signature` on deliveries (docs/05-contratos-worker.md, "Entregas do Worker ao n8n").
7
7
  * - `accessClientId` / `accessClientSecret`: Cloudflare Access service token, used by
8
- * MiddagHubspot to call the Worker's internal routes (`/internal/hubspot/*`, `/internal/events`)
9
- * as `CF-Access-Client-Id` / `CF-Access-Client-Secret` headers.
8
+ * MiddagHubspot, MiddagConnector and MiddagTrigger (editor option lists) to call the Worker's
9
+ * internal routes (`/internal/hubspot/*`, `/internal/events`, `/internal/catalog/*`) as
10
+ * `CF-Access-Client-Id` / `CF-Access-Client-Secret` headers.
10
11
  */
11
12
  export declare class MiddagConnectorApi implements ICredentialType {
12
13
  name: string;
@@ -7,8 +7,9 @@ exports.MiddagConnectorApi = void 0;
7
7
  * - `signingSecret`: the account's destination signing secret, used by MiddagTrigger to verify
8
8
  * `X-Middag-Signature` on deliveries (docs/05-contratos-worker.md, "Entregas do Worker ao n8n").
9
9
  * - `accessClientId` / `accessClientSecret`: Cloudflare Access service token, used by
10
- * MiddagHubspot to call the Worker's internal routes (`/internal/hubspot/*`, `/internal/events`)
11
- * as `CF-Access-Client-Id` / `CF-Access-Client-Secret` headers.
10
+ * MiddagHubspot, MiddagConnector and MiddagTrigger (editor option lists) to call the Worker's
11
+ * internal routes (`/internal/hubspot/*`, `/internal/events`, `/internal/catalog/*`) as
12
+ * `CF-Access-Client-Id` / `CF-Access-Client-Secret` headers.
12
13
  */
13
14
  class MiddagConnectorApi {
14
15
  constructor() {
@@ -2,7 +2,8 @@ import type { IExecuteFunctions, INodeExecutionData, INodeType, INodeTypeDescrip
2
2
  /**
3
3
  * MIDDAG Connector: actions of the connector worker, generated from the operation catalog
4
4
  * (operations.ts). One node for every provider; the provider is chosen by the worker from the
5
- * instance, not by the node.
5
+ * instance, not by the node. Not every operation fits every provider: Event Record writes a
6
+ * HubSpot timeline event (HubSpot only), Delivery Retry works for any provider.
6
7
  */
7
8
  export declare class MiddagConnector implements INodeType {
8
9
  description: INodeTypeDescription;
@@ -2,16 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MiddagConnector = void 0;
4
4
  const nodeOperationError_1 = require("../shared/nodeOperationError");
5
+ const connectorHttp_1 = require("../shared/connectorHttp");
5
6
  const operations_1 = require("./operations");
6
- const FIRST_ERROR_STATUS = 400;
7
- /** Error answered by the worker, with its status and `{error: {code}}` when it sent one. */
8
- class ConnectorHttpError extends Error {
9
- constructor(message, statusCode, code) {
10
- super(message);
11
- this.statusCode = statusCode;
12
- this.code = code;
13
- }
14
- }
15
7
  function resourceProperty() {
16
8
  const resources = new Map(operations_1.CONNECTOR_OPERATIONS.map((op) => [op.resource, op.resourceName]));
17
9
  const [first] = operations_1.CONNECTOR_OPERATIONS;
@@ -45,19 +37,8 @@ function fieldProperties() {
45
37
  displayOptions: { show: { resource: [op.resource], operation: [op.operation] } },
46
38
  })));
47
39
  }
48
- function unwrap(response) {
49
- const envelope = (typeof response.body === 'object' && response.body !== null
50
- ? response.body
51
- : {});
52
- if (response.statusCode >= FIRST_ERROR_STATUS) {
53
- const code = envelope.error?.code ?? null;
54
- const detail = code ? ` ${code}: ${envelope.error?.message ?? ''}`.trimEnd() : '';
55
- throw new ConnectorHttpError(`MIDDAG Connector returned ${response.statusCode}${detail}`, response.statusCode, code);
56
- }
57
- return (envelope.data ?? envelope);
58
- }
59
40
  function errorItem(error) {
60
- if (error instanceof ConnectorHttpError) {
41
+ if (error instanceof connectorHttp_1.ConnectorHttpError) {
61
42
  return { error: error.message, statusCode: error.statusCode, code: error.code };
62
43
  }
63
44
  return { error: error instanceof Error ? error.message : String(error) };
@@ -65,7 +46,8 @@ function errorItem(error) {
65
46
  /**
66
47
  * MIDDAG Connector: actions of the connector worker, generated from the operation catalog
67
48
  * (operations.ts). One node for every provider; the provider is chosen by the worker from the
68
- * instance, not by the node.
49
+ * instance, not by the node. Not every operation fits every provider: Event Record writes a
50
+ * HubSpot timeline event (HubSpot only), Delivery Retry works for any provider.
69
51
  */
70
52
  class MiddagConnector {
71
53
  constructor() {
@@ -109,14 +91,14 @@ class MiddagConnector {
109
91
  ignoreHttpStatusErrors: true,
110
92
  };
111
93
  const response = (await this.helpers.httpRequest(options));
112
- returnData.push({ json: unwrap(response), pairedItem: { item: i } });
94
+ returnData.push({ json: (0, connectorHttp_1.unwrap)(response), pairedItem: { item: i } });
113
95
  }
114
96
  catch (error) {
115
97
  if (this.continueOnFail()) {
116
98
  returnData.push({ json: errorItem(error), pairedItem: { item: i } });
117
99
  continue;
118
100
  }
119
- if (error instanceof operations_1.InvalidParameterError || error instanceof ConnectorHttpError) {
101
+ if (error instanceof operations_1.InvalidParameterError || error instanceof connectorHttp_1.ConnectorHttpError) {
120
102
  throw new nodeOperationError_1.NodeOperationError(this.getNode(), error.message);
121
103
  }
122
104
  throw error;
@@ -19,7 +19,10 @@ export type ConnectorOperation = {
19
19
  readonly fields: readonly INodeProperties[];
20
20
  readonly buildBody: (read: ParameterReader) => IDataObject;
21
21
  };
22
- /** `events.record` types (provider-hubspot src/domain/account-config.ts EVENT_TYPES). */
22
+ /**
23
+ * `events.record` types (provider-hubspot src/domain/account-config.ts EVENT_TYPES). The route
24
+ * writes a HubSpot timeline event, so it is HubSpot-only: the Connector only reads ActiveCampaign.
25
+ */
23
26
  export declare const RECORD_EVENT_TYPES: readonly ["order_created", "order_paid", "order_shipped", "order_updated", "product_viewed", "cart_updated", "generic_event"];
24
27
  export declare class InvalidParameterError extends Error {
25
28
  }
@@ -2,7 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CONNECTOR_OPERATIONS = exports.InvalidParameterError = exports.RECORD_EVENT_TYPES = void 0;
4
4
  exports.operationFor = operationFor;
5
- /** `events.record` types (provider-hubspot src/domain/account-config.ts EVENT_TYPES). */
5
+ /**
6
+ * `events.record` types (provider-hubspot src/domain/account-config.ts EVENT_TYPES). The route
7
+ * writes a HubSpot timeline event, so it is HubSpot-only: the Connector only reads ActiveCampaign.
8
+ */
6
9
  exports.RECORD_EVENT_TYPES = [
7
10
  'order_created',
8
11
  'order_paid',
@@ -75,7 +78,7 @@ const RECORD_EVENT = {
75
78
  resourceName: 'Event',
76
79
  operation: 'record',
77
80
  name: 'Record',
78
- action: 'Record an event on the CRM',
81
+ action: 'Record an event on the HubSpot timeline',
79
82
  method: 'POST',
80
83
  path: 'internal/events',
81
84
  buildBody: recordEventBody,
@@ -86,7 +89,7 @@ const RECORD_EVENT = {
86
89
  type: 'number',
87
90
  default: 0,
88
91
  required: true,
89
- description: 'HubSpot portal (account) ID of the Connector instance.',
92
+ description: 'HubSpot portal (account) ID of the Connector instance. Record is HubSpot-only.',
90
93
  },
91
94
  {
92
95
  displayName: 'Event Type',
@@ -1,9 +1,9 @@
1
- import type { IWebhookFunctions, IWebhookResponseData, INodeType, INodeTypeDescription, IDataObject } from 'n8n-workflow';
1
+ import type { IWebhookFunctions, IWebhookResponseData, INodeType, INodeTypeDescription, IDataObject, ILoadOptionsFunctions, INodePropertyOptions } from 'n8n-workflow';
2
2
  /**
3
3
  * Version 2 (default for new nodes) receives the CloudEvents (`application/cloudevents+json`) of
4
4
  * the MIDDAG Connector worker (`worker-ts-middag-connector-hubspot`, packages/contracts): it
5
5
  * verifies `X-Middag-Signature` over the raw body (or, when n8n did not keep it, over the
6
- * re-serialized parsed body), filters by `type` (catalog) and `provider`,
6
+ * re-serialized parsed body), filters by `type` (catalog), `provider` and `source`,
7
7
  * dedupes on `X-Middag-Delivery-Id` and always answers the HTTP request itself. Its output item is
8
8
  * `{ deliveryId, event }`, with the CloudEvent unchanged (read `event.data`). See
9
9
  * cloudEventDelivery.ts.
@@ -25,6 +25,12 @@ import type { IWebhookFunctions, IWebhookResponseData, INodeType, INodeTypeDescr
25
25
  */
26
26
  export declare class MiddagTrigger implements INodeType {
27
27
  description: INodeTypeDescription;
28
+ methods: {
29
+ loadOptions: {
30
+ getEventTypes(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]>;
31
+ getSources(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]>;
32
+ };
33
+ };
28
34
  webhook(this: IWebhookFunctions): Promise<IWebhookResponseData>;
29
35
  }
30
36
  /**
@@ -5,6 +5,7 @@ exports.outputItemFor = outputItemFor;
5
5
  const middagSignature_1 = require("../shared/middagSignature");
6
6
  const deliveryDedupe_1 = require("../shared/deliveryDedupe");
7
7
  const eventCatalog_1 = require("../shared/eventCatalog");
8
+ const catalogOptions_1 = require("../shared/catalogOptions");
8
9
  const cloudEventDelivery_1 = require("./cloudEventDelivery");
9
10
  const DELIVERY_ID_HEADER = 'x-middag-delivery-id';
10
11
  const CLOUDEVENTS_VERSION = 2;
@@ -12,7 +13,7 @@ const CLOUDEVENTS_VERSION = 2;
12
13
  * Version 2 (default for new nodes) receives the CloudEvents (`application/cloudevents+json`) of
13
14
  * the MIDDAG Connector worker (`worker-ts-middag-connector-hubspot`, packages/contracts): it
14
15
  * verifies `X-Middag-Signature` over the raw body (or, when n8n did not keep it, over the
15
- * re-serialized parsed body), filters by `type` (catalog) and `provider`,
16
+ * re-serialized parsed body), filters by `type` (catalog), `provider` and `source`,
16
17
  * dedupes on `X-Middag-Delivery-Id` and always answers the HTTP request itself. Its output item is
17
18
  * `{ deliveryId, event }`, with the CloudEvent unchanged (read `event.data`). See
18
19
  * cloudEventDelivery.ts.
@@ -72,11 +73,23 @@ class MiddagTrigger {
72
73
  required: true,
73
74
  description: 'Webhook path. Configure this exact URL as the account destination.n8nUrl.',
74
75
  },
76
+ {
77
+ displayName: 'Instance ID',
78
+ name: 'instanceId',
79
+ type: 'string',
80
+ default: '',
81
+ placeholder: '00000000-0000-0000-0000-000000000000',
82
+ displayOptions: { show: { '@version': [CLOUDEVENTS_VERSION] } },
83
+ description: 'ULID of the ActiveCampaign instance in the Connector. Filled: Event Types are loaded from its catalog. Empty: the static list is used.',
84
+ },
75
85
  {
76
86
  displayName: 'Event Types',
77
87
  name: 'eventTypes',
78
88
  type: 'multiOptions',
79
- options: eventCatalog_1.EVENT_TYPES.map((type) => ({ name: type, value: type })),
89
+ typeOptions: {
90
+ loadOptionsMethod: 'getEventTypes',
91
+ loadOptionsDependsOn: ['instanceId'],
92
+ },
80
93
  default: [],
81
94
  displayOptions: { show: { '@version': [CLOUDEVENTS_VERSION] } },
82
95
  description: 'CloudEvent types that start the workflow. Leave empty for every type. Other types are acknowledged (200) and ignored.',
@@ -90,6 +103,18 @@ class MiddagTrigger {
90
103
  displayOptions: { show: { '@version': [CLOUDEVENTS_VERSION] } },
91
104
  description: 'Providers (CloudEvent provider attribute) that start the workflow. Leave empty for every provider.',
92
105
  },
106
+ {
107
+ displayName: 'Sources',
108
+ name: 'sources',
109
+ type: 'multiOptions',
110
+ typeOptions: {
111
+ loadOptionsMethod: 'getSources',
112
+ loadOptionsDependsOn: ['instanceId'],
113
+ },
114
+ default: [],
115
+ displayOptions: { show: { '@version': [CLOUDEVENTS_VERSION] } },
116
+ description: 'Sources (CloudEvent source attribute) that start the workflow, loaded from the instance catalog. Leave empty for every source.',
117
+ },
93
118
  {
94
119
  displayName: 'Deliveries are acknowledged with 200 as soon as they are verified. If the workflow fails later, use the MIDDAG Connector node (Delivery: Retry) to have the Connector redeliver the event.',
95
120
  name: 'ackNotice',
@@ -107,6 +132,22 @@ class MiddagTrigger {
107
132
  },
108
133
  ],
109
134
  };
135
+ this.methods = {
136
+ loadOptions: {
137
+ async getEventTypes() {
138
+ const instanceId = instanceIdOf(this);
139
+ if (!instanceId)
140
+ return eventCatalog_1.EVENT_TYPES.map((type) => ({ name: type, value: type }));
141
+ return (0, catalogOptions_1.toEventTypeOptions)(await (0, catalogOptions_1.fetchCatalog)(this, instanceId));
142
+ },
143
+ async getSources() {
144
+ const instanceId = instanceIdOf(this);
145
+ if (!instanceId)
146
+ return [];
147
+ return (0, catalogOptions_1.toSourceOptions)(await (0, catalogOptions_1.fetchCatalog)(this, instanceId));
148
+ },
149
+ },
150
+ };
110
151
  }
111
152
  async webhook() {
112
153
  if (this.getNode().typeVersion >= CLOUDEVENTS_VERSION)
@@ -172,6 +213,7 @@ async function cloudEventWebhook(ctx) {
172
213
  parsedBody: rawBody === undefined ? ctx.getBodyData() : undefined,
173
214
  eventTypes: ctx.getNodeParameter('eventTypes', []),
174
215
  providers: ctx.getNodeParameter('providers', []),
216
+ sources: sourcesFilterOf(ctx),
175
217
  staticData: ctx.getWorkflowStaticData('node'),
176
218
  });
177
219
  ctx.getResponseObject().status(result.status).json(result.body);
@@ -179,6 +221,21 @@ async function cloudEventWebhook(ctx) {
179
221
  return { noWebhookResponse: true };
180
222
  return { noWebhookResponse: true, workflowData: [[{ json: result.item }]] };
181
223
  }
224
+ /**
225
+ * Sources are picked from one instance's catalog, so they only apply while instanceId is set.
226
+ * Without it the picker shows nothing, and stale selections would silently drop deliveries.
227
+ */
228
+ function sourcesFilterOf(ctx) {
229
+ const instanceId = ctx.getNodeParameter('instanceId', '');
230
+ if (typeof instanceId !== 'string' || instanceId.trim() === '')
231
+ return [];
232
+ return ctx.getNodeParameter('sources', []);
233
+ }
234
+ /** Trimmed instanceId of the node being edited; empty means "use the static lists". */
235
+ function instanceIdOf(ctx) {
236
+ const value = ctx.getCurrentNodeParameter('instanceId');
237
+ return typeof value === 'string' ? value.trim() : '';
238
+ }
182
239
  function firstValue(value) {
183
240
  return Array.isArray(value) ? value[0] : value;
184
241
  }
@@ -18,6 +18,8 @@ export type CloudEventDeliveryInput = {
18
18
  readonly eventTypes: readonly string[];
19
19
  /** Selected providers; empty means every provider. */
20
20
  readonly providers: readonly string[];
21
+ /** Selected CloudEvent `source` attributes; empty or omitted means every source. */
22
+ readonly sources?: readonly string[];
21
23
  /** n8n workflow static data of the node; the dedupe list is written into it. */
22
24
  readonly staticData: DedupeStaticData;
23
25
  readonly nowMs?: number;
@@ -34,7 +36,7 @@ export type CloudEventDeliveryResult = {
34
36
  };
35
37
  /**
36
38
  * MIDDAG Trigger v2: one delivery from the connector worker. Order: signature, envelope,
37
- * type/provider filter, dedupe, emit. Every answer is final here (the node never defers the
39
+ * type/provider/source filter, dedupe, emit. Every answer is final here (the node never defers the
38
40
  * response): a failure later in the workflow is reported back with the MIDDAG Connector node's
39
41
  * "Retry Delivery" operation, which asks the worker to redeliver.
40
42
  */
@@ -39,7 +39,7 @@ function signedBodyOf(input) {
39
39
  }
40
40
  /**
41
41
  * MIDDAG Trigger v2: one delivery from the connector worker. Order: signature, envelope,
42
- * type/provider filter, dedupe, emit. Every answer is final here (the node never defers the
42
+ * type/provider/source filter, dedupe, emit. Every answer is final here (the node never defers the
43
43
  * response): a failure later in the workflow is reported back with the MIDDAG Connector node's
44
44
  * "Retry Delivery" operation, which asks the worker to redeliver.
45
45
  */
@@ -54,7 +54,9 @@ function handleCloudEventDelivery(input) {
54
54
  if (!parsed.ok)
55
55
  return failure(HTTP_BAD_REQUEST, parsed.reason);
56
56
  const { event } = parsed;
57
- if (!isSelected(input.eventTypes, event.type) || !isSelected(input.providers, event.provider)) {
57
+ if (!isSelected(input.eventTypes, event.type) ||
58
+ !isSelected(input.providers, event.provider) ||
59
+ !isSelected(input.sources ?? [], event.source)) {
58
60
  return { status: HTTP_OK, body: { success: true, ignored: true } };
59
61
  }
60
62
  if (input.deliveryId) {
@@ -0,0 +1,24 @@
1
+ import type { ILoadOptionsFunctions, INodePropertyOptions } from 'n8n-workflow';
2
+ export type CatalogEventAction = {
3
+ readonly eventType: string;
4
+ readonly canal: string;
5
+ readonly enabled: boolean;
6
+ };
7
+ export type CatalogSource = {
8
+ readonly id: string;
9
+ readonly name: string;
10
+ readonly cloudeventSource: string;
11
+ readonly enabled: boolean;
12
+ };
13
+ export type Catalog = {
14
+ readonly eventActions: readonly CatalogEventAction[];
15
+ readonly sources: readonly CatalogSource[];
16
+ };
17
+ type CatalogContext = Pick<ILoadOptionsFunctions, 'getCredentials' | 'getNode' | 'helpers'>;
18
+ /** GET /internal/catalog/:instanceId/options with the credential's Cloudflare Access service token. */
19
+ export declare function fetchCatalog(ctx: CatalogContext, instanceId: string): Promise<Catalog>;
20
+ /** One option per event type; a type is disabled only when every one of its canais is. */
21
+ export declare function toEventTypeOptions(catalog: Catalog): INodePropertyOptions[];
22
+ /** Value is the CloudEvent `source` attribute (what the webhook filters on), not the source id. */
23
+ export declare function toSourceOptions(catalog: Catalog): INodePropertyOptions[];
24
+ export {};
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchCatalog = fetchCatalog;
4
+ exports.toEventTypeOptions = toEventTypeOptions;
5
+ exports.toSourceOptions = toSourceOptions;
6
+ const nodeOperationError_1 = require("./nodeOperationError");
7
+ const connectorHttp_1 = require("./connectorHttp");
8
+ // Connector instance ids are ULIDs (Crockford base32, 26 chars), same pattern as packages/core tenancy/ulid.ts.
9
+ const ULID_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/;
10
+ const INVALID_INSTANCE_ID_MESSAGE = 'instanceId inválido (ULID esperado).';
11
+ const DISABLED_SUFFIX = ' (desativado)';
12
+ const INVALID_PAYLOAD_MESSAGE = 'Resposta inválida do catálogo do connector.';
13
+ const NO_ACCESS_MESSAGE = 'Service token sem acesso a /internal/catalog. Verifique a credencial e a aplicação Cloudflare Access.';
14
+ const STATUS_MESSAGES = {
15
+ 400: INVALID_INSTANCE_ID_MESSAGE,
16
+ 401: NO_ACCESS_MESSAGE,
17
+ 403: NO_ACCESS_MESSAGE,
18
+ 404: 'Instância não encontrada ou não é ActiveCampaign. O catálogo só atende instâncias AC.',
19
+ 409: 'Instância inativa no connector.',
20
+ };
21
+ /** Fixed, body-free message for a failed catalog call: never echoes the response or secrets. */
22
+ function messageFor(error) {
23
+ if (error instanceof connectorHttp_1.ConnectorHttpError) {
24
+ return STATUS_MESSAGES[error.statusCode] ?? `Catálogo indisponível (status ${error.statusCode}).`;
25
+ }
26
+ return 'Catálogo indisponível (sem resposta).';
27
+ }
28
+ function isRecord(value) {
29
+ return typeof value === 'object' && value !== null;
30
+ }
31
+ function isEventAction(value) {
32
+ return (isRecord(value) &&
33
+ typeof value.eventType === 'string' &&
34
+ typeof value.canal === 'string' &&
35
+ typeof value.enabled === 'boolean');
36
+ }
37
+ function isSource(value) {
38
+ return (isRecord(value) &&
39
+ typeof value.id === 'string' &&
40
+ typeof value.name === 'string' &&
41
+ typeof value.cloudeventSource === 'string' &&
42
+ typeof value.enabled === 'boolean');
43
+ }
44
+ /** Checks every element, so a malformed 2xx fails with the fixed message, not a raw TypeError. */
45
+ function isCatalog(value) {
46
+ return (isRecord(value) &&
47
+ Array.isArray(value.eventActions) &&
48
+ value.eventActions.every(isEventAction) &&
49
+ Array.isArray(value.sources) &&
50
+ value.sources.every(isSource));
51
+ }
52
+ /** GET /internal/catalog/:instanceId/options with the credential's Cloudflare Access service token. */
53
+ async function fetchCatalog(ctx, instanceId) {
54
+ // Validate before building the URL: '.' and '..' survive encodeURIComponent and would send the
55
+ // service token to another internal route after path normalization.
56
+ if (!ULID_PATTERN.test(instanceId)) {
57
+ throw new nodeOperationError_1.NodeOperationError(ctx.getNode(), INVALID_INSTANCE_ID_MESSAGE);
58
+ }
59
+ const credentials = await ctx.getCredentials('middagConnectorApi');
60
+ const baseUrl = credentials.workerUrl.replace(/\/+$/, '');
61
+ const options = {
62
+ method: 'GET',
63
+ url: `${baseUrl}/internal/catalog/${encodeURIComponent(instanceId)}/options`,
64
+ headers: {
65
+ 'CF-Access-Client-Id': credentials.accessClientId,
66
+ 'CF-Access-Client-Secret': credentials.accessClientSecret,
67
+ },
68
+ json: true,
69
+ returnFullResponse: true,
70
+ ignoreHttpStatusErrors: true,
71
+ };
72
+ let data;
73
+ try {
74
+ data = (0, connectorHttp_1.unwrap)((await ctx.helpers.httpRequest(options)));
75
+ }
76
+ catch (error) {
77
+ throw new nodeOperationError_1.NodeOperationError(ctx.getNode(), messageFor(error));
78
+ }
79
+ if (!isCatalog(data))
80
+ throw new nodeOperationError_1.NodeOperationError(ctx.getNode(), INVALID_PAYLOAD_MESSAGE);
81
+ return data;
82
+ }
83
+ /** Enabled first, then by name; disabled entries get the "(desativado)" suffix. */
84
+ function rankOptions(options) {
85
+ return [...options]
86
+ .sort((a, b) => a.isEnabled === b.isEnabled ? a.name.localeCompare(b.name) : a.isEnabled ? -1 : 1)
87
+ .map(({ isEnabled, ...option }) => isEnabled ? option : { ...option, name: `${option.name}${DISABLED_SUFFIX}` });
88
+ }
89
+ /** One option per event type; a type is disabled only when every one of its canais is. */
90
+ function toEventTypeOptions(catalog) {
91
+ const types = [...new Set(catalog.eventActions.map((action) => action.eventType))];
92
+ const ranked = types.map((eventType) => {
93
+ const entries = catalog.eventActions.filter((action) => action.eventType === eventType);
94
+ const canais = [...new Set(entries.map((entry) => entry.canal))].sort();
95
+ return {
96
+ name: eventType,
97
+ value: eventType,
98
+ description: `Canais: ${canais.join(', ')}`,
99
+ isEnabled: entries.some((entry) => entry.enabled),
100
+ };
101
+ });
102
+ return rankOptions(ranked);
103
+ }
104
+ /** Value is the CloudEvent `source` attribute (what the webhook filters on), not the source id. */
105
+ function toSourceOptions(catalog) {
106
+ return rankOptions(catalog.sources.map((source) => ({
107
+ name: `${source.name} (${source.cloudeventSource})`,
108
+ value: source.cloudeventSource,
109
+ description: source.id,
110
+ isEnabled: source.enabled,
111
+ })));
112
+ }
@@ -0,0 +1,13 @@
1
+ import type { IDataObject } from 'n8n-workflow';
2
+ export type FullResponse = {
3
+ statusCode: number;
4
+ body: unknown;
5
+ };
6
+ /** Error answered by the worker, with its status and `{error: {code}}` when it sent one. */
7
+ export declare class ConnectorHttpError extends Error {
8
+ readonly statusCode: number;
9
+ readonly code: string | null;
10
+ constructor(message: string, statusCode: number, code: string | null);
11
+ }
12
+ /** Reads the worker envelope `{success, data, error}`; throws ConnectorHttpError on status >= 400. */
13
+ export declare function unwrap(response: FullResponse): IDataObject;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConnectorHttpError = void 0;
4
+ exports.unwrap = unwrap;
5
+ const FIRST_ERROR_STATUS = 400;
6
+ /** Error answered by the worker, with its status and `{error: {code}}` when it sent one. */
7
+ class ConnectorHttpError extends Error {
8
+ constructor(message, statusCode, code) {
9
+ super(message);
10
+ this.statusCode = statusCode;
11
+ this.code = code;
12
+ }
13
+ }
14
+ exports.ConnectorHttpError = ConnectorHttpError;
15
+ /** Reads the worker envelope `{success, data, error}`; throws ConnectorHttpError on status >= 400. */
16
+ function unwrap(response) {
17
+ const envelope = (typeof response.body === 'object' && response.body !== null
18
+ ? response.body
19
+ : {});
20
+ if (response.statusCode >= FIRST_ERROR_STATUS) {
21
+ const code = envelope.error?.code ?? null;
22
+ const detail = code ? ` ${code}: ${envelope.error?.message ?? ''}`.trimEnd() : '';
23
+ throw new ConnectorHttpError(`MIDDAG Connector returned ${response.statusCode}${detail}`, response.statusCode, code);
24
+ }
25
+ return (envelope.data ?? envelope);
26
+ }
@@ -11,6 +11,9 @@ export declare const ENTITY_ACTIONS: readonly ["created", "updated", "deleted",
11
11
  export declare const NAMED_EVENT_TYPES: readonly ["form.submitted", "card.requested", "app.installed", "app.uninstalled"];
12
12
  /** Every catalogued type: the named ones first, then `<entity>.<action>`. */
13
13
  export declare const EVENT_TYPES: readonly string[];
14
- /** Providers the Connector produces events for (`provider` extension attribute). */
14
+ /**
15
+ * Providers the Connector produces events for (`provider` extension attribute). Only the Trigger's
16
+ * filter uses this list: the envelope check accepts any provider slug, as the contracts do.
17
+ */
15
18
  export declare const PROVIDERS: readonly string[];
16
19
  export declare function isKnownEventType(type: string): boolean;
@@ -30,8 +30,11 @@ const ENTITY_EVENT_TYPES = exports.EVENT_ENTITIES.flatMap((entity) => exports.EN
30
30
  exports.EVENT_TYPES = Object.freeze([
31
31
  ...new Set([...exports.NAMED_EVENT_TYPES, ...ENTITY_EVENT_TYPES]),
32
32
  ]);
33
- /** Providers the Connector produces events for (`provider` extension attribute). */
34
- exports.PROVIDERS = Object.freeze(['hubspot']);
33
+ /**
34
+ * Providers the Connector produces events for (`provider` extension attribute). Only the Trigger's
35
+ * filter uses this list: the envelope check accepts any provider slug, as the contracts do.
36
+ */
37
+ exports.PROVIDERS = Object.freeze(['hubspot', 'activecampaign']);
35
38
  const KNOWN_TYPES = new Set(exports.EVENT_TYPES);
36
39
  function isKnownEventType(type) {
37
40
  return KNOWN_TYPES.has(type);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middag-io/n8n-nodes-middag",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "n8n community nodes for the MIDDAG Connector: a trigger for its signed CloudEvent deliveries and an action node for its operations.",
5
5
  "keywords": [
6
6
  "n8n-community-node-package",