@devrev/airsync-sdk 2.0.0-beta.1 → 2.0.0-beta.3

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 (191) hide show
  1. package/README.md +0 -4
  2. package/dist/airsync-sdk.d.ts +2059 -0
  3. package/dist/attachments-streaming/attachments-streaming-pool.d.ts +2 -1
  4. package/dist/attachments-streaming/attachments-streaming-pool.d.ts.map +1 -1
  5. package/dist/attachments-streaming/attachments-streaming-pool.interfaces.d.ts +8 -2
  6. package/dist/attachments-streaming/attachments-streaming-pool.interfaces.d.ts.map +1 -1
  7. package/dist/attachments-streaming/attachments-streaming-pool.js +27 -16
  8. package/dist/attachments-streaming/attachments-streaming-pool.test.js +246 -27
  9. package/dist/common/constants.d.ts +16 -5
  10. package/dist/common/constants.d.ts.map +1 -1
  11. package/dist/common/constants.js +20 -6
  12. package/dist/common/control-protocol.d.ts +2 -2
  13. package/dist/common/control-protocol.d.ts.map +1 -1
  14. package/dist/common/control-protocol.js +1 -5
  15. package/dist/common/helpers.d.ts +8 -0
  16. package/dist/common/helpers.d.ts.map +1 -1
  17. package/dist/common/helpers.js +15 -0
  18. package/dist/common/install-initial-domain-mapping.d.ts +2 -2
  19. package/dist/common/install-initial-domain-mapping.test.js +5 -2
  20. package/dist/common/test-utils.d.ts +19 -0
  21. package/dist/common/test-utils.d.ts.map +1 -0
  22. package/dist/common/test-utils.js +101 -0
  23. package/dist/common/time-value-resolver.d.ts +47 -0
  24. package/dist/common/time-value-resolver.d.ts.map +1 -0
  25. package/dist/common/time-value-resolver.js +141 -0
  26. package/dist/common/time-value-resolver.test.d.ts +2 -0
  27. package/dist/common/time-value-resolver.test.d.ts.map +1 -0
  28. package/dist/common/time-value-resolver.test.js +268 -0
  29. package/dist/http/axios-client-internal.d.ts.map +1 -1
  30. package/dist/http/axios-client-internal.js +7 -0
  31. package/dist/http/axios-client-internal.test.js +21 -0
  32. package/dist/http/axios-client.d.ts.map +1 -1
  33. package/dist/http/axios-client.js +6 -3
  34. package/dist/http/index.d.ts +0 -1
  35. package/dist/http/index.d.ts.map +1 -1
  36. package/dist/http/index.js +0 -1
  37. package/dist/index.d.ts +12 -10
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +18 -13
  40. package/dist/logger/logger.d.ts +1 -17
  41. package/dist/logger/logger.d.ts.map +1 -1
  42. package/dist/logger/logger.interfaces.d.ts +2 -2
  43. package/dist/logger/logger.js +35 -27
  44. package/dist/logger/logger.test.js +66 -19
  45. package/dist/mappers/mappers.interface.d.ts +5 -5
  46. package/dist/mappers/mappers.interface.js +3 -3
  47. package/dist/mappers/mappers.test.js +8 -10
  48. package/dist/mock-server/mock-server.d.ts +47 -0
  49. package/dist/mock-server/mock-server.d.ts.map +1 -0
  50. package/dist/mock-server/mock-server.interfaces.d.ts +73 -0
  51. package/dist/mock-server/mock-server.interfaces.d.ts.map +1 -0
  52. package/dist/mock-server/mock-server.interfaces.js +4 -0
  53. package/dist/mock-server/mock-server.js +278 -0
  54. package/dist/multithreading/adapters/base-adapter.d.ts +56 -0
  55. package/dist/multithreading/adapters/base-adapter.d.ts.map +1 -0
  56. package/dist/multithreading/adapters/base-adapter.emit.test.d.ts +2 -0
  57. package/dist/multithreading/adapters/base-adapter.emit.test.d.ts.map +1 -0
  58. package/dist/multithreading/adapters/base-adapter.emit.test.js +403 -0
  59. package/dist/multithreading/adapters/base-adapter.js +105 -0
  60. package/dist/multithreading/adapters/extraction-adapter.artifacts.test.d.ts +2 -0
  61. package/dist/multithreading/adapters/extraction-adapter.artifacts.test.d.ts.map +1 -0
  62. package/dist/multithreading/{worker-adapter/worker-adapter.artifacts.test.js → adapters/extraction-adapter.artifacts.test.js} +53 -5
  63. package/dist/multithreading/adapters/extraction-adapter.d.ts +58 -0
  64. package/dist/multithreading/adapters/extraction-adapter.d.ts.map +1 -0
  65. package/dist/multithreading/adapters/extraction-adapter.js +325 -0
  66. package/dist/multithreading/adapters/extraction-adapter.test.d.ts +2 -0
  67. package/dist/multithreading/adapters/extraction-adapter.test.d.ts.map +1 -0
  68. package/dist/multithreading/adapters/extraction-adapter.test.js +789 -0
  69. package/dist/multithreading/adapters/loading-adapter.d.ts +44 -0
  70. package/dist/multithreading/adapters/loading-adapter.d.ts.map +1 -0
  71. package/dist/multithreading/{worker-adapter/worker-adapter.helpers.d.ts → adapters/loading-adapter.helpers.d.ts} +1 -1
  72. package/dist/multithreading/adapters/loading-adapter.helpers.d.ts.map +1 -0
  73. package/dist/multithreading/adapters/loading-adapter.helpers.test.d.ts +2 -0
  74. package/dist/multithreading/adapters/loading-adapter.helpers.test.d.ts.map +1 -0
  75. package/dist/multithreading/{worker-adapter/worker-adapter.helpers.test.js → adapters/loading-adapter.helpers.test.js} +26 -26
  76. package/dist/multithreading/adapters/loading-adapter.js +461 -0
  77. package/dist/multithreading/adapters/loading-adapter.test.d.ts +2 -0
  78. package/dist/multithreading/adapters/loading-adapter.test.d.ts.map +1 -0
  79. package/dist/multithreading/adapters/loading-adapter.test.js +589 -0
  80. package/dist/multithreading/adapters/serialization.test.d.ts +2 -0
  81. package/dist/multithreading/adapters/serialization.test.d.ts.map +1 -0
  82. package/dist/multithreading/adapters/serialization.test.js +71 -0
  83. package/dist/multithreading/create-worker.test.js +36 -17
  84. package/dist/multithreading/process-task.d.ts +16 -1
  85. package/dist/multithreading/process-task.d.ts.map +1 -1
  86. package/dist/multithreading/process-task.js +97 -82
  87. package/dist/multithreading/process-task.test.d.ts +2 -0
  88. package/dist/multithreading/process-task.test.d.ts.map +1 -0
  89. package/dist/multithreading/process-task.test.js +146 -0
  90. package/dist/multithreading/spawn/spawn.d.ts +3 -3
  91. package/dist/multithreading/spawn/spawn.d.ts.map +1 -1
  92. package/dist/multithreading/spawn/spawn.helpers.d.ts.map +1 -1
  93. package/dist/multithreading/spawn/spawn.helpers.js +6 -14
  94. package/dist/multithreading/spawn/spawn.helpers.test.js +8 -8
  95. package/dist/multithreading/spawn/spawn.js +20 -25
  96. package/dist/multithreading/spawn/spawn.test.d.ts +2 -0
  97. package/dist/multithreading/spawn/spawn.test.d.ts.map +1 -0
  98. package/dist/multithreading/spawn/spawn.test.js +232 -0
  99. package/dist/repo/repo.d.ts.map +1 -1
  100. package/dist/repo/repo.interfaces.d.ts +4 -2
  101. package/dist/repo/repo.interfaces.d.ts.map +1 -1
  102. package/dist/repo/repo.js +4 -3
  103. package/dist/repo/repo.test.js +60 -7
  104. package/dist/state/base-state.d.ts +75 -0
  105. package/dist/state/base-state.d.ts.map +1 -0
  106. package/dist/state/base-state.js +261 -0
  107. package/dist/state/extraction-state.d.ts +29 -0
  108. package/dist/state/extraction-state.d.ts.map +1 -0
  109. package/dist/state/extraction-state.js +122 -0
  110. package/dist/state/loading-state.d.ts +19 -0
  111. package/dist/state/loading-state.d.ts.map +1 -0
  112. package/dist/state/loading-state.js +40 -0
  113. package/dist/state/state.extract-window.test.d.ts +2 -0
  114. package/dist/state/state.extract-window.test.d.ts.map +1 -0
  115. package/dist/state/state.extract-window.test.js +163 -0
  116. package/dist/state/state.interfaces.d.ts +44 -27
  117. package/dist/state/state.interfaces.d.ts.map +1 -1
  118. package/dist/state/state.interfaces.js +18 -5
  119. package/dist/state/state.pending-boundaries.test.d.ts +2 -0
  120. package/dist/state/state.pending-boundaries.test.d.ts.map +1 -0
  121. package/dist/state/state.pending-boundaries.test.js +189 -0
  122. package/dist/state/state.post-state.test.d.ts +2 -0
  123. package/dist/state/state.post-state.test.d.ts.map +1 -0
  124. package/dist/state/state.post-state.test.js +78 -0
  125. package/dist/state/state.test.js +135 -88
  126. package/dist/state/state.time-value-resolution.test.d.ts +2 -0
  127. package/dist/state/state.time-value-resolution.test.d.ts.map +1 -0
  128. package/dist/state/state.time-value-resolution.test.js +175 -0
  129. package/dist/tsdoc-metadata.json +11 -0
  130. package/dist/types/common.d.ts +0 -25
  131. package/dist/types/common.d.ts.map +1 -1
  132. package/dist/types/common.js +1 -11
  133. package/dist/types/external-domain-metadata.d.ts +20 -1
  134. package/dist/types/external-domain-metadata.d.ts.map +1 -1
  135. package/dist/types/extraction.d.ts +92 -221
  136. package/dist/types/extraction.d.ts.map +1 -1
  137. package/dist/types/extraction.js +56 -124
  138. package/dist/types/extraction.test.js +69 -43
  139. package/dist/types/index.d.ts +3 -3
  140. package/dist/types/index.d.ts.map +1 -1
  141. package/dist/types/index.js +6 -3
  142. package/dist/types/loading.d.ts +4 -24
  143. package/dist/types/loading.d.ts.map +1 -1
  144. package/dist/types/loading.js +1 -22
  145. package/dist/types/workers.d.ts +47 -29
  146. package/dist/types/workers.d.ts.map +1 -1
  147. package/dist/types/workers.js +1 -0
  148. package/dist/uploader/uploader.d.ts +1 -0
  149. package/dist/uploader/uploader.d.ts.map +1 -1
  150. package/dist/uploader/uploader.helpers.test.js +0 -11
  151. package/dist/uploader/uploader.interfaces.d.ts +3 -3
  152. package/dist/uploader/uploader.js +53 -20
  153. package/dist/uploader/uploader.test.js +22 -10
  154. package/package.json +10 -13
  155. package/dist/common/event-type-translation.d.ts +0 -24
  156. package/dist/common/event-type-translation.d.ts.map +0 -1
  157. package/dist/common/event-type-translation.js +0 -117
  158. package/dist/deprecated/adapter/index.d.ts +0 -62
  159. package/dist/deprecated/adapter/index.d.ts.map +0 -1
  160. package/dist/deprecated/adapter/index.js +0 -151
  161. package/dist/deprecated/common/helpers.d.ts +0 -7
  162. package/dist/deprecated/common/helpers.d.ts.map +0 -1
  163. package/dist/deprecated/common/helpers.js +0 -47
  164. package/dist/deprecated/demo-extractor/external_domain_metadata.json +0 -38
  165. package/dist/deprecated/demo-extractor/index.d.ts +0 -18
  166. package/dist/deprecated/demo-extractor/index.d.ts.map +0 -1
  167. package/dist/deprecated/demo-extractor/index.js +0 -161
  168. package/dist/deprecated/http/client.d.ts +0 -22
  169. package/dist/deprecated/http/client.d.ts.map +0 -1
  170. package/dist/deprecated/http/client.js +0 -161
  171. package/dist/deprecated/uploader/index.d.ts +0 -35
  172. package/dist/deprecated/uploader/index.d.ts.map +0 -1
  173. package/dist/deprecated/uploader/index.js +0 -161
  174. package/dist/http/types.d.ts +0 -17
  175. package/dist/http/types.d.ts.map +0 -1
  176. package/dist/http/types.js +0 -2
  177. package/dist/multithreading/worker-adapter/worker-adapter.artifacts.test.d.ts +0 -2
  178. package/dist/multithreading/worker-adapter/worker-adapter.artifacts.test.d.ts.map +0 -1
  179. package/dist/multithreading/worker-adapter/worker-adapter.d.ts +0 -91
  180. package/dist/multithreading/worker-adapter/worker-adapter.d.ts.map +0 -1
  181. package/dist/multithreading/worker-adapter/worker-adapter.helpers.d.ts.map +0 -1
  182. package/dist/multithreading/worker-adapter/worker-adapter.helpers.test.d.ts +0 -2
  183. package/dist/multithreading/worker-adapter/worker-adapter.helpers.test.d.ts.map +0 -1
  184. package/dist/multithreading/worker-adapter/worker-adapter.js +0 -745
  185. package/dist/multithreading/worker-adapter/worker-adapter.test.d.ts +0 -2
  186. package/dist/multithreading/worker-adapter/worker-adapter.test.d.ts.map +0 -1
  187. package/dist/multithreading/worker-adapter/worker-adapter.test.js +0 -483
  188. package/dist/state/state.d.ts +0 -30
  189. package/dist/state/state.d.ts.map +0 -1
  190. package/dist/state/state.js +0 -166
  191. /package/dist/multithreading/{worker-adapter/worker-adapter.helpers.js → adapters/loading-adapter.helpers.js} +0 -0
@@ -0,0 +1,75 @@
1
+ import { InitialDomainMapping } from '../types/common';
2
+ import { AirSyncEvent } from '../types/extraction';
3
+ import { ExtractionScope } from '../types/workers';
4
+ import { BaseSdkState, StateInterface } from './state.interfaces';
5
+ /**
6
+ * BaseState owns the state lifecycle shared by every sync mode: connector vs.
7
+ * SDK state separation, fetch/init/post against the platform, the v1->v2
8
+ * migration shim, and the snap-in-version-gated initial domain mapping install.
9
+ *
10
+ * Mode-specific subclasses (`ExtractionState`, `LoadingState`) narrow `sdkState`
11
+ * to their own SDK state shape and add mode-specific setup in their factories.
12
+ *
13
+ * @typeParam ConnectorState - the connector-owned state shape
14
+ * @typeParam SdkState - the SDK bookkeeping shape for this mode
15
+ */
16
+ export declare abstract class BaseState<ConnectorState, SdkState extends BaseSdkState> {
17
+ protected _connectorState: ConnectorState;
18
+ protected _sdkState: SdkState;
19
+ protected _extractionScope: ExtractionScope;
20
+ protected readonly initialSdkState: SdkState;
21
+ protected readonly event: AirSyncEvent;
22
+ private workerUrl;
23
+ private devrevToken;
24
+ private syncUnitId;
25
+ private requestId;
26
+ constructor({ event, initialState }: StateInterface<ConnectorState>, initialSdkState: SdkState);
27
+ /** Connector-owned state. This is what `adapter.state` exposes to snap-in code. */
28
+ get state(): ConnectorState;
29
+ set state(value: ConnectorState);
30
+ /** SDK-internal bookkeeping state. Never exposed to connector code. */
31
+ get sdkState(): SdkState;
32
+ set sdkState(value: SdkState);
33
+ get extractionScope(): ExtractionScope;
34
+ /**
35
+ * Installs the initial domain mapping when the snap-in version in state does
36
+ * not match the version in the event context. Shared by all modes so that a
37
+ * loading run still installs the mapping if extraction has not done so.
38
+ */
39
+ installInitialDomainMappingIfNeeded(initialDomainMapping?: InitialDomainMapping): Promise<void>;
40
+ /**
41
+ * Initializes the state for this adapter instance by fetching from API
42
+ * or creating an initial state if none exists (404).
43
+ *
44
+ * Reads both the v2 `{ connectorState, sdkState }` envelope and a legacy flat
45
+ * v1 blob (connector keys merged with SDK keys), migrating the latter on read.
46
+ * Always persists the v2 envelope going forward.
47
+ * @param initialState The initial connector state provided by the spawn function
48
+ */
49
+ init(initialState: ConnectorState): Promise<void>;
50
+ /**
51
+ * Normalizes a parsed on-disk state into the `{ connectorState, sdkState }`
52
+ * envelope, migrating a legacy flat v1 blob if needed.
53
+ *
54
+ * - v2 envelope (`{ connectorState, sdkState }`): used as-is.
55
+ * - v1 flat blob: SDK-owned keys (`V1_SDK_STATE_KEYS`) split into `sdkState`,
56
+ * everything else becomes connector state.
57
+ * - Malformed envelope (one side present, the other missing) fails loud.
58
+ */
59
+ private normalizeFetchedState;
60
+ /**
61
+ * Updates the state of the adapter by posting to API.
62
+ * Persists the v2 `{ connectorState, sdkState }` envelope.
63
+ * @param {object} state - The connector state to be updated
64
+ */
65
+ postState(state?: ConnectorState): Promise<void>;
66
+ /**
67
+ * Fetches the state of the adapter from API.
68
+ * @return The raw state data from API
69
+ */
70
+ fetchState(): Promise<{
71
+ state: string;
72
+ objects?: string;
73
+ }>;
74
+ }
75
+ //# sourceMappingURL=base-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-state.d.ts","sourceRoot":"","sources":["../../src/state/base-state.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAEnD,OAAO,EAEL,YAAY,EACZ,cAAc,EAEf,MAAM,oBAAoB,CAAC;AAE5B;;;;;;;;;;GAUG;AACH,8BAAsB,SAAS,CAAC,cAAc,EAAE,QAAQ,SAAS,YAAY;IAC3E,SAAS,CAAC,eAAe,EAAE,cAAc,CAAC;IAC1C,SAAS,CAAC,SAAS,EAAE,QAAQ,CAAC;IAC9B,SAAS,CAAC,gBAAgB,EAAE,eAAe,CAAM;IACjD,SAAS,CAAC,QAAQ,CAAC,eAAe,EAAE,QAAQ,CAAC;IAC7C,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IACvC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,SAAS,CAAS;gBAGxB,EAAE,KAAK,EAAE,YAAY,EAAE,EAAE,cAAc,CAAC,cAAc,CAAC,EACvD,eAAe,EAAE,QAAQ;IAY3B,mFAAmF;IACnF,IAAI,KAAK,IAAI,cAAc,CAE1B;IAED,IAAI,KAAK,CAAC,KAAK,EAAE,cAAc,EAE9B;IAED,uEAAuE;IACvE,IAAI,QAAQ,IAAI,QAAQ,CAEvB;IAED,IAAI,QAAQ,CAAC,KAAK,EAAE,QAAQ,EAE3B;IAED,IAAI,eAAe,IAAI,eAAe,CAErC;IAED;;;;OAIG;IACG,mCAAmC,CACvC,oBAAoB,CAAC,EAAE,oBAAoB,GAC1C,OAAO,CAAC,IAAI,CAAC;IAwChB;;;;;;;;OAQG;IACG,IAAI,CAAC,YAAY,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAkDvD;;;;;;;;OAQG;IACH,OAAO,CAAC,qBAAqB;IAyC7B;;;;OAIG;IACG,SAAS,CAAC,KAAK,CAAC,EAAE,cAAc;IA4DtC;;;OAGG;IACG,UAAU,IAAI,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAqBjE"}
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BaseState = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const node_worker_threads_1 = require("node:worker_threads");
9
+ const install_initial_domain_mapping_1 = require("../common/install-initial-domain-mapping");
10
+ const axios_client_internal_1 = require("../http/axios-client-internal");
11
+ const logger_1 = require("../logger/logger");
12
+ const workers_1 = require("../types/workers");
13
+ const state_interfaces_1 = require("./state.interfaces");
14
+ /**
15
+ * BaseState owns the state lifecycle shared by every sync mode: connector vs.
16
+ * SDK state separation, fetch/init/post against the platform, the v1->v2
17
+ * migration shim, and the snap-in-version-gated initial domain mapping install.
18
+ *
19
+ * Mode-specific subclasses (`ExtractionState`, `LoadingState`) narrow `sdkState`
20
+ * to their own SDK state shape and add mode-specific setup in their factories.
21
+ *
22
+ * @typeParam ConnectorState - the connector-owned state shape
23
+ * @typeParam SdkState - the SDK bookkeeping shape for this mode
24
+ */
25
+ class BaseState {
26
+ constructor({ event, initialState }, initialSdkState) {
27
+ this._extractionScope = {};
28
+ this.event = event;
29
+ this.initialSdkState = initialSdkState;
30
+ this._connectorState = initialState;
31
+ this._sdkState = Object.assign({}, initialSdkState);
32
+ this.workerUrl = event.payload.event_context.worker_data_url;
33
+ this.devrevToken = event.context.secrets.service_account_token;
34
+ this.syncUnitId = event.payload.event_context.sync_unit_id;
35
+ this.requestId = event.payload.event_context.request_id_adaas;
36
+ }
37
+ /** Connector-owned state. This is what `adapter.state` exposes to snap-in code. */
38
+ get state() {
39
+ return this._connectorState;
40
+ }
41
+ set state(value) {
42
+ this._connectorState = value;
43
+ }
44
+ /** SDK-internal bookkeeping state. Never exposed to connector code. */
45
+ get sdkState() {
46
+ return this._sdkState;
47
+ }
48
+ set sdkState(value) {
49
+ this._sdkState = value;
50
+ }
51
+ get extractionScope() {
52
+ return this._extractionScope;
53
+ }
54
+ /**
55
+ * Installs the initial domain mapping when the snap-in version in state does
56
+ * not match the version in the event context. Shared by all modes so that a
57
+ * loading run still installs the mapping if extraction has not done so.
58
+ */
59
+ async installInitialDomainMappingIfNeeded(initialDomainMapping) {
60
+ const snapInVersionId = this.event.context.snap_in_version_id;
61
+ const hasSnapInVersionInState = 'snapInVersionId' in this.sdkState;
62
+ const shouldUpdateIDM = !hasSnapInVersionInState ||
63
+ this.sdkState.snapInVersionId !== snapInVersionId;
64
+ if (!shouldUpdateIDM) {
65
+ console.log(`Snap-in version in state matches the version in event context "${snapInVersionId}". Skipping initial domain mapping installation.`);
66
+ return;
67
+ }
68
+ try {
69
+ console.log(`Snap-in version in state "${this.sdkState.snapInVersionId}" does not match the version in event context "${snapInVersionId}". Installing initial domain mapping.`);
70
+ if (initialDomainMapping) {
71
+ await (0, install_initial_domain_mapping_1.installInitialDomainMapping)(this.event, initialDomainMapping);
72
+ this.sdkState.snapInVersionId = snapInVersionId;
73
+ }
74
+ else {
75
+ throw new Error('No initial domain mapping was passed to spawn function. Skipping initial domain mapping installation.');
76
+ }
77
+ }
78
+ catch (error) {
79
+ const errorMessage = `Error while installing initial domain mapping. ${(0, logger_1.serializeError)(error)}`;
80
+ console.error(errorMessage);
81
+ node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage({
82
+ subject: workers_1.WorkerMessageSubject.WorkerMessageFailed,
83
+ payload: { message: errorMessage },
84
+ });
85
+ process.exit(1);
86
+ }
87
+ }
88
+ /**
89
+ * Initializes the state for this adapter instance by fetching from API
90
+ * or creating an initial state if none exists (404).
91
+ *
92
+ * Reads both the v2 `{ connectorState, sdkState }` envelope and a legacy flat
93
+ * v1 blob (connector keys merged with SDK keys), migrating the latter on read.
94
+ * Always persists the v2 envelope going forward.
95
+ * @param initialState The initial connector state provided by the spawn function
96
+ */
97
+ async init(initialState) {
98
+ var _a;
99
+ try {
100
+ const { state: stringifiedState, objects } = await this.fetchState();
101
+ if (!stringifiedState) {
102
+ throw new Error('No state found in response.');
103
+ }
104
+ let parsed;
105
+ try {
106
+ parsed = JSON.parse(stringifiedState);
107
+ }
108
+ catch (error) {
109
+ throw new Error(`Failed to parse state. ${error}`);
110
+ }
111
+ const { connectorState, sdkState } = this.normalizeFetchedState(parsed);
112
+ this.state = connectorState;
113
+ this.sdkState = sdkState;
114
+ console.log('State fetched successfully. Current state', {
115
+ connectorState: (0, logger_1.getPrintableState)(this.state),
116
+ sdkState: (0, logger_1.getPrintableState)(this.sdkState),
117
+ });
118
+ if (objects) {
119
+ try {
120
+ this._extractionScope = JSON.parse(objects);
121
+ }
122
+ catch (error) {
123
+ console.warn(`Failed to parse extractionScope. ${error}`);
124
+ }
125
+ }
126
+ }
127
+ catch (error) {
128
+ if (axios_1.default.isAxiosError(error) && ((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
129
+ console.log('State not found. Initializing state with initial state.');
130
+ this.state = initialState;
131
+ this.sdkState = Object.assign({}, this.initialSdkState);
132
+ await this.postState();
133
+ }
134
+ else {
135
+ const errorMessage = `Failed to init state. ${(0, logger_1.serializeError)(error)}`;
136
+ console.error(errorMessage);
137
+ node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage({
138
+ subject: workers_1.WorkerMessageSubject.WorkerMessageFailed,
139
+ payload: { message: errorMessage },
140
+ });
141
+ process.exit(1);
142
+ }
143
+ }
144
+ }
145
+ /**
146
+ * Normalizes a parsed on-disk state into the `{ connectorState, sdkState }`
147
+ * envelope, migrating a legacy flat v1 blob if needed.
148
+ *
149
+ * - v2 envelope (`{ connectorState, sdkState }`): used as-is.
150
+ * - v1 flat blob: SDK-owned keys (`V1_SDK_STATE_KEYS`) split into `sdkState`,
151
+ * everything else becomes connector state.
152
+ * - Malformed envelope (one side present, the other missing) fails loud.
153
+ */
154
+ normalizeFetchedState(parsed) {
155
+ if (parsed === null || typeof parsed !== 'object') {
156
+ throw new Error('Fetched state is not a JSON object.');
157
+ }
158
+ const record = parsed;
159
+ const hasConnector = 'connectorState' in record;
160
+ const hasSdk = 'sdkState' in record;
161
+ if (hasConnector || hasSdk) {
162
+ if (!hasConnector || !hasSdk) {
163
+ throw new Error('Malformed state envelope: expected both "connectorState" and "sdkState".');
164
+ }
165
+ return {
166
+ connectorState: record.connectorState,
167
+ sdkState: Object.assign(Object.assign({}, this.initialSdkState), record.sdkState),
168
+ };
169
+ }
170
+ // Legacy flat v1 blob: split known SDK keys out of the connector state.
171
+ const connectorState = {};
172
+ const sdkState = {};
173
+ for (const [key, value] of Object.entries(record)) {
174
+ if (state_interfaces_1.V1_SDK_STATE_KEYS.has(key)) {
175
+ sdkState[key] = value;
176
+ }
177
+ else {
178
+ connectorState[key] = value;
179
+ }
180
+ }
181
+ return {
182
+ connectorState: connectorState,
183
+ sdkState: Object.assign(Object.assign({}, this.initialSdkState), sdkState),
184
+ };
185
+ }
186
+ /**
187
+ * Updates the state of the adapter by posting to API.
188
+ * Persists the v2 `{ connectorState, sdkState }` envelope.
189
+ * @param {object} state - The connector state to be updated
190
+ */
191
+ async postState(state) {
192
+ const url = this.workerUrl + '.update';
193
+ this.state = state || this.state;
194
+ const envelope = {
195
+ connectorState: this.state,
196
+ sdkState: this.sdkState,
197
+ };
198
+ let stringifiedState;
199
+ try {
200
+ stringifiedState = JSON.stringify(envelope);
201
+ }
202
+ catch (error) {
203
+ const errorMessage = `Failed to stringify state. ${(0, logger_1.serializeError)(error)}`;
204
+ console.error(errorMessage);
205
+ node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage({
206
+ subject: workers_1.WorkerMessageSubject.WorkerMessageFailed,
207
+ payload: { message: errorMessage },
208
+ });
209
+ process.exit(1);
210
+ }
211
+ try {
212
+ await axios_client_internal_1.axiosClient.post(url, {
213
+ state: stringifiedState,
214
+ }, {
215
+ headers: {
216
+ Authorization: this.devrevToken,
217
+ },
218
+ params: {
219
+ sync_unit: this.syncUnitId,
220
+ request_id: this.requestId,
221
+ },
222
+ });
223
+ console.log('State updated successfully to', {
224
+ connectorState: (0, logger_1.getPrintableState)(this.state),
225
+ sdkState: (0, logger_1.getPrintableState)(this.sdkState),
226
+ });
227
+ }
228
+ catch (error) {
229
+ const errorMessage = `Failed to update the state. ${(0, logger_1.serializeError)(error)}`;
230
+ console.error(errorMessage);
231
+ node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage({
232
+ subject: workers_1.WorkerMessageSubject.WorkerMessageFailed,
233
+ payload: { message: errorMessage },
234
+ });
235
+ process.exit(1);
236
+ }
237
+ }
238
+ /**
239
+ * Fetches the state of the adapter from API.
240
+ * @return The raw state data from API
241
+ */
242
+ async fetchState() {
243
+ var _a, _b;
244
+ console.log(`Fetching state with sync unit id ${this.syncUnitId} and request id ${this.requestId}.`);
245
+ const url = this.workerUrl + '.get';
246
+ const response = await axios_client_internal_1.axiosClient.get(url, {
247
+ headers: {
248
+ Authorization: this.devrevToken,
249
+ },
250
+ params: {
251
+ sync_unit: this.syncUnitId,
252
+ request_id: this.requestId,
253
+ },
254
+ });
255
+ return {
256
+ state: (_a = response.data) === null || _a === void 0 ? void 0 : _a.state,
257
+ objects: (_b = response.data) === null || _b === void 0 ? void 0 : _b.objects,
258
+ };
259
+ }
260
+ }
261
+ exports.BaseState = BaseState;
@@ -0,0 +1,29 @@
1
+ import { BaseState } from './base-state';
2
+ import { ExtractionSdkState, StateInterface } from './state.interfaces';
3
+ /**
4
+ * ExtractionState is the per-mode state for extraction workers. It narrows
5
+ * `sdkState` to `ExtractionSdkState` (extraction boundaries + attachments
6
+ * bookkeeping) on top of the shared lifecycle provided by `BaseState`.
7
+ */
8
+ export declare class ExtractionState<ConnectorState> extends BaseState<ConnectorState, ExtractionSdkState> {
9
+ constructor(params: StateInterface<ConnectorState>);
10
+ /**
11
+ * Resolves the extraction window onto the event context.
12
+ *
13
+ * On StartExtractingMetadata: resolve fresh from the TimeValue objects in the
14
+ * event context and cache them as pending boundaries (always overwrite).
15
+ * On all other events: reuse the pending boundaries cached during
16
+ * StartExtractingMetadata. Finally, validate that extract_from < extract_to.
17
+ */
18
+ resolveExtractionWindow(): void;
19
+ }
20
+ /**
21
+ * Creates and initializes an `ExtractionState` for an extraction worker.
22
+ *
23
+ * For non-stateless events this fetches/migrates persisted state, installs the
24
+ * initial domain mapping if the snap-in version changed, then resolves the
25
+ * extraction window (time-value resolution + pending boundary reuse) and
26
+ * validates it.
27
+ */
28
+ export declare function createExtractionState<ConnectorState>({ event, initialState, initialDomainMapping, options, }: StateInterface<ConnectorState>): Promise<ExtractionState<ConnectorState>>;
29
+ //# sourceMappingURL=extraction-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extraction-state.d.ts","sourceRoot":"","sources":["../../src/state/extraction-state.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EACL,kBAAkB,EAElB,cAAc,EACf,MAAM,oBAAoB,CAAC;AAE5B;;;;GAIG;AACH,qBAAa,eAAe,CAAC,cAAc,CAAE,SAAQ,SAAS,CAC5D,cAAc,EACd,kBAAkB,CACnB;gBACa,MAAM,EAAE,cAAc,CAAC,cAAc,CAAC;IAIlD;;;;;;;OAOG;IACH,uBAAuB,IAAI,IAAI;CA8EhC;AAED;;;;;;;GAOG;AACH,wBAAsB,qBAAqB,CAAC,cAAc,EAAE,EAC1D,KAAK,EACL,YAAY,EACZ,oBAAoB,EACpB,OAAO,GACR,EAAE,cAAc,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC,CAkB3E"}
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExtractionState = void 0;
4
+ exports.createExtractionState = createExtractionState;
5
+ const node_worker_threads_1 = require("node:worker_threads");
6
+ const constants_1 = require("../common/constants");
7
+ const time_value_resolver_1 = require("../common/time-value-resolver");
8
+ const logger_1 = require("../logger/logger");
9
+ const extraction_1 = require("../types/extraction");
10
+ const workers_1 = require("../types/workers");
11
+ const base_state_1 = require("./base-state");
12
+ const state_interfaces_1 = require("./state.interfaces");
13
+ /**
14
+ * ExtractionState is the per-mode state for extraction workers. It narrows
15
+ * `sdkState` to `ExtractionSdkState` (extraction boundaries + attachments
16
+ * bookkeeping) on top of the shared lifecycle provided by `BaseState`.
17
+ */
18
+ class ExtractionState extends base_state_1.BaseState {
19
+ constructor(params) {
20
+ super(params, state_interfaces_1.initialExtractionSdkState);
21
+ }
22
+ /**
23
+ * Resolves the extraction window onto the event context.
24
+ *
25
+ * On StartExtractingMetadata: resolve fresh from the TimeValue objects in the
26
+ * event context and cache them as pending boundaries (always overwrite).
27
+ * On all other events: reuse the pending boundaries cached during
28
+ * StartExtractingMetadata. Finally, validate that extract_from < extract_to.
29
+ */
30
+ resolveExtractionWindow() {
31
+ const eventContext = this.event.payload.event_context;
32
+ const sdkState = this.sdkState;
33
+ if (this.event.payload.event_type === extraction_1.EventType.StartExtractingMetadata) {
34
+ const timeFields = [
35
+ {
36
+ source: 'extraction_start_time',
37
+ target: 'extract_from',
38
+ pending: 'pendingWorkersOldest',
39
+ },
40
+ {
41
+ source: 'extraction_end_time',
42
+ target: 'extract_to',
43
+ pending: 'pendingWorkersNewest',
44
+ },
45
+ ];
46
+ for (const { source, target, pending } of timeFields) {
47
+ const timeValue = eventContext[source];
48
+ if (timeValue && timeValue.type) {
49
+ try {
50
+ const resolved = (0, time_value_resolver_1.resolveTimeValue)(timeValue, sdkState);
51
+ eventContext[target] = resolved;
52
+ sdkState[pending] = resolved;
53
+ console.log(`Resolved ${target} to ${resolved}. Stored in ${pending}.`);
54
+ }
55
+ catch (error) {
56
+ const errorMessage = `Failed to resolve ${source}: ${(0, logger_1.serializeError)(error)}`;
57
+ console.error(errorMessage);
58
+ node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage({
59
+ subject: workers_1.WorkerMessageSubject.WorkerMessageFailed,
60
+ payload: { message: errorMessage },
61
+ });
62
+ process.exit(1);
63
+ }
64
+ }
65
+ }
66
+ }
67
+ else {
68
+ // Non-StartExtractingMetadata events: reuse pending values from state
69
+ if (sdkState.pendingWorkersOldest) {
70
+ eventContext.extract_from = sdkState.pendingWorkersOldest;
71
+ console.log(`Reusing pendingWorkersOldest as extract_from: ${sdkState.pendingWorkersOldest}.`);
72
+ }
73
+ else {
74
+ console.log('pendingWorkersOldest is not set in state. extract_from will not be populated for this invocation.');
75
+ }
76
+ if (sdkState.pendingWorkersNewest) {
77
+ eventContext.extract_to = sdkState.pendingWorkersNewest;
78
+ console.log(`Reusing pendingWorkersNewest as extract_to: ${sdkState.pendingWorkersNewest}.`);
79
+ }
80
+ else {
81
+ console.log('pendingWorkersNewest is not set in state. extract_to will not be populated for this invocation.');
82
+ }
83
+ }
84
+ // Validate that extract_from is before extract_to
85
+ if (eventContext.extract_from && eventContext.extract_to) {
86
+ if (eventContext.extract_from >= eventContext.extract_to) {
87
+ const errorMessage = `Invalid extraction window: extract_from (${eventContext.extract_from}) must be older than extract_to (${eventContext.extract_to}). This indicates an error in the platform.`;
88
+ console.error(errorMessage);
89
+ node_worker_threads_1.parentPort === null || node_worker_threads_1.parentPort === void 0 ? void 0 : node_worker_threads_1.parentPort.postMessage({
90
+ subject: workers_1.WorkerMessageSubject.WorkerMessageFailed,
91
+ payload: { message: errorMessage },
92
+ });
93
+ process.exit(1);
94
+ }
95
+ }
96
+ }
97
+ }
98
+ exports.ExtractionState = ExtractionState;
99
+ /**
100
+ * Creates and initializes an `ExtractionState` for an extraction worker.
101
+ *
102
+ * For non-stateless events this fetches/migrates persisted state, installs the
103
+ * initial domain mapping if the snap-in version changed, then resolves the
104
+ * extraction window (time-value resolution + pending boundary reuse) and
105
+ * validates it.
106
+ */
107
+ async function createExtractionState({ event, initialState, initialDomainMapping, options, }) {
108
+ // Deep clone the initial state to avoid mutating the original state
109
+ const deepCloneInitialState = structuredClone(initialState);
110
+ const state = new ExtractionState({
111
+ event,
112
+ initialState: deepCloneInitialState,
113
+ initialDomainMapping,
114
+ options,
115
+ });
116
+ if (!constants_1.STATELESS_EVENT_TYPES.includes(event.payload.event_type)) {
117
+ await state.init(deepCloneInitialState);
118
+ await state.installInitialDomainMappingIfNeeded(initialDomainMapping);
119
+ state.resolveExtractionWindow();
120
+ }
121
+ return state;
122
+ }
@@ -0,0 +1,19 @@
1
+ import { BaseState } from './base-state';
2
+ import { LoadingSdkState, StateInterface } from './state.interfaces';
3
+ /**
4
+ * LoadingState is the per-mode state for loading workers. It narrows `sdkState`
5
+ * to `LoadingSdkState` (files-to-load bookkeeping) on top of the shared
6
+ * lifecycle provided by `BaseState`.
7
+ */
8
+ export declare class LoadingState<ConnectorState> extends BaseState<ConnectorState, LoadingSdkState> {
9
+ constructor(params: StateInterface<ConnectorState>);
10
+ }
11
+ /**
12
+ * Creates and initializes a `LoadingState` for a loading worker.
13
+ *
14
+ * For non-stateless events this fetches/migrates persisted state and installs
15
+ * the initial domain mapping if the snap-in version changed. Loading has no
16
+ * extraction-window resolution, so the factory is otherwise minimal.
17
+ */
18
+ export declare function createLoadingState<ConnectorState>({ event, initialState, initialDomainMapping, options, }: StateInterface<ConnectorState>): Promise<LoadingState<ConnectorState>>;
19
+ //# sourceMappingURL=loading-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loading-state.d.ts","sourceRoot":"","sources":["../../src/state/loading-state.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAEL,eAAe,EACf,cAAc,EACf,MAAM,oBAAoB,CAAC;AAE5B;;;;GAIG;AACH,qBAAa,YAAY,CAAC,cAAc,CAAE,SAAQ,SAAS,CACzD,cAAc,EACd,eAAe,CAChB;gBACa,MAAM,EAAE,cAAc,CAAC,cAAc,CAAC;CAGnD;AAED;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CAAC,cAAc,EAAE,EACvD,KAAK,EACL,YAAY,EACZ,oBAAoB,EACpB,OAAO,GACR,EAAE,cAAc,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC,CAiBxE"}
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LoadingState = void 0;
4
+ exports.createLoadingState = createLoadingState;
5
+ const constants_1 = require("../common/constants");
6
+ const base_state_1 = require("./base-state");
7
+ const state_interfaces_1 = require("./state.interfaces");
8
+ /**
9
+ * LoadingState is the per-mode state for loading workers. It narrows `sdkState`
10
+ * to `LoadingSdkState` (files-to-load bookkeeping) on top of the shared
11
+ * lifecycle provided by `BaseState`.
12
+ */
13
+ class LoadingState extends base_state_1.BaseState {
14
+ constructor(params) {
15
+ super(params, state_interfaces_1.initialLoadingSdkState);
16
+ }
17
+ }
18
+ exports.LoadingState = LoadingState;
19
+ /**
20
+ * Creates and initializes a `LoadingState` for a loading worker.
21
+ *
22
+ * For non-stateless events this fetches/migrates persisted state and installs
23
+ * the initial domain mapping if the snap-in version changed. Loading has no
24
+ * extraction-window resolution, so the factory is otherwise minimal.
25
+ */
26
+ async function createLoadingState({ event, initialState, initialDomainMapping, options, }) {
27
+ // Deep clone the initial state to avoid mutating the original state
28
+ const deepCloneInitialState = structuredClone(initialState);
29
+ const state = new LoadingState({
30
+ event,
31
+ initialState: deepCloneInitialState,
32
+ initialDomainMapping,
33
+ options,
34
+ });
35
+ if (!constants_1.STATELESS_EVENT_TYPES.includes(event.payload.event_type)) {
36
+ await state.init(deepCloneInitialState);
37
+ await state.installInitialDomainMappingIfNeeded(initialDomainMapping);
38
+ }
39
+ return state;
40
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=state.extract-window.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.extract-window.test.d.ts","sourceRoot":"","sources":["../../src/state/state.extract-window.test.ts"],"names":[],"mappings":""}