@turbobase/cli 1.34.0 → 1.34.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3860,7 +3860,7 @@ ${o.map(ZP).join(`
3860
3860
  `))}async function uw(t,e,r=_o){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await vo(e,r);if(!await _a(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await se("publishing",()=>o.skillsPublish(n))}catch(a){te(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}_(f.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(f.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function dw(t,e,r=_o){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await vo(e,r);if(!await _a(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await se("unpublishing",()=>o.skillsUnpublish(n))}catch(a){te(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}_(f.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(f.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function pw(t,e,r=_o){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await vo(e,r);if(await _a(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await se("rolling back",()=>o.skillsRollback(n));_(f.green(`rolled back to v${i.version.version_no}.`))}catch(i){te(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function hw(t,e=_o){let r=await vo(t,e),n;try{n=await se("reading the releases",()=>r.skillsReleases())}catch(o){te(o,"skills:publish","read the skills releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){q("no releases yet.");return}for(let o of n.items){let s=o.is_current?f.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";_(`${s} v${o.version_no} ${o.skill_count} skill(s) ${f.dim(o.published_at)}${o.published_by?f.dim(` by ${o.published_by}`):""}${f.dim(i)}`)}}async function mw(t,e,r=_o){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await vo(e,r);if(!await _a(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3861
3861
  ${n.join(`
3862
3862
  `)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let l of n)try{i.push(await se(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof le&&u.status===404){a.push(l);continue}i.length>0&&q(f.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),te(u,"skills:publish","delete a skill"),v(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&_(f.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(f.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(f.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as fw}from"node:fs";import{join as CA,relative as IA,resolve as OA,sep as NA}from"node:path";var zA=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),LA=new Set([".mcp.json",".env"]);function jA(t){return LA.has(t)||t.startsWith(".env.")&&t!==".env.example"}function DA(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function MA(t){return t.includes(0)}async function gw(t){let e=OA(t),r={},n=[],o=[],s=[];async function i(a){let c=await fw.readdir(a,{withFileTypes:!0});for(let l of c){let u=CA(a,l.name);if(zA.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=IA(e,u).split(NA).join("/");if(jA(l.name)){o.push(p);continue}let b=await fw.readFile(u);if(!DA(b)){n.push(p);continue}MA(b)&&s.push(p),r[p]=b.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as UA}from"node:crypto";var qA="/_tb/app-assets",BA=16,FA=/^[0-9a-f]{32}$/;function yw(){return UA(BA).toString("hex")}function ZA(t){return FA.test(t)}function bw(t){if(!ZA(t))throw new Error(`not a build id: ${t}`);return`${qA}/${t}/`}var ww=7;zu();var Lu=50*1024*1024;import va from"node:fs/promises";import _s from"node:path";var ju={esbuild:"0.28.1","isolated-vm":"6.1.2"},Du="@turbobase/isolated-vm-prebuilds";function Mu(t,e){return`${t}-${e}`}function Uu(t=process.versions){return`abi${t.modules}`}var _w=["darwin-x64","win32-arm64"];async function vw(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Mu(e,r),o=_s.join(t.home,"node_modules"),s=_s.join(o,...Du.split("/"),"prebuilds",n),i=_s.join(o,"isolated-vm","prebuilds",n),a;try{a=await va.readdir(s)}catch{return[]}let c=[];await va.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=_s.join(i,l);try{await va.copyFile(_s.join(s,l),u,va.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as VA}from"node:os";import{join as xw}from"node:path";import{promises as qu}from"node:fs";function Sw(){let t=process.env.TURBOBASE_HOME??xw(VA(),".turbobase");return{dir:t,file:xw(t,"sandboxes.json")}}var HA={s:1e3,m:6e4,h:36e5,d:864e5};function KA(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*HA[e[2]]}function WA(t,e=Date.now()){return new Date(e+KA(t)).toISOString()}function GA(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function JA(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function YA(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var XA="[REDACTED]",vs=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Bu=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function QA(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Bu(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:XA:n[o]=s}return n}function eC(t,e,r){return e.map(n=>QA(t,n,r))}var kw=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),tC=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function rC(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Fu(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of tC)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=rC(t);if(!kw.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...kw].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function nC(t,e=oC){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function oC(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function sC(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function iC(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Zu(){let{file:t}=Sw();try{let e=await qu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function $w(t){let{dir:e,file:r}=Sw();await qu.mkdir(e,{recursive:!0}),await qu.writeFile(r,`${JSON.stringify(t,null,2)}
3863
- `,{mode:384})}async function aC(t){let e=await Zu();e.push(t),await $w(e)}async function Tw(t){let e=await Zu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await $w(e),n??null}async function xa(){return Zu()}function Vu(t,e=Date.now()){let r=[],n=[];for(let o of t)GA(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Rw(t,e){Fu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new vs(r);let n=JA(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>nC(l)))(e.fromTenant),i=sC(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=YA(l.rows,n),p=eC(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:WA(e.ttl,o),sampleFraction:n,url:iC(s,e.baseUrl)};return await aC(c),c}async function Ew(t,e){Fu(t.target());let n=(await xa()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Tw(e),n):null}async function Hu(t,e=Date.now()){Fu(t.target());let r=await xa(),{expired:n}=Vu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Tw(s.name),o.push(s)}return o}var xs={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},k2=Object.keys(xs).filter(t=>xs[t].mintable);var T2=xs.pat.prefix,cC=Object.entries(xs).map(([t,e])=>[e.prefix,t]),lC=/^[A-Za-z0-9_-]{20,}$/;function uC(t){if(typeof t!="string")return null;for(let[e,r]of cC)if(t.startsWith(e)&&lC.test(t.slice(e.length)))return r;return null}function Pw(t){return uC(t)==="pat"}cs();var dC=8e3,pC={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function hC(t){return pC[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function mC(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(dC)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Aw(t){return t.state==="accepted"?nt()?f.green("accepted"):"accepted":t.state==="rejected"?nt()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:nt()?f.yellow("unreachable"):"unreachable"}async function Cw(t={},e=fetch){let r=await Ar(),{file:n}=Gi();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(f.dim(`no sign-ins stored in ${n}.`));return}let o=await Qt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await mC(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(nt())_(tr(s.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),Aw(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Aw(i.check)} (updated ${i.updatedAt})`);q(f.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(f.red(`${i.baseUrl}: ${hC(i.check.reason)}.`)),q(f.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function FU(t){let e=await Ar();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function ZU(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function VU(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function HU(t,e,r){let n=await gy({baseUrl:t,token:e}),o=(await Ar()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),VU(n.baseUrl),!r)return;let s=await ZU(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function KU(t){let e=await uu(await ps(t),Mr(t)),r=Su(e);return r||v(`${t}: ${$u(e)}`),{...r,sourceCode:e}}async function eo(t,e,r,n){try{return await _e.access(t),"skipped"}catch{}return await _e.mkdir(Mr(t),{recursive:!0}),await _e.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await _e.chmod(t,n),"wrote"}async function PT(t,e){if(CT(t)!==".gitignore")return eo(t,e.content,e.executable,e.mode);let r=await _e.readFile(t,"utf8").catch(()=>null);if(r===null)return eo(t,e.content,e.executable,e.mode);let n=gb(r);return n===null?"skipped":(await _e.writeFile(t,n,"utf8"),"merged")}function cg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function gl(t){process.exit(t)}function WU(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function GU(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function JU(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function AT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function mg({includeInternal:t=!0}={}){let e=new Og;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.34.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${yu()}
3863
+ `,{mode:384})}async function aC(t){let e=await Zu();e.push(t),await $w(e)}async function Tw(t){let e=await Zu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await $w(e),n??null}async function xa(){return Zu()}function Vu(t,e=Date.now()){let r=[],n=[];for(let o of t)GA(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Rw(t,e){Fu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new vs(r);let n=JA(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>nC(l)))(e.fromTenant),i=sC(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=YA(l.rows,n),p=eC(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:WA(e.ttl,o),sampleFraction:n,url:iC(s,e.baseUrl)};return await aC(c),c}async function Ew(t,e){Fu(t.target());let n=(await xa()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Tw(e),n):null}async function Hu(t,e=Date.now()){Fu(t.target());let r=await xa(),{expired:n}=Vu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Tw(s.name),o.push(s)}return o}var xs={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},k2=Object.keys(xs).filter(t=>xs[t].mintable);var T2=xs.pat.prefix,cC=Object.entries(xs).map(([t,e])=>[e.prefix,t]),lC=/^[A-Za-z0-9_-]{20,}$/;function uC(t){if(typeof t!="string")return null;for(let[e,r]of cC)if(t.startsWith(e)&&lC.test(t.slice(e.length)))return r;return null}function Pw(t){return uC(t)==="pat"}cs();var dC=8e3,pC={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function hC(t){return pC[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function mC(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(dC)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Aw(t){return t.state==="accepted"?nt()?f.green("accepted"):"accepted":t.state==="rejected"?nt()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:nt()?f.yellow("unreachable"):"unreachable"}async function Cw(t={},e=fetch){let r=await Ar(),{file:n}=Gi();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(f.dim(`no sign-ins stored in ${n}.`));return}let o=await Qt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await mC(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(nt())_(tr(s.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),Aw(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Aw(i.check)} (updated ${i.updatedAt})`);q(f.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(f.red(`${i.baseUrl}: ${hC(i.check.reason)}.`)),q(f.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function FU(t){let e=await Ar();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function ZU(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function VU(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function HU(t,e,r){let n=await gy({baseUrl:t,token:e}),o=(await Ar()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),VU(n.baseUrl),!r)return;let s=await ZU(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function KU(t){let e=await uu(await ps(t),Mr(t)),r=Su(e);return r||v(`${t}: ${$u(e)}`),{...r,sourceCode:e}}async function eo(t,e,r,n){try{return await _e.access(t),"skipped"}catch{}return await _e.mkdir(Mr(t),{recursive:!0}),await _e.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await _e.chmod(t,n),"wrote"}async function PT(t,e){if(CT(t)!==".gitignore")return eo(t,e.content,e.executable,e.mode);let r=await _e.readFile(t,"utf8").catch(()=>null);if(r===null)return eo(t,e.content,e.executable,e.mode);let n=gb(r);return n===null?"skipped":(await _e.writeFile(t,n,"utf8"),"merged")}function cg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function gl(t){process.exit(t)}function WU(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function GU(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function JU(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function AT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function mg({includeInternal:t=!0}={}){let e=new Og;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.34.2").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${yu()}
3864
3864
  `),e.hook("preAction",(d,g)=>{Pb(e.opts(),g.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let g=Mt(d.baseUrl);d.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3865
3865
  ${ys} auth login --base-url ${g} --token tb_pat_\u2026`),Pw(d.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await HU(g,d.token,d.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async d=>Cw({probe:d.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let g=d??await FU("Pick the active instance:"),x=await Ji(g);if(!x){let T=await Ar();v(`no stored sign-in for ${Mt(g)}.`+(T.length?` Stored: ${T.map(k=>k.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Mt(g)} --token tb_pat_\u2026\`.`)}_(`active instance \u2192 ${x.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let T=await Ar();for(let k of T)await ou(k.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let g=await ou(d.baseUrl);g||v(d.baseUrl?`no stored sign-in for ${Mt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let x=await Qt();_(`signed out of ${g}.`+(x?` Active instance \u2192 ${x.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:g,token:x}=await Q(d.baseUrl),T;try{T=await On({baseUrl:g,token:x,recordsOnly:d.recordsOnly})}catch(y){let $=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test($)){q("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await On({baseUrl:g,token:x,recordsOnly:!0})}catch(E){v(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else v(`types generation failed: ${$}`)}let k=ye(process.cwd(),d.out);await _e.writeFile(k,T,"utf8"),_(`wrote ${k} (${T.split(`
3866
3866
  `).length} lines).`)}),Ib(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:g,token:x}=await Q(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let k=T.toString(),y=await fetch(`${g}/v1/catalog/grounding${k?`?${k}`:""}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"}});y.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let E=((await y.json()).markdown??"").trim(),N=ye(process.cwd(),d.out),L=d.records?` records=${d.records}`:"",M=`<!-- GENERATED by \`turbobase project grounding\` against ${g}${L} \u2014 do not edit; re-run to refresh. -->
@@ -3890,7 +3890,7 @@ samples init: ${E} written, ${N} skipped.`)});let dr=e.command("guardrails").des
3890
3890
  `+f.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(tr(k.map(bl),{head:IT})),_(f.dim(" first match wins; lower PRIO is evaluated first."))}),dr.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await k.guardrailCreate({name:d,source:g.source,record:g.record,decision:g.decision,...g.op?{op:g.op}:{},...g.target?{target:g.target}:{},...g.actor?{actor:g.actor}:{},...Number.isFinite(g.priority)?{priority:Number(g.priority)}:{},...g.when?{when:g.when}:{},...g.reason?{reason:g.reason}:{},...g.disabled?{enabled:!1}:{},...g.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch($){te($,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${$ instanceof Error?$.message:String($)}`)}_(`${f.green("\u2713")} guardrail ${f.bold(y.name??y.id)} created${y.status==="active"?"":f.dim(` (${y.status} \u2014 activate it to take effect)`)}`),_(f.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),_(f.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),dr.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,g)=>{g.decision===void 0&&g.priority===void 0&&g.when===void 0&&g.reason===void 0&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await k.guardrailUpdate(d,{...g.decision!==void 0?{decision:g.decision}:{},...Number.isFinite(g.priority)?{priority:Number(g.priority)}:{},...g.when!==void 0?{when:g.when}:{},...g.reason!==void 0?{reason:g.reason}:{}})}catch($){te($,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${$ instanceof Error?$.message:String($)}`)}_(`${f.green("\u2713")} guardrail ${f.bold(y.name??y.id)} updated`),_(f.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,g,x]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])dr.command(`${d} <name>`).description(g==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(T,k)=>{let{baseUrl:y,token:$}=await Q(k.baseUrl),E=new G({baseUrl:y,token:$});try{await E.guardrailUpdate(T,{status:g})}catch(N){te(N,"extensions:deploy",`${d} a guardrail`),v(`${d} guardrail failed: ${N instanceof Error?N.message:String(N)}`)}_(`${f.green("\u2713")} guardrail ${f.bold(T)} ${x}`),g==="inactive"&&_(f.dim(" writes it was gating now fall through to the other rules."))});dr.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T});try{await k.guardrailDelete(d)}catch(y){te(y,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${f.green("\u2713")} guardrail ${f.bold(d)} deleted`)}),dr.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y=N=>N==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let N;try{N=await k.guardrailPostureGet()}catch(L){te(L,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${L instanceof Error?L.message:String(L)}`)}_(`guardrail posture: ${f.bold(y(N.mode))}`),_(f.dim(N.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let $=d.trim().toLowerCase();$!=="allow"&&$!=="deny"&&v("posture must be 'allow' or 'deny'.");let E;try{E=await k.guardrailPostureSet($)}catch(N){te(N,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${N instanceof Error?N.message:String(N)}`)}_(`${f.green("\u2713")} guardrail posture set to ${f.bold(y(E.mode))}`),E.mode==="deny"&&_(f.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),dr.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let g;if(d.fields)try{g=JSON.parse(d.fields)}catch(E){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:x,token:T}=await Q(d.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await k.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...g?{fields:g}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){te(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return _(JSON.stringify(y,null,2));let $=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${f.red("\u2717")} ${$} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(f.dim(` ${y.reason}`))):y.allowed?_(`${f.green("\u2713")} ${$} \u2014 ${y.decision}`+(y.blockedBy?f.dim(` (rule ${y.blockedBy})`):f.dim(" (no rule matched)"))):(_(`${f.red("\u2717")} ${$} \u2014 ${y.decision} by ${f.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&_(f.dim(` ${y.message}`))),y.decision==="require_confirm"&&_(f.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let Xo=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Ei=(d,g={})=>{let x=`${f.bold(d.table)} ${f.dim(d.displayName)}`;_(d.exists===!1?`${x} ${f.dim("(new)")}`:x);for(let T of d.fields){let k=[T.required?"required":null].filter(Boolean).join(", "),y=g.showClaimants&&T.claimedBy?.length?` ${f.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${k?` (${k})`:""}${y}`)}g.showClaimants&&d.claimants.length>1&&_(f.dim(` claimed by ${d.claimants.join(", ")}`))};function Pi(d){if(d instanceof le&&d.status===409){let g=d.body;g?.error==="table_conflict"&&g.message&&(q(g.message),process.exit(1))}v(`tables: ${d instanceof Error?d.message:String(d)}`)}let fg=async d=>{let g=Ot(ye(process.cwd(),d),"public","turbobase.json"),x=await _e.readFile(g,"utf8").catch(()=>null);if(x===null)return null;let T;try{T=JSON.parse(x)}catch(y){v(`${g} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let k=T.tables;return k===void 0?{tables:[],manifestPath:g}:(Array.isArray(k)||v(`${g}: "tables" must be an array.`),{tables:k,manifestPath:g})};Xo.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x}),k;try{k=await T.tablesList()}catch(y){te(y,"extensions:deploy","list tables"),v(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(k,null,2));if(k.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(tr(k.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Xo.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,g)=>{let x=await fg(d??".");if(x||v(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`),x.tables.length===0)return _(`${x.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:k}=await Q(g.baseUrl),y=new G({baseUrl:T,token:k}),$;try{$=await se("planning tables",()=>y.tablesPlan({claimedBy:g.as,tables:x.tables}))}catch(E){te(E,"extensions:deploy","plan tables"),Pi(E)}_(`claiming as ${f.bold($.claimedBy)}`);for(let E of $.tables)Ei(E,{showClaimants:!0});_(""),_(f.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Xo.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,g)=>{let x=await fg(d??".");if(x||v(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`),x.tables.length===0)return _(`${x.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:k}=await Q(g.baseUrl),y=new G({baseUrl:T,token:k}),$;try{$=await se("applying tables",()=>y.tablesApply({claimedBy:g.as,tables:x.tables}))}catch(E){te(E,"extensions:deploy","apply tables"),Pi(E)}for(let E of $.tables)Ei(E,{showClaimants:!0});_(`applied ${$.tables.length} table${$.tables.length===1?"":"s"} as ${$.claimedBy}.`)}),Xo.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,g)=>[...g??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,g)=>{let x=g.field.map(E=>{let[N,L,M]=E.split(":");return(!N||!L)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:N,type:L,...M==="required"?{required:!0}:{}}}),{baseUrl:T,token:k}=await Q(g.baseUrl),y=new G({baseUrl:T,token:k}),$;try{$=await se(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:g.name??d,fields:x,...g.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){te(E,"extensions:deploy","create a table"),Pi(E)}for(let E of $.tables)Ei(E);_(""),_(f.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Xo.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,g)=>{g.confirm!==d&&v(`drop refused: --confirm "${g.confirm}" does not match "${d}".`);let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await se(`dropping cr_${d}`,()=>k.tablesDrop(d,g.confirm))}catch($){te($,"extensions:deploy","drop a table"),v(`drop failed: ${$ instanceof Error?$.message:String($)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let wl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");wl.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let g=ug(),x;try{x=await Rw(g,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof vs&&v(T.message),v(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}_(`sandbox ${x.name} ready.`),_(` source: ${x.fromTenant} (sampled ${Math.round(x.sampleFraction*100)}%, redacted)`),_(` url: ${x.url}`),_(` expires: ${x.expiresAt}`)}),wl.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let g=ug();await Hu(g).catch(()=>[]);let x;try{x=await Ew(g,d)}catch(T){v(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}x||v(`no sandbox named '${d}'.`),_(`destroyed sandbox ${x.name} (dropped ${x.database}).`)}),wl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=ug(),g=await Hu(d).catch(()=>[]),x=await xa(),{active:T}=Vu(x);if(T.length===0)_("no active sandboxes.");else{for(let k of T)_(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);_(`
3891
3891
  ${T.length} active sandbox(es).`)}g.length>0&&_(`(reaped ${g.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",da).action(async d=>{let{baseUrl:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x}),k;try{k=await se("exporting instance config",()=>T.configExport())}catch(E){E instanceof le&&(E.status===401||E.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let y=typeof k.serialized=="string"?k.serialized:`${JSON.stringify(k.manifest??k,null,2)}
3892
3892
  `,$=ye(process.cwd(),d.out,fs);await _e.mkdir(Mr($),{recursive:!0}),await _e.writeFile($,y,"utf8"),_(`wrote ${d.out}/${fs} (${y.split(`
3893
- `).length} lines).`)});let gg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),OT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],yg=()=>process.env.TURBOBASE_HOME?.trim()||Ot(BU(),".turbobase"),NT=()=>"1.34.0",Ai=async()=>Promise.all(OT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));gg.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ai();for(let g of d)_(`${g.present?ze.success("installed"):ze.warn("missing")} ${f.bold(g.name)} \u2014 ${g.needs}`);d.some(g=>!g.present)&&_(`
3893
+ `).length} lines).`)});let gg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),OT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],yg=()=>process.env.TURBOBASE_HOME?.trim()||Ot(BU(),".turbobase"),NT=()=>"1.34.2",Ai=async()=>Promise.all(OT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));gg.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ai();for(let g of d)_(`${g.present?ze.success("installed"):ze.warn("missing")} ${f.bold(g.name)} \u2014 ${g.needs}`);d.some(g=>!g.present)&&_(`
3894
3894
  run \`${ys} ext extras install\` to fetch them into ${yg()}.`)}),gg.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ai();if(d.every(N=>N.present)){_(ze.success("extras already installed \u2014 nothing to do."));return}let g=yg();await _e.mkdir(g,{recursive:!0});let x=d.filter(N=>!N.present).map(N=>N.name),T=Mu(process.platform,process.arch),k=async(N,L)=>{let{code:M,stderr:re}=await Ri("npm",["install","--prefix",g,"--no-audit","--no-fund",...N]);M!==0&&v(`extras install failed while installing ${L} (npm exited ${M}).
3895
3895
  ${re.trim()}
3896
3896
  These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=x.filter(N=>N!=="isolated-vm");if(y.length>0){let N=y.map(L=>`${L}@${ju[L]??"latest"}`);_(`installing ${N.join(", ")} \u2192 ${g}/node_modules \u2026`),await k(N,y.join(", "))}if(x.includes("isolated-vm")){let N=`isolated-vm@${ju["isolated-vm"]}`;if(_(`installing ${N} \u2192 ${g}/node_modules \u2026`),await k(["--ignore-scripts",N],"isolated-vm"),_w.includes(T)){let M=`${Du}@${NT()}`;_(`fetching ${M} (no upstream binary for ${T}) \u2026`);let{code:re}=await Ri("npm",["install","--prefix",g,"--no-audit","--no-fund","--ignore-scripts",M]);re!==0&&_(ze.warn(`could not fetch ${M} \u2014 falling back to a source build.`))}let L=await vw({home:g});L.length>0&&_(` ${ze.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let $=await Ai(),E=$.filter(N=>!N.present).map(N=>N.name);if(E.includes("isolated-vm")){_(ze.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${Uu()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:N}=await Ri("npm",["rebuild","--prefix",g,"isolated-vm"]);N===0&&($=await Ai(),E=$.filter(L=>!L.present).map(L=>L.name))}E.length>0&&v(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${Uu()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(ze.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let to=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return to.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let g=d.target==="approved"?"approved":d.target==="auto"?"auto":null;g||v(`--target must be 'auto' or 'approved' (got '${d.target}').`);let x=await rq(ye(process.cwd(),d.project??".")),T=Object.keys(x).length;!d.solution&&T===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let y=(d.ref?await dg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await dg(["rev-parse","HEAD"]),$=d.gitRepo??process.env.GITHUB_REPOSITORY??await dg(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,N=d.prUrl??process.env.PR_URL??null,{baseUrl:L,token:M}=await Q(d.baseUrl),re=new G({baseUrl:L,token:M}),U;try{U=await re.releaseDeploy({solutionId:d.solution??null,target:g,approvedBy:d.approvedBy??null,files:T>0?x:null,gitRepo:$,gitRef:E,gitSha:y,prUrl:N})}catch(ne){te(ne,"releases:write","release deploy"),ne instanceof le&&ne.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}_(`release ${U.releaseId} enqueued \u2192 taskId=${U.taskId} (target=${g}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Ru(()=>re.releaseStatus(U.releaseId),`release ${U.releaseId}`,d.intervalMs)}),to.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await k.releaseFiles(d)}catch(N){N instanceof le&&N.status===404&&v(`release ${d} not found.`),N instanceof le&&N.status===409&&v(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),te(N,"releases:write","pull a release"),v(`release pull failed: ${N instanceof Error?N.message:String(N)}`)}let $=ye(process.cwd(),g.dir),E=0;for(let[N,L]of[["owned",y.owned],["context",y.context]])for(let[M,re]of Object.entries(L)){let U=Ot($,N,M);await _e.mkdir(Mr(U),{recursive:!0}),await _e.writeFile(U,re,"utf8"),E++}await _e.writeFile(Ot($,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),_(`pulled release ${y.releaseId} (${y.status}) \u2192 ${$}
package/dist/turbobase.js CHANGED
@@ -3813,7 +3813,7 @@ ${o.map(T_).join(`
3813
3813
  `))}async function hm(t,e,r=qr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let o=await zr(e,r);if(!await is(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await J("publishing",()=>o.skillsPublish(n))}catch(a){V(a,"skills:publish","publish a skill"),w(`publish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function fm(t,e,r=qr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let o=await zr(e,r);if(!await is(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>o.skillsUnpublish(n))}catch(a){V(a,"skills:publish","unpublish a skill"),w(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function gm(t,e,r=qr){let n=Number(t);(!Number.isInteger(n)||n<1)&&w(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await zr(e,r);if(await is(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await J("rolling back",()=>o.skillsRollback(n));b(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){V(i,"skills:publish","roll back a skills release"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function ym(t,e=qr){let r=await zr(t,e),n;try{n=await J("reading the releases",()=>r.skillsReleases())}catch(o){V(o,"skills:publish","read the skills releases"),w(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){L("no releases yet.");return}for(let o of n.items){let s=o.is_current?m.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";b(`${s} v${o.version_no} ${o.skill_count} skill(s) ${m.dim(o.published_at)}${o.published_by?m.dim(` by ${o.published_by}`):""}${m.dim(i)}`)}}async function bm(t,e,r=qr){let n=[...new Set((t??[]).map(d=>d.trim()).filter(Boolean))];n.length===0&&w("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await zr(e,r);if(!await is(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3814
3814
  ${n.join(`
3815
3815
  `)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let d of n)try{i.push(await J(`deleting ${d}`,()=>o.skillsDelete(d)))}catch(p){if(p instanceof Q&&p.status===404){a.push(d);continue}i.length>0&&L(m.dim(`deleted before the error: ${i.map(f=>f.slug).join(", ")}`)),V(p,"skills:publish","delete a skill"),w(`delete failed on '${d}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&b(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(d=>d.wasPublished).map(d=>d.slug);l.length>0&&L(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as wm}from"node:fs";import{join as uS,relative as pS,resolve as mS,sep as hS}from"node:path";var fS=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),gS=new Set([".mcp.json",".env"]);function yS(t){return gS.has(t)||t.startsWith(".env.")&&t!==".env.example"}function bS(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function wS(t){return t.includes(0)}async function vm(t){let e=mS(t),r={},n=[],o=[],s=[];async function i(a){let l=await wm.readdir(a,{withFileTypes:!0});for(let d of l){let p=uS(a,d.name);if(fS.has(d.name))continue;if(d.isDirectory()){await i(p);continue}if(!d.isFile())continue;let f=pS(e,p).split(hS).join("/");if(yS(d.name)){o.push(f);continue}let _=await wm.readFile(p);if(!bS(_)){n.push(f);continue}wS(_)&&s.push(f),r[f]=_.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as vS}from"node:crypto";var _S="/_tb/app-assets",SS=16,kS=/^[0-9a-f]{32}$/;function _m(){return vS(SS).toString("hex")}function TS(t){return kS.test(t)}function Sm(t){if(!TS(t))throw new Error(`not a build id: ${t}`);return`${_S}/${t}/`}var km=7;Ia();var Oa=50*1024*1024;import as from"node:fs/promises";import An from"node:path";var Na={esbuild:"0.28.1","isolated-vm":"6.1.2"},La="@turbobase/isolated-vm-prebuilds";function ja(t,e){return`${t}-${e}`}function Da(t=process.versions){return`abi${t.modules}`}var Tm=["darwin-x64","win32-arm64"];async function xm(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=ja(e,r),o=An.join(t.home,"node_modules"),s=An.join(o,...La.split("/"),"prebuilds",n),i=An.join(o,"isolated-vm","prebuilds",n),a;try{a=await as.readdir(s)}catch{return[]}let l=[];await as.mkdir(i,{recursive:!0});for(let d of a){if(!d.endsWith(".node"))continue;let p=An.join(i,d);try{await as.copyFile(An.join(s,d),p,as.constants?.COPYFILE_EXCL??1),l.push(d)}catch{}}return l}import{homedir as xS}from"node:os";import{join as Rm}from"node:path";import{promises as Ua}from"node:fs";function Em(){let t=process.env.TURBOBASE_HOME??Rm(xS(),".turbobase");return{dir:t,file:Rm(t,"sandboxes.json")}}var RS={s:1e3,m:6e4,h:36e5,d:864e5};function $S(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*RS[e[2]]}function ES(t,e=Date.now()){return new Date(e+$S(t)).toISOString()}function PS(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function AS(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function CS(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var IS="[REDACTED]",Cn=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Ma=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function OS(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Ma(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:IS:n[o]=s}return n}function NS(t,e,r){return e.map(n=>OS(t,n,r))}var $m=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),LS=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function jS(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function qa(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of LS)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=jS(t);if(!$m.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...$m].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function DS(t,e=US){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function US(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function MS(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function qS(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function za(){let{file:t}=Em();try{let e=await Ua.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Pm(t){let{dir:e,file:r}=Em();await Ua.mkdir(e,{recursive:!0}),await Ua.writeFile(r,`${JSON.stringify(t,null,2)}
3816
- `,{mode:384})}async function zS(t){let e=await za();e.push(t),await Pm(e)}async function Am(t){let e=await za(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Pm(e),n??null}async function ls(){return za()}function Ba(t,e=Date.now()){let r=[],n=[];for(let o of t)PS(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Cm(t,e){qa(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Cn(r);let n=AS(e.sample),o=e.now??Date.now(),s=(e.nameGen??(d=>DS(d)))(e.fromTenant),i=MS(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let p=CS(d.rows,n),f=NS(d.table,p,d.classification);f.length>0&&await t.copyRows(i,d.table,f)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ES(e.ttl,o),sampleFraction:n,url:qS(s,e.baseUrl)};return await zS(l),l}async function Im(t,e){qa(t.target());let n=(await ls()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Am(e),n):null}async function Fa(t,e=Date.now()){qa(t.target());let r=await ls(),{expired:n}=Ba(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Am(s.name),o.push(s)}return o}var In={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},lN=Object.keys(In).filter(t=>In[t].mintable);var uN=In.pat.prefix,BS=Object.entries(In).map(([t,e])=>[e.prefix,t]),FS=/^[A-Za-z0-9_-]{20,}$/;function HS(t){if(typeof t!="string")return null;for(let[e,r]of BS)if(t.startsWith(e)&&FS.test(t.slice(e.length)))return r;return null}function Om(t){return HS(t)==="pat"}bn();var KS=8e3,VS={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function GS(t){return VS[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function WS(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(KS)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Nm(t){return t.state==="accepted"?Ie()?m.green("accepted"):"accepted":t.state==="rejected"?Ie()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ie()?m.yellow("unreachable"):"unreachable"}async function Lm(t={},e=fetch){let r=await Ot(),{file:n}=Lo();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${n}.`));return}let o=await mt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await WS(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ie())b(ft(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Nm(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Nm(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${GS(i.check.reason)}.`)),L(m.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function yA(t){let e=await Ot();e.length===0&&w("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{w("cancelled.")}}async function bA(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function wA(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function vA(t,e,r){let n=await vu({baseUrl:t,token:e}),o=(await Ot()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),wA(n.baseUrl),!r)return;let s=await bA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function _A(t){let e=await aa(await Sn(t),zt(t)),r=_a(e);return r||w(`${t}: ${Sa(e)}`),{...r,sourceCode:e}}async function Pr(t,e,r,n){try{return await ae.access(t),"skipped"}catch{}return await ae.mkdir(zt(t),{recursive:!0}),await ae.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ae.chmod(t,n),"wrote"}async function Lb(t,e){if(Db(t)!==".gitignore")return Pr(t,e.content,e.executable,e.mode);let r=await ae.readFile(t,"utf8").catch(()=>null);if(r===null)return Pr(t,e.content,e.executable,e.mode);let n=vp(r);return n===null?"skipped":(await ae.writeFile(t,n,"utf8"),"merged")}function qd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Oi(t){process.exit(t)}function SA(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function kA(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function TA(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function jb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Vd({includeInternal:t=!0}={}){let e=new gA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.34.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",u=>u.command.parent?"":`${ha()}
3816
+ `,{mode:384})}async function zS(t){let e=await za();e.push(t),await Pm(e)}async function Am(t){let e=await za(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Pm(e),n??null}async function ls(){return za()}function Ba(t,e=Date.now()){let r=[],n=[];for(let o of t)PS(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Cm(t,e){qa(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Cn(r);let n=AS(e.sample),o=e.now??Date.now(),s=(e.nameGen??(d=>DS(d)))(e.fromTenant),i=MS(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let p=CS(d.rows,n),f=NS(d.table,p,d.classification);f.length>0&&await t.copyRows(i,d.table,f)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ES(e.ttl,o),sampleFraction:n,url:qS(s,e.baseUrl)};return await zS(l),l}async function Im(t,e){qa(t.target());let n=(await ls()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Am(e),n):null}async function Fa(t,e=Date.now()){qa(t.target());let r=await ls(),{expired:n}=Ba(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Am(s.name),o.push(s)}return o}var In={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},lN=Object.keys(In).filter(t=>In[t].mintable);var uN=In.pat.prefix,BS=Object.entries(In).map(([t,e])=>[e.prefix,t]),FS=/^[A-Za-z0-9_-]{20,}$/;function HS(t){if(typeof t!="string")return null;for(let[e,r]of BS)if(t.startsWith(e)&&FS.test(t.slice(e.length)))return r;return null}function Om(t){return HS(t)==="pat"}bn();var KS=8e3,VS={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function GS(t){return VS[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function WS(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(KS)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Nm(t){return t.state==="accepted"?Ie()?m.green("accepted"):"accepted":t.state==="rejected"?Ie()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ie()?m.yellow("unreachable"):"unreachable"}async function Lm(t={},e=fetch){let r=await Ot(),{file:n}=Lo();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${n}.`));return}let o=await mt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await WS(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ie())b(ft(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Nm(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Nm(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${GS(i.check.reason)}.`)),L(m.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function yA(t){let e=await Ot();e.length===0&&w("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{w("cancelled.")}}async function bA(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function wA(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function vA(t,e,r){let n=await vu({baseUrl:t,token:e}),o=(await Ot()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),wA(n.baseUrl),!r)return;let s=await bA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function _A(t){let e=await aa(await Sn(t),zt(t)),r=_a(e);return r||w(`${t}: ${Sa(e)}`),{...r,sourceCode:e}}async function Pr(t,e,r,n){try{return await ae.access(t),"skipped"}catch{}return await ae.mkdir(zt(t),{recursive:!0}),await ae.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ae.chmod(t,n),"wrote"}async function Lb(t,e){if(Db(t)!==".gitignore")return Pr(t,e.content,e.executable,e.mode);let r=await ae.readFile(t,"utf8").catch(()=>null);if(r===null)return Pr(t,e.content,e.executable,e.mode);let n=vp(r);return n===null?"skipped":(await ae.writeFile(t,n,"utf8"),"merged")}function qd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Oi(t){process.exit(t)}function SA(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function kA(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function TA(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function jb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Vd({includeInternal:t=!0}={}){let e=new gA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.34.2").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",u=>u.command.parent?"":`${ha()}
3817
3817
  `),e.hook("preAction",(u,h)=>{Op(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async u=>{let h=rt(u.baseUrl);u.token||w(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3818
3818
  ${$n} auth login --base-url ${h} --token tb_pat_\u2026`),Om(u.token)||w("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await vA(h,u.token,u.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async u=>Lm({probe:u.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async u=>{let h=u??await yA("Pick the active instance:"),v=await jo(h);if(!v){let x=await Ot();w(`no stored sign-in for ${rt(h)}.`+(x.length?` Stored: ${x.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${rt(h)} --token tb_pat_\u2026\`.`)}b(`active instance \u2192 ${v.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async u=>{if(u.all){let x=await Ot();for(let S of x)await ta(S.baseUrl);b(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let h=await ta(u.baseUrl);h||w(u.baseUrl?`no stored sign-in for ${rt(u.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await mt();b(`signed out of ${h}.`+(v?` Active instance \u2192 ${v.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x;try{x=await mr({baseUrl:h,token:v,recordsOnly:u.recordsOnly})}catch(g){let T=g instanceof Error?g.message:String(g);if(!u.recordsOnly&&/openapi\.json failed \(401/.test(T)){L("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{x=await mr({baseUrl:h,token:v,recordsOnly:!0})}catch(E){w(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else w(`types generation failed: ${T}`)}let S=se(process.cwd(),u.out);await ae.writeFile(S,x,"utf8"),b(`wrote ${S} (${x.split(`
3819
3819
  `).length} lines).`)}),jp(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new URLSearchParams;u.records&&x.set("records",u.records),u.query&&x.set("query",u.query);let S=x.toString(),g=await fetch(`${h}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});g.ok||w(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let E=((await g.json()).markdown??"").trim(),A=se(process.cwd(),u.out),C=u.records?` records=${u.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
@@ -3843,7 +3843,7 @@ samples init: ${E} written, ${A} skipped.`)});let Tt=e.command("guardrails").des
3843
3843
  `+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ft(S.map(Li),{head:Ub})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),Tt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",u=>Number(u)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailCreate({name:u,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(T){V(T,"extensions:deploy","create a guardrail"),w(`create guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} created${g.status==="active"?"":m.dim(` (${g.status} \u2014 activate it to take effect)`)}`),b(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),b(m.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),Tt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",u=>Number(u)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&w("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailUpdate(u,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(T){V(T,"extensions:deploy","edit a guardrail"),w(`edit guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} updated`),b(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[u,h,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Tt.command(`${u} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(x,S)=>{let{baseUrl:g,token:T}=await H(S.baseUrl),E=new q({baseUrl:g,token:T});try{await E.guardrailUpdate(x,{status:h})}catch(A){V(A,"extensions:deploy",`${u} a guardrail`),w(`${u} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(x)} ${v}`),h==="inactive"&&b(m.dim(" writes it was gating now fall through to the other rules."))});Tt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x});try{await S.guardrailDelete(u)}catch(g){V(g,"extensions:deploy","delete a guardrail"),w(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(u)} deleted`)}),Tt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(u===void 0){let A;try{A=await S.guardrailPostureGet()}catch(C){V(C,"extensions:deploy","read the guardrail posture"),w(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}b(`guardrail posture: ${m.bold(g(A.mode))}`),b(m.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let T=u.trim().toLowerCase();T!=="allow"&&T!=="deny"&&w("posture must be 'allow' or 'deny'.");let E;try{E=await S.guardrailPostureSet(T)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),w(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail posture set to ${m.bold(g(E.mode))}`),E.mode==="deny"&&b(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Tt.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async u=>{let h;if(u.fields)try{h=JSON.parse(u.fields)}catch(E){w(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:v,token:x}=await H(u.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.guardrailTest({source:u.source,record:u.record,...u.actor?{actor:u.actor}:{},...u.externalId?{externalId:u.externalId}:{},...h?{fields:h}:{},...u.op?{op:u.op}:{},...u.phase?{phase:u.phase}:{}})}catch(E){V(E,"extensions:deploy","test guardrails"),w(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(u.json)return b(JSON.stringify(g,null,2));let T=`${u.source}/${g.op??u.record}`;g.degraded?(b(`${m.red("\u2717")} ${T} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${g.reason}`))):g.allowed?b(`${m.green("\u2713")} ${T} \u2014 ${g.decision}`+(g.blockedBy?m.dim(` (rule ${g.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${T} \u2014 ${g.decision} by ${m.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&b(m.dim(` ${g.message}`))),g.decision==="require_confirm"&&b(m.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let fn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),xo=(u,h={})=>{let v=`${m.bold(u.table)} ${m.dim(u.displayName)}`;b(u.exists===!1?`${v} ${m.dim("(new)")}`:v);for(let x of u.fields){let S=[x.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&x.claimedBy?.length?` ${m.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";b(` ${x.column.padEnd(28)} ${x.type}${S?` (${S})`:""}${g}`)}h.showClaimants&&u.claimants.length>1&&b(m.dim(` claimed by ${u.claimants.join(", ")}`))};function Ro(u){if(u instanceof Q&&u.status===409){let h=u.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}w(`tables: ${u instanceof Error?u.message:String(u)}`)}let Gd=async u=>{let h=et(se(process.cwd(),u),"public","turbobase.json"),v=await ae.readFile(h,"utf8").catch(()=>null);if(v===null)return null;let x;try{x=JSON.parse(v)}catch(g){w(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let S=x.tables;return S===void 0?{tables:[],manifestPath:h}:(Array.isArray(S)||w(`${h}: "tables" must be an array.`),{tables:S,manifestPath:h})};fn.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v}),S;try{S=await x.tablesList()}catch(g){V(g,"extensions:deploy","list tables"),w(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(u.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ft(S.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),fn.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(u,h)=>{let v=await Gd(u??".");if(v||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),v.tables.length===0)return b(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:S}=await H(h.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:v.tables}))}catch(E){V(E,"extensions:deploy","plan tables"),Ro(E)}b(`claiming as ${m.bold(T.claimedBy)}`);for(let E of T.tables)xo(E,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),fn.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(u,h)=>{let v=await Gd(u??".");if(v||w(`no public/turbobase.json under ${se(process.cwd(),u??".")}.`),v.tables.length===0)return b(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:S}=await H(h.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:v.tables}))}catch(E){V(E,"extensions:deploy","apply tables"),Ro(E)}for(let E of T.tables)xo(E,{showClaimants:!0});b(`applied ${T.tables.length} table${T.tables.length===1?"":"s"} as ${T.claimedBy}.`)}),fn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(u,h)=>[...h??[],u],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let v=h.field.map(E=>{let[A,C,O]=E.split(":");return(!A||!C)&&w(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&w(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:x,token:S}=await H(h.baseUrl),g=new q({baseUrl:x,token:S}),T;try{T=await J(`creating cr_${u}`,()=>g.tablesApply({tables:[{slug:u,displayName:h.name??u,fields:v,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){V(E,"extensions:deploy","create a table"),Ro(E)}for(let E of T.tables)xo(E);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),fn.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{h.confirm!==u&&w(`drop refused: --confirm "${h.confirm}" does not match "${u}".`);let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await J(`dropping cr_${u}`,()=>S.tablesDrop(u,h.confirm))}catch(T){V(T,"extensions:deploy","drop a table"),w(`drop failed: ${T instanceof Error?T.message:String(T)}`)}if(!g.removed)return b(`no table named "${u}" on this instance \u2014 nothing dropped.`);b(`dropped ${g.table} and every row in it.`)});let ji=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ji.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async u=>{process.env.TURBOBASE_SANDBOX="1";let h=Bd(),v;try{v=await Cm(h,{fromTenant:u.from,ttl:u.ttl,sample:u.sample,baseUrl:u.baseUrl})}catch(x){x instanceof Cn&&w(x.message),w(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}b(`sandbox ${v.name} ready.`),b(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),b(` url: ${v.url}`),b(` expires: ${v.expiresAt}`)}),ji.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async u=>{let h=Bd();await Fa(h).catch(()=>[]);let v;try{v=await Im(h,u)}catch(x){w(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}v||w(`no sandbox named '${u}'.`),b(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),ji.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let u=Bd(),h=await Fa(u).catch(()=>[]),v=await ls(),{active:x}=Ba(v);if(x.length===0)b("no active sandboxes.");else{for(let S of x)b(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);b(`
3844
3844
  ${x.length} active sandbox(es).`)}h.length>0&&b(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Xo).action(async u=>{let{baseUrl:h,token:v}=await H(u.baseUrl),x=new q({baseUrl:h,token:v}),S;try{S=await J("exporting instance config",()=>x.configExport())}catch(E){E instanceof Q&&(E.status===401||E.status===403)&&w("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),w(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let g=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
3845
3845
  `,T=se(process.cwd(),u.out,xn);await ae.mkdir(zt(T),{recursive:!0}),await ae.writeFile(T,g,"utf8"),b(`wrote ${u.out}/${xn} (${g.split(`
3846
- `).length} lines).`)});let Wd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Mb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Jd=()=>process.env.TURBOBASE_HOME?.trim()||et(fA(),".turbobase"),qb=()=>"1.34.0",$o=async()=>Promise.all(Mb.map(async u=>{try{return await import(u.name),{...u,present:!0}}catch{return{...u,present:!1}}}));Wd.command("status").description("Report which optional native packages are installed.").action(async()=>{let u=await $o();for(let h of u)b(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);u.some(h=>!h.present)&&b(`
3846
+ `).length} lines).`)});let Wd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Mb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Jd=()=>process.env.TURBOBASE_HOME?.trim()||et(fA(),".turbobase"),qb=()=>"1.34.2",$o=async()=>Promise.all(Mb.map(async u=>{try{return await import(u.name),{...u,present:!0}}catch{return{...u,present:!1}}}));Wd.command("status").description("Report which optional native packages are installed.").action(async()=>{let u=await $o();for(let h of u)b(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);u.some(h=>!h.present)&&b(`
3847
3847
  run \`${$n} ext extras install\` to fetch them into ${Jd()}.`)}),Wd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let u=await $o();if(u.every(A=>A.present)){b(ve.success("extras already installed \u2014 nothing to do."));return}let h=Jd();await ae.mkdir(h,{recursive:!0});let v=u.filter(A=>!A.present).map(A=>A.name),x=ja(process.platform,process.arch),S=async(A,C)=>{let{code:O,stderr:G}=await To("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&w(`extras install failed while installing ${C} (npm exited ${O}).
3848
3848
  ${G.trim()}
3849
3849
  These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=v.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(C=>`${C}@${Na[C]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await S(A,g.join(", "))}if(v.includes("isolated-vm")){let A=`isolated-vm@${Na["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${h}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),Tm.includes(x)){let O=`${La}@${qb()}`;b(`fetching ${O} (no upstream binary for ${x}) \u2026`);let{code:G}=await To("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);G!==0&&b(ve.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await xm({home:h});C.length>0&&b(` ${ve.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let T=await $o(),E=T.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){b(ve.warn(`no prebuilt isolated-vm for ${x} / Node ${process.versions.node} (${Da()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await To("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(T=await $o(),E=T.filter(C=>!C.present).map(C=>C.name))}E.length>0&&w(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${x} / Node ${process.versions.node} (${Da()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Ar=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Ar.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async u=>{let h=u.target==="approved"?"approved":u.target==="auto"?"auto":null;h||w(`--target must be 'auto' or 'approved' (got '${u.target}').`);let v=await AA(se(process.cwd(),u.project??".")),x=Object.keys(v).length;!u.solution&&x===0&&w("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(u.ref?await Fd(["rev-parse",u.ref])??u.ref:null)??process.env.GITHUB_SHA??await Fd(["rev-parse","HEAD"]),T=u.gitRepo??process.env.GITHUB_REPOSITORY??await Fd(["remote","get-url","origin"]),E=u.gitRef??process.env.GITHUB_REF??null,A=u.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await H(u.baseUrl),G=new q({baseUrl:C,token:O}),N;try{N=await G.releaseDeploy({solutionId:u.solution??null,target:h,approvedBy:u.approvedBy??null,files:x>0?v:null,gitRepo:T,gitRef:E,gitSha:g,prUrl:A})}catch(W){V(W,"releases:write","release deploy"),W instanceof Q&&W.status===404&&w("solution_not_found \u2014 no solution with that id."),w(`release deploy failed: ${W instanceof Error?W.message:String(W)}`)}b(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${h}`+(x>0?`, uploaded ${x} bundle file(s)`:", live-fetch")+")."),u.follow&&await Ta(()=>G.releaseStatus(N.releaseId),`release ${N.releaseId}`,u.intervalMs)}),Ar.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,h)=>{let{baseUrl:v,token:x}=await H(h.baseUrl),S=new q({baseUrl:v,token:x}),g;try{g=await S.releaseFiles(u)}catch(A){A instanceof Q&&A.status===404&&w(`release ${u} not found.`),A instanceof Q&&A.status===409&&w(`no built project was retained for release ${u}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),V(A,"releases:write","pull a release"),w(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let T=se(process.cwd(),h.dir),E=0;for(let[A,C]of[["owned",g.owned],["context",g.context]])for(let[O,G]of Object.entries(C)){let N=et(T,A,O);await ae.mkdir(zt(N),{recursive:!0}),await ae.writeFile(N,G,"utf8"),E++}await ae.writeFile(et(T,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),b(`pulled release ${g.releaseId} (${g.status}) \u2192 ${T}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turbobase/cli",
3
- "version": "1.34.0",
3
+ "version": "1.34.2",
4
4
  "description": "Author, test, and deploy Turbobase extensions (hooks + conduits) against a tenant over HTTP + a personal access token.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",