@yannosay/sinth 5.3.2 → 5.3.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +16 -4
  3. package/dist/browser/sinth.js +630 -81
  4. package/dist/cli/index.js +52 -10
  5. package/dist/cli/skill.d.ts +10 -0
  6. package/dist/cli/skill.js +106 -0
  7. package/dist/cli/templates.js +1 -1
  8. package/dist/compiler/codegen.js +42 -5
  9. package/dist/compiler/elements.d.ts +6 -0
  10. package/dist/compiler/elements.js +12 -0
  11. package/dist/compiler/html.d.ts +2 -0
  12. package/dist/compiler/html.js +7 -0
  13. package/dist/compiler/prerender.js +5 -3
  14. package/dist/deploy/cloudflare.d.ts +2 -0
  15. package/dist/deploy/cloudflare.js +103 -18
  16. package/dist/deploy/platforms.d.ts +20 -0
  17. package/dist/deploy/platforms.js +212 -0
  18. package/dist/deploy/redirects.d.ts +31 -0
  19. package/dist/deploy/redirects.js +102 -0
  20. package/dist/project/build.js +104 -18
  21. package/dist/project/config.d.ts +19 -0
  22. package/dist/project/config.js +66 -8
  23. package/dist/project/env.d.ts +11 -0
  24. package/dist/project/env.js +84 -0
  25. package/dist/project/project.d.ts +7 -1
  26. package/dist/project/project.js +37 -10
  27. package/dist/runtime/index.js +48 -8
  28. package/dist/runtime/router.js +17 -1
  29. package/dist/server/dev.d.ts +4 -0
  30. package/dist/server/dev.js +35 -11
  31. package/dist/server/functions-router.d.ts +60 -0
  32. package/dist/server/functions-router.js +161 -0
  33. package/dist/server/functions.d.ts +8 -12
  34. package/dist/server/functions.js +43 -133
  35. package/dist/server/preview.d.ts +3 -0
  36. package/dist/server/preview.js +8 -1
  37. package/dist/server/static.d.ts +9 -0
  38. package/dist/server/static.js +24 -1
  39. package/lib/ui/index.sinth +533 -24
  40. package/package.json +2 -1
  41. package/schema/sinth.config.schema.json +30 -1
  42. package/skills/agents.md +62 -0
  43. package/skills/sinth/SKILL.md +125 -0
  44. package/skills/sinth/references/language.md +175 -0
  45. package/skills/sinth/references/project-and-deploy.md +87 -0
  46. package/skills/sinth/references/ui.md +95 -0
@@ -42,31 +42,73 @@ const fs = __importStar(require("fs"));
42
42
  const path = __importStar(require("path"));
43
43
  const diagnostics_1 = require("../compiler/diagnostics");
44
44
  const html_1 = require("../compiler/html");
45
+ const platforms_1 = require("../deploy/platforms");
46
+ const redirects_1 = require("../deploy/redirects");
47
+ const config_1 = require("./config");
45
48
  const project_1 = require("./project");
46
49
  const ASSET_LOADERS = {
47
50
  ".png": "file", ".jpg": "file", ".jpeg": "file", ".gif": "file", ".webp": "file", ".avif": "file", ".svg": "file",
48
51
  ".ico": "file", ".woff": "file", ".woff2": "file", ".ttf": "file", ".otf": "file", ".eot": "file", ".mp4": "file",
49
52
  ".webm": "file", ".mp3": "file", ".wav": "file", ".txt": "text",
50
53
  };
54
+ /**
55
+ * A short id for a virtual CSS module. esbuild prints module paths in comments in unminified
56
+ * output, so ids never contain absolute paths of the build machine.
57
+ */
58
+ function cssModuleId(project, file) {
59
+ const rel = path.relative(project.root, file);
60
+ if (!rel.startsWith("..") && !path.isAbsolute(rel))
61
+ return rel.split(path.sep).join("/");
62
+ const parts = file.split(/[\\/]/);
63
+ const nm = parts.lastIndexOf("node_modules");
64
+ return nm !== -1 ? parts.slice(nm).join("/") : "external/" + parts.slice(-2).join("/");
65
+ }
51
66
  function sinthPlugin(project, entries, injectCss = false) {
67
+ const cssFiles = new Map();
52
68
  return {
53
69
  name: "sinth",
54
70
  setup(b) {
55
- b.onResolve({ filter: /^sinth-runtime$/ }, () => ({ path: project_1.RUNTIME_PATH }));
56
- b.onResolve({ filter: /^sinth-router$/ }, () => ({ path: project_1.ROUTER_PATH }));
71
+ b.onResolve({ filter: /^sinth-(runtime|router)$/ }, a => ({ path: a.path, namespace: "sinth-builtin" }));
72
+ b.onLoad({ filter: /.*/, namespace: "sinth-builtin" }, a => {
73
+ const file = a.path === "sinth-router" ? project_1.ROUTER_PATH : project_1.RUNTIME_PATH;
74
+ return { contents: fs.readFileSync(file, "utf-8"), loader: "js", resolveDir: path.dirname(file) };
75
+ });
57
76
  b.onResolve({ filter: /^sinth-entry:/ }, a => ({ path: a.path.slice("sinth-entry:".length), namespace: "sinth-entry" }));
58
77
  b.onLoad({ filter: /.*/, namespace: "sinth-entry" }, a => ({ contents: entries.get(a.path) ?? "", loader: "js", resolveDir: project.root }));
59
- b.onResolve({ filter: /^sinth-css:/ }, a => ({ path: a.path.slice("sinth-css:".length), namespace: "sinth-css" }));
60
- b.onLoad({ filter: /.*/, namespace: "sinth-css" }, a => (injectCss
61
- ? { contents: `import { injectCss } from "sinth-runtime";\ninjectCss(${JSON.stringify("sinth-" + a.path.length.toString(36) + "-" + path.basename(a.path))}, ${JSON.stringify(project.compile(a.path).css)});`, loader: "js", resolveDir: path.dirname(a.path) }
62
- : { contents: project.compile(a.path).css, loader: "css", resolveDir: path.dirname(a.path) }));
78
+ b.onResolve({ filter: /^sinth-css:/ }, a => {
79
+ const file = a.path.slice("sinth-css:".length);
80
+ const id = cssModuleId(project, file);
81
+ cssFiles.set(id, file);
82
+ return { path: id, namespace: "sinth-css" };
83
+ });
84
+ b.onLoad({ filter: /.*/, namespace: "sinth-css" }, a => {
85
+ const file = cssFiles.get(a.path) ?? path.resolve(project.root, a.path);
86
+ return injectCss
87
+ ? { contents: `import { injectCss } from "sinth-runtime";\ninjectCss(${JSON.stringify("sinth-css-" + a.path.replace(/[^\w-]+/g, "-"))}, ${JSON.stringify(project.compile(file).css)});`, loader: "js", resolveDir: path.dirname(file) }
88
+ : { contents: project.compile(file).css, loader: "css", resolveDir: path.dirname(file) };
89
+ });
63
90
  if (injectCss) {
64
91
  b.onLoad({ filter: /\.css$/ }, a => ({
65
92
  contents: `import { injectCss } from "sinth-runtime";\ninjectCss(${JSON.stringify("sinth-css-" + path.basename(a.path))}, ${JSON.stringify(fs.readFileSync(a.path, "utf-8"))});`,
66
93
  loader: "js",
67
94
  }));
68
95
  }
69
- b.onLoad({ filter: /\.sinth$/ }, a => ({ contents: project.compile(a.path).js, loader: "js", resolveDir: path.dirname(a.path) }));
96
+ b.onLoad({ filter: /\.sinth$/, namespace: "file" }, a => ({ contents: project.compile(a.path).js, loader: "js", resolveDir: path.dirname(a.path) }));
97
+ // .sinth files outside the project (built-in libraries, linked packages) get a short id too.
98
+ b.onResolve({ filter: /\.sinth$/ }, a => {
99
+ if (a.namespace !== "file" && a.namespace !== "sinth-entry" && a.namespace !== "sinth-module")
100
+ return undefined;
101
+ const file = path.isAbsolute(a.path) ? a.path : path.resolve(a.resolveDir, a.path);
102
+ const id = cssModuleId(project, file);
103
+ if (!id.startsWith("node_modules/") && !id.startsWith("external/"))
104
+ return undefined;
105
+ cssFiles.set(id, file);
106
+ return { path: id, namespace: "sinth-module" };
107
+ });
108
+ b.onLoad({ filter: /.*/, namespace: "sinth-module" }, a => {
109
+ const file = cssFiles.get(a.path);
110
+ return { contents: project.compile(file).js, loader: "js", resolveDir: path.dirname(file) };
111
+ });
70
112
  b.onLoad({ filter: /\.s[ac]ss$/ }, a => {
71
113
  const scss = project.scss();
72
114
  if (!scss)
@@ -251,9 +293,12 @@ async function buildProject(project, options) {
251
293
  project.invalidate();
252
294
  const pages = project.findPages();
253
295
  if (!pages.length && !findCustomElementFiles(project).length) {
254
- throw new diagnostics_1.SinthError("E0802", fs.existsSync(cfg.pagesDir) ? `No pages found in ${path.relative(project.root, cfg.pagesDir) || "."}` : `No pages found (no ${path.relative(project.root, cfg.pagesDir) || "pages"}/ folder, and no .sinth file with markup in the project root)`, undefined, fs.existsSync(cfg.pagesDir)
255
- ? "Every .sinth file in this folder is a page (files starting with '_' are skipped). Add markup to pages/index.sinth, for example: Main { Heading { \"Hello\" } }"
256
- : `Create ${path.relative(project.root, cfg.pagesDir) || "pages"}/index.sinth with some markup, for example: Main { Heading { "Hello" } }`);
296
+ const rel = (p) => path.relative(project.root, p).split(path.sep).join("/");
297
+ const pagesRel = rel(cfg.pagesDir) || "pages";
298
+ const where = rel(cfg.srcDir) ? rel(cfg.srcDir) + "/" : "the project root";
299
+ throw new diagnostics_1.SinthError("E0802", fs.existsSync(cfg.pagesDir) ? `No pages found in ${pagesRel}` : `No pages found (no ${pagesRel}/ folder, and no .sinth file with markup in ${where})`, undefined, fs.existsSync(cfg.pagesDir)
300
+ ? `Every .sinth file in this folder is a page (files starting with '_' are skipped). Add markup to ${pagesRel}/index.sinth, for example: Main { Heading { "Hello" } }`
301
+ : `Create ${pagesRel}/index.sinth with some markup, for example: Main { Heading { "Hello" } }`);
257
302
  }
258
303
  const compiled = pages.map(p => project.compilePage(p));
259
304
  const entries = new Map();
@@ -315,6 +360,7 @@ async function buildProject(project, options) {
315
360
  }
316
361
  const csp = contentSecurityPolicy(compiled, cfg.security.csp);
317
362
  const pageOutputs = [];
363
+ const summaries = [];
318
364
  const toUrl = (abs) => cfg.base + path.relative(cfg.outDir, path.resolve(project.root, abs)).replace(/\\/g, "/");
319
365
  for (const c of compiled) {
320
366
  const key = entryKey(c.page);
@@ -350,6 +396,7 @@ async function buildProject(project, options) {
350
396
  files.delete(path.relative(cfg.outDir, path.resolve(project.root, jsOut)).replace(/\\/g, "/"));
351
397
  for (const inst of c.instances) {
352
398
  const head = (0, html_1.buildHead)(inst.meta, v => project.resolveAsset(v, c.page.file));
399
+ summaries.push({ route: inst.page.route, title: head.title, description: head.metaNames.find(([k]) => k === "description")?.[1] });
353
400
  const pageHead = inst.params && c.interactive
354
401
  ? [...inlineHead, '<script type="application/json" id="sinth-params">' + JSON.stringify(inst.params).replace(/</g, "\\u003c") + "</script>"]
355
402
  : inlineHead;
@@ -367,18 +414,40 @@ async function buildProject(project, options) {
367
414
  if (!project.dev) {
368
415
  copyDir(cfg.publicDir, cfg.outDir, files, cfg.outDir);
369
416
  for (const d of cfg.staticDirs)
370
- copyDir(path.resolve(project.root, d), path.join(cfg.outDir, d), files, cfg.outDir);
371
- if (cfg.security.headers && !files.has("_headers")) {
372
- const lines = ["/*", " X-Content-Type-Options: nosniff", " Referrer-Policy: strict-origin-when-cross-origin", " X-Frame-Options: SAMEORIGIN", " Cross-Origin-Opener-Policy: same-origin"];
373
- if (csp)
374
- lines.push(` Content-Security-Policy: ${csp}`);
375
- lines.push("", `${cfg.base}_sinth/*`, " Cache-Control: public, max-age=31536000, immutable", "");
376
- files.set("_headers", { path: path.join(cfg.outDir, "_headers"), contents: Buffer.from(lines.join("\n")) });
417
+ copyDir((0, config_1.staticDirPath)(cfg, d), path.join(cfg.outDir, d), files, cfg.outDir);
418
+ if ((0, platforms_1.readsHeadersFile)(cfg.platform)) {
419
+ // Sinth's rules come first; a _headers file from public/ is appended so both apply.
420
+ const own = (cfg.security.headers ? (0, platforms_1.headersFile)((0, platforms_1.securityHeaders)(csp), cfg.base) : "") + (0, redirects_1.headerRulesFile)(cfg.headers, cfg.base);
421
+ const user = files.get("_headers");
422
+ if (own.trim())
423
+ files.set("_headers", { path: path.join(cfg.outDir, "_headers"), contents: Buffer.from(own + (user ? "\n" + Buffer.from(user.contents).toString("utf-8") : "")) });
377
424
  }
425
+ if (cfg.redirects.length) {
426
+ if (cfg.platform === "github-pages") {
427
+ for (const r of cfg.redirects) {
428
+ if ((0, redirects_1.isPattern)(r.from))
429
+ continue;
430
+ const rel = r.from.replace(/^\/+|\/+$/g, "");
431
+ const target = r.to.startsWith("/") && !r.to.startsWith("//") ? cfg.base + r.to.slice(1) : r.to;
432
+ const out = (rel ? rel + "/" : "") + "index.html";
433
+ if (!files.has(out))
434
+ files.set(out, { path: path.join(cfg.outDir, out), contents: Buffer.from((0, redirects_1.redirectPage)(target)) });
435
+ }
436
+ }
437
+ else if (cfg.platform !== "vercel") {
438
+ const user = files.get("_redirects");
439
+ files.set("_redirects", { path: path.join(cfg.outDir, "_redirects"), contents: Buffer.from((0, redirects_1.redirectsFile)(cfg.redirects, cfg.base) + (user ? Buffer.from(user.contents).toString("utf-8") : "")) });
440
+ }
441
+ }
442
+ // GitHub Pages runs Jekyll by default, which drops folders starting with "_" such as _sinth/.
443
+ if (cfg.platform === "github-pages" && !files.has(".nojekyll"))
444
+ files.set(".nojekyll", { path: path.join(cfg.outDir, ".nojekyll"), contents: Buffer.alloc(0) });
378
445
  if (cfg.site) {
379
446
  const site = cfg.site.replace(/\/$/, "");
380
447
  const urls = pageOutputs.filter(p => !/(^|\/)404$/.test(p.page.route)).map(p => ` <url><loc>${(0, html_1.escapeHtml)(site + p.page.route)}</loc></url>`);
381
448
  files.set("sitemap.xml", { path: path.join(cfg.outDir, "sitemap.xml"), contents: Buffer.from(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join("\n")}\n</urlset>\n`) });
449
+ if (!files.has("llms.txt"))
450
+ files.set("llms.txt", { path: path.join(cfg.outDir, "llms.txt"), contents: Buffer.from(llmsTxt(site, summaries)) });
382
451
  if (!files.has("robots.txt"))
383
452
  files.set("robots.txt", { path: path.join(cfg.outDir, "robots.txt"), contents: Buffer.from(`User-agent: *\nAllow: /\n\nSitemap: ${site}/sitemap.xml\n`) });
384
453
  }
@@ -390,15 +459,32 @@ async function buildProject(project, options) {
390
459
  fs.writeFileSync(f.path, f.contents);
391
460
  }
392
461
  }
462
+ const platformWarnings = project.dev ? [] : await (0, platforms_1.writePlatformOutput)(project, files, cfg.security.headers ? (0, platforms_1.securityHeaders)(csp) : {}, options.write);
393
463
  const bundlerWarnings = result.warnings.map(w => ({
394
464
  severity: "warning",
395
465
  code: "W0800",
396
466
  message: w.text,
397
467
  loc: w.location?.file && !w.location.file.endsWith(".sinth") ? { file: path.resolve(project.root, w.location.file.replace(/^[a-z-]+:/, "")), line: w.location.line, col: w.location.column + 1 } : undefined,
398
468
  }));
399
- const warnings = dedupeWarnings([...compiled.flatMap(c => c.warnings), ...bundlerWarnings]);
469
+ const warnings = dedupeWarnings([...compiled.flatMap(c => c.warnings), ...bundlerWarnings, ...platformWarnings]);
400
470
  return { pages: pageOutputs, files, warnings, durationMs: Date.now() - started };
401
471
  }
472
+ /**
473
+ * An llms.txt (https://llmstxt.org) index of the site for AI assistants and answer engines: the home
474
+ * page's title and description, then one line per page.
475
+ */
476
+ function llmsTxt(site, pages) {
477
+ const visible = pages.filter(p => !/(^|\/)404$/.test(p.route)).sort((a, b) => a.route.localeCompare(b.route));
478
+ const home = visible.find(p => p.route === "/");
479
+ const oneLine = (s) => s.replace(/\s+/g, " ").trim();
480
+ const lines = [`# ${oneLine(home?.title ?? new URL(site).hostname)}`, ""];
481
+ if (home?.description)
482
+ lines.push(`> ${oneLine(home.description)}`, "");
483
+ lines.push("## Pages", "");
484
+ for (const p of visible)
485
+ lines.push(`- [${oneLine(p.title ?? p.route)}](${site}${p.route})${p.description ? ": " + oneLine(p.description) : ""}`);
486
+ return lines.join("\n") + "\n";
487
+ }
402
488
  function dedupeWarnings(list) {
403
489
  const seen = new Set();
404
490
  return list.filter(d => {
@@ -1,3 +1,4 @@
1
+ import { HeaderRules, Redirect } from "../deploy/redirects";
1
2
  export interface CloudflareConfig {
2
3
  projectName?: string;
3
4
  accountId?: string;
@@ -7,7 +8,13 @@ export interface SecurityConfig {
7
8
  headers: boolean;
8
9
  csp: boolean | string;
9
10
  }
11
+ /** Where the site is hosted. Decides which host-specific files the build writes and how `sinth deploy` uploads. */
12
+ export type Platform = "cloudflare" | "cloudflare-workers" | "vercel" | "netlify" | "github-pages" | "static";
13
+ export declare const PLATFORMS: Platform[];
10
14
  export interface SinthConfig {
15
+ platform: Platform;
16
+ /** Folder holding pages, components, libraries and assets: the project root, or app/ (absolute after loading). */
17
+ srcDir: string;
11
18
  outDir: string;
12
19
  pagesDir: string;
13
20
  publicDir: string;
@@ -24,6 +31,11 @@ export interface SinthConfig {
24
31
  router: boolean;
25
32
  security: SecurityConfig;
26
33
  cloudflare: CloudflareConfig;
34
+ /** Normalized from the config's object form (`{ "/old": "/new" }`). */
35
+ redirects: Redirect[];
36
+ headers: HeaderRules;
37
+ /** Extra host names the dev and preview servers answer to (DNS rebinding protection), or true for any. */
38
+ allowedHosts: string[] | true;
27
39
  }
28
40
  export declare const DEFAULT_CONFIG: SinthConfig;
29
41
  export interface LoadedConfig {
@@ -32,3 +44,10 @@ export interface LoadedConfig {
32
44
  warnings: string[];
33
45
  }
34
46
  export declare function loadConfig(root: string, mode: "development" | "production"): LoadedConfig;
47
+ /**
48
+ * Uses app/ as the source folder (like Nuxt) when it exists and the root has no pages/ folder and
49
+ * no .sinth files of its own, so projects that keep everything in the root are unaffected.
50
+ */
51
+ export declare function detectSrcDir(root: string): string;
52
+ /** Resolves a static asset folder (like "assets") inside the source folder. */
53
+ export declare function staticDirPath(config: SinthConfig, dir: string): string;
@@ -33,12 +33,18 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.DEFAULT_CONFIG = void 0;
36
+ exports.DEFAULT_CONFIG = exports.PLATFORMS = void 0;
37
37
  exports.loadConfig = loadConfig;
38
+ exports.detectSrcDir = detectSrcDir;
39
+ exports.staticDirPath = staticDirPath;
38
40
  const fs = __importStar(require("fs"));
39
41
  const path = __importStar(require("path"));
40
42
  const diagnostics_1 = require("../compiler/diagnostics");
43
+ const redirects_1 = require("../deploy/redirects");
44
+ exports.PLATFORMS = ["cloudflare", "cloudflare-workers", "vercel", "netlify", "github-pages", "static"];
41
45
  exports.DEFAULT_CONFIG = {
46
+ platform: "cloudflare",
47
+ srcDir: ".",
42
48
  outDir: "dist",
43
49
  pagesDir: "pages",
44
50
  publicDir: "public",
@@ -54,10 +60,13 @@ exports.DEFAULT_CONFIG = {
54
60
  router: true,
55
61
  security: { headers: true, csp: true },
56
62
  cloudflare: {},
63
+ redirects: [],
64
+ headers: {},
65
+ allowedHosts: [],
57
66
  };
58
67
  const KNOWN_KEYS = new Set([
59
- "outDir", "pagesDir", "publicDir", "staticDirs", "libraryPaths", "site", "base", "minify", "sourcemap", "port", "host",
60
- "previewPort", "target", "router", "security", "cloudflare", "development", "production", "$schema",
68
+ "platform", "srcDir", "outDir", "pagesDir", "publicDir", "staticDirs", "libraryPaths", "site", "base", "minify", "sourcemap", "port", "host",
69
+ "previewPort", "target", "router", "security", "cloudflare", "development", "production", "$schema", "redirects", "headers", "allowedHosts",
61
70
  "sharedRuntime", "inlineJS", "inlineCSS",
62
71
  ]);
63
72
  const LEGACY_KEYS = new Set(["sharedRuntime", "inlineJS", "inlineCSS"]);
@@ -74,7 +83,7 @@ function validate(raw, file, warnings) {
74
83
  };
75
84
  const str = (v) => typeof v === "string";
76
85
  const strArr = (v) => Array.isArray(v) && v.every(x => typeof x === "string");
77
- for (const k of ["outDir", "pagesDir", "publicDir", "site", "base", "host"])
86
+ for (const k of ["srcDir", "outDir", "pagesDir", "publicDir", "site", "base", "host"])
78
87
  check(k, "a string", str);
79
88
  for (const k of ["staticDirs", "libraryPaths", "target"])
80
89
  check(k, "an array of strings", strArr);
@@ -82,7 +91,15 @@ function validate(raw, file, warnings) {
82
91
  check(k, "true or false", v => typeof v === "boolean");
83
92
  for (const k of ["port", "previewPort"])
84
93
  check(k, "a port number (1-65535)", v => Number.isInteger(v) && v > 0 && v < 65536);
94
+ check("platform", `one of ${exports.PLATFORMS.map(p => `"${p}"`).join(", ")}`, v => exports.PLATFORMS.includes(v));
85
95
  check("site", "an absolute URL like https://example.com", v => typeof v === "string" && /^https?:\/\/[^\s]+$/.test(v));
96
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
97
+ check("redirects", 'an object like { "/old": "/new" } (status 301, 302, 303, 307 or 308)', v => isObj(v) && Object.entries(v).every(([from, to]) => from.startsWith("/") && (typeof to === "string" || (isObj(to) && typeof to.to === "string" && (to.status === undefined || redirects_1.REDIRECT_STATUSES.includes(to.status))))));
98
+ check("allowedHosts", "an array of host names or true", v => v === true || (Array.isArray(v) && v.every(x => typeof x === "string")));
99
+ check("headers", 'an object like { "/api/*": { "Cache-Control": "no-store" } }', v => isObj(v) && Object.entries(v).every(([p, h]) => p.startsWith("/") && isObj(h) && Object.entries(h).every(([k, x]) => /^[A-Za-z0-9-]+$/.test(k) && typeof x === "string" && !/[\r\n]/.test(x))));
100
+ }
101
+ function normalizeRedirects(raw) {
102
+ return Object.entries(raw ?? {}).map(([from, to]) => (typeof to === "string" ? { from, to, status: 301 } : { from, to: to.to, status: to.status ?? 301 }));
86
103
  }
87
104
  function loadConfig(root, mode) {
88
105
  const warnings = [];
@@ -113,28 +130,69 @@ function loadConfig(root, mode) {
113
130
  ...stripNested(envOverrides),
114
131
  security: { ...exports.DEFAULT_CONFIG.security, ...(raw.security ?? {}), ...(envOverrides.security ?? {}) },
115
132
  cloudflare: { ...(raw.cloudflare ?? {}) },
133
+ redirects: normalizeRedirects({ ...(raw.redirects ?? {}), ...(envOverrides.redirects ?? {}) }),
134
+ headers: { ...(raw.headers ?? {}), ...(envOverrides.headers ?? {}) },
116
135
  };
117
136
  if (mode === "production" && raw.minify === undefined && envOverrides.minify === undefined)
118
137
  merged.minify = true;
119
138
  if (mode === "development" && raw.sourcemap === undefined && envOverrides.sourcemap === undefined)
120
139
  merged.sourcemap = true;
121
- merged.staticDirs = merged.staticDirs.map(d => d.replace(/^\.\//, ""));
122
- merged.libraryPaths = merged.libraryPaths.map(d => path.resolve(root, d));
140
+ const srcSet = raw.srcDir !== undefined || envOverrides.srcDir !== undefined;
141
+ merged.srcDir = path.resolve(root, srcSet ? merged.srcDir : detectSrcDir(root));
142
+ const src = merged.srcDir;
143
+ merged.staticDirs = merged.staticDirs.map(d => d.replace(/^\.\//, "").replace(/\/+$/, ""));
144
+ merged.libraryPaths = merged.libraryPaths.map(d => path.resolve(src, d));
123
145
  merged.outDir = path.resolve(root, merged.outDir);
124
- merged.pagesDir = path.resolve(root, merged.pagesDir);
146
+ merged.pagesDir = path.resolve(src, merged.pagesDir);
147
+ const publicSet = raw.publicDir !== undefined || envOverrides.publicDir !== undefined;
125
148
  merged.publicDir = path.resolve(root, merged.publicDir);
149
+ // Like Nuxt, public/ normally sits next to app/, but app/public works too.
150
+ if (!publicSet && src !== path.resolve(root) && !isDir(merged.publicDir) && isDir(path.join(src, "public")))
151
+ merged.publicDir = path.join(src, "public");
126
152
  if (!merged.base.startsWith("/"))
127
153
  merged.base = "/" + merged.base;
128
154
  if (!merged.base.endsWith("/"))
129
155
  merged.base += "/";
156
+ if (!isDir(src) && srcSet)
157
+ throw new diagnostics_1.SinthError("E0903", `srcDir '${path.relative(root, src) || "."}' does not exist`, { file, line: 1, col: 1 });
130
158
  if (merged.outDir === path.resolve(root))
131
159
  throw new diagnostics_1.SinthError("E0902", "outDir cannot be the project root", { file, line: 1, col: 1 });
132
160
  return { config: merged, file: fs.existsSync(file) ? file : undefined, warnings };
133
161
  }
162
+ function isDir(p) {
163
+ try {
164
+ return fs.statSync(p).isDirectory();
165
+ }
166
+ catch {
167
+ return false;
168
+ }
169
+ }
170
+ /**
171
+ * Uses app/ as the source folder (like Nuxt) when it exists and the root has no pages/ folder and
172
+ * no .sinth files of its own, so projects that keep everything in the root are unaffected.
173
+ */
174
+ function detectSrcDir(root) {
175
+ if (!isDir(path.join(root, "app")))
176
+ return ".";
177
+ if (isDir(path.join(root, "pages")))
178
+ return ".";
179
+ try {
180
+ if (fs.readdirSync(root).some(f => f.endsWith(".sinth")))
181
+ return ".";
182
+ }
183
+ catch {
184
+ return ".";
185
+ }
186
+ return "app";
187
+ }
188
+ /** Resolves a static asset folder (like "assets") inside the source folder. */
189
+ function staticDirPath(config, dir) {
190
+ return path.resolve(config.srcDir, dir);
191
+ }
134
192
  function stripNested(raw) {
135
193
  const out = {};
136
194
  for (const [k, v] of Object.entries(raw)) {
137
- if (k === "development" || k === "production" || k === "security" || k === "cloudflare" || k === "$schema" || LEGACY_KEYS.has(k))
195
+ if (k === "development" || k === "production" || k === "security" || k === "cloudflare" || k === "redirects" || k === "headers" || k === "$schema" || LEGACY_KEYS.has(k))
138
196
  continue;
139
197
  if (v !== undefined)
140
198
  out[k] = v;
@@ -0,0 +1,11 @@
1
+ /** Only variables with this prefix reach the browser through `import { ... } from "sinth:env"`. */
2
+ export declare const PUBLIC_PREFIX = "PUBLIC_";
3
+ /** Parses a dotenv file: `KEY=value`, `export KEY=value`, quoted values and `#` comments. */
4
+ export declare function parseEnvFile(file: string): Record<string, string>;
5
+ /**
6
+ * Variables from `.env`, `.env.local`, `.env.<mode>` and `.env.<mode>.local` (later files win), with
7
+ * the process environment taking precedence over all files, like Vite and Next.js.
8
+ */
9
+ export declare function loadEnv(root: string, mode: "development" | "production"): Record<string, string>;
10
+ /** The variables that are safe to inline into pages: those starting with PUBLIC_. */
11
+ export declare function publicEnv(root: string, mode: "development" | "production"): Record<string, string>;
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.PUBLIC_PREFIX = void 0;
37
+ exports.parseEnvFile = parseEnvFile;
38
+ exports.loadEnv = loadEnv;
39
+ exports.publicEnv = publicEnv;
40
+ const fs = __importStar(require("fs"));
41
+ const path = __importStar(require("path"));
42
+ /** Only variables with this prefix reach the browser through `import { ... } from "sinth:env"`. */
43
+ exports.PUBLIC_PREFIX = "PUBLIC_";
44
+ /** Parses a dotenv file: `KEY=value`, `export KEY=value`, quoted values and `#` comments. */
45
+ function parseEnvFile(file) {
46
+ const vars = {};
47
+ if (!fs.existsSync(file))
48
+ return vars;
49
+ for (const line of fs.readFileSync(file, "utf-8").split(/\r?\n/)) {
50
+ const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/);
51
+ if (!m)
52
+ continue;
53
+ let value = m[2];
54
+ const quote = value[0];
55
+ const close = quote === '"' || quote === "'" || quote === "`" ? value.indexOf(quote, 1) : -1;
56
+ if (close > 0)
57
+ value = quote === '"' ? value.slice(1, close).replace(/\\n/g, "\n") : value.slice(1, close);
58
+ else
59
+ value = value.replace(/(^|\s+)#.*$/, "");
60
+ vars[m[1]] = value;
61
+ }
62
+ return vars;
63
+ }
64
+ /**
65
+ * Variables from `.env`, `.env.local`, `.env.<mode>` and `.env.<mode>.local` (later files win), with
66
+ * the process environment taking precedence over all files, like Vite and Next.js.
67
+ */
68
+ function loadEnv(root, mode) {
69
+ const merged = {};
70
+ for (const name of [".env", ".env.local", `.env.${mode}`, `.env.${mode}.local`])
71
+ Object.assign(merged, parseEnvFile(path.join(root, name)));
72
+ for (const [k, v] of Object.entries(process.env))
73
+ if (v !== undefined && (k in merged || k.startsWith(exports.PUBLIC_PREFIX)))
74
+ merged[k] = v;
75
+ return merged;
76
+ }
77
+ /** The variables that are safe to inline into pages: those starting with PUBLIC_. */
78
+ function publicEnv(root, mode) {
79
+ const out = {};
80
+ for (const [k, v] of Object.entries(loadEnv(root, mode)))
81
+ if (k.startsWith(exports.PUBLIC_PREFIX))
82
+ out[k] = v;
83
+ return out;
84
+ }
@@ -47,7 +47,8 @@ export declare class Project {
47
47
  invalidate(): void;
48
48
  getFile(file: string): SinthFile;
49
49
  /**
50
- * A file is a page when it lives in the pages folder (or, without one, in the project root),
50
+ * A file is a page when it lives in the pages folder (or, without one, in the source folder: the
51
+ * project root or app/),
51
52
  * is not hidden behind a leading underscore, and is not a pure component module.
52
53
  */
53
54
  private isPageFile;
@@ -68,6 +69,11 @@ export declare class Project {
68
69
  compilePage(page: PageInfo): CompiledPage;
69
70
  private expandParams;
70
71
  private needsRuntime;
72
+ /**
73
+ * `/components/Card.sinth` in an import means the source folder (the root or app/). Files that
74
+ * only exist in the project root (for example styles next to app/) still resolve.
75
+ */
76
+ private rootPath;
71
77
  resolveAsset(value: string, fromFile: string): string;
72
78
  }
73
79
  export declare function routeParams(rel: string): string[];
@@ -43,6 +43,8 @@ const codegen_1 = require("../compiler/codegen");
43
43
  const diagnostics_1 = require("../compiler/diagnostics");
44
44
  const prerender_1 = require("../compiler/prerender");
45
45
  const parser_1 = require("../compiler/parser");
46
+ const config_1 = require("./config");
47
+ const env_1 = require("./env");
46
48
  exports.PACKAGE_ROOT = path.resolve(__dirname, "..", "..");
47
49
  exports.RUNTIME_PATH = path.join(exports.PACKAGE_ROOT, "dist", "runtime", "index.js");
48
50
  exports.ROUTER_PATH = path.join(exports.PACKAGE_ROOT, "dist", "runtime", "router.js");
@@ -92,13 +94,14 @@ class Project {
92
94
  return parsed;
93
95
  }
94
96
  /**
95
- * A file is a page when it lives in the pages folder (or, without one, in the project root),
97
+ * A file is a page when it lives in the pages folder (or, without one, in the source folder: the
98
+ * project root or app/),
96
99
  * is not hidden behind a leading underscore, and is not a pure component module.
97
100
  */
98
101
  isPageFile(abs, parsed) {
99
102
  const pagesDir = this.config.pagesDir;
100
103
  const hasPagesDir = fs.existsSync(pagesDir);
101
- const base = hasPagesDir ? pagesDir : this.root;
104
+ const base = hasPagesDir ? pagesDir : this.config.srcDir;
102
105
  const rel = relativeInside(base, abs);
103
106
  if (!rel)
104
107
  return false;
@@ -124,7 +127,7 @@ class Project {
124
127
  const sass = load("sass");
125
128
  this.scssCompiler = (src, file) => {
126
129
  try {
127
- return sass.compileString(src, { loadPaths: [path.dirname(file), this.root], style: "expanded" }).css;
130
+ return sass.compileString(src, { loadPaths: [path.dirname(file), this.config.srcDir, this.root], style: "expanded" }).css;
128
131
  }
129
132
  catch (err) {
130
133
  throw new diagnostics_1.SinthError("E0402", `SCSS error: ${err.message.split("\n")[0]}`, { file, line: 1, col: 1 });
@@ -141,7 +144,7 @@ class Project {
141
144
  }
142
145
  findPages() {
143
146
  const pagesDir = this.config.pagesDir;
144
- const base = fs.existsSync(pagesDir) ? pagesDir : this.root;
147
+ const base = fs.existsSync(pagesDir) ? pagesDir : this.config.srcDir;
145
148
  const out = [];
146
149
  const walk = (dir) => {
147
150
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
@@ -149,7 +152,7 @@ class Project {
149
152
  if (entry.isDirectory()) {
150
153
  if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith(".") || full === this.config.outDir)
151
154
  continue;
152
- if (base === this.root && ROOT_MODULE_DIRS.has(entry.name))
155
+ if (base === this.config.srcDir && ROOT_MODULE_DIRS.has(entry.name))
153
156
  continue;
154
157
  walk(full);
155
158
  }
@@ -164,7 +167,7 @@ class Project {
164
167
  return out.sort((a, b) => a.route.localeCompare(b.route));
165
168
  }
166
169
  pagesBase() {
167
- return fs.existsSync(this.config.pagesDir) ? this.config.pagesDir : this.root;
170
+ return fs.existsSync(this.config.pagesDir) ? this.config.pagesDir : this.config.srcDir;
168
171
  }
169
172
  pageInfo(file, base = this.pagesBase()) {
170
173
  const rel = path.relative(base, file).replace(/\\/g, "/").replace(/\.sinth$/, "");
@@ -247,6 +250,18 @@ class Project {
247
250
  source = mapped;
248
251
  decl = { ...decl, kind: "sinth", source, sideEffect: true };
249
252
  }
253
+ if (source === "sinth:env") {
254
+ const env = (0, env_1.publicEnv)(this.root, this.dev ? "development" : "production");
255
+ for (const s of decl.named) {
256
+ if (s.name in env)
257
+ continue;
258
+ const near = (0, diagnostics_1.suggest)(s.name, Object.keys(env));
259
+ throw new diagnostics_1.SinthError("E0607", `Environment variable '${s.name}' is not set`, s.loc, near ? `Did you mean '${near}'?`
260
+ : !s.name.startsWith(env_1.PUBLIC_PREFIX) ? `Only variables starting with ${env_1.PUBLIC_PREFIX} are available in pages, so secrets never reach the browser. Rename it to ${env_1.PUBLIC_PREFIX}${s.name}`
261
+ : `Add ${s.name}=... to .env (or .env.production for builds), or set it in the environment of the build`);
262
+ }
263
+ return { decl: { ...decl, kind: "json" }, kind: "json", specifier: "sinth:env", json: env };
264
+ }
250
265
  if (source.startsWith("sinth:")) {
251
266
  const name = source.slice(6);
252
267
  const target = this.resolveFile(path.join(exports.LIB_ROOT, name), [".sinth"]);
@@ -259,7 +274,7 @@ class Project {
259
274
  const isRelative = source.startsWith("./") || source.startsWith("../");
260
275
  const isRootAbs = source.startsWith("/") && !source.startsWith("//");
261
276
  const isUrl = /^(https?:)?\/\//.test(source);
262
- const localBase = isRootAbs ? path.join(this.root, source) : path.resolve(path.dirname(from), source);
277
+ const localBase = isRootAbs ? this.rootPath(source) : path.resolve(path.dirname(from), source);
263
278
  switch (decl.kind) {
264
279
  case "style": {
265
280
  if (isUrl)
@@ -488,19 +503,31 @@ class Project {
488
503
  };
489
504
  return visit(path.resolve(pageFile));
490
505
  }
506
+ /**
507
+ * `/components/Card.sinth` in an import means the source folder (the root or app/). Files that
508
+ * only exist in the project root (for example styles next to app/) still resolve.
509
+ */
510
+ rootPath(source) {
511
+ const inSrc = path.join(this.config.srcDir, source);
512
+ if (this.config.srcDir === path.resolve(this.root))
513
+ return inSrc;
514
+ const inRoot = path.join(this.root, source);
515
+ const exists = (p) => fs.existsSync(p) || (fs.existsSync(path.dirname(p)) && fs.readdirSync(path.dirname(p)).some(f => f.startsWith(path.basename(p) + ".")));
516
+ return !exists(inSrc) && exists(inRoot) ? inRoot : inSrc;
517
+ }
491
518
  resolveAsset(value, fromFile) {
492
519
  if (/^([a-z]+:|\/\/|#|data:)/i.test(value) || value.startsWith("/"))
493
520
  return value;
494
- const candidates = [path.resolve(path.dirname(fromFile), value), path.resolve(this.root, value)];
521
+ const candidates = [path.resolve(path.dirname(fromFile), value), path.resolve(this.config.srcDir, value), path.resolve(this.root, value)];
495
522
  for (const c of candidates) {
496
523
  if (!fs.existsSync(c))
497
524
  continue;
498
525
  if (c.startsWith(this.config.publicDir + path.sep))
499
526
  return this.config.base + path.relative(this.config.publicDir, c).replace(/\\/g, "/");
500
527
  for (const d of this.config.staticDirs) {
501
- const dir = path.resolve(this.root, d);
528
+ const dir = (0, config_1.staticDirPath)(this.config, d);
502
529
  if (c.startsWith(dir + path.sep))
503
- return this.config.base + path.relative(this.root, c).replace(/\\/g, "/");
530
+ return this.config.base + d + "/" + path.relative(dir, c).replace(/\\/g, "/");
504
531
  }
505
532
  }
506
533
  return this.config.base + value.replace(/^\.\//, "");