@mbws/plugin-sdk 0.3.19 → 0.3.21

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/vite.js CHANGED
@@ -22,6 +22,7 @@ import path from "node:path";
22
22
  import { pipeline } from "node:stream/promises";
23
23
  import zlib from "node:zlib";
24
24
  import { attachmentsOssBase, buildManifest, resolveAttachmentRefs, } from "./config.js";
25
+ import { applyStorageQuota, isStorageKeyValid, StorageQuotaError } from "./dev-storage.js";
25
26
  import { ExpandZipError, expandZipVideos } from "./expand-zip.js";
26
27
  import { generateContractTypes } from "./schema-types.js";
27
28
  // 契约类型生成经本子路径暴露(Node 端工具链用;依赖 prettier,不进根入口)
@@ -197,6 +198,10 @@ export function mbwsVitePlugin(opts) {
197
198
  const simulate = process.env.MBWS_DEV_SIMULATE?.trim();
198
199
  if (simulate)
199
200
  devEnvDefines["process.env.MBWS_DEV_SIMULATE"] = JSON.stringify(simulate);
201
+ // 开发者 key(mbws.config.ts devKey):契约端点对无已发布产物的状态强制 X-Dev-Key。
202
+ // 进 devEnvDefines 以同时落 define 与 optimizeDeps transform.define(双写防预构建吞注入)
203
+ if (config.devKey)
204
+ devEnvDefines.__MBWS_DEV_KEY__ = JSON.stringify(config.devKey);
200
205
  Object.assign(define, devEnvDefines);
201
206
  }
202
207
  // 增量配置(vite 浅合并,不覆盖用户已设项)
@@ -354,6 +359,29 @@ export function mbwsVitePlugin(opts) {
354
359
  }
355
360
  return handleDevLocalize(projectRoot, res, ref).catch(next);
356
361
  }
362
+ if (pathname === "/__mbws__/dev/write-file") {
363
+ if (req.method !== "POST") {
364
+ res.statusCode = 405;
365
+ res.end();
366
+ return;
367
+ }
368
+ // caps.exec.writeFile 的 dev 落点:面板产出的文本写进工程目录(spawn cwd = 工程根)
369
+ return handleDevWriteFile(projectRoot, req, res).catch(next);
370
+ }
371
+ if (pathname === "/__mbws__/dev/storage") {
372
+ if (req.method === "GET") {
373
+ // dev-mock storage.get:读 .mbws/storage.json 里本插件的一个键
374
+ const key = new URL(req.url ?? "/", "http://dev").searchParams.get("key") ?? "";
375
+ return handleDevStorageGet(config.id, projectRoot, res, key);
376
+ }
377
+ if (req.method === "POST") {
378
+ // dev-mock storage.set:写回 + 配额校验(64 键 / 256KB,按插件隔离)
379
+ return handleDevStorageSet(config.id, projectRoot, req, res).catch(next);
380
+ }
381
+ res.statusCode = 405;
382
+ res.end();
383
+ return undefined;
384
+ }
357
385
  if (pathname === "/__mbws__/dev/expand-zip") {
358
386
  const rel = new URL(req.url ?? "/", "http://dev").searchParams.get("path") ?? "";
359
387
  if (!rel) {
@@ -394,11 +422,12 @@ export function mbwsVitePlugin(opts) {
394
422
  }
395
423
  /**
396
424
  * 拉服务端契约生成 mbws.contract.gen.ts(内容有变才落盘——重启 dev 不产生无谓改动)。
397
- * 契约端点公开(按插件编号实时派生),失败只在 dev 控制台提示,不影响任何构建行为。
425
+ * Node 侧直连后端(不走浏览器 define),mbws.config.ts 配了 devKey 则带头——契约端点
426
+ * 对无已发布产物的状态强制 X-Dev-Key。失败只在 dev 控制台提示,不影响任何构建行为。
398
427
  */
399
428
  async function writeContractTypesFile(config, root, log) {
400
429
  try {
401
- const response = await fetch(`${resolveApiBase(config)}/api/plugin-dev-tasks/contract/by-plugin/${encodeURIComponent(config.id)}`);
430
+ const response = await fetch(`${resolveApiBase(config)}/api/plugin-dev-tasks/contract/by-plugin/${encodeURIComponent(config.id)}`, { headers: config.devKey ? { "X-Dev-Key": config.devKey } : {} });
402
431
  if (!response.ok)
403
432
  throw new Error(`HTTP ${response.status}`);
404
433
  const data = (await response.json());
@@ -749,6 +778,11 @@ async function handleDevExec(config, root, req, res) {
749
778
  const binPath = await prepareDevAttachment(config, root, attachment, write, res);
750
779
  if (!binPath)
751
780
  return;
781
+ // 附件就绪即发响应头:spawn() 在 dev-mock 里等的是 fetch 返回(= 响应头到达)。
782
+ // 不主动 flush 的话,静默运行的长作业(无输出行)要等它第一次输出/退出才有响应头,
783
+ // 插件的 `const job = await spawn(...)` 被卡满整个作业时长——宿主的 spawn 是立即
784
+ // 回 jobId 的。放在 prepareDevAttachment 之后:501(附件不可用)分支还能改状态码
785
+ res.flushHeaders();
752
786
  const proc = spawn(binPath, args, { cwd: root });
753
787
  const stderrTailChunks = [];
754
788
  let stderrTailBytes = 0;
@@ -1276,6 +1310,166 @@ async function handleDevLocalize(root, res, ref) {
1276
1310
  res.statusCode = 404;
1277
1311
  res.end(JSON.stringify({ message: `samples/${basename} 不存在` }));
1278
1312
  }
1313
+ /** 读请求体为 JSON 对象(坏 JSON / 非对象 → null,调用方回 400) */
1314
+ async function readJsonBody(req) {
1315
+ try {
1316
+ const parsed = JSON.parse((await readRequestBody(req)).toString("utf8"));
1317
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
1318
+ ? parsed
1319
+ : null;
1320
+ }
1321
+ catch {
1322
+ return null;
1323
+ }
1324
+ }
1325
+ /**
1326
+ * 工程内相对路径解析(write-file 用,与宿主 writePluginFile 同规则):必须是非空
1327
+ * 相对路径;resolve 后必须严格落在工程目录内(不得等于工程根本身)。返回 null = 越界。
1328
+ */
1329
+ export function resolveInsideRoot(root, relPath) {
1330
+ if (!relPath || path.isAbsolute(relPath))
1331
+ return null;
1332
+ const rootResolved = path.resolve(root);
1333
+ const resolved = path.resolve(rootResolved, relPath);
1334
+ if (resolved === rootResolved || !resolved.startsWith(`${rootResolved}${path.sep}`))
1335
+ return null;
1336
+ return resolved;
1337
+ }
1338
+ /**
1339
+ * caps.exec.writeFile 单次内容上限(与 SDK 常量 CAPS_WRITE_FILE_MAX_BYTES 同值):
1340
+ * 面板产出的是参数文件级别的小文本,本方法不是大数据通道。
1341
+ */
1342
+ const DEV_WRITE_FILE_MAX_BYTES = 4 * 1024 * 1024;
1343
+ /**
1344
+ * POST /__mbws__/dev/write-file?:body { path, content }——把面板产出的文本写进工程
1345
+ * 目录。path 须是工程内相对路径(父目录不存在即建,同名覆盖),与宿主
1346
+ * writePluginFile 同规则同错误码:越界/绝对路径/超限 → 400 E_INVALID_ARGS。
1347
+ */
1348
+ async function handleDevWriteFile(root, req, res) {
1349
+ const body = await readJsonBody(req);
1350
+ const relPath = body?.path;
1351
+ const content = body?.content;
1352
+ if (typeof relPath !== "string" || typeof content !== "string") {
1353
+ res.statusCode = 400;
1354
+ res.setHeader("content-type", "application/json");
1355
+ res.end(JSON.stringify({
1356
+ code: "E_INVALID_ARGS",
1357
+ message: "caps.exec.writeFile 需要 path(string) 与 content(string)",
1358
+ }));
1359
+ return;
1360
+ }
1361
+ const reject = (message) => {
1362
+ res.statusCode = 400;
1363
+ res.setHeader("content-type", "application/json");
1364
+ res.end(JSON.stringify({ code: "E_INVALID_ARGS", message }));
1365
+ };
1366
+ const target = resolveInsideRoot(root, relPath);
1367
+ if (!target)
1368
+ return reject("path 必须是工程目录内的相对路径");
1369
+ if (Buffer.byteLength(content, "utf8") > DEV_WRITE_FILE_MAX_BYTES) {
1370
+ return reject(`caps.exec.writeFile 内容超过上限(${DEV_WRITE_FILE_MAX_BYTES / 1024 / 1024}MB)`);
1371
+ }
1372
+ try {
1373
+ await fs.promises.mkdir(path.dirname(target), { recursive: true });
1374
+ await fs.promises.writeFile(target, content, "utf8");
1375
+ }
1376
+ catch (error) {
1377
+ res.statusCode = 500;
1378
+ res.setHeader("content-type", "application/json");
1379
+ res.end(JSON.stringify({
1380
+ message: `写入失败:${error instanceof Error ? error.message : String(error)}`,
1381
+ }));
1382
+ return;
1383
+ }
1384
+ res.setHeader("content-type", "application/json");
1385
+ res.setHeader("cache-control", "no-store");
1386
+ res.end(JSON.stringify({ path: path.relative(path.resolve(root), target).split(path.sep).join("/") }));
1387
+ }
1388
+ /** dev storage 落盘文件(.mbws/ 已在脚手架 .gitignore 里——纯本机状态,不进 git 不进产物) */
1389
+ const DEV_STORAGE_FILE = path.join(".mbws", "storage.json");
1390
+ /** 读某插件的键值表(文件不存在/损坏/插件未写过 → 空表) */
1391
+ function readDevStorage(root, pluginId) {
1392
+ try {
1393
+ const parsed = JSON.parse(fs.readFileSync(path.join(root, DEV_STORAGE_FILE), "utf8"));
1394
+ const entries = parsed?.plugins?.[pluginId];
1395
+ return new Map(entries && typeof entries === "object" ? Object.entries(entries) : []);
1396
+ }
1397
+ catch {
1398
+ return new Map();
1399
+ }
1400
+ }
1401
+ /**
1402
+ * 写回某插件的键值表:整文件同步读改写(同一 tick 内完成,多个并发 set 不互相覆盖)。
1403
+ * 其余插件的表原样保留——同一台机器上多个插件工程各写各的段,互不可见。
1404
+ */
1405
+ function writeDevStorage(root, pluginId, entries) {
1406
+ const file = path.join(root, DEV_STORAGE_FILE);
1407
+ let plugins = {};
1408
+ try {
1409
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
1410
+ if (parsed?.plugins && typeof parsed.plugins === "object")
1411
+ plugins = parsed.plugins;
1412
+ }
1413
+ catch {
1414
+ // 不存在/坏文件从空起步(坏文件被本次写回覆盖)
1415
+ }
1416
+ plugins[pluginId] = Object.fromEntries(entries);
1417
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1418
+ const body = { version: 1, plugins };
1419
+ fs.writeFileSync(file, `${JSON.stringify(body, null, 2)}\n`);
1420
+ }
1421
+ /** GET /__mbws__/dev/storage?key=:回 `{ value }`(未设置时无 value 字段 → undefined) */
1422
+ function handleDevStorageGet(pluginId, root, res, key) {
1423
+ if (!isStorageKeyValid(key)) {
1424
+ res.statusCode = 400;
1425
+ res.setHeader("content-type", "application/json");
1426
+ res.end(JSON.stringify({ code: "E_INVALID_ARGS", message: "storage 需要 string key" }));
1427
+ return;
1428
+ }
1429
+ const raw = readDevStorage(root, pluginId).get(key);
1430
+ let value;
1431
+ try {
1432
+ value = raw === undefined ? undefined : JSON.parse(raw);
1433
+ }
1434
+ catch {
1435
+ value = undefined; // 坏 JSON 当未设置(宿主 storageGet 同形)
1436
+ }
1437
+ res.setHeader("content-type", "application/json");
1438
+ res.setHeader("cache-control", "no-store");
1439
+ res.end(JSON.stringify({ ...(value !== undefined ? { value } : {}) }));
1440
+ }
1441
+ /**
1442
+ * POST /__mbws__/dev/storage:body { key, value }。配额与宿主同口径(64 键 / 256KB,
1443
+ * 按序列化字节数计):超限 413 `{ code: "E_QUOTA_EXCEEDED", message }`(dev-mock 转成
1444
+ * MbwsInvokeError,插件的超限分支浏览器里即可联调);key 不合法 400。
1445
+ */
1446
+ async function handleDevStorageSet(pluginId, root, req, res) {
1447
+ const body = await readJsonBody(req);
1448
+ const key = body?.key;
1449
+ if (!body || !isStorageKeyValid(key)) {
1450
+ res.statusCode = 400;
1451
+ res.setHeader("content-type", "application/json");
1452
+ res.end(JSON.stringify({ code: "E_INVALID_ARGS", message: "storage 需要 string key" }));
1453
+ return;
1454
+ }
1455
+ // 宿主 storageSet 同形:undefined 序列化成 null 落盘
1456
+ let next;
1457
+ try {
1458
+ next = applyStorageQuota(readDevStorage(root, pluginId), key, JSON.stringify(body.value ?? null));
1459
+ }
1460
+ catch (error) {
1461
+ res.statusCode = 413;
1462
+ res.setHeader("content-type", "application/json");
1463
+ res.end(JSON.stringify(error instanceof StorageQuotaError
1464
+ ? { code: error.code, message: error.message }
1465
+ : { message: "存储写入失败" }));
1466
+ return;
1467
+ }
1468
+ writeDevStorage(root, pluginId, next);
1469
+ res.setHeader("content-type", "application/json");
1470
+ res.setHeader("cache-control", "no-store");
1471
+ res.end(JSON.stringify({ ok: true }));
1472
+ }
1279
1473
  /** GET /__mbws__/dev/expand-zip?path=:把工程内 zip 解到 .mbws/expanded,返回可预览视频。 */
1280
1474
  async function handleDevExpandZip(root, res, relPath) {
1281
1475
  const rootResolved = path.resolve(root);
@@ -1335,8 +1529,10 @@ const DEV_FILE_MIME = {
1335
1529
  };
1336
1530
  /** GET /__mbws__/dev/file?path=:dev 媒体预览(工程内路径白名单 + Range 支持) */
1337
1531
  async function handleDevFile(root, req, res, relPath) {
1532
+ // 前缀必须带路径分隔符:裸 startsWith 会把同级「<工程名>2/」也算进工程目录
1338
1533
  const filePath = path.resolve(root, relPath);
1339
- if (!filePath.startsWith(path.resolve(root))) {
1534
+ const rootResolved = path.resolve(root);
1535
+ if (!filePath.startsWith(`${rootResolved}${path.sep}`)) {
1340
1536
  res.statusCode = 403;
1341
1537
  res.end();
1342
1538
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mbws/plugin-sdk",
3
- "version": "0.3.19",
3
+ "version": "0.3.21",
4
4
  "description": "Moye 插件开发 SDK——panel/viewer 与宿主的类型定义与运行时端口适配",
5
5
  "license": "MIT",
6
6
  "type": "module",