@pritzlaff/nano-app 0.0.0-stage → 0.5.2
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/AGENTS.md +66 -0
- package/LICENSE +21 -0
- package/README.md +6 -2
- package/app/app.css +160 -0
- package/app/bundle/nano-ui.js +2554 -0
- package/app/examples/auth/example.auth.js +6 -0
- package/app/examples/auth/nano.json +46 -0
- package/app/examples/chat/example.chat.js +6 -0
- package/app/examples/chat/example.messaging.js +3 -0
- package/app/examples/chat/nano.json +115 -0
- package/app/examples/drift/example.drift.js +3 -0
- package/app/examples/drift/nano.json +31 -0
- package/app/examples/kv/example.kv.js +3 -0
- package/app/examples/nano.json +356 -0
- package/app/examples/originkey/_nano/bundle/nano-ui.js +212 -0
- package/app/examples/originkey/_nano/sandbox/boot.js +1 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-2gg2vg5g.js +2 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-5h5dssvv.js +3 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-72b5e6vd.js +17 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-87v2yejk.js +2 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-hm29e227.js +7 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-jtgk4ch8.js +2 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-mqaje7vc.js +2 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-mxgap7rs.js +2 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-qy0mwf7y.js +1 -0
- package/app/examples/originkey/_nano/shared/chunks/nano-core-wanb7xw1.js +1 -0
- package/app/examples/originkey/_nano/shared/lit-class-map.js +1 -0
- package/app/examples/originkey/_nano/shared/lit-decorators.js +1 -0
- package/app/examples/originkey/_nano/shared/lit-directive.js +1 -0
- package/app/examples/originkey/_nano/shared/lit-if-defined.js +1 -0
- package/app/examples/originkey/_nano/shared/lit-ref.js +1 -0
- package/app/examples/originkey/_nano/shared/lit-repeat.js +1 -0
- package/app/examples/originkey/_nano/shared/lit-style-map.js +1 -0
- package/app/examples/originkey/_nano/shared/lit.js +1 -0
- package/app/examples/originkey/_nano/shared/nano-core.js +1 -0
- package/app/examples/originkey/_nano/shared/nano-elements.js +280 -0
- package/app/examples/originkey/_nano/shared/typebox-value.js +1 -0
- package/app/examples/originkey/_nano/shared/typebox.js +1 -0
- package/app/examples/originkey/example.originkey.js +6 -0
- package/app/examples/originkey/frame.html +1 -0
- package/app/examples/originkey/nano.json +50 -0
- package/app/examples/raft/example.raft.js +30 -0
- package/app/examples/raft/nano.json +74 -0
- package/app/examples/slice/nano.json +63 -0
- package/app/examples/slice/shout.js +14 -0
- package/app/examples/template/acme.template.js +20 -0
- package/app/examples/template/index.js +241 -0
- package/app/examples/template/nano.json +35 -0
- package/app/examples/todo/example.todo.js +8 -0
- package/app/examples/todo/nano.json +77 -0
- package/app/examples/typing/nano.json +33 -0
- package/app/favicon.svg +1 -0
- package/app/index.html +152 -0
- package/app/main.js +15908 -0
- package/app/react/index.html +50 -0
- package/app/react/main.js +9 -0
- package/app/sandbox/boot.js +980 -0
- package/app/shared/chunks/nano-core-296y9rgd.js +4321 -0
- package/app/shared/chunks/nano-core-2zz7d74m.js +16 -0
- package/app/shared/chunks/nano-core-35ryhkm1.js +33 -0
- package/app/shared/chunks/nano-core-5a3r312d.js +866 -0
- package/app/shared/chunks/nano-core-89mtxedm.js +186 -0
- package/app/shared/chunks/nano-core-bf13r20v.js +77 -0
- package/app/shared/chunks/nano-core-g3414rnc.js +248 -0
- package/app/shared/chunks/nano-core-hyg0qdwg.js +547 -0
- package/app/shared/chunks/nano-core-sxgrxy03.js +53 -0
- package/app/shared/chunks/nano-core-wg5c961d.js +4564 -0
- package/app/shared/lit-class-map.js +60 -0
- package/app/shared/lit-decorators.js +228 -0
- package/app/shared/lit-directive.js +11 -0
- package/app/shared/lit-if-defined.js +10 -0
- package/app/shared/lit-ref.js +12 -0
- package/app/shared/lit-repeat.js +141 -0
- package/app/shared/lit-style-map.js +67 -0
- package/app/shared/lit.js +47 -0
- package/app/shared/nano-core.js +2516 -0
- package/app/shared/nano-elements.js +1178 -0
- package/app/shared/typebox-value.js +78 -0
- package/app/shared/typebox.js +580 -0
- package/app/shared/versions.json +6 -0
- package/bin/nano-app.ts +34 -0
- package/package.json +22 -4
- package/src/events.ts +11 -0
- package/src/serve.ts +68 -0
- package/src/watch.ts +27 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"pods": {
|
|
3
|
+
"originKey": {
|
|
4
|
+
"implementation": "example.originkey/passkey",
|
|
5
|
+
"eager": true,
|
|
6
|
+
"isolation": "home-origin"
|
|
7
|
+
},
|
|
8
|
+
"keyLog": {
|
|
9
|
+
"implementation": "nano.ui/log",
|
|
10
|
+
"eager": false
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"runtimes": {
|
|
14
|
+
"example.originkey.main": {
|
|
15
|
+
"pods": [
|
|
16
|
+
"originKey",
|
|
17
|
+
"keyLog"
|
|
18
|
+
],
|
|
19
|
+
"subscriptions": [
|
|
20
|
+
{
|
|
21
|
+
"kind": "pipe",
|
|
22
|
+
"from": "originKey",
|
|
23
|
+
"source": "example.auth.Auth/authenticated",
|
|
24
|
+
"to": "keyLog",
|
|
25
|
+
"target": "nano.ui.Log/log"
|
|
26
|
+
}
|
|
27
|
+
]
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"modules": {
|
|
31
|
+
"example.originkey": "./example.originkey.js"
|
|
32
|
+
},
|
|
33
|
+
"frames": {
|
|
34
|
+
"example.originkey": "./frame.html"
|
|
35
|
+
},
|
|
36
|
+
"layout": {
|
|
37
|
+
"slots": [
|
|
38
|
+
{
|
|
39
|
+
"id": "originKey",
|
|
40
|
+
"runtime": "example.originkey.main",
|
|
41
|
+
"pod": "originKey"
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"id": "keyLog",
|
|
45
|
+
"runtime": "example.originkey.main",
|
|
46
|
+
"pod": "keyLog"
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import{Coord as KQ}from"@pritzlaff/nano-core";import{Type as p}from"typebox";import{Coord as RJ,Implementation as NJ,Schema as kJ,failure as wY,provide as xJ,success as TJ}from"@pritzlaff/nano-core";import{HostDeploy as ZY}from"@pritzlaff/nano-ui";import{Type as B}from"typebox";import{Coord as QJ,Schema as O,Op as V}from"@pritzlaff/nano-core";import{Any as XJ,Nothing as H}from"@pritzlaff/nano-ui";var h=QJ.namespace("example.raft"),G=B.Integer({minimum:0}),EY=B.Object({index:G,term:G,value:B.Unknown(),at:B.Number()}),f=O.define(B.Object({currentTerm:G,votedFor:B.Union([B.String(),B.Null()]),log:B.Array(EY)}),"Persistent"),u=(Y,J)=>B.Object({kind:B.Literal(Y),term:G,from:B.String(),...J}),AY=O.define(B.Union([u("vote",{lastIndex:G,lastTerm:G}),u("vote-reply",{granted:B.Boolean()}),u("append",{prevIndex:G,prevTerm:G,entries:B.Array(EY),commit:G}),u("append-reply",{success:B.Boolean(),match:G})]),"RaftMessage"),ZJ=O.define(B.Object({to:B.String(),message:AY}),"Envelope"),x=B.Object({electionMin:G,electionMax:G,heartbeat:G}),$J=B.Object({next:G,match:G,granted:B.Boolean(),rpcDue:B.Number(),heartbeatDue:B.Number()}),DY=O.define(B.Object({id:B.String(),peers:B.Array(B.String()),p:f,role:B.Union([B.Literal("follower"),B.Literal("candidate"),B.Literal("leader")]),commitIndex:G,leader:B.Union([B.String(),B.Null()]),electionAlarm:B.Number(),stopped:B.Boolean(),progress:B.Record(B.String(),$J),timing:x}),"NodeStatus"),BJ=O.define(B.Object({name:B.String(),size:B.Union([B.Literal(3),B.Literal(5)]),seed:B.Integer(),heartbeatMs:B.Optional(B.Integer({minimum:10,maximum:60000}))}),"ClusterSpec"),WJ=O.define(B.Object({name:B.String()}),"ClusterName"),KJ=O.define(B.Array(B.String()),"Names"),b=h.interface("Messaging",{send:V.action(ZJ,H)}),q=h.interface("RaftNode",{receive:V.action(AY,H),request:V.action(XJ,H),timeOut:V.action(H,H),stop:V.action(H,H),resume:V.action(H,H),restart:V.action(H,H),status:V.action(H,DY),changed:V.event(DY)}),D=h.interface("Ledger",{read:V.action(H,f),write:V.action(f,H),written:V.event(f)}),T=h.interface("Cluster",{create:V.action(BJ,H),remove:V.action(WJ,H),list:V.action(H,KJ)});import{Pod as JY}from"@pritzlaff/nano-core";import{seededRandom as IJ}from"@pritzlaff/nano-ui";import{Coord as _J,Implementation as jJ,provide as UJ,success as LY}from"@pritzlaff/nano-core";var qJ=_J.namespace("example.raft"),FJ={currentTerm:0,votedFor:null,log:[]},m=jJ.define(qJ.implementationId("ledger"),{provides:[D],make:(Y)=>{let J=FJ;return[UJ(D,{read:async()=>LY(J),write:async(Q)=>{return J=Q,await Y.publish(D.ops.written,Q),LY(null)}})]}});import{Type as y}from"typebox";import{Coord as SJ,Implementation as OJ,Schema as CJ,failure as RY,provide as MJ,success as I}from"@pritzlaff/nano-core";import{Clock as YY,Random as NY}from"@pritzlaff/nano-ui";var E=(Y)=>Y.log.length,w=(Y,J)=>J===0?0:Y.log[J-1].term,c=(Y)=>w(Y,E(Y)),l=(Y)=>Math.floor((Y.peers.length+1)/2)+1,i=(Y)=>2*Y.timing.heartbeat;var C=(Y,J,Q)=>J+Y.electionMin+Q()*(Y.electionMax-Y.electionMin);function SY(Y,J){let{n:Q}=Y;if(Q.role==="leader")Q.electionAlarm=C(Q.timing,Y.now,Y.draw);Q.p={...Q.p,currentTerm:J,votedFor:null},Q.role="follower",Q.leader=null}function t(Y){let{n:J}=Y;J.p={...J.p,currentTerm:J.p.currentTerm+1,votedFor:J.id},J.role="candidate",J.leader=null,J.electionAlarm=C(J.timing,Y.now,Y.draw);for(let Q of Object.values(J.progress))Object.assign(Q,{granted:!1,rpcDue:0})}function OY(Y){let{n:J}=Y;for(let Q of J.peers){let X=J.progress[Q];if(X.rpcDue>Y.now)continue;X.rpcDue=Y.now+i(J),Y.out.push({kind:"send",to:Q,rpc:{kind:"vote",term:J.p.currentTerm,lastIndex:E(J.p),lastTerm:c(J.p)}})}}function CY(Y,J,Q){let{n:X}=Y,Z=Q.lastTerm>c(X.p)||Q.lastTerm===c(X.p)&&Q.lastIndex>=E(X.p),$=Q.term===X.p.currentTerm&&(X.p.votedFor??J)===J&&Z;if($){if(X.p.votedFor!==J)X.p={...X.p,votedFor:J};X.electionAlarm=C(X.timing,Y.now,Y.draw)}Y.out.push({kind:"send",to:J,rpc:{kind:"vote-reply",term:X.p.currentTerm,granted:$}})}function MY(Y,J,Q){let{n:X}=Y;if(X.role!=="candidate"||Q.term!==X.p.currentTerm)return;let Z=X.progress[J];if(Z.granted=Q.granted,Z.rpcDue=X.electionAlarm,1+X.peers.filter(($)=>X.progress[$].granted).length>=l(X))HJ(Y)}function HJ(Y){let{n:J}=Y;J.role="leader",J.leader=J.id;for(let Q of Object.values(J.progress))Object.assign(Q,{next:E(J.p)+1,match:0,rpcDue:0,heartbeatDue:0})}function zY(Y){let{n:J}=Y;for(let Q of J.peers){let X=J.progress[Q];if(!(X.next<=E(J.p)&&X.rpcDue<=Y.now)&&X.heartbeatDue>Y.now)continue;let $=X.next-1;Y.out.push({kind:"send",to:Q,rpc:{kind:"append",term:J.p.currentTerm,prevIndex:$,prevTerm:w(J.p,$),entries:J.p.log.slice($),commit:J.commitIndex}}),X.rpcDue=Y.now+i(J),X.heartbeatDue=Y.now+J.timing.heartbeat}}function vY(Y,J,Q){let{n:X}=Y,Z=(W,F)=>Y.out.push({kind:"send",to:J,rpc:{kind:"append-reply",term:X.p.currentTerm,success:W,match:F}});if(Q.term<X.p.currentTerm)return Z(!1,0);if(X.role="follower",X.leader=J,X.electionAlarm=C(X.timing,Y.now,Y.draw),Q.prevIndex>E(X.p)||w(X.p,Q.prevIndex)!==Q.prevTerm)return Z(!1,0);let $=GJ(X.p.log,Q.entries);if($!==X.p.log)X.p={...X.p,log:$};let _=Q.prevIndex+Q.entries.length;X.commitIndex=Math.max(X.commitIndex,Math.min(Q.commit,_)),Z(!0,_)}function GJ(Y,J){for(let Q of J)if(Y[Q.index-1]?.term!==Q.term)Y=[...Y.slice(0,Q.index-1),Q];return Y}function bY(Y,J,Q){let{n:X}=Y;if(X.role!=="leader"||Q.term!==X.p.currentTerm)return;let Z=X.progress[J];if(Q.success)Z.match=Math.max(Z.match,Q.match),Z.next=Z.match+1;else Z.next=Math.max(1,Z.next-1);Z.rpcDue=0,PJ(Y)}function PJ(Y){let{n:J}=Y;for(let Q=E(J.p);Q>J.commitIndex&&w(J.p,Q)===J.p.currentTerm;Q--)if(1+J.peers.filter((X)=>J.progress[X].match>=Q).length>=l(J))return void(J.commitIndex=Q)}var VJ={electionMin:150,electionMax:300,heartbeat:50};function e(Y,J,Q,X,Z,$=VJ){return{id:Y,peers:J,p:Q,role:"follower",commitIndex:0,leader:null,electionAlarm:C($,X,Z),stopped:!1,progress:Object.fromEntries(J.map((_)=>[_,{next:1,match:0,granted:!1,rpcDue:0,heartbeatDue:0}])),timing:$}}function IY(Y,J,Q,X){let Z=Object.fromEntries(Object.entries(Y.progress).map(([_,W])=>[_,{...W}])),$={n:{...Y,progress:Z},now:Q,draw:X,out:[]};if(DJ($,J),$.n.p!==(J.kind==="restart"?J.p:Y.p))$.out.unshift({kind:"persist",p:$.n.p});return{node:$.n,effects:$.out}}function DJ(Y,J){let{n:Q}=Y;if(Q.stopped){if(J.kind==="resume")Q.stopped=!1;if(J.kind==="request")Y.out.push({kind:"refused",reason:"stopped"});return}switch(J.kind){case"tick":return EJ(Y);case"time-out":return t(Y);case"stop":Q.stopped=!0;return;case"resume":return;case"restart":Y.n=e(Q.id,Q.peers,J.p,Y.now,Y.draw,Q.timing);return;case"request":return AJ(Y,J.value);case"receive":return LJ(Y,J.from,J.rpc)}}function EJ(Y){if(Y.n.role!=="leader"&&Y.now>=Y.n.electionAlarm)t(Y);if(Y.n.role==="candidate")OY(Y);if(Y.n.role==="leader")zY(Y)}function AJ(Y,J){let{n:Q}=Y;if(Q.role==="leader")Q.p={...Q.p,log:[...Q.p.log,{index:E(Q.p)+1,term:Q.p.currentTerm,value:J,at:Y.now}]};else if(Q.leader)Y.out.push({kind:"refused",reason:"not leader",leader:Q.leader});else Y.out.push({kind:"refused",reason:"no leader known"})}function LJ(Y,J,Q){if(Q.term>Y.n.p.currentTerm)SY(Y,Q.term);switch(Q.kind){case"vote":return CY(Y,J,Q);case"vote-reply":return MY(Y,J,Q);case"append":return vY(Y,J,Q);case"append-reply":return bY(Y,J,Q)}}var zJ=SJ.namespace("example.raft"),vJ=3;function bJ(Y){if(Y.stopped)return;let J=Object.values(Y.progress);if(Y.role==="leader")return Math.min(...J.map((Q)=>Q.next<=E(Y.p)?Math.min(Q.rpcDue,Q.heartbeatDue):Q.heartbeatDue));if(Y.role==="candidate")return Math.min(Y.electionAlarm,...J.map((Q)=>Q.rpcDue));return Y.electionAlarm}var o=OJ.define(zJ.implementationId("node"),{provides:[q],config:CJ.define(y.Object({id:y.String(),peers:y.Array(y.String()),timing:y.Optional(x)}),"NodeConfig"),dependencies:{messaging:b,ledger:D,clock:YY,random:NY},make:(Y,{id:J,peers:Q,timing:X})=>{let Z=(K,P)=>{if(!K.ok)throw Error(`node ${J} needs ${P}: ${K.fail.reason}`);return K.value},$=Z(Y.one(b),"messaging"),_=Z(Y.one(D),"a ledger"),W=Z(Y.one(YY),"a clock"),F=Z(Y.one(NY),"a random"),j,U,A=!1,z=Promise.resolve(),s=(K)=>z=z.then(K,K),r=[],FY=async()=>{while(r.length<vJ){let K=await F.call.next(null);if(!K.ok)return K;r.push(K.value)}},HY=()=>{let K=r.shift();if(K===void 0)throw Error("more draws than DRAWS");return K},GY=async(K)=>{let P=bJ(j);if(P===U?.due)return;if(U)W.call.cancel(U.id);if(U=void 0,P===void 0||A)return;let v=await W.call.after({ms:Math.max(0,Math.ceil(P-K)),tag:J});if(v.ok)U={id:v.value,due:P}},L=(K,P)=>s(async()=>{if(A)return RY("not-found",`node ${J} is closed`);let v=typeof K==="function"?await K():I(K);if(!v.ok)return v;let g=P===void 0?await W.call.now(null):I(P);if(!g.ok)return g;let PY=await FY();if(PY)return PY;let JJ=JSON.stringify(j),n=IY(j,v.value,g.value,HY);j=n.node;try{for(let S of n.effects){let VY=S.kind==="persist"?await _.call.write(S.p):S.kind==="send"?await $.call.send({to:S.to,message:{...S.rpc,from:J}}):I(null);if(!VY.ok)return VY}}finally{if(JSON.stringify(j)!==JJ)await Y.publish(q.ops.changed,j);await GY(g.value)}let k=n.effects.find((S)=>S.kind==="refused");return k?RY("invalid-input",k.leader?`${k.reason}: the leader is ${k.leader}`:k.reason):I(null)});return s(async()=>{let K=await _.call.read(null),P=await W.call.now(null);if(!K.ok||!P.ok||await FY())return;j=e(J,Q,K.value,P.value,HY,X),await GY(P.value)}),W.on(YY.ops.fired,({output:K})=>{if(K.id!==U?.id)return;U=void 0,L({kind:"tick"},K.at)}),Y.addOnCloseListener(()=>{if(A=!0,U)W.call.cancel(U.id)}),[MJ(q,{receive:async({from:K,...P})=>L({kind:"receive",from:K,rpc:P}),request:async(K)=>L({kind:"request",value:K}),timeOut:async()=>L({kind:"time-out"}),stop:async()=>L({kind:"stop"}),resume:async()=>L({kind:"resume"}),restart:async()=>L(async()=>{let K=await _.call.read(null);return K.ok?I({kind:"restart",p:K.value}):K}),status:()=>s(async()=>I(j))})]}});var QY="raft-messaging",kY="raft-clock",xY=(Y,J)=>Y===void 0?J:{heartbeat:Y,electionMin:3*Y,electionMax:6*Y},XY=(Y,J)=>Array.from({length:J},(Q,X)=>`${Y}-${X+1}`);function TY(Y,J,Q,X){let Z=XY(Y,J),$={},_={};return Z.forEach((W,F)=>{let j=`${W}-raft`,U=`${W}-ledger`,A=`${W}-random`;$[j]=JY.eager(o,{config:{id:W,peers:Z.filter((z)=>z!==W),...X&&{timing:X}}}),$[U]=JY.eager(m),$[A]=JY.eager(IJ,{config:{seed:Q+F+1}}),_[W]={pods:[QY,kY,j,U,A],subscriptions:[...[QY,U,kY,A].map((z)=>({kind:"call",from:j,to:z})),{kind:"call",from:QY,to:j}]}}),{pods:$,runtimes:_}}var wJ=RJ.namespace("example.raft"),yY=NJ.define(wJ.implementationId("cluster"),{provides:[T],config:kJ.define(p.Union([p.Object({timing:p.Optional(x)}),p.Undefined()]),"ClusterConfig"),dependencies:{deploy:ZY},make:(Y,J)=>{let Q=new Map;return[xJ(T,{create:async({name:X,size:Z,seed:$,heartbeatMs:_})=>{if(!/^[a-z][a-z0-9-]*$/.test(X))return wY("invalid-input",`cluster name ${JSON.stringify(X)}: lowercase letters, digits and hyphens, starting with a letter`);let W=Y.one(ZY);if(!W.ok)return W;let F=await W.value.call.deploy(TY(X,Z,$,xY(_,J?.timing)));if(F.ok)Q.set(X,Z);return F},remove:async({name:X})=>{let Z=Y.one(ZY);if(!Z.ok)return Z;let $=wY("not-found",`no cluster ${X}`);for(let _ of Q.has(X)?[Q.get(X)]:[5,3])if($=await Z.value.call.undeploy({runtimes:XY(X,_)}),$.ok||$.fail.type!=="not-found")break;if($.ok)Q.delete(X);return $},list:async()=>TJ([...Q.keys()])})]}});import{Type as a}from"typebox";import{Coord as fY,Implementation as yJ,Schema as gJ,Selector as uJ,provide as fJ,success as hJ}from"@pritzlaff/nano-core";import{Clock as $Y,Random as gY}from"@pritzlaff/nano-ui";var mJ=fY.namespace("example.raft"),uY=a.Integer({minimum:0,maximum:60000}),cJ="delivery",hY=yJ.define(mJ.implementationId("messaging"),{provides:[b],config:gJ.define(a.Union([a.Object({minMs:uY,maxMs:uY}),a.Undefined()]),"MessagingConfig"),dependencies:{clock:$Y,random:gY,node:q},make:(Y,J)=>{let{minMs:Q,maxMs:X}=J??{minMs:10,maxMs:30},Z=Y.one($Y),$=Y.one(gY);if(!Z.ok)throw Error(`messaging needs a clock: ${Z.fail.reason}`);if(!$.ok)throw Error(`messaging needs a random: ${$.fail.reason}`);let _=new Map;return Z.value.on($Y.ops.fired,async({output:W})=>{let F=_.get(W.id);if(!F)return;_.delete(W.id);let j=Y.one(uJ.of(q,{runtime:fY.runtime(F.to)}));if(j.ok)await j.value.call.receive(F.message)}),[fJ(b,{send:async({to:W,message:F})=>{let j=await $.value.call.next(null);if(!j.ok)return j;let U=await Z.value.call.after({ms:Q+Math.floor(j.value*(X-Q+1)),tag:cJ});if(!U.ok)return U;return _.set(U.value,{to:W,message:F}),hJ(null)}})]}});import{LitElement as dJ,css as sJ,html as N,svg as rJ}from"lit";import{base as nJ}from"@pritzlaff/nano-elements";import{Clock as oY}from"@pritzlaff/nano-ui";import{LitElement as iJ,css as oJ,html as R}from"lit";import{base as pJ,kit as aJ}from"@pritzlaff/nano-elements";var BY=(Y,J)=>{let Q=Y-J;return`${Q>=0?"+":"-"}${Math.abs(Q).toFixed(1)} ms`};function lJ(Y,J,Q){let X=Y.progress[J];if(Y.role==="candidate"&&X.granted)return"granted";let Z=X.rpcDue>Q&&!(Y.role==="candidate"&&X.rpcDue===Y.electionAlarm);return Y.role!=="follower"&&!Y.stopped&&Z?"pending":"idle"}function WY(Y,J){let Q=Y.role==="leader"?0:(Y.electionAlarm-J)/Y.timing.electionMax;return{term:Y.p.currentTerm,role:Y.role,stopped:Y.stopped,arc:Math.min(1,Math.max(0,Q)),peers:Y.peers.map((X)=>({id:X,state:lJ(Y,X,J)}))}}function mY(Y,J){return{rows:[["state",Y.stopped?"stopped":Y.role],["currentTerm",String(Y.p.currentTerm)],["votedFor",Y.p.votedFor??"—"],["commitIndex",String(Y.commitIndex)],["election alarm",BY(Y.electionAlarm,J)]],peers:Y.peers.map((Q)=>{let X=Y.progress[Q];return{peer:Q,next:X.next,match:X.match,granted:X.granted,rpcDue:BY(X.rpcDue,J),heartbeatDue:BY(X.heartbeatDue,J)}})}}var cY=(Y,J)=>({currentTerm:Y.currentTerm,votedFor:Y.votedFor,rows:Y.log.map((Q)=>({index:Q.index,term:Q.term,value:typeof Q.value==="string"?Q.value:JSON.stringify(Q.value),at:Q.at.toFixed(1),committed:Q.index<=J}))});function lY(Y){let J=Math.max(10,...Y.map((Q)=>Q.p.log.length));return{columns:J,rows:Y.map((Q)=>({id:Q.id,cells:Array.from({length:J},(X,Z)=>{let $=Q.p.log[Z];return $?{term:$.term,committed:$.index<=Q.commitIndex}:null})}))}}function KY(Y,J,Q){if(!Y||Q-Y.wall>2000)return{sim:J,wall:Q,rate:Y?.rate??1,from:{sim:J,wall:Q}};let X=Q-Y.from.wall,Z=X>=500&&J>=Y.from.sim;return{sim:J,wall:Q,rate:Z?(J-Y.from.sim)/X:Y.rate,from:Z?{sim:J,wall:Q}:Y.from}}var _Y=[["stop","stop"],["resume","resume"],["restart","restart"],["time out","timeOut"],["request","request"]];async function jY(Y,J,Q){let X=await Y.app.call(Y.runtime,Y.pod)[q.ops[J].name](J==="request"?Q:null);return X.ok?void 0:X.fail.reason}class iY extends iJ{static properties={target:{attribute:!1},status:{attribute:!1},now:{attribute:!1},error:{state:!0},text:{state:!0}};static styles=[pJ,aJ,oJ`table { border-collapse: collapse; font-size: 12px } td, th { padding: 2px 8px; text-align: left } .row { flex-wrap: wrap } textarea { width: 100%; font: inherit }`];n=0;constructor(){super();this.now=0,this.text=""}act(Y){++this.n,jY(this.target,Y,this.text||`v${this.n}`).then((J)=>{this.error=J})}render(){if(!this.status)return R``;let Y=mY(this.status,this.now),J=this.status.role==="leader",Q=(X,Z)=>R`<button class="btn small" type="button" ?disabled=${Z==="request"&&!J} @click=${()=>this.act(Z)}>${X}</button>`;return R`<div class="col">
|
|
2
|
+
<table class="rows">${Y.rows.map(([X,Z])=>R`<tr><th>${X}</th><td>${Z}</td></tr>`)}</table>
|
|
3
|
+
<table class="peers"><tr><th>peer</th><th>next</th><th>match</th><th>vote granted</th><th>RPC due</th><th>heartbeat due</th></tr>
|
|
4
|
+
${Y.peers.map((X)=>R`<tr><td>${X.peer}</td><td>${X.next}</td><td>${X.match}</td><td>${X.granted?"yes":"no"}</td><td>${X.rpcDue}</td><td>${X.heartbeatDue}</td></tr>`)}</table>
|
|
5
|
+
<textarea rows="3" aria-label="request value" placeholder=${J?"request value (empty: v<n>)":"only the leader takes a request"} ?disabled=${!J} .value=${this.text} @input=${(X)=>{this.text=X.target.value}}></textarea>
|
|
6
|
+
<div class="row">${_Y.map(([X,Z])=>Q(X,Z))}</div>
|
|
7
|
+
${this.error?R`<p class="alert bad" role="alert">${this.error}</p>`:""}</div>`}}if(!customElements.get("raft-detail"))customElements.define("raft-detail",iY);var tJ={follower:"#8b949e",candidate:"#F5A524",leader:"#7EE787"},UY=40,pY=2*Math.PI;class aY extends dJ{static properties={target:{attribute:!1},status:{state:!0},now:{state:!0},open:{state:!0},menu:{state:!0},error:{state:!0}};static styles=[nJ,sJ`svg { cursor: pointer; width: 120px; height: 120px } dialog { color: inherit; background: Canvas; padding: 0 } .pad { padding: 1em } .menu { position: fixed; display: flex; flex-direction: column; background: Canvas; border: 1px solid currentColor; z-index: 10 } text { fill: currentColor; text-anchor: middle; font-size: 22px } .role { text-align: center; font-size: 12px; font-weight: 600 }`];n=0;close=(Y)=>{if(Y instanceof KeyboardEvent?Y.key==="Escape":!(Y.type==="contextmenu"&&Y.composedPath().includes(this)))this.menu=void 0};stop;watching;pace;frame=0;constructor(){super();this.now=0,this.open=!1}tick=()=>{let Y=this.shadowRoot?.querySelector("circle.arc");if(Y&&this.status)Y.setAttribute("stroke-dasharray",this.dash(this.status));this.frame=requestAnimationFrame(this.tick)};dash(Y){let J=this.pace,Q=pY*UY;return`${WY(Y,J?J.sim+(performance.now()-J.wall)*J.rate:this.now).arc*Q} ${Q}`}connectedCallback(){super.connectedCallback(),this.frame=requestAnimationFrame(this.tick),this.watch(),window.addEventListener("click",this.close),window.addEventListener("keydown",this.close),window.addEventListener("contextmenu",this.close)}disconnectedCallback(){super.disconnectedCallback(),cancelAnimationFrame(this.frame),window.removeEventListener("click",this.close),window.removeEventListener("keydown",this.close),window.removeEventListener("contextmenu",this.close),this.stop?.(),this.stop=this.watching=void 0}willUpdate(Y){if(Y.has("target"))this.watch()}watch(){let Y=this.target;if(!Y||!this.isConnected||this.watching===Y)return;this.stop?.(),this.watching=Y,this.status=void 0,this.now=0,this.pace=void 0;let J={status:!1,now:!1},Q=[];this.stop=()=>Q.forEach((X)=>X());try{let X=Y.app.runtime(Y.runtime);Q.push(X.subscribe(q.ops.changed,({output:Z})=>{J.status=!0,this.status=Z})),Q.push(X.subscribe(oY.ops.fired,({output:Z})=>{J.now=!0,this.now=Z.at,this.pace=KY(this.pace,Z.at,performance.now())})),Promise.all([X.get(q,{pod:Y.pod}).status(),X.get(oY).now()]).then(([Z,$])=>{if(this.watching!==Y)return;if(!J.status)this.status=Z;if(!J.now)this.now=$,this.pace=KY(this.pace,$,performance.now())},()=>{})}catch{}}updated(){let Y=this.shadowRoot?.querySelector("dialog");if(Y&&!Y.hasAttribute("open"))if(Y.showModal)Y.showModal();else Y.setAttribute("open","")}pick(Y){this.menu=void 0,jY(this.target,Y,`v${++this.n}`).then((J)=>{this.error=J})}menuItem=(Y,J)=>N`<button class="btn small" role="menuitem" type="button" ?disabled=${J==="request"&&this.status?.role!=="leader"} @click=${()=>this.pick(J)}>${Y}</button>`;render(){if(!this.status)return N``;let Y=WY(this.status,this.now),J=tJ[Y.role],Q=Y.peers.map((X,Z)=>{let $=pY*Z/Y.peers.length-Math.PI/2;return rJ`<circle class="dot ${X.state}" cx=${60+52*Math.cos($)} cy=${60+52*Math.sin($)} r="5" stroke=${J} stroke-opacity=${X.state==="idle"?0.2:1} fill=${X.state==="granted"?J:"none"}><title>${X.id}: ${X.state}</title></circle>`});return N`<svg viewBox="0 0 120 120" opacity=${Y.stopped?0.35:1} @click=${()=>{this.open=!0}} @contextmenu=${(X)=>{X.preventDefault(),this.error=void 0,this.menu={x:X.clientX,y:X.clientY}}}>
|
|
8
|
+
<circle cx="60" cy="60" r=${UY} fill="none" stroke=${J} stroke-opacity="0.25" stroke-width="6"/>
|
|
9
|
+
<circle class="arc" cx="60" cy="60" r=${UY} fill="none" stroke=${J} stroke-width="6" stroke-dasharray=${this.dash(this.status)} transform="rotate(-90 60 60)"/>
|
|
10
|
+
<text x="60" y="68">${Y.term}</text>${Q}</svg>
|
|
11
|
+
<div class="role">${Y.role}</div>
|
|
12
|
+
${this.menu?N`<div class="menu" role="menu" style="left: ${this.menu.x}px; top: ${this.menu.y}px">${_Y.map(([X,Z])=>this.menuItem(X,Z))}</div>`:""}
|
|
13
|
+
${this.error?N`<p class="alert bad" role="alert">${this.error}</p>`:""}
|
|
14
|
+
${this.open?N`<dialog @click=${(X)=>{if(X.target===X.currentTarget)this.open=!1}} @cancel=${()=>{this.open=!1}} @keydown=${(X)=>{if(X.key==="Escape")this.open=!1}}>
|
|
15
|
+
<div class="pad"><div class="row"><strong>${this.status.id}</strong><button class="btn small" type="button" aria-label="close" @click=${()=>{this.open=!1}}>✕</button></div>
|
|
16
|
+
<raft-detail .target=${this.target} .status=${this.status} .now=${this.now}></raft-detail></div></dialog>`:""}`}}if(!customElements.get("raft-node"))customElements.define("raft-node",aY);import{LitElement as eJ,css as YQ,html as qY}from"lit";import{base as JQ,kit as QQ}from"@pritzlaff/nano-elements";class dY extends eJ{static properties={target:{attribute:!1},model:{state:!0}};static styles=[JQ,QQ,YQ`table { border-collapse: collapse; font-size: 12px } td, th { padding: 2px 8px; text-align: left } .committed { color: var(--nano-good, #7EE787) } .head { margin: 0 0 4px; font-size: 12px }`];stop;watching;p;commit=0;connectedCallback(){super.connectedCallback(),this.watch()}disconnectedCallback(){super.disconnectedCallback(),this.stop?.(),this.stop=this.watching=void 0}willUpdate(Y){if(Y.has("target"))this.watch()}watch(){let Y=this.target;if(!Y||!this.isConnected||this.watching===Y)return;this.stop?.(),this.watching=Y,this.p=void 0,this.commit=0,this.model=void 0;let J=()=>{if(this.p)this.model=cY(this.p,this.commit)},Q={p:!1,commit:!1},X=[];this.stop=()=>X.forEach((Z)=>Z());try{let Z=Y.app.runtime(Y.runtime);X.push(Z.subscribe(D.ops.written,({output:$})=>{Q.p=!0,this.p=$,J()})),X.push(Z.subscribe(q.ops.changed,({output:$})=>{Q.commit=!0,this.commit=$.commitIndex,J()})),Promise.all([Z.get(D,{pod:Y.pod}).read(),Z.get(q).status()]).then(([$,_])=>{if(this.watching!==Y)return;if(!Q.p)this.p=$;if(!Q.commit)this.commit=_.commitIndex;J()},()=>{})}catch{}}render(){let Y=this.model;if(!Y)return qY``;return qY`<p class="head">currentTerm <b>${Y.currentTerm}</b> · votedFor <b>${Y.votedFor??"—"}</b></p>
|
|
17
|
+
<table><tr><th>index</th><th>term</th><th>value</th><th>at</th></tr>
|
|
18
|
+
${Y.rows.map((J)=>qY`<tr class=${J.committed?"committed":""}><td>${J.index}</td><td>${J.term}</td><td>${J.value}</td><td>${J.at}</td></tr>`)}</table>`}}if(!customElements.get("raft-ledger"))customElements.define("raft-ledger",dY);import{LitElement as ZQ,css as $Q,html as d}from"lit";import{base as BQ,kit as WQ}from"@pritzlaff/nano-elements";import{LitElement as sY,css as rY,html as M}from"lit";import{base as nY,kit as XQ}from"@pritzlaff/nano-elements";class tY extends sY{static properties={target:{attribute:!1},ids:{attribute:!1}};static styles=[nY,rY`.ring { position: relative; width: 420px; height: 420px; margin: 8px 0 } .at { position: absolute; margin: -60px 0 0 -60px; text-align: center; font-size: 12px }`];targets=[];constructor(){super();this.ids=[]}willUpdate(Y){let J=this.target;if(J&&(Y.has("target")||Y.has("ids")))this.targets=this.ids.map((Q)=>({...J,runtime:Q,pod:`${Q}-raft`}))}render(){let Y=this.ids.length;return M`<div class="ring">${this.ids.map((J,Q)=>{let X=2*Math.PI*Q/Y-Math.PI/2;return M`<div class="at" style="left:${50+36*Math.cos(X)}%;top:${50+36*Math.sin(X)}%"><raft-node .target=${this.targets[Q]}></raft-node><div>${J}</div></div>`})}</div>`}}if(!customElements.get("raft-ring"))customElements.define("raft-ring",tY);class eY extends sY{static properties={target:{attribute:!1},ids:{attribute:!1},rows:{state:!0}};static styles=[nY,XQ,rY`table { border-collapse: collapse; font-size: 12px } td, th { padding: 2px 8px; border: 1px solid var(--nano-border, #8b949e55); text-align: center } .committed { color: var(--nano-good, #7EE787) }`];stop;watching;constructor(){super();this.ids=[],this.rows=[]}disconnectedCallback(){super.disconnectedCallback(),this.stop?.(),this.stop=this.watching=void 0}connectedCallback(){super.connectedCallback(),this.watch()}willUpdate(Y){if(Y.has("target")||Y.has("ids"))this.watch()}watch(){let Y=this.target,J=this.ids;if(this.watching?.t===Y&&this.watching?.ids===J&&this.isConnected)return;this.stop?.(),this.stop=void 0,this.watching={t:Y,ids:J};let Q=()=>this.ids===J&&this.target===Y;if(this.rows=[],!Y||!this.isConnected)return;let X=new Map,Z=[];this.stop=()=>Z.forEach((_)=>_());let $=()=>{this.rows=J.flatMap((_)=>{let W=X.get(_);return W?.p?[{id:_,p:W.p,commitIndex:W.commitIndex}]:[]})};for(let _ of J){let W={commitIndex:0},F={p:!1,c:!1};X.set(_,W);try{let j=Y.app.runtime(_);Z.push(j.subscribe(D.ops.written,({output:U})=>{F.p=!0,W.p=U,$()})),Z.push(j.subscribe(q.ops.changed,({output:U})=>{F.c=!0,W.commitIndex=U.commitIndex,$()})),Promise.all([j.get(D,{pod:`${_}-ledger`}).read(),j.get(q).status()]).then(([U,A])=>{if(!Q())return;if(!F.p)W.p=U;if(!F.c)W.commitIndex=A.commitIndex;$()},()=>{})}catch{}}}render(){if(!this.rows.length)return M``;let Y=lY(this.rows);return M`<table><tr><th></th>${Array.from({length:Y.columns},(J,Q)=>M`<th>${Q+1}</th>`)}</tr>
|
|
19
|
+
${Y.rows.map((J)=>M`<tr><th>${J.id}</th>${J.cells.map((Q)=>M`<td class=${Q?.committed?"committed":""}>${Q?.term??""}</td>`)}</tr>`)}</table>`}}if(!customElements.get("raft-log"))customElements.define("raft-log",eY);class YJ extends ZQ{static properties={target:{attribute:!1},names:{state:!0},chosen:{state:!0},ids:{state:!0},error:{state:!0}};static styles=[BQ,WQ,$Q`ul { list-style: none; margin: 0; padding: 0 } label { display: inline-flex; align-items: center; gap: .35em; font-size: .85em; color: var(--nano-muted, inherit) }`];loaded;loadedFor;stop;watching;constructor(){super();this.names=[],this.ids=[]}connectedCallback(){super.connectedCallback(),this.watch()}disconnectedCallback(){super.disconnectedCallback(),this.stop?.(),this.stop=this.watching=void 0}willUpdate(Y){if(Y.has("target"))this.watch();this.draw()}get shown(){return this.chosen!==void 0&&this.names.includes(this.chosen)?this.chosen:this.names[0]}draw(){let Y=this.target,J=this.shown,Q=Y&&J!==void 0?`${J}`:void 0;if(this.loaded===Q&&this.loadedFor===Y)return;if(this.loaded=Q,this.loadedFor=Y,this.ids=[],!Y||!J)return;try{Y.app.runtime(`${J}-1`).get(q,{pod:`${J}-1-raft`}).status().then((X)=>{if(this.loaded===Q&&this.loadedFor===Y)this.ids=[X.id,...X.peers].sort()},()=>{if(this.loadedFor===Y)this.loaded=void 0})}catch{}}pod(Y){return Y.app.runtime(Y.runtime).get(T,{pod:Y.pod})}watch(){let Y=this.target;if(!Y||!this.isConnected||this.watching===Y)return;this.stop?.(),this.watching=Y,this.stop=void 0;try{this.pod(Y).list().then((J)=>{this.names=J},()=>{})}catch{}}async run(Y,J){this.error=void 0;try{await Y(),await this.pod(this.target).list().then((Q)=>{this.names=Q}),J()}catch(Q){this.error=Q.fail?.reason??String(Q)}}field=(Y)=>this.renderRoot.querySelector(`[name=${Y}]`).value;render(){let Y=this.target;if(!Y)return d``;return d`<div class="col"><div class="row">
|
|
20
|
+
<label>cluster <input class="input" name="name" placeholder="name" value="example"></label>
|
|
21
|
+
<label>nodes <select class="input" name="size"><option>3</option><option>5</option></select></label>
|
|
22
|
+
<label title="seeds the election timeouts: the same seed replays the same election">seed <input class="input" name="seed" type="number" value="1"></label>
|
|
23
|
+
<label>heartbeat ms <input class="input" name="heartbeat" type="number" value="1000"></label>
|
|
24
|
+
<button class="btn" name="create" type="button" @click=${()=>void this.run(()=>this.pod(Y).create({name:this.field("name"),size:Number(this.field("size")),seed:Number(this.field("seed")),heartbeatMs:Number(this.field("heartbeat"))}),()=>{this.chosen=this.field("name")})}>Create</button>
|
|
25
|
+
<button class="btn" name="remove" type="button" @click=${()=>void this.run(()=>this.pod(Y).remove({name:this.field("name")}),()=>{if(this.chosen===this.field("name"))this.chosen=void 0})}>Remove</button></div>
|
|
26
|
+
${this.error?d`<p class="alert bad" role="alert">${this.error}</p>`:""}
|
|
27
|
+
<ul>${this.names.map((J)=>d`<li><button class="btn" type="button" aria-pressed=${J===this.shown} @click=${()=>{this.chosen=J,this.renderRoot.querySelector("[name=name]").value=J}}>${J}</button></li>`)}</ul>
|
|
28
|
+
<raft-ring .target=${Y} .ids=${this.ids}></raft-ring><raft-log .target=${Y} .ids=${this.ids}></raft-log></div>`}}if(!customElements.get("raft-cluster"))customElements.define("raft-cluster",YJ);var vX=KQ.namespace("example.raft").provider([hY,o,m,yY]),bX={"example.raft/node":"raft-node","example.raft/ledger":"raft-ledger","example.raft/cluster":"raft-cluster"};export{bX as views,vX as default};
|
|
29
|
+
|
|
30
|
+
export const built = {"@pritzlaff/nano-core":"0.5.1"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
{
|
|
2
|
+
"pods": {
|
|
3
|
+
"cluster": {
|
|
4
|
+
"implementation": "example.raft/cluster",
|
|
5
|
+
"config": {
|
|
6
|
+
"timing": {
|
|
7
|
+
"electionMin": 3000,
|
|
8
|
+
"electionMax": 6000,
|
|
9
|
+
"heartbeat": 1000
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"eager": false
|
|
13
|
+
},
|
|
14
|
+
"raft-messaging": {
|
|
15
|
+
"implementation": "example.raft/messaging",
|
|
16
|
+
"config": {
|
|
17
|
+
"minMs": 200,
|
|
18
|
+
"maxMs": 600
|
|
19
|
+
},
|
|
20
|
+
"eager": true
|
|
21
|
+
},
|
|
22
|
+
"raft-clock": {
|
|
23
|
+
"implementation": "nano.ui/sim-clock",
|
|
24
|
+
"eager": true
|
|
25
|
+
},
|
|
26
|
+
"raft-random": {
|
|
27
|
+
"implementation": "nano.ui/seeded-random",
|
|
28
|
+
"config": {
|
|
29
|
+
"seed": 1
|
|
30
|
+
},
|
|
31
|
+
"eager": true
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"runtimes": {
|
|
35
|
+
"raft": {
|
|
36
|
+
"pods": [
|
|
37
|
+
"cluster",
|
|
38
|
+
"raft-messaging",
|
|
39
|
+
"raft-clock",
|
|
40
|
+
"raft-random"
|
|
41
|
+
],
|
|
42
|
+
"subscriptions": [
|
|
43
|
+
{
|
|
44
|
+
"kind": "call",
|
|
45
|
+
"from": "raft-messaging",
|
|
46
|
+
"to": "raft-clock"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
"kind": "call",
|
|
50
|
+
"from": "raft-messaging",
|
|
51
|
+
"to": "raft-random"
|
|
52
|
+
}
|
|
53
|
+
]
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
"modules": {
|
|
57
|
+
"example.raft": "./example.raft.js"
|
|
58
|
+
},
|
|
59
|
+
"layout": {
|
|
60
|
+
"slots": [
|
|
61
|
+
{
|
|
62
|
+
"id": "cluster",
|
|
63
|
+
"runtime": "raft",
|
|
64
|
+
"pod": "cluster"
|
|
65
|
+
}
|
|
66
|
+
],
|
|
67
|
+
"ring": {
|
|
68
|
+
"show": [
|
|
69
|
+
"example.raft/node",
|
|
70
|
+
"example.raft/messaging"
|
|
71
|
+
]
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
{
|
|
2
|
+
"pods": {
|
|
3
|
+
"in": {
|
|
4
|
+
"implementation": "nano.ui/input",
|
|
5
|
+
"eager": true
|
|
6
|
+
},
|
|
7
|
+
"wait": {
|
|
8
|
+
"implementation": "nano.ui/debounce",
|
|
9
|
+
"config": {
|
|
10
|
+
"quietMs": 10
|
|
11
|
+
},
|
|
12
|
+
"eager": true
|
|
13
|
+
},
|
|
14
|
+
"up": {
|
|
15
|
+
"implementation": "nano.ui/map",
|
|
16
|
+
"config": {
|
|
17
|
+
"code": "return String(x).toUpperCase()"
|
|
18
|
+
},
|
|
19
|
+
"eager": false
|
|
20
|
+
},
|
|
21
|
+
"out": {
|
|
22
|
+
"implementation": "nano.ui/log",
|
|
23
|
+
"eager": false
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"runtimes": {
|
|
27
|
+
"main": {
|
|
28
|
+
"pods": [
|
|
29
|
+
"in",
|
|
30
|
+
"wait",
|
|
31
|
+
"up",
|
|
32
|
+
"out"
|
|
33
|
+
],
|
|
34
|
+
"subscriptions": [
|
|
35
|
+
{
|
|
36
|
+
"kind": "pipe",
|
|
37
|
+
"from": "in",
|
|
38
|
+
"source": "nano.ui.Input/submit",
|
|
39
|
+
"to": "wait",
|
|
40
|
+
"target": "nano.ui.Debounce/push"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"kind": "pipe",
|
|
44
|
+
"from": "wait",
|
|
45
|
+
"source": "nano.ui.Debounce/flushed",
|
|
46
|
+
"to": "up",
|
|
47
|
+
"target": "nano.ui.Map/map"
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"kind": "pipe",
|
|
51
|
+
"from": "up",
|
|
52
|
+
"source": "nano.ui.Map/map",
|
|
53
|
+
"to": "out",
|
|
54
|
+
"target": "nano.ui.Log/log"
|
|
55
|
+
}
|
|
56
|
+
]
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
"modules": {
|
|
60
|
+
"nano.ui": "../../bundle/nano-ui.js",
|
|
61
|
+
"example.slice": "./shout.js"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// ../../examples/slice/shout.ts
|
|
2
|
+
import { Coord, Implementation, provide, success } from "@pritzlaff/nano-core";
|
|
3
|
+
import { MapIface } from "@pritzlaff/nano-ui";
|
|
4
|
+
var ns = Coord.namespace("example.slice");
|
|
5
|
+
var shout = Implementation.define(ns.implementationId("shout"), {
|
|
6
|
+
provides: [MapIface],
|
|
7
|
+
make: () => [provide(MapIface, { map: async (x) => success(`${x}!`) })]
|
|
8
|
+
});
|
|
9
|
+
var shout_default = ns.provider([shout]);
|
|
10
|
+
var views = { "example.slice/shout": "nano-map" };
|
|
11
|
+
export {
|
|
12
|
+
views,
|
|
13
|
+
shout_default as default
|
|
14
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import{Nano as f}from"@pritzlaff/nano-core";import{Nano as w}from"@pritzlaff/nano-core";import{Type as J}from"typebox";import{Schema as G}from"@pritzlaff/nano-core";var W=J.Union([J.Literal("+"),J.Literal("-"),J.Literal("*"),J.Literal("/")]),V=G.define(J.Object({a:J.Number(),op:W,b:J.Number()}),"Sum"),Q=G.define(J.Object({a:J.Number(),op:W,b:J.Number(),result:J.Number()}),"Calculated"),z=G.define(J.Union([J.Object({precision:J.Integer({minimum:0,maximum:100})}),J.Undefined()]),"Precision");var v=(q)=>Object.assign(Error(q),{fail:{type:"invalid-input",reason:q}}),E=({a:q,op:D,b:I},{config:U})=>{if(D==="/"&&I===0)throw v("division by zero");let j=D==="+"?q+I:D==="-"?q-I:D==="*"?q*I:q/I;return{a:q,op:D,b:I,result:Number(j.toFixed(U?.precision??6))}},Z=w.create("acme.template.Calculator").config(z,{precision:6}).emit("calculated",Q).action("evaluate",V,Q,E).action("calculate",V,Q,async(q,D)=>{let I=E(q,D);return await D.publish("calculated",I),I});import{Type as X}from"typebox";import{Nano as b}from"@pritzlaff/nano-core";var C="acme.template:history",T=()=>{try{return globalThis.localStorage??void 0}catch{return}},_=b.create("acme.template.History").state(()=>({ls:T(),memory:[]})).action("save",Q,X.Null(),(q,{state:D})=>{let I=[...k(D),q];if(D.ls)D.ls.setItem(C,JSON.stringify(I));else D.memory=I;return null}).action("load",X.Null(),X.Array(Q),(q,{state:D})=>k(D));function k(q){return q.ls?JSON.parse(q.ls.getItem(C)??"[]"):q.memory}var H=f.app("acme.template").use({calculator:Z,history:_}).subscribe(Z.events.calculated.andThen(_.actions.save));import{LitElement as m,html as A}from"lit";import{base as y,kit as u}from"@pritzlaff/nano-elements";var g=["+","-","*","/"],K=(q)=>q.fail?.reason??(q instanceof Error?q.message:String(q));class L extends m{static properties={calc:{attribute:!1},history:{attribute:!1},a:{state:!0},op:{state:!0},b:{state:!0},result:{state:!0},error:{state:!0},saved:{state:!0}};static styles=[y,u];constructor(){super();this.a=this.b="",this.op="+",this.saved=[]}iter;connectedCallback(){if(super.connectedCallback(),this.calc&&!this.iter)this.listen()}disconnectedCallback(){super.disconnectedCallback(),this.end()}willUpdate(q){if(q.has("calc")||q.has("history"))this.listen()}end(){this.iter?.return?.(),this.iter=void 0}async listen(){if(this.end(),!this.calc||!this.isConnected)return;this.load();let q=this.iter=this.calc.calculated()[Symbol.asyncIterator]();try{while(!(await q.next()).done&&this.iter===q)await this.load()}catch{}}async load(){try{this.saved=this.history?await this.history.load():[]}catch{this.saved=[]}}async equals(){if(!this.calc)return;try{this.result=(await this.calc.calculate({a:Number(this.a),op:this.op,b:Number(this.b)})).result,this.error=void 0}catch(q){this.result=void 0,this.error=K(q)}}render(){let q=(D)=>{if(D.key==="Enter")this.equals()};return A`<div class="row">
|
|
2
|
+
<input class="input" type="number" aria-label="a" .value=${this.a} @input=${(D)=>{this.a=D.target.value}} @keydown=${q}>
|
|
3
|
+
<select class="input" aria-label="operator" .value=${this.op} @change=${(D)=>{this.op=D.target.value}}>
|
|
4
|
+
${g.map((D)=>A`<option value=${D} ?selected=${D===this.op}>${D}</option>`)}</select>
|
|
5
|
+
<input class="input" type="number" aria-label="b" .value=${this.b} @input=${(D)=>{this.b=D.target.value}} @keydown=${q}>
|
|
6
|
+
<button class="btn" aria-label="equals" @click=${()=>this.equals()}>=</button>
|
|
7
|
+
<output class="badge accent" aria-label="result">${this.result??""}</output></div>
|
|
8
|
+
${this.error?A`<p class="alert bad" role="alert">${this.error}</p>`:""}
|
|
9
|
+
<ol aria-label="history">${this.saved.map((D)=>A`<li>${D.a} ${D.op} ${D.b} = ${D.result}</li>`)}</ol>`}}import{LitElement as d,css as h,html as Y,svg as p}from"lit";import{base as i,kit as c,t as x,tv as B}from"@pritzlaff/nano-elements";var r=[...Array(21)].map((q,D)=>D-10),n=["+","-","*","/"],$=200,R=120;class N extends d{static properties={calc:{attribute:!1},op:{state:!0},b:{state:!0},points:{state:!0},error:{state:!0}};static styles=[i,c,h`svg { width: 100%; max-width: 480px; background: ${x("surface")}; border-radius: ${x("radius")} }`];constructor(){super();this.op="+",this.b="1",this.points=[]}run=0;willUpdate(q){if(q.has("calc")||q.has("op")||q.has("b"))this.plot()}async plot(){let q=this.calc,D=++this.run,I=this.op,U=Number(this.b);if(!q)return;let j=await Promise.all(r.map((M)=>q.evaluate({a:M,op:I,b:U}).then((F)=>[M,F.result],(F)=>F)));if(D!==this.run)return;let O=j.filter((M)=>Array.isArray(M)&&Number.isFinite(M[1]));this.points=O,this.error=O.length?void 0:K(j.find((M)=>!Array.isArray(M))??"no points")}line(){let q=Math.max(1,...this.points.map(([,I])=>Math.abs(I))),D=([I,U])=>`${(I+10)/20*$},${R/2-U/q*(R/2-4)}`;return p`<polyline points=${this.points.map(D).join(" ")} fill="none" stroke=${B("accent")} stroke-width="2"/>`}render(){return Y`<div class="row">
|
|
10
|
+
<span>y = x</span>
|
|
11
|
+
<select class="input" aria-label="operator" .value=${this.op} @change=${(q)=>{this.op=q.target.value}}>
|
|
12
|
+
${n.map((q)=>Y`<option value=${q} ?selected=${q===this.op}>${q}</option>`)}</select>
|
|
13
|
+
<input class="input" type="number" aria-label="b" .value=${this.b} @input=${(q)=>{this.b=q.target.value}}></div>
|
|
14
|
+
${this.error?Y`<p class="alert bad" role="alert">${this.error}</p>`:""}
|
|
15
|
+
<svg aria-label="graph" viewBox="0 0 ${$} ${R}">
|
|
16
|
+
<line x1="0" y1=${R/2} x2=${$} y2=${R/2} stroke=${B("border")}/><line x1=${$/2} y1="0" x2=${$/2} y2=${R} stroke=${B("border")}/>
|
|
17
|
+
${this.points.length?this.line():""}
|
|
18
|
+
</svg>`}}var S=(q)=>{try{return q()}catch{return}};function P(q){return class extends q{#q;get target(){return this.#q}set target(D){if(this.#q=D,!D)return;let I=D.app.runtime(D.runtime);if(this.calc=S(()=>I.get(Z.interface,{pod:D.pod})),"history"in this)this.history=S(()=>I.get(_.interface))}}}var Oq=H.provider,Wq={"acme.template/calculator":["nano-calculator","nano-graph-calculator"]};if(!customElements.get("nano-calculator"))customElements.define("nano-calculator",P(L));if(!customElements.get("nano-graph-calculator"))customElements.define("nano-graph-calculator",P(N));export{Wq as views,Oq as default};
|
|
19
|
+
|
|
20
|
+
export const built = {"@pritzlaff/nano-core":"0.5.1"}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// ../../templates/nano-template/src/app.ts
|
|
2
|
+
import { Nano as Nano3 } from "@pritzlaff/nano-core";
|
|
3
|
+
|
|
4
|
+
// ../../templates/nano-template/src/calculator.ts
|
|
5
|
+
import { Nano } from "@pritzlaff/nano-core";
|
|
6
|
+
|
|
7
|
+
// ../../templates/nano-template/src/schemas.ts
|
|
8
|
+
import { Type } from "typebox";
|
|
9
|
+
import { Schema } from "@pritzlaff/nano-core";
|
|
10
|
+
var Operator = Type.Union([Type.Literal("+"), Type.Literal("-"), Type.Literal("*"), Type.Literal("/")]);
|
|
11
|
+
var Sum = Schema.define(Type.Object({ a: Type.Number(), op: Operator, b: Type.Number() }), "Sum");
|
|
12
|
+
var Calculated = Schema.define(Type.Object({ a: Type.Number(), op: Operator, b: Type.Number(), result: Type.Number() }), "Calculated");
|
|
13
|
+
var Precision = Schema.define(Type.Union([Type.Object({ precision: Type.Integer({ minimum: 0, maximum: 100 }) }), Type.Undefined()]), "Precision");
|
|
14
|
+
|
|
15
|
+
// ../../templates/nano-template/src/calculator.ts
|
|
16
|
+
var invalid = (reason) => Object.assign(new Error(reason), { fail: { type: "invalid-input", reason } });
|
|
17
|
+
var evaluate = ({ a, op, b }, { config }) => {
|
|
18
|
+
if (op === "/" && b === 0)
|
|
19
|
+
throw invalid("division by zero");
|
|
20
|
+
const result = op === "+" ? a + b : op === "-" ? a - b : op === "*" ? a * b : a / b;
|
|
21
|
+
return { a, op, b, result: Number(result.toFixed(config?.precision ?? 6)) };
|
|
22
|
+
};
|
|
23
|
+
var calculator = Nano.create("acme.template.Calculator").config(Precision, { precision: 6 }).emit("calculated", Calculated).action("evaluate", Sum, Calculated, evaluate).action("calculate", Sum, Calculated, async (sum, ctx) => {
|
|
24
|
+
const done = evaluate(sum, ctx);
|
|
25
|
+
await ctx.publish("calculated", done);
|
|
26
|
+
return done;
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
// ../../templates/nano-template/src/history.ts
|
|
30
|
+
import { Type as Type2 } from "typebox";
|
|
31
|
+
import { Nano as Nano2 } from "@pritzlaff/nano-core";
|
|
32
|
+
var KEY = "acme.template:history";
|
|
33
|
+
var local = () => {
|
|
34
|
+
try {
|
|
35
|
+
return globalThis.localStorage ?? undefined;
|
|
36
|
+
} catch {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
var history = Nano2.create("acme.template.History").state(() => ({ ls: local(), memory: [] })).action("save", Calculated, Type2.Null(), (c, { state }) => {
|
|
41
|
+
const all = [...load(state), c];
|
|
42
|
+
if (state.ls)
|
|
43
|
+
state.ls.setItem(KEY, JSON.stringify(all));
|
|
44
|
+
else
|
|
45
|
+
state.memory = all;
|
|
46
|
+
return null;
|
|
47
|
+
}).action("load", Type2.Null(), Type2.Array(Calculated), (_, { state }) => load(state));
|
|
48
|
+
function load(s) {
|
|
49
|
+
return s.ls ? JSON.parse(s.ls.getItem(KEY) ?? "[]") : s.memory;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ../../templates/nano-template/src/app.ts
|
|
53
|
+
var app = Nano3.app("acme.template").use({ calculator, history }).subscribe(calculator.events.calculated.andThen(history.actions.save));
|
|
54
|
+
|
|
55
|
+
// ../../templates/nano-template/src/basic-calculator.ts
|
|
56
|
+
import { LitElement, html } from "lit";
|
|
57
|
+
import { base, kit } from "@pritzlaff/nano-elements";
|
|
58
|
+
var OPS = ["+", "-", "*", "/"];
|
|
59
|
+
var reason = (e) => e.fail?.reason ?? (e instanceof Error ? e.message : String(e));
|
|
60
|
+
|
|
61
|
+
class BasicCalculator extends LitElement {
|
|
62
|
+
static properties = {
|
|
63
|
+
calc: { attribute: false },
|
|
64
|
+
history: { attribute: false },
|
|
65
|
+
a: { state: true },
|
|
66
|
+
op: { state: true },
|
|
67
|
+
b: { state: true },
|
|
68
|
+
result: { state: true },
|
|
69
|
+
error: { state: true },
|
|
70
|
+
saved: { state: true }
|
|
71
|
+
};
|
|
72
|
+
static styles = [base, kit];
|
|
73
|
+
constructor() {
|
|
74
|
+
super();
|
|
75
|
+
this.a = this.b = "";
|
|
76
|
+
this.op = "+";
|
|
77
|
+
this.saved = [];
|
|
78
|
+
}
|
|
79
|
+
iter;
|
|
80
|
+
connectedCallback() {
|
|
81
|
+
super.connectedCallback();
|
|
82
|
+
if (this.calc && !this.iter)
|
|
83
|
+
this.listen();
|
|
84
|
+
}
|
|
85
|
+
disconnectedCallback() {
|
|
86
|
+
super.disconnectedCallback();
|
|
87
|
+
this.end();
|
|
88
|
+
}
|
|
89
|
+
willUpdate(changed) {
|
|
90
|
+
if (changed.has("calc") || changed.has("history"))
|
|
91
|
+
this.listen();
|
|
92
|
+
}
|
|
93
|
+
end() {
|
|
94
|
+
this.iter?.return?.();
|
|
95
|
+
this.iter = undefined;
|
|
96
|
+
}
|
|
97
|
+
async listen() {
|
|
98
|
+
this.end();
|
|
99
|
+
if (!this.calc || !this.isConnected)
|
|
100
|
+
return;
|
|
101
|
+
this.load();
|
|
102
|
+
const it = this.iter = this.calc.calculated()[Symbol.asyncIterator]();
|
|
103
|
+
try {
|
|
104
|
+
while (!(await it.next()).done && this.iter === it)
|
|
105
|
+
await this.load();
|
|
106
|
+
} catch {}
|
|
107
|
+
}
|
|
108
|
+
async load() {
|
|
109
|
+
try {
|
|
110
|
+
this.saved = this.history ? await this.history.load() : [];
|
|
111
|
+
} catch {
|
|
112
|
+
this.saved = [];
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async equals() {
|
|
116
|
+
if (!this.calc)
|
|
117
|
+
return;
|
|
118
|
+
try {
|
|
119
|
+
this.result = (await this.calc.calculate({ a: Number(this.a), op: this.op, b: Number(this.b) })).result;
|
|
120
|
+
this.error = undefined;
|
|
121
|
+
} catch (e) {
|
|
122
|
+
this.result = undefined;
|
|
123
|
+
this.error = reason(e);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
render() {
|
|
127
|
+
const enter = (e) => {
|
|
128
|
+
if (e.key === "Enter")
|
|
129
|
+
this.equals();
|
|
130
|
+
};
|
|
131
|
+
return html`<div class="row">
|
|
132
|
+
<input class="input" type="number" aria-label="a" .value=${this.a} @input=${(e) => {
|
|
133
|
+
this.a = e.target.value;
|
|
134
|
+
}} @keydown=${enter}>
|
|
135
|
+
<select class="input" aria-label="operator" .value=${this.op} @change=${(e) => {
|
|
136
|
+
this.op = e.target.value;
|
|
137
|
+
}}>
|
|
138
|
+
${OPS.map((o) => html`<option value=${o} ?selected=${o === this.op}>${o}</option>`)}</select>
|
|
139
|
+
<input class="input" type="number" aria-label="b" .value=${this.b} @input=${(e) => {
|
|
140
|
+
this.b = e.target.value;
|
|
141
|
+
}} @keydown=${enter}>
|
|
142
|
+
<button class="btn" aria-label="equals" @click=${() => this.equals()}>=</button>
|
|
143
|
+
<output class="badge accent" aria-label="result">${this.result ?? ""}</output></div>
|
|
144
|
+
${this.error ? html`<p class="alert bad" role="alert">${this.error}</p>` : ""}
|
|
145
|
+
<ol aria-label="history">${this.saved.map((s) => html`<li>${s.a} ${s.op} ${s.b} = ${s.result}</li>`)}</ol>`;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// ../../templates/nano-template/src/graph-calculator.ts
|
|
150
|
+
import { LitElement as LitElement2, css, html as html2, svg } from "lit";
|
|
151
|
+
import { base as base2, kit as kit2, t, tv } from "@pritzlaff/nano-elements";
|
|
152
|
+
var XS = [...Array(21)].map((_, i) => i - 10);
|
|
153
|
+
var OPS2 = ["+", "-", "*", "/"];
|
|
154
|
+
var W = 200;
|
|
155
|
+
var H = 120;
|
|
156
|
+
|
|
157
|
+
class GraphCalculator extends LitElement2 {
|
|
158
|
+
static properties = { calc: { attribute: false }, op: { state: true }, b: { state: true }, points: { state: true }, error: { state: true } };
|
|
159
|
+
static styles = [base2, kit2, css`svg { width: 100%; max-width: 480px; background: ${t("surface")}; border-radius: ${t("radius")} }`];
|
|
160
|
+
constructor() {
|
|
161
|
+
super();
|
|
162
|
+
this.op = "+";
|
|
163
|
+
this.b = "1";
|
|
164
|
+
this.points = [];
|
|
165
|
+
}
|
|
166
|
+
run = 0;
|
|
167
|
+
willUpdate(changed) {
|
|
168
|
+
if (changed.has("calc") || changed.has("op") || changed.has("b"))
|
|
169
|
+
this.plot();
|
|
170
|
+
}
|
|
171
|
+
async plot() {
|
|
172
|
+
const calc = this.calc, run = ++this.run, op = this.op, b = Number(this.b);
|
|
173
|
+
if (!calc)
|
|
174
|
+
return;
|
|
175
|
+
const got = await Promise.all(XS.map((a) => calc.evaluate({ a, op, b }).then((r) => [a, r.result], (e) => e)));
|
|
176
|
+
if (run !== this.run)
|
|
177
|
+
return;
|
|
178
|
+
const ok = got.filter((g) => Array.isArray(g) && Number.isFinite(g[1]));
|
|
179
|
+
this.points = ok;
|
|
180
|
+
this.error = ok.length ? undefined : reason(got.find((g) => !Array.isArray(g)) ?? "no points");
|
|
181
|
+
}
|
|
182
|
+
line() {
|
|
183
|
+
const top = Math.max(1, ...this.points.map(([, y]) => Math.abs(y)));
|
|
184
|
+
const at = ([x, y]) => `${(x + 10) / 20 * W},${H / 2 - y / top * (H / 2 - 4)}`;
|
|
185
|
+
return svg`<polyline points=${this.points.map(at).join(" ")} fill="none" stroke=${tv("accent")} stroke-width="2"/>`;
|
|
186
|
+
}
|
|
187
|
+
render() {
|
|
188
|
+
return html2`<div class="row">
|
|
189
|
+
<span>y = x</span>
|
|
190
|
+
<select class="input" aria-label="operator" .value=${this.op} @change=${(e) => {
|
|
191
|
+
this.op = e.target.value;
|
|
192
|
+
}}>
|
|
193
|
+
${OPS2.map((o) => html2`<option value=${o} ?selected=${o === this.op}>${o}</option>`)}</select>
|
|
194
|
+
<input class="input" type="number" aria-label="b" .value=${this.b} @input=${(e) => {
|
|
195
|
+
this.b = e.target.value;
|
|
196
|
+
}}></div>
|
|
197
|
+
${this.error ? html2`<p class="alert bad" role="alert">${this.error}</p>` : ""}
|
|
198
|
+
<svg aria-label="graph" viewBox="0 0 ${W} ${H}">
|
|
199
|
+
<line x1="0" y1=${H / 2} x2=${W} y2=${H / 2} stroke=${tv("border")}/><line x1=${W / 2} y1="0" x2=${W / 2} y2=${H} stroke=${tv("border")}/>
|
|
200
|
+
${this.points.length ? this.line() : ""}
|
|
201
|
+
</svg>`;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ../../templates/nano-template/src/hosted.ts
|
|
206
|
+
var one = (get) => {
|
|
207
|
+
try {
|
|
208
|
+
return get();
|
|
209
|
+
} catch {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
function hosted(Base) {
|
|
214
|
+
return class extends Base {
|
|
215
|
+
#target;
|
|
216
|
+
get target() {
|
|
217
|
+
return this.#target;
|
|
218
|
+
}
|
|
219
|
+
set target(t2) {
|
|
220
|
+
this.#target = t2;
|
|
221
|
+
if (!t2)
|
|
222
|
+
return;
|
|
223
|
+
const at = t2.app.runtime(t2.runtime);
|
|
224
|
+
this.calc = one(() => at.get(calculator.interface, { pod: t2.pod }));
|
|
225
|
+
if ("history" in this)
|
|
226
|
+
this.history = one(() => at.get(history.interface));
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ../../templates/nano-template/src/index.ts
|
|
232
|
+
var src_default = app.provider;
|
|
233
|
+
var views = { "acme.template/calculator": ["nano-calculator", "nano-graph-calculator"] };
|
|
234
|
+
if (!customElements.get("nano-calculator"))
|
|
235
|
+
customElements.define("nano-calculator", hosted(BasicCalculator));
|
|
236
|
+
if (!customElements.get("nano-graph-calculator"))
|
|
237
|
+
customElements.define("nano-graph-calculator", hosted(GraphCalculator));
|
|
238
|
+
export {
|
|
239
|
+
views,
|
|
240
|
+
src_default as default
|
|
241
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"pods": {
|
|
3
|
+
"calculator": {
|
|
4
|
+
"implementation": "acme.template/calculator",
|
|
5
|
+
"config": {
|
|
6
|
+
"precision": 6
|
|
7
|
+
},
|
|
8
|
+
"eager": false
|
|
9
|
+
},
|
|
10
|
+
"history": {
|
|
11
|
+
"implementation": "acme.template/history",
|
|
12
|
+
"eager": false
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"runtimes": {
|
|
16
|
+
"main": {
|
|
17
|
+
"pods": [
|
|
18
|
+
"calculator",
|
|
19
|
+
"history"
|
|
20
|
+
],
|
|
21
|
+
"subscriptions": [
|
|
22
|
+
{
|
|
23
|
+
"kind": "pipe",
|
|
24
|
+
"from": "calculator",
|
|
25
|
+
"source": "acme.template.Calculator/calculated",
|
|
26
|
+
"to": "history",
|
|
27
|
+
"target": "acme.template.History/save"
|
|
28
|
+
}
|
|
29
|
+
]
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"modules": {
|
|
33
|
+
"acme.template": "./acme.template.js"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{LitElement as q,css as C,html as X}from"lit";import{base as E,kit as b}from"@pritzlaff/nano-elements";import{Type as H}from"typebox";import{Coord as k,Op as R,Schema as $}from"@pritzlaff/nano-core";var N;((J)=>(J.ns=k.namespace("example.todo"),J.Todo=$.define(H.Object({id:H.String(),title:H.String(),done:H.Boolean()})),J.Change=$.define(H.Object({id:H.String(),title:H.Optional(H.String()),done:H.Optional(H.Boolean())})),J.api=J.ns.interface("TodoList",{add:R.action(H.String(),J.Todo),list:R.action(H.Null(),H.Array(J.Todo)),update:R.action(J.Change,H.Union([J.Todo,H.Null()])),put:R.action(J.Todo,J.Todo),remove:R.action(H.String(),H.Boolean()),items:R.event(J.Todo)})))(N||={});class Z extends q{static properties={target:{attribute:!1},todos:{state:!0},error:{state:!0}};static styles=[E,b,C`ul { list-style: none; margin: 0; padding: 0 } li > span { flex: 1 } [role='alert'] { margin: 0 }`];watching;iter;constructor(){super();this.todos=[]}connectedCallback(){super.connectedCallback(),this.watch()}disconnectedCallback(){super.disconnectedCallback(),this.stop()}willUpdate(j){if(j.has("target"))this.watch()}stop(){this.iter?.return?.(),this.iter=this.watching=void 0}pod(j){return j.app.runtime(j.runtime).get(N.api,{pod:j.pod})}async watch(){let j=this.target;if(!j||!this.isConnected||this.watching===j)return;this.stop(),this.watching=j,this.error=void 0;let B=this.pod(j),w=this.iter=B.items()[Symbol.asyncIterator]();try{let A=await B.list();if(this.iter!==w)return;this.todos=A;while(!(await w.next()).done&&this.iter===w){let G=await B.list();if(this.iter===w)this.todos=G}}catch(A){if(this.iter===w)this.error=String(A)}}async add(j,B){let w=B.value.trim();if(!w)return;B.value="",await this.pod(j).add(w).catch((A)=>{this.error=String(A)})}run(j){j.catch((B)=>{this.error=String(B)})}render(){let j=this.target;if(!j)return X``;let B=this.pod(j);return X`<div class="col">${this.error?X`<p class="alert bad" role="alert">${this.error}</p>`:""}<div class="row">
|
|
2
|
+
<input class="input" aria-label="New todo" placeholder="What needs doing?" @keydown=${(w)=>{if(w.key==="Enter"&&!w.isComposing)this.add(j,w.target)}}><button class="btn" type="button" @click=${()=>void this.add(j,this.renderRoot.querySelector("input"))}>Add</button></div>
|
|
3
|
+
<ul>${this.todos.map((w)=>X`<li class="list-row">
|
|
4
|
+
<input type="checkbox" aria-label="Done: ${w.title}" .checked=${w.done} @change=${(A)=>this.run(B.update({id:w.id,done:A.target.checked}))}>
|
|
5
|
+
<span>${w.title}</span>
|
|
6
|
+
<button class="btn small" aria-label="Remove ${w.title}" @click=${()=>this.run(B.remove(w.id))}>×</button></li>`)}</ul></div>`}}import{Implementation as z}from"@pritzlaff/nano-core";import{Type as M}from"typebox";import{Coord as v,Op as Y,Schema as _}from"@pritzlaff/nano-core";var U;((F)=>(F.ns=v.namespace("example.kv"),F.Path=_.define(M.Array(M.String())),F.Value=_.define(M.Unsafe(M.Unknown())),F.Entry=_.define(M.Object({key:F.Path,value:F.Value})),F.api=F.ns.interface("KeyValueStore",{get:Y.action(F.Path,F.Value),put:Y.action(F.Entry,M.Null()),delete:Y.action(F.Path,M.Null()),list:Y.action(M.Object({prefix:F.Path}),M.Array(F.Entry))})))(U||={});var Q=U.api.ops,W=(j)=>["todos",j],I=0,P=()=>`${Date.now().toString(36).padStart(9,"0")}${(I++%1679616).toString(36).padStart(4,"0")}-${crypto.randomUUID().slice(0,8)}`;function g(j,B=P){return{async add(w){let A={id:B(),title:w,done:!1};return await j.put({key:W(A.id),value:A}),A},async list(){return(await j.list({prefix:["todos"]})).map((w)=>w.value)},async put(w){return await j.put({key:W(w.id),value:w}),w},async update(w){let A=await j.get(W(w.id));if(!A)return null;let G={...A,...w.title!==void 0&&{title:w.title},...w.done!==void 0&&{done:w.done}};return await j.put({key:W(w.id),value:G}),G},async remove(w){if(await j.get(W(w))===null)return!1;return await j.delete(W(w)),!0}}}var m=z.define(N.ns.implementationId("kv"),{provides:[N.api],description:"Todos kept in whichever KeyValueStore its call edge reaches.",dependencies:{store:U.api},calls:{add:{store:[Q.put]},list:{store:[Q.list]},put:{store:[Q.put]},update:{store:[Q.get,Q.put]},remove:{store:[Q.get,Q.delete]}},make:(j)=>{let B=setInterval(()=>{j.deps.store.list({prefix:["todos"]}).catch(()=>{})},1000);j.addOnCloseListener(()=>clearInterval(B));let w=(A)=>g(A.deps.store);return{add:(A,G)=>w(G).add(A),list:(A,G)=>w(G).list(),put:(A,G)=>w(G).put(A),update:(A,G)=>w(G).update(A),remove:(A,G)=>w(G).remove(A),async*items(){let A=j.one(U.api);if(A.ok){for await(let{input:G}of A.value.on(U.api.ops.put))if(G.key[0]==="todos")yield G.value}}}}}),L=N.ns.provider([m]);var p={"example.todo/kv":"todo-list"};if(!customElements.get("todo-list"))customElements.define("todo-list",Z);export{p as views,L as default};
|
|
7
|
+
|
|
8
|
+
export const built = {"@pritzlaff/nano-core":"0.5.1"}
|