@songloft/plugin-builder 2.0.0-alpha.1

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/dist/cli.js ADDED
@@ -0,0 +1,800 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/build.ts
4
+ import * as esbuild from "esbuild";
5
+ import JSZip from "jszip";
6
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, mkdirSync, existsSync, cpSync, unlinkSync, readdirSync as readdirSyncTop } from "fs";
7
+ import { join as join4, resolve, dirname as dirname2 } from "path";
8
+ import { execFileSync } from "child_process";
9
+ import { fileURLToPath } from "url";
10
+
11
+ // src/manifest.ts
12
+ import { readFileSync } from "fs";
13
+ import { join } from "path";
14
+ var ENTRY_PATH_REGEX = /^[a-z][a-z0-9-]*$/;
15
+ var SEMVER_REGEX = /^\d+\.\d+\.\d+/;
16
+ var VALID_PERMISSIONS = [
17
+ "storage",
18
+ "songs.read",
19
+ "songs.write",
20
+ "songs.*",
21
+ "playlists.read",
22
+ "playlists.write",
23
+ "playlists.*",
24
+ "inter-plugin",
25
+ "command",
26
+ "jsenv"
27
+ ];
28
+ function readManifest(cwd) {
29
+ const raw = readFileSync(join(cwd, "plugin.json"), "utf-8");
30
+ return JSON.parse(raw);
31
+ }
32
+ function validateManifest(m) {
33
+ const errors = [];
34
+ if (!m.name || m.name.length < 2 || m.name.length > 50) {
35
+ errors.push({ field: "name", message: "name must be 2-50 characters" });
36
+ }
37
+ if (!m.version || !SEMVER_REGEX.test(m.version)) {
38
+ errors.push({ field: "version", message: "version must be valid semver (x.y.z)" });
39
+ }
40
+ if (!m.entryPath || !ENTRY_PATH_REGEX.test(m.entryPath)) {
41
+ errors.push({ field: "entryPath", message: "entryPath must be lowercase kebab-case starting with a letter" });
42
+ }
43
+ if (!m.main || !m.main.endsWith(".js") && !m.main.endsWith(".jsc")) {
44
+ errors.push({ field: "main", message: "main must end with .js or .jsc" });
45
+ }
46
+ if (!Array.isArray(m.permissions)) {
47
+ errors.push({ field: "permissions", message: "permissions must be an array" });
48
+ } else {
49
+ for (const perm of m.permissions) {
50
+ if (!VALID_PERMISSIONS.includes(perm)) {
51
+ errors.push({ field: "permissions", message: `unknown permission: ${perm}` });
52
+ }
53
+ }
54
+ }
55
+ return errors;
56
+ }
57
+
58
+ // src/hash.ts
59
+ import { createHash } from "crypto";
60
+ import { readFileSync as readFileSync2, readdirSync, statSync } from "fs";
61
+ import { join as join2, relative, posix } from "path";
62
+ function sha256Hex(data) {
63
+ return createHash("sha256").update(data).digest("hex");
64
+ }
65
+ function computeEntryHash(mainJsContent) {
66
+ return sha256Hex(mainJsContent);
67
+ }
68
+ function computeCanonicalZipHash(buildDir) {
69
+ const entries = [];
70
+ function walk2(dir) {
71
+ const items = readdirSync(dir);
72
+ for (const item of items) {
73
+ const fullPath = join2(dir, item);
74
+ const stat = statSync(fullPath);
75
+ if (stat.isDirectory()) {
76
+ walk2(fullPath);
77
+ } else {
78
+ const relPath = posix.normalize(relative(buildDir, fullPath).replace(/\\/g, "/"));
79
+ if (relPath === "plugin.json") continue;
80
+ const content = readFileSync2(fullPath);
81
+ entries.push({ path: relPath, hash: sha256Hex(content) });
82
+ }
83
+ }
84
+ }
85
+ walk2(buildDir);
86
+ entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
87
+ const hasher = createHash("sha256");
88
+ for (const e of entries) {
89
+ hasher.update(e.path + "\n" + e.hash + "\n");
90
+ }
91
+ return hasher.digest("hex");
92
+ }
93
+
94
+ // src/static-assets.ts
95
+ import { readFileSync as readFileSync3, writeFileSync, renameSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
96
+ import { join as join3, dirname, basename, posix as posix2, relative as relative2 } from "path";
97
+ var ASSET_EXT = /\.(woff2?|ttf|otf|eot|png|jpe?g|gif|svg|webp|ico|mp3|mp4|wav|ogg)$/i;
98
+ var CSS_EXT = /\.css$/i;
99
+ var JS_EXT = /\.m?js$/i;
100
+ var HTML_EXT = /\.html?$/i;
101
+ var HASH_LEN = 8;
102
+ var HASHED_NAME_RE = /^(.+)[.-]([A-Za-z0-9_-]{8,})\.[^.]+$/;
103
+ function looksAlreadyHashed(filename) {
104
+ const m = HASHED_NAME_RE.exec(filename);
105
+ if (!m) return false;
106
+ const seg = m[2];
107
+ return /[A-Za-z]/.test(seg) && /\d/.test(seg);
108
+ }
109
+ function hashStaticAssets(staticBuildDir) {
110
+ const all = walk(staticBuildDir);
111
+ const rel = (p) => toPosix(relative2(staticBuildDir, p));
112
+ const assets = all.filter((p) => ASSET_EXT.test(p));
113
+ const cssList = all.filter((p) => CSS_EXT.test(p));
114
+ const jsList = all.filter((p) => JS_EXT.test(p));
115
+ const htmlList = all.filter((p) => HTML_EXT.test(p));
116
+ const pinned = collectPinnedAssets([...htmlList, ...cssList, ...jsList], rel, staticBuildDir);
117
+ const notPinned = (p) => !pinned.has(rel(p));
118
+ const renameMap = /* @__PURE__ */ new Map();
119
+ for (const file of assets.filter(notPinned)) {
120
+ const newRel = renameWithHash(staticBuildDir, rel(file));
121
+ renameMap.set(rel(file), newRel);
122
+ }
123
+ for (const file of cssList) {
124
+ const relPath = rel(file);
125
+ const content = readFileSync3(file, "utf-8");
126
+ const rewritten = rewriteCssUrls(content, relPath, renameMap);
127
+ if (rewritten !== content) writeFileSync(file, rewritten);
128
+ if (pinned.has(relPath)) continue;
129
+ const newRel = renameWithHash(staticBuildDir, relPath);
130
+ renameMap.set(relPath, newRel);
131
+ }
132
+ for (const file of jsList.filter(notPinned)) {
133
+ const newRel = renameWithHash(staticBuildDir, rel(file));
134
+ renameMap.set(rel(file), newRel);
135
+ }
136
+ for (const file of htmlList) {
137
+ const relPath = rel(file);
138
+ const html = readFileSync3(file, "utf-8");
139
+ const rewritten = rewriteHtmlRefs(html, relPath, renameMap);
140
+ if (rewritten !== html) writeFileSync(file, rewritten);
141
+ }
142
+ return { renamed: renameMap.size };
143
+ }
144
+ function collectPinnedAssets(files, rel, staticDir) {
145
+ const pinned = /* @__PURE__ */ new Set();
146
+ const re = /\/(?:[^\s"')]*\/)?static\/([A-Za-z0-9_\-./]+?)(?=["')?#\s]|$)/g;
147
+ for (const file of files) {
148
+ let content;
149
+ try {
150
+ content = readFileSync3(file, "utf-8");
151
+ } catch {
152
+ continue;
153
+ }
154
+ for (const m of content.matchAll(re)) {
155
+ const candidate = m[1].replace(/\/+$/, "");
156
+ if (!candidate) continue;
157
+ const abs = join3(staticDir, candidate);
158
+ try {
159
+ if (statSync2(abs).isFile()) pinned.add(candidate);
160
+ } catch {
161
+ }
162
+ }
163
+ }
164
+ return pinned;
165
+ }
166
+ function walk(dir) {
167
+ const out = [];
168
+ for (const item of readdirSync2(dir)) {
169
+ const full = join3(dir, item);
170
+ const st = statSync2(full);
171
+ if (st.isDirectory()) out.push(...walk(full));
172
+ else out.push(full);
173
+ }
174
+ return out;
175
+ }
176
+ function toPosix(p) {
177
+ return p.split(/[\\/]/).join("/");
178
+ }
179
+ function renameWithHash(rootDir, relPath) {
180
+ const base = basename(relPath);
181
+ if (looksAlreadyHashed(base)) return relPath;
182
+ const abs = join3(rootDir, relPath);
183
+ const hash = sha256Hex(readFileSync3(abs)).slice(0, HASH_LEN);
184
+ const dir = dirname(relPath);
185
+ const dot = base.lastIndexOf(".");
186
+ const newBase = dot <= 0 ? `${base}.${hash}` : `${base.slice(0, dot)}.${hash}${base.slice(dot)}`;
187
+ const newRel = dir === "." || dir === "" ? newBase : posix2.join(toPosix(dir), newBase);
188
+ renameSync(abs, join3(rootDir, newRel));
189
+ return newRel;
190
+ }
191
+ function resolveRef(url, fromFile) {
192
+ if (!url) return null;
193
+ if (/^(?:[a-z]+:|\/\/|#|data:|blob:|mailto:)/i.test(url)) return null;
194
+ if (url.startsWith("/")) return null;
195
+ let bare = url;
196
+ let suffix = "";
197
+ const qIdx = bare.search(/[?#]/);
198
+ if (qIdx >= 0) {
199
+ suffix = bare.slice(qIdx);
200
+ bare = bare.slice(0, qIdx);
201
+ }
202
+ const hadStaticPrefix = bare.startsWith("static/");
203
+ const isExplicitRelative = bare.startsWith("./") || bare.startsWith("../");
204
+ let staticRel;
205
+ if (hadStaticPrefix) {
206
+ staticRel = bare.slice("static/".length);
207
+ } else {
208
+ const fromDir = toPosix(dirname(fromFile));
209
+ staticRel = fromDir === "." || fromDir === "" ? bare.replace(/^\.\//, "") : posix2.normalize(posix2.join(fromDir, bare));
210
+ }
211
+ if (staticRel.startsWith("..")) return null;
212
+ return { staticRel, suffix, hadStaticPrefix, isExplicitRelative };
213
+ }
214
+ function applyRename(ref, renameMap, fromFile) {
215
+ const renamed = renameMap.get(ref.staticRel);
216
+ if (!renamed) return null;
217
+ let out;
218
+ if (ref.hadStaticPrefix) {
219
+ out = `static/${renamed}`;
220
+ } else {
221
+ const fromDir = toPosix(dirname(fromFile));
222
+ if (fromDir === "." || fromDir === "") {
223
+ out = renamed;
224
+ } else {
225
+ out = toPosix(relative2(fromDir, renamed));
226
+ }
227
+ if (ref.isExplicitRelative && !out.startsWith(".")) out = `./${out}`;
228
+ }
229
+ return out + ref.suffix;
230
+ }
231
+ function tryRewrite(url, fromFile, renameMap) {
232
+ const ref = resolveRef(url, fromFile);
233
+ if (!ref) return null;
234
+ return applyRename(ref, renameMap, fromFile);
235
+ }
236
+ function rewriteHtmlRefs(html, fromFile, renameMap) {
237
+ return html.replace(/\b(src|href)\s*=\s*(["'])([^"']+)\2/gi, (full, attr, quote, url) => {
238
+ const replaced = tryRewrite(url, fromFile, renameMap);
239
+ return replaced == null ? full : `${attr}=${quote}${replaced}${quote}`;
240
+ });
241
+ }
242
+ function rewriteCssUrls(css, fromFile, renameMap) {
243
+ css = css.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi, (full, quote, url) => {
244
+ const replaced = tryRewrite(url, fromFile, renameMap);
245
+ return replaced == null ? full : `url(${quote}${replaced}${quote})`;
246
+ });
247
+ css = css.replace(/@import\s+(['"])([^'"]+)\1/gi, (full, quote, url) => {
248
+ const replaced = tryRewrite(url, fromFile, renameMap);
249
+ return replaced == null ? full : `@import ${quote}${replaced}${quote}`;
250
+ });
251
+ return css;
252
+ }
253
+
254
+ // src/build.ts
255
+ import { getJscBinaryPath } from "@songloft/jsc";
256
+ import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
257
+ async function buildPlugin(opts) {
258
+ const cwd = resolve(opts.cwd);
259
+ const outDir = opts.outDir ? resolve(cwd, opts.outDir) : join4(cwd, "dist");
260
+ const buildDir = join4(outDir, "_build");
261
+ const mode = opts.mode ?? "production";
262
+ const manifest = readManifest(cwd);
263
+ const errors = validateManifest(manifest);
264
+ if (errors.length > 0) {
265
+ throw new Error(`Invalid plugin.json:
266
+ ${errors.map((e) => ` - ${e.field}: ${e.message}`).join("\n")}`);
267
+ }
268
+ mkdirSync(buildDir, { recursive: true });
269
+ const entryPoint = join4(cwd, "src", "main.ts");
270
+ const entryPointAlt = join4(cwd, "src", "main.js");
271
+ const actualEntry = existsSync(entryPoint) ? entryPoint : entryPointAlt;
272
+ if (!existsSync(actualEntry)) {
273
+ throw new Error(`Entry file not found: src/main.ts or src/main.js`);
274
+ }
275
+ await esbuild.build({
276
+ entryPoints: [actualEntry],
277
+ outfile: join4(buildDir, "main.js"),
278
+ bundle: true,
279
+ platform: "neutral",
280
+ format: "iife",
281
+ target: "es2020",
282
+ minify: mode === "production",
283
+ sourcemap: opts.sourcemap ? "inline" : false,
284
+ // 禁止使用 Node 内置模块
285
+ plugins: [{
286
+ name: "no-node-builtins",
287
+ setup(build2) {
288
+ build2.onResolve({ filter: /^(fs|net|http|https|child_process|os|path|crypto|stream|util|events|buffer|url|querystring|zlib)$/ }, (args2) => {
289
+ return { errors: [{ text: `Node builtin "${args2.path}" is not available in QuickJS runtime` }] };
290
+ });
291
+ }
292
+ }]
293
+ });
294
+ const staticDir = join4(cwd, "static");
295
+ if (existsSync(staticDir)) {
296
+ cpSync(staticDir, join4(buildDir, "static"), { recursive: true });
297
+ }
298
+ const staticJsAppPath = join4(buildDir, "static", "js", "app.js");
299
+ if (existsSync(staticJsAppPath)) {
300
+ const bundleOutPath = join4(buildDir, "static", "js", "app.bundle.js");
301
+ await esbuild.build({
302
+ entryPoints: [staticJsAppPath],
303
+ outfile: bundleOutPath,
304
+ bundle: true,
305
+ platform: "browser",
306
+ format: "iife",
307
+ target: "es2020",
308
+ minify: mode === "production"
309
+ });
310
+ const staticJsDir = join4(buildDir, "static", "js");
311
+ const jsFiles = readdirSyncTop(staticJsDir).filter((f) => f.endsWith(".js") && f !== "app.bundle.js");
312
+ for (const f of jsFiles) {
313
+ unlinkSync(join4(staticJsDir, f));
314
+ }
315
+ const indexHtmlPath = join4(buildDir, "static", "index.html");
316
+ if (existsSync(indexHtmlPath)) {
317
+ let html = readFileSync4(indexHtmlPath, "utf-8");
318
+ const before = html;
319
+ html = html.replace(
320
+ /<script\b[^>]*\bsrc="(?:static\/)?js\/app\.js"[^>]*><\/script>/,
321
+ '<script src="static/js/app.bundle.js"></script>'
322
+ );
323
+ if (html === before) {
324
+ throw new Error(
325
+ 'Failed to update script tag in static/index.html: expected <script ... src="static/js/app.js" ...> or <script ... src="js/app.js" ...> but pattern not found'
326
+ );
327
+ }
328
+ writeFileSync2(indexHtmlPath, html);
329
+ }
330
+ console.log(` \u{1F4E6} static/js/ bundled \u2192 app.bundle.js (${jsFiles.length} files merged)`);
331
+ }
332
+ const staticBuildDir = join4(buildDir, "static");
333
+ if (existsSync(staticBuildDir) && manifest.staticHash !== false) {
334
+ const { renamed } = hashStaticAssets(staticBuildDir);
335
+ if (renamed > 0) {
336
+ console.log(` \u{1F3F7}\uFE0F static assets hashed (${renamed} files)`);
337
+ }
338
+ }
339
+ let mainFileName = "main.js";
340
+ const mainJsPath = join4(buildDir, "main.js");
341
+ const mainJscPath = join4(buildDir, "main.jsc");
342
+ try {
343
+ const jscCmd = findJscBinary();
344
+ if (!jscCmd) {
345
+ throw new Error("jsc binary not found");
346
+ }
347
+ execFileSync(jscCmd, [mainJsPath, mainJscPath], { stdio: "pipe" });
348
+ unlinkSync(mainJsPath);
349
+ mainFileName = "main.jsc";
350
+ console.log(` \u{1F512} main.js compiled \u2192 main.jsc (via ${jscCmd})`);
351
+ } catch {
352
+ console.log(` \u26A0\uFE0F jsc not available, keeping main.js`);
353
+ }
354
+ const mainJsContent = readFileSync4(join4(buildDir, mainFileName));
355
+ const entryHash = computeEntryHash(mainJsContent);
356
+ const zipHash = computeCanonicalZipHash(buildDir);
357
+ const finalManifest = {
358
+ ...manifest,
359
+ main: mainFileName,
360
+ entryHash,
361
+ zipHash
362
+ };
363
+ writeFileSync2(join4(buildDir, "plugin.json"), JSON.stringify(finalManifest, null, 2));
364
+ mkdirSync(outDir, { recursive: true });
365
+ const zip = new JSZip();
366
+ addDirToZip(zip, buildDir, "");
367
+ const zipBuffer = await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" });
368
+ const zipPath = join4(outDir, `${manifest.entryPath}.jsplugin.zip`);
369
+ writeFileSync2(zipPath, zipBuffer);
370
+ const metaPath = join4(outDir, `${manifest.entryPath}.json`);
371
+ writeFileSync2(metaPath, JSON.stringify({
372
+ version: manifest.version,
373
+ download_url: `https://github.com/songloft-org/plugins/releases/download/jsplugin-${manifest.entryPath}-${manifest.version}/${manifest.entryPath}.jsplugin.zip`
374
+ }, null, 2));
375
+ const mainJsGzip = Buffer.byteLength(mainJsContent);
376
+ console.log(`
377
+ \u2705 Build successful!`);
378
+ console.log(` \u{1F4E6} ${zipPath} (${(zipBuffer.length / 1024).toFixed(1)} KB)`);
379
+ console.log(` \u{1F4C4} main.js: ${(mainJsGzip / 1024).toFixed(1)} KB`);
380
+ console.log(` \u{1F511} entryHash: ${entryHash}`);
381
+ console.log(` \u{1F511} zipHash: ${zipHash}
382
+ `);
383
+ return { zipPath, manifest: finalManifest, size: zipBuffer.length, entryHash, zipHash };
384
+ }
385
+ async function validatePlugin(cwd) {
386
+ const resolvedCwd = resolve(cwd);
387
+ const errors = [];
388
+ let manifest;
389
+ try {
390
+ manifest = readManifest(resolvedCwd);
391
+ } catch {
392
+ return { valid: false, errors: [{ field: "plugin.json", message: "cannot read plugin.json" }] };
393
+ }
394
+ const fieldErrors = validateManifest(manifest);
395
+ errors.push(...fieldErrors);
396
+ if (!manifest.entryHash || !manifest.zipHash) {
397
+ errors.push({ field: "hash", message: "entryHash and zipHash are required. Run `songloft-plugin build` first." });
398
+ }
399
+ return { valid: errors.length === 0, errors };
400
+ }
401
+ function findJscBinary() {
402
+ const currentDir = dirname2(fileURLToPath(import.meta.url));
403
+ try {
404
+ const jscPath = getJscBinaryPath();
405
+ if (existsSync(jscPath)) return jscPath;
406
+ } catch {
407
+ }
408
+ try {
409
+ execFileSync("jsc", ["--help"], { stdio: "pipe" });
410
+ return "jsc";
411
+ } catch {
412
+ }
413
+ const projectJsc = join4(currentDir, "..", "..", "..", "..", "jsc");
414
+ if (existsSync(projectJsc)) return projectJsc;
415
+ return null;
416
+ }
417
+ function addDirToZip(zip, dirPath, prefix) {
418
+ const items = readdirSync3(dirPath);
419
+ for (const item of items) {
420
+ const fullPath = join4(dirPath, item);
421
+ const zipPath = prefix ? `${prefix}/${item}` : item;
422
+ const stat = statSync3(fullPath);
423
+ if (stat.isDirectory()) {
424
+ addDirToZip(zip, fullPath, zipPath);
425
+ } else {
426
+ zip.file(zipPath, readFileSync4(fullPath));
427
+ }
428
+ }
429
+ }
430
+
431
+ // src/dev.ts
432
+ import { existsSync as existsSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync3, watch } from "fs";
433
+ import { join as join5, resolve as resolve2 } from "path";
434
+ import { createInterface } from "readline";
435
+ var CONFIG_FILE = ".songloft-dev.json";
436
+ var DEFAULT_HOST = "http://localhost:58091";
437
+ var WATCH_DIRS = ["src", "static"];
438
+ var WATCH_FILES = ["plugin.json"];
439
+ var DEBOUNCE_MS = 250;
440
+ var AuthError = class extends Error {
441
+ };
442
+ async function runDev(opts) {
443
+ const cwd = resolve2(opts.cwd);
444
+ const host = normalizeHost(opts.host ?? loadConfig(cwd).host ?? DEFAULT_HOST);
445
+ const state = {
446
+ config: loadConfig(cwd),
447
+ token: ""
448
+ };
449
+ await ensureAuth(cwd, host, opts, state);
450
+ let running = false;
451
+ let pending = false;
452
+ const runOnce = async (label) => {
453
+ if (running) {
454
+ pending = true;
455
+ return;
456
+ }
457
+ running = true;
458
+ try {
459
+ await doBuildUpload(cwd, host, opts, state, label);
460
+ } finally {
461
+ running = false;
462
+ if (pending) {
463
+ pending = false;
464
+ void runOnce("reload");
465
+ }
466
+ }
467
+ };
468
+ await runOnce("initial");
469
+ if (opts.once) {
470
+ console.log("\n\u2705 done (--once)");
471
+ return;
472
+ }
473
+ console.log("\n\u{1F440} watching for changes... (Ctrl+C to exit)");
474
+ startWatcher(cwd, () => {
475
+ void runOnce("reload");
476
+ });
477
+ await new Promise(() => {
478
+ });
479
+ }
480
+ async function doBuildUpload(cwd, host, opts, state, label) {
481
+ console.log(`
482
+ \u{1F527} [${label}] building...`);
483
+ let result;
484
+ try {
485
+ result = await buildPlugin({ cwd, mode: "development", sourcemap: true });
486
+ } catch (err) {
487
+ console.error(`\u274C build failed: ${err.message}`);
488
+ return;
489
+ }
490
+ try {
491
+ const { plugin, isNew } = await uploadWithAuthRetry(cwd, host, opts, state, result.zipPath, result.manifest);
492
+ state.config.pluginId = plugin.id;
493
+ state.config.entryPath = plugin.entry_path;
494
+ saveConfig(cwd, state.config);
495
+ if (isNew) {
496
+ console.log(` \u{1F4E4} installed (id=${plugin.id})`);
497
+ if (opts.enable !== false) {
498
+ try {
499
+ await enablePlugin(host, state.token, plugin.id);
500
+ console.log(" \u2705 plugin enabled");
501
+ } catch (err) {
502
+ console.warn(` \u26A0\uFE0F enable failed: ${err.message}`);
503
+ }
504
+ }
505
+ } else {
506
+ console.log(` \u{1F4E4} updated (id=${plugin.id}), ${plugin.status === "active" ? "\u267B\uFE0F hot-reloaded" : "\u23F8 inactive"}`);
507
+ }
508
+ console.log(` \u{1F310} ${host}/api/v1/jsplugin/${result.manifest.entryPath}/`);
509
+ } catch (err) {
510
+ console.error(`\u274C upload failed: ${err.message}`);
511
+ }
512
+ }
513
+ async function uploadWithAuthRetry(cwd, host, opts, state, zipPath, manifest) {
514
+ try {
515
+ return await uploadZip(host, state.token, zipPath, manifest.entryPath);
516
+ } catch (err) {
517
+ if (!(err instanceof AuthError)) throw err;
518
+ console.warn(" \u{1F510} token expired, re-authenticating...");
519
+ await doLogin(cwd, host, opts, state);
520
+ return await uploadZip(host, state.token, zipPath, manifest.entryPath);
521
+ }
522
+ }
523
+ async function ensureAuth(cwd, host, opts, state) {
524
+ if (opts.token) {
525
+ state.token = opts.token;
526
+ return;
527
+ }
528
+ await doLogin(cwd, host, opts, state);
529
+ }
530
+ async function doLogin(cwd, host, opts, state) {
531
+ const username = opts.username ?? state.config.username ?? await prompt("Username: ");
532
+ const password = opts.password ?? state.config.password ?? await prompt(`Password for ${username}: `, true);
533
+ let accessToken;
534
+ try {
535
+ ({ accessToken } = await login(host, username, password));
536
+ } catch (err) {
537
+ if (err instanceof AuthError && state.config.password) {
538
+ state.config = { ...state.config, password: void 0 };
539
+ saveConfig(cwd, state.config);
540
+ throw new Error(
541
+ "cached password rejected by server; cleared .songloft-dev.json, please re-run"
542
+ );
543
+ }
544
+ throw err;
545
+ }
546
+ state.token = accessToken;
547
+ const changed = state.config.host !== host || state.config.username !== username || state.config.password !== password;
548
+ if (changed) {
549
+ state.config = { ...state.config, host, username, password };
550
+ saveConfig(cwd, state.config);
551
+ console.log(` \u{1F4BE} credentials saved to .songloft-dev.json`);
552
+ }
553
+ console.log(` \u{1F511} logged in as ${username}`);
554
+ }
555
+ async function login(host, username, password) {
556
+ const resp = await fetch(`${host}/api/v1/auth/login`, {
557
+ method: "POST",
558
+ headers: { "Content-Type": "application/json" },
559
+ body: JSON.stringify({ username, password })
560
+ });
561
+ if (resp.status === 401) {
562
+ throw new AuthError(`login rejected: ${await safeText(resp)}`);
563
+ }
564
+ if (!resp.ok) {
565
+ throw new Error(`login failed: ${resp.status} ${await safeText(resp)}`);
566
+ }
567
+ const data = await resp.json();
568
+ return { accessToken: data.access_token };
569
+ }
570
+ async function uploadZip(host, token, zipPath, entryPath) {
571
+ const form = makeForm(zipPath, entryPath);
572
+ const resp = await fetch(`${host}/api/v1/jsplugins/upload`, {
573
+ method: "POST",
574
+ headers: { Authorization: `Bearer ${token}` },
575
+ body: form
576
+ });
577
+ if (resp.status === 401) throw new AuthError("unauthorized");
578
+ if (resp.status !== 200 && resp.status !== 201) {
579
+ throw new Error(`upload failed: HTTP ${resp.status} ${await safeText(resp)}`);
580
+ }
581
+ const data = await resp.json();
582
+ const first = data.results?.[0];
583
+ if (!first || !first.success || !first.plugin) {
584
+ const why = first?.error ?? data.message ?? "unknown error";
585
+ throw new Error(`upload failed: ${why}`);
586
+ }
587
+ return { plugin: first.plugin, isNew: resp.status === 201 };
588
+ }
589
+ async function enablePlugin(host, token, pluginId) {
590
+ const resp = await fetch(`${host}/api/v1/jsplugins/${pluginId}/enable`, {
591
+ method: "POST",
592
+ headers: { Authorization: `Bearer ${token}` }
593
+ });
594
+ if (resp.status === 401) throw new AuthError("unauthorized");
595
+ if (!resp.ok) throw new Error(`enable failed: ${resp.status} ${await safeText(resp)}`);
596
+ }
597
+ function makeForm(zipPath, entryPath) {
598
+ const bytes = readFileSync5(zipPath);
599
+ const arrayBuffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
600
+ const blob = new Blob([arrayBuffer], { type: "application/zip" });
601
+ const form = new FormData();
602
+ form.append("file", blob, `${entryPath}.jsplugin.zip`);
603
+ return form;
604
+ }
605
+ async function safeText(resp) {
606
+ try {
607
+ return (await resp.text()).slice(0, 200);
608
+ } catch {
609
+ return "";
610
+ }
611
+ }
612
+ function startWatcher(cwd, onChange) {
613
+ let timer = null;
614
+ const debounced = () => {
615
+ if (timer) clearTimeout(timer);
616
+ timer = setTimeout(() => {
617
+ timer = null;
618
+ onChange();
619
+ }, DEBOUNCE_MS);
620
+ };
621
+ for (const dir of WATCH_DIRS) {
622
+ const path = join5(cwd, dir);
623
+ if (!existsSync2(path)) continue;
624
+ try {
625
+ watch(path, { recursive: true }, (_event, filename) => {
626
+ if (filename && shouldIgnore(filename.toString())) return;
627
+ debounced();
628
+ });
629
+ } catch (err) {
630
+ console.warn(` \u26A0\uFE0F watch ${dir} failed: ${err.message}`);
631
+ }
632
+ }
633
+ for (const file of WATCH_FILES) {
634
+ const path = join5(cwd, file);
635
+ if (!existsSync2(path)) continue;
636
+ try {
637
+ watch(path, () => debounced());
638
+ } catch {
639
+ }
640
+ }
641
+ }
642
+ function shouldIgnore(filename) {
643
+ return filename.includes("node_modules") || filename.startsWith("dist/") || filename.includes("/dist/") || filename.endsWith(".swp") || filename.endsWith("~");
644
+ }
645
+ function loadConfig(cwd) {
646
+ const path = join5(cwd, CONFIG_FILE);
647
+ if (!existsSync2(path)) return {};
648
+ let raw;
649
+ try {
650
+ raw = JSON.parse(readFileSync5(path, "utf-8"));
651
+ } catch {
652
+ return {};
653
+ }
654
+ const cfg = {};
655
+ if (typeof raw.host === "string") cfg.host = raw.host;
656
+ if (typeof raw.username === "string") cfg.username = raw.username;
657
+ if (typeof raw.password === "string") cfg.password = raw.password;
658
+ if (typeof raw.pluginId === "number") cfg.pluginId = raw.pluginId;
659
+ if (typeof raw.entryPath === "string") cfg.entryPath = raw.entryPath;
660
+ return cfg;
661
+ }
662
+ function saveConfig(cwd, cfg) {
663
+ const path = join5(cwd, CONFIG_FILE);
664
+ writeFileSync3(path, JSON.stringify(cfg, null, 2) + "\n");
665
+ ensureGitignore(cwd);
666
+ }
667
+ function ensureGitignore(cwd) {
668
+ const path = join5(cwd, ".gitignore");
669
+ if (!existsSync2(path)) {
670
+ writeFileSync3(path, `${CONFIG_FILE}
671
+ `);
672
+ return;
673
+ }
674
+ const content = readFileSync5(path, "utf-8");
675
+ if (content.split("\n").some((l) => l.trim() === CONFIG_FILE)) return;
676
+ writeFileSync3(path, content.replace(/\n*$/, "") + `
677
+ ${CONFIG_FILE}
678
+ `);
679
+ }
680
+ function normalizeHost(host) {
681
+ let h = host.trim();
682
+ if (!/^https?:\/\//.test(h)) h = `http://${h}`;
683
+ return h.replace(/\/+$/, "");
684
+ }
685
+ function prompt(question, silent = false) {
686
+ return new Promise((resolveAnswer) => {
687
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
688
+ if (silent) {
689
+ const out = rl.output;
690
+ const realWrite = out.write.bind(out);
691
+ let promptShown = false;
692
+ out.write = ((chunk, ...rest) => {
693
+ if (!promptShown && typeof chunk === "string" && chunk === question) {
694
+ promptShown = true;
695
+ return realWrite(chunk, ...rest);
696
+ }
697
+ return true;
698
+ });
699
+ rl.question(question, (answer) => {
700
+ out.write = realWrite;
701
+ process.stdout.write("\n");
702
+ rl.close();
703
+ resolveAnswer(answer);
704
+ });
705
+ } else {
706
+ rl.question(question, (answer) => {
707
+ rl.close();
708
+ resolveAnswer(answer.trim());
709
+ });
710
+ }
711
+ });
712
+ }
713
+
714
+ // src/cli.ts
715
+ var args = process.argv.slice(2);
716
+ var command = args[0];
717
+ function getFlag(name) {
718
+ const idx = args.indexOf(`--${name}`);
719
+ return idx !== -1 ? args[idx + 1] : void 0;
720
+ }
721
+ function hasFlag(name) {
722
+ return args.includes(`--${name}`);
723
+ }
724
+ async function main() {
725
+ switch (command) {
726
+ case "build": {
727
+ const mode = getFlag("mode") ?? "production";
728
+ const sourcemap = hasFlag("sourcemap");
729
+ await buildPlugin({ cwd: process.cwd(), mode, sourcemap });
730
+ break;
731
+ }
732
+ case "validate": {
733
+ const result = await validatePlugin(process.cwd());
734
+ if (!result.valid) {
735
+ console.error("\u274C Validation failed:");
736
+ for (const err of result.errors) {
737
+ console.error(` - ${err.field}: ${err.message}`);
738
+ }
739
+ process.exit(1);
740
+ } else {
741
+ console.log("\u2705 Plugin is valid.");
742
+ }
743
+ break;
744
+ }
745
+ case "dev": {
746
+ await runDev({
747
+ cwd: process.cwd(),
748
+ host: getFlag("host") ?? process.env.SONGLOFT_HOST,
749
+ username: getFlag("username") ?? process.env.SONGLOFT_USER,
750
+ password: getFlag("password") ?? process.env.SONGLOFT_PASSWORD,
751
+ token: getFlag("token") ?? process.env.SONGLOFT_TOKEN,
752
+ once: hasFlag("once"),
753
+ enable: !hasFlag("no-enable")
754
+ });
755
+ break;
756
+ }
757
+ case "publish": {
758
+ console.log("\u26A0\uFE0F publish command not yet implemented (coming in v0.2)");
759
+ break;
760
+ }
761
+ default:
762
+ console.log(`Usage: songloft-plugin <command>
763
+
764
+ Commands:
765
+ build Build the plugin into a .jsplugin.zip
766
+ validate Validate plugin.json and hashes
767
+ dev Watch source + auto-build & upload to a local Songloft instance
768
+ publish Tag & trigger GitHub release (WIP)
769
+
770
+ Build options:
771
+ --mode <mode> Build mode: production (default) or development
772
+ --sourcemap Include inline source maps
773
+
774
+ Dev options:
775
+ --host <url> Songloft instance URL (default: http://localhost:58091,
776
+ also reads $SONGLOFT_HOST or .songloft-dev.json)
777
+ --username <name> Login username (or $SONGLOFT_USER)
778
+ --password <pwd> Login password (or $SONGLOFT_PASSWORD; prompt if absent)
779
+ --token <jwt> Use a pre-issued access token instead of username/password
780
+ (or $SONGLOFT_TOKEN)
781
+ --once Build + upload once and exit; skip watch mode
782
+ --no-enable Don't auto-enable the plugin after first-time install
783
+
784
+ On first run you'll be prompted for username and password; both are written to
785
+ .songloft-dev.json in the project root (added to .gitignore automatically) so
786
+ subsequent runs log in silently. Tokens are NOT cached \u2014 each session logs in
787
+ fresh, so you never have to deal with expired tokens. To rotate credentials,
788
+ edit (or delete) .songloft-dev.json.
789
+ `);
790
+ if (command) {
791
+ console.error(`Unknown command: ${command}`);
792
+ process.exit(1);
793
+ }
794
+ }
795
+ }
796
+ main().catch((err) => {
797
+ console.error(err.message || err);
798
+ process.exit(1);
799
+ });
800
+ //# sourceMappingURL=cli.js.map