scrapbox2anki
code:mod.js
var m=e=>{let{fetch:t=globalThis.fetch,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var xe=e=>typeof e=="object"&&e!==null,ke=e=>xe(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,A=e=>{try{let t=typeof e=="string"?JSON.parse(e):e;return ke(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}};var L=class extends Error{constructor(t){super(${t.status} ${t.statusText} when fetching ${t.url});this.response=t;this.name="UnexpectedResponseError";Error.captureStackTrace&&Error.captureStackTrace(this,L)}},k=async e=>{let t=e.clone(),r=await t.text(),o=A(r);if(!o)throw new L(t);return{ok:!1,value:o}};var h=e=>connect.sid=${e};var P=e=>...e.map((t,r)=>t===" "?"_":!be.includes(t)||r===e.length-1&&Ee.includes(t)?encodeURIComponent(t):t).join(""),be='@$&+=:;",',Ee=':;",';var z=(e,t,r)=>{let{sid:o,hostName:n,followRename:s,projects:i}=m(r??{}),a=new URLSearchParams;a.append("followRename",${s??!0});for(let d of i??[])a.append("projects",d);let p=https://${n}/api/pages/${e}/${P(t)}?${a.toString()};return new Request(p,o?{headers:{Cookie:h(o)}}:void 0)},G=async e=>{if(!e.ok)return e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:k(e);let t=await e.json();return{ok:!0,value:t}},O=async(e,t,r)=>{let{fetch:o}=m(r??{}),n=z(e,t,r),s=await o(n);return await G(s)};O.toRequest=z;O.fromResponse=G;var _=(e,t)=>{let{sid:r,hostName:o,sort:n,limit:s,skip:i}=m(t??{}),a=new URLSearchParams;n!==void 0&&a.append("sort",n),s!==void 0&&a.append("limit",${s}),i!==void 0&&a.append("skip",${i});let p=https://${o}/api/pages/${e}?${a.toString()};return new Request(p,r?{headers:{Cookie:h(r)}}:void 0)},Q=async e=>{if(!e.ok)return k(e);let t=await e.json();return{ok:!0,value:t}},J=async(e,t)=>{let{fetch:r}=m(t??{}),o=await r(_(e,t));return await Q(o)};J.toRequest=_;J.fromResponse=Q;var W=(e,t,r,o)=>{let{sid:n,hostName:s}=m(o??{}),i=https://${s}/api/table/${e}/${P(t)}/${encodeURIComponent(r)}.csv;return new Request(i,n?{headers:{Cookie:h(n)}}:void 0)},X=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404?{ok:!1,value:{name:"NotFoundError",message:"Table not found."}}:k(e),Z=async(e,t,r,o)=>{let{fetch:n}=m(o??{}),s=W(e,t,r,o),i=await n(s);return await X(i)};Z.toRequest=W;Z.fromResponse=X;var K=(e,t)=>{let{sid:r,hostName:o}=m(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:h(r)}}:void 0)},V=async e=>{if(!e.ok)return k(e);let t=await e.json();return{ok:!0,value:t}},H=async(e,t)=>{let{fetch:r}=m(t??{}),o=K(e,t),n=await r(o);return V(n)};H.toRequest=K;H.fromResponse=V;var Y=(e,t)=>{let{sid:r,hostName:o}=m(t??{}),n=new URLSearchParams;for(let s of e)n.append("ids",s);return new Request(https://${o}/api/projects?${n.toString()},r?{headers:{Cookie:h(r)}}:void 0)},ee=async e=>{if(!e.ok)return k(e);let t=await e.json();return{ok:!0,value:t}},te=async(e,t)=>{let{fetch:r}=m(t??{}),o=await r(Y(e,t));return ee(o)};te.toRequest=Y;te.fromResponse=ee;var re=(e,t)=>{let r=new t.Database,o={activeDecks:1,addToCur:!0,collapseTime:1200,curDeck:1,curModel:"1435645724216",dueCounts:!0,estTimes:!0,newBury:!0,newSpread:0,nextPos:1,sortBackwards:!1,sortType:"noteFld",timeLim:0},n={},s=new Map;{let g=j();g(1),n1={collapsed:!1,conf:1,desc:"",dyn:0,extendNew:10,extendRev:50,id:1,lrnToday:0,0,mod:0,name:"Default",newToday:0,0,revToday:0,0,timeToday:0,0,usn:0};let E=new Set(e.flatMap(l=>l.noteType.deck?l.deck,l.noteType.deck:l.deck));for(let l of E){let y=Le(l,g);ny.id=y,s.set(l,y.id)}}let i={},a=new Map;{let g=j(),E=new Set(e.map(l=>l.noteType));for(let l of E){let y=l.deck?s.get(l.deck):void 0,T=ve(l,y,g);iT.id=T,a.set(l,T.id)}}let p={},d={};{let g=j(),E=j();for(let l of e){let y=a.get(l.noteType);if(y===void 0)throw Error("Note type id must be already generated");let T=s.get(l.deck);if(T===void 0)throw Error("Deck id must be already generated");let q=Ne(l,y,E);pq.id=q;for(let D of we(l,T,q.id,g))dD.id=D}}let c={1:{autoplay:!0,id:1,lapse:{delays:10,leechAction:0,leechFails:8,minInt:1,mult:0},maxTaken:60,mod:0,name:"Default",new:{bury:!0,delays:1,10,initialFactor:2500,ints:1,4,7,order:1,perDay:20,separate:!0},replayq:!0,rev:{bury:!0,ease4:1.3,fuzz:.05,ivlFct:1,maxIvl:36500,minSpace:1,perDay:100},timer:0,usn:0}},u=` PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE col (
id integer primary key,
crt integer not null,
mod integer not null,
scm integer not null,
ver integer not null,
dty integer not null,
usn integer not null,
ls integer not null,
conf text not null,
models text not null,
decks text not null,
dconf text not null,
tags text not null
);
INSERT INTO "col" VALUES(
1,
1388548800,
1435645724219,
1435645724215,
11,
0,
0,
0,
'${JSON.stringify(o)}',
'${JSON.stringify(i)}',
'${JSON.stringify(n)}',
'${JSON.stringify(c)}',
'{}'
);
CREATE TABLE notes (
id integer primary key, /* 0 */
guid text not null, /* 1 */
mid integer not null, /* 2 */
mod integer not null, /* 3 */
usn integer not null, /* 4 */
tags text not null, /* 5 */
flds text not null, /* 6 */
sfld integer not null, /* 7 */
csum integer not null, /* 8 */
flags integer not null, /* 9 */
data text not null /* 10 */
);
CREATE TABLE cards (
id integer primary key, /* 0 */
nid integer not null, /* 1 */
did integer not null, /* 2 */
ord integer not null, /* 3 */
mod integer not null, /* 4 */
usn integer not null, /* 5 */
type integer not null, /* 6 */
queue integer not null, /* 7 */
due integer not null, /* 8 */
ivl integer not null, /* 9 */
factor integer not null, /* 10 */
reps integer not null, /* 11 */
lapses integer not null, /* 12 */
left integer not null, /* 13 */
odue integer not null, /* 14 */
odid integer not null, /* 15 */
flags integer not null, /* 16 */
data text not null /* 17 */
);
CREATE TABLE revlog (
id integer primary key,
cid integer not null,
usn integer not null,
ease integer not null,
ivl integer not null,
lastIvl integer not null,
factor integer not null,
time integer not null,
type integer not null
);
CREATE TABLE graves (
usn integer not null,
oid integer not null,
type integer not null
);
ANALYZE sqlite_master;
INSERT INTO "sqlite_stat1" VALUES('col',NULL,'1');
CREATE INDEX ix_notes_usn on notes (usn);
CREATE INDEX ix_cards_usn on cards (usn);
CREATE INDEX ix_revlog_usn on revlog (usn);
CREATE INDEX ix_cards_nid on cards (nid);
CREATE INDEX ix_cards_sched on cards (did, queue, due);
CREATE INDEX ix_revlog_cid on revlog (cid);
CREATE INDEX ix_notes_csum on notes (csum);
COMMIT;
;r.run(u);let b=r.prepare("insert or replace into notes values(:id,:guid,:mid,:mod,:usn,:tags,:flds,:sfld,:csum,:flags,:data)");for(let g of Object.values(p))b.run(Object.fromEntries([...Object.entries(g)].map(([E,l])=>[:${E},l])));let N=r.prepare("insert or replace into cards values(:id,:nid,:did,:ord,:mod,:usn,:type,:queue,:due,:ivl,:factor,:reps,:lapses,:left,:odue,:odid,:flags,:data)");for(let g of Object.values(d))N.run(Object.fromEntries([...Object.entries(g)].map(([E,l])=>[:${E},l])));return r.export()},oe=(e,t,r,o)=>{let n=new r;n.file("collection.anki2",e);let s=[...t instanceof Map?t.entries():Object.entries(t)],i=Object.fromEntries(s.map(([a],p)=>[p,a]));return n.file("media",JSON.stringify(i)),s.forEach(([,a],p)=>n.file(${p},a)),n.generateAsync({type:"blob",...o})},ye="",Ne=(e,t,r)=>{let o=e.fields.join(ye);return{id:r(e.id),guid:e.guid??Oe(),tags:e.tags?.map?.(n=>n.replaceAll(" ","_"))?.join?.(" ")??"",mid:t,mod:e.updated??e.id,flds:o,sfld:o,usn:-1,flags:0,data:"",csum:0}},we=(e,t,r,o)=>e.noteType.isCloze?Re(e,t,r,o):Ie(e,t,r,o),Ie=(e,t,r,o)=>{let n=e.noteType.fields.map(s=>typeof s=="string"?s:s.name);return e.noteType.templates.flatMap((s,i)=>{for(let[,a]of s.question.matchAll(/{{(?:type\:|hint\:|#|\/)?([^}]+)}}/g)){let p=n.indexOf(a);if(!(p<0)&&!e.fields[p])return[]}return[ne({ord:i,noteId:r,deckId:t,created:r},o)]})},Re=(e,t,r,o)=>{let n=e.noteType.templates[0].question,s=new Set([...n.matchAll(/{{[^}]*?cloze:(?:[^}]?:)*(.+?)}}/g),...n.matchAll(/<%cloze:(.+?)%>/g)].map(([a,p])=>p)),i=new Set([...s].flatMap(a=>{let p=e.noteType.fields.findIndex(u=>(typeof u=="string"?u:u.name)===a);return[...(p<0?"":e.fields[p]).matchAll(/{{c(\d+)::.+?}}/g)].map(([u,b])=>parseInt(b)).flatMap(u=>u>=1?[u-1]:[])}));return i.size===0&&i.add(0),[...i].map(a=>ne({ord:a,noteId:r,deckId:t,created:r},o))},ne=(e,t)=>({ord:e.ord,id:t(e.created),nid:e.noteId,did:e.deckId,mod:e.updated??Math.round(e.created/1e3),usn:-1,type:0,queue:0,due:0,ivl:0,factor:0,reps:0,lapses:0,left:0,odue:0,odid:0,flags:0,data:""}),ve=(e,t,r)=>({vers:[],name:e.name,tags:[],did:t??1,usn:-1,req:[[0,"all",[0]]],flds:e.fields.map((o,n)=>Te(o,n)),sortf:0,latexPre:e.latex?.[0]??\\documentclass12pt{article} \\special{papersize=3in,5in}
\\usepackageutf8{inputenc} \\usepackage{amssymb,amsmath}
\\pagestyle{empty}
\\setlength{\\parindent}{0in}
\\begin{document}
,tmpls:e.templates.map((o,n)=>Pe(o,n)),latexPost:e.latex?.[1]??"\\end{document}",type:e.isCloze?1:0,id:r(e.id),css:e.css??.card {
font-family: arial;
font-size: 20px;
text-align: center;
color: black;
background-color: white;
}
,mod:e.updated??Math.round(e.id/1e3)}),Te=(e,t)=>typeof e=="string"?{name:e,description:"",media:[],sticky:!1,rtl:!1,ord:t,font:"Arial",size:20}:{name:e.name,description:e.description??"",media:[],sticky:!1,rtl:e.rtl??!1,ord:t,font:e.font??"Arial",size:e.fontSize??20},Pe=(e,t)=>({name:e.name,ord:t,did:null,qfmt:e.question,bafmt:e.example?.[0]??"",afmt:e.answer,bqfmt:e.example?.[1]??""}),Le=(e,t)=>({collapsed:!1,conf:1,desc:e.description??"",dyn:0,extendNew:10,extendRev:50,id:t(e.id),lrnToday:[545,0],mod:e.updated??Math.round(e.id/1e3),name:e.name,newToday:[545,0],revToday:[545,0],timeToday:[545,0],usn:-1}),j=()=>{let e=-1;return t=>e<t?(e=t,t):++e},$="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&()*+,-./:;<=>?@[]^_{|}~",Oe=()=>{let e=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER),t="";for(;e>0;){let r=Math.floor(e/$.length),o=e%$.length;t+=$o,e=r}return t.split("").reverse().join("")};var Se=e=>({type:"title",text:e.rows0.text}),je=e=>{let{rows:t,...r}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*code:/,"");return{indent:o,type:"codeBlock",fileName:s,content:r.map(i=>i.text.substring(o+1)).join(` )}},f=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,i)=>{var a,p,d,c,u,b;if(!t&&s.nested)return(a=i?.())!==null&&a!==void 0?a:[];if(!r&&s.quoted)return(p=i?.())!==null&&p!==void 0?p:[];for(let N of o){let g=N.exec(n);if(g===null)continue;let E=n.substring(0,g.index),l=n.substring(g.index+((c=(d=g[0])===null||d===void 0?void 0:d.length)!==null&&c!==void 0?c:0)),y=e((u=g[0])!==null&&u!==void 0?u:"",s);return[...w(E,s),...y,...w(l,s)]}return(b=i?.())!==null&&b!==void 0?b:[]},x=e=>[{type:"plain",raw:e,text:e}],Ce=f(x,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]}),qe=/^>.*$/,Me=(e,t)=>t.context==="table"?x(e,t):[{type:"quote",raw:e,nodes:w(e.substring(1),{...t,quoted:!0})}],$e=f(Me,{parseOnNested:!1,parseOnQuoted:!1,patterns:[qe]}),Ue=/^\? .+$/,Be=(e,t)=>t.context==="table"?x(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],Fe=f(Be,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Ue]}),De=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)\]\]/i,Ae=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,ze=(e,t)=>{if(t.context==="table")return x(e,t);let r=e.substring(2,e.length-2),o=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(r);return[{type:"strongImage",raw:e,src:o?${r}/thumb/1000:r}]},Ge=f(ze,{parseOnNested:!1,parseOnQuoted:!0,patterns:[De,Ae]}),_e=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/;function se(e){return(t,r)=>{if(e==="strongIcon"&&r.context==="table")return x(t,r);let o=e==="icon"?t.substring(1,t.length-1):t.substring(2,t.length-2),n=o.lastIndexOf(".icon"),s=o.substring(0,n),i=s.startsWith("/")?"root":"relative",a=o.substring(n+5,o.length),p=a.startsWith("*")?parseInt(a.substring(1),10):1;return new Array(p).fill({}).map(()=>({path:s,pathType:i,type:e,raw:t}))}}var Qe=se("icon"),Je=f(Qe,{parseOnNested:!0,parseOnQuoted:!0,patterns:[_e]}),We=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,Xe=se("strongIcon"),Ze=f(Xe,{parseOnNested:!1,parseOnQuoted:!0,patterns:[We]}),Ke=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,Ve=(e,t)=>t.context==="table"?x(e,t):[{type:"strong",raw:e,nodes:w(e.substring(2,e.length-2),{...t,nested:!0})}],He=f(Ve,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Ke]}),Ye=/\[\$ .+? \]/,et=/\[\$ [^\]]+\]/,tt=(e,t)=>t.context==="table"?x(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],rt=f(tt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Ye,et]}),ot=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,nt=(e,t)=>{if(t.context==="table")return x(e,t);let r=e.indexOf(" "),o=e.substring(1,r),n=e.substring(r+1,e.length-1),s=new Set(o);if(s.has("*")){let i=o.split("*").length-1;s.delete("*"),s.add(*-${Math.min(i,10)})}return[{type:"decoration",raw:e,rawDecos:o,decos:Array.from(s),nodes:w(n,{...t,nested:!0})}]},st=f(nt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ot]}),at=/.*?/,it=(e,t)=>t.context==="table"?x(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],pt=f(it,{parseOnNested:!1,parseOnQuoted:!0,patterns:[at]}),dt=/^[$%] .+$/,ct=(e,t)=>{var r;if(t.context==="table")return x(e,t);let o=(r=e[0])!==null&&r!==void 0?r:"",n=e.substring(2);return[{type:"commandLine",raw:e,symbol:o,text:n}]},lt=f(ct,{parseOnNested:!1,parseOnQuoted:!1,patterns:[dt]}),ut=/\[\s+\]/,mt=(e,t)=>t.context==="table"?x(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],gt=f(mt,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ut]}),ft=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,ht=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?\]/i,xt=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,kt=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,bt=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg)(\?[^\]\s]+)?$/i.test(e)||Et(e),Et=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),yt=(e,t)=>{if(t.context==="table")return x(e,t);let r=e.search(/\s/),o=r!==-1?e.substring(1,r):e.substring(1,e.length-1),n=r!==-1?e.substring(r,e.length-1).trimLeft():"",[s,i]=bt(n)?[n,o]:[o,n];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(s)?${s}/thumb/1000:s,link:i}]},Nt=f(yt,{parseOnNested:!0,parseOnQuoted:!0,patterns:[ft,ht,xt,kt]}),wt=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,It=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,Rt=/\[https?:\/\/[^\s\]]+\]/,vt=/https?:\/\/[^\s]+/,Tt=(e,t)=>{if(t.context==="table")return x(e,t);let r=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,o=/^https?:\/\/[^\s\]]/.test(r),n=(o?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(r);if(n?.[0]===void 0)return[];let s=o?r.substring(n[0].length):r.substring(0,n.index-1);return[{type:"link",raw:e,pathType:"absolute",href:n[0],content:s.trim()}]},Pt=f(Tt,{parseOnNested:!0,parseOnQuoted:!0,patterns:[wt,It,Rt,vt]}),ae=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,ie=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,Lt=e=>{let[t="",r="",o=""]=e.split(","),n=parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),i=/^Z\d+$/.test(o)?parseInt(o.replace(/^Z/,""),10):14;return{latitude:n,longitude:s,zoom:i}},Ot=(e,t)=>{var r;if(t.context==="table")return x(e,t);let o=(r=e.match(ae))!==null&&r!==void 0?r:e.match(ie);if(o===null)return[];let n=e.startsWith("[N")||e.startsWith("[S"),[,s="",i=""]=n?o:[o[0],o[2],o[1]],{latitude:a,longitude:p,zoom:d}=Lt(s),c=i!==""?https://www.google.com/maps/place/${encodeURIComponent(i)}/@${a},${p},${d}z:https://www.google.com/maps/@${a},${p},${d}z;return[{type:"googleMap",raw:e,latitude:a,longitude:p,zoom:d,place:i,url:c}]},St=f(Ot,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ae,ie]}),jt=/\[\/?[^[\]]+\]/,Ct=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},qt=f(Ct,{parseOnNested:!0,parseOnQuoted:!0,patterns:[jt]}),Mt=/(?:^|\s)#\S+/,$t=(e,t)=>{if(t.context==="table")return x(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...x(r,t),{type:"hashTag",raw:o,href:o.substring(1)}]},Ut=f($t,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Mt]}),Bt=/^[0-9]+\. .*$/,Ft=(e,t)=>{if(t.context==="table")return x(e,t);let r=e.indexOf(" "),o=e.substring(0,r-1),n=parseInt(o,10),s=e.substring(r+1,e.length);return[{type:"numberList",raw:e,rawNumber:o,number:n,nodes:w(s,{...t,nested:!0})}]},Dt=f(Ft,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Bt]}),At=(e,t,r)=>{var o;return e===""?[]:(o=r?.())!==null&&o!==void 0?o:[]},zt=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>Ce(t,r))(),w=zt(At,$e,Fe,pt,lt,rt,gt,st,Ge,Ze,He,Nt,Pt,Je,St,qt,Ut,Dt),Gt=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*table:/,"");return{indent:o,type:"table",fileName:s,cells:r.map(i=>i.text.substring(o+1)).map(i=>i.split(" ").map(a=>w(a,{nested:!1,quoted:!1,context:"table"})))}},_t=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:w(r.substring(t),{nested:!1,quoted:!1,context:"line"})}},U=e=>{switch(e.type){case"title":return Se(e);case"codeBlock":return je(e);case"table":return Gt(e);case"line":return _t(e)}},R=e=>e.split( ).map(t=>{var r,o,n;return{indent:(n=(o=(r=/^\s+/.exec(t))===null||r===void 0?void 0:r[0])===null||o===void 0?void 0:o.length)!==null&&n!==void 0?n:0,text:t}}),Qt=(e,t)=>{var r,o;return(e.type==="codeBlock"||e.type==="table")&&t.indent>((o=(r=e.rows[0])===null||r===void 0?void 0:r.indent)!==null&&o!==void 0?o:0)},pe=(e,t)=>{let r=e[e.length-1];return r!==void 0&&Qt(r,t)?(r.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},v=(e,t)=>{var r;if(!((r=t.hasTitle)!==null&&r!==void 0)||r){let[o,...n]=e;return o===void 0?[]:[{type:"title",rows:[o]},...n.reduce(pe,[])]}return e.reduce(pe,[])},de=(e,t)=>{var r;let o=R(e);return v(o,{hasTitle:(r=t?.hasTitle)!==null&&r!==void 0?r:!0}).map(U)};var Jt=/^deck:\[([^[\]]*)\.icon(?:\*[1-9]\d*)?\]/,Wt=/^noteType:\[([^[\]]*)\.icon(?:\*[1-9]\d*)?\]/,ce=(e,t,r)=>{let o={notes:[]};if(r.length===0)return o;let n=v(R(r.map(a=>a.text).join(
)),{hasTitle:!0}),s=new Map,i=0;for(let a of n)switch(a.type){case"title":i++;break;case"table":i+=a.rows.length;break;case"line":{let p=a.rows[0].text.match(Jt)?.[1];p&&(o.deckRef=ue(p,e));let d=a.rows[0].text.match(Wt)?.[1];d&&(o.noteTypeRef=ue(d,e)),i++;break}case"codeBlock":{let p=Math.min(...r.slice(i,i+a.rows.length).map(g=>g.created*1e3)),d=r[i].id,c=Math.max(...r.slice(i,i+a.rows.length).map(g=>g.updated));i+=a.rows.length;let u=U(a);if(u.type!=="codeBlock")throw SyntaxError();if(!u.fileName.endsWith(".note"))break;let b=u.fileName.slice(0,-5),N=s.get(b);s.set(b,[p,d,c*1e3,N?${N}
${u.content}:u.content]);break}}return o.notes.push(...[...s.entries()].map(([a,[p,d,c,u]])=>({guid:a,id:p,updated:c,fields:[u.replaceAll(
,"<br>"),https://scrapbox.io/${e}/${P(t)}#${d}],tags:de(u).flatMap(b=>b.type!=="line"?[]:b.nodes.flatMap(N=>le(N)))}))),o},le=e=>{switch(e.type){case"hashTag":return[e.href];case"decoration":case"quote":return e.nodes.flatMap(t=>le(t));default:return[]}},ue=(e,t)=>{let[,r,o]=e.match(/^\/([\w\-]+)\/(.+)$/)??[];return r&&o?{project:r,title:o}:{project:t,title:e}};var me=e=>{if(e.length===0)return{ok:!0,value:void 0};let t=v(R(e.map(a=>a.text).join( )),{hasTitle:!0}),r,o,n,s=0,i=0;for(let a of t)switch(a.type){case"title":case"line":i++;break;case"codeBlock":i+=a.rows.length;break;case"table":{if(s=Math.max(...e.slice(i,i+a.rows.length).map(d=>d.updated),s),i+=a.rows.length,!a.rows[0].text.endsWith("deck"))break;let p=Object.fromEntries(a.rows.map(({text:d})=>d.trim().split(/\s+/)));if(Object.hasOwn(p,"name")&&!o){if(!p.name)return{ok:!1,value:B("Deck name not found.")};o=p.name}if(Object.hasOwn(p,"id")&&!r){if(!p.id)return{ok:!1,value:B("Deck id not found.")};let d=parseInt(p.id);if(isNaN(d))return{ok:!1,value:B("Deck id is not number.")};r=d}n??=p.description;break}}return{ok:!0,value:r&&o?{id:r,name:o,description:n,updated:s}:void 0}},B=e=>({name:"InvalidDeckError",message:e});var I={name:"Basic (Cloze)",id:1677417085373,fields:[{name:"Text",description:"問題文"},{name:"SourceURL",description:"問題の取得元URL"}],isCloze:!0,templates:[{name:"Card 1",answer:'{{cloze:Text}}<br><a href="{{SourceURL}}">source</a>',question:{{cloze:Text}}
{{type:Text}}}],css:.card {
display: flex;
justify-content: center;
font-family: arial;
font-size: 20px;
color: black;
background-color: white;
}
.cloze {
font-weight: bold;
color: blue;
}
.nightMode .cloze {
color: lightblue;
}},ge=e=>{if(e.length===0)return{ok:!0,value:void 0};let t=v(R(e.map(p=>p.text).join(
)),{hasTitle:!0}),r,o,n=0,s,i,a=0;for(let p of t)switch(p.type){case"title":case"line":a++;break;case"codeBlock":a+=p.rows.length;break;case"table":{if(n=Math.max(...e.slice(a,a+p.rows.length).map(c=>c.updated),n),a+=p.rows.length,!p.rows[0].text.endsWith("note type"))break;let d=Object.fromEntries(p.rows.map(({text:c})=>c.trim().split(/\s+/)));if(Object.hasOwn(d,"name")&&!o){if(!d.name)return{ok:!1,value:S("Note type name not found.")};o=d.name}if(Object.hasOwn(d,"id")&&!r){if(!d.id)return{ok:!1,value:S("Note type id not found.")};let c=parseInt(d.id);if(isNaN(c))return{ok:!1,value:S("Note type id is not number.")};r=c}if(Object.hasOwn(d,"answer")&&!s){if(!d.answer)return{ok:!1,value:S("answer not found.")};s=d.answer}if(Object.hasOwn(d,"question")&&!i){if(!d.question)return{ok:!1,value:S("question not found.")};i=d.question}break}}return{ok:!0,value:r&&o?{name:o,id:r,updated:n,fields:structuredClone(I.fields),isCloze:!0,templates:[{name:"Card 1",answer:s??I.templates[0].answer,question:i??I.templates[0].question}],css:I.css}:void 0}},S=e=>({name:"InvalidNoteTypeError",message:e});var F={name:"default",id:1},fe=new Map,Xt=e=>{if(!e)return Promise.resolve({ok:!0,value:F});let t=fe.get(C(e));if(t)return t;let r=(async()=>{let o=await O(e.project,e.title);return o.ok?me(o.value.lines):o})();return fe.set(C(e),r),r},he=new Map,Zt=e=>{if(!e)return Promise.resolve({ok:!0,value:I});let t=he.get(C(e));if(t)return t;let r=(async()=>{let o=await O(e.project,e.title);return o.ok?ge(o.value.lines):o})();return he.set(C(e),r),r},$n=async(e,t,r)=>{let o=(await Promise.all(t.map(async n=>{let{deckRef:s,noteTypeRef:i,notes:a}=ce(e,n.title,n.lines),p=await Xt(s);p.ok||console.warn(${p.value.name} ${p.value.message});let d=p.ok?p.value??F:F,c=await Zt(i);c.ok||console.warn(${c.value.name} ${c.value.message});let u=c.ok?c.value??I:I;return a.map(b=>({deck:d,noteType:u,...b}))}))).flat();return{ok:!0,value:await oe(re(o,r.sql),{},r.jsZip)}},C=e=>/${e.project}/${e.title}`;export{$n as makeApkg};