@turbobase/cli 1.48.0 → 1.48.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.
|
@@ -4394,7 +4394,7 @@ ${o.map(yC).join(`
|
|
|
4394
4394
|
`))}async function Qw(t,e,r=Ao){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&x("name at least one skill slug. `turbobase skills list` shows them.");let o=await Co(e,r);if(!await La(`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){re(a,"skills:publish","publish a skill"),x(`publish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(D(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),D(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function e_(t,e,r=Ao){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&x("name at least one skill slug. `turbobase skills list` shows them.");let o=await Co(e,r);if(!await La(`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){re(a,"skills:publish","unpublish a skill"),x(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),D(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(D(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function t_(t,e,r=Ao){let n=Number(t);(!Number.isInteger(n)||n<1)&&x(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await Co(e,r);if(await La(`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){re(i,"skills:publish","roll back a skills release"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function r_(t,e=Ao){let r=await Co(t,e),n;try{n=await ie("reading the releases",()=>r.skillsReleases())}catch(o){re(o,"skills:publish","read the skills releases"),x(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){D("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 n_(t,e,r=Ao){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&x("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await Co(e,r);if(!await La(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
4395
4395
|
${n.join(`
|
|
4396
4396
|
`)}`,"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&&D(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),re(u,"skills:publish","delete a skill"),x(`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&&D(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(D(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as o_}from"node:fs";import{join as lI,relative as uI,resolve as dI,sep as pI}from"node:path";var hI=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),mI=new Set([".mcp.json",".env"]);function fI(t){return mI.has(t)||t.startsWith(".env.")&&t!==".env.example"}function gI(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function yI(t){return t.includes(0)}async function Yu(t){let e=dI(t),r={},n=[],o=[],s=[];async function i(a){let c=await o_.readdir(a,{withFileTypes:!0});for(let l of c){let u=lI(a,l.name);if(hI.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=uI(e,u).split(pI).join("/");if(fI(l.name)){o.push(p);continue}let w=await o_.readFile(u);if(!gI(w)){n.push(p);continue}yI(w)&&s.push(p),r[p]=w.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as bI}from"node:crypto";var wI="/_tb/app-assets",_I=16,vI=/^[0-9a-f]{32}$/;function s_(){return bI(_I).toString("hex")}function xI(t){return vI.test(t)}function i_(t){if(!xI(t))throw new Error(`not a build id: ${t}`);return`${wI}/${t}/`}var a_=7;Qu();var ed=50*1024*1024;import ja from"node:fs/promises";import Ps from"node:path";var td={esbuild:"0.28.1","isolated-vm":"6.1.2"},rd="@turbobase/isolated-vm-prebuilds";function nd(t,e){return`${t}-${e}`}function od(t=process.versions){return`abi${t.modules}`}var c_=["darwin-x64","win32-arm64"];async function l_(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=nd(e,r),o=Ps.join(t.home,"node_modules"),s=Ps.join(o,...rd.split("/"),"prebuilds",n),i=Ps.join(o,"isolated-vm","prebuilds",n),a;try{a=await ja.readdir(s)}catch{return[]}let c=[];await ja.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=Ps.join(i,l);try{await ja.copyFile(Ps.join(s,l),u,ja.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as kI}from"node:os";import{join as u_}from"node:path";import{promises as sd}from"node:fs";function p_(){let t=process.env.TURBOBASE_HOME??u_(kI(),".turbobase");return{dir:t,file:u_(t,"sandboxes.json")}}var SI={s:1e3,m:6e4,h:36e5,d:864e5};function $I(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*SI[e[2]]}function TI(t,e=Date.now()){return new Date(e+$I(t)).toISOString()}function RI(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function EI(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 PI(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 AI="[REDACTED]",As=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},id=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 CI(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new id(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:AI:n[o]=s}return n}function II(t,e,r){return e.map(n=>CI(t,n,r))}var d_=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),OI=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function NI(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 ad(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 OI)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=NI(t);if(!d_.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...d_].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function LI(t,e=jI){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function jI(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function zI(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function DI(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function cd(){let{file:t}=p_();try{let e=await sd.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function h_(t){let{dir:e,file:r}=p_();await sd.mkdir(e,{recursive:!0}),await sd.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
4397
|
-
`,{mode:384})}async function MI(t){let e=await cd();e.push(t),await h_(e)}async function m_(t){let e=await cd(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await h_(e),n??null}async function za(){return cd()}function ld(t,e=Date.now()){let r=[],n=[];for(let o of t)RI(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function f_(t,e){ad(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new As(r);let n=EI(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>LI(l)))(e.fromTenant),i=zI(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=PI(l.rows,n),p=II(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:TI(e.ttl,o),sampleFraction:n,url:DI(s,e.baseUrl)};return await MI(c),c}async function g_(t,e){ad(t.target());let n=(await za()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await m_(e),n):null}async function ud(t,e=Date.now()){ad(t.target());let r=await za(),{expired:n}=ld(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await m_(s.name),o.push(s)}return o}var Cs={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"}},yV=Object.keys(Cs).filter(t=>Cs[t].mintable);var _V=Cs.pat.prefix,UI=Object.entries(Cs).map(([t,e])=>[e.prefix,t]),qI=/^[A-Za-z0-9_-]{20,}$/;function FI(t){if(typeof t!="string")return null;for(let[e,r]of UI)if(t.startsWith(e)&&qI.test(t.slice(e.length)))return r;return null}function y_(t){return FI(t)==="pat"}ys();var BI=8e3,ZI={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 VI(t){return ZI[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function HI(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(BI)})}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 b_(t){return t.state==="accepted"?ot()?g.green("accepted"):"accepted":t.state==="rejected"?ot()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:ot()?g.yellow("unreachable"):"unreachable"}async function w_(t={},e=fetch){let r=await Lr(),{file:n}=ca();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),D(g.dim(`no sign-ins stored in ${n}.`));return}let o=await nr(),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 HI(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(ot())_(Ht(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),b_(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${b_(i.check)} (updated ${i.updatedAt})`);D(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(D(g.red(`${i.baseUrl}: ${VI(i.check.reason)}.`)),D(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"&&D(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||D("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function CF(t){let e=await Lr();e.length===0&&x("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),at()||x("this command needs an explicit <base-url> in a non-interactive shell.");try{return await ct(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{x("cancelled.")}}async function IF(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 OF(t){D(""),D("Sharing is ON. Two things reach the Turbobase product team from this instance:"),D(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),D(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),D(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),D(" about OUR platform, with instance name, user names and ids masked before they leave."),D(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),D("")}async function NF(t,e,r){let n=await Vy({baseUrl:t,token:e}),o=(await Lr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),OF(n.baseUrl),!r)return;let s=await IF(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(D(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),D(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),D(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?D(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):D(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function LF(t){let e=await Su(await vs(t),Zr(t)),r=Uu(e);return r||x(`${t}: ${Fu(e)}`),{...r,sourceCode:e}}async function io(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Zr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function NR(t,e){if(jR(t)!==".gitignore")return io(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return io(t,e.content,e.executable,e.mode);let n=ew(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function Cg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;x(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Ol(t){process.exit(t)}function jF(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 zF(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 DF(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 LR(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function zg({includeInternal:t=!0}={}){let e=new oy;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.48.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Cu()}
|
|
4397
|
+
`,{mode:384})}async function MI(t){let e=await cd();e.push(t),await h_(e)}async function m_(t){let e=await cd(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await h_(e),n??null}async function za(){return cd()}function ld(t,e=Date.now()){let r=[],n=[];for(let o of t)RI(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function f_(t,e){ad(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new As(r);let n=EI(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>LI(l)))(e.fromTenant),i=zI(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=PI(l.rows,n),p=II(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:TI(e.ttl,o),sampleFraction:n,url:DI(s,e.baseUrl)};return await MI(c),c}async function g_(t,e){ad(t.target());let n=(await za()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await m_(e),n):null}async function ud(t,e=Date.now()){ad(t.target());let r=await za(),{expired:n}=ld(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await m_(s.name),o.push(s)}return o}var Cs={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"}},yV=Object.keys(Cs).filter(t=>Cs[t].mintable);var _V=Cs.pat.prefix,UI=Object.entries(Cs).map(([t,e])=>[e.prefix,t]),qI=/^[A-Za-z0-9_-]{20,}$/;function FI(t){if(typeof t!="string")return null;for(let[e,r]of UI)if(t.startsWith(e)&&qI.test(t.slice(e.length)))return r;return null}function y_(t){return FI(t)==="pat"}ys();var BI=8e3,ZI={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 VI(t){return ZI[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function HI(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(BI)})}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 b_(t){return t.state==="accepted"?ot()?g.green("accepted"):"accepted":t.state==="rejected"?ot()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:ot()?g.yellow("unreachable"):"unreachable"}async function w_(t={},e=fetch){let r=await Lr(),{file:n}=ca();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),D(g.dim(`no sign-ins stored in ${n}.`));return}let o=await nr(),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 HI(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(ot())_(Ht(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),b_(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${b_(i.check)} (updated ${i.updatedAt})`);D(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(D(g.red(`${i.baseUrl}: ${VI(i.check.reason)}.`)),D(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"&&D(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||D("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function CF(t){let e=await Lr();e.length===0&&x("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),at()||x("this command needs an explicit <base-url> in a non-interactive shell.");try{return await ct(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{x("cancelled.")}}async function IF(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 OF(t){D(""),D("Sharing is ON. Two things reach the Turbobase product team from this instance:"),D(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),D(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),D(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),D(" about OUR platform, with instance name, user names and ids masked before they leave."),D(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),D("")}async function NF(t,e,r){let n=await Vy({baseUrl:t,token:e}),o=(await Lr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),OF(n.baseUrl),!r)return;let s=await IF(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(D(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),D(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),D(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?D(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):D(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function LF(t){let e=await Su(await vs(t),Zr(t)),r=Uu(e);return r||x(`${t}: ${Fu(e)}`),{...r,sourceCode:e}}async function io(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Zr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function NR(t,e){if(jR(t)!==".gitignore")return io(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return io(t,e.content,e.executable,e.mode);let n=ew(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function Cg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;x(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Ol(t){process.exit(t)}function jF(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 zF(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 DF(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 LR(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function zg({includeInternal:t=!0}={}){let e=new oy;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.48.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Cu()}
|
|
4398
4398
|
`),e.hook("preAction",(d,h)=>{fw(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=Bt(d.baseUrl);d.token||x(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
4399
4399
|
${To} auth login --base-url ${h} --token tb_pat_\u2026`),y_(d.token)||x("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await NF(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=>w_({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 CF("Pick the active instance:"),v=await la(h);if(!v){let T=await Lr();x(`no stored sign-in for ${Bt(h)}.`+(T.length?` Stored: ${T.map(k=>k.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Bt(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 Lr();for(let k of T)await bu(k.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await bu(d.baseUrl);h||x(d.baseUrl?`no stored sign-in for ${Bt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await nr();_(`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 Dn({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)){D("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 Dn({baseUrl:h,token:v,recordsOnly:!0})}catch(E){x(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else x(`types generation failed: ${S}`)}let k=fe(process.cwd(),d.out);await be.writeFile(k,T,"utf8"),_(`wrote ${k} (${T.split(`
|
|
4400
4400
|
`).length} lines).`)}),bw(n),n.command("skills").description("Rewrite the platform's own skills in .claude/skills from this CLI (never the project's own).").option("--dir <path>","Project directory",".").action(d=>{let h=_w(fe(process.cwd(),d.dir));for(let v of h)_(vw(v))}),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 k=T.toString(),y=await fetch(`${h}/v1/catalog/grounding${k?`?${k}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});y.ok||x(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let E=((await y.json()).markdown??"").trim(),I=fe(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. -->
|
|
@@ -4424,7 +4424,7 @@ samples init: ${E} written, ${I} skipped.`)});let Pr=e.command("guardrails").des
|
|
|
4424
4424
|
`+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(Ht(k.map(zR),{head:DR})),_(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),k=new K({baseUrl:v,token:T}),y;try{y=await k.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){re(S,"extensions:deploy","create a guardrail"),x(`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&&x("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T}),y;try{y=await k.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){re(S,"extensions:deploy","edit a guardrail"),x(`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,k)=>{let{baseUrl:y,token:S}=await G(k.baseUrl),E=new K({baseUrl:y,token:S});try{await E.guardrailUpdate(T,{status:h})}catch(I){re(I,"extensions:deploy",`${d} a guardrail`),x(`${d} guardrail failed: ${I instanceof Error?I.message:String(I)}`)}_(`${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),k=new K({baseUrl:v,token:T});try{await k.guardrailDelete(d)}catch(y){re(y,"extensions:deploy","delete a guardrail"),x(`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),k=new K({baseUrl:v,token:T}),y=I=>I==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let I;try{I=await k.guardrailPostureGet()}catch(j){re(j,"extensions:deploy","read the guardrail posture"),x(`read posture failed: ${j instanceof Error?j.message:String(j)}`)}_(`guardrail posture: ${g.bold(y(I.mode))}`),_(g.dim(I.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"&&x("posture must be 'allow' or 'deny'.");let E;try{E=await k.guardrailPostureSet(S)}catch(I){re(I,"extensions:deploy","set the guardrail posture"),x(`set posture failed: ${I instanceof Error?I.message:String(I)}`)}_(`${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){x(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:v,token:T}=await G(d.baseUrl),k=new K({baseUrl:v,token:T}),y;try{y=await k.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){re(E,"extensions:deploy","test guardrails"),x(`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 as=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Mi=(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 k=[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}${k?` (${k})`:""}${y}`)}h.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ui(d){if(d instanceof se&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(D(h.message),process.exit(1))}x(`tables: ${d instanceof Error?d.message:String(d)}`)}let Dg=async d=>{let h=jt(fe(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){x(`${h} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let k=T.tables;return k===void 0?{tables:[],manifestPath:h}:(Array.isArray(k)||x(`${h}: "tables" must be an array.`),{tables:k,manifestPath:h})};as.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}),k;try{k=await T.tablesList()}catch(y){re(y,"extensions:deploy","list tables"),x(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(k,null,2));if(k.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(Ht(k.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),as.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 Dg(d??".");if(v||x(`no public/turbobase.json under ${fe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:k}=await G(h.baseUrl),y=new K({baseUrl:T,token:k}),S;try{S=await ie("planning tables",()=>y.tablesPlan({claimedBy:h.as,tables:v.tables}))}catch(E){re(E,"extensions:deploy","plan tables"),Ui(E)}_(`claiming as ${g.bold(S.claimedBy)}`);for(let E of S.tables)Mi(E,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),as.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 Dg(d??".");if(v||x(`no public/turbobase.json under ${fe(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:k}=await G(h.baseUrl),y=new K({baseUrl:T,token:k}),S;try{S=await ie("applying tables",()=>y.tablesApply({claimedBy:h.as,tables:v.tables}))}catch(E){re(E,"extensions:deploy","apply tables"),Ui(E)}for(let E of S.tables)Mi(E,{showClaimants:!0});_(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),as.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[I,j,M]=E.split(":");return(!I||!j)&&x(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&x(`--field "${E}": the third part may only be "required".`),{name:I,type:j,...M==="required"?{required:!0}:{}}}),{baseUrl:T,token:k}=await G(h.baseUrl),y=new K({baseUrl:T,token:k}),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){re(E,"extensions:deploy","create a table"),Ui(E)}for(let E of S.tables)Mi(E);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),as.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&&x(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:v,token:T}=await G(h.baseUrl),k=new K({baseUrl:v,token:T}),y;try{y=await ie(`dropping cr_${d}`,()=>k.tablesDrop(d,h.confirm))}catch(S){re(S,"extensions:deploy","drop a table"),x(`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 Ll=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ll.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=Og(),v;try{v=await f_(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof As&&x(T.message),x(`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}`)}),Ll.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=Og();await ud(h).catch(()=>[]);let v;try{v=await g_(h,d)}catch(T){x(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}v||x(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),Ll.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Og(),h=await ud(d).catch(()=>[]),v=await za(),{active:T}=ld(v);if(T.length===0)_("no active sandboxes.");else{for(let k of T)_(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);_(`
|
|
4425
4425
|
${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.",$a).action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),k;try{k=await ie("exporting instance config",()=>T.configExport())}catch(E){E instanceof se&&(E.status===401||E.status===403)&&x("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),x(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let y=typeof k.serialized=="string"?k.serialized:`${JSON.stringify(k.manifest??k,null,2)}
|
|
4426
4426
|
`,S=fe(process.cwd(),d.out,$s);await be.mkdir(Zr(S),{recursive:!0}),await be.writeFile(S,y,"utf8"),_(`wrote ${d.out}/${$s} (${y.split(`
|
|
4427
|
-
`).length} lines).`)});let Mg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),MR=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Ug=()=>process.env.TURBOBASE_HOME?.trim()||jt(AF(),".turbobase"),UR=()=>"1.48.
|
|
4427
|
+
`).length} lines).`)});let Mg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),MR=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Ug=()=>process.env.TURBOBASE_HOME?.trim()||jt(AF(),".turbobase"),UR=()=>"1.48.1",qi=async()=>Promise.all(MR.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Mg.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await qi();for(let h of d)_(`${h.present?Ne.success("installed"):Ne.warn("missing")} ${g.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&_(`
|
|
4428
4428
|
run \`${To} ext extras install\` to fetch them into ${Ug()}.`)}),Mg.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await qi();if(d.every(I=>I.present)){_(Ne.success("extras already installed \u2014 nothing to do."));return}let h=Ug();await be.mkdir(h,{recursive:!0});let v=d.filter(I=>!I.present).map(I=>I.name),T=nd(process.platform,process.arch),k=async(I,j)=>{let{code:M,stderr:V}=await zi("npm",["install","--prefix",h,"--no-audit","--no-fund",...I]);M!==0&&x(`extras install failed while installing ${j} (npm exited ${M}).
|
|
4429
4429
|
${V.trim()}
|
|
4430
4430
|
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(I=>I!=="isolated-vm");if(y.length>0){let I=y.map(j=>`${j}@${td[j]??"latest"}`);_(`installing ${I.join(", ")} \u2192 ${h}/node_modules \u2026`),await k(I,y.join(", "))}if(v.includes("isolated-vm")){let I=`isolated-vm@${td["isolated-vm"]}`;if(_(`installing ${I} \u2192 ${h}/node_modules \u2026`),await k(["--ignore-scripts",I],"isolated-vm"),c_.includes(T)){let M=`${rd}@${UR()}`;_(`fetching ${M} (no upstream binary for ${T}) \u2026`);let{code:V}=await zi("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",M]);V!==0&&_(Ne.warn(`could not fetch ${M} \u2014 falling back to a source build.`))}let j=await l_({home:h});j.length>0&&_(` ${Ne.success("prebuilt")} ${j.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await qi(),E=S.filter(I=>!I.present).map(I=>I.name);if(E.includes("isolated-vm")){_(Ne.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${od()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:I}=await zi("npm",["rebuild","--prefix",h,"isolated-vm"]);I===0&&(S=await qi(),E=S.filter(j=>!j.present).map(j=>j.name))}E.length>0&&x(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${od()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(Ne.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let ao=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");ao.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||x(`--target must be 'auto' or 'approved' (got '${d.target}').`);let v=await ZF(fe(process.cwd(),d.project??".")),T=Object.keys(v).length;!d.solution&&T===0&&x("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 Ng(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Ng(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await Ng(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,I=d.prUrl??process.env.PR_URL??null,{baseUrl:j,token:M}=await G(d.baseUrl),V=new K({baseUrl:j,token:M}),F;try{F=await V.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:T>0?v:null,gitRepo:S,gitRef:E,gitSha:y,prUrl:I})}catch(ne){re(ne,"releases:write","release deploy"),ne instanceof se&&ne.status===404&&x("solution_not_found \u2014 no solution with that id."),x(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}_(`release ${F.releaseId} enqueued \u2192 taskId=${F.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Zu(()=>V.releaseStatus(F.releaseId),`release ${F.releaseId}`,d.intervalMs)}),ao.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),k=new K({baseUrl:v,token:T}),y;try{y=await k.releaseFiles(d)}catch(I){I instanceof se&&I.status===404&&x(`release ${d} not found.`),I instanceof se&&I.status===409&&x(`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.`),re(I,"releases:write","pull a release"),x(`release pull failed: ${I instanceof Error?I.message:String(I)}`)}let S=fe(process.cwd(),h.dir),E=0;for(let[I,j]of[["owned",y.owned],["context",y.context]])for(let[M,V]of Object.entries(j)){let F=jt(S,I,M);await be.mkdir(Zr(F),{recursive:!0}),await be.writeFile(F,V,"utf8"),E++}await be.writeFile(jt(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
|
@@ -4347,7 +4347,7 @@ ${o.map(XS).join(`
|
|
|
4347
4347
|
`))}async function nm(e,t,r=Yr){let n=[...new Set(e.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Xr(t,r);if(!await _s(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",t))return;let i;try{i=await X("publishing",()=>o.skillsPublish(n))}catch(a){W(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&&(O(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),O(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function om(e,t,r=Yr){let n=[...new Set(e.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Xr(t,r);if(!await _s(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",t))return;let i;try{i=await X("unpublishing",()=>o.skillsUnpublish(n))}catch(a){W(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.`)),O(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(O(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function sm(e,t,r=Yr){let n=Number(e);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${e}'). \`turbobase skills releases\` lists them.`);let o=await Xr(t,r);if(await _s(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",t))try{let i=await X("rolling back",()=>o.skillsRollback(n));b(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){W(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function im(e,t=Yr){let r=await Xr(e,t),n;try{n=await X("reading the releases",()=>r.skillsReleases())}catch(o){W(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){O("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 am(e,t,r=Yr){let n=[...new Set((e??[]).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 Xr(t,r);if(!await _s(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
4348
4348
|
${n.join(`
|
|
4349
4349
|
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",t))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&&O(m.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),W(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&&O(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(O(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as lm}from"node:fs";import{join as Fk,relative as Hk,resolve as Vk,sep as Kk}from"node:path";var Wk=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),Gk=new Set([".mcp.json",".env"]);function Jk(e){return Gk.has(e)||e.startsWith(".env.")&&e!==".env.example"}function Yk(e){return Buffer.compare(Buffer.from(e.toString("utf8"),"utf8"),e)===0}function Xk(e){return e.includes(0)}async function Ga(e){let t=Vk(e),r={},n=[],o=[],s=[];async function i(a){let l=await lm.readdir(a,{withFileTypes:!0});for(let u of l){let p=Fk(a,u.name);if(Wk.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=Hk(t,p).split(Kk).join("/");if(Jk(u.name)){o.push(g);continue}let x=await lm.readFile(p);if(!Yk(x)){n.push(g);continue}Xk(x)&&s.push(g),r[g]=x.toString("utf8")}}return await i(t),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as Zk}from"node:crypto";var Qk="/_tb/app-assets",ex=16,tx=/^[0-9a-f]{32}$/;function cm(){return Zk(ex).toString("hex")}function rx(e){return tx.test(e)}function dm(e){if(!rx(e))throw new Error(`not a build id: ${e}`);return`${Qk}/${e}/`}var um=7;Ya();var Xa=50*1024*1024;import Ss from"node:fs/promises";import Mn from"node:path";var Za={esbuild:"0.28.1","isolated-vm":"6.1.2"},Qa="@turbobase/isolated-vm-prebuilds";function el(e,t){return`${e}-${t}`}function tl(e=process.versions){return`abi${e.modules}`}var pm=["darwin-x64","win32-arm64"];async function hm(e){let t=e.platform??process.platform,r=e.arch??process.arch,n=el(t,r),o=Mn.join(e.home,"node_modules"),s=Mn.join(o,...Qa.split("/"),"prebuilds",n),i=Mn.join(o,"isolated-vm","prebuilds",n),a;try{a=await Ss.readdir(s)}catch{return[]}let l=[];await Ss.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=Mn.join(i,u);try{await Ss.copyFile(Mn.join(s,u),p,Ss.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as nx}from"node:os";import{join as mm}from"node:path";import{promises as rl}from"node:fs";function gm(){let e=process.env.TURBOBASE_HOME??mm(nx(),".turbobase");return{dir:e,file:mm(e,"sandboxes.json")}}var ox={s:1e3,m:6e4,h:36e5,d:864e5};function sx(e){let t=/^\s*(\d+)\s*([smhd])\s*$/.exec(e);if(!t)throw new Error(`invalid --ttl '${e}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(t[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${e}': duration must be a positive integer.`);return r*ox[t[2]]}function ix(e,t=Date.now()){return new Date(t+sx(e)).toISOString()}function ax(e,t=Date.now()){let r=Date.parse(e);return Number.isNaN(r)?!0:r<=t}function lx(e){let t=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(e);if(!t)throw new Error(`invalid --sample '${e}': expected a percent like 2% (or a bare number).`);let r=Number(t[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${e}': percent must be between 0 and 100.`);return r/100}function cx(e,t){if(t>=1)return[...e];if(t<=0||e.length===0)return[];let r=Math.max(1,Math.round(1/t)),n=[];for(let o=0;o<e.length;o+=r)n.push(e[o]);return n}var dx="[REDACTED]",qn=class extends Error{constructor(t){super(t),this.name="SandboxDataCopyUnavailableError"}},nl=class extends Error{table;column;constructor(t,r,n){super(`Refusing to copy ${t}.${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=t,this.column=r}};function ux(e,t,r){let n={};for(let[o,s]of Object.entries(t)){let i=r[o];if(i===void 0)throw new nl(e,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:dx:n[o]=s}return n}function px(e,t,r){return t.map(n=>ux(e,n,r))}var fm=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),hx=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function mx(e){let t=e.trim();try{let o=new URL(t);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=t.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function ol(e){if(!e||!e.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let t=e.toLowerCase();for(let n of hx)if(t.includes(n))throw new Error(`local-only guard: target '${e}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=mx(e);if(!fm.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...fm].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function fx(e,t=gx){return`sbx-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${t()}`}function gx(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function yx(e){return`turbobase_${e.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function bx(e,t){return`${(t??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(e)}`}async function sl(){let{file:e}=gm();try{let t=await rl.readFile(e,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r:[]}catch(t){if(t.code==="ENOENT")return[];throw t}}async function ym(e){let{dir:t,file:r}=gm();await rl.mkdir(t,{recursive:!0}),await rl.writeFile(r,`${JSON.stringify(e,null,2)}
|
|
4350
|
-
`,{mode:384})}async function wx(e){let t=await sl();t.push(e),await ym(t)}async function bm(e){let t=await sl(),r=t.findIndex(o=>o.name===e);if(r===-1)return null;let[n]=t.splice(r,1);return await ym(t),n??null}async function ks(){return sl()}function il(e,t=Date.now()){let r=[],n=[];for(let o of e)ax(o.expiresAt,t)?n.push(o):r.push(o);return{active:r,expired:n}}async function wm(e,t){ol(e.target());let r=e.dataCopyUnavailable?.();if(r)throw new qn(r);let n=lx(t.sample),o=t.now??Date.now(),s=(t.nameGen??(u=>fx(u)))(t.fromTenant),i=yx(s);await e.createDatabase(i),await e.replayMigrations(i);let a=await e.readSourceTables(t.fromTenant);for(let u of a){let p=cx(u.rows,n),g=px(u.table,p,u.classification);g.length>0&&await e.copyRows(i,u.table,g)}let l={name:s,fromTenant:t.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ix(t.ttl,o),sampleFraction:n,url:bx(s,t.baseUrl)};return await wx(l),l}async function vm(e,t){ol(e.target());let n=(await ks()).find(o=>o.name===t);return n?(await e.dropDatabase(n.database),await bm(t),n):null}async function al(e,t=Date.now()){ol(e.target());let r=await ks(),{expired:n}=il(r,t),o=[];for(let s of n){try{await e.dropDatabase(s.database)}catch{continue}await bm(s.name),o.push(s)}return o}var zn={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"}},rj=Object.keys(zn).filter(e=>zn[e].mintable);var sj=zn.pat.prefix,vx=Object.entries(zn).map(([e,t])=>[t.prefix,e]),_x=/^[A-Za-z0-9_-]{20,}$/;function Sx(e){if(typeof e!="string")return null;for(let[t,r]of vx)if(e.startsWith(t)&&_x.test(e.slice(t.length)))return r;return null}function _m(e){return Sx(e)==="pat"}$n();var kx=8e3,xx={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 Tx(e){return xx[e]??`the instance rejected this token (${e}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Rx(e,t,r=fetch){let n;try{n=await r(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(kx)})}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 Sm(e){return e.state==="accepted"?Oe()?m.green("accepted"):"accepted":e.state==="rejected"?Oe()?m.red(`rejected \xB7 ${e.reason}`):`rejected \xB7 ${e.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function km(e={},t=fetch){let r=await Mt(),{file:n}=Go();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),O(m.dim(`no sign-ins stored in ${n}.`));return}let o=await yt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:e.probe===!1?{state:"accepted"}:await Rx(i.baseUrl,i.token,t)})));if(e.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(lt(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Sm(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Sm(i.check)} (updated ${i.updatedAt})`);O(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(O(m.red(`${i.baseUrl}: ${Tx(i.check.reason)}.`)),O(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"&&O(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||O("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function sI(e){let t=await Mt();t.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(e,t.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function iI(e,t){let r;try{r=await fetch(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,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 aI(e){O(""),O("Sharing is ON. Two things reach the Turbobase product team from this instance:"),O(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),O(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),O(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),O(" about OUR platform, with instance name, user names and ids masked before they leave."),O(`Turn it off: ${e}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),O("")}async function lI(e,t,r){let n=await Ju({baseUrl:e,token:t}),o=(await Mt()).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).`:".")),aI(n.baseUrl),!r)return;let s=await iI(n.baseUrl,t);s.ok||(s.kind==="wrong-host"?(O(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),O(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),O(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?O(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):O(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function cI(e){let t=await _a(await Cn(e),Wt(e)),r=Da(t);return r||v(`${e}: ${Ma(t)}`),{...r,sourceCode:t}}async function Lr(e,t,r,n){try{return await ie.access(e),"skipped"}catch{}return await ie.mkdir(Wt(e),{recursive:!0}),await ie.writeFile(e,t,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(e,n),"wrote"}async function qw(e,t){if(Bw(e)!==".gitignore")return Lr(e,t.content,t.executable,t.mode);let r=await ie.readFile(e,"utf8").catch(()=>null);if(r===null)return Lr(e,t.content,t.executable,t.mode);let n=oh(r);return n===null?"skipped":(await ie.writeFile(e,n,"utf8"),"merged")}function cu(e){if(e!==void 0){if(e==="junit"||e==="json")return e;v(`unknown --reporter '${e}' (expected 'junit' or 'json').`)}}function Yi(e){process.exit(e)}function dI(e){return{name:"turbobase ext test",cases:e.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 uI(e,t){let r=t.warnings.length===0?[{name:`${e} (${t.kind})`,status:"passed"}]:t.warnings.map(n=>({name:`${e}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${e}`,cases:r}}function pI(e){let t=[];if(e.error)return t.push({name:`replay ${e.fixtureName}`,status:"failed",type:"error",detail:e.error}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t};for(let r of e.guards)t.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 e.whenPassed&&e.applyBranch&&t.push({name:`apply-branch: ${e.applyBranch}`,status:"passed",detail:`${e.masterAction??""} (${e.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t}}function zw(e){return`${(Math.ceil(e/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function fu({includeInternal:e=!0}={}){let t=new oI;t.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.48.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),t.addHelpText("beforeAll",d=>d.command.parent?"":`${Ea()}
|
|
4350
|
+
`,{mode:384})}async function wx(e){let t=await sl();t.push(e),await ym(t)}async function bm(e){let t=await sl(),r=t.findIndex(o=>o.name===e);if(r===-1)return null;let[n]=t.splice(r,1);return await ym(t),n??null}async function ks(){return sl()}function il(e,t=Date.now()){let r=[],n=[];for(let o of e)ax(o.expiresAt,t)?n.push(o):r.push(o);return{active:r,expired:n}}async function wm(e,t){ol(e.target());let r=e.dataCopyUnavailable?.();if(r)throw new qn(r);let n=lx(t.sample),o=t.now??Date.now(),s=(t.nameGen??(u=>fx(u)))(t.fromTenant),i=yx(s);await e.createDatabase(i),await e.replayMigrations(i);let a=await e.readSourceTables(t.fromTenant);for(let u of a){let p=cx(u.rows,n),g=px(u.table,p,u.classification);g.length>0&&await e.copyRows(i,u.table,g)}let l={name:s,fromTenant:t.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ix(t.ttl,o),sampleFraction:n,url:bx(s,t.baseUrl)};return await wx(l),l}async function vm(e,t){ol(e.target());let n=(await ks()).find(o=>o.name===t);return n?(await e.dropDatabase(n.database),await bm(t),n):null}async function al(e,t=Date.now()){ol(e.target());let r=await ks(),{expired:n}=il(r,t),o=[];for(let s of n){try{await e.dropDatabase(s.database)}catch{continue}await bm(s.name),o.push(s)}return o}var zn={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"}},rj=Object.keys(zn).filter(e=>zn[e].mintable);var sj=zn.pat.prefix,vx=Object.entries(zn).map(([e,t])=>[t.prefix,e]),_x=/^[A-Za-z0-9_-]{20,}$/;function Sx(e){if(typeof e!="string")return null;for(let[t,r]of vx)if(e.startsWith(t)&&_x.test(e.slice(t.length)))return r;return null}function _m(e){return Sx(e)==="pat"}$n();var kx=8e3,xx={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 Tx(e){return xx[e]??`the instance rejected this token (${e}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Rx(e,t,r=fetch){let n;try{n=await r(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(kx)})}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 Sm(e){return e.state==="accepted"?Oe()?m.green("accepted"):"accepted":e.state==="rejected"?Oe()?m.red(`rejected \xB7 ${e.reason}`):`rejected \xB7 ${e.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function km(e={},t=fetch){let r=await Mt(),{file:n}=Go();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),O(m.dim(`no sign-ins stored in ${n}.`));return}let o=await yt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:e.probe===!1?{state:"accepted"}:await Rx(i.baseUrl,i.token,t)})));if(e.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(lt(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Sm(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Sm(i.check)} (updated ${i.updatedAt})`);O(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(O(m.red(`${i.baseUrl}: ${Tx(i.check.reason)}.`)),O(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"&&O(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||O("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function sI(e){let t=await Mt();t.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(e,t.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function iI(e,t){let r;try{r=await fetch(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,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 aI(e){O(""),O("Sharing is ON. Two things reach the Turbobase product team from this instance:"),O(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),O(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),O(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),O(" about OUR platform, with instance name, user names and ids masked before they leave."),O(`Turn it off: ${e}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),O("")}async function lI(e,t,r){let n=await Ju({baseUrl:e,token:t}),o=(await Mt()).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).`:".")),aI(n.baseUrl),!r)return;let s=await iI(n.baseUrl,t);s.ok||(s.kind==="wrong-host"?(O(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),O(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),O(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?O(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):O(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function cI(e){let t=await _a(await Cn(e),Wt(e)),r=Da(t);return r||v(`${e}: ${Ma(t)}`),{...r,sourceCode:t}}async function Lr(e,t,r,n){try{return await ie.access(e),"skipped"}catch{}return await ie.mkdir(Wt(e),{recursive:!0}),await ie.writeFile(e,t,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(e,n),"wrote"}async function qw(e,t){if(Bw(e)!==".gitignore")return Lr(e,t.content,t.executable,t.mode);let r=await ie.readFile(e,"utf8").catch(()=>null);if(r===null)return Lr(e,t.content,t.executable,t.mode);let n=oh(r);return n===null?"skipped":(await ie.writeFile(e,n,"utf8"),"merged")}function cu(e){if(e!==void 0){if(e==="junit"||e==="json")return e;v(`unknown --reporter '${e}' (expected 'junit' or 'json').`)}}function Yi(e){process.exit(e)}function dI(e){return{name:"turbobase ext test",cases:e.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 uI(e,t){let r=t.warnings.length===0?[{name:`${e} (${t.kind})`,status:"passed"}]:t.warnings.map(n=>({name:`${e}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${e}`,cases:r}}function pI(e){let t=[];if(e.error)return t.push({name:`replay ${e.fixtureName}`,status:"failed",type:"error",detail:e.error}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t};for(let r of e.guards)t.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 e.whenPassed&&e.applyBranch&&t.push({name:`apply-branch: ${e.applyBranch}`,status:"passed",detail:`${e.masterAction??""} (${e.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t}}function zw(e){return`${(Math.ceil(e/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function fu({includeInternal:e=!0}={}){let t=new oI;t.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.48.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),t.addHelpText("beforeAll",d=>d.command.parent?"":`${Ea()}
|
|
4351
4351
|
`),t.hook("preAction",(d,h)=>{wh(t.opts(),h.opts())});let r=t.command("auth").description("Sign in to an instance and manage stored credentials."),n=t.command("project").description("Set up the local project and the files an agent session reads."),o=t.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=t.command("kb").description("Write into the instance's knowledge base."),i=t.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=st(d.baseUrl);d.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
4352
4352
|
${Kr} auth login --base-url ${h} --token tb_pat_\u2026`),_m(d.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await lI(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=>km({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 sI("Pick the active instance:"),w=await Jo(h);if(!w){let T=await Mt();v(`no stored sign-in for ${st(h)}.`+(T.length?` Stored: ${T.map(_=>_.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${st(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 Mt();for(let _ of T)await fa(_.baseUrl);b(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await fa(d.baseUrl);h||v(d.baseUrl?`no stored sign-in for ${st(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await yt();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 B(d.baseUrl),T;try{T=await br({baseUrl:h,token:w,recordsOnly:d.recordsOnly})}catch(f){let S=f instanceof Error?f.message:String(f);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){O("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 br({baseUrl:h,token:w,recordsOnly:!0})}catch(E){v(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else v(`types generation failed: ${S}`)}let _=ne(process.cwd(),d.out);await ie.writeFile(_,T,"utf8"),b(`wrote ${_} (${T.split(`
|
|
4353
4353
|
`).length} lines).`)}),Sh(n),n.command("skills").description("Rewrite the platform's own skills in .claude/skills from this CLI (never the project's own).").option("--dir <path>","Project directory",".").action(d=>{let h=xh(ne(process.cwd(),d.dir));for(let w of h)b(Th(w))}),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 B(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 E=((await f.json()).markdown??"").trim(),A=ne(process.cwd(),d.out),I=d.records?` records=${d.records}`:"",N=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${I} \u2014 do not edit; re-run to refresh. -->
|
|
@@ -4377,7 +4377,7 @@ samples init: ${E} written, ${A} skipped.`)});let Ut=t.command("guardrails").des
|
|
|
4377
4377
|
`+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(lt(_.map(Fw),{head:Hw})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),Ut.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 B(h.baseUrl),_=new z({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(S){W(S,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}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>`))}),Ut.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 B(h.baseUrl),_=new z({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(S){W(S,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}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"]])Ut.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:S}=await B(_.baseUrl),E=new z({baseUrl:f,token:S});try{await E.guardrailUpdate(T,{status:h})}catch(A){W(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."))});Ut.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 B(h.baseUrl),_=new z({baseUrl:w,token:T});try{await _.guardrailDelete(d)}catch(f){W(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`)}),Ut.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 B(h.baseUrl),_=new z({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(I){W(I,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}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 S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&v("posture must be 'allow' or 'deny'.");let E;try{E=await _.guardrailPostureSet(S)}catch(A){W(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(E.mode))}`),E.mode==="deny"&&b(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Ut.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){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token:T}=await B(d.baseUrl),_=new z({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(E){W(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return b(JSON.stringify(f,null,2));let S=`${d.source}/${f.op??d.record}`;f.degraded?(b(`${m.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${f.reason}`))):f.allowed?b(`${m.green("\u2713")} ${S} \u2014 ${f.decision}`+(f.blockedBy?m.dim(` (rule ${f.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${S} \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 xn=t.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),jo=(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 Do(d){if(d instanceof Y&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(O(h.message),process.exit(1))}v(`tables: ${d instanceof Error?d.message:String(d)}`)}let gu=async d=>{let h=nt(ne(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})};xn.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 B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await T.tablesList()}catch(f){W(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(lt(_.map(f=>[f.table,f.displayName,String(f.fields.length),f.status,f.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),xn.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 gu(d??".");if(w||v(`no public/turbobase.json under ${ne(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:_}=await B(h.baseUrl),f=new z({baseUrl:T,token:_}),S;try{S=await X("planning tables",()=>f.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch(E){W(E,"extensions:deploy","plan tables"),Do(E)}b(`claiming as ${m.bold(S.claimedBy)}`);for(let E of S.tables)jo(E,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),xn.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 gu(d??".");if(w||v(`no public/turbobase.json under ${ne(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:_}=await B(h.baseUrl),f=new z({baseUrl:T,token:_}),S;try{S=await X("applying tables",()=>f.tablesApply({claimedBy:h.as,tables:w.tables}))}catch(E){W(E,"extensions:deploy","apply tables"),Do(E)}for(let E of S.tables)jo(E,{showClaimants:!0});b(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),xn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let w=h.field.map(E=>{let[A,I,N]=E.split(":");return(!A||!I)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),N!==void 0&&N!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:A,type:I,...N==="required"?{required:!0}:{}}}),{baseUrl:T,token:_}=await B(h.baseUrl),f=new z({baseUrl:T,token:_}),S;try{S=await X(`creating cr_${d}`,()=>f.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){W(E,"extensions:deploy","create a table"),Do(E)}for(let E of S.tables)jo(E);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),xn.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 B(h.baseUrl),_=new z({baseUrl:w,token:T}),f;try{f=await X(`dropping cr_${d}`,()=>_.tablesDrop(d,h.confirm))}catch(S){W(S,"extensions:deploy","drop a table"),v(`drop failed: ${S instanceof Error?S.message:String(S)}`)}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 Zi=t.command("sandbox").description("Ephemeral local authoring sandboxes.");Zi.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=uu(),w;try{w=await wm(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof qn&&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}`)}),Zi.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=uu();await al(h).catch(()=>[]);let w;try{w=await vm(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}).`)}),Zi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=uu(),h=await al(d).catch(()=>[]),w=await ks(),{active:T}=il(w);if(T.length===0)b("no active sandboxes.");else{for(let _ of T)b(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);b(`
|
|
4378
4378
|
${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.",us).action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await X("exporting instance config",()=>T.configExport())}catch(E){E instanceof Y&&(E.status===401||E.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let f=typeof _.serialized=="string"?_.serialized:`${JSON.stringify(_.manifest??_,null,2)}
|
|
4379
4379
|
`,S=ne(process.cwd(),d.out,Ln);await ie.mkdir(Wt(S),{recursive:!0}),await ie.writeFile(S,f,"utf8"),b(`wrote ${d.out}/${Ln} (${f.split(`
|
|
4380
|
-
`).length} lines).`)});let yu=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Vw=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],bu=()=>process.env.TURBOBASE_HOME?.trim()||nt(nI(),".turbobase"),Kw=()=>"1.48.
|
|
4380
|
+
`).length} lines).`)});let yu=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Vw=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],bu=()=>process.env.TURBOBASE_HOME?.trim()||nt(nI(),".turbobase"),Kw=()=>"1.48.1",Uo=async()=>Promise.all(Vw.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));yu.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Uo();for(let h of d)b(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&b(`
|
|
4381
4381
|
run \`${Kr} ext extras install\` to fetch them into ${bu()}.`)}),yu.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Uo();if(d.every(A=>A.present)){b(ve.success("extras already installed \u2014 nothing to do."));return}let h=bu();await ie.mkdir(h,{recursive:!0});let w=d.filter(A=>!A.present).map(A=>A.name),T=el(process.platform,process.arch),_=async(A,I)=>{let{code:N,stderr:M}=await No("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);N!==0&&v(`extras install failed while installing ${I} (npm exited ${N}).
|
|
4382
4382
|
${M.trim()}
|
|
4383
4383
|
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(I=>`${I}@${Za[I]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await _(A,f.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Za["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${h}/node_modules \u2026`),await _(["--ignore-scripts",A],"isolated-vm"),pm.includes(T)){let N=`${Qa}@${Kw()}`;b(`fetching ${N} (no upstream binary for ${T}) \u2026`);let{code:M}=await No("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",N]);M!==0&&b(ve.warn(`could not fetch ${N} \u2014 falling back to a source build.`))}let I=await hm({home:h});I.length>0&&b(` ${ve.success("prebuilt")} ${I.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await Uo(),E=S.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){b(ve.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${tl()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await No("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(S=await Uo(),E=S.filter(I=>!I.present).map(I=>I.name))}E.length>0&&v(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${tl()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let jr=t.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");jr.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 bI(ne(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 pu(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await pu(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await pu(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:I,token:N}=await B(d.baseUrl),M=new z({baseUrl:I,token:N}),L;try{L=await M.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:T>0?w:null,gitRepo:S,gitRef:E,gitSha:f,prUrl:A})}catch(J){W(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 ${L.releaseId} enqueued \u2192 taskId=${L.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await za(()=>M.releaseStatus(L.releaseId),`release ${L.releaseId}`,d.intervalMs)}),jr.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 B(h.baseUrl),_=new z({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.`),W(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let S=ne(process.cwd(),h.dir),E=0;for(let[A,I]of[["owned",f.owned],["context",f.context]])for(let[N,M]of Object.entries(I)){let L=nt(S,A,N);await ie.mkdir(Wt(L),{recursive:!0}),await ie.writeFile(L,M,"utf8"),E++}await ie.writeFile(nt(S,".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 ${S}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@turbobase/cli",
|
|
3
|
-
"version": "1.48.
|
|
3
|
+
"version": "1.48.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",
|