@jini-ai/integrations 0.4.2 → 0.6.10

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.
Files changed (132) hide show
  1. package/CHANGELOG.md +99 -1
  2. package/README.md +1 -0
  3. package/dist/api-connections/access-token.d.ts +9 -0
  4. package/dist/api-connections/access-token.js +92 -0
  5. package/dist/api-connections/account-actions.d.ts +40 -0
  6. package/dist/api-connections/account-actions.js +110 -0
  7. package/dist/api-connections/attempt-state.d.ts +28 -0
  8. package/dist/api-connections/attempt-state.js +73 -0
  9. package/dist/api-connections/authorization.d.ts +45 -0
  10. package/dist/api-connections/authorization.js +120 -0
  11. package/dist/api-connections/deps.d.ts +41 -0
  12. package/dist/api-connections/deps.js +13 -0
  13. package/dist/api-connections/descriptor.d.ts +6 -0
  14. package/dist/api-connections/descriptor.js +111 -0
  15. package/dist/api-connections/errors.d.ts +23 -0
  16. package/dist/api-connections/errors.js +24 -0
  17. package/dist/api-connections/finish-authorization.d.ts +24 -0
  18. package/dist/api-connections/finish-authorization.js +117 -0
  19. package/dist/api-connections/index.d.ts +18 -0
  20. package/dist/api-connections/index.js +10 -0
  21. package/dist/api-connections/install-credential.d.ts +19 -0
  22. package/dist/api-connections/install-credential.js +12 -0
  23. package/dist/api-connections/keys.d.ts +27 -0
  24. package/dist/api-connections/keys.js +22 -0
  25. package/dist/api-connections/ports.d.ts +73 -0
  26. package/dist/api-connections/ports.js +2 -0
  27. package/dist/api-connections/records.d.ts +27 -0
  28. package/dist/api-connections/records.js +52 -0
  29. package/dist/api-connections/request-checks.d.ts +18 -0
  30. package/dist/api-connections/request-checks.js +67 -0
  31. package/dist/api-connections/service.d.ts +25 -0
  32. package/dist/api-connections/service.js +26 -0
  33. package/dist/api-connections/status.d.ts +28 -0
  34. package/dist/api-connections/status.js +36 -0
  35. package/dist/api-connections/token-store/errors.d.ts +20 -0
  36. package/dist/api-connections/token-store/errors.js +38 -0
  37. package/dist/api-connections/token-store/index.d.ts +6 -0
  38. package/dist/api-connections/token-store/index.js +6 -0
  39. package/dist/api-connections/token-store/record.d.ts +69 -0
  40. package/dist/api-connections/token-store/record.js +97 -0
  41. package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
  42. package/dist/api-connections/token-store/vault-token-store.js +215 -0
  43. package/dist/api-connections/types.d.ts +101 -0
  44. package/dist/api-connections/types.js +9 -0
  45. package/dist/credentialed-http/auth-schemes.js +8 -4
  46. package/dist/credentialed-http/credentialed-request.d.ts +4 -0
  47. package/dist/credentialed-http/credentialed-request.js +61 -77
  48. package/dist/credentialed-http/response-redaction.d.ts +15 -0
  49. package/dist/credentialed-http/response-redaction.js +82 -0
  50. package/dist/media-providers/catalog.d.ts +3 -1
  51. package/dist/media-providers/catalog.js +3 -1
  52. package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
  53. package/dist/media-providers/dispatch/async-operation-store.js +75 -37
  54. package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
  55. package/dist/media-providers/dispatch/context.js +10 -2
  56. package/dist/media-providers/dispatch/engine.d.ts +6 -3
  57. package/dist/media-providers/dispatch/engine.js +99 -109
  58. package/dist/media-providers/dispatch/index.d.ts +4 -2
  59. package/dist/media-providers/dispatch/index.js +3 -1
  60. package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
  61. package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
  62. package/dist/media-providers/dispatch/node.d.ts +13 -0
  63. package/dist/media-providers/dispatch/node.js +24 -0
  64. package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
  65. package/dist/media-providers/dispatch/openai-compatible.js +90 -87
  66. package/dist/media-providers/dispatch/operation-runtime.js +116 -89
  67. package/dist/media-providers/dispatch/outbound.d.ts +8 -4
  68. package/dist/media-providers/dispatch/outbound.js +27 -26
  69. package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
  70. package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
  71. package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
  72. package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
  73. package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
  74. package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
  75. package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
  76. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
  77. package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
  78. package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
  79. package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
  80. package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
  81. package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
  82. package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
  83. package/dist/media-providers/dispatch/providers/openai.js +51 -47
  84. package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
  85. package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
  86. package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
  87. package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
  88. package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
  89. package/dist/media-providers/dispatch/response-parsers.js +37 -21
  90. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
  91. package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
  92. package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
  93. package/dist/media-providers/dispatch/types.d.ts +76 -2
  94. package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
  95. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  96. package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
  97. package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
  98. package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
  99. package/dist/media-providers/dispatch/vendor-registry.js +14 -42
  100. package/dist/media-providers/policy.js +25 -17
  101. package/dist/media-providers/providers.d.ts +5 -0
  102. package/dist/media-providers/providers.js +2 -0
  103. package/dist/media-providers/sqlite-task-store.js +12 -80
  104. package/dist/media-providers/staging.js +77 -58
  105. package/dist/media-providers/task-lifecycle.d.ts +33 -0
  106. package/dist/media-providers/task-lifecycle.js +124 -0
  107. package/dist/media-providers/task-store.js +8 -86
  108. package/dist/media-providers/ui-defaults.d.ts +10 -0
  109. package/dist/media-providers/ui-defaults.js +167 -0
  110. package/dist/media-providers/video-request.js +112 -90
  111. package/dist/saved-requests/definition.d.ts +17 -0
  112. package/dist/saved-requests/definition.js +84 -0
  113. package/dist/saved-requests/execute.d.ts +17 -0
  114. package/dist/saved-requests/execute.js +95 -0
  115. package/dist/saved-requests/index.d.ts +6 -0
  116. package/dist/saved-requests/index.js +4 -0
  117. package/dist/saved-requests/projection.d.ts +9 -0
  118. package/dist/saved-requests/projection.js +48 -0
  119. package/dist/saved-requests/schema.d.ts +7 -0
  120. package/dist/saved-requests/schema.js +73 -0
  121. package/dist/saved-requests/types.d.ts +58 -0
  122. package/dist/saved-requests/types.js +2 -0
  123. package/dist/saved-requests/validation.d.ts +46 -0
  124. package/dist/saved-requests/validation.js +66 -0
  125. package/dist/webhooks/delivery.d.ts +14 -0
  126. package/dist/webhooks/delivery.js +41 -10
  127. package/dist/webhooks/index.d.ts +1 -0
  128. package/dist/webhooks/index.js +1 -0
  129. package/dist/webhooks/ports.d.ts +23 -0
  130. package/dist/webhooks/worker.d.ts +83 -0
  131. package/dist/webhooks/worker.js +105 -0
  132. package/package.json +46 -9
@@ -0,0 +1,58 @@
1
+ import type { CredentialedRequestAuditPort } from "../credentialed-http/credentialed-request.js";
2
+ import type { CredentialSchemeRegistryPort, ResolvedCredential } from "../credentialed-http/ports.js";
3
+ import type { DnsResolver, GuardedClock, PinnedHttpTransport } from "@jini-ai/platform/http/guarded";
4
+ /** Persisted data only. Identity, policy, consent and quotas belong to the calling host. */
5
+ export interface SavedRequestDefinition {
6
+ readonly version: 1;
7
+ readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
8
+ readonly url: string;
9
+ readonly credential: {
10
+ readonly id: string;
11
+ readonly revision: string;
12
+ readonly origin: string;
13
+ };
14
+ readonly inputSchema: Readonly<Record<string, unknown>>;
15
+ readonly queryBindings: Readonly<Record<string, string>>;
16
+ readonly bodyBindings: Readonly<Record<string, string>>;
17
+ readonly staticBody?: Readonly<Record<string, unknown>>;
18
+ readonly output: {
19
+ readonly path: readonly string[];
20
+ readonly maxItems: number;
21
+ readonly fields: Readonly<Record<string, SavedRequestOutputField>>;
22
+ };
23
+ }
24
+ export interface SavedRequestOutputField {
25
+ readonly path: readonly string[];
26
+ readonly type: "string" | "number" | "boolean" | "url";
27
+ readonly maxLength?: number;
28
+ readonly allowedOrigin?: string;
29
+ }
30
+ /** Resolve opaque IDs within the mounted workspace, never editable display labels. A revision
31
+ * must change whenever account, token, origin or visitor-use authorization changes. */
32
+ export interface SavedRequestCredentialResolverPort {
33
+ resolve(required: {
34
+ workspaceId: string;
35
+ credentialId: string;
36
+ }): Promise<(ResolvedCredential & {
37
+ readonly revision: string;
38
+ }) | null>;
39
+ }
40
+ /** All effects are injected. The interpreter constructs the existing guard, so callers cannot
41
+ * accidentally supply an HTTP client with redirects or development bypasses enabled. */
42
+ export interface SavedRequestDeps {
43
+ readonly credentials: SavedRequestCredentialResolverPort;
44
+ readonly schemeRegistry: CredentialSchemeRegistryPort;
45
+ readonly audit: CredentialedRequestAuditPort;
46
+ readonly clock: GuardedClock;
47
+ readonly dns: DnsResolver;
48
+ readonly transport: PinnedHttpTransport;
49
+ readonly userAgent: string;
50
+ /** Trusted composition supplies the site's public, admin, API and control origins. */
51
+ readonly forbiddenOrigins: readonly string[];
52
+ }
53
+ /** Only positively selected values; no provider headers, diagnostics or credential metadata. */
54
+ export interface SavedRequestResult {
55
+ readonly trust: "untrusted";
56
+ readonly items: readonly Readonly<Record<string, string | number | boolean>>[];
57
+ }
58
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,46 @@
1
+ import { IntegrationError } from "../argument-error.js";
2
+ export type SavedRequestErrorCode = "invalid_definition" | "invalid_input" | "credential_changed" | "execution_failed" | "invalid_response";
3
+ /** Safe public refusal. Raw URLs, provider bodies, secrets and underlying errors never escape. */
4
+ export declare class SavedRequestError extends IntegrationError {
5
+ readonly code: SavedRequestErrorCode;
6
+ constructor(required: {
7
+ code: SavedRequestErrorCode;
8
+ }, _options?: Record<string, never>);
9
+ }
10
+ export declare function requireCondition({ valid, code }: {
11
+ valid: boolean;
12
+ code?: SavedRequestErrorCode;
13
+ }, _options?: Record<string, never>): void;
14
+ export declare function record({ value }: {
15
+ value: unknown;
16
+ }, _options?: Record<string, never>): Record<string, unknown>;
17
+ export declare function closed({ value, keys }: {
18
+ value: Record<string, unknown>;
19
+ keys: readonly string[];
20
+ }, _options?: Record<string, never>): void;
21
+ export declare function name({ value }: {
22
+ value: unknown;
23
+ }, _options?: Record<string, never>): string;
24
+ export declare function integer({ value, min, max }: {
25
+ value: unknown;
26
+ min?: number;
27
+ max: number;
28
+ }, _options?: Record<string, never>): void;
29
+ /** Bound serialized bytes before parsing/compiling. Snapshotting also prevents edits while awaiting
30
+ * credentials or DNS from changing the reviewed definition/input. @complexity O(n) bounded bytes. */
31
+ export declare function snapshot({ value, maxBytes, code }: {
32
+ value: unknown;
33
+ maxBytes: number;
34
+ code: SavedRequestErrorCode;
35
+ }, _options?: Record<string, never>): unknown;
36
+ export declare function httpsUrl({ value }: {
37
+ value: unknown;
38
+ }, _options?: Record<string, never>): URL;
39
+ export declare function fieldPath({ value }: {
40
+ value: unknown;
41
+ }, _options?: Record<string, never>): void;
42
+ /** Authentication is injected solely by the credential owner, never by bindings or static data. */
43
+ export declare function dataKey({ value }: {
44
+ value: unknown;
45
+ }, _options?: Record<string, never>): string;
46
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1,66 @@
1
+ import { IntegrationError } from "../argument-error.js";
2
+ /** Safe public refusal. Raw URLs, provider bodies, secrets and underlying errors never escape. */
3
+ export class SavedRequestError extends IntegrationError {
4
+ code;
5
+ constructor(required, _options = {}) {
6
+ super({ message: `Saved request refused: ${required.code}` });
7
+ this.code = required.code;
8
+ }
9
+ }
10
+ export function requireCondition({ valid, code = "invalid_definition" }, _options = {}) {
11
+ if (!valid)
12
+ throw new SavedRequestError({ code });
13
+ }
14
+ export function record({ value }, _options = {}) {
15
+ requireCondition({ valid: typeof value === "object" && value !== null && !Array.isArray(value) });
16
+ return value;
17
+ }
18
+ export function closed({ value, keys }, _options = {}) {
19
+ requireCondition({ valid: Object.keys(value).every(key => keys.includes(key)) });
20
+ }
21
+ export function name({ value }, _options = {}) {
22
+ requireCondition({ valid: typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(value) });
23
+ requireCondition({ valid: !["__proto__", "prototype", "constructor"].includes(value) });
24
+ return value;
25
+ }
26
+ export function integer({ value, min = 0, max }, _options = {}) {
27
+ requireCondition({ valid: Number.isSafeInteger(value) && Number(value) >= min && Number(value) <= max });
28
+ }
29
+ /** Bound serialized bytes before parsing/compiling. Snapshotting also prevents edits while awaiting
30
+ * credentials or DNS from changing the reviewed definition/input. @complexity O(n) bounded bytes. */
31
+ export function snapshot({ value, maxBytes, code }, _options = {}) {
32
+ try {
33
+ const json = JSON.stringify(value);
34
+ requireCondition({ valid: typeof json === "string" && Buffer.byteLength(json, "utf8") <= maxBytes, code });
35
+ return JSON.parse(json);
36
+ }
37
+ catch {
38
+ throw new SavedRequestError({ code });
39
+ }
40
+ }
41
+ export function httpsUrl({ value }, _options = {}) {
42
+ try {
43
+ requireCondition({ valid: typeof value === "string" });
44
+ // No template syntax or parser normalization of control characters in persisted targets.
45
+ requireCondition({ valid: !/[\s{}<>`\\]/u.test(decodeURIComponent(value)) });
46
+ const url = new URL(value);
47
+ requireCondition({ valid: url.protocol === "https:" && url.port === "" && !url.username && !url.password && !url.hash });
48
+ return url;
49
+ }
50
+ catch {
51
+ throw new SavedRequestError({ code: "invalid_definition" });
52
+ }
53
+ }
54
+ export function fieldPath({ value }, _options = {}) {
55
+ requireCondition({ valid: Array.isArray(value) && value.length <= 8 });
56
+ for (const part of value)
57
+ name({ value: part });
58
+ }
59
+ /** Authentication is injected solely by the credential owner, never by bindings or static data. */
60
+ export function dataKey({ value }, _options = {}) {
61
+ const key = name({ value });
62
+ const normalized = key.toLowerCase().replace(/[_.-]/g, "");
63
+ requireCondition({ valid: !["authorization", "proxyauthorization", "cookie", "host", "token", "accesstoken", "apikey", "password", "secret", "credential", "credentialid", "username"].includes(normalized) });
64
+ return key;
65
+ }
66
+ //# sourceMappingURL=validation.js.map
@@ -61,10 +61,24 @@ export interface ProcessDueDeliveriesRequired {
61
61
  export interface ProcessDueDeliveriesOptional {
62
62
  batchSize?: number;
63
63
  hooks?: readonly WebhookBeforeDispatchHook[];
64
+ /** Socket idle budget per request. A receiver that keeps trickling bytes never trips it. */
64
65
  requestTimeoutMs?: number;
66
+ /** Whole-request budget (DNS, connect, body) per delivery; default {@link DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS}. */
67
+ requestTotalDeadlineMs?: number;
68
+ /** Claim lease; default batchSize x requestTotalDeadlineMs + {@link WEBHOOK_CLAIM_LEASE_MARGIN_MS}. */
69
+ claimLeaseMs?: number;
70
+ /** Host shutdown: aborts the in-flight request and releases the batch's unattempted claims. */
71
+ signal?: AbortSignal;
65
72
  maxAttempts?: number;
66
73
  random?: (() => number) | undefined;
67
74
  }
75
+ /**
76
+ * The idle timeout alone lets one receiver that trickles a byte at a time hold the single-flight
77
+ * worker, and every other subscription's delivery, indefinitely. 30 s bounds each delivery.
78
+ */
79
+ export declare const DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS = 30000;
80
+ /** Slack for hooks, signing and storage writes on top of the batch's request deadlines. */
81
+ export declare const WEBHOOK_CLAIM_LEASE_MARGIN_MS = 60000;
68
82
  export interface ProcessDueDeliveriesResult {
69
83
  processed: number;
70
84
  delivered: number;
@@ -91,16 +91,32 @@ async function isAlreadyEnqueued(params) {
91
91
  });
92
92
  return existing.some((delivery) => delivery.eventId === params.eventId);
93
93
  }
94
+ /**
95
+ * The idle timeout alone lets one receiver that trickles a byte at a time hold the single-flight
96
+ * worker, and every other subscription's delivery, indefinitely. 30 s bounds each delivery.
97
+ */
98
+ export const DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS = 30_000;
99
+ /** Slack for hooks, signing and storage writes on top of the batch's request deadlines. */
100
+ export const WEBHOOK_CLAIM_LEASE_MARGIN_MS = 60_000;
94
101
  // Throwing/rejecting redaction hooks and explicit vetoes fail this attempt before signing/sending;
95
102
  // an unfiltered envelope must never fall through. Retry with normal backoff, then dead-letter.
96
103
  /** Claim and process a bounded batch; hooks fail closed and unsuccessful attempts back off or dead-letter. */
97
104
  export async function processDueDeliveries(required, optional = {}) {
98
105
  const { deliveryRepo, subscriptionRepo, envelopeStore, httpClient, signer, clock, headers } = required.deps;
99
- const { batchSize, hooks, requestTimeoutMs, maxAttempts, random } = resolveProcessDueDeliveriesOptions(optional);
106
+ const { batchSize, hooks, request, claimLeaseMs, signal, maxAttempts, random } = resolveProcessDueDeliveriesOptions(optional);
107
+ const result = { processed: 0, delivered: 0, failed: 0, dead: 0 };
108
+ if (signal?.aborted)
109
+ return result;
100
110
  const claimedAt = nowIso({ clock });
101
- const claimed = await deliveryRepo.claimPending({ batchSize, nowIso: claimedAt });
102
- const result = { processed: claimed.length, delivered: 0, failed: 0, dead: 0 };
103
- for (const row of claimed) {
111
+ // The lease makes a batch abandoned mid-flight (crash, or a shutdown that outlived its grace)
112
+ // reclaimable instead of stranding its rows in `delivering`; it covers the whole batch's deadlines.
113
+ const claimed = await deliveryRepo.claimPending({ batchSize, nowIso: claimedAt }, { claimLeaseMs });
114
+ result.processed = claimed.length;
115
+ for (const [index, row] of claimed.entries()) {
116
+ if (signal?.aborted) {
117
+ await releaseClaims(claimed.slice(index), { deliveryRepo, nextAttemptAt: claimedAt });
118
+ break;
119
+ }
104
120
  const outcome = await attemptOneDelivery(row, {
105
121
  subscriptionRepo,
106
122
  envelopeStore,
@@ -109,7 +125,7 @@ export async function processDueDeliveries(required, optional = {}) {
109
125
  headers,
110
126
  clock,
111
127
  hooks,
112
- requestTimeoutMs,
128
+ request,
113
129
  });
114
130
  const disposition = await recordDeliveryOutcome(row, outcome, { deliveryRepo, clock, maxAttempts, random });
115
131
  result[disposition] += 1;
@@ -117,8 +133,23 @@ export async function processDueDeliveries(required, optional = {}) {
117
133
  return result;
118
134
  }
119
135
  function resolveProcessDueDeliveriesOptions(optional) {
120
- const { batchSize = 20, hooks = [], requestTimeoutMs = 10_000, maxAttempts = MAX_DELIVERY_ATTEMPTS, random, } = optional;
121
- return { batchSize, hooks, requestTimeoutMs, maxAttempts, random };
136
+ const { batchSize = 20, hooks = [], requestTimeoutMs = 10_000, requestTotalDeadlineMs = DEFAULT_WEBHOOK_REQUEST_TOTAL_DEADLINE_MS, signal, maxAttempts = MAX_DELIVERY_ATTEMPTS, random, } = optional;
137
+ const claimLeaseMs = optional.claimLeaseMs ?? batchSize * requestTotalDeadlineMs + WEBHOOK_CLAIM_LEASE_MARGIN_MS;
138
+ const request = { timeoutMs: requestTimeoutMs, totalDeadlineMs: requestTotalDeadlineMs, ...(signal ? { signal } : {}) };
139
+ return { batchSize, hooks, request, claimLeaseMs, signal, maxAttempts, random };
140
+ }
141
+ /**
142
+ * Cancelled before these rows were attempted: hand them straight back (attempts restored, due at
143
+ * once) so a restart delivers them without waiting out the lease. A repo without `releaseClaim`
144
+ * leaves them to the lease.
145
+ */
146
+ async function releaseClaims(rows, deps) {
147
+ const { deliveryRepo, nextAttemptAt } = deps;
148
+ if (!deliveryRepo.releaseClaim)
149
+ return;
150
+ for (const row of rows) {
151
+ await deliveryRepo.releaseClaim({ workspaceId: row.workspaceId, id: row.id, claimedAttempts: row.attempts, nextAttemptAt });
152
+ }
122
153
  }
123
154
  async function recordDeliveryOutcome(row, outcome, deps) {
124
155
  if (outcome.ok) {
@@ -127,7 +158,7 @@ async function recordDeliveryOutcome(row, outcome, deps) {
127
158
  id: row.id,
128
159
  responseStatus: outcome.responseStatus,
129
160
  deliveredAtIso: nowIso({ clock: deps.clock }),
130
- });
161
+ }, { claimedAttempts: row.attempts });
131
162
  return "delivered";
132
163
  }
133
164
  const isExhausted = row.attempts >= deps.maxAttempts;
@@ -143,7 +174,7 @@ async function recordDeliveryOutcome(row, outcome, deps) {
143
174
  responseStatus: outcome.responseStatus,
144
175
  nextStatus,
145
176
  nextAttemptAt,
146
- }, isExhausted ? { deadAtIso: failedAtIso } : {});
177
+ }, { claimedAttempts: row.attempts, ...(isExhausted ? { deadAtIso: failedAtIso } : {}) });
147
178
  return isExhausted ? "dead" : "failed";
148
179
  }
149
180
  // Missing/inactive subscriptions, missing envelopes, hook failures, transport failures and
@@ -185,7 +216,7 @@ async function attemptOneDelivery(row, deps) {
185
216
  [deps.headers.deliveryId]: row.id,
186
217
  [deps.headers.eventId]: row.eventId,
187
218
  },
188
- timeoutMs: deps.requestTimeoutMs,
219
+ ...deps.request,
189
220
  body: rawBody,
190
221
  } });
191
222
  if (response.status >= 200 && response.status < 300) {
@@ -4,4 +4,5 @@ export * from "./subscriptions.js";
4
4
  export * from "./delivery.js";
5
5
  export * from "./signing.js";
6
6
  export * from "./signing.keyring.js";
7
+ export * from "./worker.js";
7
8
  //# sourceMappingURL=index.d.ts.map
@@ -4,4 +4,5 @@ export * from "./subscriptions.js";
4
4
  export * from "./delivery.js";
5
5
  export * from "./signing.js";
6
6
  export * from "./signing.keyring.js";
7
+ export * from "./worker.js";
7
8
  //# sourceMappingURL=index.js.map
@@ -50,15 +50,26 @@ export interface WebhookDeliveryRepoPort {
50
50
  }, optional?: {
51
51
  envelope?: WebhookEventEnvelope;
52
52
  }): Promise<void>;
53
+ /**
54
+ * Atomically claim due `pending` rows, increment `attempts` and mark them `delivering`.
55
+ * With `claimLeaseMs`, also reclaim `delivering` rows whose lease has expired and persist
56
+ * nowIso + claimLeaseMs as each claimed row's lease (its `nextAttemptAt` while delivering): a
57
+ * claimer that died or was abandoned at shutdown must not strand its rows in `delivering` forever.
58
+ */
53
59
  claimPending(required: {
54
60
  batchSize: number;
55
61
  nowIso: ISODateTime;
62
+ }, optional?: {
63
+ claimLeaseMs?: number;
56
64
  }): Promise<WebhookDeliveryRecord[]>;
65
+ /** With `claimedAttempts`, a stale outcome (the row was reclaimed since) must not overwrite the newer claim. */
57
66
  markDelivered(required: {
58
67
  workspaceId: UUID;
59
68
  id: IntegrationId;
60
69
  responseStatus: number;
61
70
  deliveredAtIso: ISODateTime;
71
+ }, optional?: {
72
+ claimedAttempts?: number;
62
73
  }): Promise<void>;
63
74
  markFailed(required: {
64
75
  workspaceId: UUID;
@@ -69,7 +80,19 @@ export interface WebhookDeliveryRepoPort {
69
80
  nextAttemptAt: ISODateTime;
70
81
  }, optional?: {
71
82
  deadAtIso?: ISODateTime;
83
+ claimedAttempts?: number;
72
84
  }): Promise<void>;
85
+ /**
86
+ * Return a claim that was never attempted (the batch was cancelled first) to `pending`, due at
87
+ * `nextAttemptAt`, undoing the claim's `attempts` increment. Fenced on `claimedAttempts`: a
88
+ * row reclaimed since is left alone. Optional: without it, the claim lease recovers the row.
89
+ */
90
+ releaseClaim?(required: {
91
+ workspaceId: UUID;
92
+ id: IntegrationId;
93
+ claimedAttempts: number;
94
+ nextAttemptAt: ISODateTime;
95
+ }, optional?: Record<string, never>): Promise<void>;
73
96
  findById(required: {
74
97
  workspaceId: UUID;
75
98
  id: IntegrationId;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @file The generic outbound webhook delivery loop: every interval it runs one delivery pass
3
+ * (`processDueDeliveries` bound to the host's ports), single flight, and on `stop` it cancels the
4
+ * running pass through an AbortSignal so the in-flight request settles and unattempted claims are
5
+ * released before the host closes its storage. Hosts own where it runs and which ports it binds.
6
+ *
7
+ * Single flight: a tick that finds the previous one still running does nothing, so a slow receiver
8
+ * (up to the per-request total deadline times the batch) never stacks claims on top of each other.
9
+ */
10
+ /** Idle wait between ticks. Short enough that a delivery leaves within seconds, long enough that
11
+ * an idle site costs one indexed `SELECT` per interval. */
12
+ export declare const WEBHOOK_DELIVERY_INTERVAL_MS = 15000;
13
+ /**
14
+ * How long `stop` waits for the cancelled pass to settle. Cancellation makes the in-flight request
15
+ * reject at once, so what remains is a few storage writes; a pass still running after the grace is
16
+ * abandoned, not awaited, and its claims are recovered by their lease.
17
+ */
18
+ export declare const WEBHOOK_DELIVERY_STOP_GRACE_MS = 1000;
19
+ /** Prefix of the one line logged for a failed tick; the loop keeps running after it. */
20
+ export declare const WEBHOOK_DELIVERY_FAILED_LINE = "[webhooks] delivery tick failed; retrying after the interval";
21
+ /** Logged when `stop` gives up waiting on a running tick. */
22
+ export declare const WEBHOOK_DELIVERY_STOP_LATE_LINE = "[webhooks] a delivery tick was still running at shutdown; it was abandoned";
23
+ /** A cancellable timer. The default implementation never keeps the process alive. */
24
+ export interface WebhookDeliveryTimer {
25
+ cancel(): void;
26
+ }
27
+ /** Timer port, injected so tests drive ticks with a fake clock. */
28
+ export interface WebhookDeliveryScheduler {
29
+ every(required: {
30
+ ms: number;
31
+ run: () => void;
32
+ }): WebhookDeliveryTimer;
33
+ after(required: {
34
+ ms: number;
35
+ run: () => void;
36
+ }): WebhookDeliveryTimer;
37
+ }
38
+ /** Node timers, unref'd: like the outbox drainer's, the loop must never hold a stopping process open. */
39
+ export declare const nodeWebhookDeliveryScheduler: WebhookDeliveryScheduler;
40
+ export interface WebhookDeliveryWorker {
41
+ /** Runs one tick now, unless one is already running (then resolves with that one). Never rejects. */
42
+ tick(): Promise<void>;
43
+ /** Stops scheduling ticks, cancels a running one and waits up to the stop grace for it. Idempotent. */
44
+ stop(): Promise<void>;
45
+ }
46
+ export interface WebhookDeliveryWorkerRequired {
47
+ /** One delivery pass. `signal` aborts when the worker stops; pass it to `processDueDeliveries`. */
48
+ processDue: (required: {
49
+ signal: AbortSignal;
50
+ }) => Promise<unknown>;
51
+ }
52
+ export interface WebhookDeliveryWorkerOptional {
53
+ intervalMs?: number;
54
+ /** How long `stop` waits for the cancelled pass; default {@link WEBHOOK_DELIVERY_STOP_GRACE_MS}. */
55
+ stopGraceMs?: number;
56
+ scheduler?: WebhookDeliveryScheduler;
57
+ log?: (line: string) => void;
58
+ }
59
+ /** The abort reason a running pass sees; recorded as the interrupted attempt's error. */
60
+ export declare class WebhookDeliveryWorkerStoppedError extends Error {
61
+ constructor();
62
+ }
63
+ /**
64
+ * One log line for a failed tick: the error's name, message (URLs removed, length capped) and
65
+ * `code`. Never the error object itself, its `cause`, stack or extra fields: a repo or transport
66
+ * error can carry a receiver URL with credentials, request headers or a payload.
67
+ *
68
+ * @complexity O(message length).
69
+ */
70
+ export declare function describeWebhookTickError(required: {
71
+ error: unknown;
72
+ }, _optional?: {}): string;
73
+ /**
74
+ * Starts the loop. The first tick runs one interval after start.
75
+ *
76
+ * @param required.processDue one delivery pass, given the worker's stop signal.
77
+ * @param optional.intervalMs idle wait between ticks; default {@link WEBHOOK_DELIVERY_INTERVAL_MS}.
78
+ * @throws RangeError when `intervalMs` or `stopGraceMs` is not a positive finite number.
79
+ * @example const worker = startWebhookDeliveryWorker({ processDue: ({ signal }) => processDueDeliveries({ deps }, { signal }) }); await worker.stop();
80
+ * @complexity O(1) per tick, beyond `processDue`.
81
+ */
82
+ export declare function startWebhookDeliveryWorker(required: WebhookDeliveryWorkerRequired, optional?: WebhookDeliveryWorkerOptional): WebhookDeliveryWorker;
83
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1,105 @@
1
+ /**
2
+ * @file The generic outbound webhook delivery loop: every interval it runs one delivery pass
3
+ * (`processDueDeliveries` bound to the host's ports), single flight, and on `stop` it cancels the
4
+ * running pass through an AbortSignal so the in-flight request settles and unattempted claims are
5
+ * released before the host closes its storage. Hosts own where it runs and which ports it binds.
6
+ *
7
+ * Single flight: a tick that finds the previous one still running does nothing, so a slow receiver
8
+ * (up to the per-request total deadline times the batch) never stacks claims on top of each other.
9
+ */
10
+ /** Idle wait between ticks. Short enough that a delivery leaves within seconds, long enough that
11
+ * an idle site costs one indexed `SELECT` per interval. */
12
+ export const WEBHOOK_DELIVERY_INTERVAL_MS = 15_000;
13
+ /**
14
+ * How long `stop` waits for the cancelled pass to settle. Cancellation makes the in-flight request
15
+ * reject at once, so what remains is a few storage writes; a pass still running after the grace is
16
+ * abandoned, not awaited, and its claims are recovered by their lease.
17
+ */
18
+ export const WEBHOOK_DELIVERY_STOP_GRACE_MS = 1_000;
19
+ /** Prefix of the one line logged for a failed tick; the loop keeps running after it. */
20
+ export const WEBHOOK_DELIVERY_FAILED_LINE = "[webhooks] delivery tick failed; retrying after the interval";
21
+ /** Logged when `stop` gives up waiting on a running tick. */
22
+ export const WEBHOOK_DELIVERY_STOP_LATE_LINE = "[webhooks] a delivery tick was still running at shutdown; it was abandoned";
23
+ const MAX_LOGGED_MESSAGE_CHARS = 200;
24
+ /** Bounds the scan of a pathological message before URLs are removed. */
25
+ const MAX_SCANNED_MESSAGE_CHARS = 2_000;
26
+ /** Node timers, unref'd: like the outbox drainer's, the loop must never hold a stopping process open. */
27
+ export const nodeWebhookDeliveryScheduler = {
28
+ every: ({ ms, run }) => {
29
+ const handle = setInterval(run, ms);
30
+ handle.unref();
31
+ return { cancel: () => clearInterval(handle) };
32
+ },
33
+ after: ({ ms, run }) => {
34
+ const handle = setTimeout(run, ms);
35
+ handle.unref();
36
+ return { cancel: () => clearTimeout(handle) };
37
+ },
38
+ };
39
+ /** The abort reason a running pass sees; recorded as the interrupted attempt's error. */
40
+ export class WebhookDeliveryWorkerStoppedError extends Error {
41
+ constructor() {
42
+ super("webhook delivery worker stopped");
43
+ this.name = "AbortError";
44
+ }
45
+ }
46
+ /**
47
+ * One log line for a failed tick: the error's name, message (URLs removed, length capped) and
48
+ * `code`. Never the error object itself, its `cause`, stack or extra fields: a repo or transport
49
+ * error can carry a receiver URL with credentials, request headers or a payload.
50
+ *
51
+ * @complexity O(message length).
52
+ */
53
+ export function describeWebhookTickError(required, _optional = {}) {
54
+ const { error } = required;
55
+ if (!(error instanceof Error))
56
+ return `${WEBHOOK_DELIVERY_FAILED_LINE}: a non-Error value was thrown`;
57
+ // Any space-separated word holding "://" is dropped whole (scheme, userinfo, host, query alike).
58
+ const words = error.message.slice(0, MAX_SCANNED_MESSAGE_CHARS).split(" ");
59
+ const message = words.map((word) => (word.includes("://") ? "[url]" : word)).join(" ").slice(0, MAX_LOGGED_MESSAGE_CHARS);
60
+ const code = error.code;
61
+ const codeSuffix = typeof code === "string" || typeof code === "number" ? ` (code ${code})` : "";
62
+ return `${WEBHOOK_DELIVERY_FAILED_LINE}: ${error.name}: ${message}${codeSuffix}`;
63
+ }
64
+ function assertPositiveFinite(value, name) {
65
+ if (!(Number.isFinite(value) && value > 0))
66
+ throw new RangeError(`webhook delivery ${name} must be a positive finite number`);
67
+ }
68
+ /**
69
+ * Starts the loop. The first tick runs one interval after start.
70
+ *
71
+ * @param required.processDue one delivery pass, given the worker's stop signal.
72
+ * @param optional.intervalMs idle wait between ticks; default {@link WEBHOOK_DELIVERY_INTERVAL_MS}.
73
+ * @throws RangeError when `intervalMs` or `stopGraceMs` is not a positive finite number.
74
+ * @example const worker = startWebhookDeliveryWorker({ processDue: ({ signal }) => processDueDeliveries({ deps }, { signal }) }); await worker.stop();
75
+ * @complexity O(1) per tick, beyond `processDue`.
76
+ */
77
+ export function startWebhookDeliveryWorker(required, optional = {}) {
78
+ const { intervalMs = WEBHOOK_DELIVERY_INTERVAL_MS, stopGraceMs = WEBHOOK_DELIVERY_STOP_GRACE_MS, scheduler = nodeWebhookDeliveryScheduler, log = (line) => console.error(line) } = optional;
79
+ assertPositiveFinite(intervalMs, "intervalMs");
80
+ assertPositiveFinite(stopGraceMs, "stopGraceMs");
81
+ const controller = new AbortController();
82
+ let running;
83
+ const tick = () => {
84
+ if (controller.signal.aborted)
85
+ return Promise.resolve();
86
+ running ??= required.processDue({ signal: controller.signal }).then(() => undefined, (error) => log(describeWebhookTickError({ error }))).finally(() => { running = undefined; });
87
+ return running;
88
+ };
89
+ const timer = scheduler.every({ ms: intervalMs, run: () => { void tick(); } });
90
+ const stop = async () => {
91
+ if (!controller.signal.aborted)
92
+ controller.abort(new WebhookDeliveryWorkerStoppedError());
93
+ timer.cancel();
94
+ if (running === undefined)
95
+ return;
96
+ let grace;
97
+ const late = new Promise((resolve) => { grace = scheduler.after({ ms: stopGraceMs, run: () => resolve("late") }); });
98
+ const outcome = await Promise.race([running, late]);
99
+ grace.cancel();
100
+ if (outcome === "late")
101
+ log(WEBHOOK_DELIVERY_STOP_LATE_LINE);
102
+ };
103
+ return { tick, stop };
104
+ }
105
+ //# sourceMappingURL=worker.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/integrations",
3
- "version": "0.4.2",
3
+ "version": "0.6.10",
4
4
  "description": "Third-party vendor integrations and outbound services, each independently importable: media generation, credentialed HTTP and webhooks.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -16,7 +16,10 @@
16
16
  "./media-providers": "node",
17
17
  "./media-providers/catalog": "universal",
18
18
  "./credentialed-http": "node",
19
- "./webhooks": "node"
19
+ "./webhooks": "node",
20
+ "./api-connections": "node",
21
+ "./media-providers/node": "node",
22
+ "./saved-requests": "node"
20
23
  }
21
24
  },
22
25
  "type": "module",
@@ -41,6 +44,21 @@
41
44
  "types": "./dist/webhooks/index.d.ts",
42
45
  "import": "./dist/webhooks/index.js",
43
46
  "default": "./dist/webhooks/index.js"
47
+ },
48
+ "./api-connections": {
49
+ "types": "./dist/api-connections/index.d.ts",
50
+ "import": "./dist/api-connections/index.js",
51
+ "default": "./dist/api-connections/index.js"
52
+ },
53
+ "./media-providers/node": {
54
+ "types": "./dist/media-providers/dispatch/node.d.ts",
55
+ "import": "./dist/media-providers/dispatch/node.js",
56
+ "default": "./dist/media-providers/dispatch/node.js"
57
+ },
58
+ "./saved-requests": {
59
+ "types": "./dist/saved-requests/index.d.ts",
60
+ "import": "./dist/saved-requests/index.js",
61
+ "default": "./dist/saved-requests/index.js"
44
62
  }
45
63
  },
46
64
  "typesVersions": {
@@ -56,6 +74,15 @@
56
74
  ],
57
75
  "webhooks": [
58
76
  "./dist/webhooks/index.d.ts"
77
+ ],
78
+ "api-connections": [
79
+ "./dist/api-connections/index.d.ts"
80
+ ],
81
+ "media-providers/node": [
82
+ "./dist/media-providers/dispatch/node.d.ts"
83
+ ],
84
+ "saved-requests": [
85
+ "./dist/saved-requests/index.d.ts"
59
86
  ]
60
87
  }
61
88
  },
@@ -76,12 +103,14 @@
76
103
  "registry": "https://registry.npmjs.org"
77
104
  },
78
105
  "dependencies": {
79
- "@jini-ai/core": "^0.4.3"
106
+ "@jini-ai/core": "^0.6.10"
80
107
  },
81
108
  "peerDependencies": {
82
- "@jini-ai/db": "^0.3.0",
109
+ "@jini-ai/db": "^0.6.10",
83
110
  "better-sqlite3": "^13.0.0",
84
- "@jini-ai/platform": "^0.5.1"
111
+ "@jini-ai/platform": "^0.6.10",
112
+ "@jini-ai/oauth": "^0.6.10",
113
+ "@cfworker/json-schema": "^4.1.1"
85
114
  },
86
115
  "peerDependenciesMeta": {
87
116
  "@jini-ai/db": {
@@ -92,16 +121,24 @@
92
121
  },
93
122
  "@jini-ai/platform": {
94
123
  "optional": true
124
+ },
125
+ "@jini-ai/oauth": {
126
+ "optional": true
127
+ },
128
+ "@cfworker/json-schema": {
129
+ "optional": true
95
130
  }
96
131
  },
97
132
  "devDependencies": {
98
133
  "@types/better-sqlite3": "^7.6.11",
99
134
  "better-sqlite3": "^13.0.0",
100
135
  "@vitest/coverage-v8": "^2.1.9",
101
- "@jini-ai/db": "^0.3.2",
102
- "@jini-ai/core": "0.4.3",
103
- "@jini-ai/agent-plugins": "0.4.3",
104
- "@jini-ai/platform": "0.5.3"
136
+ "@cfworker/json-schema": "^4.1.1",
137
+ "@jini-ai/core": "0.6.10",
138
+ "@jini-ai/db": "^0.6.10",
139
+ "@jini-ai/oauth": "0.6.10",
140
+ "@jini-ai/agent-plugins": "0.6.10",
141
+ "@jini-ai/platform": "0.6.10"
105
142
  },
106
143
  "scripts": {
107
144
  "build": "tsc -p tsconfig.json",