@friggframework/core 2.0.0--canary.658.e11f3b0.0 → 2.0.0--canary.737.83b4e17.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.
Files changed (102) hide show
  1. package/CLAUDE.md +42 -58
  2. package/application/commands/README.md +17 -11
  3. package/application/commands/entity-commands.js +18 -60
  4. package/application/commands/integration-commands.js +63 -0
  5. package/core/CLAUDE.md +1 -3
  6. package/core/Worker.js +2 -1
  7. package/core/create-handler.js +0 -3
  8. package/core/index.js +0 -6
  9. package/core/invocation-scope.js +24 -30
  10. package/database/documentdb-encryption-service.js +2 -33
  11. package/database/documentdb-utils.js +4 -1
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/ciphertext-format.js +24 -0
  14. package/database/encryption/encryption-schema-registry.js +109 -29
  15. package/database/encryption/field-encryption-service.js +55 -16
  16. package/database/encryption/prisma-encryption-extension.js +6 -9
  17. package/database/prisma.js +10 -1
  18. package/encrypt/Cryptor.js +90 -38
  19. package/errors/fetch-error.js +18 -11
  20. package/errors/index.js +4 -2
  21. package/errors/mapping-already-exists-error.js +14 -0
  22. package/generated/prisma-mongodb/edge.js +6 -2
  23. package/generated/prisma-mongodb/index.js +10 -2
  24. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  25. package/generated/prisma-mongodb/package.json +1 -1
  26. package/generated/prisma-mongodb/schema.prisma +1 -1
  27. package/generated/prisma-mongodb/wasm.js +6 -2
  28. package/generated/prisma-postgresql/edge.js +6 -2
  29. package/generated/prisma-postgresql/index.js +10 -2
  30. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  31. package/generated/prisma-postgresql/package.json +1 -1
  32. package/generated/prisma-postgresql/schema.prisma +1 -1
  33. package/generated/prisma-postgresql/wasm.js +6 -2
  34. package/handlers/WEBHOOKS.md +29 -0
  35. package/handlers/app-definition-loader.js +9 -2
  36. package/handlers/app-handler-helpers.js +12 -1
  37. package/handlers/workers/integration-defined-workers.js +0 -2
  38. package/index.js +2 -18
  39. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -13
  40. package/integrations/integration-base.js +52 -25
  41. package/integrations/integration-router.js +30 -22
  42. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  43. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  44. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  45. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  46. package/integrations/repositories/integration-mapping-repository.js +29 -0
  47. package/integrations/repositories/integration-repository-documentdb.js +42 -23
  48. package/integrations/repositories/integration-repository-interface.js +37 -21
  49. package/integrations/repositories/integration-repository-mongo.js +69 -30
  50. package/integrations/repositories/integration-repository-postgres.js +74 -30
  51. package/integrations/repositories/process-repository-mongo.js +1 -1
  52. package/integrations/tests/doubles/test-integration-repository.js +2 -15
  53. package/integrations/use-cases/add-entities-to-integration.js +92 -0
  54. package/integrations/use-cases/create-integration.js +57 -19
  55. package/integrations/use-cases/delete-integration-for-user.js +8 -11
  56. package/integrations/use-cases/get-integration-instance.js +12 -12
  57. package/integrations/use-cases/remove-entities-from-integration.js +70 -0
  58. package/integrations/use-cases/update-integration-messages.js +9 -28
  59. package/integrations/use-cases/update-integration.js +12 -12
  60. package/integrations/utils/assert-entity-ids-input.js +42 -0
  61. package/jest-setup.js +13 -2
  62. package/jest-teardown.js +5 -2
  63. package/jest.config.js +4 -0
  64. package/jest.db.config.js +23 -0
  65. package/logs/serialize.js +0 -15
  66. package/modules/module.js +0 -27
  67. package/modules/requester/requester.js +9 -211
  68. package/modules/use-cases/create-entity-from-credential.js +105 -0
  69. package/modules/use-cases/get-entity-options-by-id.js +7 -5
  70. package/modules/use-cases/get-module.js +29 -8
  71. package/modules/use-cases/process-authorization-callback.js +78 -27
  72. package/modules/use-cases/refresh-entity-options.js +7 -5
  73. package/modules/use-cases/test-module-auth.js +7 -5
  74. package/modules/utils/find-module-definition.js +23 -0
  75. package/modules/utils/map-module-dto.js +5 -3
  76. package/modules/utils/to-credential-id.js +14 -0
  77. package/package.json +10 -7
  78. package/prisma-mongodb/schema.prisma +1 -1
  79. package/prisma-postgresql/schema.prisma +1 -1
  80. package/queues/queuer-util.js +9 -7
  81. package/queues/sqs-message-body.js +17 -0
  82. package/telemetry/otel-telemetry.js +76 -3
  83. package/telemetry/telemetry-config.js +16 -5
  84. package/telemetry/telemetry-runtime.js +14 -1
  85. package/token/repositories/token-repository-documentdb.js +13 -1
  86. package/token/repositories/token-repository-mongo.js +13 -1
  87. package/token/repositories/token-repository-postgres.js +13 -1
  88. package/types/core/index.d.ts +0 -33
  89. package/types/errors/index.d.ts +0 -47
  90. package/types/integrations/index.d.ts +4 -20
  91. package/types/module-plugin/index.d.ts +0 -47
  92. package/user/tests/doubles/test-user-repository.js +1 -1
  93. package/user/use-cases/authenticate-user.js +23 -7
  94. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  95. package/core/invocation-deadline.js +0 -91
  96. package/errors/rate-limit-error.js +0 -46
  97. package/integrations/repositories/message-item-shared.js +0 -4
  98. package/integrations/tests/doubles/prisma-message-row.js +0 -24
  99. package/integrations/use-cases/record-rate-limit-message.js +0 -110
  100. package/modules/requester/rate-limit/index.js +0 -4
  101. package/modules/requester/rate-limit/parsers.js +0 -245
  102. package/modules/requester/rate-limit/policy.js +0 -304
@@ -1,110 +0,0 @@
1
- const { getLogger } = require('../../logs');
2
- const { MAX_MESSAGES_PER_TYPE } = require('./update-integration-messages');
3
-
4
- const log = getLogger('frigg.integrations');
5
-
6
- const RATE_LIMITED_MESSAGE_CODE = 'RATE_LIMITED';
7
- const SAME_LIMIT_WINDOW_MS = 60_000;
8
- const MINUTE_MS = 60_000;
9
-
10
- const isNonEmptyString = (value) => typeof value === 'string' && value !== '';
11
-
12
- const isValidTime = (value) =>
13
- value !== null &&
14
- value !== undefined &&
15
- !Number.isNaN(new Date(value).getTime());
16
-
17
- const isLink = (link) =>
18
- typeof link?.label === 'string' && typeof link?.url === 'string';
19
-
20
- const linkActions = (links) =>
21
- (Array.isArray(links) ? links : [])
22
- .filter(isLink)
23
- .map(({ label, url }) => ({ type: 'LINK', label, url }));
24
-
25
- function formatResetTime(date) {
26
- const minute = new Date(Math.ceil(date.getTime() / MINUTE_MS) * MINUTE_MS);
27
- return `${minute.toISOString().slice(0, 16).replace('T', ' ')} UTC`;
28
- }
29
-
30
- /**
31
- * @class RecordRateLimitMessage
32
- */
33
- class RecordRateLimitMessage {
34
- /**
35
- * @param {Object} params - Configuration parameters.
36
- * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository - Repository for integration data operations.
37
- */
38
- constructor({ integrationRepository }) {
39
- this.integrationRepository = integrationRepository;
40
- }
41
-
42
- /**
43
- * @async
44
- * @param {string} integrationId - ID of the integration to warn on.
45
- * @param {Object} payload - The RATE_LIMITED payload of the Module.
46
- * @param {string} payload.moduleName
47
- * @param {string} payload.reason
48
- * @param {Date|string|number} payload.retryAt
49
- * @param {Array<{label: string, url: string}>} [payload.links]
50
- */
51
- async execute(integrationId, payload) {
52
- const { moduleName, reason, retryAt, links } = payload ?? {};
53
- if (!isNonEmptyString(moduleName) || !isValidTime(retryAt)) return;
54
-
55
- try {
56
- await this._recordUnlessStored(integrationId, {
57
- moduleName,
58
- reason,
59
- resetAt: new Date(retryAt),
60
- links,
61
- });
62
- } catch (error) {
63
- log.warn('Failed to record rate limit message', {
64
- eventName:
65
- 'frigg.integrations.rate_limit_message_record_failed',
66
- integrationId,
67
- moduleName,
68
- error,
69
- });
70
- }
71
- }
72
-
73
- async _recordUnlessStored(
74
- integrationId,
75
- { moduleName, reason, resetAt, links }
76
- ) {
77
- const warnings =
78
- await this.integrationRepository.findIntegrationMessages(
79
- integrationId,
80
- 'warnings'
81
- );
82
- const alreadyRecorded = warnings.some(
83
- (warning) =>
84
- warning?.code === RATE_LIMITED_MESSAGE_CODE &&
85
- warning.module === moduleName &&
86
- Math.abs(Date.parse(warning.retryAt) - resetAt.getTime()) <=
87
- SAME_LIMIT_WINDOW_MS
88
- );
89
- if (alreadyRecorded) return;
90
-
91
- const resetsAt = formatResetTime(resetAt);
92
- await this.integrationRepository.updateIntegrationMessages(
93
- integrationId,
94
- 'warnings',
95
- {
96
- title: 'Rate limit reached',
97
- message: `The ${moduleName} API rate limit was reached and resets at ${resetsAt}.`,
98
- timestamp: Date.now(),
99
- code: RATE_LIMITED_MESSAGE_CODE,
100
- module: moduleName,
101
- reason,
102
- retryAt: resetAt.toISOString(),
103
- actions: [{ type: 'RETRY_WHEN_READY' }, ...linkActions(links)],
104
- },
105
- { keepLast: MAX_MESSAGES_PER_TYPE }
106
- );
107
- }
108
- }
109
-
110
- module.exports = { RecordRateLimitMessage };
@@ -1,4 +0,0 @@
1
- const parsers = require('./parsers');
2
- const policy = require('./policy');
3
-
4
- module.exports = { ...parsers, ...policy };
@@ -1,245 +0,0 @@
1
- const MAX_HINT_WAIT_MS = 366 * 24 * 60 * 60 * 1000;
2
-
3
- const SECONDS_PATTERN = /^\d+(?:\.\d+)?$/;
4
- const HAS_LETTER = /[A-Za-z]/;
5
- const EPOCH_SECONDS_MIN = 1e9;
6
- const EPOCH_MILLISECONDS_MIN = 1e12;
7
-
8
- const RESET_HEADERS = [
9
- 'x-ratelimit-reset',
10
- 'ratelimit-reset',
11
- 'x-rate-limit-reset',
12
- ];
13
- const REMAINING_HEADERS = [
14
- 'x-ratelimit-remaining',
15
- 'ratelimit-remaining',
16
- 'x-rate-limit-remaining',
17
- ];
18
-
19
- const isMissing = (value) => value === undefined || value === null;
20
-
21
- function readEntries(headers, wanted) {
22
- for (const entry of headers) {
23
- if (Array.isArray(entry) && String(entry[0]).toLowerCase() === wanted) {
24
- return entry[1];
25
- }
26
- }
27
- return undefined;
28
- }
29
-
30
- function readKeys(headers, wanted) {
31
- for (const key of Object.keys(headers)) {
32
- if (key.toLowerCase() === wanted) return headers[key];
33
- }
34
- return undefined;
35
- }
36
-
37
- function headerValue(headers, name) {
38
- if (!headers || typeof headers !== 'object') return undefined;
39
- const wanted = name.toLowerCase();
40
- const hasGet = typeof headers.get === 'function';
41
-
42
- let value;
43
- if (hasGet) {
44
- value = headers.get(name);
45
- if (isMissing(value)) value = headers.get(wanted);
46
- }
47
- if (isMissing(value) && typeof headers[Symbol.iterator] === 'function') {
48
- value = readEntries(headers, wanted);
49
- }
50
- if (isMissing(value) && !hasGet && !Array.isArray(headers)) {
51
- value = readKeys(headers, wanted);
52
- }
53
- if (Array.isArray(value)) value = value[0];
54
- if (isMissing(value)) return undefined;
55
-
56
- const text = String(value).trim();
57
- return text === '' ? undefined : text;
58
- }
59
-
60
- function definedOnly(fields) {
61
- const result = {};
62
- for (const [key, value] of Object.entries(fields)) {
63
- if (value !== undefined) result[key] = value;
64
- }
65
- return result;
66
- }
67
-
68
- function hintFromWait(waitMs, now, { source = 'header', ...extra } = {}) {
69
- if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > MAX_HINT_WAIT_MS) {
70
- return null;
71
- }
72
- return {
73
- waitMs,
74
- retryAt: new Date(now + waitMs),
75
- ...definedOnly(extra),
76
- source,
77
- };
78
- }
79
-
80
- function hintFromRetryAt(retryAt, now, { source = 'header', ...extra } = {}) {
81
- const at = retryAt instanceof Date ? retryAt.getTime() : Number.NaN;
82
- if (Number.isNaN(at)) return null;
83
- const waitMs = Math.max(0, at - now);
84
- if (waitMs > MAX_HINT_WAIT_MS) return null;
85
- return { waitMs, retryAt: new Date(at), ...definedOnly(extra), source };
86
- }
87
-
88
- function parseDate(text) {
89
- if (!HAS_LETTER.test(text)) return null;
90
- const at = Date.parse(text);
91
- return Number.isNaN(at) ? null : new Date(at);
92
- }
93
-
94
- function parseRetryAfter(value, { now = Date.now() } = {}) {
95
- if (isMissing(value)) return null;
96
- const text = String(value).trim();
97
- if (text === '') return null;
98
- if (SECONDS_PATTERN.test(text))
99
- return hintFromWait(Number(text) * 1000, now);
100
- const date = parseDate(text);
101
- return date ? hintFromRetryAt(date, now) : null;
102
- }
103
-
104
- function numberOrUndefined(text) {
105
- if (text === undefined) return undefined;
106
- const number = Number(text);
107
- return Number.isFinite(number) ? number : undefined;
108
- }
109
-
110
- function firstHeader(headers, names) {
111
- for (const name of names) {
112
- const value = headerValue(headers, name);
113
- if (value !== undefined) return value;
114
- }
115
- return undefined;
116
- }
117
-
118
- function parseResetValue(text, now, extra) {
119
- if (SECONDS_PATTERN.test(text)) {
120
- const number = Number(text);
121
- if (number >= EPOCH_MILLISECONDS_MIN) {
122
- return hintFromRetryAt(new Date(number), now, extra);
123
- }
124
- if (number >= EPOCH_SECONDS_MIN) {
125
- return hintFromRetryAt(new Date(number * 1000), now, extra);
126
- }
127
- return hintFromWait(number * 1000, now, extra);
128
- }
129
- const date = parseDate(text);
130
- return date ? hintFromRetryAt(date, now, extra) : null;
131
- }
132
-
133
- function parseResetHeaders(headers, { now = Date.now() } = {}) {
134
- const remaining = numberOrUndefined(
135
- firstHeader(headers, REMAINING_HEADERS)
136
- );
137
- const extra = { remaining };
138
-
139
- const after = headerValue(headers, 'x-ratelimit-reset-after');
140
- if (after !== undefined && SECONDS_PATTERN.test(after)) {
141
- return hintFromWait(Number(after) * 1000, now, extra);
142
- }
143
-
144
- for (const name of RESET_HEADERS) {
145
- const value = headerValue(headers, name);
146
- if (value === undefined) continue;
147
- const hint = parseResetValue(value, now, extra);
148
- if (hint) return hint;
149
- }
150
- return null;
151
- }
152
-
153
- function splitList(text) {
154
- const items = [];
155
- let current = '';
156
- let quoted = false;
157
- for (const char of text) {
158
- if (char === '"') quoted = !quoted;
159
- if (char === ',' && !quoted) {
160
- items.push(current);
161
- current = '';
162
- } else {
163
- current += char;
164
- }
165
- }
166
- items.push(current);
167
- return items.map((item) => item.trim()).filter(Boolean);
168
- }
169
-
170
- function parseStructuredItem(item) {
171
- const [head, ...params] = item.split(';').map((part) => part.trim());
172
- const values = {};
173
- for (const param of params) {
174
- const [key, raw] = param.split('=').map((part) => part.trim());
175
- if (key) values[key] = numberOrUndefined(raw);
176
- }
177
- const name = head.replace(/^"|"$/g, '');
178
- return {
179
- name: name || undefined,
180
- remaining: values.r,
181
- waitSeconds: values.t,
182
- };
183
- }
184
-
185
- function pickStructured(items) {
186
- const usable = items.filter(
187
- (item) => Number.isFinite(item.waitSeconds) && item.waitSeconds >= 0
188
- );
189
- usable.sort((a, b) => {
190
- const byRemaining =
191
- (a.remaining ?? Infinity) - (b.remaining ?? Infinity);
192
- if (byRemaining !== 0 && !Number.isNaN(byRemaining)) return byRemaining;
193
- return b.waitSeconds - a.waitSeconds;
194
- });
195
- return usable[0];
196
- }
197
-
198
- function readKeyValue(text, key) {
199
- const match = new RegExp(
200
- String.raw`(?:^|[,;\s])${key}\s*=\s*([^,;\s]+)`,
201
- 'i'
202
- ).exec(text);
203
- return match ? match[1] : undefined;
204
- }
205
-
206
- function parseIetfRateLimit(headers, { now = Date.now() } = {}) {
207
- const raw = headerValue(headers, 'ratelimit');
208
- if (raw === undefined) return null;
209
- const policyHeader = headerValue(headers, 'ratelimit-policy');
210
-
211
- if (/;\s*t\s*=/.test(raw)) {
212
- const chosen = pickStructured(splitList(raw).map(parseStructuredItem));
213
- if (!chosen) return null;
214
- return hintFromWait(chosen.waitSeconds * 1000, now, {
215
- remaining: chosen.remaining,
216
- policy: chosen.name ?? policyHeader,
217
- });
218
- }
219
-
220
- const reset = readKeyValue(raw, 'reset');
221
- if (reset === undefined || !SECONDS_PATTERN.test(reset)) return null;
222
- return hintFromWait(Number(reset) * 1000, now, {
223
- remaining: numberOrUndefined(readKeyValue(raw, 'remaining')),
224
- policy: policyHeader,
225
- });
226
- }
227
-
228
- const BUILT_IN_PARSERS = {
229
- retryAfter: (headers, { now } = {}) =>
230
- parseRetryAfter(headerValue(headers, 'retry-after'), { now }),
231
- resetHeaders: parseResetHeaders,
232
- ietf: parseIetfRateLimit,
233
- };
234
-
235
- module.exports = {
236
- BUILT_IN_PARSERS,
237
- MAX_HINT_WAIT_MS,
238
- definedOnly,
239
- headerValue,
240
- hintFromRetryAt,
241
- hintFromWait,
242
- parseIetfRateLimit,
243
- parseResetHeaders,
244
- parseRetryAfter,
245
- };
@@ -1,304 +0,0 @@
1
- const {
2
- BUILT_IN_PARSERS,
3
- definedOnly,
4
- hintFromRetryAt,
5
- hintFromWait,
6
- } = require('./parsers');
7
-
8
- const DEFAULT_PARSERS = ['retryAfter', 'resetHeaders', 'ietf'];
9
- const MIN_HINTED_WAIT_MS = 1_000;
10
- const JITTER_MAX_MS = 1_000;
11
- const JITTER_RATIO = 0.1;
12
-
13
- const REASONS = new Set([
14
- 'burst',
15
- 'daily',
16
- 'monthly',
17
- 'concurrency',
18
- 'unknown',
19
- ]);
20
- const CLASSIFY_SOURCES = new Set(['header', 'body', 'static']);
21
- const SCOPES = new Set(['credential', 'entity', 'app']);
22
-
23
- const normalizedPolicies = new WeakSet();
24
- const policiesByClass = new WeakMap();
25
-
26
- const isObject = (value) => value !== null && typeof value === 'object';
27
- const isThenable = (value) => typeof value?.then === 'function';
28
-
29
- function isPlainObject(value) {
30
- if (!isObject(value) || Array.isArray(value)) return false;
31
- const prototype = Object.getPrototypeOf(value);
32
- return prototype === Object.prototype || prototype === null;
33
- }
34
-
35
- function readParsers(raw, owner) {
36
- if (!Array.isArray(raw.parsers)) return [...DEFAULT_PARSERS];
37
- for (const name of raw.parsers) {
38
- if (!Object.hasOwn(BUILT_IN_PARSERS, name)) {
39
- throw new TypeError(
40
- `${owner}.rateLimit.parsers: unknown parser "${String(
41
- name
42
- )}"; known: ${Object.keys(BUILT_IN_PARSERS).join(', ')}`
43
- );
44
- }
45
- }
46
- return [...raw.parsers];
47
- }
48
-
49
- function normalizePolicy(raw, owner) {
50
- if (!isPlainObject(raw)) return undefined;
51
-
52
- const policy = {
53
- scope:
54
- SCOPES.has(raw.scope) || typeof raw.scope === 'function'
55
- ? raw.scope
56
- : 'entity',
57
- parsers: readParsers(raw, owner),
58
- };
59
- if (typeof raw.classify === 'function') {
60
- policy.classify = (signal) => raw.classify(signal);
61
- }
62
- if (Number.isFinite(raw.minRetryAfterMs) && raw.minRetryAfterMs >= 0) {
63
- policy.minRetryAfterMs = raw.minRetryAfterMs;
64
- }
65
- if (Number.isInteger(raw.maxConcurrency) && raw.maxConcurrency > 0) {
66
- policy.maxConcurrency = raw.maxConcurrency;
67
- }
68
- if (Array.isArray(raw.windows)) policy.windows = raw.windows;
69
- if (isPlainObject(raw.userHints)) policy.userHints = raw.userHints;
70
-
71
- normalizedPolicies.add(policy);
72
- return policy;
73
- }
74
-
75
- function readRateLimitPolicy(ctor) {
76
- if (typeof ctor !== 'function') return undefined;
77
- if (policiesByClass.has(ctor)) return policiesByClass.get(ctor);
78
- const policy = normalizePolicy(ctor.rateLimit, ctor.name || 'Requester');
79
- policiesByClass.set(ctor, policy);
80
- return policy;
81
- }
82
-
83
- function asPolicy(value) {
84
- if (!isObject(value)) return undefined;
85
- if (normalizedPolicies.has(value)) return value;
86
- return normalizePolicy(value, 'policy');
87
- }
88
-
89
- function computeScopeKey(policy, requester) {
90
- const label = requester?._telemetryModuleLabel?.() ?? 'unknown';
91
- const scope = policy?.scope ?? 'entity';
92
- const delegate = requester?.delegate;
93
-
94
- if (scope === 'app') return `${label}:app`;
95
- if (scope === 'entity') {
96
- const id = delegate?.entity?.id;
97
- return id === undefined || id === null
98
- ? undefined
99
- : `${label}:entity:${id}`;
100
- }
101
- if (scope === 'credential') {
102
- const credential = delegate?.credential;
103
- const id =
104
- credential?.id ??
105
- (typeof credential === 'string' ? credential : undefined);
106
- return id === undefined || id === null
107
- ? undefined
108
- : `${label}:credential:${id}`;
109
- }
110
- if (typeof scope === 'function') {
111
- try {
112
- const value = scope(requester);
113
- return typeof value === 'string' || Number.isFinite(value)
114
- ? `${label}:custom:${value}`
115
- : undefined;
116
- } catch {
117
- return undefined;
118
- }
119
- }
120
- return undefined;
121
- }
122
-
123
- function toDate(value) {
124
- if (value === undefined || value === null) return null;
125
- const date = value instanceof Date ? value : new Date(value);
126
- return Number.isNaN(date.getTime()) ? null : date;
127
- }
128
-
129
- function normalizeClassified(raw, now) {
130
- if (!isObject(raw)) return null;
131
- const retryAt = toDate(raw.retryAt);
132
- if (!REASONS.has(raw.reason) && !Number.isFinite(raw.waitMs) && !retryAt) {
133
- return null;
134
- }
135
-
136
- const extra = {
137
- reason: REASONS.has(raw.reason) ? raw.reason : 'unknown',
138
- policy: typeof raw.policy === 'string' ? raw.policy : undefined,
139
- remaining: Number.isFinite(raw.remaining) ? raw.remaining : undefined,
140
- source: CLASSIFY_SOURCES.has(raw.source) ? raw.source : 'body',
141
- };
142
-
143
- let hint = retryAt ? hintFromRetryAt(retryAt, now, extra) : null;
144
- if (!hint && Number.isFinite(raw.waitMs)) {
145
- hint = hintFromWait(raw.waitMs, now, extra);
146
- }
147
- return {
148
- reason: extra.reason,
149
- policy: extra.policy,
150
- remaining: extra.remaining,
151
- hint,
152
- };
153
- }
154
-
155
- function runClassify(policy, signal, now, onClassifyError) {
156
- if (typeof policy?.classify !== 'function') return null;
157
- let raw;
158
- try {
159
- raw = policy.classify({
160
- status: signal.status,
161
- headers: signal.headers,
162
- body: signal.body,
163
- });
164
- if (isThenable(raw)) {
165
- Promise.resolve(raw).catch(() => {});
166
- throw new TypeError(
167
- 'classify() must return a hint or null, not a Promise'
168
- );
169
- }
170
- } catch (error) {
171
- if (!onClassifyError) throw error;
172
- onClassifyError(error);
173
- return null;
174
- }
175
- return normalizeClassified(raw, now);
176
- }
177
-
178
- function parsedHint(policy, headers, now) {
179
- for (const name of policy?.parsers ?? DEFAULT_PARSERS) {
180
- const hint = BUILT_IN_PARSERS[name](headers, { now });
181
- if (hint) return hint;
182
- }
183
- return null;
184
- }
185
-
186
- function staticHint(policy, reason, now) {
187
- const window = policy?.windows?.find(
188
- (candidate) =>
189
- candidate &&
190
- candidate.name === reason &&
191
- Number.isFinite(candidate.perMs) &&
192
- candidate.perMs > 0
193
- );
194
- const waitMs = Math.max(window?.perMs ?? 0, policy?.minRetryAfterMs ?? 0);
195
- return waitMs > 0 ? hintFromWait(waitMs, now, { source: 'static' }) : null;
196
- }
197
-
198
- function withClassified(hint, classified) {
199
- return {
200
- ...hint,
201
- reason: classified?.reason ?? 'unknown',
202
- ...definedOnly({
203
- policy: classified?.policy ?? hint.policy,
204
- remaining: classified?.remaining ?? hint.remaining,
205
- }),
206
- };
207
- }
208
-
209
- function resolveCandidates(policy, signal, { now, onClassifyError }) {
210
- const classified = runClassify(policy, signal, now, onClassifyError);
211
- if (signal.status !== 429 && !classified) return { hint: null, classified };
212
- if (classified?.hint) return { hint: classified.hint, classified };
213
-
214
- const parsed = parsedHint(policy, signal.headers, now);
215
- if (parsed) return { hint: withClassified(parsed, classified), classified };
216
-
217
- const fromPolicy = staticHint(policy, classified?.reason, now);
218
- if (fromPolicy) {
219
- return { hint: withClassified(fromPolicy, classified), classified };
220
- }
221
- return { hint: null, classified };
222
- }
223
-
224
- function classifyRateLimit(policy, signal, options = {}) {
225
- const { now = Date.now(), onClassifyError } = options;
226
- return resolveCandidates(asPolicy(policy), signal, { now, onClassifyError })
227
- .hint;
228
- }
229
-
230
- function resolveRateLimitHint(policy, signal, options = {}) {
231
- const {
232
- attempt = 0,
233
- backOff = [],
234
- now = Date.now(),
235
- onClassifyError,
236
- } = options;
237
- const { hint, classified } = resolveCandidates(asPolicy(policy), signal, {
238
- now,
239
- onClassifyError,
240
- });
241
- if (hint) return hint;
242
- if (signal.status !== 429 && !classified) return null;
243
- if (signal.status !== 429) {
244
- return {
245
- reason: classified.reason,
246
- ...definedOnly({
247
- policy: classified.policy,
248
- remaining: classified.remaining,
249
- }),
250
- };
251
- }
252
-
253
- const waitMs =
254
- attempt < backOff.length ? Number(backOff[attempt]) * 1000 || 0 : 0;
255
- return {
256
- waitMs,
257
- retryAt: new Date(now + waitMs),
258
- reason: classified?.reason ?? 'unknown',
259
- ...definedOnly({
260
- policy: classified?.policy,
261
- remaining: classified?.remaining,
262
- }),
263
- source: 'backoff',
264
- };
265
- }
266
-
267
- function computeWaitMs({ hint, policy, budgetMs, random = Math.random }) {
268
- const base = Math.max(
269
- hint.waitMs,
270
- policy?.minRetryAfterMs ?? 0,
271
- MIN_HINTED_WAIT_MS
272
- );
273
- if (base > budgetMs) return { waitMs: base, fits: false };
274
-
275
- const jitter = Math.floor(
276
- random() * Math.min(JITTER_MAX_MS, base * JITTER_RATIO)
277
- );
278
- return { waitMs: Math.min(base + jitter, budgetMs), fits: true };
279
- }
280
-
281
- function inProcessBudgetMs({
282
- maxInProcessWaitMs,
283
- requestTimeoutMs = 0,
284
- remainingMs = Infinity,
285
- waitedMs = 0,
286
- } = {}) {
287
- const reserveMs = Math.min(requestTimeoutMs || 0, remainingMs / 2);
288
- return Math.max(
289
- 0,
290
- Math.min(maxInProcessWaitMs - waitedMs, remainingMs - reserveMs)
291
- );
292
- }
293
-
294
- module.exports = {
295
- DEFAULT_PARSERS,
296
- JITTER_MAX_MS,
297
- MIN_HINTED_WAIT_MS,
298
- classifyRateLimit,
299
- computeScopeKey,
300
- computeWaitMs,
301
- inProcessBudgetMs,
302
- readRateLimitPolicy,
303
- resolveRateLimitHint,
304
- };