@d10f/asciidoc-astro-loader 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -287,233 +287,6 @@ var AsciidocDocument = class {
287
287
  }
288
288
  };
289
289
 
290
- // src/schemas/index.ts
291
- var import_zod3 = require("astro/zod");
292
-
293
- // src/schemas/document.ts
294
- var import_node_path = require("path");
295
- var import_zod = require("astro/zod");
296
- var documentOptionsSchema = import_zod.z.object({
297
- mode: import_zod.z.union([import_zod.z.literal("safe"), import_zod.z.literal("unsafe")]).default("safe"),
298
- template: import_zod.z.string().default("").transform((val) => val ? (0, import_node_path.resolve)(process.cwd(), val) : ""),
299
- recursive: import_zod.z.boolean().default(false)
300
- }).passthrough().default({
301
- mode: "safe",
302
- template: "",
303
- recursive: false
304
- });
305
-
306
- // src/schemas/shiki.ts
307
- var import_zod2 = require("astro/zod");
308
- var shikiOptionsSchema = import_zod2.z.object({
309
- theme: import_zod2.z.union([
310
- import_zod2.z.string(),
311
- import_zod2.z.object({
312
- light: import_zod2.z.string(),
313
- dark: import_zod2.z.string()
314
- }).catchall(import_zod2.z.string())
315
- ]).transform(transformThemeProp).default({
316
- light: "catppuccin-latte",
317
- dark: "catppuccin-macchiato"
318
- }),
319
- defaultColor: import_zod2.z.string().default("light-dark()"),
320
- cssVariablePrefix: import_zod2.z.string().default("--shiki-"),
321
- mergeWhitespaces: import_zod2.z.union([import_zod2.z.boolean(), import_zod2.z.literal("never")]).default(true),
322
- tabindex: import_zod2.z.union([import_zod2.z.number(), import_zod2.z.string(), import_zod2.z.literal(false)]).default(false),
323
- transformers: import_zod2.z.array(
324
- import_zod2.z.object({
325
- name: import_zod2.z.string(),
326
- enforce: import_zod2.z.union([import_zod2.z.literal("pre"), import_zod2.z.literal("post")])
327
- })
328
- ).optional()
329
- }).transform(({ theme, ...rest }) => ({
330
- themes: theme,
331
- ...rest
332
- })).default({
333
- mergeWhitespaces: true,
334
- cssVariablePrefix: "--shiki-",
335
- defaultColor: "light-dark()",
336
- tabindex: false,
337
- theme: {
338
- light: "catppuccin-latte",
339
- dark: "catppuccin-macchiato"
340
- },
341
- transformers: void 0
342
- });
343
- function transformThemeProp(value) {
344
- return typeof value === "string" ? { light: value, dark: value } : value;
345
- }
346
-
347
- // src/schemas/index.ts
348
- var preambleOptionsSchema = import_zod3.z.object({
349
- tableOfContents: import_zod3.z.boolean().default(true),
350
- maxLevel: import_zod3.z.number().max(6).min(1).default(3),
351
- position: import_zod3.z.union([import_zod3.z.literal("before"), import_zod3.z.literal("after")]).default("after")
352
- }).default({
353
- tableOfContents: true,
354
- maxLevel: 3,
355
- position: "after"
356
- });
357
- var loaderOptionsSchema = import_zod3.z.object({
358
- base: import_zod3.z.string(),
359
- document: documentOptionsSchema,
360
- syntaxHighlighting: shikiOptionsSchema,
361
- preamble: preambleOptionsSchema
362
- });
363
-
364
- // src/lib/shiki/Highlighter.ts
365
- var import_shiki2 = require("shiki");
366
- async function createHighlighter(documents, themes) {
367
- const langs = documents.reduce((acc, cur) => {
368
- cur.languages.forEach((lang) => {
369
- acc.add(lang);
370
- });
371
- return acc;
372
- }, /* @__PURE__ */ new Set());
373
- const highlighter = await (0, import_shiki2.createHighlighterCore)({
374
- themes: Object.values(themes).map((theme) => {
375
- return import(`@shikijs/themes/${theme}`);
376
- }),
377
- langs: Array.from(langs).map((lang) => {
378
- return import(`@shikijs/langs/${lang}`);
379
- }),
380
- engine: (0, import_shiki2.createJavaScriptRegexEngine)()
381
- });
382
- return Object.freeze(highlighter);
383
- }
384
-
385
- // src/lib/asciidoc/converters/sourceCodeConverter.ts
386
- var import_node_path2 = require("path");
387
-
388
- // src/lib/shiki/transformers/transformAsciidocCallout.ts
389
- function transformAsciidocCallout({
390
- node,
391
- cssClasses = "pointer-events-none select-none ml-2"
392
- }) {
393
- const lineComments = ["//", "#", ";;"];
394
- const customLineComment = node.getAttribute("line-comment");
395
- if (customLineComment) {
396
- lineComments.push(escapeRegexCharacters(customLineComment));
397
- }
398
- const calloutReList = [
399
- // Handles C-style and similar comments like Perl, Python...
400
- new RegExp(`(?:${lineComments.join("|")})((?:\\s+<(\\d+)>)+)`),
401
- // Handles XML comments
402
- new RegExp(/((?:\s*<!--(\d+)-->)+)/)
403
- ];
404
- const linesWithCallout = {};
405
- return {
406
- preprocess(code) {
407
- return code.split("\n").map((line, idx) => {
408
- for (const re of calloutReList) {
409
- const match = line.match(re);
410
- if (!match) continue;
411
- const callouts = match[0].trim().replaceAll(/(?:<!--|-->|[<>])/g, "").split(" ");
412
- linesWithCallout[idx + 1] = callouts;
413
- return line.replace(re, "");
414
- }
415
- return line;
416
- }).join("\n");
417
- },
418
- line(hast, line) {
419
- const callouts = linesWithCallout[line];
420
- if (!callouts) return;
421
- callouts.forEach((calloutId) => {
422
- hast.properties[`data-callout-${calloutId}`] = "";
423
- hast.children.push({
424
- type: "element",
425
- tagName: "i",
426
- properties: {
427
- class: `conum ${cssClasses}`,
428
- "data-value": calloutId
429
- },
430
- children: [
431
- {
432
- type: "element",
433
- tagName: "b",
434
- properties: {},
435
- children: [
436
- {
437
- type: "text",
438
- value: calloutId
439
- }
440
- ]
441
- }
442
- ]
443
- });
444
- });
445
- }
446
- };
447
- }
448
-
449
- // src/lib/shiki/transformers/transformConsoleCodeBlock.ts
450
- function transformConsoleCodeBlock(options = {
451
- cssClasses: "pointer-events-none select-none mr-2 opacity-50"
452
- }) {
453
- const unselectablePrompt = `<span $1 class="${options.cssClasses}">$</span>`;
454
- const linePrefix = '<span class="line[^>]+?>';
455
- const splitPrompt = new RegExp(
456
- `(?<=${linePrefix})(?:<span (style="[^"]*?")>\\s*?\\$\\s+?([^<]))`
457
- );
458
- const trimWhitespace = new RegExp(
459
- `(?<=${linePrefix})(?:<span (style="[^"]*?")>\\s*?\\$\\s*?<\\/span>(?:<span>\\s+<\\/span>)?)`
460
- );
461
- const trimWhitespaceAhead = new RegExp(
462
- `(?<=${linePrefix}<span [^>]+?>\\$<\\/span>)(<span style="[^"]+?">)\\s+?`
463
- );
464
- return {
465
- postprocess: (html, { lang }) => {
466
- if (lang === "console") {
467
- return html.split("\n").map((line) => {
468
- return line.replace(
469
- splitPrompt,
470
- unselectablePrompt + "<span $1>$2"
471
- ).replace(trimWhitespace, unselectablePrompt).replace(trimWhitespaceAhead, "$1");
472
- }).join("\n");
473
- }
474
- }
475
- };
476
- }
477
-
478
- // src/lib/asciidoc/converters/sourceCodeConverter.ts
479
- var sourceCodeConverter = ({ transformers, template }) => {
480
- return (options, highlighter) => {
481
- return {
482
- nodeContext: "listing",
483
- nodeStyle: "source",
484
- convert(node, templateEngine) {
485
- const input = node.getSourceLines().join("\n");
486
- const lang = node.getAttribute("language");
487
- const output = highlighter.codeToHtml(input, {
488
- ...options.syntaxHighlighting,
489
- lang,
490
- transformers: [
491
- ...transformers ?? [],
492
- transformAsciidocCallout({ node }),
493
- transformConsoleCodeBlock()
494
- ]
495
- });
496
- if (templateEngine && template) {
497
- const { extension } = splitFilenameComponents(template);
498
- const engine = templateEngine.getEngineByExtension(
499
- extension || ""
500
- );
501
- if (engine) {
502
- const templateFile = (0, import_node_path2.resolve)(process.cwd(), template);
503
- if (engine.canRenderFile) {
504
- return engine.renderFile(templateFile, {
505
- content: output,
506
- lang
507
- });
508
- }
509
- }
510
- }
511
- return output;
512
- }
513
- };
514
- };
515
- };
516
-
517
290
  // src/lib/asciidoc/templates/engines/Handlebars.ts
518
291
  var import_node_fs2 = require("fs");
519
292
 
@@ -643,14 +416,211 @@ var NunjucksEngine = class extends AbstractEngine {
643
416
  }
644
417
  };
645
418
 
419
+ // src/schemas/index.ts
420
+ var import_zod3 = require("astro/zod");
421
+
422
+ // src/schemas/document.ts
423
+ var import_node_path = require("path");
424
+ var import_zod = require("astro/zod");
425
+ var documentOptionsSchema = import_zod.z.object({
426
+ mode: import_zod.z.union([import_zod.z.literal("safe"), import_zod.z.literal("unsafe")]).default("safe"),
427
+ template: import_zod.z.string().default("").transform((val) => val ? (0, import_node_path.resolve)(process.cwd(), val) : ""),
428
+ recursive: import_zod.z.boolean().default(false)
429
+ }).passthrough().default({
430
+ mode: "safe",
431
+ template: "",
432
+ recursive: false
433
+ });
434
+
435
+ // src/schemas/shiki.ts
436
+ var import_zod2 = require("astro/zod");
437
+ var shikiOptionsSchema = import_zod2.z.object({
438
+ theme: import_zod2.z.union([
439
+ import_zod2.z.string(),
440
+ import_zod2.z.object({
441
+ light: import_zod2.z.string(),
442
+ dark: import_zod2.z.string()
443
+ }).catchall(import_zod2.z.string())
444
+ ]).transform(transformThemeProp).default({
445
+ light: "catppuccin-latte",
446
+ dark: "catppuccin-macchiato"
447
+ }),
448
+ defaultColor: import_zod2.z.string().default("light-dark()"),
449
+ cssVariablePrefix: import_zod2.z.string().default("--shiki-"),
450
+ mergeWhitespaces: import_zod2.z.union([import_zod2.z.boolean(), import_zod2.z.literal("never")]).default(true),
451
+ tabindex: import_zod2.z.union([import_zod2.z.number(), import_zod2.z.string(), import_zod2.z.literal(false)]).default(false),
452
+ // transformers: z
453
+ // .array(
454
+ // z.object({
455
+ // name: z.string(),
456
+ // enforce: z.union([z.literal('pre'), z.literal('post')]),
457
+ // }),
458
+ // )
459
+ // .optional(),
460
+ callouts: import_zod2.z.object({
461
+ cssClasses: import_zod2.z.string().optional()
462
+ }).optional()
463
+ }).passthrough().transform(({ theme, ...rest }) => ({
464
+ themes: theme,
465
+ ...rest
466
+ })).default({
467
+ mergeWhitespaces: true,
468
+ cssVariablePrefix: "--shiki-",
469
+ defaultColor: "light-dark()",
470
+ tabindex: false,
471
+ theme: {
472
+ light: "catppuccin-latte",
473
+ dark: "catppuccin-macchiato"
474
+ },
475
+ // transformers: undefined,
476
+ callouts: void 0
477
+ });
478
+ function transformThemeProp(value) {
479
+ return typeof value === "string" ? { light: value, dark: value } : value;
480
+ }
481
+
482
+ // src/schemas/index.ts
483
+ var preambleOptionsSchema = import_zod3.z.object({
484
+ tableOfContents: import_zod3.z.boolean().default(true),
485
+ maxLevel: import_zod3.z.number().max(6).min(1).default(3),
486
+ position: import_zod3.z.union([import_zod3.z.literal("before"), import_zod3.z.literal("after")]).default("after")
487
+ }).default({
488
+ tableOfContents: true,
489
+ maxLevel: 3,
490
+ position: "after"
491
+ });
492
+ var loaderOptionsSchema = import_zod3.z.object({
493
+ base: import_zod3.z.string(),
494
+ document: documentOptionsSchema,
495
+ syntaxHighlighting: shikiOptionsSchema,
496
+ preamble: preambleOptionsSchema
497
+ });
498
+
499
+ // src/lib/shiki/Highlighter.ts
500
+ var import_shiki2 = require("shiki");
501
+ async function createHighlighter(documents, themes) {
502
+ const langs = documents.reduce((acc, cur) => {
503
+ cur.languages.forEach((lang) => {
504
+ acc.add(lang);
505
+ });
506
+ return acc;
507
+ }, /* @__PURE__ */ new Set());
508
+ const highlighter = await (0, import_shiki2.createHighlighterCore)({
509
+ themes: Object.values(themes).map((theme) => {
510
+ return import(`@shikijs/themes/${theme}`);
511
+ }),
512
+ langs: Array.from(langs).map((lang) => {
513
+ return import(`@shikijs/langs/${lang}`);
514
+ }),
515
+ engine: (0, import_shiki2.createJavaScriptRegexEngine)()
516
+ });
517
+ return Object.freeze(highlighter);
518
+ }
519
+
520
+ // src/lib/asciidoc/converters/sourceCodeConverter.ts
521
+ var import_node_path2 = require("path");
522
+ var sourceCodeConverter = ({ transformers, template }) => {
523
+ return (options, highlighter) => {
524
+ return {
525
+ nodeContext: "listing",
526
+ nodeStyle: "source",
527
+ convert(node, templateEngine) {
528
+ const input = node.getSourceLines().join("\n");
529
+ const lang = node.getAttribute("language");
530
+ const output = highlighter.codeToHtml(input, {
531
+ ...options.syntaxHighlighting,
532
+ lang,
533
+ transformers: (transformers ?? []).map((transformer) => {
534
+ return typeof transformer === "function" ? transformer(node) : transformer;
535
+ })
536
+ });
537
+ if (templateEngine && template) {
538
+ const { extension } = splitFilenameComponents(template);
539
+ const engine = templateEngine.getEngineByExtension(
540
+ extension || ""
541
+ );
542
+ if (engine) {
543
+ const templateFile = (0, import_node_path2.resolve)(process.cwd(), template);
544
+ if (engine.canRenderFile) {
545
+ return engine.renderFile(templateFile, {
546
+ content: output,
547
+ lang
548
+ });
549
+ }
550
+ }
551
+ }
552
+ return output;
553
+ }
554
+ };
555
+ };
556
+ };
557
+
558
+ // src/lib/shiki/transformers/transformAsciidocCallout.ts
559
+ var transformAsciidocCallout = (options) => {
560
+ return (node) => {
561
+ const lineComments = ["//", "#", ";;"];
562
+ const customLineComment = node.getAttribute("line-comment");
563
+ if (customLineComment) {
564
+ lineComments.push(escapeRegexCharacters(customLineComment));
565
+ }
566
+ const calloutReList = [
567
+ // Handles C-style and similar comments like Perl, Python...
568
+ new RegExp(`\\s+(?:${lineComments.join("|")})((?:\\s+<(\\d+)>)+)`),
569
+ // Handles XML comments
570
+ new RegExp(/((?:\s*<!--(\d+)-->)+)/)
571
+ ];
572
+ const commentTokensRe = new RegExp(
573
+ `(?:${lineComments.join("|")}|<!--|-->|[<>])`,
574
+ "g"
575
+ );
576
+ const linesWithCallout = {};
577
+ return {
578
+ preprocess(code) {
579
+ return code.split("\n").map((line, idx) => {
580
+ for (const re of calloutReList) {
581
+ const match = line.match(re);
582
+ if (!match) continue;
583
+ const callouts = match[0].replaceAll(commentTokensRe, "").trim().split(" ");
584
+ linesWithCallout[idx + 1] = callouts;
585
+ return line.replace(re, "");
586
+ }
587
+ return line;
588
+ }).join("\n");
589
+ },
590
+ line(hast, line) {
591
+ const callouts = linesWithCallout[line];
592
+ if (!callouts) return;
593
+ callouts.forEach((calloutId) => {
594
+ hast.properties[`data-callout-${calloutId}`] = "";
595
+ hast.children.push({
596
+ type: "element",
597
+ tagName: "span",
598
+ properties: {
599
+ class: options?.cssClasses ?? "conum",
600
+ style: options?.cssClasses ? "" : "user-select:none; pointer-events:none; opacity:0.5; margin-inline:8px;",
601
+ "data-value": calloutId
602
+ },
603
+ children: [
604
+ {
605
+ type: "text",
606
+ value: calloutId
607
+ }
608
+ ]
609
+ });
610
+ });
611
+ }
612
+ };
613
+ };
614
+ };
615
+
646
616
  // src/loader.ts
647
- function asciidocLoader(options) {
648
- const parsedOpts = loaderOptionsSchema.parse(options);
649
- if (parsedOpts.document.converters === void 0) {
650
- parsedOpts.document.converters = [];
617
+ function asciidocLoader(_options) {
618
+ const options = loaderOptionsSchema.parse(_options);
619
+ if (options.document.converters === void 0) {
620
+ options.document.converters = [];
651
621
  }
652
- if (parsedOpts.document.templateEngines === void 0) {
653
- parsedOpts.document.templateEngines = [
622
+ if (options.document.templateEngines === void 0) {
623
+ options.document.templateEngines = [
654
624
  new HandlebarsEngine(),
655
625
  new NunjucksEngine()
656
626
  ];
@@ -662,18 +632,18 @@ function asciidocLoader(options) {
662
632
  async load(loaderContext) {
663
633
  const { config, logger, watcher } = loaderContext;
664
634
  const root = config.root.pathname;
665
- const base = parsedOpts.base.startsWith(".") ? (0, import_node_fs4.realpathSync)(options.base) : root + options.base;
635
+ const base = options.base.startsWith(".") ? (0, import_node_fs4.realpathSync)(options.base) : root + options.base;
666
636
  const docs = (0, import_node_fs4.readdirSync)(base, "utf8").filter((file) => file.match(/(?:\.a(?:scii)?doc)$/)).map((filename) => new AsciidocDocument(`${base}/${filename}`));
667
637
  if (docs.length === 0) {
668
638
  logger.warn("No documents found for this collection.");
669
639
  return;
670
640
  }
671
- if (parsedOpts.document.template) {
641
+ if (options.document.template) {
672
642
  templateEngine = new TemplateEngineRegistry(
673
- parsedOpts.document.templateEngines,
643
+ options.document.templateEngines,
674
644
  {
675
- rootDir: parsedOpts.document.template,
676
- recursive: parsedOpts.document.recursive
645
+ rootDir: options.document.template,
646
+ recursive: options.document.recursive
677
647
  }
678
648
  );
679
649
  await templateEngine.loadEngines();
@@ -681,11 +651,11 @@ function asciidocLoader(options) {
681
651
  if (!highlighter) {
682
652
  highlighter = await createHighlighter(
683
653
  docs,
684
- parsedOpts.syntaxHighlighting.themes
654
+ options.syntaxHighlighting.themes
685
655
  );
686
656
  }
687
- const converters = parsedOpts.document.converters.map(
688
- (converter) => converter(parsedOpts, highlighter)
657
+ const converters = options.document.converters.map(
658
+ (converter) => converter(options, highlighter)
689
659
  );
690
660
  const hasSourceCodeConverter = converters.find(
691
661
  (converter) => converter.nodeContext === "listing" && converter?.nodeStyle === "source"
@@ -693,18 +663,18 @@ function asciidocLoader(options) {
693
663
  if (!hasSourceCodeConverter) {
694
664
  converters.push(
695
665
  sourceCodeConverter({
696
- transformers: parsedOpts.syntaxHighlighting.transformers
697
- })(parsedOpts, highlighter)
666
+ transformers: [
667
+ ...options.syntaxHighlighting.transformers ?? [],
668
+ transformAsciidocCallout(
669
+ options.syntaxHighlighting.callouts
670
+ )
671
+ ]
672
+ })(options, highlighter)
698
673
  );
699
674
  }
700
675
  await Promise.all(
701
676
  docs.map(
702
- (doc) => syncDocument(
703
- doc,
704
- converters,
705
- templateEngine,
706
- loaderContext
707
- )
677
+ (doc) => setDocument(doc, converters, templateEngine, loaderContext)
708
678
  )
709
679
  );
710
680
  if (watcher) {
@@ -717,11 +687,10 @@ function asciidocLoader(options) {
717
687
  const watchedFileRegExp = new RegExp(
718
688
  `^${base}.*.(a(?:scii)?doc)$`
719
689
  );
720
- console.log(this.name);
721
690
  watcher.on("change", async (changedPath) => {
722
691
  if (changedPath.match(watchedFileRegExp)) {
723
692
  const newDoc = new AsciidocDocument(changedPath);
724
- await syncDocument(
693
+ await setDocument(
725
694
  newDoc,
726
695
  converters,
727
696
  templateEngine,
@@ -729,15 +698,17 @@ function asciidocLoader(options) {
729
698
  );
730
699
  }
731
700
  });
732
- process.on("SIGINT", handle2);
733
- process.on("SIGTERM", handle2);
701
+ if (highlighter) {
702
+ process.on("SIGINT", handle2);
703
+ process.on("SIGTERM", handle2);
704
+ }
734
705
  } else {
735
706
  (0, import_node_process.nextTick)(highlighter.dispose);
736
707
  }
737
708
  }
738
709
  };
739
710
  }
740
- async function syncDocument(doc, converters, templateEngine, { parseData, store }) {
711
+ async function setDocument(doc, converters, templateEngine, { parseData, store }) {
741
712
  const data = await parseData({
742
713
  id: doc.slug,
743
714
  data: {
package/dist/index.d.cts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { LoaderContext } from 'astro/loaders';
2
- import { A as AsciidocLoader } from './index-BNxO58s3.cjs';
3
- export { a as AsciidocTemplate, C as CustomConverterFactoryFn, F as FilesystemTemplate, N as NodeContext, R as RawTemplate } from './index-BNxO58s3.cjs';
2
+ import { A as AsciidocLoader } from './index-sFlXF8Qm.cjs';
3
+ export { a as AsciidocTemplate, C as CustomConverterFactoryFn, F as FilesystemTemplate, N as NodeContext, R as RawTemplate } from './index-sFlXF8Qm.cjs';
4
4
  import 'shiki';
5
5
  import 'asciidoctor';
6
6
  import 'astro/zod';
7
7
 
8
- declare function asciidocLoader(options: AsciidocLoader): {
8
+ declare function asciidocLoader(_options: AsciidocLoader): {
9
9
  name: string;
10
10
  load(loaderContext: LoaderContext): Promise<void>;
11
11
  };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { LoaderContext } from 'astro/loaders';
2
- import { A as AsciidocLoader } from './index-BNxO58s3.js';
3
- export { a as AsciidocTemplate, C as CustomConverterFactoryFn, F as FilesystemTemplate, N as NodeContext, R as RawTemplate } from './index-BNxO58s3.js';
2
+ import { A as AsciidocLoader } from './index-sFlXF8Qm.js';
3
+ export { a as AsciidocTemplate, C as CustomConverterFactoryFn, F as FilesystemTemplate, N as NodeContext, R as RawTemplate } from './index-sFlXF8Qm.js';
4
4
  import 'shiki';
5
5
  import 'asciidoctor';
6
6
  import 'astro/zod';
7
7
 
8
- declare function asciidocLoader(options: AsciidocLoader): {
8
+ declare function asciidocLoader(_options: AsciidocLoader): {
9
9
  name: string;
10
10
  load(loaderContext: LoaderContext): Promise<void>;
11
11
  };