Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 62 additions & 10 deletions api/lesson.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { representation, quality, problem } = require('../lib/agent-http');
const { lessonDocumentSeo, seoTitleFor } = require('../lib/lesson-document');
const { cardTags, cardUrl, lessonCard } = require('../lib/og-cards');
const { readTranslationResult: readTranslationFromSource, TRANSLATION_LANGUAGES, isIndexedLanguage, translationsOf, lessonUrl, NATIVE_NAMES, RTL_LANGUAGES, OG_LOCALES } = require('../lib/lesson-translations');
const { phaseHubPath, phaseLabel } = require('../lib/hub-routes');
const { phaseHubPath, phaseLabel, lessonCleanPath } = require('../lib/hub-routes');

const REPO_ROOT = path.join(__dirname, '..');
const ORIGIN = 'https://aiengineeringfromscratch.com';
Expand All @@ -16,6 +16,9 @@ const FALLBACK_END = '<!-- AIFS:LESSON-FALLBACK:END -->';
const HUBS_START = '<!-- AIFS:LESSON-HUBS:START -->';
const HUBS_END = '<!-- AIFS:LESSON-HUBS:END -->';
const LESSON_QUERY_NAMES = new Set(['path', 'track', 'fromTrack', 'learningPath', 'lang', 'ttsTest', 'legacy']);
const CLEAN_QUERY_NAMES = ['cleanPhase', 'cleanLesson'];
const CLEAN_SEGMENT = /^[a-z0-9][a-z0-9-]*$/;
const cleanLessonIndexes = new WeakMap();
const LEARNING_PATH_ALIASES = Object.freeze({
'mcp-engineering': 'model-context-protocol',
});
Expand Down Expand Up @@ -122,6 +125,43 @@ function hasQuery(req, name) {
return queryNames(req).has(name);
}

function requestPathname(req) {
try {
return new URL(req.url || '/', 'http://localhost').pathname;
} catch (_) {
return '';
}
}

function cleanRequestPath(req) {
const pathname = requestPathname(req);
if (pathname === '/lesson' || pathname === '/lesson.html') return '';
const direct = /^\/learn\/([a-z0-9][a-z0-9-]*)\/([a-z0-9][a-z0-9-]*)$/.exec(pathname);
if (direct) return pathname;
const phase = queryValue(req, 'cleanPhase');
const lesson = queryValue(req, 'cleanLesson');
return CLEAN_SEGMENT.test(phase) && CLEAN_SEGMENT.test(lesson) ? `/learn/${phase}/${lesson}` : '';
}

function lessonPathForCleanPath(manifest, cleanPath) {
let index = cleanLessonIndexes.get(manifest);
if (!index) {
index = new Map();
for (const lessonPath of Object.keys(manifest.lessons)) {
const clean = lessonCleanPath(lessonPath);
if (clean && !index.has(clean)) index.set(clean, lessonPath);
}
cleanLessonIndexes.set(manifest, index);
}
return index.get(cleanPath) || '';
}

function withoutCleanNames(query) {
const params = new URLSearchParams(query);
for (const name of CLEAN_QUERY_NAMES) params.delete(name);
return params.toString();
}

function validLessonPath(value) {
if (!value || value.includes('..') || value.includes('\\') || value.includes('\0')) return false;
return /^(?:phases\/[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*|certifications\/[a-z0-9][a-z0-9-]*\/lessons\/[a-z0-9][a-z0-9-]*)$/.test(value);
Expand Down Expand Up @@ -284,11 +324,13 @@ function lessonHead(entry, page) {

function lessonHref(ref, contextParams) {
const params = new URLSearchParams();
params.set('path', ref.path);
const cleanPath = lessonCleanPath(ref.path);
if (!cleanPath) params.set('path', ref.path);
for (const name of ['track', 'fromTrack', 'learningPath', 'lang']) {
if (contextParams && contextParams[name]) params.set(name, contextParams[name]);
}
return `/lesson?${params.toString().replace(/&/g, '&amp;')}`;
const query = params.toString().replace(/&/g, '&amp;');
return `${cleanPath || '/lesson'}${query ? `?${query}` : ''}`;
Comment thread
rohitg00 marked this conversation as resolved.
Resolved
}

function readEnglishMarkdown(assets, lessonPath) {
Expand Down Expand Up @@ -414,15 +456,17 @@ function send(res, method, status, body, cacheControl, type = 'text/html') {
res.end(method === 'HEAD' ? '' : payload);
}

function normalizedLessonLocation(req, lessonPath, entry, assets) {
function normalizedLessonLocation(req, lessonPath, entry, assets, cleanRequest) {
const params = new URLSearchParams();
const cleanPath = lessonCleanPath(lessonPath);
const certificationLesson = /^certifications\/[a-z0-9][a-z0-9-]*\/lessons\//.test(lessonPath);
const navigationByTrack = entry.navigationByTrack && typeof entry.navigationByTrack === 'object'
? entry.navigationByTrack
: {};
let needsRedirect = hasQuery(req, 'legacy') || Array.from(queryNames(req)).some(function (name) {
return !LESSON_QUERY_NAMES.has(name);
return !LESSON_QUERY_NAMES.has(name) && !(cleanRequest && CLEAN_QUERY_NAMES.includes(name));
});
if (cleanPath && !cleanRequest) needsRedirect = true;
params.set('path', lessonPath);

if (certificationLesson && hasQuery(req, 'track')) {
Expand Down Expand Up @@ -480,13 +524,18 @@ function normalizedLessonLocation(req, lessonPath, entry, assets) {
}
}

const context = new URLSearchParams(params);
context.delete('path');
const contextQuery = context.toString();
const requestQuery = rawUrlQuery(req);
if (requestQuery !== null && requestQuery !== params.toString()) {
if (cleanRequest) {
if (requestQuery !== null && withoutCleanNames(requestQuery) !== contextQuery) needsRedirect = true;
} else if (requestQuery !== null && requestQuery !== params.toString()) {
needsRedirect = true;
}

return {
location: `/lesson?${params.toString()}`,
location: cleanPath ? `${cleanPath}${contextQuery ? `?${contextQuery}` : ''}` : `/lesson?${params.toString()}`,
needsRedirect,
params,
};
Expand Down Expand Up @@ -522,8 +571,9 @@ function createHandler(options) {
return;
}

const lessonPath = queryValue(req, 'path');
if (!validLessonPath(lessonPath)) {
const cleanRequest = cleanRequestPath(req);
const queryPath = queryValue(req, 'path');
if (!cleanRequest && !validLessonPath(queryPath)) {
send(res, method, 404, errorPage('Lesson not found', 'This lesson path does not exist. Use the catalog, sitemap, or agent curriculum index to continue.'), 'no-store');
return;
}
Expand All @@ -533,14 +583,15 @@ function createHandler(options) {
const manifest = assets && assets.manifest;
if (typeof template !== 'string') throw new Error('template-shape');
if (!manifest || !manifest.lessons || typeof manifest.lessons !== 'object') throw new Error('manifest-shape');
const lessonPath = cleanRequest ? lessonPathForCleanPath(manifest, cleanRequest) : queryPath;
const entry = Object.prototype.hasOwnProperty.call(manifest.lessons, lessonPath)
? manifest.lessons[lessonPath]
: null;
if (!entry || entry.path !== lessonPath || !entry.title) {
send(res, method, 404, errorPage('Lesson not found', 'This lesson path is not part of the current curriculum. Use the catalog, sitemap, or agent curriculum index to continue.'), 'no-store');
return;
}
const normalized = normalizedLessonLocation(req, lessonPath, entry, assets);
const normalized = normalizedLessonLocation(req, lessonPath, entry, assets, Boolean(cleanRequest));
if (normalized.needsRedirect) {
res.setHeader('Location', normalized.location);
send(res, method, 308, '', PAGE_CACHE);
Expand Down Expand Up @@ -571,6 +622,7 @@ function createHandler(options) {
let html = replaceMarkedRegion(localizedTemplate(template, servedLang), SEO_START, SEO_END, lessonHead(entry, page));
html = replaceMarkedRegion(html, FALLBACK_START, FALLBACK_END, lessonFallback(entry, lessonPath, contextParams, page, body));
html = replaceMarkedRegion(html, HUBS_START, HUBS_END, lessonHubLinks(entry, page, assets.lessonTerms, assets.cheatsheets, assets.practice));
if (cleanRequest) html = html.replace('<head>', `<head>\n <base href="/">\n <meta name="aifs-lesson-path" content="${escapeHtml(lessonPath)}">`);
res.setHeader('Vary', 'Accept, Accept-Encoding');
res.setHeader('Content-Language', servedLang);
send(res, method, 200, html, cacheControl);
Expand Down
7 changes: 6 additions & 1 deletion lib/hub-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ function phaseHubPath(lessonPath) {
return match ? phasePath(phaseSlug(match[1])) : '';
}

function lessonCleanPath(lessonPath) {
const match = /^phases\/([a-z0-9][a-z0-9-]*)\/([a-z0-9][a-z0-9-]*)$/.exec(lessonPath || '');
return match ? `/learn/${phaseSlug(match[1])}/${phaseSlug(match[2])}` : '';
}

function phaseLabel(id, name) {
return `Phase ${String(id).padStart(2, '0')}: ${name}`;
}
Expand All @@ -30,4 +35,4 @@ function glossaryLookupKey(value) {
.replace(/\s+/g, ' ');
}

module.exports = { phaseSlug, phasePath, phaseHubPath, phaseLabel, termPath, glossaryLookupKey };
module.exports = { phaseSlug, phasePath, phaseHubPath, lessonCleanPath, phaseLabel, termPath, glossaryLookupKey };
6 changes: 5 additions & 1 deletion lib/lesson-translations.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const registry = require('../languages.json');
const { readBounded } = require('./read-bounded');
const { lessonCleanPath } = require('./hub-routes');

const ORIGIN = 'https://aiengineeringfromscratch.com';
const REPOSITORY = 'rohitg00/ai-engineering-from-scratch';
Expand Down Expand Up @@ -38,7 +39,10 @@ function lessonPathFromCacheKey(key) {
}

function lessonUrl(lessonPath, lang) {
return `${ORIGIN}/lesson?path=${encodeURIComponent(lessonPath)}${lang && lang !== 'en' ? `&lang=${encodeURIComponent(lang)}` : ''}`;
const language = lang && lang !== 'en' ? `lang=${encodeURIComponent(lang)}` : '';
const clean = lessonCleanPath(lessonPath);
if (clean) return `${ORIGIN}${clean}${language ? `?${language}` : ''}`;
return `${ORIGIN}/lesson?path=${encodeURIComponent(lessonPath)}${language ? `&${language}` : ''}`;
}

function canTranslate(lang, lessonPath) {
Expand Down
6 changes: 5 additions & 1 deletion lib/og-cards.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const crypto = require('node:crypto');
const fs = require('node:fs');
const path = require('node:path');
const { normalizeWhitespace } = require('./lesson-document');
const { lessonCleanPath } = require('./hub-routes');

const ORIGIN = 'https://aiengineeringfromscratch.com';
const BRAND = 'Open source · MIT';
Expand Down Expand Up @@ -96,7 +97,10 @@ function lessonCard(entry, lang = 'en') {
: `Lesson ${match.slice(1).join('.')} · ${context.phaseName || 'AI Engineering from Scratch'}`;
const languages = String(context.languages || '').split(',').map(normalizeWhitespace).filter(value => value && value !== '—').join(', ');
const meta = translated ? `Translation · ${lang}` : certification ? INDEPENDENT : [context.type, languages].filter(Boolean).join(' · ');
return card(label, meta, entry.title, summary(entry.title, entry.description), `/lesson?path=${entry.path}${translated ? `&lang=${lang}` : ''}`);
const cleanPath = lessonCleanPath(entry.path);
const language = translated ? `lang=${lang}` : '';
const page = cleanPath ? `${cleanPath}${language ? `?${language}` : ''}` : `/lesson?path=${entry.path}${language ? `&${language}` : ''}`;
return card(label, meta, entry.title, summary(entry.title, entry.description), page);
}

function trackCard(entry) {
Expand Down
4 changes: 2 additions & 2 deletions scripts/test_agent_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,12 +153,12 @@ test('MCP rejects malformed requests, unsafe origins, unsupported transport and


test('resource and MCP read lesson translations only for allowlisted languages', async () => {
const entry = { path: 'phases/01-a/01-x', kind: 'lesson', title: 'X', description: 'X lesson', url: 'https://aiengineeringfromscratch.com/lesson?path=phases%2F01-a%2F01-x', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/phases/01-a/01-x/docs/en.md', translations: ['hi'], markdown: '# X\n' };
const entry = { path: 'phases/01-a/01-x', kind: 'lesson', title: 'X', description: 'X lesson', url: 'https://aiengineeringfromscratch.com/learn/a/x', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/phases/01-a/01-x/docs/en.md', translations: ['hi'], markdown: '# X\n' };
const read = path => (path === entry.path ? entry : null);
const fetched = [];
const readTranslation = (lang, lessonPath) => { fetched.push(`${lang}:${lessonPath}`); return Promise.resolve(lang === 'hi' ? '# एक्स\n' : null); };
const translated = await readTranslatedResource(entry.path, 'hi', { read, readTranslation });
assert.deepEqual(translated, { ...entry, lang: 'hi', url: entry.url + '&lang=hi', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/translations/i18n/hi/phases/01-a/01-x/docs/hi.md', markdown: '# एक्स\n' });
assert.deepEqual(translated, { ...entry, lang: 'hi', url: entry.url + '?lang=hi', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/translations/i18n/hi/phases/01-a/01-x/docs/hi.md', markdown: '# एक्स\n' });
assert.equal(await readTranslatedResource(entry.path, 'en', { read, readTranslation }), entry);
assert.equal(await readTranslatedResource(entry.path, 'ar', { read, readTranslation }), null);
assert.equal(await readTranslatedResource('missing', 'hi', { read, readTranslation }), null);
Expand Down
7 changes: 5 additions & 2 deletions scripts/test_agent_wire.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,12 @@ test('served routing preserves HTML, negotiates every navigation page, and recov
for (const route of ['/llms.txt','/developer.md','/sitemap.xml','/style.css?v=old','/header.js?v=old','/projects-data.js']) {
const response = await fetch(base + route); assert.equal(response.status,200,route); assert.ok((await response.text()).length > 50);
}
const lesson = '/lesson?path=phases%2F00-setup-and-tooling%2F01-dev-environment';
const lesson = '/learn/setup-and-tooling/dev-environment';
assert.equal((await fetch(base + lesson)).status,200);
const legacy = await fetch(base + lesson.replace('/lesson?','/lesson.html?'), { redirect:'manual' }); assert.equal(legacy.status,308); assert.match(legacy.headers.get('location'),/^\/lesson\?/);
const legacyQuery = '?path=phases%2F00-setup-and-tooling%2F01-dev-environment';
for (const legacyRoute of ['/lesson','/lesson.html']) {
const legacy = await fetch(base + legacyRoute + legacyQuery, { redirect:'manual' }); assert.equal(legacy.status,308); assert.equal(legacy.headers.get('location'),lesson);
}
const json = await fetch(base + '/api/v1/catalog?q=attention&limit=1'); assert.equal(json.status,200); const catalog = await json.json();
const source = await fetch(base + '/api/v1/resource?path=' + encodeURIComponent(catalog.items[0].path)); assert.ok((await source.json()).markdown);
const duplicate = await fetch(base + '/api/v1/catalog?limit=1&limit=2'); assert.equal(duplicate.status,400);
Expand Down
14 changes: 9 additions & 5 deletions scripts/test_api_state.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const resource = require('../api/v1/resource');
const mcp = require('../api/mcp');

const PERCEPTRON = 'phases/03-deep-learning-core/01-the-perceptron';
const PERCEPTRON_CLEAN = '/learn/deep-learning-core/the-perceptron';
const HINDI = '# पर्सेप्ट्रोन\n\n> पर्सेप्ट्रॉन तंत्रिका नेटवर्क का परमाणु है।\n\n## अवधारणा\n\nएक न्यूरॉन एक निर्णय लेता है।\n';
const RETRY_CACHE = 'public, max-age=0, s-maxage=300, must-revalidate';

Expand Down Expand Up @@ -113,7 +114,7 @@ test('paths without a translation source resolve as not found without fetching',
});

test('resource API caches stale translations briefly and fresh translations normally', async () => {
const entry = { path: 'phases/01-a/01-x', kind: 'lesson', title: 'X', description: 'X', url: 'https://aiengineeringfromscratch.com/lesson?path=phases%2F01-a%2F01-x', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/phases/01-a/01-x/docs/en.md', translations: ['hi'], markdown: '# X\n' };
const entry = { path: 'phases/01-a/01-x', kind: 'lesson', title: 'X', description: 'X', url: 'https://aiengineeringfromscratch.com/learn/a/x', sourceUrl: 'https://github.com/rohitg00/ai-engineering-from-scratch/blob/main/phases/01-a/01-x/docs/en.md', translations: ['hi'], markdown: '# X\n' };
const read = path => (path === entry.path ? entry : null);
for (const [stale, cache] of [[true, RETRY_CACHE], [false, 'public, max-age=300, s-maxage=86400']]) {
const readTranslation = () => Promise.resolve({ markdown: HINDI, stale });
Expand All @@ -129,7 +130,7 @@ test('resource API caches stale translations briefly and fresh translations norm
});

test('lesson pages cache stale translations briefly', async () => {
const url = `/lesson?path=${encodeURIComponent(PERCEPTRON)}&lang=hi`;
const url = `${PERCEPTRON_CLEAN}?lang=hi`;
for (const [result, cache] of [[{ markdown: HINDI, stale: true }, RETRY_CACHE], [{ markdown: HINDI, stale: false }, 'public, max-age=0, s-maxage=86400, stale-while-revalidate=604800']]) {
const handler = lessonApi.createHandler({ loadAssets: () => lessonAssets(), readTranslation: () => Promise.resolve(result) });
const response = await invoke(handler, { url });
Expand All @@ -141,7 +142,7 @@ test('lesson pages cache stale translations briefly', async () => {

test('lesson Markdown requests that reject HTML get 406 when no Markdown exists', async () => {
const handler = lessonApi.createHandler({ loadAssets: () => lessonAssets({ readMarkdown() { throw new Error('ENOENT'); } }) });
const url = `/lesson?path=${encodeURIComponent(PERCEPTRON)}`;
const url = PERCEPTRON_CLEAN;
for (const method of ['GET', 'HEAD']) {
const rejected = await invoke(handler, { method, url, headers: { accept: 'text/markdown' } });
assert.equal(rejected.statusCode, 406);
Expand All @@ -157,17 +158,20 @@ test('lesson Markdown requests that reject HTML get 406 when no Markdown exists'

test('lesson lang=en redirects to the URL without lang', async () => {
const handler = lessonApi.createHandler({ loadAssets: () => lessonAssets() });
const response = await invoke(handler, { url: `/lesson?path=${encodeURIComponent(PERCEPTRON)}&learningPath=x&lang=en` });
const response = await invoke(handler, { url: `${PERCEPTRON_CLEAN}?learningPath=x&lang=en` });
assert.equal(response.statusCode, 308);
assert.doesNotMatch(response.headers.location, /lang=/);
const legacy = await invoke(handler, { url: `/lesson?path=${encodeURIComponent(PERCEPTRON)}&learningPath=x&lang=en` });
assert.equal(legacy.statusCode, 308);
assert.equal(legacy.headers.location, response.headers.location);
const page = await invoke(handler, { url: response.headers.location });
assert.equal(page.statusCode, 200);
assert.doesNotMatch(page.body, /lang=en(?:&|")/);
});

test('lesson Content-Language is set only after the page renders', async () => {
const handler = lessonApi.createHandler({ loadAssets: () => lessonAssets({ template: '<html lang="en"><body></body></html>' }) });
const response = await invoke(handler, { url: `/lesson?path=${encodeURIComponent(PERCEPTRON)}` });
const response = await invoke(handler, { url: PERCEPTRON_CLEAN });
assert.equal(response.statusCode, 500);
assert.equal(response.headers['content-language'], undefined);
assert.equal(response.headers.vary, undefined);
Expand Down
Loading
Loading