codelight.js 0.0.0-stage → 1.0.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.
@@ -0,0 +1,723 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }/*! codelight.js 1.0.0 | MIT License | https://github.com/codelightjs/codelight.js */
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+
6
+ // src/lib/engine.ts
7
+ var LineBuilder = class {
8
+ constructor() {
9
+ __publicField(this, "tokens", []);
10
+ }
11
+ add(type, text) {
12
+ if (!text) return;
13
+ const last = this.tokens[this.tokens.length - 1];
14
+ if (last && last.type === type) last.text += text;
15
+ else this.tokens.push(type ? { type, text } : { text });
16
+ }
17
+ };
18
+ var words = (list, ci) => new Set((_nullishCoalesce(list, () => ( ""))).split(/\s+/).filter(Boolean).map((w) => ci ? w.toLowerCase() : w));
19
+ var sticky = (re) => new RegExp(re.source, re.flags.replace(/[gy]/g, "") + "y");
20
+ var NUMBER = /(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*(?:\.\d[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?)\w*/y;
21
+ var IDENT = /[A-Za-z_$][\w$]*/;
22
+ var SPACE = /\s+/y;
23
+ var OPERATOR = /[+\-*/%=<>!&|^~?:]+/y;
24
+ var CALL = /\s*\(/y;
25
+ var PUNCTUATION = "()[]{},;.";
26
+ function findClose(line, from, close, escape) {
27
+ for (let j = from; j < line.length; j++) {
28
+ if (escape && line[j] === "\\") {
29
+ j++;
30
+ continue;
31
+ }
32
+ if (line.startsWith(close, j)) return j + close.length;
33
+ }
34
+ return -1;
35
+ }
36
+ function defineLanguage(def) {
37
+ const ci = _nullishCoalesce(def.caseInsensitive, () => ( false));
38
+ const keywords = words(def.keywords, ci);
39
+ const constants = words(def.constants, ci);
40
+ const types = words(def.types, ci);
41
+ const variables = words(def.variables, ci);
42
+ const builtins = words(def.builtins, ci);
43
+ const rules = (_nullishCoalesce(def.rules, () => ( []))).map((r) => ({ match: sticky(r.match), type: r.type }));
44
+ const strings = [..._nullishCoalesce(def.strings, () => ( []))].sort((a, b) => b.open.length - a.open.length);
45
+ const ident = sticky(_nullishCoalesce(def.identifier, () => ( IDENT)));
46
+ const calls = _nullishCoalesce(def.calls, () => ( true));
47
+ function classify(word, line, end) {
48
+ const k = ci ? word.toLowerCase() : word;
49
+ if (keywords.has(k)) return "keyword";
50
+ if (constants.has(k)) return "constant";
51
+ if (types.has(k)) return "type";
52
+ if (variables.has(k)) return "variable";
53
+ if (builtins.has(k)) return "function";
54
+ if (calls) {
55
+ CALL.lastIndex = end;
56
+ if (CALL.test(line)) return "function";
57
+ }
58
+ if (def.classNames && /^[A-Z]/.test(word) && /[a-z]/.test(word)) return "type";
59
+ return void 0;
60
+ }
61
+ return {
62
+ tokenizeLine(line, state) {
63
+ const out = new LineBuilder();
64
+ let open = state;
65
+ let i = 0;
66
+ if (open) {
67
+ const end = findClose(line, 0, open.close, open.escape);
68
+ if (end < 0) {
69
+ out.add(open.type, line);
70
+ return { tokens: out.tokens, state: open };
71
+ }
72
+ out.add(open.type, line.slice(0, end));
73
+ i = end;
74
+ open = null;
75
+ }
76
+ scan: while (i < line.length) {
77
+ for (const r of rules) {
78
+ r.match.lastIndex = i;
79
+ const m2 = r.match.exec(line);
80
+ if (m2 && m2[0]) {
81
+ out.add(r.type, m2[0]);
82
+ i += m2[0].length;
83
+ continue scan;
84
+ }
85
+ }
86
+ for (const [o, c] of _nullishCoalesce(def.blockComment, () => ( []))) {
87
+ if (!line.startsWith(o, i)) continue;
88
+ const end = line.indexOf(c, i + o.length);
89
+ if (end < 0) {
90
+ out.add("comment", line.slice(i));
91
+ open = { close: c, type: "comment", escape: false };
92
+ break scan;
93
+ }
94
+ out.add("comment", line.slice(i, end + c.length));
95
+ i = end + c.length;
96
+ continue scan;
97
+ }
98
+ for (const p of _nullishCoalesce(def.lineComment, () => ( []))) {
99
+ if (line.startsWith(p, i)) {
100
+ out.add("comment", line.slice(i));
101
+ break scan;
102
+ }
103
+ }
104
+ for (const s of strings) {
105
+ if (!line.startsWith(s.open, i)) continue;
106
+ const type = _nullishCoalesce(s.type, () => ( "string"));
107
+ const close = _nullishCoalesce(s.close, () => ( s.open));
108
+ const escape = _nullishCoalesce(s.escape, () => ( true));
109
+ const end = findClose(line, i + s.open.length, close, escape);
110
+ if (end < 0) {
111
+ out.add(type, line.slice(i));
112
+ if (s.multiline) open = { close, type, escape };
113
+ break scan;
114
+ }
115
+ out.add(type, line.slice(i, end));
116
+ i = end;
117
+ continue scan;
118
+ }
119
+ let m;
120
+ NUMBER.lastIndex = i;
121
+ if (m = NUMBER.exec(line)) {
122
+ out.add("number", m[0]);
123
+ i += m[0].length;
124
+ continue;
125
+ }
126
+ ident.lastIndex = i;
127
+ if ((m = ident.exec(line)) && m[0]) {
128
+ out.add(classify(m[0], line, i + m[0].length), m[0]);
129
+ i += m[0].length;
130
+ continue;
131
+ }
132
+ SPACE.lastIndex = i;
133
+ if (m = SPACE.exec(line)) {
134
+ out.add(void 0, m[0]);
135
+ i += m[0].length;
136
+ continue;
137
+ }
138
+ OPERATOR.lastIndex = i;
139
+ if (m = OPERATOR.exec(line)) {
140
+ out.add("operator", m[0]);
141
+ i += m[0].length;
142
+ continue;
143
+ }
144
+ const ch = line[i];
145
+ out.add(PUNCTUATION.includes(ch) ? "punctuation" : void 0, ch);
146
+ i++;
147
+ }
148
+ return { tokens: out.tokens, state: open };
149
+ }
150
+ };
151
+ }
152
+ var plain = {
153
+ tokenizeLine: (line) => ({ tokens: line ? [{ text: line }] : [], state: null })
154
+ };
155
+
156
+ // src/lib/markup.ts
157
+ var TAG_OPEN = /<(\/?)([A-Za-z][\w:.-]*)/y;
158
+ var ENTITY = /&(?:#\d+|#[xX][\da-fA-F]+|\w+);/y;
159
+ var TEXT = /[^<&]+/y;
160
+ var ATTR = /[^\s=/>"']+/y;
161
+ var UNQUOTED = /[^\s>"']+/y;
162
+ var SPACE2 = /\s+/y;
163
+ var at = (re, line, i) => {
164
+ re.lastIndex = i;
165
+ return re.exec(line);
166
+ };
167
+ function createMarkup(embeds = {}) {
168
+ return {
169
+ tokenizeLine(line, state) {
170
+ const out = new LineBuilder();
171
+ let s = state;
172
+ let i = 0;
173
+ let m;
174
+ while (i < line.length) {
175
+ if (!s) {
176
+ if (line.startsWith("<!--", i)) {
177
+ const end = line.indexOf("-->", i + 4);
178
+ if (end < 0) {
179
+ out.add("comment", line.slice(i));
180
+ s = { m: "comment" };
181
+ break;
182
+ }
183
+ out.add("comment", line.slice(i, end + 3));
184
+ i = end + 3;
185
+ } else if (line.startsWith("<!", i) || line.startsWith("<?", i)) {
186
+ const end = line.indexOf(">", i);
187
+ if (end < 0) {
188
+ out.add("meta", line.slice(i));
189
+ s = { m: "meta" };
190
+ break;
191
+ }
192
+ out.add("meta", line.slice(i, end + 1));
193
+ i = end + 1;
194
+ } else if (m = at(TAG_OPEN, line, i)) {
195
+ out.add("punctuation", m[1] ? "</" : "<");
196
+ out.add("tag", m[2]);
197
+ s = { m: "tag", name: m[2].toLowerCase(), closing: !!m[1] };
198
+ i += m[0].length;
199
+ } else if (m = at(ENTITY, line, i)) {
200
+ out.add("constant", m[0]);
201
+ i += m[0].length;
202
+ } else if (m = at(TEXT, line, i)) {
203
+ out.add(void 0, m[0]);
204
+ i += m[0].length;
205
+ } else {
206
+ out.add(void 0, line[i]);
207
+ i++;
208
+ }
209
+ continue;
210
+ }
211
+ if (s.m === "comment" || s.m === "meta") {
212
+ const close = s.m === "comment" ? "-->" : ">";
213
+ const type = s.m === "comment" ? "comment" : "meta";
214
+ const end = line.indexOf(close, i);
215
+ if (end < 0) {
216
+ out.add(type, line.slice(i));
217
+ break;
218
+ }
219
+ out.add(type, line.slice(i, end + close.length));
220
+ i = end + close.length;
221
+ s = null;
222
+ continue;
223
+ }
224
+ if (s.m === "embed") {
225
+ const end = line.toLowerCase().indexOf(s.end, i);
226
+ const part = end < 0 ? line.slice(i) : line.slice(i, end);
227
+ const r = s.lang.tokenizeLine(part, s.inner);
228
+ for (const t of r.tokens) out.add(t.type, t.text);
229
+ if (end < 0) {
230
+ s = { ...s, inner: r.state };
231
+ break;
232
+ }
233
+ s = null;
234
+ i = end;
235
+ continue;
236
+ }
237
+ if (s.quote) {
238
+ const end = line.indexOf(s.quote, i);
239
+ if (end < 0) {
240
+ out.add("string", line.slice(i));
241
+ break;
242
+ }
243
+ out.add("string", line.slice(i, end + 1));
244
+ i = end + 1;
245
+ s = { ...s, quote: void 0, eq: false };
246
+ } else if (m = at(SPACE2, line, i)) {
247
+ out.add(void 0, m[0]);
248
+ i += m[0].length;
249
+ } else if (line.startsWith("/>", i) || line[i] === ">") {
250
+ const end = line[i] === ">" ? 1 : 2;
251
+ out.add("punctuation", line.slice(i, i + end));
252
+ i += end;
253
+ const lang = end === 1 && !s.closing ? embeds[s.name] : void 0;
254
+ s = lang ? { m: "embed", end: `</${s.name}`, lang, inner: null } : null;
255
+ } else if (line[i] === "=") {
256
+ out.add("operator", "=");
257
+ i++;
258
+ s = { ...s, eq: true };
259
+ } else if (line[i] === '"' || line[i] === "'") {
260
+ const q = line[i];
261
+ const end = line.indexOf(q, i + 1);
262
+ if (end < 0) {
263
+ out.add("string", line.slice(i));
264
+ s = { ...s, quote: q };
265
+ break;
266
+ }
267
+ out.add("string", line.slice(i, end + 1));
268
+ i = end + 1;
269
+ s = { ...s, eq: false };
270
+ } else if (s.eq && (m = at(UNQUOTED, line, i))) {
271
+ out.add("string", m[0]);
272
+ i += m[0].length;
273
+ s = { ...s, eq: false };
274
+ } else if (m = at(ATTR, line, i)) {
275
+ out.add("attr", m[0]);
276
+ i += m[0].length;
277
+ } else {
278
+ out.add(void 0, line[i]);
279
+ i++;
280
+ }
281
+ }
282
+ return { tokens: out.tokens, state: s };
283
+ }
284
+ };
285
+ }
286
+
287
+ // src/languages/bash.ts
288
+ var bash_default = defineLanguage({
289
+ strings: [{ open: '"', multiline: true }, { open: "'", escape: false, multiline: true }],
290
+ keywords: "if then else elif fi for while until do done case esac in function select return exit break continue local export readonly declare unset source alias time",
291
+ builtins: "echo cd printf read set shift test eval exec trap pwd ls cat grep sed awk find mkdir rm cp mv chmod chown touch curl wget tar sudo git npm npx pnpm yarn bun node deno python python3 pip pip3 docker kubectl ssh make brew apt apt-get",
292
+ rules: [
293
+ { match: /(?<=^|\s)#.*/, type: "comment" },
294
+ { match: /\$(?:\{[^}]*\}|[A-Za-z_]\w*|[\d@#?$!*-])/, type: "variable" },
295
+ { match: /(?<=^\s*(?:(?:export|local|declare|readonly)\s+)?)[A-Za-z_]\w*(?==)/, type: "variable" },
296
+ { match: /(?<=\s)--?[A-Za-z][\w-]*/, type: "attr" }
297
+ ],
298
+ identifier: /[A-Za-z_][\w-]*/,
299
+ calls: false
300
+ });
301
+
302
+ // src/languages/_common.ts
303
+ var C_COMMENTS = { lineComment: ["//"], blockComment: [["/*", "*/"]] };
304
+ var QUOTES = [{ open: '"' }, { open: "'" }];
305
+
306
+ // src/languages/c.ts
307
+ var C_KEYWORDS = "auto break case const continue default do else enum extern for goto if inline register restrict return sizeof static struct switch typedef union volatile while";
308
+ var C_TYPES = "char double float int long short signed unsigned void bool size_t ssize_t int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t FILE";
309
+ var PREPROCESSOR = [
310
+ { match: /(?<=^\s*#\s*include\s*)<[^>]*>/, type: "string" },
311
+ { match: /(?<=^\s*)#\s*[A-Za-z]+/, type: "meta" }
312
+ ];
313
+ var c_default = defineLanguage({
314
+ ...C_COMMENTS,
315
+ strings: QUOTES,
316
+ keywords: C_KEYWORDS,
317
+ types: C_TYPES,
318
+ constants: "NULL true false",
319
+ rules: PREPROCESSOR
320
+ });
321
+
322
+ // src/languages/cpp.ts
323
+ var cpp_default = defineLanguage({
324
+ ...C_COMMENTS,
325
+ strings: QUOTES,
326
+ keywords: C_KEYWORDS + " class namespace template typename public private protected virtual override final new delete this try catch throw using operator friend explicit constexpr consteval noexcept auto decltype static_cast dynamic_cast reinterpret_cast const_cast co_await co_return co_yield concept requires mutable",
327
+ types: C_TYPES + " string vector map unordered_map set array unique_ptr shared_ptr optional",
328
+ constants: "nullptr NULL true false",
329
+ rules: PREPROCESSOR,
330
+ classNames: true
331
+ });
332
+
333
+ // src/languages/csharp.ts
334
+ var csharp_default = defineLanguage({
335
+ ...C_COMMENTS,
336
+ strings: [{ open: '@"', close: '"', escape: false, multiline: true }, { open: '$"', close: '"' }, ...QUOTES],
337
+ keywords: "abstract as base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in interface internal is lock namespace new operator out override params private protected public readonly ref return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual volatile while async await var record get set init yield where when",
338
+ types: "bool byte char decimal double float int long object sbyte short string uint ulong ushort void dynamic",
339
+ constants: "true false null",
340
+ classNames: true
341
+ });
342
+
343
+ // src/languages/css.ts
344
+ var css_default = defineLanguage({
345
+ blockComment: [["/*", "*/"]],
346
+ strings: QUOTES,
347
+ rules: [
348
+ { match: /@[\w-]+/, type: "keyword" },
349
+ { match: /#[\da-fA-F]{3,8}(?![\w-])/, type: "number" },
350
+ { match: /(?:--|-?[A-Za-z])[\w-]*(?=\s*:(?!:)[^{};]*(?:[;})]|$))/, type: "property" },
351
+ { match: /[.#][A-Za-z_-][\w-]*/, type: "type" },
352
+ { match: /::?[A-Za-z-]+/, type: "attr" },
353
+ { match: /!\s*important/, type: "keyword" }
354
+ ],
355
+ identifier: /-?[A-Za-z_][\w-]*/
356
+ });
357
+
358
+ // src/languages/diff.ts
359
+ var diff = {
360
+ tokenizeLine(line) {
361
+ if (!line) return { tokens: [], state: null };
362
+ const type = line.startsWith("+++") || line.startsWith("---") || line.startsWith("@@") || line.startsWith("diff ") || line.startsWith("index ") ? "meta" : line[0] === "+" ? "inserted" : line[0] === "-" ? "deleted" : void 0;
363
+ return { tokens: [type ? { type, text: line } : { text: line }], state: null };
364
+ }
365
+ };
366
+ var diff_default = diff;
367
+
368
+ // src/languages/go.ts
369
+ var go_default = defineLanguage({
370
+ ...C_COMMENTS,
371
+ strings: [{ open: '"' }, { open: "'" }, { open: "`", escape: false, multiline: true }],
372
+ keywords: "break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var",
373
+ constants: "true false nil iota",
374
+ types: "string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex64 complex128 bool byte rune error any",
375
+ builtins: "append cap close copy delete len make new panic print println recover"
376
+ });
377
+
378
+ // src/languages/java.ts
379
+ var java_default = defineLanguage({
380
+ ...C_COMMENTS,
381
+ strings: [{ open: '"""', multiline: true }, ...QUOTES],
382
+ keywords: "abstract assert break case catch class const continue default do else enum extends final finally for goto if implements import instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws transient try volatile while var record sealed permits yield",
383
+ types: "boolean byte char double float int long short void",
384
+ constants: "true false null",
385
+ rules: [{ match: /@[A-Za-z_]\w*/, type: "meta" }],
386
+ classNames: true
387
+ });
388
+
389
+ // src/languages/javascript.ts
390
+ var JS_KEYWORDS = "break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield async await of static get set from as";
391
+ var JS_CONSTANTS = "true false null undefined NaN Infinity";
392
+ var JSX_TAG = { match: /(?<=(?:^|[(=?:,&|{}[>;]|\breturn)\s*)<\/?[A-Za-z][\w.:-]*(?=[\s/>]|$)/, type: "tag" };
393
+ var DECORATOR = { match: /@[A-Za-z_$][\w$.]*/, type: "meta" };
394
+ var javascript_default = defineLanguage({
395
+ ...C_COMMENTS,
396
+ strings: [...QUOTES, { open: "`", multiline: true }],
397
+ keywords: JS_KEYWORDS,
398
+ constants: JS_CONSTANTS,
399
+ rules: [JSX_TAG, DECORATOR],
400
+ classNames: true
401
+ });
402
+
403
+ // src/languages/json.ts
404
+ var json_default = defineLanguage({
405
+ ...C_COMMENTS,
406
+ strings: [{ open: '"' }],
407
+ constants: "true false null",
408
+ rules: [{ match: /"(?:[^"\\]|\\.)*"(?=\s*:)/, type: "property" }],
409
+ calls: false
410
+ });
411
+
412
+ // src/languages/php.ts
413
+ var php_default = defineLanguage({
414
+ lineComment: ["//", "#"],
415
+ blockComment: [["/*", "*/"]],
416
+ strings: [{ open: '"', multiline: true }, { open: "'", multiline: true }],
417
+ keywords: "abstract and array as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum extends final finally fn for foreach function global goto if implements include include_once instanceof insteadof interface isset list match namespace new or print private protected public readonly require require_once return static switch throw trait try unset use var while xor yield",
418
+ constants: "true false null TRUE FALSE NULL",
419
+ types: "int float string bool void mixed never object iterable",
420
+ rules: [
421
+ { match: /<\?(?:php|=)?|\?>/, type: "meta" },
422
+ { match: /\$[A-Za-z_]\w*/, type: "variable" }
423
+ ],
424
+ classNames: true
425
+ });
426
+
427
+ // src/languages/python.ts
428
+ var python_default = defineLanguage({
429
+ lineComment: ["#"],
430
+ strings: [{ open: '"""', multiline: true }, { open: "'''", multiline: true }, ...QUOTES],
431
+ keywords: "and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield match case",
432
+ constants: "True False None",
433
+ variables: "self cls",
434
+ types: "int float str bool list dict set tuple bytes object Exception",
435
+ rules: [
436
+ { match: /(?<=^\s*)@[\w.]+/, type: "meta" },
437
+ { match: /[rRbBuUfF]{1,2}(?=["'])/, type: "string" }
438
+ ],
439
+ classNames: true
440
+ });
441
+
442
+ // src/languages/ruby.ts
443
+ var ruby_default = defineLanguage({
444
+ lineComment: ["#"],
445
+ strings: [{ open: '"', multiline: true }, { open: "'", multiline: true }],
446
+ keywords: "alias and begin break case class def defined? do else elsif end ensure for if in module next not or redo rescue retry return self super then undef unless until when while yield require require_relative include extend attr_accessor attr_reader attr_writer private protected public lambda proc",
447
+ builtins: "puts print p raise",
448
+ constants: "true false nil",
449
+ rules: [
450
+ { match: /@{1,2}[A-Za-z_]\w*|\$[A-Za-z_]\w*/, type: "variable" },
451
+ { match: /(?<![:\w]):[A-Za-z_]\w*[?!]?/, type: "constant" }
452
+ ],
453
+ identifier: /[A-Za-z_]\w*[?!]?/,
454
+ classNames: true
455
+ });
456
+
457
+ // src/languages/rust.ts
458
+ var rust_default = defineLanguage({
459
+ ...C_COMMENTS,
460
+ strings: [{ open: '"', multiline: true }, { open: "'" }],
461
+ keywords: "as async await break const continue crate dyn else enum extern fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait type unsafe use where while",
462
+ constants: "true false None",
463
+ types: "i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 bool char str",
464
+ rules: [
465
+ { match: /#!?\[[^\]]*\]/, type: "meta" },
466
+ { match: /'[A-Za-z_]\w*(?!')/, type: "keyword" },
467
+ { match: /[A-Za-z_]\w*!(?=\s*[([{])/, type: "function" }
468
+ ],
469
+ classNames: true
470
+ });
471
+
472
+ // src/languages/sql.ts
473
+ var sql_default = defineLanguage({
474
+ lineComment: ["--"],
475
+ blockComment: [["/*", "*/"]],
476
+ strings: [
477
+ { open: "'", escape: false },
478
+ { open: '"', escape: false, type: "property" },
479
+ { open: "`", escape: false, type: "property" }
480
+ ],
481
+ keywords: "select from where and or not insert into values update set delete create table alter drop index primary key foreign references join left right inner outer full cross on as group by order having limit offset union all distinct case when then else end is in like ilike between exists default constraint unique check view begin commit rollback transaction returning with recursive if desc asc add column grant revoke cascade truncate database schema explain using natural over partition window",
482
+ constants: "null true false",
483
+ types: "int integer bigint smallint serial bigserial varchar char text boolean bool date time timestamp timestamptz interval decimal numeric float real double precision uuid json jsonb blob bytea",
484
+ caseInsensitive: true
485
+ });
486
+
487
+ // src/languages/typescript.ts
488
+ var TS_KEYWORDS = " interface type enum implements namespace declare abstract readonly private protected public keyof infer is satisfies asserts module override unique";
489
+ var ts = (jsx) => ({
490
+ ...C_COMMENTS,
491
+ strings: [...QUOTES, { open: "`", multiline: true }],
492
+ keywords: JS_KEYWORDS + TS_KEYWORDS,
493
+ types: "string number boolean any unknown never void object symbol bigint",
494
+ constants: JS_CONSTANTS,
495
+ // Plain TypeScript has no JSX, so `Map<string, number>` is never mistaken for a tag.
496
+ rules: jsx ? [JSX_TAG, DECORATOR] : [DECORATOR],
497
+ classNames: true
498
+ });
499
+ var typescript_default = defineLanguage(ts(false));
500
+ var tsx = defineLanguage(ts(true));
501
+
502
+ // src/languages/xml.ts
503
+ var xml_default = createMarkup({ script: javascript_default, style: css_default });
504
+
505
+ // src/languages/yaml.ts
506
+ var yaml_default = defineLanguage({
507
+ strings: [{ open: '"' }, { open: "'", escape: false }],
508
+ constants: "true false null yes no on off ~",
509
+ caseInsensitive: true,
510
+ rules: [
511
+ { match: /(?<=^|\s)#.*/, type: "comment" },
512
+ { match: /^(?:---|\.\.\.)(?=\s*$)/, type: "meta" },
513
+ { match: /[^\s#:'"[\]{},-][^#:]*?(?=:(?:\s|$))|(?<=^\s*-\s+)[^\s#:'"[\]{},][^#:]*?(?=:(?:\s|$))/, type: "property" },
514
+ { match: /[&*][\w-]+/, type: "variable" },
515
+ { match: /!!?[\w-]+/, type: "type" }
516
+ ],
517
+ identifier: /[A-Za-z_][\w-]*/,
518
+ calls: false
519
+ });
520
+
521
+ // src/languages/index.ts
522
+ var LANGUAGES = {
523
+ javascript: javascript_default,
524
+ typescript: typescript_default,
525
+ tsx,
526
+ json: json_default,
527
+ python: python_default,
528
+ bash: bash_default,
529
+ ruby: ruby_default,
530
+ php: php_default,
531
+ go: go_default,
532
+ rust: rust_default,
533
+ java: java_default,
534
+ c: c_default,
535
+ cpp: cpp_default,
536
+ csharp: csharp_default,
537
+ sql: sql_default,
538
+ css: css_default,
539
+ yaml: yaml_default,
540
+ xml: xml_default,
541
+ diff: diff_default,
542
+ plaintext: plain
543
+ };
544
+
545
+ // src/lib/registry.ts
546
+ var registry = new Map(Object.entries(LANGUAGES));
547
+ var aliases = new Map(
548
+ Object.entries({
549
+ js: "javascript",
550
+ jsx: "javascript",
551
+ mjs: "javascript",
552
+ cjs: "javascript",
553
+ node: "javascript",
554
+ ts: "typescript",
555
+ mts: "typescript",
556
+ cts: "typescript",
557
+ jsonc: "json",
558
+ json5: "json",
559
+ py: "python",
560
+ python3: "python",
561
+ sh: "bash",
562
+ shell: "bash",
563
+ zsh: "bash",
564
+ shellscript: "bash",
565
+ console: "bash",
566
+ terminal: "bash",
567
+ rb: "ruby",
568
+ golang: "go",
569
+ rs: "rust",
570
+ h: "c",
571
+ "c++": "cpp",
572
+ cc: "cpp",
573
+ cxx: "cpp",
574
+ hpp: "cpp",
575
+ cs: "csharp",
576
+ "c#": "csharp",
577
+ postgres: "sql",
578
+ postgresql: "sql",
579
+ mysql: "sql",
580
+ sqlite: "sql",
581
+ plsql: "sql",
582
+ scss: "css",
583
+ less: "css",
584
+ yml: "yaml",
585
+ html: "xml",
586
+ xhtml: "xml",
587
+ svg: "xml",
588
+ vue: "xml",
589
+ svelte: "xml",
590
+ patch: "diff",
591
+ text: "plaintext",
592
+ txt: "plaintext",
593
+ plain: "plaintext",
594
+ "": "plaintext"
595
+ })
596
+ );
597
+ function getLanguage(name) {
598
+ const key = (_nullishCoalesce(name, () => ( ""))).trim().toLowerCase();
599
+ return _nullishCoalesce(registry.get(key), () => ( registry.get(_nullishCoalesce(aliases.get(key), () => ( "")))));
600
+ }
601
+ function registerLanguage(name, language, alias = []) {
602
+ registry.set(name.toLowerCase(), language);
603
+ for (const a of alias) aliases.set(a.toLowerCase(), name.toLowerCase());
604
+ }
605
+ function listLanguages() {
606
+ return [...registry.keys()];
607
+ }
608
+
609
+ // src/lib/stream.ts
610
+ var resolve = (lang) => typeof lang === "object" ? lang : _nullishCoalesce(getLanguage(lang), () => ( plain));
611
+ var ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
612
+ function escapeHtml(text) {
613
+ return text.replace(/[&<>"]/g, (ch) => ESCAPES[ch]);
614
+ }
615
+ function renderLine(line) {
616
+ let html = "";
617
+ for (const t of line) html += t.type ? `<span class="cl-${t.type}">${escapeHtml(t.text)}</span>` : escapeHtml(t.text);
618
+ return html;
619
+ }
620
+ function tokenize(code, lang) {
621
+ const language = resolve(lang);
622
+ let state = null;
623
+ return code.split("\n").map((raw) => {
624
+ const r = language.tokenizeLine(raw.replace(/\r$/, ""), state);
625
+ state = r.state;
626
+ return r.tokens;
627
+ });
628
+ }
629
+ function highlight(code, lang) {
630
+ return tokenize(code, lang).map(renderLine).join("\n");
631
+ }
632
+ function createStream(lang) {
633
+ const language = resolve(lang);
634
+ let state = null;
635
+ let pending = "";
636
+ let text = "";
637
+ return {
638
+ get text() {
639
+ return text;
640
+ },
641
+ push(chunk) {
642
+ text += chunk;
643
+ pending += chunk;
644
+ const lines = [];
645
+ let nl;
646
+ while ((nl = pending.indexOf("\n")) >= 0) {
647
+ const r = language.tokenizeLine(pending.slice(0, nl).replace(/\r$/, ""), state);
648
+ lines.push(r.tokens);
649
+ state = r.state;
650
+ pending = pending.slice(nl + 1);
651
+ }
652
+ return { lines, tail: language.tokenizeLine(pending.replace(/\r$/, ""), state).tokens };
653
+ }
654
+ };
655
+ }
656
+
657
+ // src/lib/dom.ts
658
+ function mount(target, options = {}) {
659
+ const doc = target.ownerDocument;
660
+ let lang = options.lang;
661
+ let stream;
662
+ let tail;
663
+ const lineElement = () => {
664
+ const el = doc.createElement("span");
665
+ el.className = "cl-line";
666
+ return el;
667
+ };
668
+ const start = () => {
669
+ stream = createStream(lang);
670
+ tail = lineElement();
671
+ target.replaceChildren(tail);
672
+ };
673
+ target.classList.add("cl");
674
+ start();
675
+ const view = {
676
+ get text() {
677
+ return stream.text;
678
+ },
679
+ get lang() {
680
+ return lang;
681
+ },
682
+ write(chunk) {
683
+ if (!chunk) return;
684
+ const { lines, tail: last } = stream.push(chunk);
685
+ if (lines.length) {
686
+ const done = doc.createDocumentFragment();
687
+ for (const line of lines) {
688
+ const el = lineElement();
689
+ el.innerHTML = renderLine(line);
690
+ done.append(el, "\n");
691
+ }
692
+ target.insertBefore(done, tail);
693
+ }
694
+ tail.innerHTML = renderLine(last);
695
+ },
696
+ set(text) {
697
+ const shown = stream.text;
698
+ if (text === shown) return;
699
+ if (text.startsWith(shown)) return view.write(text.slice(shown.length));
700
+ start();
701
+ view.write(text);
702
+ },
703
+ reset(next) {
704
+ if (next !== void 0) lang = next;
705
+ start();
706
+ }
707
+ };
708
+ return view;
709
+ }
710
+
711
+
712
+
713
+
714
+
715
+
716
+
717
+
718
+
719
+
720
+
721
+
722
+
723
+ exports.defineLanguage = defineLanguage; exports.createMarkup = createMarkup; exports.getLanguage = getLanguage; exports.registerLanguage = registerLanguage; exports.listLanguages = listLanguages; exports.escapeHtml = escapeHtml; exports.renderLine = renderLine; exports.tokenize = tokenize; exports.highlight = highlight; exports.createStream = createStream; exports.mount = mount;