Integrate Antirion admin with FastAPI and htmx
Add the shared document API, constructor and expert editors, isolated preview, and fragment catalog metadata with typed block IDs. Include design references, specification 001, QA scripts, project guidance, and cached Docker dependency installation. Leave example sites for a separate commit.
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
/* Stage 3. Offline YAML-frontmatter subset codec for a design prototype.
|
||||
* Supports block mappings/sequences, JSON-style quoted scalar values, single quotes,
|
||||
* booleans, null, numbers and |- literal scalars. No anchors, tags, flow objects,
|
||||
* complex keys or duplicate keys: these are errors, never silently discarded.
|
||||
* Production parser: use vetted YAML 1.2 implementation in Python backend.
|
||||
*/
|
||||
(()=>{'use strict';
|
||||
const own=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
|
||||
const isMap=o=>o!==null&&typeof o==='object'&&!Array.isArray(o);
|
||||
function error(message,line,path=''){const e=new Error(message);e.line=line;e.path=path;throw e;}
|
||||
function scalar(raw,line,path){const s=raw.trim();if(!s)return '';
|
||||
if(s[0]==='"') {try{const x=JSON.parse(s);if(typeof x!=='string')error('Ожидается строка',line,path);return x}catch(e){error('Некорректная строка в двойных кавычках',line,path)}}
|
||||
if(s[0]==="'"){if(!/^'(?:[^']|'')*'$/.test(s))error('Незакрытая строка в одинарных кавычках',line,path);return s.slice(1,-1).replace(/''/g,"'");}
|
||||
if(s==='true')return true;if(s==='false')return false;if(s==='null'||s==='~')return null;
|
||||
if(/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(s))return Number(s);
|
||||
if(s==='[]')return [];if(s==='{}')return {};
|
||||
if(s[0]==='['||s[0]==='{')error('Flow-style YAML не поддерживается этим прототипом; используйте вложенные строки',line,path);
|
||||
if(s.startsWith('!')||s.startsWith('&')||s.startsWith('*'))error('YAML tags/anchors/aliases не поддерживаются',line,path);
|
||||
if(/:\s/.test(s))error('Строка с «: » должна быть заключена в кавычки',line,path);
|
||||
return s;
|
||||
}
|
||||
function linesOf(yaml,offset){return yaml.replace(/\r\n?/g,'\n').split('\n').map((raw,i)=>({raw,num:i+offset+1,indent:raw.match(/^ */)[0].length,txt:raw.trim()}));}
|
||||
function parseYaml(yaml,offset=1,locations={}){const lines=linesOf(yaml,offset);let at=0;
|
||||
const skip=()=>{while(at<lines.length&&(!lines[at].txt||lines[at].txt.startsWith('#')))at++;};
|
||||
function valueInline(v,line,path,indent){if(v==='|'||v==='|-'||v==='>'||v==='>-'){
|
||||
const text=[];while(at<lines.length){const n=lines[at];if(n.txt&&n.indent<=indent)break;if(n.txt&&n.indent<indent+2)error('Неправильный отступ multiline YAML',n.num,path);text.push(n.raw.slice(indent+2));at++;}
|
||||
const joined=text.join(v.startsWith('>')?' ':'\n');return v.endsWith('-')?joined:joined+'\n';}
|
||||
return scalar(v,line,path);
|
||||
}
|
||||
function parseBlock(indent,path){skip();if(at>=lines.length)return {};
|
||||
if(lines[at].indent!==indent)error('Неверный отступ YAML: ожидался '+indent,lines[at].num,path);
|
||||
const sequence=lines[at].txt.startsWith('- ');const out=sequence?[]:{};
|
||||
while(true){skip();if(at>=lines.length||lines[at].indent<indent)break;
|
||||
const l=lines[at];if(l.indent!==indent)error('Неверный отступ YAML',l.num,path);
|
||||
if(sequence){if(!l.txt.startsWith('- '))error('Ожидался элемент списка «- ...»',l.num,path);
|
||||
const rest=l.txt.slice(2);at++;
|
||||
if(!rest){skip();out.push(at<lines.length&&lines[at].indent>indent?parseBlock(lines[at].indent,path+'['+out.length+']'):null);continue;}
|
||||
const m=rest.match(/^([a-zA-Z_][\w.-]*):(?:\s+(.*)|\s*)$/);
|
||||
if(!m){out.push(scalar(rest,l.num,path+'['+out.length+']'));continue;}
|
||||
// YAML block sequence item with a nested mapping; subsequent mapping entries are indented by 2.
|
||||
const item={},key=m[1],childPath=path+'['+out.length+']';
|
||||
locations[childPath+'.'+key]=l.num;
|
||||
const rawval=m[2]??'';
|
||||
if(rawval){item[key]=valueInline(rawval,l.num,childPath+'.'+key,indent+2);}
|
||||
else{skip();item[key]=at<lines.length&&lines[at].indent>indent+2?parseBlock(lines[at].indent,childPath+'.'+key):null;}
|
||||
skip();if(at<lines.length&&lines[at].indent===indent+2&&!lines[at].txt.startsWith('- ')){
|
||||
const tail=parseBlock(indent+2,childPath);
|
||||
if(!isMap(tail))error('Поле списка должно быть отображением',l.num,childPath);
|
||||
for(const k of Object.keys(tail)){if(own(item,k))error('Повторное поле '+k,l.num,childPath+'.'+k);item[k]=tail[k];}
|
||||
}
|
||||
out.push(item);
|
||||
}else{
|
||||
if(l.txt.startsWith('- '))error('Список в объекте требует ключа',l.num,path);
|
||||
const m=l.txt.match(/^([a-zA-Z_][\w.-]*):(?:\s+(.*)|\s*)$/);
|
||||
if(!m)error('Ожидается ключ: значение',l.num,path);
|
||||
const key=m[1],value=m[2]??'',childPath=path?path+'.'+key:key;
|
||||
locations[childPath]=l.num;
|
||||
if(own(out,key))error('Повторный YAML-ключ: '+key,l.num,childPath);
|
||||
at++;
|
||||
if(value){out[key]=valueInline(value,l.num,childPath,indent);continue;}
|
||||
skip();out[key]=at<lines.length&&lines[at].indent>indent?parseBlock(lines[at].indent,childPath):{};
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
skip();if(at>=lines.length)return {};
|
||||
if(lines[at].indent!==0)error('Первый ключ YAML должен начинаться без отступа',lines[at].num,'frontmatter');
|
||||
const data=parseBlock(0,'');skip();if(at<lines.length)error('Неожиданные строки после YAML',lines[at].num,'frontmatter');return data;
|
||||
}
|
||||
function split(src){const str=String(src).replace(/\r\n?/g,'\n');const lines=str.split('\n');if(lines[0]!=='---')error('Файл должен начинаться с ---',1,'frontmatter');let closing=-1;
|
||||
for(let i=1;i<lines.length;i++){if(lines[i]==='---'){closing=i;break;}}
|
||||
if(closing<0)error('Не найдено закрывающее --- для YAML front matter',lines.length,'frontmatter');
|
||||
return {front:lines.slice(1,closing).join('\n'),body:lines.slice(closing+1).join('\n'),endLine:closing+1};
|
||||
}
|
||||
function parse(src){const doc=split(src),locations={};return {data:parseYaml(doc.front,1,locations),body:doc.body,meta:{frontEnd:doc.endLine,hasComments:doc.front.split('\n').some(x=>/^\s*#/.test(x)),locations}};}
|
||||
function quote(x){if(typeof x==='boolean'||x===null||typeof x==='number')return JSON.stringify(x);return JSON.stringify(String(x));}
|
||||
function stringify(data,indent=0){const pre=' '.repeat(indent),lines=[];
|
||||
for(const [key,value] of Object.entries(data||{})){
|
||||
if(isMap(value)){const kv=Object.keys(value);if(!kv.length){lines.push(pre+key+': {}');continue;}lines.push(pre+key+':');lines.push(stringify(value,indent+2));}
|
||||
else if(Array.isArray(value)){
|
||||
if(!value.length){lines.push(pre+key+': []');continue;}
|
||||
lines.push(pre+key+':');
|
||||
for(const item of value){if(isMap(item)){
|
||||
const entries=Object.entries(item);
|
||||
if(!entries.length){lines.push(pre+' - {}');continue;}
|
||||
const [firstKey,firstVal]=entries[0];
|
||||
if(isMap(firstVal)||Array.isArray(firstVal)){lines.push(pre+' -');lines.push(stringify(item,indent+4));continue;}
|
||||
lines.push(pre+' - '+firstKey+': '+quote(firstVal));
|
||||
if(entries.length>1)lines.push(stringify(Object.fromEntries(entries.slice(1)),indent+4));
|
||||
}else lines.push(pre+' - '+quote(item));}
|
||||
}
|
||||
else if(typeof value==='string'&&value.includes('\n')){
|
||||
lines.push(pre+key+': |-');for(const part of value.split('\n'))lines.push(pre+' '+part);
|
||||
}else lines.push(pre+key+': '+quote(value));
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
function serialize(data,body){return '---\n'+stringify(data)+'\n---\n'+String(body??'');}
|
||||
window.SiteExpertCodec={parse,serialize,stringify,isMap,error};
|
||||
})();
|
||||
Reference in New Issue
Block a user