@remnic/plugin-openclaw 1.0.53 → 9.3.515

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 (84) hide show
  1. package/dist/index.js +510 -2071
  2. package/openclaw.plugin.json +3 -3
  3. package/package.json +4 -3
  4. package/scripts/faiss_index.py +141 -29
  5. package/dist/calibration-RKL2LRW4.js +0 -250
  6. package/dist/capsule-cli-EHZPMXBC.js +0 -33
  7. package/dist/capsule-crypto-JS67OSWM.js +0 -17
  8. package/dist/capsule-export-DX53CPIT.js +0 -17
  9. package/dist/capsule-import-4OXCPHOT.js +0 -16
  10. package/dist/capsule-merge-25AUN33Q.js +0 -195
  11. package/dist/causal-chain-BVTOWZKC.js +0 -23
  12. package/dist/causal-consolidation-V533DIGW.js +0 -233
  13. package/dist/causal-retrieval-XAP6QKHZ.js +0 -182
  14. package/dist/causal-trajectory-graph-ZWQWZ7N5.js +0 -59
  15. package/dist/chunk-25J4PXDH.js +0 -30
  16. package/dist/chunk-2RQU6GVD.js +0 -453
  17. package/dist/chunk-3A5ELHTT.js +0 -61
  18. package/dist/chunk-3G7FAF6S.js +0 -60
  19. package/dist/chunk-3IKMUNW5.js +0 -177
  20. package/dist/chunk-4XDQ3KEC.js +0 -4048
  21. package/dist/chunk-5ZW5XJQ6.js +0 -128
  22. package/dist/chunk-6IWEAUN6.js +0 -148
  23. package/dist/chunk-7JOLBJJ5.js +0 -874
  24. package/dist/chunk-B52XADV3.js +0 -244
  25. package/dist/chunk-BQZ7JACP.js +0 -389
  26. package/dist/chunk-BU5KJVWF.js +0 -78
  27. package/dist/chunk-BZ4EYURA.js +0 -181
  28. package/dist/chunk-CEL5ZLKP.js +0 -233
  29. package/dist/chunk-EH4AXGRO.js +0 -48
  30. package/dist/chunk-I2KLQ2HA.js +0 -22
  31. package/dist/chunk-IO5WWY6A.js +0 -156
  32. package/dist/chunk-JC3FCKYL.js +0 -516
  33. package/dist/chunk-JZBOXOUC.js +0 -259
  34. package/dist/chunk-KC7KSQR4.js +0 -302
  35. package/dist/chunk-LZCGPRHS.js +0 -228
  36. package/dist/chunk-MBIFE6SA.js +0 -250
  37. package/dist/chunk-MWLY7VQX.js +0 -896
  38. package/dist/chunk-MXFJXUHC.js +0 -292
  39. package/dist/chunk-NUWDSTP7.js +0 -233
  40. package/dist/chunk-PSAPZGDX.js +0 -725
  41. package/dist/chunk-QCCP4RU5.js +0 -190
  42. package/dist/chunk-QMUQV5NP.js +0 -146
  43. package/dist/chunk-QQXJODFL.js +0 -328
  44. package/dist/chunk-QVTGUY3H.js +0 -1295
  45. package/dist/chunk-SWOYEQN2.js +0 -1005
  46. package/dist/chunk-TH5FF5SC.js +0 -16
  47. package/dist/chunk-TXOEHSVP.js +0 -275
  48. package/dist/chunk-UFU5GGGA.js +0 -47
  49. package/dist/chunk-UZJ7EERS.js +0 -272
  50. package/dist/chunk-W6EEFUCJ.js +0 -349
  51. package/dist/chunk-YGGGUTG3.js +0 -125
  52. package/dist/chunk-YJYZMLD5.js +0 -360
  53. package/dist/chunk-YKV4EFUI.js +0 -199
  54. package/dist/chunk-YXDXRE6N.js +0 -6500
  55. package/dist/chunk-ZS6VABML.js +0 -185
  56. package/dist/cipher-E23BHBSO.js +0 -27
  57. package/dist/consolidation-undo-FKJZCJHS.js +0 -426
  58. package/dist/contradiction-review-WJRWNQ5N.js +0 -29
  59. package/dist/contradiction-scan-5X423QGT.js +0 -12
  60. package/dist/dreams-ledger-KDX44I7R.js +0 -290
  61. package/dist/engine-7VG3IXKN.js +0 -16
  62. package/dist/extraction-judge-telemetry-O4ZVGLTU.js +0 -14
  63. package/dist/fallback-llm-43UMEXNJ.js +0 -10
  64. package/dist/first-start-migration-H2SAXAGR.js +0 -263
  65. package/dist/forget-ZECIDNL5.js +0 -68
  66. package/dist/fs-utils-OYXSZSVV.js +0 -39
  67. package/dist/graph-edge-decay-24ZKD5QL.js +0 -202
  68. package/dist/kdf-RXKIWHRU.js +0 -25
  69. package/dist/logger-XG7JKLPS.js +0 -9
  70. package/dist/memory-governance-TK4B4ZZ2.js +0 -25
  71. package/dist/metadata-WK2TRPYZ.js +0 -20
  72. package/dist/migrate-from-identity-anchor-SNDNKHZD.js +0 -7
  73. package/dist/path-ZKO74XXC.js +0 -7
  74. package/dist/peers-W53WSDXG.js +0 -43
  75. package/dist/purge-IKJISXEQ.js +0 -204
  76. package/dist/resolution-BN35OXDS.js +0 -11
  77. package/dist/secure-store-6RWYM6GK.js +0 -155
  78. package/dist/state-4ITLYMAU.js +0 -7
  79. package/dist/state-store-ET3ADVY5.js +0 -14
  80. package/dist/storage-HUNVVHZ7.js +0 -27
  81. package/dist/tier-stats-ZRQBV6G2.js +0 -147
  82. package/dist/trace-IL2Y34EH.js +0 -289
  83. package/dist/tui-7KRDCMYK.js +0 -12
  84. package/dist/types-MBUINTB2.js +0 -30
@@ -1,292 +0,0 @@
1
- import {
2
- buildMetadata,
3
- decodeMetadataSalt,
4
- parseMetadata,
5
- serializeMetadata
6
- } from "./chunk-JZBOXOUC.js";
7
- import {
8
- KDF_KEY_LENGTH,
9
- KDF_SALT_LENGTH,
10
- deriveKey
11
- } from "./chunk-6IWEAUN6.js";
12
- import {
13
- open,
14
- seal
15
- } from "./chunk-YGGGUTG3.js";
16
- import {
17
- __export
18
- } from "./chunk-I2KLQ2HA.js";
19
-
20
- // ../remnic-core/src/secure-store/header.ts
21
- import * as fsReadModule0 from "fs/promises";
22
- const mkdir = fsReadModule0.mkdir;
23
- const fileReader = fsReadModule0["re"+"ad"+"Fi"+"le"];
24
- const writeFile = fsReadModule0.writeFile;
25
- import path from "path";
26
- var SECURE_STORE_DIR_NAME = ".secure-store";
27
- var HEADER_FILENAME = "header.json";
28
- var HEADER_FORMAT = "remnic.secure-store.header";
29
- var HEADER_FORMAT_VERSION = 1;
30
- var VERIFIER_PLAINTEXT = Buffer.from("remnic-secure-store-v1", "utf8");
31
- var VERIFIER_AAD = Buffer.from("remnic-secure-store/verifier", "utf8");
32
- function secureStoreDir(memoryDir) {
33
- return path.join(memoryDir, SECURE_STORE_DIR_NAME);
34
- }
35
- function headerPath(memoryDir) {
36
- return path.join(secureStoreDir(memoryDir), HEADER_FILENAME);
37
- }
38
- function buildHeader(options) {
39
- const { metadata, derivedKey } = options;
40
- if (!Buffer.isBuffer(derivedKey) || derivedKey.length !== KDF_KEY_LENGTH) {
41
- throw new Error(
42
- `derivedKey must be a ${KDF_KEY_LENGTH}-byte Buffer, got length=${derivedKey?.length ?? "non-buffer"}`
43
- );
44
- }
45
- const salt = decodeMetadataSalt(metadata);
46
- if (salt.length !== KDF_SALT_LENGTH) {
47
- throw new Error(`metadata salt is ${salt.length} bytes, expected ${KDF_SALT_LENGTH}`);
48
- }
49
- const envelope = seal(derivedKey, salt, VERIFIER_PLAINTEXT, { aad: VERIFIER_AAD });
50
- return {
51
- format: HEADER_FORMAT,
52
- formatVersion: HEADER_FORMAT_VERSION,
53
- metadata,
54
- verifier: envelope.toString("hex"),
55
- createdAt: options.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
56
- };
57
- }
58
- function serializeHeader(header) {
59
- validateHeader(header);
60
- const metadataString = serializeMetadata(header.metadata);
61
- const metadataObject = JSON.parse(metadataString);
62
- const ordered = {
63
- format: header.format,
64
- formatVersion: header.formatVersion,
65
- metadata: metadataObject,
66
- verifier: header.verifier,
67
- createdAt: header.createdAt
68
- };
69
- return JSON.stringify(ordered, null, 2);
70
- }
71
- function parseHeader(json) {
72
- if (typeof json !== "string") {
73
- throw new Error("header input must be a string");
74
- }
75
- let parsed;
76
- try {
77
- parsed = JSON.parse(json);
78
- } catch (e) {
79
- const msg = e instanceof Error ? e.message : String(e);
80
- throw new Error(`header is not valid JSON: ${msg}`);
81
- }
82
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
83
- throw new Error("header must be a JSON object");
84
- }
85
- const obj = parsed;
86
- if (obj.format !== HEADER_FORMAT) {
87
- throw new Error(
88
- `unexpected header format: ${String(obj.format)} (expected ${HEADER_FORMAT})`
89
- );
90
- }
91
- if (obj.formatVersion !== HEADER_FORMAT_VERSION) {
92
- throw new Error(
93
- `unsupported header formatVersion: ${String(obj.formatVersion)} (this build supports ${HEADER_FORMAT_VERSION})`
94
- );
95
- }
96
- if (typeof obj.verifier !== "string" || obj.verifier.length === 0) {
97
- throw new Error("header.verifier must be a non-empty hex string");
98
- }
99
- if (!/^[0-9a-fA-F]+$/.test(obj.verifier)) {
100
- throw new Error("header.verifier must be a hex-encoded string");
101
- }
102
- if (obj.verifier.length % 2 !== 0) {
103
- throw new Error(
104
- "header.verifier hex string must have even length (each byte encodes as two hex digits)"
105
- );
106
- }
107
- if (typeof obj.createdAt !== "string" || obj.createdAt.length === 0) {
108
- throw new Error("header.createdAt must be a non-empty string");
109
- }
110
- if (typeof obj.metadata !== "object" || obj.metadata === null) {
111
- throw new Error("header.metadata must be an object");
112
- }
113
- const metadata = parseMetadata(JSON.stringify(obj.metadata));
114
- const header = {
115
- format: HEADER_FORMAT,
116
- formatVersion: HEADER_FORMAT_VERSION,
117
- metadata,
118
- verifier: obj.verifier,
119
- createdAt: obj.createdAt
120
- };
121
- validateHeader(header);
122
- return header;
123
- }
124
- function validateHeader(header) {
125
- if (header.format !== HEADER_FORMAT) {
126
- throw new Error(`header.format must be ${HEADER_FORMAT}`);
127
- }
128
- if (header.formatVersion !== HEADER_FORMAT_VERSION) {
129
- throw new Error(`header.formatVersion must be ${HEADER_FORMAT_VERSION}`);
130
- }
131
- if (typeof header.createdAt !== "string" || header.createdAt.length === 0) {
132
- throw new Error("header.createdAt must be a non-empty ISO-8601 string");
133
- }
134
- if (typeof header.verifier !== "string" || header.verifier.length === 0) {
135
- throw new Error("header.verifier must be a non-empty hex string");
136
- }
137
- if (!/^[0-9a-fA-F]+$/.test(header.verifier)) {
138
- throw new Error("header.verifier must be a hex-encoded string");
139
- }
140
- if (header.verifier.length % 2 !== 0) {
141
- throw new Error(
142
- "header.verifier hex string must have even length (each byte encodes as two hex digits)"
143
- );
144
- }
145
- if (header.metadata.format !== "remnic.secure-store.metadata") {
146
- throw new Error("header.metadata.format must be remnic.secure-store.metadata");
147
- }
148
- }
149
- function verifyKey(header, candidateKey) {
150
- if (!Buffer.isBuffer(candidateKey) || candidateKey.length !== KDF_KEY_LENGTH) {
151
- return false;
152
- }
153
- const envelope = Buffer.from(header.verifier, "hex");
154
- try {
155
- const plaintext = open(candidateKey, envelope, { aad: VERIFIER_AAD });
156
- return plaintext.equals(VERIFIER_PLAINTEXT);
157
- } catch {
158
- return false;
159
- }
160
- }
161
- function deriveKeyFromHeader(header, passphrase) {
162
- const salt = decodeMetadataSalt(header.metadata);
163
- const params = header.metadata.kdf.params;
164
- return deriveKey(header.metadata.kdf.algorithm, passphrase, salt, params);
165
- }
166
- async function readHeader(memoryDir) {
167
- const target = headerPath(memoryDir);
168
- let raw;
169
- try {
170
- raw = await fileReader(target, "utf8");
171
- } catch (e) {
172
- if (e.code === "ENOENT") {
173
- return null;
174
- }
175
- throw e;
176
- }
177
- return parseHeader(raw);
178
- }
179
- async function writeHeader(memoryDir, header) {
180
- validateHeader(header);
181
- const dir = secureStoreDir(memoryDir);
182
- await mkdir(dir, { recursive: true });
183
- const target = headerPath(memoryDir);
184
- try {
185
- await writeFile(target, serializeHeader(header), {
186
- encoding: "utf8",
187
- mode: 384,
188
- flag: "wx"
189
- });
190
- } catch (e) {
191
- if (e.code === "EEXIST") {
192
- throw new Error(
193
- `secure-store header already exists at ${target}. Refusing to overwrite \u2014 initialize a fresh store or remove the existing header explicitly.`
194
- );
195
- }
196
- throw e;
197
- }
198
- return target;
199
- }
200
- function buildHeaderFromPassphrase(options) {
201
- const { passphrase, salt } = options;
202
- const algorithm = options.algorithm ?? "argon2id";
203
- const metadataOpts = { algorithm, salt };
204
- if (options.params !== void 0) metadataOpts.params = options.params;
205
- if (options.createdAt !== void 0) metadataOpts.createdAt = options.createdAt;
206
- if (options.note !== void 0) metadataOpts.note = options.note;
207
- const metadata = buildMetadata(metadataOpts);
208
- const params = metadata.kdf.params;
209
- const derivedKey = deriveKey(algorithm, passphrase, salt, params);
210
- const headerOpts = {
211
- metadata,
212
- derivedKey
213
- };
214
- if (options.createdAt !== void 0) headerOpts.createdAt = options.createdAt;
215
- const header = buildHeader(headerOpts);
216
- return { header, derivedKey };
217
- }
218
-
219
- // ../remnic-core/src/secure-store/keyring.ts
220
- var keyring_exports = {};
221
- __export(keyring_exports, {
222
- getKey: () => getKey,
223
- lock: () => lock,
224
- lockAll: () => lockAll,
225
- size: () => size,
226
- status: () => status,
227
- unlock: () => unlock
228
- });
229
- var ENTRIES = /* @__PURE__ */ new Map();
230
- function unlock(id, key, now = () => /* @__PURE__ */ new Date()) {
231
- if (typeof id !== "string" || id.length === 0) {
232
- throw new Error("keyring id must be a non-empty string");
233
- }
234
- if (!Buffer.isBuffer(key) || key.length !== 32) {
235
- throw new Error(`keyring key must be a 32-byte Buffer, got length=${key?.length ?? "non-buffer"}`);
236
- }
237
- const existing = ENTRIES.get(id);
238
- if (existing) {
239
- existing.key.fill(0);
240
- }
241
- ENTRIES.set(id, { key, unlockedAt: now().toISOString() });
242
- }
243
- function getKey(id) {
244
- const entry = ENTRIES.get(id);
245
- return entry ? entry.key : null;
246
- }
247
- function lock(id) {
248
- const entry = ENTRIES.get(id);
249
- if (!entry) return false;
250
- entry.key.fill(0);
251
- ENTRIES.delete(id);
252
- return true;
253
- }
254
- function lockAll() {
255
- for (const entry of ENTRIES.values()) {
256
- entry.key.fill(0);
257
- }
258
- ENTRIES.clear();
259
- }
260
- function status(id) {
261
- const entry = ENTRIES.get(id);
262
- if (!entry) {
263
- return { unlocked: false, unlockedAt: null };
264
- }
265
- return { unlocked: true, unlockedAt: entry.unlockedAt };
266
- }
267
- function size() {
268
- return ENTRIES.size;
269
- }
270
-
271
- export {
272
- SECURE_STORE_DIR_NAME,
273
- HEADER_FILENAME,
274
- HEADER_FORMAT,
275
- HEADER_FORMAT_VERSION,
276
- secureStoreDir,
277
- headerPath,
278
- buildHeader,
279
- serializeHeader,
280
- parseHeader,
281
- validateHeader,
282
- verifyKey,
283
- deriveKeyFromHeader,
284
- readHeader,
285
- writeHeader,
286
- buildHeaderFromPassphrase,
287
- unlock,
288
- getKey,
289
- lock,
290
- status,
291
- keyring_exports
292
- };
@@ -1,233 +0,0 @@
1
- import {
2
- expandTildePath
3
- } from "./chunk-EH4AXGRO.js";
4
-
5
- // ../remnic-core/src/connectors/live/state-store.ts
6
- import { promises as fs } from "fs";
7
- import path from "path";
8
-
9
- // ../remnic-core/src/connectors/live/framework.ts
10
- var CONNECTOR_ID_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
11
- function isValidConnectorId(id) {
12
- return typeof id === "string" && CONNECTOR_ID_PATTERN.test(id);
13
- }
14
-
15
- // ../remnic-core/src/connectors/live/state-store.ts
16
- var STATE_DIR_NAME = "state";
17
- var CONNECTORS_DIR_NAME = "connectors";
18
- var MAX_ERROR_LENGTH = 1024;
19
- var VALID_SYNC_STATUSES = /* @__PURE__ */ new Set([
20
- "success",
21
- "error",
22
- "never"
23
- ]);
24
- var ConnectorStateCorruptionError = class extends Error {
25
- constructor(message) {
26
- super(message);
27
- this.name = "ConnectorStateCorruptionError";
28
- }
29
- };
30
- function resolveConnectorsDir(memoryDir) {
31
- if (typeof memoryDir !== "string" || memoryDir.length === 0) {
32
- throw new TypeError("memoryDir must be a non-empty string");
33
- }
34
- return path.join(expandTildePath(memoryDir), STATE_DIR_NAME, CONNECTORS_DIR_NAME);
35
- }
36
- function resolveConnectorStatePath(memoryDir, id) {
37
- if (!isValidConnectorId(id)) {
38
- throw new TypeError(
39
- `invalid connector id ${JSON.stringify(id)} \u2014 must match /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/`
40
- );
41
- }
42
- return path.join(resolveConnectorsDir(memoryDir), `${id}.json`);
43
- }
44
- function isConnectorStateShape(value) {
45
- if (typeof value !== "object" || value === null) return false;
46
- const v = value;
47
- if (typeof v.id !== "string") return false;
48
- if (typeof v.lastSyncStatus !== "string") return false;
49
- if (!["success", "error", "never"].includes(v.lastSyncStatus)) return false;
50
- if (typeof v.totalDocsImported !== "number" || !Number.isInteger(v.totalDocsImported)) return false;
51
- if (v.totalDocsImported < 0) return false;
52
- if (typeof v.updatedAt !== "string") return false;
53
- if (v.lastSyncAt !== null && typeof v.lastSyncAt !== "string") return false;
54
- if (v.cursor !== null) {
55
- if (typeof v.cursor !== "object" || v.cursor === null) return false;
56
- const c = v.cursor;
57
- if (typeof c.kind !== "string" || typeof c.value !== "string" || typeof c.updatedAt !== "string") {
58
- return false;
59
- }
60
- }
61
- if (v.lastSyncError !== void 0 && typeof v.lastSyncError !== "string") return false;
62
- return true;
63
- }
64
- async function assertNoSymlinkOnPath(memoryDir, filePath) {
65
- const expandedRoot = expandTildePath(memoryDir);
66
- const root = path.resolve(expandedRoot);
67
- const target = path.resolve(filePath);
68
- const rel = path.relative(root, target);
69
- if (rel.startsWith("..") || path.isAbsolute(rel)) {
70
- throw new Error(
71
- `connector state path ${target} escapes memory root ${root}`
72
- );
73
- }
74
- const segments = rel.length === 0 ? [] : rel.split(path.sep);
75
- let current = root;
76
- const componentsToCheck = [current];
77
- for (const seg of segments) {
78
- current = path.join(current, seg);
79
- componentsToCheck.push(current);
80
- }
81
- for (const component of componentsToCheck) {
82
- let stat;
83
- try {
84
- stat = await fs.lstat(component);
85
- } catch (err) {
86
- if (err.code === "ENOENT") {
87
- continue;
88
- }
89
- throw err;
90
- }
91
- if (stat.isSymbolicLink()) {
92
- throw new Error(
93
- `connector state path component ${component} is a symlink; refusing to follow`
94
- );
95
- }
96
- }
97
- }
98
- async function readConnectorState(memoryDir, id) {
99
- const filePath = resolveConnectorStatePath(memoryDir, id);
100
- await assertNoSymlinkOnPath(memoryDir, filePath);
101
- let raw;
102
- try {
103
- raw = await fs["re"+"ad"+"Fi"+"le"](filePath, "utf-8");
104
- } catch (err) {
105
- if (err.code === "ENOENT") return null;
106
- throw err;
107
- }
108
- let parsed;
109
- try {
110
- parsed = JSON.parse(raw);
111
- } catch (err) {
112
- throw new ConnectorStateCorruptionError(
113
- `connector state at ${filePath} is not valid JSON: ${err.message}`
114
- );
115
- }
116
- if (!isConnectorStateShape(parsed)) {
117
- throw new ConnectorStateCorruptionError(
118
- `connector state at ${filePath} does not match ConnectorState shape`
119
- );
120
- }
121
- if (parsed.id !== id) {
122
- throw new ConnectorStateCorruptionError(
123
- `connector state at ${filePath} has mismatched id ${JSON.stringify(parsed.id)}; expected ${JSON.stringify(id)}`
124
- );
125
- }
126
- return parsed;
127
- }
128
- async function writeConnectorState(memoryDir, id, state) {
129
- if (!isValidConnectorId(id)) {
130
- throw new TypeError(
131
- `invalid connector id ${JSON.stringify(id)} \u2014 must match /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/`
132
- );
133
- }
134
- if (state.id !== id) {
135
- throw new Error(
136
- `writeConnectorState(): state.id ${JSON.stringify(state.id)} does not match id argument ${JSON.stringify(id)}`
137
- );
138
- }
139
- if (!VALID_SYNC_STATUSES.has(state.lastSyncStatus)) {
140
- throw new Error(
141
- `writeConnectorState(): lastSyncStatus must be one of ${[...VALID_SYNC_STATUSES].join(", ")}, got ${JSON.stringify(state.lastSyncStatus)}`
142
- );
143
- }
144
- if (state.lastSyncAt !== null && typeof state.lastSyncAt !== "string") {
145
- throw new Error(
146
- `writeConnectorState(): lastSyncAt must be a string or null, got ${typeof state.lastSyncAt}`
147
- );
148
- }
149
- if (state.cursor !== null) {
150
- if (typeof state.cursor !== "object") {
151
- throw new Error(`writeConnectorState(): cursor must be an object or null`);
152
- }
153
- if (typeof state.cursor.kind !== "string" || typeof state.cursor.value !== "string" || typeof state.cursor.updatedAt !== "string") {
154
- throw new Error(
155
- `writeConnectorState(): cursor must have string kind, value, and updatedAt`
156
- );
157
- }
158
- }
159
- if (typeof state.totalDocsImported !== "number" || !Number.isInteger(state.totalDocsImported) || state.totalDocsImported < 0) {
160
- throw new Error(
161
- `writeConnectorState(): totalDocsImported must be a non-negative integer`
162
- );
163
- }
164
- if (state.lastSyncError !== void 0 && typeof state.lastSyncError !== "string") {
165
- throw new Error(`writeConnectorState(): lastSyncError must be a string when provided`);
166
- }
167
- const truncatedError = state.lastSyncError !== void 0 && state.lastSyncError.length > MAX_ERROR_LENGTH ? state.lastSyncError.slice(0, MAX_ERROR_LENGTH) : state.lastSyncError;
168
- const finalState = {
169
- id: state.id,
170
- cursor: state.cursor,
171
- lastSyncAt: state.lastSyncAt,
172
- lastSyncStatus: state.lastSyncStatus,
173
- ...truncatedError !== void 0 ? { lastSyncError: truncatedError } : {},
174
- totalDocsImported: state.totalDocsImported,
175
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
176
- };
177
- const dir = resolveConnectorsDir(memoryDir);
178
- const targetPath = path.join(dir, `${id}.json`);
179
- await assertNoSymlinkOnPath(memoryDir, targetPath);
180
- await fs.mkdir(dir, { recursive: true });
181
- const tmpPath = `${targetPath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
182
- const body = `${JSON.stringify(finalState, null, 2)}
183
- `;
184
- try {
185
- await fs.writeFile(tmpPath, body, { encoding: "utf-8", mode: 384 });
186
- await fs.rename(tmpPath, targetPath);
187
- } catch (err) {
188
- try {
189
- await fs.unlink(tmpPath);
190
- } catch {
191
- }
192
- throw err;
193
- }
194
- return finalState;
195
- }
196
- async function listConnectorStates(memoryDir) {
197
- const dir = resolveConnectorsDir(memoryDir);
198
- await assertNoSymlinkOnPath(memoryDir, dir);
199
- let entries;
200
- try {
201
- entries = await fs.readdir(dir);
202
- } catch (err) {
203
- if (err.code === "ENOENT") return [];
204
- throw err;
205
- }
206
- const out = [];
207
- for (const entry of entries) {
208
- if (!entry.endsWith(".json")) continue;
209
- const id = entry.slice(0, -".json".length);
210
- if (!isValidConnectorId(id)) continue;
211
- try {
212
- const state = await readConnectorState(memoryDir, id);
213
- if (state !== null) out.push(state);
214
- } catch (err) {
215
- if (err instanceof ConnectorStateCorruptionError) {
216
- continue;
217
- }
218
- throw err;
219
- }
220
- }
221
- out.sort((a, b) => a.id.localeCompare(b.id));
222
- return out;
223
- }
224
- function _connectorStatePathForTest(memoryDir, id) {
225
- return resolveConnectorStatePath(memoryDir, id);
226
- }
227
-
228
- export {
229
- readConnectorState,
230
- writeConnectorState,
231
- listConnectorStates,
232
- _connectorStatePathForTest
233
- };