@ontosdk/next 1.3.5 → 1.3.7
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/QUICKSTART.md +16 -15
- package/README.md +5 -35
- package/dist/cli.js +12 -11
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +12 -11
- package/dist/cli.mjs.map +1 -1
- package/package.json +1 -1
- package/src/cli.ts +11 -7
package/QUICKSTART.md
CHANGED
|
@@ -2,28 +2,29 @@
|
|
|
2
2
|
|
|
3
3
|
Get AI discovery working in 60 seconds.
|
|
4
4
|
|
|
5
|
-
## Step 1:
|
|
5
|
+
## Step 1: Initialize
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Run the following command in your project root to generate your configuration and middleware:
|
|
8
8
|
|
|
9
|
-
```
|
|
10
|
-
|
|
9
|
+
```bash
|
|
10
|
+
npx onto-next init
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
This will create `onto.config.ts` and `middleware.ts` for you.
|
|
11
14
|
|
|
12
|
-
|
|
13
|
-
name: 'My Site',
|
|
14
|
-
summary: 'Brief description for AI agents',
|
|
15
|
-
baseUrl: 'https://example.com',
|
|
15
|
+
## Step 2: Configure Build
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
{ path: '/', description: 'Homepage' },
|
|
19
|
-
{ path: '/docs', description: 'Documentation' }
|
|
20
|
-
]
|
|
21
|
-
};
|
|
17
|
+
Update your `package.json` to process your pages after building:
|
|
22
18
|
|
|
23
|
-
|
|
19
|
+
```json
|
|
20
|
+
{
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "next build && onto-next"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
24
25
|
```
|
|
25
26
|
|
|
26
|
-
## Step
|
|
27
|
+
## Step 3: Test
|
|
27
28
|
|
|
28
29
|
Start your dev server and visit:
|
|
29
30
|
|
package/README.md
CHANGED
|
@@ -21,18 +21,12 @@ The Onto SDK automatically converts your Next.js pages into AI-friendly Markdown
|
|
|
21
21
|
npm install @ontosdk/next
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
-
### 2.
|
|
24
|
+
### 2. Initialize
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
Run the initialization command to automatically generate your `onto.config.ts` and `middleware.ts`:
|
|
27
27
|
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
export { middleware };
|
|
32
|
-
|
|
33
|
-
export const config = {
|
|
34
|
-
matcher: ['/((?!api|_next|.*\\..*).*)'],
|
|
35
|
-
};
|
|
28
|
+
```bash
|
|
29
|
+
npx onto-next init
|
|
36
30
|
```
|
|
37
31
|
|
|
38
32
|
### 3. Configure Build
|
|
@@ -47,27 +41,6 @@ Update your `package.json`:
|
|
|
47
41
|
}
|
|
48
42
|
```
|
|
49
43
|
|
|
50
|
-
### 4. Create `onto.config.ts`
|
|
51
|
-
|
|
52
|
-
Create `onto.config.ts` in your project root for dynamic `llms.txt` generation:
|
|
53
|
-
|
|
54
|
-
```typescript
|
|
55
|
-
import type { OntoConfig } from '@ontosdk/next';
|
|
56
|
-
|
|
57
|
-
const config: OntoConfig = {
|
|
58
|
-
name: 'My Project',
|
|
59
|
-
summary: 'A brief description of what your site does',
|
|
60
|
-
baseUrl: 'https://example.com',
|
|
61
|
-
|
|
62
|
-
routes: [
|
|
63
|
-
{ path: '/', description: 'Homepage' },
|
|
64
|
-
{ path: '/docs', description: 'Documentation' }
|
|
65
|
-
]
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
export default config;
|
|
69
|
-
```
|
|
70
|
-
|
|
71
44
|
That's it! Your site is now optimized for AI agents.
|
|
72
45
|
|
|
73
46
|
## How It Works
|
|
@@ -220,10 +193,7 @@ import type { OntoConfig, OntoRoute } from '@ontosdk/next';
|
|
|
220
193
|
### Utility Functions
|
|
221
194
|
|
|
222
195
|
```typescript
|
|
223
|
-
import {
|
|
224
|
-
|
|
225
|
-
// Load config from project root
|
|
226
|
-
const config = await loadOntoConfig();
|
|
196
|
+
import { generateLlmsTxt } from '@ontosdk/next';
|
|
227
197
|
|
|
228
198
|
// Generate llms.txt content
|
|
229
199
|
const llmsTxt = generateLlmsTxt(config);
|
package/dist/cli.js
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var z=Object.create;var
|
|
2
|
+
"use strict";var z=Object.create;var k=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var A=(t,n,e,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of N(n))!E.call(t,s)&&s!==e&&k(t,s,{get:()=>n[s],enumerable:!(o=L(n,s))||o.enumerable});return t};var $=(t,n,e)=>(e=t!=null?z(_(t)):{},A(n||!t||!t.__esModule?k(e,"default",{value:t,enumerable:!0}):e,t));var T=require("glob"),r=$(require("fs")),a=$(require("path")),i=$(require("picocolors"));var j=$(require("cheerio")),v=$(require("turndown")),D=new v.default({headingStyle:"atx",codeBlockStyle:"fenced"});function b(t,n="Generated Output"){let e=t.length,o=j.load(t),s=o("title").text()||o("h1").first().text()||"Untitled Page",p=o('meta[name="description"]').attr("content")||"No description found.",g=[];o('script[type="application/ld+json"]').each((m,l)=>{try{let u=o(l).html()||"",h=JSON.parse(u);g.push(h)}catch{}}),o("script, style, noscript, iframe, svg, nav, footer, meta, link, header").remove();let f="";o("main").length>0?f=o("main").html()||"":o("article").length>0?f=o("article").html()||"":f=o("body").html()||"";let x=D.turndown(f),d=[`# ${s}`,`> ${p}`,"",`**Source:** ${n}`,`**Extracted:** ${new Date().toISOString()}`,"","---",""].join(`
|
|
3
3
|
`)+x;g.length>0&&(d+=`
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
## Structured Data (JSON-LD)
|
|
7
7
|
\`\`\`json
|
|
8
|
-
`,g.forEach(
|
|
9
|
-
`}),d+="```\n");let w=d.length,c=
|
|
8
|
+
`,g.forEach(m=>{d+=JSON.stringify(m,null,2)+`
|
|
9
|
+
`}),d+="```\n");let w=d.length,c=e>0?(e-w)/e*100:0;return{markdown:d,metadata:{title:s,description:p,jsonLd:g},stats:{originalHtmlSize:e,markdownSize:w,tokenReductionRatio:c}}}function C(t){let n=[];if(n.push(`# ${t.name}`),n.push(""),n.push(`> ${t.summary}`),n.push(""),t.routes&&t.routes.length>0){n.push("## Key Routes"),n.push("");for(let e of t.routes){let o=`${t.baseUrl}${e.path}`;n.push(`- [${e.path}](${o}): ${e.description}`)}n.push("")}if(t.externalLinks&&t.externalLinks.length>0){n.push("## Resources"),n.push("");for(let e of t.externalLinks)e.description?n.push(`- [${e.title}](${e.url}): ${e.description}`):n.push(`- [${e.title}](${e.url})`);n.push("")}if(t.sections&&t.sections.length>0)for(let e of t.sections)n.push(`## ${e.heading}`),n.push(""),n.push(e.content),n.push("");return n.join(`
|
|
10
10
|
`).trim()+`
|
|
11
|
-
`}async function K(){try{let
|
|
12
|
-
[Onto] Initializing project...`)),
|
|
11
|
+
`}async function K(){let t=process.cwd();try{let o=await import("file:///"+a.default.join(t,"onto.config").replace(/\\/g,"/")+".ts");return o.default||o}catch{try{let s=await import("file:///"+a.default.join(t,"onto.config").replace(/\\/g,"/")+".js");return s.default||s}catch{return null}}}function H(){let t=a.default.join(process.cwd(),".env.local");r.default.existsSync(t)&&r.default.readFileSync(t,"utf8").split(/\r?\n/).forEach(e=>{let o=e.trim();if(!o||o.startsWith("#"))return;let[s,...p]=o.split("=");s&&p.length>0&&(process.env[s.trim()]=p.join("=").trim().replace(/^["']|["']$/g,""))})}async function U(){let t=process.cwd(),n=a.default.join(t,"onto.config.ts"),e=a.default.join(t,"middleware.ts");console.log(i.default.cyan(`
|
|
12
|
+
[Onto] Initializing project...`)),r.default.existsSync(n)?console.log(i.default.yellow("\u2139 onto.config.ts already exists, skipping.")):(r.default.writeFileSync(n,`import { OntoConfig } from '@ontosdk/next';
|
|
13
13
|
|
|
14
14
|
const config: OntoConfig = {
|
|
15
15
|
name: 'My Project',
|
|
16
16
|
summary: 'A short description of my project for AI agents.',
|
|
17
|
+
baseUrl: 'https://example.com',
|
|
17
18
|
routes: [
|
|
18
19
|
{
|
|
19
20
|
path: '/',
|
|
@@ -24,7 +25,7 @@ const config: OntoConfig = {
|
|
|
24
25
|
};
|
|
25
26
|
|
|
26
27
|
export default config;
|
|
27
|
-
`,"utf8"),console.log(
|
|
28
|
+
`,"utf8"),console.log(i.default.green("\u2713 Created")+" onto.config.ts")),r.default.existsSync(e)?console.log(i.default.yellow("\u2139 middleware.ts already exists, skipping.")):(r.default.writeFileSync(e,`import { NextRequest } from 'next/server';
|
|
28
29
|
import { ontoMiddleware } from '@ontosdk/next/middleware';
|
|
29
30
|
import ontoConfig from './onto.config';
|
|
30
31
|
|
|
@@ -42,9 +43,9 @@ export const config = {
|
|
|
42
43
|
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
|
|
43
44
|
],
|
|
44
45
|
};
|
|
45
|
-
`,"utf8"),console.log(
|
|
46
|
-
Initialization complete! \u{1F680}`)),console.log(
|
|
47
|
-
`))}async function
|
|
48
|
-
[Onto] Starting Semantic Output Generation...`));let
|
|
49
|
-
`))}
|
|
46
|
+
`,"utf8"),console.log(i.default.green("\u2713 Created")+" middleware.ts")),console.log(i.default.magenta(`
|
|
47
|
+
Initialization complete! \u{1F680}`)),console.log(i.default.dim("Next steps:")),console.log(i.default.dim("1. Update your routes in onto.config.ts")),console.log(i.default.dim(`2. Run "npm run build" to generate manifests
|
|
48
|
+
`))}async function B(){if(process.argv.slice(2)[0]==="init"){await U();return}H(),console.log(i.default.cyan(`
|
|
49
|
+
[Onto] Starting Semantic Output Generation...`));let e=process.cwd(),o=a.default.join(e,".next/server/app"),s=a.default.join(e,"public/.onto");if(!r.default.existsSync(o)){console.log(i.default.yellow(`[Onto] Could not find Next.js app output at ${o}`)),console.log(i.default.yellow('[Onto] Ensure this is run after "next build" and you are using the App Router.'));return}let p=await(0,T.glob)("**/*.html",{cwd:o});if(p.length===0){console.log(i.default.yellow("[Onto] No static HTML files found to process."));return}r.default.existsSync(s)||r.default.mkdirSync(s,{recursive:!0});let g=0,f=0,x=0;for(let c of p){let m=a.default.join(o,c),l=c.replace(/\.html$/,".md"),u=a.default.join(s,l);try{let h=r.default.readFileSync(m,"utf8"),y=b(h,`/${l.replace(/\.md$/,"")}`),P=a.default.dirname(u);r.default.existsSync(P)||r.default.mkdirSync(P,{recursive:!0}),r.default.writeFileSync(u,y.markdown,"utf8"),g+=y.stats.originalHtmlSize,f+=y.stats.markdownSize,x++;let R=(y.stats.originalHtmlSize/1024).toFixed(1),F=(y.stats.markdownSize/1024).toFixed(1),S=c.replace(/\.html$/,"");S==="index"?S="/":S=`/${S}`,console.log(i.default.green("\u2713 Optimized")+i.default.dim(` ${S} `)+i.default.blue(`[${R}KB -> ${F}KB]`))}catch(h){console.error(i.default.red(`\u2717 Failed to process ${c}: ${h.message}`))}}console.log(i.default.bold(i.default.magenta(`Processed ${x} pages. Total Size: ${(g/1024).toFixed(1)}KB -> ${(f/1024).toFixed(1)}KB`)));let O=process.env.ONTO_API_KEY,d=process.env.ONTO_DASHBOARD_URL||"https://app.buildonto.dev";if(O&&x>0){console.log(i.default.cyan(`[Onto] Syncing manifest with Control Plane [${d}]...`));try{let c=p.map(l=>{let u=l.replace(/\.html$/,""),h=u==="index"?"/":`/${u}`,y=a.default.join(s,l.replace(/\.html$/,".md"));return{route:h,filename:`${u}.md`,content:r.default.readFileSync(y,"utf8")}}),m=await fetch(`${d}/api/files`,{method:"POST",headers:{"x-onto-key":O,"Content-Type":"application/json"},body:JSON.stringify({files:c})});if(m.ok)console.log(i.default.green("\u2713 Control Plane sync successful"));else{let l=await m.json().catch(()=>({}));console.log(i.default.yellow(`\u26A0 Control Plane sync skipped: ${l.error||m.statusText}`))}}catch(c){console.log(i.default.yellow(`\u26A0 Control Plane sync failed: ${c.message}`))}}let w=await K();if(w){let c=C(w),m=a.default.join(e,"public/llms.txt"),l=a.default.join(e,"public");r.default.existsSync(l)||r.default.mkdirSync(l,{recursive:!0}),r.default.writeFileSync(m,c,"utf8"),console.log(i.default.green("\u2713 Generated")+i.default.dim(" /llms.txt"))}console.log(i.default.dim(`Edge payloads are ready at /public/.onto/*
|
|
50
|
+
`))}B().catch(t=>{console.error(i.default.red(`[Onto] Fatal Error: ${t.message}`)),process.exit(1)});
|
|
50
51
|
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/extractor.ts","../src/config.ts"],"sourcesContent":["#!/usr/bin/env node\r\nimport { glob } from 'glob';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport pc from 'picocolors';\r\nimport { extractContent } from './extractor';\r\nimport { generateLlmsTxt, OntoConfig } from './config';\r\n\r\nasync function loadOntoConfig(): Promise<OntoConfig | null> {\r\n try {\r\n const configPath = path.join(process.cwd(), 'onto.config');\r\n // Node.js dynamic import\r\n const config = await import('file://' + configPath.replace(/\\\\/g, '/') + '.ts');\r\n return config.default || config;\r\n } catch (error) {\r\n try {\r\n const configPath = path.join(process.cwd(), 'onto.config');\r\n const config = await import('file://' + configPath.replace(/\\\\/g, '/') + '.js');\r\n return config.default || config;\r\n } catch (e) {\r\n return null;\r\n }\r\n }\r\n}\r\n\r\n// Simple helper to load .env.local from the current working directory\r\nfunction loadEnv() {\r\n const envPath = path.join(process.cwd(), '.env.local');\r\n if (fs.existsSync(envPath)) {\r\n const envContent = fs.readFileSync(envPath, 'utf8');\r\n envContent.split(/\\r?\\n/).forEach(line => {\r\n const trimmedLine = line.trim();\r\n if (!trimmedLine || trimmedLine.startsWith('#')) return;\r\n const [key, ...valueParts] = trimmedLine.split('=');\r\n if (key && valueParts.length > 0) {\r\n process.env[key.trim()] = valueParts.join('=').trim().replace(/^[\"']|[\"']$/g, '');\r\n }\r\n });\r\n }\r\n}\r\n\r\nasync function init() {\r\n const cwd = process.cwd();\r\n const configPath = path.join(cwd, 'onto.config.ts');\r\n const middlewarePath = path.join(cwd, 'middleware.ts');\r\n\r\n console.log(pc.cyan('\\n[Onto] Initializing project...'));\r\n\r\n // 1. Create onto.config.ts\r\n if (!fs.existsSync(configPath)) {\r\n const configTemplate = `import { OntoConfig } from '@ontosdk/next';\r\n\r\nconst config: OntoConfig = {\r\n name: 'My Project',\r\n summary: 'A short description of my project for AI agents.',\r\n routes: [\r\n { \r\n path: '/', \r\n description: 'The homepage of my application.',\r\n pageType: 'about'\r\n }\r\n ]\r\n};\r\n\r\nexport default config;\r\n`;\r\n fs.writeFileSync(configPath, configTemplate, 'utf8');\r\n console.log(pc.green('✓ Created') + ' onto.config.ts');\r\n } else {\r\n console.log(pc.yellow('ℹ onto.config.ts already exists, skipping.'));\r\n }\r\n\r\n // 2. Create middleware.ts\r\n if (!fs.existsSync(middlewarePath)) {\r\n const middlewareTemplate = `import { NextRequest } from 'next/server';\r\nimport { ontoMiddleware } from '@ontosdk/next/middleware';\r\nimport ontoConfig from './onto.config';\r\n\r\nexport const middleware = (req: NextRequest) => ontoMiddleware(req, ontoConfig);\r\n\r\nexport const config = {\r\n matcher: [\r\n /*\r\n * Match all request paths except for the ones starting with:\r\n * - api (API routes)\r\n * - _next/static (static files)\r\n * - _next/image (image optimization files)\r\n * - favicon.ico, sitemap.xml, robots.txt (metadata files)\r\n */\r\n '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',\r\n ],\r\n};\r\n`;\r\n fs.writeFileSync(middlewarePath, middlewareTemplate, 'utf8');\r\n console.log(pc.green('✓ Created') + ' middleware.ts');\r\n } else {\r\n console.log(pc.yellow('ℹ middleware.ts already exists, skipping.'));\r\n }\r\n\r\n console.log(pc.magenta('\\nInitialization complete! 🚀'));\r\n console.log(pc.dim('Next steps:'));\r\n console.log(pc.dim('1. Update your routes in onto.config.ts'));\r\n console.log(pc.dim('2. Run \"npm run build\" to generate manifests\\n'));\r\n}\r\n\r\nasync function main() {\r\n const args = process.argv.slice(2);\r\n const command = args[0];\r\n\r\n if (command === 'init') {\r\n await init();\r\n return;\r\n }\r\n\r\n loadEnv();\r\n console.log(pc.cyan('\\n[Onto] Starting Semantic Output Generation...'));\r\n // ... rest of the existing main function logic ...\r\n\r\n const cwd = process.cwd();\r\n const nextAppDirDir = path.join(cwd, '.next/server/app');\r\n const ontoPublicDir = path.join(cwd, 'public/.onto');\r\n\r\n if (!fs.existsSync(nextAppDirDir)) {\r\n console.log(pc.yellow(`[Onto] Could not find Next.js app output at ${nextAppDirDir}`));\r\n console.log(pc.yellow(`[Onto] Ensure this is run after \"next build\" and you are using the App Router.`));\r\n return;\r\n }\r\n\r\n // Find all HTML files rendered by Next.js in the app directory\r\n const files = await glob('**/*.html', { cwd: nextAppDirDir });\r\n\r\n if (files.length === 0) {\r\n console.log(pc.yellow(`[Onto] No static HTML files found to process.`));\r\n return;\r\n }\r\n\r\n // Ensure output directory exists\r\n if (!fs.existsSync(ontoPublicDir)) {\r\n fs.mkdirSync(ontoPublicDir, { recursive: true });\r\n }\r\n\r\n let totalOriginalSize = 0;\r\n let totalMarkdownSize = 0;\r\n let totalFilesProcessed = 0;\r\n\r\n for (const file of files) {\r\n const inputPath = path.join(nextAppDirDir, file);\r\n\r\n // We map file path e.g. \"pricing.html\" to \"pricing.md\", or \"blog/post.html\" to \"blog/post.md\"\r\n let outputPathRelative = file.replace(/\\.html$/, '.md');\r\n // If it's a dynamic route page, or purely root index.html\r\n const outputPath = path.join(ontoPublicDir, outputPathRelative);\r\n\r\n try {\r\n const htmlContent = fs.readFileSync(inputPath, 'utf8');\r\n\r\n const result = extractContent(htmlContent, `/${outputPathRelative.replace(/\\.md$/, '')}`);\r\n\r\n // Ensure specific sub-directory exists (e.g., for blog/post.md)\r\n const outputDir = path.dirname(outputPath);\r\n if (!fs.existsSync(outputDir)) {\r\n fs.mkdirSync(outputDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(outputPath, result.markdown, 'utf8');\r\n\r\n totalOriginalSize += result.stats.originalHtmlSize;\r\n totalMarkdownSize += result.stats.markdownSize;\r\n totalFilesProcessed++;\r\n\r\n const origKb = (result.stats.originalHtmlSize / 1024).toFixed(1);\r\n const mdKb = (result.stats.markdownSize / 1024).toFixed(1);\r\n\r\n // /index.html -> /\r\n let routeName = file.replace(/\\.html$/, '');\r\n if (routeName === 'index') routeName = '/';\r\n else routeName = `/${routeName}`;\r\n\r\n console.log(\r\n pc.green(`✓ Optimized`) +\r\n pc.dim(` ${routeName} `) +\r\n pc.blue(`[${origKb}KB -> ${mdKb}KB]`)\r\n );\r\n } catch (e: any) {\r\n console.error(pc.red(`✗ Failed to process ${file}: ${e.message}`));\r\n }\r\n }\r\n\r\n console.log(\r\n pc.bold(\r\n pc.magenta(`Processed ${totalFilesProcessed} pages. Total Size: ${(totalOriginalSize / 1024).toFixed(1)}KB -> ${(totalMarkdownSize / 1024).toFixed(1)}KB`)\r\n )\r\n );\r\n\r\n // Sync with Onto Control Plane (Premium)\r\n const ONTO_API_KEY = process.env.ONTO_API_KEY;\r\n const DASHBOARD_URL = process.env.ONTO_DASHBOARD_URL || 'https://app.buildonto.dev';\r\n\r\n if (ONTO_API_KEY && totalFilesProcessed > 0) {\r\n console.log(pc.cyan(`[Onto] Syncing manifest with Control Plane [${DASHBOARD_URL}]...`));\r\n try {\r\n const manifest = files.map(file => {\r\n const routeName = file.replace(/\\.html$/, '');\r\n const route = routeName === 'index' ? '/' : `/${routeName}`;\r\n const mdPath = path.join(ontoPublicDir, file.replace(/\\.html$/, '.md'));\r\n return {\r\n route,\r\n filename: `${routeName}.md`,\r\n content: fs.readFileSync(mdPath, 'utf8')\r\n };\r\n });\r\n\r\n const res = await fetch(`${DASHBOARD_URL}/api/files`, {\r\n method: 'POST',\r\n headers: {\r\n 'x-onto-key': ONTO_API_KEY,\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({ files: manifest })\r\n });\r\n\r\n if (res.ok) {\r\n console.log(pc.green('✓ Control Plane sync successful'));\r\n } else {\r\n const errData = await res.json().catch(() => ({}));\r\n console.log(pc.yellow(`⚠ Control Plane sync skipped: ${errData.error || res.statusText}`));\r\n }\r\n } catch (e: any) {\r\n console.log(pc.yellow(`⚠ Control Plane sync failed: ${e.message}`));\r\n }\r\n }\r\n\r\n // --- Generate llms.txt manifest ---\r\n const config = await loadOntoConfig();\r\n if (config) {\r\n const llmsTxtContent = generateLlmsTxt(config);\r\n const llmsTxtPath = path.join(cwd, 'public/llms.txt');\r\n \r\n // Ensure public dir exists\r\n const publicDir = path.join(cwd, 'public');\r\n if (!fs.existsSync(publicDir)) {\r\n fs.mkdirSync(publicDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(llmsTxtPath, llmsTxtContent, 'utf8');\r\n console.log(pc.green('✓ Generated') + pc.dim(' /llms.txt'));\r\n }\r\n\r\n console.log(pc.dim(`Edge payloads are ready at /public/.onto/*\\n`));\r\n}\r\n\r\nmain().catch(e => {\r\n console.error(pc.red(`[Onto] Fatal Error: ${e.message}`));\r\n process.exit(1);\r\n});\r\n","import * as cheerio from 'cheerio';\r\nimport TurndownService from 'turndown';\r\n\r\nconst turndownService = new TurndownService({\r\n headingStyle: 'atx',\r\n codeBlockStyle: 'fenced',\r\n});\r\n\r\n// Configure turndown to keep some layout or handle semantic tags differently if needed\r\n\r\nexport interface ExtractionResult {\r\n markdown: string;\r\n metadata: {\r\n title: string;\r\n description: string;\r\n jsonLd: any[];\r\n };\r\n stats: {\r\n originalHtmlSize: number;\r\n markdownSize: number;\r\n tokenReductionRatio: number;\r\n };\r\n}\r\n\r\n/**\r\n * Extracts pure semantic markdown and metadata from rendered Next.js HTML strings.\r\n * @param html The raw HTML string.\r\n * @param sourceUrl (Optional) the URL this was generated from, to attach as metadata.\r\n * @returns {ExtractionResult} The extracted payload.\r\n */\r\nexport function extractContent(html: string, sourceUrl: string = 'Generated Output'): ExtractionResult {\r\n const originalSize = html.length;\r\n\r\n const $ = cheerio.load(html);\r\n\r\n // 1. Extract Metadata BEFORE removing structure\r\n const title = $('title').text() || $('h1').first().text() || 'Untitled Page';\r\n const description = $('meta[name=\"description\"]').attr('content') || 'No description found.';\r\n\r\n const jsonLdScripts: any[] = [];\r\n $('script[type=\"application/ld+json\"]').each((_, el) => {\r\n try {\r\n const raw = $(el).html() || '';\r\n const parsed = JSON.parse(raw);\r\n jsonLdScripts.push(parsed);\r\n } catch {\r\n // ignore bad json\r\n }\r\n });\r\n\r\n // 2. Strip noise (React boilerplate, styles, unnecessary tags)\r\n $('script, style, noscript, iframe, svg, nav, footer, meta, link, header').remove();\r\n\r\n // Optionally remove typical Next.js hidden wrappers if they don't contain real content.\r\n // Next.js uses <div id=\"__next\"> but we mostly just want semantic content.\r\n\r\n // 3. Find the entry point for content\r\n // Prefer <main> or <article> over <body>\r\n let contentHtml = '';\r\n if ($('main').length > 0) {\r\n contentHtml = $('main').html() || '';\r\n } else if ($('article').length > 0) {\r\n contentHtml = $('article').html() || '';\r\n } else {\r\n contentHtml = $('body').html() || '';\r\n }\r\n\r\n // 4. Convert to Markdown\r\n let markdown = turndownService.turndown(contentHtml);\r\n\r\n // 5. Optionally inject Metadata header\r\n const headerLines = [\r\n `# ${title}`,\r\n `> ${description}`,\r\n ``,\r\n `**Source:** ${sourceUrl}`,\r\n `**Extracted:** ${new Date().toISOString()}`,\r\n ``,\r\n `---`,\r\n ``\r\n ];\r\n\r\n let finalMarkdown = headerLines.join('\\n') + markdown;\r\n\r\n // Add JSON-LD section if exists\r\n if (jsonLdScripts.length > 0) {\r\n finalMarkdown += '\\n\\n---\\n## Structured Data (JSON-LD)\\n```json\\n';\r\n jsonLdScripts.forEach(j => {\r\n finalMarkdown += JSON.stringify(j, null, 2) + '\\n';\r\n });\r\n finalMarkdown += '```\\n';\r\n }\r\n\r\n const markdownSize = finalMarkdown.length;\r\n const tokenReductionRatio = originalSize > 0 ? ((originalSize - markdownSize) / originalSize) * 100 : 0;\r\n\r\n return {\r\n markdown: finalMarkdown,\r\n metadata: {\r\n title,\r\n description,\r\n jsonLd: jsonLdScripts\r\n },\r\n stats: {\r\n originalHtmlSize: originalSize,\r\n markdownSize,\r\n tokenReductionRatio\r\n }\r\n };\r\n}\r\n\r\nexport async function generateStaticPayloads(nextAppDirDir: string, ontoPublicDir: string) {\r\n const fs = await import('fs');\r\n const path = await import('path');\r\n const { glob } = await import('glob');\r\n\r\n if (!fs.existsSync(nextAppDirDir)) {\r\n return;\r\n }\r\n\r\n const files = await glob('**/*.html', { cwd: nextAppDirDir });\r\n if (files.length === 0) return;\r\n\r\n if (!fs.existsSync(ontoPublicDir)) {\r\n fs.mkdirSync(ontoPublicDir, { recursive: true });\r\n }\r\n\r\n let totalFilesProcessed = 0;\r\n\r\n for (const file of files) {\r\n const inputPath = path.join(nextAppDirDir, file);\r\n const outputPathRelative = file.replace(/\\.html$/, '.md');\r\n const outputPath = path.join(ontoPublicDir, outputPathRelative);\r\n\r\n try {\r\n const htmlContent = fs.readFileSync(inputPath, 'utf8');\r\n\r\n let routeName = file.replace(/\\.html$/, '');\r\n if (routeName === 'index') routeName = '/';\r\n else routeName = `/${routeName}`;\r\n\r\n const result = extractContent(htmlContent, routeName);\r\n\r\n const outputDir = path.dirname(outputPath);\r\n if (!fs.existsSync(outputDir)) {\r\n fs.mkdirSync(outputDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(outputPath, result.markdown, 'utf8');\r\n totalFilesProcessed++;\r\n } catch (e: any) {\r\n console.error(`[Onto] Failed to process ${file}: ${e.message}`);\r\n }\r\n }\r\n console.log(`[Onto] Successfully generated ${totalFilesProcessed} semantic markdown endpoints.`);\r\n}\r\n","/**\r\n * Configuration schema for onto.config.ts\r\n * Used to dynamically generate llms.txt and other AI discovery files\r\n */\r\n\r\nexport type PageType = 'scoring' | 'about' | 'default';\r\n\r\nexport interface OntoRoute {\r\n /**\r\n * The URL path (e.g., '/docs', '/api/reference')\r\n */\r\n path: string;\r\n /**\r\n * Description of what this route contains\r\n */\r\n description: string;\r\n /**\r\n * Optional: Page type for automatic JSON-LD schema injection\r\n * - 'scoring': Injects Methodology schema with AIO scoring weights (40/35/25)\r\n * - 'about': Injects Organization/AboutPage schema\r\n * - 'default': No automatic schema injection\r\n */\r\n pageType?: PageType;\r\n}\r\n\r\nexport interface OntoConfig {\r\n /**\r\n * The name of your project or site (required)\r\n * Used as the H1 heading in llms.txt\r\n */\r\n name: string;\r\n\r\n /**\r\n * A short summary of your project (required)\r\n * Displayed as a blockquote in llms.txt\r\n * Should contain key information necessary for understanding the rest of the file\r\n */\r\n summary: string;\r\n\r\n /**\r\n * The base URL of your site (e.g., 'https://example.com')\r\n */\r\n baseUrl: string;\r\n\r\n /**\r\n * Optional: Additional sections to include in llms.txt\r\n * Each section can contain any markdown content\r\n */\r\n sections?: {\r\n heading: string;\r\n content: string;\r\n }[];\r\n\r\n /**\r\n * Key routes that AI agents should know about\r\n * These will be formatted as a markdown list in llms.txt\r\n */\r\n routes?: OntoRoute[];\r\n\r\n /**\r\n * Optional: Links to external resources (documentation, API references, etc.)\r\n */\r\n externalLinks?: {\r\n title: string;\r\n url: string;\r\n description?: string;\r\n }[];\r\n\r\n /**\r\n * Optional: Organization information for JSON-LD schemas\r\n */\r\n organization?: {\r\n name: string;\r\n description?: string;\r\n url?: string;\r\n logo?: string;\r\n foundingDate?: string;\r\n };\r\n}\r\n\r\n/**\r\n * Generate llms.txt content from OntoConfig\r\n * Follows the llms.txt specification:\r\n * - H1 with project name\r\n * - Blockquote with summary\r\n * - Additional markdown sections\r\n */\r\nexport function generateLlmsTxt(config: OntoConfig): string {\r\n const lines: string[] = [];\r\n\r\n // H1: Project name (required)\r\n lines.push(`# ${config.name}`);\r\n lines.push('');\r\n\r\n // Blockquote: Summary (required)\r\n lines.push(`> ${config.summary}`);\r\n lines.push('');\r\n\r\n // Key Routes section (if provided)\r\n if (config.routes && config.routes.length > 0) {\r\n lines.push('## Key Routes');\r\n lines.push('');\r\n for (const route of config.routes) {\r\n const fullUrl = `${config.baseUrl}${route.path}`;\r\n lines.push(`- [${route.path}](${fullUrl}): ${route.description}`);\r\n }\r\n lines.push('');\r\n }\r\n\r\n // External Links section (if provided)\r\n if (config.externalLinks && config.externalLinks.length > 0) {\r\n lines.push('## Resources');\r\n lines.push('');\r\n for (const link of config.externalLinks) {\r\n if (link.description) {\r\n lines.push(`- [${link.title}](${link.url}): ${link.description}`);\r\n } else {\r\n lines.push(`- [${link.title}](${link.url})`);\r\n }\r\n }\r\n lines.push('');\r\n }\r\n\r\n // Custom sections (if provided)\r\n if (config.sections && config.sections.length > 0) {\r\n for (const section of config.sections) {\r\n lines.push(`## ${section.heading}`);\r\n lines.push('');\r\n lines.push(section.content);\r\n lines.push('');\r\n }\r\n }\r\n\r\n return lines.join('\\n').trim() + '\\n';\r\n}\r\n"],"mappings":";wdACA,IAAAA,EAAqB,gBACrBC,EAAe,iBACfC,EAAiB,mBACjBC,EAAe,yBCJf,IAAAC,EAAyB,sBACzBC,EAA4B,uBAEtBC,EAAkB,IAAI,EAAAC,QAAgB,CACxC,aAAc,MACd,eAAgB,QACpB,CAAC,EAwBM,SAASC,EAAeC,EAAcC,EAAoB,mBAAsC,CACnG,IAAMC,EAAeF,EAAK,OAEpBG,EAAY,OAAKH,CAAI,EAGrBI,EAAQD,EAAE,OAAO,EAAE,KAAK,GAAKA,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,GAAK,gBACvDE,EAAcF,EAAE,0BAA0B,EAAE,KAAK,SAAS,GAAK,wBAE/DG,EAAuB,CAAC,EAC9BH,EAAE,oCAAoC,EAAE,KAAK,CAACI,EAAGC,IAAO,CACpD,GAAI,CACA,IAAMC,EAAMN,EAAEK,CAAE,EAAE,KAAK,GAAK,GACtBE,EAAS,KAAK,MAAMD,CAAG,EAC7BH,EAAc,KAAKI,CAAM,CAC7B,MAAQ,CAER,CACJ,CAAC,EAGDP,EAAE,uEAAuE,EAAE,OAAO,EAOlF,IAAIQ,EAAc,GACdR,EAAE,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D,QAAG,IAAI,uBAAuB,EAAE,OAAO,EAAE,CAAC,EACxD,QAAQ,KAAK,CAAC,CAClB,CAAC","names":["import_glob","import_fs","import_path","import_picocolors","cheerio","import_turndown","turndownService","TurndownService","extractContent","html","sourceUrl","originalSize","$","title","description","jsonLdScripts","_","el","raw","parsed","contentHtml","markdown","finalMarkdown","j","markdownSize","tokenReductionRatio","generateLlmsTxt","config","lines","route","fullUrl","link","section","loadOntoConfig","config","path","loadEnv","envPath","fs","line","trimmedLine","key","valueParts","init","cwd","configPath","middlewarePath","pc","main","nextAppDirDir","ontoPublicDir","files","totalOriginalSize","totalMarkdownSize","totalFilesProcessed","file","inputPath","outputPathRelative","outputPath","htmlContent","result","extractContent","outputDir","origKb","mdKb","routeName","e","ONTO_API_KEY","DASHBOARD_URL","manifest","route","mdPath","res","errData","llmsTxtContent","generateLlmsTxt","llmsTxtPath","publicDir"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/extractor.ts","../src/config.ts"],"sourcesContent":["#!/usr/bin/env node\r\nimport { glob } from 'glob';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport pc from 'picocolors';\r\nimport { extractContent } from './extractor';\r\nimport { generateLlmsTxt, OntoConfig } from './config';\r\n\r\nasync function loadOntoConfig(): Promise<OntoConfig | null> {\r\n const cwd = process.cwd();\r\n try {\r\n const configPath = path.join(cwd, 'onto.config');\r\n // On Windows, file:/// is often required for absolute paths\r\n const tsPath = 'file:///' + configPath.replace(/\\\\/g, '/') + '.ts';\r\n const config = await import(tsPath);\r\n return config.default || config;\r\n } catch (error: any) {\r\n try {\r\n const configPath = path.join(cwd, 'onto.config');\r\n const jsPath = 'file:///' + configPath.replace(/\\\\/g, '/') + '.js';\r\n const config = await import(jsPath);\r\n return config.default || config;\r\n } catch (e: any) {\r\n return null;\r\n }\r\n }\r\n}\r\n\r\n// Simple helper to load .env.local from the current working directory\r\nfunction loadEnv() {\r\n const envPath = path.join(process.cwd(), '.env.local');\r\n if (fs.existsSync(envPath)) {\r\n const envContent = fs.readFileSync(envPath, 'utf8');\r\n envContent.split(/\\r?\\n/).forEach(line => {\r\n const trimmedLine = line.trim();\r\n if (!trimmedLine || trimmedLine.startsWith('#')) return;\r\n const [key, ...valueParts] = trimmedLine.split('=');\r\n if (key && valueParts.length > 0) {\r\n process.env[key.trim()] = valueParts.join('=').trim().replace(/^[\"']|[\"']$/g, '');\r\n }\r\n });\r\n }\r\n}\r\n\r\nasync function init() {\r\n const cwd = process.cwd();\r\n const configPath = path.join(cwd, 'onto.config.ts');\r\n const middlewarePath = path.join(cwd, 'middleware.ts');\r\n\r\n console.log(pc.cyan('\\n[Onto] Initializing project...'));\r\n\r\n // 1. Create onto.config.ts\r\n if (!fs.existsSync(configPath)) {\r\n const configTemplate = `import { OntoConfig } from '@ontosdk/next';\r\n\r\nconst config: OntoConfig = {\r\n name: 'My Project',\r\n summary: 'A short description of my project for AI agents.',\r\n baseUrl: 'https://example.com',\r\n routes: [\r\n { \r\n path: '/', \r\n description: 'The homepage of my application.',\r\n pageType: 'about'\r\n }\r\n ]\r\n};\r\n\r\nexport default config;\r\n`;\r\n fs.writeFileSync(configPath, configTemplate, 'utf8');\r\n console.log(pc.green('✓ Created') + ' onto.config.ts');\r\n } else {\r\n console.log(pc.yellow('ℹ onto.config.ts already exists, skipping.'));\r\n }\r\n\r\n // 2. Create middleware.ts\r\n if (!fs.existsSync(middlewarePath)) {\r\n const middlewareTemplate = `import { NextRequest } from 'next/server';\r\nimport { ontoMiddleware } from '@ontosdk/next/middleware';\r\nimport ontoConfig from './onto.config';\r\n\r\nexport const middleware = (req: NextRequest) => ontoMiddleware(req, ontoConfig);\r\n\r\nexport const config = {\r\n matcher: [\r\n /*\r\n * Match all request paths except for the ones starting with:\r\n * - api (API routes)\r\n * - _next/static (static files)\r\n * - _next/image (image optimization files)\r\n * - favicon.ico, sitemap.xml, robots.txt (metadata files)\r\n */\r\n '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',\r\n ],\r\n};\r\n`;\r\n fs.writeFileSync(middlewarePath, middlewareTemplate, 'utf8');\r\n console.log(pc.green('✓ Created') + ' middleware.ts');\r\n } else {\r\n console.log(pc.yellow('ℹ middleware.ts already exists, skipping.'));\r\n }\r\n\r\n console.log(pc.magenta('\\nInitialization complete! 🚀'));\r\n console.log(pc.dim('Next steps:'));\r\n console.log(pc.dim('1. Update your routes in onto.config.ts'));\r\n console.log(pc.dim('2. Run \"npm run build\" to generate manifests\\n'));\r\n}\r\n\r\nasync function main() {\r\n const args = process.argv.slice(2);\r\n const command = args[0];\r\n\r\n if (command === 'init') {\r\n await init();\r\n return;\r\n }\r\n\r\n loadEnv();\r\n console.log(pc.cyan('\\n[Onto] Starting Semantic Output Generation...'));\r\n // ... rest of the existing main function logic ...\r\n\r\n const cwd = process.cwd();\r\n const nextAppDirDir = path.join(cwd, '.next/server/app');\r\n const ontoPublicDir = path.join(cwd, 'public/.onto');\r\n\r\n if (!fs.existsSync(nextAppDirDir)) {\r\n console.log(pc.yellow(`[Onto] Could not find Next.js app output at ${nextAppDirDir}`));\r\n console.log(pc.yellow(`[Onto] Ensure this is run after \"next build\" and you are using the App Router.`));\r\n return;\r\n }\r\n\r\n // Find all HTML files rendered by Next.js in the app directory\r\n const files = await glob('**/*.html', { cwd: nextAppDirDir });\r\n\r\n if (files.length === 0) {\r\n console.log(pc.yellow(`[Onto] No static HTML files found to process.`));\r\n return;\r\n }\r\n\r\n // Ensure output directory exists\r\n if (!fs.existsSync(ontoPublicDir)) {\r\n fs.mkdirSync(ontoPublicDir, { recursive: true });\r\n }\r\n\r\n let totalOriginalSize = 0;\r\n let totalMarkdownSize = 0;\r\n let totalFilesProcessed = 0;\r\n\r\n for (const file of files) {\r\n const inputPath = path.join(nextAppDirDir, file);\r\n\r\n // We map file path e.g. \"pricing.html\" to \"pricing.md\", or \"blog/post.html\" to \"blog/post.md\"\r\n let outputPathRelative = file.replace(/\\.html$/, '.md');\r\n // If it's a dynamic route page, or purely root index.html\r\n const outputPath = path.join(ontoPublicDir, outputPathRelative);\r\n\r\n try {\r\n const htmlContent = fs.readFileSync(inputPath, 'utf8');\r\n\r\n const result = extractContent(htmlContent, `/${outputPathRelative.replace(/\\.md$/, '')}`);\r\n\r\n // Ensure specific sub-directory exists (e.g., for blog/post.md)\r\n const outputDir = path.dirname(outputPath);\r\n if (!fs.existsSync(outputDir)) {\r\n fs.mkdirSync(outputDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(outputPath, result.markdown, 'utf8');\r\n\r\n totalOriginalSize += result.stats.originalHtmlSize;\r\n totalMarkdownSize += result.stats.markdownSize;\r\n totalFilesProcessed++;\r\n\r\n const origKb = (result.stats.originalHtmlSize / 1024).toFixed(1);\r\n const mdKb = (result.stats.markdownSize / 1024).toFixed(1);\r\n\r\n // /index.html -> /\r\n let routeName = file.replace(/\\.html$/, '');\r\n if (routeName === 'index') routeName = '/';\r\n else routeName = `/${routeName}`;\r\n\r\n console.log(\r\n pc.green(`✓ Optimized`) +\r\n pc.dim(` ${routeName} `) +\r\n pc.blue(`[${origKb}KB -> ${mdKb}KB]`)\r\n );\r\n } catch (e: any) {\r\n console.error(pc.red(`✗ Failed to process ${file}: ${e.message}`));\r\n }\r\n }\r\n\r\n console.log(\r\n pc.bold(\r\n pc.magenta(`Processed ${totalFilesProcessed} pages. Total Size: ${(totalOriginalSize / 1024).toFixed(1)}KB -> ${(totalMarkdownSize / 1024).toFixed(1)}KB`)\r\n )\r\n );\r\n\r\n // Sync with Onto Control Plane (Premium)\r\n const ONTO_API_KEY = process.env.ONTO_API_KEY;\r\n const DASHBOARD_URL = process.env.ONTO_DASHBOARD_URL || 'https://app.buildonto.dev';\r\n\r\n if (ONTO_API_KEY && totalFilesProcessed > 0) {\r\n console.log(pc.cyan(`[Onto] Syncing manifest with Control Plane [${DASHBOARD_URL}]...`));\r\n try {\r\n const manifest = files.map(file => {\r\n const routeName = file.replace(/\\.html$/, '');\r\n const route = routeName === 'index' ? '/' : `/${routeName}`;\r\n const mdPath = path.join(ontoPublicDir, file.replace(/\\.html$/, '.md'));\r\n return {\r\n route,\r\n filename: `${routeName}.md`,\r\n content: fs.readFileSync(mdPath, 'utf8')\r\n };\r\n });\r\n\r\n const res = await fetch(`${DASHBOARD_URL}/api/files`, {\r\n method: 'POST',\r\n headers: {\r\n 'x-onto-key': ONTO_API_KEY,\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({ files: manifest })\r\n });\r\n\r\n if (res.ok) {\r\n console.log(pc.green('✓ Control Plane sync successful'));\r\n } else {\r\n const errData = await res.json().catch(() => ({}));\r\n console.log(pc.yellow(`⚠ Control Plane sync skipped: ${errData.error || res.statusText}`));\r\n }\r\n } catch (e: any) {\r\n console.log(pc.yellow(`⚠ Control Plane sync failed: ${e.message}`));\r\n }\r\n }\r\n\r\n // --- Generate llms.txt manifest ---\r\n const config = await loadOntoConfig();\r\n if (config) {\r\n const llmsTxtContent = generateLlmsTxt(config);\r\n const llmsTxtPath = path.join(cwd, 'public/llms.txt');\r\n \r\n // Ensure public dir exists\r\n const publicDir = path.join(cwd, 'public');\r\n if (!fs.existsSync(publicDir)) {\r\n fs.mkdirSync(publicDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(llmsTxtPath, llmsTxtContent, 'utf8');\r\n console.log(pc.green('✓ Generated') + pc.dim(' /llms.txt'));\r\n }\r\n\r\n console.log(pc.dim(`Edge payloads are ready at /public/.onto/*\\n`));\r\n}\r\n\r\nmain().catch(e => {\r\n console.error(pc.red(`[Onto] Fatal Error: ${e.message}`));\r\n process.exit(1);\r\n});\r\n","import * as cheerio from 'cheerio';\r\nimport TurndownService from 'turndown';\r\n\r\nconst turndownService = new TurndownService({\r\n headingStyle: 'atx',\r\n codeBlockStyle: 'fenced',\r\n});\r\n\r\n// Configure turndown to keep some layout or handle semantic tags differently if needed\r\n\r\nexport interface ExtractionResult {\r\n markdown: string;\r\n metadata: {\r\n title: string;\r\n description: string;\r\n jsonLd: any[];\r\n };\r\n stats: {\r\n originalHtmlSize: number;\r\n markdownSize: number;\r\n tokenReductionRatio: number;\r\n };\r\n}\r\n\r\n/**\r\n * Extracts pure semantic markdown and metadata from rendered Next.js HTML strings.\r\n * @param html The raw HTML string.\r\n * @param sourceUrl (Optional) the URL this was generated from, to attach as metadata.\r\n * @returns {ExtractionResult} The extracted payload.\r\n */\r\nexport function extractContent(html: string, sourceUrl: string = 'Generated Output'): ExtractionResult {\r\n const originalSize = html.length;\r\n\r\n const $ = cheerio.load(html);\r\n\r\n // 1. Extract Metadata BEFORE removing structure\r\n const title = $('title').text() || $('h1').first().text() || 'Untitled Page';\r\n const description = $('meta[name=\"description\"]').attr('content') || 'No description found.';\r\n\r\n const jsonLdScripts: any[] = [];\r\n $('script[type=\"application/ld+json\"]').each((_, el) => {\r\n try {\r\n const raw = $(el).html() || '';\r\n const parsed = JSON.parse(raw);\r\n jsonLdScripts.push(parsed);\r\n } catch {\r\n // ignore bad json\r\n }\r\n });\r\n\r\n // 2. Strip noise (React boilerplate, styles, unnecessary tags)\r\n $('script, style, noscript, iframe, svg, nav, footer, meta, link, header').remove();\r\n\r\n // Optionally remove typical Next.js hidden wrappers if they don't contain real content.\r\n // Next.js uses <div id=\"__next\"> but we mostly just want semantic content.\r\n\r\n // 3. Find the entry point for content\r\n // Prefer <main> or <article> over <body>\r\n let contentHtml = '';\r\n if ($('main').length > 0) {\r\n contentHtml = $('main').html() || '';\r\n } else if ($('article').length > 0) {\r\n contentHtml = $('article').html() || '';\r\n } else {\r\n contentHtml = $('body').html() || '';\r\n }\r\n\r\n // 4. Convert to Markdown\r\n let markdown = turndownService.turndown(contentHtml);\r\n\r\n // 5. Optionally inject Metadata header\r\n const headerLines = [\r\n `# ${title}`,\r\n `> ${description}`,\r\n ``,\r\n `**Source:** ${sourceUrl}`,\r\n `**Extracted:** ${new Date().toISOString()}`,\r\n ``,\r\n `---`,\r\n ``\r\n ];\r\n\r\n let finalMarkdown = headerLines.join('\\n') + markdown;\r\n\r\n // Add JSON-LD section if exists\r\n if (jsonLdScripts.length > 0) {\r\n finalMarkdown += '\\n\\n---\\n## Structured Data (JSON-LD)\\n```json\\n';\r\n jsonLdScripts.forEach(j => {\r\n finalMarkdown += JSON.stringify(j, null, 2) + '\\n';\r\n });\r\n finalMarkdown += '```\\n';\r\n }\r\n\r\n const markdownSize = finalMarkdown.length;\r\n const tokenReductionRatio = originalSize > 0 ? ((originalSize - markdownSize) / originalSize) * 100 : 0;\r\n\r\n return {\r\n markdown: finalMarkdown,\r\n metadata: {\r\n title,\r\n description,\r\n jsonLd: jsonLdScripts\r\n },\r\n stats: {\r\n originalHtmlSize: originalSize,\r\n markdownSize,\r\n tokenReductionRatio\r\n }\r\n };\r\n}\r\n\r\nexport async function generateStaticPayloads(nextAppDirDir: string, ontoPublicDir: string) {\r\n const fs = await import('fs');\r\n const path = await import('path');\r\n const { glob } = await import('glob');\r\n\r\n if (!fs.existsSync(nextAppDirDir)) {\r\n return;\r\n }\r\n\r\n const files = await glob('**/*.html', { cwd: nextAppDirDir });\r\n if (files.length === 0) return;\r\n\r\n if (!fs.existsSync(ontoPublicDir)) {\r\n fs.mkdirSync(ontoPublicDir, { recursive: true });\r\n }\r\n\r\n let totalFilesProcessed = 0;\r\n\r\n for (const file of files) {\r\n const inputPath = path.join(nextAppDirDir, file);\r\n const outputPathRelative = file.replace(/\\.html$/, '.md');\r\n const outputPath = path.join(ontoPublicDir, outputPathRelative);\r\n\r\n try {\r\n const htmlContent = fs.readFileSync(inputPath, 'utf8');\r\n\r\n let routeName = file.replace(/\\.html$/, '');\r\n if (routeName === 'index') routeName = '/';\r\n else routeName = `/${routeName}`;\r\n\r\n const result = extractContent(htmlContent, routeName);\r\n\r\n const outputDir = path.dirname(outputPath);\r\n if (!fs.existsSync(outputDir)) {\r\n fs.mkdirSync(outputDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(outputPath, result.markdown, 'utf8');\r\n totalFilesProcessed++;\r\n } catch (e: any) {\r\n console.error(`[Onto] Failed to process ${file}: ${e.message}`);\r\n }\r\n }\r\n console.log(`[Onto] Successfully generated ${totalFilesProcessed} semantic markdown endpoints.`);\r\n}\r\n","/**\r\n * Configuration schema for onto.config.ts\r\n * Used to dynamically generate llms.txt and other AI discovery files\r\n */\r\n\r\nexport type PageType = 'scoring' | 'about' | 'default';\r\n\r\nexport interface OntoRoute {\r\n /**\r\n * The URL path (e.g., '/docs', '/api/reference')\r\n */\r\n path: string;\r\n /**\r\n * Description of what this route contains\r\n */\r\n description: string;\r\n /**\r\n * Optional: Page type for automatic JSON-LD schema injection\r\n * - 'scoring': Injects Methodology schema with AIO scoring weights (40/35/25)\r\n * - 'about': Injects Organization/AboutPage schema\r\n * - 'default': No automatic schema injection\r\n */\r\n pageType?: PageType;\r\n}\r\n\r\nexport interface OntoConfig {\r\n /**\r\n * The name of your project or site (required)\r\n * Used as the H1 heading in llms.txt\r\n */\r\n name: string;\r\n\r\n /**\r\n * A short summary of your project (required)\r\n * Displayed as a blockquote in llms.txt\r\n * Should contain key information necessary for understanding the rest of the file\r\n */\r\n summary: string;\r\n\r\n /**\r\n * The base URL of your site (e.g., 'https://example.com')\r\n */\r\n baseUrl: string;\r\n\r\n /**\r\n * Optional: Additional sections to include in llms.txt\r\n * Each section can contain any markdown content\r\n */\r\n sections?: {\r\n heading: string;\r\n content: string;\r\n }[];\r\n\r\n /**\r\n * Key routes that AI agents should know about\r\n * These will be formatted as a markdown list in llms.txt\r\n */\r\n routes?: OntoRoute[];\r\n\r\n /**\r\n * Optional: Links to external resources (documentation, API references, etc.)\r\n */\r\n externalLinks?: {\r\n title: string;\r\n url: string;\r\n description?: string;\r\n }[];\r\n\r\n /**\r\n * Optional: Organization information for JSON-LD schemas\r\n */\r\n organization?: {\r\n name: string;\r\n description?: string;\r\n url?: string;\r\n logo?: string;\r\n foundingDate?: string;\r\n };\r\n}\r\n\r\n/**\r\n * Generate llms.txt content from OntoConfig\r\n * Follows the llms.txt specification:\r\n * - H1 with project name\r\n * - Blockquote with summary\r\n * - Additional markdown sections\r\n */\r\nexport function generateLlmsTxt(config: OntoConfig): string {\r\n const lines: string[] = [];\r\n\r\n // H1: Project name (required)\r\n lines.push(`# ${config.name}`);\r\n lines.push('');\r\n\r\n // Blockquote: Summary (required)\r\n lines.push(`> ${config.summary}`);\r\n lines.push('');\r\n\r\n // Key Routes section (if provided)\r\n if (config.routes && config.routes.length > 0) {\r\n lines.push('## Key Routes');\r\n lines.push('');\r\n for (const route of config.routes) {\r\n const fullUrl = `${config.baseUrl}${route.path}`;\r\n lines.push(`- [${route.path}](${fullUrl}): ${route.description}`);\r\n }\r\n lines.push('');\r\n }\r\n\r\n // External Links section (if provided)\r\n if (config.externalLinks && config.externalLinks.length > 0) {\r\n lines.push('## Resources');\r\n lines.push('');\r\n for (const link of config.externalLinks) {\r\n if (link.description) {\r\n lines.push(`- [${link.title}](${link.url}): ${link.description}`);\r\n } else {\r\n lines.push(`- [${link.title}](${link.url})`);\r\n }\r\n }\r\n lines.push('');\r\n }\r\n\r\n // Custom sections (if provided)\r\n if (config.sections && config.sections.length > 0) {\r\n for (const section of config.sections) {\r\n lines.push(`## ${section.heading}`);\r\n lines.push('');\r\n lines.push(section.content);\r\n lines.push('');\r\n }\r\n }\r\n\r\n return lines.join('\\n').trim() + '\\n';\r\n}\r\n"],"mappings":";wdACA,IAAAA,EAAqB,gBACrBC,EAAe,iBACfC,EAAiB,mBACjBC,EAAe,yBCJf,IAAAC,EAAyB,sBACzBC,EAA4B,uBAEtBC,EAAkB,IAAI,EAAAC,QAAgB,CACxC,aAAc,MACd,eAAgB,QACpB,CAAC,EAwBM,SAASC,EAAeC,EAAcC,EAAoB,mBAAsC,CACnG,IAAMC,EAAeF,EAAK,OAEpBG,EAAY,OAAKH,CAAI,EAGrBI,EAAQD,EAAE,OAAO,EAAE,KAAK,GAAKA,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,GAAK,gBACvDE,EAAcF,EAAE,0BAA0B,EA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AG,WAAWsC,CAAS,GACxB,EAAAtC,QAAG,UAAUsC,EAAW,CAAE,UAAW,EAAK,CAAC,EAG/C,EAAAtC,QAAG,cAAcqC,EAAaF,EAAgB,MAAM,EACpD,QAAQ,IAAI,EAAA3B,QAAG,MAAM,kBAAa,EAAI,EAAAA,QAAG,IAAI,YAAY,CAAC,CAC9D,CAEA,QAAQ,IAAI,EAAAA,QAAG,IAAI;AAAA,CAA8C,CAAC,CACtE,CAEAC,EAAK,EAAE,MAAMkB,GAAK,CACd,QAAQ,MAAM,EAAAnB,QAAG,IAAI,uBAAuBmB,EAAE,OAAO,EAAE,CAAC,EACxD,QAAQ,KAAK,CAAC,CAClB,CAAC","names":["import_glob","import_fs","import_path","import_picocolors","cheerio","import_turndown","turndownService","TurndownService","extractContent","html","sourceUrl","originalSize","$","title","description","jsonLdScripts","_","el","raw","parsed","contentHtml","markdown","finalMarkdown","j","markdownSize","tokenReductionRatio","generateLlmsTxt","config","lines","route","fullUrl","link","section","loadOntoConfig","cwd","config","path","loadEnv","envPath","fs","line","trimmedLine","key","valueParts","init","configPath","middlewarePath","pc","main","nextAppDirDir","ontoPublicDir","files","totalOriginalSize","totalMarkdownSize","totalFilesProcessed","file","inputPath","outputPathRelative","outputPath","htmlContent","result","extractContent","outputDir","origKb","mdKb","routeName","e","ONTO_API_KEY","DASHBOARD_URL","manifest","route","mdPath","res","errData","llmsTxtContent","generateLlmsTxt","llmsTxtPath","publicDir"]}
|
package/dist/cli.mjs
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{glob as R}from"glob";import s from"fs";import
|
|
2
|
+
import{glob as R}from"glob";import s from"fs";import a from"path";import i from"picocolors";import*as P from"cheerio";import C from"turndown";var T=new C({headingStyle:"atx",codeBlockStyle:"fenced"});function k(n,o="Generated Output"){let t=n.length,e=P.load(n),r=e("title").text()||e("h1").first().text()||"Untitled Page",p=e('meta[name="description"]').attr("content")||"No description found.",g=[];e('script[type="application/ld+json"]').each((m,l)=>{try{let u=e(l).html()||"",h=JSON.parse(u);g.push(h)}catch{}}),e("script, style, noscript, iframe, svg, nav, footer, meta, link, header").remove();let f="";e("main").length>0?f=e("main").html()||"":e("article").length>0?f=e("article").html()||"":f=e("body").html()||"";let x=T.turndown(f),d=[`# ${r}`,`> ${p}`,"",`**Source:** ${o}`,`**Extracted:** ${new Date().toISOString()}`,"","---",""].join(`
|
|
3
3
|
`)+x;g.length>0&&(d+=`
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
## Structured Data (JSON-LD)
|
|
7
7
|
\`\`\`json
|
|
8
|
-
`,g.forEach(
|
|
9
|
-
`}),d+="```\n");let w=d.length,
|
|
8
|
+
`,g.forEach(m=>{d+=JSON.stringify(m,null,2)+`
|
|
9
|
+
`}),d+="```\n");let w=d.length,c=t>0?(t-w)/t*100:0;return{markdown:d,metadata:{title:r,description:p,jsonLd:g},stats:{originalHtmlSize:t,markdownSize:w,tokenReductionRatio:c}}}function j(n){let o=[];if(o.push(`# ${n.name}`),o.push(""),o.push(`> ${n.summary}`),o.push(""),n.routes&&n.routes.length>0){o.push("## Key Routes"),o.push("");for(let t of n.routes){let e=`${n.baseUrl}${t.path}`;o.push(`- [${t.path}](${e}): ${t.description}`)}o.push("")}if(n.externalLinks&&n.externalLinks.length>0){o.push("## Resources"),o.push("");for(let t of n.externalLinks)t.description?o.push(`- [${t.title}](${t.url}): ${t.description}`):o.push(`- [${t.title}](${t.url})`);o.push("")}if(n.sections&&n.sections.length>0)for(let t of n.sections)o.push(`## ${t.heading}`),o.push(""),o.push(t.content),o.push("");return o.join(`
|
|
10
10
|
`).trim()+`
|
|
11
|
-
`}async function F(){try{let e=await import("file
|
|
12
|
-
[Onto] Initializing project...`)),s.existsSync(
|
|
11
|
+
`}async function F(){let n=process.cwd();try{let e=await import("file:///"+a.join(n,"onto.config").replace(/\\/g,"/")+".ts");return e.default||e}catch{try{let r=await import("file:///"+a.join(n,"onto.config").replace(/\\/g,"/")+".js");return r.default||r}catch{return null}}}function z(){let n=a.join(process.cwd(),".env.local");s.existsSync(n)&&s.readFileSync(n,"utf8").split(/\r?\n/).forEach(t=>{let e=t.trim();if(!e||e.startsWith("#"))return;let[r,...p]=e.split("=");r&&p.length>0&&(process.env[r.trim()]=p.join("=").trim().replace(/^["']|["']$/g,""))})}async function L(){let n=process.cwd(),o=a.join(n,"onto.config.ts"),t=a.join(n,"middleware.ts");console.log(i.cyan(`
|
|
12
|
+
[Onto] Initializing project...`)),s.existsSync(o)?console.log(i.yellow("\u2139 onto.config.ts already exists, skipping.")):(s.writeFileSync(o,`import { OntoConfig } from '@ontosdk/next';
|
|
13
13
|
|
|
14
14
|
const config: OntoConfig = {
|
|
15
15
|
name: 'My Project',
|
|
16
16
|
summary: 'A short description of my project for AI agents.',
|
|
17
|
+
baseUrl: 'https://example.com',
|
|
17
18
|
routes: [
|
|
18
19
|
{
|
|
19
20
|
path: '/',
|
|
@@ -24,7 +25,7 @@ const config: OntoConfig = {
|
|
|
24
25
|
};
|
|
25
26
|
|
|
26
27
|
export default config;
|
|
27
|
-
`,"utf8"),console.log(
|
|
28
|
+
`,"utf8"),console.log(i.green("\u2713 Created")+" onto.config.ts")),s.existsSync(t)?console.log(i.yellow("\u2139 middleware.ts already exists, skipping.")):(s.writeFileSync(t,`import { NextRequest } from 'next/server';
|
|
28
29
|
import { ontoMiddleware } from '@ontosdk/next/middleware';
|
|
29
30
|
import ontoConfig from './onto.config';
|
|
30
31
|
|
|
@@ -42,9 +43,9 @@ export const config = {
|
|
|
42
43
|
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
|
|
43
44
|
],
|
|
44
45
|
};
|
|
45
|
-
`,"utf8"),console.log(
|
|
46
|
-
Initialization complete! \u{1F680}`)),console.log(
|
|
47
|
-
`))}async function N(){if(process.argv.slice(2)[0]==="init"){await L();return}z(),console.log(
|
|
48
|
-
[Onto] Starting Semantic Output Generation...`));let t=process.cwd(),
|
|
49
|
-
`))}N().catch(
|
|
46
|
+
`,"utf8"),console.log(i.green("\u2713 Created")+" middleware.ts")),console.log(i.magenta(`
|
|
47
|
+
Initialization complete! \u{1F680}`)),console.log(i.dim("Next steps:")),console.log(i.dim("1. Update your routes in onto.config.ts")),console.log(i.dim(`2. Run "npm run build" to generate manifests
|
|
48
|
+
`))}async function N(){if(process.argv.slice(2)[0]==="init"){await L();return}z(),console.log(i.cyan(`
|
|
49
|
+
[Onto] Starting Semantic Output Generation...`));let t=process.cwd(),e=a.join(t,".next/server/app"),r=a.join(t,"public/.onto");if(!s.existsSync(e)){console.log(i.yellow(`[Onto] Could not find Next.js app output at ${e}`)),console.log(i.yellow('[Onto] Ensure this is run after "next build" and you are using the App Router.'));return}let p=await R("**/*.html",{cwd:e});if(p.length===0){console.log(i.yellow("[Onto] No static HTML files found to process."));return}s.existsSync(r)||s.mkdirSync(r,{recursive:!0});let g=0,f=0,x=0;for(let c of p){let m=a.join(e,c),l=c.replace(/\.html$/,".md"),u=a.join(r,l);try{let h=s.readFileSync(m,"utf8"),y=k(h,`/${l.replace(/\.md$/,"")}`),O=a.dirname(u);s.existsSync(O)||s.mkdirSync(O,{recursive:!0}),s.writeFileSync(u,y.markdown,"utf8"),g+=y.stats.originalHtmlSize,f+=y.stats.markdownSize,x++;let v=(y.stats.originalHtmlSize/1024).toFixed(1),b=(y.stats.markdownSize/1024).toFixed(1),S=c.replace(/\.html$/,"");S==="index"?S="/":S=`/${S}`,console.log(i.green("\u2713 Optimized")+i.dim(` ${S} `)+i.blue(`[${v}KB -> ${b}KB]`))}catch(h){console.error(i.red(`\u2717 Failed to process ${c}: ${h.message}`))}}console.log(i.bold(i.magenta(`Processed ${x} pages. Total Size: ${(g/1024).toFixed(1)}KB -> ${(f/1024).toFixed(1)}KB`)));let $=process.env.ONTO_API_KEY,d=process.env.ONTO_DASHBOARD_URL||"https://app.buildonto.dev";if($&&x>0){console.log(i.cyan(`[Onto] Syncing manifest with Control Plane [${d}]...`));try{let c=p.map(l=>{let u=l.replace(/\.html$/,""),h=u==="index"?"/":`/${u}`,y=a.join(r,l.replace(/\.html$/,".md"));return{route:h,filename:`${u}.md`,content:s.readFileSync(y,"utf8")}}),m=await fetch(`${d}/api/files`,{method:"POST",headers:{"x-onto-key":$,"Content-Type":"application/json"},body:JSON.stringify({files:c})});if(m.ok)console.log(i.green("\u2713 Control Plane sync successful"));else{let l=await m.json().catch(()=>({}));console.log(i.yellow(`\u26A0 Control Plane sync skipped: ${l.error||m.statusText}`))}}catch(c){console.log(i.yellow(`\u26A0 Control Plane sync failed: ${c.message}`))}}let w=await F();if(w){let c=j(w),m=a.join(t,"public/llms.txt"),l=a.join(t,"public");s.existsSync(l)||s.mkdirSync(l,{recursive:!0}),s.writeFileSync(m,c,"utf8"),console.log(i.green("\u2713 Generated")+i.dim(" /llms.txt"))}console.log(i.dim(`Edge payloads are ready at /public/.onto/*
|
|
50
|
+
`))}N().catch(n=>{console.error(i.red(`[Onto] Fatal Error: ${n.message}`)),process.exit(1)});
|
|
50
51
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/extractor.ts","../src/config.ts"],"sourcesContent":["#!/usr/bin/env node\r\nimport { glob } from 'glob';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport pc from 'picocolors';\r\nimport { extractContent } from './extractor';\r\nimport { generateLlmsTxt, OntoConfig } from './config';\r\n\r\nasync function loadOntoConfig(): Promise<OntoConfig | null> {\r\n try {\r\n const configPath = path.join(process.cwd(), 'onto.config');\r\n // Node.js dynamic import\r\n const config = await import('file://' + configPath.replace(/\\\\/g, '/') + '.ts');\r\n return config.default || config;\r\n } catch (error) {\r\n try {\r\n const configPath = path.join(process.cwd(), 'onto.config');\r\n const config = await import('file://' + configPath.replace(/\\\\/g, '/') + '.js');\r\n return config.default || config;\r\n } catch (e) {\r\n return null;\r\n }\r\n }\r\n}\r\n\r\n// Simple helper to load .env.local from the current working directory\r\nfunction loadEnv() {\r\n const envPath = path.join(process.cwd(), '.env.local');\r\n if (fs.existsSync(envPath)) {\r\n const envContent = fs.readFileSync(envPath, 'utf8');\r\n envContent.split(/\\r?\\n/).forEach(line => {\r\n const trimmedLine = line.trim();\r\n if (!trimmedLine || trimmedLine.startsWith('#')) return;\r\n const [key, ...valueParts] = trimmedLine.split('=');\r\n if (key && valueParts.length > 0) {\r\n process.env[key.trim()] = valueParts.join('=').trim().replace(/^[\"']|[\"']$/g, '');\r\n }\r\n });\r\n }\r\n}\r\n\r\nasync function init() {\r\n const cwd = process.cwd();\r\n const configPath = path.join(cwd, 'onto.config.ts');\r\n const middlewarePath = path.join(cwd, 'middleware.ts');\r\n\r\n console.log(pc.cyan('\\n[Onto] Initializing project...'));\r\n\r\n // 1. Create onto.config.ts\r\n if (!fs.existsSync(configPath)) {\r\n const configTemplate = `import { OntoConfig } from '@ontosdk/next';\r\n\r\nconst config: OntoConfig = {\r\n name: 'My Project',\r\n summary: 'A short description of my project for AI agents.',\r\n routes: [\r\n { \r\n path: '/', \r\n description: 'The homepage of my application.',\r\n pageType: 'about'\r\n }\r\n ]\r\n};\r\n\r\nexport default config;\r\n`;\r\n fs.writeFileSync(configPath, configTemplate, 'utf8');\r\n console.log(pc.green('✓ Created') + ' onto.config.ts');\r\n } else {\r\n console.log(pc.yellow('ℹ onto.config.ts already exists, skipping.'));\r\n }\r\n\r\n // 2. Create middleware.ts\r\n if (!fs.existsSync(middlewarePath)) {\r\n const middlewareTemplate = `import { NextRequest } from 'next/server';\r\nimport { ontoMiddleware } from '@ontosdk/next/middleware';\r\nimport ontoConfig from './onto.config';\r\n\r\nexport const middleware = (req: NextRequest) => ontoMiddleware(req, ontoConfig);\r\n\r\nexport const config = {\r\n matcher: [\r\n /*\r\n * Match all request paths except for the ones starting with:\r\n * - api (API routes)\r\n * - _next/static (static files)\r\n * - _next/image (image optimization files)\r\n * - favicon.ico, sitemap.xml, robots.txt (metadata files)\r\n */\r\n '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',\r\n ],\r\n};\r\n`;\r\n fs.writeFileSync(middlewarePath, middlewareTemplate, 'utf8');\r\n console.log(pc.green('✓ Created') + ' middleware.ts');\r\n } else {\r\n console.log(pc.yellow('ℹ middleware.ts already exists, skipping.'));\r\n }\r\n\r\n console.log(pc.magenta('\\nInitialization complete! 🚀'));\r\n console.log(pc.dim('Next steps:'));\r\n console.log(pc.dim('1. Update your routes in onto.config.ts'));\r\n console.log(pc.dim('2. Run \"npm run build\" to generate manifests\\n'));\r\n}\r\n\r\nasync function main() {\r\n const args = process.argv.slice(2);\r\n const command = args[0];\r\n\r\n if (command === 'init') {\r\n await init();\r\n return;\r\n }\r\n\r\n loadEnv();\r\n console.log(pc.cyan('\\n[Onto] Starting Semantic Output Generation...'));\r\n // ... rest of the existing main function logic ...\r\n\r\n const cwd = process.cwd();\r\n const nextAppDirDir = path.join(cwd, '.next/server/app');\r\n const ontoPublicDir = path.join(cwd, 'public/.onto');\r\n\r\n if (!fs.existsSync(nextAppDirDir)) {\r\n console.log(pc.yellow(`[Onto] Could not find Next.js app output at ${nextAppDirDir}`));\r\n console.log(pc.yellow(`[Onto] Ensure this is run after \"next build\" and you are using the App Router.`));\r\n return;\r\n }\r\n\r\n // Find all HTML files rendered by Next.js in the app directory\r\n const files = await glob('**/*.html', { cwd: nextAppDirDir });\r\n\r\n if (files.length === 0) {\r\n console.log(pc.yellow(`[Onto] No static HTML files found to process.`));\r\n return;\r\n }\r\n\r\n // Ensure output directory exists\r\n if (!fs.existsSync(ontoPublicDir)) {\r\n fs.mkdirSync(ontoPublicDir, { recursive: true });\r\n }\r\n\r\n let totalOriginalSize = 0;\r\n let totalMarkdownSize = 0;\r\n let totalFilesProcessed = 0;\r\n\r\n for (const file of files) {\r\n const inputPath = path.join(nextAppDirDir, file);\r\n\r\n // We map file path e.g. \"pricing.html\" to \"pricing.md\", or \"blog/post.html\" to \"blog/post.md\"\r\n let outputPathRelative = file.replace(/\\.html$/, '.md');\r\n // If it's a dynamic route page, or purely root index.html\r\n const outputPath = path.join(ontoPublicDir, outputPathRelative);\r\n\r\n try {\r\n const htmlContent = fs.readFileSync(inputPath, 'utf8');\r\n\r\n const result = extractContent(htmlContent, `/${outputPathRelative.replace(/\\.md$/, '')}`);\r\n\r\n // Ensure specific sub-directory exists (e.g., for blog/post.md)\r\n const outputDir = path.dirname(outputPath);\r\n if (!fs.existsSync(outputDir)) {\r\n fs.mkdirSync(outputDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(outputPath, result.markdown, 'utf8');\r\n\r\n totalOriginalSize += result.stats.originalHtmlSize;\r\n totalMarkdownSize += result.stats.markdownSize;\r\n totalFilesProcessed++;\r\n\r\n const origKb = (result.stats.originalHtmlSize / 1024).toFixed(1);\r\n const mdKb = (result.stats.markdownSize / 1024).toFixed(1);\r\n\r\n // /index.html -> /\r\n let routeName = file.replace(/\\.html$/, '');\r\n if (routeName === 'index') routeName = '/';\r\n else routeName = `/${routeName}`;\r\n\r\n console.log(\r\n pc.green(`✓ Optimized`) +\r\n pc.dim(` ${routeName} `) +\r\n pc.blue(`[${origKb}KB -> ${mdKb}KB]`)\r\n );\r\n } catch (e: any) {\r\n console.error(pc.red(`✗ Failed to process ${file}: ${e.message}`));\r\n }\r\n }\r\n\r\n console.log(\r\n pc.bold(\r\n pc.magenta(`Processed ${totalFilesProcessed} pages. Total Size: ${(totalOriginalSize / 1024).toFixed(1)}KB -> ${(totalMarkdownSize / 1024).toFixed(1)}KB`)\r\n )\r\n );\r\n\r\n // Sync with Onto Control Plane (Premium)\r\n const ONTO_API_KEY = process.env.ONTO_API_KEY;\r\n const DASHBOARD_URL = process.env.ONTO_DASHBOARD_URL || 'https://app.buildonto.dev';\r\n\r\n if (ONTO_API_KEY && totalFilesProcessed > 0) {\r\n console.log(pc.cyan(`[Onto] Syncing manifest with Control Plane [${DASHBOARD_URL}]...`));\r\n try {\r\n const manifest = files.map(file => {\r\n const routeName = file.replace(/\\.html$/, '');\r\n const route = routeName === 'index' ? '/' : `/${routeName}`;\r\n const mdPath = path.join(ontoPublicDir, file.replace(/\\.html$/, '.md'));\r\n return {\r\n route,\r\n filename: `${routeName}.md`,\r\n content: fs.readFileSync(mdPath, 'utf8')\r\n };\r\n });\r\n\r\n const res = await fetch(`${DASHBOARD_URL}/api/files`, {\r\n method: 'POST',\r\n headers: {\r\n 'x-onto-key': ONTO_API_KEY,\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({ files: manifest })\r\n });\r\n\r\n if (res.ok) {\r\n console.log(pc.green('✓ Control Plane sync successful'));\r\n } else {\r\n const errData = await res.json().catch(() => ({}));\r\n console.log(pc.yellow(`⚠ Control Plane sync skipped: ${errData.error || res.statusText}`));\r\n }\r\n } catch (e: any) {\r\n console.log(pc.yellow(`⚠ Control Plane sync failed: ${e.message}`));\r\n }\r\n }\r\n\r\n // --- Generate llms.txt manifest ---\r\n const config = await loadOntoConfig();\r\n if (config) {\r\n const llmsTxtContent = generateLlmsTxt(config);\r\n const llmsTxtPath = path.join(cwd, 'public/llms.txt');\r\n \r\n // Ensure public dir exists\r\n const publicDir = path.join(cwd, 'public');\r\n if (!fs.existsSync(publicDir)) {\r\n fs.mkdirSync(publicDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(llmsTxtPath, llmsTxtContent, 'utf8');\r\n console.log(pc.green('✓ Generated') + pc.dim(' /llms.txt'));\r\n }\r\n\r\n console.log(pc.dim(`Edge payloads are ready at /public/.onto/*\\n`));\r\n}\r\n\r\nmain().catch(e => {\r\n console.error(pc.red(`[Onto] Fatal Error: ${e.message}`));\r\n process.exit(1);\r\n});\r\n","import * as cheerio from 'cheerio';\r\nimport TurndownService from 'turndown';\r\n\r\nconst turndownService = new TurndownService({\r\n headingStyle: 'atx',\r\n codeBlockStyle: 'fenced',\r\n});\r\n\r\n// Configure turndown to keep some layout or handle semantic tags differently if needed\r\n\r\nexport interface ExtractionResult {\r\n markdown: string;\r\n metadata: {\r\n title: string;\r\n description: string;\r\n jsonLd: any[];\r\n };\r\n stats: {\r\n originalHtmlSize: number;\r\n markdownSize: number;\r\n tokenReductionRatio: number;\r\n };\r\n}\r\n\r\n/**\r\n * Extracts pure semantic markdown and metadata from rendered Next.js HTML strings.\r\n * @param html The raw HTML string.\r\n * @param sourceUrl (Optional) the URL this was generated from, to attach as metadata.\r\n * @returns {ExtractionResult} The extracted payload.\r\n */\r\nexport function extractContent(html: string, sourceUrl: string = 'Generated Output'): ExtractionResult {\r\n const originalSize = html.length;\r\n\r\n const $ = cheerio.load(html);\r\n\r\n // 1. Extract Metadata BEFORE removing structure\r\n const title = $('title').text() || $('h1').first().text() || 'Untitled Page';\r\n const description = $('meta[name=\"description\"]').attr('content') || 'No description found.';\r\n\r\n const jsonLdScripts: any[] = [];\r\n $('script[type=\"application/ld+json\"]').each((_, el) => {\r\n try {\r\n const raw = $(el).html() || '';\r\n const parsed = JSON.parse(raw);\r\n jsonLdScripts.push(parsed);\r\n } catch {\r\n // ignore bad json\r\n }\r\n });\r\n\r\n // 2. Strip noise (React boilerplate, styles, unnecessary tags)\r\n $('script, style, noscript, iframe, svg, nav, footer, meta, link, header').remove();\r\n\r\n // Optionally remove typical Next.js hidden wrappers if they don't contain real content.\r\n // Next.js uses <div id=\"__next\"> but we mostly just want semantic content.\r\n\r\n // 3. Find the entry point for content\r\n // Prefer <main> or <article> over <body>\r\n let contentHtml = '';\r\n if ($('main').length > 0) {\r\n contentHtml = $('main').html() || '';\r\n } else if ($('article').length > 0) {\r\n contentHtml = $('article').html() || '';\r\n } else {\r\n contentHtml = $('body').html() || '';\r\n }\r\n\r\n // 4. Convert to Markdown\r\n let markdown = turndownService.turndown(contentHtml);\r\n\r\n // 5. Optionally inject Metadata header\r\n const headerLines = [\r\n `# ${title}`,\r\n `> ${description}`,\r\n ``,\r\n `**Source:** ${sourceUrl}`,\r\n `**Extracted:** ${new Date().toISOString()}`,\r\n ``,\r\n `---`,\r\n ``\r\n ];\r\n\r\n let finalMarkdown = headerLines.join('\\n') + markdown;\r\n\r\n // Add JSON-LD section if exists\r\n if (jsonLdScripts.length > 0) {\r\n finalMarkdown += '\\n\\n---\\n## Structured Data (JSON-LD)\\n```json\\n';\r\n jsonLdScripts.forEach(j => {\r\n finalMarkdown += JSON.stringify(j, null, 2) + '\\n';\r\n });\r\n finalMarkdown += '```\\n';\r\n }\r\n\r\n const markdownSize = finalMarkdown.length;\r\n const tokenReductionRatio = originalSize > 0 ? ((originalSize - markdownSize) / originalSize) * 100 : 0;\r\n\r\n return {\r\n markdown: finalMarkdown,\r\n metadata: {\r\n title,\r\n description,\r\n jsonLd: jsonLdScripts\r\n },\r\n stats: {\r\n originalHtmlSize: originalSize,\r\n markdownSize,\r\n tokenReductionRatio\r\n }\r\n };\r\n}\r\n\r\nexport async function generateStaticPayloads(nextAppDirDir: string, ontoPublicDir: string) {\r\n const fs = await import('fs');\r\n const path = await import('path');\r\n const { glob } = await import('glob');\r\n\r\n if (!fs.existsSync(nextAppDirDir)) {\r\n return;\r\n }\r\n\r\n const files = await glob('**/*.html', { cwd: nextAppDirDir });\r\n if (files.length === 0) return;\r\n\r\n if (!fs.existsSync(ontoPublicDir)) {\r\n fs.mkdirSync(ontoPublicDir, { recursive: true });\r\n }\r\n\r\n let totalFilesProcessed = 0;\r\n\r\n for (const file of files) {\r\n const inputPath = path.join(nextAppDirDir, file);\r\n const outputPathRelative = file.replace(/\\.html$/, '.md');\r\n const outputPath = path.join(ontoPublicDir, outputPathRelative);\r\n\r\n try {\r\n const htmlContent = fs.readFileSync(inputPath, 'utf8');\r\n\r\n let routeName = file.replace(/\\.html$/, '');\r\n if (routeName === 'index') routeName = '/';\r\n else routeName = `/${routeName}`;\r\n\r\n const result = extractContent(htmlContent, routeName);\r\n\r\n const outputDir = path.dirname(outputPath);\r\n if (!fs.existsSync(outputDir)) {\r\n fs.mkdirSync(outputDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(outputPath, result.markdown, 'utf8');\r\n totalFilesProcessed++;\r\n } catch (e: any) {\r\n console.error(`[Onto] Failed to process ${file}: ${e.message}`);\r\n }\r\n }\r\n console.log(`[Onto] Successfully generated ${totalFilesProcessed} semantic markdown endpoints.`);\r\n}\r\n","/**\r\n * Configuration schema for onto.config.ts\r\n * Used to dynamically generate llms.txt and other AI discovery files\r\n */\r\n\r\nexport type PageType = 'scoring' | 'about' | 'default';\r\n\r\nexport interface OntoRoute {\r\n /**\r\n * The URL path (e.g., '/docs', '/api/reference')\r\n */\r\n path: string;\r\n /**\r\n * Description of what this route contains\r\n */\r\n description: string;\r\n /**\r\n * Optional: Page type for automatic JSON-LD schema injection\r\n * - 'scoring': Injects Methodology schema with AIO scoring weights (40/35/25)\r\n * - 'about': Injects Organization/AboutPage schema\r\n * - 'default': No automatic schema injection\r\n */\r\n pageType?: PageType;\r\n}\r\n\r\nexport interface OntoConfig {\r\n /**\r\n * The name of your project or site (required)\r\n * Used as the H1 heading in llms.txt\r\n */\r\n name: string;\r\n\r\n /**\r\n * A short summary of your project (required)\r\n * Displayed as a blockquote in llms.txt\r\n * Should contain key information necessary for understanding the rest of the file\r\n */\r\n summary: string;\r\n\r\n /**\r\n * The base URL of your site (e.g., 'https://example.com')\r\n */\r\n baseUrl: string;\r\n\r\n /**\r\n * Optional: Additional sections to include in llms.txt\r\n * Each section can contain any markdown content\r\n */\r\n sections?: {\r\n heading: string;\r\n content: string;\r\n }[];\r\n\r\n /**\r\n * Key routes that AI agents should know about\r\n * These will be formatted as a markdown list in llms.txt\r\n */\r\n routes?: OntoRoute[];\r\n\r\n /**\r\n * Optional: Links to external resources (documentation, API references, etc.)\r\n */\r\n externalLinks?: {\r\n title: string;\r\n url: string;\r\n description?: string;\r\n }[];\r\n\r\n /**\r\n * Optional: Organization information for JSON-LD schemas\r\n */\r\n organization?: {\r\n name: string;\r\n description?: string;\r\n url?: string;\r\n logo?: string;\r\n foundingDate?: string;\r\n };\r\n}\r\n\r\n/**\r\n * Generate llms.txt content from OntoConfig\r\n * Follows the llms.txt specification:\r\n * - H1 with project name\r\n * - Blockquote with summary\r\n * - Additional markdown sections\r\n */\r\nexport function generateLlmsTxt(config: OntoConfig): string {\r\n const lines: string[] = [];\r\n\r\n // H1: Project name (required)\r\n lines.push(`# ${config.name}`);\r\n lines.push('');\r\n\r\n // Blockquote: Summary (required)\r\n lines.push(`> ${config.summary}`);\r\n lines.push('');\r\n\r\n // Key Routes section (if provided)\r\n if (config.routes && config.routes.length > 0) {\r\n lines.push('## Key Routes');\r\n lines.push('');\r\n for (const route of config.routes) {\r\n const fullUrl = `${config.baseUrl}${route.path}`;\r\n lines.push(`- [${route.path}](${fullUrl}): ${route.description}`);\r\n }\r\n lines.push('');\r\n }\r\n\r\n // External Links section (if provided)\r\n if (config.externalLinks && config.externalLinks.length > 0) {\r\n lines.push('## Resources');\r\n lines.push('');\r\n for (const link of config.externalLinks) {\r\n if (link.description) {\r\n lines.push(`- [${link.title}](${link.url}): ${link.description}`);\r\n } else {\r\n lines.push(`- [${link.title}](${link.url})`);\r\n }\r\n }\r\n lines.push('');\r\n }\r\n\r\n // Custom sections (if provided)\r\n if (config.sections && config.sections.length > 0) {\r\n for (const section of config.sections) {\r\n lines.push(`## ${section.heading}`);\r\n lines.push('');\r\n lines.push(section.content);\r\n lines.push('');\r\n }\r\n }\r\n\r\n return lines.join('\\n').trim() + '\\n';\r\n}\r\n"],"mappings":";AACA,OAAS,QAAAA,MAAY,OACrB,OAAOC,MAAQ,KACf,OAAOC,MAAU,OACjB,OAAOC,MAAQ,aCJf,UAAYC,MAAa,UACzB,OAAOC,MAAqB,WAE5B,IAAMC,EAAkB,IAAID,EAAgB,CACxC,aAAc,MACd,eAAgB,QACpB,CAAC,EAwBM,SAASE,EAAeC,EAAcC,EAAoB,mBAAsC,CACnG,IAAMC,EAAeF,EAAK,OAEpBG,EAAY,OAAKH,CAAI,EAGrBI,EAAQD,EAAE,OAAO,EAAE,KA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AC,CACtE,CAEAC,EAAK,EAAE,MAAMmB,GAAK,CACd,QAAQ,MAAMpB,EAAG,IAAI,uBAAuBoB,EAAE,OAAO,EAAE,CAAC,EACxD,QAAQ,KAAK,CAAC,CAClB,CAAC","names":["glob","fs","path","pc","cheerio","TurndownService","turndownService","extractContent","html","sourceUrl","originalSize","$","title","description","jsonLdScripts","_","el","raw","parsed","contentHtml","markdown","finalMarkdown","j","markdownSize","tokenReductionRatio","generateLlmsTxt","config","lines","route","fullUrl","link","section","loadOntoConfig","config","path","loadEnv","envPath","fs","line","trimmedLine","key","valueParts","init","cwd","configPath","middlewarePath","pc","main","nextAppDirDir","ontoPublicDir","files","glob","totalOriginalSize","totalMarkdownSize","totalFilesProcessed","file","inputPath","outputPathRelative","outputPath","htmlContent","result","extractContent","outputDir","origKb","mdKb","routeName","e","ONTO_API_KEY","DASHBOARD_URL","manifest","route","mdPath","res","errData","llmsTxtContent","generateLlmsTxt","llmsTxtPath","publicDir"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/extractor.ts","../src/config.ts"],"sourcesContent":["#!/usr/bin/env node\r\nimport { glob } from 'glob';\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport pc from 'picocolors';\r\nimport { extractContent } from './extractor';\r\nimport { generateLlmsTxt, OntoConfig } from './config';\r\n\r\nasync function loadOntoConfig(): Promise<OntoConfig | null> {\r\n const cwd = process.cwd();\r\n try {\r\n const configPath = path.join(cwd, 'onto.config');\r\n // On Windows, file:/// is often required for absolute paths\r\n const tsPath = 'file:///' + configPath.replace(/\\\\/g, '/') + '.ts';\r\n const config = await import(tsPath);\r\n return config.default || config;\r\n } catch (error: any) {\r\n try {\r\n const configPath = path.join(cwd, 'onto.config');\r\n const jsPath = 'file:///' + configPath.replace(/\\\\/g, '/') + '.js';\r\n const config = await import(jsPath);\r\n return config.default || config;\r\n } catch (e: any) {\r\n return null;\r\n }\r\n }\r\n}\r\n\r\n// Simple helper to load .env.local from the current working directory\r\nfunction loadEnv() {\r\n const envPath = path.join(process.cwd(), '.env.local');\r\n if (fs.existsSync(envPath)) {\r\n const envContent = fs.readFileSync(envPath, 'utf8');\r\n envContent.split(/\\r?\\n/).forEach(line => {\r\n const trimmedLine = line.trim();\r\n if (!trimmedLine || trimmedLine.startsWith('#')) return;\r\n const [key, ...valueParts] = trimmedLine.split('=');\r\n if (key && valueParts.length > 0) {\r\n process.env[key.trim()] = valueParts.join('=').trim().replace(/^[\"']|[\"']$/g, '');\r\n }\r\n });\r\n }\r\n}\r\n\r\nasync function init() {\r\n const cwd = process.cwd();\r\n const configPath = path.join(cwd, 'onto.config.ts');\r\n const middlewarePath = path.join(cwd, 'middleware.ts');\r\n\r\n console.log(pc.cyan('\\n[Onto] Initializing project...'));\r\n\r\n // 1. Create onto.config.ts\r\n if (!fs.existsSync(configPath)) {\r\n const configTemplate = `import { OntoConfig } from '@ontosdk/next';\r\n\r\nconst config: OntoConfig = {\r\n name: 'My Project',\r\n summary: 'A short description of my project for AI agents.',\r\n baseUrl: 'https://example.com',\r\n routes: [\r\n { \r\n path: '/', \r\n description: 'The homepage of my application.',\r\n pageType: 'about'\r\n }\r\n ]\r\n};\r\n\r\nexport default config;\r\n`;\r\n fs.writeFileSync(configPath, configTemplate, 'utf8');\r\n console.log(pc.green('✓ Created') + ' onto.config.ts');\r\n } else {\r\n console.log(pc.yellow('ℹ onto.config.ts already exists, skipping.'));\r\n }\r\n\r\n // 2. Create middleware.ts\r\n if (!fs.existsSync(middlewarePath)) {\r\n const middlewareTemplate = `import { NextRequest } from 'next/server';\r\nimport { ontoMiddleware } from '@ontosdk/next/middleware';\r\nimport ontoConfig from './onto.config';\r\n\r\nexport const middleware = (req: NextRequest) => ontoMiddleware(req, ontoConfig);\r\n\r\nexport const config = {\r\n matcher: [\r\n /*\r\n * Match all request paths except for the ones starting with:\r\n * - api (API routes)\r\n * - _next/static (static files)\r\n * - _next/image (image optimization files)\r\n * - favicon.ico, sitemap.xml, robots.txt (metadata files)\r\n */\r\n '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',\r\n ],\r\n};\r\n`;\r\n fs.writeFileSync(middlewarePath, middlewareTemplate, 'utf8');\r\n console.log(pc.green('✓ Created') + ' middleware.ts');\r\n } else {\r\n console.log(pc.yellow('ℹ middleware.ts already exists, skipping.'));\r\n }\r\n\r\n console.log(pc.magenta('\\nInitialization complete! 🚀'));\r\n console.log(pc.dim('Next steps:'));\r\n console.log(pc.dim('1. Update your routes in onto.config.ts'));\r\n console.log(pc.dim('2. Run \"npm run build\" to generate manifests\\n'));\r\n}\r\n\r\nasync function main() {\r\n const args = process.argv.slice(2);\r\n const command = args[0];\r\n\r\n if (command === 'init') {\r\n await init();\r\n return;\r\n }\r\n\r\n loadEnv();\r\n console.log(pc.cyan('\\n[Onto] Starting Semantic Output Generation...'));\r\n // ... rest of the existing main function logic ...\r\n\r\n const cwd = process.cwd();\r\n const nextAppDirDir = path.join(cwd, '.next/server/app');\r\n const ontoPublicDir = path.join(cwd, 'public/.onto');\r\n\r\n if (!fs.existsSync(nextAppDirDir)) {\r\n console.log(pc.yellow(`[Onto] Could not find Next.js app output at ${nextAppDirDir}`));\r\n console.log(pc.yellow(`[Onto] Ensure this is run after \"next build\" and you are using the App Router.`));\r\n return;\r\n }\r\n\r\n // Find all HTML files rendered by Next.js in the app directory\r\n const files = await glob('**/*.html', { cwd: nextAppDirDir });\r\n\r\n if (files.length === 0) {\r\n console.log(pc.yellow(`[Onto] No static HTML files found to process.`));\r\n return;\r\n }\r\n\r\n // Ensure output directory exists\r\n if (!fs.existsSync(ontoPublicDir)) {\r\n fs.mkdirSync(ontoPublicDir, { recursive: true });\r\n }\r\n\r\n let totalOriginalSize = 0;\r\n let totalMarkdownSize = 0;\r\n let totalFilesProcessed = 0;\r\n\r\n for (const file of files) {\r\n const inputPath = path.join(nextAppDirDir, file);\r\n\r\n // We map file path e.g. \"pricing.html\" to \"pricing.md\", or \"blog/post.html\" to \"blog/post.md\"\r\n let outputPathRelative = file.replace(/\\.html$/, '.md');\r\n // If it's a dynamic route page, or purely root index.html\r\n const outputPath = path.join(ontoPublicDir, outputPathRelative);\r\n\r\n try {\r\n const htmlContent = fs.readFileSync(inputPath, 'utf8');\r\n\r\n const result = extractContent(htmlContent, `/${outputPathRelative.replace(/\\.md$/, '')}`);\r\n\r\n // Ensure specific sub-directory exists (e.g., for blog/post.md)\r\n const outputDir = path.dirname(outputPath);\r\n if (!fs.existsSync(outputDir)) {\r\n fs.mkdirSync(outputDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(outputPath, result.markdown, 'utf8');\r\n\r\n totalOriginalSize += result.stats.originalHtmlSize;\r\n totalMarkdownSize += result.stats.markdownSize;\r\n totalFilesProcessed++;\r\n\r\n const origKb = (result.stats.originalHtmlSize / 1024).toFixed(1);\r\n const mdKb = (result.stats.markdownSize / 1024).toFixed(1);\r\n\r\n // /index.html -> /\r\n let routeName = file.replace(/\\.html$/, '');\r\n if (routeName === 'index') routeName = '/';\r\n else routeName = `/${routeName}`;\r\n\r\n console.log(\r\n pc.green(`✓ Optimized`) +\r\n pc.dim(` ${routeName} `) +\r\n pc.blue(`[${origKb}KB -> ${mdKb}KB]`)\r\n );\r\n } catch (e: any) {\r\n console.error(pc.red(`✗ Failed to process ${file}: ${e.message}`));\r\n }\r\n }\r\n\r\n console.log(\r\n pc.bold(\r\n pc.magenta(`Processed ${totalFilesProcessed} pages. Total Size: ${(totalOriginalSize / 1024).toFixed(1)}KB -> ${(totalMarkdownSize / 1024).toFixed(1)}KB`)\r\n )\r\n );\r\n\r\n // Sync with Onto Control Plane (Premium)\r\n const ONTO_API_KEY = process.env.ONTO_API_KEY;\r\n const DASHBOARD_URL = process.env.ONTO_DASHBOARD_URL || 'https://app.buildonto.dev';\r\n\r\n if (ONTO_API_KEY && totalFilesProcessed > 0) {\r\n console.log(pc.cyan(`[Onto] Syncing manifest with Control Plane [${DASHBOARD_URL}]...`));\r\n try {\r\n const manifest = files.map(file => {\r\n const routeName = file.replace(/\\.html$/, '');\r\n const route = routeName === 'index' ? '/' : `/${routeName}`;\r\n const mdPath = path.join(ontoPublicDir, file.replace(/\\.html$/, '.md'));\r\n return {\r\n route,\r\n filename: `${routeName}.md`,\r\n content: fs.readFileSync(mdPath, 'utf8')\r\n };\r\n });\r\n\r\n const res = await fetch(`${DASHBOARD_URL}/api/files`, {\r\n method: 'POST',\r\n headers: {\r\n 'x-onto-key': ONTO_API_KEY,\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({ files: manifest })\r\n });\r\n\r\n if (res.ok) {\r\n console.log(pc.green('✓ Control Plane sync successful'));\r\n } else {\r\n const errData = await res.json().catch(() => ({}));\r\n console.log(pc.yellow(`⚠ Control Plane sync skipped: ${errData.error || res.statusText}`));\r\n }\r\n } catch (e: any) {\r\n console.log(pc.yellow(`⚠ Control Plane sync failed: ${e.message}`));\r\n }\r\n }\r\n\r\n // --- Generate llms.txt manifest ---\r\n const config = await loadOntoConfig();\r\n if (config) {\r\n const llmsTxtContent = generateLlmsTxt(config);\r\n const llmsTxtPath = path.join(cwd, 'public/llms.txt');\r\n \r\n // Ensure public dir exists\r\n const publicDir = path.join(cwd, 'public');\r\n if (!fs.existsSync(publicDir)) {\r\n fs.mkdirSync(publicDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(llmsTxtPath, llmsTxtContent, 'utf8');\r\n console.log(pc.green('✓ Generated') + pc.dim(' /llms.txt'));\r\n }\r\n\r\n console.log(pc.dim(`Edge payloads are ready at /public/.onto/*\\n`));\r\n}\r\n\r\nmain().catch(e => {\r\n console.error(pc.red(`[Onto] Fatal Error: ${e.message}`));\r\n process.exit(1);\r\n});\r\n","import * as cheerio from 'cheerio';\r\nimport TurndownService from 'turndown';\r\n\r\nconst turndownService = new TurndownService({\r\n headingStyle: 'atx',\r\n codeBlockStyle: 'fenced',\r\n});\r\n\r\n// Configure turndown to keep some layout or handle semantic tags differently if needed\r\n\r\nexport interface ExtractionResult {\r\n markdown: string;\r\n metadata: {\r\n title: string;\r\n description: string;\r\n jsonLd: any[];\r\n };\r\n stats: {\r\n originalHtmlSize: number;\r\n markdownSize: number;\r\n tokenReductionRatio: number;\r\n };\r\n}\r\n\r\n/**\r\n * Extracts pure semantic markdown and metadata from rendered Next.js HTML strings.\r\n * @param html The raw HTML string.\r\n * @param sourceUrl (Optional) the URL this was generated from, to attach as metadata.\r\n * @returns {ExtractionResult} The extracted payload.\r\n */\r\nexport function extractContent(html: string, sourceUrl: string = 'Generated Output'): ExtractionResult {\r\n const originalSize = html.length;\r\n\r\n const $ = cheerio.load(html);\r\n\r\n // 1. Extract Metadata BEFORE removing structure\r\n const title = $('title').text() || $('h1').first().text() || 'Untitled Page';\r\n const description = $('meta[name=\"description\"]').attr('content') || 'No description found.';\r\n\r\n const jsonLdScripts: any[] = [];\r\n $('script[type=\"application/ld+json\"]').each((_, el) => {\r\n try {\r\n const raw = $(el).html() || '';\r\n const parsed = JSON.parse(raw);\r\n jsonLdScripts.push(parsed);\r\n } catch {\r\n // ignore bad json\r\n }\r\n });\r\n\r\n // 2. Strip noise (React boilerplate, styles, unnecessary tags)\r\n $('script, style, noscript, iframe, svg, nav, footer, meta, link, header').remove();\r\n\r\n // Optionally remove typical Next.js hidden wrappers if they don't contain real content.\r\n // Next.js uses <div id=\"__next\"> but we mostly just want semantic content.\r\n\r\n // 3. Find the entry point for content\r\n // Prefer <main> or <article> over <body>\r\n let contentHtml = '';\r\n if ($('main').length > 0) {\r\n contentHtml = $('main').html() || '';\r\n } else if ($('article').length > 0) {\r\n contentHtml = $('article').html() || '';\r\n } else {\r\n contentHtml = $('body').html() || '';\r\n }\r\n\r\n // 4. Convert to Markdown\r\n let markdown = turndownService.turndown(contentHtml);\r\n\r\n // 5. Optionally inject Metadata header\r\n const headerLines = [\r\n `# ${title}`,\r\n `> ${description}`,\r\n ``,\r\n `**Source:** ${sourceUrl}`,\r\n `**Extracted:** ${new Date().toISOString()}`,\r\n ``,\r\n `---`,\r\n ``\r\n ];\r\n\r\n let finalMarkdown = headerLines.join('\\n') + markdown;\r\n\r\n // Add JSON-LD section if exists\r\n if (jsonLdScripts.length > 0) {\r\n finalMarkdown += '\\n\\n---\\n## Structured Data (JSON-LD)\\n```json\\n';\r\n jsonLdScripts.forEach(j => {\r\n finalMarkdown += JSON.stringify(j, null, 2) + '\\n';\r\n });\r\n finalMarkdown += '```\\n';\r\n }\r\n\r\n const markdownSize = finalMarkdown.length;\r\n const tokenReductionRatio = originalSize > 0 ? ((originalSize - markdownSize) / originalSize) * 100 : 0;\r\n\r\n return {\r\n markdown: finalMarkdown,\r\n metadata: {\r\n title,\r\n description,\r\n jsonLd: jsonLdScripts\r\n },\r\n stats: {\r\n originalHtmlSize: originalSize,\r\n markdownSize,\r\n tokenReductionRatio\r\n }\r\n };\r\n}\r\n\r\nexport async function generateStaticPayloads(nextAppDirDir: string, ontoPublicDir: string) {\r\n const fs = await import('fs');\r\n const path = await import('path');\r\n const { glob } = await import('glob');\r\n\r\n if (!fs.existsSync(nextAppDirDir)) {\r\n return;\r\n }\r\n\r\n const files = await glob('**/*.html', { cwd: nextAppDirDir });\r\n if (files.length === 0) return;\r\n\r\n if (!fs.existsSync(ontoPublicDir)) {\r\n fs.mkdirSync(ontoPublicDir, { recursive: true });\r\n }\r\n\r\n let totalFilesProcessed = 0;\r\n\r\n for (const file of files) {\r\n const inputPath = path.join(nextAppDirDir, file);\r\n const outputPathRelative = file.replace(/\\.html$/, '.md');\r\n const outputPath = path.join(ontoPublicDir, outputPathRelative);\r\n\r\n try {\r\n const htmlContent = fs.readFileSync(inputPath, 'utf8');\r\n\r\n let routeName = file.replace(/\\.html$/, '');\r\n if (routeName === 'index') routeName = '/';\r\n else routeName = `/${routeName}`;\r\n\r\n const result = extractContent(htmlContent, routeName);\r\n\r\n const outputDir = path.dirname(outputPath);\r\n if (!fs.existsSync(outputDir)) {\r\n fs.mkdirSync(outputDir, { recursive: true });\r\n }\r\n\r\n fs.writeFileSync(outputPath, result.markdown, 'utf8');\r\n totalFilesProcessed++;\r\n } catch (e: any) {\r\n console.error(`[Onto] Failed to process ${file}: ${e.message}`);\r\n }\r\n }\r\n console.log(`[Onto] Successfully generated ${totalFilesProcessed} semantic markdown endpoints.`);\r\n}\r\n","/**\r\n * Configuration schema for onto.config.ts\r\n * Used to dynamically generate llms.txt and other AI discovery files\r\n */\r\n\r\nexport type PageType = 'scoring' | 'about' | 'default';\r\n\r\nexport interface OntoRoute {\r\n /**\r\n * The URL path (e.g., '/docs', '/api/reference')\r\n */\r\n path: string;\r\n /**\r\n * Description of what this route contains\r\n */\r\n description: string;\r\n /**\r\n * Optional: Page type for automatic JSON-LD schema injection\r\n * - 'scoring': Injects Methodology schema with AIO scoring weights (40/35/25)\r\n * - 'about': Injects Organization/AboutPage schema\r\n * - 'default': No automatic schema injection\r\n */\r\n pageType?: PageType;\r\n}\r\n\r\nexport interface OntoConfig {\r\n /**\r\n * The name of your project or site (required)\r\n * Used as the H1 heading in llms.txt\r\n */\r\n name: string;\r\n\r\n /**\r\n * A short summary of your project (required)\r\n * Displayed as a blockquote in llms.txt\r\n * Should contain key information necessary for understanding the rest of the file\r\n */\r\n summary: string;\r\n\r\n /**\r\n * The base URL of your site (e.g., 'https://example.com')\r\n */\r\n baseUrl: string;\r\n\r\n /**\r\n * Optional: Additional sections to include in llms.txt\r\n * Each section can contain any markdown content\r\n */\r\n sections?: {\r\n heading: string;\r\n content: string;\r\n }[];\r\n\r\n /**\r\n * Key routes that AI agents should know about\r\n * These will be formatted as a markdown list in llms.txt\r\n */\r\n routes?: OntoRoute[];\r\n\r\n /**\r\n * Optional: Links to external resources (documentation, API references, etc.)\r\n */\r\n externalLinks?: {\r\n title: string;\r\n url: string;\r\n description?: string;\r\n }[];\r\n\r\n /**\r\n * Optional: Organization information for JSON-LD schemas\r\n */\r\n organization?: {\r\n name: string;\r\n description?: string;\r\n url?: string;\r\n logo?: string;\r\n foundingDate?: string;\r\n };\r\n}\r\n\r\n/**\r\n * Generate llms.txt content from OntoConfig\r\n * Follows the llms.txt specification:\r\n * - H1 with project name\r\n * - Blockquote with summary\r\n * - Additional markdown sections\r\n */\r\nexport function generateLlmsTxt(config: OntoConfig): string {\r\n const lines: string[] = [];\r\n\r\n // H1: Project name (required)\r\n lines.push(`# ${config.name}`);\r\n lines.push('');\r\n\r\n // Blockquote: Summary (required)\r\n lines.push(`> ${config.summary}`);\r\n lines.push('');\r\n\r\n // Key Routes section (if provided)\r\n if (config.routes && config.routes.length > 0) {\r\n lines.push('## Key Routes');\r\n lines.push('');\r\n for (const route of config.routes) {\r\n const fullUrl = `${config.baseUrl}${route.path}`;\r\n lines.push(`- [${route.path}](${fullUrl}): ${route.description}`);\r\n }\r\n lines.push('');\r\n }\r\n\r\n // External Links section (if provided)\r\n if (config.externalLinks && config.externalLinks.length > 0) {\r\n lines.push('## Resources');\r\n lines.push('');\r\n for (const link of config.externalLinks) {\r\n if (link.description) {\r\n lines.push(`- [${link.title}](${link.url}): ${link.description}`);\r\n } else {\r\n lines.push(`- [${link.title}](${link.url})`);\r\n }\r\n }\r\n lines.push('');\r\n }\r\n\r\n // Custom sections (if provided)\r\n if (config.sections && config.sections.length > 0) {\r\n for (const section of config.sections) {\r\n lines.push(`## ${section.heading}`);\r\n lines.push('');\r\n lines.push(section.content);\r\n lines.push('');\r\n }\r\n }\r\n\r\n return lines.join('\\n').trim() + '\\n';\r\n}\r\n"],"mappings":";AACA,OAAS,QAAAA,MAAY,OACrB,OAAOC,MAAQ,KACf,OAAOC,MAAU,OACjB,OAAOC,MAAQ,aCJf,UAAYC,MAAa,UACzB,OAAOC,MAAqB,WAE5B,IAAMC,EAAkB,IAAID,EAAgB,CACxC,aAAc,MACd,eAAgB,QACpB,CAAC,EAwBM,SAASE,EAAeC,EAAcC,EAAoB,mBAAsC,CACnG,IAAMC,EAAeF,EAAK,OAEpBG,EAAY,OAAKH,CAAI,EAGrBI,EAAQD,EAAE,OAAO,EAAE,KAAK,GAAKA,EAAE,I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,CACtE,CAEAC,EAAK,EAAE,MAAMmB,GAAK,CACd,QAAQ,MAAMpB,EAAG,IAAI,uBAAuBoB,EAAE,OAAO,EAAE,CAAC,EACxD,QAAQ,KAAK,CAAC,CAClB,CAAC","names":["glob","fs","path","pc","cheerio","TurndownService","turndownService","extractContent","html","sourceUrl","originalSize","$","title","description","jsonLdScripts","_","el","raw","parsed","contentHtml","markdown","finalMarkdown","j","markdownSize","tokenReductionRatio","generateLlmsTxt","config","lines","route","fullUrl","link","section","loadOntoConfig","cwd","config","path","loadEnv","envPath","fs","line","trimmedLine","key","valueParts","init","configPath","middlewarePath","pc","main","nextAppDirDir","ontoPublicDir","files","glob","totalOriginalSize","totalMarkdownSize","totalFilesProcessed","file","inputPath","outputPathRelative","outputPath","htmlContent","result","extractContent","outputDir","origKb","mdKb","routeName","e","ONTO_API_KEY","DASHBOARD_URL","manifest","route","mdPath","res","errData","llmsTxtContent","generateLlmsTxt","llmsTxtPath","publicDir"]}
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -7,17 +7,20 @@ import { extractContent } from './extractor';
|
|
|
7
7
|
import { generateLlmsTxt, OntoConfig } from './config';
|
|
8
8
|
|
|
9
9
|
async function loadOntoConfig(): Promise<OntoConfig | null> {
|
|
10
|
+
const cwd = process.cwd();
|
|
10
11
|
try {
|
|
11
|
-
const configPath = path.join(
|
|
12
|
-
//
|
|
13
|
-
const
|
|
12
|
+
const configPath = path.join(cwd, 'onto.config');
|
|
13
|
+
// On Windows, file:/// is often required for absolute paths
|
|
14
|
+
const tsPath = 'file:///' + configPath.replace(/\\/g, '/') + '.ts';
|
|
15
|
+
const config = await import(tsPath);
|
|
14
16
|
return config.default || config;
|
|
15
|
-
} catch (error) {
|
|
17
|
+
} catch (error: any) {
|
|
16
18
|
try {
|
|
17
|
-
const configPath = path.join(
|
|
18
|
-
const
|
|
19
|
+
const configPath = path.join(cwd, 'onto.config');
|
|
20
|
+
const jsPath = 'file:///' + configPath.replace(/\\/g, '/') + '.js';
|
|
21
|
+
const config = await import(jsPath);
|
|
19
22
|
return config.default || config;
|
|
20
|
-
} catch (e) {
|
|
23
|
+
} catch (e: any) {
|
|
21
24
|
return null;
|
|
22
25
|
}
|
|
23
26
|
}
|
|
@@ -53,6 +56,7 @@ async function init() {
|
|
|
53
56
|
const config: OntoConfig = {
|
|
54
57
|
name: 'My Project',
|
|
55
58
|
summary: 'A short description of my project for AI agents.',
|
|
59
|
+
baseUrl: 'https://example.com',
|
|
56
60
|
routes: [
|
|
57
61
|
{
|
|
58
62
|
path: '/',
|