artifacty 0.1.1 → 0.2.0

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.
@@ -15,7 +15,7 @@ const messages = {
15
15
  ...(globalThis.ARTIFACTY_I18N || {})
16
16
  };
17
17
 
18
- const SUPPORTED_FORMATS = ["markdown", "html", "json", "text", "code", "svg", "mermaid", "react"];
18
+ const SUPPORTED_FORMATS = ["markdown", "html", "json", "text", "code", "svg", "mermaid", "react", "sarif", "csv", "image", "video"];
19
19
 
20
20
  const editorTheme = EditorView.theme({
21
21
  "&": {
@@ -128,7 +128,7 @@ function enhanceTextarea(textarea) {
128
128
  updatePreview();
129
129
 
130
130
  function updateToolbar(format) {
131
- formatJsonButton.hidden = format !== "json";
131
+ formatJsonButton.hidden = format !== "json" && format !== "sarif";
132
132
  status.textContent = formatLabel(format);
133
133
  }
134
134
 
@@ -158,7 +158,7 @@ function enhanceTextarea(textarea) {
158
158
  return;
159
159
  }
160
160
 
161
- if (format === "json") {
161
+ if (format === "json" || format === "sarif") {
162
162
  const pre = document.createElement("pre");
163
163
  try {
164
164
  pre.textContent = JSON.stringify(JSON.parse(content), null, 2);
@@ -191,7 +191,7 @@ function languageExtension(format) {
191
191
  if (format === "html" || format === "svg") {
192
192
  return html();
193
193
  }
194
- if (format === "json") {
194
+ if (format === "json" || format === "sarif") {
195
195
  return json();
196
196
  }
197
197
  if (format === "markdown") {
@@ -212,6 +212,18 @@ function detectFormat({ explicit, fileName, content }) {
212
212
  if (lowerName.endsWith(".md") || lowerName.endsWith(".markdown")) {
213
213
  return "markdown";
214
214
  }
215
+ if (lowerName.endsWith(".sarif") || lowerName.endsWith(".sarif.json")) {
216
+ return "sarif";
217
+ }
218
+ if (lowerName.endsWith(".csv")) {
219
+ return "csv";
220
+ }
221
+ if (/\.(png|jpe?g|gif|webp)$/.test(lowerName)) {
222
+ return "image";
223
+ }
224
+ if (/\.(mp4|webm)$/.test(lowerName)) {
225
+ return "video";
226
+ }
215
227
  if (lowerName.endsWith(".json")) {
216
228
  return "json";
217
229
  }
@@ -241,6 +253,18 @@ function detectFormat({ explicit, fileName, content }) {
241
253
  if (trimmed.startsWith("<!doctype") || trimmed.startsWith("<html") || trimmed.startsWith("<")) {
242
254
  return "html";
243
255
  }
256
+ if (looksLikeSarif(trimmed)) {
257
+ return "sarif";
258
+ }
259
+ if (looksLikeCsv(trimmed)) {
260
+ return "csv";
261
+ }
262
+ if (/^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(trimmed)) {
263
+ return "image";
264
+ }
265
+ if (/^data:video\/(?:mp4|webm);base64,/i.test(trimmed)) {
266
+ return "video";
267
+ }
244
268
  if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
245
269
  return "json";
246
270
  }
@@ -255,6 +279,54 @@ function formatLabel(format) {
255
279
  return messages.mode.replaceAll("{format}", label);
256
280
  }
257
281
 
282
+ function looksLikeSarif(value) {
283
+ const trimmed = String(value || "").trim();
284
+ if (!trimmed.startsWith("{")) {
285
+ return false;
286
+ }
287
+ try {
288
+ const parsed = JSON.parse(trimmed);
289
+ return parsed &&
290
+ typeof parsed === "object" &&
291
+ Array.isArray(parsed.runs) &&
292
+ (typeof parsed.version === "string" || String(parsed.$schema || "").toLowerCase().includes("sarif"));
293
+ } catch {
294
+ return false;
295
+ }
296
+ }
297
+
298
+ function looksLikeCsv(value) {
299
+ const lines = String(value || "")
300
+ .trim()
301
+ .split(/\r?\n/)
302
+ .map((line) => line.trimEnd())
303
+ .filter(Boolean)
304
+ .slice(0, 5);
305
+ if (lines.length < 2 || lines[0].trimStart().startsWith("|")) {
306
+ return false;
307
+ }
308
+ const counts = lines.map(csvFieldCount);
309
+ return counts[0] > 1 && counts.every((count) => count === counts[0]);
310
+ }
311
+
312
+ function csvFieldCount(line) {
313
+ let count = 1;
314
+ let inQuotes = false;
315
+ for (let index = 0; index < line.length; index += 1) {
316
+ const char = line[index];
317
+ if (char === "\"") {
318
+ if (inQuotes && line[index + 1] === "\"") {
319
+ index += 1;
320
+ } else {
321
+ inQuotes = !inQuotes;
322
+ }
323
+ } else if (char === "," && !inQuotes) {
324
+ count += 1;
325
+ }
326
+ }
327
+ return count;
328
+ }
329
+
258
330
  function invalidJsonMessage(error) {
259
331
  return messages.invalidJson.replaceAll("{message}", error.message);
260
332
  }
@@ -0,0 +1,344 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { createStore } from "./storage.js";
6
+ import { readServerState, serverStatePath } from "./server-state.js";
7
+
8
+ const DEFAULT_READY_TIMEOUT_MS = 5000;
9
+
10
+ export async function startBackgroundServer(options = {}) {
11
+ if (options.generateToken && options.apiToken) {
12
+ throw new Error("Use either --api-token or --generate-token, not both");
13
+ }
14
+
15
+ const store = createStore({ home: options.home });
16
+ const paths = backgroundPaths(store);
17
+ const current = await backgroundStatus({ home: store.home });
18
+ if (current.running) {
19
+ throw new Error(`Artifacty server is already running on ${current.url || "unknown URL"} (pid ${current.pid})`);
20
+ }
21
+
22
+ mkdirSync(paths.logDir, { recursive: true });
23
+ mkdirSync(store.home, { recursive: true });
24
+
25
+ const child = spawnDetachedServer(options, store, paths);
26
+
27
+ writeFileSync(paths.pidFile, `${child.pid}\n`, "utf8");
28
+
29
+ try {
30
+ const ready = await waitForReady({
31
+ store,
32
+ pid: child.pid,
33
+ timeoutMs: Number(options.timeout || DEFAULT_READY_TIMEOUT_MS)
34
+ });
35
+ child.unref();
36
+ return {
37
+ action: "start",
38
+ running: true,
39
+ pid: child.pid,
40
+ url: ready.url,
41
+ home: store.home,
42
+ logs: {
43
+ stdout: paths.stdoutLog,
44
+ stderr: paths.stderrLog
45
+ },
46
+ statePath: serverStatePath(store)
47
+ };
48
+ } catch (error) {
49
+ try {
50
+ await terminatePid(child.pid);
51
+ } catch {
52
+ // Process may already have exited during startup.
53
+ }
54
+ rmSync(paths.pidFile, { force: true });
55
+ const logTail = await tailFile(paths.stderrLog);
56
+ const message = logTail ? `${error.message}\n${logTail}` : error.message;
57
+ throw new Error(message);
58
+ }
59
+ }
60
+
61
+ export async function stopBackgroundServer(options = {}) {
62
+ const store = createStore({ home: options.home });
63
+ const paths = backgroundPaths(store);
64
+ const status = await backgroundStatus({ home: store.home });
65
+
66
+ if (!status.pid || !status.pidFileExists) {
67
+ return {
68
+ action: "stop",
69
+ stopped: false,
70
+ running: status.running,
71
+ reason: status.pid ? "server was not started by artifacty start" : "server is not running",
72
+ pid: status.pid || null,
73
+ home: store.home
74
+ };
75
+ }
76
+
77
+ if (!status.processRunning) {
78
+ rmSync(paths.pidFile, { force: true });
79
+ return {
80
+ action: "stop",
81
+ stopped: false,
82
+ running: false,
83
+ reason: "removed stale pid file",
84
+ pid: status.pid,
85
+ home: store.home
86
+ };
87
+ }
88
+
89
+ if (!options.force && !status.stateMatchesPid && !status.healthy) {
90
+ return {
91
+ action: "stop",
92
+ stopped: false,
93
+ running: status.running,
94
+ reason: "pid file does not match a healthy Artifacty server; retry with --force to stop the recorded pid",
95
+ pid: status.pid,
96
+ home: store.home
97
+ };
98
+ }
99
+
100
+ await terminatePid(status.pid);
101
+ let stopped = await waitForStop(status.pid, Number(options.timeout || DEFAULT_READY_TIMEOUT_MS));
102
+ if (!stopped && options.force) {
103
+ await terminatePid(status.pid, { force: true });
104
+ stopped = await waitForStop(status.pid, 1000);
105
+ }
106
+ if (!stopped) {
107
+ return {
108
+ action: "stop",
109
+ stopped: false,
110
+ running: true,
111
+ reason: "server did not stop before timeout; retry with --force",
112
+ pid: status.pid,
113
+ home: store.home
114
+ };
115
+ }
116
+ rmSync(paths.pidFile, { force: true });
117
+
118
+ return {
119
+ action: "stop",
120
+ stopped: true,
121
+ running: false,
122
+ pid: status.pid,
123
+ home: store.home
124
+ };
125
+ }
126
+
127
+ export async function backgroundStatus(options = {}) {
128
+ const store = createStore({ home: options.home });
129
+ const paths = backgroundPaths(store);
130
+ const state = await readServerState(store);
131
+ const pidFromFile = readPidFile(paths.pidFile);
132
+ const pid = pidFromFile || state?.pid || null;
133
+ const processRunning = pid ? isPidRunning(pid) : false;
134
+ const health = state?.url ? await fetchHealth(state.url) : { ok: false };
135
+ const stateMatchesPid = Boolean(pid && state?.pid === pid);
136
+
137
+ return {
138
+ action: "status",
139
+ running: Boolean(processRunning && health.ok),
140
+ processRunning,
141
+ healthy: Boolean(health.ok),
142
+ platform: process.platform,
143
+ pid,
144
+ statePid: state?.pid || null,
145
+ stateMatchesPid,
146
+ pidFileExists: existsSync(paths.pidFile),
147
+ managed: Boolean(pidFromFile),
148
+ url: state?.url || null,
149
+ home: store.home,
150
+ logs: {
151
+ stdout: paths.stdoutLog,
152
+ stderr: paths.stderrLog
153
+ },
154
+ statePath: serverStatePath(store)
155
+ };
156
+ }
157
+
158
+ export function backgroundPaths(store) {
159
+ const logDir = path.join(store.home, "logs");
160
+ return {
161
+ logDir,
162
+ pidFile: path.join(store.home, "server.pid"),
163
+ stdoutLog: path.join(logDir, "server.out.log"),
164
+ stderrLog: path.join(logDir, "server.err.log")
165
+ };
166
+ }
167
+
168
+ export function stopCommandForPlatform(pid, options = {}, platform = process.platform) {
169
+ if (platform !== "win32") {
170
+ return null;
171
+ }
172
+ const args = ["/PID", String(pid), "/T"];
173
+ if (options.force) {
174
+ args.push("/F");
175
+ }
176
+ return { command: "taskkill", args };
177
+ }
178
+
179
+ function spawnDetachedServer(options, store, paths) {
180
+ let stdoutFd;
181
+ let stderrFd;
182
+ try {
183
+ stdoutFd = openSync(paths.stdoutLog, "a");
184
+ stderrFd = openSync(paths.stderrLog, "a");
185
+ return spawn(process.execPath, buildServerArgs(options, store), {
186
+ detached: true,
187
+ env: buildServerEnv(options),
188
+ stdio: ["ignore", stdoutFd, stderrFd],
189
+ windowsHide: true
190
+ });
191
+ } finally {
192
+ closeFd(stdoutFd);
193
+ closeFd(stderrFd);
194
+ }
195
+ }
196
+
197
+ export function buildServerArgs(options, store) {
198
+ const args = [options.serverPath];
199
+ addValueArg(args, "--host", options.host);
200
+ addValueArg(args, "--port", options.port);
201
+ addValueArg(args, "--home", store.home);
202
+ addValueArg(args, "--share-mode", options.shareMode);
203
+ addValueArg(args, "--bytes", options.bytes);
204
+ if (options.generateToken) {
205
+ args.push("--generate-token");
206
+ }
207
+ if (options.allowSecrets) {
208
+ args.push("--allow-secrets");
209
+ }
210
+ return args;
211
+ }
212
+
213
+ function buildServerEnv(options) {
214
+ return {
215
+ ...process.env,
216
+ ...(options.apiToken ? { ARTIFACTY_API_TOKEN: options.apiToken } : {})
217
+ };
218
+ }
219
+
220
+ async function terminatePid(pid, options = {}) {
221
+ const command = stopCommandForPlatform(pid, options);
222
+ if (command) {
223
+ await execFileQuiet(command.command, command.args).catch((error) => {
224
+ if (!isPidRunning(pid)) {
225
+ return;
226
+ }
227
+ throw new Error(`Failed to stop Windows process ${pid}: ${error.stderr || error.message}`);
228
+ });
229
+ return;
230
+ }
231
+
232
+ const signal = options.force ? "SIGKILL" : "SIGTERM";
233
+ try {
234
+ process.kill(-pid, signal);
235
+ } catch {
236
+ try {
237
+ process.kill(pid, signal);
238
+ } catch (error) {
239
+ if (error.code !== "ESRCH") {
240
+ throw error;
241
+ }
242
+ }
243
+ }
244
+ }
245
+
246
+ function execFileQuiet(command, args) {
247
+ return new Promise((resolve, reject) => {
248
+ execFile(command, args, { windowsHide: true }, (error, stdout, stderr) => {
249
+ if (error) {
250
+ reject(Object.assign(error, { stdout, stderr }));
251
+ return;
252
+ }
253
+ resolve({ stdout, stderr });
254
+ });
255
+ });
256
+ }
257
+
258
+ function addValueArg(args, name, value) {
259
+ if (value !== undefined && value !== null && value !== "") {
260
+ args.push(name, String(value));
261
+ }
262
+ }
263
+
264
+ async function waitForReady({ store, pid, timeoutMs }) {
265
+ const deadline = Date.now() + timeoutMs;
266
+ while (Date.now() < deadline) {
267
+ if (!isPidRunning(pid)) {
268
+ throw new Error("Artifacty server exited before it became ready");
269
+ }
270
+ const state = await readServerState(store);
271
+ if (state?.pid === pid && state.url) {
272
+ const health = await fetchHealth(state.url);
273
+ if (health.ok) {
274
+ return state;
275
+ }
276
+ }
277
+ await delay(100);
278
+ }
279
+ throw new Error(`Timed out waiting for Artifacty server to become ready after ${timeoutMs}ms`);
280
+ }
281
+
282
+ async function waitForStop(pid, timeoutMs) {
283
+ const deadline = Date.now() + timeoutMs;
284
+ while (Date.now() < deadline) {
285
+ if (!isPidRunning(pid)) {
286
+ return true;
287
+ }
288
+ await delay(100);
289
+ }
290
+ return !isPidRunning(pid);
291
+ }
292
+
293
+ function readPidFile(pidFile) {
294
+ try {
295
+ const pid = Number(readFileSync(pidFile, "utf8").trim());
296
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
297
+ } catch {
298
+ return null;
299
+ }
300
+ }
301
+
302
+ function isPidRunning(pid) {
303
+ try {
304
+ process.kill(pid, 0);
305
+ return true;
306
+ } catch (error) {
307
+ return error.code === "EPERM";
308
+ }
309
+ }
310
+
311
+ async function fetchHealth(url) {
312
+ try {
313
+ const response = await fetch(`${url}/health`, {
314
+ signal: AbortSignal.timeout(500)
315
+ });
316
+ return { ok: response.ok, status: response.status };
317
+ } catch {
318
+ return { ok: false };
319
+ }
320
+ }
321
+
322
+ async function tailFile(file, maxBytes = 2000) {
323
+ try {
324
+ const content = await readFile(file, "utf8");
325
+ return content.slice(-maxBytes).trim();
326
+ } catch {
327
+ return "";
328
+ }
329
+ }
330
+
331
+ function delay(ms) {
332
+ return new Promise((resolve) => setTimeout(resolve, ms));
333
+ }
334
+
335
+ function closeFd(fd) {
336
+ if (typeof fd !== "number") {
337
+ return;
338
+ }
339
+ try {
340
+ closeSync(fd);
341
+ } catch {
342
+ // The child inherited the descriptor; parent cleanup is best effort.
343
+ }
344
+ }