kenobi-pages 0.1.18 → 0.1.19
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/bin/cli.mjs +7 -7
- package/package.json +1 -1
package/bin/cli.mjs
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Ce=Object.defineProperty;var r=(e,t)=>Ce(e,"name",{value:t,configurable:!0});var y=class extends Error{static{r(this,"CliError")}exitCode;payload;constructor(t,n=1){super(t.message),this.name="CliError",this.exitCode=n,this.payload={ok:!1,...t}}},d=r((e,t)=>new y({status:null,code:"invalid_usage",message:e,details:t},2),"usageError"),C=r((e,t)=>new y({status:404,code:"not_found",message:e,details:t},3),"notFoundError"),p=r((e,t,n)=>{if(!e)throw d(t,n);return e},"assertArg"),l=r(e=>{console.log(JSON.stringify(e,null,2))},"printJson"),te=r(e=>{console.error(JSON.stringify(e,null,2))},"writeError"),ne=r(e=>{e instanceof y&&(te(e.payload),process.exit(e.exitCode));let t=e instanceof Error?e.message:"Unknown error";te({ok:!1,status:null,code:"runtime_error",message:t}),process.exit(1)},"handleCliError");var g=r((e,t)=>{let n=e.indexOf(t);return n!==-1?e[n+1]:void 0},"parseFlag"),
|
|
3
|
-
`)){let c=i.trim();if(!c||c.startsWith("#"))continue;let a=c.match(/^([A-Z_][A-Z0-9_]*)=["']?([^"']*)["']?$/);a&&(e[a[1]]??=a[2])}}return e},"loadEnvFromCwd"),H=null,R=r(e=>process.env[e]?process.env[e]:(H??=Ne(),H[e]),"getEnvVar"),Ke=r(()=>{H=null},"resetEnvCache"),
|
|
2
|
+
var Ce=Object.defineProperty;var r=(e,t)=>Ce(e,"name",{value:t,configurable:!0});var y=class extends Error{static{r(this,"CliError")}exitCode;payload;constructor(t,n=1){super(t.message),this.name="CliError",this.exitCode=n,this.payload={ok:!1,...t}}},d=r((e,t)=>new y({status:null,code:"invalid_usage",message:e,details:t},2),"usageError"),C=r((e,t)=>new y({status:404,code:"not_found",message:e,details:t},3),"notFoundError"),p=r((e,t,n)=>{if(!e)throw d(t,n);return e},"assertArg"),l=r(e=>{console.log(JSON.stringify(e,null,2))},"printJson"),te=r(e=>{console.error(JSON.stringify(e,null,2))},"writeError"),ne=r(e=>{e instanceof y&&(te(e.payload),process.exit(e.exitCode));let t=e instanceof Error?e.message:"Unknown error";te({ok:!1,status:null,code:"runtime_error",message:t}),process.exit(1)},"handleCliError");var g=r((e,t)=>{let n=e.indexOf(t);return n!==-1?e[n+1]:void 0},"parseFlag"),h=r((e,t)=>e.includes(t),"hasFlag"),f=r((e,t,n)=>{let o=g(e,t);if(!o||o.startsWith("--"))throw d(n);return o},"parseRequiredFlag"),L=r((e,t)=>{let n=g(e,t);if(n===void 0)return;let o=Number(n);if(!Number.isInteger(o)||o<=0)throw d(`${t} must be a positive integer`);return o},"parseOptionalPositiveIntFlag"),B=r((e,t)=>{let n=g(e,t);if(n===void 0)return;let o=Number(n);if(!Number.isInteger(o)||o<0)throw d(`${t} must be a non-negative integer`);return o},"parseOptionalNonNegativeIntFlag");import{appendFileSync as je,existsSync as G,readFileSync as V,writeFileSync as oe}from"node:fs";import{resolve as se}from"node:path";var Ae="https://kenobi.ai",w="KENOBI_PAGES_KEY",re=[".env.local",".env",".env.development",".env.development.local"],Ne=r(()=>{let e={},t=process.cwd();for(let n of re){let o=se(t,n);if(!G(o))continue;let s=V(o,"utf-8");for(let i of s.split(`
|
|
3
|
+
`)){let c=i.trim();if(!c||c.startsWith("#"))continue;let a=c.match(/^([A-Z_][A-Z0-9_]*)=["']?([^"']*)["']?$/);a&&(e[a[1]]??=a[2])}}return e},"loadEnvFromCwd"),H=null,R=r(e=>process.env[e]?process.env[e]:(H??=Ne(),H[e]),"getEnvVar"),Ke=r(()=>{H=null},"resetEnvCache"),b=r(()=>(R("KENOBI_BASE_URL")??Ae).replace(/\/+$/,""),"getBaseUrl"),ie=r(()=>{let e=R(w);if(e)return e;throw new y({status:null,code:"missing_api_key",message:`No API key found. Run 'npx kenobi-pages init' or set ${w}.`},4)},"getApiKey"),ae=r(()=>R(w),"getApiKeyOptional"),U=r(()=>{let e=process.cwd();return re.filter(t=>G(se(e,t)))},"discoverEnvFiles"),ce=r((e,t,n)=>{let o=V(e,"utf-8");if(o.includes(t)){console.error(` ${t} already present in ${e.split("/").pop()}`);return}let s=o.endsWith(`
|
|
4
4
|
`)?"":`
|
|
5
5
|
`;je(e,`${s}${t}="${n}"
|
|
6
6
|
`),console.error(` Added ${t} to ${e.split("/").pop()}`)},"appendEnvVar"),j=r((e,t,n)=>{oe(e,`${t}="${n}"
|
|
7
7
|
`)},"writeEnvFile"),q=r((e,t,n)=>{let o=G(e)?V(e,"utf-8"):"",s=`${t}="${n}"`,i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`^${i}=.*$`,"m"),a=c.test(o)?o.replace(c,s):`${o}${o.length>0&&!o.endsWith(`
|
|
8
8
|
`)?`
|
|
9
9
|
`:""}${s}
|
|
10
|
-
`;oe(e,a),Ke()},"upsertEnvVar");var De=r(async e=>{let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}},"parseErrorBody"),_e=r(e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"error"in e){let t=e.error;return typeof t=="string"?t:JSON.stringify(t)}return"Kenobi API request failed"},"errorMessageFromBody"),Je=r(e=>e===401||e===403?4:e===404?3:1,"exitCodeForStatus"),u=r(async(e,t={})=>{let n=await fetch(`${S()}${e}`,{method:t.method??"GET",headers:{"x-kenobi-key":ie(),"Content-Type":"application/json"},body:t.body?JSON.stringify(t.body):void 0});if(n.ok)return await n.json();let o=await De(n);throw new y({status:n.status,code:n.status===401||n.status===403?"unauthorized":"api_error",message:_e(o),details:o},Je(n.status))},"fetchKenobi"),v=r(e=>{let t=new URLSearchParams;for(let[n,o]of Object.entries(e))o!==void 0&&t.set(n,o);return t.toString()},"buildQuery");var $=r(e=>Object.keys(e??{}),"keys"),le=r(e=>{let t=e.packJson??null,n=t?.tokens??{},o=t?.surfaces??{},s=t?.typography??{},i=t?.accents??{};return{designPack:{id:e.id,status:e.status,hostDomain:t?.hostDomain??e.hostDomain??null,raw:t},templateGuidance:{brandSummary:t?.compositionDescription??"Use the raw design pack tokens and recipes as the source of truth.",tokens:{color:n.color??{},font:n.font??{},radius:n.radius??{},container:n.container??{},section:n.section??{}},surfaces:o,typography:s,accents:i,use:["Use color, font, radius, spacing, surface, and typography recipes from this design pack before inventing new styles.","Preserve the source site's visual rhythm, density, button treatment, and section composition.","Keep the template source self-contained and accept all dynamic values through the Template content prop."],avoid:["Do not use generic SaaS gradients, decorative orbs, or unrelated stock-style visuals.","Do not introduce a new palette when the design pack already contains brand colors.","Do not hard-code personalized copy that should come from the content schema."],availableRecipes:{colors:$(n.color),fonts:$(n.font),radii:$(n.radius),surfaces:$(o),typography:$(s),accents:$(i)}}}},"exportDesignPackForAgent");var We=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),Me=r(e=>new Promise(t=>setTimeout(t,e)),"sleep"),Le=r(e=>{console.error(JSON.stringify({event:"poll",taskStatus:e}))},"emitPollEvent"),Be=r((e,t)=>{if(typeof t.ok=="boolean")return{envelope:t,exitCode:t.ok?0:1};let n=typeof t.status=="string"?t.status:"UNKNOWN",o=t.designPack,i=(o!==null&&typeof o=="object"&&"id"in o&&typeof o.id=="number"?o.id:null)??(typeof t.designPackId=="number"?t.designPackId:null),c=n==="COMPLETED"&&o!==null&&typeof o=="object"&&i!==null;return{envelope:{...t,ok:c,taskStatus:n,designPackStatus:c?"ready":"failed",designPackId:i,nextCommand:c&&i!==null?`kenobi-pages design-pack export ${e} ${i}`:null},exitCode:c?0:1}},"resolveDesignPackTerminal"),He=r(async(e,t)=>{let n=2e3,o=15e3;for(;;){await Me(n);let s=await u(`/api/v1/pages/evidence-bundles/${e}/design-packs/runs/${t}`),i=typeof s.taskStatus=="string"?s.taskStatus:typeof s.status=="string"?s.status:"UNKNOWN";if(Le(i),!We.has(i)){n=Math.min(n*1.5,o);continue}let{envelope:c,exitCode:a}=Be(e,s);l(c),a!==0&&process.exit(a);return}},"pollDesignPack"),ue=r(async e=>{let[t,...n]=e,o=n[0];if(t==="list"){p(o,"Usage: kenobi-pages design-pack list <bundleId>"),l(await u(`/api/v1/pages/evidence-bundles/${o}/design-packs`));return}if(t==="generate"){p(o,"Usage: kenobi-pages design-pack generate <bundleId> [--wait]");let s=await u(`/api/v1/pages/evidence-bundles/${o}/design-packs`,{method:"POST",body:w(n.slice(1),"--dry-run")?{dryRun:!0}:{}});if(w(n.slice(1),"--dry-run")){l(s);return}if(!w(n.slice(1),"--wait")){l(s);return}let i=typeof s.taskId=="string"?s.taskId:void 0;if(!i){l(s);return}console.error(JSON.stringify({event:"queued",taskId:i})),await He(o,i);return}if(t==="status"){let s=p(n[1],"Usage: kenobi-pages design-pack status <bundleId> <taskId>");p(o,"Usage: kenobi-pages design-pack status <bundleId> <taskId>"),l(await u(`/api/v1/pages/evidence-bundles/${o}/design-packs/runs/${s}`));return}if(t==="get"){let s=p(n[1],"Usage: kenobi-pages design-pack get <bundleId> <designPackId>");p(o,"Usage: kenobi-pages design-pack get <bundleId> <designPackId>"),l(await u(`/api/v1/pages/evidence-bundles/${o}/design-packs/${s}`));return}if(t==="export"){let s=p(n[1],"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");p(o,"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");let i=await u(`/api/v1/pages/evidence-bundles/${o}/design-packs/${s}`);l(le(i.designPack??{}));return}throw d(`Unknown design-pack command: ${e.join(" ")}`)},"handleDesignPack");import{existsSync as Ge,readFileSync as Ve}from"node:fs";import{dirname as de,join as qe}from"node:path";import{fileURLToPath as Ye}from"node:url";var ze=r(()=>{let e=de(Ye(import.meta.url));for(let t=0;t<6;t+=1){let n=qe(e,"package.json");if(Ge(n))try{let o=JSON.parse(Ve(n,"utf-8"));if(o.name==="kenobi-pages"&&o.version)return o.version}catch{return"unknown"}e=de(e)}return"unknown"},"findPackageVersion"),pe=ze();var Qe=r(async e=>{try{let t=await fetch(`${S()}/api/v1/cortex/sources`,{headers:{"x-kenobi-key":e,"Content-Type":"application/json"}});if(!t.ok)return{auth:{ok:!1,status:t.status},sources:{count:null}};let n=await t.json();return{auth:{ok:!0,status:t.status},sources:{count:Array.isArray(n.sources)?n.sources.length:0}}}catch(t){return{auth:{ok:!1,status:null,error:t instanceof Error?t.message:"Unknown error"},sources:{count:null}}}},"authCheck"),ge=r(async()=>{let e=ae(),t=U(),n=e?await Qe(e):{auth:{ok:!1,status:null,skipped:!0},sources:{count:null}},o=[];e?n.auth.ok||o.push("Check that the Kenobi API key is valid for this org."):o.push(`Run 'kenobi-pages init' or set ${h}.`),e&&n.auth.ok&&n.sources.count===0&&o.push("Connect at least one source in Kenobi before building data-backed workflows."),l({ok:!!(e&&n.auth.ok),cli:{version:pe},env:{hasApiKey:!!e,apiKeyEnvVar:h,baseUrl:S(),envFiles:t},auth:n.auth,sources:n.sources,nextSteps:o})},"handleDoctor");import{readFile as me}from"node:fs/promises";var fe=r(()=>new Promise((e,t)=>{if(process.stdin.isTTY){e("");return}let n="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",o=>{n+=o}),process.stdin.on("end",()=>e(n)),process.stdin.on("error",t)}),"readStdin"),b=r((e,t)=>{try{return JSON.parse(e)}catch{throw d(`Invalid JSON for ${t}`)}},"parseJson"),x=r(async(e,t)=>b(await me(e,"utf-8"),t),"readJsonFile"),O=r(async(e,t)=>{if(!e){let n=await fe();if(!n.trim())throw d(`Missing ${t}`);return b(n,t)}if(e==="-"){let n=await fe();if(!n.trim())throw d(`Missing ${t} on stdin`);return b(n,t)}return e.trim().startsWith("{")||e.trim().startsWith("[")?b(e,t):x(e,t)},"readJsonSource"),F=r(async(e,t="JSON")=>{let n=g(e,"--file");if(n)return x(n,t);let o=e.find(s=>s.trim().startsWith("{")||s.trim().startsWith("["));return O(o,t)},"readJsonInput"),we=r(async(e,t,n)=>{let o=g(e,t);if(o!==void 0)return O(o,n)},"readJsonFlag"),A=r(async(e,t,n)=>O(g(e,t),n),"readRequiredJsonFlag"),he=r(async(e,t,n)=>{let o=g(e,t);if(!o||o.startsWith("--"))throw d(`Missing ${n}`);return me(o,"utf-8")},"readTextFileFlag");var Ze=r((e,t)=>{let n={url:e},o=g(t,"--viewport"),s=g(t,"--headers"),i=g(t,"--wait-for-selector"),c=B(t,"--wait-timeout"),a=g(t,"--wait-until"),m=B(t,"--extra-wait-ms");return o&&(n.viewport=b(o,"--viewport")),s&&(n.headers=b(s,"--headers")),i&&(n.waitForSelector=i),c!==void 0&&(n.waitTimeout=c),a&&(n.waitUntil=a.trim().startsWith("[")?b(a,"--wait-until"):a),m!==void 0&&(n.extraWaitMs=m),w(t,"--block-annoyances")&&(n.blockAnnoyances=!0),w(t,"--dry-run")&&(n.dryRun=!0),n},"createEvidenceBody"),ke=r(async e=>{let[t,...n]=e;if(t==="list"){l(await u("/api/v1/pages/evidence-bundles"));return}if(t==="create"){let o=p(n[0],"Usage: kenobi-pages evidence create <url> [flags]");l(await u("/api/v1/pages/evidence-bundles",{method:"POST",body:Ze(o,n.slice(1))}));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages evidence get <bundleId>");l(await u(`/api/v1/pages/evidence-bundles/${o}`));return}throw d(`Unknown evidence command: ${e.join(" ")}`)},"handleEvidence");var Xe="kenobi.page",et=r(e=>(e??Xe).replace(/^https?:\/\//,"").replace(/\/+$/,"").toLowerCase(),"normalizeHostedDomain"),tt=r(()=>et(R("KENOBI_PAGES_HOSTED_DOMAIN")),"getHostedPagesDomain"),I=r(({siteSlug:e,templateSlug:t,itemSlug:n})=>`https://${e}.${tt()}/${t}/${n}`,"buildHostedPublicUrl"),ye=r((e,t)=>{if(typeof e!="object"||e===null)return e;let n=e,o=typeof n.siteSlug=="string"?n.siteSlug:t?.siteSlug,s=typeof n.templateSlug=="string"?n.templateSlug:t?.templateSlug,i=typeof n.itemSlug=="string"?n.itemSlug:t?.itemSlug;return!o||!s||!i?e:{...e,publicUrl:I({siteSlug:o,templateSlug:s,itemSlug:i})}},"maybeDecorateHostedContent"),Y=r((e,t)=>({...e,publicUrl:I(t)}),"decorateHostedContentResponse");var be=r(async e=>{let t=f(e,"--template-slug","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),n=f(e,"--template-name","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),o=await he(e,"--source","--source <tsx-file>"),s=f(e,"--schema","Missing --schema <json-file>"),i=f(e,"--content","Missing --content <json-file>"),c=L(e,"--design-pack-id"),a=g(e,"--site-slug"),m=g(e,"--site-name"),k={templateSlug:t,templateName:n,sourceTsx:o,contentSchema:{title:n,schemaJson:await x(s,"--schema")},defaultContentJson:await x(i,"--content"),setCurrentDraft:!w(e,"--no-current-draft")};return c!==void 0&&(k.designPackId=c),a&&(k.site={slug:a,...m?{name:m}:{}}),k},"parseHostedDraftBody"),Se=r(e=>{let t=typeof e.previewPath=="string"?e.previewPath:null;return{...e,...t?{previewUrl:`${S()}${t}`}:{}}},"withPreviewUrl"),nt=r(async e=>{let[t,...n]=e;if(t==="list"){l(await u("/api/v1/pages/hosted/sites"));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted site get <siteSlug>");l(await u(`/api/v1/pages/hosted/sites?${v({slug:o})}`));return}throw d(`Unknown hosted site command: ${e.join(" ")}`)},"handleHostedSite"),ot=r(async e=>{let[t,...n]=e;if(t==="list"){let o=v({full:w(n,"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates${o?`?${o}`:""}`));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted template get <templateIdOrSlug> [--full]"),s=v({full:w(n.slice(1),"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates/${o}${s?`?${s}`:""}`));return}throw d(`Unknown hosted template command: ${e.join(" ")}`)},"handleHostedTemplate"),st=r(async e=>{let[t,...n]=e;if(t==="list"){let o=p(n[0],"Usage: kenobi-pages hosted publication list <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${o}/publications`));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>"),s=p(n[1],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>");l(await u(`/api/v1/pages/hosted/templates/${o}/publications/${s}`));return}throw d(`Unknown hosted publication command: ${e.join(" ")}`)},"handleHostedPublication"),rt=r(async e=>{let[t,...n]=e;if(t==="list"){let o=f(n,"--site","Usage: kenobi-pages hosted content list --site <siteSlug> [--template <templateSlug>]"),s=g(n,"--template"),i=await u(`/api/v1/pages/hosted/instances?${v({siteSlug:o,templateSlug:s})}`);l({...i,instances:(i.instances??[]).map(c=>ye(c,{siteSlug:o,templateSlug:s}))});return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),s=p(n[1],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),c=await u(`/api/v1/pages/hosted/instances/${o}/${s}/${i}`);l(Y(c,{siteSlug:o,templateSlug:s,itemSlug:i}));return}if(t==="upsert"){let o=f(n,"--site","Usage: kenobi-pages hosted content upsert --site <siteSlug> --template <templateSlug> --item <itemSlug> --content <json|file|->"),s=f(n,"--template","Missing --template <templateSlug>"),i=f(n,"--item","Missing --item <itemSlug>"),c=L(n,"--publication-id"),a=await A(n,"--content","--content"),m=await u("/api/v1/pages/hosted/instances",{method:"POST",body:{siteSlug:o,templateSlug:s,itemSlug:i,contentJson:a,...c!==void 0?{publicationId:c}:{}}});l(Y(m,{siteSlug:o,templateSlug:s,itemSlug:i}));return}if(t==="verify"){let o=p(n[0],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),s=p(n[1],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),c=I({siteSlug:o,templateSlug:s,itemSlug:i});try{let a=await u(`/api/v1/pages/hosted/instances/${o}/${s}/${i}`);l({ok:!0,publicUrl:c,resolved:!0,contentValid:!0,publication:a.templatePublication??null})}catch(a){if(!(a instanceof y))throw a;let k=(typeof a.payload.details=="object"&&a.payload.details!==null&&"stage"in a.payload.details?a.payload.details.stage:null)==="invalid-content"?!1:null;l({ok:!1,publicUrl:c,resolved:a.payload.status!==404,contentValid:k,publication:null,error:a.payload}),process.exit(a.exitCode)}return}throw d(`Unknown hosted content command: ${e.join(" ")}`)},"handleHostedContent"),it=r(async e=>{let[t,...n]=e;if(t==="create"){let o=["--site-slug",f(n,"--site-slug","Missing --site-slug <siteSlug>"),...g(n,"--site-name")?["--site-name",g(n,"--site-name")]:[],"--template-slug",f(n,"--template-slug","Missing --template-slug <templateSlug>"),"--template-name",f(n,"--template-name","Missing --template-name <templateName>"),"--source",f(n,"--source","Missing --source <tsx-file>"),"--schema",f(n,"--schema","Missing --schema <json-file>"),"--content",f(n,"--content","Missing --content <json-file>"),...g(n,"--design-pack-id")?["--design-pack-id",g(n,"--design-pack-id")]:[],...w(n,"--no-current-draft")?["--no-current-draft"]:[]];l(Se(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await be(o)})));return}throw d(`Unknown hosted page command: ${e.join(" ")}`)},"handleHostedPage"),ve=r(async e=>{let[t,n,...o]=e;if(t==="site")return nt([n,...o].filter(Boolean));if(t==="template")return ot([n,...o].filter(Boolean));if(t==="publication")return st([n,...o].filter(Boolean));if(t==="content")return rt([n,...o].filter(Boolean));if(t==="page")return it([n,...o].filter(Boolean));if(t==="draft"&&n==="save"){l(Se(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await be(o)})));return}if(t==="publish"){let s=p(n,"Usage: kenobi-pages hosted publish <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${s}/publish`,{method:"POST"}));return}throw d(`Unknown hosted command: ${e.join(" ")}`)},"handleHosted");import{readFile as at}from"node:fs/promises";var ct=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),lt="hosted-pages",ut="Usage: kenobi-pages run <workflowIdOrSlug> [--dry-run] [--debug] [--params '<json>'|--params-file params.json] [--context <text>|--context-file notes.md]",dt=r(e=>new Promise(t=>setTimeout(t,e)),"sleep"),pt=r(e=>{console.error(JSON.stringify({event:"poll",taskStatus:e}))},"emitPollEvent"),gt=r(e=>{if(!e||typeof e!="object")return null;let n=e.deliveries;if(!Array.isArray(n))return null;for(let o of n){if(!o||typeof o!="object")continue;let s=o;if(s.adapter!==lt)continue;let i=s.metadata;if(!i||typeof i!="object")continue;let c=i,a=c.siteSlug,m=c.templateSlug,k=c.itemSlug;if(typeof a=="string"&&typeof m=="string"&&typeof k=="string")return`kenobi-pages hosted content verify ${a} ${m} ${k}`}return null},"extractHostedPagesVerifyCommand"),ft=r(e=>e==="COMPLETED"?"completed":e==="FAILED"||e==="CANCELED"||e==="SYSTEM_FAILURE"||e==="CRASHED"?"failed":e==="QUEUED"||e==="DELAYED"||e==="FROZEN"?"queued":"running","mapWorkflowRunStatusLegacy"),mt=r(e=>{if(typeof e.ok=="boolean")return{envelope:e,exitCode:e.ok?0:1};let t=typeof e.status=="string"?e.status:"UNKNOWN",n=ft(t),o=n==="completed",s=o&&e.output!==void 0&&e.output!==null?gt(e.output):null;return{envelope:{...e,ok:o,taskStatus:t,runStatus:n,nextCommand:s},exitCode:o?0:1}},"resolveRunTerminal"),wt=r(e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"message"in e){let t=e.message;if(typeof t=="string")return t}return"Unknown error"},"runStatusErrorMessage"),xe=r(async e=>{let t=p(e[0],ut),n=e.slice(1),o=g(n,"--params"),s=g(n,"--params-file"),i=g(n,"--context"),c=g(n,"--context-file"),a=w(n,"--dry-run"),m=w(n,"--debug");if(s?.startsWith("--"))throw d("Missing --params-file <path>");if(c?.startsWith("--"))throw d("Missing --context-file <path>");let k=s?await x(s,"--params-file"):o?b(o,"--params"):{},X=c?await at(c,"utf-8"):i,K={params:k};X&&(K.context=X),a&&(K.dryRun=!0);let D=await u(`/api/v1/cortex/workflows/${t}/run`,{method:"POST",body:K});if(a){l(D);return}let _=typeof D.runId=="string"?D.runId:void 0;if(!_)throw d("Run did not return a runId");console.error(JSON.stringify({event:"triggered",runId:_})),console.error(JSON.stringify({event:"polling_started"}));let J=2e3,Te=15e3;for(;;){await dt(J);let E=await u(`/api/v1/cortex/workflows/${t}/runs/${_}${m?"?debug=true":""}`),W=typeof E.taskStatus=="string"?E.taskStatus:typeof E.status=="string"?E.status:"UNKNOWN";if(pt(W),!ct.has(W)){J=Math.min(J*1.5,Te);continue}let{envelope:ee,exitCode:M}=mt(E);M!==0&&console.error(JSON.stringify({event:"terminal_failed",taskStatus:W,message:wt(ee.error)})),l(ee),M!==0&&process.exit(M);return}},"handleRun");var N=r((e,t)=>{let n=" ".repeat(t);switch(e.type){case"string":case"url":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return e.items?.type==="object"&&e.items.fields?`Array<{
|
|
10
|
+
`;oe(e,a),Ke()},"upsertEnvVar");var De=r(async e=>{let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}},"parseErrorBody"),_e=r(e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"error"in e){let t=e.error;return typeof t=="string"?t:JSON.stringify(t)}return"Kenobi API request failed"},"errorMessageFromBody"),Je=r(e=>e===401||e===403?4:e===404?3:1,"exitCodeForStatus"),u=r(async(e,t={})=>{let n=await fetch(`${b()}${e}`,{method:t.method??"GET",headers:{"x-kenobi-key":ie(),"Content-Type":"application/json"},body:t.body?JSON.stringify(t.body):void 0});if(n.ok)return await n.json();let o=await De(n);throw new y({status:n.status,code:n.status===401||n.status===403?"unauthorized":"api_error",message:_e(o),details:o},Je(n.status))},"fetchKenobi"),v=r(e=>{let t=new URLSearchParams;for(let[n,o]of Object.entries(e))o!==void 0&&t.set(n,o);return t.toString()},"buildQuery");var $=r(e=>Object.keys(e??{}),"keys"),le=r(e=>{let t=e.packJson??null,n=t?.tokens??{},o=t?.surfaces??{},s=t?.typography??{},i=t?.accents??{};return{designPack:{id:e.id,status:e.status,hostDomain:t?.hostDomain??e.hostDomain??null,raw:t},templateGuidance:{brandSummary:t?.compositionDescription??"Use the raw design pack tokens and recipes as the source of truth.",tokens:{color:n.color??{},font:n.font??{},radius:n.radius??{},container:n.container??{},section:n.section??{}},surfaces:o,typography:s,accents:i,use:["Treat this design pack as the default styling source of truth for the template.","Start every visual decision from the pack's tokens, surfaces, typography, accents, spacing, radius, and composition description.","Use color, font, radius, spacing, surface, and typography recipes from this design pack before inventing new styles.","Preserve the source site's visual rhythm, density, button treatment, and section composition.","Keep the template source self-contained and accept all dynamic values through the Template content prop."],avoid:["Do not use generic SaaS gradients, decorative orbs, or unrelated stock-style visuals.","Do not introduce a new palette when the design pack already contains brand colors.","Do not invent a font system, surface language, decorative style, or generic layout unless the design pack is missing that information.","Do not depart from the design pack without making the deviation explicit.","Do not hard-code personalized copy that should come from the content schema."],availableRecipes:{colors:$(n.color),fonts:$(n.font),radii:$(n.radius),surfaces:$(o),typography:$(s),accents:$(i)}}}},"exportDesignPackForAgent");var We=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),Me=r(e=>new Promise(t=>setTimeout(t,e)),"sleep"),Le=r(e=>{console.error(JSON.stringify({event:"poll",taskStatus:e}))},"emitPollEvent"),Be=r((e,t)=>{if(typeof t.ok=="boolean")return{envelope:t,exitCode:t.ok?0:1};let n=typeof t.status=="string"?t.status:"UNKNOWN",o=t.designPack,i=(o!==null&&typeof o=="object"&&"id"in o&&typeof o.id=="number"?o.id:null)??(typeof t.designPackId=="number"?t.designPackId:null),c=n==="COMPLETED"&&o!==null&&typeof o=="object"&&i!==null;return{envelope:{...t,ok:c,taskStatus:n,designPackStatus:c?"ready":"failed",designPackId:i,nextCommand:c&&i!==null?`kenobi-pages design-pack export ${e} ${i}`:null},exitCode:c?0:1}},"resolveDesignPackTerminal"),He=r(async(e,t)=>{let n=2e3,o=15e3;for(;;){await Me(n);let s=await u(`/api/v1/pages/evidence-bundles/${e}/design-packs/runs/${t}`),i=typeof s.taskStatus=="string"?s.taskStatus:typeof s.status=="string"?s.status:"UNKNOWN";if(Le(i),!We.has(i)){n=Math.min(n*1.5,o);continue}let{envelope:c,exitCode:a}=Be(e,s);l(c),a!==0&&process.exit(a);return}},"pollDesignPack"),ue=r(async e=>{let[t,...n]=e,o=n[0];if(t==="list"){p(o,"Usage: kenobi-pages design-pack list <bundleId>"),l(await u(`/api/v1/pages/evidence-bundles/${o}/design-packs`));return}if(t==="generate"){p(o,"Usage: kenobi-pages design-pack generate <bundleId> [--wait]");let s=await u(`/api/v1/pages/evidence-bundles/${o}/design-packs`,{method:"POST",body:h(n.slice(1),"--dry-run")?{dryRun:!0}:{}});if(h(n.slice(1),"--dry-run")){l(s);return}if(!h(n.slice(1),"--wait")){l(s);return}let i=typeof s.taskId=="string"?s.taskId:void 0;if(!i){l(s);return}console.error(JSON.stringify({event:"queued",taskId:i})),await He(o,i);return}if(t==="status"){let s=p(n[1],"Usage: kenobi-pages design-pack status <bundleId> <taskId>");p(o,"Usage: kenobi-pages design-pack status <bundleId> <taskId>"),l(await u(`/api/v1/pages/evidence-bundles/${o}/design-packs/runs/${s}`));return}if(t==="get"){let s=p(n[1],"Usage: kenobi-pages design-pack get <bundleId> <designPackId>");p(o,"Usage: kenobi-pages design-pack get <bundleId> <designPackId>"),l(await u(`/api/v1/pages/evidence-bundles/${o}/design-packs/${s}`));return}if(t==="export"){let s=p(n[1],"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");p(o,"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");let i=await u(`/api/v1/pages/evidence-bundles/${o}/design-packs/${s}`);l(le(i.designPack??{}));return}throw d(`Unknown design-pack command: ${e.join(" ")}`)},"handleDesignPack");import{existsSync as Ge,readFileSync as Ve}from"node:fs";import{dirname as de,join as qe}from"node:path";import{fileURLToPath as Ye}from"node:url";var ze=r(()=>{let e=de(Ye(import.meta.url));for(let t=0;t<6;t+=1){let n=qe(e,"package.json");if(Ge(n))try{let o=JSON.parse(Ve(n,"utf-8"));if(o.name==="kenobi-pages"&&o.version)return o.version}catch{return"unknown"}e=de(e)}return"unknown"},"findPackageVersion"),pe=ze();var Qe=r(async e=>{try{let t=await fetch(`${b()}/api/v1/cortex/sources`,{headers:{"x-kenobi-key":e,"Content-Type":"application/json"}});if(!t.ok)return{auth:{ok:!1,status:t.status},sources:{count:null}};let n=await t.json();return{auth:{ok:!0,status:t.status},sources:{count:Array.isArray(n.sources)?n.sources.length:0}}}catch(t){return{auth:{ok:!1,status:null,error:t instanceof Error?t.message:"Unknown error"},sources:{count:null}}}},"authCheck"),ge=r(async()=>{let e=ae(),t=U(),n=e?await Qe(e):{auth:{ok:!1,status:null,skipped:!0},sources:{count:null}},o=[];e?n.auth.ok||o.push("Check that the Kenobi API key is valid for this org."):o.push(`Run 'kenobi-pages init' or set ${w}.`),e&&n.auth.ok&&n.sources.count===0&&o.push("Connect at least one source in Kenobi before building data-backed workflows."),l({ok:!!(e&&n.auth.ok),cli:{version:pe},env:{hasApiKey:!!e,apiKeyEnvVar:w,baseUrl:b(),envFiles:t},auth:n.auth,sources:n.sources,nextSteps:o})},"handleDoctor");import{readFile as me}from"node:fs/promises";var fe=r(()=>new Promise((e,t)=>{if(process.stdin.isTTY){e("");return}let n="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",o=>{n+=o}),process.stdin.on("end",()=>e(n)),process.stdin.on("error",t)}),"readStdin"),S=r((e,t)=>{try{return JSON.parse(e)}catch{throw d(`Invalid JSON for ${t}`)}},"parseJson"),x=r(async(e,t)=>S(await me(e,"utf-8"),t),"readJsonFile"),O=r(async(e,t)=>{if(!e){let n=await fe();if(!n.trim())throw d(`Missing ${t}`);return S(n,t)}if(e==="-"){let n=await fe();if(!n.trim())throw d(`Missing ${t} on stdin`);return S(n,t)}return e.trim().startsWith("{")||e.trim().startsWith("[")?S(e,t):x(e,t)},"readJsonSource"),F=r(async(e,t="JSON")=>{let n=g(e,"--file");if(n)return x(n,t);let o=e.find(s=>s.trim().startsWith("{")||s.trim().startsWith("["));return O(o,t)},"readJsonInput"),he=r(async(e,t,n)=>{let o=g(e,t);if(o!==void 0)return O(o,n)},"readJsonFlag"),A=r(async(e,t,n)=>O(g(e,t),n),"readRequiredJsonFlag"),we=r(async(e,t,n)=>{let o=g(e,t);if(!o||o.startsWith("--"))throw d(`Missing ${n}`);return me(o,"utf-8")},"readTextFileFlag");var Ze=r((e,t)=>{let n={url:e},o=g(t,"--viewport"),s=g(t,"--headers"),i=g(t,"--wait-for-selector"),c=B(t,"--wait-timeout"),a=g(t,"--wait-until"),m=B(t,"--extra-wait-ms");return o&&(n.viewport=S(o,"--viewport")),s&&(n.headers=S(s,"--headers")),i&&(n.waitForSelector=i),c!==void 0&&(n.waitTimeout=c),a&&(n.waitUntil=a.trim().startsWith("[")?S(a,"--wait-until"):a),m!==void 0&&(n.extraWaitMs=m),h(t,"--block-annoyances")&&(n.blockAnnoyances=!0),h(t,"--dry-run")&&(n.dryRun=!0),n},"createEvidenceBody"),ke=r(async e=>{let[t,...n]=e;if(t==="list"){l(await u("/api/v1/pages/evidence-bundles"));return}if(t==="create"){let o=p(n[0],"Usage: kenobi-pages evidence create <url> [flags]");l(await u("/api/v1/pages/evidence-bundles",{method:"POST",body:Ze(o,n.slice(1))}));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages evidence get <bundleId>");l(await u(`/api/v1/pages/evidence-bundles/${o}`));return}throw d(`Unknown evidence command: ${e.join(" ")}`)},"handleEvidence");var Xe="kenobi.page",et=r(e=>(e??Xe).replace(/^https?:\/\//,"").replace(/\/+$/,"").toLowerCase(),"normalizeHostedDomain"),tt=r(()=>et(R("KENOBI_PAGES_HOSTED_DOMAIN")),"getHostedPagesDomain"),I=r(({siteSlug:e,templateSlug:t,itemSlug:n})=>`https://${e}.${tt()}/${t}/${n}`,"buildHostedPublicUrl"),ye=r((e,t)=>{if(typeof e!="object"||e===null)return e;let n=e,o=typeof n.siteSlug=="string"?n.siteSlug:t?.siteSlug,s=typeof n.templateSlug=="string"?n.templateSlug:t?.templateSlug,i=typeof n.itemSlug=="string"?n.itemSlug:t?.itemSlug;return!o||!s||!i?e:{...e,publicUrl:I({siteSlug:o,templateSlug:s,itemSlug:i})}},"maybeDecorateHostedContent"),Y=r((e,t)=>({...e,publicUrl:I(t)}),"decorateHostedContentResponse");var Se=r(async e=>{let t=f(e,"--template-slug","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),n=f(e,"--template-name","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),o=await we(e,"--source","--source <tsx-file>"),s=f(e,"--schema","Missing --schema <json-file>"),i=f(e,"--content","Missing --content <json-file>"),c=L(e,"--design-pack-id"),a=g(e,"--site-slug"),m=g(e,"--site-name"),k={templateSlug:t,templateName:n,sourceTsx:o,contentSchema:{title:n,schemaJson:await x(s,"--schema")},defaultContentJson:await x(i,"--content"),setCurrentDraft:!h(e,"--no-current-draft")};return c!==void 0&&(k.designPackId=c),a&&(k.site={slug:a,...m?{name:m}:{}}),k},"parseHostedDraftBody"),be=r(e=>{let t=typeof e.previewPath=="string"?e.previewPath:null;return{...e,...t?{previewUrl:`${b()}${t}`}:{}}},"withPreviewUrl"),nt=r(async e=>{let[t,...n]=e;if(t==="list"){l(await u("/api/v1/pages/hosted/sites"));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted site get <siteSlug>");l(await u(`/api/v1/pages/hosted/sites?${v({slug:o})}`));return}throw d(`Unknown hosted site command: ${e.join(" ")}`)},"handleHostedSite"),ot=r(async e=>{let[t,...n]=e;if(t==="list"){let o=v({full:h(n,"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates${o?`?${o}`:""}`));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted template get <templateIdOrSlug> [--full]"),s=v({full:h(n.slice(1),"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates/${o}${s?`?${s}`:""}`));return}throw d(`Unknown hosted template command: ${e.join(" ")}`)},"handleHostedTemplate"),st=r(async e=>{let[t,...n]=e;if(t==="list"){let o=p(n[0],"Usage: kenobi-pages hosted publication list <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${o}/publications`));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>"),s=p(n[1],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>");l(await u(`/api/v1/pages/hosted/templates/${o}/publications/${s}`));return}throw d(`Unknown hosted publication command: ${e.join(" ")}`)},"handleHostedPublication"),rt=r(async e=>{let[t,...n]=e;if(t==="list"){let o=f(n,"--site","Usage: kenobi-pages hosted content list --site <siteSlug> [--template <templateSlug>]"),s=g(n,"--template"),i=await u(`/api/v1/pages/hosted/instances?${v({siteSlug:o,templateSlug:s})}`);l({...i,instances:(i.instances??[]).map(c=>ye(c,{siteSlug:o,templateSlug:s}))});return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),s=p(n[1],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),c=await u(`/api/v1/pages/hosted/instances/${o}/${s}/${i}`);l(Y(c,{siteSlug:o,templateSlug:s,itemSlug:i}));return}if(t==="upsert"){let o=f(n,"--site","Usage: kenobi-pages hosted content upsert --site <siteSlug> --template <templateSlug> --item <itemSlug> --content <json|file|->"),s=f(n,"--template","Missing --template <templateSlug>"),i=f(n,"--item","Missing --item <itemSlug>"),c=L(n,"--publication-id"),a=await A(n,"--content","--content"),m=await u("/api/v1/pages/hosted/instances",{method:"POST",body:{siteSlug:o,templateSlug:s,itemSlug:i,contentJson:a,...c!==void 0?{publicationId:c}:{}}});l(Y(m,{siteSlug:o,templateSlug:s,itemSlug:i}));return}if(t==="verify"){let o=p(n[0],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),s=p(n[1],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),c=I({siteSlug:o,templateSlug:s,itemSlug:i});try{let a=await u(`/api/v1/pages/hosted/instances/${o}/${s}/${i}`);l({ok:!0,publicUrl:c,resolved:!0,contentValid:!0,publication:a.templatePublication??null})}catch(a){if(!(a instanceof y))throw a;let k=(typeof a.payload.details=="object"&&a.payload.details!==null&&"stage"in a.payload.details?a.payload.details.stage:null)==="invalid-content"?!1:null;l({ok:!1,publicUrl:c,resolved:a.payload.status!==404,contentValid:k,publication:null,error:a.payload}),process.exit(a.exitCode)}return}throw d(`Unknown hosted content command: ${e.join(" ")}`)},"handleHostedContent"),it=r(async e=>{let[t,...n]=e;if(t==="create"){let o=["--site-slug",f(n,"--site-slug","Missing --site-slug <siteSlug>"),...g(n,"--site-name")?["--site-name",g(n,"--site-name")]:[],"--template-slug",f(n,"--template-slug","Missing --template-slug <templateSlug>"),"--template-name",f(n,"--template-name","Missing --template-name <templateName>"),"--source",f(n,"--source","Missing --source <tsx-file>"),"--schema",f(n,"--schema","Missing --schema <json-file>"),"--content",f(n,"--content","Missing --content <json-file>"),...g(n,"--design-pack-id")?["--design-pack-id",g(n,"--design-pack-id")]:[],...h(n,"--no-current-draft")?["--no-current-draft"]:[]];l(be(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await Se(o)})));return}throw d(`Unknown hosted page command: ${e.join(" ")}`)},"handleHostedPage"),ve=r(async e=>{let[t,n,...o]=e;if(t==="site")return nt([n,...o].filter(Boolean));if(t==="template")return ot([n,...o].filter(Boolean));if(t==="publication")return st([n,...o].filter(Boolean));if(t==="content")return rt([n,...o].filter(Boolean));if(t==="page")return it([n,...o].filter(Boolean));if(t==="draft"&&n==="save"){l(be(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await Se(o)})));return}if(t==="publish"){let s=p(n,"Usage: kenobi-pages hosted publish <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${s}/publish`,{method:"POST"}));return}throw d(`Unknown hosted command: ${e.join(" ")}`)},"handleHosted");import{readFile as at}from"node:fs/promises";var ct=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),lt="hosted-pages",ut="Usage: kenobi-pages run <workflowIdOrSlug> [--dry-run] [--debug] [--params '<json>'|--params-file params.json] [--context <text>|--context-file notes.md]",dt=r(e=>new Promise(t=>setTimeout(t,e)),"sleep"),pt=r(e=>{console.error(JSON.stringify({event:"poll",taskStatus:e}))},"emitPollEvent"),gt=r(e=>{if(!e||typeof e!="object")return null;let n=e.deliveries;if(!Array.isArray(n))return null;for(let o of n){if(!o||typeof o!="object")continue;let s=o;if(s.adapter!==lt)continue;let i=s.metadata;if(!i||typeof i!="object")continue;let c=i,a=c.siteSlug,m=c.templateSlug,k=c.itemSlug;if(typeof a=="string"&&typeof m=="string"&&typeof k=="string")return`kenobi-pages hosted content verify ${a} ${m} ${k}`}return null},"extractHostedPagesVerifyCommand"),ft=r(e=>e==="COMPLETED"?"completed":e==="FAILED"||e==="CANCELED"||e==="SYSTEM_FAILURE"||e==="CRASHED"?"failed":e==="QUEUED"||e==="DELAYED"||e==="FROZEN"?"queued":"running","mapWorkflowRunStatusLegacy"),mt=r(e=>{if(typeof e.ok=="boolean")return{envelope:e,exitCode:e.ok?0:1};let t=typeof e.status=="string"?e.status:"UNKNOWN",n=ft(t),o=n==="completed",s=o&&e.output!==void 0&&e.output!==null?gt(e.output):null;return{envelope:{...e,ok:o,taskStatus:t,runStatus:n,nextCommand:s},exitCode:o?0:1}},"resolveRunTerminal"),ht=r(e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"message"in e){let t=e.message;if(typeof t=="string")return t}return"Unknown error"},"runStatusErrorMessage"),xe=r(async e=>{let t=p(e[0],ut),n=e.slice(1),o=g(n,"--params"),s=g(n,"--params-file"),i=g(n,"--context"),c=g(n,"--context-file"),a=h(n,"--dry-run"),m=h(n,"--debug");if(s?.startsWith("--"))throw d("Missing --params-file <path>");if(c?.startsWith("--"))throw d("Missing --context-file <path>");let k=s?await x(s,"--params-file"):o?S(o,"--params"):{},X=c?await at(c,"utf-8"):i,K={params:k};X&&(K.context=X),a&&(K.dryRun=!0);let D=await u(`/api/v1/cortex/workflows/${t}/run`,{method:"POST",body:K});if(a){l(D);return}let _=typeof D.runId=="string"?D.runId:void 0;if(!_)throw d("Run did not return a runId");console.error(JSON.stringify({event:"triggered",runId:_})),console.error(JSON.stringify({event:"polling_started"}));let J=2e3,Te=15e3;for(;;){await dt(J);let E=await u(`/api/v1/cortex/workflows/${t}/runs/${_}${m?"?debug=true":""}`),W=typeof E.taskStatus=="string"?E.taskStatus:typeof E.status=="string"?E.status:"UNKNOWN";if(pt(W),!ct.has(W)){J=Math.min(J*1.5,Te);continue}let{envelope:ee,exitCode:M}=mt(E);M!==0&&console.error(JSON.stringify({event:"terminal_failed",taskStatus:W,message:ht(ee.error)})),l(ee),M!==0&&process.exit(M);return}},"handleRun");var N=r((e,t)=>{let n=" ".repeat(t);switch(e.type){case"string":case"url":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return e.items?.type==="object"&&e.items.fields?`Array<{
|
|
11
11
|
${Object.entries(e.items.fields).map(([i,c])=>`${n} ${i}: ${N(c,t+2)}`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
${n} }>`:`${e.items?N(e.items,t):"unknown"}[]`;case"object":return e.fields?`{
|
|
14
14
|
${Object.entries(e.fields).map(([s,i])=>`${n} ${s}: ${N(i,t+1)}`).join(`
|
|
15
15
|
`)}
|
|
16
|
-
${n}}`:"Record<string, unknown>";default:return"unknown"}},"schemaTypeToTs"),
|
|
16
|
+
${n}}`:"Record<string, unknown>";default:return"unknown"}},"schemaTypeToTs"),wt=r(e=>`${e.replace(/[^a-zA-Z0-9\s]/g,"").split(/\s+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}Content`,"interfaceNameFromTitle"),kt=r(async e=>(await u(`/api/v1/cortex/workflows/${e}`)).id,"resolveWorkflowId"),yt=r(async e=>{let[t,...n]=e;if(t==="list"){l(await u("/api/v1/pages/self-hosted/schemas"));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages self-hosted schema get <workflowIdOrSlug>");l(await u(`/api/v1/pages/self-hosted/${o}/schema`));return}if(t==="codegen"){let o=p(n[0],"Usage: kenobi-pages self-hosted schema codegen <workflowIdOrSlug>"),s=await u(`/api/v1/pages/self-hosted/${o}/schema`),i=Object.entries(s.schema).map(([c,a])=>`${a.description?` /** ${a.description} */
|
|
17
17
|
`:""} ${c}: ${N(a,1)}`).join(`
|
|
18
|
-
`);console.log(`export interface ${
|
|
18
|
+
`);console.log(`export interface ${wt(s.title??"KenobiPage")} {
|
|
19
19
|
${i}
|
|
20
|
-
}`);return}if(t==="push"){let o=p(n[0],"Usage: kenobi-pages self-hosted schema push <name> '<json>'"),s=await F(n.slice(1),"schema");l(await u("/api/v1/pages/self-hosted/schemas",{method:"POST",body:{title:o,schemaJson:s}}));return}throw d(`Unknown self-hosted schema command: ${e.join(" ")}`)},"handleSchema"),
|
|
20
|
+
}`);return}if(t==="push"){let o=p(n[0],"Usage: kenobi-pages self-hosted schema push <name> '<json>'"),s=await F(n.slice(1),"schema");l(await u("/api/v1/pages/self-hosted/schemas",{method:"POST",body:{title:o,schemaJson:s}}));return}throw d(`Unknown self-hosted schema command: ${e.join(" ")}`)},"handleSchema"),St=r(async e=>{let[t,...n]=e;if(t==="list"){let o=p(n[0],"Usage: kenobi-pages self-hosted content list <workflowIdOrSlug>");l(await u(`/api/v1/pages/self-hosted/content-entries?${v({workflowId:o})}`));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages self-hosted content get <workflowIdOrSlug> <slug>"),s=p(n[1],"Usage: kenobi-pages self-hosted content get <workflowIdOrSlug> <slug>");l(await u(`/api/v1/pages/self-hosted/${o}/${s}`));return}if(t==="upsert"){let o=f(n,"--workflow","Missing --workflow <idOrSlug>"),s=f(n,"--source-key","Missing --source-key <sourceKey>"),i=f(n,"--slug","Missing --slug <slug>"),c=await A(n,"--content","--content"),a=await he(n,"--metadata","--metadata");l(await u("/api/v1/pages/self-hosted/content-entries",{method:"POST",body:{workflowId:await kt(o),slug:i,sourceKey:s,contentJson:c,...a!==void 0?{metadataJson:a}:{}}}));return}throw d(`Unknown self-hosted content command: ${e.join(" ")}`)},"handleContent"),$e=r(async e=>{let[t,n,...o]=e;if(t==="schema")return yt([n,...o].filter(Boolean));if(t==="content")return St([n,...o].filter(Boolean));throw d(`Unknown self-hosted command: ${e.join(" ")}`)},"handleSelfHosted");var Ie=r(async e=>{let[t,...n]=e;if(t===void 0||t==="list"){l(await u("/api/v1/cortex/sources"));return}if(t==="sample"){let o=p(n[0],"Usage: kenobi-pages sources sample <sourceKey>");l(await u(`/api/v1/cortex/sources/${encodeURIComponent(o)}/sample`));return}if(t==="schema"){let o=p(n[0],"Usage: kenobi-pages sources schema <sourceKey>"),i=(await u("/api/v1/cortex/sources")).sources.find(c=>c.sourceKey===o);if(!i)throw C(`Source not found: ${o}`);l({sourceKey:o,schema:i.schema??null});return}throw d(`Unknown sources command: ${e.join(" ")}`)},"handleSources");var bt=r(e=>{let t=e.resolution;return t?t.kind==="single"?"Use one record from this source.":t.kind==="lookup"?`Look up one record where ${t.field??"(missing field)"} equals runtime param ${t.param??"(missing param)"}.`:t.kind==="collection"?"Use this source as a collection.":`Unknown source resolution: ${t.kind??"(missing kind)"}.`:"Resolution is not configured."},"formatSourceResolution"),Ee=r((e,t)=>{let n=new Set;for(let o of Object.values(e.output?.fields??{}))o.binding?.strategy==="passthrough"&&o.binding.sourceId===t&&o.binding.sourceField&&n.add(o.binding.sourceField);for(let o of e.generationGroups??[])for(let s of o.contextSources??[])s.sourceId===t&&(s.fields?s.fields.forEach(i=>n.add(i)):Object.keys((e.sources??[]).find(i=>i.id===t)?.schema??{}).forEach(i=>n.add(i)));return[...n].sort((o,s)=>o.localeCompare(s))},"fieldsForSource"),Re=r((e,t)=>Object.entries(e.output?.fields??{}).filter(([,n])=>n.binding?.groupId===t).map(([n])=>n).sort((n,o)=>n.localeCompare(o)),"producedByGroup"),vt=r(e=>{let t=e.adapterConfig??{},n=typeof t.slugField=="string"?t.slugField:null;if(e.adapter==="hosted-pages"){let o=typeof t.siteSlug=="string"?t.siteSlug:null,s=typeof t.templateSlug=="string"?t.templateSlug:null;return{id:e.id,type:e.adapter,writes:o&&s&&n?I({siteSlug:o,templateSlug:s,itemSlug:`{${n}}`}):"Hosted page URL pattern is incomplete.",slugField:n}}return e.adapter==="self-hosted-pages"?{id:e.id,type:e.adapter,writes:n?`Self-hosted page content keyed by workflowId + {${n}}.`:"Self-hosted page slug field is not configured.",slugField:n}:{id:e.id,type:e.adapter??"unknown",writes:"Destination is not a Kenobi Pages destination.",slugField:n}},"destinationSummary"),xt=r(e=>{let t=[],n=new Set((e.params??[]).map(i=>i.name)),o=e.output?.fields??{},s=new Set;for(let[i,c]of Object.entries(o)){let a=c.binding;(!a||a.strategy==="unconfigured")&&t.push(`Output field "${i}" is unconfigured.`),a?.strategy==="param"&&a.paramName&&!n.has(a.paramName)&&t.push(`Output field "${i}" references missing param "${a.paramName}".`),(a?.strategy==="generate"||a?.strategy==="generate-image")&&s.add(i)}for(let i of e.sources??[])i.resolution?.kind==="lookup"&&i.resolution.param&&(n.has(i.resolution.param)||t.push(`Source "${i.id}" lookup references missing param "${i.resolution.param}".`));for(let i of e.generationGroups??[])Re(e,i.id).length===0&&t.push(`Generation group "${i.id}" does not produce any output fields.`);for(let i of e.destinations??[]){let c=i.adapterConfig??{},a=typeof c.slugField=="string"?c.slugField:null;if(!a){t.push(`Destination "${i.id}" is missing adapterConfig.slugField.`);continue}o[a]?o[a].type!=="string"&&t.push(`Destination "${i.id}" slugField "${a}" is not a string field.`):t.push(`Destination "${i.id}" slugField "${a}" is not in output.fields.`)}return t},"collectWarnings"),Ue=r(e=>({summary:e.description??e.output?.title??e.id??"Kenobi workflow",inputs:(e.params??[]).map(t=>({name:t.name,description:t.description??null})),sources:(e.sources??[]).map(t=>({id:t.id,title:t.title??t.id,provider:t.provider??null,sourceKey:t.dataSourceKey??null,resolution:bt(t),fieldsUsed:Ee(e,t.id)})),generation:(e.generationGroups??[]).map(t=>({group:t.id,strategy:t.strategy??null,uses:(t.contextSources??[]).map(n=>({sourceId:n.sourceId,fields:n.fields??Ee(e,n.sourceId)})),produces:Re(e,t.id)})),output:{dataSourceKey:e.output?.dataSourceKey??null,title:e.output?.title??null,fields:Object.keys(e.output?.fields??{})},destinations:(e.destinations??[]).map(vt),warnings:xt(e)}),"explainWorkflow");var Oe=r((e,t)=>Object.fromEntries(Object.entries(e).map(([n,o])=>[n,{...o,binding:n===t?{strategy:"param",paramName:t}:{strategy:"unconfigured"}}])),"asUnconfiguredOutputFields"),Fe=r((e,t)=>({...e,[t]:{type:"string",description:"URL slug for the generated page.",...e[t]}}),"ensureSlugField"),$t=r(e=>e.split(":").pop()?.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()||"pages-workflow","slugFromSourceKey"),z=r(async e=>{let t=g(e,"--config");if(t!==void 0){if(t.startsWith("--"))throw d("Missing --config '<json>'");return O(t,"workflow config")}return F(e,"workflow config")},"readWorkflowConfig"),It=r(async e=>{let t=f(e,"--template-publication","Usage: kenobi-pages workflow scaffold hosted --template-publication <templateId:publicationId> --site <siteSlug> --template <templateSlug> --slug-field <field>"),[n,o]=t.split(":");if(!n||!o)throw d("--template-publication must be <templateId:publicationId>");let s=f(e,"--site","Missing --site <siteSlug>"),i=f(e,"--template","Missing --template <templateSlug>"),c=f(e,"--slug-field","Missing --slug-field <field>"),m=(await u(`/api/v1/pages/hosted/templates/${n}/publications/${o}`)).cortexOutputFieldSpecs??{},k=Oe(Fe(m,c),c);l({id:`${s}-${i}`,params:[{name:c,description:"Public hosted page item slug."}],sources:[],output:{dataSourceKey:`hosted-pages:${i}`,title:`${i} hosted page`,fields:k},generationGroups:[],destinations:[{id:"hosted-pages",adapter:"hosted-pages",adapterConfig:{siteSlug:s,templateSlug:i,slugField:c,publicationId:Number(o)}}]})},"scaffoldHosted"),Et=r(async e=>{let t=f(e,"--source-key","Usage: kenobi-pages workflow scaffold self-hosted --source-key <sourceKey> --slug-field <field>"),n=f(e,"--slug-field","Missing --slug-field <field>"),s=(await u("/api/v1/cortex/sources")).sources.find(a=>a.sourceKey===t);if(!s)throw C(`Source not found: ${t}`);let i=Oe(Fe(s.schema??{},n),n),c=$t(t);l({id:c,params:[{name:n,description:"URL slug for the generated page."}],sources:[],output:{dataSourceKey:t,title:s.sourceTitle??c,fields:i},generationGroups:[],destinations:[{id:"self-hosted-pages",adapter:"self-hosted-pages",adapterConfig:{slugField:n}}]})},"scaffoldSelfHosted"),Rt=r(async e=>{let[t,...n]=e;if(t==="hosted")return It(n);if(t==="self-hosted")return Et(n);throw d(`Unknown workflow scaffold command: ${e.join(" ")}`)},"handleScaffold"),Q=r(async e=>{let[t,...n]=e;if(t===void 0||t==="list"){l(await u("/api/v1/cortex/workflows"));return}if(t==="create"){let o=f(n,"--name","Missing --name <name>"),s=f(n,"--slug","Missing --slug <slug>"),i=g(n,"--description"),c=h(n,"--dry-run"),a={name:o,slug:s,config:await z(n)};i&&(a.description=i),c&&(a.dryRun=!0),l(await u("/api/v1/cortex/workflows",{method:"POST",body:a}));return}if(t==="validate"){let o=f(n,"--name","Missing --name <name>"),s=f(n,"--slug","Missing --slug <slug>"),i=g(n,"--description"),c={name:o,slug:s,config:await z(n)};i&&(c.description=i),l(await u("/api/v1/cortex/workflows/validate",{method:"POST",body:c}));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages workflow get <workflowIdOrSlug>");l(await u(`/api/v1/cortex/workflows/${o}?full=true`));return}if(t==="update"){let o=p(n[0],"Usage: kenobi-pages workflow update <workflowIdOrSlug> [flags]"),s=n.slice(1),i={},c=h(s,"--dry-run"),a=g(s,"--name"),m=g(s,"--description");if(a&&(i.name=a),m!==void 0&&(i.description=m),(s.includes("--config")||s.includes("--file"))&&(i.config=await z(s)),c&&(i.dryRun=!0),Object.keys(i).length===(c?1:0))throw d("Nothing to update");l(await u(`/api/v1/cortex/workflows/${o}`,{method:"PUT",body:i}));return}if(t==="delete"){let o=p(n[0],"Usage: kenobi-pages workflow delete <workflowIdOrSlug>");l(await u(`/api/v1/cortex/workflows/${o}`,{method:"DELETE"}));return}if(t==="explain"){let o=await F(n,"workflow config");l(Ue(o));return}if(t==="scaffold")return Rt(n);throw d(`Unknown workflow command: ${e.join(" ")}`)},"handleWorkflows");var Ut=`kenobi-pages - Kenobi Pages CLI
|
|
21
21
|
|
|
22
22
|
Commands:
|
|
23
23
|
doctor
|
|
@@ -92,4 +92,4 @@ Output:
|
|
|
92
92
|
Environment:
|
|
93
93
|
KENOBI_PAGES_KEY Org public key. Set via init or in your env file.
|
|
94
94
|
KENOBI_BASE_URL Optional API base URL override.
|
|
95
|
-
`,Z=r(()=>{console.log(Ut)},"printHelp");import{resolve as P}from"node:path";import{createInterface as Ot}from"node:readline";var T=r(e=>new Promise(t=>{let n=Ot({input:process.stdin,output:process.stderr});n.question(e,o=>{n.close(),t(o.trim())})}),"prompt"),Ft=r(async e=>e.startsWith("pk_live_")||e.startsWith("pk_test_")?!0:(console.error(` Warning: "${e}" does not look like a Kenobi key (expected pk_live_... or pk_test_...).`),(await T(" Continue anyway? (y/N): ")).toLowerCase()==="y"),"validateKey"),Pt=r(()=>U()[0]??".env.local","defaultEnvFile"),Tt=r(e=>{let t=g(e,"--key");if(!t||t.startsWith("--"))throw d("Usage: kenobi-pages init --key <key> [--env-file <path>] [--base-url <url>]");let n=g(e,"--env-file")??Pt(),o=g(e,"--base-url"),s=P(process.cwd(),n);q(s,
|
|
95
|
+
`,Z=r(()=>{console.log(Ut)},"printHelp");import{resolve as P}from"node:path";import{createInterface as Ot}from"node:readline";var T=r(e=>new Promise(t=>{let n=Ot({input:process.stdin,output:process.stderr});n.question(e,o=>{n.close(),t(o.trim())})}),"prompt"),Ft=r(async e=>e.startsWith("pk_live_")||e.startsWith("pk_test_")?!0:(console.error(` Warning: "${e}" does not look like a Kenobi key (expected pk_live_... or pk_test_...).`),(await T(" Continue anyway? (y/N): ")).toLowerCase()==="y"),"validateKey"),Pt=r(()=>U()[0]??".env.local","defaultEnvFile"),Tt=r(e=>{let t=g(e,"--key");if(!t||t.startsWith("--"))throw d("Usage: kenobi-pages init --key <key> [--env-file <path>] [--base-url <url>]");let n=g(e,"--env-file")??Pt(),o=g(e,"--base-url"),s=P(process.cwd(),n);q(s,w,t),o&&!o.startsWith("--")&&q(s,"KENOBI_BASE_URL",o),l({ok:!0,envFile:n,wrote:{[w]:!0,KENOBI_BASE_URL:!!(o&&!o.startsWith("--"))}})},"nonInteractiveInit"),Pe=r(async(e=[])=>{if(g(e,"--key")!==void 0){Tt(e);return}console.error(""),console.error(" Kenobi Pages - Setup"),console.error(""),console.error(" Find your API key at: https://kenobi.ai/setup"),console.error("");let t=await T(" Paste your API key (pk_live_... or pk_test_...): ");t||(console.error(" No key provided. Aborting."),process.exit(1)),await Ft(t)||(console.error(" Aborting."),process.exit(1));let n=U();if(n.length>0){console.error(""),console.error(" Found env files in this project:"),n.forEach((i,c)=>console.error(` ${c+1}. ${i}`)),console.error(` ${n.length+1}. Create a new file`),console.error(` ${n.length+2}. Skip`),console.error("");let o=await T(` Which file should ${w} be added to? [1]: `),s=o===""?0:parseInt(o,10)-1;if(s===n.length){let i=await T(" Filename (e.g. .env.local): ");i&&(j(P(process.cwd(),i),w,t),console.error(` Created ${i} with ${w}`))}else s>=0&&s<n.length&&ce(P(process.cwd(),n[s]),w,t)}else{console.error("");let o=await T(" No env files found. Create one? (filename or 'n' to skip) [.env.local]: ");o.toLowerCase()!=="n"&&o!==""?(j(P(process.cwd(),o),w,t),console.error(` Created ${o} with ${w}`)):o===""&&(j(P(process.cwd(),".env.local"),w,t),console.error(` Created .env.local with ${w}`))}console.error(""),console.error(" Done. Your agent can now use kenobi-pages commands."),console.error(" Run 'npx kenobi-pages --help' to see what is available."),console.error("")},"initCommand");var Ct=r(async e=>{if(e.length===0||e[0]==="--help"||e[0]==="-h"){Z();return}let[t,...n]=e;if(n.includes("--help")||n.includes("-h")){Z();return}if(t==="init")return Pe(n);if(t==="doctor")return ge();if(t==="evidence")return ke(n);if(t==="design-pack")return ue(n);if(t==="hosted")return ve(n);if(t==="self-hosted")return $e(n);if(t==="sources")return Ie(n);if(t==="workflows")return Q(["list",...n]);if(t==="workflow")return Q(n);if(t==="run")return xe(n);throw d(`Unknown command: ${e.join(" ")}`)},"main");Ct(process.argv.slice(2)).catch(ne);
|