@artenx/dshb 0.1.39 → 0.1.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/auth/gate.d.ts +9 -1
- package/lib/auth/gate.js +12 -5
- package/lib/auth/gate.js.map +1 -1
- package/lib/auth/index.js +42 -9
- package/lib/auth/index.js.map +1 -1
- package/lib/catalog-BPkswHoz.js +121 -0
- package/lib/catalog-BPkswHoz.js.map +1 -0
- package/lib/client.js +482 -45
- package/lib/client.js.map +1 -1
- package/lib/{connection-sIX25pkS.d.ts → connection-CDJM9aUw.d.ts} +10 -3
- package/lib/core/index.js +480 -4
- package/lib/core/index.js.map +1 -1
- package/lib/core/routes.d.ts +1 -1
- package/lib/core/sync/coordinator.d.ts +5 -5
- package/lib/core/sync/coordinator.js +39 -6
- package/lib/core/sync/coordinator.js.map +1 -1
- package/lib/core/sync/host-key.d.ts +1 -1
- package/lib/core/sync/internal-routes.d.ts +3 -3
- package/lib/core/sync/internal-routes.js +36 -3
- package/lib/core/sync/internal-routes.js.map +1 -1
- package/lib/core/sync/model.d.ts +2 -2
- package/lib/core/sync/model.js +62 -1
- package/lib/core/sync/model.js.map +1 -1
- package/lib/core/sync/node-sync.d.ts +1 -1
- package/lib/core/sync/offline-archive.d.ts +6 -4
- package/lib/core/sync/offline-archive.js +31 -8
- package/lib/core/sync/offline-archive.js.map +1 -1
- package/lib/core/sync/offline-routes.js +29 -3
- package/lib/core/sync/offline-routes.js.map +1 -1
- package/lib/core/sync/peer-manager.d.ts +2 -2
- package/lib/core/sync/peer-manager.js +2 -0
- package/lib/core/sync/peer-manager.js.map +1 -1
- package/lib/core/sync/protocol.d.ts +2 -2
- package/lib/core/sync/protocol.js +2 -1
- package/lib/core/sync/protocol.js.map +1 -1
- package/lib/core/sync/remote-helper.js +4 -2
- package/lib/core/sync/remote-helper.js.map +1 -1
- package/lib/core/sync/routes.d.ts +1 -1
- package/lib/core/sync/routes.js +26 -1
- package/lib/core/sync/routes.js.map +1 -1
- package/lib/core/sync/session-journal.d.ts +1 -1
- package/lib/core/sync/session-routes.d.ts +1 -1
- package/lib/core/sync/session-routes.js +1 -1
- package/lib/core/sync/session-routes.js.map +1 -1
- package/lib/core/sync/session-sync.d.ts +1 -1
- package/lib/core/sync/session-sync.js +1 -1
- package/lib/core/sync/ssh-transport.d.ts +1 -1
- package/lib/core/sync/ssh-transport.js +73 -3
- package/lib/core/sync/ssh-transport.js.map +1 -1
- package/lib/core/sync/stores.d.ts +1 -1
- package/lib/core/sync/stores.js +8 -2
- package/lib/core/sync/stores.js.map +1 -1
- package/lib/core/workspaces.d.ts +1 -1
- package/lib/exec-ssh/connection-pool.d.ts +1 -1
- package/lib/exec-ssh/connection.d.ts +2 -2
- package/lib/exec-ssh/connection.js +29 -12
- package/lib/exec-ssh/connection.js.map +1 -1
- package/lib/exec-ssh/executor.d.ts +10 -1
- package/lib/exec-ssh/executor.js +91 -42
- package/lib/exec-ssh/executor.js.map +1 -1
- package/lib/exec-ssh/index.d.ts +1 -1
- package/lib/{host-key-CSnpIrjq.d.ts → host-key-CjO13Ds4.d.ts} +2 -2
- package/lib/{model-CKTBf-Pl.d.ts → model-CX2TlH2E.d.ts} +70 -6
- package/lib/{node-sync-C3Ym-HDu.d.ts → node-sync-qnJ7u0TU.d.ts} +3 -3
- package/lib/{protocol-DJ0zyVlB.d.ts → protocol-DyPDIJWa.d.ts} +3 -2
- package/lib/selection-BABQH1Rt.js +48 -0
- package/lib/selection-BABQH1Rt.js.map +1 -0
- package/lib/{session-journal-VE_1tA2-.d.ts → session-journal-lum5L2ip.d.ts} +2 -2
- package/lib/{session-sync-BBCm_ou2.js → session-sync-BV1CSYic.js} +85 -2
- package/lib/session-sync-BV1CSYic.js.map +1 -0
- package/lib/{session-sync-Bw0cZ4oa.d.ts → session-sync-Be5wuYHJ.d.ts} +12 -6
- package/lib/{ssh-transport-COZe0BDr.d.ts → ssh-transport-Cevwfre9.d.ts} +25 -6
- package/lib/{stores-puyTC075.d.ts → stores-BwQLabuJ.d.ts} +2 -2
- package/package.json +3 -1
- package/lib/session-sync-BBCm_ou2.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-routes.js","names":[],"sources":["../../../src/core/sync/internal-routes.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { isLoopbackRequest } from '../../auth/loopback.js'\nimport { SyncNodeManifestError, type SyncNodeService } from './node-sync.js'\nimport {\n MAX_SESSION_OBJECT_STREAM_BYTES,\n SYNC_PROTOCOL_VERSION,\n SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY,\n SYNC_SESSION_EVENT_TAIL_CAPABILITY,\n SYNC_SESSION_MANIFEST_CAPABILITY,\n SYNC_SESSION_OBJECT_STREAM_CAPABILITY,\n} from './protocol.js'\nimport { SyncSessionError, type SyncSessionEventPrefix, type SyncSessionService, validateObjectPayload } from './session-sync.js'\nimport type { SyncStateStore } from './stores.js'\n\n// 与 MAX_SYNC_TRANSFER_BYTES 对齐的请求体硬上限:超限直接断开(resolve null → 400),\n// 避免对端(或恶意请求)把宿主堆吃满。协调器分批后正常请求远小于该值。\nconst MAX_APPLY_BODY_BYTES = 128 * 1024 * 1024\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })\n res.end(JSON.stringify(body))\n}\n\nfunction pathSegments(req: IncomingMessage): string[] {\n return new URL(req.url ?? '/', 'http://x').pathname.split('/').filter(Boolean)\n}\n\nfunction readJsonBody(req: IncomingMessage): Promise<Record<string, unknown> | null> {\n return new Promise((resolve) => {\n if (req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') {\n resolve(null)\n return\n }\n const chunks: Buffer[] = []\n let size = 0\n let settled = false\n const fail = (): void => {\n if (settled) return\n settled = true\n resolve(null)\n }\n req.on('data', (chunk: Buffer) => {\n if (settled) return\n size += chunk.length\n if (size > MAX_APPLY_BODY_BYTES) {\n fail()\n req.destroy()\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => {\n if (settled) return\n try {\n const value: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n fail()\n return\n }\n settled = true\n resolve(value as Record<string, unknown>)\n } catch {\n fail()\n }\n })\n req.on('error', fail)\n })\n}\n\n/**\n * 会话对象带外流端点(POST /api/dshb/sync/internal/sessions/objects):\n * - 拉取模式(application/json 请求体 {objects: 描述符[]}):把本地对象编码为\n * \"JSON 头行 + 原始字节\" 帧流响应,磁盘到网络流式读出,内存 O(帧)。\n * - 推送模式(application/x-dshb-object-stream 请求体):请求帧流直接落盘\n * 收件箱(边收边校验摘要),返回 JSON 摘要。\n * 两种模式全程流式,单对象体积上限 MAX_SESSION_OBJECT_STREAM_BYTES(64GB),\n * 不受 JSON bundle 传输上限约束。\n */\nasync function handleSessionObjects(\n sessionSync: SyncSessionService,\n req: IncomingMessage,\n res: ServerResponse,\n): Promise<void> {\n if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {\n sendJson(res, 403, { ok: false, error: 'loopback access required' })\n return\n }\n const contentType = req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase()\n if (contentType === 'application/x-dshb-object-stream') {\n try {\n const received = await sessionSync.ingestObjectStream(req)\n sendJson(res, 200, { ok: true, received })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'object-stream-failed'\n sendJson(res, 422, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'object stream ingest failed' })\n }\n return\n }\n if (contentType !== 'application/json') {\n sendJson(res, 400, { ok: false, code: 'object-request-invalid', error: 'json or object-stream content type is required' })\n return\n }\n const body = await readJsonBody(req)\n if (!body || !Array.isArray(body.objects) || body.objects.length > 10_000 ||\n body.objects.some((object) => {\n try {\n return validateObjectPayload(object).deferred !== true\n } catch {\n return true\n }\n })) {\n sendJson(res, 400, { ok: false, code: 'object-request-invalid', error: 'deferred session object descriptors are required' })\n return\n }\n const objects = (body.objects as unknown[]).map((object) => validateObjectPayload(object))\n res.writeHead(200, { 'content-type': 'application/x-dshb-object-stream', 'cache-control': 'no-store' })\n try {\n for await (const chunk of sessionSync.streamObjects(objects)) {\n if (!res.write(chunk)) {\n await new Promise<void>((resolve, reject) => {\n res.once('drain', resolve)\n res.once('error', reject)\n })\n }\n }\n res.end()\n } catch {\n res.destroy()\n }\n}\n\nexport function registerSyncInternalRoutes(\n ctx: Context,\n state: SyncStateStore,\n nodeSync?: SyncNodeService,\n sessionSync?: SyncSessionService,\n): void {\n const capabilities = [\n 'peer-handshake',\n ...(nodeSync ? ['node-sync'] : []),\n ...(sessionSync ? ['session-sync', SYNC_SESSION_MANIFEST_CAPABILITY, SYNC_SESSION_EVENT_TAIL_CAPABILITY, SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY, SYNC_SESSION_OBJECT_STREAM_CAPABILITY] : []),\n ]\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'exact',\n path: '/api/dshb/sync/internal/handshake',\n handler: (req: IncomingMessage, res: ServerResponse) => {\n if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {\n sendJson(res, 403, { ok: false, error: 'loopback access required' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n try {\n sendJson(res, 200, {\n ok: true,\n protocolVersion: SYNC_PROTOCOL_VERSION,\n instanceId: state.instanceId(),\n capabilities,\n })\n } catch {\n sendJson(res, 503, { ok: false, error: 'sync identity unavailable' })\n }\n },\n }),\n )\n\n if (nodeSync) ctx.effect(() =>\n ctx.webServer.register({\n kind: 'prefix',\n path: '/api/dshb/sync/internal/nodes',\n handler: async (req, res) => {\n if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {\n sendJson(res, 403, { ok: false, error: 'loopback access required' })\n return\n }\n const segments = pathSegments(req)\n const action = segments[5]\n if (segments.length !== 6) {\n sendJson(res, 404, { ok: false, error: 'not found' })\n return\n }\n if (req.method === 'GET' && action === 'manifest') {\n try {\n sendJson(res, 200, { ok: true, manifest: await nodeSync.exportManifest(), capabilities })\n } catch {\n sendJson(res, 500, { ok: false, error: 'node manifest export failed' })\n }\n return\n }\n if (req.method === 'POST' && action === 'apply') {\n const body = await readJsonBody(req)\n if (!body || !Array.isArray(body.records) || typeof body.sourceName !== 'string') {\n sendJson(res, 400, { ok: false, error: 'records and sourceName are required' })\n return\n }\n try {\n sendJson(res, 200, { ok: true, result: await nodeSync.applyManifest(body.records, body.sourceName) })\n } catch (error) {\n const status = error instanceof SyncNodeManifestError ? 400 : 500\n sendJson(res, status, { ok: false, error: status === 400 ? 'node manifest rejected' : 'node manifest apply failed' })\n }\n return\n }\n sendJson(res, 404, { ok: false, error: 'not found' })\n },\n }),\n )\n\n if (!sessionSync) return\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'prefix',\n path: '/api/dshb/sync/internal/sessions',\n handler: async (req, res) => {\n if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {\n sendJson(res, 403, { ok: false, error: 'loopback access required' })\n return\n }\n const segments = pathSegments(req)\n const action = segments[5]\n if (segments.length !== 6) {\n sendJson(res, 404, { ok: false, error: 'not found' })\n return\n }\n if (req.method === 'GET' && action === 'bundle') {\n try {\n sendJson(res, 200, { ok: true, bundle: await sessionSync.exportBundle() })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-export-failed'\n const status = code === 'bundle-too-large' ? 413 : 500\n sendJson(res, status, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'session bundle export failed' })\n }\n return\n }\n if (req.method === 'GET' && action === 'manifest') {\n try {\n sendJson(res, 200, { ok: true, manifest: await sessionSync.exportManifest() })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-export-failed'\n const status = code === 'bundle-too-large' ? 413 : 500\n sendJson(res, status, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'session manifest export failed' })\n }\n return\n }\n if (req.method === 'POST' && action === 'entries') {\n const body = await readJsonBody(req)\n const prefixesValid = body?.prefixes === undefined || (Array.isArray(body.prefixes) &&\n body.prefixes.every((prefix) => prefix !== null && typeof prefix === 'object' && !Array.isArray(prefix)))\n if (!body || !Array.isArray(body.keys) || !body.keys.every((key) => typeof key === 'string') ||\n typeof body.manifestDigest !== 'string' || !prefixesValid) {\n sendJson(res, 400, { ok: false, code: 'session-request-invalid', error: 'keys, manifestDigest, and valid prefixes are required' })\n return\n }\n try {\n sendJson(res, 200, {\n ok: true,\n bundle: await sessionSync.exportEntries(\n body.keys as string[],\n body.manifestDigest,\n (body.prefixes ?? []) as SyncSessionEventPrefix[],\n { deferredObjects: body.deferredObjects === true },\n ),\n })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-export-failed'\n const status = code === 'bundle-too-large' ? 413 : 500\n sendJson(res, status, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'session entries export failed' })\n }\n return\n }\n if (req.method === 'POST' && action === 'objects') {\n await handleSessionObjects(sessionSync, req, res)\n return\n }\n if (req.method === 'POST' && action === 'apply') {\n const body = await readJsonBody(req)\n if (!body || body.bundle === null || typeof body.bundle !== 'object' ||\n typeof body.sourceName !== 'string' || typeof body.peerId !== 'string' || !/^p-[a-f0-9]{24}$/.test(body.peerId)) {\n sendJson(res, 400, { ok: false, code: 'session-request-invalid', error: 'bundle, sourceName, and peerId are required' })\n return\n }\n try {\n sendJson(res, 200, {\n ok: true,\n result: await sessionSync.applyBundle(body.bundle, body.sourceName, body.peerId),\n })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-apply-failed'\n const status = code === 'bundle-too-large' ? 413\n : ['manifest-invalid', 'manifest-digest', 'object-invalid', 'session-format'].includes(code) ? 400\n : code === 'workspace-unmapped' || code === 'session-delta-prefix' ? 409 : 500\n sendJson(res, status, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'session bundle apply failed' })\n }\n return\n }\n sendJson(res, 404, { ok: false, error: 'not found' })\n },\n }),\n )\n}\n"],"mappings":";;;;;AAkBA,MAAM,uBAAuB;AAE7B,SAAS,SAAS,KAAqB,QAAgB,MAAqB;CAC1E,IAAI,UAAU,QAAQ;EAAE,gBAAgB;EAAoB,iBAAiB;CAAW,CAAC;CACzF,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC;AAC9B;AAEA,SAAS,aAAa,KAAgC;CACpD,OAAO,IAAI,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;AAC/E;AAEA,SAAS,aAAa,KAA+D;CACnF,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,IAAI,QAAQ,eAAe,EAAE,MAAM,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,YAAY,MAAM,oBAAoB;GAC9F,QAAQ,IAAI;GACZ;EACF;EACA,MAAM,SAAmB,CAAC;EAC1B,IAAI,OAAO;EACX,IAAI,UAAU;EACd,MAAM,aAAmB;GACvB,IAAI,SAAS;GACb,UAAU;GACV,QAAQ,IAAI;EACd;EACA,IAAI,GAAG,SAAS,UAAkB;GAChC,IAAI,SAAS;GACb,QAAQ,MAAM;GACd,IAAI,OAAO,sBAAsB;IAC/B,KAAK;IACL,IAAI,QAAQ;IACZ;GACF;GACA,OAAO,KAAK,KAAK;EACnB,CAAC;EACD,IAAI,GAAG,aAAa;GAClB,IAAI,SAAS;GACb,IAAI;IACF,MAAM,QAAiB,KAAK,MAAM,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC;IACxE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;KACvE,KAAK;KACL;IACF;IACA,UAAU;IACV,QAAQ,KAAgC;GAC1C,QAAQ;IACN,KAAK;GACP;EACF,CAAC;EACD,IAA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K,KAAK;IAAE,IAAI;IAAO,OAAO;GAAY,CAAC;EACtD;CACF,CAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"internal-routes.js","names":[],"sources":["../../../src/core/sync/internal-routes.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { isLoopbackRequest } from '../../auth/loopback.js'\nimport { SyncNodeManifestError, type SyncNodeService } from './node-sync.js'\nimport {\n MAX_SESSION_OBJECT_STREAM_BYTES,\n SYNC_PROTOCOL_VERSION,\n SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY,\n SYNC_SESSION_EVENT_TAIL_CAPABILITY,\n SYNC_SESSION_MANIFEST_CAPABILITY,\n SYNC_SESSION_OBJECT_STREAM_CAPABILITY,\n SYNC_CATALOG_CAPABILITY,\n} from './protocol.js'\nimport { SyncSessionError, type SyncSessionEventPrefix, type SyncSessionService, validateObjectPayload } from './session-sync.js'\nimport type { SyncStateStore } from './stores.js'\nimport { exportSyncCatalog } from './catalog.js'\n\n// 与 MAX_SYNC_TRANSFER_BYTES 对齐的请求体硬上限:超限直接断开(resolve null → 400),\n// 避免对端(或恶意请求)把宿主堆吃满。协调器分批后正常请求远小于该值。\nconst MAX_APPLY_BODY_BYTES = 128 * 1024 * 1024\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })\n res.end(JSON.stringify(body))\n}\n\nfunction pathSegments(req: IncomingMessage): string[] {\n return new URL(req.url ?? '/', 'http://x').pathname.split('/').filter(Boolean)\n}\n\nfunction readJsonBody(req: IncomingMessage): Promise<Record<string, unknown> | null> {\n return new Promise((resolve) => {\n if (req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') {\n resolve(null)\n return\n }\n const chunks: Buffer[] = []\n let size = 0\n let settled = false\n const fail = (): void => {\n if (settled) return\n settled = true\n resolve(null)\n }\n req.on('data', (chunk: Buffer) => {\n if (settled) return\n size += chunk.length\n if (size > MAX_APPLY_BODY_BYTES) {\n fail()\n req.destroy()\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => {\n if (settled) return\n try {\n const value: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n fail()\n return\n }\n settled = true\n resolve(value as Record<string, unknown>)\n } catch {\n fail()\n }\n })\n req.on('error', fail)\n })\n}\n\n/**\n * 会话对象带外流端点(POST /api/dshb/sync/internal/sessions/objects):\n * - 拉取模式(application/json 请求体 {objects: 描述符[]}):把本地对象编码为\n * \"JSON 头行 + 原始字节\" 帧流响应,磁盘到网络流式读出,内存 O(帧)。\n * - 推送模式(application/x-dshb-object-stream 请求体):请求帧流直接落盘\n * 收件箱(边收边校验摘要),返回 JSON 摘要。\n * 两种模式全程流式,单对象体积上限 MAX_SESSION_OBJECT_STREAM_BYTES(64GB),\n * 不受 JSON bundle 传输上限约束。\n */\nasync function handleSessionObjects(\n sessionSync: SyncSessionService,\n req: IncomingMessage,\n res: ServerResponse,\n): Promise<void> {\n if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {\n sendJson(res, 403, { ok: false, error: 'loopback access required' })\n return\n }\n const contentType = req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase()\n if (contentType === 'application/x-dshb-object-stream') {\n try {\n const received = await sessionSync.ingestObjectStream(req)\n sendJson(res, 200, { ok: true, received })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'object-stream-failed'\n sendJson(res, 422, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'object stream ingest failed' })\n }\n return\n }\n if (contentType !== 'application/json') {\n sendJson(res, 400, { ok: false, code: 'object-request-invalid', error: 'json or object-stream content type is required' })\n return\n }\n const body = await readJsonBody(req)\n if (!body || !Array.isArray(body.objects) || body.objects.length > 10_000 ||\n body.objects.some((object) => {\n try {\n return validateObjectPayload(object).deferred !== true\n } catch {\n return true\n }\n })) {\n sendJson(res, 400, { ok: false, code: 'object-request-invalid', error: 'deferred session object descriptors are required' })\n return\n }\n const objects = (body.objects as unknown[]).map((object) => validateObjectPayload(object))\n res.writeHead(200, { 'content-type': 'application/x-dshb-object-stream', 'cache-control': 'no-store' })\n try {\n for await (const chunk of sessionSync.streamObjects(objects)) {\n if (!res.write(chunk)) {\n await new Promise<void>((resolve, reject) => {\n res.once('drain', resolve)\n res.once('error', reject)\n })\n }\n }\n res.end()\n } catch {\n res.destroy()\n }\n}\n\nexport function registerSyncInternalRoutes(\n ctx: Context,\n state: SyncStateStore,\n nodeSync?: SyncNodeService,\n sessionSync?: SyncSessionService,\n): void {\n const capabilities = [\n 'peer-handshake',\n ...(nodeSync ? ['node-sync'] : []),\n ...(sessionSync ? ['session-sync', SYNC_SESSION_MANIFEST_CAPABILITY, SYNC_SESSION_EVENT_TAIL_CAPABILITY, SYNC_SESSION_BUNDLE_OBJECTS_CAPABILITY, SYNC_SESSION_OBJECT_STREAM_CAPABILITY] : []),\n ...(nodeSync && sessionSync ? [SYNC_CATALOG_CAPABILITY] : []),\n ]\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'exact',\n path: '/api/dshb/sync/internal/handshake',\n handler: (req: IncomingMessage, res: ServerResponse) => {\n if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {\n sendJson(res, 403, { ok: false, error: 'loopback access required' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n try {\n sendJson(res, 200, {\n ok: true,\n protocolVersion: SYNC_PROTOCOL_VERSION,\n instanceId: state.instanceId(),\n capabilities,\n })\n } catch {\n sendJson(res, 503, { ok: false, error: 'sync identity unavailable' })\n }\n },\n }),\n )\n\n if (nodeSync) ctx.effect(() =>\n ctx.webServer.register({\n kind: 'prefix',\n path: '/api/dshb/sync/internal/nodes',\n handler: async (req, res) => {\n if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {\n sendJson(res, 403, { ok: false, error: 'loopback access required' })\n return\n }\n const segments = pathSegments(req)\n const action = segments[5]\n if (segments.length !== 6) {\n sendJson(res, 404, { ok: false, error: 'not found' })\n return\n }\n if (req.method === 'GET' && action === 'manifest') {\n try {\n sendJson(res, 200, { ok: true, manifest: await nodeSync.exportManifest(), capabilities })\n } catch {\n sendJson(res, 500, { ok: false, error: 'node manifest export failed' })\n }\n return\n }\n if (req.method === 'POST' && action === 'apply') {\n const body = await readJsonBody(req)\n if (!body || !Array.isArray(body.records) || typeof body.sourceName !== 'string') {\n sendJson(res, 400, { ok: false, error: 'records and sourceName are required' })\n return\n }\n try {\n sendJson(res, 200, { ok: true, result: await nodeSync.applyManifest(body.records, body.sourceName) })\n } catch (error) {\n const status = error instanceof SyncNodeManifestError ? 400 : 500\n sendJson(res, status, { ok: false, error: status === 400 ? 'node manifest rejected' : 'node manifest apply failed' })\n }\n return\n }\n sendJson(res, 404, { ok: false, error: 'not found' })\n },\n }),\n )\n\n if (nodeSync && sessionSync) ctx.effect(() =>\n ctx.webServer.register({\n kind: 'exact',\n path: '/api/dshb/sync/internal/catalog',\n handler: async (req, res) => {\n if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {\n sendJson(res, 403, { ok: false, error: 'loopback access required' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n try {\n sendJson(res, 200, { ok: true, catalog: await exportSyncCatalog(nodeSync, sessionSync) })\n } catch {\n sendJson(res, 500, { ok: false, error: 'sync catalog export failed' })\n }\n },\n }),\n )\n\n if (!sessionSync) return\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'prefix',\n path: '/api/dshb/sync/internal/sessions',\n handler: async (req, res) => {\n if (!isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) {\n sendJson(res, 403, { ok: false, error: 'loopback access required' })\n return\n }\n const segments = pathSegments(req)\n const action = segments[5]\n if (segments.length !== 6) {\n sendJson(res, 404, { ok: false, error: 'not found' })\n return\n }\n if (req.method === 'GET' && action === 'bundle') {\n try {\n sendJson(res, 200, { ok: true, bundle: await sessionSync.exportBundle() })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-export-failed'\n const status = code === 'bundle-too-large' ? 413 : 500\n sendJson(res, status, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'session bundle export failed' })\n }\n return\n }\n if (req.method === 'GET' && action === 'manifest') {\n try {\n sendJson(res, 200, { ok: true, manifest: await sessionSync.exportManifest() })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-export-failed'\n const status = code === 'bundle-too-large' ? 413 : 500\n sendJson(res, status, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'session manifest export failed' })\n }\n return\n }\n if (req.method === 'POST' && action === 'entries') {\n const body = await readJsonBody(req)\n const prefixesValid = body?.prefixes === undefined || (Array.isArray(body.prefixes) &&\n body.prefixes.every((prefix) => prefix !== null && typeof prefix === 'object' && !Array.isArray(prefix)))\n if (!body || !Array.isArray(body.keys) || !body.keys.every((key) => typeof key === 'string') ||\n typeof body.manifestDigest !== 'string' || !prefixesValid) {\n sendJson(res, 400, { ok: false, code: 'session-request-invalid', error: 'keys, manifestDigest, and valid prefixes are required' })\n return\n }\n try {\n sendJson(res, 200, {\n ok: true,\n bundle: await sessionSync.exportEntries(\n body.keys as string[],\n body.manifestDigest,\n (body.prefixes ?? []) as SyncSessionEventPrefix[],\n { deferredObjects: body.deferredObjects === true },\n ),\n })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-export-failed'\n const status = code === 'bundle-too-large' ? 413 : 500\n sendJson(res, status, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'session entries export failed' })\n }\n return\n }\n if (req.method === 'POST' && action === 'objects') {\n await handleSessionObjects(sessionSync, req, res)\n return\n }\n if (req.method === 'POST' && action === 'apply') {\n const body = await readJsonBody(req)\n if (!body || body.bundle === null || typeof body.bundle !== 'object' ||\n typeof body.sourceName !== 'string' || typeof body.peerId !== 'string' || !/^p-[a-f0-9]{24}$/.test(body.peerId)) {\n sendJson(res, 400, { ok: false, code: 'session-request-invalid', error: 'bundle, sourceName, and peerId are required' })\n return\n }\n try {\n sendJson(res, 200, {\n ok: true,\n result: await sessionSync.applyBundle(body.bundle, body.sourceName, body.peerId),\n })\n } catch (error) {\n const code = error instanceof SyncSessionError ? error.code : 'session-apply-failed'\n const status = code === 'bundle-too-large' ? 413\n : ['manifest-invalid', 'manifest-digest', 'object-invalid', 'session-format'].includes(code) ? 400\n : code === 'workspace-unmapped' || code === 'session-delta-prefix' ? 409 : 500\n sendJson(res, status, { ok: false, code, error: error instanceof SyncSessionError ? error.message : 'session bundle apply failed' })\n }\n return\n }\n sendJson(res, 404, { ok: false, error: 'not found' })\n },\n }),\n )\n}\n"],"mappings":";;;;;;AAoBA,MAAM,uBAAuB;AAE7B,SAAS,SAAS,KAAqB,QAAgB,MAAqB;CAC1E,IAAI,UAAU,QAAQ;EAAE,gBAAgB;EAAoB,iBAAiB;CAAW,CAAC;CACzF,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC;AAC9B;AAEA,SAAS,aAAa,KAAgC;CACpD,OAAO,IAAI,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;AAC/E;AAEA,SAAS,aAAa,KAA+D;CACnF,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,IAAI,QAAQ,eAAe,EAAE,MAAM,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,YAAY,MAAM,oBAAoB;GAC9F,QAAQ,IAAI;GACZ;EACF;EACA,MAAM,SAAmB,CAAC;EAC1B,IAAI,OAAO;EACX,IAAI,UAAU;EACd,MAAM,aAAmB;GACvB,IAAI,SAAS;GACb,UAAU;GACV,QAAQ,IAAI;EACd;EACA,IAAI,GAAG,SAAS,UAAkB;GACh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Origin, SyncPeer, SyncPeerDraft, SyncPeerProgress, SyncProvenance, SyncRecordMetadata, SyncSchedule, SyncSessionArchive, SyncState, SyncWorkspaceMapping, isNonNegativeSafeInteger, isRecord, parseSyncPeer, parseSyncPeerDraft, syncRecordKey, syncWorkspaceKey };
|
|
1
|
+
import { C as parseSyncPeer, D as syncWorkspaceKey, E as syncRecordKey, S as isRecord, T as parseSyncSelection, _ as SyncSessionArchive, a as SyncDirection, b as SyncWorkspaceOrigin, c as SyncMode, d as SyncPeerDraft, f as SyncPeerProgress, g as SyncSelection, h as SyncSchedule, i as SyncCatalogWorkspace, l as SyncOrigin, m as SyncRecordMetadata, n as SyncCatalogNode, o as SyncEntityKind, p as SyncProvenance, r as SyncCatalogSession, s as SyncImportMethod, t as SyncCatalog, u as SyncPeer, v as SyncState, w as parseSyncPeerDraft, x as isNonNegativeSafeInteger, y as SyncWorkspaceMapping } from "../../model-CX2TlH2E.js";
|
|
2
|
+
export { SyncCatalog, SyncCatalogNode, SyncCatalogSession, SyncCatalogWorkspace, SyncDirection, SyncEntityKind, SyncImportMethod, SyncMode, SyncOrigin, SyncPeer, SyncPeerDraft, SyncPeerProgress, SyncProvenance, SyncRecordMetadata, SyncSchedule, SyncSelection, SyncSessionArchive, SyncState, SyncWorkspaceMapping, SyncWorkspaceOrigin, isNonNegativeSafeInteger, isRecord, parseSyncPeer, parseSyncPeerDraft, parseSyncSelection, syncRecordKey, syncWorkspaceKey };
|
package/lib/core/sync/model.js
CHANGED
|
@@ -12,7 +12,9 @@ const PEER_FIELDS = /* @__PURE__ */ new Set([
|
|
|
12
12
|
"remoteWebPort",
|
|
13
13
|
"direction",
|
|
14
14
|
"schedule",
|
|
15
|
+
"mode",
|
|
15
16
|
"syncSessions",
|
|
17
|
+
"selection",
|
|
16
18
|
"enabled",
|
|
17
19
|
"hostKeyFingerprint"
|
|
18
20
|
]);
|
|
@@ -34,6 +36,62 @@ function port(value, label) {
|
|
|
34
36
|
if (!Number.isSafeInteger(value) || value < 1 || value > 65535) throw new Error(`${label} must be an integer between 1 and 65535`);
|
|
35
37
|
return value;
|
|
36
38
|
}
|
|
39
|
+
function parseOrigin(value, label) {
|
|
40
|
+
const input = record(value, label);
|
|
41
|
+
if (Object.keys(input).some((key) => key !== "originInstanceId" && key !== "originEntityId")) throw new Error(`${label} contains unsupported fields`);
|
|
42
|
+
return {
|
|
43
|
+
originInstanceId: text(input.originInstanceId, `${label}.originInstanceId`, 512),
|
|
44
|
+
originEntityId: text(input.originEntityId, `${label}.originEntityId`, 512)
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function parseSyncSelection(value) {
|
|
48
|
+
const input = record(value, "selection");
|
|
49
|
+
if (Object.keys(input).some((key) => ![
|
|
50
|
+
"mode",
|
|
51
|
+
"nodes",
|
|
52
|
+
"workspaces",
|
|
53
|
+
"sessions"
|
|
54
|
+
].includes(key))) throw new Error("selection contains unsupported fields");
|
|
55
|
+
if (input.mode !== "all" && input.mode !== "selected") throw new Error("selection mode is invalid");
|
|
56
|
+
const parseOrigins = (value, label) => {
|
|
57
|
+
if (value === void 0) return [];
|
|
58
|
+
if (!Array.isArray(value) || value.length > 1e4) throw new Error(`${label} must be an array of at most 10000 items`);
|
|
59
|
+
const origins = value.map((item, index) => parseOrigin(item, `${label}[${index}]`));
|
|
60
|
+
const keys = origins.map((origin) => JSON.stringify([origin.originInstanceId, origin.originEntityId]));
|
|
61
|
+
if (new Set(keys).size !== keys.length) throw new Error(`${label} contains duplicate origins`);
|
|
62
|
+
return origins;
|
|
63
|
+
};
|
|
64
|
+
const nodes = parseOrigins(input.nodes, "selection.nodes");
|
|
65
|
+
const rawWorkspaces = input.workspaces;
|
|
66
|
+
if (rawWorkspaces !== void 0 && (!Array.isArray(rawWorkspaces) || rawWorkspaces.length > 1e4)) throw new Error("selection.workspaces must be an array of at most 10000 items");
|
|
67
|
+
const workspaces = (rawWorkspaces ?? []).map((value, index) => {
|
|
68
|
+
const workspace = record(value, `selection.workspaces[${index}]`);
|
|
69
|
+
if (Object.keys(workspace).some((key) => ![
|
|
70
|
+
"originInstanceId",
|
|
71
|
+
"originEntityId",
|
|
72
|
+
"remotePath"
|
|
73
|
+
].includes(key)) || typeof workspace.remotePath !== "string" || workspace.remotePath.length > 4096 || !posix.isAbsolute(workspace.remotePath) || posix.normalize(workspace.remotePath) !== workspace.remotePath) throw new Error(`selection.workspaces[${index}] is invalid`);
|
|
74
|
+
const { remotePath, ...origin } = workspace;
|
|
75
|
+
return {
|
|
76
|
+
...parseOrigin(origin, `selection.workspaces[${index}]`),
|
|
77
|
+
remotePath
|
|
78
|
+
};
|
|
79
|
+
});
|
|
80
|
+
const workspaceKeys = workspaces.map((workspace) => JSON.stringify([
|
|
81
|
+
workspace.originInstanceId,
|
|
82
|
+
workspace.originEntityId,
|
|
83
|
+
workspace.remotePath
|
|
84
|
+
]));
|
|
85
|
+
if (new Set(workspaceKeys).size !== workspaceKeys.length) throw new Error("selection.workspaces contains duplicate origins");
|
|
86
|
+
const sessions = parseOrigins(input.sessions, "selection.sessions");
|
|
87
|
+
if (input.mode === "all" && (nodes.length > 0 || workspaces.length > 0 || sessions.length > 0)) throw new Error("all selection cannot contain explicit origins");
|
|
88
|
+
return {
|
|
89
|
+
mode: input.mode,
|
|
90
|
+
nodes,
|
|
91
|
+
workspaces,
|
|
92
|
+
sessions
|
|
93
|
+
};
|
|
94
|
+
}
|
|
37
95
|
function parseSyncPeer(value) {
|
|
38
96
|
const input = record(value, "sync peer");
|
|
39
97
|
for (const key of Object.keys(input)) if (!PEER_FIELDS.has(key)) throw new Error(`sync peer contains unsupported field: ${key}`);
|
|
@@ -47,6 +105,7 @@ function parseSyncPeer(value) {
|
|
|
47
105
|
if (input.authKind !== "password" && input.authKind !== "key") throw new Error("authKind must be password or key");
|
|
48
106
|
if (input.direction !== "pull" && input.direction !== "bidirectional") throw new Error("direction must be pull or bidirectional");
|
|
49
107
|
if (input.schedule !== "manual" && input.schedule !== "every-5m") throw new Error("schedule must be manual or every-5m");
|
|
108
|
+
if (input.mode !== void 0 && input.mode !== "full" && input.mode !== "metadata") throw new Error("mode must be full or metadata");
|
|
50
109
|
if (typeof input.syncSessions !== "boolean" || typeof input.enabled !== "boolean") throw new Error("syncSessions and enabled must be booleans");
|
|
51
110
|
const remoteDshHome = optionalText(input.remoteDshHome, "remoteDshHome", 4096);
|
|
52
111
|
if (remoteDshHome !== void 0) {
|
|
@@ -66,7 +125,9 @@ function parseSyncPeer(value) {
|
|
|
66
125
|
...input.remoteWebPort === void 0 ? {} : { remoteWebPort: port(input.remoteWebPort, "remoteWebPort") },
|
|
67
126
|
direction: input.direction,
|
|
68
127
|
schedule: input.schedule,
|
|
128
|
+
mode: input.mode === void 0 ? "full" : input.mode,
|
|
69
129
|
syncSessions: input.syncSessions,
|
|
130
|
+
...input.selection === void 0 ? {} : { selection: parseSyncSelection(input.selection) },
|
|
70
131
|
enabled: input.enabled,
|
|
71
132
|
...hostKeyFingerprint === void 0 ? {} : { hostKeyFingerprint }
|
|
72
133
|
};
|
|
@@ -101,6 +162,6 @@ function isNonNegativeSafeInteger(value) {
|
|
|
101
162
|
return Number.isSafeInteger(value) && value >= 0;
|
|
102
163
|
}
|
|
103
164
|
//#endregion
|
|
104
|
-
export { isNonNegativeSafeInteger, isRecord, parseSyncPeer, parseSyncPeerDraft, syncRecordKey, syncWorkspaceKey };
|
|
165
|
+
export { isNonNegativeSafeInteger, isRecord, parseSyncPeer, parseSyncPeerDraft, parseSyncSelection, syncRecordKey, syncWorkspaceKey };
|
|
105
166
|
|
|
106
167
|
//# sourceMappingURL=model.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":[],"sources":["../../../src/core/sync/model.ts"],"sourcesContent":["import { posix } from 'node:path'\nimport type { SyncRevision } from './revision.js'\n\nexport type SyncDirection = 'pull' | 'bidirectional'\nexport type SyncSchedule = 'manual' | 'every-5m'\nexport type SyncEntityKind = 'node' | 'session'\nexport type SyncImportMethod = 'peer' | 'offline'\n\nexport interface SyncPeer {\n id: string\n name: string\n host: string\n port: number\n username: string\n authKind: 'password' | 'key'\n remoteDshHome?: string\n remoteProfile?: string\n remoteWebPort?: number\n direction: SyncDirection\n schedule: SyncSchedule\n syncSessions: boolean\n enabled: boolean\n hostKeyFingerprint?: string\n}\n\nexport type SyncPeerDraft = Omit<SyncPeer, 'id' | 'hostKeyFingerprint'>\n\nexport interface SyncOrigin {\n originInstanceId: string\n originEntityId: string\n}\n\nexport interface SyncProvenance extends SyncOrigin {\n localEntityId: string\n importedVia?: SyncImportMethod\n sourceName?: string\n}\n\nexport interface SyncRecordMetadata extends SyncProvenance {\n kind: SyncEntityKind\n revision: SyncRevision\n contentDigest: string\n stateDigest?: string\n workspaceOrigin?: SyncOrigin\n deleted?: boolean\n pendingRemoval?: boolean\n credentialsRequired?: boolean\n}\n\nexport interface SyncPeerProgress {\n lastRunAt?: string\n lastRunStatus?: 'running' | 'succeeded' | 'failed' | 'stopped'\n lastSuccessAt?: string\n lastManifestDigest?: string\n watermark?: string\n lastErrorCode?: string\n lastErrorMessage?: string\n lastResult?: {\n imported: number\n exported: number\n skipped: number\n pendingRemoval: number\n importedSessions: number\n exportedSessions: number\n skippedSessions: number\n }\n}\n\nexport interface SyncWorkspaceMapping {\n originInstanceId: string\n originWorkspaceId: string\n localWorkspaceId: string\n localPath: string\n localNodeId: string\n remotePath: string\n title: string\n revision: SyncRevision\n contentDigest: string\n}\n\nexport interface SyncSessionArchive {\n branchId: string\n originInstanceId: string\n originSessionId: string\n localSessionId: string\n revision: SyncRevision\n contentDigest: string\n stateDigest: string\n workspacePosition: number\n workspaceId?: string\n workspaceOrigin?: SyncOrigin\n archivedAt: string\n}\n\nexport interface SyncState {\n version: 1\n clock: { physicalTimeMs: number; logicalCounter: number }\n peers: Record<string, SyncPeerProgress>\n records: Record<string, SyncRecordMetadata>\n workspaces: Record<string, SyncWorkspaceMapping>\n archives: Record<string, SyncSessionArchive>\n}\n\nconst PEER_FIELDS = new Set([\n 'id',\n 'name',\n 'host',\n 'port',\n 'username',\n 'authKind',\n 'remoteDshHome',\n 'remoteProfile',\n 'remoteWebPort',\n 'direction',\n 'schedule',\n 'syncSessions',\n 'enabled',\n 'hostKeyFingerprint',\n])\n\nconst PEER_DRAFT_FIELDS = new Set([...PEER_FIELDS].filter((field) => field !== 'id' && field !== 'hostKeyFingerprint'))\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n return value as Record<string, unknown>\n}\n\nfunction text(value: unknown, label: string, maxLength: number): string {\n if (typeof value !== 'string') throw new Error(`${label} must be a string`)\n const result = value.trim()\n if (!result || result.length > maxLength || /[\\u0000-\\u001f\\u007f]/.test(result)) {\n throw new Error(`${label} is invalid`)\n }\n return result\n}\n\nfunction optionalText(value: unknown, label: string, maxLength: number): string | undefined {\n return value === undefined ? undefined : text(value, label, maxLength)\n}\n\nfunction port(value: unknown, label: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > 65535) {\n throw new Error(`${label} must be an integer between 1 and 65535`)\n }\n return value as number\n}\n\nexport function parseSyncPeer(value: unknown): SyncPeer {\n const input = record(value, 'sync peer')\n for (const key of Object.keys(input)) {\n if (!PEER_FIELDS.has(key)) throw new Error(`sync peer contains unsupported field: ${key}`)\n }\n\n const id = text(input.id, 'id', 128)\n if (!/^[a-z][a-z0-9-]*$/.test(id)) throw new Error('id is invalid')\n\n const name = text(input.name, 'name', 128)\n const host = text(input.host, 'host', 255)\n if (/\\s/.test(host)) throw new Error('host is invalid')\n\n const username = text(input.username, 'username', 128)\n if (/\\s/.test(username)) throw new Error('username is invalid')\n\n if (input.authKind !== 'password' && input.authKind !== 'key') {\n throw new Error('authKind must be password or key')\n }\n if (input.direction !== 'pull' && input.direction !== 'bidirectional') {\n throw new Error('direction must be pull or bidirectional')\n }\n if (input.schedule !== 'manual' && input.schedule !== 'every-5m') {\n throw new Error('schedule must be manual or every-5m')\n }\n if (typeof input.syncSessions !== 'boolean' || typeof input.enabled !== 'boolean') {\n throw new Error('syncSessions and enabled must be booleans')\n }\n\n const remoteDshHome = optionalText(input.remoteDshHome, 'remoteDshHome', 4096)\n if (remoteDshHome !== undefined) {\n if (!posix.isAbsolute(remoteDshHome) || remoteDshHome.split('/').includes('..') || remoteDshHome.includes('\\\\')) {\n throw new Error('remoteDshHome must be a normalized absolute path')\n }\n }\n\n const remoteProfile = optionalText(input.remoteProfile, 'remoteProfile', 256)\n const hostKeyFingerprint = optionalText(input.hostKeyFingerprint, 'hostKeyFingerprint', 512)\n\n return {\n id,\n name,\n host,\n port: port(input.port, 'port'),\n username,\n authKind: input.authKind,\n ...(remoteDshHome === undefined ? {} : { remoteDshHome: posix.normalize(remoteDshHome) }),\n ...(remoteProfile === undefined ? {} : { remoteProfile }),\n ...(input.remoteWebPort === undefined ? {} : { remoteWebPort: port(input.remoteWebPort, 'remoteWebPort') }),\n direction: input.direction,\n schedule: input.schedule,\n syncSessions: input.syncSessions,\n enabled: input.enabled,\n ...(hostKeyFingerprint === undefined ? {} : { hostKeyFingerprint }),\n }\n}\n\nexport function parseSyncPeerDraft(value: unknown): SyncPeerDraft {\n const input = record(value, 'sync peer draft')\n for (const key of Object.keys(input)) {\n if (!PEER_DRAFT_FIELDS.has(key)) throw new Error(`sync peer draft contains unsupported field: ${key}`)\n }\n const { id, ...draft } = parseSyncPeer({ ...input, id: `p-${'0'.repeat(24)}` })\n void id\n return draft\n}\n\nexport function syncRecordKey(kind: SyncEntityKind, origin: SyncOrigin): string {\n return JSON.stringify([kind, origin.originInstanceId, origin.originEntityId])\n}\n\nexport function syncWorkspaceKey(originInstanceId: string, originWorkspaceId: string, remotePath: string): string {\n return JSON.stringify([originInstanceId, originWorkspaceId, remotePath])\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nexport function isNonNegativeSafeInteger(value: unknown): value is number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AAI,EAAE,eAAe,KAAK,MAAM,eAAe,eAAe,EAAE;EACzG,WAAW,MAAM;EACjB,UAAU,MAAM;EAChB,cAAc,MAAM;EACpB,SAAS,MAAM;EACf,GAAI,uBAAuB,KAAA,IAAY,CAAC,IAAI,EAAE,mBAAmB;CACnE;AACF;AAEA,SAAgB,mBAAmB,OAA+B;CAChE,MAAM,QAAQ,OAAO,OAAO,iBAAiB;CAC7C,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GACjC,IAAI,CAAC,kBAAkB,IAAI,GAAG,GAAG,MAAM,IAAI,MAAM,+CAA+C,KAAK;CAEvG,MAAM,EAAE,IAAI,GAAG,UAAU,cAAc;EAAE,GAAG;EAAO,IAAI,KAAK,IAAI,OAAO,EAAE;CAAI,CAAC;CAE9E,OAAO;AACT;AAEA,SAAgB,cAAc,MAAsB,QAA4B;CAC9E,OAAO,KAAK,UAAU;EAAC;EAAM,OAAO;EAAkB,OAAO;CAAc,CAAC;AAC9E;AAEA,SAAgB,iBAAiB,kBAA0B,mBAA2B,YAA4B;CAChH,OAAO,KAAK,UAAU;EAAC;EAAkB;EAAmB;CAAU,CAAC;AACzE;AAEA,SAAgB,SAAS,OAAkD;CACzE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,yBAAyB,OAAiC;CACxE,OAAO,OAAO,cAAc,KAAK,KAAM,SAAoB;AAC7D"}
|
|
1
|
+
{"version":3,"file":"model.js","names":[],"sources":["../../../src/core/sync/model.ts"],"sourcesContent":["import { posix } from 'node:path'\nimport type { SyncRevision } from './revision.js'\n\nexport type SyncDirection = 'pull' | 'bidirectional'\nexport type SyncSchedule = 'manual' | 'every-5m'\nexport type SyncEntityKind = 'node' | 'session'\nexport type SyncImportMethod = 'peer' | 'offline'\n/** 全量同步传输会话内容;元数据同步只同步目录,点击会话时经 wss 实时操作远端。 */\nexport type SyncMode = 'full' | 'metadata'\n\nexport interface SyncOrigin {\n originInstanceId: string\n originEntityId: string\n}\n\nexport interface SyncPeer {\n id: string\n name: string\n host: string\n port: number\n username: string\n authKind: 'password' | 'key'\n remoteDshHome?: string\n remoteProfile?: string\n remoteWebPort?: number\n direction: SyncDirection\n schedule: SyncSchedule\n mode: SyncMode\n syncSessions: boolean\n selection?: SyncSelection\n enabled: boolean\n hostKeyFingerprint?: string\n}\n\nexport interface SyncWorkspaceOrigin extends SyncOrigin {\n remotePath: string\n}\n\nexport interface SyncSelection {\n mode: 'all' | 'selected'\n nodes: SyncOrigin[]\n workspaces: SyncWorkspaceOrigin[]\n sessions: SyncOrigin[]\n}\n\nexport interface SyncCatalogNode {\n origin: SyncOrigin\n name: string\n type: 'remote-ssh' | 'remote-docker'\n}\n\nexport interface SyncCatalogWorkspace {\n origin: SyncOrigin\n nodeOrigin: SyncOrigin\n remotePath: string\n title: string\n}\n\nexport interface SyncCatalogSession {\n origin: SyncOrigin\n workspaceOrigin?: SyncOrigin\n workspaceRemotePath?: string\n nodeOrigin?: SyncOrigin\n sessionId: string\n title?: string\n sizeBytes?: number\n branchId?: string\n deleted?: boolean\n}\n\nexport interface SyncCatalog {\n protocolVersion: 1\n instanceId: string\n nodes: SyncCatalogNode[]\n workspaces: SyncCatalogWorkspace[]\n sessions: SyncCatalogSession[]\n}\n\nexport interface SyncPeer {\n id: string\n name: string\n host: string\n port: number\n username: string\n authKind: 'password' | 'key'\n remoteDshHome?: string\n remoteProfile?: string\n remoteWebPort?: number\n direction: SyncDirection\n schedule: SyncSchedule\n syncSessions: boolean\n selection?: SyncSelection\n enabled: boolean\n hostKeyFingerprint?: string\n}\n\nexport type SyncPeerDraft = Omit<SyncPeer, 'id' | 'hostKeyFingerprint'>\n\nexport interface SyncProvenance extends SyncOrigin {\n localEntityId: string\n importedVia?: SyncImportMethod\n sourceName?: string\n}\n\nexport interface SyncRecordMetadata extends SyncProvenance {\n kind: SyncEntityKind\n revision: SyncRevision\n contentDigest: string\n stateDigest?: string\n workspaceOrigin?: SyncOrigin\n deleted?: boolean\n pendingRemoval?: boolean\n credentialsRequired?: boolean\n}\n\nexport interface SyncPeerProgress {\n lastRunAt?: string\n lastRunStatus?: 'running' | 'succeeded' | 'failed' | 'stopped'\n lastSuccessAt?: string\n lastManifestDigest?: string\n watermark?: string\n lastErrorCode?: string\n lastErrorMessage?: string\n lastResult?: {\n imported: number\n exported: number\n skipped: number\n pendingRemoval: number\n importedSessions: number\n exportedSessions: number\n skippedSessions: number\n /** 元数据同步最近一次目录计数(可选,旧状态缺省)。 */\n catalogNodes?: number\n catalogWorkspaces?: number\n catalogSessions?: number\n }\n}\n\nexport interface SyncWorkspaceMapping {\n originInstanceId: string\n originWorkspaceId: string\n localWorkspaceId: string\n localPath: string\n localNodeId: string\n remotePath: string\n title: string\n revision: SyncRevision\n contentDigest: string\n}\n\nexport interface SyncSessionArchive {\n branchId: string\n originInstanceId: string\n originSessionId: string\n localSessionId: string\n revision: SyncRevision\n contentDigest: string\n stateDigest: string\n workspacePosition: number\n workspaceId?: string\n workspaceOrigin?: SyncOrigin\n archivedAt: string\n}\n\nexport interface SyncState {\n version: 1\n clock: { physicalTimeMs: number; logicalCounter: number }\n peers: Record<string, SyncPeerProgress>\n records: Record<string, SyncRecordMetadata>\n workspaces: Record<string, SyncWorkspaceMapping>\n archives: Record<string, SyncSessionArchive>\n}\n\nconst PEER_FIELDS = new Set([\n 'id',\n 'name',\n 'host',\n 'port',\n 'username',\n 'authKind',\n 'remoteDshHome',\n 'remoteProfile',\n 'remoteWebPort',\n 'direction',\n 'schedule',\n 'mode',\n 'syncSessions',\n 'selection',\n 'enabled',\n 'hostKeyFingerprint',\n])\n\nconst PEER_DRAFT_FIELDS = new Set([...PEER_FIELDS].filter((field) => field !== 'id' && field !== 'hostKeyFingerprint'))\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n return value as Record<string, unknown>\n}\n\nfunction text(value: unknown, label: string, maxLength: number): string {\n if (typeof value !== 'string') throw new Error(`${label} must be a string`)\n const result = value.trim()\n if (!result || result.length > maxLength || /[\\u0000-\\u001f\\u007f]/.test(result)) {\n throw new Error(`${label} is invalid`)\n }\n return result\n}\n\nfunction optionalText(value: unknown, label: string, maxLength: number): string | undefined {\n return value === undefined ? undefined : text(value, label, maxLength)\n}\n\nfunction port(value: unknown, label: string): number {\n if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > 65535) {\n throw new Error(`${label} must be an integer between 1 and 65535`)\n }\n return value as number\n}\n\nfunction parseOrigin(value: unknown, label: string): SyncOrigin {\n const input = record(value, label)\n if (Object.keys(input).some((key) => key !== 'originInstanceId' && key !== 'originEntityId')) {\n throw new Error(`${label} contains unsupported fields`)\n }\n return {\n originInstanceId: text(input.originInstanceId, `${label}.originInstanceId`, 512),\n originEntityId: text(input.originEntityId, `${label}.originEntityId`, 512),\n }\n}\n\nexport function parseSyncSelection(value: unknown): SyncSelection {\n const input = record(value, 'selection')\n if (Object.keys(input).some((key) => !['mode', 'nodes', 'workspaces', 'sessions'].includes(key))) {\n throw new Error('selection contains unsupported fields')\n }\n if (input.mode !== 'all' && input.mode !== 'selected') throw new Error('selection mode is invalid')\n const parseOrigins = (value: unknown, label: string): SyncOrigin[] => {\n if (value === undefined) return []\n if (!Array.isArray(value) || value.length > 10_000) throw new Error(`${label} must be an array of at most 10000 items`)\n const origins = value.map((item, index) => parseOrigin(item, `${label}[${index}]`))\n const keys = origins.map((origin) => JSON.stringify([origin.originInstanceId, origin.originEntityId]))\n if (new Set(keys).size !== keys.length) throw new Error(`${label} contains duplicate origins`)\n return origins\n }\n const nodes = parseOrigins(input.nodes, 'selection.nodes')\n const rawWorkspaces = input.workspaces\n if (rawWorkspaces !== undefined && (!Array.isArray(rawWorkspaces) || rawWorkspaces.length > 10_000)) {\n throw new Error('selection.workspaces must be an array of at most 10000 items')\n }\n const workspaces = (rawWorkspaces ?? []).map((value, index) => {\n const workspace = record(value, `selection.workspaces[${index}]`)\n if (Object.keys(workspace).some((key) => !['originInstanceId', 'originEntityId', 'remotePath'].includes(key)) ||\n typeof workspace.remotePath !== 'string' || workspace.remotePath.length > 4096 || !posix.isAbsolute(workspace.remotePath) ||\n posix.normalize(workspace.remotePath) !== workspace.remotePath) {\n throw new Error(`selection.workspaces[${index}] is invalid`)\n }\n const { remotePath, ...origin } = workspace\n return { ...parseOrigin(origin, `selection.workspaces[${index}]`), remotePath: remotePath as string }\n })\n const workspaceKeys = workspaces.map((workspace) => JSON.stringify([\n workspace.originInstanceId, workspace.originEntityId, workspace.remotePath,\n ]))\n if (new Set(workspaceKeys).size !== workspaceKeys.length) throw new Error('selection.workspaces contains duplicate origins')\n const sessions = parseOrigins(input.sessions, 'selection.sessions')\n if (input.mode === 'all' && (nodes.length > 0 || workspaces.length > 0 || sessions.length > 0)) {\n throw new Error('all selection cannot contain explicit origins')\n }\n return { mode: input.mode, nodes, workspaces, sessions }\n}\n\nexport function parseSyncPeer(value: unknown): SyncPeer {\n const input = record(value, 'sync peer')\n for (const key of Object.keys(input)) {\n if (!PEER_FIELDS.has(key)) throw new Error(`sync peer contains unsupported field: ${key}`)\n }\n\n const id = text(input.id, 'id', 128)\n if (!/^[a-z][a-z0-9-]*$/.test(id)) throw new Error('id is invalid')\n\n const name = text(input.name, 'name', 128)\n const host = text(input.host, 'host', 255)\n if (/\\s/.test(host)) throw new Error('host is invalid')\n\n const username = text(input.username, 'username', 128)\n if (/\\s/.test(username)) throw new Error('username is invalid')\n\n if (input.authKind !== 'password' && input.authKind !== 'key') {\n throw new Error('authKind must be password or key')\n }\n if (input.direction !== 'pull' && input.direction !== 'bidirectional') {\n throw new Error('direction must be pull or bidirectional')\n }\n if (input.schedule !== 'manual' && input.schedule !== 'every-5m') {\n throw new Error('schedule must be manual or every-5m')\n }\n if (input.mode !== undefined && input.mode !== 'full' && input.mode !== 'metadata') {\n throw new Error('mode must be full or metadata')\n }\n if (typeof input.syncSessions !== 'boolean' || typeof input.enabled !== 'boolean') {\n throw new Error('syncSessions and enabled must be booleans')\n }\n\n const remoteDshHome = optionalText(input.remoteDshHome, 'remoteDshHome', 4096)\n if (remoteDshHome !== undefined) {\n if (!posix.isAbsolute(remoteDshHome) || remoteDshHome.split('/').includes('..') || remoteDshHome.includes('\\\\')) {\n throw new Error('remoteDshHome must be a normalized absolute path')\n }\n }\n\n const remoteProfile = optionalText(input.remoteProfile, 'remoteProfile', 256)\n const hostKeyFingerprint = optionalText(input.hostKeyFingerprint, 'hostKeyFingerprint', 512)\n\n return {\n id,\n name,\n host,\n port: port(input.port, 'port'),\n username,\n authKind: input.authKind,\n ...(remoteDshHome === undefined ? {} : { remoteDshHome: posix.normalize(remoteDshHome) }),\n ...(remoteProfile === undefined ? {} : { remoteProfile }),\n ...(input.remoteWebPort === undefined ? {} : { remoteWebPort: port(input.remoteWebPort, 'remoteWebPort') }),\n direction: input.direction,\n schedule: input.schedule,\n // 旧 peer 数据没有 mode 字段:缺省按全量同步处理,保持既有行为不变。\n mode: input.mode === undefined ? 'full' : input.mode,\n syncSessions: input.syncSessions,\n ...(input.selection === undefined ? {} : { selection: parseSyncSelection(input.selection) }),\n enabled: input.enabled,\n ...(hostKeyFingerprint === undefined ? {} : { hostKeyFingerprint }),\n }\n}\n\nexport function parseSyncPeerDraft(value: unknown): SyncPeerDraft {\n const input = record(value, 'sync peer draft')\n for (const key of Object.keys(input)) {\n if (!PEER_DRAFT_FIELDS.has(key)) throw new Error(`sync peer draft contains unsupported field: ${key}`)\n }\n const { id, ...draft } = parseSyncPeer({ ...input, id: `p-${'0'.repeat(24)}` })\n void id\n return draft\n}\n\nexport function syncRecordKey(kind: SyncEntityKind, origin: SyncOrigin): string {\n return JSON.stringify([kind, origin.originInstanceId, origin.originEntityId])\n}\n\nexport function syncWorkspaceKey(originInstanceId: string, originWorkspaceId: string, remotePath: string): string {\n return JSON.stringify([originInstanceId, originWorkspaceId, remotePath])\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nexport function isNonNegativeSafeInteger(value: unknown): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0\n}\n"],"mappings":";;AA6KA,MAAM,8BAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,oBAAoB,IAAI,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC,QAAQ,UAAU,UAAU,QAAQ,UAAU,oBAAoB,CAAC;AAEtH,SAAS,OAAO,OAAgB,OAAwC;CACtE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,GAAG,MAAM,mBAAmB;CAE9C,OAAO;AACT;AAEA,SAAS,KAAK,OAAgB,OAAe,WAA2B;CACtE,IAAI,OAAO,UAAU,UAAU,MAAM,IAAI,MAAM,GAAG,MAAM,kBAAkB;CAC1E,MAAM,SAAS,MAAM,KAAK;CAC1B,IAAI,CAAC,UAAU,OAAO,SAAS,aAAa,wBAAwB,KAAK,MAAM,GAC7E,MAAM,IAAI,MAAM,GAAG,MAAM,YAAY;CAEvC,OAAO;AACT;AAEA,SAAS,aAAa,OAAgB,OAAe,WAAuC;CAC1F,OAAO,UAAU,KAAA,IAAY,KAAA,IAAY,KAAK,OAAO,OAAO,SAAS;AACvE;AAEA,SAAS,KAAK,OAAgB,OAAuB;CACnD,IAAI,CAAC,OAAO,cAAc,KAAK,KAAM,QAAmB,KAAM,QAAmB,OAC/E,MAAM,IAAI,MAAM,GAAG,MAAM,wCAAwC;CAEnE,OAAO;AACT;AAEA,SAAS,YAAY,OAAgB,OAA2B;CAC9D,MAAM,QAAQ,OAAO,OAAO,KAAK;CACjC,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,QAAQ,QAAQ,sBAAsB,QAAQ,gBAAgB,GACzF,MAAM,IAAI,M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AM,eAAe,eAAe,EAAE;EACzG,WAAW,MAAM;EACjB,UAAU,MAAM;EAEhB,MAAM,MAAM,SAAS,KAAA,IAAY,SAAS,MAAM;EAChD,cAAc,MAAM;EACpB,GAAI,MAAM,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,mBAAmB,MAAM,SAAS,EAAE;EAC1F,SAAS,MAAM;EACf,GAAI,uBAAuB,KAAA,IAAY,CAAC,IAAI,EAAE,mBAAmB;CACnE;AACF;AAEA,SAAgB,mBAAmB,OAA+B;CAChE,MAAM,QAAQ,OAAO,OAAO,iBAAiB;CAC7C,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,GACjC,IAAI,CAAC,kBAAkB,IAAI,GAAG,GAAG,MAAM,IAAI,MAAM,+CAA+C,KAAK;CAEvG,MAAM,EAAE,IAAI,GAAG,UAAU,cAAc;EAAE,GAAG;EAAO,IAAI,KAAK,IAAI,OAAO,EAAE;CAAI,CAAC;CAE9E,OAAO;AACT;AAEA,SAAgB,cAAc,MAAsB,QAA4B;CAC9E,OAAO,KAAK,UAAU;EAAC;EAAM,OAAO;EAAkB,OAAO;CAAc,CAAC;AAC9E;AAEA,SAAgB,iBAAiB,kBAA0B,mBAA2B,YAA4B;CAChH,OAAO,KAAK,UAAU;EAAC;EAAkB;EAAmB;CAAU,CAAC;AACzE;AAEA,SAAgB,SAAS,OAAkD;CACzE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,yBAAyB,OAAiC;CACxE,OAAO,OAAO,cAAc,KAAK,KAAM,SAAoB;AAC7D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as SyncNodeManifestError, c as SyncNodeView, i as SyncNodeManifest, n as SyncNodeEntry, o as SyncNodeProfile, r as SyncNodeInUseError, s as SyncNodeService, t as SyncNodeApplyResult } from "../../node-sync-
|
|
1
|
+
import { a as SyncNodeManifestError, c as SyncNodeView, i as SyncNodeManifest, n as SyncNodeEntry, o as SyncNodeProfile, r as SyncNodeInUseError, s as SyncNodeService, t as SyncNodeApplyResult } from "../../node-sync-qnJ7u0TU.js";
|
|
2
2
|
export { SyncNodeApplyResult, SyncNodeEntry, SyncNodeInUseError, SyncNodeManifest, SyncNodeManifestError, SyncNodeProfile, SyncNodeService, SyncNodeView };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { g as SyncSelection, t as SyncCatalog } from "../../model-CX2TlH2E.js";
|
|
2
|
+
import { n as SyncStateStore } from "../../stores-BwQLabuJ.js";
|
|
3
|
+
import { s as SyncNodeService } from "../../node-sync-qnJ7u0TU.js";
|
|
4
|
+
import { h as SyncSessionService } from "../../session-sync-Be5wuYHJ.js";
|
|
4
5
|
//#region src/core/sync/offline-archive.d.ts
|
|
5
6
|
declare const MAX_OFFLINE_ARCHIVE_BYTES: number;
|
|
6
7
|
declare class SyncOfflineArchiveError extends Error {
|
|
@@ -39,7 +40,8 @@ declare class SyncOfflineArchiveService {
|
|
|
39
40
|
private readonly home;
|
|
40
41
|
private readonly journal;
|
|
41
42
|
constructor(nodes: SyncNodeService, sessions: SyncSessionService, home?: string, getAvailableBytes?: (path: string) => bigint, state?: SyncStateStore | undefined);
|
|
42
|
-
exportArchive(password: string, includeSessions?: boolean): Promise<SyncOfflineArchiveFile>;
|
|
43
|
+
exportArchive(password: string, includeSessions?: boolean, selection?: SyncSelection): Promise<SyncOfflineArchiveFile>;
|
|
44
|
+
catalog(): Promise<SyncCatalog>;
|
|
43
45
|
importArchive(password: string, input: AsyncIterable<Uint8Array>): Promise<SyncOfflineImportResult>;
|
|
44
46
|
recoverPending(): Promise<void>;
|
|
45
47
|
cleanupStagingDirectories(): void;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { f as validateSyncSessionBundle, n as SyncSessionError } from "../../session-sync-
|
|
1
|
+
import { f as validateSyncSessionBundle, n as SyncSessionError, o as makeSyncSessionBundle } from "../../session-sync-BV1CSYic.js";
|
|
2
|
+
import { t as exportSyncCatalog } from "../../catalog-BPkswHoz.js";
|
|
3
|
+
import { i as syncOriginKey, n as selectionIncludesNode, r as selectionIncludesSession, t as resolveSyncSelection } from "../../selection-BABQH1Rt.js";
|
|
2
4
|
import { SyncOfflineArchiveJournalStore } from "./offline-journal.js";
|
|
3
5
|
import { homedir } from "node:os";
|
|
4
6
|
import { appendFileSync, chmodSync, closeSync, createReadStream, createWriteStream, mkdirSync, mkdtempSync, openSync, readSync, readdirSync, rmSync, statSync, statfsSync, writeFileSync } from "node:fs";
|
|
@@ -367,8 +369,11 @@ var SyncOfflineArchiveService = class {
|
|
|
367
369
|
this.home = homeDirectory(home);
|
|
368
370
|
this.journal = new SyncOfflineArchiveJournalStore(this.home);
|
|
369
371
|
}
|
|
370
|
-
exportArchive(password, includeSessions = false) {
|
|
371
|
-
return this.serializeMutation(() => this.exportArchiveNow(password, includeSessions));
|
|
372
|
+
exportArchive(password, includeSessions = false, selection) {
|
|
373
|
+
return this.serializeMutation(() => this.exportArchiveNow(password, includeSessions, selection));
|
|
374
|
+
}
|
|
375
|
+
catalog() {
|
|
376
|
+
return exportSyncCatalog(this.nodes, this.sessions);
|
|
372
377
|
}
|
|
373
378
|
importArchive(password, input) {
|
|
374
379
|
return this.serializeMutation(async () => {
|
|
@@ -397,19 +402,37 @@ var SyncOfflineArchiveService = class {
|
|
|
397
402
|
force: true
|
|
398
403
|
});
|
|
399
404
|
}
|
|
400
|
-
async exportArchiveNow(passwordValue, includeSessions) {
|
|
405
|
+
async exportArchiveNow(passwordValue, includeSessions, selection) {
|
|
401
406
|
const password = validatePassword(passwordValue);
|
|
402
407
|
if (typeof includeSessions !== "boolean") throw new SyncOfflineArchiveError("request-invalid", "Session inclusion option is invalid");
|
|
403
408
|
const nodeManifest = await this.nodes.exportManifest();
|
|
404
409
|
this.nodes.validateManifest(nodeManifest.records);
|
|
405
|
-
|
|
406
|
-
|
|
410
|
+
let sessionBundle = includeSessions ? await this.sessions.exportBundle() : void 0;
|
|
411
|
+
let selectedNodeManifest = nodeManifest;
|
|
412
|
+
if (selection?.mode === "selected") {
|
|
413
|
+
const catalog = await exportSyncCatalog(this.nodes, this.sessions);
|
|
414
|
+
const scope = resolveSyncSelection(selection, catalog);
|
|
415
|
+
selectedNodeManifest = {
|
|
416
|
+
...nodeManifest,
|
|
417
|
+
records: nodeManifest.records.filter((entry) => selectionIncludesNode(entry.metadata, scope))
|
|
418
|
+
};
|
|
419
|
+
if (sessionBundle) {
|
|
420
|
+
const selectedSessionIds = new Set(catalog.sessions.filter((session) => scope.sessions.has(syncOriginKey(session.origin))).map((session) => session.sessionId));
|
|
421
|
+
const selectedEntries = sessionBundle.entries.filter((entry) => selectionIncludesSession(entry.metadata, scope));
|
|
422
|
+
const entryIds = new Set(selectedEntries.map((entry) => entry.sourceLocalSessionId).filter((id) => Boolean(id)));
|
|
423
|
+
const selectedSkipped = sessionBundle.skipped.filter((entry) => selectedSessionIds.has(entry.sessionId) || entryIds.has(entry.sessionId));
|
|
424
|
+
const selectedSharedIds = new Set(selectedEntries.flatMap((entry) => entry.sharedObjectIds ?? []));
|
|
425
|
+
const selectedObjects = sessionBundle.objects?.filter((object) => selectedSharedIds.has(object.id));
|
|
426
|
+
sessionBundle = makeSyncSessionBundle(sessionBundle.instanceId, selectedEntries, selectedSkipped, selectedObjects);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
const nodesData = Buffer.from(JSON.stringify(selectedNodeManifest), "utf8");
|
|
407
430
|
const sessionsData = sessionBundle ? Buffer.from(JSON.stringify(sessionBundle), "utf8") : void 0;
|
|
408
|
-
const records = summaryRecords(
|
|
431
|
+
const records = summaryRecords(selectedNodeManifest, sessionBundle);
|
|
409
432
|
const manifest = {
|
|
410
433
|
format: "dshb-sync",
|
|
411
434
|
formatVersion: ARCHIVE_VERSION,
|
|
412
|
-
instanceId:
|
|
435
|
+
instanceId: selectedNodeManifest.instanceId,
|
|
413
436
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
414
437
|
includeSessions,
|
|
415
438
|
...sessionBundle ? { sessionFormatVersion: 4 } : {},
|