/* 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'||v==='>-'){ const text=[];while(at')?' ':'\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].indentindent?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]=atindent+2?parseBlock(lines[at].indent,childPath+'.'+key):null;} skip();if(atindent?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/^\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}; })();