@com55/node-red-ai-access 0.2.0-beta.3 → 0.2.0-beta.4
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/CHANGELOG.md +10 -0
- package/ai-access.html +1 -1
- package/dist/plugin.cjs +3 -32
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
6
6
|
and this project adheres to
|
|
7
7
|
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
8
8
|
|
|
9
|
+
## [0.2.0-beta.4] - 2026-10-28
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- Removed dark-mode support from the `/ai-access` dashboard and the OAuth
|
|
14
|
+
consent / sign-in pages. They always use the light theme
|
|
15
|
+
(`color-scheme: light`), even when the OS prefers dark. The beta.3 dark
|
|
16
|
+
variant left some components unreadable (e.g. removed-node diff rows in
|
|
17
|
+
proposal cards).
|
|
18
|
+
|
|
9
19
|
## [0.2.0-beta.3] - 2026-10-28
|
|
10
20
|
|
|
11
21
|
### Breaking
|
package/ai-access.html
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
}
|
|
15
15
|
window.__com55AiAccessSidebarLoading = true;
|
|
16
16
|
|
|
17
|
-
var EDITOR_SIDEBAR_ASSET_VERSION = '0.2.0-beta.
|
|
17
|
+
var EDITOR_SIDEBAR_ASSET_VERSION = '0.2.0-beta.4';
|
|
18
18
|
var root = (RED.settings.httpAdminRoot || '/').replace(/\/$/, '');
|
|
19
19
|
var src =
|
|
20
20
|
(root || '') +
|
package/dist/plugin.cjs
CHANGED
|
@@ -6,7 +6,7 @@ ${t}`))return{text:t,summary:t};let r=t.split(/\n(?=#{1,3}\s+)/),o="",s,i;for(le
|
|
|
6
6
|
`;break;case"r":r="\r";break;case"t":r=" ";break;case"b":r="\b";break;case"f":r="\f";break;case"v":r="\v";break;case"0":r="\0";break;case"\\":r="\\";break;case"'":r="'";break;case'"':r='"';break;case"/":r="/";break;default:r=n;break}return{char:r,next:t+1}}function El(e){return e==="_DEFAULT_"?"":e}function sr(e){let t=e.trimStart();if(t.startsWith("'")||t.startsWith('"')){let r=t[0],o=1,s="";for(;o<t.length;){let i=t[o];if(i==="\\"&&o+1<t.length){let d=Cl(t,o+1);s+=d.char,o=d.next;continue}if(i===r)break;s+=i,o+=1}return El(s)}if(t.startsWith("[")){let r=Us(t);if(!r)return;let o=r.slice(1,-1).trim();if(!o)return[];let s=[],i=0;for(;i<o.length;){for(;i<o.length&&/[\s,]/.test(o.charAt(i));)i+=1;if(i>=o.length)break;let d=o.slice(i),l=sr(d);s.push(l);let c=co(d);i+=c>0?c:1}return s}if(t.startsWith("{")){let r=xn(t);if(!r)return;let o=r.slice(1,-1);if(!o.trim())return{};let s={},i=0;for(;i<o.length;){for(;i<o.length&&/[\s,]/.test(o.charAt(i));)i+=1;if(i>=o.length)break;let d;if(o[i]==="'"||o[i]==='"'){let c=sr(o.slice(i));d=typeof c=="string"?c:"",i+=co(o.slice(i))}else{let c=/^[a-zA-Z_$][\w$]*/.exec(o.slice(i));if(!c)break;d=c[0],i+=d.length}for(;i<o.length&&/\s/.test(o.charAt(i));)i+=1;if(o[i]!==":")break;for(i+=1;i<o.length&&/\s/.test(o.charAt(i));)i+=1;let l=o.slice(i);s[d]=sr(l),i+=co(l)}return s}let n=/^-?\d+(?:\.\d+)?/.exec(t);if(n)return Number(n[0]);if(t.startsWith("true"))return!0;if(t.startsWith("false"))return!1;if(t.startsWith("null"))return null}function co(e){let t=e.trimStart(),n=e.length-t.length;if(t.startsWith("'")||t.startsWith('"')){let o=t[0],s=1;for(;s<t.length;){if(t[s]==="\\"&&s+1<t.length){s+=2;continue}if(t[s]===o)return n+s+1;s+=1}return n+t.length}if(t.startsWith("[")){let o=Us(t);return n+(o?.length??1)}if(t.startsWith("{")){let o=xn(t);return n+(o?.length??1)}let r=/^(?:-?\d+(?:\.\d+)?|true|false|null)/.exec(t);return r?n+r[0].length:n+1}function Us(e){if(!e.startsWith("["))return null;let t=0,n=null,r=!1;for(let o=0;o<e.length;o++){let s=e[o];if(n){if(r){r=!1;continue}if(s==="\\"){r=!0;continue}s===n&&(n=null);continue}if(s==="'"||s==='"'){n=s;continue}if(s==="[")t+=1;else if(s==="]"&&(t-=1,t===0))return e.slice(0,o+1)}return null}function Il(e){return sr(e)}function Nl(e,t){for(let n of e)if(n.types.includes(t)){let r=n.id.includes("/")||n.types.length===1?n.id:`${n.module}/${t}`;return{set:n,setId:r}}return null}function yo(e,t){let n=e.toLowerCase();return t.includes(e)?e:t.find(r=>r.toLowerCase()===n)}async function ct(e,t,n={}){if(!t||typeof t!="string")throw new y("Missing node type","missing_node_type");let r=n.includeHelp!==!1;if(fo(t)){let l={type:t,module:"node-red",category:"config",inputs:0,outputs:0,defaults:null};return r&&(l.help={summary:"Built-in structural Node-RED type (not a palette node)."}),l}let o=await e.listNodeSets(),s=o.flatMap(l=>l.types),i=Nl(o,t);if(!i){let l=yo(t,s);throw l&&l!==t?new y(`Node type '${t}' was not found \u2014 did you mean '${l}'? Types are case-sensitive.`,"node_type_not_found",{statusCode:404,details:{type:t,didYouMean:l,caseSensitive:!0,nearest:[l]}}):new y(`Node type '${t}' was not found`,"node_type_not_found",{statusCode:404,details:{type:t,nearest:mo(t,s,5)}})}let d={type:t,module:i.set.module,setId:i.setId,inputs:1,outputs:1,defaults:null};if(i.set.version&&(d.version=i.set.version),typeof i.set.enabled=="boolean"&&(d.enabled=i.set.enabled),typeof e.getNodeConfigHtml=="function")try{let l=await e.getNodeConfigHtml(i.setId)??await e.getNodeConfigHtml(`${i.set.module}/${t}`)??await e.getNodeConfigHtml(t);if(l){let c=Rl(l,t);c&&(c.category&&(d.category=c.category),c.color&&(d.color=c.color),d.inputs=c.inputs??d.inputs,d.outputs=c.outputs??d.outputs,c.defaults&&Object.keys(c.defaults).length>0?d.defaults=c.defaults:d.defaults=null,c.requiredConfigNodeTypes&&(d.requiredConfigNodeTypes=c.requiredConfigNodeTypes),r&&c.help&&(d.help=_l(c.help)))}}catch{}return d}async function Bs(e,t){let{allNames:n}=await go(e),r=new Set(n),o=new Set,s=a(l=>{let c=Je(l,"node.type");if(o.has(c)||fo(c)){o.add(c);return}if(o.add(c),r.has(c))return;let u=yo(c,n);throw u&&u!==c?new y(`Unknown node type '${c}' \u2014 did you mean '${u}'? Types are case-sensitive.`,"unknown_node_type",{details:{type:c,didYouMean:u,caseSensitive:!0,nearest:[u]}}):new y(`Unknown node type '${c}'. Call node-types / palette search; ask the user to install via Manage palette, then recheck.`,"unknown_node_type",{details:{type:c,nearest:mo(c,n,5)}})},"checkType"),i=a(l=>{if(!l||typeof l!="object"||Array.isArray(l))return;let c=l;typeof c.id=="string"&&c.id.length>0&&s(c.type)},"visitNodeOrConfig");a(l=>{if(!l||typeof l!="object"||Array.isArray(l))return;let c=l;if(c.type!==void 0&&s(c.type),Array.isArray(c.nodes))for(let u of c.nodes)i(u);if(Array.isArray(c.configs))for(let u of c.configs)i(u)},"visitTab")(t)}async function qs(e,t){let n=Je(t,"node.type");if(fo(n))return;let{allNames:r}=await go(e);if(r.includes(n))return;let o=yo(n,r);throw o&&o!==n?new y(`Unknown node type '${n}' \u2014 did you mean '${o}'? Types are case-sensitive.`,"unknown_node_type",{details:{type:n,didYouMean:o,caseSensitive:!0,nearest:[o]}}):new y(`Unknown node type '${n}'. Call node-types / palette search; ask the user to install via Manage palette, then recheck.`,"unknown_node_type",{details:{type:n,nearest:mo(n,r,5)}})}async function Fl(e,t){let n=new Headers({Accept:"application/json"});t&&n.set("If-None-Match",t);let r=await fetch(e,{headers:n}),o=r.headers.get("etag")??void 0;if(r.status===304)return{status:304,...o?{etag:o}:{}};if(!r.ok)return{status:r.status,body:null,...o?{etag:o}:{}};let s=await r.json();return{status:r.status,body:s,...o?{etag:o}:{}}}async function Ol(e,t){let n=Date.now();if(ke&&n-ke.fetchedAt<gl)return ke.body;let r=ke?.etag,o=await e(t,r);if(o.status===304&&ke)return ke={...ke,fetchedAt:n,...o.etag?{etag:o.etag}:{}},ke.body;if(!o.body||!Array.isArray(o.body.modules)){if(ke)return ke.body;throw new y("Node-RED catalogue unavailable","catalogue_unavailable",{statusCode:502})}return ke={fetchedAt:n,body:o.body,...o.etag?{etag:o.etag}:{}},o.body}async function ar(e,t,n={}){let r=t.trim();if(!r)throw new y("q query parameter is required","missing_query");let o=n.limit??fl,s=n.catalogueUrl??hl,i=n.catalogueFetcher??Fl,d=await Ol(i,s),l=Array.isArray(d.modules)?d.modules:[],c=await e.listNodeSets(),u=new Set(c.flatMap(g=>{let x=[g.module,g.id];return g.id.includes("/")&&x.push(g.id.split("/")[0]??g.module),x.map(S=>S.toLowerCase())})),p=r.toLowerCase(),f=[];for(let g of l){let x=g.id.toLowerCase(),S=(g.keywords??[]).map(ot=>String(ot).toLowerCase()),E=(g.description??"").toLowerCase(),I=$l(p,x,S,E);if(I<=0)continue;let N={module:g.id,installed:u.has(x)};typeof g.description=="string"&&(N.description=g.description),typeof g.version=="string"&&(N.version=g.version),typeof g.updated_at=="string"&&(N.updated=g.updated_at),typeof g.downloads=="number"&&(N.downloads=g.downloads),typeof g.url=="string"&&(N.link=g.url),f.push({item:N,score:I})}f.sort((g,x)=>x.score-g.score||(x.item.downloads??0)-(g.item.downloads??0)||g.item.module.localeCompare(x.item.module));let m=f.length,h=m>o;return{q:r,modules:f.slice(0,o).map(g=>g.item),total:m,truncated:h,hint:ml}}function $l(e,t,n,r){if(!e)return 0;if(t===e||t===`node-red-contrib-${e}`||t===`node-red-node-${e}`)return 1e4;let o=0;t.startsWith(`node-red-contrib-${e}`)||t.startsWith(`node-red-node-${e}`)?o+=500:t.startsWith(e)?o+=80:t.includes(e)&&(o+=60);for(let s of n)s===e?o+=50:s.startsWith(e)||e.startsWith(s)?o+=35:s.includes(e)&&(o+=25);return r.includes(e)&&(o+=10),o}var Ms,ul,pl,fl,ml,hl,gl,yl,vl,uo,Is,po,ke,ut=U(()=>{"use strict";Ms=require("module");K();ul=new Set(["tab","subflow","group","junction"]),pl=100,fl=30,ml="Recommend only \u2014 ask the user to install via Manage palette, then recheck node-types. This API never installs. Core Node-RED nodes (module node-red) are not listed in the public catalogue; use node-types for installed core types.",hl="https://catalogue.nodered.org/catalogue.json",gl=3600*1e3,yl=["inject","debug","function","template","comment","change","switch","delay","trigger","link in","link out","link call","mqtt in","mqtt out","http in","http response","http request","websocket in","websocket out","tcp in","tcp out","udp in","udp out","catch","status","complete","join","split","sort","batch","csv","html","json","xml","yaml","file","file in","watch","exec","range","rbe"];a(fo,"isStructuralNodeType");a(Je,"requireNodeTypeName");a(wl,"editDistance");a(bl,"sharedPrefixLength");vl=new Set(["unknown","tab","subflow","group"]);a(kl,"nearestDistanceCutoff");a(mo,"nearestNodeTypes");a(Al,"trimTrailingSlash");a(Ds,"createPluginRequire");a(xl,"isRuntimeSettingsAvailable");a(js,"normalizeNodeSet");a(ho,"createStaticNodeTypesAdapter");uo=class{static{a(this,"HttpNodeTypesAdapter")}baseUrl;accessToken;fetchImpl;constructor(t){this.baseUrl=Al(t.baseUrl),this.accessToken=t.accessToken,this.fetchImpl=t.fetch??globalThis.fetch.bind(globalThis)}headers(t){let n=new Headers;return n.set("Accept",t),this.accessToken&&n.set("Authorization",`Bearer ${this.accessToken}`),n}async listNodeSets(){let t=await this.fetchImpl(`${this.baseUrl}/nodes`,{headers:this.headers("application/json")});if(!t.ok)throw new Error(`Admin API GET /nodes failed (${t.status})`);let n=await t.json();if(!Array.isArray(n))throw new Error("Admin API GET /nodes returned non-array JSON");let r=[];for(let o of n){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=js(o);s&&r.push(s)}return r}async getNodeConfigHtml(t,n){let r=t.split("/").map(i=>encodeURIComponent(i)).join("/"),o=n?`?lang=${encodeURIComponent(n)}`:"",s=await this.fetchImpl(`${this.baseUrl}/nodes/${r}${o}`,{headers:this.headers("text/html")});return s.status===404||!s.ok?null:s.text()}},Is={user:null,req:null},po=class{constructor(t){this.nodes=t}static{a(this,"RedNodeTypesAdapter")}async listNodeSets(){if(typeof this.nodes.getNodeList!="function")return[];let t,n=this.nodes.getNodeList;try{t=await Promise.resolve(n(Is))}catch{try{t=await Promise.resolve(n())}catch{return[]}}if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=js(o);s&&r.push(s)}return r}async getNodeConfigHtml(t,n){if(typeof this.nodes.getNodeConfig!="function")return null;try{let r=await Promise.resolve(this.nodes.getNodeConfig({id:t,lang:n??"en-US",...Is}));if(typeof r=="string"&&r.length>0)return r}catch{}try{let r=await Promise.resolve(this.nodes.getNodeConfig(t,n));return typeof r=="string"&&r.length>0?r:null}catch{return null}}};a(Hs,"createNodeTypesAdapter");a(go,"flattenInstalledTypes");a(Sl,"matchesQuery");a(ir,"listNodeTypes");a(Tl,"extractHelpScriptBody");a(Ns,"removeHtmlBlocks");a(Pl,"stripHelpText");a(Rl,"parseRegisterTypeFromHtml");a(Fs,"parseRegisterTypeAt");a(_l,"splitHelpSections");a(xn,"extractBalancedObject");a(Os,"matchStringProp");a($s,"matchNumberProp");a(Ll,"parseDefaultsBlock");a(Cl,"unescapeJsStringEscape");a(El,"normalizeDefaultValue");a(sr,"parseJsLiteral");a(co,"measureJsLiteralLength");a(Us,"extractBalancedArray");a(Il,"parseLooseValue");a(Nl,"findSetForType");a(yo,"findCaseInsensitiveType");a(ct,"getNodeTypeDetail");a(Bs,"assertKnownNodeTypes");a(qs,"assertKnownNodeType");ke=null;a(Fl,"defaultCatalogueFetcher");a(Ol,"loadCatalogue");a(ar,"searchPalette");a($l,"paletteMatchScore")});function Ke(e){if(e.length===0)return;let t=e[0];if(!t)return;let n=e.map(s=>{let i={...s};return delete i.statusCode,i});if(e.length>1)throw new y(`${e.length} validation errors`,"validation_failed",{statusCode:400,details:{errors:n,errorCount:e.length}});let r={errors:n};for(let[s,i]of Object.entries(t))s==="code"||s==="error"||s==="errors"||s==="statusCode"||i!==void 0&&(r[s]=i);let o=typeof t.statusCode=="number"?t.statusCode:400;throw new y(t.error,t.code,{statusCode:o,details:r})}function wo(e,t="payload.flow"){let n=new Map;for(let o of e)for(let s of o){if(!s||typeof s!="object"||Array.isArray(s))continue;let i=s.id;typeof i=="string"&&i.length>0&&n.set(i,(n.get(i)??0)+1)}let r=[];for(let[o,s]of n)s>1&&r.push({code:"duplicate_node_id",error:`Node id '${o}' appears ${s} times in ${t}; node ids must be unique`,nodeId:o,count:s});return r}function Ml(e){let t=typeof e.label=="string"&&e.label?` '${e.label}'`:"";return e.type==="tab"?`tab${t||` '${e.id}'`}`:e.type==="subflow"?`subflow${t||` '${e.id}'`}`:typeof e.z=="string"&&e.z?`${e.type} node on '${e.z}'`:`global ${e.type} config node`}function zs(e,t,n){let r=new Map;for(let i of n)!i||typeof i.id!="string"||i.id===t||i.z===t||r.set(i.id,i);let o=[],s=new Set;for(let i of[e.nodes,e.configs])if(Array.isArray(i))for(let d of i){let l=d&&typeof d=="object"?d.id:void 0;if(typeof l!="string"||!l||s.has(l))continue;if(s.add(l),l===t){o.push({code:"duplicate_node_id",error:`Node id '${l}' equals the tab id; node ids must be unique across all flows`,nodeId:l});continue}let c=r.get(l);c&&o.push({code:"duplicate_node_id",error:`Node id '${l}' is already used by ${Ml(c)}; node ids must be unique across all flows`,nodeId:l})}return o}function Ws(e){let t=new Map;for(let n of[e.nodes,e.configs])if(Array.isArray(n))for(let r of n){if(!r||typeof r!="object"||Array.isArray(r))continue;let o=r;typeof o.id=="string"&&t.set(o.id,o)}return t}function jl(e,t){let n=new Set([...Object.keys(e),...Object.keys(t)]);for(let r of n)if(!Dl.has(r)&&JSON.stringify(e[r])!==JSON.stringify(t[r]))return!0;return!1}function Hl(e,t){let n=Ws(t);if(!e)return new Set(n.keys());let r=Ws(e),o=new Set;for(let[s,i]of n){let d=r.get(s);(!d||jl(d,i))&&o.add(s)}return o}function Gs(e,t){let n=[],r=e;typeof r.id!="string"||r.id.length===0?n.push({code:"missing_flow_id",error:"payload.flow.id is required and must match payload.flowId"}):r.id!==t&&n.push({code:"invalid_flow_id",error:`payload.flow.id ('${r.id}') must match payload.flowId ('${t}')`}),"nodes"in r?Array.isArray(r.nodes)||n.push({code:"invalid_nodes",error:"payload.flow.nodes must be an array"}):n.push({code:"invalid_nodes",error:"payload.flow.nodes must be an array (use [] to clear the tab intentionally)"}),"configs"in r&&r.configs!==void 0&&!Array.isArray(r.configs)&&n.push({code:"invalid_nodes",error:"payload.flow.configs must be an array"});let o=[];Array.isArray(r.nodes)&&o.push({key:"nodes",list:r.nodes}),Array.isArray(r.configs)&&o.push({key:"configs",list:r.configs}),n.push(...wo(o.map(s=>s.list)));for(let{key:s,list:i}of o)for(let d=0;d<i.length;d+=1){let l=i[d];if(!l||typeof l!="object"||Array.isArray(l)){n.push({code:"invalid_node",error:`payload.flow.${s}[${d}] must be an object`});continue}let c=l;(typeof c.id!="string"||c.id.length===0)&&n.push({code:"missing_node_id",error:`payload.flow.${s}[${d}] needs a non-empty string id`});try{Je(c.type,"node.type")}catch(u){u instanceof y&&n.push({code:u.code,error:u.message,...typeof c.id=="string"?{nodeId:c.id}:{}})}"wires"in c&&Mt(c.wires,n,typeof c.id=="string"?c.id:void 0)}return n}function Mt(e,t,n){if(!Array.isArray(e))return t.push({code:"invalid_wires",error:"wires must be an array of output ports (each a list of node ids)",...n?{nodeId:n}:{}}),!1;for(let r of e){if(!Array.isArray(r))return t.push({code:"invalid_wires",error:"wires must be an array of output ports (each a list of node ids)",...n?{nodeId:n}:{}}),!1;for(let o of r)if(typeof o!="string"||o.length===0)return t.push({code:"invalid_wires",error:"wires targets must be non-empty node id strings",...n?{nodeId:n}:{}}),!1}return!0}async function Ul(e,t){if(typeof e.outputs=="number"&&Number.isFinite(e.outputs)&&e.outputs>=0)return Math.trunc(e.outputs);let n=typeof e.type=="string"?e.type:"";if(!(!t||!n))try{return(await ct(t,n,{includeHelp:!1})).outputs}catch{return}}function Bl(e,t,n){let r=typeof e.type=="string"?e.type:"node";if(!(n.length<=t))return t===0?{code:"invalid_wires",error:`${r} has 0 outputs; wires must be []`,nodeId:e.id,type:r}:{code:"invalid_wires",error:`${r} has ${t} outputs; wires has ${n.length} port arrays (max ${t})`,nodeId:e.id,type:r}}function ql(e){return Array.isArray(e)&&e.some(t=>typeof t=="string"&&t.length>0)}function Wl(e,t){return t<=0?!1:!("wires"in e)||e.wires===void 0?!0:Array.isArray(e.wires)?!e.wires.some(ql):!1}async function bo(e,t,n={}){let r=[],o=[],s=new Set(e.map(d=>d.id)),i=n.softWarningNodeIds;for(let d of e){let l=await Ul(d,t),c=typeof d.type=="string"?d.type:"node",u=!i||i.has(d.id);if("wires"in d&&d.wires!==void 0){if(!Mt(d.wires,r,d.id))continue;let p=d.wires;if(l!==void 0){let f=Bl(d,l,p);f?(f.cause="excess_ports",r.push(f)):u&&p.length<l&&o.push({code:"incomplete_wires",error:`${c} '${d.id}' declares ${l} outputs but wires has only ${p.length} port(s)`,nodeId:d.id,type:c})}for(let f of p)for(let m of f){let h=String(m);s.has(h)||r.push({code:"invalid_wires",error:`Wire target '${h}' on node '${d.id}' was not found in this flow (add the node in the same patch or use an existing id)`,nodeId:d.id,cause:"missing_target",targetId:h})}}u&&l!==void 0&&Wl(d,l)&&o.push({code:"unwired_node",error:`Node '${d.id}' (${c}) has ${l} output(s) but is not wired to anything yet`,nodeId:d.id,type:c})}return{errors:r,warnings:o}}function vo(e,t){let n=[];for(let r of e)r.z===void 0||r.z===""||typeof r.z=="string"&&r.z!==t&&n.push({code:"z_mismatch",error:`Node '${r.id}' has z='${r.z}' but flow id is '${t}'`,nodeId:r.id});return n}function zl(e,t){return e.filter(n=>n.type===t).map(n=>n.id)}async function ko(e,t,n){let r=[],o=[...t];for(let s of e){let i;try{i=Je(s.type,"node.type")}catch{continue}let d;try{d=await ct(n,i,{includeHelp:!1})}catch{continue}let l=d.defaults;if(!l||typeof l!="object")continue;let c=new Set(d.requiredConfigNodeTypes??[]);for(let[u,p]of Object.entries(l)){if(!p||typeof p!="object"||Array.isArray(p))continue;let f=p.type;if(typeof f!="string"||!f)continue;let h=p.required===!0||c.has(f),g=s[u],x=zl(o,f);if(typeof g!="string"||g.length===0){h&&r.push({code:"missing_config_node",error:`Node '${s.id}' (${i}) has no ${f} on '${u}' yet \u2014 configure before deploy if needed`,nodeId:s.id,type:i,property:u,configType:f,candidates:x});continue}o.find(E=>E.id===g)?.type!==f&&r.push({code:"missing_config_node",error:`Node '${s.id}' property '${u}' does not resolve to a ${f} config yet`,nodeId:s.id,type:i,property:u,configType:f,candidates:x})}}return r}async function Js(e,t={}){let n=t.flowId??(typeof e.id=="string"?e.id:""),r=Array.isArray(e.nodes)?e.nodes:[],o=Array.isArray(e.configs)?e.configs:[],s=[],i=[];n&&s.push(...vo(r,n));let d=t.baseFlow?Hl(t.baseFlow,e):void 0,l=await bo(r,t.nodeTypes,{...d?{softWarningNodeIds:d}:{}});if(s.push(...l.errors),i.push(...l.warnings),t.nodeTypes){let c=await ko(r,o,t.nodeTypes);d?i.push(...c.filter(u=>!u.nodeId||d.has(u.nodeId))):i.push(...c)}return{errors:s,warnings:i}}var Dl,Ao=U(()=>{"use strict";K();ut();a(Ke,"throwValidationIssues");a(wo,"collectDuplicateNodeIdIssues");a(Ml,"describeLiveNode");a(zs,"collectCrossFlowDuplicateIssues");Dl=new Set(["x","y","w","h","g","id","z"]);a(Ws,"collectNodesMap");a(jl,"nodeContentChanged");a(Hl,"changedNodeIds");a(Gs,"collectFullFlowShapeIssues");a(Mt,"assertValidWiresShape");a(Ul,"resolveNodeOutputCount");a(Bl,"wireCountIssue");a(ql,"portHasTargets");a(Wl,"nodeIsUnwired");a(bo,"collectWireValidation");a(vo,"collectZMismatchIssues");a(zl,"configCandidates");a(ko,"collectConfigWarnings");a(Js,"validateFlowTab")});function Ve(e,t="node"){return typeof e=="string"&&e.trim()?e.trim():t}function dr(e){let t=new Map;for(let n of e)n.type==="tab"&&typeof n.id=="string"&&typeof n.label=="string"&&n.label.trim()&&t.set(n.id,n.label.trim());return t}function Vs(e,t){e[Ks]=t}function Kl(e){if(!e)return;let t=e[Ks];return t instanceof Map?t:void 0}function Vl(e){return typeof e!="string"||!e.trim()?new Set:new Set(e.split(",").map(t=>t.trim()).filter(Boolean))}function Xl(e){if(e===!0||e===1)return!0;if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}return!1}function re(e){let t=Vl(e.include);return Xl(e.include_payload)&&(t.add("payload"),t.add("baseFlow")),t}function q(e,t){let n={req:e};t!==void 0&&(n.httpAdminRoot=t);let r=Kl(e);return r&&(n.liveFlowLabels=r),n}function Dt(e){return typeof e.name=="string"&&e.name.trim()?e.name.trim():typeof e.label=="string"&&e.label.trim()?e.label.trim():""}function Sn(e){return`"${e.replace(/"/g,"'")}"`}function jt(e){let t=new Map;for(let n of e.nodes??[])t.set(n.id,n);for(let n of e.configs??[])t.set(n.id,n);return t}function Yl(e,t){let n=new Set(["x","y","w","h","g","id","z"]),r=new Set([...Object.keys(e),...Object.keys(t)]);for(let o of r)if(!n.has(o)&&JSON.stringify(e[o])!==JSON.stringify(t[o]))return!0;return!1}function Ql(e,t){let n=Dt(e),r=Dt(t);if(!n||!r||n===r)return!1;let o=new Set(["x","y","w","h","g","id","z","name","label"]),s=new Set([...Object.keys(e),...Object.keys(t)]);for(let i of s)if(!o.has(i)&&JSON.stringify(e[i])!==JSON.stringify(t[i]))return!1;return!0}function xo(e,t){let n=[],r=[],o=[];for(let[s,i]of t)e.has(s)||n.push(i);for(let[s,i]of e)t.has(s)||r.push(i);for(let[s,i]of t){let d=e.get(s);d&&Yl(d,i)&&o.push({before:d,after:i})}return{added:n,removed:r,modified:o}}function lr(e){return e===1?"node":"nodes"}function Zl(e){return e.length===1&&e[0]?`adds 1 ${Ve(e[0].type)}`:`adds ${e.length} ${lr(e.length)}`}function ec(e){return`deletes ${e} ${lr(e)}`}function tc(e){return`edits ${e} ${lr(e)}`}function nc(e){let t=[];e.removed>0&&t.push(ec(e.removed));let n=e.added??[],r=e.addedCount??n.length;r>0&&t.push(n.length===r?Zl(n):`adds ${r} ${lr(r)}`),(e.modified??0)>0&&t.push(tc(e.modified??0));let o=t.length?t.join(", "):"replaces nodes",s=e.flowLabel?.trim();return s?`Replace ${s}: ${o}`:`Replace flow: ${o}`}function rc(e){let{added:t,removed:n,modified:r}=e;if(t.length+n.length+r.length!==1)return;if(t[0]){let u=t[0],p=Ve(u.type),f=Dt(u);return f?`Add ${p} node ${Sn(f)}`:`Add ${p} node`}if(n[0]){let u=n[0],p=Ve(u.type),f=Dt(u);return f?`Remove ${p} node ${Sn(f)}`:`Remove ${p} node`}let s=r[0];if(!s)return;let i=Ve(s.after.type,Ve(s.before.type)),d=Dt(s.before),l=Dt(s.after);if(Ql(s.before,s.after)&&d&&l)return`Rename ${i} node ${Sn(d)} \u2192 ${Sn(l)}`;let c=l||d;return c?`Edit ${i} ${Sn(c)}`:`Edit ${i}`}function So(e,t){return typeof e?.label=="string"&&e.label.trim()?e.label.trim():typeof t?.label=="string"&&t.label.trim()?t.label.trim():""}function cr(e,t){if(typeof e.flowLabel=="string"&&e.flowLabel.trim())return e.flowLabel.trim();let n=So(e.payload?.flow,e.baseFlow);if(n)return n;let r=e.payload?.flowId;return r&&t?.has(r)?t.get(r)??"":""}function Xs(e,t){let n=t.trim(),r=e.trim();if(!n||!r||r.includes(n))return r;let o=r.lastIndexOf(" in ");if(o>=0){let s=r.slice(o+4);if(s.length>0&&n.startsWith(s))return r}return`${r} in ${n}`}function To(e,t){let n=xo(jt(e??{}),jt(t)),r=n.added.length+n.removed.length+n.modified.length,o=So(t,e);if(r===0)return o?`Update ${o}`:"Update flow";if(n.removed.length>0)return nc({...o?{flowLabel:o}:{},removed:n.removed.length,added:n.added,modified:n.modified.length});if(r>Jl)return o?`${r} changes in ${o}`:`${r} changes`;let s=rc(n)??(o?`Update ${o}`:"Update flow");return Xs(s,o)}function oc(e,t){let n=(e??"").trim();return!!(!n||n.includes("[object Object]")||/^Update(\s|$)/i.test(n)||t>0&&!/^Replace\b/i.test(n))}function Po(e,t){return`${e} \xB7 ${ic(t)}`}function sc(e){let t=e>=0?"+":"-",n=Math.abs(e),r=String(Math.floor(n/60)).padStart(2,"0"),o=String(n%60).padStart(2,"0");return`${t}${r}:${o}`}function ic(e,t=new Date(e)){let n=Number.isNaN(t.getTime())?new Date(e):t;if(Number.isNaN(n.getTime()))return e.slice(0,16);let r=n.getDate(),s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n.getMonth()]??"Jan",i=String(n.getHours()).padStart(2,"0"),d=String(n.getMinutes()).padStart(2,"0"),l=sc(-n.getTimezoneOffset());return`${r} ${s} ${i}:${d} ${l}`}function ur(e){if(typeof e!="string")return;let t=e.replace(/\0/g,"").replace(/[\u0001-\u001F\u007F]/g," ").replace(/\s+/g," ").trim().slice(0,Gl).trim();return t.length>0?t:void 0}function ac(e,t){let n=ae(t);return`${n==="/"?"/ai-access":`${n}/ai-access`}#proposal=${encodeURIComponent(e)}`}function Ro(e,t={}){let n=cr(e,t.liveFlowLabels),r=ur(e.title),o=To(e.baseFlow,n&&!So(e.payload.flow,e.baseFlow)?{...e.payload.flow,label:n}:e.payload.flow),s=xo(jt(e.baseFlow??{}),jt(e.payload.flow)),i=oc(r,s.removed.length)?o:r??o;return Xs(i,n)}function dc(e){return typeof e.storedTitle=="string"&&e.storedTitle?e.storedTitle:ur(e.title)}function oe(e,t={}){let n=Ro(e,t),r=cr(e,t.liveFlowLabels),o=dc(e)??n,s=ac(e.id,t.httpAdminRoot),i=t.req?vn(t.req,s):s;return{...e,title:n,storedTitle:o,flowLabel:r,displayName:Po(n,e.createdAt),reviewUrl:i,reviewPath:s}}function lc(e){let t=xo(jt(e.baseFlow??{}),jt(e.payload.flow)),n=[];return t.added.length>0&&n.push(t.added.length===1?"Adds 1 node":`Adds ${t.added.length} nodes`),t.removed.length>0&&n.push(t.removed.length===1?"Deletes 1 node":`Deletes ${t.removed.length} nodes`),t.modified.length>0&&n.push(t.modified.length===1?"Edits 1 node":`Edits ${t.modified.length} nodes`),n.length===0?"No node changes":n.map((r,o)=>o===0?r:r.charAt(0).toLowerCase()+r.slice(1)).join(", ")}function cc(e){if(e.kind==="oauth")return{kind:"oauth",clientId:e.clientId,user:e.user};let t={kind:e.kind,linkId:e.linkId};return typeof e.label=="string"&&e.label.length>0&&(t.label=e.label),t}function ce(e,t={}){let n=oe(e,t),r=t.include??new Set,o={id:n.id,status:n.status,type:n.type,title:n.title,storedTitle:n.storedTitle,displayName:n.displayName,flowLabel:n.flowLabel,reviewUrl:n.reviewUrl,reviewPath:n.reviewPath,createdAt:n.createdAt,updatedAt:n.updatedAt,expectedRev:n.expectedRev,createdBy:cc(n.createdBy),changeSummary:lc(e)};return r.has("payload")&&(o.payload=n.payload),r.has("baseFlow")&&n.baseFlow!==void 0&&(o.baseFlow=n.baseFlow),n.warnings&&n.warnings.length>0&&(o.warnings=n.warnings),n.baseRevStale!==void 0&&(o.baseRevStale=n.baseRevStale),n.decidedBy!==void 0&&(o.decidedBy=n.decidedBy),n.reason!==void 0&&(o.reason=n.reason),n.resultRev!==void 0&&(o.resultRev=n.resultRev),o}function Ys(e,t={}){return e.map(n=>ce(n,t))}var Gl,Jl,Ks,Ae=U(()=>{"use strict";ie();_e();Gl=80,Jl=1;a(Ve,"nodeTypeText");Ks=Symbol.for("ai-access.liveFlowLabels");a(dr,"liveFlowLabelsFromFlows");a(Vs,"setRequestFlowLabels");a(Kl,"getRequestFlowLabels");a(Vl,"parseIncludeQuery");a(Xl,"isTruthyFlag");a(re,"resolveIncludeFromQuery");a(q,"presentOptionsFor");a(Dt,"nodeLabel");a(Sn,"quoteName");a(jt,"collectNodes");a(Yl,"nodeContentChanged");a(Ql,"isRenameOnly");a(xo,"classifyFlowChanges");a(lr,"pluralNodes");a(Zl,"describeAddedClause");a(ec,"describeRemovedClause");a(tc,"describeModifiedClause");a(nc,"buildReplaceFlowTitle");a(rc,"describeOneChange");a(So,"flowLabelHint");a(cr,"resolveFlowLabel");a(Xs,"ensureTitleIncludesFlowName");a(To,"autoGenerateProposalTitle");a(oc,"shouldRefreshDisplayTitle");a(Po,"buildProposalDisplayName");a(sc,"formatUtcOffset");a(ic,"formatProposalSubmittedAt");a(ur,"sanitizeProposalTitle");a(ac,"buildProposalReviewPath");a(Ro,"resolveProposalTitle");a(dc,"storedTitleOf");a(oe,"presentProposal");a(lc,"buildChangeSummary");a(cc,"presentCreatedByForApi");a(ce,"presentProposalForApi");a(Ys,"presentProposalsForApi")});function Qs(e){let t=new Map;for(let n of e.nodes??[])t.set(n.id,n);for(let n of e.configs??[])t.set(n.id,n);return t}function pc(e,t){let n=new Set([...Object.keys(e),...Object.keys(t)]),r=[];for(let o of n)uc.has(o)||JSON.stringify(e[o])!==JSON.stringify(t[o])&&r.push(o);return r.sort()}function Zs(e){let t=Qs(e.baseFlow??{}),n=Qs(e.payload.flow),r=new Map;for(let[o,s]of n){let i=t.get(o);if(!i){r.set(o,new Set(["*"]));continue}let d=pc(i,s);d.length>0&&r.set(o,new Set(d))}for(let[o]of t)n.has(o)||r.set(o,new Set(["*"]));return r}function fc(e,t){let n=[],r=[];for(let[o,s]of e){let i=t.get(o);if(!i)continue;n.push(o);let d=[];for(let c of s){if(c==="*"){d.push(...[...i].filter(u=>u!=="*")),i.has("*")&&d.push("*");continue}(i.has(c)||i.has("*"))&&d.push(c)}let l=[...new Set(d)].sort();l.length>0&&r.push({nodeId:o,fields:l})}return n.sort(),{nodeIds:n,fields:r}}function V(e,t,n={}){let r=0;for(let o of e.list())if(o.status==="pending"&&!(n.flowId&&o.payload.flowId!==n.flowId)&&o.expectedRev!==t)try{e.markClosed(o.id,"expired",mc),r+=1}catch{}return r}function ei(e,t,n,r){let o=`Superseded by approved proposal ${n} (resultRev ${r}). Re-read the flow and resubmit if still needed.`,s=0;for(let i of e.list())if(!(i.id===n||i.status!=="pending"||i.payload.flowId!==t))try{e.markClosed(i.id,"superseded",o),s+=1}catch{}return s}function Ie(e,t,n){let r=Zs(t),o=[];for(let s of e.list()){if(s.id===t.id||s.status!=="pending"||s.payload.flowId!==t.payload.flowId)continue;let i=Ro(s),d=n?lt(s.createdBy)===n:lt(s.createdBy)===lt(t.createdBy),l=fc(r,Zs(s)),c=s.expectedRev===t.expectedRev,u=l.nodeIds.length>0;if(!c&&!u)continue;let p={id:s.id,title:i,displayName:Po(i,s.createdAt),mine:d};l.nodeIds.length>0&&(p.overlappingNodeIds=l.nodeIds),l.fields.length>0&&(p.overlappingFields=l.fields),o.push(p)}return{conflictingProposals:o}}function Ne(e){let t={};return e.conflictingProposals.length>0&&(t.conflictingProposals=e.conflictingProposals,t.warning="Other pending proposals touch the same flow \u2014 approve order may conflict (like a git merge)."),t}function Q(e){return e>0?{autoClosedCount:e}:{}}var uc,mc,Xe=U(()=>{"use strict";Ge();Ae();uc=new Set(["x","y","w","h","g","id","z"]);a(Qs,"collectNodes");a(pc,"changedFieldKeys");a(Zs,"computeProposalTouches");a(fc,"overlapBetween");mc="Proposal expired: the live flow revision moved past expectedRev. Re-read the flow and resubmit.";a(V,"expireStalePendingProposals");a(ei,"supersedePendingOnFlow");a(Ie,"findConflictingProposals");a(Ne,"conflictWarningFields");a(Q,"autoClosedFields")});var di={};ds(di,{applyFlowNodeOps:()=>pt,applyReplaceTextToValue:()=>ai,buildPatchedFlowTab:()=>Tn,collectSetProps:()=>_o,decodeBase64UrlJson:()=>Pn,findTextOccurrences:()=>ii,interpretPatch:()=>Rn});function si(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function hc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new y(`add op needs node as an object (got ${si(e)})`,"invalid_node")}async function Tn(e,t,n){return pt(e,t,n.map(r=>({op:"set",nodeId:r.nodeId,set:r.set})))}function ii(e,t){if(!t)return[];let n=[],r=0;for(;r<=e.length;){let o=e.indexOf(t,r);if(o<0)break;n.push(o),r=o+t.length}return n}function ai(e,t,n,r,o){if(oi.has(t))throw new y(`Cannot change protected node property '${t}' via replace_text`,"protected_property");if(typeof n!="string"||n.length===0)throw new y("find must be a non-empty string","missing_find");if(typeof r!="string")throw new y("replace must be a string","invalid_replace");if(e===void 0)throw new y(`Field '${t}' was not found on the node`,"field_not_found");if(typeof e!="string")throw new y(`Field '${t}' is not a string (got ${e===null?"null":typeof e})`,"field_not_string");let s=ii(e,n);if(s.length===0)throw new y(`Text not found in field '${t}'`,"text_not_found",{details:{matchCount:0}});let i=o;if(i===void 0){if(s.length>1)throw new y(`Found ${s.length} matches in '${t}'; pass occurrence (1-based) to pick one`,"ambiguous_match",{statusCode:409,details:{matchCount:s.length}});i=1}if(!Number.isInteger(i)||i<1||i>s.length)throw new y(`occurrence must be an integer from 1 to ${s.length}`,"invalid_occurrence",{details:{matchCount:s.length}});let d=s[i-1];if(d===void 0)throw new y(`occurrence must be an integer from 1 to ${s.length}`,"invalid_occurrence",{details:{matchCount:s.length}});return e.slice(0,d)+r+e.slice(d+n.length)}function gc(e){let t=[];for(let n of e)if(n.op==="add"){let r=n.node;if(typeof r!="object"||r===null||Array.isArray(r)){t.push({code:"invalid_node",error:`add op needs node as an object (got ${si(r)})`});continue}let o=r;(!o.id||typeof o.id!="string")&&t.push({code:"missing_node_id",error:"add op needs node.id"});try{Je(o.type,"node.type")}catch(s){s instanceof y&&t.push({code:s.code,error:s.message,nodeId:o.id})}"wires"in o&&Mt(o.wires,t,typeof o.id=="string"?o.id:void 0)}else n.op==="set"&&typeof n.set=="object"&&"wires"in n.set&&Mt(n.set.wires,t,n.nodeId);return t}function yc(e){let t=new Set;for(let n of e)n.op==="add"&&typeof n.node.id=="string"?t.add(n.node.id):n.op!=="add"&&typeof n.nodeId=="string"&&t.add(n.nodeId);return t}async function pt(e,t,n,r={}){if(!t)throw new y("flow id is required","missing_flow_id");if(!n.length)throw new y("At least one node edit is required","missing_edits");let o=gc(n);o.push(...wo([n.flatMap(h=>h.op==="add"?[h.node]:[])],"the batch (add ops)")),Ke(o);let s=await e.getFlow(t);if(r.expectedRev!==void 0&&s.rev!==r.expectedRev){let h=Array.isArray(s.flow.nodes)?[...s.flow.nodes]:[];return{expectedRev:s.rev,flow:{...s.flow,id:s.flow.id,type:s.flow.type??"tab",nodes:h}}}let i=Array.isArray(s.flow.nodes)?[...s.flow.nodes]:[],d=Array.isArray(s.flow.configs)?[...s.flow.configs]:[],l={...s.flow,id:s.flow.id,type:s.flow.type??"tab",nodes:i,configs:d},c=i.map(h=>({...h})),u=[];for(let h of n)try{h.op==="add"&&r.nodeTypes&&await qs(r.nodeTypes,h.node.type),ni(c,t,h)}catch(g){if(g instanceof y)u.push({code:g.code,error:g.message,...g.statusCode!==400?{statusCode:g.statusCode}:{},...g.details??{}});else throw g}u.push(...vo(c,t));let p=yc(n),f=await bo(c,r.nodeTypes,{softWarningNodeIds:p});u.push(...f.errors),Ke(u);for(let h of n)ni(i,t,h);let m=[...f.warnings];if(r.nodeTypes){let h=await ko(i,d,r.nodeTypes);m.push(...h.filter(g=>!g.nodeId||p.has(g.nodeId)))}return{expectedRev:s.rev,flow:l,...m.length>0?{warnings:m}:{}}}function ti(e,t,n){if(!t||typeof t!="string")throw new y("Each edit needs a node id","missing_node_id");let r=e.findIndex(o=>o.id===t);if(r<0||!e[r])throw new y(`Node '${t}' was not found in flow '${n}'`,"node_not_found",{statusCode:404});return r}function ni(e,t,n){if(n.op==="add"){let i=n.node;if(!i.id||typeof i.id!="string")throw new y("add op needs node.id","missing_node_id");if(Je(i.type,"node.type"),e.some(d=>d.id===i.id))throw new y(`Node '${i.id}' already exists in flow '${t}'`,"node_already_exists");e.push({...i,id:i.id,type:i.type,z:typeof i.z=="string"&&i.z?i.z:t});return}if(n.op==="remove"){let i=ti(e,n.nodeId,t);e.splice(i,1);return}let r=ti(e,n.nodeId,t),o=e[r];if(!o)throw new y(`Node '${n.nodeId}' was not found in flow '${t}'`,"node_not_found",{statusCode:404});if(n.op==="replace_text"){if(!(n.field in o))throw new y(`Field '${n.field}' was not found on the node`,"field_not_found");let i=ai(o[n.field],n.field,n.find,n.replace,n.occurrence);e[r]={...o,id:o.id,type:o.type,[n.field]:i};return}let s={...o,id:o.id,type:o.type};for(let[i,d]of Object.entries(n.set)){if(oi.has(i))throw new y(`Cannot change protected node property '${i}' via GET propose`,"protected_property");if(i==="wires"){let l=[];Mt(d,l,n.nodeId),Ke(l)}s[i]=d}e[r]=s}function ri(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e)}function _o(e){let t={},n=e.set;if(n&&typeof n=="object"&&!Array.isArray(n))for(let[r,o]of Object.entries(n)){let s=ri(o);s!==void 0&&(t[r]=s)}for(let[r,o]of Object.entries(e)){if(!r.startsWith("set.")||r.length<=4)continue;let s=r.slice(4);if(typeof o=="string")t[s]=o;else if(Array.isArray(o)&&typeof o[0]=="string")t[s]=o[0];else{let i=ri(o);i!==void 0&&(t[s]=i)}}return t}function Pn(e){let t;try{t=Buffer.from(e,"base64url").toString("utf8")}catch{throw new y("patch must be base64url-encoded JSON","invalid_patch")}try{return JSON.parse(t)}catch{throw new y("patch JSON is malformed","invalid_patch_json")}}function wc(e,t){if(typeof e.flowId=="string"&&e.flowId)return e.flowId;let n=e.flow;if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n.id;if(typeof r=="string"&&r)return r}return t}function Lo(e){return typeof e.id=="string"&&e.id?e.id:typeof e.nodeId=="string"&&e.nodeId?e.nodeId:typeof e.node=="string"&&e.node?e.node:""}function bc(e){if(e==null||e==="")return;let t;if(typeof e=="number")t=e;else if(typeof e=="string")t=Number(e);else if(typeof e=="boolean"||typeof e=="bigint")t=Number(e);else throw new y("occurrence must be a positive integer","invalid_occurrence");if(!Number.isFinite(t))throw new y("occurrence must be a positive integer","invalid_occurrence");return Math.trunc(t)}function vc(e){let t=e.node;if(t!==void 0)return hc(t),{op:"add",node:t};let n={...e};return delete n.op,{op:"add",node:n}}function kc(e){let t=Lo(e);if(!t)throw new y("replace_text op needs node id","missing_node_id");let n=typeof e.field=="string"?e.field:"";if(!n)throw new y("replace_text op needs field","missing_field");if(typeof e.find!="string")throw new y("replace_text op needs find string","missing_find");if(typeof e.replace!="string")throw new y("replace_text op needs replace string","invalid_replace");let r=bc(e.occurrence),o={op:"replace_text",nodeId:t,field:n,find:e.find,replace:e.replace};return r!==void 0&&(o.occurrence=r),o}function Ac(e){let t=Lo(e);if(!t)throw new y("Each patch.nodes entry needs id","missing_node_id");let n=e.set,r={};if(n&&typeof n=="object"&&!Array.isArray(n))Object.assign(r,n);else for(let[o,s]of Object.entries(e))o==="id"||o==="nodeId"||o==="node"||o==="set"||o==="op"||(r[o]=s);return{op:"set",nodeId:t,set:r}}function xc(e){let t=typeof e.op=="string"?e.op.toLowerCase():"set";if(t==="add")return vc(e);if(t==="remove"){let n=Lo(e);if(!n)throw new y("remove op needs id","missing_node_id");return{op:"remove",nodeId:n}}if(t==="replace_text")return kc(e);if(t!=="set")throw new y("nodes[].op must be 'add', 'remove', 'set', or 'replace_text'","invalid_patch");return Ac(e)}function Rn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new y("patch must be a JSON object","invalid_patch");let n=e;if(n.type==="replace_flow"||n.flow&&typeof n.flow=="object"){let r=wc(n,t);if(!r)throw new y("patch.replace_flow needs flowId","missing_flow_id");return{kind:"replace_flow",flowId:r,flow:n.flow}}if(Array.isArray(n.nodes)){let r=typeof n.flowId=="string"?n.flowId:t;if(!r)throw new y("patch.nodes needs flow id","missing_flow_id");let o=[];for(let i of n.nodes){if(!i||typeof i!="object"||Array.isArray(i))throw new y("Each patch.nodes entry must be an object","invalid_patch");o.push(xc(i))}let s=o.filter(i=>i.op==="set").map(i=>({nodeId:i.nodeId,set:i.set}));return{kind:"nodes",flowId:r,ops:o,edits:s}}throw new y("patch must include nodes[] edits or type/flow for replace_flow","invalid_patch")}var oi,pr=U(()=>{"use strict";K();Ao();ut();oi=new Set(["id","type","z"]);a(si,"describeNonObjectNode");a(hc,"assertAddNodeObject");a(Tn,"buildPatchedFlowTab");a(ii,"findTextOccurrences");a(ai,"applyReplaceTextToValue");a(gc,"collectOpShapeIssues");a(yc,"touchedNodeIdsFromOps");a(pt,"applyFlowNodeOps");a(ti,"requireNodeIndex");a(ni,"applyOneNodeOp");a(ri,"stringifyQueryValue");a(_o,"collectSetProps");a(Pn,"decodeBase64UrlJson");a(wc,"resolveReplaceFlowId");a(Lo,"resolveNodeId");a(bc,"parseOccurrence");a(vc,"parseAddOp");a(kc,"parseReplaceTextOp");a(Ac,"parseSetOp");a(xc,"parseNodeOp");a(Rn,"interpretPatch")});function Ht(e,t){return lt(e.createdBy)===t.id}function Co(e,t){return!t||t.length===0||t.includes(e)}function Sc(e){return typeof e=="string"&&ci.has(e)}function Bt(e,t){let n=Tc[e],r=e!=="status"&&Array.isArray(t);return new y(r?`Invalid ${e} filter: pass it at most once (multiple values are not supported). Allowed: ${n}`:`Invalid ${e} filter. Allowed: ${n}`,"invalid_filter",{details:{parameter:e,allowed:n,hint:`Pass ${e} as ${n}, or omit it.`}})}function fr(e,t){if(Array.isArray(t))throw Bt(e,t);return t}function Pc(e){return typeof e=="number"?Number.isInteger(e)?e:null:typeof e=="string"&&/^-?\d+$/.test(e.trim())?Number(e.trim()):null}function Eo(e){return e==null||e===""}function Rc(e){if(!Eo(e)){if(e==="true"||e==="1"||e===!0)return!0;if(e==="false"||e==="0"||e===!1)return!1;throw Bt("mine",e)}}function Io(e){if(Eo(e))return;let t=(Array.isArray(e)?e:[e]).flatMap(r=>typeof r=="string"?r.split(","):[r]),n=[];for(let r of t){let o=typeof r=="string"?r.trim():r;if(o!==""){if(!Sc(o))throw Bt("status",e);n.includes(o)||n.push(o)}}return n.length>0?n:void 0}function li(e,t,n,r){if(Eo(t))return;let o=Pc(t);if(o===null||o<n||o>r)throw Bt(e,t);return o}function mr(e){let t={},n=Rc(fr("mine",e.mine));n!==void 0&&(t.mine=n);let r=Io(e.status);r&&(t.status=r);let o=fr("flowId",e.flowId??e.flow_id??e.flow);typeof o=="string"&&o.length>0&&(t.flowId=o);let s=li("limit",fr("limit",e.limit),1,Ut);s!==void 0&&(t.limit=s);let i=li("offset",fr("offset",e.offset),0,Number.MAX_SAFE_INTEGER);return i!==void 0&&(t.offset=i),t}function ft(e){let t=e.offset+e.returned,n=t<e.total;return{total:e.total,offset:e.offset,...e.limit!==null?{limit:e.limit}:{},hasMore:n,...n?{nextOffset:t}:{}}}function _c(e,t){let n=e.length,r=t.offset!==void 0&&t.offset>0?t.offset:0;if(t.limit===void 0)return{items:r>0?e.slice(r):e,total:n,limit:null,offset:r};let o=Math.min(Math.max(1,t.limit),Ut);return{items:e.slice(r,r+o),total:n,limit:o,offset:r}}function qt(e,t,n={},r={}){let o=r.mine===!0?t.id:void 0,s={};o&&(s.linkId=o),r.flowId&&(s.flowId=r.flowId);let d=e.list(s).filter(c=>r.mine!==!1||!Ht(c,t)).filter(c=>Co(c.status,r.status)).map(c=>({...oe(c,n),mine:Ht(c,t)})),l=_c(d,r);return{proposals:l.items,total:l.total,limit:l.limit,offset:l.offset}}function De(e,t,n,r={}){if(!n)throw new y("Missing proposal id","missing_proposal_id");let o=e.get(n);return{...oe(o,r),mine:Ht(o,t)}}function Lc(e){let t={kind:"access-link",linkId:e.id};return typeof e.label=="string"&&e.label&&(t.label=e.label),t}function Wt(e,t,n,r,o,s={}){if(!r)throw new y("Missing proposal id","missing_proposal_id");let i;try{i=e.get(r)}catch(f){throw f instanceof ne,f}if(!Ht(i,n))throw new Ot(r);if(i.status!=="pending")throw new te(r,i.status);let d=typeof o=="string"&&o.trim()?o.replace(/\0/g,"").trim().slice(0,2e3):"Withdrawn by access link",l=Lc(n),c=e.markWithdrawn(r,l,d),u=oe(c,s),p=u.flowLabel||void 0;return t.append("proposal.withdrawn",l,{proposalId:c.id,flowId:c.payload.flowId,title:u.title,displayName:u.displayName,reason:d,...p?{flowLabel:p}:{}}),{...u,mine:!0}}function Cc(e,t,n,r={}){let o;try{o=e.get(t.id)}catch{return{}}if(r.liveRev){V(e,r.liveRev,{flowId:o.payload.flowId});try{o=e.get(t.id)}catch{return{}}}return o.status!=="pending"?{}:Ne(Ie(e,o,n))}function ue(e,t,n,r={},o={}){let s="mine"in n?n:{...oe(n,r),mine:Ht(n,t)},i=0;if(o.liveRev)try{let c=e.get(s.id).payload.flowId;i=V(e,o.liveRev,{flowId:c});let u=e.get(s.id);s={...oe(u,r),mine:Ht(u,t)}}catch{}let d=ce(s,r),l={...d,mine:s.mine,...Q(i)};return o.includeConflicts!==!1&&d.status==="pending"&&Object.assign(l,Cc(e,d,t.id)),l}async function pe(e){let t=await e.getFlows();return{rev:t.rev,flows:t.flows}}async function xe(e,t){if(!t)throw new y("Missing flow id","missing_flow_id");let n=await e.getFlow(t);return{rev:n.rev,flow:$t(t,n.flow)}}function Ec(e){if(typeof e.expectedRev=="string"&&e.expectedRev.length>0)return e.expectedRev;if(typeof e.expected_rev=="string"&&e.expected_rev.length>0)return e.expected_rev}function ui(e,t){if("nodes"in e&&e.nodes!==void 0&&!Array.isArray(e.nodes))throw new y("payload.nodes must be an array of node ops","invalid_nodes");if(t!==void 0&&!Array.isArray(t))throw new y("nodes must be an array of node ops","invalid_nodes")}async function Ic(e,t,n,r,o){let{applyFlowNodeOps:s,interpretPatch:i}=await Promise.resolve().then(()=>(pr(),di));ui(n,r);let d=Array.isArray(n.nodes)?n.nodes:Array.isArray(r)?r:null;if(!d)throw new y("payload.flow is required","missing_flow");let l=n.flowId,c=typeof l=="string"?l:"";if(!c)throw new y("payload.flowId is required","missing_flow_id");let u=i({nodes:d,flowId:c},c);if(u.kind!=="nodes")throw new y("payload.nodes must be node ops","invalid_patch");let p=await s(e,u.flowId,u.ops,{expectedRev:t,...o?{nodeTypes:o}:{}});if(p.expectedRev!==t)throw new J(t,p.expectedRev,"submit_proposal");return{flowId:u.flowId,flow:p.flow}}async function Nc(e,t,n,r,o){let s=n.flowId,i=n.flow,d=!i||typeof i!="object"||Array.isArray(i);if(d&&ui(n,r),d&&(Array.isArray(n.nodes)||Array.isArray(r))){let l=await Ic(e,t,n,r,o);s=l.flowId,i=l.flow}if(typeof s!="string"||s.length===0)throw new y("payload.flowId is required","missing_flow_id");if(!i||typeof i!="object"||Array.isArray(i))throw new y("payload.flow is required","missing_flow");return{flowId:s,flow:i}}function Fc(e,t){try{return{safeExpectedRev:Ee(e.slice(0,200),"expectedRev"),safeFlowId:Ee(t.slice(0,200),"flowId")}}catch{throw new y("expectedRev and payload.flowId must be safe path segments","invalid_path_segment")}}async function Ye(e,t,n,r,o,s={},i){let d=r.type,l=Ec(r),c=r.payload;if(d!=="replace_flow")throw new y("type must be 'replace_flow'","invalid_proposal_type");if(!l)throw new y("expectedRev is required (top-level field next to type and payload)","missing_expected_rev");if(!c||typeof c!="object"||Array.isArray(c))throw new y("payload must be an object","invalid_payload");let p=await Nc(o,l,c,r.nodes,i),{safeExpectedRev:f,safeFlowId:m}=Fc(l,p.flowId),h=p.flow,g=Buffer.byteLength(JSON.stringify(c),"utf8");if(g>j)throw new X("proposal payload",g,j);Ke(Gs(h,m));let S=Ft(h),E=await o.getFlows();if(E.rev!==f)throw new J(f,E.rev,"submit_proposal");Ke(zs(S,m,E.flows));let I=await o.getFlow(m);if(I.rev!==f)throw new J(f,I.rev,"submit_proposal");let N=Ft(I.flow);i&&await Bs(i,S);let{errors:ot,warnings:me}=await Js(S,{flowId:m,baseFlow:N,...i?{nodeTypes:i}:{}});Ke(ot);let A={kind:"access-link",linkId:n.id};n.label!==void 0&&(A.label=n.label);let v=n.oauthClientId&&n.oauthUser?{kind:"oauth",clientId:n.oauthClientId,user:n.oauthUser}:A,w=ur(r.title)??To(N,S),b=e.create({type:"replace_flow",expectedRev:f,payload:{flowId:m,flow:S},baseFlow:N,title:w,createdBy:v,...me.length>0?{warnings:me}:{}}),k=oe(b,s),L=k.flowLabel||void 0;return t.append("proposal.created",A,{proposalId:b.id,flowId:m,expectedRev:f,title:k.title,displayName:k.displayName,...L?{flowLabel:L}:{},...me.length>0?{warningCount:me.length}:{}}),k}function O(e,t="rest"){return _n(e,t)}var Ut,ci,Tc,y,K=U(()=>{"use strict";ve();or();Ge();er();G();Fe();Ao();ut();Xe();Ae();a(Ht,"isMineProposal");Ut=200,ci=new Set(["pending","approved","rejected","failed","withdrawn","expired","superseded"]);a(Co,"matchesStatusFilter");a(Sc,"isProposalStatus");Tc={status:[...ci].join(", "),limit:`integer 1\u2013${Ut}`,offset:"integer \u2265 0",mine:"true, false, 1, 0",flowId:"one flow tab id"};a(Bt,"invalidFilterError");a(fr,"singleQueryValue");a(Pc,"parseIntegerFilter");a(Eo,"isUnset");a(Rc,"parseMineFilter");a(Io,"parseStatusFilter");a(li,"parseRangeFilter");a(mr,"parseListProposalsQuery");a(ft,"listPageFields");a(_c,"applyListPagination");a(qt,"listAccessibleProposals");a(De,"getAccessibleProposal");a(Lc,"accessLinkActor");a(Wt,"withdrawMyProposal");a(Cc,"conflictsForProposal");a(ue,"presentAccessibleProposalForApi");y=class extends Error{static{a(this,"AiOpsValidationError")}statusCode;code;details;constructor(t,n="validation_error",r={}){super(t),this.name="AiOpsValidationError",this.code=n,this.statusCode=r.statusCode??400,r.details&&(this.details=r.details)}};a(pe,"listFlows");a(xe,"getFlow");a(Ec,"resolveExpectedRev");a(ui,"assertNodesArrayOrAbsent");a(Ic,"materializePayloadFromNodes");a(Nc,"resolveReplaceFlowPayload");a(Fc,"assertSafeRevAndFlowId");a(Ye,"submitReplaceFlowProposal");a(O,"aiOpsErrorToHttp")});function No(e){return e==="get_link"?86400:2592e3}function Fo(e,t){return e==="get_link"?`get_link ttlSeconds must be \u2264 ${t} (24 hours)`:`ttlSeconds must be \u2264 ${t} (30 days) for ${e} tokens`}var mt,Ln=U(()=>{"use strict";a(No,"maxTtlSecondsForKind");a(Fo,"ttlCapErrorMessage");mt="ttlSeconds must be a positive number of seconds within the cap for the token kind: get_link \u2264 86400 (24h); rest and mcp \u2264 2592000 (30 days)."});function P(e,t,n,r,o=Jt,s="error"){return{code:e,status:t,meaning:n,hint:r,channels:o,kind:s}}function Cn(e){return $c.get(e)?.hint}function pi(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|")}function fi(){let e=a(s=>`| \`${s.code}\` | ${s.status} | ${pi(s.meaning)} | ${pi(s.hint)} | ${s.channels.join(", ")} |`,"row"),t=["| Code | HTTP | Meaning | Next step | Channels |","| --- | --- | --- | --- | --- |"],n=hr.filter(s=>s.kind==="error"),r=hr.filter(s=>s.kind==="warning"),o=hr.filter(s=>s.kind==="status");return[...t,...n.map(e),"","**Warnings** (in `warnings[]` on a successful propose; never blocking):","",...t,...r.map(e),"","**Auto-closed proposal statuses.** Pending proposals are closed automatically: `expired` when the live flow rev moves past their `expectedRev`, `superseded` when another proposal on the same flow is approved. Submit, get, and list responses include `autoClosedCount` when that request auto-closed proposals (omitted when zero).","",...t,...o.map(e)].join(`
|
|
7
7
|
`)}var Jt,zt,Oo,Oc,Gt,hr,$c,gr=U(()=>{"use strict";Ln();Jt=["GET","REST","MCP"],zt=["GET"],Oo=["REST","MCP"],Oc=["GET","REST"],Gt=["admin"];a(P,"e");hr=[P("access_link_missing",401,"No Bearer / path token","Ask the user for a new access link of the right kind"),P("bearer_scheme_required",401,"Auth used Basic (or non-Bearer)","Send `Authorization: Bearer <token>`",Oo),P("token_expired",401,"Known token past `expiresAt` (body includes `expiredAt` and `accessLinksUrl`)","Ask the user to create a new link on the `/ai-access` dashboard \u2192 Access tokens (`accessLinksUrl`)"),P("access_link_invalid",401,"Unknown, revoked, or cleared after restart","Ask the user for a new access link"),P("wrong_token_kind",403,"Token kind does not match this surface","Mint the matching kind on `/ai-access` \u2192 Access tokens; show `tellUser` to the human"),P("ai_features_disabled",403,"Plugin AI features off","Owner enables AI Access / `adminAuth`"),P("auth_required",401,"Admin session required","Sign in to the Node-RED editor",Gt),P("insufficient_permissions",403,"Admin lacks required scope","Need `*` for link mint / approve",Gt),P("invalid_link_kind",400,"Unknown `kind` on create","Use `get_link`, `rest`, or `mcp`",Gt),P("invalid_ttl",400,"`ttlSeconds` is zero, negative, not a number, or over the cap for the kind",mt,Gt),P("access_link_limit",409,"Too many active links","Revoke an existing link first",Gt),P("access_link_not_found",404,"Unknown link id on revoke","List links and use an existing id",Gt),P("link_create_not_supported",403,"Attempted mint under a GET link","Admin mints via `POST /mcp/api/v1/links` only",zt),P("rate_limited",429,"Per-IP or per-token limit","Wait `retryAfter` / `Retry-After`"),P("payload_too_large",413,"Body / proposal over ~1.5MB","Shrink content"),P("invalid_json",400,"Malformed JSON body","Fix Content-Type / body",Oo),P("unsupported_media_type",415,"POST body is not `application/json`","Send `Content-Type: application/json`",Oo),P("url_too_long",414,"GET URL over soft cap (~8KB)","Use chunked drafts or REST/MCP",zt),P("not_found",404,"Unknown path or resource","Re-read docs / discovery"),P("missing_query",400,"Required search `q` missing","Pass `?q=`",Oc),P("invalid_filter",400,"Invalid list filter (`status`, `limit`, `offset`, `mine`); body names `parameter` and `allowed`","Use an allowed value: status one of the proposal statuses; limit integer 1\u2013200; offset integer \u2265 0; mine true|false"),P("invalid_arguments",400,"MCP tool arguments failed schema validation; body names `parameter`","Fix the named argument to match the tool input schema (see tools/list)",["MCP"]),P("invalid_diff_format",400,"Unknown `format` on proposal diff","Use `format=summary` (default) or `format=full`"),P("confirm_required",400,"GET withdraw without `confirm=1`","Repeat the request with `confirm=1`",zt),P("missing_expected_rev",400,"Proposal submitted without `expectedRev` / `rev`","Read the flow and pass its `rev`"),P("version_mismatch",409,"Stale `rev` / `expectedRev`","Re-read flows and resubmit"),P("proposal_not_found",404,"Unknown proposal id","List proposals and use an existing id"),P("proposal_not_pending",409,"Action needs a pending proposal","Only pending can withdraw / decide"),P("proposal_not_owned",403,"Withdraw of another token\u2019s proposal","Only the creating token can withdraw"),P("validation_failed",400,"Several validation errors at once (message `N validation errors`)","Fix every entry in errors[] and resubmit."),P("duplicate_node_id",400,"The same node id appears more than once in a full tab or batch","Give every node a unique id"),P("missing_node_id",400,"Node / op without an id","Include a non-empty string id"),P("missing_node_type",400,"Node without a `type`","Set `type` to an installed palette type name"),P("invalid_node_type",400,"`type` is not a string","Use the palette type name exactly"),P("invalid_nodes",400,"`flow.nodes` / `flow.configs` not an array","Send arrays (use `[]` to clear)"),P("invalid_node",400,"Node entry is not an object","Send `{ id, type, \u2026 }` objects"),P("invalid_wires",400,"Bad wires shape, missing target, or more ports than outputs","Wire only to existing node ids / ports"),P("z_mismatch",400,"Node `z` differs from the flow id","Set `z` to the tab id or omit it"),P("node_already_exists",400,"`add` op for an id already in the flow","Use `set` or a new id"),P("protected_property",400,"Tried to change id / type / z","Omit id, type, and z from edits"),P("node_not_found",404,"Unknown node (single error only; several errors \u2192 `validation_failed`)","Re-read the flow"),P("field_not_found",404,"Unknown field on a node","Re-read the node"),P("text_not_found",400,"`replace_text` find had no match","Re-read field; find is exact"),P("ambiguous_match",409,"`replace_text` matched more than once","Pass `occurrence` (1-based) or unique find"),P("unknown_node_type",400,"Proposal uses a type that is not installed","List node-types / palette search; ask user to install"),P("node_type_not_found",404,"Unknown type on node-types detail","List types or search palette"),P("chunk_conflict",409,"Same draft seq re-sent with different data","Re-send identical data or start a new draft",zt),P("missing_chunks",400,"Draft submit with gaps in seq","Upload every seq from 0 through max",zt),P("draft_hash_mismatch",400,"Draft sha256 does not match assembled bytes","Send the hex sha256 of the assembled UTF-8",zt),P("missing_config_node",201,"Warning: node has no (or an unresolved) config node yet","Configure before deploy if needed; see `candidates`",Jt,"warning"),P("unwired_node",201,"Warning: node has outputs but no wires","Wire it, or ignore while scaffolding",Jt,"warning"),P("incomplete_wires",201,"Warning: fewer wire ports than outputs","Add ports if outputs should connect",Jt,"warning"),P("expired",200,"Status: pending proposal auto-closed because the live flow rev moved past `expectedRev`","Re-read the flow and submit a new proposal",Jt,"status"),P("superseded",200,"Status: pending proposal auto-closed because another proposal on the same flow was approved","Re-read the flow and submit a new proposal if still needed",Jt,"status"),P("upstream_error",502,"Node-RED runtime/flows error","Retry; check Node-RED logs"),P("internal_error",500,"Unexpected server error","Retry; check Node-RED logs")],$c=new Map(hr.map(e=>[e.code,e]));a(Cn,"registryHint");a(pi,"cell");a(fi,"renderGetLinkErrorTable")});function se(e,t,n={}){return $o(e,t,n)}function Mc(e,t){return t==="excess_ports"?e==="mcp"?"This node has more wire ports than its type declares \u2014 remove extra ports or raise the node outputs, then retry.":e==="rest"?"This node has more wire ports than its type declares \u2014 trim wires[] or raise outputs, then retry.":"This node has more wire ports than its type declares \u2014 trim wires or raise outputs, then retry.":t==="missing_target"?e==="mcp"?"Wire targets must be node ids in this flow \u2014 add the node in the same patch or use get_flow ids.":e==="rest"?"Wire targets must be node ids in this flow \u2014 add the node in the same patch or use GET /flows/{id} ids.":"wires must list existing node ids (or add those nodes in the same patch).":e==="mcp"||e==="rest"?"Fix wires: targets must exist in this flow, and port count must not exceed the node outputs.":"wires must list existing node ids (or add those nodes in the same patch)."}function Dc(e){return e==="mcp"?"Call list_node_types or search_palette. Ask the user to install via Manage palette, then recheck. This API never installs.":e==="rest"?"Call GET /node-types?q= or GET /palette/search?q=. Ask the user to install via Manage palette, then recheck. This API never installs.":"Call GET \u2026/node-types?q= or \u2026/palette/search?q=. Ask the user to install via Manage palette, then recheck. This API never installs."}function Qe(e,t,n,r){return e==="mcp"?t:e==="rest"?n:r}function $o(e,t,n={}){switch(e){case"version_mismatch":return Qe(t,"Re-read with list_flows/get_flow and retry with the current rev.","Re-read the flow and retry with the current rev.","Re-read the flow and retry with the current rev.");case"node_not_found":return Qe(t,"Call get_flow or get_node and use a node id from that response.","Call GET /flows/{id} and use a node id from that response.","Call GET \u2026/flows/<id> and use a node id from that response.");case"flow_not_found":return Qe(t,"Call list_flows to list valid ids.","Call GET /flows to list valid ids.","Use an id from GET ./flows.");case"proposal_not_found":return Qe(t,"Call list_proposals and use an id from that response.","List proposals and use an id from that response.","List proposals and use an id from that response.");case"proposal_not_owned":return"Only the access link that created a pending proposal can withdraw it.";case"proposal_not_pending":return"Only pending proposals can be withdrawn or decided.";case"confirm_required":return"Add confirm=1 to the withdraw URL (required so link prefetchers cannot withdraw).";case"invalid_wires":return Mc(t,n.cause);case"node_type_not_found":case"unknown_node_type":return Dc(t);case"missing_node_type":return'Each add op needs node.type as a non-empty string (e.g. "inject").';case"invalid_line_range":return Qe(t,'Pass lines as "A" or "A-B" (1-based inclusive). Reversed ranges (end < start) are invalid.',"Use lines=A or lines=A-B (1-based inclusive). Reversed ranges (end < start) are invalid.","Use lines=A or lines=A-B (1-based inclusive). Reversed ranges (end < start) are invalid.");case"line_range_out_of_bounds":return"start is past the end of the field \u2014 check totalLines and request a lower lines range.";case"ambiguous_match":return"find matched more than once \u2014 pass occurrence=N (1-based) or a more unique find string.";case"missing_expected_rev":return Qe(t,"Pass expectedRev from list_flows/get_flow (top-level, next to type and payload).","Pass expectedRev from GET /flows or GET /flows/{id} (top-level, next to type and payload).","Pass rev from GET \u2026/flows or \u2026/flows/<id>.");case"missing_query":return Qe(t,"Pass a non-empty q string.","q query parameter is required.","q query parameter is required.");case"unsupported_media_type":return"Send Content-Type: application/json with a JSON body.";case"text_not_found":return"Re-read the node field; find must match exactly (case-sensitive).";case"field_not_found":return"Re-read the node; field must be an existing string property (template, func, \u2026).";case"field_not_string":return Qe(t,"This tool only returns string fields (template, func, \u2026). Use get_node for other property types.","This endpoint only returns string fields (template, func, \u2026). Use GET /nodes/{id} for other property types.","This endpoint only returns string fields (template, func, \u2026). Use GET /nodes/{id} for other property types.");default:return}}function _n(e,t,n={}){let r=n.canonicalizeMessage!==!1,o=null;if(e instanceof y?o={statusCode:e.statusCode,body:{error:e.message,code:e.code,...e.details??{}}}:e instanceof J?o={statusCode:e.statusCode,body:{error:e.message,code:e.code,expectedRev:e.expectedRev,currentRev:e.currentRev}}:e instanceof z?o={statusCode:e.statusCode,body:{error:e.message,code:e.code,flowId:e.flowId}}:e instanceof ne||e instanceof Ot||e instanceof te||e instanceof X?o={statusCode:e.statusCode,body:{error:e.message,code:e.code}}:(e instanceof Ce||e instanceof be)&&(o={statusCode:e.statusCode,body:{error:e.message,code:e.code}}),!o)return null;let s=o.body.code;if(r&&!Array.isArray(o.body.errors)){let i=Oe[s];i&&(o.body.error=i)}if(typeof o.body.hint!="string"||!o.body.hint){let i=$o(s,t,{cause:o.body.cause})??Cn(s);i&&(o.body.hint=i)}return o}function mi(e,t,n={}){let o={error:n.error??Oe[t]??"Request failed",code:t,...n.details??{}},s=$o(t,e,{cause:o.cause})??Cn(t);return s&&(o.hint=s),{statusCode:n.statusCode??400,body:o}}var Oe,Fe=U(()=>{"use strict";ve();Ge();G();K();gr();Oe={node_not_found:"Node was not found",flow_not_found:"Flow was not found",field_not_found:"Field was not found",field_not_string:"Field is not a string",missing_query:"q query parameter is required",missing_flow_id:"Missing flow id",missing_node_id:"Missing node id",missing_field:"Missing field name",invalid_line_range:"lines must be A or A-B (1-based inclusive; end >= start)",line_range_out_of_bounds:"lines range is out of bounds",proposal_not_found:"Proposal was not found",proposal_not_owned:"Proposal was not created by this access link",proposal_not_pending:"Proposal is not pending",confirm_required:"Withdraw over GET requires confirm=1",unsupported_media_type:"Content-Type must be application/json",upstream_error:"Upstream request failed",internal_error:"Internal server error"};a(se,"channelErrorHint");a(Mc,"invalidWiresHint");a(Dc,"nodeTypeHint");a(Qe,"pickChannel");a($o,"hintFor");a(_n,"mapErrorForChannel");a(mi,"buildChannelError")});var vm={};ds(vm,{ACCESS_LINK_INVALID_MESSAGE:()=>st,ACCESS_LINK_MISSING_MESSAGE:()=>le,AccessLinkStore:()=>At,EDITOR_SIDEBAR_ASSET_VERSION:()=>Xt,MAX_PROPOSAL_JSON_BYTES:()=>j,SettingsStore:()=>Lt,acceptedMediaTypes:()=>wd,areAiFeaturesEnabled:()=>ge,bindSettingsStore:()=>Jn,createPluginServices:()=>Vr,default:()=>bm,getStorageDir:()=>Hr,isAdminAuthEnabled:()=>W,isMcpStreamRequest:()=>bd,packageVersion:()=>Vt,registerRoutes:()=>vd,renderEditorSidebarJs:()=>yr,renderEditorSidebarLoaderHtml:()=>wi,requireAccessLink:()=>Nt,resolveAiAccessSettings:()=>he});module.exports=Pd(vm);var yd=require("fs");var Un=require("fs"),un=require("path");G();function Bn(e){let t=(0,un.join)(e,".ai-access");return{root:t,proposals:(0,un.join)(t,"proposals"),logs:(0,un.join)(t,"logs"),settings:(0,un.join)(t,"config.json")}}a(Bn,"resolveAiAccessPaths");function Qr(e){(0,Un.mkdirSync)(e,{recursive:!0,mode:Yr});try{(0,Un.chmodSync)(e,Yr)}catch{}}a(Qr,"mkdirSecure");function fs(e){Qr(e.root),Qr(e.proposals),Qr(e.logs)}a(fs,"ensureAiAccessDirs");it();_e();function Yn(e){let t=ae(e);return`auth-tokens${(t==="/"?"":t).replace(/\//g,"-")}`}a(Yn,"editorAuthTokenKey");_e();Fe();function jc(e){if(!e)return!1;let t=e.split(";")[0]?.trim().toLowerCase()??"";return t==="application/json"||t.endsWith("+json")}a(jc,"isJsonContentType");function Hc(e){let t=e.headers["content-length"];if(typeof t=="string"&&t.length>0){let n=Number(t);if(Number.isFinite(n)&&n>0)return!0;if(n===0)return!1}return e.headers["transfer-encoding"]!==void 0}a(Hc,"hasRequestBody");function je(e="rest"){return(t,n,r)=>{let o=t.headers["content-type"];if(jc(o)){r();return}if(!o&&!Hc(t)){r();return}let s=mi(e,"unsupported_media_type",{statusCode:415});n.status(s.statusCode).json(s.body)}}a(je,"requireJsonContentType");var Uc="text/plain; charset=utf-8",Bc="text/html; charset=utf-8",qc="default-src 'none'; base-uri 'self'; form-action 'none'; frame-ancestors 'none'";function Wc(e){let t=e.query?.format;return typeof t=="string"?t.toLowerCase():void 0}a(Wc,"formatParam");function zc(e){let t=Wc(e);if(t==="md"||t==="json")return"native";if(!e.get("accept"))return"html";let n=e.accepts(["text/html","application/json","text/markdown","text/plain"]);return n==="application/json"||n==="text/markdown"?"native":n==="text/plain"?"plain":"html"}a(zc,"chooseGetLinkRepresentation");function hi(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}a(hi,"escapeHtml");var Gc=/(?<![A-Za-z0-9_.~\-/])\.\/[A-Za-z0-9._~\-/]+(?:\?[A-Za-z0-9._~\-=&%]+)?/g;function Jc(e){return e.replace(Gc,(t,n)=>{if(e.startsWith("<",n+t.length))return t;let r=t.replace(/[.]+$/,""),o=t.slice(r.length);return r.length<=2||r.includes("..")||r.includes("//")||r.includes("&")?t:`<a href="${r}">${r}</a>${o}`})}a(Jc,"linkifyEscaped");function Kc(e,t){return`<!doctype html>
|
|
8
8
|
<html><head><meta charset="utf-8">${t?`<base href="${hi(t)}">`:""}<title>Node-RED AI Access</title></head><body><pre>${Jc(hi(e))}</pre></body></html>
|
|
9
|
-
`}a(Kc,"renderGetLinkHtml");function Vc(e){let t=e.split("?")[0]??"",n=/^(.*?\/mcp\/a\/[A-Za-z0-9_-]+)(?:\/|$)/.exec(t);if(!(!n?.[1]||!/^[A-Za-z0-9._~\-/]*$/.test(n[1])))return`${n[1]}/`}a(Vc,"getLinkBaseHref");function Xc(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}a(Xc,"prettyJson");function gi(){return(e,t,n)=>{let r=zc(e),o=Vc(e.originalUrl);t.vary("Accept"),t.setHeader("Cache-Control","no-store"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("X-Robots-Tag","noindex, nofollow"),t.setHeader("X-Content-Type-Options","nosniff");let s=t.send.bind(t);t.send=(i=>{let d=String(t.getHeader("Content-Type")??"").toLowerCase(),l=d.startsWith("application/json"),c=d.startsWith("text/markdown");if(r==="native"||!l&&!c||t.headersSent)return s(i);let u=typeof i=="string"?i:Buffer.isBuffer(i)?i.toString("utf8"):void 0;return u===void 0?s(i):r==="plain"?(t.setHeader("Content-Type",Uc),s(u)):(t.setHeader("Content-Type",Bc),t.setHeader("Content-Security-Policy",qc),s(Kc(l?Xc(u):u,o)))}),n()}}a(gi,"getLinkContentNegotiation");qn();_e();function Yc(e){let t=de(e.settings.httpAdminRoot),n=qe(e.settings.httpAdminRoot),r="0.2.0-beta.
|
|
9
|
+
`}a(Kc,"renderGetLinkHtml");function Vc(e){let t=e.split("?")[0]??"",n=/^(.*?\/mcp\/a\/[A-Za-z0-9_-]+)(?:\/|$)/.exec(t);if(!(!n?.[1]||!/^[A-Za-z0-9._~\-/]*$/.test(n[1])))return`${n[1]}/`}a(Vc,"getLinkBaseHref");function Xc(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}a(Xc,"prettyJson");function gi(){return(e,t,n)=>{let r=zc(e),o=Vc(e.originalUrl);t.vary("Accept"),t.setHeader("Cache-Control","no-store"),t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("X-Robots-Tag","noindex, nofollow"),t.setHeader("X-Content-Type-Options","nosniff");let s=t.send.bind(t);t.send=(i=>{let d=String(t.getHeader("Content-Type")??"").toLowerCase(),l=d.startsWith("application/json"),c=d.startsWith("text/markdown");if(r==="native"||!l&&!c||t.headersSent)return s(i);let u=typeof i=="string"?i:Buffer.isBuffer(i)?i.toString("utf8"):void 0;return u===void 0?s(i):r==="plain"?(t.setHeader("Content-Type",Uc),s(u)):(t.setHeader("Content-Type",Bc),t.setHeader("Content-Security-Policy",qc),s(Kc(l?Xc(u):u,o)))}),n()}}a(gi,"getLinkContentNegotiation");qn();_e();function Yc(e){let t=de(e.settings.httpAdminRoot),n=qe(e.settings.httpAdminRoot),r="0.2.0-beta.4",o=[{method:"GET",path:"/",auth:"none",summary:"This discovery index"},{method:"GET",path:"/openapi.yaml",auth:"none",summary:"OpenAPI 3.1 specification (YAML)"},{method:"GET",path:"/openapi.json",auth:"none",summary:"OpenAPI 3.1 specification (JSON)"},{method:"GET",path:"/status",auth:"admin-or-access-link",summary:"Plugin status and caller info"},{method:"GET",path:"/flows",auth:"admin-or-access-link",summary:"List flows + rev"},{method:"GET",path:"/flows/{id}",auth:"admin-or-access-link",summary:"Get one flow tab + rev (?summary=1 for node list without field contents)"},{method:"GET",path:"/nodes/{id}",auth:"admin-or-access-link",summary:"Get one full node (optional ?flow=)"},{method:"GET",path:"/nodes/{id}/field/{name}",auth:"admin-or-access-link",summary:"Get one node field (?lines=A-B optional)"},{method:"GET",path:"/search",auth:"admin-or-access-link",summary:"Text search across string fields (?q=&flow=)"},{method:"GET",path:"/node-types",auth:"admin-or-access-link",summary:"List installed palette node types (?q= filter)"},{method:"GET",path:"/node-types/{type}",auth:"admin-or-access-link",summary:"Detail for one installed node type (defaults JSON, inputs/outputs, help; ?help=0 omits help)"},{method:"GET",path:"/palette/search",auth:"admin-or-access-link",summary:"Search Node-RED catalogue (recommend only; never installs) (?q=)"},{method:"POST",path:"/proposals",auth:"access-link",summary:"Create a replace_flow proposal"},{method:"GET",path:"/proposals",auth:"admin-or-access-link",summary:"List proposals (admin: all; link: own)"},{method:"GET",path:"/proposals/{id}",auth:"admin-or-access-link",summary:"Get one proposal"},{method:"GET",path:"/proposals/{id}/diff",auth:"admin-or-access-link",summary:"Diff proposal vs current flow"}];return{ok:!0,name:"node-red-ai-access",version:r,description:"Temporary, owner-approved Node-RED access for AI clients over plain HTTP (REST) or MCP.",auth:{scheme:"Bearer",header:"Authorization: Bearer <token>",description:"An admin with * mints tokens on the /ai-access dashboard (Access tokens tab) (POST /links only \u2014 never under GET /mcp/a/<token>). Each token has kind get_link | rest | mcp and only works on that surface. Send rest/mcp tokens as Authorization: Bearer <token>. Missing/invalid \u2192 401 access_link_missing / access_link_invalid; wrong kind \u2192 403 wrong_token_kind. GET /mcp/a links cannot create tokens.",tokenKinds:["get_link","rest","mcp"],mint:{path:"/links",method:"POST",auth:"admin",note:"Admin * only. Not available under /mcp/a/<token>."}},openapi:`${t}/openapi.yaml`,openapiJson:`${t}/openapi.json`,mcp:n,apiBase:t,getLink:{base:"/mcp/a/<token>",canMintTokens:!1,note:"Self-contained GET surface for get_link tokens only. No POST /links equivalent."},endpoints:o}}a(Yc,"buildDiscoveryIndex");function Mo(e){return(t,n)=>{n.status(200).json(Yc(e))}}a(Mo,"discoveryIndexHandler");function yi(){return(e,t)=>{t.status(404).json({error:"Not found",code:"not_found"})}}a(yi,"mcpApiNotFoundHandler");var Kt;function Vt(){return Kt||(Kt="0.2.0-beta.4",Kt)}a(Vt,"packageVersion");var Xt=Vt();function Qc(){return`#red-ui-sidebar-ai-access {
|
|
10
10
|
position: relative;
|
|
11
11
|
height: 100%;
|
|
12
12
|
display: flex;
|
|
@@ -950,9 +950,8 @@ strings you will paste publicly beyond this temporary link.
|
|
|
950
950
|
`)){let f=i.split(`
|
|
951
951
|
`);for(let m=0;m<f.length;m+=1){let g=(f[m]??"").indexOf(n);if(g>=0){let x=0;for(let S=0;S<m;S+=1)x+=(f[S]?.length??0)+1;u(m+1,x+g)}}}if(n.includes(`
|
|
952
952
|
`)){let f=0;for(;f<=i.length;){let m=i.indexOf(n,f);if(m<0)break;u(Uu(i,m),m),f=m+Math.max(1,n.length)}}if(d.length===0)continue;let p=d.length;r.push({flowId:t,nodeId:e.id,field:s,lines:d.slice(0,Ou),lineCount:p,snippet:Hu(i,Math.max(0,c),n.length)})}return r.length>=o}a(qo,"searchInNode");function qi(e){return[...e.nodes??[],...e.configs??[]]}a(qi,"nodePool");async function Bu(e,t,n,r,o){let s=await xe(e,t);for(let i of qi(s.flow))if(qo(i,t,n,r,o))return{rev:s.rev,truncated:!0};return{rev:s.rev,truncated:!1}}a(Bu,"searchOneFlow");async function qu(e,t,n,r){let o=await pe(e),s=new Set;for(let i of Ui(o.flows))if(i.id)try{let d=await xe(e,i.id);for(let l of qi(d.flow))if(s.add(l.id),qo(l,i.id,t,n,r))return{rev:o.rev,truncated:!0}}catch{}for(let i of o.flows){if(!i||typeof i!="object"||Array.isArray(i))continue;let d=i;if(!d.id||s.has(d.id)||d.type==="tab"||d.type==="subflow")continue;let l=typeof d.z=="string"?d.z:null;if(qo(d,l,t,n,r))return{rev:o.rev,truncated:!0}}return{rev:o.rev,truncated:!1}}a(qu,"searchAllFlows");async function Pr(e,t,n={}){if(typeof t!="string"||!t.trim())throw new y("q query parameter is required","missing_query");let r=typeof n.cap=="number"&&n.cap>0?Math.floor(n.cap):Fu,o=[],s=n.flowId?await Bu(e,n.flowId,t,o,r):await qu(e,t,o,r),i={rev:s.rev,q:t,hits:o,hitCount:o.length,truncated:s.truncated,cap:r};return n.flowId&&(i.flowId=n.flowId),i}a(Pr,"searchFlows");function Wi(e){if(e===void 0)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}a(Wi,"isTruthyQueryFlag");function Wu(e,t,n){switch(e){case"node_not_found":case"flow_not_found":case"field_not_found":return n??se(e,t);default:return se(e,t)}}a(Wu,"layeredReadErrorHint");function yt(e){return Oe[e]??"Request failed"}a(yt,"safeErrorText");function fe(e,t,n){e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Content-Type","application/json; charset=utf-8"),e.status(t).json(n)}a(fe,"sendJson");function Rr(e,t,n,r){let o=O(t,n);if(!o)return!1;let s=o.body.code,i={error:yt(s),code:s};typeof o.body.matchCount=="number"&&(i.matchCount=o.body.matchCount),typeof o.body.totalLines=="number"&&(i.totalLines=o.body.totalLines),typeof o.body.expectedRev=="string"&&(i.expectedRev=o.body.expectedRev),typeof o.body.currentRev=="string"&&(i.currentRev=o.body.currentRev);let d=Wu(s,n,r);return d&&(i.hint=d),fe(e,o.statusCode,i),!0}a(Rr,"sendMappedError");function _r(e){fe(e,502,{error:yt("upstream_error"),code:"upstream_error"})}a(_r,"sendUpstreamError");function Lr(e,t="rest"){return async(n,r)=>{let o=n.params.id;if(typeof o!="string"||o.length===0){fe(r,400,{error:yt("missing_flow_id"),code:"missing_flow_id"});return}let s=Wi(_(n.query,"summary"));try{if(s){fe(r,200,await xr(e,o));return}fe(r,200,await xe(e,o))}catch(i){if(Rr(r,i,t))return;_r(r)}}}a(Lr,"getFlowOrSummaryHandler");function Cr(e,t="rest"){return async(n,r)=>{let o=n.params.id;if(typeof o!="string"||!o){fe(r,400,{error:yt("missing_node_id"),code:"missing_node_id"});return}let s=_(n.query,"flow");try{fe(r,200,await Sr(e,o,s))}catch(i){if(Rr(r,i,t,t==="get"?"Call GET \u2026/flows/<id>?summary=1 or \u2026/search?q=\u2026":t==="mcp"?void 0:"Call GET \u2026/flows/<id>?summary=1 or \u2026/search?q=\u2026"))return;_r(r)}}}a(Cr,"getNodeHandler");function Er(e,t="rest"){return async(n,r)=>{let o=n.params.id,s=n.params.name;if(typeof o!="string"||!o){fe(r,400,{error:yt("missing_node_id"),code:"missing_node_id"});return}if(typeof s!="string"||!s){fe(r,400,{error:yt("missing_field"),code:"missing_field"});return}let i=_(n.query,"flow"),d=_(n.query,"lines");try{fe(r,200,await Tr(e,o,s,{...i?{flowId:i}:{},...d?{lines:d}:{}}))}catch(l){if(Rr(r,l,t,"Use summary/search to discover node ids and fields."))return;_r(r)}}}a(Er,"getNodeFieldHandler");function Ir(e,t="rest"){return async(n,r)=>{let o=_(n.query,"q");if(!o){fe(r,400,{error:yt("missing_query"),code:"missing_query",hint:t==="get"?"Example: GET \u2026/search?q=TODO&flow=tab1":se("missing_query",t)});return}let s=_(n.query,"flow");try{fe(r,200,await Pr(e,o,s?{flowId:s}:{}))}catch(i){if(Rr(r,i,t))return;_r(r)}}}a(Ir,"searchFlowsHandler");K();ut();var zu={missing_node_type:"Missing node type",missing_query:"q query parameter is required",node_type_not_found:"Node type was not found",catalogue_unavailable:"Node-RED catalogue unavailable",unknown_node_type:"Unknown node type",upstream_error:"Upstream error"};function En(e){return zu[e]??"Request failed"}a(En,"safeErrorText");function et(e,t,n){e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Content-Type","application/json; charset=utf-8"),e.setHeader("Cache-Control","no-store"),e.status(t).json(n)}a(et,"sendJson");function Wo(e,t){let n=O(t);if(!n)return!1;let r=n.body.code,o={error:En(r),code:r};return typeof n.body.type=="string"&&(o.type=n.body.type),Array.isArray(n.body.nearest)&&(o.nearest=n.body.nearest),typeof n.body.didYouMean=="string"?(o.didYouMean=n.body.didYouMean,o.caseSensitive=!0,o.hint=`Types are case-sensitive \u2014 use '${n.body.didYouMean}' exactly.`):(r==="node_type_not_found"||r==="unknown_node_type")&&(o.hint="Call GET \u2026/node-types?q= or \u2026/palette/search?q=. Ask the user to install via Manage palette, then recheck node-types. This API never installs."),r==="catalogue_unavailable"&&(o.hint="Retry later; palette search is recommend-only and never installs packages."),et(e,n.statusCode,o),!0}a(Wo,"sendMappedError");function Nr(e){return async(t,n)=>{try{let r=_(t.query,"q"),o=await ir(e.nodeTypes,r?{q:r}:{});et(n,200,o)}catch(r){if(Wo(n,r))return;et(n,502,{error:En("upstream_error"),code:"upstream_error"})}}}a(Nr,"listNodeTypesHandler");function Fr(e){return async(t,n)=>{try{let r=t.params.type,o=typeof r=="string"?decodeURIComponent(r):"",s=_(t.query,"help"),i=!(s==="0"||s==="false"||s==="no"||s==="omit"),d=await ct(e.nodeTypes,o,{includeHelp:i});et(n,200,d)}catch(r){if(Wo(n,r))return;et(n,502,{error:En("upstream_error"),code:"upstream_error"})}}}a(Fr,"getNodeTypeHandler");function Or(e){return async(t,n)=>{try{let r=_(t.query,"q");if(!r){et(n,400,{error:En("missing_query"),code:"missing_query",hint:"Pass ?q= to search the Node-RED catalogue (recommend only)."});return}let o=await ar(e.nodeTypes,r,{...e.catalogueFetcher?{catalogueFetcher:e.catalogueFetcher}:{},...e.catalogueUrl?{catalogueUrl:e.catalogueUrl}:{}});et(n,200,o)}catch(r){if(Wo(n,r))return;et(n,502,{error:En("upstream_error"),code:"upstream_error"})}}}a(Or,"searchPaletteHandler");Xe();ve();function tn(e,t){return e[t]??""}a(tn,"lineAt");function In(e,t,n){let r=e[t];return r?r[n]??0:0}a(In,"cell");function zi(e,t,n,r){let o=e[t];o&&(o[n]=r)}a(zi,"setCell");function Ji(e,t){let n=Gi(e),r=Gi(t),o=n.length,s=r.length,i=[];for(let u=0;u<=o;u+=1){let p=[];for(let f=0;f<=s;f+=1)p.push(0);i.push(p)}for(let u=o-1;u>=0;u-=1)for(let p=s-1;p>=0;p-=1)tn(n,u)===tn(r,p)?zi(i,u,p,In(i,u+1,p+1)+1):zi(i,u,p,Math.max(In(i,u+1,p),In(i,u,p+1)));let d=[],l=0,c=0;for(;l<o&&c<s;){let u=tn(n,l),p=tn(r,c);u===p?(d.push({op:"equal",text:u}),l+=1,c+=1):In(i,l+1,c)>=In(i,l,c+1)?(d.push({op:"remove",text:u}),l+=1):(d.push({op:"add",text:p}),c+=1)}for(;l<o;)d.push({op:"remove",text:tn(n,l)}),l+=1;for(;c<s;)d.push({op:"add",text:tn(r,c)}),c+=1;return d}a(Ji,"diffLines");function Gi(e){return e.length===0?[]:e.split(`
|
|
953
|
-
`)}a(Gi,"splitLines");Ae();var Xi=new Set(["func","template","info","payload","code","text","format","syntax"]),Gu=new Set(["x","y","w","h","wires","g"]),Ju=new Set(["w","h","g"]);function wt(e){if(typeof e.name=="string"&&e.name.length>0)return e.name;if(typeof e.label=="string"&&e.label.length>0)return e.label}a(wt,"nodeName");function Ki(e){let t=new Map;for(let n of e.nodes??[])t.set(n.id,n);for(let n of e.configs??[])t.set(n.id,n);return t}a(Ki,"collectNodes");function Dr(e){if(e===void 0)return"undefined";if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Dr).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${Dr(t[r])}`).join(",")}}`}a(Dr,"stableStringify");function Yi(e,t){return Dr(e)===Dr(t)}a(Yi,"valuesEqual");function jr(e){return typeof e=="string"?e:null}a(jr,"asText");function Ku(e){return/<\/?[a-z][\s\S]*>/i.test(e.slice(0,800))}a(Ku,"looksLikeHtml");function Vu(e,t,n){if(t!=="template")return!1;let r=typeof e.format=="string"?e.format.toLowerCase():"";return r==="html"||r==="handlebars"||r==="mustache"?!0:Ku(n)}a(Vu,"isHtmlTemplateField");function Qi(e,t,n){let r=jr(n);if(Xi.has(t)&&r!==null){let o={key:t,kind:"text",value:r};return Vu(e,t,r)&&(o.preview="html"),o}return{key:t,kind:"scalar",value:n===void 0?null:n}}a(Qi,"toPresenceProperty");function Xu(e,t){let n=[];for(let r of[...Object.keys(e)].sort())if(!(Ju.has(r)||r==="id"||r==="z")){if(r==="wires"){let o=Zi(e,t);n.push({key:"wires",kind:"scalar",value:o.length>0?o:e.wires??null});continue}n.push(Qi(e,r,e[r]))}return n}a(Xu,"nodeProperties");function Zi(e,t){let n=e.wires;if(!Array.isArray(n)||n.length===0)return[];let r=[];return n.forEach((o,s)=>{if(!Array.isArray(o))return;let i=[];for(let d of o){if(typeof d!="string"||!d)continue;let l=t.get(d);i.push({id:d,name:l?wt(l)??l.type:d})}r.push({port:s,to:i})}),r}a(Zi,"describeWiresStructured");var Yu=new Set(["func","template","code","text"]);function Qu(e,t){let n=[],r=wt(e);r&&n.push({key:"name",kind:"scalar",value:r});let o=Zi(e,t);o.length>0&&n.push({key:"wires",kind:"scalar",value:o});for(let s of Yu){if(!(s in e))continue;let i=jr(e[s]);i===null||i.length===0||n.push(Qi(e,s,i))}return n}a(Qu,"buildKeyFields");function Zu(e,t,n){let r=Ve(e.type),o=wt(e),s=o?` "${o}"`:"",i=t?` in "${t}"`:"",d=n===1?"1 field":`${n} fields`;return`Changes ${r} node${s}${i} (${d})`}a(Zu,"buildModifiedSummary");function ep(e,t,n){let r=Ve(e.type),o=wt(e),s=t==="added"?"Adds":"Removes",i=t==="added"?"to":"from",d=o?` ${JSON.stringify(o)}`:"",l=n?` ${i} flow ${JSON.stringify(n)}`:"",c=`${s} ${r} node${d}${l}`;if(t==="added"&&r==="template"){let u=typeof e.field=="string"&&e.field?e.field:"";u&&(c+=`, output to msg.${u}`)}return c}a(ep,"buildPresenceSummary");function $r(e,t,n,r){let o={id:e.id,type:e.type,summary:ep(e,t,n),keyFields:Qu(e,r),properties:Xu(e,r)},s=wt(e);return s!==void 0&&(o.name=s),o}a($r,"toPresenceNode");function tp(e,t){let n=new Set([...Object.keys(e),...Object.keys(t)]),r=[];for(let o of[...n].sort()){if(Gu.has(o)||o==="id"||o==="z")continue;let s=e[o],i=t[o];if(Yi(s,i))continue;let d=jr(s),l=jr(i);if(Xi.has(o)&&(d!==null||l!==null)){let c=d??"",u=l??"";r.push({key:o,kind:"text",before:c,after:u,lines:Ji(c,u)});continue}r.push({key:o,kind:"scalar",before:s===void 0?null:s,after:i===void 0?null:i})}return r}a(tp,"compareNodes");function np(e,t){let n=["label","disabled","info","env"],r=[];for(let o of n)Yi(e[o],t[o])||r.push(o);return r}a(np,"compareTabMeta");function Mr(e){return typeof e.label=="string"&&e.label.trim()?e.label.trim():""}a(Mr,"flowLabelOf");function ea(e,t){let n=Ki(t),r=Ki(e),o=Mr(e)||Mr(t),s=Mr(t)||Mr(e),i=[],d=[],l=[];for(let c of e.nodes??[])n.has(c.id)||i.push($r(c,"added",o,r));for(let c of e.configs??[])n.has(c.id)||i.push($r(c,"added",o,r));for(let c of t.nodes??[])r.has(c.id)||d.push($r(c,"removed",s,n));for(let c of t.configs??[])r.has(c.id)||d.push($r(c,"removed",s,n));for(let[c,u]of r){let p=n.get(c);if(!p)continue;let f=tp(p,u);if(f.length>0){let m={id:c,type:u.type||p.type,summary:Zu(u,o||s,f.length),changes:f},h=wt(u)??wt(p);h!==void 0&&(m.name=h),l.push(m)}}return l.sort((c,u)=>c.id.localeCompare(u.id)),{summary:{added:i.length,removed:d.length,modified:l.length,tabChanges:np(t,e),beforeNodeCount:n.size,afterNodeCount:r.size},added:i,removed:d,modified:l}}a(ea,"buildDiffSections");function Vi(e,t,n={}){let r=ea(e.payload.flow,t.flow),o=n.currentRev??t.rev,s=e.expectedRev,i=n.baseRevStale??(e.status==="pending"&&s!==o),d={proposalId:e.id,flowId:e.payload.flowId,expectedRev:s,currentRev:o,baseRevStale:i,compareAgainst:n.compareAgainst??"current",...r};return e.warnings&&e.warnings.length>0&&(d.warnings=e.warnings.map(l=>({...l}))),n.baseSnapshotMissing&&(d.baseSnapshotMissing=!0),n.vsCurrent&&(d.vsCurrent=n.vsCurrent),d}a(Vi,"buildProposalDiff");async function nn(e,t){let n=e.payload.flowId,r={id:n,type:"tab",nodes:[],configs:[]},o=e.expectedRev,s=r;try{let c=await t.getFlow(n);o=c.rev,s=c.flow}catch(c){if(!(c instanceof z))throw c;try{o=(await t.getFlows()).rev}catch{}}let d=e.status==="pending"&&e.expectedRev!==o,l=e.baseFlow;if(l!==void 0){let c=d?ea(e.payload.flow,s):void 0;return Vi(e,{rev:e.expectedRev,flow:l},{currentRev:o,compareAgainst:"base",baseRevStale:d,...c?{vsCurrent:c}:{}})}return Vi(e,{rev:o,flow:s},{compareAgainst:"current",baseSnapshotMissing:!0,baseRevStale:d})}a(nn,"computeProposalDiff");Ae();_e();ye();var ta=require("path");function Hr(e){return(0,ta.join)(e.userDir,".ai-access")}a(Hr,"getStorageDir");var rp=["status:read","flows:read","proposals:create","proposals:read-own"];function zo(){return Vt()}a(zo,"readPackageVersion");function op(e,t=Date.now()){let n=Date.parse(e);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):0}a(op,"secondsRemainingUntil");function sp(e,t=Date.now()){let n=Date.parse(e);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/6e4)):0}a(sp,"minutesRemainingUntil");function ip(e,t){let n=de(t),r=qe(t),o=`${n}/openapi.yaml`,s=`${n}/openapi.json`;return e==="rest"?{api:n,openapi:o,openapiJson:s,discovery:n}:e==="mcp"?{rpc:r,discovery:n}:{discovery:n}}a(ip,"baseUrlsForTokenKind");function rn(e,t){let n=Kn(e,t),r=he(e.settings);if(t.auth){let o=t.auth.extra?.user;return{ok:!0,version:zo(),adminAuthEnabled:n.adminAuthEnabled,aiAccessEnabled:r.enabled,aiFeaturesEnabled:n.aiFeaturesEnabled,allowWithoutAdminAuth:n.allowWithoutAdminAuth,permission:t.auth.scopes.includes("propose")?"propose":"read",capabilities:{view:!0,manageLinks:!1,approveProposals:!1},defaultLinkTtlSeconds:r.defaultLinkTtlSeconds,maxActiveLinks:r.maxActiveLinks,defaultDeploymentType:r.defaultDeploymentType,caller:{kind:"oauth",clientId:t.auth.clientId,user:typeof o=="string"?o:"owner",scopes:t.auth.scopes}}}if(t.accessLink){let o=Date.now();return{ok:!0,version:zo(),adminAuthEnabled:n.adminAuthEnabled,aiAccessEnabled:r.enabled,aiFeaturesEnabled:n.aiFeaturesEnabled,allowWithoutAdminAuth:n.allowWithoutAdminAuth,permission:null,capabilities:{view:!0,manageLinks:!1,approveProposals:!1},defaultLinkTtlSeconds:r.defaultLinkTtlSeconds,maxActiveLinks:r.maxActiveLinks,defaultDeploymentType:r.defaultDeploymentType,caller:{kind:"access-link",linkId:t.accessLink.id,tokenKind:t.accessLink.kind,...t.accessLink.label!==void 0?{label:t.accessLink.label}:{},expiresAt:t.accessLink.expiresAt,minutesRemaining:sp(t.accessLink.expiresAt,o),secondsRemaining:op(t.accessLink.expiresAt,o),permissions:[...rp],baseUrls:ip(t.accessLink.kind,e.settings.httpAdminRoot)}}}return{ok:!0,version:zo(),adminAuthEnabled:n.adminAuthEnabled,aiAccessEnabled:r.enabled,aiFeaturesEnabled:n.aiFeaturesEnabled,allowWithoutAdminAuth:n.allowWithoutAdminAuth,permission:n.permission,capabilities:n.capabilities,storageDir:Hr(e.settings),defaultLinkTtlSeconds:r.defaultLinkTtlSeconds,maxActiveLinks:r.maxActiveLinks,defaultDeploymentType:r.defaultDeploymentType,caller:{kind:"admin",...n.permission?{permission:n.permission}:{}}}}a(rn,"buildStatus");function na(e,t){let n=t.draftStore??new br,r=t.rateLimiters??Ci(t.rateLimit??e.settings.aiAccess),o=e.httpAdmin,s="/mcp/a/:token",i=[r.ip,Ii(e,t.linkStore),r.token];o.use("/mcp/a",gi()),o.get(s,...i,R((u,p)=>{F(p),p.setHeader("X-Content-Type-Options","nosniff");let f=de(e.settings.httpAdminRoot),m=u.accessLink;if(!m){C(p,401,"Access link required","access_link_missing");return}let h=Si({link:m,openapiPath:`${f}/openapi.yaml`,restApiBase:f,mcpRpcPath:qe(e.settings.httpAdminRoot),publicOrigin:oo(u)});p.status(200).type("text/markdown; charset=utf-8").send(h)})),o.get(`${s}/status`,...i,R((u,p)=>{F(p),p.json(rn(e,u))})),o.get(`${s}/flows`,...i,R(async(u,p)=>{F(p);try{p.json(await pe(t.flowAdapter))}catch(f){let m=O(f);if(m){p.status(m.statusCode).json({...m.body,hint:"Retry after the owner fixes the plugin runtime."});return}C(p,502,f instanceof Error?f.message:String(f),"upstream_error")}})),o.get(`${s}/flows/:id`,...i,R(async(u,p)=>{F(p),await Lr(t.flowAdapter,"get")(u,p)})),o.get(`${s}/nodes/:id`,...i,R(async(u,p)=>{F(p),await Cr(t.flowAdapter,"get")(u,p)})),o.get(`${s}/nodes/:id/field/:name`,...i,R(async(u,p)=>{F(p),await Er(t.flowAdapter,"get")(u,p)})),o.get(`${s}/search`,...i,R(async(u,p)=>{F(p),await Ir(t.flowAdapter,"get")(u,p)}));let d={nodeTypes:t.nodeTypesAdapter,...t.catalogueFetcher?{catalogueFetcher:t.catalogueFetcher}:{},...t.catalogueUrl?{catalogueUrl:t.catalogueUrl}:{}};o.get(`${s}/node-types`,...i,R(async(u,p)=>{F(p),await Nr(d)(u,p)})),o.get(`${s}/node-types/:type`,...i,R(async(u,p)=>{F(p),await Fr(d)(u,p)})),o.get(`${s}/palette/search`,...i,R(async(u,p)=>{F(p),await Or(d)(u,p)}));let l=e.settings.httpAdminRoot;ap(o,s,i,t,l),o.get(`${s}/propose`,...i,R(ji(t.proposalStore,t.auditLog,t.flowAdapter,l,t.nodeTypesAdapter))),cp(o,s,i,n,t,l);let c=Fi();return o.all(`${s}/links`,c),o.all(`${s}/links/:id`,c),o.use("/mcp/a",Ni()),n}a(na,"registerGetLinkRoutes");function ap(e,t,n,r,o){e.get(`${t}/proposals`,...n,R(async(s,i)=>{F(i);let d=s.accessLink;if(!d){C(i,401,"Access link required","access_link_missing");return}let l=q(s,o),c=re(s.query),u=mr(s.query),p;try{p=(await pe(r.flowAdapter)).rev}catch{}let f=p?V(r.proposalStore,p):0,m=qt(r.proposalStore,d,l,u);i.json({proposals:m.proposals.map(h=>ue(r.proposalStore,d,h,{...l,include:c},{includeConflicts:!1})),...ft({...m,returned:m.proposals.length}),...Q(f)})})),e.get(`${t}/proposals/:id`,...n,R(async(s,i)=>{F(i);let d=s.params.id,l=s.accessLink;if(typeof d!="string"||!d){C(i,400,"Missing proposal id","missing_proposal_id");return}if(!l){C(i,401,"Access link required","access_link_missing");return}try{let c=q(s,o),u=re(s.query),p;try{p=(await pe(r.flowAdapter)).rev}catch{}let f=De(r.proposalStore,l,d,c);i.json(ue(r.proposalStore,l,f,{...c,include:u},{...p?{liveRev:p}:{}}))}catch(c){let u=O(c,"get");if(u){i.status(u.statusCode).json({...u.body,hint:u.body.hint??"List proposals with GET \u2026/proposals."});return}$(i,c);return}})),dp(e,t,n,r,o),lp(e,t,n,r,o)}a(ap,"registerGetLinkProposalRoutes");function dp(e,t,n,r,o){e.get(`${t}/proposals/:id/withdraw`,...n,R((s,i)=>{F(i);let d=s.params.id,l=s.accessLink;if(typeof d!="string"||!d){C(i,400,"Missing proposal id","missing_proposal_id");return}if(!l){C(i,401,"Access link required","access_link_missing");return}let c=s.query.confirm;if(c!=="1"&&c!=="true"){C(i,400,"Withdraw over GET requires confirm=1","confirm_required",se("confirm_required","get"));return}let u=typeof s.query.reason=="string"?s.query.reason:void 0,p=q(s,o),f=re(s.query);try{let m=Wt(r.proposalStore,r.auditLog,l,d,u,p);i.json(ue(r.proposalStore,l,m,{...p,include:f}))}catch(m){let h=O(m,"get");if(h){let g=h.body.code;C(i,h.statusCode,Oe[g]??"Request failed",g,se(g,"get"));return}C(i,500,"Internal server error","internal_error");return}}))}a(dp,"registerGetLinkWithdrawRoute");function lp(e,t,n,r,o){e.get(`${t}/proposals/:id/diff`,...n,R(async(s,i)=>{F(i);let d=s.params.id,l=s.accessLink;if(typeof d!="string"||!d){C(i,400,"Missing proposal id","missing_proposal_id");return}if(!l){C(i,401,"Access link required","access_link_missing");return}try{let c=De(r.proposalStore,l,d,q(s,o)),u=_(s.query,"format"),p=Yt(u==="json"||u==="md"?void 0:u);if(!p.ok){C(i,400,"Invalid diff format","invalid_diff_format","Valid formats: summary, full (default summary).");return}i.json(Qt(await nn(c,r.flowAdapter),p.format))}catch(c){let u=O(c);if(u){i.status(u.statusCode).json(u.body);return}$(i,c);return}}))}a(lp,"registerGetLinkDiffRoute");function cp(e,t,n,r,o,s){e.get(`${t}/draft/new`,...n,R($i(r,o.flowAdapter))),e.get(`${t}/draft/:draftId/append`,...n,R(Mi(r))),e.get(`${t}/draft/:draftId/submit`,...n,R(Di(r,o.proposalStore,o.auditLog,o.flowAdapter,s,o.nodeTypesAdapter)))}a(cp,"registerGetLinkDraftRoutes");G();var ra=require("module");function up(){if(typeof require=="function")return require;let e=(0,eval)("import.meta.url");return(0,ra.createRequire)(e)}a(up,"createPluginRequire");function pp(e){try{let r=up()("@node-red/runtime")._?.adminApi?.httpAdmin;if(r&&typeof r.use=="function"&&r!==e.httpAdmin)return r}catch{}return null}a(pp,"resolveEditorHttpAdmin");function oa(e){let t=[e.httpAdmin],n=pp(e);return n&&t.push(n),t}a(oa,"httpAdminAppsForMcpErrors");var sa=Symbol.for("com55.ai-access.mcpJsonErrorHandler");function fp(e){let t=e??"/";for(;t.endsWith("/");)t=t.slice(0,-1);let n=new Set;for(let r of t?["",t]:[""])for(let o of["/mcp","/mcp/rpc"])n.add(r+o),n.add(`${r+o}/`);return r=>n.has(r)}a(fp,"mcpRpcMatcher");function Go(e){return e.includes("/mcp")}a(Go,"isMcpPath");function mp(e){return e.path||e.url||e.originalUrl||""}a(mp,"requestPath");function hp(e){if(!e||typeof e!="object")return!1;let t=e;if(t.type==="entity.parse.failed"||e instanceof SyntaxError)return!0;let n=typeof e.message=="string"?e.message:"";return/JSON/i.test(n)&&(t.status===400||t.statusCode===400)}a(hp,"isJsonParseError");function gp(e){if(!e||typeof e!="object")return!1;let t=e;return t.type==="entity.too.large"||t.status===413||t.statusCode===413||t.message==="request entity too large"}a(gp,"isPayloadTooLarge");function yp(e){let t=fp(e);return(n,r,o,s)=>{if(o.headersSent){s(n);return}let i=mp(r);if(hp(n)&&Go(i)){if(t(i)){o.status(400).json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null});return}o.status(400).json({error:"Invalid JSON body",code:"invalid_json"});return}if(gp(n)&&Go(i)){o.status(413).json({error:`Request body exceeds limit of ${j} bytes`,code:"payload_too_large"});return}if(Go(i)){if(t(i)){o.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:wr(n).error,data:{code:"internal_error"}},id:null});return}o.status(500).json(wr(n));return}s(n)}}a(yp,"mcpJsonErrorHandler");function wp(e,t){let n=e;n[sa]||(n[sa]=!0,e.use(yp(t)))}a(wp,"attachOnce");function ia(e){for(let t of oa(e))wp(t,e.settings.httpAdminRoot)}a(ia,"attachMcpJsonErrorHandlers");Ln();var bt=class extends Error{static{a(this,"AccessLinkLimitError")}code="access_link_limit";statusCode=409;constructor(t){super(`Cannot create access link: at most ${t} active links are allowed. Revoke an existing link first.`),this.name="AccessLinkLimitError"}},vt=class extends Error{static{a(this,"AccessLinkNotFoundError")}code="access_link_not_found";statusCode=404;constructor(t){super(`Access link '${t}' was not found`),this.name="AccessLinkNotFoundError"}},Nn=class extends Error{static{a(this,"AccessLinkValidationError")}code="access_link_invalid";statusCode=400;constructor(t){super(t),this.name="AccessLinkValidationError"}},tt=class extends Error{static{a(this,"AccessLinkTtlError")}code="invalid_ttl";statusCode=400;hint=mt;constructor(t){super(t),this.name="AccessLinkTtlError"}};var kt=require("crypto");Ln();function Jo(e){return e==="get_link"||e==="rest"||e==="mcp"}a(Jo,"isAccessLinkKind");function Ko(e){return e??"get_link"}a(Ko,"resolveAccessLinkKind");function aa(e){return(0,kt.createHash)("sha256").update(e,"utf8").digest("hex")}a(aa,"hashToken");function bp(e,t){let n=Buffer.from(e,"utf8"),r=Buffer.from(t,"utf8");return n.length!==r.length?!1:(0,kt.timingSafeEqual)(n,r)}a(bp,"hashesEqual");function Fn(e){let t={id:e.id,kind:Ko(e.kind),createdAt:new Date(e.createdAtMs).toISOString(),expiresAt:new Date(e.expiresAtMs).toISOString()};return e.label!==void 0&&(t.label=e.label),e.lastUsedAtMs!==void 0&&(t.lastUsedAt=new Date(e.lastUsedAtMs).toISOString()),e.createdBy!==void 0&&(t.createdBy=e.createdBy),t}a(Fn,"toPublic");var At=class{static{a(this,"AccessLinkStore")}links=new Map;defaultTtlSeconds;maxActiveLinks;now;randomId;randomToken;constructor(t={}){this.defaultTtlSeconds=t.defaultTtlSeconds??14400,this.maxActiveLinks=t.maxActiveLinks??10,this.now=t.now??(()=>Date.now()),this.randomId=t.randomId??(()=>(0,kt.randomBytes)(12).toString("hex")),this.randomToken=t.randomToken??(()=>`aia_${(0,kt.randomBytes)(32).toString("base64url")}`)}configureDefaults(t){typeof t.defaultTtlSeconds=="number"&&Number.isFinite(t.defaultTtlSeconds)&&t.defaultTtlSeconds>0&&(this.defaultTtlSeconds=Math.floor(t.defaultTtlSeconds)),typeof t.maxActiveLinks=="number"&&Number.isFinite(t.maxActiveLinks)&&t.maxActiveLinks>0&&(this.maxActiveLinks=Math.floor(t.maxActiveLinks))}isActive(t,n){return t.revokedAtMs!==void 0?!1:t.expiresAtMs>n}list(){let t=this.now();return[...this.links.values()].filter(n=>this.isActive(n,t)).sort((n,r)=>r.createdAtMs-n.createdAtMs).map(Fn)}create(t={}){let n=this.now();if([...this.links.values()].filter(p=>this.isActive(p,n)).length>=this.maxActiveLinks)throw new bt(this.maxActiveLinks);let o=this.defaultTtlSeconds;if(t.ttlSeconds!==void 0){if(typeof t.ttlSeconds!="number"||!Number.isFinite(t.ttlSeconds)||t.ttlSeconds<=0)throw new tt("ttlSeconds must be a positive number");o=Math.floor(t.ttlSeconds)}let s=typeof t.label=="string"&&t.label.trim().length>0?t.label.trim():void 0,i=Ko(t.kind),d=No(i);if(o>d)throw new tt(Fo(i,d));let l=this.randomId(),c=this.randomToken(),u={id:l,tokenHash:aa(c),kind:i,createdAtMs:n,expiresAtMs:n+o*1e3};return s!==void 0&&(u.label=s),t.createdBy!==void 0&&(u.createdBy=t.createdBy),this.links.set(l,u),{...Fn(u),token:c}}revoke(t){let n=this.links.get(t);if(!n)throw new vt(t);return n.revokedAtMs??=this.now(),Fn(n)}getById(t){if(typeof t!="string"||t.length===0)return null;let n=this.links.get(t);return n?Fn(n):null}validateResult(t){if(typeof t!="string"||t.length===0)return{status:"invalid"};let n=aa(t),r=this.now();for(let o of this.links.values())if(bp(o.tokenHash,n))return o.revokedAtMs!==void 0?{status:"invalid"}:o.expiresAtMs<=r?{status:"expired",expiresAt:new Date(o.expiresAtMs).toISOString()}:(o.lastUsedAtMs=r,{status:"active",link:Fn(o)});return{status:"invalid"}}validate(t){let n=this.validateResult(t);return n.status==="active"?n.link:null}size(){return this.links.size}clear(){this.links.clear()}upsertRecordForTest(t){let n={...t};delete n.token,this.links.set(t.id,n)}};Ln();ie();ye();function Vo(e,t){return t}a(Vo,"storeForRequest");function la(e){let t=typeof e.user?.username=="string"?e.user.username:void 0;return t?{kind:"admin",username:t}:{kind:"admin"}}a(la,"adminActor");function Ur(e){let t=he(e.settings);return new At({defaultTtlSeconds:t.defaultLinkTtlSeconds,maxActiveLinks:t.maxActiveLinks})}a(Ur,"createConfiguredLinkStore");function ca(e){e.setHeader("Cache-Control","no-store"),e.setHeader("Pragma","no-cache")}a(ca,"noStore");function ua(e,t){return(n,r)=>{let s=Vo(e,t).list();ca(r),r.json({links:s})}}a(ua,"listLinksHandler");function pa(e,t,n){return(r,o)=>{let s=r.body??{},i={};if(s.ttlSeconds!==void 0){if(typeof s.ttlSeconds!="number"){o.status(400).json({error:"ttlSeconds must be a positive number",code:"invalid_ttl",hint:mt});return}i.ttlSeconds=s.ttlSeconds}if(typeof s.label=="string"&&(i.label=s.label),s.kind!==void 0){if(!Jo(s.kind)){o.status(400).json({error:"kind must be one of: 'get_link', 'rest', 'mcp'",code:"invalid_link_kind"});return}i.kind=s.kind}typeof r.user?.username=="string"&&(i.createdBy=r.user.username);try{let d=Vo(e,t).create(i),l=d.kind;if(n){let c=Date.parse(d.createdAt),u=Date.parse(d.expiresAt),p=Number.isFinite(c)&&Number.isFinite(u)&&u>c?Math.round((u-c)/1e3):void 0;n.append("link.created",la(r),{linkId:d.id,label:d.label,expiresAt:d.expiresAt,createdAt:d.createdAt,kind:l,...p!==void 0?{ttlSeconds:p}:{}})}if(ca(o),l==="get_link"){let c=Ps(r,e.settings.httpAdminRoot,d.token);o.status(201).json({...d,url:c});return}o.status(201).json({...d})}catch(d){if(d instanceof bt){o.status(d.statusCode).json({error:d.message,code:d.code});return}if(d instanceof tt){o.status(d.statusCode).json({error:d.message,code:d.code,hint:d.hint});return}if(d instanceof Nn){o.status(d.statusCode).json({error:d.message,code:d.code});return}$(o,d);return}}}a(pa,"createLinkHandler");function fa(e,t,n){return(r,o)=>{let s=r.params.id;if(typeof s!="string"||s.length===0){o.status(400).json({error:"Missing link id"});return}try{let i=Vo(e,t).revoke(s);if(n){let d=Date.parse(i.createdAt),l=Date.parse(i.expiresAt),c=Number.isFinite(d)&&Number.isFinite(l)&&l>d?Math.round((l-d)/1e3):void 0;n.append("link.revoked",la(r),{linkId:i.id,label:i.label,expiresAt:i.expiresAt,createdAt:i.createdAt,kind:i.kind,...c!==void 0?{ttlSeconds:c}:{}})}o.json({revoked:!0,link:i})}catch(i){if(i instanceof vt){o.status(i.statusCode).json({error:i.message,code:i.code});return}$(o,i);return}}}a(fa,"revokeLinkHandler");function vp(e){let t=Date.parse(e.createdAt),n=Date.parse(e.expiresAt);if(Number.isFinite(t)&&Number.isFinite(n)&&n>t)return Math.round((n-t)/1e3)}a(vp,"ttlSecondsFromLink");function kp(e,t){if(!t||e.action!=="link.created"&&e.action!=="link.revoked")return e;let n={...e.details??{}},r=typeof n.linkId=="string"?n.linkId:"";if(!r)return e;let o=n.label==null||n.label==="",s=n.expiresAt==null||n.expiresAt==="",i=n.createdAt==null||n.createdAt==="",d=n.ttlSeconds==null;if(!o&&!s&&!i&&!d)return e;let l=t.getById(r);if(!l)return e;if(o&&l.label&&(n.label=l.label),s&&(n.expiresAt=l.expiresAt),i&&(n.createdAt=l.createdAt),d){let c=vp(l);c!==void 0&&(n.ttlSeconds=c)}return{...e,details:n}}a(kp,"enrichAuditLogEntry");function ma(e,t){return(n,r)=>{let o=n.query.limit,s=100;if(typeof o=="string"&&o.length>0){let d=Number(o);Number.isFinite(d)&&d>0&&(s=Math.min(Math.floor(d),500))}let i=e.list(s).map(d=>kp(d,t));r.json({logs:i})}}a(ma,"listLogsHandler");var Xo=require("@modelcontextprotocol/sdk/server/mcp.js"),ha=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),T=require("zod");Ge();G();it();K();Fe();ut();Xe();Ae();function ga(){return"0.2.0-beta.3"}a(ga,"pluginVersion");async function ya(e){try{return(await pe(e)).rev}catch{return}}a(ya,"tryLiveRev");function Z(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}a(Z,"jsonResult");function Yo(e){return e===!0?new Set(["payload","baseFlow"]):new Set}a(Yo,"includeSetFromPayloadFlag");function ee(e,t=500){let n=_n(e,"mcp");if(n)return{isError:!0,content:[{type:"text",text:JSON.stringify({...n.body,statusCode:n.statusCode})}]};let r=e instanceof Error?e.message:String(e);return{isError:!0,content:[{type:"text",text:JSON.stringify({error:r,code:"internal_error",statusCode:t})}]}}a(ee,"jsonError");var Ap=new Set(["list_proposals","list_my_proposals"]),xp=new Set(["status","limit","offset","mine","flowId"]);function Sp(e){return!!e&&typeof e=="object"&&typeof e.safeParseAsync=="function"}a(Sp,"isZodLikeSchema");function Tp(e,t,n){let r=t&&typeof t=="object"?t:{},o=n[0],s=o?.path&&o.path.length>0?String(o.path[0]):"(arguments)";if(Ap.has(e)&&xp.has(s))return Bt(s,r[s]);let i=n.map(l=>({parameter:l.path&&l.path.length>0?l.path.map(String).join("."):"(arguments)",message:l.message??"Invalid value"})),d=i.length===1?`Invalid argument '${i[0]?.parameter}' for tool ${e}: ${i[0]?.message}`:`${i.length} invalid arguments for tool ${e}`;return new y(d,"invalid_arguments",{details:{parameter:s,errors:i,hint:`Fix '${s}' to match the ${e} input schema (see tools/list).`}})}a(Tp,"mcpArgumentError");function wa(e){let t=e,n=t.validateToolInput;typeof n=="function"&&(t.validateToolInput=async(r,o,s)=>{let i=r.inputSchema;if(!Sp(i))return n.call(e,r,o,s);let d=await i.safeParseAsync(o??{});if(d.success)return d.data;let l=_n(Tp(s,o,d.error.issues),"mcp"),c=l?{...l.body,statusCode:l.statusCode}:{};throw new Error(JSON.stringify(c))})}a(wa,"installMcpArgumentErrorMapping");function ba(e,t,n,r){e.registerTool("get_status",{description:'Return plugin status (version, AI feature flags, storage path, deploy defaults). For access-link callers, permission is null and caller.kind is "access-link" \u2014 that is expected, not an error. Use before other tools to confirm the plugin is enabled.'},()=>{try{return Z(rn(t,r))}catch(o){return ee(o)}}),e.registerTool("list_flows",{description:"List all flows as a flat Admin API v2 array plus the current rev string. Returns { rev, flows }. Call this (or get_flow) before submit_proposal so expectedRev matches."},async()=>{try{return Z(await pe(n.flowAdapter))}catch(o){return ee(o,502)}}),e.registerTool("get_flow",{description:"Get one tab/subflow by id with nested nodes/configs and the current rev. Pass summary=true for a lightweight node list (id/type/name/wires/bytes, no field contents). Prefer summary \u2192 search_flows \u2192 get_node_field(lines) \u2192 replace_text \u2192 submit_proposal. Returns { rev, flow } or summary shape. Use rev as expectedRev when submitting.",inputSchema:{id:T.z.string().min(1).describe("Flow / tab id"),summary:T.z.boolean().optional().describe("When true, return node list with sizes only (no field contents)")}},async({id:o,summary:s})=>{try{return Z(s?await xr(n.flowAdapter,o):await xe(n.flowAdapter,o))}catch(i){return ee(i,502)}}),e.registerTool("get_node",{description:"Get one full node by id (includes owning flowId when known). Optional flow scopes the lookup.",inputSchema:{id:T.z.string().min(1).describe("Node id"),flow:T.z.string().min(1).optional().describe("Optional tab id to scope the lookup")}},async({id:o,flow:s})=>{try{return Z(await Sr(n.flowAdapter,o,s))}catch(i){return ee(i,502)}}),e.registerTool("get_node_field",{description:'Get one string field from a node. Optional lines="A-B" (1-based inclusive) returns a slice; response always includes totalLines and bytes.',inputSchema:{id:T.z.string().min(1).describe("Node id"),field:T.z.string().min(1).describe("Field name (e.g. template, func)"),lines:T.z.string().optional().describe("Optional 1-based line range A or A-B"),flow:T.z.string().min(1).optional().describe("Optional tab id to scope the lookup")}},async({id:o,field:s,lines:i,flow:d})=>{try{return Z(await Tr(n.flowAdapter,o,s,{...d?{flowId:d}:{},...i?{lines:i}:{}}))}catch(l){return ee(l,502)}}),e.registerTool("search_flows",{description:"Text search across string fields. Returns hits with node id, field, line numbers, and a short snippet. Results are capped; truncated=true when the cap is hit. Optional flow scopes to one tab.",inputSchema:{q:T.z.string().describe("Substring to find (case-sensitive; non-empty required)"),flow:T.z.string().min(1).optional().describe("Optional tab id")}},async({q:o,flow:s})=>{try{return Z(await Pr(n.flowAdapter,o,s?{flowId:s}:{}))}catch(i){return ee(i,502)}}),e.registerTool("list_node_types",{description:"List installed Node-RED palette node types (type, module, category, description, \u2026). Optional q filters type/module/category/description (case-insensitive). Results are capped. Call this before proposing nodes with unfamiliar types.",inputSchema:{q:T.z.string().optional().describe("Optional case-insensitive filter")}},async({q:o})=>{try{return Z(await ir(n.nodeTypesAdapter,o?{q:o}:{}))}catch(s){return ee(s,502)}}),e.registerTool("get_node_type",{description:"Get detail for one installed node type: defaults (JSON), inputs/outputs (always set), requiredConfigNodeTypes, help sections (summary/inputs/outputs), category/module/color. Types are case-sensitive. Pass includeHelp=false to omit help. 404 node_type_not_found when unknown (didYouMean on case mismatch; else nearest names).",inputSchema:{type:T.z.string().min(1).describe("Node type id (e.g. inject, template) \u2014 case-sensitive"),includeHelp:T.z.boolean().optional().describe("When false, omit help sections (default true)")}},async({type:o,includeHelp:s})=>{try{return Z(await ct(n.nodeTypesAdapter,o,{includeHelp:s!==!1}))}catch(i){return ee(i,502)}}),e.registerTool("search_palette",{description:"Search the public Node-RED catalogue for modules to recommend. Returns module id, description, version, updated, link, and installed boolean (cross-checked against installed modules). Core node-red types are not in the catalogue \u2014 use list_node_types. RECOMMEND ONLY \u2014 never installs.",inputSchema:{q:T.z.string().describe("Search string (id / description / keywords; non-empty required)")}},async({q:o})=>{try{return Z(await ar(n.nodeTypesAdapter,o,{...n.catalogueFetcher?{catalogueFetcher:n.catalogueFetcher}:{},...n.catalogueUrl?{catalogueUrl:n.catalogueUrl}:{}}))}catch(s){return ee(s,502)}})}a(ba,"registerReadTools");function va(e,t,n,r,o){let s=q(r,t.settings.httpAdminRoot);e.registerTool("submit_proposal",{description:`Submit a replace_flow proposal for owner approval (does not deploy). Preferred for small string edits: payload: { flowId, nodes: [{ op:"replace_text", node, field, find, replace, occurrence? }] } \u2014 find must be unique unless occurrence (1-based) is set; multiple replace_text ops apply in order; yields a short readable diff. Or send a full tab: payload.flow from get_flow (id, type, label?, nodes[], configs?). Inputs (all top-level, next to each other): type="replace_flow", expectedRev (required string from list_flows/get_flow rev; expected_rev alias accepted), optional title (\u226480 chars), and payload: { flowId, flow? } and/or payload.nodes / top-level nodes. Do not nest expectedRev inside payload. Payload size limit is ${j} bytes (413 if exceeded). expectedRev is checked against the live rev at submit time (409 if stale). replace_text errors: 400 text_not_found; 409 ambiguous_match with matchCount. Unknown palette types return 400 unknown_node_type with nearest matches \u2014 call list_node_types / search_palette and ask the user to install via Manage palette (never auto-install). Returns a lean proposal (id, status, title, storedTitle, flowLabel, displayName, reviewUrl, changeSummary, \u2026) by default; title may gain " in <flow>"; storedTitle is the title as saved (your title without that suffix, or the auto-generated title, which may already name the flow). Pass include_payload=true to include payload and baseFlow. When telling the user about the proposal, cite displayName and reviewUrl \u2014 not the raw id. Humans approve on the /ai-access dashboard (reviewUrl opens/scrolls to it).`,inputSchema:{type:T.z.literal("replace_flow").describe("Must be 'replace_flow'"),expectedRev:T.z.string().min(1).optional().describe("Top-level current flow revision from get_flow/list_flows (required at submit; sit next to type and payload, not inside payload)"),expected_rev:T.z.string().min(1).optional().describe("Alias for expectedRev (snake_case); prefer expectedRev"),title:T.z.string().max(80).optional().describe("Optional short human title (\u226480 chars). Auto-generated from changes when omitted."),include_payload:T.z.boolean().optional().describe("When true, include payload and baseFlow in the response (default lean)"),nodes:T.z.array(T.z.record(T.z.string(),T.z.unknown())).optional().describe("Optional node ops (set/add/remove/replace_text). Same as payload.nodes when flow is omitted."),payload:T.z.object({flowId:T.z.string().min(1).describe("Tab id to replace"),flow:T.z.object({id:T.z.string().optional(),type:T.z.string().optional().describe("Usually 'tab' (included by get_flow)"),label:T.z.string().optional(),nodes:T.z.array(T.z.record(T.z.string(),T.z.unknown())).optional().describe("Child nodes for the tab (from get_flow.nodes)"),configs:T.z.array(T.z.record(T.z.string(),T.z.unknown())).optional()}).passthrough().optional().describe("Full tab from get_flow; omit when using nodes ops"),nodes:T.z.array(T.z.record(T.z.string(),T.z.unknown())).optional().describe("Node ops applied to the live tab (prefer replace_text for small string edits)")}).describe("Replacement flow payload and/or node ops")}},async i=>{try{let d=await Ye(n.proposalStore,n.auditLog,o,{...i,expectedRev:typeof i.expectedRev=="string"&&i.expectedRev.length>0?i.expectedRev:i.expected_rev},n.flowAdapter,s,n.nodeTypesAdapter),l={...ce(d,{...s,include:Yo(i.include_payload)}),mine:!0},c=V(n.proposalStore,d.expectedRev,{flowId:d.payload.flowId}),u=Ne(Ie(n.proposalStore,n.proposalStore.get(d.id),o.id));return Z({...l,...u,...Q(c)})}catch(d){return ee(d)}}),Rp(e,n,o,s),_p(e,n,o,s)}a(va,"registerProposalTools");function Pp(e,t,n,r){let o={mine:T.z.boolean().optional().describe("true: only proposals created by this access link; false: only other links\u2019 proposals"),status:T.z.union([T.z.string(),T.z.array(T.z.string())]).optional().describe("Filter by proposal status: one value, an array, or a comma-separated string (pending, approved, rejected, failed, withdrawn, expired, superseded). An empty array or empty string means no status filter."),flowId:T.z.string().optional().describe("Filter by flow tab id (payload.flowId)"),limit:T.z.number().int().min(1).max(Ut).optional().describe(`Page size (1\u2013${Ut}). Omit to return all matches.`),offset:T.z.number().int().min(0).optional().describe("Skip this many filtered results (default 0)"),include_payload:T.z.boolean().optional().describe("When true, include payload and baseFlow on each proposal")},s=a(async i=>{try{let d=Yo(i.include_payload),l=await ya(t.flowAdapter),c=l?V(t.proposalStore,l):0,u={};typeof i.mine=="boolean"&&(u.mine=i.mine);let p=Io(i.status);p&&(u.status=p),typeof i.flowId=="string"&&i.flowId.length>0&&(u.flowId=i.flowId),typeof i.limit=="number"&&(u.limit=i.limit),typeof i.offset=="number"&&(u.offset=i.offset);let f=qt(t.proposalStore,n,r,u);return Z({proposals:f.proposals.map(m=>ue(t.proposalStore,n,m,{...r,include:d},{includeConflicts:!1})),...ft({...f,returned:f.proposals.length}),...Q(c)})}catch(d){return ee(d)}},"listProposalsHandler");e.registerTool("list_proposals",{description:"List proposals visible to this access link (all proposals by default). Each item includes mine:true|false for the caller. Filter with mine, status, and/or flowId; paginate with limit/offset (response includes total, offset, hasMore, nextOffset). Invalid filters return invalid_filter. Returns lean { proposals, total, \u2026 } with title, displayName, reviewUrl, changeSummary (no payload/baseFlow unless include_payload=true). Prefer displayName + reviewUrl when referring to a proposal with the user (not the raw id).",inputSchema:o},s),e.registerTool("list_my_proposals",{description:"Alias of list_proposals. Prefer list_proposals. Lists proposals visible to this access link with optional mine/status/flowId filters and limit/offset pagination.",inputSchema:o},s)}a(Pp,"registerListProposalsTools");function Rp(e,t,n,r){Pp(e,t,n,r),e.registerTool("get_proposal",{description:"Get any proposal by id (all tokens can read). Response includes mine:true|false and, for pending proposals, conflictingProposals when other pending work touches the same flow. Lean by default (no payload/baseFlow); pass include_payload=true for full bodies. Cite displayName + reviewUrl when talking to the user.",inputSchema:{id:T.z.string().min(1).describe("Proposal id (prop-\u2026)"),include_payload:T.z.boolean().optional().describe("When true, include payload and baseFlow")}},async({id:o,include_payload:s})=>{try{let i=await ya(t.flowAdapter),d=De(t.proposalStore,n,o,r);return Z(ue(t.proposalStore,n,d,{...r,include:Yo(s)},{...i?{liveRev:i}:{}}))}catch(i){return ee(i)}})}a(Rp,"registerProposalQueryTools");function _p(e,t,n,r){e.registerTool("get_proposal_diff",{description:"Diff any proposal against its stored baseFlow snapshot (what changed). Optional format=summary|full (default summary). Pending + stale also includes vsCurrent.",inputSchema:{id:T.z.string().min(1).describe("Proposal id (prop-\u2026)"),format:T.z.enum(["summary","full"]).optional().describe("Diff payload format (default summary)")}},async({id:o,format:s})=>{try{let i=De(t.proposalStore,n,o),d=Yt(s??"summary");if(!d.ok)return ee(new y("Invalid diff format","invalid_diff_format",{details:{hint:"Valid formats: summary, full (default summary)."}}));let l=Qt(await nn(i,t.flowAdapter),d.format);return Z(l)}catch(i){return ee(i)}}),e.registerTool("withdraw_proposal",{description:"Withdraw one of YOUR pending proposals (status becomes withdrawn, not rejected). Optional reason. Only the creating access link can withdraw; other tokens get 403. Cite displayName + reviewUrl when telling the user.",inputSchema:{id:T.z.string().min(1).describe("Proposal id (prop-\u2026) owned by this access link"),reason:T.z.string().optional().describe("Optional withdraw reason")}},({id:o,reason:s})=>{try{let i=Wt(t.proposalStore,t.auditLog,n,o,s,r);return Z(ue(t.proposalStore,n,i,r))}catch(i){return ee(i)}})}a(_p,"registerProposalActionTools");function Lp(e,t,n){let r=new Xo.McpServer({name:"node-red-ai-access",version:ga()});wa(r);let o=n.accessLink;if(!o)throw new Error("Access link required");return ba(r,e,t,n),va(r,e,t,n,o),r}a(Lp,"createAiMcpServer");function Qo(e,t){return async(n,r,o)=>{try{if(!n.accessLink&&!n.auth){r.setHeader("WWW-Authenticate",Y),r.status(401).json({error:le,code:Le});return}let s=n.accessLink?Lp(e,t,n):Cp(e,t,n),i=new ha.StreamableHTTPServerTransport({enableJsonResponse:!0});await s.connect(i),await i.handleRequest(n,r,n.body),r.on("close",()=>{i.close(),s.close()})}catch(s){if(!r.headersSent){$(r,s);return}o(s instanceof Error?s:new Error(String(s)))}}}a(Qo,"mcpRpcPostHandler");function Cp(e,t,n){let r=new Xo.McpServer({name:"node-red-ai-access",version:ga()});if(wa(r),ba(r,e,t,n),(n.auth?.scopes??[]).includes("propose")){let s=typeof n.auth?.extra?.user=="string"?n.auth.extra.user:"owner",i=n.auth?.clientId??"",l={id:lo(i,s),kind:"mcp",createdAt:new Date().toISOString(),expiresAt:new Date((n.auth?.expiresAt??0)*1e3).toISOString(),createdBy:s,oauthClientId:i,oauthUser:s};va(r,e,t,n,l)}return r}a(Cp,"createOAuthMcpServer");function On(e,t){t.status(405).set("Allow","POST").json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed. Use POST for Streamable HTTP."},id:null})}a(On,"mcpRpcMethodNotAllowed");var $n=require("crypto"),sn=require("fs"),ts=require("path"),B=require("@modelcontextprotocol/sdk/server/auth/errors.js"),Ta=require("@modelcontextprotocol/sdk/server/auth/handlers/authorize.js"),ns=require("@modelcontextprotocol/sdk/server/auth/handlers/metadata.js"),Pa=require("@modelcontextprotocol/sdk/server/auth/handlers/register.js"),Ra=require("@modelcontextprotocol/sdk/server/auth/handlers/revoke.js"),_a=require("@modelcontextprotocol/sdk/server/auth/handlers/token.js"),La=require("@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js"),Ca=require("@modelcontextprotocol/sdk/server/auth/router.js"),Ea=ln(require("express"),1);G();_e();function $e(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}a($e,"esc");var ka={read:'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5c-5 0-9 4.5-10 7 1 2.5 5 7 10 7s9-4.5 10-7c-1-2.5-5-7-10-7Zm0 11.5a4.5 4.5 0 1 1 0-9 4.5 4.5 0 0 1 0 9Zm0-2.3a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4Z"/></svg>',propose:'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 17.2V20h2.8l8.3-8.3-2.8-2.8L4 17.2Zm13.7-7.6a1 1 0 0 0 0-1.4l-1.9-1.9a1 1 0 0 0-1.4 0l-1.4 1.4 2.8 2.8 1.9-1.9Z"/></svg>'},Ep={read:["Read your flows","View flows, nodes, node types and AI Access logs."],propose:["Propose flow changes","Submit change proposals. Nothing is deployed until you approve it in Node-RED."]},Ip='<svg class="logo" viewBox="0 0 48 48" aria-hidden="true"><rect width="48" height="48" rx="11" fill="#8f0000"/><path d="M11 15h9a4 4 0 0 1 4 4v10a4 4 0 0 0 4 4h9" fill="none" stroke="#fff" stroke-width="3" stroke-linecap="round"/><rect x="6" y="11" width="9" height="8" rx="2.5" fill="#fff"/><rect x="33" y="29" width="9" height="8" rx="2.5" fill="#fff"/><circle cx="37.5" cy="16" r="5" fill="none" stroke="#fff" stroke-width="2.4"/><path d="M37.5 13.5v5M35 16h5" stroke="#fff" stroke-width="2.2" stroke-linecap="round"/></svg>',Np=`
|
|
954
|
-
:root{color-scheme:light
|
|
955
|
-
@media (prefers-color-scheme:dark){:root{--bg:#0b0f14;--card:#151b23;--text:#e5e7eb;--muted:#9ca3af;--line:#273140;--soft:#1b2330;--brand:#c0262d;--brand-2:#ef4444;--warn-bg:#2a1a0e;--warn:#fdba74;--focus:#60a5fa}}
|
|
953
|
+
`)}a(Gi,"splitLines");Ae();var Xi=new Set(["func","template","info","payload","code","text","format","syntax"]),Gu=new Set(["x","y","w","h","wires","g"]),Ju=new Set(["w","h","g"]);function wt(e){if(typeof e.name=="string"&&e.name.length>0)return e.name;if(typeof e.label=="string"&&e.label.length>0)return e.label}a(wt,"nodeName");function Ki(e){let t=new Map;for(let n of e.nodes??[])t.set(n.id,n);for(let n of e.configs??[])t.set(n.id,n);return t}a(Ki,"collectNodes");function Dr(e){if(e===void 0)return"undefined";if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Dr).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${Dr(t[r])}`).join(",")}}`}a(Dr,"stableStringify");function Yi(e,t){return Dr(e)===Dr(t)}a(Yi,"valuesEqual");function jr(e){return typeof e=="string"?e:null}a(jr,"asText");function Ku(e){return/<\/?[a-z][\s\S]*>/i.test(e.slice(0,800))}a(Ku,"looksLikeHtml");function Vu(e,t,n){if(t!=="template")return!1;let r=typeof e.format=="string"?e.format.toLowerCase():"";return r==="html"||r==="handlebars"||r==="mustache"?!0:Ku(n)}a(Vu,"isHtmlTemplateField");function Qi(e,t,n){let r=jr(n);if(Xi.has(t)&&r!==null){let o={key:t,kind:"text",value:r};return Vu(e,t,r)&&(o.preview="html"),o}return{key:t,kind:"scalar",value:n===void 0?null:n}}a(Qi,"toPresenceProperty");function Xu(e,t){let n=[];for(let r of[...Object.keys(e)].sort())if(!(Ju.has(r)||r==="id"||r==="z")){if(r==="wires"){let o=Zi(e,t);n.push({key:"wires",kind:"scalar",value:o.length>0?o:e.wires??null});continue}n.push(Qi(e,r,e[r]))}return n}a(Xu,"nodeProperties");function Zi(e,t){let n=e.wires;if(!Array.isArray(n)||n.length===0)return[];let r=[];return n.forEach((o,s)=>{if(!Array.isArray(o))return;let i=[];for(let d of o){if(typeof d!="string"||!d)continue;let l=t.get(d);i.push({id:d,name:l?wt(l)??l.type:d})}r.push({port:s,to:i})}),r}a(Zi,"describeWiresStructured");var Yu=new Set(["func","template","code","text"]);function Qu(e,t){let n=[],r=wt(e);r&&n.push({key:"name",kind:"scalar",value:r});let o=Zi(e,t);o.length>0&&n.push({key:"wires",kind:"scalar",value:o});for(let s of Yu){if(!(s in e))continue;let i=jr(e[s]);i===null||i.length===0||n.push(Qi(e,s,i))}return n}a(Qu,"buildKeyFields");function Zu(e,t,n){let r=Ve(e.type),o=wt(e),s=o?` "${o}"`:"",i=t?` in "${t}"`:"",d=n===1?"1 field":`${n} fields`;return`Changes ${r} node${s}${i} (${d})`}a(Zu,"buildModifiedSummary");function ep(e,t,n){let r=Ve(e.type),o=wt(e),s=t==="added"?"Adds":"Removes",i=t==="added"?"to":"from",d=o?` ${JSON.stringify(o)}`:"",l=n?` ${i} flow ${JSON.stringify(n)}`:"",c=`${s} ${r} node${d}${l}`;if(t==="added"&&r==="template"){let u=typeof e.field=="string"&&e.field?e.field:"";u&&(c+=`, output to msg.${u}`)}return c}a(ep,"buildPresenceSummary");function $r(e,t,n,r){let o={id:e.id,type:e.type,summary:ep(e,t,n),keyFields:Qu(e,r),properties:Xu(e,r)},s=wt(e);return s!==void 0&&(o.name=s),o}a($r,"toPresenceNode");function tp(e,t){let n=new Set([...Object.keys(e),...Object.keys(t)]),r=[];for(let o of[...n].sort()){if(Gu.has(o)||o==="id"||o==="z")continue;let s=e[o],i=t[o];if(Yi(s,i))continue;let d=jr(s),l=jr(i);if(Xi.has(o)&&(d!==null||l!==null)){let c=d??"",u=l??"";r.push({key:o,kind:"text",before:c,after:u,lines:Ji(c,u)});continue}r.push({key:o,kind:"scalar",before:s===void 0?null:s,after:i===void 0?null:i})}return r}a(tp,"compareNodes");function np(e,t){let n=["label","disabled","info","env"],r=[];for(let o of n)Yi(e[o],t[o])||r.push(o);return r}a(np,"compareTabMeta");function Mr(e){return typeof e.label=="string"&&e.label.trim()?e.label.trim():""}a(Mr,"flowLabelOf");function ea(e,t){let n=Ki(t),r=Ki(e),o=Mr(e)||Mr(t),s=Mr(t)||Mr(e),i=[],d=[],l=[];for(let c of e.nodes??[])n.has(c.id)||i.push($r(c,"added",o,r));for(let c of e.configs??[])n.has(c.id)||i.push($r(c,"added",o,r));for(let c of t.nodes??[])r.has(c.id)||d.push($r(c,"removed",s,n));for(let c of t.configs??[])r.has(c.id)||d.push($r(c,"removed",s,n));for(let[c,u]of r){let p=n.get(c);if(!p)continue;let f=tp(p,u);if(f.length>0){let m={id:c,type:u.type||p.type,summary:Zu(u,o||s,f.length),changes:f},h=wt(u)??wt(p);h!==void 0&&(m.name=h),l.push(m)}}return l.sort((c,u)=>c.id.localeCompare(u.id)),{summary:{added:i.length,removed:d.length,modified:l.length,tabChanges:np(t,e),beforeNodeCount:n.size,afterNodeCount:r.size},added:i,removed:d,modified:l}}a(ea,"buildDiffSections");function Vi(e,t,n={}){let r=ea(e.payload.flow,t.flow),o=n.currentRev??t.rev,s=e.expectedRev,i=n.baseRevStale??(e.status==="pending"&&s!==o),d={proposalId:e.id,flowId:e.payload.flowId,expectedRev:s,currentRev:o,baseRevStale:i,compareAgainst:n.compareAgainst??"current",...r};return e.warnings&&e.warnings.length>0&&(d.warnings=e.warnings.map(l=>({...l}))),n.baseSnapshotMissing&&(d.baseSnapshotMissing=!0),n.vsCurrent&&(d.vsCurrent=n.vsCurrent),d}a(Vi,"buildProposalDiff");async function nn(e,t){let n=e.payload.flowId,r={id:n,type:"tab",nodes:[],configs:[]},o=e.expectedRev,s=r;try{let c=await t.getFlow(n);o=c.rev,s=c.flow}catch(c){if(!(c instanceof z))throw c;try{o=(await t.getFlows()).rev}catch{}}let d=e.status==="pending"&&e.expectedRev!==o,l=e.baseFlow;if(l!==void 0){let c=d?ea(e.payload.flow,s):void 0;return Vi(e,{rev:e.expectedRev,flow:l},{currentRev:o,compareAgainst:"base",baseRevStale:d,...c?{vsCurrent:c}:{}})}return Vi(e,{rev:o,flow:s},{compareAgainst:"current",baseSnapshotMissing:!0,baseRevStale:d})}a(nn,"computeProposalDiff");Ae();_e();ye();var ta=require("path");function Hr(e){return(0,ta.join)(e.userDir,".ai-access")}a(Hr,"getStorageDir");var rp=["status:read","flows:read","proposals:create","proposals:read-own"];function zo(){return Vt()}a(zo,"readPackageVersion");function op(e,t=Date.now()){let n=Date.parse(e);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):0}a(op,"secondsRemainingUntil");function sp(e,t=Date.now()){let n=Date.parse(e);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/6e4)):0}a(sp,"minutesRemainingUntil");function ip(e,t){let n=de(t),r=qe(t),o=`${n}/openapi.yaml`,s=`${n}/openapi.json`;return e==="rest"?{api:n,openapi:o,openapiJson:s,discovery:n}:e==="mcp"?{rpc:r,discovery:n}:{discovery:n}}a(ip,"baseUrlsForTokenKind");function rn(e,t){let n=Kn(e,t),r=he(e.settings);if(t.auth){let o=t.auth.extra?.user;return{ok:!0,version:zo(),adminAuthEnabled:n.adminAuthEnabled,aiAccessEnabled:r.enabled,aiFeaturesEnabled:n.aiFeaturesEnabled,allowWithoutAdminAuth:n.allowWithoutAdminAuth,permission:t.auth.scopes.includes("propose")?"propose":"read",capabilities:{view:!0,manageLinks:!1,approveProposals:!1},defaultLinkTtlSeconds:r.defaultLinkTtlSeconds,maxActiveLinks:r.maxActiveLinks,defaultDeploymentType:r.defaultDeploymentType,caller:{kind:"oauth",clientId:t.auth.clientId,user:typeof o=="string"?o:"owner",scopes:t.auth.scopes}}}if(t.accessLink){let o=Date.now();return{ok:!0,version:zo(),adminAuthEnabled:n.adminAuthEnabled,aiAccessEnabled:r.enabled,aiFeaturesEnabled:n.aiFeaturesEnabled,allowWithoutAdminAuth:n.allowWithoutAdminAuth,permission:null,capabilities:{view:!0,manageLinks:!1,approveProposals:!1},defaultLinkTtlSeconds:r.defaultLinkTtlSeconds,maxActiveLinks:r.maxActiveLinks,defaultDeploymentType:r.defaultDeploymentType,caller:{kind:"access-link",linkId:t.accessLink.id,tokenKind:t.accessLink.kind,...t.accessLink.label!==void 0?{label:t.accessLink.label}:{},expiresAt:t.accessLink.expiresAt,minutesRemaining:sp(t.accessLink.expiresAt,o),secondsRemaining:op(t.accessLink.expiresAt,o),permissions:[...rp],baseUrls:ip(t.accessLink.kind,e.settings.httpAdminRoot)}}}return{ok:!0,version:zo(),adminAuthEnabled:n.adminAuthEnabled,aiAccessEnabled:r.enabled,aiFeaturesEnabled:n.aiFeaturesEnabled,allowWithoutAdminAuth:n.allowWithoutAdminAuth,permission:n.permission,capabilities:n.capabilities,storageDir:Hr(e.settings),defaultLinkTtlSeconds:r.defaultLinkTtlSeconds,maxActiveLinks:r.maxActiveLinks,defaultDeploymentType:r.defaultDeploymentType,caller:{kind:"admin",...n.permission?{permission:n.permission}:{}}}}a(rn,"buildStatus");function na(e,t){let n=t.draftStore??new br,r=t.rateLimiters??Ci(t.rateLimit??e.settings.aiAccess),o=e.httpAdmin,s="/mcp/a/:token",i=[r.ip,Ii(e,t.linkStore),r.token];o.use("/mcp/a",gi()),o.get(s,...i,R((u,p)=>{F(p),p.setHeader("X-Content-Type-Options","nosniff");let f=de(e.settings.httpAdminRoot),m=u.accessLink;if(!m){C(p,401,"Access link required","access_link_missing");return}let h=Si({link:m,openapiPath:`${f}/openapi.yaml`,restApiBase:f,mcpRpcPath:qe(e.settings.httpAdminRoot),publicOrigin:oo(u)});p.status(200).type("text/markdown; charset=utf-8").send(h)})),o.get(`${s}/status`,...i,R((u,p)=>{F(p),p.json(rn(e,u))})),o.get(`${s}/flows`,...i,R(async(u,p)=>{F(p);try{p.json(await pe(t.flowAdapter))}catch(f){let m=O(f);if(m){p.status(m.statusCode).json({...m.body,hint:"Retry after the owner fixes the plugin runtime."});return}C(p,502,f instanceof Error?f.message:String(f),"upstream_error")}})),o.get(`${s}/flows/:id`,...i,R(async(u,p)=>{F(p),await Lr(t.flowAdapter,"get")(u,p)})),o.get(`${s}/nodes/:id`,...i,R(async(u,p)=>{F(p),await Cr(t.flowAdapter,"get")(u,p)})),o.get(`${s}/nodes/:id/field/:name`,...i,R(async(u,p)=>{F(p),await Er(t.flowAdapter,"get")(u,p)})),o.get(`${s}/search`,...i,R(async(u,p)=>{F(p),await Ir(t.flowAdapter,"get")(u,p)}));let d={nodeTypes:t.nodeTypesAdapter,...t.catalogueFetcher?{catalogueFetcher:t.catalogueFetcher}:{},...t.catalogueUrl?{catalogueUrl:t.catalogueUrl}:{}};o.get(`${s}/node-types`,...i,R(async(u,p)=>{F(p),await Nr(d)(u,p)})),o.get(`${s}/node-types/:type`,...i,R(async(u,p)=>{F(p),await Fr(d)(u,p)})),o.get(`${s}/palette/search`,...i,R(async(u,p)=>{F(p),await Or(d)(u,p)}));let l=e.settings.httpAdminRoot;ap(o,s,i,t,l),o.get(`${s}/propose`,...i,R(ji(t.proposalStore,t.auditLog,t.flowAdapter,l,t.nodeTypesAdapter))),cp(o,s,i,n,t,l);let c=Fi();return o.all(`${s}/links`,c),o.all(`${s}/links/:id`,c),o.use("/mcp/a",Ni()),n}a(na,"registerGetLinkRoutes");function ap(e,t,n,r,o){e.get(`${t}/proposals`,...n,R(async(s,i)=>{F(i);let d=s.accessLink;if(!d){C(i,401,"Access link required","access_link_missing");return}let l=q(s,o),c=re(s.query),u=mr(s.query),p;try{p=(await pe(r.flowAdapter)).rev}catch{}let f=p?V(r.proposalStore,p):0,m=qt(r.proposalStore,d,l,u);i.json({proposals:m.proposals.map(h=>ue(r.proposalStore,d,h,{...l,include:c},{includeConflicts:!1})),...ft({...m,returned:m.proposals.length}),...Q(f)})})),e.get(`${t}/proposals/:id`,...n,R(async(s,i)=>{F(i);let d=s.params.id,l=s.accessLink;if(typeof d!="string"||!d){C(i,400,"Missing proposal id","missing_proposal_id");return}if(!l){C(i,401,"Access link required","access_link_missing");return}try{let c=q(s,o),u=re(s.query),p;try{p=(await pe(r.flowAdapter)).rev}catch{}let f=De(r.proposalStore,l,d,c);i.json(ue(r.proposalStore,l,f,{...c,include:u},{...p?{liveRev:p}:{}}))}catch(c){let u=O(c,"get");if(u){i.status(u.statusCode).json({...u.body,hint:u.body.hint??"List proposals with GET \u2026/proposals."});return}$(i,c);return}})),dp(e,t,n,r,o),lp(e,t,n,r,o)}a(ap,"registerGetLinkProposalRoutes");function dp(e,t,n,r,o){e.get(`${t}/proposals/:id/withdraw`,...n,R((s,i)=>{F(i);let d=s.params.id,l=s.accessLink;if(typeof d!="string"||!d){C(i,400,"Missing proposal id","missing_proposal_id");return}if(!l){C(i,401,"Access link required","access_link_missing");return}let c=s.query.confirm;if(c!=="1"&&c!=="true"){C(i,400,"Withdraw over GET requires confirm=1","confirm_required",se("confirm_required","get"));return}let u=typeof s.query.reason=="string"?s.query.reason:void 0,p=q(s,o),f=re(s.query);try{let m=Wt(r.proposalStore,r.auditLog,l,d,u,p);i.json(ue(r.proposalStore,l,m,{...p,include:f}))}catch(m){let h=O(m,"get");if(h){let g=h.body.code;C(i,h.statusCode,Oe[g]??"Request failed",g,se(g,"get"));return}C(i,500,"Internal server error","internal_error");return}}))}a(dp,"registerGetLinkWithdrawRoute");function lp(e,t,n,r,o){e.get(`${t}/proposals/:id/diff`,...n,R(async(s,i)=>{F(i);let d=s.params.id,l=s.accessLink;if(typeof d!="string"||!d){C(i,400,"Missing proposal id","missing_proposal_id");return}if(!l){C(i,401,"Access link required","access_link_missing");return}try{let c=De(r.proposalStore,l,d,q(s,o)),u=_(s.query,"format"),p=Yt(u==="json"||u==="md"?void 0:u);if(!p.ok){C(i,400,"Invalid diff format","invalid_diff_format","Valid formats: summary, full (default summary).");return}i.json(Qt(await nn(c,r.flowAdapter),p.format))}catch(c){let u=O(c);if(u){i.status(u.statusCode).json(u.body);return}$(i,c);return}}))}a(lp,"registerGetLinkDiffRoute");function cp(e,t,n,r,o,s){e.get(`${t}/draft/new`,...n,R($i(r,o.flowAdapter))),e.get(`${t}/draft/:draftId/append`,...n,R(Mi(r))),e.get(`${t}/draft/:draftId/submit`,...n,R(Di(r,o.proposalStore,o.auditLog,o.flowAdapter,s,o.nodeTypesAdapter)))}a(cp,"registerGetLinkDraftRoutes");G();var ra=require("module");function up(){if(typeof require=="function")return require;let e=(0,eval)("import.meta.url");return(0,ra.createRequire)(e)}a(up,"createPluginRequire");function pp(e){try{let r=up()("@node-red/runtime")._?.adminApi?.httpAdmin;if(r&&typeof r.use=="function"&&r!==e.httpAdmin)return r}catch{}return null}a(pp,"resolveEditorHttpAdmin");function oa(e){let t=[e.httpAdmin],n=pp(e);return n&&t.push(n),t}a(oa,"httpAdminAppsForMcpErrors");var sa=Symbol.for("com55.ai-access.mcpJsonErrorHandler");function fp(e){let t=e??"/";for(;t.endsWith("/");)t=t.slice(0,-1);let n=new Set;for(let r of t?["",t]:[""])for(let o of["/mcp","/mcp/rpc"])n.add(r+o),n.add(`${r+o}/`);return r=>n.has(r)}a(fp,"mcpRpcMatcher");function Go(e){return e.includes("/mcp")}a(Go,"isMcpPath");function mp(e){return e.path||e.url||e.originalUrl||""}a(mp,"requestPath");function hp(e){if(!e||typeof e!="object")return!1;let t=e;if(t.type==="entity.parse.failed"||e instanceof SyntaxError)return!0;let n=typeof e.message=="string"?e.message:"";return/JSON/i.test(n)&&(t.status===400||t.statusCode===400)}a(hp,"isJsonParseError");function gp(e){if(!e||typeof e!="object")return!1;let t=e;return t.type==="entity.too.large"||t.status===413||t.statusCode===413||t.message==="request entity too large"}a(gp,"isPayloadTooLarge");function yp(e){let t=fp(e);return(n,r,o,s)=>{if(o.headersSent){s(n);return}let i=mp(r);if(hp(n)&&Go(i)){if(t(i)){o.status(400).json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null});return}o.status(400).json({error:"Invalid JSON body",code:"invalid_json"});return}if(gp(n)&&Go(i)){o.status(413).json({error:`Request body exceeds limit of ${j} bytes`,code:"payload_too_large"});return}if(Go(i)){if(t(i)){o.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:wr(n).error,data:{code:"internal_error"}},id:null});return}o.status(500).json(wr(n));return}s(n)}}a(yp,"mcpJsonErrorHandler");function wp(e,t){let n=e;n[sa]||(n[sa]=!0,e.use(yp(t)))}a(wp,"attachOnce");function ia(e){for(let t of oa(e))wp(t,e.settings.httpAdminRoot)}a(ia,"attachMcpJsonErrorHandlers");Ln();var bt=class extends Error{static{a(this,"AccessLinkLimitError")}code="access_link_limit";statusCode=409;constructor(t){super(`Cannot create access link: at most ${t} active links are allowed. Revoke an existing link first.`),this.name="AccessLinkLimitError"}},vt=class extends Error{static{a(this,"AccessLinkNotFoundError")}code="access_link_not_found";statusCode=404;constructor(t){super(`Access link '${t}' was not found`),this.name="AccessLinkNotFoundError"}},Nn=class extends Error{static{a(this,"AccessLinkValidationError")}code="access_link_invalid";statusCode=400;constructor(t){super(t),this.name="AccessLinkValidationError"}},tt=class extends Error{static{a(this,"AccessLinkTtlError")}code="invalid_ttl";statusCode=400;hint=mt;constructor(t){super(t),this.name="AccessLinkTtlError"}};var kt=require("crypto");Ln();function Jo(e){return e==="get_link"||e==="rest"||e==="mcp"}a(Jo,"isAccessLinkKind");function Ko(e){return e??"get_link"}a(Ko,"resolveAccessLinkKind");function aa(e){return(0,kt.createHash)("sha256").update(e,"utf8").digest("hex")}a(aa,"hashToken");function bp(e,t){let n=Buffer.from(e,"utf8"),r=Buffer.from(t,"utf8");return n.length!==r.length?!1:(0,kt.timingSafeEqual)(n,r)}a(bp,"hashesEqual");function Fn(e){let t={id:e.id,kind:Ko(e.kind),createdAt:new Date(e.createdAtMs).toISOString(),expiresAt:new Date(e.expiresAtMs).toISOString()};return e.label!==void 0&&(t.label=e.label),e.lastUsedAtMs!==void 0&&(t.lastUsedAt=new Date(e.lastUsedAtMs).toISOString()),e.createdBy!==void 0&&(t.createdBy=e.createdBy),t}a(Fn,"toPublic");var At=class{static{a(this,"AccessLinkStore")}links=new Map;defaultTtlSeconds;maxActiveLinks;now;randomId;randomToken;constructor(t={}){this.defaultTtlSeconds=t.defaultTtlSeconds??14400,this.maxActiveLinks=t.maxActiveLinks??10,this.now=t.now??(()=>Date.now()),this.randomId=t.randomId??(()=>(0,kt.randomBytes)(12).toString("hex")),this.randomToken=t.randomToken??(()=>`aia_${(0,kt.randomBytes)(32).toString("base64url")}`)}configureDefaults(t){typeof t.defaultTtlSeconds=="number"&&Number.isFinite(t.defaultTtlSeconds)&&t.defaultTtlSeconds>0&&(this.defaultTtlSeconds=Math.floor(t.defaultTtlSeconds)),typeof t.maxActiveLinks=="number"&&Number.isFinite(t.maxActiveLinks)&&t.maxActiveLinks>0&&(this.maxActiveLinks=Math.floor(t.maxActiveLinks))}isActive(t,n){return t.revokedAtMs!==void 0?!1:t.expiresAtMs>n}list(){let t=this.now();return[...this.links.values()].filter(n=>this.isActive(n,t)).sort((n,r)=>r.createdAtMs-n.createdAtMs).map(Fn)}create(t={}){let n=this.now();if([...this.links.values()].filter(p=>this.isActive(p,n)).length>=this.maxActiveLinks)throw new bt(this.maxActiveLinks);let o=this.defaultTtlSeconds;if(t.ttlSeconds!==void 0){if(typeof t.ttlSeconds!="number"||!Number.isFinite(t.ttlSeconds)||t.ttlSeconds<=0)throw new tt("ttlSeconds must be a positive number");o=Math.floor(t.ttlSeconds)}let s=typeof t.label=="string"&&t.label.trim().length>0?t.label.trim():void 0,i=Ko(t.kind),d=No(i);if(o>d)throw new tt(Fo(i,d));let l=this.randomId(),c=this.randomToken(),u={id:l,tokenHash:aa(c),kind:i,createdAtMs:n,expiresAtMs:n+o*1e3};return s!==void 0&&(u.label=s),t.createdBy!==void 0&&(u.createdBy=t.createdBy),this.links.set(l,u),{...Fn(u),token:c}}revoke(t){let n=this.links.get(t);if(!n)throw new vt(t);return n.revokedAtMs??=this.now(),Fn(n)}getById(t){if(typeof t!="string"||t.length===0)return null;let n=this.links.get(t);return n?Fn(n):null}validateResult(t){if(typeof t!="string"||t.length===0)return{status:"invalid"};let n=aa(t),r=this.now();for(let o of this.links.values())if(bp(o.tokenHash,n))return o.revokedAtMs!==void 0?{status:"invalid"}:o.expiresAtMs<=r?{status:"expired",expiresAt:new Date(o.expiresAtMs).toISOString()}:(o.lastUsedAtMs=r,{status:"active",link:Fn(o)});return{status:"invalid"}}validate(t){let n=this.validateResult(t);return n.status==="active"?n.link:null}size(){return this.links.size}clear(){this.links.clear()}upsertRecordForTest(t){let n={...t};delete n.token,this.links.set(t.id,n)}};Ln();ie();ye();function Vo(e,t){return t}a(Vo,"storeForRequest");function la(e){let t=typeof e.user?.username=="string"?e.user.username:void 0;return t?{kind:"admin",username:t}:{kind:"admin"}}a(la,"adminActor");function Ur(e){let t=he(e.settings);return new At({defaultTtlSeconds:t.defaultLinkTtlSeconds,maxActiveLinks:t.maxActiveLinks})}a(Ur,"createConfiguredLinkStore");function ca(e){e.setHeader("Cache-Control","no-store"),e.setHeader("Pragma","no-cache")}a(ca,"noStore");function ua(e,t){return(n,r)=>{let s=Vo(e,t).list();ca(r),r.json({links:s})}}a(ua,"listLinksHandler");function pa(e,t,n){return(r,o)=>{let s=r.body??{},i={};if(s.ttlSeconds!==void 0){if(typeof s.ttlSeconds!="number"){o.status(400).json({error:"ttlSeconds must be a positive number",code:"invalid_ttl",hint:mt});return}i.ttlSeconds=s.ttlSeconds}if(typeof s.label=="string"&&(i.label=s.label),s.kind!==void 0){if(!Jo(s.kind)){o.status(400).json({error:"kind must be one of: 'get_link', 'rest', 'mcp'",code:"invalid_link_kind"});return}i.kind=s.kind}typeof r.user?.username=="string"&&(i.createdBy=r.user.username);try{let d=Vo(e,t).create(i),l=d.kind;if(n){let c=Date.parse(d.createdAt),u=Date.parse(d.expiresAt),p=Number.isFinite(c)&&Number.isFinite(u)&&u>c?Math.round((u-c)/1e3):void 0;n.append("link.created",la(r),{linkId:d.id,label:d.label,expiresAt:d.expiresAt,createdAt:d.createdAt,kind:l,...p!==void 0?{ttlSeconds:p}:{}})}if(ca(o),l==="get_link"){let c=Ps(r,e.settings.httpAdminRoot,d.token);o.status(201).json({...d,url:c});return}o.status(201).json({...d})}catch(d){if(d instanceof bt){o.status(d.statusCode).json({error:d.message,code:d.code});return}if(d instanceof tt){o.status(d.statusCode).json({error:d.message,code:d.code,hint:d.hint});return}if(d instanceof Nn){o.status(d.statusCode).json({error:d.message,code:d.code});return}$(o,d);return}}}a(pa,"createLinkHandler");function fa(e,t,n){return(r,o)=>{let s=r.params.id;if(typeof s!="string"||s.length===0){o.status(400).json({error:"Missing link id"});return}try{let i=Vo(e,t).revoke(s);if(n){let d=Date.parse(i.createdAt),l=Date.parse(i.expiresAt),c=Number.isFinite(d)&&Number.isFinite(l)&&l>d?Math.round((l-d)/1e3):void 0;n.append("link.revoked",la(r),{linkId:i.id,label:i.label,expiresAt:i.expiresAt,createdAt:i.createdAt,kind:i.kind,...c!==void 0?{ttlSeconds:c}:{}})}o.json({revoked:!0,link:i})}catch(i){if(i instanceof vt){o.status(i.statusCode).json({error:i.message,code:i.code});return}$(o,i);return}}}a(fa,"revokeLinkHandler");function vp(e){let t=Date.parse(e.createdAt),n=Date.parse(e.expiresAt);if(Number.isFinite(t)&&Number.isFinite(n)&&n>t)return Math.round((n-t)/1e3)}a(vp,"ttlSecondsFromLink");function kp(e,t){if(!t||e.action!=="link.created"&&e.action!=="link.revoked")return e;let n={...e.details??{}},r=typeof n.linkId=="string"?n.linkId:"";if(!r)return e;let o=n.label==null||n.label==="",s=n.expiresAt==null||n.expiresAt==="",i=n.createdAt==null||n.createdAt==="",d=n.ttlSeconds==null;if(!o&&!s&&!i&&!d)return e;let l=t.getById(r);if(!l)return e;if(o&&l.label&&(n.label=l.label),s&&(n.expiresAt=l.expiresAt),i&&(n.createdAt=l.createdAt),d){let c=vp(l);c!==void 0&&(n.ttlSeconds=c)}return{...e,details:n}}a(kp,"enrichAuditLogEntry");function ma(e,t){return(n,r)=>{let o=n.query.limit,s=100;if(typeof o=="string"&&o.length>0){let d=Number(o);Number.isFinite(d)&&d>0&&(s=Math.min(Math.floor(d),500))}let i=e.list(s).map(d=>kp(d,t));r.json({logs:i})}}a(ma,"listLogsHandler");var Xo=require("@modelcontextprotocol/sdk/server/mcp.js"),ha=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),T=require("zod");Ge();G();it();K();Fe();ut();Xe();Ae();function ga(){return"0.2.0-beta.4"}a(ga,"pluginVersion");async function ya(e){try{return(await pe(e)).rev}catch{return}}a(ya,"tryLiveRev");function Z(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}a(Z,"jsonResult");function Yo(e){return e===!0?new Set(["payload","baseFlow"]):new Set}a(Yo,"includeSetFromPayloadFlag");function ee(e,t=500){let n=_n(e,"mcp");if(n)return{isError:!0,content:[{type:"text",text:JSON.stringify({...n.body,statusCode:n.statusCode})}]};let r=e instanceof Error?e.message:String(e);return{isError:!0,content:[{type:"text",text:JSON.stringify({error:r,code:"internal_error",statusCode:t})}]}}a(ee,"jsonError");var Ap=new Set(["list_proposals","list_my_proposals"]),xp=new Set(["status","limit","offset","mine","flowId"]);function Sp(e){return!!e&&typeof e=="object"&&typeof e.safeParseAsync=="function"}a(Sp,"isZodLikeSchema");function Tp(e,t,n){let r=t&&typeof t=="object"?t:{},o=n[0],s=o?.path&&o.path.length>0?String(o.path[0]):"(arguments)";if(Ap.has(e)&&xp.has(s))return Bt(s,r[s]);let i=n.map(l=>({parameter:l.path&&l.path.length>0?l.path.map(String).join("."):"(arguments)",message:l.message??"Invalid value"})),d=i.length===1?`Invalid argument '${i[0]?.parameter}' for tool ${e}: ${i[0]?.message}`:`${i.length} invalid arguments for tool ${e}`;return new y(d,"invalid_arguments",{details:{parameter:s,errors:i,hint:`Fix '${s}' to match the ${e} input schema (see tools/list).`}})}a(Tp,"mcpArgumentError");function wa(e){let t=e,n=t.validateToolInput;typeof n=="function"&&(t.validateToolInput=async(r,o,s)=>{let i=r.inputSchema;if(!Sp(i))return n.call(e,r,o,s);let d=await i.safeParseAsync(o??{});if(d.success)return d.data;let l=_n(Tp(s,o,d.error.issues),"mcp"),c=l?{...l.body,statusCode:l.statusCode}:{};throw new Error(JSON.stringify(c))})}a(wa,"installMcpArgumentErrorMapping");function ba(e,t,n,r){e.registerTool("get_status",{description:'Return plugin status (version, AI feature flags, storage path, deploy defaults). For access-link callers, permission is null and caller.kind is "access-link" \u2014 that is expected, not an error. Use before other tools to confirm the plugin is enabled.'},()=>{try{return Z(rn(t,r))}catch(o){return ee(o)}}),e.registerTool("list_flows",{description:"List all flows as a flat Admin API v2 array plus the current rev string. Returns { rev, flows }. Call this (or get_flow) before submit_proposal so expectedRev matches."},async()=>{try{return Z(await pe(n.flowAdapter))}catch(o){return ee(o,502)}}),e.registerTool("get_flow",{description:"Get one tab/subflow by id with nested nodes/configs and the current rev. Pass summary=true for a lightweight node list (id/type/name/wires/bytes, no field contents). Prefer summary \u2192 search_flows \u2192 get_node_field(lines) \u2192 replace_text \u2192 submit_proposal. Returns { rev, flow } or summary shape. Use rev as expectedRev when submitting.",inputSchema:{id:T.z.string().min(1).describe("Flow / tab id"),summary:T.z.boolean().optional().describe("When true, return node list with sizes only (no field contents)")}},async({id:o,summary:s})=>{try{return Z(s?await xr(n.flowAdapter,o):await xe(n.flowAdapter,o))}catch(i){return ee(i,502)}}),e.registerTool("get_node",{description:"Get one full node by id (includes owning flowId when known). Optional flow scopes the lookup.",inputSchema:{id:T.z.string().min(1).describe("Node id"),flow:T.z.string().min(1).optional().describe("Optional tab id to scope the lookup")}},async({id:o,flow:s})=>{try{return Z(await Sr(n.flowAdapter,o,s))}catch(i){return ee(i,502)}}),e.registerTool("get_node_field",{description:'Get one string field from a node. Optional lines="A-B" (1-based inclusive) returns a slice; response always includes totalLines and bytes.',inputSchema:{id:T.z.string().min(1).describe("Node id"),field:T.z.string().min(1).describe("Field name (e.g. template, func)"),lines:T.z.string().optional().describe("Optional 1-based line range A or A-B"),flow:T.z.string().min(1).optional().describe("Optional tab id to scope the lookup")}},async({id:o,field:s,lines:i,flow:d})=>{try{return Z(await Tr(n.flowAdapter,o,s,{...d?{flowId:d}:{},...i?{lines:i}:{}}))}catch(l){return ee(l,502)}}),e.registerTool("search_flows",{description:"Text search across string fields. Returns hits with node id, field, line numbers, and a short snippet. Results are capped; truncated=true when the cap is hit. Optional flow scopes to one tab.",inputSchema:{q:T.z.string().describe("Substring to find (case-sensitive; non-empty required)"),flow:T.z.string().min(1).optional().describe("Optional tab id")}},async({q:o,flow:s})=>{try{return Z(await Pr(n.flowAdapter,o,s?{flowId:s}:{}))}catch(i){return ee(i,502)}}),e.registerTool("list_node_types",{description:"List installed Node-RED palette node types (type, module, category, description, \u2026). Optional q filters type/module/category/description (case-insensitive). Results are capped. Call this before proposing nodes with unfamiliar types.",inputSchema:{q:T.z.string().optional().describe("Optional case-insensitive filter")}},async({q:o})=>{try{return Z(await ir(n.nodeTypesAdapter,o?{q:o}:{}))}catch(s){return ee(s,502)}}),e.registerTool("get_node_type",{description:"Get detail for one installed node type: defaults (JSON), inputs/outputs (always set), requiredConfigNodeTypes, help sections (summary/inputs/outputs), category/module/color. Types are case-sensitive. Pass includeHelp=false to omit help. 404 node_type_not_found when unknown (didYouMean on case mismatch; else nearest names).",inputSchema:{type:T.z.string().min(1).describe("Node type id (e.g. inject, template) \u2014 case-sensitive"),includeHelp:T.z.boolean().optional().describe("When false, omit help sections (default true)")}},async({type:o,includeHelp:s})=>{try{return Z(await ct(n.nodeTypesAdapter,o,{includeHelp:s!==!1}))}catch(i){return ee(i,502)}}),e.registerTool("search_palette",{description:"Search the public Node-RED catalogue for modules to recommend. Returns module id, description, version, updated, link, and installed boolean (cross-checked against installed modules). Core node-red types are not in the catalogue \u2014 use list_node_types. RECOMMEND ONLY \u2014 never installs.",inputSchema:{q:T.z.string().describe("Search string (id / description / keywords; non-empty required)")}},async({q:o})=>{try{return Z(await ar(n.nodeTypesAdapter,o,{...n.catalogueFetcher?{catalogueFetcher:n.catalogueFetcher}:{},...n.catalogueUrl?{catalogueUrl:n.catalogueUrl}:{}}))}catch(s){return ee(s,502)}})}a(ba,"registerReadTools");function va(e,t,n,r,o){let s=q(r,t.settings.httpAdminRoot);e.registerTool("submit_proposal",{description:`Submit a replace_flow proposal for owner approval (does not deploy). Preferred for small string edits: payload: { flowId, nodes: [{ op:"replace_text", node, field, find, replace, occurrence? }] } \u2014 find must be unique unless occurrence (1-based) is set; multiple replace_text ops apply in order; yields a short readable diff. Or send a full tab: payload.flow from get_flow (id, type, label?, nodes[], configs?). Inputs (all top-level, next to each other): type="replace_flow", expectedRev (required string from list_flows/get_flow rev; expected_rev alias accepted), optional title (\u226480 chars), and payload: { flowId, flow? } and/or payload.nodes / top-level nodes. Do not nest expectedRev inside payload. Payload size limit is ${j} bytes (413 if exceeded). expectedRev is checked against the live rev at submit time (409 if stale). replace_text errors: 400 text_not_found; 409 ambiguous_match with matchCount. Unknown palette types return 400 unknown_node_type with nearest matches \u2014 call list_node_types / search_palette and ask the user to install via Manage palette (never auto-install). Returns a lean proposal (id, status, title, storedTitle, flowLabel, displayName, reviewUrl, changeSummary, \u2026) by default; title may gain " in <flow>"; storedTitle is the title as saved (your title without that suffix, or the auto-generated title, which may already name the flow). Pass include_payload=true to include payload and baseFlow. When telling the user about the proposal, cite displayName and reviewUrl \u2014 not the raw id. Humans approve on the /ai-access dashboard (reviewUrl opens/scrolls to it).`,inputSchema:{type:T.z.literal("replace_flow").describe("Must be 'replace_flow'"),expectedRev:T.z.string().min(1).optional().describe("Top-level current flow revision from get_flow/list_flows (required at submit; sit next to type and payload, not inside payload)"),expected_rev:T.z.string().min(1).optional().describe("Alias for expectedRev (snake_case); prefer expectedRev"),title:T.z.string().max(80).optional().describe("Optional short human title (\u226480 chars). Auto-generated from changes when omitted."),include_payload:T.z.boolean().optional().describe("When true, include payload and baseFlow in the response (default lean)"),nodes:T.z.array(T.z.record(T.z.string(),T.z.unknown())).optional().describe("Optional node ops (set/add/remove/replace_text). Same as payload.nodes when flow is omitted."),payload:T.z.object({flowId:T.z.string().min(1).describe("Tab id to replace"),flow:T.z.object({id:T.z.string().optional(),type:T.z.string().optional().describe("Usually 'tab' (included by get_flow)"),label:T.z.string().optional(),nodes:T.z.array(T.z.record(T.z.string(),T.z.unknown())).optional().describe("Child nodes for the tab (from get_flow.nodes)"),configs:T.z.array(T.z.record(T.z.string(),T.z.unknown())).optional()}).passthrough().optional().describe("Full tab from get_flow; omit when using nodes ops"),nodes:T.z.array(T.z.record(T.z.string(),T.z.unknown())).optional().describe("Node ops applied to the live tab (prefer replace_text for small string edits)")}).describe("Replacement flow payload and/or node ops")}},async i=>{try{let d=await Ye(n.proposalStore,n.auditLog,o,{...i,expectedRev:typeof i.expectedRev=="string"&&i.expectedRev.length>0?i.expectedRev:i.expected_rev},n.flowAdapter,s,n.nodeTypesAdapter),l={...ce(d,{...s,include:Yo(i.include_payload)}),mine:!0},c=V(n.proposalStore,d.expectedRev,{flowId:d.payload.flowId}),u=Ne(Ie(n.proposalStore,n.proposalStore.get(d.id),o.id));return Z({...l,...u,...Q(c)})}catch(d){return ee(d)}}),Rp(e,n,o,s),_p(e,n,o,s)}a(va,"registerProposalTools");function Pp(e,t,n,r){let o={mine:T.z.boolean().optional().describe("true: only proposals created by this access link; false: only other links\u2019 proposals"),status:T.z.union([T.z.string(),T.z.array(T.z.string())]).optional().describe("Filter by proposal status: one value, an array, or a comma-separated string (pending, approved, rejected, failed, withdrawn, expired, superseded). An empty array or empty string means no status filter."),flowId:T.z.string().optional().describe("Filter by flow tab id (payload.flowId)"),limit:T.z.number().int().min(1).max(Ut).optional().describe(`Page size (1\u2013${Ut}). Omit to return all matches.`),offset:T.z.number().int().min(0).optional().describe("Skip this many filtered results (default 0)"),include_payload:T.z.boolean().optional().describe("When true, include payload and baseFlow on each proposal")},s=a(async i=>{try{let d=Yo(i.include_payload),l=await ya(t.flowAdapter),c=l?V(t.proposalStore,l):0,u={};typeof i.mine=="boolean"&&(u.mine=i.mine);let p=Io(i.status);p&&(u.status=p),typeof i.flowId=="string"&&i.flowId.length>0&&(u.flowId=i.flowId),typeof i.limit=="number"&&(u.limit=i.limit),typeof i.offset=="number"&&(u.offset=i.offset);let f=qt(t.proposalStore,n,r,u);return Z({proposals:f.proposals.map(m=>ue(t.proposalStore,n,m,{...r,include:d},{includeConflicts:!1})),...ft({...f,returned:f.proposals.length}),...Q(c)})}catch(d){return ee(d)}},"listProposalsHandler");e.registerTool("list_proposals",{description:"List proposals visible to this access link (all proposals by default). Each item includes mine:true|false for the caller. Filter with mine, status, and/or flowId; paginate with limit/offset (response includes total, offset, hasMore, nextOffset). Invalid filters return invalid_filter. Returns lean { proposals, total, \u2026 } with title, displayName, reviewUrl, changeSummary (no payload/baseFlow unless include_payload=true). Prefer displayName + reviewUrl when referring to a proposal with the user (not the raw id).",inputSchema:o},s),e.registerTool("list_my_proposals",{description:"Alias of list_proposals. Prefer list_proposals. Lists proposals visible to this access link with optional mine/status/flowId filters and limit/offset pagination.",inputSchema:o},s)}a(Pp,"registerListProposalsTools");function Rp(e,t,n,r){Pp(e,t,n,r),e.registerTool("get_proposal",{description:"Get any proposal by id (all tokens can read). Response includes mine:true|false and, for pending proposals, conflictingProposals when other pending work touches the same flow. Lean by default (no payload/baseFlow); pass include_payload=true for full bodies. Cite displayName + reviewUrl when talking to the user.",inputSchema:{id:T.z.string().min(1).describe("Proposal id (prop-\u2026)"),include_payload:T.z.boolean().optional().describe("When true, include payload and baseFlow")}},async({id:o,include_payload:s})=>{try{let i=await ya(t.flowAdapter),d=De(t.proposalStore,n,o,r);return Z(ue(t.proposalStore,n,d,{...r,include:Yo(s)},{...i?{liveRev:i}:{}}))}catch(i){return ee(i)}})}a(Rp,"registerProposalQueryTools");function _p(e,t,n,r){e.registerTool("get_proposal_diff",{description:"Diff any proposal against its stored baseFlow snapshot (what changed). Optional format=summary|full (default summary). Pending + stale also includes vsCurrent.",inputSchema:{id:T.z.string().min(1).describe("Proposal id (prop-\u2026)"),format:T.z.enum(["summary","full"]).optional().describe("Diff payload format (default summary)")}},async({id:o,format:s})=>{try{let i=De(t.proposalStore,n,o),d=Yt(s??"summary");if(!d.ok)return ee(new y("Invalid diff format","invalid_diff_format",{details:{hint:"Valid formats: summary, full (default summary)."}}));let l=Qt(await nn(i,t.flowAdapter),d.format);return Z(l)}catch(i){return ee(i)}}),e.registerTool("withdraw_proposal",{description:"Withdraw one of YOUR pending proposals (status becomes withdrawn, not rejected). Optional reason. Only the creating access link can withdraw; other tokens get 403. Cite displayName + reviewUrl when telling the user.",inputSchema:{id:T.z.string().min(1).describe("Proposal id (prop-\u2026) owned by this access link"),reason:T.z.string().optional().describe("Optional withdraw reason")}},({id:o,reason:s})=>{try{let i=Wt(t.proposalStore,t.auditLog,n,o,s,r);return Z(ue(t.proposalStore,n,i,r))}catch(i){return ee(i)}})}a(_p,"registerProposalActionTools");function Lp(e,t,n){let r=new Xo.McpServer({name:"node-red-ai-access",version:ga()});wa(r);let o=n.accessLink;if(!o)throw new Error("Access link required");return ba(r,e,t,n),va(r,e,t,n,o),r}a(Lp,"createAiMcpServer");function Qo(e,t){return async(n,r,o)=>{try{if(!n.accessLink&&!n.auth){r.setHeader("WWW-Authenticate",Y),r.status(401).json({error:le,code:Le});return}let s=n.accessLink?Lp(e,t,n):Cp(e,t,n),i=new ha.StreamableHTTPServerTransport({enableJsonResponse:!0});await s.connect(i),await i.handleRequest(n,r,n.body),r.on("close",()=>{i.close(),s.close()})}catch(s){if(!r.headersSent){$(r,s);return}o(s instanceof Error?s:new Error(String(s)))}}}a(Qo,"mcpRpcPostHandler");function Cp(e,t,n){let r=new Xo.McpServer({name:"node-red-ai-access",version:ga()});if(wa(r),ba(r,e,t,n),(n.auth?.scopes??[]).includes("propose")){let s=typeof n.auth?.extra?.user=="string"?n.auth.extra.user:"owner",i=n.auth?.clientId??"",l={id:lo(i,s),kind:"mcp",createdAt:new Date().toISOString(),expiresAt:new Date((n.auth?.expiresAt??0)*1e3).toISOString(),createdBy:s,oauthClientId:i,oauthUser:s};va(r,e,t,n,l)}return r}a(Cp,"createOAuthMcpServer");function On(e,t){t.status(405).set("Allow","POST").json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed. Use POST for Streamable HTTP."},id:null})}a(On,"mcpRpcMethodNotAllowed");var $n=require("crypto"),sn=require("fs"),ts=require("path"),B=require("@modelcontextprotocol/sdk/server/auth/errors.js"),Ta=require("@modelcontextprotocol/sdk/server/auth/handlers/authorize.js"),ns=require("@modelcontextprotocol/sdk/server/auth/handlers/metadata.js"),Pa=require("@modelcontextprotocol/sdk/server/auth/handlers/register.js"),Ra=require("@modelcontextprotocol/sdk/server/auth/handlers/revoke.js"),_a=require("@modelcontextprotocol/sdk/server/auth/handlers/token.js"),La=require("@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js"),Ca=require("@modelcontextprotocol/sdk/server/auth/router.js"),Ea=ln(require("express"),1);G();_e();function $e(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}a($e,"esc");var ka={read:'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5c-5 0-9 4.5-10 7 1 2.5 5 7 10 7s9-4.5 10-7c-1-2.5-5-7-10-7Zm0 11.5a4.5 4.5 0 1 1 0-9 4.5 4.5 0 0 1 0 9Zm0-2.3a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4Z"/></svg>',propose:'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 17.2V20h2.8l8.3-8.3-2.8-2.8L4 17.2Zm13.7-7.6a1 1 0 0 0 0-1.4l-1.9-1.9a1 1 0 0 0-1.4 0l-1.4 1.4 2.8 2.8 1.9-1.9Z"/></svg>'},Ep={read:["Read your flows","View flows, nodes, node types and AI Access logs."],propose:["Propose flow changes","Submit change proposals. Nothing is deployed until you approve it in Node-RED."]},Ip='<svg class="logo" viewBox="0 0 48 48" aria-hidden="true"><rect width="48" height="48" rx="11" fill="#8f0000"/><path d="M11 15h9a4 4 0 0 1 4 4v10a4 4 0 0 0 4 4h9" fill="none" stroke="#fff" stroke-width="3" stroke-linecap="round"/><rect x="6" y="11" width="9" height="8" rx="2.5" fill="#fff"/><rect x="33" y="29" width="9" height="8" rx="2.5" fill="#fff"/><circle cx="37.5" cy="16" r="5" fill="none" stroke="#fff" stroke-width="2.4"/><path d="M37.5 13.5v5M35 16h5" stroke="#fff" stroke-width="2.2" stroke-linecap="round"/></svg>',Np=`
|
|
954
|
+
:root{color-scheme:light;--bg:#f3f4f6;--card:#fff;--text:#111827;--muted:#4b5563;--line:#e5e7eb;--soft:#f9fafb;--brand:#8f0000;--brand-2:#b91c1c;--ok:#0f766e;--warn-bg:#fff7ed;--warn:#9a3412;--focus:#2563eb}
|
|
956
955
|
*{box-sizing:border-box}
|
|
957
956
|
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px 16px;background:var(--bg);color:var(--text);font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
958
957
|
.card{width:100%;max-width:440px;background:var(--card);border:1px solid var(--line);border-radius:16px;box-shadow:0 10px 30px rgba(0,0,0,.08);overflow:hidden}
|
|
@@ -5996,34 +5995,6 @@ dialog h3 { margin: 0 0 0.4rem; }
|
|
|
5996
5995
|
nav.tabs button { flex: 0 0 auto; }
|
|
5997
5996
|
.field-line { flex-wrap: wrap; }
|
|
5998
5997
|
}
|
|
5999
|
-
@media (prefers-color-scheme: dark) {
|
|
6000
|
-
:root {
|
|
6001
|
-
color-scheme: dark;
|
|
6002
|
-
--bg: #12171d;
|
|
6003
|
-
--ink: #e3e9ef;
|
|
6004
|
-
--muted: #9aa8b6;
|
|
6005
|
-
--accent: #4cc59a;
|
|
6006
|
-
--accent-soft: #1d3a31;
|
|
6007
|
-
--warn-bg: #3a2e1a;
|
|
6008
|
-
--warn-border: #a2772f;
|
|
6009
|
-
--danger: #ff8a8a;
|
|
6010
|
-
--card: #1b222a;
|
|
6011
|
-
--line: #33404d;
|
|
6012
|
-
--ok: #6fd3a5;
|
|
6013
|
-
--soft: #222b35;
|
|
6014
|
-
--input-bg: #11161c;
|
|
6015
|
-
}
|
|
6016
|
-
body { background: var(--bg); }
|
|
6017
|
-
input, select, textarea { background: var(--input-bg); color: var(--ink); border-color: var(--line); }
|
|
6018
|
-
a { color: #7cc4ff; }
|
|
6019
|
-
.flash.error, .check-result.is-fail { background: #3a1f22; border-color: #6b3036; }
|
|
6020
|
-
.flash.ok, .check-result.is-ok { background: #173327; border-color: #2d6149; }
|
|
6021
|
-
.warn-text { color: #f0c36d; }
|
|
6022
|
-
.warning { background: var(--warn-bg); color: var(--ink); }
|
|
6023
|
-
button.action, button.action.danger, nav.tabs button[aria-selected="true"] { color: #0d1a14; }
|
|
6024
|
-
button.action.secondary { background: var(--soft); color: var(--ink); border-color: var(--line); }
|
|
6025
|
-
dialog { background: var(--card); color: var(--ink); }
|
|
6026
|
-
}
|
|
6027
5998
|
`}a($f,"pageStylesDashboard");function Ua(){return(Rf()+_f()+Lf()+Cf()+Ef()+If()+Nf()+Ff()+Of()+$f()).trim()}a(Ua,"pageStyles");function Mf(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}a(Mf,"escapeHtml");function Df(){return`
|
|
6028
5999
|
<header class="page-header">
|
|
6029
6000
|
<h1>Node-RED AI Access</h1>
|
package/package.json
CHANGED