comarkserv 0.1.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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +389 -0
  3. package/dist/THIRD_PARTY_LICENSES.md +932 -0
  4. package/dist/build-CsToYJrU.mjs +2 -0
  5. package/dist/build-Cv5aO0CB.mjs +205 -0
  6. package/dist/cli.d.mts +1 -0
  7. package/dist/cli.mjs +894 -0
  8. package/dist/cloudflared-6f_lzz4F.mjs +181 -0
  9. package/dist/dist-B-IALNns.mjs +2 -0
  10. package/dist/dist-BK-bpLWg.mjs +2 -0
  11. package/dist/dist-BQzCbTko.mjs +1693 -0
  12. package/dist/dist-BWcWG5YB.mjs +671 -0
  13. package/dist/dist-BiVw4ojz.mjs +592 -0
  14. package/dist/dist-BnmL9jeq.mjs +538 -0
  15. package/dist/dist-BtedNLrc.mjs +276 -0
  16. package/dist/dist-BvdNTrap.mjs +2710 -0
  17. package/dist/dist-ByijHttv.mjs +69 -0
  18. package/dist/dist-C2E4zSX1.mjs +347 -0
  19. package/dist/dist-CWYRQLUT.mjs +2 -0
  20. package/dist/dist-CXQ7eTfT.mjs +417 -0
  21. package/dist/dist-CfsjQ0o8.mjs +905 -0
  22. package/dist/dist-CsTXDvwi.mjs +300 -0
  23. package/dist/dist-CtONMLh4.mjs +283 -0
  24. package/dist/dist-DMftjyxU.mjs +370 -0
  25. package/dist/dist-Dr9uTCX7.mjs +2 -0
  26. package/dist/dist-Dxvc11TH.mjs +339 -0
  27. package/dist/dist-GmbcGEAc.mjs +3 -0
  28. package/dist/dist-V1rkISnf.mjs +220 -0
  29. package/dist/dist-ZoN94PJ0.mjs +76 -0
  30. package/dist/dist-fh99cWMN.mjs +524 -0
  31. package/dist/editor-CHDyOp-8.mjs +721 -0
  32. package/dist/index.d.mts +301 -0
  33. package/dist/index.mjs +6 -0
  34. package/dist/languages-C0kEygG_.mjs +119 -0
  35. package/dist/markdown-BqKed1Vq.mjs +710 -0
  36. package/dist/markdown-DWuqfzps.mjs +2 -0
  37. package/dist/rolldown-runtime-CMFfr-1z.mjs +26 -0
  38. package/dist/server-Dkjk_D1Y.mjs +2628 -0
  39. package/dist/terminal-aKr5Xlp3.mjs +169 -0
  40. package/dist/themes-mEufQ_3e.mjs +2194 -0
  41. package/dist/twinkleplop.production-Coccf2Q9.mjs +2 -0
  42. package/dist/twinkleplop.production-DekYmX6O.mjs +4697 -0
  43. package/dist/twinkleplop.tokens-CgBUTCSg.mjs +76 -0
  44. package/package.json +133 -0
@@ -0,0 +1,2628 @@
1
+ import { O as relative, S as getAssets, T as dirname$1, _ as injectClient, a as themeWatchPath, b as renderReadme, d as hasHiddenSegment, f as isMarkdown, g as serverLinks, h as readDirectory, i as isThemeSource, k as resolve$1, l as crumbsFor, o as createSearchIndex, p as isSkippedPath, r as createThemeStore, s as extractOutline, t as OMARCHY_CURRENT, v as renderListing, x as renderStatus, y as renderPage } from "./themes-mEufQ_3e.mjs";
2
+ import { existsSync, readdirSync, stat, unwatchFile, watch, watchFile } from "node:fs";
3
+ import { lstat, open, readFile, readdir, realpath, stat as stat$1 } from "node:fs/promises";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import * as sp from "node:path";
6
+ import { basename, join, resolve, sep } from "node:path";
7
+ import { networkInterfaces, tmpdir, type } from "node:os";
8
+ import { promisify, styleText } from "node:util";
9
+ import { brotliCompress, constants as constants$1, gzip } from "node:zlib";
10
+ import { staticMiddleware } from "srvx/static";
11
+ import { EventEmitter } from "node:events";
12
+ import { Readable } from "node:stream";
13
+ import { createServer } from "node:net";
14
+ import { serve } from "srvx";
15
+ //#region src/share.ts
16
+ /** The Cloudflare documents that a user must accept before untun installs cloudflared. */
17
+ const CLOUDFLARE_LINKS = {
18
+ license: "https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/license/",
19
+ terms: "https://www.cloudflare.com/terms/",
20
+ privacy: "https://www.cloudflare.com/privacypolicy/"
21
+ };
22
+ /** The error when cloudflared must be installed and the user did not accept the Cloudflare license. */
23
+ var ShareConsentError = class extends Error {
24
+ constructor() {
25
+ super("Accept the Cloudflare license before comarkserv installs cloudflared.");
26
+ this.name = "ShareConsentError";
27
+ }
28
+ };
29
+ /** Returns true when untun installed cloudflared already, so no consent is necessary. */
30
+ function isCloudflaredInstalled() {
31
+ const directory = join(tmpdir(), "node-untun");
32
+ return existsSync(directory) && readdirSync(directory).some((name) => name.startsWith("cloudflared"));
33
+ }
34
+ const untunTunnel = async (options) => {
35
+ const { startTunnel } = await import("./dist-ZoN94PJ0.mjs");
36
+ return startTunnel(options);
37
+ };
38
+ function createShareService(options = {}) {
39
+ const startTunnel = options.startTunnel ?? untunTunnel;
40
+ const isInstalled = options.isInstalled ?? isCloudflaredInstalled;
41
+ const listeners = /* @__PURE__ */ new Set();
42
+ let tunnel;
43
+ let url;
44
+ let starting;
45
+ let error;
46
+ const status = () => ({
47
+ state: url ? "on" : starting ? "starting" : "off",
48
+ ...url ? { url } : {},
49
+ needsConsent: !isInstalled(),
50
+ ...error ? { error } : {}
51
+ });
52
+ const notify = () => {
53
+ const current = status();
54
+ for (const listener of listeners) listener(current);
55
+ };
56
+ const start = async (request) => {
57
+ if (url) return url;
58
+ if (starting) return starting;
59
+ const accept = request.accept === true;
60
+ if (!accept && !isInstalled()) throw new ShareConsentError();
61
+ error = void 0;
62
+ starting = (async () => {
63
+ const started = await startTunnel({
64
+ url: request.origin,
65
+ acceptCloudflareNotice: accept
66
+ });
67
+ if (!started) throw new Error("The tunnel did not start.");
68
+ const publicUrl = await started.getURL();
69
+ tunnel = started;
70
+ url = publicUrl;
71
+ return publicUrl;
72
+ })();
73
+ notify();
74
+ try {
75
+ return await starting;
76
+ } catch (cause) {
77
+ error = cause instanceof Error ? cause.message : String(cause);
78
+ throw cause;
79
+ } finally {
80
+ starting = void 0;
81
+ notify();
82
+ }
83
+ };
84
+ const stop = async () => {
85
+ const running = tunnel;
86
+ tunnel = void 0;
87
+ url = void 0;
88
+ if (running) {
89
+ await running.close();
90
+ notify();
91
+ }
92
+ };
93
+ return {
94
+ status,
95
+ start,
96
+ stop,
97
+ subscribe: (listener) => {
98
+ listeners.add(listener);
99
+ return () => listeners.delete(listener);
100
+ }
101
+ };
102
+ }
103
+ //#endregion
104
+ //#region node_modules/.pnpm/readdirp@5.1.1/node_modules/readdirp/index.js
105
+ const EntryTypes = {
106
+ FILE_TYPE: "files",
107
+ DIR_TYPE: "directories",
108
+ FILE_DIR_TYPE: "files_directories",
109
+ EVERYTHING_TYPE: "all"
110
+ };
111
+ const defaultOptions = {
112
+ root: ".",
113
+ fileFilter: (_entryInfo) => true,
114
+ directoryFilter: (_entryInfo) => true,
115
+ type: EntryTypes.FILE_TYPE,
116
+ lstat: false,
117
+ depth: 2147483648,
118
+ alwaysStat: false,
119
+ highWaterMark: 256
120
+ };
121
+ Object.freeze(defaultOptions);
122
+ const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
123
+ const NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set([
124
+ "ENOENT",
125
+ "EPERM",
126
+ "EACCES",
127
+ "ELOOP",
128
+ RECURSIVE_ERROR_CODE
129
+ ]);
130
+ const ALL_TYPES = [
131
+ EntryTypes.DIR_TYPE,
132
+ EntryTypes.EVERYTHING_TYPE,
133
+ EntryTypes.FILE_DIR_TYPE,
134
+ EntryTypes.FILE_TYPE
135
+ ];
136
+ const DIR_TYPES = /* @__PURE__ */ new Set([
137
+ EntryTypes.DIR_TYPE,
138
+ EntryTypes.EVERYTHING_TYPE,
139
+ EntryTypes.FILE_DIR_TYPE
140
+ ]);
141
+ const FILE_TYPES = /* @__PURE__ */ new Set([
142
+ EntryTypes.EVERYTHING_TYPE,
143
+ EntryTypes.FILE_DIR_TYPE,
144
+ EntryTypes.FILE_TYPE
145
+ ]);
146
+ const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
147
+ const wantBigintFsStats = process.platform === "win32";
148
+ const emptyFn = (_entryInfo) => true;
149
+ const normalizeFilter = (filter) => {
150
+ if (filter === void 0) return emptyFn;
151
+ if (typeof filter === "function") return filter;
152
+ if (typeof filter === "string") {
153
+ const fl = filter.trim();
154
+ return (entry) => entry.basename === fl;
155
+ }
156
+ if (Array.isArray(filter)) {
157
+ const trItems = filter.map((item) => item.trim());
158
+ return (entry) => trItems.some((f) => entry.basename === f);
159
+ }
160
+ return emptyFn;
161
+ };
162
+ var ReaddirpStream = class extends Readable {
163
+ /**
164
+ * Directories discovered but not yet emitted from. Listings are read
165
+ * lazily (on pop, plus one prefetch) instead of eagerly on discovery:
166
+ * keeping whole listings for every queued dir balloons RAM on wide trees.
167
+ */
168
+ parents;
169
+ reading;
170
+ parent;
171
+ _stat;
172
+ _maxDepth;
173
+ _wantsDir;
174
+ _wantsFile;
175
+ _wantsEverything;
176
+ _root;
177
+ _isDirent;
178
+ _statsProp;
179
+ _rdOptions;
180
+ _fileFilter;
181
+ _directoryFilter;
182
+ _relStart;
183
+ constructor(options = {}) {
184
+ super({
185
+ objectMode: true,
186
+ autoDestroy: true,
187
+ highWaterMark: options.highWaterMark ?? defaultOptions.highWaterMark
188
+ });
189
+ const opts = {
190
+ ...defaultOptions,
191
+ ...options
192
+ };
193
+ const root = opts.root ?? defaultOptions.root;
194
+ const type = opts.type ?? defaultOptions.type;
195
+ this._fileFilter = normalizeFilter(opts.fileFilter);
196
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
197
+ const statMethod = opts.lstat ? lstat : stat$1;
198
+ if (wantBigintFsStats) this._stat = (path) => statMethod(path, { bigint: true });
199
+ else this._stat = statMethod;
200
+ this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
201
+ this._wantsDir = DIR_TYPES.has(type);
202
+ this._wantsFile = FILE_TYPES.has(type);
203
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
204
+ this._root = resolve(root);
205
+ this._relStart = this._root.endsWith(sep) ? this._root.length : this._root.length + 1;
206
+ this._isDirent = !opts.alwaysStat;
207
+ this._statsProp = this._isDirent ? "dirent" : "stats";
208
+ this._rdOptions = {
209
+ encoding: "utf8",
210
+ withFileTypes: this._isDirent
211
+ };
212
+ const rootDir = {
213
+ path: this._root,
214
+ depth: 1
215
+ };
216
+ rootDir.pending = this._exploreDir(this._root, 1);
217
+ this.parents = [rootDir];
218
+ this.reading = false;
219
+ this.parent = void 0;
220
+ }
221
+ async _read(batch) {
222
+ if (this.reading) return;
223
+ this.reading = true;
224
+ try {
225
+ while (!this.destroyed && batch > 0) {
226
+ const par = this.parent;
227
+ const fil = par && par.files;
228
+ if (fil && fil.length > 0) {
229
+ const { path, depth } = par;
230
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
231
+ const awaited = this._isDirent ? slice : await Promise.all(slice);
232
+ for (const entry of awaited) {
233
+ if (!entry) continue;
234
+ if (this.destroyed) return;
235
+ let entryType = this._getEntryType(entry);
236
+ if (typeof entryType !== "string") entryType = await entryType;
237
+ if (entryType === "directory" && this._directoryFilter(entry)) {
238
+ if (depth <= this._maxDepth) this.parents.push({
239
+ path: entry.fullPath,
240
+ depth: depth + 1
241
+ });
242
+ if (this._wantsDir) {
243
+ this.push(entry);
244
+ batch--;
245
+ }
246
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
247
+ if (this._wantsFile) {
248
+ this.push(entry);
249
+ batch--;
250
+ }
251
+ }
252
+ }
253
+ } else {
254
+ const parent = this.parents.pop();
255
+ if (!parent) {
256
+ this.push(null);
257
+ break;
258
+ }
259
+ const dir = parent.pending ?? this._exploreDir(parent.path, parent.depth);
260
+ const next = this.parents[this.parents.length - 1];
261
+ if (next && !next.pending) next.pending = this._exploreDir(next.path, next.depth);
262
+ this.parent = await dir;
263
+ if (this.destroyed) return;
264
+ }
265
+ }
266
+ } catch (error) {
267
+ this.destroy(error);
268
+ } finally {
269
+ this.reading = false;
270
+ }
271
+ }
272
+ async _exploreDir(path, depth) {
273
+ let files;
274
+ try {
275
+ files = await readdir(path, this._rdOptions);
276
+ } catch (error) {
277
+ this._onError(error);
278
+ }
279
+ return {
280
+ files,
281
+ depth,
282
+ path
283
+ };
284
+ }
285
+ _formatEntry(dirent, path) {
286
+ const basename = this._isDirent ? dirent.name : dirent;
287
+ const fullPath = join(path, basename);
288
+ const entry = {
289
+ path: fullPath.slice(this._relStart),
290
+ fullPath,
291
+ basename
292
+ };
293
+ if (this._isDirent) {
294
+ entry.dirent = dirent;
295
+ return entry;
296
+ }
297
+ return this._stat(fullPath).then((stats) => {
298
+ entry.stats = stats;
299
+ return entry;
300
+ }, (err) => {
301
+ this._onError(err);
302
+ });
303
+ }
304
+ _onError(err) {
305
+ if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err);
306
+ else this.destroy(err);
307
+ }
308
+ _getEntryType(entry) {
309
+ if (!entry || !(this._statsProp in entry)) return "";
310
+ const stats = entry[this._statsProp];
311
+ if (stats.isFile()) return "file";
312
+ if (stats.isDirectory()) return "directory";
313
+ if (stats.isSymbolicLink()) return this._getSymlinkEntryType(entry);
314
+ return "";
315
+ }
316
+ async _getSymlinkEntryType(entry) {
317
+ const full = entry.fullPath;
318
+ try {
319
+ const entryRealPath = await realpath(full);
320
+ const entryRealPathStats = await lstat(entryRealPath);
321
+ if (entryRealPathStats.isFile()) return "file";
322
+ if (entryRealPathStats.isDirectory()) {
323
+ const len = entryRealPath.length;
324
+ if (full.startsWith(entryRealPath) && full[len] === sep) {
325
+ const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
326
+ recursiveError.code = RECURSIVE_ERROR_CODE;
327
+ this._onError(recursiveError);
328
+ return "";
329
+ }
330
+ return "directory";
331
+ }
332
+ } catch (error) {
333
+ this._onError(error);
334
+ }
335
+ return "";
336
+ }
337
+ _includeAsFile(entry) {
338
+ const stats = entry && entry[this._statsProp];
339
+ return stats && this._wantsEverything && !stats.isDirectory();
340
+ }
341
+ };
342
+ /**
343
+ * Streaming version: Reads all files and directories in given root recursively.
344
+ * Consumes ~constant small amount of RAM.
345
+ * @param root Root directory
346
+ * @param options Options to specify root (start directory), filters and recursion depth
347
+ */
348
+ function readdirp(root, options = {}) {
349
+ let type = options.entryType || options.type;
350
+ if (type === "both") type = EntryTypes.FILE_DIR_TYPE;
351
+ if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
352
+ else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
353
+ else if (type && !ALL_TYPES.includes(type)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
354
+ const opts = {
355
+ ...options,
356
+ root
357
+ };
358
+ if (type) opts.type = type;
359
+ return new ReaddirpStream(opts);
360
+ }
361
+ //#endregion
362
+ //#region node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/handler.js
363
+ const STR_DATA = "data";
364
+ const STR_CLOSE = "close";
365
+ const EMPTY_FN = () => {};
366
+ const pl = process.platform;
367
+ const isWindows = pl === "win32";
368
+ const isMacos = pl === "darwin";
369
+ const isLinux = pl === "linux";
370
+ const isFreeBSD = pl === "freebsd";
371
+ const isIBMi = type() === "OS400";
372
+ const EVENTS = {
373
+ ALL: "all",
374
+ READY: "ready",
375
+ ADD: "add",
376
+ CHANGE: "change",
377
+ ADD_DIR: "addDir",
378
+ UNLINK: "unlink",
379
+ UNLINK_DIR: "unlinkDir",
380
+ RAW: "raw",
381
+ ERROR: "error"
382
+ };
383
+ const EV = EVENTS;
384
+ const THROTTLE_MODE_WATCH = "watch";
385
+ const statMethods = {
386
+ lstat,
387
+ stat: stat$1
388
+ };
389
+ const KEY_LISTENERS = "listeners";
390
+ const KEY_ERR = "errHandlers";
391
+ const KEY_RAW = "rawEmitters";
392
+ const HANDLER_KEYS = [
393
+ KEY_LISTENERS,
394
+ KEY_ERR,
395
+ KEY_RAW
396
+ ];
397
+ const binaryExtensions = /* @__PURE__ */ new Set([
398
+ "3dm",
399
+ "3ds",
400
+ "3g2",
401
+ "3gp",
402
+ "7z",
403
+ "a",
404
+ "aac",
405
+ "adp",
406
+ "afdesign",
407
+ "afphoto",
408
+ "afpub",
409
+ "ai",
410
+ "aif",
411
+ "aiff",
412
+ "alz",
413
+ "ape",
414
+ "apk",
415
+ "appimage",
416
+ "ar",
417
+ "arj",
418
+ "asf",
419
+ "au",
420
+ "avi",
421
+ "bak",
422
+ "baml",
423
+ "bh",
424
+ "bin",
425
+ "bk",
426
+ "bmp",
427
+ "btif",
428
+ "bz2",
429
+ "bzip2",
430
+ "cab",
431
+ "caf",
432
+ "cgm",
433
+ "class",
434
+ "cmx",
435
+ "cpio",
436
+ "cr2",
437
+ "cur",
438
+ "dat",
439
+ "dcm",
440
+ "deb",
441
+ "dex",
442
+ "djvu",
443
+ "dll",
444
+ "dmg",
445
+ "dng",
446
+ "doc",
447
+ "docm",
448
+ "docx",
449
+ "dot",
450
+ "dotm",
451
+ "dra",
452
+ "DS_Store",
453
+ "dsk",
454
+ "dts",
455
+ "dtshd",
456
+ "dvb",
457
+ "dwg",
458
+ "dxf",
459
+ "ecelp4800",
460
+ "ecelp7470",
461
+ "ecelp9600",
462
+ "egg",
463
+ "eol",
464
+ "eot",
465
+ "epub",
466
+ "exe",
467
+ "f4v",
468
+ "fbs",
469
+ "fh",
470
+ "fla",
471
+ "flac",
472
+ "flatpak",
473
+ "fli",
474
+ "flv",
475
+ "fpx",
476
+ "fst",
477
+ "fvt",
478
+ "g3",
479
+ "gh",
480
+ "gif",
481
+ "graffle",
482
+ "gz",
483
+ "gzip",
484
+ "h261",
485
+ "h263",
486
+ "h264",
487
+ "icns",
488
+ "ico",
489
+ "ief",
490
+ "img",
491
+ "ipa",
492
+ "iso",
493
+ "jar",
494
+ "jpeg",
495
+ "jpg",
496
+ "jpgv",
497
+ "jpm",
498
+ "jxr",
499
+ "key",
500
+ "ktx",
501
+ "lha",
502
+ "lib",
503
+ "lvp",
504
+ "lz",
505
+ "lzh",
506
+ "lzma",
507
+ "lzo",
508
+ "m3u",
509
+ "m4a",
510
+ "m4v",
511
+ "mar",
512
+ "mdi",
513
+ "mht",
514
+ "mid",
515
+ "midi",
516
+ "mj2",
517
+ "mka",
518
+ "mkv",
519
+ "mmr",
520
+ "mng",
521
+ "mobi",
522
+ "mov",
523
+ "movie",
524
+ "mp3",
525
+ "mp4",
526
+ "mp4a",
527
+ "mpeg",
528
+ "mpg",
529
+ "mpga",
530
+ "mxu",
531
+ "nef",
532
+ "npx",
533
+ "numbers",
534
+ "nupkg",
535
+ "o",
536
+ "odp",
537
+ "ods",
538
+ "odt",
539
+ "oga",
540
+ "ogg",
541
+ "ogv",
542
+ "otf",
543
+ "ott",
544
+ "pages",
545
+ "pbm",
546
+ "pcx",
547
+ "pdb",
548
+ "pdf",
549
+ "pea",
550
+ "pgm",
551
+ "pic",
552
+ "png",
553
+ "pnm",
554
+ "pot",
555
+ "potm",
556
+ "potx",
557
+ "ppa",
558
+ "ppam",
559
+ "ppm",
560
+ "pps",
561
+ "ppsm",
562
+ "ppsx",
563
+ "ppt",
564
+ "pptm",
565
+ "pptx",
566
+ "psd",
567
+ "pya",
568
+ "pyc",
569
+ "pyo",
570
+ "pyv",
571
+ "qt",
572
+ "rar",
573
+ "ras",
574
+ "raw",
575
+ "resources",
576
+ "rgb",
577
+ "rip",
578
+ "rlc",
579
+ "rmf",
580
+ "rmvb",
581
+ "rpm",
582
+ "rtf",
583
+ "rz",
584
+ "s3m",
585
+ "s7z",
586
+ "scpt",
587
+ "sgi",
588
+ "shar",
589
+ "snap",
590
+ "sil",
591
+ "sketch",
592
+ "slk",
593
+ "smv",
594
+ "snk",
595
+ "so",
596
+ "stl",
597
+ "suo",
598
+ "sub",
599
+ "swf",
600
+ "tar",
601
+ "tbz",
602
+ "tbz2",
603
+ "tga",
604
+ "tgz",
605
+ "thmx",
606
+ "tif",
607
+ "tiff",
608
+ "tlz",
609
+ "ttc",
610
+ "ttf",
611
+ "txz",
612
+ "udf",
613
+ "uvh",
614
+ "uvi",
615
+ "uvm",
616
+ "uvp",
617
+ "uvs",
618
+ "uvu",
619
+ "viv",
620
+ "vob",
621
+ "war",
622
+ "wav",
623
+ "wax",
624
+ "wbmp",
625
+ "wdp",
626
+ "weba",
627
+ "webm",
628
+ "webp",
629
+ "whl",
630
+ "wim",
631
+ "wm",
632
+ "wma",
633
+ "wmv",
634
+ "wmx",
635
+ "woff",
636
+ "woff2",
637
+ "wrm",
638
+ "wvx",
639
+ "xbm",
640
+ "xif",
641
+ "xla",
642
+ "xlam",
643
+ "xls",
644
+ "xlsb",
645
+ "xlsm",
646
+ "xlsx",
647
+ "xlt",
648
+ "xltm",
649
+ "xltx",
650
+ "xm",
651
+ "xmind",
652
+ "xpi",
653
+ "xpm",
654
+ "xwd",
655
+ "xz",
656
+ "z",
657
+ "zip",
658
+ "zipx"
659
+ ]);
660
+ const isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());
661
+ const foreach = (val, fn) => {
662
+ if (val instanceof Set) val.forEach(fn);
663
+ else fn(val);
664
+ };
665
+ const addAndConvert = (main, prop, item) => {
666
+ let container = main[prop];
667
+ if (!(container instanceof Set)) main[prop] = container = /* @__PURE__ */ new Set([container]);
668
+ container.add(item);
669
+ };
670
+ const clearItem = (cont) => (key) => {
671
+ const set = cont[key];
672
+ if (set instanceof Set) set.clear();
673
+ else delete cont[key];
674
+ };
675
+ const delFromSet = (main, prop, item) => {
676
+ const container = main[prop];
677
+ if (container instanceof Set) container.delete(item);
678
+ else if (container === item) delete main[prop];
679
+ };
680
+ const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
681
+ const FsWatchInstances = /* @__PURE__ */ new Map();
682
+ /**
683
+ * Instantiates the fs_watch interface
684
+ * @param path to be watched
685
+ * @param options to be passed to fs_watch
686
+ * @param listener main event handler
687
+ * @param errHandler emits info about errors
688
+ * @param emitRaw emits raw event data
689
+ * @returns {NativeFsWatcher}
690
+ */
691
+ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
692
+ const handleEvent = (rawEvent, evPath) => {
693
+ listener(path);
694
+ emitRaw(rawEvent, evPath, { watchedPath: path });
695
+ if (evPath && path !== evPath) fsWatchBroadcast(sp.resolve(path, evPath), KEY_LISTENERS, sp.join(path, evPath));
696
+ };
697
+ try {
698
+ return watch(path, { persistent: options.persistent }, handleEvent);
699
+ } catch (error) {
700
+ errHandler(error);
701
+ return;
702
+ }
703
+ }
704
+ /**
705
+ * Helper for passing fs_watch event data to a collection of listeners
706
+ * @param fullPath absolute path bound to fs_watch instance
707
+ */
708
+ const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
709
+ const cont = FsWatchInstances.get(fullPath);
710
+ if (!cont) return;
711
+ foreach(cont[listenerType], (listener) => {
712
+ listener(val1, val2, val3);
713
+ });
714
+ };
715
+ /**
716
+ * Instantiates the fs_watch interface or binds listeners
717
+ * to an existing one covering the same file system entry
718
+ * @param path
719
+ * @param fullPath absolute path
720
+ * @param options to be passed to fs_watch
721
+ * @param handlers container for event listener functions
722
+ */
723
+ const setFsWatchListener = (path, fullPath, options, handlers) => {
724
+ const { listener, errHandler, rawEmitter } = handlers;
725
+ let cont = FsWatchInstances.get(fullPath);
726
+ let watcher;
727
+ if (!options.persistent) {
728
+ watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
729
+ if (!watcher) return;
730
+ return watcher.close.bind(watcher);
731
+ }
732
+ if (cont) {
733
+ addAndConvert(cont, KEY_LISTENERS, listener);
734
+ addAndConvert(cont, KEY_ERR, errHandler);
735
+ addAndConvert(cont, KEY_RAW, rawEmitter);
736
+ } else {
737
+ watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
738
+ if (!watcher) return;
739
+ watcher.on(EV.ERROR, async (error) => {
740
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
741
+ if (cont) cont.watcherUnusable = true;
742
+ if (isWindows && error.code === "EPERM") try {
743
+ await (await open(path, "r")).close();
744
+ broadcastErr(error);
745
+ } catch (err) {}
746
+ else broadcastErr(error);
747
+ });
748
+ cont = {
749
+ listeners: listener,
750
+ errHandlers: errHandler,
751
+ rawEmitters: rawEmitter,
752
+ watcher
753
+ };
754
+ FsWatchInstances.set(fullPath, cont);
755
+ }
756
+ return () => {
757
+ delFromSet(cont, KEY_LISTENERS, listener);
758
+ delFromSet(cont, KEY_ERR, errHandler);
759
+ delFromSet(cont, KEY_RAW, rawEmitter);
760
+ if (isEmptySet(cont.listeners)) {
761
+ cont.watcher.close();
762
+ FsWatchInstances.delete(fullPath);
763
+ HANDLER_KEYS.forEach(clearItem(cont));
764
+ cont.watcher = void 0;
765
+ Object.freeze(cont);
766
+ }
767
+ };
768
+ };
769
+ const FsWatchFileInstances = /* @__PURE__ */ new Map();
770
+ /**
771
+ * Instantiates the fs_watchFile interface or binds listeners
772
+ * to an existing one covering the same file system entry
773
+ * @param path to be watched
774
+ * @param fullPath absolute path
775
+ * @param options options to be passed to fs_watchFile
776
+ * @param handlers container for event listener functions
777
+ * @returns closer
778
+ */
779
+ const setFsWatchFileListener = (path, fullPath, options, handlers) => {
780
+ const { listener, rawEmitter } = handlers;
781
+ let cont = FsWatchFileInstances.get(fullPath);
782
+ const copts = cont && cont.options;
783
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
784
+ unwatchFile(fullPath);
785
+ cont = void 0;
786
+ }
787
+ if (cont) {
788
+ addAndConvert(cont, KEY_LISTENERS, listener);
789
+ addAndConvert(cont, KEY_RAW, rawEmitter);
790
+ } else {
791
+ cont = {
792
+ listeners: listener,
793
+ rawEmitters: rawEmitter,
794
+ options,
795
+ watcher: watchFile(fullPath, options, (curr, prev) => {
796
+ foreach(cont.rawEmitters, (rawEmitter) => {
797
+ rawEmitter(EV.CHANGE, fullPath, {
798
+ curr,
799
+ prev
800
+ });
801
+ });
802
+ const currmtime = curr.mtimeMs;
803
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener) => listener(path, curr));
804
+ })
805
+ };
806
+ FsWatchFileInstances.set(fullPath, cont);
807
+ }
808
+ return () => {
809
+ delFromSet(cont, KEY_LISTENERS, listener);
810
+ delFromSet(cont, KEY_RAW, rawEmitter);
811
+ if (isEmptySet(cont.listeners)) {
812
+ FsWatchFileInstances.delete(fullPath);
813
+ unwatchFile(fullPath);
814
+ cont.options = cont.watcher = void 0;
815
+ Object.freeze(cont);
816
+ }
817
+ };
818
+ };
819
+ /**
820
+ * @mixin
821
+ */
822
+ var NodeFsHandler = class {
823
+ fsw;
824
+ _boundHandleError;
825
+ constructor(fsW) {
826
+ this.fsw = fsW;
827
+ this._boundHandleError = (error) => fsW._handleError(error);
828
+ }
829
+ /**
830
+ * Watch file for changes with fs_watchFile or fs_watch.
831
+ * @param path to file or dir
832
+ * @param listener on fs change
833
+ * @returns closer for the watcher instance
834
+ */
835
+ _watchWithNodeFs(path, listener) {
836
+ const opts = this.fsw.options;
837
+ const directory = sp.dirname(path);
838
+ const basename = sp.basename(path);
839
+ this.fsw._getWatchedDir(directory).add(basename);
840
+ const absolutePath = sp.resolve(path);
841
+ const options = { persistent: opts.persistent };
842
+ if (!listener) listener = EMPTY_FN;
843
+ let closer;
844
+ if (opts.usePolling) {
845
+ options.interval = opts.interval !== opts.binaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
846
+ closer = setFsWatchFileListener(path, absolutePath, options, {
847
+ listener,
848
+ rawEmitter: this.fsw._emitRaw
849
+ });
850
+ } else closer = setFsWatchListener(path, absolutePath, options, {
851
+ listener,
852
+ errHandler: this._boundHandleError,
853
+ rawEmitter: this.fsw._emitRaw
854
+ });
855
+ return closer;
856
+ }
857
+ /**
858
+ * Watch a file and emit add event if warranted.
859
+ * @returns closer for the watcher instance
860
+ */
861
+ _handleFile(file, stats, initialAdd) {
862
+ if (this.fsw.closed) return;
863
+ const dirname = sp.dirname(file);
864
+ const basename = sp.basename(file);
865
+ const parent = this.fsw._getWatchedDir(dirname);
866
+ let prevStats = stats;
867
+ if (parent.has(basename)) return;
868
+ const listener = async (path, newStats) => {
869
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
870
+ if (!newStats || newStats.mtimeMs === 0) try {
871
+ const newStats = await stat$1(file);
872
+ if (this.fsw.closed) return;
873
+ const at = newStats.atimeMs;
874
+ const mt = newStats.mtimeMs;
875
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
876
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {
877
+ this.fsw._closeFile(path);
878
+ prevStats = newStats;
879
+ const closer = this._watchWithNodeFs(file, listener);
880
+ if (closer) this.fsw._addPathCloser(path, closer);
881
+ } else prevStats = newStats;
882
+ } catch (error) {
883
+ this.fsw._remove(dirname, basename);
884
+ }
885
+ else if (parent.has(basename)) {
886
+ const at = newStats.atimeMs;
887
+ const mt = newStats.mtimeMs;
888
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
889
+ prevStats = newStats;
890
+ }
891
+ };
892
+ const closer = this._watchWithNodeFs(file, listener);
893
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
894
+ if (!this.fsw._throttle(EV.ADD, file, 0)) return;
895
+ this.fsw._emit(EV.ADD, file, stats);
896
+ }
897
+ return closer;
898
+ }
899
+ /**
900
+ * Handle symlinks encountered while reading a dir.
901
+ * @param entry returned by readdirp
902
+ * @param directory path of dir being read
903
+ * @param path of this item
904
+ * @param item basename of this item
905
+ * @returns true if no more processing is needed for this entry.
906
+ */
907
+ async _handleSymlink(entry, directory, path, item) {
908
+ if (this.fsw.closed) return;
909
+ const full = entry.fullPath;
910
+ const dir = this.fsw._getWatchedDir(directory);
911
+ if (!this.fsw.options.followSymlinks) {
912
+ this.fsw._incrReadyCount();
913
+ let linkPath;
914
+ try {
915
+ linkPath = await realpath(path);
916
+ } catch (e) {
917
+ this.fsw._emitReady();
918
+ return true;
919
+ }
920
+ if (this.fsw.closed) return;
921
+ if (dir.has(item)) {
922
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
923
+ this.fsw._symlinkPaths.set(full, linkPath);
924
+ this.fsw._emit(EV.CHANGE, path, entry.stats);
925
+ }
926
+ } else {
927
+ dir.add(item);
928
+ this.fsw._symlinkPaths.set(full, linkPath);
929
+ this.fsw._emit(EV.ADD, path, entry.stats);
930
+ }
931
+ this.fsw._emitReady();
932
+ return true;
933
+ }
934
+ if (this.fsw._symlinkPaths.has(full)) return true;
935
+ this.fsw._symlinkPaths.set(full, true);
936
+ }
937
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
938
+ directory = sp.join(directory, "");
939
+ const throttleKey = target ? `${directory}:${target}` : directory;
940
+ throttler = this.fsw._throttle("readdir", throttleKey, 1e3);
941
+ if (!throttler) return;
942
+ const previous = this.fsw._getWatchedDir(wh.path);
943
+ const current = /* @__PURE__ */ new Set();
944
+ let stream = this.fsw._readdirp(directory, {
945
+ fileFilter: (entry) => wh.filterPath(entry),
946
+ directoryFilter: (entry) => wh.filterDir(entry)
947
+ });
948
+ if (!stream) return;
949
+ stream.on(STR_DATA, async (entry) => {
950
+ if (this.fsw.closed) {
951
+ stream = void 0;
952
+ return;
953
+ }
954
+ const item = entry.path;
955
+ let path = sp.join(directory, item);
956
+ current.add(item);
957
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) return;
958
+ if (this.fsw.closed) {
959
+ stream = void 0;
960
+ return;
961
+ }
962
+ if (item === target || !target && !previous.has(item)) {
963
+ this.fsw._incrReadyCount();
964
+ path = sp.join(dir, sp.relative(dir, path));
965
+ this._addToNodeFs(path, initialAdd, wh, depth + 1);
966
+ }
967
+ }).on(EV.ERROR, this._boundHandleError);
968
+ return new Promise((resolve, reject) => {
969
+ if (!stream) return reject();
970
+ stream.once("end", () => {
971
+ if (this.fsw.closed) {
972
+ stream = void 0;
973
+ return;
974
+ }
975
+ const wasThrottled = throttler ? throttler.clear() : false;
976
+ resolve(void 0);
977
+ previous.getChildren().filter((item) => {
978
+ return item !== directory && !current.has(item);
979
+ }).forEach((item) => {
980
+ this.fsw._remove(directory, item);
981
+ });
982
+ stream = void 0;
983
+ if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
984
+ });
985
+ });
986
+ }
987
+ /**
988
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
989
+ * @param dir fs path
990
+ * @param stats
991
+ * @param initialAdd
992
+ * @param depth relative to user-supplied path
993
+ * @param target child path targeted for watch
994
+ * @param wh Common watch helpers for this path
995
+ * @param realpath
996
+ * @returns closer for the watcher instance.
997
+ */
998
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
999
+ const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));
1000
+ const tracked = parentDir.has(sp.basename(dir));
1001
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) this.fsw._emit(EV.ADD_DIR, dir, stats);
1002
+ parentDir.add(sp.basename(dir));
1003
+ this.fsw._getWatchedDir(dir);
1004
+ let throttler;
1005
+ let closer;
1006
+ const oDepth = this.fsw.options.depth;
1007
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
1008
+ if (!target) {
1009
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
1010
+ if (this.fsw.closed) return;
1011
+ }
1012
+ closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
1013
+ if (stats && stats.mtimeMs === 0) return;
1014
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
1015
+ });
1016
+ }
1017
+ return closer;
1018
+ }
1019
+ /**
1020
+ * Handle added file, directory, or glob pattern.
1021
+ * Delegates call to _handleFile / _handleDir after checks.
1022
+ * @param path to file or ir
1023
+ * @param initialAdd was the file added at watch instantiation?
1024
+ * @param priorWh depth relative to user-supplied path
1025
+ * @param depth Child path actually targeted for watch
1026
+ * @param target Child path actually targeted for watch
1027
+ */
1028
+ async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
1029
+ const ready = this.fsw._emitReady;
1030
+ if (this.fsw._isIgnored(path) || this.fsw.closed) {
1031
+ ready();
1032
+ return false;
1033
+ }
1034
+ const wh = this.fsw._getWatchHelpers(path);
1035
+ if (priorWh) {
1036
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
1037
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
1038
+ }
1039
+ try {
1040
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
1041
+ if (this.fsw.closed) return;
1042
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
1043
+ ready();
1044
+ return false;
1045
+ }
1046
+ const follow = this.fsw.options.followSymlinks;
1047
+ let closer;
1048
+ if (stats.isDirectory()) {
1049
+ const absPath = sp.resolve(path);
1050
+ const targetPath = follow ? await realpath(path) : path;
1051
+ if (this.fsw.closed) return;
1052
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
1053
+ if (this.fsw.closed) return;
1054
+ if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath);
1055
+ } else if (stats.isSymbolicLink()) {
1056
+ const targetPath = follow ? await realpath(path) : path;
1057
+ if (this.fsw.closed) return;
1058
+ const parent = sp.dirname(wh.watchPath);
1059
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
1060
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
1061
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
1062
+ if (this.fsw.closed) return;
1063
+ if (targetPath !== void 0) this.fsw._symlinkPaths.set(sp.resolve(path), targetPath);
1064
+ } else closer = this._handleFile(wh.watchPath, stats, initialAdd);
1065
+ ready();
1066
+ if (closer) this.fsw._addPathCloser(path, closer);
1067
+ return false;
1068
+ } catch (error) {
1069
+ if (this.fsw._handleError(error)) {
1070
+ ready();
1071
+ return path;
1072
+ }
1073
+ }
1074
+ }
1075
+ };
1076
+ //#endregion
1077
+ //#region node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/index.js
1078
+ /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
1079
+ const SLASH = "/";
1080
+ const SLASH_SLASH = "//";
1081
+ const ONE_DOT = ".";
1082
+ const TWO_DOTS = "..";
1083
+ const STRING_TYPE = "string";
1084
+ const BACK_SLASH_RE = /\\/g;
1085
+ const DOUBLE_SLASH_RE = /\/\//g;
1086
+ const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
1087
+ const REPLACER_RE = /^\.[/\\]/;
1088
+ function arrify(item) {
1089
+ return Array.isArray(item) ? item : [item];
1090
+ }
1091
+ const isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
1092
+ function createPattern(matcher) {
1093
+ if (typeof matcher === "function") return matcher;
1094
+ if (typeof matcher === "string") return (string) => matcher === string;
1095
+ if (matcher instanceof RegExp) return (string) => matcher.test(string);
1096
+ if (typeof matcher === "object" && matcher !== null) return (string) => {
1097
+ if (matcher.path === string) return true;
1098
+ if (matcher.recursive) {
1099
+ const relative = sp.relative(matcher.path, string);
1100
+ if (!relative) return false;
1101
+ return !relative.startsWith("..") && !sp.isAbsolute(relative);
1102
+ }
1103
+ return false;
1104
+ };
1105
+ return () => false;
1106
+ }
1107
+ function normalizePath(path) {
1108
+ if (typeof path !== "string") throw new Error("string expected");
1109
+ path = sp.normalize(path);
1110
+ path = path.replace(/\\/g, "/");
1111
+ let prepend = false;
1112
+ if (path.startsWith("//")) prepend = true;
1113
+ path = path.replace(DOUBLE_SLASH_RE, "/");
1114
+ if (prepend) path = "/" + path;
1115
+ return path;
1116
+ }
1117
+ function matchPatterns(patterns, testString, stats) {
1118
+ const path = normalizePath(testString);
1119
+ for (let index = 0; index < patterns.length; index++) {
1120
+ const pattern = patterns[index];
1121
+ if (pattern(path, stats)) return true;
1122
+ }
1123
+ return false;
1124
+ }
1125
+ function anymatch(matchers, testString) {
1126
+ if (matchers == null) throw new TypeError("anymatch: specify first argument");
1127
+ const patterns = arrify(matchers).map((matcher) => createPattern(matcher));
1128
+ if (testString == null) return (testString, stats) => {
1129
+ return matchPatterns(patterns, testString, stats);
1130
+ };
1131
+ return matchPatterns(patterns, testString);
1132
+ }
1133
+ const unifyPaths = (paths_) => {
1134
+ const paths = arrify(paths_).flat();
1135
+ if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`);
1136
+ return paths.map(normalizePathToUnix);
1137
+ };
1138
+ const toUnix = (string) => {
1139
+ let str = string.replace(BACK_SLASH_RE, SLASH);
1140
+ let prepend = false;
1141
+ if (str.startsWith(SLASH_SLASH)) prepend = true;
1142
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
1143
+ if (prepend) str = SLASH + str;
1144
+ return str;
1145
+ };
1146
+ const normalizePathToUnix = (path) => toUnix(sp.normalize(toUnix(path)));
1147
+ const normalizeIgnored = (cwd = "") => (path) => {
1148
+ if (typeof path === "string") return normalizePathToUnix(sp.isAbsolute(path) ? path : sp.join(cwd, path));
1149
+ else return path;
1150
+ };
1151
+ const getAbsolutePath = (path, cwd) => {
1152
+ if (sp.isAbsolute(path)) return path;
1153
+ return sp.join(cwd, path);
1154
+ };
1155
+ const EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
1156
+ /**
1157
+ * Directory entry.
1158
+ */
1159
+ var DirEntry = class {
1160
+ path;
1161
+ _removeWatcher;
1162
+ items;
1163
+ constructor(dir, removeWatcher) {
1164
+ this.path = dir;
1165
+ this._removeWatcher = removeWatcher;
1166
+ this.items = /* @__PURE__ */ new Set();
1167
+ }
1168
+ add(item) {
1169
+ const { items } = this;
1170
+ if (!items) return;
1171
+ if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
1172
+ }
1173
+ async remove(item) {
1174
+ const { items } = this;
1175
+ if (!items) return;
1176
+ items.delete(item);
1177
+ if (items.size > 0) return;
1178
+ const dir = this.path;
1179
+ try {
1180
+ await readdir(dir);
1181
+ } catch (err) {
1182
+ if (this._removeWatcher) this._removeWatcher(sp.dirname(dir), sp.basename(dir));
1183
+ }
1184
+ }
1185
+ has(item) {
1186
+ const { items } = this;
1187
+ if (!items) return;
1188
+ return items.has(item);
1189
+ }
1190
+ getChildren() {
1191
+ const { items } = this;
1192
+ if (!items) return [];
1193
+ return [...items.values()];
1194
+ }
1195
+ dispose() {
1196
+ this.items.clear();
1197
+ this.path = "";
1198
+ this._removeWatcher = EMPTY_FN;
1199
+ this.items = EMPTY_SET;
1200
+ Object.freeze(this);
1201
+ }
1202
+ };
1203
+ const STAT_METHOD_F = "stat";
1204
+ const STAT_METHOD_L = "lstat";
1205
+ var WatchHelper = class {
1206
+ fsw;
1207
+ path;
1208
+ watchPath;
1209
+ fullWatchPath;
1210
+ dirParts;
1211
+ followSymlinks;
1212
+ statMethod;
1213
+ constructor(path, follow, fsw) {
1214
+ this.fsw = fsw;
1215
+ const watchPath = path;
1216
+ this.path = path = path.replace(REPLACER_RE, "");
1217
+ this.watchPath = watchPath;
1218
+ this.fullWatchPath = sp.resolve(watchPath);
1219
+ this.dirParts = [];
1220
+ this.dirParts.forEach((parts) => {
1221
+ if (parts.length > 1) parts.pop();
1222
+ });
1223
+ this.followSymlinks = follow;
1224
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1225
+ }
1226
+ entryPath(entry) {
1227
+ return sp.join(this.watchPath, sp.relative(this.watchPath, entry.fullPath));
1228
+ }
1229
+ filterPath(entry) {
1230
+ const { stats } = entry;
1231
+ if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
1232
+ const resolvedPath = this.entryPath(entry);
1233
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1234
+ }
1235
+ filterDir(entry) {
1236
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
1237
+ }
1238
+ };
1239
+ /**
1240
+ * Watches files & directories for changes. Emitted events:
1241
+ * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
1242
+ *
1243
+ * new FSWatcher()
1244
+ * .add(directories)
1245
+ * .on('add', path => log('File', path, 'was added'))
1246
+ */
1247
+ var FSWatcher = class extends EventEmitter {
1248
+ closed;
1249
+ options;
1250
+ _closers;
1251
+ _ignoredPaths;
1252
+ _throttled;
1253
+ _streams;
1254
+ _symlinkPaths;
1255
+ _watched;
1256
+ _pendingWrites;
1257
+ _pendingUnlinks;
1258
+ _readyCount;
1259
+ _emitReady;
1260
+ _closePromise;
1261
+ _userIgnored;
1262
+ _readyEmitted;
1263
+ _emitRaw;
1264
+ _boundRemove;
1265
+ _nodeFsHandler;
1266
+ constructor(_opts = {}) {
1267
+ super();
1268
+ this.closed = false;
1269
+ this._closers = /* @__PURE__ */ new Map();
1270
+ this._ignoredPaths = /* @__PURE__ */ new Set();
1271
+ this._throttled = /* @__PURE__ */ new Map();
1272
+ this._streams = /* @__PURE__ */ new Set();
1273
+ this._symlinkPaths = /* @__PURE__ */ new Map();
1274
+ this._watched = /* @__PURE__ */ new Map();
1275
+ this._pendingWrites = /* @__PURE__ */ new Map();
1276
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
1277
+ this._readyCount = 0;
1278
+ this._readyEmitted = false;
1279
+ const awf = _opts.awaitWriteFinish;
1280
+ const DEF_AWF = {
1281
+ stabilityThreshold: 2e3,
1282
+ pollInterval: 100
1283
+ };
1284
+ const opts = {
1285
+ persistent: true,
1286
+ ignoreInitial: false,
1287
+ ignorePermissionErrors: false,
1288
+ interval: 100,
1289
+ binaryInterval: 300,
1290
+ followSymlinks: true,
1291
+ usePolling: false,
1292
+ atomic: true,
1293
+ ..._opts,
1294
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1295
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? {
1296
+ ...DEF_AWF,
1297
+ ...awf
1298
+ } : false
1299
+ };
1300
+ if (isIBMi) opts.usePolling = true;
1301
+ if (opts.atomic === void 0) opts.atomic = !opts.usePolling;
1302
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
1303
+ if (envPoll !== void 0) {
1304
+ const envLower = envPoll.toLowerCase();
1305
+ if (envLower === "false" || envLower === "0") opts.usePolling = false;
1306
+ else if (envLower === "true" || envLower === "1") opts.usePolling = true;
1307
+ else opts.usePolling = !!envLower;
1308
+ }
1309
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
1310
+ if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
1311
+ let readyCalls = 0;
1312
+ this._emitReady = () => {
1313
+ readyCalls++;
1314
+ if (readyCalls >= this._readyCount) {
1315
+ this._emitReady = EMPTY_FN;
1316
+ this._readyEmitted = true;
1317
+ process.nextTick(() => this.emit(EVENTS.READY));
1318
+ }
1319
+ };
1320
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
1321
+ this._boundRemove = this._remove.bind(this);
1322
+ this.options = opts;
1323
+ this._nodeFsHandler = new NodeFsHandler(this);
1324
+ Object.freeze(opts);
1325
+ }
1326
+ _addIgnoredPath(matcher) {
1327
+ if (isMatcherObject(matcher)) {
1328
+ for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) return;
1329
+ }
1330
+ this._ignoredPaths.add(matcher);
1331
+ }
1332
+ _removeIgnoredPath(matcher) {
1333
+ this._ignoredPaths.delete(matcher);
1334
+ if (typeof matcher === "string") {
1335
+ for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher) this._ignoredPaths.delete(ignored);
1336
+ }
1337
+ }
1338
+ /**
1339
+ * Adds paths to be watched on an existing FSWatcher instance.
1340
+ * @param paths_ file or file list. Other arguments are unused
1341
+ */
1342
+ add(paths_, _origAdd, _internal) {
1343
+ const { cwd } = this.options;
1344
+ this.closed = false;
1345
+ this._closePromise = void 0;
1346
+ let paths = unifyPaths(paths_);
1347
+ if (cwd) paths = paths.map((path) => {
1348
+ return getAbsolutePath(path, cwd);
1349
+ });
1350
+ paths.forEach((path) => {
1351
+ this._removeIgnoredPath(path);
1352
+ });
1353
+ this._userIgnored = void 0;
1354
+ if (!this._readyCount) this._readyCount = 0;
1355
+ this._readyCount += paths.length;
1356
+ Promise.all(paths.map(async (path) => {
1357
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, void 0, 0, _origAdd);
1358
+ if (res) this._emitReady();
1359
+ return res;
1360
+ })).then((results) => {
1361
+ if (this.closed) return;
1362
+ results.forEach((item) => {
1363
+ if (item) this.add(sp.dirname(item), sp.basename(_origAdd || item));
1364
+ });
1365
+ });
1366
+ return this;
1367
+ }
1368
+ /**
1369
+ * Close watchers or start ignoring events from specified paths.
1370
+ */
1371
+ unwatch(paths_) {
1372
+ if (this.closed) return this;
1373
+ const paths = unifyPaths(paths_);
1374
+ const { cwd } = this.options;
1375
+ paths.forEach((path) => {
1376
+ if (!sp.isAbsolute(path) && !this._closers.has(path)) {
1377
+ if (cwd) path = sp.join(cwd, path);
1378
+ path = sp.resolve(path);
1379
+ }
1380
+ this._closePath(path);
1381
+ this._addIgnoredPath(path);
1382
+ if (this._watched.has(path)) this._addIgnoredPath({
1383
+ path,
1384
+ recursive: true
1385
+ });
1386
+ this._userIgnored = void 0;
1387
+ });
1388
+ return this;
1389
+ }
1390
+ /**
1391
+ * Close watchers and remove all listeners from watched paths.
1392
+ */
1393
+ close() {
1394
+ if (this._closePromise) return this._closePromise;
1395
+ this.closed = true;
1396
+ this.removeAllListeners();
1397
+ const closers = [];
1398
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
1399
+ const promise = closer();
1400
+ if (promise instanceof Promise) closers.push(promise);
1401
+ }));
1402
+ this._streams.forEach((stream) => stream.destroy());
1403
+ this._userIgnored = void 0;
1404
+ this._readyCount = 0;
1405
+ this._readyEmitted = false;
1406
+ this._watched.forEach((dirent) => dirent.dispose());
1407
+ this._closers.clear();
1408
+ this._watched.clear();
1409
+ this._streams.clear();
1410
+ this._symlinkPaths.clear();
1411
+ this._throttled.clear();
1412
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
1413
+ return this._closePromise;
1414
+ }
1415
+ /**
1416
+ * Expose list of watched paths
1417
+ * @returns for chaining
1418
+ */
1419
+ getWatched() {
1420
+ const watchList = {};
1421
+ this._watched.forEach((entry, dir) => {
1422
+ const index = (this.options.cwd ? sp.relative(this.options.cwd, dir) : dir) || ONE_DOT;
1423
+ watchList[index] = entry.getChildren().sort();
1424
+ });
1425
+ return watchList;
1426
+ }
1427
+ emitWithAll(event, args) {
1428
+ this.emit(event, ...args);
1429
+ if (event !== EVENTS.ERROR) this.emit(EVENTS.ALL, event, ...args);
1430
+ }
1431
+ /**
1432
+ * Normalize and emit events.
1433
+ * Calling _emit DOES NOT MEAN emit() would be called!
1434
+ * @param event Type of event
1435
+ * @param path File or directory path
1436
+ * @param stats arguments to be passed with event
1437
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1438
+ */
1439
+ async _emit(event, path, stats) {
1440
+ if (this.closed) return;
1441
+ const opts = this.options;
1442
+ if (isWindows) path = sp.normalize(path);
1443
+ if (opts.cwd) path = sp.relative(opts.cwd, path);
1444
+ const args = [path];
1445
+ if (stats != null) args.push(stats);
1446
+ const awf = opts.awaitWriteFinish;
1447
+ let pw;
1448
+ if (awf && (pw = this._pendingWrites.get(path))) {
1449
+ pw.lastChange = /* @__PURE__ */ new Date();
1450
+ return this;
1451
+ }
1452
+ if (opts.atomic) {
1453
+ if (event === EVENTS.UNLINK) {
1454
+ this._pendingUnlinks.set(path, [event, ...args]);
1455
+ setTimeout(() => {
1456
+ this._pendingUnlinks.forEach((entry, path) => {
1457
+ this.emit(...entry);
1458
+ this.emit(EVENTS.ALL, ...entry);
1459
+ this._pendingUnlinks.delete(path);
1460
+ });
1461
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
1462
+ return this;
1463
+ }
1464
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
1465
+ event = EVENTS.CHANGE;
1466
+ this._pendingUnlinks.delete(path);
1467
+ }
1468
+ }
1469
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1470
+ const awfEmit = (err, stats) => {
1471
+ if (err) {
1472
+ event = EVENTS.ERROR;
1473
+ args[0] = err;
1474
+ this.emitWithAll(event, args);
1475
+ } else if (stats) {
1476
+ if (args.length > 1) args[1] = stats;
1477
+ else args.push(stats);
1478
+ this.emitWithAll(event, args);
1479
+ }
1480
+ };
1481
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
1482
+ return this;
1483
+ }
1484
+ if (event === EVENTS.CHANGE) {
1485
+ if (!this._throttle(EVENTS.CHANGE, path, 50)) return this;
1486
+ }
1487
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1488
+ const fullPath = opts.cwd ? sp.join(opts.cwd, path) : path;
1489
+ let stats;
1490
+ try {
1491
+ stats = await stat$1(fullPath);
1492
+ } catch (err) {}
1493
+ if (!stats || this.closed) return;
1494
+ args.push(stats);
1495
+ }
1496
+ this.emitWithAll(event, args);
1497
+ return this;
1498
+ }
1499
+ /**
1500
+ * Common handler for errors
1501
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1502
+ */
1503
+ _handleError(error) {
1504
+ const code = error && error.code;
1505
+ if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EVENTS.ERROR, error);
1506
+ return error || this.closed;
1507
+ }
1508
+ /**
1509
+ * Helper utility for throttling
1510
+ * @param actionType type being throttled
1511
+ * @param path being acted upon
1512
+ * @param timeout duration of time to suppress duplicate actions
1513
+ * @returns tracking object or false if action should be suppressed
1514
+ */
1515
+ _throttle(actionType, path, timeout) {
1516
+ if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map());
1517
+ const action = this._throttled.get(actionType);
1518
+ if (!action) throw new Error("invalid throttle");
1519
+ const actionPath = action.get(path);
1520
+ if (actionPath) {
1521
+ actionPath.count++;
1522
+ return false;
1523
+ }
1524
+ let timeoutObject;
1525
+ const clear = () => {
1526
+ const item = action.get(path);
1527
+ const count = item ? item.count : 0;
1528
+ action.delete(path);
1529
+ clearTimeout(timeoutObject);
1530
+ if (item) clearTimeout(item.timeoutObject);
1531
+ return count;
1532
+ };
1533
+ timeoutObject = setTimeout(clear, timeout);
1534
+ const thr = {
1535
+ timeoutObject,
1536
+ clear,
1537
+ count: 0
1538
+ };
1539
+ action.set(path, thr);
1540
+ return thr;
1541
+ }
1542
+ _incrReadyCount() {
1543
+ return this._readyCount++;
1544
+ }
1545
+ /**
1546
+ * Awaits write operation to finish.
1547
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
1548
+ * @param path being acted upon
1549
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
1550
+ * @param event
1551
+ * @param awfEmit Callback to be called when ready for event to be emitted.
1552
+ */
1553
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
1554
+ const awf = this.options.awaitWriteFinish;
1555
+ if (typeof awf !== "object") return;
1556
+ const pollInterval = awf.pollInterval;
1557
+ let timeoutHandler;
1558
+ let fullPath = path;
1559
+ if (this.options.cwd && !sp.isAbsolute(path)) fullPath = sp.join(this.options.cwd, path);
1560
+ const now = /* @__PURE__ */ new Date();
1561
+ const writes = this._pendingWrites;
1562
+ function awaitWriteFinishFn(prevStat) {
1563
+ stat(fullPath, (err, curStat) => {
1564
+ if (err || !writes.has(path)) {
1565
+ if (err && err.code !== "ENOENT") awfEmit(err);
1566
+ return;
1567
+ }
1568
+ const now = Number(/* @__PURE__ */ new Date());
1569
+ if (prevStat && curStat.size !== prevStat.size) writes.get(path).lastChange = now;
1570
+ if (now - writes.get(path).lastChange >= threshold) {
1571
+ writes.delete(path);
1572
+ awfEmit(void 0, curStat);
1573
+ } else timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
1574
+ });
1575
+ }
1576
+ if (!writes.has(path)) {
1577
+ writes.set(path, {
1578
+ lastChange: now,
1579
+ cancelWait: () => {
1580
+ writes.delete(path);
1581
+ clearTimeout(timeoutHandler);
1582
+ return event;
1583
+ }
1584
+ });
1585
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
1586
+ }
1587
+ }
1588
+ /**
1589
+ * Determines whether user has asked to ignore this path.
1590
+ */
1591
+ _isIgnored(path, stats) {
1592
+ if (this.options.atomic && DOT_RE.test(path)) return true;
1593
+ if (!this._userIgnored) {
1594
+ const { cwd } = this.options;
1595
+ const ignored = (this.options.ignored || []).map(normalizeIgnored(cwd));
1596
+ const list = [...[...this._ignoredPaths].map(normalizeIgnored(cwd)), ...ignored];
1597
+ this._userIgnored = anymatch(list, void 0);
1598
+ }
1599
+ return this._userIgnored(path, stats);
1600
+ }
1601
+ _isntIgnored(path, stat) {
1602
+ return !this._isIgnored(path, stat);
1603
+ }
1604
+ /**
1605
+ * Provides a set of common helpers and properties relating to symlink handling.
1606
+ * @param path file or directory pattern being watched
1607
+ */
1608
+ _getWatchHelpers(path) {
1609
+ return new WatchHelper(path, this.options.followSymlinks, this);
1610
+ }
1611
+ /**
1612
+ * Provides directory tracking objects
1613
+ * @param directory path of the directory
1614
+ */
1615
+ _getWatchedDir(directory) {
1616
+ const dir = sp.resolve(directory);
1617
+ if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
1618
+ return this._watched.get(dir);
1619
+ }
1620
+ /**
1621
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
1622
+ */
1623
+ _hasReadPermissions(stats) {
1624
+ if (this.options.ignorePermissionErrors) return true;
1625
+ return Boolean(Number(stats.mode) & 256);
1626
+ }
1627
+ /**
1628
+ * Handles emitting unlink events for
1629
+ * files and directories, and via recursion, for
1630
+ * files and directories within directories that are unlinked
1631
+ * @param directory within which the following item is located
1632
+ * @param item base path of item/directory
1633
+ */
1634
+ _remove(directory, item, isDirectory) {
1635
+ const path = sp.join(directory, item);
1636
+ const fullPath = sp.resolve(path);
1637
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
1638
+ if (!this._throttle("remove", path, 100)) return;
1639
+ if (!isDirectory && this._watched.size === 1) this.add(directory, item, true);
1640
+ this._getWatchedDir(path).getChildren().forEach((nested) => this._remove(path, nested));
1641
+ const parent = this._getWatchedDir(directory);
1642
+ const wasTracked = parent.has(item);
1643
+ parent.remove(item);
1644
+ if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
1645
+ let relPath = path;
1646
+ if (this.options.cwd) relPath = sp.relative(this.options.cwd, path);
1647
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
1648
+ if (this._pendingWrites.get(relPath).cancelWait() === EVENTS.ADD) return;
1649
+ }
1650
+ this._watched.delete(path);
1651
+ this._watched.delete(fullPath);
1652
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
1653
+ if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
1654
+ this._closePath(path);
1655
+ }
1656
+ /**
1657
+ * Closes all watchers for a path
1658
+ */
1659
+ _closePath(path) {
1660
+ this._closeFile(path);
1661
+ const dir = sp.dirname(path);
1662
+ this._getWatchedDir(dir).remove(sp.basename(path));
1663
+ }
1664
+ /**
1665
+ * Closes only file-specific watchers
1666
+ */
1667
+ _closeFile(path) {
1668
+ const closers = this._closers.get(path);
1669
+ if (!closers) return;
1670
+ closers.forEach((closer) => closer());
1671
+ this._closers.delete(path);
1672
+ }
1673
+ _addPathCloser(path, closer) {
1674
+ if (!closer) return;
1675
+ let list = this._closers.get(path);
1676
+ if (!list) {
1677
+ list = [];
1678
+ this._closers.set(path, list);
1679
+ }
1680
+ list.push(closer);
1681
+ }
1682
+ _readdirp(root, opts) {
1683
+ if (this.closed) return;
1684
+ let stream = readdirp(root, {
1685
+ type: EVENTS.ALL,
1686
+ alwaysStat: true,
1687
+ lstat: true,
1688
+ ...opts,
1689
+ depth: 0
1690
+ });
1691
+ this._streams.add(stream);
1692
+ stream.once(STR_CLOSE, () => {
1693
+ stream = void 0;
1694
+ });
1695
+ stream.once("end", () => {
1696
+ if (stream) {
1697
+ this._streams.delete(stream);
1698
+ stream = void 0;
1699
+ }
1700
+ });
1701
+ return stream;
1702
+ }
1703
+ };
1704
+ /**
1705
+ * Instantiates watcher with paths to be tracked.
1706
+ * @param paths file / directory paths
1707
+ * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
1708
+ * @returns an instance of FSWatcher for chaining.
1709
+ * @example
1710
+ * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
1711
+ * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
1712
+ */
1713
+ function watch$1(paths, options = {}) {
1714
+ const watcher = new FSWatcher(options);
1715
+ watcher.add(paths);
1716
+ return watcher;
1717
+ }
1718
+ //#endregion
1719
+ //#region src/theme-server.ts
1720
+ const RAW_PATH = /^raw\/([^/]+)\/([^/]+)$/;
1721
+ const DEBOUNCE = 80;
1722
+ function notFound() {
1723
+ return new Response("Not found", { status: 404 });
1724
+ }
1725
+ function text(body, cacheControl) {
1726
+ return new Response(body, { headers: {
1727
+ "content-type": "text/plain; charset=utf-8",
1728
+ "cache-control": cacheControl
1729
+ } });
1730
+ }
1731
+ function createThemeService(options) {
1732
+ const { store, prefix } = options;
1733
+ const omarchyPath = resolve$1(options.omarchyPath ?? OMARCHY_CURRENT);
1734
+ const cwd = options.cwd ?? process.cwd();
1735
+ const defaultPath = themeWatchPath(options.spec, cwd, omarchyPath);
1736
+ const listeners = /* @__PURE__ */ new Set();
1737
+ const timers = /* @__PURE__ */ new Map();
1738
+ let version = 0;
1739
+ const load = () => store.load(options.spec, cwd).catch((error) => {
1740
+ const message = error instanceof Error ? error.message : String(error);
1741
+ console.warn(`comarkserv: ${message} The pages use the GitHub theme.`);
1742
+ });
1743
+ let current = load();
1744
+ const emit = (theme) => {
1745
+ if (theme) for (const listener of listeners) listener(theme);
1746
+ };
1747
+ const onFile = async (path) => {
1748
+ if (path === defaultPath) {
1749
+ version++;
1750
+ current = load();
1751
+ emit(await current);
1752
+ } else if (path === omarchyPath) emit(await store.load("omarchy", cwd).catch(() => void 0));
1753
+ };
1754
+ let watcher;
1755
+ let ready = Promise.resolve();
1756
+ const files = /* @__PURE__ */ new Set();
1757
+ if (options.watch) {
1758
+ if (defaultPath) files.add(resolve$1(defaultPath));
1759
+ if (existsSync(omarchyPath)) files.add(omarchyPath);
1760
+ }
1761
+ if (files.size > 0) {
1762
+ const active = watch$1([...files].map((file) => file === omarchyPath ? dirname$1(dirname$1(file)) : dirname$1(file)), {
1763
+ ignoreInitial: true,
1764
+ depth: 1,
1765
+ ignored: (path, stats) => stats?.isFile() === true && !files.has(resolve$1(path))
1766
+ });
1767
+ active.on("all", (_event, path) => {
1768
+ const file = resolve$1(path);
1769
+ if (!files.has(file)) return;
1770
+ clearTimeout(timers.get(file));
1771
+ timers.set(file, setTimeout(() => void onFile(file), DEBOUNCE));
1772
+ });
1773
+ active.on("error", () => {});
1774
+ ready = new Promise((done) => active.once("ready", () => done()));
1775
+ watcher = active;
1776
+ }
1777
+ const catalog = async () => {
1778
+ const entries = await store.catalog((source, id) => `${prefix}raw/${source}/${id}`).catch(() => []);
1779
+ if (existsSync(omarchyPath)) entries.unshift({
1780
+ id: "omarchy-live",
1781
+ name: "Omarchy (live)",
1782
+ source: "omarchy-live",
1783
+ url: `${prefix}omarchy-live`
1784
+ });
1785
+ return Response.json(entries, { headers: { "cache-control": "no-cache" } });
1786
+ };
1787
+ const handle = async (_request, name) => {
1788
+ if (name === "catalog.json") return catalog();
1789
+ if (name === "omarchy-live") {
1790
+ const body = await readFile(omarchyPath, "utf8").catch(() => void 0);
1791
+ return body === void 0 ? notFound() : text(body, "no-cache");
1792
+ }
1793
+ const [, source = "", id = ""] = RAW_PATH.exec(name) ?? [];
1794
+ if (!isThemeSource(source)) return notFound();
1795
+ const body = await store.raw(source, id).catch(() => void 0);
1796
+ return body === void 0 ? notFound() : text(body, "public, max-age=86400");
1797
+ };
1798
+ return {
1799
+ ready,
1800
+ current: () => current,
1801
+ version: () => version,
1802
+ handle,
1803
+ subscribe: (listener) => {
1804
+ listeners.add(listener);
1805
+ return () => listeners.delete(listener);
1806
+ },
1807
+ close: async () => {
1808
+ for (const timer of timers.values()) clearTimeout(timer);
1809
+ listeners.clear();
1810
+ await watcher?.close();
1811
+ }
1812
+ };
1813
+ }
1814
+ //#endregion
1815
+ //#region src/watch.ts
1816
+ function watchTree(root, options) {
1817
+ const listeners = /* @__PURE__ */ new Set();
1818
+ let pending = /* @__PURE__ */ new Set();
1819
+ let timer;
1820
+ const watcher = watch$1(root, {
1821
+ ignoreInitial: true,
1822
+ ignored: (path) => {
1823
+ const local = relative(root, path);
1824
+ return local !== "" && options.ignore(local);
1825
+ }
1826
+ });
1827
+ const flush = () => {
1828
+ timer = void 0;
1829
+ const paths = [...pending];
1830
+ pending = /* @__PURE__ */ new Set();
1831
+ for (const listener of listeners) listener(paths);
1832
+ };
1833
+ watcher.on("all", (_event, path) => {
1834
+ pending.add(`/${relative(root, path)}`);
1835
+ timer ??= setTimeout(flush, options.debounce ?? 30);
1836
+ });
1837
+ watcher.on("error", () => {});
1838
+ return {
1839
+ ready: new Promise((resolve) => watcher.once("ready", () => resolve())),
1840
+ subscribe: (listener) => {
1841
+ listeners.add(listener);
1842
+ return () => listeners.delete(listener);
1843
+ },
1844
+ close: async () => {
1845
+ if (timer) clearTimeout(timer);
1846
+ listeners.clear();
1847
+ await watcher.close();
1848
+ }
1849
+ };
1850
+ }
1851
+ //#endregion
1852
+ //#region src/handler.ts
1853
+ /** The URL prefix of the files and endpoints of comarkserv itself. */
1854
+ const INTERNAL_PREFIX = "/__comarkserv/";
1855
+ const HTML = "text/html; charset=utf-8";
1856
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
1857
+ "localhost",
1858
+ "127.0.0.1",
1859
+ "[::1]"
1860
+ ]);
1861
+ const PROXY_HEADERS = [
1862
+ "cf-ray",
1863
+ "cf-connecting-ip",
1864
+ "x-forwarded-for",
1865
+ "forwarded",
1866
+ "x-real-ip"
1867
+ ];
1868
+ /** Returns true for a request from a browser on this machine, not through a tunnel or a proxy. */
1869
+ function isLocalRequest(request) {
1870
+ return LOOPBACK_HOSTS.has(new URL(request.url).hostname) && PROXY_HEADERS.every((header) => !request.headers.has(header));
1871
+ }
1872
+ /**
1873
+ * Returns true for an action from a comarkserv page on this machine: a local request,
1874
+ * from the same origin, with the custom header. A cross-origin request with that
1875
+ * header needs a preflight, and the server answers no preflight.
1876
+ */
1877
+ function isLocalAction(request) {
1878
+ const origin = request.headers.get("origin");
1879
+ return isLocalRequest(request) && (origin === null || origin === new URL(request.url).origin) && request.headers.get("x-comarkserv-action") === "1";
1880
+ }
1881
+ async function qrCode(text) {
1882
+ const { renderSVG } = await import("./dist-CfsjQ0o8.mjs");
1883
+ return renderSVG(text, {
1884
+ pixelSize: 4,
1885
+ whiteColor: "#ffffff",
1886
+ blackColor: "#1f2328"
1887
+ });
1888
+ }
1889
+ const MIN_COMPRESS_SIZE = 1024;
1890
+ const IMMUTABLE = "public, max-age=31536000, immutable";
1891
+ const brotli = promisify(brotliCompress);
1892
+ const gzipAsync = promisify(gzip);
1893
+ var Lru = class {
1894
+ map = /* @__PURE__ */ new Map();
1895
+ max;
1896
+ constructor(max) {
1897
+ this.max = max;
1898
+ }
1899
+ get(key) {
1900
+ const value = this.map.get(key);
1901
+ if (value !== void 0) {
1902
+ this.map.delete(key);
1903
+ this.map.set(key, value);
1904
+ }
1905
+ return value;
1906
+ }
1907
+ set(key, value) {
1908
+ this.map.delete(key);
1909
+ this.map.set(key, value);
1910
+ if (this.map.size > this.max) this.map.delete(this.map.keys().next().value ?? "");
1911
+ }
1912
+ delete(key) {
1913
+ this.map.delete(key);
1914
+ }
1915
+ };
1916
+ function makeBody(text, type, etag) {
1917
+ return {
1918
+ text,
1919
+ type,
1920
+ etag: `W/"${etag ?? createHash("sha1").update(text).digest("base64url").slice(0, 16)}"`,
1921
+ encoded: /* @__PURE__ */ new Map()
1922
+ };
1923
+ }
1924
+ function negotiate(header) {
1925
+ if (!header) return void 0;
1926
+ const accepted = /* @__PURE__ */ new Set();
1927
+ for (const part of header.toLowerCase().split(",")) {
1928
+ const [name = "", ...params] = part.trim().split(";");
1929
+ const quality = params.find((param) => param.trim().startsWith("q="));
1930
+ if (quality && Number(quality.trim().slice(2)) === 0) continue;
1931
+ accepted.add(name.trim());
1932
+ }
1933
+ if (accepted.has("br")) return "br";
1934
+ if (accepted.has("gzip")) return "gzip";
1935
+ }
1936
+ async function compress(text, encoding) {
1937
+ const data = encoding === "br" ? await brotli(text, { params: {
1938
+ [constants$1.BROTLI_PARAM_QUALITY]: 5,
1939
+ [constants$1.BROTLI_PARAM_SIZE_HINT]: Buffer.byteLength(text)
1940
+ } }) : await gzipAsync(text, { level: 6 });
1941
+ return new Uint8Array(data);
1942
+ }
1943
+ function etagMatches(header, etag) {
1944
+ if (!header) return false;
1945
+ const weak = (tag) => tag.trim().replace(/^W\//, "");
1946
+ return header.split(",").some((tag) => tag.trim() === "*" || weak(tag) === weak(etag));
1947
+ }
1948
+ async function respond(request, body, init = {}) {
1949
+ const status = init.status ?? 200;
1950
+ const headers = new Headers({
1951
+ "content-type": body.type,
1952
+ "cache-control": "no-cache",
1953
+ etag: body.etag,
1954
+ ...init.headers
1955
+ });
1956
+ if (status === 200 && etagMatches(request.headers.get("if-none-match"), body.etag)) return new Response(null, {
1957
+ status: 304,
1958
+ headers
1959
+ });
1960
+ const compressible = body.text.length >= MIN_COMPRESS_SIZE;
1961
+ if (compressible) headers.set("vary", "accept-encoding");
1962
+ if (request.method === "HEAD") return new Response(null, {
1963
+ status,
1964
+ headers
1965
+ });
1966
+ const encoding = compressible ? negotiate(request.headers.get("accept-encoding")) : void 0;
1967
+ if (!encoding) return new Response(body.text, {
1968
+ status,
1969
+ headers
1970
+ });
1971
+ let data = body.encoded.get(encoding);
1972
+ if (!data) {
1973
+ data = compress(body.text, encoding);
1974
+ body.encoded.set(encoding, data);
1975
+ }
1976
+ headers.set("content-encoding", encoding);
1977
+ return new Response(await data, {
1978
+ status,
1979
+ headers
1980
+ });
1981
+ }
1982
+ function timing(ms, cached) {
1983
+ return `render;dur=${ms.toFixed(2)}${cached ? ", cache;desc=\"hit\"" : ""}`;
1984
+ }
1985
+ function errorText(error) {
1986
+ return error instanceof Error ? error.stack ?? error.message : String(error);
1987
+ }
1988
+ function createHandler(options = {}) {
1989
+ const root = resolve(options.root ?? process.cwd());
1990
+ const rootName = basename(root) || root;
1991
+ const livereload = options.livereload ?? true;
1992
+ const editor = options.editor ?? true;
1993
+ const shareService = options.share === false ? void 0 : options.shareService ?? createShareService();
1994
+ const openEditor = options.openEditor ?? (async (file, line) => (await import("./editor-CHDyOp-8.mjs")).openInEditor(file, line));
1995
+ const dotfiles = options.dotfiles ?? false;
1996
+ let renderer;
1997
+ const getRenderer = () => renderer ??= import("./markdown-DWuqfzps.mjs").then((module) => module.createMarkdownRenderer(options));
1998
+ const renders = new Lru(options.cacheSize ?? 500);
1999
+ const pages = new Lru(options.cacheSize ?? 500);
2000
+ const search = createSearchIndex({
2001
+ root,
2002
+ dotfiles
2003
+ });
2004
+ const serverId = randomUUID();
2005
+ const streams = /* @__PURE__ */ new Set();
2006
+ const themes = createThemeService({
2007
+ spec: options.theme ?? "github",
2008
+ store: options.themeStore ?? createThemeStore({ omarchyPath: options.omarchyPath }),
2009
+ prefix: `${INTERNAL_PREFIX}themes/`,
2010
+ watch: livereload,
2011
+ omarchyPath: options.omarchyPath
2012
+ });
2013
+ const assets = getAssets();
2014
+ const assetBodies = {
2015
+ "app.css": makeBody(assets["app.css"].body, assets["app.css"].type, assets["app.css"].version),
2016
+ "app.js": makeBody(assets["app.js"].body, assets["app.js"].type, assets["app.js"].version)
2017
+ };
2018
+ const pageAssets = {
2019
+ css: `${INTERNAL_PREFIX}app.css?v=${assets["app.css"].version}`,
2020
+ js: `${INTERNAL_PREFIX}app.js?v=${assets["app.js"].version}`,
2021
+ katex: `${INTERNAL_PREFIX}katex/katex.min.css?v=${assets.katexVersion}`
2022
+ };
2023
+ const config = (source, kind, lines) => ({
2024
+ root: "/",
2025
+ search: `${INTERNAL_PREFIX}search.json`,
2026
+ events: livereload ? `${INTERNAL_PREFIX}events` : "",
2027
+ themes: `${INTERNAL_PREFIX}themes/catalog.json`,
2028
+ edit: editor ? `${INTERNAL_PREFIX}edit` : "",
2029
+ share: shareService ? `${INTERNAL_PREFIX}share` : "",
2030
+ local: `${INTERNAL_PREFIX}local`,
2031
+ source,
2032
+ kind,
2033
+ ...lines ? { lines } : {}
2034
+ });
2035
+ const page = async (input) => renderPage({
2036
+ ...input,
2037
+ assets: pageAssets,
2038
+ theme: await themes.current()
2039
+ });
2040
+ const watcher = livereload ? watchTree(root, { ignore: (path) => isSkippedPath(path, dotfiles) }) : void 0;
2041
+ watcher?.subscribe((paths) => {
2042
+ search.invalidate(paths);
2043
+ for (const path of paths) {
2044
+ renders.delete(join(root, path));
2045
+ pages.delete(path);
2046
+ pages.delete(path.slice(0, path.lastIndexOf("/") + 1));
2047
+ }
2048
+ });
2049
+ const serveStatic = staticMiddleware({
2050
+ dir: root,
2051
+ dotfiles: dotfiles ? true : [".well-known"],
2052
+ renderHTML: livereload ? ({ request, html }) => {
2053
+ const source = decodeURIComponent(new URL(request.url).pathname);
2054
+ const injected = injectClient(html, config(source, "html"), pageAssets);
2055
+ return new Response(injected, { headers: { "content-type": HTML } });
2056
+ } : void 0
2057
+ });
2058
+ const serveKatex = staticMiddleware({
2059
+ dir: assets.katexDir,
2060
+ maxAge: 31536e3,
2061
+ immutable: true,
2062
+ dotfiles: false
2063
+ });
2064
+ const renderFile = (path, info) => {
2065
+ const stamp = `${info.mtimeMs}:${info.size}`;
2066
+ const cached = renders.get(path);
2067
+ if (cached?.stamp === stamp) return cached.result;
2068
+ const result = (async () => {
2069
+ const started = performance.now();
2070
+ const [render, source] = await Promise.all([getRenderer(), readFile(path, "utf8")]);
2071
+ const rendered = await render(source);
2072
+ const lines = Object.fromEntries(extractOutline(source).headings.map((heading) => [heading.id, heading.line]));
2073
+ return {
2074
+ rendered,
2075
+ ms: performance.now() - started,
2076
+ lines
2077
+ };
2078
+ })();
2079
+ renders.set(path, {
2080
+ stamp,
2081
+ result
2082
+ });
2083
+ result.catch(() => renders.delete(path));
2084
+ return result;
2085
+ };
2086
+ const notFound = async (request, pathname) => respond(request, makeBody(await page({
2087
+ title: "Not found",
2088
+ content: renderStatus(404, "Not found", `There is no file at ${pathname}.`),
2089
+ crumbs: crumbsFor(pathname, rootName),
2090
+ config: config(pathname, "status")
2091
+ }), HTML), { status: 404 });
2092
+ const failure = async (request, pathname, error, source = pathname) => respond(request, makeBody(await page({
2093
+ title: "Render error",
2094
+ content: renderStatus(500, "Render error", `comarkserv could not render ${pathname}.`, errorText(error)),
2095
+ crumbs: crumbsFor(pathname, rootName),
2096
+ config: config(source, "markdown")
2097
+ }), HTML), { status: 500 });
2098
+ const markdownPage = async (request, pathname, path, info, source) => {
2099
+ const stamp = `${info.mtimeMs}:${info.size}:${themes.version()}`;
2100
+ const cached = pages.get(pathname);
2101
+ if (cached?.stamp === stamp) return respond(request, cached.body, { headers: { "server-timing": timing(cached.ms, true) } });
2102
+ let timed;
2103
+ try {
2104
+ timed = await renderFile(path, info);
2105
+ } catch (error) {
2106
+ return failure(request, pathname, error, source);
2107
+ }
2108
+ const { rendered, ms } = timed;
2109
+ const body = makeBody(await page({
2110
+ title: rendered.title ?? basename(path),
2111
+ description: rendered.description,
2112
+ content: rendered.html,
2113
+ toc: rendered.toc,
2114
+ crumbs: crumbsFor(pathname, rootName),
2115
+ features: rendered.features,
2116
+ rawHref: `${encodeURI(source)}?raw`,
2117
+ footer: `rendered in ${ms.toFixed(1)} ms`,
2118
+ config: config(source, "markdown", timed.lines)
2119
+ }), HTML);
2120
+ pages.set(pathname, {
2121
+ stamp,
2122
+ body,
2123
+ ms
2124
+ });
2125
+ return respond(request, body, { headers: { "server-timing": timing(ms, false) } });
2126
+ };
2127
+ const directoryPage = async (request, pathname, path) => {
2128
+ const started = performance.now();
2129
+ const directory = await readDirectory(path, {
2130
+ dotfiles,
2131
+ links: serverLinks
2132
+ });
2133
+ const names = new Set(directory.entries.map((entry) => entry.name));
2134
+ if (names.has("index.html")) return serveStatic(request, () => notFound(request, pathname));
2135
+ if (names.has("index.md")) {
2136
+ const index = join(path, "index.md");
2137
+ return markdownPage(request, pathname, index, await stat$1(index), `${pathname}index.md`);
2138
+ }
2139
+ let content = renderListing(directory.entries, pathname === "/" ? void 0 : "../");
2140
+ let readme;
2141
+ if (directory.readme) {
2142
+ const readmePath = join(path, directory.readme);
2143
+ try {
2144
+ readme = (await renderFile(readmePath, await stat$1(readmePath))).rendered;
2145
+ content += renderReadme(directory.readme, readme.html);
2146
+ } catch (error) {
2147
+ content += renderStatus(500, "Render error", `comarkserv could not render ${directory.readme}.`, errorText(error));
2148
+ }
2149
+ }
2150
+ const ms = performance.now() - started;
2151
+ const count = directory.entries.length;
2152
+ return respond(request, makeBody(await page({
2153
+ title: pathname === "/" ? rootName : pathname.slice(1),
2154
+ content,
2155
+ contentClass: "cms-directory",
2156
+ toc: readme?.toc,
2157
+ crumbs: crumbsFor(pathname, rootName),
2158
+ features: readme?.features,
2159
+ footer: `${count} ${count === 1 ? "item" : "items"} · rendered in ${ms.toFixed(1)} ms`,
2160
+ config: config(pathname, "directory")
2161
+ }), HTML), { headers: { "server-timing": timing(ms, false) } });
2162
+ };
2163
+ const events = (request) => {
2164
+ if (!watcher) return new Response("Live reload is off", { status: 404 });
2165
+ const encoder = new TextEncoder();
2166
+ let close = () => {};
2167
+ const stream = new ReadableStream({
2168
+ start(controller) {
2169
+ const send = (text) => {
2170
+ try {
2171
+ controller.enqueue(encoder.encode(text));
2172
+ } catch {
2173
+ close();
2174
+ }
2175
+ };
2176
+ const unsubscribe = watcher.subscribe((paths) => {
2177
+ send(`event: change\ndata: ${JSON.stringify({ paths })}\n\n`);
2178
+ });
2179
+ const unsubscribeTheme = themes.subscribe((theme) => {
2180
+ send(`event: theme\ndata: ${JSON.stringify({ theme })}\n\n`);
2181
+ });
2182
+ const unsubscribeShare = shareService?.subscribe((status) => {
2183
+ send(`event: share\ndata: ${JSON.stringify(status)}\n\n`);
2184
+ });
2185
+ const ping = setInterval(() => send(": ping\n\n"), 25e3);
2186
+ close = () => {
2187
+ clearInterval(ping);
2188
+ unsubscribe();
2189
+ unsubscribeTheme();
2190
+ unsubscribeShare?.();
2191
+ streams.delete(close);
2192
+ try {
2193
+ controller.close();
2194
+ } catch {}
2195
+ };
2196
+ streams.add(close);
2197
+ request.signal.addEventListener("abort", () => close(), { once: true });
2198
+ send(`retry: 1000\nevent: hello\ndata: ${JSON.stringify({ id: serverId })}\n\n`);
2199
+ },
2200
+ cancel() {
2201
+ close();
2202
+ }
2203
+ });
2204
+ return new Response(stream, { headers: {
2205
+ "content-type": "text/event-stream",
2206
+ "cache-control": "no-cache",
2207
+ "x-accel-buffering": "no"
2208
+ } });
2209
+ };
2210
+ const edit = async (request) => {
2211
+ if (!editor) return new Response("Not found", { status: 404 });
2212
+ if (request.method !== "POST") return new Response("Method not allowed", {
2213
+ status: 405,
2214
+ headers: { allow: "POST" }
2215
+ });
2216
+ if (!isLocalAction(request)) return new Response("Forbidden", { status: 403 });
2217
+ const body = await request.json().catch(() => ({}));
2218
+ const pathname = typeof body.path === "string" ? body.path : "";
2219
+ const visible = pathname.startsWith("/") && !pathname.includes("\0") && (dotfiles || !hasHiddenSegment(pathname));
2220
+ const path = resolve(root, `.${pathname}`);
2221
+ const inside = path === root || path.startsWith(root + sep);
2222
+ if (!(visible && inside ? await stat$1(path).catch(() => void 0) : void 0)?.isFile()) return new Response("Not found", { status: 404 });
2223
+ const line = typeof body.line === "number" && Number.isInteger(body.line) && body.line > 0 ? body.line : void 0;
2224
+ try {
2225
+ await openEditor(path, line);
2226
+ } catch (error) {
2227
+ const message = error instanceof Error ? error.message : String(error);
2228
+ return Response.json({ error: message }, { status: 500 });
2229
+ }
2230
+ return new Response(null, { status: 204 });
2231
+ };
2232
+ const localCheck = (request) => {
2233
+ if (!isLocalRequest(request)) return new Response("Forbidden", { status: 403 });
2234
+ return Response.json({
2235
+ edit: editor,
2236
+ share: shareService ? shareService.status() : null
2237
+ }, { headers: { "cache-control": "no-store" } });
2238
+ };
2239
+ const shareState = async (path, status = 200) => {
2240
+ const current = shareService?.status();
2241
+ let extra = {};
2242
+ if (current?.url) {
2243
+ const page = typeof path === "string" && path.startsWith("/") && !path.startsWith("//") ? new URL(path, current.url).href : current.url;
2244
+ extra = {
2245
+ page,
2246
+ qr: await qrCode(page)
2247
+ };
2248
+ }
2249
+ return Response.json({
2250
+ ...current,
2251
+ links: CLOUDFLARE_LINKS,
2252
+ ...extra
2253
+ }, { status });
2254
+ };
2255
+ const shareAction = async (request) => {
2256
+ if (!shareService) return new Response("Not found", { status: 404 });
2257
+ if (request.method !== "POST") return new Response("Method not allowed", {
2258
+ status: 405,
2259
+ headers: { allow: "POST" }
2260
+ });
2261
+ if (!isLocalAction(request)) return new Response("Forbidden", { status: 403 });
2262
+ const body = await request.json().catch(() => ({}));
2263
+ if (body.action === "stop") await shareService.stop();
2264
+ else if (body.action === "start") try {
2265
+ await shareService.start({
2266
+ origin: new URL(request.url).origin,
2267
+ accept: body.accept === true
2268
+ });
2269
+ } catch (error) {
2270
+ return shareState(body.path, error instanceof ShareConsentError ? 409 : 500);
2271
+ }
2272
+ return shareState(body.path);
2273
+ };
2274
+ const internal = async (request, name) => {
2275
+ if (name === "local") return localCheck(request);
2276
+ if (name === "app.css" || name === "app.js") return respond(request, assetBodies[name], { headers: { "cache-control": IMMUTABLE } });
2277
+ if (name === "search.json") return Response.json(await search.get(), { headers: { "cache-control": "no-cache" } });
2278
+ if (name === "events") return events(request);
2279
+ if (name.startsWith("themes/")) return themes.handle(request, name.slice(7));
2280
+ if (name.startsWith("katex/")) {
2281
+ const url = new URL(request.url);
2282
+ url.pathname = `/${name.slice(6)}`;
2283
+ return serveKatex(new Request(url, request), () => new Response("Not found", { status: 404 }));
2284
+ }
2285
+ return new Response("Not found", { status: 404 });
2286
+ };
2287
+ const handle = async (request) => {
2288
+ const requested = new URL(request.url).pathname;
2289
+ if (requested === `/__comarkserv/edit`) return edit(request);
2290
+ if (requested === `/__comarkserv/share`) return shareAction(request);
2291
+ if (request.method !== "GET" && request.method !== "HEAD") return new Response("Method not allowed", {
2292
+ status: 405,
2293
+ headers: { allow: "GET, HEAD" }
2294
+ });
2295
+ const url = new URL(request.url);
2296
+ let pathname;
2297
+ try {
2298
+ pathname = decodeURIComponent(url.pathname);
2299
+ } catch {
2300
+ return new Response("Bad request", { status: 400 });
2301
+ }
2302
+ if (pathname.startsWith("/__comarkserv/")) return internal(request, pathname.slice(14));
2303
+ if (pathname.includes("\0") || !dotfiles && hasHiddenSegment(pathname)) return notFound(request, pathname);
2304
+ const path = resolve(root, `.${pathname}`);
2305
+ if (path !== root && !path.startsWith(root + sep)) return notFound(request, pathname);
2306
+ const info = await stat$1(path).catch(() => void 0);
2307
+ if (!info) return notFound(request, pathname);
2308
+ if (info.isDirectory()) {
2309
+ if (!pathname.endsWith("/")) return new Response(null, {
2310
+ status: 301,
2311
+ headers: { location: `${url.pathname}/${url.search}` }
2312
+ });
2313
+ return directoryPage(request, pathname, path);
2314
+ }
2315
+ if (!info.isFile()) return notFound(request, pathname);
2316
+ if (isMarkdown(path)) {
2317
+ if (url.searchParams.has("raw")) return respond(request, makeBody(await readFile(path, "utf8"), "text/plain; charset=utf-8"));
2318
+ return markdownPage(request, pathname, path, info, pathname);
2319
+ }
2320
+ return serveStatic(request, () => notFound(request, pathname));
2321
+ };
2322
+ return {
2323
+ root,
2324
+ share: shareService,
2325
+ warmup: async () => {
2326
+ await Promise.all([getRenderer(), themes.current()]);
2327
+ },
2328
+ fetch: async (request) => {
2329
+ try {
2330
+ return await handle(request);
2331
+ } catch (error) {
2332
+ const pathname = new URL(request.url).pathname;
2333
+ return failure(request, pathname, error);
2334
+ }
2335
+ },
2336
+ close: async () => {
2337
+ await Promise.all([
2338
+ watcher?.close(),
2339
+ themes.close(),
2340
+ shareService?.stop()
2341
+ ]);
2342
+ for (const close of streams) close();
2343
+ }
2344
+ };
2345
+ }
2346
+ //#endregion
2347
+ //#region node_modules/.pnpm/get-port-please@3.2.0/node_modules/get-port-please/dist/index.mjs
2348
+ const unsafePorts = /* @__PURE__ */ new Set([
2349
+ 1,
2350
+ 7,
2351
+ 9,
2352
+ 11,
2353
+ 13,
2354
+ 15,
2355
+ 17,
2356
+ 19,
2357
+ 20,
2358
+ 21,
2359
+ 22,
2360
+ 23,
2361
+ 25,
2362
+ 37,
2363
+ 42,
2364
+ 43,
2365
+ 53,
2366
+ 69,
2367
+ 77,
2368
+ 79,
2369
+ 87,
2370
+ 95,
2371
+ 101,
2372
+ 102,
2373
+ 103,
2374
+ 104,
2375
+ 109,
2376
+ 110,
2377
+ 111,
2378
+ 113,
2379
+ 115,
2380
+ 117,
2381
+ 119,
2382
+ 123,
2383
+ 135,
2384
+ 137,
2385
+ 139,
2386
+ 143,
2387
+ 161,
2388
+ 179,
2389
+ 389,
2390
+ 427,
2391
+ 465,
2392
+ 512,
2393
+ 513,
2394
+ 514,
2395
+ 515,
2396
+ 526,
2397
+ 530,
2398
+ 531,
2399
+ 532,
2400
+ 540,
2401
+ 548,
2402
+ 554,
2403
+ 556,
2404
+ 563,
2405
+ 587,
2406
+ 601,
2407
+ 636,
2408
+ 989,
2409
+ 990,
2410
+ 993,
2411
+ 995,
2412
+ 1719,
2413
+ 1720,
2414
+ 1723,
2415
+ 2049,
2416
+ 3659,
2417
+ 4045,
2418
+ 5060,
2419
+ 5061,
2420
+ 6e3,
2421
+ 6566,
2422
+ 6665,
2423
+ 6666,
2424
+ 6667,
2425
+ 6668,
2426
+ 6669,
2427
+ 6697,
2428
+ 10080
2429
+ ]);
2430
+ function isUnsafePort(port) {
2431
+ return unsafePorts.has(port);
2432
+ }
2433
+ function isSafePort(port) {
2434
+ return !isUnsafePort(port);
2435
+ }
2436
+ var GetPortError = class extends Error {
2437
+ constructor(message, opts) {
2438
+ super(message, opts);
2439
+ this.message = message;
2440
+ }
2441
+ name = "GetPortError";
2442
+ };
2443
+ function _log(verbose, message) {
2444
+ if (verbose) console.log(`[get-port] ${message}`);
2445
+ }
2446
+ function _generateRange(from, to) {
2447
+ if (to < from) return [];
2448
+ const r = [];
2449
+ for (let index = from; index <= to; index++) r.push(index);
2450
+ return r;
2451
+ }
2452
+ function _tryPort(port, host) {
2453
+ return new Promise((resolve) => {
2454
+ const server = createServer();
2455
+ server.unref();
2456
+ server.on("error", () => {
2457
+ resolve(false);
2458
+ });
2459
+ server.listen({
2460
+ port,
2461
+ host
2462
+ }, () => {
2463
+ const { port: port2 } = server.address();
2464
+ server.close(() => {
2465
+ resolve(isSafePort(port2) && port2);
2466
+ });
2467
+ });
2468
+ });
2469
+ }
2470
+ function _getLocalHosts(additional) {
2471
+ const hosts = new Set(additional);
2472
+ for (const _interface of Object.values(networkInterfaces())) for (const config of _interface || []) if (config.address && !config.internal && !config.address.startsWith("fe80::") && !config.address.startsWith("169.254")) hosts.add(config.address);
2473
+ return [...hosts];
2474
+ }
2475
+ async function _findPort(ports, host) {
2476
+ for (const port of ports) {
2477
+ const r = await _tryPort(port, host);
2478
+ if (r) return r;
2479
+ }
2480
+ }
2481
+ function _fmtOnHost(hostname) {
2482
+ return hostname ? `on host ${JSON.stringify(hostname)}` : "on any host";
2483
+ }
2484
+ const HOSTNAME_RE = /^(?!-)[\d.:A-Za-z-]{1,63}(?<!-)$/;
2485
+ function _validateHostname(hostname, _public, verbose) {
2486
+ if (hostname && !HOSTNAME_RE.test(hostname)) {
2487
+ const fallbackHost = _public ? "0.0.0.0" : "127.0.0.1";
2488
+ _log(verbose, `Invalid hostname: ${JSON.stringify(hostname)}. Using ${JSON.stringify(fallbackHost)} as fallback.`);
2489
+ return fallbackHost;
2490
+ }
2491
+ return hostname;
2492
+ }
2493
+ async function getPort(_userOptions = {}) {
2494
+ if (typeof _userOptions === "number" || typeof _userOptions === "string") _userOptions = { port: Number.parseInt(_userOptions + "") || 0 };
2495
+ const _port = Number(_userOptions.port ?? process.env.PORT);
2496
+ const _userSpecifiedAnyPort = Boolean(_userOptions.port || _userOptions.ports?.length || _userOptions.portRange?.length);
2497
+ const options = {
2498
+ random: _port === 0,
2499
+ ports: [],
2500
+ portRange: [],
2501
+ alternativePortRange: _userSpecifiedAnyPort ? [] : [3e3, 3100],
2502
+ verbose: false,
2503
+ ..._userOptions,
2504
+ port: _port,
2505
+ host: _validateHostname(_userOptions.host ?? process.env.HOST, _userOptions.public, _userOptions.verbose)
2506
+ };
2507
+ if (options.random && !_userSpecifiedAnyPort) return getRandomPort(options.host);
2508
+ const portsToCheck = [
2509
+ options.port,
2510
+ ...options.ports,
2511
+ ..._generateRange(...options.portRange)
2512
+ ].filter((port) => {
2513
+ if (!port) return false;
2514
+ if (!isSafePort(port)) {
2515
+ _log(options.verbose, `Ignoring unsafe port: ${port}`);
2516
+ return false;
2517
+ }
2518
+ return true;
2519
+ });
2520
+ if (portsToCheck.length === 0) portsToCheck.push(3e3);
2521
+ let availablePort = await _findPort(portsToCheck, options.host);
2522
+ if (!availablePort && options.alternativePortRange.length > 0) {
2523
+ availablePort = await _findPort(_generateRange(...options.alternativePortRange), options.host);
2524
+ if (portsToCheck.length > 0) {
2525
+ let message = `Unable to find an available port (tried ${portsToCheck.join("-")} ${_fmtOnHost(options.host)}).`;
2526
+ if (availablePort) message += ` Using alternative port ${availablePort}.`;
2527
+ _log(options.verbose, message);
2528
+ }
2529
+ }
2530
+ if (!availablePort && _userOptions.random !== false) {
2531
+ availablePort = await getRandomPort(options.host);
2532
+ if (availablePort) _log(options.verbose, `Using random port ${availablePort}`);
2533
+ }
2534
+ if (!availablePort) {
2535
+ const triedRanges = [
2536
+ options.port,
2537
+ options.portRange.join("-"),
2538
+ options.alternativePortRange.join("-")
2539
+ ].filter(Boolean).join(", ");
2540
+ throw new GetPortError(`Unable to find an available port ${_fmtOnHost(options.host)} (tried ${triedRanges})`);
2541
+ }
2542
+ return availablePort;
2543
+ }
2544
+ async function getRandomPort(host) {
2545
+ const port = await checkPort(0, host);
2546
+ if (port === false) throw new GetPortError(`Unable to find a random port ${_fmtOnHost(host)}`);
2547
+ return port;
2548
+ }
2549
+ async function checkPort(port, host = process.env.HOST, verbose) {
2550
+ if (!host) host = _getLocalHosts([void 0, "0.0.0.0"]);
2551
+ if (!Array.isArray(host)) return _tryPort(port, host);
2552
+ for (const _host of host) {
2553
+ const _port = await _tryPort(port, _host);
2554
+ if (_port === false) {
2555
+ if (port < 1024 && verbose) _log(verbose, `Unable to listen to the privileged port ${port} ${_fmtOnHost(_host)}`);
2556
+ return false;
2557
+ }
2558
+ if (port === 0 && _port !== 0) port = _port;
2559
+ }
2560
+ return port;
2561
+ }
2562
+ //#endregion
2563
+ //#region src/server.ts
2564
+ const DEFAULT_PORT = 8642;
2565
+ /** Returns the first free port from `start`. With `strict`, it rejects when `start` is in use. */
2566
+ async function findPort(start, host, strict) {
2567
+ if (start === 0) return 0;
2568
+ if (!strict) return getPort({
2569
+ port: start,
2570
+ portRange: [start, start + 20],
2571
+ alternativePortRange: [start + 21, start + 100],
2572
+ host
2573
+ });
2574
+ if (await checkPort(start, host)) return start;
2575
+ throw new Error(`Port ${start} is in use. Choose another port, or remove --strict-port.`);
2576
+ }
2577
+ function statusColor(status) {
2578
+ if (status >= 500) return "red";
2579
+ if (status >= 400) return "yellow";
2580
+ if (status >= 300) return "cyan";
2581
+ return "green";
2582
+ }
2583
+ const logger = async (request, next) => {
2584
+ const started = performance.now();
2585
+ const response = await next();
2586
+ const { pathname, search } = new URL(request.url);
2587
+ if (!pathname.startsWith("/__comarkserv/")) {
2588
+ const time = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB");
2589
+ const ms = (performance.now() - started).toFixed(1);
2590
+ console.log(`${styleText("dim", time)} ${styleText(statusColor(response.status), String(response.status))} ${request.method} ${decodeURIComponent(pathname)}${search} ${styleText("dim", `${ms} ms`)}`);
2591
+ }
2592
+ return response;
2593
+ };
2594
+ /** Starts a comarkserv server with srvx. */
2595
+ async function startServer(options = {}) {
2596
+ const host = options.host ?? "localhost";
2597
+ const port = await findPort(options.port ?? 8642, host, options.strictPort ?? false);
2598
+ const handler = createHandler(options);
2599
+ const server = serve({
2600
+ fetch: handler.fetch,
2601
+ port,
2602
+ hostname: host,
2603
+ silent: true,
2604
+ gracefulShutdown: false,
2605
+ middleware: options.log ? [logger] : []
2606
+ });
2607
+ try {
2608
+ await server.ready();
2609
+ } catch (error) {
2610
+ await handler.close();
2611
+ throw error;
2612
+ }
2613
+ setImmediate(() => void handler.warmup());
2614
+ const url = new URL(server.url ?? `http://${host}:${port}/`);
2615
+ if (host === "localhost" || url.hostname === "0.0.0.0" || url.hostname === "[::]") url.hostname = "localhost";
2616
+ return {
2617
+ url: url.href,
2618
+ port: Number(url.port) || port,
2619
+ host,
2620
+ handler,
2621
+ close: async () => {
2622
+ await handler.close();
2623
+ await server.close(true);
2624
+ }
2625
+ };
2626
+ }
2627
+ //#endregion
2628
+ export { createHandler as a, INTERNAL_PREFIX as i, findPort as n, CLOUDFLARE_LINKS as o, startServer as r, isCloudflaredInstalled as s, DEFAULT_PORT as t };