@north-light/plugin 0.3.579 → 0.3.587
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/dist/serve.js +3 -3
- package/package.json +3 -3
package/dist/serve.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var ee=Object.defineProperty;var s=(n,e)=>ee(n,"name",{value:e,configurable:!0});import{approvalFor as ne}from"./approval.js";import{requestSpendCheck as te}from"./receipts.js";import{validateDeclaredResult as re,validateValue as ie}from"@north-light/api/command-manifest";import{errorResponse as A,LeafError as T,leafErrorResponse as L,storedAnswerHeaders as oe}from"./errors.js";import{buildCommandManifest as ae}from"./manifest.js";import{buildBundle as de}from"./bundle.js";import{parseCrtrCaller as se}from"./caller.js";import{createCallerVerifier as ce,normalizeProviderId as ue,scopeMissing as fe}from"./verify.js";const V=/^v([1-9][0-9]*)$/;function Oe(n,e={}){if(e.token!==void 0&&e.auth!==void 0)throw new Error("createFetchHandler takes either token or auth, not both");if(e.token!==void 0&&e.receipts!==void 0)throw new Error("createFetchHandler cannot meter with a static token");if(e.receipts!==void 0&&!/^app:[A-Za-z0-9_-]{1,64}$/.test(e.receipts.provider))throw new Error("createFetchHandler receipts.provider must be an app principal (app:<id>)");const i=e.auth===void 0?void 0:ue(e.auth),t=Array.isArray(n)||n.version!==void 0,r=me(Array.isArray(n)?n:[n],Array.isArray(n),i),d=r[0].plugin.name;for(const f of r)for(const b of f.commands.values())if(b.leaf.sideEffect&&e.requests===void 0)throw new Error(`createFetchHandler needs requests for side-effect leaf ${b.path.join(" ")}`);const c=e.auth===void 0?void 0:ce(e.auth);if(c!==void 0){for(const f of r)for(const b of f.commands.values())if(b.scope===void 0)throw new Error(`createFetchHandler auth needs a group on every leaf; ${b.path.join(" ")} has none`)}const o=new Map,y=e.baseUrl===void 0?void 0:D(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${d} is serving without bearer authentication`);const m=s(async(f,b,z)=>{const u=`${b.version}\0${z}`;let l=o.get(u);if(l===void 0){const I=await de(b.plugin,{mountPath:z,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:I.tar,etag:I.etag},o.set(u,l)}const p={ETag:l.etag};return f.headers.get("if-none-match")===l.etag?new Response(null,{status:304,headers:p}):new Response(new Uint8Array(l.tar).buffer,{headers:{...p,"Content-Type":"application/x-tar"}})},"archiveResponse");return async f=>{if(f.method!=="POST"&&e.token!==void 0&&!Y(f.headers.get("authorization")??"",`Bearer ${e.token}`))return A(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."});const b=new URL(f.url).pathname;if(f.method==="GET"){if(!t)return m(f,h,y??D(b));const w=J(b),j=w[w.length-1],R=y??D(`/${w.slice(0,-1).join("/")}`);if(j==="versions")return Response.json({latest:h.version,supported:r.map(v=>v.version)});const H=j===void 0?null:V.exec(j),k=H===null?void 0:r.find(v=>v.version===Number(H[1]));return k===void 0?P():m(f,k,`${R}/v${k.version}`)}if(f.method!=="POST")return P();const z=performance.now();let u,l;const p=[];let I=[],F=!1,B=!1;const E=s(w=>{if(l!==void 0)try{e.onAnswer?.({...u===void 0?{}:{sub:u.sub,grantee:u.grantee,initiatingApp:u.initiatingApp,act:u.act,jti:u.jti,requestId:u.requestId,...u.runId===void 0?{}:{runId:u.runId}},...u===void 0&&g!==null&&g!==""?{requestId:g}:{},tool:l.path.slice(1).join(" "),status:w.status,durationMs:performance.now()-z,...p.length===0?{}:{receiptId:p[0].receipt_id},...p.length>1?{receiptIds:p.map(j=>j.receipt_id)}:{},replayed:B})}catch{}return w},"answer");let g=f.headers.get("crtr-request-id");try{if(l=t?ge(r,b):we(h.commands,b),e.token!==void 0&&!Y(f.headers.get("authorization")??"",`Bearer ${e.token}`))return E(A(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."}));const w=c===void 0?void 0:await c(f);if(l===void 0)return P();if(w!==void 0&&!w.scope.includes(l.scope)){u=Object.freeze({...w,requestId:g??"",...f.headers.get("crtr-run-id")?{runId:f.headers.get("crtr-run-id")}:{}});const a=l.leaf.group,x=i===void 0&&a!==void 0?w.scope.find($=>$.endsWith(`:${a}`)&&$.length>a.length+1)?.slice(0,-(a.length+1)):void 0;throw fe(l.scope,x)}if(w!==void 0){if(g===null||g==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const a=f.headers.get("crtr-run-id"),x=se(f.headers.get("crtr-caller"));u=Object.freeze({...w,requestId:g,...a!==null&&a!==""?{runId:a}:{},...Object.keys(x).length>0?{crtr:Object.freeze(x)}:{}})}const j=await ye(f,l.manifest,w!==void 0);if(l.leaf.sideEffect){if(g===null||g==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const a=u===void 0?null:{sub:u.sub,grantee:u.grantee};if(!await e.requests.record(g,a)){B=!0;const $=await he(e.requests,g,a,l.plugin.timeouts?.requestMs??3e4);if($!==!0){const _=$.headers.get("Crtr-Receipt");if(_!==null)try{const C=JSON.parse(_);p.push(...Array.isArray(C)?C:[C])}catch{}return E($)}B=!1}F=!0}const R=l,H={request:f,...u!==void 0?{caller:u}:{},...g!==null&&g!==""?{causedBy:`request:${g}`}:{},approval:ne(f),meter(a){if(u===void 0)throw new Error("ctx.meter needs an authenticated caller");if(p.some(S=>S.unit===a.unit))throw new Error(`ctx.meter may be called only once for unit ${a.unit}`);if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const x=a.receiptId??u.requestId;if(p.some(S=>S.receipt_id===x))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${x} is taken`);const $=R.path.slice(1).join(" "),_=I.find(S=>S.mode==="unit"&&S.unit===a.unit),C=a.usdEquivalent??(_?.usd_per_unit!=null?a.units*_.usd_per_unit:0),G={receipt_id:x,provider:e.receipts.provider,tool:$,sub:u.sub,grantee:u.grantee,payer:u.payer,units:a.units,unit:a.unit,usd_equivalent:C,request_id:u.requestId,...u.runId!==void 0?{run_id:u.runId}:{},time:new Date().toISOString()};return p.push(G),G},async checkSpend(){if(u===void 0)throw new Error("ctx.checkSpend needs an authenticated caller");if(e.receipts===void 0)throw new Error("ctx.checkSpend needs receipts with a provider and outbox");if(e.receipts.ledger===void 0)throw new Error("ctx.checkSpend needs receipts.ledger (the provider's directory client credentials)");const a=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"")?.[1];if(a===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");return I=(await te(e.auth.issuer,a,R.path.slice(1).join(" "),e.receipts.ledger)).prices,{prices:I}}};let k,v;try{const a=await l.leaf.run(j,H);k=l.leaf.streaming?await xe(a,e.onError,l.path):Ee(a,l.manifest)}catch(a){a instanceof T?(k=L(a),v=a.headers):(N(e.onError,a,l.path),k=M(a))}if(F&&k.status===403&&await le(k))return await e.requests.delete(g),E(W(k,p));try{if(F)await e.requests.store(g,{status:k.status,body:await k.clone().text(),...v!==void 0?{headers:{...v}}:{},...p.length>0?{receipt:p[0]}:{},...p.length>1?{receipts:[...p]}:{}});else if(p.length>0){if(e.receipts===void 0)throw new Error(`No receipt outbox for ${R.path.join(" ")}`);for(const a of p)await e.receipts.outbox.save(a)}}catch(a){return N(e.onError,a,l.path,p),E(M(a))}return E(W(k,p))}catch(w){return w instanceof T?E(L(w)):(N(e.onError,w,l?.path??[]),E(M(w)))}}}s(Oe,"createFetchHandler");function M(n){return A(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(M,"handlerFailed");function W(n,e){if(e.length===0)return n;const i=new Headers(n.headers);return i.set("Crtr-Receipt",Z(e)),new Response(n.body,{status:n.status,headers:i})}s(W,"responseWithReceipts");function Z(n){return JSON.stringify(n.length===1?n[0]:n)}s(Z,"receiptHeader");async function le(n){try{const e=await n.clone().json();return U(e)&&U(e.error)&&e.error.code==="approval_required"}catch{return!1}}s(le,"isApprovalRequired");async function he(n,e,i,t){for(;;){const r=await n.read(e);if(r===null){if(await n.record(e,i))return!0;continue}if(r.identity?.sub!==i?.sub||r.identity?.grantee!==i?.grantee)return A(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const d=oe(r.answer.headers);d.set("Content-Type","application/json");const c=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return c.length>0&&d.set("Crtr-Receipt",Z(c)),new Response(r.answer.body,{status:r.answer.status,headers:d})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return M(new Error("The earlier request has no stored answer."));await new Promise(d=>setTimeout(d,Math.min(25,Math.max(1,new Date(r.recordedAt).getTime()+t-Date.now()))))}}s(he,"replay");function me(n,e,i){if(n.length===0)throw new Error("createFetchHandler needs at least one plugin definition");const t=n[0].name,r=new Map;for(const d of n){if(d.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${d.name}`);if(e&&d.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const c=d.version??1;if(r.has(c))throw new Error(`createFetchHandler got two definitions of ${t} major ${c}`);r.set(c,{version:c,plugin:d,commands:pe(d,i)})}return[...r.values()].sort((d,c)=>d.version-c.version)}s(me,"servedMajors");function pe(n,e){const t=ae(n,{mountPath:""}).mounts[0]?.node;if(t===void 0||t.kind!=="branch")throw new Error("Generated plugin manifest has no root branch");const r=new Map;return K(t.children,n.commands,[t.name],n,r,e),r}s(pe,"commandMap");function K(n,e,i,t,r,d){const c=Object.entries(e);if(n.length!==c.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[o,[y,h]]of c.entries()){const m=n[o];if(m===void 0||m.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${y}`);const f=[...i,m.name];if(m.kind==="branch"&&h.kind==="branch"){K(m.children,h.children,f,t,r,d);continue}if(m.kind==="leaf"&&h.kind==="leaf"){r.set(f.join("/"),{path:f,leaf:h,plugin:t,manifest:m,...h.group!==void 0?{scope:`${d??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${y}`)}}s(K,"collectCommands");function we(n,e){const i=J(e);for(let t=0;t<i.length;t+=1){const r=n.get(i.slice(t).join("/"));if(r!==void 0)return r}}s(we,"findCommand");function ge(n,e){const i=J(e);for(let t=i.length-2;t>=0;t-=1){const r=V.exec(i[t]);if(r===null)continue;const c=n.find(o=>o.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(c!==void 0)return c}}s(ge,"findVersionedCommand");function J(n){return n.split("/").filter(e=>e.length>0)}s(J,"pathSegments");async function ye(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const o=JSON.parse(t);if(!U(o))throw new Error("not an object");r=o}catch{throw q("Request body must be a JSON object.",i?"body":void 0,i,t)}const d=new Map(e.params.map(o=>[o.name,o]));for(const o of Object.keys(r))if(!d.has(o))throw i?q(`Unknown parameter ${o}.`,o,!0,r[o]):new T({code:"unknown_parameter",message:`Unknown parameter ${o}.`,field:o});const c={};for(const o of e.params){if(!Object.hasOwn(r,o.name)){if(o.required)throw q(`Missing required parameter ${o.name}.`,o.name,i,null);continue}const y=r[o.name];if(o.kind==="flag"&&o.type==="json"){const m=ie(o.shape,y,o.name);if(m!==null)throw q(`Invalid value for ${m.path}: expected ${m.expected}, got ${m.receivedType}.`,m.path,i,y);c[X(o.name)]=y;continue}const h=be(y,o);if(h===void 0)throw q(`Invalid value for parameter ${o.name}.`,o.name,i,y);c[X(o.name)]=h}return c}s(ye,"decodeInput");function be(n,e){if(e.kind!=="stdin"&&e.kind!=="context-file"&&e.repeatable){if(!Array.isArray(n))return;const i=n.map(t=>Q(t,e));return i.some(t=>t===void 0)?void 0:i}return Q(n,e)}s(be,"decodeParameter");function Q(n,e){if(e.kind==="stdin"||e.kind==="positional")return typeof n=="string"?n:void 0;if(e.kind!=="context-file"){if(e.type==="string")return typeof n=="string"?n:void 0;if(e.type==="int")return typeof n=="number"&&Number.isInteger(n)?n:void 0;if(e.type==="bool")return typeof n=="boolean"?n:void 0;if(e.type==="enum")return typeof n=="string"&&Array.isArray(e.choices)&&e.choices.includes(n)?n:void 0;if(e.type==="file")return typeof n=="string"?n:void 0;if(e.type==="path")return typeof n!="string"?void 0:e.encoding==="base64"?ke(n):n}}s(Q,"decodeScalar");function ke(n){if(!(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0))try{const e=atob(n);return Uint8Array.from(e,i=>i.charCodeAt(0))}catch{return}}s(ke,"decodeBase64");function Ee(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw O("result")}if(!U(t))throw O("result");const r=re(e.output,t);if(r!==null)throw O(r.field,r.receivedType);for(const d of Object.keys(t))if(!e.output.some(c=>c.name===d))throw O(d);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(Ee,"resultResponse");async function xe(n,e,i){if(!$e(n))throw O("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,d=await t.next();let c=d.done,o=c?void 0:r.encode(`${JSON.stringify(d.value)}
|
|
2
|
-
`);const
|
|
3
|
-
`))}catch(m){
|
|
1
|
+
var ee=Object.defineProperty;var s=(n,e)=>ee(n,"name",{value:e,configurable:!0});import{approvalFor as ne}from"./approval.js";import{requestSpendCheck as te}from"./receipts.js";import{validateDeclaredResult as re,validateValue as ie}from"@north-light/api/command-manifest";import{errorResponse as E,LeafError as T,leafErrorResponse as V,storedAnswerHeaders as oe}from"./errors.js";import{buildCommandManifest as de}from"./manifest.js";import{buildBundle as ae}from"./bundle.js";import{parseCrtrCaller as se}from"./caller.js";import{createCallerVerifier as ce,normalizeProviderId as ue,scopeMissing as fe}from"./verify.js";const P=/^v([1-9][0-9]*)$/;function Me(n,e={}){if(e.token!==void 0&&e.auth!==void 0)throw new Error("createFetchHandler takes either token or auth, not both");if(e.token!==void 0&&e.receipts!==void 0)throw new Error("createFetchHandler cannot meter with a static token");if(e.receipts!==void 0&&!/^app:[A-Za-z0-9_-]{1,64}$/.test(e.receipts.provider))throw new Error("createFetchHandler receipts.provider must be an app principal (app:<id>)");const i=e.auth===void 0?void 0:ue(e.auth),t=Array.isArray(n)||n.version!==void 0,r=me(Array.isArray(n)?n:[n],Array.isArray(n),i),a=r[0].plugin.name;for(const f of r)for(const y of f.commands.values())if(y.leaf.sideEffect&&e.requests===void 0)throw new Error(`createFetchHandler needs requests for side-effect leaf ${y.path.join(" ")}`);const c=e.auth===void 0?void 0:ce(e.auth);if(c!==void 0){for(const f of r)for(const y of f.commands.values())if(y.scope===void 0)throw new Error(`createFetchHandler auth needs a group on every leaf; ${y.path.join(" ")} has none`)}const d=new Map,b=e.baseUrl===void 0?void 0:G(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${a} is serving without bearer authentication`);const m=s(async(f,y,M)=>{const u=`${y.version}\0${M}`;let l=d.get(u);if(l===void 0){const I=await ae(y.plugin,{mountPath:M,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:I.tar,etag:I.etag},d.set(u,l)}const p={ETag:l.etag};return f.headers.get("if-none-match")===l.etag?new Response(null,{status:304,headers:p}):new Response(new Uint8Array(l.tar).buffer,{headers:{...p,"Content-Type":"application/x-tar"}})},"archiveResponse");return async f=>{if(f.method!=="POST"&&e.token!==void 0&&!Y(f.headers.get("authorization")??"",`Bearer ${e.token}`))return E(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."});const y=new URL(f.url).pathname;if(f.method==="GET"){if(!t)return m(f,h,b??G(y));const w=H(y),$=w[w.length-1],S=b??G(`/${w.slice(0,-1).join("/")}`);if($==="versions")return Response.json({latest:h.version,supported:r.map(A=>A.version)});const N=$===void 0?null:P.exec($),k=N===null?void 0:r.find(A=>A.version===Number(N[1]));return k===void 0?D():m(f,k,`${S}/v${k.version}`)}if(f.method!=="POST")return D();const M=performance.now();let u,l;const p=[];let I=[],B=!1,J=!1;const j=s(w=>{if(l!==void 0)try{e.onAnswer?.({...u===void 0?{}:{sub:u.sub,grantee:u.grantee,initiatingApp:u.initiatingApp,act:u.act,jti:u.jti,requestId:u.requestId,...u.runId===void 0?{}:{runId:u.runId}},...u===void 0&&g!==null&&g!==""?{requestId:g}:{},tool:l.path.slice(1).join(" "),status:w.status,durationMs:performance.now()-M,...p.length===0?{}:{receiptId:p[0].receipt_id},...p.length>1?{receiptIds:p.map($=>$.receipt_id)}:{},replayed:J})}catch{}return w},"answer");let g=f.headers.get("crtr-request-id");try{if(l=t?ge(r,y):we(h.commands,y),e.token!==void 0&&!Y(f.headers.get("authorization")??"",`Bearer ${e.token}`))return j(E(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."}));const w=c===void 0?void 0:await c(f);if(l===void 0){const o=t?ye(r,y):void 0;return j(o===void 0?D():be(o,r))}if(w!==void 0&&!w.scope.includes(l.scope)){u=Object.freeze({...w,requestId:g??"",...f.headers.get("crtr-run-id")?{runId:f.headers.get("crtr-run-id")}:{}});const o=l.leaf.group,v=i===void 0&&o!==void 0?w.scope.find(x=>x.endsWith(`:${o}`)&&x.length>o.length+1)?.slice(0,-(o.length+1)):void 0;throw fe(l.scope,v)}if(w!==void 0){if(g===null||g==="")return j(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=f.headers.get("crtr-run-id"),v=se(f.headers.get("crtr-caller"));u=Object.freeze({...w,requestId:g,...o!==null&&o!==""?{runId:o}:{},...Object.keys(v).length>0?{crtr:Object.freeze(v)}:{}})}const $=await ke(f,l.manifest,w!==void 0);if(l.leaf.sideEffect){if(g===null||g==="")return j(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=u===void 0?null:{sub:u.sub,grantee:u.grantee};if(!await e.requests.record(g,o)){J=!0;const x=await he(e.requests,g,o,l.plugin.timeouts?.requestMs??3e4);if(x!==!0){const _=x.headers.get("Crtr-Receipt");if(_!==null)try{const C=JSON.parse(_);p.push(...Array.isArray(C)?C:[C])}catch{}return j(x)}J=!1}B=!0}const S=l,N={request:f,...u!==void 0?{caller:u}:{},...g!==null&&g!==""?{causedBy:`request:${g}`}:{},approval:ne(f),meter(o){if(u===void 0)throw new Error("ctx.meter needs an authenticated caller");if(p.some(R=>R.unit===o.unit))throw new Error(`ctx.meter may be called only once for unit ${o.unit}`);if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const v=o.receiptId??u.requestId;if(p.some(R=>R.receipt_id===v))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${v} is taken`);const x=S.path.slice(1).join(" "),_=I.find(R=>R.mode==="unit"&&R.unit===o.unit),C=o.usdEquivalent??(_?.usd_per_unit!=null?o.units*_.usd_per_unit:0),L={receipt_id:v,provider:e.receipts.provider,tool:x,sub:u.sub,grantee:u.grantee,payer:u.payer,units:o.units,unit:o.unit,usd_equivalent:C,request_id:u.requestId,...u.runId!==void 0?{run_id:u.runId}:{},time:new Date().toISOString()};return p.push(L),L},async checkSpend(){if(u===void 0)throw new Error("ctx.checkSpend needs an authenticated caller");if(e.receipts===void 0)throw new Error("ctx.checkSpend needs receipts with a provider and outbox");if(e.receipts.ledger===void 0)throw new Error("ctx.checkSpend needs receipts.ledger (the provider's directory client credentials)");const o=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"")?.[1];if(o===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");return I=(await te(e.auth.issuer,o,S.path.slice(1).join(" "),e.receipts.ledger)).prices,{prices:I}}};let k,A;try{const o=await l.leaf.run($,N);k=l.leaf.streaming?await Ee(o,e.onError,l.path):xe(o,l.manifest)}catch(o){o instanceof T?(k=V(o),A=o.headers):(U(e.onError,o,l.path),k=z(o))}if(B&&k.status===403&&await le(k))return await e.requests.delete(g),j(W(k,p));try{if(B)await e.requests.store(g,{status:k.status,body:await k.clone().text(),...A!==void 0?{headers:{...A}}:{},...p.length>0?{receipt:p[0]}:{},...p.length>1?{receipts:[...p]}:{}});else if(p.length>0){if(e.receipts===void 0)throw new Error(`No receipt outbox for ${S.path.join(" ")}`);for(const o of p)await e.receipts.outbox.save(o)}}catch(o){return U(e.onError,o,l.path,p),j(z(o))}return j(W(k,p))}catch(w){return w instanceof T?j(V(w)):(U(e.onError,w,l?.path??[]),j(z(w)))}}}s(Me,"createFetchHandler");function z(n){return E(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(z,"handlerFailed");function W(n,e){if(e.length===0)return n;const i=new Headers(n.headers);return i.set("Crtr-Receipt",Z(e)),new Response(n.body,{status:n.status,headers:i})}s(W,"responseWithReceipts");function Z(n){return JSON.stringify(n.length===1?n[0]:n)}s(Z,"receiptHeader");async function le(n){try{const e=await n.clone().json();return F(e)&&F(e.error)&&e.error.code==="approval_required"}catch{return!1}}s(le,"isApprovalRequired");async function he(n,e,i,t){for(;;){const r=await n.read(e);if(r===null){if(await n.record(e,i))return!0;continue}if(r.identity?.sub!==i?.sub||r.identity?.grantee!==i?.grantee)return E(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const a=oe(r.answer.headers);a.set("Content-Type","application/json");const c=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return c.length>0&&a.set("Crtr-Receipt",Z(c)),new Response(r.answer.body,{status:r.answer.status,headers:a})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return z(new Error("The earlier request has no stored answer."));await new Promise(a=>setTimeout(a,Math.min(25,Math.max(1,new Date(r.recordedAt).getTime()+t-Date.now()))))}}s(he,"replay");function me(n,e,i){if(n.length===0)throw new Error("createFetchHandler needs at least one plugin definition");const t=n[0].name,r=new Map;for(const a of n){if(a.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${a.name}`);if(e&&a.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const c=a.version??1;if(r.has(c))throw new Error(`createFetchHandler got two definitions of ${t} major ${c}`);r.set(c,{version:c,plugin:a,commands:pe(a,i)})}return[...r.values()].sort((a,c)=>a.version-c.version)}s(me,"servedMajors");function pe(n,e){const t=de(n,{mountPath:""}).mounts[0]?.node;if(t===void 0||t.kind!=="branch")throw new Error("Generated plugin manifest has no root branch");const r=new Map;return K(t.children,n.commands,[t.name],n,r,e),r}s(pe,"commandMap");function K(n,e,i,t,r,a){const c=Object.entries(e);if(n.length!==c.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[d,[b,h]]of c.entries()){const m=n[d];if(m===void 0||m.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${b}`);const f=[...i,m.name];if(m.kind==="branch"&&h.kind==="branch"){K(m.children,h.children,f,t,r,a);continue}if(m.kind==="leaf"&&h.kind==="leaf"){r.set(f.join("/"),{path:f,leaf:h,plugin:t,manifest:m,...h.group!==void 0?{scope:`${a??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${b}`)}}s(K,"collectCommands");function we(n,e){const i=H(e);for(let t=0;t<i.length;t+=1){const r=n.get(i.slice(t).join("/"));if(r!==void 0)return r}}s(we,"findCommand");function ge(n,e){const i=H(e);for(let t=i.length-2;t>=0;t-=1){const r=P.exec(i[t]);if(r===null)continue;const c=n.find(d=>d.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(c!==void 0)return c}}s(ge,"findVersionedCommand");function ye(n,e){const i=H(e);for(let t=i.length-2;t>=0;t-=1){const r=P.exec(i[t]);if(r!==null)return n.some(a=>a.version===Number(r[1]))?void 0:Number(r[1])}}s(ye,"unservedMajor");function be(n,e){return E(410,{code:"unsupported_major",message:`Major ${n} is not served; supported majors: ${e.map(i=>i.version).join(", ")}.`,next:"Refetch the provider bundle and retry with its current major.",received:n})}s(be,"unsupportedMajor");function H(n){return n.split("/").filter(e=>e.length>0)}s(H,"pathSegments");async function ke(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const d=JSON.parse(t);if(!F(d))throw new Error("not an object");r=d}catch{throw q("Request body must be a JSON object.",i?"body":void 0,i,t)}const a=new Map(e.params.map(d=>[d.name,d]));for(const d of Object.keys(r))if(!a.has(d))throw i?q(`Unknown parameter ${d}.`,d,!0,r[d]):new T({code:"unknown_parameter",message:`Unknown parameter ${d}.`,field:d});const c={};for(const d of e.params){if(!Object.hasOwn(r,d.name)){if(d.required)throw q(`Missing required parameter ${d.name}.`,d.name,i,null);continue}const b=r[d.name];if(d.kind==="flag"&&d.type==="json"){const m=ie(d.shape,b,d.name);if(m!==null)throw q(`Invalid value for ${m.path}: expected ${m.expected}, got ${m.receivedType}.`,m.path,i,b);c[X(d.name)]=b;continue}const h=je(b,d);if(h===void 0)throw q(`Invalid value for parameter ${d.name}.`,d.name,i,b);c[X(d.name)]=h}return c}s(ke,"decodeInput");function je(n,e){if(e.kind!=="stdin"&&e.kind!=="context-file"&&e.repeatable){if(!Array.isArray(n))return;const i=n.map(t=>Q(t,e));return i.some(t=>t===void 0)?void 0:i}return Q(n,e)}s(je,"decodeParameter");function Q(n,e){if(e.kind==="stdin"||e.kind==="positional")return typeof n=="string"?n:void 0;if(e.kind!=="context-file"){if(e.type==="string")return typeof n=="string"?n:void 0;if(e.type==="int")return typeof n=="number"&&Number.isInteger(n)?n:void 0;if(e.type==="bool")return typeof n=="boolean"?n:void 0;if(e.type==="enum")return typeof n=="string"&&Array.isArray(e.choices)&&e.choices.includes(n)?n:void 0;if(e.type==="file")return typeof n=="string"?n:void 0;if(e.type==="path")return typeof n!="string"?void 0:e.encoding==="base64"?ve(n):n}}s(Q,"decodeScalar");function ve(n){if(!(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0))try{const e=atob(n);return Uint8Array.from(e,i=>i.charCodeAt(0))}catch{return}}s(ve,"decodeBase64");function xe(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw O("result")}if(!F(t))throw O("result");const r=re(e.output,t);if(r!==null)throw O(r.field,r.receivedType);for(const a of Object.keys(t))if(!e.output.some(c=>c.name===a))throw O(a);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(xe,"resultResponse");async function Ee(n,e,i){if(!$e(n))throw O("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,a=await t.next();let c=a.done,d=c?void 0:r.encode(`${JSON.stringify(a.value)}
|
|
2
|
+
`);const b=new ReadableStream({async pull(h){if(d!==void 0){h.enqueue(d),d=void 0;return}if(c){h.close();return}try{const m=await t.next();m.done?(c=!0,h.close()):h.enqueue(r.encode(`${JSON.stringify(m.value)}
|
|
3
|
+
`))}catch(m){U(e,m,i),h.error(m)}},async cancel(h){await t.return?.(h)}});return new Response(b,{headers:{"Content-Type":"application/x-ndjson"}})}s(Ee,"streamResponse");function U(n,e,i,t=[]){try{t.length>1?n?.(e,i,t[0],t):n?.(e,i,t[0])}catch{}}s(U,"reportUnhandledError");function O(n,e){return new T({code:"handler_output_invalid",message:`Handler returned an invalid value for ${n}.`,status:500,field:n,...e!==void 0?{received:e}:{}})}s(O,"outputInvalid");function q(n,e,i=!1,t){return new T({code:i?"invalid_argument":"invalid_input",message:n,...e!==void 0?{field:e}:{},...i?{received:t}:{}})}s(q,"invalidInput");function D(){return E(404,{code:"no_such_command",message:"No command matches this request."})}s(D,"noSuchCommand");function G(n){return n==="/"?"":n.replace(/\/+$/,"")}s(G,"mountPath");function X(n){return n.replace(/-([a-z])/g,(e,i)=>i.toUpperCase())}s(X,"camel");function Y(n,e){const i=new TextEncoder().encode(n),t=new TextEncoder().encode(e);let r=i.length^t.length;for(let a=0;a<Math.min(i.length,t.length);a+=1)r|=i[a]^t[a];return r===0}s(Y,"constantTimeEqual");function F(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}s(F,"isRecord");function $e(n){return typeof n=="object"&&n!==null&&Symbol.asyncIterator in n}s($e,"isAsyncIterable");export{Me as createFetchHandler};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.587",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.587",
|
|
31
|
+
"@north-light/identity": "0.3.587"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|