@north-light/plugin 0.3.518 → 0.3.520
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/client/index.d.ts +25 -0
- package/dist/client/index.js +70 -0
- package/dist/compare.d.ts +10 -1
- package/dist/compare.js +1 -1
- package/dist/define.d.ts +6 -6
- package/dist/define.js +1 -1
- package/dist/fields.d.ts +28 -2
- package/dist/fields.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/manifest.js +1 -1
- package/dist/params.d.ts +24 -2
- package/dist/params.js +1 -1
- package/dist/serve.js +3 -3
- package/dist/watchable.d.ts +13 -0
- package/dist/watchable.js +1 -0
- package/package.json +7 -3
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { HttpPluginCommandManifest } from '@north-light/api/plugin-manifest';
|
|
2
|
+
/** Raised on every change to the emitted bytes, so a caller can tell which stored packages predate the change. */
|
|
3
|
+
export declare const GENERATOR_REVISION = 2;
|
|
4
|
+
export interface ClientGeneratorInput {
|
|
5
|
+
/** The provider's registration id; also the package name `@northlight-providers/<providerId>`. */
|
|
6
|
+
readonly providerId: string;
|
|
7
|
+
/** The provider major the client always sends as `version`. */
|
|
8
|
+
readonly major: number;
|
|
9
|
+
/** The package version being minted, `<major>.<minor>.<patch>`. */
|
|
10
|
+
readonly version: string;
|
|
11
|
+
/** The stored `commands.json` of that major. */
|
|
12
|
+
readonly commands: HttpPluginCommandManifest;
|
|
13
|
+
/** The names of the provider's groups whose `who` is `own`; their leaves are not emitted. */
|
|
14
|
+
readonly ownGroups: readonly string[];
|
|
15
|
+
}
|
|
16
|
+
export interface ClientGeneratorOutput {
|
|
17
|
+
readonly files: {
|
|
18
|
+
readonly 'package.json': string;
|
|
19
|
+
readonly 'index.js': string;
|
|
20
|
+
readonly 'index.d.ts': string;
|
|
21
|
+
};
|
|
22
|
+
/** Hex SHA-256 of the canonical JSON (keys sorted) of `{ commands, ownGroups }` with `ownGroups` sorted. */
|
|
23
|
+
readonly inputDigest: string;
|
|
24
|
+
}
|
|
25
|
+
export declare function generateClient(input: ClientGeneratorInput): ClientGeneratorOutput;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
var E=Object.defineProperty;var a=(e,n)=>E(e,"name",{value:n,configurable:!0});import{createHash as N}from"node:crypto";import{validateCommandManifest as J}from"@north-light/api/command-manifest";const K=2,_=">=0.3.0 <1",A=/^[a-z0-9][a-z0-9_-]*$/,C=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","implements","interface","package","private","protected","public","await","then","constructor","prototype","__proto__"]),q=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function W(e){const{providerId:n,major:r,version:t}=e;if(!A.test(n))throw new Error(`providerId ${JSON.stringify(n)} is not a valid npm package name part`);if(!Number.isInteger(r)||r<1)throw new Error(`major must be a positive integer, got ${r}`);if(!new RegExp(`^${r}\\.\\d+\\.\\d+$`).test(t))throw new Error(`version ${JSON.stringify(t)} is not ${r}.<minor>.<patch>`);const s=[...new Set(e.ownGroups)].sort(),o=new Set(s),i=N("sha256").update(b({commands:e.commands,ownGroups:s})).digest("hex"),c=k(D(e.commands),[],o),p=w(d(n.split(/[-_]+/).filter(f=>f!=="").join("-")));if(p==="scopes")throw new Error('a provider id may not be "scopes"');const u=[...new Set($(c).flatMap(f=>f.group===void 0?[]:[`${n}:${f.group}`]))].sort(),y=`// @northlight-providers/${n} ${t} (provider ${n}, major ${r}, inputDigest ${i})
|
|
2
|
+
// Generated; do not edit.
|
|
3
|
+
`,R={name:`@northlight-providers/${n}`,version:t,type:"module",main:"index.js",types:"index.d.ts",exports:{".":{types:"./index.d.ts",import:"./index.js"}},sideEffects:!1,peerDependencies:{"@north-light/sdk":_}};return{files:{"package.json":`${JSON.stringify(R,null,2)}
|
|
4
|
+
`,"index.js":G(y,n,r,p,u,c),"index.d.ts":z(y,n,p,u,c)},inputDigest:i}}a(W,"generateClient");function D(e){const n=J(e,{transport:"http",reservedCoreNames:new Set});if(n.manifest===void 0)throw new Error(`the commands manifest is not valid: ${n.issues.map(s=>`${s.path??""} ${s.message} (${s.received})`.trim()).join("; ")}`);const r=n.manifest.roots,t=r[0];return r.length===1&&t?.kind==="branch"?t.children:r}a(D,"treeRoots");function k(e,n,r){const t=[],s=new Set;for(const o of e){const i=w(d(o.name)),c=[...n,o.name];let p;if(o.kind==="branch"){const u=k(o.children,c,r);u.length>0&&(p={kind:"branch",key:i,node:o,children:u})}else!(o.group!==void 0&&r.has(o.group))&&!o.params.some(u=>u.kind==="context-file"&&u.required)&&(p={kind:"leaf",key:i,segments:c,group:o.group,node:o,params:I(o.params)});if(p!==void 0){if(s.has(i))throw new Error(`commands ${c.join(" ")} and a sibling both generate the name ${i}`);s.add(i),t.push(p)}}return t}a(k,"collect");function $(e){return e.flatMap(n=>n.kind==="leaf"?[n]:$(n.children))}a($,"leaves");function I(e){const n=[],r=new Set;for(const t of e){if(t.kind==="context-file")continue;const s=d(t.name);if(r.has(s))throw new Error(`parameters of one command collide on the name ${s}`);r.add(s);const o=t.kind!=="stdin"&&t.repeatable===!0;let i,c=!1;t.kind==="stdin"||t.kind==="positional"?i="string":t.type==="int"?i="number":t.type==="bool"?i="boolean":t.type==="enum"?i=(t.choices??[]).map(u=>JSON.stringify(u)).join(" | ")||"never":t.type==="json"?i=l(t.shape,""):t.type==="path"&&t.encoding==="base64"?(c=!0,i="Uint8Array"):i="string";const p=o&&/[|]/.test(i)?`(${i})`:i;n.push({key:s,wire:t.name,type:o?`${p}[]`:i,required:t.required,constraint:t.constraint,base64:c,repeatable:o})}return n}a(I,"paramModels");function d(e){return e.replace(/-([a-z0-9])/g,(n,r)=>r.toUpperCase())}a(d,"camel");function w(e){const n=/^[0-9]/.test(e)?`_${e}`:e;return C.has(n)?`${n}_`:n}a(w,"safeName");function g(e){const n=d(e);return`${n[0].toUpperCase()}${n.slice(1)}`}a(g,"pascal");function v(e){return e.segments.map(g).join("_")}a(v,"typeBase");function j(e){return e.endsWith(" | null")?{base:e.slice(0,-7),nullable:!0}:{base:e,nullable:!1}}a(j,"nullable");function h(e){return q.test(e)?e:JSON.stringify(e)}a(h,"propertyKey");function l(e,n){const{base:r,nullable:t}=j(e.type);let s;switch(r){case"object":s=e.children===void 0?"Record<string, unknown>":e.children.length===0?"Record<string, never>":x(e.children,n);break;case"array":{if(e.items===void 0){s="unknown[]";break}const o=l(e.items,n);s=P(e.items)?`(${o})[]`:`${o}[]`;break}case"map":s=`Record<string, ${e.items===void 0?"unknown":l(e.items,n)}>`;break;case"union":s=(e.variants??[]).map(o=>l(o,n)).join(" | ")||"never";break;case"enum":s=(e.values??[]).map(o=>JSON.stringify(o)).join(" | ")||"never";break;case"int":case"number":s="number";break;case"bool":s="boolean";break;case"string":case"path":case"markdown":case"file":s="string";break;default:s="unknown"}return t?`${s} | null`:s}a(l,"shapeType");function P(e){const{base:n,nullable:r}=j(e.type);return r||n==="union"||n==="enum"}a(P,"needsParens");function x(e,n){if(e.length===0)return"{}";const r=`${n} `;return`{
|
|
5
|
+
${e.map(s=>`${m(s.constraint,r)}${r}${h(s.name)}${s.required?"":"?"}: ${l(s,r)};`).join(`
|
|
6
|
+
`)}
|
|
7
|
+
${n}}`}a(x,"objectType");function m(e,n,r=[]){const t=[e,...r].flatMap(s=>s.split(`
|
|
8
|
+
`)).map(s=>s.replace(/\*\//g,"*\\/").trimEnd());for(;t.length>0&&t[t.length-1]==="";)t.pop();return t.length===0?"":`${n}/**
|
|
9
|
+
${t.map(s=>`${n} *${s===""?"":` ${s}`}`).join(`
|
|
10
|
+
`)}
|
|
11
|
+
${n} */
|
|
12
|
+
`}a(m,"doc");function T(e,n){const{node:r}=e;return[r.description,"",`When to use: ${r.whenToUse}`,"",`Effects: ${r.effects.join(" ")}`,...e.group!==void 0?["",`Scope: ${n}:${e.group}`]:[]]}a(T,"leafDoc");function z(e,n,r,t,s){const o=[e,`import type { RequestOptions } from '@north-light/sdk';
|
|
13
|
+
`,"export interface ProviderRuntime {"," providers: {"," call(input: { provider: string; tool: string; arguments: Record<string, unknown>; version?: number; approval?: string; machine?: string }, options?: RequestOptions): Promise<unknown>;"," };",`}
|
|
14
|
+
`,`export type CallOptions = RequestOptions & { approval?: string; machine?: string };
|
|
15
|
+
`,`export declare const scopes: readonly [${t.map(i=>JSON.stringify(i)).join(", ")}];
|
|
16
|
+
`];for(const i of $(s)){const c=v(i);if(i.params.length>0){const p=i.params.map(u=>`${m(u.constraint," ")} ${u.key}${u.required?"":"?"}: ${u.type};`);o.push(`export interface ${c}Args {
|
|
17
|
+
${p.join(`
|
|
18
|
+
`)}
|
|
19
|
+
}
|
|
20
|
+
`)}o.push(`export interface ${c}Result ${x(i.node.output,"")}
|
|
21
|
+
`)}return o.push(`export interface ${g(r)}Client ${O(s,"",n)}
|
|
22
|
+
`),o.push(`export declare function ${r}(runtime: ProviderRuntime): ${g(r)}Client;
|
|
23
|
+
`),o.push(`export default ${r};
|
|
24
|
+
`),o.join(`
|
|
25
|
+
`)}a(z,"renderDts");function O(e,n,r){const t=`${n} `;return`{
|
|
26
|
+
${e.map(o=>{if(o.kind==="branch")return`${m(o.node.description,t)}${t}${h(o.key)}: ${O(o.children,t,r)};`;const i=v(o),c=o.params.length>0?`args: ${i}Args`:"args?: Record<string, never>",[p,...u]=T(o,r);return`${m(p,t,u)}${t}${h(o.key)}(${c}, options?: CallOptions): Promise<${i}Result>;`}).join(`
|
|
27
|
+
`)}
|
|
28
|
+
${n}}`}a(O,"clientType");function G(e,n,r,t,s,o){return`${e}
|
|
29
|
+
const $provider = ${JSON.stringify(n)};
|
|
30
|
+
const $major = ${r};
|
|
31
|
+
|
|
32
|
+
export const scopes = ${JSON.stringify(s)};
|
|
33
|
+
|
|
34
|
+
function $base64(bytes) {
|
|
35
|
+
let text = '';
|
|
36
|
+
for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
37
|
+
return btoa(text);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function $wire(args, spec) {
|
|
41
|
+
const wire = {};
|
|
42
|
+
for (const [key, name, base64] of spec) {
|
|
43
|
+
if (args == null || !Object.hasOwn(args, key) || args[key] === undefined) continue;
|
|
44
|
+
const value = args[key];
|
|
45
|
+
wire[name] = base64 === 0 ? value : Array.isArray(value) ? value.map($base64) : $base64(value);
|
|
46
|
+
}
|
|
47
|
+
return wire;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function $call(runtime, tool, args, spec, options) {
|
|
51
|
+
const { approval, machine, ...requestOptions } = options ?? {};
|
|
52
|
+
return runtime.providers.call({
|
|
53
|
+
provider: $provider,
|
|
54
|
+
tool,
|
|
55
|
+
arguments: $wire(args, spec),
|
|
56
|
+
version: $major,
|
|
57
|
+
...(approval !== undefined ? { approval } : {}),
|
|
58
|
+
...(machine !== undefined ? { machine } : {}),
|
|
59
|
+
}, requestOptions);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function ${t}(runtime) {
|
|
63
|
+
return ${S(o," ")};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export default ${t};
|
|
67
|
+
`}a(G,"renderJs");function S(e,n){const r=`${n} `;return`{
|
|
68
|
+
${e.map(s=>{const o=JSON.stringify(s.key);if(s.kind==="branch")return`${r}${o}: ${S(s.children,r)},`;const i=JSON.stringify(s.params.map(c=>[c.key,c.wire,c.base64?1:0]));return`${r}${o}: (args, options) => $call(runtime, ${JSON.stringify(s.segments.join(" "))}, args, ${i}, options),`}).join(`
|
|
69
|
+
`)}
|
|
70
|
+
${n}}`}a(S,"clientJs");function b(e){return Array.isArray(e)?`[${e.map(n=>b(n===void 0?null:n)).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[t])=>r<t?-1:r>t?1:0).map(([r,t])=>`${JSON.stringify(r)}:${b(t)}`).join(",")}}`:JSON.stringify(e)}a(b,"canonicalJson");export{K as GENERATOR_REVISION,W as generateClient};
|
package/dist/compare.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { HttpPluginCommandManifest } from '@north-light/api/plugin-manifest';
|
|
1
|
+
import type { HttpPluginCommandManifest, ManifestFieldShape } from '@north-light/api/plugin-manifest';
|
|
2
2
|
/** A change to a command contract that requires a new provider major. */
|
|
3
3
|
export interface BreakingManifestChange {
|
|
4
4
|
/** Space-joined command path, including the plugin name. */
|
|
@@ -7,3 +7,12 @@ export interface BreakingManifestChange {
|
|
|
7
7
|
}
|
|
8
8
|
/** Compare the command contracts of two archives for the same provider major. */
|
|
9
9
|
export declare function compareManifests(previous: HttpPluginCommandManifest, next: HttpPluginCommandManifest): BreakingManifestChange[];
|
|
10
|
+
type Direction = 'input' | 'output';
|
|
11
|
+
/**
|
|
12
|
+
* Every breaking difference between two shapes, each with its full path.
|
|
13
|
+
* Input: `next` must accept every value `old` accepted, so old's values must fit next.
|
|
14
|
+
* Output: every value `next` can return must fit the type generated from `old`, so next's values must fit old; a
|
|
15
|
+
* member `old` does not declare is ignored, but removing any member is breaking.
|
|
16
|
+
*/
|
|
17
|
+
export declare function compatible(old: ManifestFieldShape, next: ManifestFieldShape, direction: Direction, path: string): string[];
|
|
18
|
+
export {};
|
package/dist/compare.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var x=Object.defineProperty;var p=(e,o)=>x(e,"name",{value:o,configurable:!0});function z(e,o){const r=k(e),t=k(o),a=[];for(const[s,u]of r){const i=t.get(s);if(!i){a.push({leaf:s,rule:"tool removed or renamed; bump the major"});continue}u.group!==i.group&&a.push({leaf:s,rule:"tool group changed; bump the major"}),B(u,i,s,a),F(u,i,s,a),L(u,i,s,a),P(u.output,i.output,s,a)}return a}p(z,"compareManifests");function B(e,o,r,t){const a=new Map(o.params.map(n=>[n.name,n]));for(const n of e.params){const f=a.get(n.name);if(!f){t.push({leaf:r,rule:`parameter ${n.name} removed; bump the major`});continue}if(S(n)!==S(f)){t.push({leaf:r,rule:`parameter ${n.name} type changed; bump the major`});continue}if(n.kind==="flag"&&f.kind==="flag"&&n.type==="json"&&f.type==="json"&&n.shape&&f.shape)for(const c of N(n.shape,f.shape,"input",`--${n.name}`))t.push({leaf:r,rule:`${c}; bump the major`});if(!n.required&&f.required&&t.push({leaf:r,rule:`parameter ${n.name} became required; bump the major`}),n.kind==="flag"&&f.kind==="flag"){for(const w of n.choices??[])f.choices?.includes(w)||t.push({leaf:r,rule:`parameter ${n.name} enum value ${w} removed; bump the major`});const c=$(n),m=$(f);c!==void 0&&m!==void 0&&m!==c&&t.push({leaf:r,rule:`parameter ${n.name} default changed (${c} -> ${m}), so a caller that omits it gets a different page; bump the major`})}(n.kind==="flag"||n.kind==="positional")&&(f.kind==="flag"||f.kind==="positional")&&n.defaultFromEnv!==f.defaultFromEnv&&t.push({leaf:r,rule:`parameter ${n.name} environment default changed (${n.defaultFromEnv??"none"} -> ${f.defaultFromEnv??"none"}); bump the major`})}const s=new Set(e.params.map(n=>n.name));for(const n of o.params)!s.has(n.name)&&n.required&&t.push({leaf:r,rule:`required parameter ${n.name} added; bump the major`});const u=e.params.filter(n=>n.kind==="positional").map(n=>n.name),i=o.params.filter(n=>n.kind==="positional").map(n=>n.name),d=u.findIndex((n,f)=>a.has(n)&&i[f]!==n);d>=0&&t.push({leaf:r,rule:`positional parameter ${u[d]} moved from position ${d+1}; bump the major`})}p(B,"compareParams");const h=p(e=>e.toLowerCase().replace(/[^a-z0-9]/g,""),"normalize"),A=new Set(["limit","pagesize","perpage","maxresults","take"]),E=new Set(["cursor","page","pagetoken","offset"]),M=new Set(["nextcursor","nextpage","nextpagetoken","hasmore","truncated"]);function $(e){if(e.type!=="int"||!A.has(h(e.name)))return;const o=/\bdefaults?(?: of| to| is)?\s+(\d+)/i.exec(e.constraint);return o?Number(o[1]):void 0}p($,"statedLimit");function F(e,o,r,t){const a=p(m=>m.kind==="flag"&&$(m)!==void 0,"limited"),s=p(m=>m.kind==="flag"&&E.has(h(m.name)),"cursored");if(e.params.some(a)||e.params.some(s)&&e.output.some(m=>M.has(h(m.name))))return;const u=new Set(e.params.map(m=>m.name)),i=new Set(e.output.map(m=>m.name)),d=o.params.filter(m=>!u.has(m.name)&&a(m)).map(m=>`--${m.name} defaulting to ${$(m)}`),n=o.params.filter(m=>!u.has(m.name)&&s(m)).map(m=>`--${m.name}`),f=o.output.filter(m=>!i.has(m.name)&&M.has(h(m.name))).map(m=>`output ${m.name}`),c=n.length>0&&f.length>0;(d.length||c)&&t.push({leaf:r,rule:`gained paging (${[...d,...c?[...n,...f]:[]].join(", ")}) where it returned everything, so callers that do not page now get a partial answer; bump the major`})}p(F,"comparePaging");function L(e,o,r,t){const a=[],s=p(u=>u.replace(/\/v\d+(?=\/|$)/g,"/v*"),"route");e.rest.method!==o.rest.method&&a.push("method"),s(e.rest.path)!==s(o.rest.path)&&a.push("path"),!!e.rest.streaming!=!!o.rest.streaming&&a.push("streaming"),e.rest.bodyRoot!==o.rest.bodyRoot&&a.push("body root"),JSON.stringify(q(e.rest.body))!==JSON.stringify(q(o.rest.body))&&a.push("constant body fields");for(const[u,i]of Object.entries(e.rest.params)){const d=o.rest.params[u];d&&(i.in!==d.in||(i.as??u)!==(d.as??u))&&a.push(`parameter ${u} placement`)}a.length&&t.push({leaf:r,rule:`request mapping changed (${a.join(", ")}); bump the major`})}p(L,"compareRequest");function q(e){return Object.entries(e??{}).sort(([o],[r])=>o<r?-1:1)}p(q,"sorted");function k(e){const o=new Map;function r(t,a){const s=[...a,t.name];if(t.kind==="leaf")o.set(s.join(" "),t);else for(const u of t.children)r(u,s)}p(r,"visit");for(const t of e.mounts)r(t.node,t.parent);return o}p(k,"leaves");function S(e){return e.kind==="flag"?`${e.kind}:${e.type}:${!!e.repeatable}:${e.type==="path"?e.encoding:""}`:e.kind==="positional"?`${e.kind}:${e.type??"string"}:${!!e.repeatable}:${e.type==="path"?e.encoding:""}`:e.kind}p(S,"parameterType");function P(e,o,r,t){const a=new Map(o.map(u=>[u.name,u])),s=new Set(e.map(u=>u.name));for(const u of o)!s.has(u.name)&&b(u.type)==="file"&&t.push({leaf:r,rule:`file output field ${u.name} added; bump the major`});for(const u of e){const i=a.get(u.name);if(!i){t.push({leaf:r,rule:`output field ${u.name} removed; bump the major`});continue}u.required&&!i.required&&t.push({leaf:r,rule:`output field ${u.name} became optional; bump the major`});for(const d of N(u,i,"output",u.name))t.push({leaf:r,rule:`${d}; bump the major`})}}p(P,"compareFields");function b(e){return e.endsWith(" | null")?e.slice(0,-7):e}p(b,"baseType");function N(e,o,r,t){return r==="input"?g(e,o,r,t):g(o,e,r,t)}p(N,"compatible");function g(e,o,r,t){const a=r==="input";if(v(e)&&!v(o))return[`${r==="input"?"parameter":"output field"} ${t} ${a?"| null removed":"| null added"}`];if(l(e)!=="union"&&l(o)!=="union")return l(e)==="null"?[]:O(y(e),y(o),r,t);const s=j(o);return j(e).some(i=>!s.some(d=>O(i,d,r,t).length===0))?[`${r==="input"?"parameter":"output field"} ${t} ${a?"union variant removed":"union variant added"}`]:[]}p(g,"fits");function v(e){return R(e.type)||l(e)==="null"||l(e)==="union"&&(e.variants??[]).some(v)}p(v,"nullableDeep");function y(e){return R(e.type)?{...e,type:b(e.type)}:e}p(y,"withoutNull");function j(e){const o=l(e);if(o==="null")return[];if(o==="union")return(e.variants??[]).flatMap(j);const r=y(e);return o==="enum"&&e.values!==void 0?e.values.map(t=>({...r,values:[t]})):[r]}p(j,"atoms");function O(e,o,r,t){const a=r==="input"?"parameter":"output field",s=p((n,f)=>[`${a} ${n} ${f}`],"fail"),u=r==="input",i=l(e),d=l(o);return d==="unknown"?[]:i==="unknown"||i!==d&&!(i==="int"&&d==="number")?s(t,"type changed"):i==="enum"?o.values===void 0?[]:e.values===void 0||e.values.some(n=>!o.values.includes(n))?s(t,u?"enum value removed":"enum value added"):[]:i==="array"||i==="map"?o.items===void 0?[]:e.items===void 0?s(t,u?"items added":"type changed"):g(e.items,o.items,r,`${t}${i==="array"?"[]":"[*]"}`):i==="object"?T(e,o,r,t):[]}p(O,"fitsAtom");function T(e,o,r,t){const a=r==="input"?"parameter":"output field",s=r==="input";if(o.children===void 0)return[];if(e.children===void 0)return[`${a} ${t} ${s?"object closed":"object opened"}`];const u=[],i=new Map(e.children.map(n=>[n.name,n])),d=new Map(o.children.map(n=>[n.name,n]));for(const[n,f]of i){const c=d.get(n);if(c===void 0){s&&u.push(`${a} ${t}.${n} removed`);continue}!f.required&&c.required&&u.push(`${a} ${t}.${n} ${s?"became required":"became optional"}`),u.push(...g(f,c,r,`${t}.${n}`))}for(const[n,f]of d)i.has(n)||(s?f.required&&u.push(`${a} ${t}.${n} required member added`):u.push(`${a} ${t}.${n} removed`));return u}p(T,"fitMembers");function R(e){return e.endsWith(" | null")}p(R,"isNullable");function l(e){return b(e.type).toLowerCase()}p(l,"shapeBase");export{z as compareManifests,N as compatible};
|
package/dist/define.d.ts
CHANGED
|
@@ -89,8 +89,8 @@ export interface LeafNode {
|
|
|
89
89
|
readonly whenToUse: string;
|
|
90
90
|
/** The short outcome, shown in listings. */
|
|
91
91
|
readonly summary: string;
|
|
92
|
-
/** How prominently crtr lists the command. Defaults to `normal`. */
|
|
93
|
-
readonly tier?: 'normal' | 'common' | 'important';
|
|
92
|
+
/** How prominently crtr lists the command. `hidden` leaves it out of every listing; an exact-path call still runs. Defaults to `normal`. */
|
|
93
|
+
readonly tier?: 'hidden' | 'normal' | 'common' | 'important';
|
|
94
94
|
/** Input parameters by camelCase key, each built with `param.*`. */
|
|
95
95
|
readonly params: Record<string, AnyParam>;
|
|
96
96
|
/** Result fields by key, each built with `field.*`. */
|
|
@@ -121,8 +121,8 @@ export interface BranchNode {
|
|
|
121
121
|
readonly whenToUse: string;
|
|
122
122
|
/** The short outcome, shown in listings. */
|
|
123
123
|
readonly summary: string;
|
|
124
|
-
/** How prominently crtr lists the branch. Defaults to `normal`. */
|
|
125
|
-
readonly tier?: 'normal' | 'common' | 'important';
|
|
124
|
+
/** How prominently crtr lists the branch. `hidden` leaves it out of every listing; an exact-path call still runs. Defaults to `normal`. */
|
|
125
|
+
readonly tier?: 'hidden' | 'normal' | 'common' | 'important';
|
|
126
126
|
/** Nested branches and leaves by camelCase key. */
|
|
127
127
|
readonly children: Record<string, LeafNode | BranchNode>;
|
|
128
128
|
}
|
|
@@ -234,7 +234,7 @@ export declare function defineLeaf<P extends object = {}, const O extends object
|
|
|
234
234
|
description: string;
|
|
235
235
|
whenToUse: string;
|
|
236
236
|
summary: string;
|
|
237
|
-
tier?: 'normal' | 'common' | 'important';
|
|
237
|
+
tier?: 'hidden' | 'normal' | 'common' | 'important';
|
|
238
238
|
group?: string;
|
|
239
239
|
sideEffect?: boolean;
|
|
240
240
|
params?: P;
|
|
@@ -250,7 +250,7 @@ export declare function defineStreamingLeaf<P extends object = {}, O extends obj
|
|
|
250
250
|
description: string;
|
|
251
251
|
whenToUse: string;
|
|
252
252
|
summary: string;
|
|
253
|
-
tier?: 'normal' | 'common' | 'important';
|
|
253
|
+
tier?: 'hidden' | 'normal' | 'common' | 'important';
|
|
254
254
|
group?: string;
|
|
255
255
|
sideEffect?: boolean;
|
|
256
256
|
params?: P;
|
package/dist/define.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var T=Object.defineProperty;var o=(e,t)=>T(e,"name",{value:t,configurable:!0});import{LOCAL as U,mentionsFile as L,objectBlocksShapeReasons as K,objectKindReadReasons as R,outputBaseType as w}from"@north-light/api/command-manifest";class s extends Error{static{o(this,"PluginDefinitionError")}constructor(t){super(t),this.name="PluginDefinitionError"}}function Q(e){return{kind:"leaf",description:e.description,whenToUse:e.whenToUse,summary:e.summary,...e.tier!==void 0?{tier:e.tier}:{},...e.group!==void 0?{group:e.group}:{},...e.sideEffect!==void 0?{sideEffect:e.sideEffect}:{},params:e.params??{},output:e.output,effects:e.effects,streaming:!1,run:o((t,n)=>Promise.resolve(e.handler(t,n)),"run")}}o(Q,"defineLeaf");function X(e){return{kind:"leaf",description:e.description,whenToUse:e.whenToUse,summary:e.summary,...e.tier!==void 0?{tier:e.tier}:{},...e.group!==void 0?{group:e.group}:{},...e.sideEffect!==void 0?{sideEffect:e.sideEffect}:{},params:e.params??{},output:e.output,effects:e.effects,streaming:!0,run:o((t,n)=>Promise.resolve(e.handler(t,n)),"run")}}o(X,"defineStreamingLeaf");function ee(e){return{kind:"branch",...e}}o(ee,"defineBranch");function te(e){if(B(e.name,"plugin name"),d(e.description,"plugin description"),d(e.whenToUse,"plugin whenToUse"),d(e.summary,"plugin summary"),d(e.rootEntry?.concept,"plugin rootEntry.concept"),d(e.rootEntry?.description,"plugin rootEntry.description"),d(e.rootEntry?.whenToUse,"plugin rootEntry.whenToUse"),Z(e.timeouts),e.version!==void 0&&(typeof e.version!="number"||!Number.isInteger(e.version)||e.version<1))throw new s("plugin version must be an integer of at least 1");if(e.provider!==void 0&&typeof e.provider!="boolean")throw new s("plugin provider must be a boolean");if(e.provider===!0&&e.version===void 0)throw new s("a provider plugin must declare its major version");for(const[t,n]of Object.entries(e.commands))O(n,[e.name,t]);if(e.provider===!0){const t=_(e.commands,[e.name]);t!==void 0&&r(t,"needs a group because the plugin is a provider")}if(e.groups!==void 0){if(e.provider!==!0)throw new s("groups can only be declared by a provider plugin; set provider: true");S(e.groups,e.commands,e.name)}for(const t of e.memory??[])J(t);return e.objectKinds!==void 0&&F(e.objectKinds,e.name,e.commands),Object.freeze({name:e.name,description:e.description,whenToUse:e.whenToUse,summary:e.summary,rootEntry:Object.freeze({...e.rootEntry}),commands:g(e.commands),memory:Object.freeze((e.memory??[]).map(W)),...e.timeouts!==void 0?{timeouts:Object.freeze({...e.timeouts})}:{},...e.version!==void 0?{version:e.version}:{},...e.provider!==void 0?{provider:e.provider}:{},...e.objectKinds!==void 0?{objectKinds:M(e.objectKinds)}:{},...e.groups!==void 0?{groups:x(e.groups)}:{}})}o(te,"definePlugin");function S(e,t,n){if(!u(e))throw new s("groups must be an object keyed by group id");for(const[i,f]of Object.entries(e)){if(!z.test(i))throw new s(`group ${JSON.stringify(i)} must match [A-Za-z0-9_-]{1,64}`);if(!u(f))throw new s(`group "${i}" must be an object with consentLine`);const l=Object.keys(f).filter(c=>c!=="consentLine"&&c!=="who"&&c!=="allowlist");if(l.length>0)throw new s(`group "${i}" has unknown keys: ${l.join(", ")}`);if(d(f.consentLine,`group "${i}" consentLine`),f.who!==void 0&&f.who!=="own"&&f.who!=="user"&&f.who!=="allowlist"&&f.who!=="any")throw new s(`group "${i}" who must be own, user, allowlist, or any`);if(f.who==="allowlist"){if(!Array.isArray(f.allowlist)||f.allowlist.length===0||!f.allowlist.every(c=>typeof c=="string"&&/^app:.+/.test(c)))throw new s(`group "${i}" allowlist must be a non-empty array of app principals ("app:<id>") when who is allowlist`)}else if(f.allowlist!==void 0)throw new s(`group "${i}" allowlist is only allowed with who: "allowlist"`)}const a=new Set;for(const[i,f]of b(t,[n]))f.group!==void 0&&(Object.hasOwn(e,f.group)||r(i,`names group "${f.group}", which definePlugin groups does not declare`),a.add(f.group));for(const i of Object.keys(e))if(!a.has(i))throw new s(`group "${i}" is declared but no leaf uses it`)}o(S,"validateGroups");function x(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Object.freeze({consentLine:n.consentLine,...n.who!==void 0?{who:n.who}:{},...n.allowlist!==void 0?{allowlist:Object.freeze([...n.allowlist])}:{}})])))}o(x,"snapshotGroups");function F(e,t,n){if(!u(e))throw new s("objectKinds must be an object keyed by relative kind name");const a={};for(const[f,l]of Object.entries(e)){if(!U.test(f))throw new s(`object kind ${JSON.stringify(f)} must be a lowercase relative name without a "."; the bundle prefixes it with the provider id`);a[`${t}.${f}`]=l}const i=K({object_kinds:a});if(i.length===0){const{leafPaths:f,streamingLeafPaths:l}=N(n);for(const[c,P]of Object.entries(a))i.push(...R(c,P,t,f,l))}if(i.length>0)throw new s(i.join("; "))}o(F,"validateObjectKinds");function N(e){const t=new Set,n=new Set;for(const[a,i]of b(e,[])){const f=a.map(A).join(" ");t.add(f),i.streaming&&n.add(f)}return{leafPaths:t,streamingLeafPaths:n}}o(N,"leafPathsOf");function M(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Object.freeze({description:n.description,events:Object.freeze(Object.fromEntries(Object.entries(n.events).map(([a,i])=>[a,Object.freeze({...i})]))),...n.read!==void 0?{read:Object.freeze({command:Object.freeze([...n.read.command])})}:{}})])))}o(M,"snapshotObjectKinds");function _(e,t){for(const[n,a]of b(e,t))if(a.group===void 0)return n}o(_,"firstLeafWithoutGroup");function*b(e,t){for(const[n,a]of Object.entries(e)){const i=[...t,n];a.kind==="leaf"?yield[i,a]:yield*b(a.children,i)}}o(b,"leavesOf");function g(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,C(n)])))}o(g,"snapshotCommands");function C(e){return e.kind==="branch"?Object.freeze({kind:"branch",description:e.description,whenToUse:e.whenToUse,summary:e.summary,...e.tier!==void 0?{tier:e.tier}:{},children:g(e.children)}):Object.freeze({kind:"leaf",description:e.description,whenToUse:e.whenToUse,summary:e.summary,...e.tier!==void 0?{tier:e.tier}:{},params:q(e.params),output:p(e.output),effects:Object.freeze([...e.effects]),streaming:e.streaming,...e.group!==void 0?{group:e.group}:{},...e.sideEffect!==void 0?{sideEffect:e.sideEffect}:{},run:e.run})}o(C,"snapshotNode");function q(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,D(n)])))}o(q,"snapshotParams");function D(e){return e.kind==="flag"&&e.type==="enum"?Object.freeze({...e,choices:Object.freeze([...e.choices])}):Object.freeze({...e})}o(D,"snapshotParam");function p(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,j(n)])))}o(p,"snapshotOutput");function j(e){return Object.freeze({...e,...e.children!==void 0?{children:p(e.children)}:{},...e.items!==void 0?{items:j(e.items)}:{},...e.values!==void 0?{values:Object.freeze([...e.values])}:{}})}o(j,"snapshotField");function O(e,t){(!u(e)||e.kind!=="branch"&&e.kind!=="leaf")&&r(t,"must be a branch or leaf defined by this package"),d(e.description,`${m(t)} description`),d(e.whenToUse,`${m(t)} whenToUse`),d(e.summary,`${m(t)} summary`),e.tier!==void 0&&e.tier!=="normal"&&e.tier!=="common"&&e.tier!=="important"&&r(t,"tier must be normal, common, or important");const n=t.at(-1);if(n===void 0&&r(t,"has no command name"),E(n,`${m(t)} command key`),e.kind==="branch"){u(e.children)||r(t,"branch children must be an object");for(const[i,f]of Object.entries(e.children))O(f,[...t,i]);return}e.group!==void 0&&(typeof e.group!="string"||!z.test(e.group))&&r(t,`group ${JSON.stringify(e.group)} must match [A-Za-z0-9_-]{1,64}`),e.sideEffect!==void 0&&typeof e.sideEffect!="boolean"&&r(t,"sideEffect must be a boolean"),u(e.params)||r(t,"leaf params must be an object");for(const[i,f]of Object.entries(e.params))E(i,`${m(t)} parameter key`),I(f,[...t,`parameter ${i}`]);Object.values(e.params).filter(i=>u(i)&&i.kind==="positional").length>1&&r(t,"a leaf may have at most one positional parameter"),u(e.output)||r(t,"leaf output must be an object");let a;for(const[i,f]of Object.entries(e.output))i.length===0&&r(t,"output field names must not be empty"),y(f,[...t,`output ${i}`],!0),w(f.type)==="file"&&(a!==void 0&&r(t,`declares file outputs ${a} and ${i}; a leaf may declare at most one file output`),a=i);(!Array.isArray(e.effects)||e.effects.length===0||!e.effects.every(i=>typeof i=="string"))&&r(t,"leaf effects must be a non-empty array of strings"),typeof e.streaming!="boolean"&&r(t,"leaf streaming must be a boolean"),typeof e.run!="function"&&r(t,"leaf handler must be a function")}o(O,"validateNode");function I(e,t){if((!u(e)||e.kind!=="flag"&&e.kind!=="positional"&&e.kind!=="stdin")&&r(t,"must be a parameter descriptor produced by param.*"),d(e.constraint,`${m(t)} constraint`),(typeof e.required!="boolean"||typeof e.repeatable!="boolean")&&r(t,"required and repeatable must be booleans"),e.kind==="stdin"){e.repeatable&&r(t,"stdin cannot be repeatable"),Object.hasOwn(e,"default")&&r(t,"stdin parameters cannot have a default");return}if(e.kind==="positional"){e.type!=="string"&&r(t,"positional parameters must have type string"),Object.hasOwn(e,"default")&&r(t,"positional parameters cannot have a default");return}if(e.type==="enum"?(!Array.isArray(e.choices)||e.choices.length===0||!e.choices.every(a=>typeof a=="string"))&&r(t,"enum parameters need at least one string choice"):e.type!=="string"&&e.type!=="int"&&e.type!=="bool"&&e.type!=="path"&&e.type!=="file"&&r(t,"flag parameters must have a supported type"),(e.type==="bool"||e.type==="path"||e.type==="file")&&e.repeatable&&r(t,`${e.type} parameters cannot be repeatable`),e.type==="path"&&e.encoding!=="text"&&e.encoding!=="base64"&&r(t,"path parameters must have text or base64 encoding"),e.type!=="path"&&e.encoding!==void 0&&r(t,"encoding is only valid on path parameters"),e.repeatable&&Object.hasOwn(e,"default")&&r(t,"repeatable parameters cannot have a default"),!Object.hasOwn(e,"default"))return;const n=e.default;e.type==="string"&&typeof n!="string"&&r(t,"string parameter defaults must be strings"),e.type==="int"&&(typeof n!="number"||!Number.isInteger(n))&&r(t,"int parameter defaults must be integers"),e.type==="bool"&&typeof n!="boolean"&&r(t,"bool parameter defaults must be booleans"),e.type==="enum"&&(typeof n!="string"||!Array.isArray(e.choices)||!e.choices.includes(n))&&r(t,"enum parameter defaults must be one of their choices"),(e.type==="path"||e.type==="file")&&r(t,`${e.type} parameters cannot have a default`)}o(I,"validateParam");function y(e,t,n){(!u(e)||typeof e.type!="string"||e.type.length===0||typeof e.constraint!="string"||typeof e.required!="boolean")&&r(t,"must be an output field descriptor produced by field.*");const a=w(e.type);if(e.kind!==void 0&&a!=="file"&&r(t,"is a parameter descriptor; declare output fields with field.*"),L(e.type)&&a!=="file"&&r(t,`has type ${e.type}; a file output is one file, declared file or file | null`),a==="file"&&!n&&r(t,"is a file, which is only valid as a top-level output field"),e.children!==void 0){a!=="object"&&r(t,"children are only valid on an object field"),u(e.children)||r(t,"children must be an object of output fields");for(const[i,f]of Object.entries(e.children))i.length===0&&r(t,"member names must not be empty"),y(f,[...t,`member ${i}`],!1)}e.items!==void 0&&(a!=="array"&&r(t,"items are only valid on an array field"),y(e.items,[...t,"items"],!1)),e.values!==void 0&&(a!=="enum"&&r(t,"values are only valid on an enum field"),(!Array.isArray(e.values)||e.values.length===0||!e.values.every(i=>typeof i=="string"&&i.length>0))&&r(t,"enum values must be a non-empty array of non-empty strings"),new Set(e.values).size!==e.values.length&&r(t,"enum values must be unique"))}o(y,"validateField");function J(e){if(!u(e)||typeof e.name!="string"||!Y(e.name))throw new s("memory document name must be a safe relative path");if(e.kind!=="knowledge"&&e.kind!=="preference")throw new s(`memory document ${e.name} has an invalid kind`);if(d(e.whenAndWhyToRead,`memory document ${e.name} whenAndWhyToRead`),typeof e.body!="string")throw new s(`memory document ${e.name} body must be a string`);if(e.unlisted!==void 0&&typeof e.unlisted!="boolean")throw new s(`memory document ${e.name} unlisted must be a boolean`);if(e.rules!==void 0){if(!Array.isArray(e.rules))throw new s(`memory document ${e.name} rules must be an array`);e.rules.forEach((t,n)=>G(t,`memory document ${e.name} rules[${n}]`))}}o(J,"validateMemoryDoc");const v=["boot","file-read","document-read","command","pre-command"],$=["on","deliver","match","matchFrontmatter","if"];function G(e,t){if(!u(e))throw new s(`${t} must be an object`);for(const n of Object.keys(e))if(!$.includes(n))throw new s(`${t} has unknown key ${n}; a rule carries only ${$.join(", ")}`);if(typeof e.on!="string"||!v.includes(e.on))throw new s(`${t} on must be one of ${v.join(", ")}`);if(e.deliver!=="name"&&e.deliver!=="preview"&&e.deliver!=="content")throw new s(`${t} deliver must be name, preview or content`);if(e.match!==void 0){if(e.on==="boot")throw new s(`${t} match is meaningless on boot; drop it`);if(!Array.isArray(e.match)||e.match.length===0||!e.match.every(n=>typeof n=="string"&&n.trim().length>0))throw new s(`${t} match must be a non-empty array of non-empty globs`)}if(e.matchFrontmatter!==void 0){if(e.on!=="file-read")throw new s(`${t} matchFrontmatter applies only to file-read`);k(e.matchFrontmatter,`${t} matchFrontmatter`)}if(e.on!=="boot"&&e.match===void 0&&e.matchFrontmatter===void 0)throw new s(`${t} needs match${e.on==="file-read"?" or matchFrontmatter":""} on ${e.on}`);e.if!==void 0&&k(e.if,`${t} if`)}o(G,"validateMemoryRule");function k(e,t){if(!u(e))throw new s(`${t} must be a field\u2192matcher object`);if(!h(e,0))throw new s(`${t} must hold only strings, finite numbers, booleans, null, arrays and plain objects`)}o(k,"assertCondition");function h(e,t){return t>32?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.every(n=>h(n,t+1)):!u(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null?!1:Object.values(e).every(n=>h(n,t+1))}o(h,"isPlainJson");function W(e){const{rules:t,...n}=e;return Object.freeze({...n,...t!==void 0?{rules:Object.freeze(t.map(a=>structuredClone(a)))}:{}})}o(W,"freezeMemoryDoc");function Z(e){if(e!==void 0){if(!u(e))throw new s("timeouts must be an object");for(const t of["connectMs","requestMs","streamIdleMs"]){const n=e[t];if(n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0))throw new s(`timeouts.${t} must be a positive integer`)}}}o(Z,"assertTimeouts");const z=/^[A-Za-z0-9_-]{1,64}$/;function E(e,t){if(A(e).replace(/-([a-z])/g,(a,i)=>i.toUpperCase())!==e)throw new s(`${t} must round-trip between camelCase and kebab-case`)}o(E,"assertKey");function B(e,t){if(!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(e))throw new s(`${t} must be lowercase kebab-case`)}o(B,"assertKebabName");function A(e){const t=e.replace(/[A-Z]/g,n=>`-${n.toLowerCase()}`);if(!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(t))throw new s(`invalid key ${JSON.stringify(e)}; use camelCase keys that convert to lowercase kebab-case`);return t}o(A,"kebab");function d(e,t){if(typeof e!="string"||e.length===0)throw new s(`${t} must be a non-empty string`)}o(d,"assertText");function Y(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}o(Y,"isSafeRelativePath");function u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(u,"isRecord");function r(e,t){throw new s(`${m(e)} ${t}`)}o(r,"fail");function m(e){return e.join(" ")}o(m,"formatPath");export{s as PluginDefinitionError,ee as defineBranch,Q as defineLeaf,te as definePlugin,X as defineStreamingLeaf,A as kebab};
|
|
1
|
+
var T=Object.defineProperty;var s=(e,t)=>T(e,"name",{value:t,configurable:!0});import{LOCAL as U,mentionsFile as L,objectBlocksShapeReasons as K,objectKindReadReasons as R,outputBaseType as g}from"@north-light/api/command-manifest";class f extends Error{static{s(this,"PluginDefinitionError")}constructor(t){super(t),this.name="PluginDefinitionError"}}function Q(e){return{kind:"leaf",description:e.description,whenToUse:e.whenToUse,summary:e.summary,...e.tier!==void 0?{tier:e.tier}:{},...e.group!==void 0?{group:e.group}:{},...e.sideEffect!==void 0?{sideEffect:e.sideEffect}:{},params:e.params??{},output:e.output,effects:e.effects,streaming:!1,run:s((t,n)=>Promise.resolve(e.handler(t,n)),"run")}}s(Q,"defineLeaf");function X(e){return{kind:"leaf",description:e.description,whenToUse:e.whenToUse,summary:e.summary,...e.tier!==void 0?{tier:e.tier}:{},...e.group!==void 0?{group:e.group}:{},...e.sideEffect!==void 0?{sideEffect:e.sideEffect}:{},params:e.params??{},output:e.output,effects:e.effects,streaming:!0,run:s((t,n)=>Promise.resolve(e.handler(t,n)),"run")}}s(X,"defineStreamingLeaf");function ee(e){return{kind:"branch",...e}}s(ee,"defineBranch");function te(e){if(B(e.name,"plugin name"),d(e.description,"plugin description"),d(e.whenToUse,"plugin whenToUse"),d(e.summary,"plugin summary"),d(e.rootEntry?.concept,"plugin rootEntry.concept"),d(e.rootEntry?.description,"plugin rootEntry.description"),d(e.rootEntry?.whenToUse,"plugin rootEntry.whenToUse"),Z(e.timeouts),e.version!==void 0&&(typeof e.version!="number"||!Number.isInteger(e.version)||e.version<1))throw new f("plugin version must be an integer of at least 1");if(e.provider!==void 0&&typeof e.provider!="boolean")throw new f("plugin provider must be a boolean");if(e.provider===!0&&e.version===void 0)throw new f("a provider plugin must declare its major version");for(const[t,n]of Object.entries(e.commands))v(n,[e.name,t]);if(e.provider===!0){const t=_(e.commands,[e.name]);t!==void 0&&r(t,"needs a group because the plugin is a provider")}if(e.groups!==void 0){if(e.provider!==!0)throw new f("groups can only be declared by a provider plugin; set provider: true");S(e.groups,e.commands,e.name)}for(const t of e.memory??[])J(t);return e.objectKinds!==void 0&&F(e.objectKinds,e.name,e.commands),Object.freeze({name:e.name,description:e.description,whenToUse:e.whenToUse,summary:e.summary,rootEntry:Object.freeze({...e.rootEntry}),commands:p(e.commands),memory:Object.freeze((e.memory??[]).map(W)),...e.timeouts!==void 0?{timeouts:Object.freeze({...e.timeouts})}:{},...e.version!==void 0?{version:e.version}:{},...e.provider!==void 0?{provider:e.provider}:{},...e.objectKinds!==void 0?{objectKinds:M(e.objectKinds)}:{},...e.groups!==void 0?{groups:x(e.groups)}:{}})}s(te,"definePlugin");function S(e,t,n){if(!u(e))throw new f("groups must be an object keyed by group id");for(const[i,o]of Object.entries(e)){if(!z.test(i))throw new f(`group ${JSON.stringify(i)} must match [A-Za-z0-9_-]{1,64}`);if(!u(o))throw new f(`group "${i}" must be an object with consentLine`);const l=Object.keys(o).filter(c=>c!=="consentLine"&&c!=="who"&&c!=="allowlist");if(l.length>0)throw new f(`group "${i}" has unknown keys: ${l.join(", ")}`);if(d(o.consentLine,`group "${i}" consentLine`),o.who!==void 0&&o.who!=="own"&&o.who!=="user"&&o.who!=="allowlist"&&o.who!=="any")throw new f(`group "${i}" who must be own, user, allowlist, or any`);if(o.who==="allowlist"){if(!Array.isArray(o.allowlist)||o.allowlist.length===0||!o.allowlist.every(c=>typeof c=="string"&&/^app:.+/.test(c)))throw new f(`group "${i}" allowlist must be a non-empty array of app principals ("app:<id>") when who is allowlist`)}else if(o.allowlist!==void 0)throw new f(`group "${i}" allowlist is only allowed with who: "allowlist"`)}const a=new Set;for(const[i,o]of y(t,[n]))o.group!==void 0&&(Object.hasOwn(e,o.group)||r(i,`names group "${o.group}", which definePlugin groups does not declare`),a.add(o.group));for(const i of Object.keys(e))if(!a.has(i))throw new f(`group "${i}" is declared but no leaf uses it`)}s(S,"validateGroups");function x(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Object.freeze({consentLine:n.consentLine,...n.who!==void 0?{who:n.who}:{},...n.allowlist!==void 0?{allowlist:Object.freeze([...n.allowlist])}:{}})])))}s(x,"snapshotGroups");function F(e,t,n){if(!u(e))throw new f("objectKinds must be an object keyed by relative kind name");const a={};for(const[o,l]of Object.entries(e)){if(!U.test(o))throw new f(`object kind ${JSON.stringify(o)} must be a lowercase relative name without a "."; the bundle prefixes it with the provider id`);a[`${t}.${o}`]=l}const i=K({object_kinds:a});if(i.length===0){const{leafPaths:o,streamingLeafPaths:l}=N(n);for(const[c,P]of Object.entries(a))i.push(...R(c,P,t,o,l))}if(i.length>0)throw new f(i.join("; "))}s(F,"validateObjectKinds");function N(e){const t=new Set,n=new Set;for(const[a,i]of y(e,[])){const o=a.map(A).join(" ");t.add(o),i.streaming&&n.add(o)}return{leafPaths:t,streamingLeafPaths:n}}s(N,"leafPathsOf");function M(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Object.freeze({description:n.description,events:Object.freeze(Object.fromEntries(Object.entries(n.events).map(([a,i])=>[a,Object.freeze({...i})]))),...n.read!==void 0?{read:Object.freeze({command:Object.freeze([...n.read.command])})}:{}})])))}s(M,"snapshotObjectKinds");function _(e,t){for(const[n,a]of y(e,t))if(a.group===void 0)return n}s(_,"firstLeafWithoutGroup");function*y(e,t){for(const[n,a]of Object.entries(e)){const i=[...t,n];a.kind==="leaf"?yield[i,a]:yield*y(a.children,i)}}s(y,"leavesOf");function p(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,C(n)])))}s(p,"snapshotCommands");function C(e){return e.kind==="branch"?Object.freeze({kind:"branch",description:e.description,whenToUse:e.whenToUse,summary:e.summary,...e.tier!==void 0?{tier:e.tier}:{},children:p(e.children)}):Object.freeze({kind:"leaf",description:e.description,whenToUse:e.whenToUse,summary:e.summary,...e.tier!==void 0?{tier:e.tier}:{},params:q(e.params),output:j(e.output),effects:Object.freeze([...e.effects]),streaming:e.streaming,...e.group!==void 0?{group:e.group}:{},...e.sideEffect!==void 0?{sideEffect:e.sideEffect}:{},run:e.run})}s(C,"snapshotNode");function q(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,D(n)])))}s(q,"snapshotParams");function D(e){return e.kind==="flag"&&e.type==="enum"?Object.freeze({...e,choices:Object.freeze([...e.choices])}):e.kind==="flag"&&e.type==="json"?Object.freeze({...e,shape:h(e.shape)}):Object.freeze({...e})}s(D,"snapshotParam");function j(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([t,n])=>[t,h(n)])))}s(j,"snapshotOutput");function h(e){return Object.freeze({...e,...e.children!==void 0?{children:j(e.children)}:{},...e.items!==void 0?{items:h(e.items)}:{},...e.variants!==void 0?{variants:Object.freeze(e.variants.map(h))}:{},...e.values!==void 0?{values:Object.freeze([...e.values])}:{}})}s(h,"snapshotField");function v(e,t){(!u(e)||e.kind!=="branch"&&e.kind!=="leaf")&&r(t,"must be a branch or leaf defined by this package"),d(e.description,`${m(t)} description`),d(e.whenToUse,`${m(t)} whenToUse`),d(e.summary,`${m(t)} summary`),e.tier!==void 0&&e.tier!=="hidden"&&e.tier!=="normal"&&e.tier!=="common"&&e.tier!=="important"&&r(t,"tier must be hidden, normal, common, or important");const n=t.at(-1);if(n===void 0&&r(t,"has no command name"),E(n,`${m(t)} command key`),e.kind==="branch"){u(e.children)||r(t,"branch children must be an object");for(const[i,o]of Object.entries(e.children))v(o,[...t,i]);return}e.group!==void 0&&(typeof e.group!="string"||!z.test(e.group))&&r(t,`group ${JSON.stringify(e.group)} must match [A-Za-z0-9_-]{1,64}`),e.sideEffect!==void 0&&typeof e.sideEffect!="boolean"&&r(t,"sideEffect must be a boolean"),u(e.params)||r(t,"leaf params must be an object");for(const[i,o]of Object.entries(e.params))E(i,`${m(t)} parameter key`),I(o,[...t,`parameter ${i}`]);Object.values(e.params).filter(i=>u(i)&&i.kind==="positional").length>1&&r(t,"a leaf may have at most one positional parameter"),u(e.output)||r(t,"leaf output must be an object");let a;for(const[i,o]of Object.entries(e.output))i.length===0&&r(t,"output field names must not be empty"),b(o,[...t,`output ${i}`],!0),g(o.type)==="file"&&(a!==void 0&&r(t,`declares file outputs ${a} and ${i}; a leaf may declare at most one file output`),a=i);(!Array.isArray(e.effects)||e.effects.length===0||!e.effects.every(i=>typeof i=="string"))&&r(t,"leaf effects must be a non-empty array of strings"),typeof e.streaming!="boolean"&&r(t,"leaf streaming must be a boolean"),typeof e.run!="function"&&r(t,"leaf handler must be a function")}s(v,"validateNode");function I(e,t){if((!u(e)||e.kind!=="flag"&&e.kind!=="positional"&&e.kind!=="stdin")&&r(t,"must be a parameter descriptor produced by param.*"),d(e.constraint,`${m(t)} constraint`),(typeof e.required!="boolean"||typeof e.repeatable!="boolean")&&r(t,"required and repeatable must be booleans"),e.kind==="stdin"){e.repeatable&&r(t,"stdin cannot be repeatable"),Object.hasOwn(e,"default")&&r(t,"stdin parameters cannot have a default");return}if(e.kind==="positional"){e.type!=="string"&&r(t,"positional parameters must have type string"),Object.hasOwn(e,"default")&&r(t,"positional parameters cannot have a default");return}if(e.type==="enum"?(!Array.isArray(e.choices)||e.choices.length===0||!e.choices.every(a=>typeof a=="string"))&&r(t,"enum parameters need at least one string choice"):e.type!=="string"&&e.type!=="int"&&e.type!=="bool"&&e.type!=="path"&&e.type!=="file"&&e.type!=="json"&&r(t,"flag parameters must have a supported type"),(e.type==="bool"||e.type==="path"||e.type==="file"||e.type==="json")&&e.repeatable&&r(t,`${e.type} parameters cannot be repeatable`),e.type==="path"&&e.encoding!=="text"&&e.encoding!=="base64"&&r(t,"path parameters must have text or base64 encoding"),e.type==="json"?b(e.shape,[...t,"shape"],!1):e.shape!==void 0&&r(t,"shape is only valid on json parameters"),e.type!=="path"&&e.encoding!==void 0&&r(t,"encoding is only valid on path parameters"),e.repeatable&&Object.hasOwn(e,"default")&&r(t,"repeatable parameters cannot have a default"),!Object.hasOwn(e,"default"))return;const n=e.default;e.type==="string"&&typeof n!="string"&&r(t,"string parameter defaults must be strings"),e.type==="int"&&(typeof n!="number"||!Number.isInteger(n))&&r(t,"int parameter defaults must be integers"),e.type==="bool"&&typeof n!="boolean"&&r(t,"bool parameter defaults must be booleans"),e.type==="enum"&&(typeof n!="string"||!Array.isArray(e.choices)||!e.choices.includes(n))&&r(t,"enum parameter defaults must be one of their choices"),(e.type==="path"||e.type==="file"||e.type==="json")&&r(t,`${e.type} parameters cannot have a default`)}s(I,"validateParam");function b(e,t,n){(!u(e)||typeof e.type!="string"||e.type.length===0||typeof e.constraint!="string"||typeof e.required!="boolean")&&r(t,"must be an output field descriptor produced by field.*");const a=g(e.type);if(e.kind!==void 0&&a!=="file"&&r(t,"is a parameter descriptor; declare output fields with field.*"),L(e.type)&&a!=="file"&&r(t,`has type ${e.type}; a file output is one file, declared file or file | null`),a==="file"&&!n&&r(t,"is a file, which is only valid as a top-level output field"),e.children!==void 0){a!=="object"&&r(t,"children are only valid on an object field"),u(e.children)||r(t,"children must be an object of output fields");for(const[i,o]of Object.entries(e.children))i.length===0&&r(t,"member names must not be empty"),b(o,[...t,`member ${i}`],!1)}e.items!==void 0&&(a!=="array"&&a!=="map"&&r(t,"items are only valid on an array or map field"),b(e.items,[...t,"items"],!1)),a==="map"&&e.items===void 0&&r(t,"a map field needs the shape of its values"),e.variants!==void 0&&a!=="union"&&r(t,"variants are only valid on a union field"),a==="union"&&((!Array.isArray(e.variants)||e.variants.length<2)&&r(t,"a union field needs two or more variants"),e.variants.forEach((i,o)=>b(i,[...t,`variant ${o}`],!1))),e.values!==void 0&&(a!=="enum"&&r(t,"values are only valid on an enum field"),(!Array.isArray(e.values)||e.values.length===0||!e.values.every(i=>typeof i=="string"&&i.length>0))&&r(t,"enum values must be a non-empty array of non-empty strings"),new Set(e.values).size!==e.values.length&&r(t,"enum values must be unique"))}s(b,"validateField");function J(e){if(!u(e)||typeof e.name!="string"||!Y(e.name))throw new f("memory document name must be a safe relative path");if(e.kind!=="knowledge"&&e.kind!=="preference")throw new f(`memory document ${e.name} has an invalid kind`);if(d(e.whenAndWhyToRead,`memory document ${e.name} whenAndWhyToRead`),typeof e.body!="string")throw new f(`memory document ${e.name} body must be a string`);if(e.unlisted!==void 0&&typeof e.unlisted!="boolean")throw new f(`memory document ${e.name} unlisted must be a boolean`);if(e.rules!==void 0){if(!Array.isArray(e.rules))throw new f(`memory document ${e.name} rules must be an array`);e.rules.forEach((t,n)=>G(t,`memory document ${e.name} rules[${n}]`))}}s(J,"validateMemoryDoc");const O=["boot","file-read","document-read","command","pre-command"],$=["on","deliver","match","matchFrontmatter","if"];function G(e,t){if(!u(e))throw new f(`${t} must be an object`);for(const n of Object.keys(e))if(!$.includes(n))throw new f(`${t} has unknown key ${n}; a rule carries only ${$.join(", ")}`);if(typeof e.on!="string"||!O.includes(e.on))throw new f(`${t} on must be one of ${O.join(", ")}`);if(e.deliver!=="name"&&e.deliver!=="preview"&&e.deliver!=="content")throw new f(`${t} deliver must be name, preview or content`);if(e.match!==void 0){if(e.on==="boot")throw new f(`${t} match is meaningless on boot; drop it`);if(!Array.isArray(e.match)||e.match.length===0||!e.match.every(n=>typeof n=="string"&&n.trim().length>0))throw new f(`${t} match must be a non-empty array of non-empty globs`)}if(e.matchFrontmatter!==void 0){if(e.on!=="file-read")throw new f(`${t} matchFrontmatter applies only to file-read`);k(e.matchFrontmatter,`${t} matchFrontmatter`)}if(e.on!=="boot"&&e.match===void 0&&e.matchFrontmatter===void 0)throw new f(`${t} needs match${e.on==="file-read"?" or matchFrontmatter":""} on ${e.on}`);e.if!==void 0&&k(e.if,`${t} if`)}s(G,"validateMemoryRule");function k(e,t){if(!u(e))throw new f(`${t} must be a field\u2192matcher object`);if(!w(e,0))throw new f(`${t} must hold only strings, finite numbers, booleans, null, arrays and plain objects`)}s(k,"assertCondition");function w(e,t){return t>32?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.every(n=>w(n,t+1)):!u(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null?!1:Object.values(e).every(n=>w(n,t+1))}s(w,"isPlainJson");function W(e){const{rules:t,...n}=e;return Object.freeze({...n,...t!==void 0?{rules:Object.freeze(t.map(a=>structuredClone(a)))}:{}})}s(W,"freezeMemoryDoc");function Z(e){if(e!==void 0){if(!u(e))throw new f("timeouts must be an object");for(const t of["connectMs","requestMs","streamIdleMs"]){const n=e[t];if(n!==void 0&&(typeof n!="number"||!Number.isInteger(n)||n<=0))throw new f(`timeouts.${t} must be a positive integer`)}}}s(Z,"assertTimeouts");const z=/^[A-Za-z0-9_-]{1,64}$/;function E(e,t){if(A(e).replace(/-([a-z])/g,(a,i)=>i.toUpperCase())!==e)throw new f(`${t} must round-trip between camelCase and kebab-case`)}s(E,"assertKey");function B(e,t){if(!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(e))throw new f(`${t} must be lowercase kebab-case`)}s(B,"assertKebabName");function A(e){const t=e.replace(/[A-Z]/g,n=>`-${n.toLowerCase()}`);if(!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(t))throw new f(`invalid key ${JSON.stringify(e)}; use camelCase keys that convert to lowercase kebab-case`);return t}s(A,"kebab");function d(e,t){if(typeof e!="string"||e.length===0)throw new f(`${t} must be a non-empty string`)}s(d,"assertText");function Y(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}s(Y,"isSafeRelativePath");function u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(u,"isRecord");function r(e,t){throw new f(`${m(e)} ${t}`)}s(r,"fail");function m(e){return e.join(" ")}s(m,"formatPath");export{f as PluginDefinitionError,ee as defineBranch,Q as defineLeaf,te as definePlugin,X as defineStreamingLeaf,A as kebab};
|
package/dist/fields.d.ts
CHANGED
|
@@ -8,8 +8,10 @@ export interface OutField<T extends string, Req extends boolean> {
|
|
|
8
8
|
readonly required: Req;
|
|
9
9
|
/** An object field's members by name, set by `field.object({ … })`. */
|
|
10
10
|
readonly children?: Readonly<Record<string, OutField<string, boolean>>>;
|
|
11
|
-
/** An array field's element shape, set by `field.array(field.…)`. */
|
|
11
|
+
/** An array field's element shape or a map field's value shape, set by `field.array(field.…)` or `field.map(field.…)`. */
|
|
12
12
|
readonly items?: OutField<string, boolean>;
|
|
13
|
+
/** A union field's alternatives, set by `field.union([…])`. */
|
|
14
|
+
readonly variants?: readonly OutField<string, boolean>[];
|
|
13
15
|
/** An enum field's allowed values, set by `field.enum([…])`. */
|
|
14
16
|
readonly values?: readonly string[];
|
|
15
17
|
}
|
|
@@ -29,6 +31,14 @@ export type ObjectField<C extends Record<string, FieldShape>, Req extends boolea
|
|
|
29
31
|
export type ArrayField<I extends FieldShape, Req extends boolean> = Omit<OutField<'array', Req>, 'items'> & {
|
|
30
32
|
readonly items: I;
|
|
31
33
|
};
|
|
34
|
+
/** A map field with typed values under string keys, as returned by `field.map(field.…)`. */
|
|
35
|
+
export type MapField<I extends FieldShape, Req extends boolean> = Omit<OutField<'map', Req>, 'items'> & {
|
|
36
|
+
readonly items: I;
|
|
37
|
+
};
|
|
38
|
+
/** A union field of two or more alternative shapes, as returned by `field.union([…])`. */
|
|
39
|
+
export type UnionField<V extends readonly FieldShape[], Req extends boolean> = Omit<OutField<'union', Req>, 'variants'> & {
|
|
40
|
+
readonly variants: V;
|
|
41
|
+
};
|
|
32
42
|
/** A field restricted to fixed values, as returned by `field.enum([…])`. */
|
|
33
43
|
export type EnumField<V extends string, Req extends boolean> = OutField<'enum', Req> & {
|
|
34
44
|
readonly values: readonly V[];
|
|
@@ -51,7 +61,7 @@ export interface FileOutputValue {
|
|
|
51
61
|
readonly size: number;
|
|
52
62
|
readonly sha256: string;
|
|
53
63
|
}
|
|
54
|
-
type FieldValue<F> = F extends {
|
|
64
|
+
export type FieldValue<F> = F extends {
|
|
55
65
|
type: `${infer B} | null`;
|
|
56
66
|
} ? FieldValue<Omit<F, 'type'> & {
|
|
57
67
|
type: B;
|
|
@@ -71,6 +81,16 @@ type FieldValue<F> = F extends {
|
|
|
71
81
|
} ? readonly FieldValue<I>[] : F extends {
|
|
72
82
|
type: 'array';
|
|
73
83
|
} ? readonly unknown[] : F extends {
|
|
84
|
+
type: 'map';
|
|
85
|
+
items: infer I;
|
|
86
|
+
} ? {
|
|
87
|
+
readonly [key: string]: FieldValue<I>;
|
|
88
|
+
} : F extends {
|
|
89
|
+
type: 'map';
|
|
90
|
+
} ? Record<string, unknown> : F extends {
|
|
91
|
+
type: 'union';
|
|
92
|
+
variants: readonly (infer V)[];
|
|
93
|
+
} ? FieldValue<V> : F extends {
|
|
74
94
|
type: 'int' | 'number';
|
|
75
95
|
} ? number : F extends {
|
|
76
96
|
type: 'bool';
|
|
@@ -114,6 +134,12 @@ export declare const field: {
|
|
|
114
134
|
bool<Req extends boolean = true>(constraint: string, opts?: FieldOptions<Req>): OutField<"bool", Req>;
|
|
115
135
|
object: typeof object;
|
|
116
136
|
array: typeof array;
|
|
137
|
+
/** A field holding a JSON object whose every value has the `values` shape, under any string keys. */
|
|
138
|
+
map<const I extends FieldShape, Req extends boolean = true>(values: I, constraint?: string, opts?: FieldOptions<Req>): MapField<I, Req>;
|
|
139
|
+
/** A field holding any one of two or more alternative shapes; the handler sees their union. */
|
|
140
|
+
union<const V extends readonly [FieldShape, FieldShape, ...FieldShape[]], Req extends boolean = true>(variants: V, constraint: string, opts?: FieldOptions<Req>): UnionField<V, Req>;
|
|
141
|
+
/** A field holding any JSON value; the handler sees `unknown`. */
|
|
142
|
+
unknown<Req extends boolean = true>(constraint: string, opts?: FieldOptions<Req>): OutField<"unknown", Req>;
|
|
117
143
|
/** A string field holding one of `values`, which the handler sees as literal types. */
|
|
118
144
|
enum<const V extends string, Req extends boolean = true>(values: readonly V[], constraint: string, opts?: FieldOptions<Req>): EnumField<V, Req>;
|
|
119
145
|
/**
|
package/dist/fields.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var i=Object.defineProperty;var u=(r,
|
|
1
|
+
var i=Object.defineProperty;var u=(r,n)=>i(r,"name",{value:n,configurable:!0});function e(r,n,t={}){return{type:r,constraint:n,required:t.required??!0}}u(e,"defineField");function o(r,n,t){return typeof r=="string"?e("object",r,n??{}):{...e("object",n??"",t),children:r}}u(o,"object");function a(r,n,t){return typeof r=="string"?e("array",r,n??{}):{...e("array",n??r.constraint,t),items:r}}u(a,"array");const p={string(r,n={}){return e("string",r,n)},int(r,n={}){return e("int",r,n)},number(r,n={}){return e("number",r,n)},bool(r,n={}){return e("bool",r,n)},object:o,array:a,map(r,n,t={}){return{...e("map",n??r.constraint,t),items:r}},union(r,n,t={}){return{...e("union",n,t),variants:r}},unknown(r,n={}){return e("unknown",r,n)},enum(r,n,t={}){return{...e("enum",n,t),values:r}},file(r,n={}){return{kind:"flag",type:"file",constraint:r,required:n.required??!1,repeatable:!1}},markdown(r,n={}){return e("markdown",r,n)},path(r,n={}){return e("path",r,n)},of(r,n,t={}){return e(r,n,t)},nullable(r){return{...r,type:`${r.type} | null`}}};export{p as field};
|
package/dist/index.d.ts
CHANGED
|
@@ -10,3 +10,4 @@ export { createNodeHandler, type NodeHandlerOptions, type NodeLikeRequest, type
|
|
|
10
10
|
export { createCallerVerifier, type CallerVerifier, type FetchHandlerAuth } from './verify.js';
|
|
11
11
|
export { postReceipt, ReceiptPostError, SpendRefusedError, type LedgerCredentials, type Receipt, type ReceiptOptions, type ReceiptOutbox, type SpendCheckAnswer, type SpendPrice } from './receipts.js';
|
|
12
12
|
export { LeafError, type LeafErrorOptions, type LeafErrorQuestion } from './errors.js';
|
|
13
|
+
export { customObjectPublishFailure } from './watchable.js';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./params.js";export*from"./fields.js";export*from"./define.js";export*from"./manifest.js";import{compareManifests as m}from"./compare.js";export*from"./bundle.js";import{parseCrtrCaller as s}from"./caller.js";export*from"./serve.js";import{createNodeHandler as l}from"./node.js";import{createCallerVerifier as
|
|
1
|
+
export*from"./params.js";export*from"./fields.js";export*from"./define.js";export*from"./manifest.js";import{compareManifests as m}from"./compare.js";export*from"./bundle.js";import{parseCrtrCaller as s}from"./caller.js";export*from"./serve.js";import{createNodeHandler as l}from"./node.js";import{createCallerVerifier as u}from"./verify.js";import{postReceipt as C,ReceiptPostError as E,SpendRefusedError as R}from"./receipts.js";import{LeafError as P}from"./errors.js";import{customObjectPublishFailure as j}from"./watchable.js";export{P as LeafError,E as ReceiptPostError,R as SpendRefusedError,m as compareManifests,u as createCallerVerifier,l as createNodeHandler,j as customObjectPublishFailure,s as parseCrtrCaller,C as postReceipt};
|
package/dist/manifest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var y=Object.defineProperty;var i=(e,t)=>y(e,"name",{value:t,configurable:!0});import{validateCommandManifest as w}from"@north-light/api/command-manifest";import{kebab as f}from"./define.js";class h extends Error{static{i(this,"ManifestInvalidError")}issues;constructor(t){super(`Generated command manifest is invalid: ${t.map(r=>r.message).join("; ")}`),this.name="ManifestInvalidError",this.issues=t}}function E(e,t){const r=j(t.mountPath),a={schemaVersion:1,...e.version!==void 0?{version:e.version}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...e.timeouts!==void 0?{timeouts:e.timeouts}:{},mounts:[{parent:[],node:{...v(e.name,e.description,e.whenToUse,e.summary,void 0),rootEntry:e.rootEntry,children:Object.entries(e.commands).map(([c,m])=>p(c,m,[e.name],r))}}]},s=w(a,{transport:"http",reservedCoreNames:new Set});if(s.issues.length>0)throw new h(s.issues);return a}i(E,"buildCommandManifest");function p(e,t,r,a){const s=f(e),c=[...r,s];if(t.kind==="branch")return{...v(s,t.description,t.whenToUse,t.summary,t.tier),children:Object.entries(t.children).map(([o,n])=>p(o,n,c,a))};const m=Object.entries(t.params).map(([o,n])=>{const d=f(o);return n.kind==="stdin"?{kind:n.kind,name:d,required:n.required,constraint:n.constraint}:n.kind==="flag"&&n.type==="json"?{name:d,...n,shape:u(n.shape)}:{name:d,...n}}),l=Object.fromEntries(m.map(o=>[o.name,{in:"body"}]));return{kind:"leaf",name:s,description:t.description,whenToUse:t.whenToUse,...t.tier!==void 0?{tier:t.tier}:{},summary:t.summary,...t.group!==void 0?{group:t.group}:{},params:m,output:b(t.output),effects:t.effects,rest:{method:"POST",path:`${a}/${c.join("/")}`,...t.streaming?{streaming:!0}:{},params:l}}}i(p,"toManifestNode");function b(e){return Object.entries(e).map(([t,r])=>({name:t,...u(r),required:r.required}))}i(b,"toManifestFields");function u(e){return{type:e.type,constraint:e.constraint,...e.children!==void 0?{children:b(e.children)}:{},...e.items!==void 0?{items:u(e.items)}:{},...e.variants!==void 0?{variants:e.variants.map(u)}:{},...e.values!==void 0?{values:[...e.values]}:{}}}i(u,"toManifestShape");function v(e,t,r,a,s){return{kind:"branch",name:e,description:t,whenToUse:r,...s!==void 0?{tier:s}:{},summary:a}}i(v,"branch");function j(e){if(e===""||e==="/")return"";if(!e.startsWith("/")||e.includes("?")||e.includes("#"))throw new h([{code:"command_rest_invalid",message:"mountPath must be an absolute pathname",received:e,expected:"an absolute pathname",next:"Pass the handler mount path, such as /crtr."}]);return e.replace(/\/+$/,"")}i(j,"normalizeMountPath");export{h as ManifestInvalidError,E as buildCommandManifest};
|
package/dist/params.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type FileField } from './fields.js';
|
|
1
|
+
import { type FileField, type FieldValue, type OutField } from './fields.js';
|
|
2
2
|
/** How `param.path` hands the caller's file to the handler. */
|
|
3
3
|
export type Encoding = 'text' | 'base64';
|
|
4
4
|
/** A string flag, as returned by `param.string`. */
|
|
@@ -66,6 +66,18 @@ export interface FlagPathParam<Req extends boolean, Enc extends Encoding> {
|
|
|
66
66
|
readonly required: Req;
|
|
67
67
|
readonly repeatable: false;
|
|
68
68
|
}
|
|
69
|
+
/** A flag carrying one JSON value of a declared shape, as returned by `param.json`. Never repeatable, never defaulted. */
|
|
70
|
+
export interface FlagJsonParam<S extends OutField<string, boolean>, Req extends boolean> {
|
|
71
|
+
readonly kind: 'flag';
|
|
72
|
+
readonly type: 'json';
|
|
73
|
+
/** What the value must be, written for the agent supplying it. */
|
|
74
|
+
readonly constraint: string;
|
|
75
|
+
/** The shape of the value. Its own `required` is ignored. */
|
|
76
|
+
readonly shape: S;
|
|
77
|
+
/** True when the command cannot run without it. */
|
|
78
|
+
readonly required: Req;
|
|
79
|
+
readonly repeatable: false;
|
|
80
|
+
}
|
|
69
81
|
/** The one positional argument a leaf may take, as returned by `param.positional`. */
|
|
70
82
|
export interface PositionalParam<Req extends boolean, Rep extends boolean> {
|
|
71
83
|
readonly kind: 'positional';
|
|
@@ -87,8 +99,11 @@ export interface StdinParam<Req extends boolean> {
|
|
|
87
99
|
readonly repeatable: false;
|
|
88
100
|
}
|
|
89
101
|
/** Any parameter descriptor a `param.*` builder returns. */
|
|
90
|
-
export type AnyParam = FlagStringParam<boolean, boolean> | FlagIntParam<boolean, boolean> | FlagBoolParam<boolean> | FlagEnumParam<string, boolean, boolean> | FlagPathParam<boolean, Encoding> | FileField<boolean> | PositionalParam<boolean, boolean> | StdinParam<boolean>;
|
|
102
|
+
export type AnyParam = FlagStringParam<boolean, boolean> | FlagIntParam<boolean, boolean> | FlagBoolParam<boolean> | FlagEnumParam<string, boolean, boolean> | FlagPathParam<boolean, Encoding> | FlagJsonParam<OutField<string, boolean>, boolean> | FileField<boolean> | PositionalParam<boolean, boolean> | StdinParam<boolean>;
|
|
91
103
|
type Scalar<P> = P extends {
|
|
104
|
+
type: 'json';
|
|
105
|
+
shape: infer S;
|
|
106
|
+
} ? FieldValue<S> : P extends {
|
|
92
107
|
type: 'enum';
|
|
93
108
|
choices: readonly (infer C)[];
|
|
94
109
|
} ? C : P extends {
|
|
@@ -140,6 +155,13 @@ export declare const param: {
|
|
|
140
155
|
required?: Req;
|
|
141
156
|
default?: boolean;
|
|
142
157
|
}): FlagBoolParam<Req>;
|
|
158
|
+
/**
|
|
159
|
+
* A flag carrying one JSON value of `shape`, checked against it by crtr while parsing the
|
|
160
|
+
* command line and by the server on arrival. The handler sees the parsed value, typed from the shape.
|
|
161
|
+
*/
|
|
162
|
+
json<const S extends OutField<string, boolean>, Req extends boolean = false>(shape: S, constraint: string, opts?: {
|
|
163
|
+
required?: Req;
|
|
164
|
+
}): FlagJsonParam<S, Req>;
|
|
143
165
|
/**
|
|
144
166
|
* A flag whose value is the contents of a local file the crtr caller names, never the path
|
|
145
167
|
* string. `text` decodes UTF-8; `base64` yields a `Uint8Array`.
|
package/dist/params.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{field as l}from"./fields.js";const i={string(r,e={}){return{kind:"flag",type:"string",constraint:r,required:e.required??!1,repeatable:e.repeatable??!1,...e.default!==void 0?{default:e.default}:{}}},enum(r,e,a={}){return{kind:"flag",type:"enum",choices:r,constraint:e,required:a.required??!1,repeatable:a.repeatable??!1,...a.default!==void 0?{default:a.default}:{}}},int(r,e={}){return{kind:"flag",type:"int",constraint:r,required:e.required??!1,repeatable:e.repeatable??!1,...e.default!==void 0?{default:e.default}:{}}},bool(r,e={}){return{kind:"flag",type:"bool",constraint:r,required:e.required??!1,repeatable:!1,...e.default!==void 0?{default:e.default}:{}}},path(r,e={}){return{kind:"flag",type:"path",constraint:r,required:e.required??!1,repeatable:!1,encoding:e.encoding??"text"}},file:l.file,positional(r,e={}){return{kind:"positional",type:"string",constraint:r,required:e.required??!1,repeatable:e.repeatable??!1}},stdin(r,e={}){return{kind:"stdin",constraint:r,required:e.required??!1,repeatable:!1}}};export{i as param};
|
|
1
|
+
import{field as l}from"./fields.js";const i={string(r,e={}){return{kind:"flag",type:"string",constraint:r,required:e.required??!1,repeatable:e.repeatable??!1,...e.default!==void 0?{default:e.default}:{}}},enum(r,e,a={}){return{kind:"flag",type:"enum",choices:r,constraint:e,required:a.required??!1,repeatable:a.repeatable??!1,...a.default!==void 0?{default:a.default}:{}}},int(r,e={}){return{kind:"flag",type:"int",constraint:r,required:e.required??!1,repeatable:e.repeatable??!1,...e.default!==void 0?{default:e.default}:{}}},bool(r,e={}){return{kind:"flag",type:"bool",constraint:r,required:e.required??!1,repeatable:!1,...e.default!==void 0?{default:e.default}:{}}},json(r,e,a={}){return{kind:"flag",type:"json",constraint:e,shape:r,required:a.required??!1,repeatable:!1}},path(r,e={}){return{kind:"flag",type:"path",constraint:r,required:e.required??!1,repeatable:!1,encoding:e.encoding??"text"}},file:l.file,positional(r,e={}){return{kind:"positional",type:"string",constraint:r,required:e.required??!1,repeatable:e.repeatable??!1}},stdin(r,e={}){return{kind:"stdin",constraint:r,required:e.required??!1,repeatable:!1}}};export{i as param};
|
package/dist/serve.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var s=(n,e)=>Y(n,"name",{value:e,configurable:!0});import{approvalFor as ee}from"./approval.js";import{requestSpendCheck as ne}from"./receipts.js";import{validateDeclaredResult as te}from"@north-light/api/command-manifest";import{errorResponse as A,LeafError as O,leafErrorResponse as L,storedAnswerHeaders as re}from"./errors.js";import{buildCommandManifest as ie}from"./manifest.js";import{buildBundle as oe}from"./bundle.js";import{parseCrtrCaller as de}from"./caller.js";import{createCallerVerifier as ae,normalizeProviderId as se,scopeMissing as ce}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:se(e.auth),t=Array.isArray(n)||n.version!==void 0,r=le(Array.isArray(n)?n:[n],Array.isArray(n),i),d=r[0].plugin.name;for(const f of r)for(const g of f.commands.values())if(g.leaf.sideEffect&&e.requests===void 0)throw new Error(`createFetchHandler needs requests for side-effect leaf ${g.path.join(" ")}`);const u=e.auth===void 0?void 0:ae(e.auth);if(u!==void 0){for(const f of r)for(const g of f.commands.values())if(g.scope===void 0)throw new Error(`createFetchHandler auth needs a group on every leaf; ${g.path.join(" ")} has none`)}const a=new Map,k=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 w=s(async(f,g,q)=>{const c=`${g.version}\0${q}`;let l=a.get(c);if(l===void 0){const I=await oe(g.plugin,{mountPath:q,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:I.tar,etag:I.etag},a.set(c,l)}const m={ETag:l.etag};return f.headers.get("if-none-match")===l.etag?new Response(null,{status:304,headers:m}):new Response(new Uint8Array(l.tar).buffer,{headers:{...m,"Content-Type":"application/x-tar"}})},"archiveResponse");return async f=>{if(f.method!=="POST"&&e.token!==void 0&&!X(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 g=new URL(f.url).pathname;if(f.method==="GET"){if(!t)return w(f,h,k??D(g));const p=J(g),$=p[p.length-1],R=k??D(`/${p.slice(0,-1).join("/")}`);if($==="versions")return Response.json({latest:h.version,supported:r.map(v=>v.version)});const z=$===void 0?null:V.exec($),b=z===null?void 0:r.find(v=>v.version===Number(z[1]));return b===void 0?P():w(f,b,`${R}/v${b.version}`)}if(f.method!=="POST")return P();const q=performance.now();let c,l;const m=[];let I=[],F=!1,B=!1;const E=s(p=>{if(l!==void 0)try{e.onAnswer?.({...c===void 0?{}:{sub:c.sub,grantee:c.grantee,initiatingApp:c.initiatingApp,act:c.act,jti:c.jti,requestId:c.requestId,...c.runId===void 0?{}:{runId:c.runId}},...c===void 0&&y!==null&&y!==""?{requestId:y}:{},tool:l.path.slice(1).join(" "),status:p.status,durationMs:performance.now()-q,...m.length===0?{}:{receiptId:m[0].receipt_id},...m.length>1?{receiptIds:m.map($=>$.receipt_id)}:{},replayed:B})}catch{}return p},"answer");let y=f.headers.get("crtr-request-id");try{if(l=t?pe(r,g):me(h.commands,g),e.token!==void 0&&!X(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 p=u===void 0?void 0:await u(f);if(l===void 0)return P();if(p!==void 0&&!p.scope.includes(l.scope)){c=Object.freeze({...p,requestId:y??"",...f.headers.get("crtr-run-id")?{runId:f.headers.get("crtr-run-id")}:{}});const o=l.leaf.group,x=i===void 0&&o!==void 0?p.scope.find(j=>j.endsWith(`:${o}`)&&j.length>o.length+1)?.slice(0,-(o.length+1)):void 0;throw ce(l.scope,x)}if(p!==void 0){if(y===null||y==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=f.headers.get("crtr-run-id"),x=de(f.headers.get("crtr-caller"));c=Object.freeze({...p,requestId:y,...o!==null&&o!==""?{runId:o}:{},...Object.keys(x).length>0?{crtr:Object.freeze(x)}:{}})}const $=await we(f,l.manifest,p!==void 0);if(l.leaf.sideEffect){if(y===null||y==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=c===void 0?null:{sub:c.sub,grantee:c.grantee};if(!await e.requests.record(y,o)){B=!0;const j=await fe(e.requests,y,o,l.plugin.timeouts?.requestMs??3e4);if(j!==!0){const _=j.headers.get("Crtr-Receipt");if(_!==null)try{const C=JSON.parse(_);m.push(...Array.isArray(C)?C:[C])}catch{}return E(j)}B=!1}F=!0}const R=l,z={request:f,...c!==void 0?{caller:c}:{},approval:ee(f),meter(o){if(c===void 0)throw new Error("ctx.meter needs an authenticated caller");if(m.some(S=>S.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 x=o.receiptId??c.requestId;if(m.some(S=>S.receipt_id===x))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${x} is taken`);const j=R.path.slice(1).join(" "),_=I.find(S=>S.mode==="unit"&&S.unit===o.unit),C=o.usdEquivalent??(_?.usd_per_unit!=null?o.units*_.usd_per_unit:0),G={receipt_id:x,provider:e.receipts.provider,tool:j,sub:c.sub,grantee:c.grantee,payer:c.payer,units:o.units,unit:o.unit,usd_equivalent:C,request_id:c.requestId,...c.runId!==void 0?{run_id:c.runId}:{},time:new Date().toISOString()};return m.push(G),G},async checkSpend(){if(c===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 ne(e.auth.issuer,o,R.path.slice(1).join(" "),e.receipts.ledger)).prices,{prices:I}}};let b,v;try{const o=await l.leaf.run($,z);b=l.leaf.streaming?await ke(o,e.onError,l.path):be(o,l.manifest)}catch(o){o instanceof O?(b=L(o),v=o.headers):(M(e.onError,o,l.path),b=H(o))}if(F&&b.status===403&&await ue(b))return await e.requests.delete(y),E(W(b,m));try{if(F)await e.requests.store(y,{status:b.status,body:await b.clone().text(),...v!==void 0?{headers:{...v}}:{},...m.length>0?{receipt:m[0]}:{},...m.length>1?{receipts:[...m]}:{}});else if(m.length>0){if(e.receipts===void 0)throw new Error(`No receipt outbox for ${R.path.join(" ")}`);for(const o of m)await e.receipts.outbox.save(o)}}catch(o){return M(e.onError,o,l.path,m),E(H(o))}return E(W(b,m))}catch(p){return p instanceof O?E(L(p)):(M(e.onError,p,l?.path??[]),E(H(p)))}}}s(Oe,"createFetchHandler");function H(n){return A(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(H,"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 ue(n){try{const e=await n.clone().json();return U(e)&&U(e.error)&&e.error.code==="approval_required"}catch{return!1}}s(ue,"isApprovalRequired");async function fe(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=re(r.answer.headers);d.set("Content-Type","application/json");const u=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return u.length>0&&d.set("Crtr-Receipt",Z(u)),new Response(r.answer.body,{status:r.answer.status,headers:d})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return H(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(fe,"replay");function le(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 u=d.version??1;if(r.has(u))throw new Error(`createFetchHandler got two definitions of ${t} major ${u}`);r.set(u,{version:u,plugin:d,commands:he(d,i)})}return[...r.values()].sort((d,u)=>d.version-u.version)}s(le,"servedMajors");function he(n,e){const t=ie(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(he,"commandMap");function K(n,e,i,t,r,d){const u=Object.entries(e);if(n.length!==u.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[a,[k,h]]of u.entries()){const w=n[a];if(w===void 0||w.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${k}`);const f=[...i,w.name];if(w.kind==="branch"&&h.kind==="branch"){K(w.children,h.children,f,t,r,d);continue}if(w.kind==="leaf"&&h.kind==="leaf"){r.set(f.join("/"),{path:f,leaf:h,plugin:t,manifest:w,...h.group!==void 0?{scope:`${d??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${k}`)}}s(K,"collectCommands");function me(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(me,"findCommand");function pe(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 u=n.find(a=>a.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(u!==void 0)return u}}s(pe,"findVersionedCommand");function J(n){return n.split("/").filter(e=>e.length>0)}s(J,"pathSegments");async function we(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const a=JSON.parse(t);if(!U(a))throw new Error("not an object");r=a}catch{throw N("Request body must be a JSON object.",i?"body":void 0,i,t)}const d=new Map(e.params.map(a=>[a.name,a]));for(const a of Object.keys(r))if(!d.has(a))throw i?N(`Unknown parameter ${a}.`,a,!0,r[a]):new O({code:"unknown_parameter",message:`Unknown parameter ${a}.`,field:a});const u={};for(const a of e.params){if(!Object.hasOwn(r,a.name)){if(a.required)throw N(`Missing required parameter ${a.name}.`,a.name,i,null);continue}const k=r[a.name],h=ge(k,a);if(h===void 0)throw N(`Invalid value for parameter ${a.name}.`,a.name,i,k);u[Ee(a.name)]=h}return u}s(we,"decodeInput");function ge(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(ge,"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"?ye(n):n}}s(Q,"decodeScalar");function ye(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(ye,"decodeBase64");function be(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw T("result")}if(!U(t))throw T("result");const r=te(e.output,t);if(r!==null)throw T(r.field,r.receivedType);for(const d of Object.keys(t))if(!e.output.some(u=>u.name===d))throw T(d);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(be,"resultResponse");async function ke(n,e,i){if(!xe(n))throw T("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,d=await t.next();let u=d.done,a=u?void 0:r.encode(`${JSON.stringify(d.value)}
|
|
2
|
-
`);const
|
|
3
|
-
`))}catch(
|
|
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 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 o=new Map,g=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,y,z)=>{const u=`${y.version}\0${z}`;let l=o.get(u);if(l===void 0){const I=await de(y.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 y=new URL(f.url).pathname;if(f.method==="GET"){if(!t)return m(f,h,g??D(y));const w=J(y),$=w[w.length-1],R=g??D(`/${w.slice(0,-1).join("/")}`);if($==="versions")return Response.json({latest:h.version,supported:r.map(v=>v.version)});const H=$===void 0?null:V.exec($),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&&b!==null&&b!==""?{requestId:b}:{},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($=>$.receipt_id)}:{},replayed:B})}catch{}return w},"answer");let b=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 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:b??"",...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(j=>j.endsWith(`:${a}`)&&j.length>a.length+1)?.slice(0,-(a.length+1)):void 0;throw fe(l.scope,x)}if(w!==void 0){if(b===null||b==="")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:b,...a!==null&&a!==""?{runId:a}:{},...Object.keys(x).length>0?{crtr:Object.freeze(x)}:{}})}const $=await ye(f,l.manifest,w!==void 0);if(l.leaf.sideEffect){if(b===null||b==="")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(b,a)){B=!0;const j=await he(e.requests,b,a,l.plugin.timeouts?.requestMs??3e4);if(j!==!0){const _=j.headers.get("Crtr-Receipt");if(_!==null)try{const C=JSON.parse(_);p.push(...Array.isArray(C)?C:[C])}catch{}return E(j)}B=!1}F=!0}const R=l,H={request:f,...u!==void 0?{caller:u}:{},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 j=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:j,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($,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(b),E(W(k,p));try{if(F)await e.requests.store(b,{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,[g,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 ${g}`);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 ${g}`)}}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 g=r[o.name];if(o.kind==="flag"&&o.type==="json"){const m=ie(o.shape,g,o.name);if(m!==null)throw q(`Invalid value for ${m.path}: expected ${m.expected}, got ${m.receivedType}.`,m.path,i,g);c[X(o.name)]=g;continue}const h=be(g,o);if(h===void 0)throw q(`Invalid value for parameter ${o.name}.`,o.name,i,g);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(!je(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 g=new ReadableStream({async pull(h){if(o!==void 0){h.enqueue(o),o=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){N(e,m,i),h.error(m)}},async cancel(h){await t.return?.(h)}});return new Response(g,{headers:{"Content-Type":"application/x-ndjson"}})}s(xe,"streamResponse");function N(n,e,i,t=[]){try{t.length>1?n?.(e,i,t[0],t):n?.(e,i,t[0])}catch{}}s(N,"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 P(){return A(404,{code:"no_such_command",message:"No command matches this request."})}s(P,"noSuchCommand");function D(n){return n==="/"?"":n.replace(/\/+$/,"")}s(D,"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 d=0;d<Math.min(i.length,t.length);d+=1)r|=i[d]^t[d];return r===0}s(Y,"constantTimeEqual");function U(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}s(U,"isRecord");function je(n){return typeof n=="object"&&n!==null&&Symbol.asyncIterator in n}s(je,"isAsyncIterable");export{Oe as createFetchHandler};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a provider should treat a custom-object publish the daemon refused: `'drop'` when retrying cannot
|
|
3
|
+
* help (the event is malformed or its object does not exist), `'retry'` when a later attempt can succeed.
|
|
4
|
+
*
|
|
5
|
+
* Pass `{ status, code }` from the SDK's `APIError`, or `undefined` for any other exception (a network
|
|
6
|
+
* failure is retried). `unknown_event` retries even though the daemon answers it with HTTP 400: it means
|
|
7
|
+
* the daemon has not yet registered the provider's event catalog, which clears on its own. Expiry and
|
|
8
|
+
* backoff timing stay with the provider.
|
|
9
|
+
*/
|
|
10
|
+
export declare function customObjectPublishFailure(failure: {
|
|
11
|
+
status: number;
|
|
12
|
+
code: string;
|
|
13
|
+
} | undefined): 'drop' | 'retry';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var r=Object.defineProperty;var n=(t,s)=>r(t,"name",{value:s,configurable:!0});function o(t){return!t||t.code==="unknown_event"?"retry":t.status===400||t.status===404||t.status===422?"drop":"retry"}n(o,"customObjectPublishFailure");export{o as customObjectPublishFailure};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.520",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
".": {
|
|
9
9
|
"types": "./dist/index.d.ts",
|
|
10
10
|
"import": "./dist/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./client": {
|
|
13
|
+
"types": "./dist/client/index.d.ts",
|
|
14
|
+
"import": "./dist/client/index.js"
|
|
11
15
|
}
|
|
12
16
|
},
|
|
13
17
|
"files": [
|
|
@@ -23,8 +27,8 @@
|
|
|
23
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
24
28
|
},
|
|
25
29
|
"dependencies": {
|
|
26
|
-
"@north-light/api": "0.3.
|
|
27
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.520",
|
|
31
|
+
"@north-light/identity": "0.3.520"
|
|
28
32
|
},
|
|
29
33
|
"license": "UNLICENSED",
|
|
30
34
|
"publishConfig": {
|