@rawdash/connector-workos 0.0.1 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -136,13 +136,13 @@ WorkOS list endpoints return X-RateLimit-Remaining and X-RateLimit-Reset (Unix s
136
136
 
137
137
  ## Limitations
138
138
 
139
- - Authentication events use the WorkOS Events API filtered to authentication._ event types (sign-in success and failure across SSO, OAuth, password, magic auth, MFA). Other event categories (dsync._, organization.\*) are not synced.
139
+ - Authentication events use the WorkOS Events API filtered to `authentication.*` event types (sign-in success and failure across SSO, OAuth, password, magic auth, MFA). Other event categories (`dsync.*`, `organization.*`) are not synced.
140
140
  - Organizations, connections, and directories are fetched in full on every sync; the WorkOS list endpoints do not expose a server-side updated_at filter, so the scope is cleared and rewritten on full syncs and left untouched on incremental syncs.
141
141
  - Directory-sync user and group rows are out of scope; this connector tracks the directory entities themselves, not their imported memberships.
142
142
 
143
143
  ## Links
144
144
 
145
- - [Rawdash docs](https://rawdash.dev/docs/connectors/)
145
+ - [Rawdash docs](https://rawdash.dev/docs/connectors)
146
146
  - [WorkOS API docs](https://workos.com/docs/reference)
147
147
  - [GitHub](https://github.com/rawdash/rawdash)
148
148
 
package/dist/index.js CHANGED
@@ -81,7 +81,7 @@ var doc = defineConnectorDoc({
81
81
  },
82
82
  rateLimit: "WorkOS list endpoints return X-RateLimit-Remaining and X-RateLimit-Reset (Unix seconds) headers when throttling kicks in; the shared HTTP client falls back to Retry-After on 429.",
83
83
  limitations: [
84
- "Authentication events use the WorkOS Events API filtered to authentication.* event types (sign-in success and failure across SSO, OAuth, password, magic auth, MFA). Other event categories (dsync.*, organization.*) are not synced.",
84
+ "Authentication events use the WorkOS Events API filtered to `authentication.*` event types (sign-in success and failure across SSO, OAuth, password, magic auth, MFA). Other event categories (`dsync.*`, `organization.*`) are not synced.",
85
85
  "Organizations, connections, and directories are fetched in full on every sync; the WorkOS list endpoints do not expose a server-side updated_at filter, so the scope is cleared and rewritten on full syncs and left untouched on incremental syncs.",
86
86
  "Directory-sync user and group rows are out of scope; this connector tracks the directory entities themselves, not their imported memberships."
87
87
  ]
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/workos.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type FetchPageResult,\n type JSONValue,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n apiKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'API key',\n description:\n 'WorkOS API key (server-side, starts with `sk_`). Used as a bearer token on every request. Read-only access is sufficient for sync.',\n placeholder: 'WORKOS_API_KEY',\n secret: true,\n }),\n resources: z\n .array(\n z.enum(['organizations', 'connections', 'directories', 'auth_events']),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which WorkOS resources to sync. Omit to sync all of them.',\n }),\n authEventsLookbackDays: z\n .number()\n .int()\n .positive()\n .max(90)\n .optional()\n .meta({\n label: 'Auth events lookback (days)',\n description:\n 'On a full sync (and when no incremental cursor is available), how many days of authentication events to fetch. Defaults to 30. Caps at 90.',\n placeholder: '30',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'WorkOS',\n category: 'security',\n brandColor: '#6363F1',\n tagline:\n 'Sync organizations, SSO connections, directory-sync directories, and authentication events from a WorkOS workspace for B2B SaaS onboarding and SSO-activity dashboards.',\n vendor: {\n name: 'WorkOS',\n domain: 'workos.com',\n apiDocs: 'https://workos.com/docs/reference',\n website: 'https://workos.com',\n },\n auth: {\n summary:\n 'A WorkOS API key (server-side, starts with `sk_`) is required. It is sent as a bearer token on every request and never leaves the workspace.',\n setup: [\n 'Sign in to the WorkOS Dashboard and switch to the environment (Sandbox or Production) you want to sync.',\n 'Open API Keys in the left navigation.',\n 'Create a new secret key (or copy an existing one). WorkOS only shows the secret once on creation.',\n 'Store it as a rawdash secret and reference it from the connector config as `apiKey: secret(\"WORKOS_API_KEY\")`.',\n ],\n },\n rateLimit:\n 'WorkOS list endpoints return X-RateLimit-Remaining and X-RateLimit-Reset (Unix seconds) headers when throttling kicks in; the shared HTTP client falls back to Retry-After on 429.',\n limitations: [\n 'Authentication events use the WorkOS Events API filtered to authentication.* event types (sign-in success and failure across SSO, OAuth, password, magic auth, MFA). Other event categories (dsync.*, organization.*) are not synced.',\n 'Organizations, connections, and directories are fetched in full on every sync; the WorkOS list endpoints do not expose a server-side updated_at filter, so the scope is cleared and rewritten on full syncs and left untouched on incremental syncs.',\n 'Directory-sync user and group rows are out of scope; this connector tracks the directory entities themselves, not their imported memberships.',\n ],\n});\n\nexport type WorkOSResource =\n | 'organizations'\n | 'connections'\n | 'directories'\n | 'auth_events';\n\nexport interface WorkOSSettings {\n resources?: readonly WorkOSResource[];\n authEventsLookbackDays?: number;\n}\n\nconst workosCredentials = {\n apiKey: {\n description: 'WorkOS API key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype WorkOSCredentials = typeof workosCredentials;\n\nconst PHASE_ORDER = [\n 'organizations',\n 'connections',\n 'directories',\n 'auth_events',\n] as const;\n\ntype WorkOSPhase = (typeof PHASE_ORDER)[number];\n\ntype WorkOSSyncCursor = ChunkedSyncCursor<WorkOSPhase, string>;\n\nconst isWorkOSSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst ORGANIZATION_ENTITY = 'workos_organization';\nconst CONNECTION_ENTITY = 'workos_connection';\nconst DIRECTORY_ENTITY = 'workos_directory';\nconst AUTH_EVENT = 'workos_auth_event';\n\nconst PAGE_SIZE = 100;\nconst DEFAULT_AUTH_LOOKBACK_DAYS = 30;\nconst BASE_URL = 'https://api.workos.com';\n\nconst AUTH_EVENT_TYPES = [\n 'authentication.email_verification_succeeded',\n 'authentication.magic_auth_succeeded',\n 'authentication.magic_auth_failed',\n 'authentication.mfa_succeeded',\n 'authentication.mfa_failed',\n 'authentication.oauth_succeeded',\n 'authentication.oauth_failed',\n 'authentication.password_succeeded',\n 'authentication.password_failed',\n 'authentication.sso_succeeded',\n 'authentication.sso_failed',\n] as const;\n\ntype AuthEventType = (typeof AUTH_EVENT_TYPES)[number];\n\nconst idString = z.string().min(1);\n\nconst listMetadataSchema = z.object({\n before: z.string().nullish(),\n after: z.string().nullish(),\n});\n\nconst organizationDomainSchema = z.object({\n domain: z.string(),\n state: z.string().nullish(),\n});\n\nconst organizationSchema = z.object({\n id: idString,\n name: z.string(),\n domains: z.array(organizationDomainSchema).nullish(),\n allow_profiles_outside_organization: z.boolean().nullish(),\n created_at: z.string(),\n updated_at: z.string().nullish(),\n});\n\nconst organizationsResponseSchema = z.object({\n data: z.array(organizationSchema),\n list_metadata: listMetadataSchema,\n});\n\nconst connectionSchema = z.object({\n id: idString,\n name: z.string(),\n organization_id: z.string().nullish(),\n connection_type: z.string(),\n state: z.string().nullish(),\n status: z.string().nullish(),\n created_at: z.string(),\n updated_at: z.string().nullish(),\n});\n\nconst connectionsResponseSchema = z.object({\n data: z.array(connectionSchema),\n list_metadata: listMetadataSchema,\n});\n\nconst directorySchema = z.object({\n id: idString,\n name: z.string(),\n organization_id: z.string().nullish(),\n type: z.string(),\n state: z.string().nullish(),\n created_at: z.string(),\n updated_at: z.string().nullish(),\n});\n\nconst directoriesResponseSchema = z.object({\n data: z.array(directorySchema),\n list_metadata: listMetadataSchema,\n});\n\nconst eventSchema = z.object({\n id: idString,\n event: z.string(),\n created_at: z.string(),\n data: z\n .object({\n organization_id: z.string().nullish(),\n user_id: z.string().nullish(),\n email: z.string().nullish(),\n ip_address: z.string().nullish(),\n connection_id: z.string().nullish(),\n connection_type: z.string().nullish(),\n })\n .passthrough()\n .nullish(),\n});\n\nconst eventsResponseSchema = z.object({\n data: z.array(eventSchema),\n list_metadata: listMetadataSchema,\n});\n\nexport const workosResources = defineResources({\n [ORGANIZATION_ENTITY]: {\n shape: 'entity',\n filterable: [],\n description:\n 'WorkOS organizations (tenants) with their display name, domains, and creation timestamp.',\n endpoint: 'GET /organizations',\n fields: [\n { name: 'name', description: 'Organization display name.' },\n {\n name: 'domains',\n description:\n 'Comma-separated list of domains attached to the organization.',\n },\n {\n name: 'createdAt',\n description: 'When the organization was created (Unix ms).',\n },\n ],\n responses: { organizations: organizationsResponseSchema },\n },\n [CONNECTION_ENTITY]: {\n shape: 'entity',\n filterable: [\n {\n field: 'state',\n ops: ['eq'],\n values: ['active', 'inactive', 'draft', 'linked', 'unlinked'],\n },\n { field: 'connectionType', ops: ['eq'] },\n ],\n description:\n 'WorkOS SSO connections (one per identity provider per organization) with their type, state, and parent organization.',\n endpoint: 'GET /connections',\n fields: [\n {\n name: 'connectionType',\n description: 'Connection type (e.g. OktaSAML, AzureSAML, GoogleOAuth).',\n },\n {\n name: 'organizationId',\n description: 'WorkOS organization that owns the connection.',\n },\n {\n name: 'state',\n description:\n 'Lifecycle state (active, inactive, draft, linked, unlinked).',\n },\n { name: 'name', description: 'Connection display name.' },\n {\n name: 'createdAt',\n description: 'When the connection was created (Unix ms).',\n },\n ],\n responses: { connections: connectionsResponseSchema },\n },\n [DIRECTORY_ENTITY]: {\n shape: 'entity',\n filterable: [\n {\n field: 'state',\n ops: ['eq'],\n values: ['active', 'inactive', 'validating', 'linked', 'unlinked'],\n },\n { field: 'directoryType', ops: ['eq'] },\n ],\n description:\n 'WorkOS directory-sync directories (SCIM/HRIS feeds) with their type, state, and parent organization.',\n endpoint: 'GET /directories',\n fields: [\n {\n name: 'directoryType',\n description:\n 'Directory provider type (e.g. okta scim v2.0, azure scim v2.0, bamboohr).',\n },\n {\n name: 'organizationId',\n description: 'WorkOS organization that owns the directory.',\n },\n {\n name: 'state',\n description:\n 'Lifecycle state (active, inactive, validating, linked, unlinked).',\n },\n { name: 'name', description: 'Directory display name.' },\n {\n name: 'createdAt',\n description: 'When the directory was created (Unix ms).',\n },\n ],\n responses: { directories: directoriesResponseSchema },\n },\n [AUTH_EVENT]: {\n shape: 'event',\n filterable: [\n { field: 'eventType', ops: ['eq'], values: [...AUTH_EVENT_TYPES] },\n ],\n description:\n 'Authentication events from the WorkOS Events API (SSO, OAuth, password, magic auth, and MFA sign-in successes and failures).',\n endpoint: 'GET /events',\n notes:\n 'Filtered to the authentication.* event family. Incremental syncs pass `range_start` so only events newer than the watermark are returned.',\n fields: [\n {\n name: 'eventType',\n description: 'WorkOS event name (authentication.sso_succeeded, etc).',\n },\n {\n name: 'outcome',\n description: '\"succeeded\" or \"failed\" derived from the event suffix.',\n },\n {\n name: 'method',\n description:\n 'Authentication method (sso, oauth, password, magic_auth, mfa, email_verification).',\n },\n {\n name: 'organizationId',\n description: 'WorkOS organization the event belongs to (may be null).',\n },\n {\n name: 'userId',\n description: 'WorkOS user id involved in the event (may be null).',\n },\n {\n name: 'connectionId',\n description: 'WorkOS connection id used for the event (may be null).',\n },\n {\n name: 'connectionType',\n description:\n 'Connection type used for the event (may be null for non-SSO methods).',\n },\n {\n name: 'ipAddress',\n description: 'Client IP captured by WorkOS (may be null).',\n },\n ],\n responses: { auth_events: eventsResponseSchema },\n },\n});\n\nexport const id = 'workos';\n\ntype OrganizationsResponse = z.infer<typeof organizationsResponseSchema>;\ntype ConnectionsResponse = z.infer<typeof connectionsResponseSchema>;\ntype DirectoriesResponse = z.infer<typeof directoriesResponseSchema>;\ntype EventsResponse = z.infer<typeof eventsResponseSchema>;\n\ntype WorkOSOrganization = z.infer<typeof organizationSchema>;\ntype WorkOSConnection = z.infer<typeof connectionSchema>;\ntype WorkOSDirectory = z.infer<typeof directorySchema>;\ntype WorkOSEvent = z.infer<typeof eventSchema>;\n\ninterface FetchedPage<T> {\n items: T[];\n next: string | null;\n}\n\nfunction isoToMs(value: string | null | undefined): number | null {\n if (!value) {\n return null;\n }\n return parseEpoch(value, 'iso');\n}\n\nfunction isoToMsOrZero(value: string | null | undefined): number {\n return isoToMs(value) ?? 0;\n}\n\nfunction summarizeDomains(\n domains: WorkOSOrganization['domains'],\n): string | null {\n if (!domains || domains.length === 0) {\n return null;\n }\n return domains.map((d) => d.domain).join(', ');\n}\n\nfunction deriveOutcome(eventType: string): 'succeeded' | 'failed' | null {\n if (eventType.endsWith('_succeeded')) {\n return 'succeeded';\n }\n if (eventType.endsWith('_failed')) {\n return 'failed';\n }\n return null;\n}\n\nfunction deriveMethod(eventType: string): string | null {\n const m = /^authentication\\.(.+?)_(?:succeeded|failed)$/.exec(eventType);\n return m ? m[1]! : null;\n}\n\nfunction isAuthEventType(value: string): value is AuthEventType {\n return (AUTH_EVENT_TYPES as readonly string[]).includes(value);\n}\n\nfunction lookbackStartIso(days: number): string {\n const ts = Date.now() - days * 24 * 60 * 60 * 1000;\n return new Date(ts).toISOString();\n}\n\nexport class WorkOSConnector extends BaseConnector<\n WorkOSSettings,\n WorkOSCredentials\n> {\n static readonly id = id;\n\n static readonly resources = workosResources;\n\n static readonly schemas = schemasFromResources(workosResources);\n\n static create(input: unknown, ctx?: ConnectorContext): WorkOSConnector {\n const parsed = configFields.parse(input);\n return new WorkOSConnector(\n {\n resources: parsed.resources,\n authEventsLookbackDays: parsed.authEventsLookbackDays,\n },\n { apiKey: parsed.apiKey },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = workosCredentials;\n\n private buildHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.creds.apiKey}`,\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('workos'),\n };\n }\n\n private apiGet<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n });\n }\n\n private buildListUrl(\n path: string,\n after: string | null,\n extra: Record<string, string> = {},\n ): string {\n const url = new URL(`${BASE_URL}${path}`);\n url.searchParams.set('limit', String(PAGE_SIZE));\n url.searchParams.set('order', 'asc');\n if (after) {\n url.searchParams.set('after', after);\n }\n for (const [k, v] of Object.entries(extra)) {\n url.searchParams.append(k, v);\n }\n return url.toString();\n }\n\n private buildEventsUrl(after: string | null, options: SyncOptions): string {\n const url = new URL(`${BASE_URL}/events`);\n url.searchParams.set('limit', String(PAGE_SIZE));\n for (const t of AUTH_EVENT_TYPES) {\n url.searchParams.append('events', t);\n }\n if (after) {\n url.searchParams.set('after', after);\n } else {\n const rangeStart = options.since ?? this.defaultEventsRangeStart();\n url.searchParams.set('range_start', rangeStart);\n }\n return url.toString();\n }\n\n private defaultEventsRangeStart(): string {\n const days =\n this.settings.authEventsLookbackDays ?? DEFAULT_AUTH_LOOKBACK_DAYS;\n return lookbackStartIso(days);\n }\n\n private async fetchOrganizationsPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchedPage<WorkOSOrganization>> {\n const url = this.buildListUrl('/organizations', page);\n const res = await this.apiGet<OrganizationsResponse>(\n url,\n 'organizations',\n signal,\n );\n const next = res.body.list_metadata.after ?? null;\n return { items: res.body.data, next };\n }\n\n private async fetchConnectionsPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchedPage<WorkOSConnection>> {\n const url = this.buildListUrl('/connections', page);\n const res = await this.apiGet<ConnectionsResponse>(\n url,\n 'connections',\n signal,\n );\n const next = res.body.list_metadata.after ?? null;\n return { items: res.body.data, next };\n }\n\n private async fetchDirectoriesPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchedPage<WorkOSDirectory>> {\n const url = this.buildListUrl('/directories', page);\n const res = await this.apiGet<DirectoriesResponse>(\n url,\n 'directories',\n signal,\n );\n const next = res.body.list_metadata.after ?? null;\n return { items: res.body.data, next };\n }\n\n private async fetchEventsPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<FetchedPage<WorkOSEvent>> {\n const url = this.buildEventsUrl(page, options);\n const res = await this.apiGet<EventsResponse>(url, 'auth_events', signal);\n const next = res.body.list_metadata.after ?? null;\n return { items: res.body.data, next };\n }\n\n private async fetchPhasePage(\n phase: WorkOSPhase,\n page: string | null,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<FetchPageResult<string>> {\n switch (phase) {\n case 'organizations':\n return this.fetchOrganizationsPage(page, signal);\n case 'connections':\n return this.fetchConnectionsPage(page, signal);\n case 'directories':\n return this.fetchDirectoriesPage(page, signal);\n case 'auth_events':\n return this.fetchEventsPage(page, options, signal);\n }\n }\n\n private async writeOrganizations(\n storage: StorageHandle,\n items: WorkOSOrganization[],\n ): Promise<void> {\n for (const org of items) {\n await storage.entity({\n type: ORGANIZATION_ENTITY,\n id: org.id,\n attributes: {\n name: org.name,\n domains: summarizeDomains(org.domains),\n createdAt: isoToMs(org.created_at),\n },\n updated_at: isoToMsOrZero(org.updated_at ?? org.created_at),\n });\n }\n }\n\n private async writeConnections(\n storage: StorageHandle,\n items: WorkOSConnection[],\n ): Promise<void> {\n for (const c of items) {\n await storage.entity({\n type: CONNECTION_ENTITY,\n id: c.id,\n attributes: {\n name: c.name,\n connectionType: c.connection_type,\n organizationId: c.organization_id ?? null,\n state: c.state ?? c.status ?? null,\n createdAt: isoToMs(c.created_at),\n },\n updated_at: isoToMsOrZero(c.updated_at ?? c.created_at),\n });\n }\n }\n\n private async writeDirectories(\n storage: StorageHandle,\n items: WorkOSDirectory[],\n ): Promise<void> {\n for (const d of items) {\n await storage.entity({\n type: DIRECTORY_ENTITY,\n id: d.id,\n attributes: {\n name: d.name,\n directoryType: d.type,\n organizationId: d.organization_id ?? null,\n state: d.state ?? null,\n createdAt: isoToMs(d.created_at),\n },\n updated_at: isoToMsOrZero(d.updated_at ?? d.created_at),\n });\n }\n }\n\n private async writeAuthEvents(\n storage: StorageHandle,\n items: WorkOSEvent[],\n sinceMs: number | null,\n ): Promise<void> {\n for (const ev of items) {\n if (!isAuthEventType(ev.event)) {\n continue;\n }\n const ts = isoToMs(ev.created_at);\n if (ts === null) {\n continue;\n }\n if (sinceMs !== null && ts <= sinceMs) {\n continue;\n }\n const data = ev.data ?? {};\n const attributes: Record<string, JSONValue> = {\n eventType: ev.event,\n outcome: deriveOutcome(ev.event),\n method: deriveMethod(ev.event),\n organizationId: data.organization_id ?? null,\n userId: data.user_id ?? null,\n connectionId: data.connection_id ?? null,\n connectionType: data.connection_type ?? null,\n ipAddress: data.ip_address ?? null,\n eventId: ev.id,\n };\n await storage.event({\n name: AUTH_EVENT,\n start_ts: ts,\n end_ts: null,\n attributes,\n });\n }\n }\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: WorkOSPhase,\n isFull: boolean,\n ): Promise<void> {\n if (!isFull) {\n return;\n }\n switch (phase) {\n case 'organizations':\n await storage.entities([], { types: [ORGANIZATION_ENTITY] });\n return;\n case 'connections':\n await storage.entities([], { types: [CONNECTION_ENTITY] });\n return;\n case 'directories':\n await storage.entities([], { types: [DIRECTORY_ENTITY] });\n return;\n case 'auth_events':\n await storage.events([], { names: [AUTH_EVENT] });\n return;\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: WorkOSPhase,\n items: unknown[],\n sinceMs: number | null,\n ): Promise<void> {\n switch (phase) {\n case 'organizations':\n return this.writeOrganizations(storage, items as WorkOSOrganization[]);\n case 'connections':\n return this.writeConnections(storage, items as WorkOSConnection[]);\n case 'directories':\n return this.writeDirectories(storage, items as WorkOSDirectory[]);\n case 'auth_events':\n return this.writeAuthEvents(storage, items as WorkOSEvent[], sinceMs);\n }\n }\n\n private resolveCursor(cursor: unknown): WorkOSSyncCursor | undefined {\n return isWorkOSSyncCursor(cursor) ? cursor : undefined;\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const sinceMs = options.since ? Date.parse(options.since) : null;\n const sinceMsOrNull =\n sinceMs !== null && Number.isFinite(sinceMs) ? sinceMs : null;\n\n const phases = selectActivePhases<WorkOSResource, WorkOSPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<WorkOSPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) =>\n this.fetchPhasePage(phase, page, options, sig),\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n await this.writePhase(storage, phase, items, sinceMsOrNull);\n },\n });\n }\n}\n","import { WorkOSConnector } from './workos';\n\nexport {\n WorkOSConnector,\n workosResources as resources,\n configFields,\n doc,\n id,\n} from './workos';\nexport type { WorkOSResource, WorkOSSettings } from './workos';\nexport default WorkOSConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AKJO,SAAS,WACd,OACA,MACe;AACf,MAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,WAAO;EACT;AACA,MAAI,SAAS,OAA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AO,MAAM;AAAA,QACzD;AACA,cAAM,KAAK,WAAW,SAAS,OAAO,OAAO,aAAa;AAAA,MAC5D;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC7uBA,IAAO,gBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/workos.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type FetchPageResult,\n type JSONValue,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n apiKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'API key',\n description:\n 'WorkOS API key (server-side, starts with `sk_`). Used as a bearer token on every request. Read-only access is sufficient for sync.',\n placeholder: 'WORKOS_API_KEY',\n secret: true,\n }),\n resources: z\n .array(\n z.enum(['organizations', 'connections', 'directories', 'auth_events']),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which WorkOS resources to sync. Omit to sync all of them.',\n }),\n authEventsLookbackDays: z\n .number()\n .int()\n .positive()\n .max(90)\n .optional()\n .meta({\n label: 'Auth events lookback (days)',\n description:\n 'On a full sync (and when no incremental cursor is available), how many days of authentication events to fetch. Defaults to 30. Caps at 90.',\n placeholder: '30',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'WorkOS',\n category: 'security',\n brandColor: '#6363F1',\n tagline:\n 'Sync organizations, SSO connections, directory-sync directories, and authentication events from a WorkOS workspace for B2B SaaS onboarding and SSO-activity dashboards.',\n vendor: {\n name: 'WorkOS',\n domain: 'workos.com',\n apiDocs: 'https://workos.com/docs/reference',\n website: 'https://workos.com',\n },\n auth: {\n summary:\n 'A WorkOS API key (server-side, starts with `sk_`) is required. It is sent as a bearer token on every request and never leaves the workspace.',\n setup: [\n 'Sign in to the WorkOS Dashboard and switch to the environment (Sandbox or Production) you want to sync.',\n 'Open API Keys in the left navigation.',\n 'Create a new secret key (or copy an existing one). WorkOS only shows the secret once on creation.',\n 'Store it as a rawdash secret and reference it from the connector config as `apiKey: secret(\"WORKOS_API_KEY\")`.',\n ],\n },\n rateLimit:\n 'WorkOS list endpoints return X-RateLimit-Remaining and X-RateLimit-Reset (Unix seconds) headers when throttling kicks in; the shared HTTP client falls back to Retry-After on 429.',\n limitations: [\n 'Authentication events use the WorkOS Events API filtered to `authentication.*` event types (sign-in success and failure across SSO, OAuth, password, magic auth, MFA). Other event categories (`dsync.*`, `organization.*`) are not synced.',\n 'Organizations, connections, and directories are fetched in full on every sync; the WorkOS list endpoints do not expose a server-side updated_at filter, so the scope is cleared and rewritten on full syncs and left untouched on incremental syncs.',\n 'Directory-sync user and group rows are out of scope; this connector tracks the directory entities themselves, not their imported memberships.',\n ],\n});\n\nexport type WorkOSResource =\n | 'organizations'\n | 'connections'\n | 'directories'\n | 'auth_events';\n\nexport interface WorkOSSettings {\n resources?: readonly WorkOSResource[];\n authEventsLookbackDays?: number;\n}\n\nconst workosCredentials = {\n apiKey: {\n description: 'WorkOS API key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype WorkOSCredentials = typeof workosCredentials;\n\nconst PHASE_ORDER = [\n 'organizations',\n 'connections',\n 'directories',\n 'auth_events',\n] as const;\n\ntype WorkOSPhase = (typeof PHASE_ORDER)[number];\n\ntype WorkOSSyncCursor = ChunkedSyncCursor<WorkOSPhase, string>;\n\nconst isWorkOSSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst ORGANIZATION_ENTITY = 'workos_organization';\nconst CONNECTION_ENTITY = 'workos_connection';\nconst DIRECTORY_ENTITY = 'workos_directory';\nconst AUTH_EVENT = 'workos_auth_event';\n\nconst PAGE_SIZE = 100;\nconst DEFAULT_AUTH_LOOKBACK_DAYS = 30;\nconst BASE_URL = 'https://api.workos.com';\n\nconst AUTH_EVENT_TYPES = [\n 'authentication.email_verification_succeeded',\n 'authentication.magic_auth_succeeded',\n 'authentication.magic_auth_failed',\n 'authentication.mfa_succeeded',\n 'authentication.mfa_failed',\n 'authentication.oauth_succeeded',\n 'authentication.oauth_failed',\n 'authentication.password_succeeded',\n 'authentication.password_failed',\n 'authentication.sso_succeeded',\n 'authentication.sso_failed',\n] as const;\n\ntype AuthEventType = (typeof AUTH_EVENT_TYPES)[number];\n\nconst idString = z.string().min(1);\n\nconst listMetadataSchema = z.object({\n before: z.string().nullish(),\n after: z.string().nullish(),\n});\n\nconst organizationDomainSchema = z.object({\n domain: z.string(),\n state: z.string().nullish(),\n});\n\nconst organizationSchema = z.object({\n id: idString,\n name: z.string(),\n domains: z.array(organizationDomainSchema).nullish(),\n allow_profiles_outside_organization: z.boolean().nullish(),\n created_at: z.string(),\n updated_at: z.string().nullish(),\n});\n\nconst organizationsResponseSchema = z.object({\n data: z.array(organizationSchema),\n list_metadata: listMetadataSchema,\n});\n\nconst connectionSchema = z.object({\n id: idString,\n name: z.string(),\n organization_id: z.string().nullish(),\n connection_type: z.string(),\n state: z.string().nullish(),\n status: z.string().nullish(),\n created_at: z.string(),\n updated_at: z.string().nullish(),\n});\n\nconst connectionsResponseSchema = z.object({\n data: z.array(connectionSchema),\n list_metadata: listMetadataSchema,\n});\n\nconst directorySchema = z.object({\n id: idString,\n name: z.string(),\n organization_id: z.string().nullish(),\n type: z.string(),\n state: z.string().nullish(),\n created_at: z.string(),\n updated_at: z.string().nullish(),\n});\n\nconst directoriesResponseSchema = z.object({\n data: z.array(directorySchema),\n list_metadata: listMetadataSchema,\n});\n\nconst eventSchema = z.object({\n id: idString,\n event: z.string(),\n created_at: z.string(),\n data: z\n .object({\n organization_id: z.string().nullish(),\n user_id: z.string().nullish(),\n email: z.string().nullish(),\n ip_address: z.string().nullish(),\n connection_id: z.string().nullish(),\n connection_type: z.string().nullish(),\n })\n .passthrough()\n .nullish(),\n});\n\nconst eventsResponseSchema = z.object({\n data: z.array(eventSchema),\n list_metadata: listMetadataSchema,\n});\n\nexport const workosResources = defineResources({\n [ORGANIZATION_ENTITY]: {\n shape: 'entity',\n filterable: [],\n description:\n 'WorkOS organizations (tenants) with their display name, domains, and creation timestamp.',\n endpoint: 'GET /organizations',\n fields: [\n { name: 'name', description: 'Organization display name.' },\n {\n name: 'domains',\n description:\n 'Comma-separated list of domains attached to the organization.',\n },\n {\n name: 'createdAt',\n description: 'When the organization was created (Unix ms).',\n },\n ],\n responses: { organizations: organizationsResponseSchema },\n },\n [CONNECTION_ENTITY]: {\n shape: 'entity',\n filterable: [\n {\n field: 'state',\n ops: ['eq'],\n values: ['active', 'inactive', 'draft', 'linked', 'unlinked'],\n },\n { field: 'connectionType', ops: ['eq'] },\n ],\n description:\n 'WorkOS SSO connections (one per identity provider per organization) with their type, state, and parent organization.',\n endpoint: 'GET /connections',\n fields: [\n {\n name: 'connectionType',\n description: 'Connection type (e.g. OktaSAML, AzureSAML, GoogleOAuth).',\n },\n {\n name: 'organizationId',\n description: 'WorkOS organization that owns the connection.',\n },\n {\n name: 'state',\n description:\n 'Lifecycle state (active, inactive, draft, linked, unlinked).',\n },\n { name: 'name', description: 'Connection display name.' },\n {\n name: 'createdAt',\n description: 'When the connection was created (Unix ms).',\n },\n ],\n responses: { connections: connectionsResponseSchema },\n },\n [DIRECTORY_ENTITY]: {\n shape: 'entity',\n filterable: [\n {\n field: 'state',\n ops: ['eq'],\n values: ['active', 'inactive', 'validating', 'linked', 'unlinked'],\n },\n { field: 'directoryType', ops: ['eq'] },\n ],\n description:\n 'WorkOS directory-sync directories (SCIM/HRIS feeds) with their type, state, and parent organization.',\n endpoint: 'GET /directories',\n fields: [\n {\n name: 'directoryType',\n description:\n 'Directory provider type (e.g. okta scim v2.0, azure scim v2.0, bamboohr).',\n },\n {\n name: 'organizationId',\n description: 'WorkOS organization that owns the directory.',\n },\n {\n name: 'state',\n description:\n 'Lifecycle state (active, inactive, validating, linked, unlinked).',\n },\n { name: 'name', description: 'Directory display name.' },\n {\n name: 'createdAt',\n description: 'When the directory was created (Unix ms).',\n },\n ],\n responses: { directories: directoriesResponseSchema },\n },\n [AUTH_EVENT]: {\n shape: 'event',\n filterable: [\n { field: 'eventType', ops: ['eq'], values: [...AUTH_EVENT_TYPES] },\n ],\n description:\n 'Authentication events from the WorkOS Events API (SSO, OAuth, password, magic auth, and MFA sign-in successes and failures).',\n endpoint: 'GET /events',\n notes:\n 'Filtered to the authentication.* event family. Incremental syncs pass `range_start` so only events newer than the watermark are returned.',\n fields: [\n {\n name: 'eventType',\n description: 'WorkOS event name (authentication.sso_succeeded, etc).',\n },\n {\n name: 'outcome',\n description: '\"succeeded\" or \"failed\" derived from the event suffix.',\n },\n {\n name: 'method',\n description:\n 'Authentication method (sso, oauth, password, magic_auth, mfa, email_verification).',\n },\n {\n name: 'organizationId',\n description: 'WorkOS organization the event belongs to (may be null).',\n },\n {\n name: 'userId',\n description: 'WorkOS user id involved in the event (may be null).',\n },\n {\n name: 'connectionId',\n description: 'WorkOS connection id used for the event (may be null).',\n },\n {\n name: 'connectionType',\n description:\n 'Connection type used for the event (may be null for non-SSO methods).',\n },\n {\n name: 'ipAddress',\n description: 'Client IP captured by WorkOS (may be null).',\n },\n ],\n responses: { auth_events: eventsResponseSchema },\n },\n});\n\nexport const id = 'workos';\n\ntype OrganizationsResponse = z.infer<typeof organizationsResponseSchema>;\ntype ConnectionsResponse = z.infer<typeof connectionsResponseSchema>;\ntype DirectoriesResponse = z.infer<typeof directoriesResponseSchema>;\ntype EventsResponse = z.infer<typeof eventsResponseSchema>;\n\ntype WorkOSOrganization = z.infer<typeof organizationSchema>;\ntype WorkOSConnection = z.infer<typeof connectionSchema>;\ntype WorkOSDirectory = z.infer<typeof directorySchema>;\ntype WorkOSEvent = z.infer<typeof eventSchema>;\n\ninterface FetchedPage<T> {\n items: T[];\n next: string | null;\n}\n\nfunction isoToMs(value: string | null | undefined): number | null {\n if (!value) {\n return null;\n }\n return parseEpoch(value, 'iso');\n}\n\nfunction isoToMsOrZero(value: string | null | undefined): number {\n return isoToMs(value) ?? 0;\n}\n\nfunction summarizeDomains(\n domains: WorkOSOrganization['domains'],\n): string | null {\n if (!domains || domains.length === 0) {\n return null;\n }\n return domains.map((d) => d.domain).join(', ');\n}\n\nfunction deriveOutcome(eventType: string): 'succeeded' | 'failed' | null {\n if (eventType.endsWith('_succeeded')) {\n return 'succeeded';\n }\n if (eventType.endsWith('_failed')) {\n return 'failed';\n }\n return null;\n}\n\nfunction deriveMethod(eventType: string): string | null {\n const m = /^authentication\\.(.+?)_(?:succeeded|failed)$/.exec(eventType);\n return m ? m[1]! : null;\n}\n\nfunction isAuthEventType(value: string): value is AuthEventType {\n return (AUTH_EVENT_TYPES as readonly string[]).includes(value);\n}\n\nfunction lookbackStartIso(days: number): string {\n const ts = Date.now() - days * 24 * 60 * 60 * 1000;\n return new Date(ts).toISOString();\n}\n\nexport class WorkOSConnector extends BaseConnector<\n WorkOSSettings,\n WorkOSCredentials\n> {\n static readonly id = id;\n\n static readonly resources = workosResources;\n\n static readonly schemas = schemasFromResources(workosResources);\n\n static create(input: unknown, ctx?: ConnectorContext): WorkOSConnector {\n const parsed = configFields.parse(input);\n return new WorkOSConnector(\n {\n resources: parsed.resources,\n authEventsLookbackDays: parsed.authEventsLookbackDays,\n },\n { apiKey: parsed.apiKey },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = workosCredentials;\n\n private buildHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.creds.apiKey}`,\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('workos'),\n };\n }\n\n private apiGet<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n });\n }\n\n private buildListUrl(\n path: string,\n after: string | null,\n extra: Record<string, string> = {},\n ): string {\n const url = new URL(`${BASE_URL}${path}`);\n url.searchParams.set('limit', String(PAGE_SIZE));\n url.searchParams.set('order', 'asc');\n if (after) {\n url.searchParams.set('after', after);\n }\n for (const [k, v] of Object.entries(extra)) {\n url.searchParams.append(k, v);\n }\n return url.toString();\n }\n\n private buildEventsUrl(after: string | null, options: SyncOptions): string {\n const url = new URL(`${BASE_URL}/events`);\n url.searchParams.set('limit', String(PAGE_SIZE));\n for (const t of AUTH_EVENT_TYPES) {\n url.searchParams.append('events', t);\n }\n if (after) {\n url.searchParams.set('after', after);\n } else {\n const rangeStart = options.since ?? this.defaultEventsRangeStart();\n url.searchParams.set('range_start', rangeStart);\n }\n return url.toString();\n }\n\n private defaultEventsRangeStart(): string {\n const days =\n this.settings.authEventsLookbackDays ?? DEFAULT_AUTH_LOOKBACK_DAYS;\n return lookbackStartIso(days);\n }\n\n private async fetchOrganizationsPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchedPage<WorkOSOrganization>> {\n const url = this.buildListUrl('/organizations', page);\n const res = await this.apiGet<OrganizationsResponse>(\n url,\n 'organizations',\n signal,\n );\n const next = res.body.list_metadata.after ?? null;\n return { items: res.body.data, next };\n }\n\n private async fetchConnectionsPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchedPage<WorkOSConnection>> {\n const url = this.buildListUrl('/connections', page);\n const res = await this.apiGet<ConnectionsResponse>(\n url,\n 'connections',\n signal,\n );\n const next = res.body.list_metadata.after ?? null;\n return { items: res.body.data, next };\n }\n\n private async fetchDirectoriesPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchedPage<WorkOSDirectory>> {\n const url = this.buildListUrl('/directories', page);\n const res = await this.apiGet<DirectoriesResponse>(\n url,\n 'directories',\n signal,\n );\n const next = res.body.list_metadata.after ?? null;\n return { items: res.body.data, next };\n }\n\n private async fetchEventsPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<FetchedPage<WorkOSEvent>> {\n const url = this.buildEventsUrl(page, options);\n const res = await this.apiGet<EventsResponse>(url, 'auth_events', signal);\n const next = res.body.list_metadata.after ?? null;\n return { items: res.body.data, next };\n }\n\n private async fetchPhasePage(\n phase: WorkOSPhase,\n page: string | null,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<FetchPageResult<string>> {\n switch (phase) {\n case 'organizations':\n return this.fetchOrganizationsPage(page, signal);\n case 'connections':\n return this.fetchConnectionsPage(page, signal);\n case 'directories':\n return this.fetchDirectoriesPage(page, signal);\n case 'auth_events':\n return this.fetchEventsPage(page, options, signal);\n }\n }\n\n private async writeOrganizations(\n storage: StorageHandle,\n items: WorkOSOrganization[],\n ): Promise<void> {\n for (const org of items) {\n await storage.entity({\n type: ORGANIZATION_ENTITY,\n id: org.id,\n attributes: {\n name: org.name,\n domains: summarizeDomains(org.domains),\n createdAt: isoToMs(org.created_at),\n },\n updated_at: isoToMsOrZero(org.updated_at ?? org.created_at),\n });\n }\n }\n\n private async writeConnections(\n storage: StorageHandle,\n items: WorkOSConnection[],\n ): Promise<void> {\n for (const c of items) {\n await storage.entity({\n type: CONNECTION_ENTITY,\n id: c.id,\n attributes: {\n name: c.name,\n connectionType: c.connection_type,\n organizationId: c.organization_id ?? null,\n state: c.state ?? c.status ?? null,\n createdAt: isoToMs(c.created_at),\n },\n updated_at: isoToMsOrZero(c.updated_at ?? c.created_at),\n });\n }\n }\n\n private async writeDirectories(\n storage: StorageHandle,\n items: WorkOSDirectory[],\n ): Promise<void> {\n for (const d of items) {\n await storage.entity({\n type: DIRECTORY_ENTITY,\n id: d.id,\n attributes: {\n name: d.name,\n directoryType: d.type,\n organizationId: d.organization_id ?? null,\n state: d.state ?? null,\n createdAt: isoToMs(d.created_at),\n },\n updated_at: isoToMsOrZero(d.updated_at ?? d.created_at),\n });\n }\n }\n\n private async writeAuthEvents(\n storage: StorageHandle,\n items: WorkOSEvent[],\n sinceMs: number | null,\n ): Promise<void> {\n for (const ev of items) {\n if (!isAuthEventType(ev.event)) {\n continue;\n }\n const ts = isoToMs(ev.created_at);\n if (ts === null) {\n continue;\n }\n if (sinceMs !== null && ts <= sinceMs) {\n continue;\n }\n const data = ev.data ?? {};\n const attributes: Record<string, JSONValue> = {\n eventType: ev.event,\n outcome: deriveOutcome(ev.event),\n method: deriveMethod(ev.event),\n organizationId: data.organization_id ?? null,\n userId: data.user_id ?? null,\n connectionId: data.connection_id ?? null,\n connectionType: data.connection_type ?? null,\n ipAddress: data.ip_address ?? null,\n eventId: ev.id,\n };\n await storage.event({\n name: AUTH_EVENT,\n start_ts: ts,\n end_ts: null,\n attributes,\n });\n }\n }\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: WorkOSPhase,\n isFull: boolean,\n ): Promise<void> {\n if (!isFull) {\n return;\n }\n switch (phase) {\n case 'organizations':\n await storage.entities([], { types: [ORGANIZATION_ENTITY] });\n return;\n case 'connections':\n await storage.entities([], { types: [CONNECTION_ENTITY] });\n return;\n case 'directories':\n await storage.entities([], { types: [DIRECTORY_ENTITY] });\n return;\n case 'auth_events':\n await storage.events([], { names: [AUTH_EVENT] });\n return;\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: WorkOSPhase,\n items: unknown[],\n sinceMs: number | null,\n ): Promise<void> {\n switch (phase) {\n case 'organizations':\n return this.writeOrganizations(storage, items as WorkOSOrganization[]);\n case 'connections':\n return this.writeConnections(storage, items as WorkOSConnection[]);\n case 'directories':\n return this.writeDirectories(storage, items as WorkOSDirectory[]);\n case 'auth_events':\n return this.writeAuthEvents(storage, items as WorkOSEvent[], sinceMs);\n }\n }\n\n private resolveCursor(cursor: unknown): WorkOSSyncCursor | undefined {\n return isWorkOSSyncCursor(cursor) ? cursor : undefined;\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const sinceMs = options.since ? Date.parse(options.since) : null;\n const sinceMsOrNull =\n sinceMs !== null && Number.isFinite(sinceMs) ? sinceMs : null;\n\n const phases = selectActivePhases<WorkOSResource, WorkOSPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<WorkOSPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) =>\n this.fetchPhasePage(phase, page, options, sig),\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n await this.writePhase(storage, phase, items, sinceMsOrNull);\n },\n });\n }\n}\n","import { WorkOSConnector } from './workos';\n\nexport {\n WorkOSConnector,\n workosResources as resources,\n configFields,\n doc,\n id,\n} from './workos';\nexport type { WorkOSResource, WorkOSSettings } from './workos';\nexport default WorkOSConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AKJO,SAAS,WACd,OACA,MACe;AACf,MAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,WAAO;EACT;AACA,MAAI,SAAS,OAAO;AAClB,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO;IACT;AACA,UAAM,KAAK,IAAI,KAAK,KAAK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AA,IACF,CAAC;AAAA,EACH;AACF;;;AC7uBA,IAAO,gBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rawdash/connector-workos",
3
- "version": "0.0.1",
3
+ "version": "0.27.0",
4
4
  "description": "Rawdash connector for WorkOS — syncs organizations, SSO connections, directory-sync directories, and authentication events from the WorkOS API into the six-shape storage model",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -22,22 +22,22 @@
22
22
  "import": "./dist/index.js"
23
23
  }
24
24
  },
25
- "scripts": {
26
- "build": "tsup",
27
- "typecheck": "tsc --noEmit",
28
- "lint": "eslint src",
29
- "test": "vitest run"
30
- },
31
25
  "dependencies": {
32
- "@rawdash/core": "workspace:*",
33
- "zod": "^4.4.3"
26
+ "zod": "^4.4.3",
27
+ "@rawdash/core": "0.27.0"
34
28
  },
35
29
  "devDependencies": {
36
- "@rawdash/connector-shared": "workspace:*",
37
- "@rawdash/connector-test-utils": "workspace:*",
38
30
  "fast-check": "^4.8.0",
39
31
  "tsup": "^8.0.0",
40
32
  "typescript": "^5.7.2",
41
- "vitest": "^4.1.4"
33
+ "vitest": "^4.1.4",
34
+ "@rawdash/connector-test-utils": "0.0.10",
35
+ "@rawdash/connector-shared": "0.3.1"
36
+ },
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "typecheck": "tsc --noEmit",
40
+ "lint": "eslint src",
41
+ "test": "vitest run"
42
42
  }
43
- }
43
+ }