@d10f/asciidoc-astro-loader 0.0.2 → 0.0.4

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,213 @@ 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 = (converterOptions) => {
523
+ const transformers = converterOptions?.transformers;
524
+ const template = converterOptions?.template;
525
+ return (options, highlighter) => {
526
+ return {
527
+ nodeContext: "listing",
528
+ nodeStyle: "source",
529
+ convert(node, templateEngine) {
530
+ const input = node.getSourceLines().join("\n");
531
+ const lang = node.getAttribute("language");
532
+ const output = highlighter.codeToHtml(input, {
533
+ ...options.syntaxHighlighting,
534
+ lang,
535
+ transformers: (transformers ?? []).map((transformer) => {
536
+ return typeof transformer === "function" ? transformer(node) : transformer;
537
+ })
538
+ });
539
+ if (templateEngine && template) {
540
+ const { extension } = splitFilenameComponents(template);
541
+ const engine = templateEngine.getEngineByExtension(
542
+ extension || ""
543
+ );
544
+ if (engine) {
545
+ const templateFile = (0, import_node_path2.resolve)(process.cwd(), template);
546
+ if (engine.canRenderFile) {
547
+ return engine.renderFile(templateFile, {
548
+ content: output,
549
+ lang
550
+ });
551
+ }
552
+ }
553
+ }
554
+ return output;
555
+ }
556
+ };
557
+ };
558
+ };
559
+
560
+ // src/lib/shiki/transformers/transformAsciidocCallout.ts
561
+ var transformAsciidocCallout = (options) => {
562
+ return (node) => {
563
+ const lineComments = ["//", "#", ";;"];
564
+ const customLineComment = node.getAttribute("line-comment");
565
+ if (customLineComment) {
566
+ lineComments.push(escapeRegexCharacters(customLineComment));
567
+ }
568
+ const calloutReList = [
569
+ // Handles C-style and similar comments like Perl, Python...
570
+ new RegExp(`\\s+(?:${lineComments.join("|")})((?:\\s+<(\\d+)>)+)`),
571
+ // Handles XML comments
572
+ new RegExp(/((?:\s*<!--(\d+)-->)+)/)
573
+ ];
574
+ const commentTokensRe = new RegExp(
575
+ `(?:${lineComments.join("|")}|<!--|-->|[<>])`,
576
+ "g"
577
+ );
578
+ const linesWithCallout = {};
579
+ return {
580
+ preprocess(code) {
581
+ return code.split("\n").map((line, idx) => {
582
+ for (const re of calloutReList) {
583
+ const match = line.match(re);
584
+ if (!match) continue;
585
+ const callouts = match[0].replaceAll(commentTokensRe, "").trim().split(" ");
586
+ linesWithCallout[idx + 1] = callouts;
587
+ return line.replace(re, "");
588
+ }
589
+ return line;
590
+ }).join("\n");
591
+ },
592
+ line(hast, line) {
593
+ const callouts = linesWithCallout[line];
594
+ if (!callouts) return;
595
+ callouts.forEach((calloutId) => {
596
+ hast.properties[`data-callout-${calloutId}`] = "";
597
+ hast.children.push({
598
+ type: "element",
599
+ tagName: "span",
600
+ properties: {
601
+ class: options?.cssClasses ?? "conum",
602
+ style: options?.cssClasses ? "" : "user-select:none; pointer-events:none; opacity:0.5; margin-inline:8px;",
603
+ "data-value": calloutId
604
+ },
605
+ children: [
606
+ {
607
+ type: "text",
608
+ value: calloutId
609
+ }
610
+ ]
611
+ });
612
+ });
613
+ }
614
+ };
615
+ };
616
+ };
617
+
646
618
  // src/loader.ts
647
- function asciidocLoader(options) {
648
- const parsedOpts = loaderOptionsSchema.parse(options);
649
- if (parsedOpts.document.converters === void 0) {
650
- parsedOpts.document.converters = [];
619
+ function asciidocLoader(_options) {
620
+ const options = loaderOptionsSchema.parse(_options);
621
+ if (options.document.converters === void 0) {
622
+ options.document.converters = [];
651
623
  }
652
- if (parsedOpts.document.templateEngines === void 0) {
653
- parsedOpts.document.templateEngines = [
624
+ if (options.document.templateEngines === void 0) {
625
+ options.document.templateEngines = [
654
626
  new HandlebarsEngine(),
655
627
  new NunjucksEngine()
656
628
  ];
@@ -662,18 +634,18 @@ function asciidocLoader(options) {
662
634
  async load(loaderContext) {
663
635
  const { config, logger, watcher } = loaderContext;
664
636
  const root = config.root.pathname;
665
- const base = parsedOpts.base.startsWith(".") ? (0, import_node_fs4.realpathSync)(options.base) : root + options.base;
637
+ const base = options.base.startsWith(".") ? (0, import_node_fs4.realpathSync)(options.base) : root + options.base;
666
638
  const docs = (0, import_node_fs4.readdirSync)(base, "utf8").filter((file) => file.match(/(?:\.a(?:scii)?doc)$/)).map((filename) => new AsciidocDocument(`${base}/${filename}`));
667
639
  if (docs.length === 0) {
668
640
  logger.warn("No documents found for this collection.");
669
641
  return;
670
642
  }
671
- if (parsedOpts.document.template) {
643
+ if (options.document.template) {
672
644
  templateEngine = new TemplateEngineRegistry(
673
- parsedOpts.document.templateEngines,
645
+ options.document.templateEngines,
674
646
  {
675
- rootDir: parsedOpts.document.template,
676
- recursive: parsedOpts.document.recursive
647
+ rootDir: options.document.template,
648
+ recursive: options.document.recursive
677
649
  }
678
650
  );
679
651
  await templateEngine.loadEngines();
@@ -681,11 +653,11 @@ function asciidocLoader(options) {
681
653
  if (!highlighter) {
682
654
  highlighter = await createHighlighter(
683
655
  docs,
684
- parsedOpts.syntaxHighlighting.themes
656
+ options.syntaxHighlighting.themes
685
657
  );
686
658
  }
687
- const converters = parsedOpts.document.converters.map(
688
- (converter) => converter(parsedOpts, highlighter)
659
+ const converters = options.document.converters.map(
660
+ (converter) => converter(options, highlighter)
689
661
  );
690
662
  const hasSourceCodeConverter = converters.find(
691
663
  (converter) => converter.nodeContext === "listing" && converter?.nodeStyle === "source"
@@ -693,18 +665,18 @@ function asciidocLoader(options) {
693
665
  if (!hasSourceCodeConverter) {
694
666
  converters.push(
695
667
  sourceCodeConverter({
696
- transformers: parsedOpts.syntaxHighlighting.transformers
697
- })(parsedOpts, highlighter)
668
+ transformers: [
669
+ ...options.syntaxHighlighting.transformers ?? [],
670
+ transformAsciidocCallout(
671
+ options.syntaxHighlighting.callouts
672
+ )
673
+ ]
674
+ })(options, highlighter)
698
675
  );
699
676
  }
700
677
  await Promise.all(
701
678
  docs.map(
702
- (doc) => syncDocument(
703
- doc,
704
- converters,
705
- templateEngine,
706
- loaderContext
707
- )
679
+ (doc) => setDocument(doc, converters, templateEngine, loaderContext)
708
680
  )
709
681
  );
710
682
  if (watcher) {
@@ -717,11 +689,10 @@ function asciidocLoader(options) {
717
689
  const watchedFileRegExp = new RegExp(
718
690
  `^${base}.*.(a(?:scii)?doc)$`
719
691
  );
720
- console.log(this.name);
721
692
  watcher.on("change", async (changedPath) => {
722
693
  if (changedPath.match(watchedFileRegExp)) {
723
694
  const newDoc = new AsciidocDocument(changedPath);
724
- await syncDocument(
695
+ await setDocument(
725
696
  newDoc,
726
697
  converters,
727
698
  templateEngine,
@@ -729,15 +700,17 @@ function asciidocLoader(options) {
729
700
  );
730
701
  }
731
702
  });
732
- process.on("SIGINT", handle2);
733
- process.on("SIGTERM", handle2);
703
+ if (highlighter) {
704
+ process.on("SIGINT", handle2);
705
+ process.on("SIGTERM", handle2);
706
+ }
734
707
  } else {
735
708
  (0, import_node_process.nextTick)(highlighter.dispose);
736
709
  }
737
710
  }
738
711
  };
739
712
  }
740
- async function syncDocument(doc, converters, templateEngine, { parseData, store }) {
713
+ async function setDocument(doc, converters, templateEngine, { parseData, store }) {
741
714
  const data = await parseData({
742
715
  id: doc.slug,
743
716
  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-CS3PBqxf.cjs';
3
+ export { a as AsciidocTemplate, C as CustomConverterFactoryFn, F as FilesystemTemplate, N as NodeContext, R as RawTemplate } from './index-CS3PBqxf.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-CS3PBqxf.js';
3
+ export { a as AsciidocTemplate, C as CustomConverterFactoryFn, F as FilesystemTemplate, N as NodeContext, R as RawTemplate } from './index-CS3PBqxf.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
  };