@polarityio/integration-types 1.2.1 → 3.0.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/context.d.ts CHANGED
@@ -118,6 +118,137 @@ export interface PolarityCache {
118
118
  integration: IntegrationCache;
119
119
  user: UserCache;
120
120
  }
121
+ /**
122
+ * Proxy configuration for per-integration HTTP proxy overrides (tier 1).
123
+ *
124
+ * Present only when the Polarity admin has configured a per-integration
125
+ * proxy override. Global proxy settings (tier 2) and host environment
126
+ * proxy variables (tier 3) are **not** surfaced here — they are injected
127
+ * into the worker subprocess environment and picked up by HTTP clients
128
+ * automatically.
129
+ *
130
+ * @example Resolving the proxy URL for a request
131
+ * ```typescript
132
+ * const proxyUrl = context.network.proxy?.https ?? context.network.proxy?.http;
133
+ * ```
134
+ */
135
+ export interface NetworkProxy {
136
+ /**
137
+ * HTTP proxy URL for plain-text requests.
138
+ * Omitted (not `null`) when unset.
139
+ *
140
+ * @example "http://user:pass@proxy.corp:8080"
141
+ */
142
+ http?: string;
143
+ /**
144
+ * HTTPS proxy URL for TLS requests.
145
+ * Omitted (not `null`) when unset. Today this is typically the same
146
+ * URL as `http`; both fields exist for future per-scheme support.
147
+ *
148
+ * @example "http://user:pass@proxy.corp:8080"
149
+ */
150
+ https?: string;
151
+ /**
152
+ * Comma- or whitespace-separated list of hosts/domains that bypass
153
+ * the per-integration proxy.
154
+ *
155
+ * - Omitted when unset (no explicit bypass list configured).
156
+ * - `null` only when the admin explicitly set the bypass list to empty
157
+ * (a valid `NO_PROXY` value meaning "no exceptions — proxy everything").
158
+ *
159
+ * Supports patterns: exact host, `.suffix` domain matching, and `*` wildcard.
160
+ *
161
+ * @example "localhost,.internal,*.corp"
162
+ */
163
+ noProxy?: string | null;
164
+ }
165
+ /**
166
+ * Per-integration network configuration provided on every dispatch via
167
+ * `context.network`.
168
+ *
169
+ * Contains **tier-1** (per-integration) TLS and proxy overrides configured
170
+ * by the Polarity admin. Global and host proxy settings are handled
171
+ * transparently via the worker environment and do not appear here.
172
+ *
173
+ * ### Precedence
174
+ *
175
+ * 1. **Tier 1 — Per-integration** → surfaces on `context.network`
176
+ * 2. **Tier 2 — Global Proxy Settings** → worker env (`HTTPS_PROXY`, etc.)
177
+ * 3. **Tier 3 — Host env** → inherited by worker subprocess
178
+ *
179
+ * ### Key Rules
180
+ *
181
+ * - Do **not** cache HTTP clients across dispatches — settings may change
182
+ * between dispatches when an admin updates the configuration.
183
+ * - Do **not** set `process.env.HTTP_PROXY` or
184
+ * `process.env.NODE_TLS_REJECT_UNAUTHORIZED` at runtime — this is racy
185
+ * on shared workers and leaks settings between integrations.
186
+ * - When `proxy` is absent, do nothing — the worker env carries
187
+ * tier 2/3 and most HTTP clients pick it up natively.
188
+ *
189
+ * @example Basic usage with any HTTP client
190
+ * ```typescript
191
+ * async function doLookup(entities, options, context) {
192
+ * const proxyUrl = context.network.proxy?.https ?? context.network.proxy?.http;
193
+ * const rejectUnauthorized = context.network.rejectUnauthorized !== false;
194
+ * // Wire proxyUrl and rejectUnauthorized into your HTTP client
195
+ * }
196
+ * ```
197
+ *
198
+ * @example Usage with postman-request
199
+ * ```typescript
200
+ * async function doLookup(entities, options, context) {
201
+ * const proxy = context.network.proxy?.https ?? context.network.proxy?.http;
202
+ * const client = request.defaults({
203
+ * ...(proxy && { proxy }),
204
+ * ...(context.network.rejectUnauthorized === false && {
205
+ * strictSSL: false,
206
+ * rejectUnauthorized: false,
207
+ * }),
208
+ * });
209
+ * }
210
+ * ```
211
+ *
212
+ * @example Usage with axios
213
+ * ```typescript
214
+ * async function doLookup(entities, options, context) {
215
+ * const proxyUrl = context.network.proxy?.https ?? context.network.proxy?.http;
216
+ * const config: AxiosRequestConfig = {};
217
+ * if (proxyUrl) {
218
+ * const u = new URL(proxyUrl);
219
+ * config.proxy = {
220
+ * protocol: u.protocol.replace(':', ''),
221
+ * host: u.hostname,
222
+ * port: Number(u.port) || (u.protocol === 'https:' ? 443 : 80),
223
+ * ...(u.username && { auth: { username: u.username, password: u.password } }),
224
+ * };
225
+ * }
226
+ * if (context.network.rejectUnauthorized === false) {
227
+ * config.httpsAgent = new https.Agent({ rejectUnauthorized: false });
228
+ * }
229
+ * }
230
+ * ```
231
+ */
232
+ export interface NetworkContext {
233
+ /**
234
+ * Per-integration proxy override (tier 1).
235
+ *
236
+ * **Omitted entirely** when no per-integration proxy is configured.
237
+ * When absent, HTTP clients should use their default behavior
238
+ * (which will pick up tier 2/3 from the worker environment).
239
+ */
240
+ proxy?: NetworkProxy;
241
+ /**
242
+ * Whether outbound TLS certificates should be verified.
243
+ *
244
+ * - `true` (default) — enforce certificate validation.
245
+ * - `false` — skip TLS certificate verification. Corresponds to the
246
+ * integration's "Allow Unauthorized TLS Certificates" admin setting.
247
+ *
248
+ * **Always present** — TLS strictness is meaningful regardless of proxy config.
249
+ */
250
+ rejectUnauthorized: boolean;
251
+ }
121
252
  /**
122
253
  * Integration context provided to integration functions (`doLookup`, `onMessage`,
123
254
  * `onDetails`, `validateOptions`).
@@ -128,6 +259,43 @@ export interface IntegrationContext {
128
259
  userId: number;
129
260
  logger: Logger;
130
261
  limiter: Limiter;
131
- startPolling: (pollName: string) => void;
262
+ /** Per-integration network (TLS/proxy) configuration provided by the runtime on every dispatch. */
263
+ network: NetworkContext;
264
+ /**
265
+ * Starts a named poller that was defined in the integration's `poll` export.
266
+ *
267
+ * If the poller is already running, this call is a no-op.
268
+ *
269
+ * @param pollName - The key from the integration's `poll` record identifying
270
+ * which poller to start.
271
+ * @param runImmediately - When `true` (default), the poll function fires once
272
+ * immediately before the first scheduled interval or cron tick. When `false`,
273
+ * the first execution waits for the next scheduled tick.
274
+ *
275
+ * @example Start a poller and fire immediately
276
+ * ```typescript
277
+ * context.startPolling('refreshTokens');
278
+ * ```
279
+ *
280
+ * @example Start a poller but wait for the first scheduled tick
281
+ * ```typescript
282
+ * context.startPolling('weeklyReport', false);
283
+ * ```
284
+ */
285
+ startPolling: (pollName: string, runImmediately?: boolean) => void;
286
+ /**
287
+ * Stops a named poller that is currently running.
288
+ *
289
+ * If the poller is not running, this call is a no-op. A stopped poller can be
290
+ * restarted later via `startPolling()`.
291
+ *
292
+ * @param pollName - The key from the integration's `poll` record identifying
293
+ * which poller to stop.
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * context.stopPolling('refreshTokens');
298
+ * ```
299
+ */
132
300
  stopPolling: (pollName: string) => void;
133
301
  }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  export type { Channel, StandardEntityType, EntityType, EntityTypeIdentifier, EntityPosition, OnDemandRequestContext, ScreenChangeRequestContext, RequestContext, Entity } from './entity';
2
2
  export type { SelectTypeOptionValue, PossibleUserOptionValue, DoLookupUserOptions, ValidateOptionsUserOption, ValidateOptionsUserOptions, ValidationError } from './user-options';
3
3
  export type { LookupResult, DoLookupResult } from './result';
4
- export type { CacheOptions, GlobalCache, IntegrationCache, UserCache, PolarityCache, IntegrationContext } from './context';
4
+ export type { CacheOptions, GlobalCache, IntegrationCache, UserCache, PolarityCache, NetworkProxy, NetworkContext, IntegrationContext } from './context';
5
5
  export type { ThrottleStrategy, ScheduleOptions, LimiterCounts, ThrottleSettings, ScopedLimiter, Limiter } from './limiter';
6
6
  export type { Logger } from './logger';
7
7
  export type { Integration } from './integration';
8
- export type { PollFunction, IntervalPollSpec, CronPollSpec, PollSpec, Poll } from './polling';
8
+ export type { PollFunction, PollFailureStrategy, IntervalPollSpec, CronPollSpec, PollSpec, Poll } from './polling';
9
9
  export type { TextOption, BooleanOption, NumberOption, SelectOption, IntegrationOption, LogLevel, RequestConfig, IntegrationConfig } from './config';
package/dist/polling.d.ts CHANGED
@@ -1,68 +1,218 @@
1
1
  import type { DoLookupUserOptions } from './user-options';
2
2
  import type { IntegrationContext } from './context';
3
3
  /**
4
- * A function that is called on a polling schedule.
4
+ * The function invoked on each poll cycle (interval tick or cron trigger).
5
5
  *
6
- * Receives admin-only (global) user options and the integration context.
6
+ * Receives admin-only user options (matching the integration's `config.json` shape)
7
+ * and the full integration context. The function should perform its work and return
8
+ * without a meaningful value — any returned value is discarded by the runtime.
9
+ *
10
+ * ### Execution Model
11
+ *
12
+ * Poll functions run in a **dedicated polling worker** that is separate from the
13
+ * integration workers handling `doLookup`, `onMessage`, and `onDetails` dispatches.
14
+ * Each poll function executes **once per integration** — not once per worker instance.
15
+ * This means poll functions are singletons: even if multiple integration workers are
16
+ * running, only one instance of each poller is active at any time.
17
+ *
18
+ * Because the polling worker is isolated, poll functions do not share in-memory state
19
+ * with integration dispatch workers. Use `context.cache` to exchange data between
20
+ * poll functions and dispatch handlers.
21
+ *
22
+ * @param options - Admin-only (global) user options for the integration.
23
+ * @param context - The integration context providing cache, logger, limiter, and network utilities.
7
24
  */
8
25
  export type PollFunction = (options: DoLookupUserOptions, context: IntegrationContext) => Promise<void>;
26
+ /**
27
+ * Strategy the runtime uses when a poll function throws an unhandled error.
28
+ *
29
+ * - `'retry'` — The runtime catches the error and retries the poll function on
30
+ * the next scheduled tick. Useful for transient failures (e.g., network timeouts).
31
+ * - `'shutdown'` — The runtime stops the integration entirely and surfaces the
32
+ * error to the Polarity frontend. Use for unrecoverable failures where continued
33
+ * polling would be harmful.
34
+ */
35
+ export type PollFailureStrategy = 'retry' | 'shutdown';
36
+ /**
37
+ * Shared configuration for all poll specifications.
38
+ */
9
39
  interface BasePollSpec {
10
- /** The function to call on each poll cycle. */
40
+ /**
41
+ * The function to invoke on each poll cycle.
42
+ *
43
+ * @see {@link PollFunction}
44
+ */
11
45
  function: PollFunction;
12
46
  /**
13
- * Whether to start polling automatically when the integration loads.
14
- * If `false`, polling must be started manually via `context.startPolling()`.
47
+ * Whether to start this poller automatically when the integration is loaded
48
+ * by the runtime.
49
+ *
50
+ * - `true` — Polling begins immediately after the integration's `startup`
51
+ * hook completes.
52
+ * - `false` (default) — Polling does not begin until explicitly started via
53
+ * `context.startPolling(pollName)`.
54
+ *
55
+ * @default false
15
56
  */
16
57
  autostart?: boolean;
17
58
  /**
18
- * Strategy to use when the poll function throws an error.
59
+ * Whether to execute the poll function immediately when the poller starts,
60
+ * before waiting for the first interval tick or cron trigger.
61
+ *
62
+ * - `true` — The poll function fires once immediately on start, then
63
+ * continues on its normal schedule.
64
+ * - `false` (default) — The first execution occurs after the first
65
+ * interval/cron tick.
19
66
  *
20
- * - `'restart'` — Retry the function with linear backoff until it succeeds,
21
- * then resume the normal schedule.
22
- * - `'shutdown'` — Stop the integration and report an error to the frontend.
67
+ * This applies to automatic start (when `autostart` is `true`). When a poller
68
+ * is started manually via `context.startPolling()`, the method's own
69
+ * `runImmediately` parameter takes precedence over this spec-level value.
70
+ *
71
+ * @default false
72
+ */
73
+ runImmediately?: boolean;
74
+ /**
75
+ * Strategy to use when the poll function throws an unhandled error.
76
+ *
77
+ * @default 'retry'
78
+ * @see {@link PollFailureStrategy}
23
79
  */
24
- failureStrategy?: 'restart' | 'shutdown';
80
+ failureStrategy?: PollFailureStrategy;
25
81
  }
26
82
  /**
27
- * A poll specification that runs on a fixed interval.
83
+ * A poll specification that runs on a fixed time interval.
84
+ *
85
+ * The interval defines the delay **between** the completion of one invocation
86
+ * and the start of the next — not a fixed-rate schedule. If the poll function
87
+ * takes longer than the interval, executions will not overlap.
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * const spec: IntervalPollSpec = {
92
+ * function: doRefreshTokens,
93
+ * interval: 60, // every 60 seconds
94
+ * autostart: true,
95
+ * runImmediately: true, // fire once immediately on start
96
+ * failureStrategy: 'retry'
97
+ * };
98
+ * ```
28
99
  */
29
100
  export interface IntervalPollSpec extends BasePollSpec {
30
- /** Polling interval in milliseconds. */
101
+ /**
102
+ * Polling interval in **seconds**.
103
+ *
104
+ * Must be a positive number. The runtime waits this many seconds after the
105
+ * previous invocation completes before starting the next one.
106
+ */
31
107
  interval: number;
108
+ /** @internal Discriminator — `cron` is not allowed on interval-based specs. */
32
109
  cron?: never;
33
110
  }
34
111
  /**
35
112
  * A poll specification that runs on a cron schedule.
113
+ *
114
+ * Uses standard 5-field cron syntax (`minute hour day-of-month month day-of-week`).
115
+ * All times are evaluated in UTC.
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * const spec: CronPollSpec = {
120
+ * function: doWeeklyReport,
121
+ * cron: '0 9 * * 1', // every Monday at 09:00 UTC
122
+ * failureStrategy: 'shutdown'
123
+ * };
124
+ * ```
36
125
  */
37
126
  export interface CronPollSpec extends BasePollSpec {
38
- /** A cron expression defining the polling schedule (e.g., `"0 9 * * *"`). */
127
+ /**
128
+ * A cron expression defining the polling schedule.
129
+ *
130
+ * Uses standard 5-field syntax: `minute hour day-of-month month day-of-week`.
131
+ * All times are evaluated in UTC.
132
+ *
133
+ * Common patterns:
134
+ * - `'0 9 * * *'` — daily at 09:00 UTC
135
+ * - `'0 0 * * 6'` — every Saturday at midnight UTC
136
+ * - `'0/5 * * * *'` — every 5 minutes (step syntax)
137
+ */
39
138
  cron: string;
139
+ /** @internal Discriminator — `interval` is not allowed on cron-based specs. */
40
140
  interval?: never;
41
141
  }
42
142
  /**
43
143
  * A single poll specification — either interval-based or cron-based.
144
+ *
145
+ * Use {@link IntervalPollSpec} for fixed-delay polling (e.g., every 30 seconds)
146
+ * or {@link CronPollSpec} for calendar-based scheduling (e.g., daily at 9 AM).
147
+ *
148
+ * These two forms are mutually exclusive: a spec must define either `interval`
149
+ * or `cron`, but never both.
44
150
  */
45
151
  export type PollSpec = IntervalPollSpec | CronPollSpec;
46
152
  /**
47
153
  * A record of named poll specifications exported by an integration.
48
154
  *
49
- * Each key is the poll name (used with `context.startPolling()` / `context.stopPolling()`),
50
- * and the value defines the schedule and function to call.
155
+ * Each key is the **poll name** — a unique identifier used with
156
+ * `context.startPolling()` and `context.stopPolling()` to manually control
157
+ * individual pollers at runtime.
51
158
  *
52
- * @example
159
+ * ### Runtime Behavior
160
+ *
161
+ * Pollers execute in a **dedicated polling worker** that is independent of the
162
+ * integration workers handling lookup and message dispatches. Regardless of how
163
+ * many integration worker instances are running, each poller runs exactly **once
164
+ * per integration** — ensuring that scheduled tasks (e.g., token refresh, report
165
+ * generation) are not duplicated across workers.
166
+ *
167
+ * @example Basic polling configuration
53
168
  * ```typescript
169
+ * import type { Poll } from '@polarityio/integration-types';
170
+ *
54
171
  * const poll: Poll = {
55
172
  * refreshTokens: {
56
173
  * function: doRefreshTokens,
57
- * interval: 10000,
58
- * autostart: true
174
+ * interval: 30, // every 30 seconds
175
+ * autostart: true,
176
+ * runImmediately: true
59
177
  * },
60
- * uploadReport: {
61
- * function: doUploadReport,
62
- * cron: "0 9 * * *",
63
- * failureStrategy: "restart"
178
+ * weeklyReport: {
179
+ * function: doWeeklyReport,
180
+ * cron: '0 9 * * 1', // Mondays at 09:00 UTC
181
+ * failureStrategy: 'shutdown'
64
182
  * }
65
183
  * };
184
+ *
185
+ * export { poll };
186
+ * ```
187
+ *
188
+ * @example One-time initialization pattern
189
+ *
190
+ * Because poll functions are singletons (one instance per integration), you can
191
+ * use a poller with `runImmediately: true` and `autostart: true` to guarantee a
192
+ * function runs exactly once across all integration workers. The function stops
193
+ * itself after the first execution by calling `context.stopPolling()`.
194
+ *
195
+ * ```typescript
196
+ * import type { Poll, PollFunction } from '@polarityio/integration-types';
197
+ *
198
+ * const initializeOnce: PollFunction = async (options, context) => {
199
+ * // Perform one-time setup (e.g., seed cache, register webhooks)
200
+ * await seedIntegrationCache(options, context);
201
+ *
202
+ * // Stop the poller — this function will never run again
203
+ * context.stopPolling('initialize');
204
+ * };
205
+ *
206
+ * const poll: Poll = {
207
+ * initialize: {
208
+ * function: initializeOnce,
209
+ * interval: 60, // interval is required but irrelevant here
210
+ * autostart: true,
211
+ * runImmediately: true // fire immediately on integration load
212
+ * }
213
+ * };
214
+ *
215
+ * export { poll };
66
216
  * ```
67
217
  */
68
218
  export type Poll = Record<string, PollSpec>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polarityio/integration-types",
3
- "version": "1.2.1",
3
+ "version": "3.0.0",
4
4
  "description": "TypeScript type definitions for Polarity Integrations",
5
5
  "types": "./dist/index.d.ts",
6
6
  "exports": {