@devrev/airsync-sdk 2.0.0-beta.6 → 2.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +8 -12
  2. package/dist/attachments-streaming/attachments-streaming-pool.d.ts.map +1 -1
  3. package/dist/attachments-streaming/attachments-streaming-pool.js +8 -9
  4. package/dist/common/constants.d.ts +0 -7
  5. package/dist/common/constants.d.ts.map +1 -1
  6. package/dist/common/constants.js +1 -28
  7. package/dist/common/helpers.d.ts.map +1 -1
  8. package/dist/common/helpers.js +1 -1
  9. package/dist/http/errors.d.ts +8 -0
  10. package/dist/http/errors.d.ts.map +1 -0
  11. package/dist/http/errors.js +31 -0
  12. package/dist/index.d.ts +18 -13
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +14 -11
  15. package/dist/logger/logger.d.ts.map +1 -1
  16. package/dist/logger/logger.interfaces.d.ts +2 -2
  17. package/dist/logger/logger.interfaces.d.ts.map +1 -1
  18. package/dist/mappers/mappers.d.ts +9 -3
  19. package/dist/mappers/mappers.d.ts.map +1 -1
  20. package/dist/mappers/mappers.interfaces.d.ts +0 -2
  21. package/dist/mappers/mappers.interfaces.d.ts.map +1 -1
  22. package/dist/mappers/mappers.js +33 -13
  23. package/dist/multithreading/adapters/base-adapter.d.ts +16 -35
  24. package/dist/multithreading/adapters/base-adapter.d.ts.map +1 -1
  25. package/dist/multithreading/adapters/base-adapter.js +89 -23
  26. package/dist/multithreading/adapters/extraction-adapter.d.ts +24 -20
  27. package/dist/multithreading/adapters/extraction-adapter.d.ts.map +1 -1
  28. package/dist/multithreading/adapters/extraction-adapter.js +175 -122
  29. package/dist/multithreading/adapters/loading-adapter.d.ts +13 -23
  30. package/dist/multithreading/adapters/loading-adapter.d.ts.map +1 -1
  31. package/dist/multithreading/adapters/loading-adapter.js +176 -301
  32. package/dist/multithreading/emit.d.ts.map +1 -1
  33. package/dist/multithreading/process-task.d.ts.map +1 -1
  34. package/dist/multithreading/process-task.js +24 -6
  35. package/dist/multithreading/spawn/spawn.d.ts +6 -1
  36. package/dist/multithreading/spawn/spawn.d.ts.map +1 -1
  37. package/dist/multithreading/spawn/spawn.helpers.d.ts.map +1 -1
  38. package/dist/multithreading/spawn/spawn.helpers.js +17 -52
  39. package/dist/multithreading/spawn/spawn.js +30 -26
  40. package/dist/multithreading/worker.js +15 -1
  41. package/dist/repo/repo.d.ts +4 -5
  42. package/dist/repo/repo.d.ts.map +1 -1
  43. package/dist/repo/repo.interfaces.d.ts +5 -4
  44. package/dist/repo/repo.interfaces.d.ts.map +1 -1
  45. package/dist/repo/repo.js +13 -15
  46. package/dist/state/base-state.d.ts +10 -5
  47. package/dist/state/base-state.d.ts.map +1 -1
  48. package/dist/state/base-state.js +39 -36
  49. package/dist/state/extraction-state.d.ts.map +1 -1
  50. package/dist/state/extraction-state.js +39 -4
  51. package/dist/state/state.interfaces.d.ts +13 -7
  52. package/dist/state/state.interfaces.d.ts.map +1 -1
  53. package/dist/state/state.interfaces.js +6 -8
  54. package/dist/state/time-value-resolver.d.ts.map +1 -1
  55. package/dist/state/time-value-resolver.js +3 -2
  56. package/dist/testing/mock-event.d.ts.map +1 -1
  57. package/dist/testing/mock-event.js +0 -8
  58. package/dist/testing/mock-server.d.ts +2 -0
  59. package/dist/testing/mock-server.d.ts.map +1 -1
  60. package/dist/testing/mock-server.interfaces.d.ts +6 -0
  61. package/dist/testing/mock-server.interfaces.d.ts.map +1 -1
  62. package/dist/testing/mock-server.js +37 -6
  63. package/dist/testing/test-adapters.d.ts +22 -0
  64. package/dist/testing/test-adapters.d.ts.map +1 -0
  65. package/dist/testing/test-adapters.js +32 -0
  66. package/dist/types/common.d.ts +4 -1
  67. package/dist/types/common.d.ts.map +1 -1
  68. package/dist/types/common.js +1 -1
  69. package/dist/types/errors.d.ts +13 -7
  70. package/dist/types/errors.d.ts.map +1 -1
  71. package/dist/types/errors.js +24 -0
  72. package/dist/types/extraction.d.ts +60 -44
  73. package/dist/types/extraction.d.ts.map +1 -1
  74. package/dist/types/extraction.js +10 -1
  75. package/dist/types/loading.d.ts +11 -30
  76. package/dist/types/loading.d.ts.map +1 -1
  77. package/dist/types/workers.d.ts +27 -23
  78. package/dist/types/workers.d.ts.map +1 -1
  79. package/dist/uploader/uploader.d.ts +1 -2
  80. package/dist/uploader/uploader.d.ts.map +1 -1
  81. package/dist/uploader/uploader.helpers.d.ts +3 -0
  82. package/dist/uploader/uploader.helpers.d.ts.map +1 -1
  83. package/dist/uploader/uploader.helpers.js +16 -0
  84. package/dist/uploader/uploader.interfaces.d.ts +4 -29
  85. package/dist/uploader/uploader.interfaces.d.ts.map +1 -1
  86. package/dist/uploader/uploader.js +4 -23
  87. package/docs/MIGRATION.md +651 -0
  88. package/package.json +24 -10
  89. package/MIGRATION.md +0 -1028
@@ -0,0 +1,651 @@
1
+ # Migrating connectors from v1 (`@devrev/ts-adaas`) to v2 (`@devrev/airsync-sdk`)
2
+
3
+ This is the complete list of connector-facing changes from `@devrev/ts-adaas`
4
+ 1.x to `@devrev/airsync-sdk` 2.x, written so an AI agent can apply it on its
5
+ own:
6
+
7
+ > Read `MIGRATION.md` from `@devrev/airsync-sdk` and migrate this connector.
8
+
9
+ It ships in the package at `node_modules/@devrev/airsync-sdk/docs/MIGRATION.md`
10
+ (read it from disk; the `exports` map only blocks `import`/`require`). Before
11
+ v2 is installed, use
12
+ `https://raw.githubusercontent.com/devrev/adaas-sdk/v2/docs/MIGRATION.md`.
13
+
14
+ **The wire protocol is unchanged.** Event payloads, routes, headers, the
15
+ artifact flow and every event-type and `ERROR_CODE=…` string are identical to
16
+ v1. Only the TypeScript API changed, all at once, with no compatibility shims.
17
+
18
+ ---
19
+
20
+ ## Runbook
21
+
22
+ **Rules.** Work autonomously; when a rewrite is ambiguous, pick the option
23
+ that preserves runtime behavior and note it in `MIGRATION_REVIEW.md`. Migrate
24
+ source **and** tests. Never change a runtime string value. Don't add comments
25
+ about the migration; the `// v1` / `// v2` labels here are reading aids. Leave
26
+ no compile errors or orphaned imports. A section with no hits is a no-op.
27
+ Existing comments and commented-out code that describe v1 behavior (`emit`,
28
+ `{ id }` / `{ error }` returns, `.data.sync_mapper_record`) are rewritten to
29
+ v2; templates are copied into new connectors, so stale comments spread.
30
+
31
+ 1. **Locate the package.** Find the `package.json` that depends on
32
+ `@devrev/ts-adaas` (generated connectors keep it in `code/`). Run everything
33
+ from there. If it already depends on `@devrev/airsync-sdk` only, report
34
+ "already on v2" and stop.
35
+ 2. **Start from green latest v1.** If behind the latest stable 1.x, upgrade and
36
+ apply the release notes of every release in between that mentions a
37
+ migration (the last ones were 1.16.0–1.18.0), then get tsc/lint/build/test
38
+ green on v1. Record failures that remain as **Pre-existing**.
39
+ 3. **Install v2.**
40
+ ```bash
41
+ npm uninstall @devrev/ts-adaas
42
+ npm install @devrev/airsync-sdk@beta # @latest after GA
43
+ ```
44
+ If the installed `docs/MIGRATION.md` differs from this copy, switch to it.
45
+ 4. **Apply §1–§14 in order** across source and tests. After §1, search by
46
+ symbol (`\.emit\(`, `WorkerAdapter`, `sync_mapper_record`, …), not by the old
47
+ package name; test files that import nothing from the SDK still need
48
+ changes.
49
+ 5. **Verify**: `npm install && npx tsc --noEmit && npm run lint && npm run build && npm test`.
50
+ If tsconfig excludes tests, the test run is their type check. Fix and rerun,
51
+ at most 4 attempts; the migration must add no new failures compared to
52
+ step 2.
53
+ 6. **Sweep.** This must return nothing except legitimate hits (an
54
+ `EventEmitter.emit`, the connector's own `axiosClient` from §9):
55
+ ```bash
56
+ grep -rnE "@devrev/ts-adaas|airsync-sdk/dist|\bprocessTask\b|WorkerAdapter|\.emit\(|hasWorkerEmitted|Airdrop(Event|Message)|axiosClient|(format|serialize)AxiosError|workerPath:|overridenOptions|skipConfirmation|isLocalDevelopment|--local|(Extractor|Loader)EventType|ExtractionCommonError|ERROR_CODE=|sdkState|onUpload|uploadedArtifacts|currentEventDataLength|EXTRACTION_(DATA|METADATA|ATTACHMENTS|EXTERNAL_SYNC_UNITS)_" \
57
+ --include='*.ts' --include='*.js' --include='*.json' --include='*.yml' --include='*.yaml' --include='*.md' --include='*.mdc' . \
58
+ | grep -vE 'node_modules|/dist/|/coverage/|package-lock.json|MIGRATION_REVIEW.md'
59
+ ```
60
+ Also grep `getByExternalId|getByTargetId` and check each call against §10:
61
+ existence checks there compile but silently invert.
62
+ Then rewrite any connector docs (`README`, `AGENTS.md`, `CLAUDE.md`, `docs/`)
63
+ that describe v1 behavior.
64
+ 7. **Write `MIGRATION_REVIEW.md`** at the repo root: one line per section that
65
+ changed code with `high` / `medium` / `low confidence`, a sentence on what
66
+ to verify for medium/low, and the final check results with an
67
+ **Unresolved** list. Use medium/low for anything judged: emits bubbled out of
68
+ helpers (§4), paths that emitted nothing (§4), `onTimeout` bodies kept (§4),
69
+ delay values that look like milliseconds or headers (§4), the cursor decision
70
+ (§8), ESU repo rewrites (§7), mapper error handling (§10), and a v1 baseline
71
+ upgrade.
72
+ ```markdown
73
+ # v2 Migration Review
74
+ Migrated `@devrev/ts-adaas` 1.20.2 → `@devrev/airsync-sdk` 2.0.0.
75
+ - §4 emit→return — high confidence
76
+ - §8 state / cursor — low confidence: repointed `lastSuccessfulSyncStarted`
77
+ to `extract_from`; confirm the connector didn't own this cursor.
78
+ ## Verification
79
+ tsc ✓ · lint ✓ · build ✓ · test ✓ (48 passed)
80
+ ```
81
+ 8. **Report** the start and end versions, which sections fired, the check
82
+ results and how many review entries need a second look.
83
+
84
+ ---
85
+
86
+ ## 1. Package, imports and runtime
87
+
88
+ - Replace `@devrev/ts-adaas` with `@devrev/airsync-sdk` **everywhere the
89
+ string appears**: imports, `jest.mock` / `jest.requireActual` arguments and
90
+ `moduleNameMapper`.
91
+ - **Import only from the root.** `exports` exposes nothing else, so every
92
+ `@devrev/airsync-sdk/dist/**` import fails with
93
+ `ERR_PACKAGE_PATH_NOT_EXPORTED`. Everything public is on the root, including
94
+ `Mappers`, `Item`, `ItemTypeToLoad`, `InitialSyncScope`, the mapper
95
+ `*Params` / `*Response` types and `SyncMapperRecord*`. Deep imports with no
96
+ root equivalent are listed in §11. Never import the SDK's internal HTTP client
97
+ (`dist/http/axios-client-internal`): use the connector's own client (§9).
98
+ - **Node.js ≥ 20.** Bump the connector's `engines`, CI image and `.nvmrc` if
99
+ they pin older. Dependabot / CI configs that name `@devrev/ts-adaas` switch to
100
+ `@devrev/airsync-sdk`.
101
+ - `ts-node` and `@devrev/typescript-sdk` are no longer SDK dependencies. A
102
+ connector that runs `.ts` workers directly needs `ts-node` in its own
103
+ `devDependencies`. A connector that uses `@devrev/typescript-sdk` must list
104
+ it. `InputData` (the type of `event.input_data`) is now exported from the
105
+ root.
106
+
107
+ ## 2. Event types
108
+
109
+ | v1 | v2 |
110
+ |----|----|
111
+ | `AirdropEvent` | `AirSyncEvent` |
112
+ | `AirdropMessage` | `AirSyncMessage` |
113
+
114
+ The shapes are unchanged. `AirSyncEvent.context` now also declares `user_id`,
115
+ `dev_oid`, `source_id` and `service_account_id` (on `event.context`, not on
116
+ `payload.event_context`). Delete a hand-rolled context type that added these
117
+ (e.g. `interface CustomAirdropEvent extends AirdropEvent { context: CustomContext }`):
118
+ a narrower `context` no longer satisfies `AirSyncEvent`. Keep only the fields
119
+ the SDK type lacks.
120
+
121
+ Deprecated `EventContext` aliases are removed. Use the current names:
122
+
123
+ | Removed | Use |
124
+ |---------|-----|
125
+ | `dev_org` | `dev_oid` |
126
+ | `dev_user`, `dev_user_id` | `dev_uid` |
127
+ | `external_sync_unit` | `external_sync_unit_id` |
128
+ | `external_system` | `external_system_id` |
129
+ | `sync_run`, `sync_run_id` | `run_id` |
130
+ | `uuid` | `request_id_adaas` |
131
+
132
+ `reset_extraction` and `reset_extract_from` remain (the SDK never read them);
133
+ leave connector logic that uses them alone.
134
+
135
+ ## 3. `spawn`
136
+
137
+ | v1 | v2 |
138
+ |----|----|
139
+ | `workerPath` | removed; use `baseWorkerPath` |
140
+ | `baseWorkerPath?` | **required**, the directory containing `workers/` (usually `__dirname`) |
141
+ | `options.workerPathOverrides` | top-level `workerPathOverrides` |
142
+ | `options: WorkerAdapterOptions` | `options?: SpawnOptions` (`{ timeout?, batchSize? }`) |
143
+ | `options.isLocalDevelopment`, `--local` argv | removed; set `AIRSYNC_LOCAL_DEVELOPMENT=1` |
144
+
145
+ ```ts
146
+ // v1
147
+ spawn({
148
+ event,
149
+ initialState,
150
+ workerPath: __dirname + '/workers/data-extraction',
151
+ options: { isLocalDevelopment: true, workerPathOverrides: { [EventType.StartExtractingData]: '/workers/custom' } },
152
+ });
153
+ // v2
154
+ spawn({
155
+ event,
156
+ initialState,
157
+ baseWorkerPath: __dirname,
158
+ workerPathOverrides: { [EventType.StartExtractingData]: '/workers/custom' },
159
+ });
160
+ ```
161
+
162
+ - If `workerPath` came from a dispatcher helper (e.g.
163
+ `getWorkerPerLoadingPhase(event)`), delete the helper and its now-unused
164
+ imports.
165
+ - **Fixture and test events** must use the modern event-type strings; v1
166
+ translated legacy ones and v2 doesn't. Replace `EXTRACTION_EXTERNAL_SYNC_UNITS_START`,
167
+ `EXTRACTION_METADATA_START`, `EXTRACTION_DATA_START` / `_CONTINUE` / `_DELETE`
168
+ and `EXTRACTION_ATTACHMENTS_START` / `_CONTINUE` / `_DELETE` with
169
+ `START_EXTRACTING_EXTERNAL_SYNC_UNITS`, `START_EXTRACTING_METADATA`,
170
+ `START_EXTRACTING_DATA` / `CONTINUE_EXTRACTING_DATA` /
171
+ `START_DELETING_EXTRACTOR_STATE` and `START_EXTRACTING_ATTACHMENTS` /
172
+ `CONTINUE_EXTRACTING_ATTACHMENTS` / `START_DELETING_EXTRACTOR_ATTACHMENTS_STATE`.
173
+ - **Local mode** comes only from the `AIRSYNC_LOCAL_DEVELOPMENT=1` environment
174
+ variable, and is ignored on Lambda. A local runner that did
175
+ `process.argv.push('--local')` sets
176
+ `process.env.AIRSYNC_LOCAL_DEVELOPMENT = '1'` before calling `spawn` instead.
177
+
178
+ ## 4. Workers return a `TaskResult` instead of emitting
179
+
180
+ `adapter.emit` is gone (a compile error). A task reports how the phase ended by
181
+ returning a result; the SDK picks the platform event and emits it exactly once.
182
+
183
+ ```ts
184
+ export type TaskResult =
185
+ | { status: 'success' }
186
+ | { status: 'progress' }
187
+ | { status: 'delay'; delaySeconds: number }
188
+ | { status: 'error'; error: ErrorRecord }; // { message: string; code?: AirSyncErrorCode }
189
+ ```
190
+
191
+ Replace `processTask` with `processExtractionTask` or `processLoadingTask`,
192
+ depending on the worker (extraction workers use repos or `streamAttachments`;
193
+ loading workers use `loadItemTypes`, `loadAttachments` or `mappers`). Their
194
+ generic stays the connector state: `processTask<State>` →
195
+ `processExtractionTask<State>`.
196
+
197
+ ```ts
198
+ // v1
199
+ processTask({
200
+ task: async ({ adapter }) => {
201
+ // ...
202
+ await adapter.emit(ExtractorEventType.DataExtractionDone);
203
+ },
204
+ onTimeout: async ({ adapter }) => {
205
+ await adapter.postState();
206
+ await adapter.emit(ExtractorEventType.DataExtractionProgress);
207
+ },
208
+ });
209
+ // v2
210
+ processExtractionTask({
211
+ task: async ({ adapter }) => {
212
+ // ...
213
+ return { status: 'success' };
214
+ },
215
+ });
216
+ ```
217
+
218
+ | v1 | v2 |
219
+ |----|----|
220
+ | `emit(XxxDone)` | `return { status: 'success' }` |
221
+ | `emit(XxxProgress, { progress })` | `return { status: 'progress' }` |
222
+ | `emit(XxxDelayed, { delay })` | `return { status: 'delay', delaySeconds: delay }` — keep the same number; the platform always read it as seconds. If it is clearly milliseconds or a raw `Retry-After` header, keep the behavior (`Number(header)`) and flag it in the review |
223
+ | `emit(XxxDelayed)` with no `delay` | `delaySeconds` is required; use the connector's existing default retry constant, else `0` (what v1 effectively sent), and flag it |
224
+ | `emit(XxxError, { error })` | `return { status: 'error', error }` — `error` is required; fall back to `{ message: '<phase> failed' }` |
225
+ | `emit(XxxDone, { error })` (finished with warnings) | `return { status: 'success' }` and log the error. Returning `error` would fail the phase |
226
+ | `emit(ExternalSyncUnitExtractionDone, { external_sync_units })` | push to a repo, then `success` (§7) |
227
+ | `emit(MetadataExtractionDone, { pre_extraction_item_counts })` | `adapter.preExtractionItemCounts = counts`, then `success` |
228
+ | a path that **emitted nothing** (a `catch` that only logs, a branch that falls through) | `{ status: 'error', error: { message } }`, or rethrow. In v1 the SDK reported these as a phase error ("Worker exited without emitting"); never turn them into `success` or `progress` |
229
+ | any `emit(XxxDone)` after `loadItemTypes` / `loadAttachments` / `streamAttachments`, guarded (`!adapter.hasWorkerEmitted && !adapter.isTimeout`) or not | `return adapter.loadItemTypes(...)` (or the other call). Never discard their result and return `success`: v1 emitted their `delay` / `error` itself. Drop the guard and any module-level "already emitted" flags |
230
+
231
+ In non-resumable phases (external sync units, state deletion), `progress` and
232
+ `delay` become `*Error`.
233
+
234
+ **Emits inside helpers.** Only the task's return value reaches the SDK, so a
235
+ helper that emitted must hand its result back up. Either return
236
+ `TaskResult | null` up the call chain (`null` = keep going), or record it and
237
+ return it once the loop ends:
238
+
239
+ ```ts
240
+ private result: TaskResult | undefined;
241
+ private onPermissionDenied() {
242
+ this.result = { status: 'error', error: { message: '...' } };
243
+ }
244
+ // at the end of the task: a recorded result, else continue only on timeout
245
+ return this.result ?? (adapter.isTimeout
246
+ ? { status: 'progress' }
247
+ : { status: 'error', error: { message: 'Extraction ended without a result' } });
248
+ ```
249
+
250
+ If a shared `handleError` emitted from many `catch` blocks that rethrow, v1
251
+ kept only the first emit. Record the first result (`firstError ??= …`) and
252
+ return it from the task's outermost `catch`.
253
+
254
+ If a helper (often the HTTP client's 429 handler) **emitted and then threw a
255
+ sentinel error** that call sites rethrow, keep the throw, drop the emit, and map
256
+ it in the task's outermost `catch`:
257
+ `if (e instanceof RateLimitDelayedError) return { status: 'delay', delaySeconds: e.retryAfterSeconds };`.
258
+ Don't let it reach a generic error branch, or every rate limit fails the sync.
259
+ In external sync units (non-resumable) the SDK still sends `delay` as an
260
+ error; that matches nothing better, so keep it and flag it in the review.
261
+
262
+ Tests of helpers that now record a result read it back
263
+ (`expect(extractor['result']).toEqual(…)`) or, for `TaskResult | null`
264
+ helpers, assert on the return value.
265
+
266
+ **Timeouts.**
267
+
268
+ - In the **task body**, `if (adapter.isTimeout) return;` becomes
269
+ `return { status: 'progress' };`. The same applies to a `return;` in a
270
+ `catch` that handles a timeout (`if (adapter.isTimeout || e instanceof
271
+ MyTimeout) return;`). Early `return`s inside `Promise<void>` helpers stay as
272
+ they are, as long as the task checks `isTimeout` after calling them.
273
+ - After the soft timeout, a returned `success` or `progress` is replaced by
274
+ the `onTimeout` result. A returned `error` or `delay` is always emitted as is.
275
+ - `onTimeout` is optional and defaults to `progress` (or a timeout error in
276
+ external sync units and state deletion; metadata is resumable). v1 ran
277
+ `onTimeout` only when the task finished **without emitting**; v2 also runs it
278
+ when the task returns `success` after the timeout. So:
279
+ - **Delete** it when it only emitted the usual event or computed a
280
+ `progress` number, when the v1 task emitted on every path, or when the task
281
+ only returns `loadItemTypes` / `loadAttachments` / `streamAttachments`
282
+ (they handled the timeout themselves).
283
+ - **Keep** it, returning a `TaskResult`, only when it could actually run in
284
+ v1 (the task had a path that didn't emit) **and** it did real work or set a
285
+ custom error. Make its body safe to run after a completed task. A custom
286
+ "Lambda timeout" `onTimeout` on a task that emits on every path is
287
+ deleted.
288
+ - Don't call `process.exit()` or `postState()` in `onTimeout`; the SDK saves
289
+ state and exits.
290
+
291
+ **Throws.** A task that throws emits the phase's `*Error` with the message,
292
+ along with the artifacts already uploaded. `repo.push()` and `repo.upload()`
293
+ resolve `void` and throw if an upload fails. **Any use of `push()`'s value is
294
+ now wrong**, and `Boolean(await repo.push(x))` or `if (!(await …push(x)))`
295
+ compiles but is always falsy. Make wrappers `await repo.push(x)` and return
296
+ `true` (or `void`). Keep a top-level `try/catch` that maps an error to `delay`
297
+ (e.g. a thrown 429); otherwise it's only needed for a custom message.
298
+
299
+ `ProcessTaskInterface<T>` and `TaskAdapterInterface<T>` now take the
300
+ **adapter** type: `ProcessTaskInterface<ExtractionAdapter<State>>`, not
301
+ `<State>`.
302
+
303
+ ## 5. Adapters
304
+
305
+ The `WorkerAdapter` class is gone. Annotate with the phase's adapter:
306
+
307
+ ```ts
308
+ async function extractList(adapter: ExtractionAdapter<State>) { ... }
309
+ ```
310
+
311
+ | Members | On |
312
+ |---------|----|
313
+ | `initializeRepos`, `getRepo`, `streamAttachments`, `processAttachment`, `shouldExtract`, `artifacts`, `preExtractionItemCounts` | `ExtractionAdapter` |
314
+ | `loadItemTypes`, `loadAttachments`, `mappers`, `reports`, `processedFiles` | `LoadingAdapter` |
315
+ | `event`, `state`, `postState`, `uploadArtifact`, `downloadArtifact`, `isTimeout`, `extractionScope` | both |
316
+
317
+ - The adapters and `Repo` are **type-only**: `new ExtractionAdapter(...)` and
318
+ `class X extends LoadingAdapter<S>` don't compile; `interface X extends …`
319
+ does. SDK internals (`emit`, `sdkState`, `options`, constructors, …) aren't
320
+ public. `isTimeout` and `artifacts` are read-only.
321
+ - Code that used `adapter.mappers` during extraction creates its own
322
+ `new Mappers({ event: adapter.event })` once in the task (or a class
323
+ constructor) and passes it down to helpers as a `mappers` argument typed
324
+ `Pick<Mappers, 'getByExternalId'>`; tests then pass a plain double.
325
+ - **Integration tests** that built an adapter by hand use the root factories:
326
+
327
+ ```ts
328
+ // v1
329
+ const adapter = new WorkerAdapter({ event, adapterState: new State({ event, initialState }) });
330
+ adapterState.state.fromDevRev = { filesToLoad };
331
+ // v2
332
+ const adapter = createTestExtractionAdapter({ event, initialState });
333
+ const loader = createTestLoadingAdapter({ event, initialState, filesToLoad });
334
+ ```
335
+
336
+ Platform calls still go to the event's URLs. Build the event with
337
+ `createMockEvent(mockServer.baseUrl, …)` and serve the URLs with
338
+ `MockServer`. Artifact downloads need two routes: `GET
339
+ /internal/airdrop.artifacts.download-url` returning `{ download_url }`, and
340
+ that URL serving the gzipped JSONL. Assert on the returned `TaskResult`,
341
+ `adapter.reports` and `adapter.processedFiles`, not on `emit` or SDK state;
342
+ to test a resume, build a second adapter with `filesToLoad` at the cursor you
343
+ expect. To simulate a timeout, use a plain mock object, not a real adapter.
344
+ Test repos are plain objects (`{ itemType, push: jest.fn() }`).
345
+ - `adapter.postState()` takes no argument and **throws** on failure (v1 exited
346
+ the process). State is saved on every emit, so keep a call only to save
347
+ state before an external write that must not be repeated. v1
348
+ `postState(next)` becomes `adapter.state = next; await adapter.postState();`.
349
+
350
+ ## 6. Loading, attachments and callback results
351
+
352
+ `loadItemTypes`, `loadAttachments` and `streamAttachments` return a
353
+ `TaskResult`. Return it directly:
354
+
355
+ ```ts
356
+ processLoadingTask({ task: async ({ adapter }) => adapter.loadItemTypes({ itemTypesToLoad }) });
357
+ processExtractionTask({ task: async ({ adapter }) => adapter.streamAttachments({ stream }) });
358
+ ```
359
+
360
+ The result has no `reports` / `processed_files`. To add a report, push it to
361
+ `adapter.reports` before returning. Tests assert on `adapter.reports`.
362
+
363
+ **Connector callbacks** return a `status` union, like `TaskResult`:
364
+
365
+ | Callback | v1 | v2 |
366
+ |----------|----|----|
367
+ | attachment `stream` | `{ httpStream }` / `{ delay }` / `{ error: { message, statusCode? } }` | `{ status: 'success', httpStream }` / `{ status: 'delay', delaySeconds }` / `{ status: 'error', error: { message } }` |
368
+ | loader `create` / `update` | `{ id, modifiedDate? }` / `{ delay }` / `{ error: 'msg' \| { message } }` / neither (counted as failed) | `{ status: 'success', id, modifiedDate? }` / `{ status: 'delay', delaySeconds }` / `{ status: 'error', error: { message } }` |
369
+ | `adapter.processAttachment`, custom `iterator` | `{ delay? , error? } \| undefined` | `{ status: 'success' }` / `{ status: 'delay', delaySeconds }` / `{ status: 'error', error }` |
370
+
371
+ ```ts
372
+ // custom iterator, v2
373
+ const response = await adapter.processAttachment(attachment, stream);
374
+ if (response.status === 'delay') return response;
375
+ if (response.status === 'error') console.warn(response.error.message);
376
+ // ...
377
+ return { status: 'success' }; // was a bare `return;`
378
+ ```
379
+
380
+ - Loader `error` results still count as failed and loading continues. A v1
381
+ result with **both** `delay` and `error` becomes `delay` (v1 honored the delay).
382
+ - `success` needs a real `id`: a v1 `{ id }` whose value may be `undefined`
383
+ (from an untyped response) was counted as failed, so guard it:
384
+ `if (!id) return { status: 'error', error: { message } }`. Extra fields such
385
+ as `skip` are dropped; every `success` creates or updates a mapper record.
386
+ - Shared helpers typed as these responses change too. Callers that read
387
+ `result.delay` or interpolate `${result.error}` (now an object) switch on
388
+ `result.status`.
389
+ - An error `code` returned from the stream callback is only logged; the pool
390
+ skips that attachment.
391
+ - `httpStream` is typed `HttpStreamResponse` (`{ data, headers }`); an axios
392
+ response still satisfies it. Types derived by indexing the old interface
393
+ (`ExternalSystemAttachmentStreamingResponse['httpStream']`) use the root
394
+ `HttpStreamResponse` instead.
395
+ - `statusCode` on stream errors is gone; put it in the message if you need it.
396
+
397
+ **`processAttachment` works in any extraction phase.** SSOR artifacts created
398
+ outside the attachments phase are held by the SDK and reported with
399
+ `ATTACHMENT_EXTRACTION_DONE`. **Delete any workaround** for this, along with
400
+ its state fields and tests. Workarounds typically override the
401
+ `ssor_attachment` repo's `onUpload`, splice `uploadedArtifacts`, adjust
402
+ `currentEventDataLength`, or stash artifact refs in state.
403
+
404
+ ## 7. External sync units go through a repo
405
+
406
+ `EventData.external_sync_units` is removed. Push them to a repo:
407
+
408
+ ```ts
409
+ adapter.initializeRepos([
410
+ // matches the batching v1 used for the inline path
411
+ { itemType: AirSyncDefaultItemTypes.EXTERNAL_SYNC_UNITS, overriddenOptions: { batchSize: 25000 } },
412
+ ]);
413
+ await adapter.getRepo(AirSyncDefaultItemTypes.EXTERNAL_SYNC_UNITS)?.push(externalSyncUnits);
414
+ return { status: 'success' };
415
+ ```
416
+
417
+ If the connector already pushed ESUs to a repo, keep its options as they are
418
+ (apart from the §14 rename and removing `skipConfirmation`) and only convert
419
+ the emit.
420
+
421
+ ## 8. State: connector state only
422
+
423
+ - `adapter.state` is the connector's own state (the `initialState` shape);
424
+ reads and writes work as before. SDK bookkeeping (`toDevRev`, `fromDevRev`,
425
+ `workers*`, `pendingWorkers*`, `lastSyncStarted`,
426
+ `lastSuccessfulSyncStarted`, `snapInVersionId`) is internal. The
427
+ `AdapterState<S>` alias is removed; use your own `State` type.
428
+ - **Persisted state** becomes `{ stateVersion: 2, connectorState, sdkState }`.
429
+ A v1 blob is migrated automatically on first read: known SDK keys move to
430
+ `sdkState` and everything else becomes connector state. **Rolling back to v1
431
+ after a v2 worker has run is not supported**; drain or reset syncs first. A
432
+ v1 state with a top-level key named `connectorState` or `sdkState` is
433
+ misread; rename it before upgrading.
434
+ - **Sync window**: read
435
+ `adapter.event.payload.event_context.extract_from` / `extract_to`. The SDK
436
+ resolves them from the platform's time values, or from the last successful
437
+ sync on platforms that don't send them.
438
+ - Remove SDK fields (`toDevRev`, `fromDevRev`, …) from the connector's own
439
+ `State` interface, `getInitialState` and fixtures.
440
+
441
+ **`lastSyncStarted` / `lastSuccessfulSyncStarted`: rename or repoint.**
442
+ Getting this wrong compiles but silently breaks incremental sync.
443
+
444
+ - **Not in the connector's `State` interface** (it came from the SDK): delete
445
+ writes, and repoint reads to `extract_from`.
446
+ - **Declared and used as the connector's own cursor** (derived from data, or
447
+ read alongside `extract_from`): **rename** it (e.g. →
448
+ `lastSuccessfulWindowStart`) everywhere, including fixtures. Otherwise the v1
449
+ auto-migration moves it into SDK state and the connector loses it.
450
+ - **Declared but only mirrors the SDK**: its only writes are "now" when data
451
+ extraction starts and a copy on finish. Treat it as not declared, **even if
452
+ it is read next to `extract_from`**. Renaming would leave it empty after the
453
+ upgrade, because the v1 value moves into SDK state.
454
+
455
+ `extract_from` equals the last successful sync start only when the platform
456
+ sends no time window. If a repointed read feeds logic beyond "skip items older
457
+ than this" (e.g. distinguishing first syncs), flag it as low confidence; there
458
+ is no public "last successful sync" value. Fixtures move from
459
+ `adapter.state.lastSuccessfulSyncStarted = X` to
460
+ `event.payload.event_context.extract_from = X`.
461
+
462
+ ## 9. HTTP: bring your own axios client
463
+
464
+ `axios`, `axiosClient`, `formatAxiosError`, `serializeAxiosError` and
465
+ `HTTPResponse` are no longer exported. Add `axios` (and `axios-retry` for a
466
+ retrying client) to the connector's dependencies.
467
+
468
+ - **`axios`** (v1 re-exported plain axios, without retries) →
469
+ `import axios from 'axios'`. Calls stay as they are; don't route them through
470
+ a retrying client.
471
+ - **`axiosClient`** → the connector's own client, in its own module (e.g.
472
+ `src/http/axios-client.ts`), so tests can mock that module:
473
+
474
+ ```ts
475
+ import axios from 'axios';
476
+ import axiosRetry from 'axios-retry';
477
+
478
+ export const axiosClient = axios.create();
479
+ axiosRetry(axiosClient, {
480
+ retries: 5,
481
+ retryDelay: (retryCount, error) => axiosRetry.exponentialDelay(retryCount, error, 1000),
482
+ retryCondition: (error) =>
483
+ (axiosRetry.isNetworkOrIdempotentRequestError(error) && error.response?.status !== 429) ||
484
+ (error.response?.status ?? 0) >= 500,
485
+ onMaxRetryTimesExceeded: (error) => {
486
+ delete error.config?.headers?.authorization;
487
+ delete error.config?.headers?.Authorization;
488
+ delete error.request?._header;
489
+ },
490
+ });
491
+ ```
492
+
493
+ A deep import of the SDK's internal client (`dist/http/axios-client-internal`)
494
+ relied on more: a 30 s timeout, retries of 429s that send `Retry-After` (waiting
495
+ that long) and of `ECONNABORTED`. Reproduce what the connector depends on with
496
+ `axios.create({ timeout: 30_000 })`, `shouldResetTimeout: true`, and a
497
+ `retryCondition` / `retryDelay` that honor `Retry-After`.
498
+
499
+ For logging, use the root `serializeError(error)`, which returns a string.
500
+ Where `serializeAxiosError(e)` was used as an object (spread, or `.response`),
501
+ build the fields you need from the axios error yourself, leaving out headers.
502
+
503
+ ## 10. Mappers
504
+
505
+ | Method | v1 | v2 |
506
+ |--------|----|----|
507
+ | `getByTargetId`, `getByExternalId` | `AxiosResponse<T>`; rejects with 404 when missing | `T \| null`; `null` when no record exists |
508
+ | `create`, `update` | `AxiosResponse<T>` | `T` |
509
+ | any other failure | axios error | `AirSyncHttpError` (`message`, `status?`), exported from the root |
510
+
511
+ ```ts
512
+ // v1
513
+ try {
514
+ const res = await mappers.getByTargetId({ sync_unit, target });
515
+ return res.data.sync_mapper_record.external_ids[0];
516
+ } catch (e) {
517
+ if (axios.isAxiosError(e) && e.response?.status === 404) return undefined;
518
+ throw e;
519
+ }
520
+ // v2
521
+ const record = await mappers.getByTargetId({ sync_unit, target });
522
+ return record?.sync_mapper_record.external_ids[0];
523
+ ```
524
+
525
+ - Drop `.data`; loosely typed code would otherwise read `undefined`.
526
+ - **Existence checks invert silently.** `try { await mappers.getByExternalId(…); return true; } catch { return false; }`
527
+ now always returns `true`, because a missing record resolves `null`. Rewrite
528
+ the `try` body as `return (await mappers.getByExternalId(…)) !== null;` and
529
+ **keep the `catch`** if v1 had one, so other failures still mean what they
530
+ meant before. Find these with
531
+ `grep -n "getByExternalId\|getByTargetId"`, not by searching for 404.
532
+ - Hand-written structural types (`{ getByTargetId(): Promise<{ data?: … }> }`)
533
+ keep `.data` compiling. Replace them with `Pick<Mappers, 'getByTargetId'>`.
534
+ - Replace 404 `catch` branches with a `null` check.
535
+ - Replace `isAxiosError` checks on mapper calls with
536
+ `e instanceof AirSyncHttpError` / `e.status`. Checks on the connector's own
537
+ HTTP calls stay.
538
+ - Test doubles: `mockResolvedValue({ data: { sync_mapper_record } })` →
539
+ `mockResolvedValue({ sync_mapper_record })`; a 404 `mockRejectedValue(...)`
540
+ or a "not found" `mockResolvedValue({ data: {} })` → `mockResolvedValue(null)`.
541
+ Find them with `grep sync_mapper_record`.
542
+
543
+ ## 11. Removed symbols
544
+
545
+ | Removed | Replacement |
546
+ |---------|-------------|
547
+ | `ExtractorEventType`, `LoaderEventType` | none; return a `TaskResult` (§4), and in tests assert on it. Compare against the raw wire string if really needed |
548
+ | `ExtractionCommonError` | `AirSyncErrorCode` on `error.code` (§12) |
549
+ | `WorkerAdapterOptions` | `SpawnOptions` (spawn), `RepoOptions` (`overriddenOptions`) |
550
+ | `WorkerAdapterInterface`, `SpawnInterface`, `StreamResponse`, `StreamAttachmentsResponse` | none; drop the import |
551
+ | `ArtifactsPrepareResponse` | none; if the connector uses it as its own type, declare it locally (`{ url: string; id: string; form_data: { key: string; value: string }[] }`) |
552
+ | worker IPC types (`WorkerEvent`, `WorkerMessage*`, `WorkerData`, `GetWorkerPathInterface`) | none; assert on the returned `TaskResult` |
553
+ | `State`, `createAdapterState`, `ToDevRev`, `AdapterState` | `createTest*Adapter` (§5); drop SDK state types (§8) |
554
+ | `Uploader` (deep import of `dist/uploader/uploader`, used to store and read back the connector's own artifacts) | `adapter.uploadArtifact(itemType, data)` → `{ id }` and `adapter.downloadArtifact<T>(id)` → `T[]`; both throw instead of returning `{ error }` |
555
+ | `Adapter`, `createAdapter`, `DemoExtractor`, `HTTPClient`, `defaultResponse`, deprecated `Uploader` | the v2 worker contract, your own axios client, repos |
556
+ | `ExtractionMode` | `SyncMode` |
557
+ | `EventContextIn`, `EventContextOut` | `EventContext` |
558
+ | `DomainObjectState`, `ErrorLevel`, `LogRecord`, `AdapterUpdateParams` | none |
559
+ | `translate*EventType` helpers | none; the platform sends modern strings |
560
+ | `EventType.UnknownEventType` | the string `'UNKNOWN_EVENT_TYPE'` |
561
+ | `adapter.hasWorkerEmitted`, `adapter.emit` spies | none; return / assert on the `TaskResult` (§4, §13) |
562
+ | `EventData.progress`, `EventData.external_sync_units` | none (§4, §7) |
563
+
564
+ Deprecated `EventType` members are removed. They had **different** string
565
+ values from their replacements:
566
+
567
+ | Removed | Use |
568
+ |---------|-----|
569
+ | `ExtractionExternalSyncUnitsStart` | `StartExtractingExternalSyncUnits` |
570
+ | `ExtractionMetadataStart` | `StartExtractingMetadata` |
571
+ | `ExtractionDataStart` / `ExtractionDataContinue` | `StartExtractingData` / `ContinueExtractingData` |
572
+ | `ExtractionDataDelete` | `StartDeletingExtractorState` |
573
+ | `ExtractionAttachmentsStart` / `ExtractionAttachmentsContinue` | `StartExtractingAttachments` / `ContinueExtractingAttachments` |
574
+ | `ExtractionAttachmentsDelete` | `StartDeletingExtractorAttachmentsState` |
575
+
576
+ This also applies to `workerPathOverrides` keys. `EventType` can gain members
577
+ in minor versions, so give `switch` statements over it a `default`.
578
+
579
+ ## 12. Error codes
580
+
581
+ `ExtractionCommonError` is now `AirSyncErrorCode`. Its values are bare codes,
582
+ and you set them on `error.code`:
583
+
584
+ ```ts
585
+ // v1
586
+ return { status: 'error', error: { message: ExtractionCommonError.EXTERNAL_SYNC_UNIT_DELETED } };
587
+ // v2
588
+ return {
589
+ status: 'error',
590
+ error: { message: `Project ${id} was deleted.`, code: AirSyncErrorCode.EXTERNAL_SYNC_UNIT_DELETED },
591
+ };
592
+ ```
593
+
594
+ The platform only recognizes a code when the message is exactly
595
+ `ERROR_CODE=<code>`, so the SDK sends just that and logs your `message`. Write
596
+ a useful `message`. Raw `'ERROR_CODE=…'` strings and connector helpers that
597
+ return them (`HISTORICAL_DONE`, `authErrorCode(e)`) still work at runtime but
598
+ are migrated too: make the helper return `AirSyncErrorCode | undefined`, set it
599
+ as `code`, and update tests that pin the literal. The wire string doesn't
600
+ change.
601
+
602
+ ## 13. Tests
603
+
604
+ - Mock factories: `processTask` → `processExtractionTask` /
605
+ `processLoadingTask`. Drop the `WorkerAdapter`, `axios`, `axiosClient` and
606
+ `emit: jest.fn()` keys; if nothing is left, or the file under test never
607
+ imports the SDK, delete the `jest.mock` entirely. Keep `jest.requireActual`
608
+ only for enums that still exist (`EventType`, `SyncMode`, `AirSyncErrorCode`).
609
+ - HTTP mocks: a test that mocked the SDK's `axiosClient` mocks the connector's
610
+ client module instead (`jest.mock('../http/axios-client', () => ({ axiosClient: { get: jest.fn(), post: jest.fn() } }))`).
611
+ Don't automock `axios` when the source calls `axios.create()`, because the
612
+ client becomes `undefined`. For plain `axios` use
613
+ `jest.mock('axios', () => ({ __esModule: true, default: { get: jest.fn(), isAxiosError: jest.fn() }, AxiosError: jest.requireActual('axios').AxiosError }))`.
614
+ Patching a client's `defaults.adapter` now affects only connector traffic.
615
+ - ESU tests assert on the repo: give the mock adapter
616
+ `initializeRepos: jest.fn()` and `getRepo: () => ({ push: mockPush })`, then
617
+ check `mockPush.mock.calls[0][0]`.
618
+ - Replace emit assertions with assertions on the returned result. This applies
619
+ to helpers you call directly too.
620
+ ```ts
621
+ const result = await mockProcessTask.mock.calls[0][0].task({ adapter });
622
+ expect(result).toEqual({ status: 'success' });
623
+ ```
624
+ - Casts like `as unknown as WorkerAdapter<S>` become `ExtractionAdapter<S>` /
625
+ `LoadingAdapter<S>`.
626
+ - Update doubles and fixtures to the v2 shapes: `delaySeconds`, callback
627
+ `status` unions (§6), mapper `null` / unwrapped bodies (§10), `code` on
628
+ errors (§12), renamed state fields and the removed SDK fields (§8).
629
+ - Source that now calls `new Mappers(...)` needs a `Mappers` mock in the SDK
630
+ module factory.
631
+ - For a deleted `onTimeout`, drop the tests of its body and assert it's
632
+ `undefined`. Tests of a deleted SSOR workaround go with it.
633
+
634
+ ## 14. Smaller changes
635
+
636
+ - `RepoInterface.overridenOptions` → `overriddenOptions`.
637
+ - `skipConfirmation` is removed; the SDK handles the ESU repo itself.
638
+ - `NormalizedAttachment.grand_parent_id` is `string`; use `String(id)`.
639
+
640
+ ---
641
+
642
+ ## Rare cases
643
+
644
+ - **Attachment syncs started on SDK < 1.15.2 and still in flight** re-upload
645
+ their already-processed attachments once. Drain them before upgrading if
646
+ that matters.
647
+ - **`is_sdk_log`** is no longer on log lines; update dashboards that filter on
648
+ it.
649
+ - **Connectors migrated against a beta (≤ `2.0.0-beta.6`)** must re-apply
650
+ §3–§14 against GA, because most of the API above changed after those betas.
651
+ State they wrote is still read.