ima2-gen 1.1.21 → 1.1.23
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/README.md +44 -7
- package/bin/commands/video.js +14 -0
- package/bin/ima2.js +14 -4
- package/bin/lib/platform.js +34 -5
- package/docs/README.ko.md +43 -2
- package/lib/agentQueueWorker.js +6 -0
- package/lib/agentRuntime.js +3 -2
- package/lib/atomicWrite.js +14 -0
- package/lib/grokImageAdapter.js +6 -0
- package/lib/grokProxyLauncher.js +5 -3
- package/lib/grokVideoAdapter.js +1 -1
- package/lib/grokVideoPlannerPrompt.js +10 -0
- package/lib/inflight.js +1 -1
- package/lib/oauthLauncher.js +5 -0
- package/lib/videoFrameExtract.js +3 -3
- package/package.json +5 -7
- package/routes/capabilities.js +13 -0
- package/routes/edit.js +2 -1
- package/routes/generate.js +32 -6
- package/routes/health.js +4 -3
- package/routes/multimode.js +2 -1
- package/routes/video.js +35 -3
- package/server.js +29 -2
- package/skills/ima2/SKILL.md +48 -6
- package/ui/dist/.vite/manifest.json +12 -12
- package/ui/dist/assets/{AgentWorkspace-B_hq9CLg.js → AgentWorkspace-C21zqdTZ.js} +1 -1
- package/ui/dist/assets/{CardNewsWorkspace-wD12J7qk.js → CardNewsWorkspace-BN-ga1lG.js} +1 -1
- package/ui/dist/assets/{NodeCanvas-CI_wuPMf.js → NodeCanvas-BbMa4IhI.js} +1 -1
- package/ui/dist/assets/{PromptBuilderPanel-CUTujJUV.js → PromptBuilderPanel-DRwBJRDQ.js} +1 -1
- package/ui/dist/assets/{PromptImportDialog-CUi66jPK.js → PromptImportDialog-Dp85kHCq.js} +2 -2
- package/ui/dist/assets/{PromptImportDiscoverySection-Cm3vrjY4.js → PromptImportDiscoverySection-BE8Q8MLD.js} +1 -1
- package/ui/dist/assets/{PromptImportFolderSection-DOtWTD9n.js → PromptImportFolderSection-PtH5x0sc.js} +1 -1
- package/ui/dist/assets/{PromptLibraryPanel-BMjQegRa.js → PromptLibraryPanel-FnM9tHI9.js} +2 -2
- package/ui/dist/assets/SettingsWorkspace-MARPGyBL.js +1 -0
- package/ui/dist/assets/index-BAFI6htx.js +42 -0
- package/ui/dist/assets/{index-31uVIdt4.js → index-BSXxr_Bt.js} +1 -1
- package/ui/dist/assets/index-DS-ADE7U.css +1 -0
- package/ui/dist/index.html +2 -2
- package/bin/commands/annotate.ts +0 -119
- package/bin/commands/cancel.ts +0 -48
- package/bin/commands/canvas-versions.ts +0 -80
- package/bin/commands/capabilities.ts +0 -110
- package/bin/commands/cardnews.ts +0 -249
- package/bin/commands/comfy.ts +0 -54
- package/bin/commands/config.ts +0 -186
- package/bin/commands/defaults.ts +0 -192
- package/bin/commands/doctor.ts +0 -202
- package/bin/commands/edit.ts +0 -150
- package/bin/commands/gen.ts +0 -214
- package/bin/commands/grok.ts +0 -90
- package/bin/commands/history.ts +0 -146
- package/bin/commands/ls.ts +0 -64
- package/bin/commands/metadata.ts +0 -39
- package/bin/commands/multimode.ts +0 -196
- package/bin/commands/node.ts +0 -166
- package/bin/commands/observability.ts +0 -176
- package/bin/commands/ping.ts +0 -31
- package/bin/commands/prompt-sub/build.ts +0 -101
- package/bin/commands/prompt.ts +0 -492
- package/bin/commands/ps.ts +0 -81
- package/bin/commands/session.ts +0 -266
- package/bin/commands/show.ts +0 -72
- package/bin/commands/skill.ts +0 -70
- package/bin/commands/video.ts +0 -442
- package/bin/ima2.ts +0 -430
- package/bin/lib/args.ts +0 -92
- package/bin/lib/browser-id.ts +0 -16
- package/bin/lib/client.ts +0 -122
- package/bin/lib/config-store.ts +0 -120
- package/bin/lib/destructive-confirm.ts +0 -19
- package/bin/lib/doctor-checks.ts +0 -91
- package/bin/lib/error-hints.ts +0 -23
- package/bin/lib/files.ts +0 -39
- package/bin/lib/output.ts +0 -73
- package/bin/lib/platform.ts +0 -99
- package/bin/lib/recover-output.ts +0 -139
- package/bin/lib/sse.ts +0 -73
- package/bin/lib/star-prompt.ts +0 -97
- package/bin/lib/storage-doctor.ts +0 -39
- package/bin/lib/ui-build.ts +0 -85
- package/config.ts +0 -354
- package/lib/agentCommandParser.ts +0 -69
- package/lib/agentGenerationPlanner.ts +0 -273
- package/lib/agentQuestionResponder.ts +0 -266
- package/lib/agentQueueStore.ts +0 -270
- package/lib/agentQueueWorker.ts +0 -89
- package/lib/agentRuntime.ts +0 -604
- package/lib/agentSettings.ts +0 -72
- package/lib/agentStore.ts +0 -422
- package/lib/agentStoreRows.ts +0 -136
- package/lib/agentTypes.ts +0 -154
- package/lib/apiCachePolicy.ts +0 -11
- package/lib/assetLifecycle.ts +0 -146
- package/lib/canvasVersionStore.ts +0 -223
- package/lib/capabilities.ts +0 -126
- package/lib/cardNewsGenerator.ts +0 -271
- package/lib/cardNewsJobStore.ts +0 -142
- package/lib/cardNewsManifestStore.ts +0 -154
- package/lib/cardNewsPlanner.ts +0 -236
- package/lib/cardNewsPlannerClient.ts +0 -155
- package/lib/cardNewsPlannerPrompt.ts +0 -62
- package/lib/cardNewsPlannerSchema.ts +0 -321
- package/lib/cardNewsRoleTemplateStore.ts +0 -47
- package/lib/cardNewsTemplateStore.ts +0 -252
- package/lib/codexDetect.ts +0 -71
- package/lib/comfyBridge.ts +0 -235
- package/lib/composerSnapshot.ts +0 -33
- package/lib/configKeys.ts +0 -62
- package/lib/db.ts +0 -295
- package/lib/errInfo.ts +0 -43
- package/lib/errorClassify.ts +0 -100
- package/lib/generationCancel.ts +0 -28
- package/lib/generationErrors.ts +0 -238
- package/lib/grokImageAdapter.ts +0 -513
- package/lib/grokMultimodeAdapter.ts +0 -84
- package/lib/grokProxyLauncher.ts +0 -153
- package/lib/grokRuntime.ts +0 -23
- package/lib/grokSizeMapper.ts +0 -71
- package/lib/grokVideoAdapter.ts +0 -458
- package/lib/grokVideoCanvas.ts +0 -26
- package/lib/grokVideoDownload.ts +0 -59
- package/lib/grokVideoPlannerPrompt.ts +0 -67
- package/lib/historyIndex.ts +0 -51
- package/lib/historyList.ts +0 -181
- package/lib/imageMetadata.ts +0 -113
- package/lib/imageMetadataStore.ts +0 -67
- package/lib/imageModels.ts +0 -165
- package/lib/inflight.ts +0 -281
- package/lib/localImportStore.ts +0 -114
- package/lib/logger.ts +0 -161
- package/lib/nodeStore.ts +0 -91
- package/lib/oauthLauncher.ts +0 -94
- package/lib/oauthNormalize.ts +0 -30
- package/lib/oauthProxy/errors.ts +0 -128
- package/lib/oauthProxy/generators.ts +0 -494
- package/lib/oauthProxy/index.ts +0 -28
- package/lib/oauthProxy/prompts.ts +0 -123
- package/lib/oauthProxy/references.ts +0 -45
- package/lib/oauthProxy/runtime.ts +0 -115
- package/lib/oauthProxy/streams.ts +0 -232
- package/lib/oauthProxy/types.ts +0 -9
- package/lib/oauthProxy.ts +0 -3
- package/lib/openDirectory.ts +0 -47
- package/lib/pngInfo.ts +0 -26
- package/lib/promptBuilder/attachments.ts +0 -74
- package/lib/promptBuilder/client.ts +0 -130
- package/lib/promptBuilder/constants.ts +0 -9
- package/lib/promptBuilder/context.ts +0 -36
- package/lib/promptBuilder/errors.ts +0 -12
- package/lib/promptBuilder/requestSchema.ts +0 -56
- package/lib/promptBuilder/responseParser.ts +0 -219
- package/lib/promptBuilder/systemPrompt.ts +0 -135
- package/lib/promptBuilder/transport.ts +0 -94
- package/lib/promptBuilder/types.ts +0 -109
- package/lib/promptImport/curatedSources.ts +0 -141
- package/lib/promptImport/discoveryRegistry.ts +0 -329
- package/lib/promptImport/errors.ts +0 -18
- package/lib/promptImport/githubDiscovery.ts +0 -309
- package/lib/promptImport/githubFolder.ts +0 -397
- package/lib/promptImport/githubSource.ts +0 -257
- package/lib/promptImport/gptImageHints.ts +0 -70
- package/lib/promptImport/parsePromptCandidates.ts +0 -179
- package/lib/promptImport/promptIndex.ts +0 -326
- package/lib/promptImport/rankPromptCandidates.ts +0 -65
- package/lib/promptImport/types.ts +0 -103
- package/lib/promptSafetyPolicy.ts +0 -5
- package/lib/providerOptions.ts +0 -56
- package/lib/referenceImageCompress.ts +0 -84
- package/lib/refs.ts +0 -133
- package/lib/requestLogger.ts +0 -49
- package/lib/responsesDoctor.ts +0 -456
- package/lib/responsesErrors.ts +0 -83
- package/lib/responsesFallback.ts +0 -114
- package/lib/responsesImageAdapter.ts +0 -466
- package/lib/responsesParse.ts +0 -452
- package/lib/responsesTools.ts +0 -28
- package/lib/runtimeContext.ts +0 -146
- package/lib/runtimePorts.ts +0 -105
- package/lib/sessionStore.ts +0 -308
- package/lib/storageMigration.ts +0 -310
- package/lib/styleSheet.ts +0 -139
- package/lib/systemTrash.ts +0 -20
- package/lib/videoContinuity.ts +0 -180
- package/lib/videoFrameExtract.ts +0 -78
- package/lib/videoSeriesChain.ts +0 -29
- package/lib/visibleTextLanguagePolicy.ts +0 -7
- package/routes/agent.ts +0 -308
- package/routes/annotations.ts +0 -118
- package/routes/canvasVersions.ts +0 -69
- package/routes/capabilities.ts +0 -18
- package/routes/cardNews.ts +0 -211
- package/routes/comfy.ts +0 -43
- package/routes/edit.ts +0 -352
- package/routes/generate.ts +0 -492
- package/routes/grok.ts +0 -24
- package/routes/health.ts +0 -123
- package/routes/history.ts +0 -221
- package/routes/imageImport.ts +0 -37
- package/routes/index.ts +0 -52
- package/routes/metadata.ts +0 -77
- package/routes/multimode.ts +0 -499
- package/routes/nodes.ts +0 -578
- package/routes/promptBuilder.ts +0 -37
- package/routes/promptImport.ts +0 -379
- package/routes/prompts.ts +0 -428
- package/routes/quota.ts +0 -89
- package/routes/sessions.ts +0 -317
- package/routes/storage.ts +0 -47
- package/routes/video.ts +0 -300
- package/routes/videoExtended.ts +0 -284
- package/server.ts +0 -293
- package/ui/dist/assets/SettingsWorkspace-PiaVnsdA.js +0 -1
- package/ui/dist/assets/index-CjgnNtgt.css +0 -1
- package/ui/dist/assets/index-Da2s4_-5.js +0 -36
package/lib/runtimePorts.ts
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
import { createServer, type Server } from "node:net";
|
|
2
|
-
|
|
3
|
-
const DEFAULT_MAX_ATTEMPTS = 20;
|
|
4
|
-
|
|
5
|
-
export function parseLocalhostPortFromUrl(url: string) {
|
|
6
|
-
try {
|
|
7
|
-
const parsed = new URL(url);
|
|
8
|
-
const port = Number(parsed.port);
|
|
9
|
-
return Number.isFinite(port) && port > 0 ? port : null;
|
|
10
|
-
} catch {
|
|
11
|
-
return null;
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function stripV1FromOAuthUrl(url: string) {
|
|
16
|
-
return String(url || "").replace(/\/v1\/?$/, "");
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export function parseOAuthReadyUrl(line: string) {
|
|
20
|
-
const text = String(line || "");
|
|
21
|
-
const match = text.match(/https?:\/\/(?:127\.0\.0\.1|localhost):\d+(?:\/v1)?/i);
|
|
22
|
-
return match ? stripV1FromOAuthUrl(match[0]) : null;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
function checkPort(port: number, host?: string) {
|
|
26
|
-
return new Promise((resolve, reject) => {
|
|
27
|
-
const probe = createServer()
|
|
28
|
-
.once("error", (err: NodeJS.ErrnoException) => {
|
|
29
|
-
probe.close(() => {});
|
|
30
|
-
reject(err);
|
|
31
|
-
})
|
|
32
|
-
.once("listening", () => {
|
|
33
|
-
probe.close(() => resolve(true));
|
|
34
|
-
});
|
|
35
|
-
if (host) probe.listen(port, host);
|
|
36
|
-
else probe.listen(port);
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
interface PortOptions {
|
|
41
|
-
maxAttempts?: number;
|
|
42
|
-
host?: string;
|
|
43
|
-
label?: string;
|
|
44
|
-
onFallback?: (info: { label: string; requestedPort: number; actualPort: number }) => void;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export async function findAvailablePort(startPort: number, options: PortOptions = {}) {
|
|
48
|
-
const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
49
|
-
const host = options.host;
|
|
50
|
-
for (let offset = 0; offset <= maxAttempts; offset++) {
|
|
51
|
-
const port = Number(startPort) + offset;
|
|
52
|
-
try {
|
|
53
|
-
await checkPort(port, host);
|
|
54
|
-
return port;
|
|
55
|
-
} catch (err) {
|
|
56
|
-
if ((err as NodeJS.ErrnoException)?.code !== "EADDRINUSE") throw err;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
const err = new Error(`No available port found from ${startPort} to ${Number(startPort) + maxAttempts}`) as Error & { code?: string };
|
|
60
|
-
err.code = "PORT_RANGE_EXHAUSTED";
|
|
61
|
-
throw err;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
interface ListenLike {
|
|
65
|
-
listen: ((port: number, host: string) => Server) | ((port: number) => Server) | ((...args: never[]) => Server);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
function listenOnce(app: ListenLike, port: number, host?: string): Promise<Server> {
|
|
69
|
-
return new Promise((resolve, reject) => {
|
|
70
|
-
const listen = app.listen as (...args: unknown[]) => Server;
|
|
71
|
-
const server = host ? listen.call(app, port, host) : listen.call(app, port);
|
|
72
|
-
server.once("listening", () => resolve(server));
|
|
73
|
-
server.once("error", (err: NodeJS.ErrnoException) => reject(err));
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export async function listenWithPortFallback(app: ListenLike, startPort: number, options: PortOptions = {}) {
|
|
78
|
-
const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
79
|
-
const host = options.host;
|
|
80
|
-
const label = options.label || "server";
|
|
81
|
-
for (let offset = 0; offset <= maxAttempts; offset++) {
|
|
82
|
-
const port = Number(startPort) + offset;
|
|
83
|
-
try {
|
|
84
|
-
const server = await listenOnce(app, port, host);
|
|
85
|
-
if (offset > 0 && typeof options.onFallback === "function") {
|
|
86
|
-
options.onFallback({ label, requestedPort: Number(startPort), actualPort: port });
|
|
87
|
-
}
|
|
88
|
-
return server;
|
|
89
|
-
} catch (err) {
|
|
90
|
-
if ((err as NodeJS.ErrnoException)?.code !== "EADDRINUSE") throw err;
|
|
91
|
-
if (offset >= maxAttempts) {
|
|
92
|
-
const exhausted = new Error(`${label} port range exhausted from ${startPort} to ${port}`) as Error & { code?: string; cause?: unknown };
|
|
93
|
-
exhausted.code = "PORT_RANGE_EXHAUSTED";
|
|
94
|
-
exhausted.cause = err;
|
|
95
|
-
throw exhausted;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
throw new Error(`${label} failed to bind`);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export function getServerPort(server: Server | null | undefined) {
|
|
103
|
-
const address = server?.address?.();
|
|
104
|
-
return typeof address === "object" && address ? address.port : null;
|
|
105
|
-
}
|
package/lib/sessionStore.ts
DELETED
|
@@ -1,308 +0,0 @@
|
|
|
1
|
-
import { ulid } from "ulid";
|
|
2
|
-
import { getDb } from "./db.js";
|
|
3
|
-
|
|
4
|
-
function now() {
|
|
5
|
-
return Date.now();
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
export function createSession({ title = "Untitled" } = {}) {
|
|
9
|
-
const db = getDb();
|
|
10
|
-
const id = "s_" + ulid();
|
|
11
|
-
const t = now();
|
|
12
|
-
db.prepare(
|
|
13
|
-
"INSERT INTO sessions (id, title, created_at, updated_at, graph_version) VALUES (?, ?, ?, ?, 0)",
|
|
14
|
-
).run(id, title, t, t);
|
|
15
|
-
return { id, title, createdAt: t, updatedAt: t, graphVersion: 0 };
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
type SessionRow = {
|
|
19
|
-
id: string;
|
|
20
|
-
title: string;
|
|
21
|
-
createdAt: number;
|
|
22
|
-
updatedAt: number;
|
|
23
|
-
graphVersion: number;
|
|
24
|
-
};
|
|
25
|
-
type NodeRow = { id: string; x: number; y: number; data: string };
|
|
26
|
-
type EdgeRow = { id: string; source: string; target: string; data: string };
|
|
27
|
-
type StyleSheetRow = { styleSheet: string | null; styleSheetEnabled: number | null };
|
|
28
|
-
|
|
29
|
-
export function listSessions() {
|
|
30
|
-
const db = getDb();
|
|
31
|
-
const rows = db
|
|
32
|
-
.prepare(
|
|
33
|
-
"SELECT id, title, created_at AS createdAt, updated_at AS updatedAt, graph_version AS graphVersion FROM sessions ORDER BY updated_at DESC",
|
|
34
|
-
)
|
|
35
|
-
.all() as SessionRow[];
|
|
36
|
-
return rows.map((r) => ({
|
|
37
|
-
...r,
|
|
38
|
-
nodeCount: (db
|
|
39
|
-
.prepare("SELECT COUNT(*) AS c FROM nodes WHERE session_id = ?")
|
|
40
|
-
.get(r.id) as { c: number } | undefined)?.c ?? 0,
|
|
41
|
-
}));
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export function getSession(id: string) {
|
|
45
|
-
const db = getDb();
|
|
46
|
-
const session = db
|
|
47
|
-
.prepare(
|
|
48
|
-
"SELECT id, title, created_at AS createdAt, updated_at AS updatedAt, graph_version AS graphVersion FROM sessions WHERE id = ?",
|
|
49
|
-
)
|
|
50
|
-
.get(id) as SessionRow | undefined;
|
|
51
|
-
if (!session) return null;
|
|
52
|
-
const nodes = (db
|
|
53
|
-
.prepare("SELECT id, x, y, data FROM nodes WHERE session_id = ?")
|
|
54
|
-
.all(id) as NodeRow[])
|
|
55
|
-
.map((n) => ({ id: n.id, x: n.x, y: n.y, data: safeParse(n.data) }));
|
|
56
|
-
const edges = (db
|
|
57
|
-
.prepare("SELECT id, source, target, data FROM edges WHERE session_id = ?")
|
|
58
|
-
.all(id) as EdgeRow[])
|
|
59
|
-
.map((e) => ({
|
|
60
|
-
id: e.id,
|
|
61
|
-
source: e.source,
|
|
62
|
-
target: e.target,
|
|
63
|
-
data: safeParse(e.data),
|
|
64
|
-
}));
|
|
65
|
-
return { ...session, nodes, edges };
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export function getSessionTitleMap(ids: string[] = []) {
|
|
69
|
-
const cleanIds = [...new Set(ids.filter((id) => typeof id === "string" && id.length > 0))];
|
|
70
|
-
if (cleanIds.length === 0) return new Map<string, string>();
|
|
71
|
-
const placeholders = cleanIds.map(() => "?").join(", ");
|
|
72
|
-
const rows = getDb()
|
|
73
|
-
.prepare(`SELECT id, title FROM sessions WHERE id IN (${placeholders})`)
|
|
74
|
-
.all(...cleanIds) as Array<{ id: string; title: string }>;
|
|
75
|
-
return new Map(rows.map((row) => [row.id, row.title]));
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export function renameSession(id: string, title: string) {
|
|
79
|
-
const db = getDb();
|
|
80
|
-
const res = db
|
|
81
|
-
.prepare("UPDATE sessions SET title = ?, updated_at = ? WHERE id = ?")
|
|
82
|
-
.run(title, now(), id);
|
|
83
|
-
return res.changes > 0;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export function deleteSession(id: string) {
|
|
87
|
-
const db = getDb();
|
|
88
|
-
const res = db.prepare("DELETE FROM sessions WHERE id = ?").run(id);
|
|
89
|
-
return res.changes > 0;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
const MAX_STR = 10_000;
|
|
93
|
-
|
|
94
|
-
function cleanStr(v: unknown): string {
|
|
95
|
-
if (typeof v !== "string") return "";
|
|
96
|
-
return v.length > MAX_STR ? v.slice(0, MAX_STR) : v;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
function cleanData(v: unknown): string {
|
|
100
|
-
try {
|
|
101
|
-
const json = JSON.stringify(v ?? {});
|
|
102
|
-
return json.length > MAX_STR * 10 ? "{}" : json;
|
|
103
|
-
} catch {
|
|
104
|
-
return "{}";
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
interface NodeInput {
|
|
109
|
-
id?: unknown;
|
|
110
|
-
x?: unknown;
|
|
111
|
-
y?: unknown;
|
|
112
|
-
data?: unknown;
|
|
113
|
-
position?: { x?: unknown; y?: unknown };
|
|
114
|
-
[k: string]: unknown;
|
|
115
|
-
}
|
|
116
|
-
interface EdgeInput {
|
|
117
|
-
id?: unknown;
|
|
118
|
-
source?: unknown;
|
|
119
|
-
target?: unknown;
|
|
120
|
-
data?: unknown;
|
|
121
|
-
[k: string]: unknown;
|
|
122
|
-
}
|
|
123
|
-
type GraphErr = Error & { code?: string; status?: number; currentVersion?: number };
|
|
124
|
-
|
|
125
|
-
function normalizeGraphPayload(nodes: NodeInput[], edges: EdgeInput[]) {
|
|
126
|
-
const nodeIds = new Set(nodes.map((n) => n?.id).filter(Boolean).map(String));
|
|
127
|
-
const cleanEdges = edges.filter(
|
|
128
|
-
(e) => e?.id && e?.source && e?.target && nodeIds.has(String(e.source)) && nodeIds.has(String(e.target)),
|
|
129
|
-
);
|
|
130
|
-
const incomingByTarget = new Map<string, EdgeInput>();
|
|
131
|
-
for (const edge of cleanEdges) {
|
|
132
|
-
const target = String(edge.target);
|
|
133
|
-
if (incomingByTarget.has(target)) {
|
|
134
|
-
const err = new Error(`Node ${target} has multiple parent edges`) as GraphErr;
|
|
135
|
-
err.code = "GRAPH_PARENT_CONFLICT";
|
|
136
|
-
err.status = 409;
|
|
137
|
-
throw err;
|
|
138
|
-
}
|
|
139
|
-
incomingByTarget.set(target, edge);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
const nodeDataById = new Map<string, Record<string, unknown>>();
|
|
143
|
-
for (const node of nodes) {
|
|
144
|
-
if (!node?.id) continue;
|
|
145
|
-
const data = node.data && typeof node.data === "object" && !Array.isArray(node.data)
|
|
146
|
-
? { ...(node.data as Record<string, unknown>) }
|
|
147
|
-
: {};
|
|
148
|
-
nodeDataById.set(String(node.id), data);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
const normalizedNodes = nodes.map((node) => {
|
|
152
|
-
if (!node?.id) return node;
|
|
153
|
-
const id = String(node.id);
|
|
154
|
-
const data: Record<string, unknown> = { ...(nodeDataById.get(id) ?? {}) };
|
|
155
|
-
const incoming = incomingByTarget.get(id);
|
|
156
|
-
if (!incoming) {
|
|
157
|
-
data.parentServerNodeId = null;
|
|
158
|
-
} else {
|
|
159
|
-
const parentData = nodeDataById.get(String(incoming.source)) ?? {};
|
|
160
|
-
data.parentServerNodeId = typeof parentData.serverNodeId === "string"
|
|
161
|
-
? parentData.serverNodeId
|
|
162
|
-
: null;
|
|
163
|
-
}
|
|
164
|
-
return { ...node, data };
|
|
165
|
-
});
|
|
166
|
-
|
|
167
|
-
return { nodes: normalizedNodes, edges: cleanEdges };
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
interface SaveGraphOptions {
|
|
171
|
-
nodes?: NodeInput[];
|
|
172
|
-
edges?: EdgeInput[];
|
|
173
|
-
expectedVersion?: number | null;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export function saveGraph(sessionId: string, { nodes = [], edges = [], expectedVersion = null }: SaveGraphOptions = {}) {
|
|
177
|
-
const db = getDb();
|
|
178
|
-
const sessionExists = db
|
|
179
|
-
.prepare("SELECT 1 FROM sessions WHERE id = ?")
|
|
180
|
-
.get(sessionId);
|
|
181
|
-
if (!sessionExists) {
|
|
182
|
-
const err = new Error(`Session not found: ${sessionId}`) as GraphErr;
|
|
183
|
-
err.code = "SESSION_NOT_FOUND";
|
|
184
|
-
err.status = 404;
|
|
185
|
-
throw err;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
const versionRow = db
|
|
189
|
-
.prepare("SELECT graph_version AS graphVersion FROM sessions WHERE id = ?")
|
|
190
|
-
.get(sessionId) as { graphVersion?: number } | undefined;
|
|
191
|
-
const currentVersion = versionRow?.graphVersion ?? 0;
|
|
192
|
-
if (
|
|
193
|
-
typeof expectedVersion === "number" &&
|
|
194
|
-
Number.isFinite(expectedVersion) &&
|
|
195
|
-
expectedVersion !== currentVersion
|
|
196
|
-
) {
|
|
197
|
-
const err = new Error(
|
|
198
|
-
`Graph version conflict for session ${sessionId}: expected ${expectedVersion}, got ${currentVersion}`,
|
|
199
|
-
) as GraphErr;
|
|
200
|
-
err.code = "GRAPH_VERSION_CONFLICT";
|
|
201
|
-
err.status = 409;
|
|
202
|
-
err.currentVersion = currentVersion;
|
|
203
|
-
throw err;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
const normalized = normalizeGraphPayload(nodes, edges);
|
|
207
|
-
|
|
208
|
-
const tx = db.transaction(() => {
|
|
209
|
-
db.prepare("DELETE FROM nodes WHERE session_id = ?").run(sessionId);
|
|
210
|
-
db.prepare("DELETE FROM edges WHERE session_id = ?").run(sessionId);
|
|
211
|
-
|
|
212
|
-
const insNode = db.prepare(
|
|
213
|
-
"INSERT INTO nodes (session_id, id, x, y, data) VALUES (?, ?, ?, ?, ?)",
|
|
214
|
-
);
|
|
215
|
-
for (const n of normalized.nodes) {
|
|
216
|
-
if (!n?.id) continue;
|
|
217
|
-
const pos = (n.position ?? {}) as { x?: unknown; y?: unknown };
|
|
218
|
-
const x = Number((n.x ?? pos.x ?? 0) as number);
|
|
219
|
-
const y = Number((n.y ?? pos.y ?? 0) as number);
|
|
220
|
-
insNode.run(
|
|
221
|
-
sessionId,
|
|
222
|
-
cleanStr(String(n.id)),
|
|
223
|
-
Number.isFinite(x) ? x : 0,
|
|
224
|
-
Number.isFinite(y) ? y : 0,
|
|
225
|
-
cleanData(n.data),
|
|
226
|
-
);
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
const insEdge = db.prepare(
|
|
230
|
-
"INSERT INTO edges (session_id, id, source, target, data) VALUES (?, ?, ?, ?, ?)",
|
|
231
|
-
);
|
|
232
|
-
for (const e of normalized.edges) {
|
|
233
|
-
insEdge.run(
|
|
234
|
-
sessionId,
|
|
235
|
-
cleanStr(String(e.id)),
|
|
236
|
-
cleanStr(String(e.source)),
|
|
237
|
-
cleanStr(String(e.target)),
|
|
238
|
-
cleanData(e.data),
|
|
239
|
-
);
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
db.prepare("UPDATE sessions SET updated_at = ?, graph_version = graph_version + 1 WHERE id = ?").run(
|
|
243
|
-
now(),
|
|
244
|
-
sessionId,
|
|
245
|
-
);
|
|
246
|
-
|
|
247
|
-
return (db
|
|
248
|
-
.prepare("SELECT graph_version AS graphVersion FROM sessions WHERE id = ?")
|
|
249
|
-
.get(sessionId) as { graphVersion: number }).graphVersion;
|
|
250
|
-
});
|
|
251
|
-
|
|
252
|
-
const nextVersion = tx();
|
|
253
|
-
return { ok: true, graphVersion: nextVersion };
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
function safeParse(json: string): Record<string, unknown> {
|
|
257
|
-
try {
|
|
258
|
-
const parsed: unknown = JSON.parse(json);
|
|
259
|
-
return (parsed && typeof parsed === "object" ? parsed : {}) as Record<string, unknown>;
|
|
260
|
-
} catch {
|
|
261
|
-
return {};
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
export function ensureDefaultSession() {
|
|
266
|
-
const sessions = listSessions();
|
|
267
|
-
if (sessions.length > 0) return sessions[0];
|
|
268
|
-
return createSession({ title: "My first graph" });
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
// ── Style sheet (0.10) ───────────────────────────────────────────────────
|
|
272
|
-
export function getStyleSheet(sessionId: string) {
|
|
273
|
-
const db = getDb();
|
|
274
|
-
const row = db
|
|
275
|
-
.prepare(
|
|
276
|
-
"SELECT style_sheet AS styleSheet, style_sheet_enabled AS styleSheetEnabled FROM sessions WHERE id = ?",
|
|
277
|
-
)
|
|
278
|
-
.get(sessionId) as StyleSheetRow | undefined;
|
|
279
|
-
if (!row) return null;
|
|
280
|
-
let parsed = null;
|
|
281
|
-
if (row.styleSheet) {
|
|
282
|
-
try {
|
|
283
|
-
parsed = JSON.parse(row.styleSheet);
|
|
284
|
-
} catch {
|
|
285
|
-
parsed = null;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
return { styleSheet: parsed, enabled: !!row.styleSheetEnabled };
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
export function setStyleSheet(sessionId: string, sheet: unknown) {
|
|
292
|
-
const db = getDb();
|
|
293
|
-
const json = sheet == null ? null : JSON.stringify(sheet);
|
|
294
|
-
const res = db
|
|
295
|
-
.prepare("UPDATE sessions SET style_sheet = ?, updated_at = ? WHERE id = ?")
|
|
296
|
-
.run(json, now(), sessionId);
|
|
297
|
-
return res.changes > 0;
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
export function setStyleSheetEnabled(sessionId: string, enabled: boolean) {
|
|
301
|
-
const db = getDb();
|
|
302
|
-
const res = db
|
|
303
|
-
.prepare(
|
|
304
|
-
"UPDATE sessions SET style_sheet_enabled = ?, updated_at = ? WHERE id = ?",
|
|
305
|
-
)
|
|
306
|
-
.run(enabled ? 1 : 0, now(), sessionId);
|
|
307
|
-
return res.changes > 0;
|
|
308
|
-
}
|