@turbobase/cli 1.40.0 → 1.40.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.
|
@@ -4177,7 +4177,7 @@ ${o.map(fA).join(`
|
|
|
4177
4177
|
`))}async function Sw(t,e,r=xo){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 So(e,r);if(!await xa(`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 ie("publishing",()=>o.skillsPublish(n))}catch(a){ee(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}_(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 $w(t,e,r=xo){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 So(e,r);if(!await xa(`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 ie("unpublishing",()=>o.skillsUnpublish(n))}catch(a){ee(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}_(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 Tw(t,e,r=xo){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 So(e,r);if(await xa(`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 ie("rolling back",()=>o.skillsRollback(n));_(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){ee(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Rw(t,e=xo){let r=await So(t,e),n;try{n=await ie("reading the releases",()=>r.skillsReleases())}catch(o){ee(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}`:"";_(`${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 Ew(t,e,r=xo){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 So(e,r);if(!await xa(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
4178
4178
|
${n.join(`
|
|
4179
4179
|
`)}`,"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 ie(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof se&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),ee(u,"skills:publish","delete a skill"),k(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&_(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 Pw}from"node:fs";import{join as rC,relative as nC,resolve as oC,sep as sC}from"node:path";var iC=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),aC=new Set([".mcp.json",".env"]);function cC(t){return aC.has(t)||t.startsWith(".env.")&&t!==".env.example"}function lC(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function uC(t){return t.includes(0)}async function Aw(t){let e=oC(t),r={},n=[],o=[],s=[];async function i(a){let c=await Pw.readdir(a,{withFileTypes:!0});for(let l of c){let u=rC(a,l.name);if(iC.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=nC(e,u).split(sC).join("/");if(cC(l.name)){o.push(p);continue}let b=await Pw.readFile(u);if(!lC(b)){n.push(p);continue}uC(b)&&s.push(p),r[p]=b.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as dC}from"node:crypto";var pC="/_tb/app-assets",hC=16,mC=/^[0-9a-f]{32}$/;function Cw(){return dC(hC).toString("hex")}function fC(t){return mC.test(t)}function Iw(t){if(!fC(t))throw new Error(`not a build id: ${t}`);return`${pC}/${t}/`}var Ow=7;Mu();var Uu=50*1024*1024;import Sa from"node:fs/promises";import ks from"node:path";var qu={esbuild:"0.28.1","isolated-vm":"6.1.2"},Fu="@turbobase/isolated-vm-prebuilds";function Bu(t,e){return`${t}-${e}`}function Zu(t=process.versions){return`abi${t.modules}`}var Nw=["darwin-x64","win32-arm64"];async function Lw(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Bu(e,r),o=ks.join(t.home,"node_modules"),s=ks.join(o,...Fu.split("/"),"prebuilds",n),i=ks.join(o,"isolated-vm","prebuilds",n),a;try{a=await Sa.readdir(s)}catch{return[]}let c=[];await Sa.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=ks.join(i,l);try{await Sa.copyFile(ks.join(s,l),u,Sa.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as gC}from"node:os";import{join as jw}from"node:path";import{promises as Vu}from"node:fs";function Dw(){let t=process.env.TURBOBASE_HOME??jw(gC(),".turbobase");return{dir:t,file:jw(t,"sandboxes.json")}}var yC={s:1e3,m:6e4,h:36e5,d:864e5};function bC(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*yC[e[2]]}function wC(t,e=Date.now()){return new Date(e+bC(t)).toISOString()}function _C(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function vC(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 kC(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 xC="[REDACTED]",xs=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Hu=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 SC(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Hu(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:xC:n[o]=s}return n}function $C(t,e,r){return e.map(n=>SC(t,n,r))}var zw=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),TC=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function RC(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Ku(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of TC)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=RC(t);if(!zw.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...zw].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function EC(t,e=PC){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function PC(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function AC(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function CC(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Wu(){let{file:t}=Dw();try{let e=await Vu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Mw(t){let{dir:e,file:r}=Dw();await Vu.mkdir(e,{recursive:!0}),await Vu.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
4180
|
-
`,{mode:384})}async function IC(t){let e=await Wu();e.push(t),await Mw(e)}async function Uw(t){let e=await Wu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Mw(e),n??null}async function $a(){return Wu()}function Gu(t,e=Date.now()){let r=[],n=[];for(let o of t)_C(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function qw(t,e){Ku(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new xs(r);let n=vC(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>EC(l)))(e.fromTenant),i=AC(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=kC(l.rows,n),p=$C(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:wC(e.ttl,o),sampleFraction:n,url:CC(s,e.baseUrl)};return await IC(c),c}async function Fw(t,e){Ku(t.target());let n=(await $a()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Uw(e),n):null}async function Ju(t,e=Date.now()){Ku(t.target());let r=await $a(),{expired:n}=Gu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Uw(s.name),o.push(s)}return o}var Ss={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","rest:read","rest:write","ai:invoke"],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"}},J2=Object.keys(Ss).filter(t=>Ss[t].mintable);var Q2=Ss.pat.prefix,OC=Object.entries(Ss).map(([t,e])=>[e.prefix,t]),NC=/^[A-Za-z0-9_-]{20,}$/;function LC(t){if(typeof t!="string")return null;for(let[e,r]of OC)if(t.startsWith(e)&&NC.test(t.slice(e.length)))return r;return null}function Bw(t){return LC(t)==="pat"}us();var jC=8e3,zC={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 DC(t){return zC[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function MC(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(jC)})}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 Zw(t){return t.state==="accepted"?nt()?g.green("accepted"):"accepted":t.state==="rejected"?nt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:nt()?g.yellow("unreachable"):"unreachable"}async function Vw(t={},e=fetch){let r=await Cr(),{file:n}=Yi();if(r.length===0){_("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 Qt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await MC(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(nt())_(tr(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Zw(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Zw(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}: ${DC(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 mq(t){let e=await Cr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function fq(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 gq(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 yq(t,e,r){let n=await ky({baseUrl:t,token:e}),o=(await Cr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),gq(n.baseUrl),!r)return;let s=await fq(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 bq(t){let e=await hu(await ms(t),Ur(t)),r=Ru(e);return r||k(`${t}: ${Pu(e)}`),{...r,sourceCode:e}}async function to(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Ur(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function BT(t,e){if(VT(t)!==".gitignore")return to(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return to(t,e.content,e.executable,e.mode);let n=Pb(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function pg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function wl(t){process.exit(t)}function wq(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 _q(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 vq(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 ZT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function bg({includeInternal:t=!0}={}){let e=new zg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.40.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${_u()}
|
|
4180
|
+
`,{mode:384})}async function IC(t){let e=await Wu();e.push(t),await Mw(e)}async function Uw(t){let e=await Wu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Mw(e),n??null}async function $a(){return Wu()}function Gu(t,e=Date.now()){let r=[],n=[];for(let o of t)_C(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function qw(t,e){Ku(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new xs(r);let n=vC(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>EC(l)))(e.fromTenant),i=AC(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=kC(l.rows,n),p=$C(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:wC(e.ttl,o),sampleFraction:n,url:CC(s,e.baseUrl)};return await IC(c),c}async function Fw(t,e){Ku(t.target());let n=(await $a()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Uw(e),n):null}async function Ju(t,e=Date.now()){Ku(t.target());let r=await $a(),{expired:n}=Gu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Uw(s.name),o.push(s)}return o}var Ss={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","rest:read","rest:write","ai:invoke"],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"}},J2=Object.keys(Ss).filter(t=>Ss[t].mintable);var Q2=Ss.pat.prefix,OC=Object.entries(Ss).map(([t,e])=>[e.prefix,t]),NC=/^[A-Za-z0-9_-]{20,}$/;function LC(t){if(typeof t!="string")return null;for(let[e,r]of OC)if(t.startsWith(e)&&NC.test(t.slice(e.length)))return r;return null}function Bw(t){return LC(t)==="pat"}us();var jC=8e3,zC={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 DC(t){return zC[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function MC(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(jC)})}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 Zw(t){return t.state==="accepted"?nt()?g.green("accepted"):"accepted":t.state==="rejected"?nt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:nt()?g.yellow("unreachable"):"unreachable"}async function Vw(t={},e=fetch){let r=await Cr(),{file:n}=Yi();if(r.length===0){_("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 Qt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await MC(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(nt())_(tr(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Zw(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Zw(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}: ${DC(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 mq(t){let e=await Cr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function fq(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 gq(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 yq(t,e,r){let n=await ky({baseUrl:t,token:e}),o=(await Cr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),gq(n.baseUrl),!r)return;let s=await fq(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 bq(t){let e=await hu(await ms(t),Ur(t)),r=Ru(e);return r||k(`${t}: ${Pu(e)}`),{...r,sourceCode:e}}async function to(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Ur(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function BT(t,e){if(VT(t)!==".gitignore")return to(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return to(t,e.content,e.executable,e.mode);let n=Pb(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function pg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function wl(t){process.exit(t)}function wq(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 _q(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 vq(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 ZT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function bg({includeInternal:t=!0}={}){let e=new zg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.40.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${_u()}
|
|
4181
4181
|
`),e.hook("preAction",(d,h)=>{Bb(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let h=Ut(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
4182
4182
|
${wo} auth login --base-url ${h} --token tb_pat_\u2026`),Bw(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await yq(h,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=>Vw({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 h=d??await mq("Pick the active instance:"),v=await Xi(h);if(!v){let T=await Cr();k(`no stored sign-in for ${Ut(h)}.`+(T.length?` Stored: ${T.map(x=>x.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Ut(h)} --token tb_pat_\u2026\`.`)}_(`active instance \u2192 ${v.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let T=await Cr();for(let x of T)await au(x.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await au(d.baseUrl);h||k(d.baseUrl?`no stored sign-in for ${Ut(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await Qt();_(`signed out of ${h}.`+(v?` Active instance \u2192 ${v.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T;try{T=await Nn({baseUrl:h,token:v,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 Nn({baseUrl:h,token:v,recordsOnly:!0})}catch(E){k(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else k(`types generation failed: ${S}`)}let x=ge(process.cwd(),d.out);await be.writeFile(x,T,"utf8"),_(`wrote ${x} (${T.split(`
|
|
4183
4183
|
`).length} lines).`)}),Hb(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:h,token:v}=await G(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(`${h}/v1/catalog/grounding${x?`?${x}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});y.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let E=((await y.json()).markdown??"").trim(),O=ge(process.cwd(),d.out),j=d.records?` records=${d.records}`:"",M=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${j} \u2014 do not edit; re-run to refresh. -->
|
|
@@ -4207,7 +4207,7 @@ samples init: ${E} written, ${O} skipped.`)});let pr=e.command("guardrails").des
|
|
|
4207
4207
|
`+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(tr(x.map(vl),{head:HT})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),pr.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:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await x.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(S){ee(S,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),_(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),pr.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:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await x.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(S){ee(S,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,h,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])pr.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(T,x)=>{let{baseUrl:y,token:S}=await G(x.baseUrl),E=new K({baseUrl:y,token:S});try{await E.guardrailUpdate(T,{status:h})}catch(O){ee(O,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${O instanceof Error?O.message:String(O)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(T)} ${v}`),h==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});pr.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:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T});try{await x.guardrailDelete(d)}catch(y){ee(y,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),pr.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:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y=O=>O==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let O;try{O=await x.guardrailPostureGet()}catch(j){ee(j,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${j instanceof Error?j.message:String(j)}`)}_(`guardrail posture: ${g.bold(y(O.mode))}`),_(g.dim(O.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 E;try{E=await x.guardrailPostureSet(S)}catch(O){ee(O,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${O instanceof Error?O.message:String(O)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(E.mode))}`),E.mode==="deny"&&_(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),pr.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:v,token:T}=await G(d.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await x.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){ee(E,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return _(JSON.stringify(y,null,2));let S=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${g.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(g.dim(` ${y.reason}`))):y.allowed?_(`${g.green("\u2713")} ${S} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(_(`${g.red("\u2717")} ${S} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&_(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&_(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let es=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Ai=(d,h={})=>{let v=`${g.bold(d.table)} ${g.dim(d.displayName)}`;_(d.exists===!1?`${v} ${g.dim("(new)")}`:v);for(let T of d.fields){let x=[T.required?"required":null].filter(Boolean).join(", "),y=h.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${x?` (${x})`:""}${y}`)}h.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ci(d){if(d instanceof se&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(q(h.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let wg=async d=>{let h=Ot(ge(process.cwd(),d),"public","turbobase.json"),v=await be.readFile(h,"utf8").catch(()=>null);if(v===null)return null;let T;try{T=JSON.parse(v)}catch(y){k(`${h} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let x=T.tables;return x===void 0?{tables:[],manifestPath:h}:(Array.isArray(x)||k(`${h}: "tables" must be an array.`),{tables:x,manifestPath:h})};es.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:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),x;try{x=await T.tablesList()}catch(y){ee(y,"extensions:deploy","list tables"),k(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(x,null,2));if(x.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(tr(x.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),es.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 v=await wg(d??".");if(v||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:x}=await G(h.baseUrl),y=new K({baseUrl:T,token:x}),S;try{S=await ie("planning tables",()=>y.tablesPlan({claimedBy:h.as,tables:v.tables}))}catch(E){ee(E,"extensions:deploy","plan tables"),Ci(E)}_(`claiming as ${g.bold(S.claimedBy)}`);for(let E of S.tables)Ai(E,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),es.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 v=await wg(d??".");if(v||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:x}=await G(h.baseUrl),y=new K({baseUrl:T,token:x}),S;try{S=await ie("applying tables",()=>y.tablesApply({claimedBy:h.as,tables:v.tables}))}catch(E){ee(E,"extensions:deploy","apply tables"),Ci(E)}for(let E of S.tables)Ai(E,{showClaimants:!0});_(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),es.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 v=h.field.map(E=>{let[O,j,M]=E.split(":");return(!O||!j)&&k(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&k(`--field "${E}": the third part may only be "required".`),{name:O,type:j,...M==="required"?{required:!0}:{}}}),{baseUrl:T,token:x}=await G(h.baseUrl),y=new K({baseUrl:T,token:x}),S;try{S=await ie(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:v,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){ee(E,"extensions:deploy","create a table"),Ci(E)}for(let E of S.tables)Ai(E);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),es.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:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await ie(`dropping cr_${d}`,()=>x.tablesDrop(d,h.confirm))}catch(S){ee(S,"extensions:deploy","drop a table"),k(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let kl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");kl.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=mg(),v;try{v=await qw(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof xs&&k(T.message),k(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}_(`sandbox ${v.name} ready.`),_(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),_(` url: ${v.url}`),_(` expires: ${v.expiresAt}`)}),kl.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=mg();await Ju(h).catch(()=>[]);let v;try{v=await Fw(h,d)}catch(T){k(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}v||k(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),kl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=mg(),h=await Ju(d).catch(()=>[]),v=await $a(),{active:T}=Gu(v);if(T.length===0)_("no active sandboxes.");else{for(let x of T)_(` ${x.name} from=${x.fromTenant} expires=${x.expiresAt} ${x.url}`);_(`
|
|
4208
4208
|
${T.length} active sandbox(es).`)}h.length>0&&_(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",ma).action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),x;try{x=await ie("exporting instance config",()=>T.configExport())}catch(E){E instanceof se&&(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 y=typeof x.serialized=="string"?x.serialized:`${JSON.stringify(x.manifest??x,null,2)}
|
|
4209
4209
|
`,S=ge(process.cwd(),d.out,bs);await be.mkdir(Ur(S),{recursive:!0}),await be.writeFile(S,y,"utf8"),_(`wrote ${d.out}/${bs} (${y.split(`
|
|
4210
|
-
`).length} lines).`)});let _g=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),KT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],vg=()=>process.env.TURBOBASE_HOME?.trim()||Ot(hq(),".turbobase"),WT=()=>"1.40.
|
|
4210
|
+
`).length} lines).`)});let _g=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),KT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],vg=()=>process.env.TURBOBASE_HOME?.trim()||Ot(hq(),".turbobase"),WT=()=>"1.40.1",Ii=async()=>Promise.all(KT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));_g.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ii();for(let h of d)_(`${h.present?Le.success("installed"):Le.warn("missing")} ${g.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&_(`
|
|
4211
4211
|
run \`${wo} ext extras install\` to fetch them into ${vg()}.`)}),_g.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ii();if(d.every(O=>O.present)){_(Le.success("extras already installed \u2014 nothing to do."));return}let h=vg();await be.mkdir(h,{recursive:!0});let v=d.filter(O=>!O.present).map(O=>O.name),T=Bu(process.platform,process.arch),x=async(O,j)=>{let{code:M,stderr:re}=await Pi("npm",["install","--prefix",h,"--no-audit","--no-fund",...O]);M!==0&&k(`extras install failed while installing ${j} (npm exited ${M}).
|
|
4212
4212
|
${re.trim()}
|
|
4213
4213
|
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(O=>O!=="isolated-vm");if(y.length>0){let O=y.map(j=>`${j}@${qu[j]??"latest"}`);_(`installing ${O.join(", ")} \u2192 ${h}/node_modules \u2026`),await x(O,y.join(", "))}if(v.includes("isolated-vm")){let O=`isolated-vm@${qu["isolated-vm"]}`;if(_(`installing ${O} \u2192 ${h}/node_modules \u2026`),await x(["--ignore-scripts",O],"isolated-vm"),Nw.includes(T)){let M=`${Fu}@${WT()}`;_(`fetching ${M} (no upstream binary for ${T}) \u2026`);let{code:re}=await Pi("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",M]);re!==0&&_(Le.warn(`could not fetch ${M} \u2014 falling back to a source build.`))}let j=await Lw({home:h});j.length>0&&_(` ${Le.success("prebuilt")} ${j.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await Ii(),E=S.filter(O=>!O.present).map(O=>O.name);if(E.includes("isolated-vm")){_(Le.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${Zu()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:O}=await Pi("npm",["rebuild","--prefix",h,"isolated-vm"]);O===0&&(S=await Ii(),E=S.filter(j=>!j.present).map(j=>j.name))}E.length>0&&k(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${Zu()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(Le.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let ro=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");ro.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 v=await Rq(ge(process.cwd(),d.project??".")),T=Object.keys(v).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 fg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await fg(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await fg(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,O=d.prUrl??process.env.PR_URL??null,{baseUrl:j,token:M}=await G(d.baseUrl),re=new K({baseUrl:j,token:M}),U;try{U=await re.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:T>0?v:null,gitRepo:S,gitRef:E,gitSha:y,prUrl:O})}catch(ne){ee(ne,"releases:write","release deploy"),ne instanceof se&&ne.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}_(`release ${U.releaseId} enqueued \u2192 taskId=${U.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Cu(()=>re.releaseStatus(U.releaseId),`release ${U.releaseId}`,d.intervalMs)}),ro.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:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await x.releaseFiles(d)}catch(O){O instanceof se&&O.status===404&&k(`release ${d} not found.`),O instanceof se&&O.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.`),ee(O,"releases:write","pull a release"),k(`release pull failed: ${O instanceof Error?O.message:String(O)}`)}let S=ge(process.cwd(),h.dir),E=0;for(let[O,j]of[["owned",y.owned],["context",y.context]])for(let[M,re]of Object.entries(j)){let U=Ot(S,O,M);await be.mkdir(Ur(U),{recursive:!0}),await be.writeFile(U,re,"utf8"),E++}await be.writeFile(Ot(S,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),_(`pulled release ${y.releaseId} (${y.status}) \u2192 ${S}
|
package/dist/turbobase.js
CHANGED
|
@@ -4130,7 +4130,7 @@ ${o.map(J_).join(`
|
|
|
4130
4130
|
`))}async function Eh(t,e,r=Fr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Hr(e,r);if(!await cs(`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 X("publishing",()=>o.skillsPublish(n))}catch(a){V(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Ph(t,e,r=Fr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Hr(e,r);if(!await cs(`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 X("unpublishing",()=>o.skillsUnpublish(n))}catch(a){V(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Ah(t,e,r=Fr){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await Hr(e,r);if(await cs(`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 X("rolling back",()=>o.skillsRollback(n));b(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){V(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Ch(t,e=Fr){let r=await Hr(t,e),n;try{n=await X("reading the releases",()=>r.skillsReleases())}catch(o){V(o,"skills:publish","read the skills releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){L("no releases yet.");return}for(let o of n.items){let s=o.is_current?m.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";b(`${s} v${o.version_no} ${o.skill_count} skill(s) ${m.dim(o.published_at)}${o.published_by?m.dim(` by ${o.published_by}`):""}${m.dim(i)}`)}}async function Ih(t,e,r=Fr){let n=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await Hr(e,r);if(!await cs(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
4131
4131
|
${n.join(`
|
|
4132
4132
|
`)}`,"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 n)try{i.push(await X(`deleting ${u}`,()=>o.skillsDelete(u)))}catch(p){if(p instanceof Y&&p.status===404){a.push(u);continue}i.length>0&&L(m.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),V(p,"skills:publish","delete a skill"),v(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&b(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Oh}from"node:fs";import{join as jS,relative as DS,resolve as US,sep as MS}from"node:path";var qS=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),zS=new Set([".mcp.json",".env"]);function BS(t){return zS.has(t)||t.startsWith(".env.")&&t!==".env.example"}function FS(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function HS(t){return t.includes(0)}async function Nh(t){let e=US(t),r={},n=[],o=[],s=[];async function i(a){let l=await Oh.readdir(a,{withFileTypes:!0});for(let u of l){let p=jS(a,u.name);if(qS.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=DS(e,p).split(MS).join("/");if(BS(u.name)){o.push(g);continue}let S=await Oh.readFile(p);if(!FS(S)){n.push(g);continue}HS(S)&&s.push(g),r[g]=S.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as KS}from"node:crypto";var VS="/_tb/app-assets",GS=16,WS=/^[0-9a-f]{32}$/;function Lh(){return KS(GS).toString("hex")}function JS(t){return WS.test(t)}function jh(t){if(!JS(t))throw new Error(`not a build id: ${t}`);return`${VS}/${t}/`}var Dh=7;ja();var Da=50*1024*1024;import ds from"node:fs/promises";import In from"node:path";var Ua={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ma="@turbobase/isolated-vm-prebuilds";function qa(t,e){return`${t}-${e}`}function za(t=process.versions){return`abi${t.modules}`}var Uh=["darwin-x64","win32-arm64"];async function Mh(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=qa(e,r),o=In.join(t.home,"node_modules"),s=In.join(o,...Ma.split("/"),"prebuilds",n),i=In.join(o,"isolated-vm","prebuilds",n),a;try{a=await ds.readdir(s)}catch{return[]}let l=[];await ds.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=In.join(i,u);try{await ds.copyFile(In.join(s,u),p,ds.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as YS}from"node:os";import{join as qh}from"node:path";import{promises as Ba}from"node:fs";function Bh(){let t=process.env.TURBOBASE_HOME??qh(YS(),".turbobase");return{dir:t,file:qh(t,"sandboxes.json")}}var XS={s:1e3,m:6e4,h:36e5,d:864e5};function ZS(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*XS[e[2]]}function QS(t,e=Date.now()){return new Date(e+ZS(t)).toISOString()}function ek(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function tk(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 rk(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 nk="[REDACTED]",On=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Fa=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 ok(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Fa(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:nk:n[o]=s}return n}function sk(t,e,r){return e.map(n=>ok(t,n,r))}var zh=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),ik=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function ak(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 Ha(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 ik)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=ak(t);if(!zh.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...zh].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function lk(t,e=ck){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function ck(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function dk(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function uk(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ka(){let{file:t}=Bh();try{let e=await Ba.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Fh(t){let{dir:e,file:r}=Bh();await Ba.mkdir(e,{recursive:!0}),await Ba.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
4133
|
-
`,{mode:384})}async function pk(t){let e=await Ka();e.push(t),await Fh(e)}async function Hh(t){let e=await Ka(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Fh(e),n??null}async function us(){return Ka()}function Va(t,e=Date.now()){let r=[],n=[];for(let o of t)ek(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Kh(t,e){Ha(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new On(r);let n=tk(e.sample),o=e.now??Date.now(),s=(e.nameGen??(u=>lk(u)))(e.fromTenant),i=dk(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=rk(u.rows,n),g=sk(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:QS(e.ttl,o),sampleFraction:n,url:uk(s,e.baseUrl)};return await pk(l),l}async function Vh(t,e){Ha(t.target());let n=(await us()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Hh(e),n):null}async function Ga(t,e=Date.now()){Ha(t.target());let r=await us(),{expired:n}=Va(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Hh(s.name),o.push(s)}return o}var Nn={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","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},LN=Object.keys(Nn).filter(t=>Nn[t].mintable);var UN=Nn.pat.prefix,hk=Object.entries(Nn).map(([t,e])=>[e.prefix,t]),mk=/^[A-Za-z0-9_-]{20,}$/;function fk(t){if(typeof t!="string")return null;for(let[e,r]of hk)if(t.startsWith(e)&&mk.test(t.slice(e.length)))return r;return null}function Gh(t){return fk(t)==="pat"}vn();var gk=8e3,yk={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 bk(t){return yk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function wk(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(gk)})}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 Wh(t){return t.state==="accepted"?Oe()?m.green("accepted"):"accepted":t.state==="rejected"?Oe()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function Jh(t={},e=fetch){let r=await Lt(),{file:n}=Do();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${n}.`));return}let o=await ht(),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 wk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(ft(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Wh(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Wh(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${bk(i.check.reason)}.`)),L(m.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function BA(t){let e=await Lt();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function FA(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 HA(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 KA(t,e,r){let n=await Ru({baseUrl:t,token:e}),o=(await Lt()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),HA(n.baseUrl),!r)return;let s=await FA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function VA(t){let e=await da(await Tn(t),Ft(t)),r=Ta(e);return r||v(`${t}: ${Ra(e)}`),{...r,sourceCode:e}}async function Ar(t,e,r,n){try{return await ie.access(t),"skipped"}catch{}return await ie.mkdir(Ft(t),{recursive:!0}),await ie.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(t,n),"wrote"}async function Jb(t,e){if(Xb(t)!==".gitignore")return Ar(t,e.content,e.executable,e.mode);let r=await ie.readFile(t,"utf8").catch(()=>null);if(r===null)return Ar(t,e.content,e.executable,e.mode);let n=Op(r);return n===null?"skipped":(await ie.writeFile(t,n,"utf8"),"merged")}function Hd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function ji(t){process.exit(t)}function GA(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 WA(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 JA(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 Yb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Yd({includeInternal:t=!0}={}){let e=new zA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.40.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${ya()}
|
|
4133
|
+
`,{mode:384})}async function pk(t){let e=await Ka();e.push(t),await Fh(e)}async function Hh(t){let e=await Ka(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Fh(e),n??null}async function us(){return Ka()}function Va(t,e=Date.now()){let r=[],n=[];for(let o of t)ek(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Kh(t,e){Ha(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new On(r);let n=tk(e.sample),o=e.now??Date.now(),s=(e.nameGen??(u=>lk(u)))(e.fromTenant),i=dk(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=rk(u.rows,n),g=sk(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:QS(e.ttl,o),sampleFraction:n,url:uk(s,e.baseUrl)};return await pk(l),l}async function Vh(t,e){Ha(t.target());let n=(await us()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Hh(e),n):null}async function Ga(t,e=Date.now()){Ha(t.target());let r=await us(),{expired:n}=Va(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Hh(s.name),o.push(s)}return o}var Nn={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","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},LN=Object.keys(Nn).filter(t=>Nn[t].mintable);var UN=Nn.pat.prefix,hk=Object.entries(Nn).map(([t,e])=>[e.prefix,t]),mk=/^[A-Za-z0-9_-]{20,}$/;function fk(t){if(typeof t!="string")return null;for(let[e,r]of hk)if(t.startsWith(e)&&mk.test(t.slice(e.length)))return r;return null}function Gh(t){return fk(t)==="pat"}vn();var gk=8e3,yk={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 bk(t){return yk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function wk(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(gk)})}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 Wh(t){return t.state==="accepted"?Oe()?m.green("accepted"):"accepted":t.state==="rejected"?Oe()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function Jh(t={},e=fetch){let r=await Lt(),{file:n}=Do();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${n}.`));return}let o=await ht(),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 wk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(ft(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Wh(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Wh(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${bk(i.check.reason)}.`)),L(m.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function BA(t){let e=await Lt();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function FA(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 HA(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 KA(t,e,r){let n=await Ru({baseUrl:t,token:e}),o=(await Lt()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),HA(n.baseUrl),!r)return;let s=await FA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function VA(t){let e=await da(await Tn(t),Ft(t)),r=Ta(e);return r||v(`${t}: ${Ra(e)}`),{...r,sourceCode:e}}async function Ar(t,e,r,n){try{return await ie.access(t),"skipped"}catch{}return await ie.mkdir(Ft(t),{recursive:!0}),await ie.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(t,n),"wrote"}async function Jb(t,e){if(Xb(t)!==".gitignore")return Ar(t,e.content,e.executable,e.mode);let r=await ie.readFile(t,"utf8").catch(()=>null);if(r===null)return Ar(t,e.content,e.executable,e.mode);let n=Op(r);return n===null?"skipped":(await ie.writeFile(t,n,"utf8"),"merged")}function Hd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function ji(t){process.exit(t)}function GA(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 WA(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 JA(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 Yb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Yd({includeInternal:t=!0}={}){let e=new zA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.40.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${ya()}
|
|
4134
4134
|
`),e.hook("preAction",(d,h)=>{Gp(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let h=rt(d.baseUrl);d.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
4135
4135
|
${Mr} auth login --base-url ${h} --token tb_pat_\u2026`),Gh(d.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await KA(h,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=>Jh({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 h=d??await BA("Pick the active instance:"),w=await Uo(h);if(!w){let T=await Lt();v(`no stored sign-in for ${rt(h)}.`+(T.length?` Stored: ${T.map(_=>_.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${rt(h)} --token tb_pat_\u2026\`.`)}b(`active instance \u2192 ${w.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 Lt();for(let _ of T)await oa(_.baseUrl);b(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await oa(d.baseUrl);h||v(d.baseUrl?`no stored sign-in for ${rt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await ht();b(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.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:h,token:w}=await z(d.baseUrl),T;try{T=await mr({baseUrl:h,token:w,recordsOnly:d.recordsOnly})}catch(f){let k=f instanceof Error?f.message:String(f);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(k)){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{T=await mr({baseUrl:h,token:w,recordsOnly:!0})}catch($){v(`types generation failed: ${$ instanceof Error?$.message:String($)}`)}}else v(`types generation failed: ${k}`)}let _=oe(process.cwd(),d.out);await ie.writeFile(_,T,"utf8"),b(`wrote ${_} (${T.split(`
|
|
4136
4136
|
`).length} lines).`)}),Yp(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:h,token:w}=await z(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let _=T.toString(),f=await fetch(`${h}/v1/catalog/grounding${_?`?${_}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});f.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${f.status}`);let $=((await f.json()).markdown??"").trim(),A=oe(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. -->
|
|
@@ -4160,7 +4160,7 @@ samples init: ${$} written, ${A} skipped.`)});let xt=e.command("guardrails").des
|
|
|
4160
4160
|
`+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ft(_.map(Ui),{head:Zb})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),xt.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:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.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(k){V(k,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${k instanceof Error?k.message:String(k)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} created${f.status==="active"?"":m.dim(` (${f.status} \u2014 activate it to take effect)`)}`),b(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.actor?` actor=${f.actor}`:""}${f.when?` where ${f.when}`:""} @prio ${f.priority}`)),b(m.dim(` verify with: turbobase guardrails test --source ${f.source==="*"?"<source>":f.source} --record <record>`))}),xt.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&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.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(k){V(k,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${k instanceof Error?k.message:String(k)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} updated`),b(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.when?` where ${f.when}`:""} @prio ${f.priority}`))});for(let[d,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])xt.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(T,_)=>{let{baseUrl:f,token:k}=await z(_.baseUrl),$=new q({baseUrl:f,token:k});try{await $.guardrailUpdate(T,{status:h})}catch(A){V(A,"extensions:deploy",`${d} a guardrail`),v(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(T)} ${w}`),h==="inactive"&&b(m.dim(" writes it was gating now fall through to the other rules."))});xt.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:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T});try{await _.guardrailDelete(d)}catch(f){V(f,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${f instanceof Error?f.message:String(f)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(d)} deleted`)}),xt.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:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await _.guardrailPostureGet()}catch(C){V(C,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}b(`guardrail posture: ${m.bold(f(A.mode))}`),b(m.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let k=d.trim().toLowerCase();k!=="allow"&&k!=="deny"&&v("posture must be 'allow' or 'deny'.");let $;try{$=await _.guardrailPostureSet(k)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail posture set to ${m.bold(f($.mode))}`),$.mode==="deny"&&b(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),xt.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($){v(`--fields must be valid JSON: ${$ instanceof Error?$.message:String($)}`)}let{baseUrl:w,token:T}=await z(d.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.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($){V($,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${$ instanceof Error?$.message:String($)}`)}if(d.json)return b(JSON.stringify(f,null,2));let k=`${d.source}/${f.op??d.record}`;f.degraded?(b(`${m.red("\u2717")} ${k} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${f.reason}`))):f.allowed?b(`${m.green("\u2713")} ${k} \u2014 ${f.decision}`+(f.blockedBy?m.dim(` (rule ${f.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${k} \u2014 ${f.decision} by ${m.bold(f.blockedBy??"?")} at the ${f.phase} gate`),f.message&&b(m.dim(` ${f.message}`))),f.decision==="require_confirm"&&b(m.yellow(" this write is HELD for operator approval, not refused.")),f.allowed||(process.exitCode=1)});let yn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),$o=(d,h={})=>{let w=`${m.bold(d.table)} ${m.dim(d.displayName)}`;b(d.exists===!1?`${w} ${m.dim("(new)")}`:w);for(let T of d.fields){let _=[T.required?"required":null].filter(Boolean).join(", "),f=h.showClaimants&&T.claimedBy?.length?` ${m.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";b(` ${T.column.padEnd(28)} ${T.type}${_?` (${_})`:""}${f}`)}h.showClaimants&&d.claimants.length>1&&b(m.dim(` claimed by ${d.claimants.join(", ")}`))};function Eo(d){if(d instanceof Y&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}v(`tables: ${d instanceof Error?d.message:String(d)}`)}let Xd=async d=>{let h=et(oe(process.cwd(),d),"public","turbobase.json"),w=await ie.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let T;try{T=JSON.parse(w)}catch(f){v(`${h} is not valid JSON: ${f instanceof Error?f.message:String(f)}`)}let _=T.tables;return _===void 0?{tables:[],manifestPath:h}:(Array.isArray(_)||v(`${h}: "tables" must be an array.`),{tables:_,manifestPath:h})};yn.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 z(d.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.tablesList()}catch(f){V(f,"extensions:deploy","list tables"),v(`list tables failed: ${f instanceof Error?f.message:String(f)}`)}if(d.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ft(_.map(f=>[f.table,f.displayName,String(f.fields.length),f.status,f.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),yn.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 Xd(d??".");if(w||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:_}=await z(h.baseUrl),f=new q({baseUrl:T,token:_}),k;try{k=await X("planning tables",()=>f.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch($){V($,"extensions:deploy","plan tables"),Eo($)}b(`claiming as ${m.bold(k.claimedBy)}`);for(let $ of k.tables)$o($,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),yn.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 Xd(d??".");if(w||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:_}=await z(h.baseUrl),f=new q({baseUrl:T,token:_}),k;try{k=await X("applying tables",()=>f.tablesApply({claimedBy:h.as,tables:w.tables}))}catch($){V($,"extensions:deploy","apply tables"),Eo($)}for(let $ of k.tables)$o($,{showClaimants:!0});b(`applied ${k.tables.length} table${k.tables.length===1?"":"s"} as ${k.claimedBy}.`)}),yn.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($=>{let[A,C,O]=$.split(":");return(!A||!C)&&v(`--field "${$}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&v(`--field "${$}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:T,token:_}=await z(h.baseUrl),f=new q({baseUrl:T,token:_}),k;try{k=await X(`creating cr_${d}`,()=>f.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch($){V($,"extensions:deploy","create a table"),Eo($)}for(let $ of k.tables)$o($);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),yn.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&&v(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await X(`dropping cr_${d}`,()=>_.tablesDrop(d,h.confirm))}catch(k){V(k,"extensions:deploy","drop a table"),v(`drop failed: ${k instanceof Error?k.message:String(k)}`)}if(!f.removed)return b(`no table named "${d}" on this instance \u2014 nothing dropped.`);b(`dropped ${f.table} and every row in it.`)});let Mi=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Mi.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=Vd(),w;try{w=await Kh(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof On&&v(T.message),v(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}b(`sandbox ${w.name} ready.`),b(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),b(` url: ${w.url}`),b(` expires: ${w.expiresAt}`)}),Mi.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=Vd();await Ga(h).catch(()=>[]);let w;try{w=await Vh(h,d)}catch(T){v(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}w||v(`no sandbox named '${d}'.`),b(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Mi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Vd(),h=await Ga(d).catch(()=>[]),w=await us(),{active:T}=Va(w);if(T.length===0)b("no active sandboxes.");else{for(let _ of T)b(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);b(`
|
|
4161
4161
|
${T.length} active sandbox(es).`)}h.length>0&&b(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",es).action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await X("exporting instance config",()=>T.configExport())}catch($){$ instanceof Y&&($.status===401||$.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${$ instanceof Error?$.message:String($)}`)}let f=typeof _.serialized=="string"?_.serialized:`${JSON.stringify(_.manifest??_,null,2)}
|
|
4162
4162
|
`,k=oe(process.cwd(),d.out,En);await ie.mkdir(Ft(k),{recursive:!0}),await ie.writeFile(k,f,"utf8"),b(`wrote ${d.out}/${En} (${f.split(`
|
|
4163
|
-
`).length} lines).`)});let Zd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Qb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Qd=()=>process.env.TURBOBASE_HOME?.trim()||et(qA(),".turbobase"),ew=()=>"1.40.
|
|
4163
|
+
`).length} lines).`)});let Zd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Qb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Qd=()=>process.env.TURBOBASE_HOME?.trim()||et(qA(),".turbobase"),ew=()=>"1.40.1",Po=async()=>Promise.all(Qb.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Zd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Po();for(let h of d)b(`${h.present?_e.success("installed"):_e.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&b(`
|
|
4164
4164
|
run \`${Mr} ext extras install\` to fetch them into ${Qd()}.`)}),Zd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Po();if(d.every(A=>A.present)){b(_e.success("extras already installed \u2014 nothing to do."));return}let h=Qd();await ie.mkdir(h,{recursive:!0});let w=d.filter(A=>!A.present).map(A=>A.name),T=qa(process.platform,process.arch),_=async(A,C)=>{let{code:O,stderr:W}=await Ro("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&v(`extras install failed while installing ${C} (npm exited ${O}).
|
|
4165
4165
|
${W.trim()}
|
|
4166
4166
|
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},f=w.filter(A=>A!=="isolated-vm");if(f.length>0){let A=f.map(C=>`${C}@${Ua[C]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await _(A,f.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Ua["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${h}/node_modules \u2026`),await _(["--ignore-scripts",A],"isolated-vm"),Uh.includes(T)){let O=`${Ma}@${ew()}`;b(`fetching ${O} (no upstream binary for ${T}) \u2026`);let{code:W}=await Ro("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);W!==0&&b(_e.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await Mh({home:h});C.length>0&&b(` ${_e.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let k=await Po(),$=k.filter(A=>!A.present).map(A=>A.name);if($.includes("isolated-vm")){b(_e.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${za()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await Ro("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(k=await Po(),$=k.filter(C=>!C.present).map(C=>C.name))}$.length>0&&v(`npm succeeded but ${$.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${za()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(_e.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Cr=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");Cr.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||v(`--target must be 'auto' or 'approved' (got '${d.target}').`);let w=await tC(oe(process.cwd(),d.project??".")),T=Object.keys(w).length;!d.solution&&T===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let f=(d.ref?await Gd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Gd(["rev-parse","HEAD"]),k=d.gitRepo??process.env.GITHUB_REPOSITORY??await Gd(["remote","get-url","origin"]),$=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await z(d.baseUrl),W=new q({baseUrl:C,token:O}),N;try{N=await W.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:T>0?w:null,gitRepo:k,gitRef:$,gitSha:f,prUrl:A})}catch(J){V(J,"releases:write","release deploy"),J instanceof Y&&J.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${J instanceof Error?J.message:String(J)}`)}b(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Ea(()=>W.releaseStatus(N.releaseId),`release ${N.releaseId}`,d.intervalMs)}),Cr.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:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.releaseFiles(d)}catch(A){A instanceof Y&&A.status===404&&v(`release ${d} not found.`),A instanceof Y&&A.status===409&&v(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),V(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let k=oe(process.cwd(),h.dir),$=0;for(let[A,C]of[["owned",f.owned],["context",f.context]])for(let[O,W]of Object.entries(C)){let N=et(k,A,O);await ie.mkdir(Ft(N),{recursive:!0}),await ie.writeFile(N,W,"utf8"),$++}await ie.writeFile(et(k,".turbobase-release.json"),JSON.stringify({releaseId:f.releaseId,version:f.version,contentDigest:f.contentDigest},null,2),"utf8"),b(`pulled release ${f.releaseId} (${f.status}) \u2192 ${k}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@turbobase/cli",
|
|
3
|
-
"version": "1.40.
|
|
3
|
+
"version": "1.40.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",
|