assignment-user-matcher 1.1.6 → 1.2.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 (43) hide show
  1. package/dist/index.d.ts +4 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +26 -1
  4. package/dist/managers/ReliabilityManager.d.ts +42 -0
  5. package/dist/managers/ReliabilityManager.d.ts.map +1 -0
  6. package/dist/managers/ReliabilityManager.js +115 -0
  7. package/dist/managers/TelemetryManager.d.ts +13 -0
  8. package/dist/managers/TelemetryManager.d.ts.map +1 -0
  9. package/dist/managers/TelemetryManager.js +52 -0
  10. package/dist/managers/WorkflowManager.d.ts +62 -0
  11. package/dist/managers/WorkflowManager.d.ts.map +1 -0
  12. package/dist/managers/WorkflowManager.js +654 -0
  13. package/dist/matcher.class.d.ts +142 -77
  14. package/dist/matcher.class.d.ts.map +1 -1
  15. package/dist/matcher.class.js +437 -438
  16. package/dist/queries/index.d.ts +5 -0
  17. package/dist/queries/index.d.ts.map +1 -0
  18. package/dist/queries/index.js +20 -0
  19. package/dist/queries/pagination.d.ts +51 -0
  20. package/dist/queries/pagination.d.ts.map +1 -0
  21. package/dist/queries/pagination.js +200 -0
  22. package/dist/scoring/index.d.ts +5 -0
  23. package/dist/scoring/index.d.ts.map +1 -0
  24. package/dist/scoring/index.js +20 -0
  25. package/dist/scoring/match-score.d.ts +19 -0
  26. package/dist/scoring/match-score.d.ts.map +1 -0
  27. package/dist/scoring/match-score.js +84 -0
  28. package/dist/types/matcher.d.ts +261 -0
  29. package/dist/types/matcher.d.ts.map +1 -0
  30. package/dist/types/matcher.js +2 -0
  31. package/dist/utils/cidr.d.ts +40 -0
  32. package/dist/utils/cidr.d.ts.map +1 -0
  33. package/dist/utils/cidr.js +150 -0
  34. package/dist/utils/index.d.ts +6 -0
  35. package/dist/utils/index.d.ts.map +1 -0
  36. package/dist/utils/index.js +21 -0
  37. package/dist/utils/keys.d.ts +45 -0
  38. package/dist/utils/keys.d.ts.map +1 -0
  39. package/dist/utils/keys.js +57 -0
  40. package/dist/workflow-builder.d.ts +182 -0
  41. package/dist/workflow-builder.d.ts.map +1 -0
  42. package/dist/workflow-builder.js +341 -0
  43. package/package.json +1 -1
@@ -0,0 +1,261 @@
1
+ import { createClient } from 'redis';
2
+ export type RedisClientType = ReturnType<typeof createClient>;
3
+ export interface User {
4
+ id: string;
5
+ tags: string[];
6
+ routingWeights?: Record<string, number>;
7
+ ip?: string;
8
+ [key: string]: any;
9
+ }
10
+ export type Assignment = {
11
+ id: string;
12
+ tags: string[];
13
+ priority?: number;
14
+ allowedCidrs?: string[];
15
+ [key: string]: any;
16
+ };
17
+ export type Stats = {
18
+ users?: number;
19
+ usersWithoutAssignment?: string[];
20
+ remainingAssignments?: number;
21
+ };
22
+ export type MatcherOptions = {
23
+ relevantBatchSize?: number;
24
+ redisPrefix?: string;
25
+ maxUserBacklogSize?: number;
26
+ enableDefaultMatching?: boolean;
27
+ matchExpirationMs?: number;
28
+ prioritizationFunction?: (...args: (Assignment | undefined)[]) => Promise<number>;
29
+ matchingFunction?: (user: User, assignmentTags: string, assignmentPriority: number | string, assignmentId?: string) => Promise<[number, number]>;
30
+ /** Enable workflow orchestration features */
31
+ enableWorkflows?: boolean;
32
+ /** Consumer group name for Redis Streams (defaults to 'orchestrator') */
33
+ streamConsumerGroup?: string;
34
+ /** Consumer name within the group (defaults to random UUID) */
35
+ streamConsumerName?: string;
36
+ /** Maximum retries for failed workflow events before moving to DLQ (default: 3) */
37
+ workflowMaxRetries?: number;
38
+ /** TTL for idempotency keys in milliseconds (default: 86400000 = 24h) */
39
+ workflowIdempotencyTtlMs?: number;
40
+ /** Minimum idle time before reclaiming orphaned messages in ms (default: 60000 = 1min) */
41
+ workflowOrphanReclaimMs?: number;
42
+ /** Number of failures before circuit breaker opens (default: 5) */
43
+ workflowCircuitBreakerThreshold?: number;
44
+ /** Time to wait before attempting to close circuit breaker in ms (default: 30000) */
45
+ workflowCircuitBreakerResetMs?: number;
46
+ /** Enable audit trail stream for compliance (default: false) */
47
+ workflowAuditEnabled?: boolean;
48
+ /** Snapshot workflow definitions at instance creation for versioning (default: true) */
49
+ workflowSnapshotDefinitions?: boolean;
50
+ /** Enable OpenTelemetry tracing (default: false) */
51
+ enableOpenTelemetry?: boolean;
52
+ };
53
+ /** @deprecated Use MatcherOptions instead */
54
+ export type options = MatcherOptions;
55
+ /** Event types for workflow lifecycle */
56
+ export type WorkflowEventType = 'STARTED' | 'COMPLETED' | 'REJECTED' | 'EXPIRED' | 'FAILED';
57
+ /** Event published to Redis Streams for workflow orchestration */
58
+ export interface WorkflowEvent {
59
+ eventId: string;
60
+ type: WorkflowEventType;
61
+ userId: string;
62
+ assignmentId: string;
63
+ workflowInstanceId?: string;
64
+ stepId?: string;
65
+ timestamp: number;
66
+ payload?: Record<string, any>;
67
+ }
68
+ /** Routing condition for workflow branching */
69
+ export interface WorkflowRouting {
70
+ /** Condition expression evaluated against assignment result (e.g., 'result.score > 80') */
71
+ condition: string;
72
+ /** Target step ID if condition is true */
73
+ targetStepId: string;
74
+ }
75
+ /** A single step in a workflow definition */
76
+ export interface WorkflowStep {
77
+ /** Unique identifier for this step within the workflow */
78
+ id: string;
79
+ /** Human-readable name */
80
+ name: string;
81
+ /** Assignment template - merged with workflow context when creating the assignment */
82
+ assignmentTemplate: Partial<Assignment>;
83
+ /** Target user selector: 'initiator' | 'previous' | specific userId | tag-based selector */
84
+ targetUser: 'initiator' | 'previous' | string | {
85
+ tag: string;
86
+ };
87
+ /** Routing rules for branching (evaluated in order, first match wins) */
88
+ routing?: WorkflowRouting[];
89
+ /** Default next step if no routing condition matches (null = end workflow) */
90
+ defaultNextStepId?: string | null;
91
+ /** For parallel execution: IDs of steps to execute simultaneously */
92
+ parallelStepIds?: string[];
93
+ /** For parallel joins: wait for all parallel steps before continuing */
94
+ waitForAll?: boolean;
95
+ /** Failure policy for parallel steps: 'abort' | 'continue' | 'retry' */
96
+ failurePolicy?: 'abort' | 'continue' | 'retry';
97
+ /** Maximum retries for this step (default: 0) */
98
+ maxRetries?: number;
99
+ /** Timeout override for this step in milliseconds */
100
+ timeoutMs?: number;
101
+ }
102
+ /** A workflow definition (template) */
103
+ export interface WorkflowDefinition {
104
+ /** Unique identifier for this workflow definition */
105
+ id: string;
106
+ /** Human-readable name */
107
+ name: string;
108
+ /** Version for schema evolution */
109
+ version: number;
110
+ /** The entry point step ID */
111
+ initialStepId: string;
112
+ /** All steps in this workflow */
113
+ steps: WorkflowStep[];
114
+ /** Default timeout for steps in milliseconds */
115
+ defaultTimeoutMs?: number;
116
+ /** Metadata for the workflow */
117
+ metadata?: Record<string, any>;
118
+ }
119
+ /** Status of a workflow instance */
120
+ export type WorkflowInstanceStatus = 'active' | 'completed' | 'failed' | 'cancelled';
121
+ /** Tracks the state of a parallel execution branch */
122
+ export interface ParallelBranchState {
123
+ stepId: string;
124
+ assignmentId: string;
125
+ status: 'pending' | 'completed' | 'failed';
126
+ result?: Record<string, any>;
127
+ }
128
+ /** A running instance of a workflow */
129
+ export interface WorkflowInstance {
130
+ /** Unique identifier for this instance */
131
+ id: string;
132
+ /** Reference to the workflow definition */
133
+ workflowDefinitionId: string;
134
+ /** The user who initiated this workflow */
135
+ initiatorUserId: string;
136
+ /** Current status */
137
+ status: WorkflowInstanceStatus;
138
+ /** Current step ID (null if completed or in parallel execution) */
139
+ currentStepId: string | null;
140
+ /** Current assignment ID being processed */
141
+ currentAssignmentId?: string;
142
+ /** For parallel execution: track all active branches */
143
+ parallelBranches?: ParallelBranchState[];
144
+ /** Persistent context passed between steps */
145
+ context: Record<string, any>;
146
+ /** History of completed steps with their results */
147
+ history: Array<{
148
+ stepId: string;
149
+ assignmentId: string;
150
+ userId: string;
151
+ completedAt: number;
152
+ result?: Record<string, any>;
153
+ }>;
154
+ /** Retry count for current step */
155
+ retryCount: number;
156
+ /** Version for optimistic locking */
157
+ version: number;
158
+ /** Timestamps */
159
+ createdAt: number;
160
+ updatedAt: number;
161
+ /** Snapshot of the workflow definition at instance creation time (for versioning) */
162
+ definitionSnapshot?: WorkflowDefinition;
163
+ }
164
+ /** Result payload when completing an assignment */
165
+ export interface AssignmentResult {
166
+ /** Outcome: success or failure */
167
+ success: boolean;
168
+ /** Arbitrary result data for routing decisions */
169
+ data?: Record<string, any>;
170
+ /** Error message if failed */
171
+ error?: string;
172
+ }
173
+ /** Dead Letter Queue entry for failed events */
174
+ export interface DeadLetterEntry {
175
+ /** Original event that failed */
176
+ event: WorkflowEvent;
177
+ /** Reason the event failed */
178
+ reason: string;
179
+ /** Error message if available */
180
+ errorMessage?: string;
181
+ /** Error stack trace if available */
182
+ errorStack?: string;
183
+ /** Timestamp when moved to DLQ */
184
+ movedAt: number;
185
+ /** Number of processing attempts before moving to DLQ */
186
+ retryCount: number;
187
+ }
188
+ /** Audit trail entry for compliance */
189
+ export interface AuditEntry {
190
+ /** Timestamp of the action */
191
+ timestamp: number;
192
+ /** Type of action */
193
+ action: string;
194
+ /** Resource ID (event ID, workflow instance ID, etc.) */
195
+ resourceId: string;
196
+ /** Type of resource */
197
+ resourceType: string;
198
+ /** Consumer ID that processed the event */
199
+ consumerId: string;
200
+ /** Additional details */
201
+ details?: Record<string, any>;
202
+ }
203
+ /** Circuit breaker state for backpressure management */
204
+ export interface CircuitBreakerState {
205
+ /** Current state of the circuit breaker */
206
+ state: 'closed' | 'open' | 'half-open';
207
+ /** Number of consecutive failures */
208
+ failureCount: number;
209
+ /** Timestamp of last failure */
210
+ lastFailureTime: number;
211
+ }
212
+ /** Workflow instance with resolved definition for versioning */
213
+ export interface WorkflowInstanceWithSnapshot extends WorkflowInstance {
214
+ /** Resolved definition (from snapshot or registry) */
215
+ resolvedDefinition?: WorkflowDefinition;
216
+ }
217
+ /** Fluent builder for creating workflow steps */
218
+ export interface WorkflowStepBuilder {
219
+ /** Set the step name */
220
+ name(name: string): WorkflowStepBuilder;
221
+ /** Set the assignment template */
222
+ assignment(template: Partial<Assignment>): WorkflowStepBuilder;
223
+ /** Set the target user */
224
+ targetUser(target: 'initiator' | 'previous' | string | {
225
+ tag: string;
226
+ }): WorkflowStepBuilder;
227
+ /** Add a routing condition */
228
+ when(condition: string, targetStepId: string): WorkflowStepBuilder;
229
+ /** Set the default next step */
230
+ then(stepId: string | null): WorkflowStepBuilder;
231
+ /** Add parallel steps */
232
+ parallel(stepIds: string[]): WorkflowStepBuilder;
233
+ /** Set wait for all parallel steps */
234
+ waitForAll(wait: boolean): WorkflowStepBuilder;
235
+ /** Set failure policy */
236
+ onFailure(policy: 'abort' | 'continue' | 'retry'): WorkflowStepBuilder;
237
+ /** Set max retries */
238
+ retries(count: number): WorkflowStepBuilder;
239
+ /** Set step timeout */
240
+ timeout(ms: number): WorkflowStepBuilder;
241
+ /** Build the step */
242
+ build(): WorkflowStep;
243
+ }
244
+ /** Fluent builder for creating workflow definitions */
245
+ export interface WorkflowDefinitionBuilder {
246
+ /** Set the workflow name */
247
+ name(name: string): WorkflowDefinitionBuilder;
248
+ /** Set the workflow version */
249
+ version(version: number): WorkflowDefinitionBuilder;
250
+ /** Set the initial step ID */
251
+ startWith(stepId: string): WorkflowDefinitionBuilder;
252
+ /** Add a step to the workflow */
253
+ addStep(step: WorkflowStep): WorkflowDefinitionBuilder;
254
+ /** Set default timeout for all steps */
255
+ defaultTimeout(ms: number): WorkflowDefinitionBuilder;
256
+ /** Add metadata */
257
+ metadata(data: Record<string, any>): WorkflowDefinitionBuilder;
258
+ /** Build the workflow definition */
259
+ build(): WorkflowDefinition;
260
+ }
261
+ //# sourceMappingURL=matcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matcher.d.ts","sourceRoot":"","sources":["../../src/types/matcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAErC,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;AAE9D,MAAM,WAAW,IAAI;IACjB,EAAE,EAAE,MAA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;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,yBAAyB,CAAC;IAC/D,oCAAoC;IACpC,KAAK,IAAI,kBAAkB,CAAC;CAC/B"}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,40 @@
1
+ /**
2
+ * CIDR/IP Matching Utilities
3
+ * Pure functions for IPv4/IPv6 parsing and CIDR range matching
4
+ */
5
+ /**
6
+ * Parse an IPv4 address into a BigInt representation
7
+ */
8
+ export declare function parseIPv4(ip: string): bigint | null;
9
+ /**
10
+ * Parse an IPv6 address into a BigInt representation
11
+ * Handles full, compressed (::), and IPv4-mapped formats
12
+ */
13
+ export declare function parseIPv6(ip: string): bigint | null;
14
+ /**
15
+ * Parse an IP address (auto-detect IPv4 or IPv6)
16
+ * Returns { value: BigInt, isIPv6: boolean } or null if invalid
17
+ */
18
+ export declare function parseIP(ip: string): {
19
+ value: bigint;
20
+ isIPv6: boolean;
21
+ } | null;
22
+ /**
23
+ * Parse a CIDR notation string (e.g., '192.168.1.0/24' or '2001:db8::/32')
24
+ * Returns { network: BigInt, prefixLength: number, isIPv6: boolean } or null
25
+ */
26
+ export declare function parseCIDR(cidr: string): {
27
+ network: bigint;
28
+ prefixLength: number;
29
+ isIPv6: boolean;
30
+ } | null;
31
+ /**
32
+ * Check if an IP address is within a CIDR range
33
+ */
34
+ export declare function isIpInCidr(ip: string, cidr: string): boolean;
35
+ /**
36
+ * Check if a user's IP matches any of the allowed CIDRs
37
+ * Returns true if no CIDRs are specified (open assignment) or if IP matches any CIDR
38
+ */
39
+ export declare function checkCidrMatch(userIp: string | undefined, allowedCidrs: string[] | undefined): boolean;
40
+ //# sourceMappingURL=cidr.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cidr.d.ts","sourceRoot":"","sources":["../../src/utils/cidr.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;GAEG;AACH,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAWnD;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAqCnD;AAED;;;GAGG;AACH,wBAAgB,OAAO,CAAC,EAAE,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAkB7E;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAqBzG;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAc5D;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,SAAS,GAAG,OAAO,CAatG"}
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ /**
3
+ * CIDR/IP Matching Utilities
4
+ * Pure functions for IPv4/IPv6 parsing and CIDR range matching
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.checkCidrMatch = exports.isIpInCidr = exports.parseCIDR = exports.parseIP = exports.parseIPv6 = exports.parseIPv4 = void 0;
8
+ /**
9
+ * Parse an IPv4 address into a BigInt representation
10
+ */
11
+ function parseIPv4(ip) {
12
+ const parts = ip.split('.');
13
+ if (parts.length !== 4)
14
+ return null;
15
+ let result = 0n;
16
+ for (const part of parts) {
17
+ const num = parseInt(part, 10);
18
+ if (isNaN(num) || num < 0 || num > 255)
19
+ return null;
20
+ result = (result << 8n) | BigInt(num);
21
+ }
22
+ return result;
23
+ }
24
+ exports.parseIPv4 = parseIPv4;
25
+ /**
26
+ * Parse an IPv6 address into a BigInt representation
27
+ * Handles full, compressed (::), and IPv4-mapped formats
28
+ */
29
+ function parseIPv6(ip) {
30
+ // Handle IPv4-mapped IPv6 (::ffff:192.168.1.1)
31
+ const ipv4MappedMatch = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
32
+ if (ipv4MappedMatch) {
33
+ const ipv4 = parseIPv4(ipv4MappedMatch[1]);
34
+ if (ipv4 === null)
35
+ return null;
36
+ return 0xffff00000000n | ipv4;
37
+ }
38
+ // Handle :: expansion
39
+ let fullIp = ip.toLowerCase();
40
+ if (fullIp.includes('::')) {
41
+ const parts = fullIp.split('::');
42
+ if (parts.length > 2)
43
+ return null; // Invalid: more than one ::
44
+ const leftParts = parts[0] ? parts[0].split(':') : [];
45
+ const rightParts = parts[1] ? parts[1].split(':') : [];
46
+ const missingGroups = 8 - leftParts.length - rightParts.length;
47
+ if (missingGroups < 0)
48
+ return null;
49
+ const allParts = [...leftParts, ...Array(missingGroups).fill('0'), ...rightParts];
50
+ fullIp = allParts.join(':');
51
+ }
52
+ const groups = fullIp.split(':');
53
+ if (groups.length !== 8)
54
+ return null;
55
+ let result = 0n;
56
+ for (const group of groups) {
57
+ if (group.length === 0 || group.length > 4)
58
+ return null;
59
+ const num = parseInt(group, 16);
60
+ if (isNaN(num) || num < 0 || num > 0xffff)
61
+ return null;
62
+ result = (result << 16n) | BigInt(num);
63
+ }
64
+ return result;
65
+ }
66
+ exports.parseIPv6 = parseIPv6;
67
+ /**
68
+ * Parse an IP address (auto-detect IPv4 or IPv6)
69
+ * Returns { value: BigInt, isIPv6: boolean } or null if invalid
70
+ */
71
+ function parseIP(ip) {
72
+ if (!ip || typeof ip !== 'string')
73
+ return null;
74
+ const trimmed = ip.trim();
75
+ // Try IPv4 first (contains dots, no colons)
76
+ if (trimmed.includes('.') && !trimmed.includes(':')) {
77
+ const value = parseIPv4(trimmed);
78
+ if (value !== null)
79
+ return { value, isIPv6: false };
80
+ }
81
+ // Try IPv6 (contains colons)
82
+ if (trimmed.includes(':')) {
83
+ const value = parseIPv6(trimmed);
84
+ if (value !== null)
85
+ return { value, isIPv6: true };
86
+ }
87
+ return null;
88
+ }
89
+ exports.parseIP = parseIP;
90
+ /**
91
+ * Parse a CIDR notation string (e.g., '192.168.1.0/24' or '2001:db8::/32')
92
+ * Returns { network: BigInt, prefixLength: number, isIPv6: boolean } or null
93
+ */
94
+ function parseCIDR(cidr) {
95
+ if (!cidr || typeof cidr !== 'string')
96
+ return null;
97
+ const parts = cidr.trim().split('/');
98
+ if (parts.length !== 2)
99
+ return null;
100
+ const ip = parseIP(parts[0]);
101
+ if (!ip)
102
+ return null;
103
+ const prefixLength = parseInt(parts[1], 10);
104
+ const maxPrefix = ip.isIPv6 ? 128 : 32;
105
+ if (isNaN(prefixLength) || prefixLength < 0 || prefixLength > maxPrefix)
106
+ return null;
107
+ // Calculate network address by masking
108
+ const totalBits = ip.isIPv6 ? 128 : 32;
109
+ const hostBits = totalBits - prefixLength;
110
+ const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
111
+ const network = ip.value & mask;
112
+ return { network, prefixLength, isIPv6: ip.isIPv6 };
113
+ }
114
+ exports.parseCIDR = parseCIDR;
115
+ /**
116
+ * Check if an IP address is within a CIDR range
117
+ */
118
+ function isIpInCidr(ip, cidr) {
119
+ const parsedIp = parseIP(ip);
120
+ const parsedCidr = parseCIDR(cidr);
121
+ if (!parsedIp || !parsedCidr)
122
+ return false;
123
+ // IP version must match CIDR version
124
+ if (parsedIp.isIPv6 !== parsedCidr.isIPv6)
125
+ return false;
126
+ const totalBits = parsedIp.isIPv6 ? 128 : 32;
127
+ const hostBits = totalBits - parsedCidr.prefixLength;
128
+ const mask = hostBits === totalBits ? 0n : ((1n << BigInt(totalBits)) - 1n) ^ ((1n << BigInt(hostBits)) - 1n);
129
+ return (parsedIp.value & mask) === parsedCidr.network;
130
+ }
131
+ exports.isIpInCidr = isIpInCidr;
132
+ /**
133
+ * Check if a user's IP matches any of the allowed CIDRs
134
+ * Returns true if no CIDRs are specified (open assignment) or if IP matches any CIDR
135
+ */
136
+ function checkCidrMatch(userIp, allowedCidrs) {
137
+ // If no CIDR restrictions, assignment is open to all
138
+ if (!allowedCidrs || allowedCidrs.length === 0)
139
+ return true;
140
+ // If CIDRs are specified but user has no IP, deny match
141
+ if (!userIp)
142
+ return false;
143
+ // Check if user IP matches any allowed CIDR
144
+ for (const cidr of allowedCidrs) {
145
+ if (isIpInCidr(userIp, cidr))
146
+ return true;
147
+ }
148
+ return false;
149
+ }
150
+ exports.checkCidrMatch = checkCidrMatch;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Utility exports
3
+ */
4
+ export * from './cidr';
5
+ export * from './keys';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,QAAQ,CAAC;AACvB,cAAc,QAAQ,CAAC"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ /**
18
+ * Utility exports
19
+ */
20
+ __exportStar(require("./cidr"), exports);
21
+ __exportStar(require("./keys"), exports);
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Redis Key Builders
3
+ * Centralized key generation for consistent Redis key naming
4
+ */
5
+ export interface RedisKeyConfig {
6
+ prefix: string;
7
+ }
8
+ /**
9
+ * Creates Redis key builder functions with a given prefix
10
+ */
11
+ export declare function createKeyBuilders(config: RedisKeyConfig): {
12
+ users: () => string;
13
+ userAssignments: (userId: string) => string;
14
+ userRejected: (userId: string) => string;
15
+ assignments: () => string;
16
+ assignmentsRef: () => string;
17
+ assignmentsGeo: () => string;
18
+ assignmentPriority: (id: string) => string;
19
+ assignmentTags: (id: string) => string;
20
+ pendingAssignmentsData: () => string;
21
+ pendingAssignmentsExpiry: () => string;
22
+ assignmentOwner: () => string;
23
+ acceptedAssignments: () => string;
24
+ allTags: () => string;
25
+ tagAssignments: (tag: string) => string;
26
+ tempUserCandidates: (userId: string) => string;
27
+ tempUserExclude: (userId: string) => string;
28
+ tempUserFinal: (userId: string) => string;
29
+ workflowDefinitions: () => string;
30
+ workflowDefinition: (id: string) => string;
31
+ workflowInstances: () => string;
32
+ workflowInstance: (id: string) => string;
33
+ workflowInstancesByUser: (userId: string) => string;
34
+ workflowAssignmentLink: (assignmentId: string) => string;
35
+ completedAssignments: () => string;
36
+ eventStream: () => string;
37
+ eventStreamDeadLetter: () => string;
38
+ deadLetterQueue: () => string;
39
+ processedEvents: () => string;
40
+ eventRetryCount: (eventId: string) => string;
41
+ workflowStepExpiry: (instanceId: string, stepId: string) => string;
42
+ workflowAuditStream: () => string;
43
+ };
44
+ export type KeyBuilders = ReturnType<typeof createKeyBuilders>;
45
+ //# sourceMappingURL=keys.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../../src/utils/keys.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,cAAc;IAC3B,MAAM,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc;;8BAMtB,MAAM;2BACT,MAAM;;;;6BAMJ,MAAM;yBACV,MAAM;;;;;;0BAUL,MAAM;iCAGC,MAAM;8BACT,MAAM;4BACR,MAAM;;6BAIL,MAAM;;2BAER,MAAM;sCACK,MAAM;2CACD,MAAM;;;;;;+BAalB,MAAM;qCACA,MAAM,UAAU,MAAM;;EAG9D;AAED,MAAM,MAAM,WAAW,GAAG,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAAC"}
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ /**
3
+ * Redis Key Builders
4
+ * Centralized key generation for consistent Redis key naming
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.createKeyBuilders = void 0;
8
+ /**
9
+ * Creates Redis key builder functions with a given prefix
10
+ */
11
+ function createKeyBuilders(config) {
12
+ const { prefix } = config;
13
+ return {
14
+ // User keys
15
+ users: () => `${prefix}users`,
16
+ userAssignments: (userId) => `${prefix}user:${userId}:assignments`,
17
+ userRejected: (userId) => `${prefix}user:${userId}:rejected`,
18
+ // Assignment keys
19
+ assignments: () => `${prefix}assignments`,
20
+ assignmentsRef: () => `${prefix}assignments:ref`,
21
+ assignmentsGeo: () => `${prefix}assignments:geo`,
22
+ assignmentPriority: (id) => `${prefix}assignment:${id}:priority`,
23
+ assignmentTags: (id) => `${prefix}assignment:${id}:tags`,
24
+ // Pending/accepted state keys
25
+ pendingAssignmentsData: () => `${prefix}assignments:pending:data`,
26
+ pendingAssignmentsExpiry: () => `${prefix}assignments:pending:expiry`,
27
+ assignmentOwner: () => `${prefix}assignments:pending:owner`,
28
+ acceptedAssignments: () => `${prefix}assignments:accepted`,
29
+ // Tag keys
30
+ allTags: () => `${prefix}all:tags`,
31
+ tagAssignments: (tag) => `${prefix}tag:${tag}:assignments`,
32
+ // Temp keys (for computations)
33
+ tempUserCandidates: (userId) => `${prefix}tmp:user:${userId}:candidates`,
34
+ tempUserExclude: (userId) => `${prefix}tmp:user:${userId}:exclude`,
35
+ tempUserFinal: (userId) => `${prefix}tmp:user:${userId}:final`,
36
+ // Workflow keys
37
+ workflowDefinitions: () => `${prefix}workflows:definitions`,
38
+ workflowDefinition: (id) => `${prefix}workflow:${id}:definition`,
39
+ workflowInstances: () => `${prefix}workflows:instances`,
40
+ workflowInstance: (id) => `${prefix}workflow:instance:${id}`,
41
+ workflowInstancesByUser: (userId) => `${prefix}user:${userId}:workflow:instances`,
42
+ workflowAssignmentLink: (assignmentId) => `${prefix}assignment:${assignmentId}:workflow`,
43
+ // Completed assignments store
44
+ completedAssignments: () => `${prefix}assignments:completed`,
45
+ // Redis Streams keys
46
+ eventStream: () => `${prefix}events:stream`,
47
+ eventStreamDeadLetter: () => `${prefix}events:deadletter`,
48
+ // Workflow reliability keys
49
+ // Reliability and audit keys
50
+ deadLetterQueue: () => `${prefix}workflow:dlq`,
51
+ processedEvents: () => `${prefix}events:processed`,
52
+ eventRetryCount: (eventId) => `${prefix}events:retries:${eventId}`,
53
+ workflowStepExpiry: (instanceId, stepId) => `${prefix}workflow:${instanceId}:step:${stepId}:expiry`,
54
+ workflowAuditStream: () => `${prefix}workflow:audit:stream`,
55
+ };
56
+ }
57
+ exports.createKeyBuilders = createKeyBuilders;