@turbobase/cli 1.23.0 → 1.23.1

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.
@@ -3740,7 +3740,7 @@ ${o.map(G0).join(`
3740
3740
  `))}async function Nb(t,e,r=bo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await wo(e,r);if(!await fa(`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 ae("publishing",()=>o.skillsPublish(n))}catch(a){se(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}v(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function zb(t,e,r=bo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await wo(e,r);if(!await fa(`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 ae("unpublishing",()=>o.skillsUnpublish(n))}catch(a){se(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}v(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function jb(t,e,r=bo){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await wo(e,r);if(await fa(`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 ae("rolling back",()=>o.skillsRollback(n));v(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){se(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Lb(t,e=bo){let r=await wo(t,e),n;try{n=await ae("reading the releases",()=>r.skillsReleases())}catch(o){se(o,"skills:publish","read the skills releases"),k(`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?g.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";v(`${s} v${o.version_no} ${o.skill_count} skill(s) ${g.dim(o.published_at)}${o.published_by?g.dim(` by ${o.published_by}`):""}${g.dim(i)}`)}}async function Db(t,e,r=bo){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await wo(e,r);if(!await fa(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3741
3741
  ${n.join(`
3742
3742
  `)}`,"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 ae(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof le&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),se(u,"skills:publish","delete a skill"),k(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&v(g.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Mb}from"node:fs";import{join as _P,relative as xP,resolve as kP,sep as $P}from"node:path";var SP=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),TP=new Set([".mcp.json",".env"]);function EP(t){return TP.has(t)||t.startsWith(".env.")&&t!==".env.example"}function RP(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function PP(t){return t.includes(0)}async function Ub(t){let e=kP(t),r={},n=[],o=[],s=[];async function i(a){let c=await Mb.readdir(a,{withFileTypes:!0});for(let l of c){let u=_P(a,l.name);if(SP.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=xP(e,u).split($P).join("/");if(EP(l.name)){o.push(p);continue}let w=await Mb.readFile(u);if(!RP(w)){n.push(p);continue}PP(w)&&s.push(p),r[p]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as AP}from"node:crypto";var IP="/_tb/app-assets",OP=16,CP=/^[0-9a-f]{32}$/;function qb(){return AP(OP).toString("hex")}function NP(t){return CP.test(t)}function Bb(t){if(!NP(t))throw new Error(`not a build id: ${t}`);return`${IP}/${t}/`}var Zb=7;Su();var Tu=50*1024*1024;import ma from"node:fs/promises";import gs from"node:path";var Eu={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ru="@turbobase/isolated-vm-prebuilds";function Pu(t,e){return`${t}-${e}`}function Au(t=process.versions){return`abi${t.modules}`}var Fb=["darwin-x64","win32-arm64"];async function Hb(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Pu(e,r),o=gs.join(t.home,"node_modules"),s=gs.join(o,...Ru.split("/"),"prebuilds",n),i=gs.join(o,"isolated-vm","prebuilds",n),a;try{a=await ma.readdir(s)}catch{return[]}let c=[];await ma.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=gs.join(i,l);try{await ma.copyFile(gs.join(s,l),u,ma.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as zP}from"node:os";import{join as Vb}from"node:path";import{promises as Iu}from"node:fs";function Wb(){let t=process.env.TURBOBASE_HOME??Vb(zP(),".turbobase");return{dir:t,file:Vb(t,"sandboxes.json")}}var jP={s:1e3,m:6e4,h:36e5,d:864e5};function LP(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*jP[e[2]]}function DP(t,e=Date.now()){return new Date(e+LP(t)).toISOString()}function MP(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function UP(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 qP(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 BP="[REDACTED]",ys=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Ou=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 ZP(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Ou(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:BP:n[o]=s}return n}function FP(t,e,r){return e.map(n=>ZP(t,n,r))}var Kb=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),HP=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function VP(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 Cu(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 HP)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=VP(t);if(!Kb.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Kb].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function KP(t,e=WP){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function WP(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function GP(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function JP(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Nu(){let{file:t}=Wb();try{let e=await Iu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Gb(t){let{dir:e,file:r}=Wb();await Iu.mkdir(e,{recursive:!0}),await Iu.writeFile(r,`${JSON.stringify(t,null,2)}
3743
- `,{mode:384})}async function YP(t){let e=await Nu();e.push(t),await Gb(e)}async function Jb(t){let e=await Nu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Gb(e),n??null}async function ga(){return Nu()}function zu(t,e=Date.now()){let r=[],n=[];for(let o of t)MP(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Yb(t,e){Cu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new ys(r);let n=UP(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>KP(l)))(e.fromTenant),i=GP(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=qP(l.rows,n),p=FP(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:DP(e.ttl,o),sampleFraction:n,url:JP(s,e.baseUrl)};return await YP(c),c}async function Xb(t,e){Cu(t.target());let n=(await ga()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Jb(e),n):null}async function ju(t,e=Date.now()){Cu(t.target());let r=await ga(),{expired:n}=zu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Jb(s.name),o.push(s)}return o}var bs={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"}},DZ=Object.keys(bs).filter(t=>bs[t].mintable);var qZ=bs.pat.prefix,XP=Object.entries(bs).map(([t,e])=>[e.prefix,t]),QP=/^[A-Za-z0-9_-]{20,}$/;function eA(t){if(typeof t!="string")return null;for(let[e,r]of XP)if(t.startsWith(e)&&QP.test(t.slice(e.length)))return r;return null}function Qb(t){return eA(t)==="pat"}ss();var tA=8e3,rA={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 nA(t){return rA[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function oA(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(tA)})}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 ew(t){return t.state==="accepted"?tt()?g.green("accepted"):"accepted":t.state==="rejected"?tt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:tt()?g.yellow("unreachable"):"unreachable"}async function tw(t={},e=fetch){let r=await Rr(),{file:n}=Fi();if(r.length===0){v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Xt(),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 oA(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(tt())v(Qt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),ew(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} ${ew(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${nA(i.check.reason)}.`)),q(g.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(g.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 CM(t){let e=await Rr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await mt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function NM(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 zM(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 jM(t,e,r){let n=await sy({baseUrl:t,token:e}),o=(await Rr()).length-1;if(v(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),zM(n.baseUrl),!r)return;let s=await NM(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 LM(t){let e=await ou(await ls(t),Lr(t)),r=yu(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);k(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Xn(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Lr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function QS(t,e){if(tT(t)!==".gitignore")return Xn(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return Xn(t,e.content,e.executable,e.mode);let n=Ky(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function Xm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function ul(t){process.exit(t)}function DM(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 MM(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 UM(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 eT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function og({includeInternal:t=!0}={}){let e=new kg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.23.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${du()}
3743
+ `,{mode:384})}async function YP(t){let e=await Nu();e.push(t),await Gb(e)}async function Jb(t){let e=await Nu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Gb(e),n??null}async function ga(){return Nu()}function zu(t,e=Date.now()){let r=[],n=[];for(let o of t)MP(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Yb(t,e){Cu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new ys(r);let n=UP(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>KP(l)))(e.fromTenant),i=GP(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=qP(l.rows,n),p=FP(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:DP(e.ttl,o),sampleFraction:n,url:JP(s,e.baseUrl)};return await YP(c),c}async function Xb(t,e){Cu(t.target());let n=(await ga()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Jb(e),n):null}async function ju(t,e=Date.now()){Cu(t.target());let r=await ga(),{expired:n}=zu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Jb(s.name),o.push(s)}return o}var bs={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"}},DZ=Object.keys(bs).filter(t=>bs[t].mintable);var qZ=bs.pat.prefix,XP=Object.entries(bs).map(([t,e])=>[e.prefix,t]),QP=/^[A-Za-z0-9_-]{20,}$/;function eA(t){if(typeof t!="string")return null;for(let[e,r]of XP)if(t.startsWith(e)&&QP.test(t.slice(e.length)))return r;return null}function Qb(t){return eA(t)==="pat"}ss();var tA=8e3,rA={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 nA(t){return rA[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function oA(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(tA)})}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 ew(t){return t.state==="accepted"?tt()?g.green("accepted"):"accepted":t.state==="rejected"?tt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:tt()?g.yellow("unreachable"):"unreachable"}async function tw(t={},e=fetch){let r=await Rr(),{file:n}=Fi();if(r.length===0){v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Xt(),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 oA(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(tt())v(Qt(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),ew(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)v(`${i.active?"* ":" "}${i.baseUrl} ${ew(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${nA(i.check.reason)}.`)),q(g.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(g.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 CM(t){let e=await Rr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ft()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await mt(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function NM(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 zM(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 jM(t,e,r){let n=await sy({baseUrl:t,token:e}),o=(await Rr()).length-1;if(v(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),zM(n.baseUrl),!r)return;let s=await NM(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 LM(t){let e=await ou(await ls(t),Lr(t)),r=yu(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);k(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Xn(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Lr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function QS(t,e){if(tT(t)!==".gitignore")return Xn(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return Xn(t,e.content,e.executable,e.mode);let n=Ky(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function Xm(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function ul(t){process.exit(t)}function DM(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 MM(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 UM(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 eT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function og({includeInternal:t=!0}={}){let e=new kg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.23.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${du()}
3744
3744
  `),e.hook("preAction",(d,m)=>{ib(e.opts(),m.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 m=Dt(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3745
3745
  ${hs} auth login --base-url ${m} --token tb_pat_\u2026`),Qb(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await jM(m,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=>tw({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 m=d??await CM("Pick the active instance:"),_=await Hi(m);if(!_){let T=await Rr();k(`no stored sign-in for ${Dt(m)}.`+(T.length?` Stored: ${T.map(x=>x.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Dt(m)} --token tb_pat_\u2026\`.`)}v(`active instance \u2192 ${_.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 Rr();for(let x of T)await Xl(x.baseUrl);v(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let m=await Xl(d.baseUrl);m||k(d.baseUrl?`no stored sign-in for ${Dt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let _=await Xt();v(`signed out of ${m}.`+(_?` Active instance \u2192 ${_.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:m,token:_}=await ne(d.baseUrl),T;try{T=await In({baseUrl:m,token:_,recordsOnly:d.recordsOnly})}catch(y){let S=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){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 In({baseUrl:m,token:_,recordsOnly:!0})}catch(R){k(`types generation failed: ${R instanceof Error?R.message:String(R)}`)}}else k(`types generation failed: ${S}`)}let x=ge(process.cwd(),d.out);await be.writeFile(x,T,"utf8"),v(`wrote ${x} (${T.split(`
3746
3746
  `).length} lines).`)}),lb(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:m,token:_}=await ne(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let x=T.toString(),y=await fetch(`${m}/v1/catalog/grounding${x?`?${x}`:""}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});y.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let R=((await y.json()).markdown??"").trim(),N=ge(process.cwd(),d.out),L=d.records?` records=${d.records}`:"",D=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${L} \u2014 do not edit; re-run to refresh. -->
@@ -3770,7 +3770,7 @@ samples init: ${R} written, ${N} skipped.`)});let lr=e.command("guardrails").des
3770
3770
  `+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));v(Qt(x.map($i),{head:pl})),v(g.dim(" first match wins; lower PRIO is evaluated first."))}),lr.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,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.guardrailCreate({name:d,source:m.source,record:m.record,decision:m.decision,...m.op?{op:m.op}:{},...m.target?{target:m.target}:{},...m.actor?{actor:m.actor}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when?{when:m.when}:{},...m.reason?{reason:m.reason}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){se(S,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),v(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),v(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),lr.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,m)=>{m.decision===void 0&&m.priority===void 0&&m.when===void 0&&m.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.guardrailUpdate(d,{...m.decision!==void 0?{decision:m.decision}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when!==void 0?{when:m.when}:{},...m.reason!==void 0?{reason:m.reason}:{}})}catch(S){se(S,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),v(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,m,_]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])lr.command(`${d} <name>`).description(m==="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,x)=>{let{baseUrl:y,token:S}=await ne(x.baseUrl),R=new ee({baseUrl:y,token:S});try{await R.guardrailUpdate(T,{status:m})}catch(N){se(N,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${N instanceof Error?N.message:String(N)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(T)} ${_}`),m==="inactive"&&v(g.dim(" writes it was gating now fall through to the other rules."))});lr.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,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T});try{await x.guardrailDelete(d)}catch(y){se(y,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}v(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),lr.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,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,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 x.guardrailPostureGet()}catch(L){se(L,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${L instanceof Error?L.message:String(L)}`)}v(`guardrail posture: ${g.bold(y(N.mode))}`),v(g.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 S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&k("posture must be 'allow' or 'deny'.");let R;try{R=await x.guardrailPostureSet(S)}catch(N){se(N,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${N instanceof Error?N.message:String(N)}`)}v(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(R.mode))}`),R.mode==="deny"&&v(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),lr.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 m;if(d.fields)try{m=JSON.parse(d.fields)}catch(R){k(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:_,token:T}=await ne(d.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...m?{fields:m}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){se(R,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return v(JSON.stringify(y,null,2));let S=`${d.source}/${y.op??d.record}`;y.degraded?(v(`${g.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),v(g.dim(` ${y.reason}`))):y.allowed?v(`${g.green("\u2713")} ${S} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(v(`${g.red("\u2717")} ${S} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&v(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&v(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let Go=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Si=(d,m={})=>{let _=`${g.bold(d.table)} ${g.dim(d.displayName)}`;v(d.exists===!1?`${_} ${g.dim("(new)")}`:_);for(let T of d.fields){let x=[T.required?"required":null].filter(Boolean).join(", "),y=m.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";v(` ${T.column.padEnd(28)} ${T.type}${x?` (${x})`:""}${y}`)}m.showClaimants&&d.claimants.length>1&&v(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ti(d){if(d instanceof le&&d.status===409){let m=d.body;m?.error==="table_conflict"&&m.message&&(q(m.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let sg=async d=>{let m=Ot(ge(process.cwd(),d),"public","turbobase.json"),_=await be.readFile(m,"utf8").catch(()=>null);if(_===null)return null;let T;try{T=JSON.parse(_)}catch(y){k(`${m} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let x=T.tables;return x===void 0?{tables:[],manifestPath:m}:(Array.isArray(x)||k(`${m}: "tables" must be an array.`),{tables:x,manifestPath:m})};Go.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:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await T.tablesList()}catch(y){se(y,"extensions:deploy","list tables"),k(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return v(JSON.stringify(x,null,2));if(x.length===0)return v("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");v(Qt(x.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Go.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,m)=>{let _=await sg(d??".");if(_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),_.tables.length===0)return v(`${_.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:x}=await ne(m.baseUrl),y=new ee({baseUrl:T,token:x}),S;try{S=await ae("planning tables",()=>y.tablesPlan({claimedBy:m.as,tables:_.tables}))}catch(R){se(R,"extensions:deploy","plan tables"),Ti(R)}v(`claiming as ${g.bold(S.claimedBy)}`);for(let R of S.tables)Si(R,{showClaimants:!0});v(""),v(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Go.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,m)=>{let _=await sg(d??".");if(_||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),_.tables.length===0)return v(`${_.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:x}=await ne(m.baseUrl),y=new ee({baseUrl:T,token:x}),S;try{S=await ae("applying tables",()=>y.tablesApply({claimedBy:m.as,tables:_.tables}))}catch(R){se(R,"extensions:deploy","apply tables"),Ti(R)}for(let R of S.tables)Si(R,{showClaimants:!0});v(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),Go.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,m)=>[...m??[],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,m)=>{let _=m.field.map(R=>{let[N,L,D]=R.split(":");return(!N||!L)&&k(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),D!==void 0&&D!=="required"&&k(`--field "${R}": the third part may only be "required".`),{name:N,type:L,...D==="required"?{required:!0}:{}}}),{baseUrl:T,token:x}=await ne(m.baseUrl),y=new ee({baseUrl:T,token:x}),S;try{S=await ae(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:m.name??d,fields:_,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){se(R,"extensions:deploy","create a table"),Ti(R)}for(let R of S.tables)Si(R);v(""),v(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Go.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,m)=>{m.confirm!==d&&k(`drop refused: --confirm "${m.confirm}" does not match "${d}".`);let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await ae(`dropping cr_${d}`,()=>x.tablesDrop(d,m.confirm))}catch(S){se(S,"extensions:deploy","drop a table"),k(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!y.removed)return v(`no table named "${d}" on this instance \u2014 nothing dropped.`);v(`dropped ${y.table} and every row in it.`)});let hl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");hl.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 m=eg(),_;try{_=await Yb(m,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof ys&&k(T.message),k(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}v(`sandbox ${_.name} ready.`),v(` source: ${_.fromTenant} (sampled ${Math.round(_.sampleFraction*100)}%, redacted)`),v(` url: ${_.url}`),v(` expires: ${_.expiresAt}`)}),hl.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 m=eg();await ju(m).catch(()=>[]);let _;try{_=await Xb(m,d)}catch(T){k(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}_||k(`no sandbox named '${d}'.`),v(`destroyed sandbox ${_.name} (dropped ${_.database}).`)}),hl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=eg(),m=await ju(d).catch(()=>[]),_=await ga(),{active:T}=zu(_);if(T.length===0)v("no active sandboxes.");else{for(let x of T)v(` ${x.name} from=${x.fromTenant} expires=${x.expiresAt} ${x.url}`);v(`
3771
3771
  ${T.length} active sandbox(es).`)}m.length>0&&v(`(reaped ${m.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.",ia).action(async d=>{let{baseUrl:m,token:_}=await ne(d.baseUrl),T=new ee({baseUrl:m,token:_}),x;try{x=await ae("exporting instance config",()=>T.configExport())}catch(R){R instanceof le&&(R.status===401||R.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let y=typeof x.serialized=="string"?x.serialized:`${JSON.stringify(x.manifest??x,null,2)}
3772
3772
  `,S=ge(process.cwd(),d.out,ds);await be.mkdir(Lr(S),{recursive:!0}),await be.writeFile(S,y,"utf8"),v(`wrote ${d.out}/${ds} (${y.split(`
3773
- `).length} lines).`)});let ig=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),rT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],ag=()=>process.env.TURBOBASE_HOME?.trim()||Ot(OM(),".turbobase"),nT=()=>"1.23.0",Ei=async()=>Promise.all(rT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));ig.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ei();for(let m of d)v(`${m.present?Ke.success("installed"):Ke.warn("missing")} ${g.bold(m.name)} \u2014 ${m.needs}`);d.some(m=>!m.present)&&v(`
3773
+ `).length} lines).`)});let ig=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),rT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],ag=()=>process.env.TURBOBASE_HOME?.trim()||Ot(OM(),".turbobase"),nT=()=>"1.23.1",Ei=async()=>Promise.all(rT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));ig.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ei();for(let m of d)v(`${m.present?Ke.success("installed"):Ke.warn("missing")} ${g.bold(m.name)} \u2014 ${m.needs}`);d.some(m=>!m.present)&&v(`
3774
3774
  run \`${hs} ext extras install\` to fetch them into ${ag()}.`)}),ig.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ei();if(d.every(N=>N.present)){v(Ke.success("extras already installed \u2014 nothing to do."));return}let m=ag();await be.mkdir(m,{recursive:!0});let _=d.filter(N=>!N.present).map(N=>N.name),T=Pu(process.platform,process.arch),x=async(N,L)=>{let{code:D,stderr:H}=await ki("npm",["install","--prefix",m,"--no-audit","--no-fund",...N]);D!==0&&k(`extras install failed while installing ${L} (npm exited ${D}).
3775
3775
  ${H.trim()}
3776
3776
  These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=_.filter(N=>N!=="isolated-vm");if(y.length>0){let N=y.map(L=>`${L}@${Eu[L]??"latest"}`);v(`installing ${N.join(", ")} \u2192 ${m}/node_modules \u2026`),await x(N,y.join(", "))}if(_.includes("isolated-vm")){let N=`isolated-vm@${Eu["isolated-vm"]}`;if(v(`installing ${N} \u2192 ${m}/node_modules \u2026`),await x(["--ignore-scripts",N],"isolated-vm"),Fb.includes(T)){let D=`${Ru}@${nT()}`;v(`fetching ${D} (no upstream binary for ${T}) \u2026`);let{code:H}=await ki("npm",["install","--prefix",m,"--no-audit","--no-fund","--ignore-scripts",D]);H!==0&&v(Ke.warn(`could not fetch ${D} \u2014 falling back to a source build.`))}let L=await Hb({home:m});L.length>0&&v(` ${Ke.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await Ei(),R=S.filter(N=>!N.present).map(N=>N.name);if(R.includes("isolated-vm")){v(Ke.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${Au()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:N}=await ki("npm",["rebuild","--prefix",m,"isolated-vm"]);N===0&&(S=await Ei(),R=S.filter(L=>!L.present).map(L=>L.name))}R.length>0&&k(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${Au()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),v(Ke.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Qn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Qn.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 m=d.target==="approved"?"approved":d.target==="auto"?"auto":null;m||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let _=await VM(ge(process.cwd(),d.project??".")),T=Object.keys(_).length;!d.solution&&T===0&&k("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 tg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await tg(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await tg(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,N=d.prUrl??process.env.PR_URL??null,{baseUrl:L,token:D}=await ne(d.baseUrl),H=new ee({baseUrl:L,token:D}),j;try{j=await H.releaseDeploy({solutionId:d.solution??null,target:m,approvedBy:d.approvedBy??null,files:T>0?_:null,gitRepo:S,gitRef:R,gitSha:y,prUrl:N})}catch(Q){se(Q,"releases:write","release deploy"),Q instanceof le&&Q.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${Q instanceof Error?Q.message:String(Q)}`)}v(`release ${j.releaseId} enqueued \u2192 taskId=${j.taskId} (target=${m}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await wu(()=>H.releaseStatus(j.releaseId),`release ${j.releaseId}`,d.intervalMs)}),Qn.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,m)=>{let{baseUrl:_,token:T}=await ne(m.baseUrl),x=new ee({baseUrl:_,token:T}),y;try{y=await x.releaseFiles(d)}catch(N){N instanceof le&&N.status===404&&k(`release ${d} not found.`),N instanceof le&&N.status===409&&k(`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.`),se(N,"releases:write","pull a release"),k(`release pull failed: ${N instanceof Error?N.message:String(N)}`)}let S=ge(process.cwd(),m.dir),R=0;for(let[N,L]of[["owned",y.owned],["context",y.context]])for(let[D,H]of Object.entries(L)){let j=Ot(S,N,D);await be.mkdir(Lr(j),{recursive:!0}),await be.writeFile(j,H,"utf8"),R++}await be.writeFile(Ot(S,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),v(`pulled release ${y.releaseId} (${y.status}) \u2192 ${S}
package/dist/turbobase.js CHANGED
@@ -3693,7 +3693,7 @@ ${s.map(Pv).join(`
3693
3693
  `))}async function Up(t,e,n=Mn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let s=await qn(e,n);if(!await Qs(`Publish ${r.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 Z("publishing",()=>s.skillsPublish(r))}catch(a){J(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(f.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Mp(t,e,n=Mn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let s=await qn(e,n);if(!await Qs(`Move ${r.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 Z("unpublishing",()=>s.skillsUnpublish(r))}catch(a){J(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(f.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function qp(t,e,n=Mn){let r=Number(t);(!Number.isInteger(r)||r<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let s=await qn(e,n);if(await Qs(`Roll the skills back to release v${r}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await Z("rolling back",()=>s.skillsRollback(r));y(f.green(`rolled back to v${i.version.version_no}.`))}catch(i){J(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function zp(t,e=Mn){let n=await qn(t,e),r;try{r=await Z("reading the releases",()=>n.skillsReleases())}catch(s){J(s,"skills:publish","read the skills releases"),k(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){L("no releases yet.");return}for(let s of r.items){let o=s.is_current?f.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";y(`${o} v${s.version_no} ${s.skill_count} skill(s) ${f.dim(s.published_at)}${s.published_by?f.dim(` by ${s.published_by}`):""}${f.dim(i)}`)}}async function Bp(t,e,n=Mn){let r=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];r.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let s=await qn(e,n);if(!await Qs(r.length===1?`Delete the skill '${r[0]}'?`:`Delete ${r.length} skills?
3694
3694
  ${r.join(`
3695
3695
  `)}`,"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 u of r)try{i.push(await Z(`deleting ${u}`,()=>s.skillsDelete(u)))}catch(p){if(p instanceof Q&&p.status===404){a.push(u);continue}i.length>0&&L(f.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),J(p,"skills:publish","delete a skill"),k(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&y(f.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(f.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(f.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Fp}from"node:fs";import{join as tk,relative as nk,resolve as rk,sep as sk}from"node:path";var ok=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),ik=new Set([".mcp.json",".env"]);function ak(t){return ik.has(t)||t.startsWith(".env.")&&t!==".env.example"}function lk(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function ck(t){return t.includes(0)}async function Hp(t){let e=rk(t),n={},r=[],s=[],o=[];async function i(a){let l=await Fp.readdir(a,{withFileTypes:!0});for(let u of l){let p=tk(a,u.name);if(ok.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=nk(e,p).split(sk).join("/");if(ak(u.name)){s.push(g);continue}let x=await Fp.readFile(p);if(!lk(x)){r.push(g);continue}ck(x)&&o.push(g),n[g]=x.toString("utf8")}}return await i(e),{files:n,skipped:r,secrets:s,unstorable:o}}import{randomBytes as dk}from"node:crypto";var uk="/_tb/app-assets",pk=16,hk=/^[0-9a-f]{32}$/;function Kp(){return dk(pk).toString("hex")}function fk(t){return hk.test(t)}function Vp(t){if(!fk(t))throw new Error(`not a build id: ${t}`);return`${uk}/${t}/`}var Gp=7;Sa();var _a=50*1024*1024;import eo from"node:fs/promises";import Tr from"node:path";var $a={esbuild:"0.28.1","isolated-vm":"6.1.2"},xa="@turbobase/isolated-vm-prebuilds";function Ta(t,e){return`${t}-${e}`}function Ra(t=process.versions){return`abi${t.modules}`}var Wp=["darwin-x64","win32-arm64"];async function Jp(t){let e=t.platform??process.platform,n=t.arch??process.arch,r=Ta(e,n),s=Tr.join(t.home,"node_modules"),o=Tr.join(s,...xa.split("/"),"prebuilds",r),i=Tr.join(s,"isolated-vm","prebuilds",r),a;try{a=await eo.readdir(o)}catch{return[]}let l=[];await eo.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=Tr.join(i,u);try{await eo.copyFile(Tr.join(o,u),p,eo.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as mk}from"node:os";import{join as Yp}from"node:path";import{promises as Ea}from"node:fs";function Xp(){let t=process.env.TURBOBASE_HOME??Yp(mk(),".turbobase");return{dir:t,file:Yp(t,"sandboxes.json")}}var gk={s:1e3,m:6e4,h:36e5,d:864e5};function bk(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 n=Number(e[1]);if(!Number.isFinite(n)||n<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return n*gk[e[2]]}function yk(t,e=Date.now()){return new Date(e+bk(t)).toISOString()}function wk(t,e=Date.now()){let n=Date.parse(t);return Number.isNaN(n)?!0:n<=e}function vk(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 n=Number(e[1]);if(!Number.isFinite(n)||n<0||n>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return n/100}function kk(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let n=Math.max(1,Math.round(1/e)),r=[];for(let s=0;s<t.length;s+=n)r.push(t[s]);return r}var Sk="[REDACTED]",Rr=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Pa=class extends Error{table;column;constructor(e,n,r){super(`Refusing to copy ${e}.${n} into a sandbox: ${r}. 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=n}};function _k(t,e,n){let r={};for(let[s,o]of Object.entries(e)){let i=n[s];if(i===void 0)throw new Pa(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?r[s]=o==null?o:Sk:r[s]=o}return r}function $k(t,e,n){return e.map(r=>_k(t,r,n))}var Zp=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),xk=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function Tk(t){let e=t.trim();try{let s=new URL(e);if(s.hostname)return s.hostname.toLowerCase()}catch{}let n=e.replace(/^[a-z]+:\/\//i,""),r=(n.split("/")[0]??n).split("@").pop()??n;return(r.split(":")[0]??r).toLowerCase()}function Aa(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let r of xk)if(e.includes(r))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${r}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let n=Tk(t);if(!Zp.has(n))throw new Error(`local-only guard: target host '${n}' is not a recognised local Postgres (${[...Zp].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function Rk(t,e=Ek){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Ek(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function Pk(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Ak(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ia(){let{file:t}=Xp();try{let e=await Ea.readFile(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Qp(t){let{dir:e,file:n}=Xp();await Ea.mkdir(e,{recursive:!0}),await Ea.writeFile(n,`${JSON.stringify(t,null,2)}
3696
- `,{mode:384})}async function Ik(t){let e=await Ia();e.push(t),await Qp(e)}async function eh(t){let e=await Ia(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await Qp(e),r??null}async function to(){return Ia()}function Ca(t,e=Date.now()){let n=[],r=[];for(let s of t)wk(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function th(t,e){Aa(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new Rr(n);let r=vk(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Rk(u)))(e.fromTenant),i=Pk(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=kk(u.rows,r),g=$k(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:yk(e.ttl,s),sampleFraction:r,url:Ak(o,e.baseUrl)};return await Ik(l),l}async function nh(t,e){Aa(t.target());let r=(await to()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await eh(e),r):null}async function Oa(t,e=Date.now()){Aa(t.target());let n=await to(),{expired:r}=Ca(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await eh(o.name),s.push(o)}return s}var Er={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"}},_C=Object.keys(Er).filter(t=>Er[t].mintable);var TC=Er.pat.prefix,Ck=Object.entries(Er).map(([t,e])=>[e.prefix,t]),Ok=/^[A-Za-z0-9_-]{20,}$/;function Nk(t){if(typeof t!="string")return null;for(let[e,n]of Ck)if(t.startsWith(e)&&Ok.test(t.slice(e.length)))return n;return null}function rh(t){return Nk(t)==="pat"}mr();var Lk=8e3,jk={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 Dk(t){return jk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Uk(t,e,n=fetch){let r;try{r=await n(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(Lk)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(r.status===200||r.status===403)return{state:"accepted"};if(r.status===401){let o=await r.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(r.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${r.status} \u2014 this host does not serve the /v1 API`}}function sh(t){return t.state==="accepted"?Pe()?f.green("accepted"):"accepted":t.state==="rejected"?Pe()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Pe()?f.yellow("unreachable"):"unreachable"}async function oh(t={},e=fetch){let n=await It(),{file:r}=Ps();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(f.dim(`no sign-ins stored in ${r}.`));return}let s=await pt(),o=await Promise.all(n.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await Uk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Pe())y(ht(o.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),sh(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${sh(i.check)} (updated ${i.updatedAt})`);L(f.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(f.red(`${i.baseUrl}: ${Dk(i.check.reason)}.`)),L(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"&&L(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function aP(t){let e=await It();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ze()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Be(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{k("cancelled.")}}async function lP(t,e){let n;try{n=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}function cP(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 dP(t,e,n){let r=await cu({baseUrl:t,token:e}),s=(await It()).length-1;if(y(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),cP(r.baseUrl),!n)return;let o=await lP(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.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.")):o.kind==="bad-token"?L(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function uP(t){let e=await ta(await wr(t),Mt(t)),n=fa(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);k(r?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...n,sourceCode:e}}async function En(t,e,n,r){try{return await oe.access(t),"skipped"}catch{}return await oe.mkdir(Mt(t),{recursive:!0}),await oe.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await oe.chmod(t,r),"wrote"}async function oy(t,e){if(ay(t)!==".gitignore")return En(t,e.content,e.executable,e.mode);let n=await oe.readFile(t,"utf8").catch(()=>null);if(n===null)return En(t,e.content,e.executable,e.mode);let r=Zu(n);return r===null?"skipped":(await oe.writeFile(t,r,"utf8"),"merged")}function Ad(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Ri(t){process.exit(t)}function pP(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function hP(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function fP(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 n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.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 iy(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function jd({includeInternal:t=!0}={}){let e=new iP;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.23.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${la()}
3696
+ `,{mode:384})}async function Ik(t){let e=await Ia();e.push(t),await Qp(e)}async function eh(t){let e=await Ia(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await Qp(e),r??null}async function to(){return Ia()}function Ca(t,e=Date.now()){let n=[],r=[];for(let s of t)wk(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function th(t,e){Aa(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new Rr(n);let r=vk(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Rk(u)))(e.fromTenant),i=Pk(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=kk(u.rows,r),g=$k(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:yk(e.ttl,s),sampleFraction:r,url:Ak(o,e.baseUrl)};return await Ik(l),l}async function nh(t,e){Aa(t.target());let r=(await to()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await eh(e),r):null}async function Oa(t,e=Date.now()){Aa(t.target());let n=await to(),{expired:r}=Ca(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await eh(o.name),s.push(o)}return s}var Er={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"}},_C=Object.keys(Er).filter(t=>Er[t].mintable);var TC=Er.pat.prefix,Ck=Object.entries(Er).map(([t,e])=>[e.prefix,t]),Ok=/^[A-Za-z0-9_-]{20,}$/;function Nk(t){if(typeof t!="string")return null;for(let[e,n]of Ck)if(t.startsWith(e)&&Ok.test(t.slice(e.length)))return n;return null}function rh(t){return Nk(t)==="pat"}mr();var Lk=8e3,jk={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 Dk(t){return jk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Uk(t,e,n=fetch){let r;try{r=await n(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(Lk)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(r.status===200||r.status===403)return{state:"accepted"};if(r.status===401){let o=await r.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(r.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${r.status} \u2014 this host does not serve the /v1 API`}}function sh(t){return t.state==="accepted"?Pe()?f.green("accepted"):"accepted":t.state==="rejected"?Pe()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Pe()?f.yellow("unreachable"):"unreachable"}async function oh(t={},e=fetch){let n=await It(),{file:r}=Ps();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(f.dim(`no sign-ins stored in ${r}.`));return}let s=await pt(),o=await Promise.all(n.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await Uk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Pe())y(ht(o.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),sh(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${sh(i.check)} (updated ${i.updatedAt})`);L(f.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(f.red(`${i.baseUrl}: ${Dk(i.check.reason)}.`)),L(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"&&L(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function aP(t){let e=await It();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ze()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Be(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{k("cancelled.")}}async function lP(t,e){let n;try{n=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}function cP(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 dP(t,e,n){let r=await cu({baseUrl:t,token:e}),s=(await It()).length-1;if(y(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),cP(r.baseUrl),!n)return;let o=await lP(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.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.")):o.kind==="bad-token"?L(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function uP(t){let e=await ta(await wr(t),Mt(t)),n=fa(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);k(r?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...n,sourceCode:e}}async function En(t,e,n,r){try{return await oe.access(t),"skipped"}catch{}return await oe.mkdir(Mt(t),{recursive:!0}),await oe.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await oe.chmod(t,r),"wrote"}async function oy(t,e){if(ay(t)!==".gitignore")return En(t,e.content,e.executable,e.mode);let n=await oe.readFile(t,"utf8").catch(()=>null);if(n===null)return En(t,e.content,e.executable,e.mode);let r=Zu(n);return r===null?"skipped":(await oe.writeFile(t,r,"utf8"),"merged")}function Ad(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Ri(t){process.exit(t)}function pP(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function hP(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function fP(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 n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.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 iy(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function jd({includeInternal:t=!0}={}){let e=new iP;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.23.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${la()}
3697
3697
  `),e.hook("preAction",(d,h)=>{dp(e.opts(),h.opts())});let n=e.command("auth").description("Sign in to an instance and manage stored credentials."),r=e.command("project").description("Set up the local project and the files an agent session reads."),s=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),o=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.");n.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 h=tt(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3698
3698
  ${_r} auth login --base-url ${h} --token tb_pat_\u2026`),rh(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await dP(h,d.token,d.verify)}),n.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=>oh({probe:d.probe})),n.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let h=d??await aP("Pick the active instance:"),w=await As(h);if(!w){let $=await It();k(`no stored sign-in for ${tt(h)}.`+($.length?` Stored: ${$.map(v=>v.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${tt(h)} --token tb_pat_\u2026\`.`)}y(`active instance \u2192 ${w.baseUrl}.`)}),n.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 $=await It();for(let v of $)await Ji(v.baseUrl);y(`removed ${$.length} stored sign-in${$.length===1?"":"s"}.`);return}let h=await Ji(d.baseUrl);h||k(d.baseUrl?`no stored sign-in for ${tt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await pt();y(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),r.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:h,token:w}=await G(d.baseUrl),$;try{$=await pn({baseUrl:h,token:w,recordsOnly:d.recordsOnly})}catch(m){let _=m instanceof Error?m.message:String(m);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(_)){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{$=await pn({baseUrl:h,token:w,recordsOnly:!0})}catch(E){k(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else k(`types generation failed: ${_}`)}let v=se(process.cwd(),d.out);await oe.writeFile(v,$,"utf8"),y(`wrote ${v} (${$.split(`
3699
3699
  `).length} lines).`)}),hp(r),r.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:h,token:w}=await G(d.baseUrl),$=new URLSearchParams;d.records&&$.set("records",d.records),d.query&&$.set("query",d.query);let v=$.toString(),m=await fetch(`${h}/v1/catalog/grounding${v?`?${v}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});m.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${m.status}`);let E=((await m.json()).markdown??"").trim(),A=se(process.cwd(),d.out),C=d.records?` records=${d.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
@@ -3723,7 +3723,7 @@ samples init: ${E} written, ${A} skipped.`)});let St=e.command("guardrails").des
3723
3723
  `+f.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(ht(v.map(vs),{head:Pi})),y(f.dim(" first match wins; lower PRIO is evaluated first."))}),St.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,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await v.guardrailCreate({name:d,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(_){J(_,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} created${m.status==="active"?"":f.dim(` (${m.status} \u2014 activate it to take effect)`)}`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.actor?` actor=${m.actor}`:""}${m.when?` where ${m.when}`:""} @prio ${m.priority}`)),y(f.dim(` verify with: turbobase guardrails test --source ${m.source==="*"?"<source>":m.source} --record <record>`))}),St.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,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await v.guardrailUpdate(d,{...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(_){J(_,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} updated`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.when?` where ${m.when}`:""} @prio ${m.priority}`))});for(let[d,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])St.command(`${d} <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($,v)=>{let{baseUrl:m,token:_}=await G(v.baseUrl),E=new H({baseUrl:m,token:_});try{await E.guardrailUpdate($,{status:h})}catch(A){J(A,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail ${f.bold($)} ${w}`),h==="inactive"&&y(f.dim(" writes it was gating now fall through to the other rules."))});St.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,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$});try{await v.guardrailDelete(d)}catch(m){J(m,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(d)} deleted`)}),St.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,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await v.guardrailPostureGet()}catch(C){J(C,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}y(`guardrail posture: ${f.bold(m(A.mode))}`),y(f.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 _=d.trim().toLowerCase();_!=="allow"&&_!=="deny"&&k("posture must be 'allow' or 'deny'.");let E;try{E=await v.guardrailPostureSet(_)}catch(A){J(A,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail posture set to ${f.bold(m(E.mode))}`),E.mode==="deny"&&y(f.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),St.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 h;if(d.fields)try{h=JSON.parse(d.fields)}catch(E){k(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token:$}=await G(d.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await v.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){J(E,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return y(JSON.stringify(m,null,2));let _=`${d.source}/${m.op??d.record}`;m.degraded?(y(`${f.red("\u2717")} ${_} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(f.dim(` ${m.reason}`))):m.allowed?y(`${f.green("\u2713")} ${_} \u2014 ${m.decision}`+(m.blockedBy?f.dim(` (rule ${m.blockedBy})`):f.dim(" (no rule matched)"))):(y(`${f.red("\u2717")} ${_} \u2014 ${m.decision} by ${f.bold(m.blockedBy??"?")} at the ${m.phase} gate`),m.message&&y(f.dim(` ${m.message}`))),m.decision==="require_confirm"&&y(f.yellow(" this write is HELD for operator approval, not refused.")),m.allowed||(process.exitCode=1)});let pr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),ks=(d,h={})=>{let w=`${f.bold(d.table)} ${f.dim(d.displayName)}`;y(d.exists===!1?`${w} ${f.dim("(new)")}`:w);for(let $ of d.fields){let v=[$.required?"required":null].filter(Boolean).join(", "),m=h.showClaimants&&$.claimedBy?.length?` ${f.dim(`\u2190 ${$.claimedBy.join(", ")}`)}`:"";y(` ${$.column.padEnd(28)} ${$.type}${v?` (${v})`:""}${m}`)}h.showClaimants&&d.claimants.length>1&&y(f.dim(` claimed by ${d.claimants.join(", ")}`))};function Ss(d){if(d instanceof Q&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let Dd=async d=>{let h=Qe(se(process.cwd(),d),"public","turbobase.json"),w=await oe.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let $;try{$=JSON.parse(w)}catch(m){k(`${h} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let v=$.tables;return v===void 0?{tables:[],manifestPath:h}:(Array.isArray(v)||k(`${h}: "tables" must be an array.`),{tables:v,manifestPath:h})};pr.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:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w}),v;try{v=await $.tablesList()}catch(m){J(m,"extensions:deploy","list tables"),k(`list tables failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(v,null,2));if(v.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(ht(v.map(m=>[m.table,m.displayName,String(m.fields.length),m.status,m.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),pr.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,h)=>{let w=await Dd(d??".");if(w||k(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:$,token:v}=await G(h.baseUrl),m=new H({baseUrl:$,token:v}),_;try{_=await Z("planning tables",()=>m.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch(E){J(E,"extensions:deploy","plan tables"),Ss(E)}y(`claiming as ${f.bold(_.claimedBy)}`);for(let E of _.tables)ks(E,{showClaimants:!0});y(""),y(f.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),pr.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,h)=>{let w=await Dd(d??".");if(w||k(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:$,token:v}=await G(h.baseUrl),m=new H({baseUrl:$,token:v}),_;try{_=await Z("applying tables",()=>m.tablesApply({claimedBy:h.as,tables:w.tables}))}catch(E){J(E,"extensions:deploy","apply tables"),Ss(E)}for(let E of _.tables)ks(E,{showClaimants:!0});y(`applied ${_.tables.length} table${_.tables.length===1?"":"s"} as ${_.claimedBy}.`)}),pr.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,h)=>[...h??[],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,h)=>{let w=h.field.map(E=>{let[A,C,O]=E.split(":");return(!A||!C)&&k(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&k(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:$,token:v}=await G(h.baseUrl),m=new H({baseUrl:$,token:v}),_;try{_=await Z(`creating cr_${d}`,()=>m.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){J(E,"extensions:deploy","create a table"),Ss(E)}for(let E of _.tables)ks(E);y(""),y(f.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),pr.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,h)=>{h.confirm!==d&&k(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await Z(`dropping cr_${d}`,()=>v.tablesDrop(d,h.confirm))}catch(_){J(_,"extensions:deploy","drop a table"),k(`drop failed: ${_ instanceof Error?_.message:String(_)}`)}if(!m.removed)return y(`no table named "${d}" on this instance \u2014 nothing dropped.`);y(`dropped ${m.table} and every row in it.`)});let Ai=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ai.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 h=Cd(),w;try{w=await th(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch($){$ instanceof Rr&&k($.message),k(`sandbox create failed: ${$ instanceof Error?$.message:String($)}`)}y(`sandbox ${w.name} ready.`),y(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),y(` url: ${w.url}`),y(` expires: ${w.expiresAt}`)}),Ai.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 h=Cd();await Oa(h).catch(()=>[]);let w;try{w=await nh(h,d)}catch($){k(`sandbox destroy failed: ${$ instanceof Error?$.message:String($)}`)}w||k(`no sandbox named '${d}'.`),y(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Ai.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Cd(),h=await Oa(d).catch(()=>[]),w=await to(),{active:$}=Ca(w);if($.length===0)y("no active sandboxes.");else{for(let v of $)y(` ${v.name} from=${v.fromTenant} expires=${v.expiresAt} ${v.url}`);y(`
3724
3724
  ${$.length} active sandbox(es).`)}h.length>0&&y(`(reaped ${h.length} expired sandbox(es).)`)}),s.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.",Ks).action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w}),v;try{v=await Z("exporting instance config",()=>$.configExport())}catch(E){E instanceof Q&&(E.status===401||E.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let m=typeof v.serialized=="string"?v.serialized:`${JSON.stringify(v.manifest??v,null,2)}
3725
3725
  `,_=se(process.cwd(),d.out,kr);await oe.mkdir(Mt(_),{recursive:!0}),await oe.writeFile(_,m,"utf8"),y(`wrote ${d.out}/${kr} (${m.split(`
3726
- `).length} lines).`)});let Ud=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),ly=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Md=()=>process.env.TURBOBASE_HOME?.trim()||Qe(oP(),".turbobase"),cy=()=>"1.23.0",_s=async()=>Promise.all(ly.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Ud.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await _s();for(let h of d)y(`${h.present?Se.success("installed"):Se.warn("missing")} ${f.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
3726
+ `).length} lines).`)});let Ud=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),ly=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Md=()=>process.env.TURBOBASE_HOME?.trim()||Qe(oP(),".turbobase"),cy=()=>"1.23.1",_s=async()=>Promise.all(ly.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Ud.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await _s();for(let h of d)y(`${h.present?Se.success("installed"):Se.warn("missing")} ${f.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
3727
3727
  run \`${_r} ext extras install\` to fetch them into ${Md()}.`)}),Ud.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await _s();if(d.every(A=>A.present)){y(Se.success("extras already installed \u2014 nothing to do."));return}let h=Md();await oe.mkdir(h,{recursive:!0});let w=d.filter(A=>!A.present).map(A=>A.name),$=Ta(process.platform,process.arch),v=async(A,C)=>{let{code:O,stderr:U}=await ws("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&k(`extras install failed while installing ${C} (npm exited ${O}).
3728
3728
  ${U.trim()}
3729
3729
  These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},m=w.filter(A=>A!=="isolated-vm");if(m.length>0){let A=m.map(C=>`${C}@${$a[C]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await v(A,m.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${$a["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await v(["--ignore-scripts",A],"isolated-vm"),Wp.includes($)){let O=`${xa}@${cy()}`;y(`fetching ${O} (no upstream binary for ${$}) \u2026`);let{code:U}=await ws("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);U!==0&&y(Se.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await Jp({home:h});C.length>0&&y(` ${Se.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${$}`)}let _=await _s(),E=_.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){y(Se.warn(`no prebuilt isolated-vm for ${$} / Node ${process.versions.node} (${Ra()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await ws("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(_=await _s(),E=_.filter(C=>!C.present).map(C=>C.name))}E.length>0&&k(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${$} / Node ${process.versions.node} (${Ra()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),y(Se.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Pn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Pn.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 h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let w=await vP(se(process.cwd(),d.project??".")),$=Object.keys(w).length;!d.solution&&$===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let m=(d.ref?await Od(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Od(["rev-parse","HEAD"]),_=d.gitRepo??process.env.GITHUB_REPOSITORY??await Od(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await G(d.baseUrl),U=new H({baseUrl:C,token:O}),I;try{I=await U.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:$>0?w:null,gitRepo:_,gitRef:E,gitSha:m,prUrl:A})}catch(F){J(F,"releases:write","release deploy"),F instanceof Q&&F.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${F instanceof Error?F.message:String(F)}`)}y(`release ${I.releaseId} enqueued \u2192 taskId=${I.taskId} (target=${h}`+($>0?`, uploaded ${$} bundle file(s)`:", live-fetch")+")."),d.follow&&await ga(()=>U.releaseStatus(I.releaseId),`release ${I.releaseId}`,d.intervalMs)}),Pn.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,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await v.releaseFiles(d)}catch(A){A instanceof Q&&A.status===404&&k(`release ${d} not found.`),A instanceof Q&&A.status===409&&k(`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.`),J(A,"releases:write","pull a release"),k(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let _=se(process.cwd(),h.dir),E=0;for(let[A,C]of[["owned",m.owned],["context",m.context]])for(let[O,U]of Object.entries(C)){let I=Qe(_,A,O);await oe.mkdir(Mt(I),{recursive:!0}),await oe.writeFile(I,U,"utf8"),E++}await oe.writeFile(Qe(_,".turbobase-release.json"),JSON.stringify({releaseId:m.releaseId,version:m.version,contentDigest:m.contentDigest},null,2),"utf8"),y(`pulled release ${m.releaseId} (${m.status}) \u2192 ${_}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turbobase/cli",
3
- "version": "1.23.0",
3
+ "version": "1.23.1",
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",