@open-slide/core 2.0.0-beta.6 → 2.0.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.
@@ -1,16 +1,16 @@
1
1
  import { n as defaultDesign } from "./design-Cpqx7SJs.js";
2
+ import { C as reorderDefaultExportPagesInSource, D as updateMetaTitleInSource, E as rmSlideDir, O as validateSlideName, S as removePageFromDefaultExportInSource, T as resolveSlideEntry, _ as SLIDE_ID_RE, a as readBody, b as duplicateSlideDir, c as FOLDER_ID_RE, d as readManifest, f as validateIcon, g as shortId, h as writeManifest, i as makeContext, k as validateMutationRequest, l as foldersManifestPath, m as validateReorder, n as registerUpdateRoutes, o as readSlideSource, p as validateName, r as json, s as resolveSlideEntryPath, u as newFolderId, v as duplicateNotesElementInSource, w as reorderNotesArrayInSource, x as removeNotesElementInSource, y as duplicatePageInDefaultExportInSource } from "./update-moCkSyvg.js";
2
3
  import { createRequire } from "node:module";
3
4
  import path from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { existsSync, readFileSync } from "node:fs";
6
- import { randomUUID } from "node:crypto";
7
7
  import fs from "node:fs/promises";
8
+ import { parse } from "@babel/parser";
9
+ import { randomUUID } from "node:crypto";
8
10
  import tailwindcss from "@tailwindcss/vite";
9
11
  import react from "@vitejs/plugin-react";
10
12
  import * as t from "@babel/types";
11
13
  import { isJSXElement, isJSXFragment } from "@babel/types";
12
- import { parse } from "@babel/parser";
13
- import { spawn } from "node:child_process";
14
14
  import fg from "fast-glob";
15
15
  import { loadConfigFromFile, normalizePath } from "vite";
16
16
  //#region src/editing/babel-walk.ts
@@ -1215,526 +1215,6 @@ function applyRevertAsset(source, assetPath) {
1215
1215
  return applySplices(source, splices);
1216
1216
  }
1217
1217
  //#endregion
1218
- //#region src/editing/slide-ops.ts
1219
- const SLIDE_ID_RE = /^[a-z0-9_-]+$/i;
1220
- function validateSlideName(v) {
1221
- if (typeof v !== "string") return null;
1222
- const trimmed = v.trim();
1223
- if (trimmed.length < 1 || trimmed.length > 80) return null;
1224
- return trimmed;
1225
- }
1226
- function unwrapExpression(node) {
1227
- let current = node;
1228
- while (current && (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression")) current = current.expression;
1229
- return current;
1230
- }
1231
- function readMetaTitleInSource(source) {
1232
- let ast;
1233
- try {
1234
- ast = parse(source, {
1235
- sourceType: "module",
1236
- plugins: ["typescript", "jsx"],
1237
- errorRecovery: true
1238
- });
1239
- } catch {
1240
- return { kind: "unsupported" };
1241
- }
1242
- const body = ast.program?.body ?? [];
1243
- for (const stmt of body) {
1244
- if (stmt.type !== "ExportNamedDeclaration") continue;
1245
- const decl = stmt.declaration;
1246
- if (decl?.type !== "VariableDeclaration") continue;
1247
- const declarations = decl.declarations ?? [];
1248
- for (const d of declarations) {
1249
- const id = d.id;
1250
- if (id?.type !== "Identifier" || id.name !== "meta") continue;
1251
- const init = unwrapExpression(d.init);
1252
- if (init?.type !== "ObjectExpression") return { kind: "unsupported" };
1253
- const properties = init.properties ?? [];
1254
- for (const property of properties) {
1255
- if (property.type !== "ObjectProperty" || property.computed) continue;
1256
- const key = property.key;
1257
- if ((key?.type === "Identifier" ? key.name : key?.type === "StringLiteral" ? key.value : void 0) !== "title") continue;
1258
- const value = property.value;
1259
- if (value?.type === "StringLiteral" && typeof value.value === "string") return {
1260
- kind: "found",
1261
- title: value.value
1262
- };
1263
- if (value?.type === "TemplateLiteral") {
1264
- const expressions = value.expressions ?? [];
1265
- const firstValue = (value.quasis ?? [])[0]?.value;
1266
- const cooked = firstValue?.cooked;
1267
- const raw = firstValue?.raw;
1268
- if (expressions.length === 0 && typeof (cooked ?? raw) === "string") return {
1269
- kind: "found",
1270
- title: cooked ?? raw
1271
- };
1272
- }
1273
- return { kind: "unsupported" };
1274
- }
1275
- return { kind: "missing" };
1276
- }
1277
- }
1278
- return { kind: "missing" };
1279
- }
1280
- async function rmSlideDir(slidesRoot, slideId) {
1281
- if (!SLIDE_ID_RE.test(slideId)) return false;
1282
- const dir = path.resolve(slidesRoot, slideId);
1283
- if (!dir.startsWith(slidesRoot + path.sep)) return false;
1284
- try {
1285
- await fs.rm(dir, {
1286
- recursive: true,
1287
- force: true
1288
- });
1289
- return true;
1290
- } catch {
1291
- return false;
1292
- }
1293
- }
1294
- async function duplicateSlideDir(slidesRoot, slideId, desiredId) {
1295
- if (!SLIDE_ID_RE.test(slideId)) return {
1296
- ok: false,
1297
- status: 400,
1298
- error: "invalid slideId"
1299
- };
1300
- const root = path.resolve(slidesRoot);
1301
- const srcDir = path.resolve(root, slideId);
1302
- if (!srcDir.startsWith(root + path.sep)) return {
1303
- ok: false,
1304
- status: 400,
1305
- error: "invalid slideId"
1306
- };
1307
- try {
1308
- await fs.access(path.join(srcDir, "index.tsx"));
1309
- } catch {
1310
- return {
1311
- ok: false,
1312
- status: 404,
1313
- error: "slide not found"
1314
- };
1315
- }
1316
- let newId;
1317
- if (desiredId !== void 0) {
1318
- if (!SLIDE_ID_RE.test(desiredId)) return {
1319
- ok: false,
1320
- status: 400,
1321
- error: "invalid newId"
1322
- };
1323
- newId = desiredId;
1324
- const dstDir = path.resolve(root, newId);
1325
- if (!dstDir.startsWith(root + path.sep)) return {
1326
- ok: false,
1327
- status: 400,
1328
- error: "invalid newId"
1329
- };
1330
- try {
1331
- await fs.access(dstDir);
1332
- return {
1333
- ok: false,
1334
- status: 409,
1335
- error: "slide already exists"
1336
- };
1337
- } catch {}
1338
- } else {
1339
- let suffix = 1;
1340
- while (true) {
1341
- newId = suffix === 1 ? `${slideId}-copy` : `${slideId}-copy-${suffix}`;
1342
- try {
1343
- await fs.access(path.resolve(root, newId));
1344
- suffix++;
1345
- } catch {
1346
- break;
1347
- }
1348
- }
1349
- }
1350
- const dstDir = path.resolve(root, newId);
1351
- if (!dstDir.startsWith(root + path.sep)) return {
1352
- ok: false,
1353
- status: 400,
1354
- error: "invalid newId"
1355
- };
1356
- const srcEntry = path.join(srcDir, "index.tsx");
1357
- let copiedEntrySource;
1358
- try {
1359
- const source = await fs.readFile(srcEntry, "utf8");
1360
- const metaTitle = readMetaTitleInSource(source);
1361
- if (metaTitle.kind === "unsupported") return {
1362
- ok: false,
1363
- status: 422,
1364
- error: "could not update copied slide title"
1365
- };
1366
- const updated = updateMetaTitleInSource(source, `${metaTitle.kind === "found" ? metaTitle.title : slideId} (copy)`);
1367
- if (updated === null) return {
1368
- ok: false,
1369
- status: 422,
1370
- error: "could not update copied slide title"
1371
- };
1372
- copiedEntrySource = updated;
1373
- } catch {
1374
- return {
1375
- ok: false,
1376
- status: 404,
1377
- error: "slide not found"
1378
- };
1379
- }
1380
- try {
1381
- await fs.cp(srcDir, dstDir, {
1382
- recursive: true,
1383
- errorOnExist: true,
1384
- force: false
1385
- });
1386
- await fs.writeFile(path.join(dstDir, "index.tsx"), copiedEntrySource, "utf8");
1387
- return {
1388
- ok: true,
1389
- slideId: newId
1390
- };
1391
- } catch (err) {
1392
- if (err.code === "EEXIST") return {
1393
- ok: false,
1394
- status: 409,
1395
- error: "slide already exists"
1396
- };
1397
- return {
1398
- ok: false,
1399
- status: 500,
1400
- error: String(err.message ?? err)
1401
- };
1402
- }
1403
- }
1404
- function resolveSlideEntry(slidesRoot, slideId) {
1405
- if (!SLIDE_ID_RE.test(slideId)) return null;
1406
- const dir = path.resolve(slidesRoot, slideId);
1407
- if (!dir.startsWith(slidesRoot + path.sep)) return null;
1408
- return path.join(dir, "index.tsx");
1409
- }
1410
- function escapeSingleQuoted(s) {
1411
- return s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
1412
- }
1413
- /**
1414
- * Rewrite (or insert) the `title` field in the slide module's `export const meta`.
1415
- *
1416
- * Strategy:
1417
- * 1. Find `export const meta` and brace-match its object literal.
1418
- * 2. If the object already has a `title: '...'` entry, replace the literal.
1419
- * 3. If the object exists but has no title, inject a new `title: '...'` line
1420
- * as the first property (preserving the author's surrounding indentation).
1421
- * 4. If there is no `meta` export at all, insert a fresh one right before
1422
- * `export default`.
1423
- *
1424
- * Returns the rewritten source, or `null` if the file shape was too surprising
1425
- * to touch safely (e.g. `export default` missing when we'd need to inject meta).
1426
- */
1427
- function updateMetaTitleInSource(source, title) {
1428
- const newLiteral = `'${escapeSingleQuoted(title)}'`;
1429
- const metaStart = source.search(/export\s+const\s+meta\b/);
1430
- if (metaStart !== -1) {
1431
- const eqIdx = source.indexOf("=", metaStart);
1432
- if (eqIdx === -1) return null;
1433
- const openBrace = source.indexOf("{", eqIdx);
1434
- if (openBrace === -1) return null;
1435
- let depth = 0;
1436
- let closeBrace = -1;
1437
- for (let i = openBrace; i < source.length; i++) {
1438
- const ch = source[i];
1439
- if (ch === "{") depth++;
1440
- else if (ch === "}") {
1441
- depth--;
1442
- if (depth === 0) {
1443
- closeBrace = i;
1444
- break;
1445
- }
1446
- }
1447
- }
1448
- if (closeBrace === -1) return null;
1449
- const body = source.slice(openBrace + 1, closeBrace);
1450
- const titleRe = /(^|[\s,{])(title\s*:\s*)(['"`])((?:\\.|(?!\3).)*)\3/;
1451
- const match = body.match(titleRe);
1452
- if (match) {
1453
- const newBody = body.replace(titleRe, `${match[1]}${match[2]}${newLiteral}`);
1454
- return source.slice(0, openBrace + 1) + newBody + source.slice(closeBrace);
1455
- }
1456
- const firstIndentMatch = body.match(/\n([ \t]+)\S/);
1457
- const insertion = `\n${firstIndentMatch ? firstIndentMatch[1] : " "}title: ${newLiteral}${body.replace(/^\s*\n?/, "").trim().length > 0 ? "," : ""}`;
1458
- return source.slice(0, openBrace + 1) + insertion + body + source.slice(closeBrace);
1459
- }
1460
- const exportDefaultIdx = source.search(/export\s+default\b/);
1461
- if (exportDefaultIdx === -1) return null;
1462
- const insertion = `export const meta: SlideMeta = { title: ${newLiteral} };\n\n`;
1463
- return source.slice(0, exportDefaultIdx) + insertion + source.slice(exportDefaultIdx);
1464
- }
1465
- function findDefaultExportArray(source) {
1466
- let ast;
1467
- try {
1468
- ast = parse(source, {
1469
- sourceType: "module",
1470
- plugins: ["typescript", "jsx"],
1471
- errorRecovery: true
1472
- });
1473
- } catch {
1474
- return null;
1475
- }
1476
- const body = ast.program?.body ?? [];
1477
- for (const node of body) {
1478
- if (node.type !== "ExportDefaultDeclaration") continue;
1479
- let inner = node.declaration;
1480
- while (inner && (inner.type === "TSAsExpression" || inner.type === "TSSatisfiesExpression")) inner = inner.expression;
1481
- if (inner?.type !== "ArrayExpression") return null;
1482
- const arrayStart = inner.start;
1483
- const arrayEnd = inner.end;
1484
- const rawElements = inner.elements ?? [];
1485
- const elements = [];
1486
- for (const el of rawElements) {
1487
- if (!el || typeof el.start !== "number" || typeof el.end !== "number") return null;
1488
- elements.push({
1489
- start: el.start,
1490
- end: el.end
1491
- });
1492
- }
1493
- return {
1494
- elements,
1495
- arrayStart,
1496
- arrayEnd
1497
- };
1498
- }
1499
- return null;
1500
- }
1501
- /**
1502
- * Rewrite `export default [...]` so its elements appear in the requested order.
1503
- *
1504
- * `order[i]` is the original index that should land at new position `i`. The
1505
- * function preserves each element's exact source slice (including any inline
1506
- * comments that hug an identifier) and keeps the inter-element separator slots
1507
- * in their original positions, so a 3-page array `[A, B, C]` reordered to
1508
- * `[2, 0, 1]` becomes `[C, A, B]` with the same indentation and trailing
1509
- * commas the author wrote.
1510
- *
1511
- * Returns `null` when the file's default export isn't an array literal, or the
1512
- * order is not a valid permutation of `[0, n-1]`.
1513
- */
1514
- function reorderDefaultExportPagesInSource(source, order) {
1515
- const found = findDefaultExportArray(source);
1516
- if (!found) return null;
1517
- const { elements, arrayStart, arrayEnd } = found;
1518
- const n = elements.length;
1519
- if (order.length !== n) return null;
1520
- const seen = /* @__PURE__ */ new Set();
1521
- for (const idx of order) {
1522
- if (!Number.isInteger(idx) || idx < 0 || idx >= n) return null;
1523
- if (seen.has(idx)) return null;
1524
- seen.add(idx);
1525
- }
1526
- if (n === 0) return source;
1527
- let identity = true;
1528
- for (let i = 0; i < n; i++) if (order[i] !== i) {
1529
- identity = false;
1530
- break;
1531
- }
1532
- if (identity) return source;
1533
- const prefix = source.slice(arrayStart, elements[0].start);
1534
- const suffix = source.slice(elements[n - 1].end, arrayEnd);
1535
- const separators = [];
1536
- for (let i = 0; i < n - 1; i++) separators.push(source.slice(elements[i].end, elements[i + 1].start));
1537
- const elementText = elements.map((el) => source.slice(el.start, el.end));
1538
- let rebuilt = prefix + elementText[order[0]];
1539
- for (let i = 1; i < n; i++) rebuilt += separators[i - 1] + elementText[order[i]];
1540
- rebuilt += suffix;
1541
- return source.slice(0, arrayStart) + rebuilt + source.slice(arrayEnd);
1542
- }
1543
- function findNotesArray(source) {
1544
- let ast;
1545
- try {
1546
- ast = parse(source, {
1547
- sourceType: "module",
1548
- plugins: ["typescript", "jsx"],
1549
- errorRecovery: true
1550
- });
1551
- } catch {
1552
- return "invalid";
1553
- }
1554
- const body = ast.program?.body ?? [];
1555
- for (const stmt of body) {
1556
- if (stmt.type !== "ExportNamedDeclaration") continue;
1557
- const decl = stmt.declaration;
1558
- if (decl?.type !== "VariableDeclaration") continue;
1559
- const declarations = decl.declarations ?? [];
1560
- for (const d of declarations) {
1561
- const id = d.id;
1562
- if (id?.type !== "Identifier" || id.name !== "notes") continue;
1563
- const init = d.init;
1564
- if (init?.type !== "ArrayExpression") return "invalid";
1565
- const arrayStart = init.start;
1566
- const arrayEnd = init.end;
1567
- if (typeof arrayStart !== "number" || typeof arrayEnd !== "number") return "invalid";
1568
- const rawElements = init.elements ?? [];
1569
- const elementTexts = [];
1570
- for (const el of rawElements) {
1571
- if (el === null) {
1572
- elementTexts.push("undefined");
1573
- continue;
1574
- }
1575
- if (el.type === "SpreadElement") return "invalid";
1576
- const start = el.start;
1577
- const end = el.end;
1578
- if (typeof start !== "number" || typeof end !== "number") return "invalid";
1579
- elementTexts.push(source.slice(start, end));
1580
- }
1581
- return {
1582
- arrayStart,
1583
- arrayEnd,
1584
- elementTexts
1585
- };
1586
- }
1587
- }
1588
- return null;
1589
- }
1590
- /**
1591
- * Reorder `export const notes = [...]` to follow the page-array reorder.
1592
- *
1593
- * `order[i]` is the original page index that should land at new position `i`.
1594
- * The notes array is index-aligned with the pages array but may be shorter
1595
- * (trailing `undefined` slots are routinely trimmed). Missing elements are
1596
- * treated as `undefined`, and trailing `undefined` is trimmed again after
1597
- * reordering to keep the file tidy.
1598
- *
1599
- * Returns the rewritten source, the original source if no `notes` export
1600
- * exists or the reorder is a no-op, or `null` if the `notes` export's shape
1601
- * is too surprising to touch safely.
1602
- */
1603
- function reorderNotesArrayInSource(source, order) {
1604
- for (const idx of order) if (!Number.isInteger(idx) || idx < 0) return null;
1605
- const found = findNotesArray(source);
1606
- if (found === "invalid") return null;
1607
- if (found === null) return source;
1608
- const { arrayStart, arrayEnd, elementTexts } = found;
1609
- const pick = (i) => i >= 0 && i < elementTexts.length ? elementTexts[i] : "undefined";
1610
- return rebuildNotesArray(source, arrayStart, arrayEnd, order.map(pick));
1611
- }
1612
- /**
1613
- * Remove the note aligned with the page at `index` so the `notes` export stays
1614
- * index-aligned with `export default [...]` after a page deletion. Mirrors
1615
- * {@link removePageFromDefaultExportInSource}.
1616
- *
1617
- * Returns the rewritten source, the original source if no `notes` export exists
1618
- * or the index falls past the recorded notes, or `null` if the `notes` export's
1619
- * shape is too surprising to touch safely.
1620
- */
1621
- function removeNotesElementInSource(source, index) {
1622
- if (!Number.isInteger(index) || index < 0) return null;
1623
- const found = findNotesArray(source);
1624
- if (found === "invalid") return null;
1625
- if (found === null) return source;
1626
- const { arrayStart, arrayEnd, elementTexts } = found;
1627
- if (index >= elementTexts.length) return source;
1628
- const next = elementTexts.slice();
1629
- next.splice(index, 1);
1630
- return rebuildNotesArray(source, arrayStart, arrayEnd, next);
1631
- }
1632
- /**
1633
- * Duplicate the note aligned with the page at `index`, inserting the copy right
1634
- * after it so the `notes` export stays index-aligned with `export default [...]`
1635
- * after a page duplication. Mirrors {@link duplicatePageInDefaultExportInSource}.
1636
- *
1637
- * Returns the rewritten source, the original source if no `notes` export exists
1638
- * or the index falls past the recorded notes (the new slot and everything after
1639
- * it are absent, so nothing shifts), or `null` if the shape is too surprising.
1640
- */
1641
- function duplicateNotesElementInSource(source, index) {
1642
- if (!Number.isInteger(index) || index < 0) return null;
1643
- const found = findNotesArray(source);
1644
- if (found === "invalid") return null;
1645
- if (found === null) return source;
1646
- const { arrayStart, arrayEnd, elementTexts } = found;
1647
- if (index >= elementTexts.length) return source;
1648
- const next = elementTexts.slice();
1649
- next.splice(index + 1, 0, next[index]);
1650
- return rebuildNotesArray(source, arrayStart, arrayEnd, next);
1651
- }
1652
- function rebuildNotesArray(source, arrayStart, arrayEnd, elements) {
1653
- const trimmed = elements.slice();
1654
- while (trimmed.length > 0 && trimmed[trimmed.length - 1] === "undefined") trimmed.pop();
1655
- const replacement = trimmed.length === 0 ? "[]" : `[\n${trimmed.map((s) => ` ${s},`).join("\n")}\n]`;
1656
- if (replacement === source.slice(arrayStart, arrayEnd)) return source;
1657
- return source.slice(0, arrayStart) + replacement + source.slice(arrayEnd);
1658
- }
1659
- /**
1660
- * Remove the element at `index` from `export default [...]`.
1661
- *
1662
- * Preserves the source slice of every other element, dropping the separator
1663
- * immediately following the removed element (or the preceding one when the
1664
- * removed element is the last). Returns `null` when the default export isn't
1665
- * an array literal or `index` is out of range.
1666
- */
1667
- function removePageFromDefaultExportInSource(source, index) {
1668
- const found = findDefaultExportArray(source);
1669
- if (!found) return null;
1670
- const { elements, arrayStart, arrayEnd } = found;
1671
- const n = elements.length;
1672
- if (!Number.isInteger(index) || index < 0 || index >= n) return null;
1673
- if (n === 1) return `${source.slice(0, arrayStart)}[]${source.slice(arrayEnd)}`;
1674
- const prefix = source.slice(arrayStart, elements[0].start);
1675
- const suffix = source.slice(elements[n - 1].end, arrayEnd);
1676
- const separators = [];
1677
- for (let i = 0; i < n - 1; i++) separators.push(source.slice(elements[i].end, elements[i + 1].start));
1678
- const elementText = elements.map((el) => source.slice(el.start, el.end));
1679
- const keptElements = [];
1680
- const keptSeparators = [];
1681
- for (let i = 0; i < n; i++) {
1682
- if (i === index) continue;
1683
- keptElements.push(elementText[i]);
1684
- }
1685
- for (let i = 0; i < n - 1; i++) {
1686
- if (index === n - 1 ? i === n - 2 : i === index) continue;
1687
- keptSeparators.push(separators[i]);
1688
- }
1689
- let rebuilt = prefix + keptElements[0];
1690
- for (let i = 1; i < keptElements.length; i++) rebuilt += keptSeparators[i - 1] + keptElements[i];
1691
- rebuilt += suffix;
1692
- return source.slice(0, arrayStart) + rebuilt + source.slice(arrayEnd);
1693
- }
1694
- function chooseInsertSeparator(prefix, existingSeparators) {
1695
- const sample = existingSeparators.find((s) => s.includes(","));
1696
- if (sample) return sample;
1697
- if (prefix.includes("\n")) {
1698
- const m = prefix.match(/\n([ \t]*)$/);
1699
- return `,\n${m ? m[1] : " "}`;
1700
- }
1701
- return ", ";
1702
- }
1703
- /**
1704
- * Duplicate the element at `index` in `export default [...]`, inserting the
1705
- * copy immediately after the original. Reuses an existing inter-element
1706
- * separator when one is available so the cloned entry matches the surrounding
1707
- * indentation. Returns `null` when the default export isn't an array literal
1708
- * or `index` is out of range.
1709
- */
1710
- function duplicatePageInDefaultExportInSource(source, index) {
1711
- const found = findDefaultExportArray(source);
1712
- if (!found) return null;
1713
- const { elements, arrayStart, arrayEnd } = found;
1714
- const n = elements.length;
1715
- if (!Number.isInteger(index) || index < 0 || index >= n) return null;
1716
- const prefix = source.slice(arrayStart, elements[0].start);
1717
- const suffix = source.slice(elements[n - 1].end, arrayEnd);
1718
- const separators = [];
1719
- for (let i = 0; i < n - 1; i++) separators.push(source.slice(elements[i].end, elements[i + 1].start));
1720
- const elementText = elements.map((el) => source.slice(el.start, el.end));
1721
- const insertSep = chooseInsertSeparator(prefix, separators);
1722
- const newElements = [];
1723
- const newSeparators = [];
1724
- for (let i = 0; i < n; i++) {
1725
- newElements.push(elementText[i]);
1726
- if (i === index) {
1727
- newElements.push(elementText[i]);
1728
- newSeparators.push(insertSep);
1729
- }
1730
- if (i < n - 1) newSeparators.push(separators[i]);
1731
- }
1732
- let rebuilt = prefix + newElements[0];
1733
- for (let i = 1; i < newElements.length; i++) rebuilt += newSeparators[i - 1] + newElements[i];
1734
- rebuilt += suffix;
1735
- return source.slice(0, arrayStart) + rebuilt + source.slice(arrayEnd);
1736
- }
1737
- //#endregion
1738
1218
  //#region src/files/assets.ts
1739
1219
  const GLOBAL_SCOPE = "@global";
1740
1220
  const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
@@ -1797,194 +1277,6 @@ function resolveScopedAssetFile(slidesRoot, globalAssetsRoot, scope, filename) {
1797
1277
  return file;
1798
1278
  }
1799
1279
  //#endregion
1800
- //#region src/http/request-guard.ts
1801
- function headerValue(req, name) {
1802
- const raw = req.headers[name.toLowerCase()];
1803
- return (Array.isArray(raw) ? raw[0] : raw)?.trim() ?? null;
1804
- }
1805
- function firstCommaToken(value) {
1806
- if (!value) return null;
1807
- const [first] = value.split(",", 1);
1808
- return first?.trim() || null;
1809
- }
1810
- function requestProto(req) {
1811
- const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
1812
- if (forwarded === "http" || forwarded === "https") return forwarded;
1813
- return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
1814
- }
1815
- function normalizedOrigin(origin) {
1816
- try {
1817
- const url = new URL(origin);
1818
- return `${url.protocol}//${url.host}`.toLowerCase();
1819
- } catch {
1820
- return null;
1821
- }
1822
- }
1823
- function validateMutationRequest(req, opts = {}) {
1824
- if (opts.requireJsonBody) {
1825
- if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
1826
- ok: false,
1827
- status: 415,
1828
- error: "content-type must be application/json"
1829
- };
1830
- }
1831
- if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
1832
- ok: false,
1833
- status: 403,
1834
- error: "cross-site request blocked"
1835
- };
1836
- const originRaw = headerValue(req, "origin");
1837
- if (!originRaw) return { ok: true };
1838
- if (originRaw.toLowerCase() === "null") return {
1839
- ok: false,
1840
- status: 403,
1841
- error: "opaque origin is not allowed"
1842
- };
1843
- const actualOrigin = normalizedOrigin(originRaw);
1844
- if (!actualOrigin) return {
1845
- ok: false,
1846
- status: 403,
1847
- error: "invalid origin header"
1848
- };
1849
- const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
1850
- if (!host) return {
1851
- ok: false,
1852
- status: 400,
1853
- error: "missing host header"
1854
- };
1855
- if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
1856
- ok: false,
1857
- status: 403,
1858
- error: "origin mismatch"
1859
- };
1860
- return { ok: true };
1861
- }
1862
- //#endregion
1863
- //#region src/files/short-id.ts
1864
- function shortId(prefix) {
1865
- return `${prefix}-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
1866
- }
1867
- //#endregion
1868
- //#region src/files/folders.ts
1869
- const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
1870
- const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
1871
- function foldersManifestPath(slidesRoot) {
1872
- return path.join(slidesRoot, ".folders.json");
1873
- }
1874
- function emptyManifest() {
1875
- return {
1876
- folders: [],
1877
- assignments: {}
1878
- };
1879
- }
1880
- async function readManifest(file) {
1881
- try {
1882
- const raw = await fs.readFile(file, "utf8");
1883
- const parsed = JSON.parse(raw);
1884
- return {
1885
- folders: Array.isArray(parsed.folders) ? parsed.folders : [],
1886
- assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
1887
- };
1888
- } catch (err) {
1889
- if (err.code === "ENOENT") return emptyManifest();
1890
- throw err;
1891
- }
1892
- }
1893
- async function writeManifest(file, manifest) {
1894
- await fs.mkdir(path.dirname(file), { recursive: true });
1895
- await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
1896
- }
1897
- function newFolderId() {
1898
- return shortId("f");
1899
- }
1900
- function validateName(v) {
1901
- if (typeof v !== "string") return null;
1902
- const trimmed = v.trim();
1903
- if (trimmed.length < 1 || trimmed.length > 40) return null;
1904
- return trimmed;
1905
- }
1906
- function validateReorder(v, current) {
1907
- if (!Array.isArray(v) || v.length !== current.length) return null;
1908
- const known = new Set(current.map((f) => f.id));
1909
- const seen = /* @__PURE__ */ new Set();
1910
- const out = [];
1911
- for (const id of v) {
1912
- if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
1913
- if (!known.has(id) || seen.has(id)) return null;
1914
- seen.add(id);
1915
- out.push(id);
1916
- }
1917
- return out;
1918
- }
1919
- function validateIcon(v) {
1920
- if (!v || typeof v !== "object") return null;
1921
- const icon = v;
1922
- if (icon.type === "emoji") {
1923
- if (typeof icon.value !== "string") return null;
1924
- if (icon.value.length < 1 || icon.value.length > 8) return null;
1925
- return {
1926
- type: "emoji",
1927
- value: icon.value
1928
- };
1929
- }
1930
- if (icon.type === "color") {
1931
- if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
1932
- return {
1933
- type: "color",
1934
- value: icon.value
1935
- };
1936
- }
1937
- return null;
1938
- }
1939
- //#endregion
1940
- //#region src/vite/routes/context.ts
1941
- function makeContext(opts) {
1942
- const userCwd = opts.userCwd;
1943
- const slidesDir = opts.slidesDir ?? "slides";
1944
- const assetsDir = opts.assetsDir ?? "assets";
1945
- const slidesRoot = path.resolve(userCwd, slidesDir);
1946
- return {
1947
- userCwd,
1948
- slidesDir,
1949
- slidesRoot,
1950
- globalAssetsRoot: path.resolve(userCwd, assetsDir),
1951
- manifestPath: foldersManifestPath(slidesRoot),
1952
- coreVersion: opts.coreVersion
1953
- };
1954
- }
1955
- async function readBody(req) {
1956
- return await new Promise((resolve, reject) => {
1957
- const chunks = [];
1958
- req.on("data", (c) => chunks.push(c));
1959
- req.on("end", () => {
1960
- const raw = Buffer.concat(chunks).toString("utf8");
1961
- if (!raw) return resolve({});
1962
- try {
1963
- resolve(JSON.parse(raw));
1964
- } catch (e) {
1965
- reject(e);
1966
- }
1967
- });
1968
- req.on("error", reject);
1969
- });
1970
- }
1971
- function json(res, status, body) {
1972
- res.statusCode = status;
1973
- res.setHeader("content-type", "application/json");
1974
- res.end(JSON.stringify(body));
1975
- }
1976
- function resolveSlideEntryPath(ctx, slideId) {
1977
- return resolveSlideEntry(ctx.slidesRoot, slideId);
1978
- }
1979
- async function readSlideSource(file) {
1980
- try {
1981
- return await fs.readFile(file, "utf8");
1982
- } catch (err) {
1983
- if (err.code === "ENOENT") return null;
1984
- throw err;
1985
- }
1986
- }
1987
- //#endregion
1988
1280
  //#region src/vite/routes/assets.ts
1989
1281
  function registerAssetRoutes(server, ctx) {
1990
1282
  server.middlewares.use("/__assets", async (req, res, next) => {
@@ -2270,7 +1562,8 @@ function registerCommentRoutes(server, ctx) {
2270
1562
  const method = req.method ?? "GET";
2271
1563
  try {
2272
1564
  if (method === "GET" && url.pathname === "/") {
2273
- const file = resolveSlideEntryPath(ctx, url.searchParams.get("slideId") ?? "");
1565
+ const slideId = url.searchParams.get("slideId") ?? "";
1566
+ const file = resolveSlideEntryPath(ctx, slideId);
2274
1567
  if (!file) return json(res, 400, { error: "invalid slideId" });
2275
1568
  const source = await readSlideSource(file);
2276
1569
  if (source === null) return json(res, 404, { error: "slide not found" });
@@ -2280,7 +1573,8 @@ function registerCommentRoutes(server, ctx) {
2280
1573
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
2281
1574
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
2282
1575
  const body = await readBody(req);
2283
- const file = resolveSlideEntryPath(ctx, body.slideId ?? "");
1576
+ const slideId = body.slideId ?? "";
1577
+ const file = resolveSlideEntryPath(ctx, slideId);
2284
1578
  if (!file) return json(res, 400, { error: "invalid slideId" });
2285
1579
  if (!body.line || body.line < 1) return json(res, 400, { error: "invalid line" });
2286
1580
  if (!body.text || typeof body.text !== "string") return json(res, 400, { error: "missing text" });
@@ -2297,9 +1591,10 @@ function registerCommentRoutes(server, ctx) {
2297
1591
  const marker = `\n${plan.indent}{/* @slide-comment id="${id}" ts="${ts}" text="${payload}" */}`;
2298
1592
  const next = source.slice(0, plan.offset) + marker + source.slice(plan.offset);
2299
1593
  await fs.writeFile(file, next, "utf8");
1594
+ const markerLine = offsetToLine(next, plan.offset + 1);
2300
1595
  return json(res, 200, {
2301
1596
  id,
2302
- line: offsetToLine(next, plan.offset + 1)
1597
+ line: markerLine
2303
1598
  });
2304
1599
  }
2305
1600
  if (method === "DELETE" && url.pathname.startsWith("/")) {
@@ -2307,7 +1602,8 @@ function registerCommentRoutes(server, ctx) {
2307
1602
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
2308
1603
  const id = url.pathname.slice(1);
2309
1604
  if (!/^c-[a-f0-9]+$/.test(id)) return json(res, 400, { error: "invalid id" });
2310
- const file = resolveSlideEntryPath(ctx, url.searchParams.get("slideId") ?? "");
1605
+ const slideId = url.searchParams.get("slideId") ?? "";
1606
+ const file = resolveSlideEntryPath(ctx, slideId);
2311
1607
  if (!file) return json(res, 400, { error: "invalid slideId" });
2312
1608
  const source = await readSlideSource(file);
2313
1609
  if (source === null) return json(res, 404, { error: "slide not found" });
@@ -2444,7 +1740,8 @@ function registerEditRoutes(server, ctx) {
2444
1740
  try {
2445
1741
  if (url.pathname === "/") {
2446
1742
  const body = await readBody(req);
2447
- const file = resolveSlideEntryPath(ctx, body.slideId ?? "");
1743
+ const slideId = body.slideId ?? "";
1744
+ const file = resolveSlideEntryPath(ctx, slideId);
2448
1745
  if (!file) return json(res, 400, { error: "invalid slideId" });
2449
1746
  if (!body.line || body.line < 1) return json(res, 400, { error: "invalid line" });
2450
1747
  if (!Array.isArray(body.ops)) return json(res, 400, { error: "missing ops" });
@@ -2480,7 +1777,8 @@ function registerEditRoutes(server, ctx) {
2480
1777
  }
2481
1778
  if (url.pathname === "/batch") {
2482
1779
  const body = await readBody(req);
2483
- const file = resolveSlideEntryPath(ctx, body.slideId ?? "");
1780
+ const slideId = body.slideId ?? "";
1781
+ const file = resolveSlideEntryPath(ctx, slideId);
2484
1782
  if (!file) return json(res, 400, { error: "invalid slideId" });
2485
1783
  if (!Array.isArray(body.edits)) return json(res, 400, { error: "missing edits" });
2486
1784
  const source = await readSlideSource(file);
@@ -2507,7 +1805,10 @@ function registerFolderRoutes(server, ctx) {
2507
1805
  const url = new URL(req.url ?? "/", "http://local");
2508
1806
  const method = req.method ?? "GET";
2509
1807
  try {
2510
- if (method === "GET" && url.pathname === "/") return json(res, 200, await readManifest(ctx.manifestPath));
1808
+ if (method === "GET" && url.pathname === "/") {
1809
+ const manifest = await readManifest(ctx.manifestPath);
1810
+ return json(res, 200, manifest);
1811
+ }
2511
1812
  if (method === "POST" && url.pathname === "/") {
2512
1813
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
2513
1814
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
@@ -2672,11 +1973,12 @@ function registerGfontsRoutes(server) {
2672
1973
  const limit = Number(reqUrl.searchParams.get("limit")) || 30;
2673
1974
  let entries = await loadCatalog();
2674
1975
  if (q) entries = entries.filter((e) => e.family.toLowerCase().includes(q));
2675
- return json(res, 200, entries.slice().sort((a, b) => a.popularity - b.popularity).slice(0, limit).map((e) => ({
1976
+ const items = entries.slice().sort((a, b) => a.popularity - b.popularity).slice(0, limit).map((e) => ({
2676
1977
  family: e.family,
2677
1978
  category: e.category,
2678
1979
  variants: e.variants
2679
- })));
1980
+ }));
1981
+ return json(res, 200, items);
2680
1982
  }
2681
1983
  if (reqUrl.pathname === "/download") {
2682
1984
  const family = reqUrl.searchParams.get("family");
@@ -2819,7 +2121,8 @@ function registerSlideRoutes(server, ctx) {
2819
2121
  if (method === "PATCH") {
2820
2122
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
2821
2123
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
2822
- const name = validateSlideName((await readBody(req)).name);
2124
+ const body = await readBody(req);
2125
+ const name = validateSlideName(body.name);
2823
2126
  if (!name) return json(res, 400, { error: "invalid name" });
2824
2127
  const entry = resolveSlideEntry(ctx.slidesRoot, slideId);
2825
2128
  if (!entry) return json(res, 400, { error: "invalid slideId" });
@@ -2897,179 +2200,6 @@ function registerSvglRoutes(server) {
2897
2200
  });
2898
2201
  }
2899
2202
  //#endregion
2900
- //#region src/vite/routes/update.ts
2901
- const PKG = "@open-slide/core";
2902
- const CACHE_TTL_MS = 6e5;
2903
- const COMMAND_TIMEOUT_MS = 3e5;
2904
- let cache = null;
2905
- let updateInFlight = null;
2906
- function parseSemver(v) {
2907
- const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(v.trim());
2908
- if (!m) return null;
2909
- return [
2910
- Number(m[1]),
2911
- Number(m[2]),
2912
- Number(m[3])
2913
- ];
2914
- }
2915
- function isOutdated(current, latest) {
2916
- const a = parseSemver(current);
2917
- const b = parseSemver(latest);
2918
- if (!a || !b) return false;
2919
- for (let i = 0; i < 3; i++) {
2920
- if (b[i] > a[i]) return true;
2921
- if (b[i] < a[i]) return false;
2922
- }
2923
- return false;
2924
- }
2925
- async function fetchLatest(now) {
2926
- if (cache && now - cache.at < CACHE_TTL_MS) return cache.latest;
2927
- try {
2928
- const res = await fetch(`https://registry.npmjs.org/${PKG}/latest`, {
2929
- signal: AbortSignal.timeout(3e3),
2930
- headers: { accept: "application/json" }
2931
- });
2932
- if (!res.ok) throw new Error(`registry ${res.status}`);
2933
- const body = await res.json();
2934
- const latest = typeof body.version === "string" ? body.version : null;
2935
- cache = {
2936
- at: now,
2937
- latest
2938
- };
2939
- return latest;
2940
- } catch {
2941
- return cache?.latest ?? null;
2942
- }
2943
- }
2944
- async function fileExists(file) {
2945
- try {
2946
- await fs.access(file);
2947
- return true;
2948
- } catch {
2949
- return false;
2950
- }
2951
- }
2952
- async function detectPackageManager(cwd) {
2953
- const ua = process.env.npm_config_user_agent ?? "";
2954
- if (ua.startsWith("pnpm")) return "pnpm";
2955
- if (ua.startsWith("yarn")) return "yarn";
2956
- if (ua.startsWith("bun")) return "bun";
2957
- if (ua.startsWith("npm")) return "npm";
2958
- if (await fileExists(path.join(cwd, "pnpm-lock.yaml"))) return "pnpm";
2959
- if (await fileExists(path.join(cwd, "yarn.lock"))) return "yarn";
2960
- if (await fileExists(path.join(cwd, "bun.lockb"))) return "bun";
2961
- if (await fileExists(path.join(cwd, "bun.lock"))) return "bun";
2962
- if (await fileExists(path.join(cwd, "package-lock.json"))) return "npm";
2963
- return "npm";
2964
- }
2965
- function updateCommandFor(packageManager) {
2966
- switch (packageManager) {
2967
- case "pnpm": return {
2968
- cmd: "pnpm",
2969
- args: ["add", `${PKG}@latest`]
2970
- };
2971
- case "yarn": return {
2972
- cmd: "yarn",
2973
- args: ["add", `${PKG}@latest`]
2974
- };
2975
- case "bun": return {
2976
- cmd: "bun",
2977
- args: ["add", `${PKG}@latest`]
2978
- };
2979
- case "npm": return {
2980
- cmd: "npm",
2981
- args: ["install", `${PKG}@latest`]
2982
- };
2983
- }
2984
- }
2985
- function localOpenSlideCommand(cwd) {
2986
- const bin = process.platform === "win32" ? "open-slide.cmd" : "open-slide";
2987
- return {
2988
- cmd: path.join(cwd, "node_modules", ".bin", bin),
2989
- args: ["sync:skills"]
2990
- };
2991
- }
2992
- function formatCommand(spec) {
2993
- return [spec.cmd, ...spec.args].join(" ");
2994
- }
2995
- async function runCommand(spec, cwd) {
2996
- await new Promise((resolve, reject) => {
2997
- const child = spawn(spec.cmd, spec.args, {
2998
- cwd,
2999
- env: process.env,
3000
- shell: process.platform === "win32",
3001
- stdio: [
3002
- "ignore",
3003
- "ignore",
3004
- "pipe"
3005
- ]
3006
- });
3007
- let stderr = "";
3008
- const timer = setTimeout(() => {
3009
- child.kill();
3010
- reject(/* @__PURE__ */ new Error(`${formatCommand(spec)} timed out`));
3011
- }, COMMAND_TIMEOUT_MS);
3012
- child.stderr.on("data", (chunk) => {
3013
- stderr += chunk.toString("utf8");
3014
- if (stderr.length > 2e3) stderr = stderr.slice(-2e3);
3015
- });
3016
- child.on("error", (err) => {
3017
- clearTimeout(timer);
3018
- reject(err);
3019
- });
3020
- child.on("close", (code) => {
3021
- clearTimeout(timer);
3022
- if (code === 0) {
3023
- resolve();
3024
- return;
3025
- }
3026
- const detail = stderr.trim();
3027
- reject(new Error(detail || `${formatCommand(spec)} exited with code ${code ?? "unknown"}`));
3028
- });
3029
- });
3030
- }
3031
- async function updatePackage(ctx) {
3032
- const packageManager = await detectPackageManager(ctx.userCwd);
3033
- const updateCommand = updateCommandFor(packageManager);
3034
- const syncCommand = localOpenSlideCommand(ctx.userCwd);
3035
- await runCommand(updateCommand, ctx.userCwd);
3036
- await runCommand(syncCommand, ctx.userCwd);
3037
- cache = null;
3038
- const latest = await fetchLatest(Date.now());
3039
- return {
3040
- packageManager,
3041
- command: `${formatCommand(updateCommand)} && open-slide sync:skills`,
3042
- latest,
3043
- message: "Updated @open-slide/core and synced skills."
3044
- };
3045
- }
3046
- function registerUpdateRoutes(server, ctx) {
3047
- server.middlewares.use("/__update-check", async (req, res, next) => {
3048
- if ((req.method ?? "GET") !== "GET") return next();
3049
- const latest = await fetchLatest(Date.now());
3050
- const result = {
3051
- current: ctx.coreVersion,
3052
- latest,
3053
- outdated: latest ? isOutdated(ctx.coreVersion, latest) : false
3054
- };
3055
- res.setHeader("cache-control", "no-store");
3056
- json(res, 200, result);
3057
- });
3058
- server.middlewares.use("/__update-package", async (req, res, next) => {
3059
- if ((req.method ?? "GET") !== "POST") return next();
3060
- const guard = validateMutationRequest(req);
3061
- if (!guard.ok) return json(res, guard.status, { error: guard.error });
3062
- try {
3063
- updateInFlight ??= updatePackage(ctx).finally(() => {
3064
- updateInFlight = null;
3065
- });
3066
- json(res, 200, await updateInFlight);
3067
- } catch (err) {
3068
- json(res, 500, { error: err instanceof Error ? err.message : "update failed" });
3069
- }
3070
- });
3071
- }
3072
- //#endregion
3073
2203
  //#region src/vite/routes/watchers.ts
3074
2204
  function registerWatchers(server, ctx) {
3075
2205
  server.watcher.add(ctx.manifestPath);