@constela/start 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,17 +1,32 @@
1
1
  import {
2
+ DataLoader,
3
+ LayoutResolver,
2
4
  build,
3
5
  createDevServer,
4
6
  filePathToPattern,
7
+ generateStaticPaths,
5
8
  getMimeType,
6
9
  isPathSafe,
10
+ loadApi,
11
+ loadComponentDefinitions,
12
+ loadFile,
13
+ loadGlob,
14
+ loadLayout,
15
+ mdxContentToNode,
16
+ mdxToConstela,
17
+ resolveLayout,
7
18
  resolveStaticFile,
8
- scanRoutes
9
- } from "./chunk-JXIOHPG5.js";
19
+ scanLayouts,
20
+ scanRoutes,
21
+ transformCsv,
22
+ transformMdx,
23
+ transformYaml
24
+ } from "./chunk-6AN7W7KZ.js";
10
25
  import {
11
26
  generateHydrationScript,
12
27
  renderPage,
13
28
  wrapHtml
14
- } from "./chunk-QLDID7EZ.js";
29
+ } from "./chunk-PUTC5BCP.js";
15
30
 
16
31
  // src/build/ssg.ts
17
32
  import { mkdir, writeFile } from "fs/promises";
@@ -89,7 +104,12 @@ async function generateSinglePage(pattern, outDir, program, params = {}) {
89
104
  query: new URLSearchParams()
90
105
  };
91
106
  const content = await renderPage(program, ctx);
92
- const hydrationScript = generateHydrationScript(program);
107
+ const routeContext = {
108
+ params,
109
+ query: {},
110
+ path: pattern
111
+ };
112
+ const hydrationScript = generateHydrationScript(program, void 0, routeContext);
93
113
  const html = wrapHtml(content, hydrationScript);
94
114
  await writeFile(outputPath, html, "utf-8");
95
115
  return outputPath;
@@ -109,6 +129,12 @@ async function generateStaticPages(routes, outDir, options = {}) {
109
129
  }
110
130
  for (const pathData of staticPaths.paths) {
111
131
  const program = await resolvePageExport(pageExport, pathData.params, route.params);
132
+ if (pathData.data !== void 0) {
133
+ program.importData = {
134
+ ...program.importData,
135
+ __pathData: pathData.data
136
+ };
137
+ }
112
138
  const resolvedPattern = resolvePattern(route.pattern, pathData.params);
113
139
  const filePath = await generateSinglePage(
114
140
  resolvedPattern,
@@ -231,7 +257,7 @@ function createErrorResponse(error) {
231
257
  }
232
258
  function createAdapter(options) {
233
259
  const { routes, loadModule = defaultLoadModule } = options;
234
- async function fetch2(request) {
260
+ async function fetch(request) {
235
261
  try {
236
262
  const url = new URL(request.url);
237
263
  let pathname = url.pathname;
@@ -272,7 +298,12 @@ function createAdapter(options) {
272
298
  params: matchedParams,
273
299
  query: url.searchParams
274
300
  });
275
- const hydrationScript = generateHydrationScript(program);
301
+ const routeContext = {
302
+ params: matchedParams,
303
+ query: Object.fromEntries(url.searchParams.entries()),
304
+ path: url.pathname
305
+ };
306
+ const hydrationScript = generateHydrationScript(program, void 0, routeContext);
276
307
  const html = wrapHtml(content, hydrationScript);
277
308
  return new Response(html, {
278
309
  status: 200,
@@ -283,915 +314,8 @@ function createAdapter(options) {
283
314
  return createErrorResponse(error);
284
315
  }
285
316
  }
286
- return { fetch: fetch2 };
287
- }
288
-
289
- // src/layout/resolver.ts
290
- import { existsSync, statSync } from "fs";
291
- import { join as join2, basename } from "path";
292
- import fg from "fast-glob";
293
- import { isLayoutProgram } from "@constela/core";
294
- async function scanLayouts(layoutsDir) {
295
- if (!existsSync(layoutsDir)) {
296
- throw new Error(`Layouts directory does not exist: ${layoutsDir}`);
297
- }
298
- const stat = statSync(layoutsDir);
299
- if (!stat.isDirectory()) {
300
- throw new Error(`Path is not a directory: ${layoutsDir}`);
301
- }
302
- const files = await fg(["**/*.ts", "**/*.tsx"], {
303
- cwd: layoutsDir,
304
- ignore: ["**/_*", "**/*.d.ts"]
305
- });
306
- const layouts = files.filter((file) => {
307
- const name = basename(file);
308
- if (name.startsWith("_")) return false;
309
- if (name.endsWith(".d.ts")) return false;
310
- if (!name.endsWith(".ts") && !name.endsWith(".tsx")) return false;
311
- return true;
312
- }).map((file) => {
313
- const name = basename(file).replace(/\.(tsx?|ts)$/, "");
314
- return {
315
- name,
316
- file: join2(layoutsDir, file)
317
- };
318
- });
319
- return layouts;
320
- }
321
- function resolveLayout(layoutName, layouts) {
322
- return layouts.find((l) => l.name === layoutName);
323
- }
324
- async function loadLayout(layoutFile) {
325
- try {
326
- const module = await import(layoutFile);
327
- const exported = module.default || module;
328
- if (!isLayoutProgram(exported)) {
329
- throw new Error(`File is not a valid layout: ${layoutFile}`);
330
- }
331
- return exported;
332
- } catch (error) {
333
- if (error instanceof Error && error.message.includes("not a valid layout")) {
334
- throw error;
335
- }
336
- throw new Error(`Failed to load layout: ${layoutFile}`);
337
- }
338
- }
339
- var LayoutResolver = class {
340
- layoutsDir;
341
- layouts = [];
342
- loadedLayouts = /* @__PURE__ */ new Map();
343
- initialized = false;
344
- constructor(layoutsDir) {
345
- this.layoutsDir = layoutsDir;
346
- }
347
- /**
348
- * Initialize the resolver by scanning the layouts directory
349
- */
350
- async initialize() {
351
- try {
352
- this.layouts = await scanLayouts(this.layoutsDir);
353
- this.initialized = true;
354
- } catch {
355
- this.layouts = [];
356
- this.initialized = true;
357
- }
358
- }
359
- /**
360
- * Check if a layout exists
361
- */
362
- hasLayout(name) {
363
- return this.layouts.some((l) => l.name === name);
364
- }
365
- /**
366
- * Get a layout by name
367
- *
368
- * @param name - Layout name
369
- * @returns The layout program or undefined if not found
370
- */
371
- async getLayout(name) {
372
- const cached = this.loadedLayouts.get(name);
373
- if (cached) {
374
- return cached;
375
- }
376
- const scanned = resolveLayout(name, this.layouts);
377
- if (!scanned) {
378
- return void 0;
379
- }
380
- const layout = await loadLayout(scanned.file);
381
- this.loadedLayouts.set(name, layout);
382
- return layout;
383
- }
384
- /**
385
- * Compose a page with its layout
386
- *
387
- * @param page - Page program to compose
388
- * @returns Composed program (or original if no layout)
389
- * @throws Error if specified layout is not found
390
- */
391
- async composeWithLayout(page) {
392
- const layoutName = page.route?.layout;
393
- if (!layoutName) {
394
- return page;
395
- }
396
- if (!this.hasLayout(layoutName)) {
397
- const available = this.layouts.map((l) => l.name).join(", ");
398
- throw new Error(
399
- `Layout '${layoutName}' not found. Available layouts: ${available || "none"}`
400
- );
401
- }
402
- const layout = await this.getLayout(layoutName);
403
- if (!layout) {
404
- throw new Error(`Layout '${layoutName}' not found`);
405
- }
406
- return page;
407
- }
408
- /**
409
- * Get all scanned layouts
410
- */
411
- getAll() {
412
- return [...this.layouts];
413
- }
414
- };
415
-
416
- // src/data/loader.ts
417
- import { existsSync as existsSync2, readFileSync } from "fs";
418
- import { basename as basename2, extname, join as join3 } from "path";
419
- import fg2 from "fast-glob";
420
-
421
- // src/build/mdx.ts
422
- import { unified } from "unified";
423
- import remarkParse from "remark-parse";
424
- import remarkMdx from "remark-mdx";
425
- import remarkGfm from "remark-gfm";
426
- import matter from "gray-matter";
427
- function lit(value) {
428
- return { expr: "lit", value };
429
- }
430
- function textNode(value) {
431
- return { kind: "text", value: lit(value) };
432
- }
433
- function elementNode(tag, props, children) {
434
- const node = { kind: "element", tag };
435
- if (props && Object.keys(props).length > 0) {
436
- node.props = props;
437
- }
438
- if (children && children.length > 0) {
439
- node.children = children;
440
- }
441
- return node;
442
- }
443
- function codeNode(language, content) {
444
- return {
445
- kind: "code",
446
- language: lit(language),
447
- content: lit(content)
448
- };
449
- }
450
- function wrapNodes(nodes) {
451
- if (nodes.length === 0) {
452
- return elementNode("div");
453
- }
454
- if (nodes.length === 1 && nodes[0]) {
455
- return nodes[0];
456
- }
457
- return elementNode("div", void 0, nodes);
458
- }
459
- function isCustomComponent(name) {
460
- if (!name) return false;
461
- return /^[A-Z]/.test(name);
462
- }
463
- var DISALLOWED_PATTERNS = [
464
- /\bfunction\b/i,
465
- /\b(eval|Function|setTimeout|setInterval)\b/,
466
- /\bimport\b/,
467
- /\brequire\b/,
468
- /\bfetch\b/,
469
- /\bwindow\b/,
470
- /\bdocument\b/,
471
- /\bglobal\b/,
472
- /\bprocess\b/,
473
- /\b__proto__\b/,
474
- /\bconstructor\b/,
475
- /\bprototype\b/
476
- ];
477
- function isSafeLiteral(value) {
478
- return !DISALLOWED_PATTERNS.some((pattern) => pattern.test(value));
479
- }
480
- function safeEvalLiteral(value) {
481
- try {
482
- return JSON.parse(value);
483
- } catch {
484
- }
485
- if (!isSafeLiteral(value)) {
486
- return null;
487
- }
488
- try {
489
- const fn = new Function(`return (${value});`);
490
- return fn();
491
- } catch {
492
- return null;
493
- }
494
- }
495
- function parseAttributeValue(attr) {
496
- if (attr.value === null) {
497
- return lit(true);
498
- }
499
- if (typeof attr.value === "string") {
500
- return lit(attr.value);
501
- }
502
- if (attr.value.type === "mdxJsxAttributeValueExpression") {
503
- const exprValue = attr.value.value.trim();
504
- if (exprValue === "true") return lit(true);
505
- if (exprValue === "false") return lit(false);
506
- if (exprValue === "null") return lit(null);
507
- const num = Number(exprValue);
508
- if (!Number.isNaN(num)) return lit(num);
509
- if (exprValue.startsWith("[") || exprValue.startsWith("{")) {
510
- const parsed = safeEvalLiteral(exprValue);
511
- if (parsed !== null && parsed !== void 0) {
512
- return lit(parsed);
513
- }
514
- }
515
- return lit(exprValue);
516
- }
517
- return lit(null);
518
- }
519
- function transformNode(node, ctx) {
520
- switch (node.type) {
521
- case "heading":
522
- return elementNode(
523
- `h${node.depth}`,
524
- void 0,
525
- transformChildren(node.children, ctx)
526
- );
527
- case "paragraph":
528
- return elementNode("p", void 0, transformChildren(node.children, ctx));
529
- case "text":
530
- return textNode(node.value);
531
- case "emphasis":
532
- return elementNode("em", void 0, transformChildren(node.children, ctx));
533
- case "strong":
534
- return elementNode("strong", void 0, transformChildren(node.children, ctx));
535
- case "link": {
536
- const props = {
537
- href: lit(node.url)
538
- };
539
- if (node["title"]) {
540
- props["title"] = lit(node["title"]);
541
- }
542
- return elementNode("a", props, transformChildren(node.children, ctx));
543
- }
544
- case "inlineCode":
545
- return elementNode("code", void 0, [textNode(node.value)]);
546
- case "code": {
547
- const lang = node.lang || "text";
548
- return codeNode(lang, node.value);
549
- }
550
- case "blockquote":
551
- return elementNode("blockquote", void 0, transformChildren(node.children, ctx));
552
- case "list": {
553
- const tag = node.ordered ? "ol" : "ul";
554
- return elementNode(tag, void 0, transformChildren(node.children, ctx));
555
- }
556
- case "listItem": {
557
- const children = [];
558
- for (const child of node.children) {
559
- if (child.type === "paragraph") {
560
- children.push(...transformChildren(child.children, ctx));
561
- } else {
562
- const transformed = transformNode(child, ctx);
563
- if (transformed) {
564
- if (Array.isArray(transformed)) {
565
- children.push(...transformed);
566
- } else {
567
- children.push(transformed);
568
- }
569
- }
570
- }
571
- }
572
- return elementNode("li", void 0, children);
573
- }
574
- case "thematicBreak":
575
- return elementNode("hr");
576
- case "break":
577
- return elementNode("br");
578
- case "image": {
579
- const props = {
580
- src: lit(node.url)
581
- };
582
- if (node["alt"]) {
583
- props["alt"] = lit(node["alt"]);
584
- }
585
- if (node["title"]) {
586
- props["title"] = lit(node["title"]);
587
- }
588
- return elementNode("img", props);
589
- }
590
- case "html":
591
- return textNode(node.value);
592
- // MDX JSX elements
593
- case "mdxJsxFlowElement":
594
- case "mdxJsxTextElement":
595
- return transformJsxElement(node, ctx);
596
- // MDX expressions
597
- case "mdxFlowExpression":
598
- case "mdxTextExpression": {
599
- const exprNode = node;
600
- const value = exprNode.value.trim();
601
- if (value === "") return null;
602
- if (value === "true") return textNode("true");
603
- if (value === "false") return textNode("false");
604
- if (value === "null") return textNode("null");
605
- const num = Number(value);
606
- if (!Number.isNaN(num)) return textNode(String(num));
607
- return textNode(value);
608
- }
609
- // GFM extensions
610
- case "table":
611
- return elementNode("table", void 0, transformChildren(node.children, ctx));
612
- case "tableRow":
613
- return elementNode("tr", void 0, transformChildren(node.children, ctx));
614
- case "tableCell":
615
- return elementNode("td", void 0, transformChildren(node.children, ctx));
616
- case "delete":
617
- return elementNode("del", void 0, transformChildren(node.children, ctx));
618
- default:
619
- return null;
620
- }
621
- }
622
- function transformJsxElement(node, ctx) {
623
- const name = node.name;
624
- if (!name) {
625
- const children2 = transformChildren(node.children, ctx);
626
- return wrapNodes(children2);
627
- }
628
- if (isCustomComponent(name)) {
629
- const def = ctx.components[name];
630
- if (!def) {
631
- throw new Error(`Undefined component: ${name}`);
632
- }
633
- const props2 = {};
634
- for (const attr of node.attributes) {
635
- if (attr.type === "mdxJsxAttribute") {
636
- props2[attr.name] = parseAttributeValue(attr);
637
- }
638
- }
639
- const children2 = transformChildren(node.children, ctx);
640
- return applyComponentView(def.view, props2, children2);
641
- }
642
- const props = {};
643
- for (const attr of node.attributes) {
644
- if (attr.type === "mdxJsxAttribute") {
645
- props[attr.name] = parseAttributeValue(attr);
646
- }
647
- }
648
- const children = transformChildren(node.children, ctx);
649
- return elementNode(name, props, children);
650
- }
651
- function substituteExpression(expr, props) {
652
- const exprAny = expr;
653
- if (exprAny.expr === "param") {
654
- const paramExpr = expr;
655
- const propValue = props[paramExpr.name];
656
- if (!propValue) {
657
- return { expr: "lit", value: null };
658
- }
659
- if (paramExpr.path && propValue.expr === "var") {
660
- const varExpr = propValue;
661
- return {
662
- expr: "var",
663
- name: varExpr.name,
664
- path: paramExpr.path
665
- };
666
- }
667
- return propValue;
668
- }
669
- if (expr.expr === "bin") {
670
- const binExpr = expr;
671
- return {
672
- expr: "bin",
673
- op: binExpr.op,
674
- left: substituteExpression(binExpr.left, props),
675
- right: substituteExpression(binExpr.right, props)
676
- };
677
- }
678
- if (expr.expr === "not") {
679
- const notExpr = expr;
680
- return {
681
- expr: "not",
682
- operand: substituteExpression(notExpr.operand, props)
683
- };
684
- }
685
- if (expr.expr === "cond") {
686
- const condExpr = expr;
687
- return {
688
- expr: "cond",
689
- if: substituteExpression(condExpr.if, props),
690
- then: substituteExpression(condExpr.then, props),
691
- else: substituteExpression(condExpr.else, props)
692
- };
693
- }
694
- if (expr.expr === "get") {
695
- const getExpr = expr;
696
- return {
697
- expr: "get",
698
- base: substituteExpression(getExpr.base, props),
699
- path: getExpr.path
700
- };
701
- }
702
- return expr;
703
- }
704
- function applyComponentView(view, props, children) {
705
- return substituteInNode(view, props, children);
706
- }
707
- function substituteInNode(node, props, children) {
708
- switch (node.kind) {
709
- case "each": {
710
- const eachNode = node;
711
- const result = {
712
- kind: "each",
713
- items: substituteExpression(eachNode.items, props),
714
- as: eachNode.as,
715
- body: substituteInNode(eachNode.body, props, children)
716
- };
717
- if (eachNode.index) {
718
- result.index = eachNode.index;
719
- }
720
- if (eachNode.key) {
721
- result.key = substituteExpression(eachNode.key, props);
722
- }
723
- return result;
724
- }
725
- case "text": {
726
- const textNode2 = node;
727
- return {
728
- kind: "text",
729
- value: substituteExpression(textNode2.value, props)
730
- };
731
- }
732
- case "if": {
733
- const ifNode = node;
734
- const result = {
735
- kind: "if",
736
- condition: substituteExpression(ifNode.condition, props),
737
- then: substituteInNode(ifNode.then, props, children)
738
- };
739
- if (ifNode.else) {
740
- result.else = substituteInNode(ifNode.else, props, children);
741
- }
742
- return result;
743
- }
744
- case "element": {
745
- const elem = node;
746
- const newProps = {};
747
- if (elem.props) {
748
- for (const [key, value] of Object.entries(elem.props)) {
749
- newProps[key] = substituteExpression(value, props);
750
- }
751
- }
752
- let newChildren;
753
- if (elem.children) {
754
- newChildren = [];
755
- for (const child of elem.children) {
756
- if (child.kind === "slot") {
757
- newChildren.push(...children);
758
- } else {
759
- newChildren.push(substituteInNode(child, props, children));
760
- }
761
- }
762
- }
763
- return elementNode(
764
- elem.tag,
765
- Object.keys(newProps).length > 0 ? newProps : void 0,
766
- newChildren && newChildren.length > 0 ? newChildren : void 0
767
- );
768
- }
769
- case "markdown":
770
- case "code":
771
- return node;
772
- default:
773
- return node;
774
- }
775
- }
776
- function transformChildren(children, ctx) {
777
- const result = [];
778
- for (const child of children) {
779
- const transformed = transformNode(child, ctx);
780
- if (transformed) {
781
- if (Array.isArray(transformed)) {
782
- result.push(...transformed);
783
- } else {
784
- result.push(transformed);
785
- }
786
- }
787
- }
788
- return result;
789
- }
790
- function transformRoot(root, ctx) {
791
- const nodes = transformChildren(root.children, ctx);
792
- return wrapNodes(nodes);
793
- }
794
- async function mdxToConstela(source, options) {
795
- const { content, data: _frontmatter } = matter(source);
796
- const processor = unified().use(remarkParse).use(remarkGfm).use(remarkMdx);
797
- const tree = processor.parse(content);
798
- const ctx = {
799
- components: options?.components ?? {}
800
- };
801
- const view = transformRoot(tree, ctx);
802
- return {
803
- version: "1.0",
804
- state: {},
805
- actions: {},
806
- view
807
- };
808
- }
809
- async function mdxContentToNode(content, options) {
810
- const processor = unified().use(remarkParse).use(remarkGfm).use(remarkMdx);
811
- const tree = processor.parse(content);
812
- const ctx = {
813
- components: options?.components ?? {}
814
- };
815
- return transformRoot(tree, ctx);
816
- }
817
-
818
- // src/data/loader.ts
819
- var mdxContentToNode2 = mdxContentToNode;
820
- function parseYaml(content) {
821
- const result = {};
822
- const lines = content.split("\n");
823
- const stack = [{ indent: -2, obj: result }];
824
- for (let i = 0; i < lines.length; i++) {
825
- const line = lines[i];
826
- if (!line || line.trim() === "" || line.trim().startsWith("#")) continue;
827
- const arrayMatch = line.match(/^(\s*)-\s*(.*)$/);
828
- if (arrayMatch) {
829
- const [, indentStr2, rest] = arrayMatch;
830
- const indent2 = indentStr2?.length ?? 0;
831
- while (stack.length > 1 && indent2 <= stack[stack.length - 1].indent) {
832
- stack.pop();
833
- }
834
- const parent = stack[stack.length - 1];
835
- const key2 = parent.key;
836
- if (key2) {
837
- if (!Array.isArray(parent.obj[key2])) {
838
- parent.obj[key2] = [];
839
- }
840
- const arr = parent.obj[key2];
841
- const objMatch = rest?.match(/^([\w-]+):\s*(.*)$/);
842
- if (objMatch) {
843
- const [, k, v] = objMatch;
844
- const newObj = {};
845
- if (v?.trim()) {
846
- newObj[k] = parseValue(v);
847
- }
848
- arr.push(newObj);
849
- stack.push({ indent: indent2, obj: newObj, key: k, isArray: true });
850
- } else if (rest?.trim()) {
851
- arr.push(parseValue(rest.trim()));
852
- }
853
- }
854
- continue;
855
- }
856
- const match = line.match(/^(\s*)([\w-]+):\s*(.*)$/);
857
- if (!match) continue;
858
- const [, indentStr, key, value] = match;
859
- const indent = indentStr?.length ?? 0;
860
- while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
861
- stack.pop();
862
- }
863
- let targetObj;
864
- const currentTop = stack[stack.length - 1];
865
- if (currentTop.isArray) {
866
- targetObj = currentTop.obj;
867
- } else if (currentTop.key) {
868
- if (!currentTop.obj[currentTop.key]) {
869
- currentTop.obj[currentTop.key] = {};
870
- }
871
- targetObj = currentTop.obj[currentTop.key];
872
- } else {
873
- targetObj = currentTop.obj;
874
- }
875
- if (value?.trim() === "" || value === void 0) {
876
- const newObj = {};
877
- targetObj[key] = newObj;
878
- stack.push({ indent, obj: targetObj, key });
879
- } else {
880
- targetObj[key] = parseValue(value);
881
- }
882
- }
883
- return result;
884
- }
885
- function parseValue(value) {
886
- const trimmed = value.trim();
887
- if (trimmed === "true") return true;
888
- if (trimmed === "false") return false;
889
- if (trimmed === "null" || trimmed === "~") return null;
890
- if (/^-?\d+$/.test(trimmed)) return parseInt(trimmed, 10);
891
- if (/^-?\d+\.\d+$/.test(trimmed)) return parseFloat(trimmed);
892
- if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
893
- return trimmed.slice(1, -1);
894
- }
895
- return trimmed;
896
- }
897
- function loadComponentDefinitions(baseDir, componentsPath) {
898
- const fullPath = join3(baseDir, componentsPath);
899
- const resolvedBase = join3(baseDir, "");
900
- const resolvedPath = join3(fullPath, "");
901
- if (!resolvedPath.startsWith(resolvedBase)) {
902
- throw new Error(`Invalid component path: path traversal detected`);
903
- }
904
- if (!existsSync2(fullPath)) {
905
- throw new Error(`MDX components file not found: ${fullPath}`);
906
- }
907
- const content = readFileSync(fullPath, "utf-8");
908
- try {
909
- return JSON.parse(content);
910
- } catch {
911
- throw new Error(`Invalid JSON in MDX components file: ${fullPath}`);
912
- }
913
- }
914
- async function transformMdx(content, file, options) {
915
- const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
916
- let frontmatter = {};
917
- let mdxContent;
918
- if (match) {
919
- frontmatter = parseYaml(match[1]);
920
- mdxContent = match[2].trim();
921
- } else {
922
- mdxContent = content.trim();
923
- }
924
- const compiledContent = await mdxContentToNode(
925
- mdxContent,
926
- options?.components ? { components: options.components } : void 0
927
- );
928
- const fmSlug = frontmatter["slug"];
929
- const slug = typeof fmSlug === "string" ? fmSlug : basename2(file, extname(file));
930
- return {
931
- file,
932
- raw: content,
933
- frontmatter,
934
- content: compiledContent,
935
- slug
936
- };
937
- }
938
- function transformYaml(content) {
939
- return parseYaml(content);
940
- }
941
- function transformCsv(content) {
942
- const lines = content.trim().split("\n");
943
- if (lines.length === 0) return [];
944
- const headerLine = lines[0];
945
- const headers = parseCSVLine(headerLine);
946
- const result = [];
947
- for (let i = 1; i < lines.length; i++) {
948
- const line = lines[i];
949
- if (line.trim() === "") continue;
950
- const values = parseCSVLine(line);
951
- const row = {};
952
- for (let j = 0; j < headers.length; j++) {
953
- row[headers[j].trim()] = (values[j] ?? "").trim();
954
- }
955
- result.push(row);
956
- }
957
- return result;
958
- }
959
- function parseCSVLine(line) {
960
- const result = [];
961
- let current = "";
962
- let inQuotes = false;
963
- for (let i = 0; i < line.length; i++) {
964
- const char = line[i];
965
- if (char === '"') {
966
- inQuotes = !inQuotes;
967
- } else if (char === "," && !inQuotes) {
968
- result.push(current);
969
- current = "";
970
- } else {
971
- current += char;
972
- }
973
- }
974
- result.push(current);
975
- return result;
976
- }
977
- function applyTransform(content, transform, filename) {
978
- if (!transform) {
979
- if (filename.endsWith(".json")) {
980
- return JSON.parse(content);
981
- }
982
- return content;
983
- }
984
- switch (transform) {
985
- case "mdx":
986
- throw new Error("MDX transform for single files is not supported via loadFile. Use loadGlob instead.");
987
- case "yaml":
988
- return transformYaml(content);
989
- case "csv":
990
- return transformCsv(content);
991
- default:
992
- return content;
993
- }
994
- }
995
- async function loadGlob(baseDir, pattern, transform, options) {
996
- const files = await fg2(pattern, { cwd: baseDir });
997
- if (transform === "mdx") {
998
- const results2 = [];
999
- for (const file of files) {
1000
- const fullPath = join3(baseDir, file);
1001
- const content = readFileSync(fullPath, "utf-8");
1002
- const transformed = await transformMdx(content, file, options);
1003
- results2.push(transformed);
1004
- }
1005
- return results2;
1006
- }
1007
- const results = [];
1008
- for (const file of files) {
1009
- const fullPath = join3(baseDir, file);
1010
- const content = readFileSync(fullPath, "utf-8");
1011
- results.push({
1012
- file,
1013
- raw: content
1014
- });
1015
- }
1016
- return results;
1017
- }
1018
- async function loadFile(baseDir, filePath, transform) {
1019
- const fullPath = join3(baseDir, filePath);
1020
- if (!existsSync2(fullPath)) {
1021
- throw new Error(`File not found: ${fullPath}`);
1022
- }
1023
- const content = readFileSync(fullPath, "utf-8");
1024
- return applyTransform(content, transform, filePath);
1025
- }
1026
- async function loadApi(url, transform) {
1027
- try {
1028
- const response = await fetch(url);
1029
- if (!response.ok) {
1030
- throw new Error(`api request failed: ${response.status} ${response.statusText}`);
1031
- }
1032
- if (transform === "csv") {
1033
- const text = await response.text();
1034
- return transformCsv(text);
1035
- }
1036
- return await response.json();
1037
- } catch (error) {
1038
- if (error instanceof Error && error.message.includes("api request failed")) {
1039
- throw error;
1040
- }
1041
- throw new Error(`Network error: ${error.message}`);
1042
- }
1043
- }
1044
- function evaluateParamExpression(expr, item) {
1045
- switch (expr.expr) {
1046
- case "lit":
1047
- return String(expr.value);
1048
- case "var":
1049
- if (expr.name === "item") {
1050
- if (expr.path) {
1051
- return getNestedValue(item, expr.path);
1052
- }
1053
- return String(item);
1054
- }
1055
- return "";
1056
- case "get":
1057
- if (expr.base.expr === "var" && expr.base.name === "item") {
1058
- return getNestedValue(item, expr.path);
1059
- }
1060
- return "";
1061
- default:
1062
- return "";
1063
- }
1064
- }
1065
- function getNestedValue(obj, path) {
1066
- const parts = path.split(".");
1067
- let current = obj;
1068
- for (const part of parts) {
1069
- if (current === null || current === void 0) return "";
1070
- if (typeof current !== "object") return "";
1071
- current = current[part];
1072
- }
1073
- return current !== void 0 && current !== null ? String(current) : "";
317
+ return { fetch };
1074
318
  }
1075
- async function generateStaticPaths(data, staticPathsDef) {
1076
- const paths = [];
1077
- for (const item of data) {
1078
- const params = {};
1079
- for (const [paramName, paramExpr] of Object.entries(staticPathsDef.params)) {
1080
- params[paramName] = evaluateParamExpression(paramExpr, item);
1081
- }
1082
- paths.push({ params, data: item });
1083
- }
1084
- return paths;
1085
- }
1086
- var DataLoader = class {
1087
- cache = /* @__PURE__ */ new Map();
1088
- componentCache = /* @__PURE__ */ new Map();
1089
- projectRoot;
1090
- constructor(projectRoot) {
1091
- this.projectRoot = projectRoot;
1092
- }
1093
- /**
1094
- * Resolve components from string path or import reference
1095
- */
1096
- resolveComponents(ref, imports) {
1097
- if (typeof ref === "string") {
1098
- if (this.componentCache.has(ref)) {
1099
- return this.componentCache.get(ref);
1100
- }
1101
- const defs = loadComponentDefinitions(this.projectRoot, ref);
1102
- this.componentCache.set(ref, defs);
1103
- return defs;
1104
- }
1105
- if (ref.expr === "import") {
1106
- if (!imports) {
1107
- throw new Error(`Import context required for component reference "${ref.name}"`);
1108
- }
1109
- const imported = imports[ref.name];
1110
- if (!imported || typeof imported !== "object") {
1111
- throw new Error(`Component import "${ref.name}" not found or invalid`);
1112
- }
1113
- return imported;
1114
- }
1115
- return {};
1116
- }
1117
- /**
1118
- * Load a single data source
1119
- */
1120
- async loadDataSource(name, dataSource, context) {
1121
- if (this.cache.has(name)) {
1122
- return this.cache.get(name);
1123
- }
1124
- let componentDefs;
1125
- if (dataSource.transform === "mdx" && dataSource.components) {
1126
- componentDefs = this.resolveComponents(
1127
- dataSource.components,
1128
- context?.imports
1129
- );
1130
- }
1131
- let data;
1132
- switch (dataSource.type) {
1133
- case "glob":
1134
- if (!dataSource.pattern) {
1135
- throw new Error(`Glob data source '${name}' requires pattern`);
1136
- }
1137
- data = await loadGlob(
1138
- this.projectRoot,
1139
- dataSource.pattern,
1140
- dataSource.transform,
1141
- componentDefs ? { components: componentDefs } : void 0
1142
- );
1143
- break;
1144
- case "file":
1145
- if (!dataSource.path) {
1146
- throw new Error(`File data source '${name}' requires path`);
1147
- }
1148
- data = await loadFile(this.projectRoot, dataSource.path, dataSource.transform);
1149
- break;
1150
- case "api":
1151
- if (!dataSource.url) {
1152
- throw new Error(`API data source '${name}' requires url`);
1153
- }
1154
- data = await loadApi(dataSource.url, dataSource.transform);
1155
- break;
1156
- default:
1157
- throw new Error(`Unknown data source type: ${dataSource.type}`);
1158
- }
1159
- this.cache.set(name, data);
1160
- return data;
1161
- }
1162
- /**
1163
- * Load all data sources
1164
- */
1165
- async loadAllDataSources(dataSources) {
1166
- const result = {};
1167
- for (const [name, source] of Object.entries(dataSources)) {
1168
- result[name] = await this.loadDataSource(name, source);
1169
- }
1170
- return result;
1171
- }
1172
- /**
1173
- * Clear cache for a specific data source or all caches
1174
- */
1175
- clearCache(name) {
1176
- if (name) {
1177
- this.cache.delete(name);
1178
- } else {
1179
- this.cache.clear();
1180
- }
1181
- }
1182
- /**
1183
- * Clear all cache entries
1184
- */
1185
- clearAllCache() {
1186
- this.cache.clear();
1187
- }
1188
- /**
1189
- * Get the current cache size
1190
- */
1191
- getCacheSize() {
1192
- return this.cache.size;
1193
- }
1194
- };
1195
319
  export {
1196
320
  DataLoader,
1197
321
  LayoutResolver,
@@ -1211,7 +335,7 @@ export {
1211
335
  loadFile,
1212
336
  loadGlob,
1213
337
  loadLayout,
1214
- mdxContentToNode2 as mdxContentToNode,
338
+ mdxContentToNode,
1215
339
  mdxToConstela,
1216
340
  resolveLayout,
1217
341
  resolvePageExport,