@tiptap/cli 3.10.7 → 3.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +17 -17
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import jo from"path";import{Command as _o}from"commander";import{z as le}from"zod";import{createPrompt as Ln,useState as tt,useKeypress as Mn,usePrefix as Bn,usePagination as Wn,useRef as Rt,useMemo as nt,useEffect as zn,isBackspaceKey as Kn,isEnterKey as Vn,isUpKey as rt,isDownKey as Nt,isNumberKey as Jn,Separator as Ae,ValidationError as qn,makeTheme as Yn}from"@inquirer/core";import jt from"yoctocolors-cjs";import Gn from"@inquirer/figures";import Hn from"ansi-escapes";import{Separator as As}from"@inquirer/core";var Xn={icon:{cursor:Gn.pointer},style:{disabled:e=>jt.dim(`- ${e}`),description:e=>jt.cyan(e)},indexMode:"hidden"};function pe(e){return!Ae.isSeparator(e)&&!e.disabled}function Zn(e){return e.map(t=>{if(Ae.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let n=t.name??String(t.value),r={value:t.value,name:n,short:t.short??n,disabled:t.disabled??!1};return t.description&&(r.description=t.description),r})}var Pe=Ln((e,t)=>{let{loop:n=!0,pageSize:r=7,instructions:s}=e,i=Rt(!0),c=Yn(Xn,e.theme),[l
|
|
3
|
-
${c.style.description(
|
|
4
|
-
${g}${m}${v}${Hn.cursorHide}`});import{Separator as xe,input as Oo,confirm as kl,checkbox as Fo}from"@inquirer/prompts";import mr from"path";import B from"path";import{createMatchPath as Qn}from"tsconfig-paths";async function O(e,t){return Qn(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as sr}from"cosmiconfig";import ir from"fast-glob";import{loadConfig as ar}from"tsconfig-paths";import{z as E}from"zod";import Ot from"path";var u={"next-app":{name:"next-app",label:"Next.js",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}},"next-pages":{name:"next-pages",label:"Next.js",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}},"react-router":{name:"react-router",label:"React Router",links:{installation:"https://tiptap.dev/docs/ui-components/install/react-router"}},vite:{name:"vite",label:"Vite",links:{installation:"https://tiptap.dev/docs/ui-components/install/vite"}},astro:{name:"astro",label:"Astro",links:{installation:"https://tiptap.dev/docs/ui-components/install/astro"}},laravel:{name:"laravel",label:"Laravel",links:{installation:"https://tiptap.dev/docs/ui-components/install/laravel"}},"tanstack-start":{name:"tanstack-start",label:"TanStack Start",links:{installation:"https://tiptap.dev/docs/ui-components/install/tanstack"}},manual:{name:"manual",label:"Manual",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}}};import er from"path";import tr from"fs-extra";function _t(e="",t=!0){let n=er.join(e,"package.json");return tr.readJSONSync(n,{throws:t})}import Ut from"fast-glob";import Ft from"fs-extra";import{loadConfig as nr}from"tsconfig-paths";var Dt=["**/node_modules/**",".next","public","dist","build"];async function D(e){let[t,n,r,s,i]=await Promise.all([Ut.glob("**/{next,vite,astro,app}.config.*|gatsby-config.*|composer.json|react-router.config.*",{cwd:e,deep:3,ignore:Dt}),Ft.pathExists(Ot.resolve(e,"src")),or(e),rr(e),_t(e,!1)]),c=await Ft.pathExists(Ot.resolve(e,`${n?"src/":""}app`)),l={framework:u.manual,isSrcDir:n,isRSC:!1,isTsx:r,aliasPrefix:s};return t.find(p=>p.startsWith("next.config."))?.length?(l.framework=c?u["next-app"]:u["next-pages"],l.isRSC=c,l):t.find(p=>p.startsWith("astro.config."))?.length?(l.framework=u.astro,l):t.find(p=>p.startsWith("composer.json"))?.length?(l.framework=u.laravel,l):t.find(p=>p.startsWith("app.config."))?.length&&[...Object.keys(i?.dependencies??{}),...Object.keys(i?.devDependencies??{})].find(p=>p.startsWith("@tanstack/start"))?(l.framework=u["tanstack-start"],l):t.find(p=>p.startsWith("react-router.config."))?.length?(l.framework=u["react-router"],l):(t.find(p=>p.startsWith("vite.config."))?.length&&(l.framework=u.vite),l)}async function rr(e){let t=await nr(e);if(t?.resultType==="failed"||!Object.entries(t?.paths).length)return null;for(let[n,r]of Object.entries(t.paths))if(r.includes("./*")||r.includes("./src/*")||r.includes("./app/*")||r.includes("./resources/js/*"))return n.replace(/\/\*$/,"")??null;return Object.keys(t?.paths)?.[0].replace(/\/\*$/,"")??null}async function or(e){return(await Ut.glob("tsconfig.*",{cwd:e,deep:1,ignore:Dt})).length>0}async function Lt(e,t=null){let[n,r]=await Promise.all([Y(e),t?Promise.resolve(t):D(e)]);if(n)return n;if(!r)return null;let s={rsc:r.isRSC,tsx:r.isTsx,aliases:{components:`${r.aliasPrefix}/components`,contexts:`${r.aliasPrefix}/contexts`,hooks:`${r.aliasPrefix}/hooks`,tiptapIcons:`${r.aliasPrefix}/components/tiptap-icons`,lib:`${r.aliasPrefix}/lib`,tiptapExtensions:`${r.aliasPrefix}/components/tiptap-extensions`,tiptapNodes:`${r.aliasPrefix}/components/tiptap-nodes`,tiptapUi:`${r.aliasPrefix}/components/tiptap-ui`,tiptapUiPrimitives:`${r.aliasPrefix}/components/tiptap-ui-primitives`,tiptapUiUtils:`${r.aliasPrefix}/components/tiptap-ui-utils`,styles:`${r.aliasPrefix}/styles`}};return await re(e,s)}var ot="@/components",st="@/contexts",it="@/hooks",at="@/components/tiptap-icons",$e="@/lib",ct="@/components/tiptap-extension",lt="@/components/tiptap-node",pt="@/components/tiptap-ui",mt="@/components/tiptap-ui-primitive",dt="@/components/tiptap-ui-utils",ft="@/styles",cr=sr("components",{searchPlaces:["components.json"]}),oe=E.object({rsc:E.coerce.boolean().default(!1),tsx:E.coerce.boolean().default(!0),aliases:E.object({components:E.string(),contexts:E.string().optional(),hooks:E.string().optional(),tiptapIcons:E.string().optional(),lib:E.string().optional(),tiptapExtensions:E.string().optional(),tiptapNodes:E.string().optional(),tiptapUi:E.string().optional(),tiptapUiPrimitives:E.string().optional(),tiptapUiUtils:E.string().optional(),styles:E.string().optional()})}),Mt=oe.extend({resolvedPaths:E.object({cwd:E.string(),components:E.string(),contexts:E.string(),hooks:E.string(),tiptapIcons:E.string(),lib:E.string(),tiptapExtensions:E.string(),tiptapNodes:E.string(),tiptapUi:E.string(),tiptapUiPrimitives:E.string(),tiptapUiUtils:E.string(),styles:E.string()})}),lr=E.record(Mt);async function Y(e){let t=await cr.search(e),n=await D(e),r={components:ot,contexts:st,hooks:it,tiptapIcons:at,lib:$e,tiptapExtensions:ct,tiptapNodes:lt,tiptapUi:pt,tiptapUiPrimitives:mt,tiptapUiUtils:dt,styles:ft},s=(c,l)=>Object.fromEntries(Object.entries(c).map(([p,w])=>[p,w.replace(/^@/,l)])),i;if(t){let c={...r,...t.config.aliases};n?.aliasPrefix?i=oe.parse({...t.config,aliases:s(c,n.aliasPrefix)}):i=oe.parse({...t.config,aliases:c})}else{let c=r;n?.aliasPrefix&&(c=s(c,n.aliasPrefix)),i=oe.parse({rsc:n?.isRSC??!1,tsx:n?.isTsx??!0,aliases:c})}return await re(e,i)}async function re(e,t){let n=await ar(e);if(n.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${n.message??""}`.trim());return Mt.parse({...t,resolvedPaths:{cwd:e,components:await O(t.aliases.components,n),contexts:t.aliases.contexts?await O(t.aliases.contexts,n):B.resolve(await O(t.aliases.components,n)??e,"..","contexts"),hooks:t.aliases.hooks?await O(t.aliases.hooks,n):B.resolve(await O(t.aliases.components,n)??e,"..","hooks"),tiptapIcons:t.aliases.tiptapIcons?await O(t.aliases.tiptapIcons,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-icons"),lib:t.aliases.lib?await O(t.aliases.lib,n):B.resolve(await O($e,n)??e,".."),tiptapExtensions:t.aliases.tiptapExtensions?await O(t.aliases.tiptapExtensions,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-extension"),tiptapNodes:t.aliases.tiptapNodes?await O(t.aliases.tiptapNodes,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-node"),tiptapUi:t.aliases.tiptapUi?await O(t.aliases.tiptapUi,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-ui"),tiptapUiPrimitives:t.aliases.tiptapUiPrimitives?await O(t.aliases.tiptapUiPrimitives,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-ui-primitive"),tiptapUiUtils:t.aliases.tiptapUiUtils?await O(t.aliases.tiptapUiUtils,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-ui-utils"),styles:t.aliases.styles?await O(t.aliases.styles,n):B.resolve(e,"styles")}})}async function Bt(e){let t={};for(let r of Object.keys(e.aliases)){if(!pr(r,e))continue;let s=e.resolvedPaths[r],i=await ut(e.resolvedPaths.cwd,s);if(!i){t[r]=e;continue}t[r]=await Y(i)}let n=lr.safeParse(t);return n.success?n.data:null}async function ut(e,t){let n=gt(e,t),r=B.relative(n,t),i=(await ir.glob("**/package.json",{cwd:n,deep:3,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/public/**"]})).map(c=>B.dirname(c)).find(c=>r.startsWith(c));return i?B.join(n,i):null}function pr(e,t){return Object.keys(t.resolvedPaths).includes(e)}function gt(e,t){let n=e.split(B.sep),r=t.split(B.sep),s=[];for(let i=0;i<Math.min(n.length,r.length)&&n[i]===r[i];i++)s.push(n[i]);return s.join(B.sep)}import V from"chalk";var a={cyan:V.cyan,magenta:V.magenta,gray:V.gray,white:V.white,yellow:V.yellow,green:V.green,red:V.red,blue:V.blue,reset:V.reset,dim:V.dim,bold:V.bold,whiteBold:V.white.bold};var ve=e=>e.map(String).join(" "),o={error(...e){console.log(a.red(ve(e)))},warn(...e){console.log(a.yellow(ve(e)))},info(...e){console.log(a.cyan(ve(e)))},success(...e){console.log(a.green(ve(e)))},log(...e){console.log(ve(e))},break(){console.log("")}};import Wt from"fs-extra";async function zt(e){let t={};if(!Wt.existsSync(e.cwd)||!Wt.existsSync(mr.resolve(e.cwd,"package.json")))return t["1"]=!0,{errors:t,config:null};try{let n=await Y(e.cwd);return{errors:t,config:n}}catch(n){console.log("[preFlightAdd] - ",n),o.break(),o.error(`Make sure you are in a valid project directory. Run ${a.cyan("npx @tiptap/cli init")} to create a new project.`),o.break(),process.exit(0)}}import de from"path";import{z as dr}from"zod";function _(e){if(o.error("Something went wrong. Please check the error below for more details."),o.error("If the problem persists, please open an issue on GitHub."),o.error(""),typeof e=="string"&&(o.error(e),o.break(),process.exit(0)),e instanceof dr.ZodError){o.error("Validation failed:");for(let[t,n]of Object.entries(e.flatten().fieldErrors))o.error(`- ${a.cyan(t)}: ${n}`);o.break(),process.exit(0)}e instanceof Error&&(o.error(e.message),o.break(),process.exit(0)),o.break(),process.exit(0)}import{z as R}from"zod";var Kt=R.enum(["registry:context","registry:extension","registry:hook","registry:icon","registry:lib","registry:node","registry:template","registry:ui-primitive","registry:ui","registry:ui-utils","registry:page","registry:component","registry:style","registry:asset"]),Re=["start","team","growth","enterprise","business"],fr=["open-source","light"],ur=[...Re,...fr],gr=R.array(R.enum(ur)).default([]),Vt=R.object({path:R.string(),content:R.string().optional(),type:Kt,target:R.string().optional()}),ie=R.object({name:R.string(),type:Kt,description:R.string().optional(),dependencies:R.array(R.string()).optional(),devDependencies:R.array(R.string()).optional(),registryDependencies:R.array(R.string()).optional(),files:R.array(Vt).optional(),meta:R.record(R.string(),R.any()).optional(),plans:gr.optional(),hide:R.boolean().default(!1).optional(),isNew:R.boolean().default(!1).optional()}),gi=R.array(ie),Jt=R.array(ie.extend({files:R.array(R.union([R.string(),Vt])).optional()})),qt=ie.pick({dependencies:!0,devDependencies:!0,files:!0});import ht from"deepmerge";import{HttpsProxyAgent as yr}from"https-proxy-agent";import yt from"node-fetch";import{z as wr}from"zod";import hr from"conf";var Ne=class{config;logger;constructor(t){this.logger=t,this.config=new hr({projectName:"tiptap-cli",clearInvalidConfig:!0,schema:{bearerToken:{type:"string"},authToken:{type:"string"},email:{type:"string"},loginDate:{type:"string"},plans:{type:"array",items:{type:"string"},default:[]},licenseAccepted:{type:"boolean"},licenseAcceptedDate:{type:"string"}}})}safeError(t,n){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n??"Unknown error");try{this.logger.error(`${t}: ${r}`)}catch{}}setBearerToken(t,n){try{this.config.set("bearerToken",t),this.config.set("loginDate",new Date().toISOString()),n?.email&&this.config.set("email",n.email),n?.plans&&this.config.set("plans",n.plans)}catch(r){this.safeError("Failed to store bearer token",r)}}getBearerToken(){try{return this.config.get("bearerToken")??null}catch(t){return this.safeError("Failed to retrieve bearer token",t),null}}setAuthToken(t,n){try{this.config.set("authToken",t),this.config.set("loginDate",new Date().toISOString()),n?.email&&this.config.set("email",n.email),n?.plans&&this.config.set("plans",n.plans)}catch(r){this.safeError("Failed to store auth token",r)}}getAuthToken(){try{return this.config.get("authToken")??null}catch(t){return this.safeError("Failed to retrieve auth token",t),null}}getUserInfo(){return{email:this.config.get("email"),plans:this.config.get("plans")??[],loginDate:this.config.get("loginDate")}}getTokenExpiration(){let t=this.config.get("loginDate");if(!t)return null;let n=new Date(t);return n.setMonth(n.getMonth()+11),n.toISOString()}isValidToken(){let t=this.getBearerToken(),n=this.getAuthToken();if(!t&&!n)return!1;let r=this.getTokenExpiration();return r&&new Date(r)<=new Date?(this.clear(),!1):!0}clear(){try{this.config.clear()}catch(t){this.safeError("Failed to clear token storage",t)}}hasPlan(t){let n=this.config.get("plans")??[];return Array.isArray(n)&&n.includes(t)}setLicenseAccepted(){try{this.config.set("licenseAccepted",!0),this.config.set("licenseAcceptedDate",new Date().toISOString())}catch(t){this.safeError("Failed to store license acceptance",t)}}hasAcceptedLicense(){try{return this.config.get("licenseAccepted")??!1}catch(t){return this.safeError("Failed to retrieve license acceptance",t),!1}}clearLicenseAcceptance(){try{this.config.delete("licenseAccepted"),this.config.delete("licenseAcceptedDate")}catch(t){this.safeError("Failed to clear license acceptance",t)}}};var N=new Ne(o);var X="https://template.tiptap.dev",wt=process.env.https_proxy?new yr(process.env.https_proxy):void 0;async function Z(){try{let[e]=await je(["index.json"]);return Jt.parse(e)}catch(e){o.error(`
|
|
2
|
+
import jo from"path";import{Command as _o}from"commander";import{z as le}from"zod";import{createPrompt as Ln,useState as tt,useKeypress as Mn,usePrefix as Bn,usePagination as Wn,useRef as Rt,useMemo as nt,useEffect as zn,isBackspaceKey as Kn,isEnterKey as Vn,isUpKey as rt,isDownKey as Nt,isNumberKey as Jn,Separator as Ae,ValidationError as qn,makeTheme as Yn}from"@inquirer/core";import jt from"yoctocolors-cjs";import Gn from"@inquirer/figures";import Hn from"ansi-escapes";import{Separator as As}from"@inquirer/core";var Xn={icon:{cursor:Gn.pointer},style:{disabled:e=>jt.dim(`- ${e}`),description:e=>jt.cyan(e)},indexMode:"hidden"};function pe(e){return!Ae.isSeparator(e)&&!e.disabled}function Zn(e){return e.map(t=>{if(Ae.isSeparator(t))return t;if(typeof t=="string")return{value:t,name:t,short:t,disabled:!1};let n=t.name??String(t.value),r={value:t.value,name:n,short:t.short??n,disabled:t.disabled??!1};return t.description&&(r.description=t.description),r})}var Pe=Ln((e,t)=>{let{loop:n=!0,pageSize:r=7,instructions:s}=e,i=Rt(!0),c=Yn(Xn,e.theme),[p,l]=tt("idle"),w=Bn({status:p,theme:c}),d=Rt(),[h,u]=tt(!0),k=nt(()=>Zn(e.choices),[e.choices]),P=nt(()=>{let y=k.findIndex(pe),T=k.findLastIndex(pe);if(y===-1)throw new qn("[select prompt] No selectable choices. All choices are disabled.");return{first:y,last:T}},[k]),x=nt(()=>"default"in e?k.findIndex(y=>pe(y)&&y.value===e.default):-1,[e.default,k]),[I,b]=tt(x===-1?P.first:x),A=k[I];Mn((y,T)=>{if(clearTimeout(d.current),u(!1),Vn(y))l("done"),t(A.value);else if(rt(y)||Nt(y)){if(T.clearLine(0),n||rt(y)&&I!==P.first||Nt(y)&&I!==P.last){let S=rt(y)?-1:1,L=I;do L=(L+S+k.length)%k.length;while(!pe(k[L]));b(L)}}else if(Jn(y)&&!Number.isNaN(Number(T.line))){let S=Number(T.line)-1,L=k[S];L!=null&&pe(L)&&b(S),d.current=setTimeout(()=>{T.clearLine(0)},700)}else if(Kn(y))T.clearLine(0);else{let S=T.line.toLowerCase(),L=k.findIndex(ne=>Ae.isSeparator(ne)||!pe(ne)?!1:ne.name.toLowerCase().startsWith(S));L!==-1&&b(L),d.current=setTimeout(()=>{T.clearLine(0)},700)}}),zn(()=>()=>{clearTimeout(d.current)},[]);let F=c.style.message(e.message,p),D="",m="";typeof s=="string"&&(D=s);let g=Wn({items:k,active:I,renderItem({item:y,isActive:T,index:S}){if(Ae.isSeparator(y))return` ${y.separator}`;let L=c.indexMode==="number"?`${S+1}. `:"";if(y.disabled){let et=typeof y.disabled=="string"?y.disabled:"(disabled)";return c.style.disabled(`${L}${y.name} ${et}`)}let ne=T?c.style.highlight:et=>et,Un=T?c.icon.cursor:" ";return ne(`${Un} ${L}${y.name}`)},pageSize:r,loop:n});if(p==="done")return`${w} ${F} ${c.style.answer(A.short)}`;let v=A.description?`
|
|
3
|
+
${c.style.description(A.description)}`:"";return`${[w,F,D].filter(Boolean).join(" ")}
|
|
4
|
+
${g}${m}${v}${Hn.cursorHide}`});import{Separator as xe,input as Oo,confirm as kl,checkbox as Fo}from"@inquirer/prompts";import mr from"path";import B from"path";import{createMatchPath as Qn}from"tsconfig-paths";async function O(e,t){return Qn(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as sr}from"cosmiconfig";import ir from"fast-glob";import{loadConfig as ar}from"tsconfig-paths";import{z as E}from"zod";import Ot from"path";var f={"next-app":{name:"next-app",label:"Next.js",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}},"next-pages":{name:"next-pages",label:"Next.js",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}},"react-router":{name:"react-router",label:"React Router",links:{installation:"https://tiptap.dev/docs/ui-components/install/react-router"}},vite:{name:"vite",label:"Vite",links:{installation:"https://tiptap.dev/docs/ui-components/install/vite"}},astro:{name:"astro",label:"Astro",links:{installation:"https://tiptap.dev/docs/ui-components/install/astro"}},laravel:{name:"laravel",label:"Laravel",links:{installation:"https://tiptap.dev/docs/ui-components/install/laravel"}},"tanstack-start":{name:"tanstack-start",label:"TanStack Start",links:{installation:"https://tiptap.dev/docs/ui-components/install/tanstack"}},manual:{name:"manual",label:"Manual",links:{installation:"https://tiptap.dev/docs/ui-components/install/next"}}};import er from"path";import tr from"fs-extra";function _t(e="",t=!0){let n=er.join(e,"package.json");return tr.readJSONSync(n,{throws:t})}import Dt from"fast-glob";import Ft from"fs-extra";import{loadConfig as nr}from"tsconfig-paths";var Ut=["**/node_modules/**",".next","public","dist","build"];async function U(e){let[t,n,r,s,i]=await Promise.all([Dt.glob("**/{next,vite,astro,app}.config.*|gatsby-config.*|composer.json|react-router.config.*",{cwd:e,deep:3,ignore:Ut}),Ft.pathExists(Ot.resolve(e,"src")),or(e),rr(e),_t(e,!1)]),c=await Ft.pathExists(Ot.resolve(e,`${n?"src/":""}app`)),p={framework:f.manual,isSrcDir:n,isRSC:!1,isTsx:r,aliasPrefix:s};return t.find(l=>l.startsWith("next.config."))?.length?(p.framework=c?f["next-app"]:f["next-pages"],p.isRSC=c,p):t.find(l=>l.startsWith("astro.config."))?.length?(p.framework=f.astro,p):t.find(l=>l.startsWith("composer.json"))?.length?(p.framework=f.laravel,p):t.find(l=>l.startsWith("app.config."))?.length&&[...Object.keys(i?.dependencies??{}),...Object.keys(i?.devDependencies??{})].find(l=>l.startsWith("@tanstack/start"))?(p.framework=f["tanstack-start"],p):t.find(l=>l.startsWith("react-router.config."))?.length?(p.framework=f["react-router"],p):(t.find(l=>l.startsWith("vite.config."))?.length&&(p.framework=f.vite),p)}async function rr(e){let t=await nr(e);if(t?.resultType==="failed"||!Object.entries(t?.paths).length)return null;for(let[n,r]of Object.entries(t.paths))if(r.includes("./*")||r.includes("./src/*")||r.includes("./app/*")||r.includes("./resources/js/*"))return n.replace(/\/\*$/,"")??null;return Object.keys(t?.paths)?.[0].replace(/\/\*$/,"")??null}async function or(e){return(await Dt.glob("tsconfig.*",{cwd:e,deep:1,ignore:Ut})).length>0}async function Lt(e,t=null){let[n,r]=await Promise.all([Y(e),t?Promise.resolve(t):U(e)]);if(n)return n;if(!r)return null;let s={rsc:r.isRSC,tsx:r.isTsx,aliases:{components:`${r.aliasPrefix}/components`,contexts:`${r.aliasPrefix}/contexts`,hooks:`${r.aliasPrefix}/hooks`,tiptapIcons:`${r.aliasPrefix}/components/tiptap-icons`,lib:`${r.aliasPrefix}/lib`,tiptapExtensions:`${r.aliasPrefix}/components/tiptap-extensions`,tiptapNodes:`${r.aliasPrefix}/components/tiptap-nodes`,tiptapUi:`${r.aliasPrefix}/components/tiptap-ui`,tiptapUiPrimitives:`${r.aliasPrefix}/components/tiptap-ui-primitives`,tiptapUiUtils:`${r.aliasPrefix}/components/tiptap-ui-utils`,styles:`${r.aliasPrefix}/styles`}};return await re(e,s)}var ot="@/components",st="@/contexts",it="@/hooks",at="@/components/tiptap-icons",$e="@/lib",ct="@/components/tiptap-extension",lt="@/components/tiptap-node",pt="@/components/tiptap-ui",mt="@/components/tiptap-ui-primitive",dt="@/components/tiptap-ui-utils",ft="@/styles",cr=sr("components",{searchPlaces:["components.json"]}),oe=E.object({rsc:E.coerce.boolean().default(!1),tsx:E.coerce.boolean().default(!0),aliases:E.object({components:E.string(),contexts:E.string().optional(),hooks:E.string().optional(),tiptapIcons:E.string().optional(),lib:E.string().optional(),tiptapExtensions:E.string().optional(),tiptapNodes:E.string().optional(),tiptapUi:E.string().optional(),tiptapUiPrimitives:E.string().optional(),tiptapUiUtils:E.string().optional(),styles:E.string().optional()})}),Mt=oe.extend({resolvedPaths:E.object({cwd:E.string(),components:E.string(),contexts:E.string(),hooks:E.string(),tiptapIcons:E.string(),lib:E.string(),tiptapExtensions:E.string(),tiptapNodes:E.string(),tiptapUi:E.string(),tiptapUiPrimitives:E.string(),tiptapUiUtils:E.string(),styles:E.string()})}),lr=E.record(Mt);async function Y(e){let t=await cr.search(e),n=await U(e),r={components:ot,contexts:st,hooks:it,tiptapIcons:at,lib:$e,tiptapExtensions:ct,tiptapNodes:lt,tiptapUi:pt,tiptapUiPrimitives:mt,tiptapUiUtils:dt,styles:ft},s=(c,p)=>Object.fromEntries(Object.entries(c).map(([l,w])=>[l,w.replace(/^@/,p)])),i;if(t){let c={...r,...t.config.aliases};n?.aliasPrefix?i=oe.parse({...t.config,aliases:s(c,n.aliasPrefix)}):i=oe.parse({...t.config,aliases:c})}else{let c=r;n?.aliasPrefix&&(c=s(c,n.aliasPrefix)),i=oe.parse({rsc:n?.isRSC??!1,tsx:n?.isTsx??!0,aliases:c})}return await re(e,i)}async function re(e,t){let n=await ar(e);if(n.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${n.message??""}`.trim());return Mt.parse({...t,resolvedPaths:{cwd:e,components:await O(t.aliases.components,n),contexts:t.aliases.contexts?await O(t.aliases.contexts,n):B.resolve(await O(t.aliases.components,n)??e,"..","contexts"),hooks:t.aliases.hooks?await O(t.aliases.hooks,n):B.resolve(await O(t.aliases.components,n)??e,"..","hooks"),tiptapIcons:t.aliases.tiptapIcons?await O(t.aliases.tiptapIcons,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-icons"),lib:t.aliases.lib?await O(t.aliases.lib,n):B.resolve(await O($e,n)??e,".."),tiptapExtensions:t.aliases.tiptapExtensions?await O(t.aliases.tiptapExtensions,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-extension"),tiptapNodes:t.aliases.tiptapNodes?await O(t.aliases.tiptapNodes,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-node"),tiptapUi:t.aliases.tiptapUi?await O(t.aliases.tiptapUi,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-ui"),tiptapUiPrimitives:t.aliases.tiptapUiPrimitives?await O(t.aliases.tiptapUiPrimitives,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-ui-primitive"),tiptapUiUtils:t.aliases.tiptapUiUtils?await O(t.aliases.tiptapUiUtils,n):B.resolve(await O(t.aliases.components,n)??e,"tiptap-ui-utils"),styles:t.aliases.styles?await O(t.aliases.styles,n):B.resolve(e,"styles")}})}async function Bt(e){let t={};for(let r of Object.keys(e.aliases)){if(!pr(r,e))continue;let s=e.resolvedPaths[r],i=await ut(e.resolvedPaths.cwd,s);if(!i){t[r]=e;continue}t[r]=await Y(i)}let n=lr.safeParse(t);return n.success?n.data:null}async function ut(e,t){let n=gt(e,t),r=B.relative(n,t),i=(await ir.glob("**/package.json",{cwd:n,deep:3,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/public/**"]})).map(c=>B.dirname(c)).find(c=>r.startsWith(c));return i?B.join(n,i):null}function pr(e,t){return Object.keys(t.resolvedPaths).includes(e)}function gt(e,t){let n=e.split(B.sep),r=t.split(B.sep),s=[];for(let i=0;i<Math.min(n.length,r.length)&&n[i]===r[i];i++)s.push(n[i]);return s.join(B.sep)}import V from"chalk";var a={cyan:V.cyan,magenta:V.magenta,gray:V.gray,white:V.white,yellow:V.yellow,green:V.green,red:V.red,blue:V.blue,reset:V.reset,dim:V.dim,bold:V.bold,whiteBold:V.white.bold};var ve=e=>e.map(String).join(" "),o={error(...e){console.log(a.red(ve(e)))},warn(...e){console.log(a.yellow(ve(e)))},info(...e){console.log(a.cyan(ve(e)))},success(...e){console.log(a.green(ve(e)))},log(...e){console.log(ve(e))},break(){console.log("")}};import Wt from"fs-extra";async function zt(e){let t={};if(!Wt.existsSync(e.cwd)||!Wt.existsSync(mr.resolve(e.cwd,"package.json")))return t["1"]=!0,{errors:t,config:null};try{let n=await Y(e.cwd);return{errors:t,config:n}}catch(n){console.log("[preFlightAdd] - ",n),o.break(),o.error(`Make sure you are in a valid project directory. Run ${a.cyan("npx @tiptap/cli init")} to create a new project.`),o.break(),process.exit(0)}}import de from"path";import{z as dr}from"zod";function _(e){if(o.error("Something went wrong. Please check the error below for more details."),o.error("If the problem persists, please open an issue on GitHub."),o.error(""),typeof e=="string"&&(o.error(e),o.break(),process.exit(0)),e instanceof dr.ZodError){o.error("Validation failed:");for(let[t,n]of Object.entries(e.flatten().fieldErrors))o.error(`- ${a.cyan(t)}: ${n}`);o.break(),process.exit(0)}e instanceof Error&&(o.error(e.message),o.break(),process.exit(0)),o.break(),process.exit(0)}import{z as R}from"zod";var Kt=R.enum(["registry:context","registry:extension","registry:hook","registry:icon","registry:lib","registry:node","registry:template","registry:ui-primitive","registry:ui","registry:ui-utils","registry:page","registry:component","registry:style","registry:asset"]),Re=["start","team","growth","enterprise","business"],fr=["open-source","light"],ur=[...Re,...fr],gr=R.array(R.enum(ur)).default([]),Vt=R.object({path:R.string(),content:R.string().optional(),type:Kt,target:R.string().optional()}),ie=R.object({name:R.string(),type:Kt,description:R.string().optional(),dependencies:R.array(R.string()).optional(),devDependencies:R.array(R.string()).optional(),registryDependencies:R.array(R.string()).optional(),files:R.array(Vt).optional(),meta:R.record(R.string(),R.any()).optional(),plans:gr.optional(),hide:R.boolean().default(!1).optional(),isNew:R.boolean().default(!1).optional()}),gi=R.array(ie),Jt=R.array(ie.extend({files:R.array(R.union([R.string(),Vt])).optional()})),qt=ie.pick({dependencies:!0,devDependencies:!0,files:!0});import ht from"deepmerge";import{HttpsProxyAgent as yr}from"https-proxy-agent";import yt from"node-fetch";import{z as wr}from"zod";import hr from"conf";var Ne=class{config;logger;constructor(t){this.logger=t,this.config=new hr({projectName:"tiptap-cli",clearInvalidConfig:!0,schema:{bearerToken:{type:"string"},authToken:{type:"string"},email:{type:"string"},loginDate:{type:"string"},plans:{type:"array",items:{type:"string"},default:[]},licenseAccepted:{type:"boolean"},licenseAcceptedDate:{type:"string"}}})}safeError(t,n){let r=n instanceof Error?`${n.name}: ${n.message}`:String(n??"Unknown error");try{this.logger.error(`${t}: ${r}`)}catch{}}setBearerToken(t,n){try{this.config.set("bearerToken",t),this.config.set("loginDate",new Date().toISOString()),n?.email&&this.config.set("email",n.email),n?.plans&&this.config.set("plans",n.plans)}catch(r){this.safeError("Failed to store bearer token",r)}}getBearerToken(){try{return this.config.get("bearerToken")??null}catch(t){return this.safeError("Failed to retrieve bearer token",t),null}}setAuthToken(t,n){try{this.config.set("authToken",t),this.config.set("loginDate",new Date().toISOString()),n?.email&&this.config.set("email",n.email),n?.plans&&this.config.set("plans",n.plans)}catch(r){this.safeError("Failed to store auth token",r)}}getAuthToken(){try{return this.config.get("authToken")??null}catch(t){return this.safeError("Failed to retrieve auth token",t),null}}getUserInfo(){return{email:this.config.get("email"),plans:this.config.get("plans")??[],loginDate:this.config.get("loginDate")}}getTokenExpiration(){let t=this.config.get("loginDate");if(!t)return null;let n=new Date(t);return n.setMonth(n.getMonth()+11),n.toISOString()}isValidToken(){let t=this.getBearerToken(),n=this.getAuthToken();if(!t&&!n)return!1;let r=this.getTokenExpiration();return r&&new Date(r)<=new Date?(this.clear(),!1):!0}clear(){try{this.config.clear()}catch(t){this.safeError("Failed to clear token storage",t)}}hasPlan(t){let n=this.config.get("plans")??[];return Array.isArray(n)&&n.includes(t)}setLicenseAccepted(){try{this.config.set("licenseAccepted",!0),this.config.set("licenseAcceptedDate",new Date().toISOString())}catch(t){this.safeError("Failed to store license acceptance",t)}}hasAcceptedLicense(){try{return this.config.get("licenseAccepted")??!1}catch(t){return this.safeError("Failed to retrieve license acceptance",t),!1}}clearLicenseAcceptance(){try{this.config.delete("licenseAccepted"),this.config.delete("licenseAcceptedDate")}catch(t){this.safeError("Failed to clear license acceptance",t)}}};var N=new Ne(o);var X="https://template.tiptap.dev",wt=process.env.https_proxy?new yr(process.env.https_proxy):void 0;async function Z(){try{let[e]=await je(["index.json"]);return Jt.parse(e)}catch(e){o.error(`
|
|
5
5
|
`),_(e)}}function Yt(e,t){let n={400:"Bad request",401:"Unauthorized",403:"Forbidden",404:"Not found",500:"Internal server error"},r=t?` at ${a.cyan(t)}`:"";switch(e.status){case 401:return N.clear(),new Error(`You are not authorized to access the component${r}.
|
|
6
6
|
Please run ${a.cyan("@tiptap/cli login")} to log in to your Tiptap Cloud account.`);case 404:return new Error(`The component${r} was not found.
|
|
7
7
|
It may not exist at the registry. Please make sure it is a valid component.`);case 403:return new Error(`You do not have access to the component${r}.
|
|
8
8
|
Your account may not have the required subscription plan for this component.
|
|
9
9
|
Please upgrade your subscription or use a component available in your current plan.`);default:let s=n[e.status]||e.statusText;return new Error(`Failed to fetch${r}.
|
|
10
10
|
${s}`)}}async function xr(e,t){let n=Ht(e),r=await yt(n,{agent:wt,headers:t});if(!r.ok)throw Yt(r,n);return r.json()}async function kr(e,t){let n=await yt(`${X}/api/registry/components/batch`,{method:"POST",agent:wt,headers:t,body:JSON.stringify({components:e})});if(!n.ok)throw Yt(n);return await n.json()}async function je(e){try{let t=N.getBearerToken(),n={"Content-Type":"application/json"};t&&(n.Authorization=`Bearer ${t}`);let r=e.map(s=>s.includes("/components/")?s.replace(/.*\/components\//,"").replace(".json",""):s.replace(".json",""));return r.length>1?await kr(r,n):Promise.all(e.map(s=>xr(s,n)))}catch(t){return o.error(`
|
|
11
|
-
`),_(t),[]}}async function Pr(e){let t=await yt(`${X}/api/registry/dependencies`,{method:"POST",agent:wt,headers:{"Content-Type":"application/json"},body:JSON.stringify({components:e})});if(!t.ok)throw new Error(`Failed to fetch registry dependencies: ${t.statusText}`);return await t.json()}async function Gt(e,t){try{if(!await Z())return null;e.includes("index")&&e.unshift("index");let r=await xt(e),s=await je(r),i=wr.array(ie).parse(s);if(!i)return null;let l=(await D(t.resolvedPaths.cwd))?.framework.name,p=ht.all(i.map(h=>h.dependencies??[])),w=ht.all(i.map(h=>h.devDependencies??[])),d=Tr(w,l);return qt.parse({dependencies:p,devDependencies:d,files:ht.all(i.map(h=>h.files??[]))})}catch(n){return _(n),null}}async function xt(e){return(await Pr(e)).map(r=>Ht(`components/${r}.json`))}function Ht(e){if(vr(e))return new URL(e).toString();if(!X)throw new Error("No registry URL found");if(e==="index.json")return`${X}/r/${e}`;if(e.startsWith("components/")){let t=e.replace("components/","").replace(".json","");return`${X}/api/registry/components/${t}`}return`${X}/${e}`}function vr(e){try{return new URL(e),!0}catch{return!1}}function Xt(){return new Map([["registry:ui","tiptapUi"],["registry:ui-primitive","tiptapUiPrimitives"],["registry:ui-utils","tiptapUiUtils"],["registry:extension","tiptapExtensions"],["registry:node","tiptapNodes"],["registry:context","contexts"],["registry:hook","hooks"],["registry:lib","lib"],["registry:context","components"],["registry:template","tiptapTemplates"],["registry:component","components"],["registry:icon","titpapIcons"],["registry:style","styles"]])}function Zt(e){let t=new Map;return e.forEach(n=>{n.registryDependencies&&n.registryDependencies.forEach(r=>{t.set(r,n)})}),t}function Tr(e,t){let n=Array.isArray(e)?e:[];if(!n.length)return[];let r=n.map(s=>String(s));if(t){let s=r.includes("sass"),i=r.includes("sass-embedded");if(s||i){let c=[...r],l=[u.astro.name,u.laravel.name,u.vite.name,u["tanstack-start"].name,u["react-router"].name],p=[u["next-app"].name,u["next-pages"].name];return l.includes(t)?c=c.filter(w=>w!=="sass"):p.includes(t)&&(c=c.filter(w=>w!=="sass-embedded")),c}}return r}import br from"ora";var Sr={frames:[`${a.cyan("\u2588")}`,`${a.cyan("\u2588")}`,`${a.cyan("\u2588")}`," "," "," "],interval:200};function A(e,t){return br({text:e,spinner:Sr,color:"cyan",isSilent:t?.silent})}import{detect as Ir}from"@antfu/ni";import Qt from"fs-extra";import en from"path";async function z(e,{withFallback:t}={withFallback:!1}){let n=await Ir({programmatic:!0,cwd:e});if(n==="deno"&&(n=void 0),n==="yarn@berry")return"yarn";if(n==="pnpm@6")return"pnpm";if(n==="bun")return"bun";if(!t)return n??"npm";let r=process.env.npm_config_user_agent||"";return r.startsWith("yarn")?"yarn":r.startsWith("pnpm")?"pnpm":r.startsWith("bun")?"bun":"npm"}function me(e){let t=Qt.existsSync(en.join(e,"bun.lock")),n=Qt.existsSync(en.join(e,"bunfig.toml"));return!!(t&&n)}import{execa as Cr}from"execa";async function kt(e,t,n){if(e=Array.from(new Set(e)),!e?.length)return;n={silent:!1,...n};let r=A("Installing dependencies.",{silent:n.silent}).start(),s=await z(t.resolvedPaths.cwd);await Cr(s,[s==="npm"?"install":"add",...s==="npm"?["--save"]:[],...e],{cwd:t.resolvedPaths.cwd}),r.stopAndPersist({symbol:a.cyan("\u2714")})}import{existsSync as cn,promises as Pt}from"fs";import J,{basename as Kr}from"path";import{promises as Dr}from"fs";import{tmpdir as Lr}from"os";import sn from"path";var _e=async({sourceFile:e,config:t,packageManager:n})=>{let r=e.getImportDeclarations();for(let s of r){let i=Ar(s.getModuleSpecifierValue(),t);me(t.resolvedPaths.cwd)&&i.endsWith(".scss")&&(i=i.replace(/\.scss$/,".css")),i&&s.setModuleSpecifier(i)}return e};function Ar(e,t){if(!e.startsWith("@/registry/")){let n=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${n}/`)}return e.match(/@\/registry\/tiptap-templates\/([^/]+)\/components\//)?e.replace(/@\/registry\/tiptap-templates\/([^/]+)\/components\//,`${t.aliases.components}/tiptap-templates/$1/`):e.match(/@\/registry\/tiptap-templates\/([^/]+)\/(?!components\/)/)?e.replace(/@\/registry\/tiptap-templates\/([^/]+)\//,`${t.aliases.components}/tiptap-templates/$1/`):t.aliases.components&&e.match(/@\/registry\/components/)?e.replace(/@\/registry\/components/,t.aliases.components):t.aliases.contexts&&e.match(/@\/registry\/contexts/)?e.replace(/@\/registry\/contexts/,t.aliases.contexts):t.aliases.tiptapExtensions&&e.match(/@\/registry\/tiptap-extension/)?e.replace(/@\/registry\/tiptap-extension/,t.aliases.tiptapExtensions):t.aliases.hooks&&e.match(/@\/registry\/hooks/)?e.replace(/@\/registry\/hooks/,t.aliases.hooks):t.aliases.tiptapIcons&&e.match(/@\/registry\/tiptap-icons/)?e.replace(/@\/registry\/tiptap-icons/,t.aliases.tiptapIcons):t.aliases.lib&&e.match(/@\/registry\/lib/)?e.replace(/@\/registry\/lib/,t.aliases.lib):t.aliases.tiptapNodes&&e.match(/@\/registry\/tiptap-node/)?e.replace(/@\/registry\/tiptap-node/,t.aliases.tiptapNodes):t.aliases.tiptapUiPrimitives&&e.match(/@\/registry\/tiptap-ui-primitive/)?e.replace(/@\/registry\/tiptap-ui-primitive/,t.aliases.tiptapUiPrimitives):t.aliases.tiptapUiUtils&&e.match(/@\/registry\/tiptap-ui-utils/)?e.replace(/@\/registry\/tiptap-ui-utils/,t.aliases.tiptapUiUtils):t.aliases.tiptapUi&&e.match(/@\/registry\/tiptap-ui/)?e.replace(/@\/registry\/tiptap-ui/,t.aliases.tiptapUi):t.aliases.styles&&e.match(/@\/registry\/styles/)?e.replace(/@\/registry\/styles/,t.aliases.styles):e.replace(/^@\/registry\/[^/]+(?:\/.*\/)?/,t.aliases.components+"/")}import{transformFromAstSync as Er}from"@babel/core";import{parse as $r}from"@babel/parser";import Rr from"@babel/plugin-transform-typescript";import*as Oe from"recast";var Nr={sourceType:"module",allowImportExportEverywhere:!0,allowReturnOutsideFunction:!0,startLine:1,tokens:!0,plugins:["asyncGenerators","bigInt","classPrivateMethods","classPrivateProperties","classProperties","classStaticBlock","decimal","decorators-legacy","doExpressions","dynamicImport","exportDefaultFrom","exportNamespaceFrom","functionBind","functionSent","importAssertions","importMeta","nullishCoalescingOperator","numericSeparator","objectRestSpread","optionalCatchBinding","optionalChaining",["pipelineOperator",{proposal:"minimal"}],["recordAndTuple",{syntaxType:"hash"}],"throwExpressions","topLevelAwait","v8intrinsic","typescript","jsx"]},tn=async({sourceFile:e,config:t})=>{let n=e.getFullText();if(t.tsx)return n;let r=Oe.parse(n,{parser:{parse:i=>$r(i,Nr)}}),s=Er(r,n,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Rr],configFile:!1});if(!s||!s.ast)throw new Error("Failed to transform JSX");return Oe.print(s.ast).code};import{SyntaxKind as jr}from"ts-morph";var _r=/^["']use client["']$/g,Fe=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let n=e.getFirstChildByKind(jr.ExpressionStatement);return n&&_r.test(n.getText())&&n.remove(),e};import{Node as Ue,SyntaxKind as $}from"ts-morph";var Or=[{name:"cta",matchType:"contains",caseSensitive:!1,onlyInFiles:["notion-like-editor.tsx"]},{name:"initialContent",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"JSONContent",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"onCreate",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"getDocumentId",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]}];function M(e,t,n){return t.some(r=>{if(r.onlyInFiles&&!r.onlyInFiles.some(c=>n.endsWith(c)))return!1;let s=r.caseSensitive?e:e.toLowerCase(),i=r.caseSensitive?r.name:r.name.toLowerCase();switch(r.matchType){case"exact":return s===i;case"contains":return s.includes(i);case"startsWith":return s.startsWith(i);case"endsWith":return s.endsWith(i);case"regex":return r.pattern?new RegExp(r.pattern,r.caseSensitive?"":"i").test(s):!1;default:return!1}})}function Fr(e,t){let n=t.name;return n===u["next-app"].name||n===u["next-pages"].name?`NEXT_PUBLIC_${e}`:n===u.astro.name?`PUBLIC_${e}`:n===u.vite.name||n===u["tanstack-start"].name||n===u["react-router"].name?`VITE_${e}`:(n===u.laravel.name||n===u.manual.name,e)}function nn(e){return e.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_)/,"")}async function Ur(e,t){let n=await D(t.resolvedPaths.cwd);if(!n)return;let r=[],s=e.getDescendantsOfKind($.BinaryExpression);for(let l of s)if(l.getOperatorToken().getKind()===$.BarBarToken){let w=l.getLeft().getText();if(w.match(/^process\.env\.[A-Z_]+$/)){let d=w.match(/process\.env\.([A-Z_]+)/);if(d&&d[1]){let h=nn(d[1]),f=n.framework.name,x;f===u.astro.name?x=`import.meta.env.PUBLIC_${h}`:f===u.vite.name||f===u["tanstack-start"].name||f===u["react-router"].name?x=`import.meta.env.VITE_${h}`:f===u["next-app"].name||f===u["next-pages"].name?x=`process.env.NEXT_PUBLIC_${h}`:x=`process.env.${h}`;let k=l.getRight().getText(),P=`${x} || ${k}`;r.push({node:l,newText:P})}}}let i=e.getDescendantsOfKind($.CallExpression);for(let l of i){let w=l.getExpression().getText();if(w.match(/^alert$/)){let d=l.getArguments();if(d.length>0){let f=d[0].getText();if(f.includes("TIPTAP_COLLAB_TOKEN")||f.includes("TIPTAP_COLLAB_DOC_PREFIX")||f.includes("TIPTAP_AI_TOKEN")){let x=f,k=["TIPTAP_COLLAB_DOC_PREFIX","TIPTAP_COLLAB_APP_ID","TIPTAP_COLLAB_TOKEN","TIPTAP_AI_APP_ID","TIPTAP_AI_TOKEN","USE_JWT_TOKEN_API_ENDPOINT"];for(let P of k){let I=Fr(P,n.framework);x=x.replace(new RegExp(P,"g"),I)}if(x!==f){let P=`${w}(${x})`;r.push({node:l,newText:P})}}}}}let c=e.getDescendantsOfKind($.PropertyAccessExpression);for(let l of c){let p=l.getText();if(p.match(/^process\.env\.[A-Z_]+$/)){if(l.getParent()?.getKind()===$.BinaryExpression)continue;let d=p.match(/process\.env\.([A-Z_]+)/);if(d&&d[1]){let h=nn(d[1]),f=n.framework.name,x;f===u.astro.name?x=`import.meta.env.PUBLIC_${h}`:f===u.vite.name||f===u["tanstack-start"].name||f===u["react-router"].name?x=`import.meta.env.VITE_${h}`:f===u["next-app"].name||f===u["next-pages"].name?x=`process.env.NEXT_PUBLIC_${h}`:x=`process.env.${h}`,r.push({node:l,newText:x})}}}for(let{node:l,newText:p}of r)try{l.replaceWithText(p)}catch(w){console.warn(`Skipping transformation of node: ${w}`)}}var De=async({sourceFile:e,config:t})=>{let n=Or,r=e.getFilePath(),s=[],i=e.getImportDeclarations();for(let m of i){let g=m.getModuleSpecifierValue();if(n.some(S=>M(g,[S],r))){s.push({node:m,action:"remove"});continue}let v=m.getDefaultImport();if(v&&M(v.getText(),n,r)){s.push({node:m,action:"remove"});continue}let y=m.getNamedImports(),b=y.filter(S=>M(S.getName(),n,r));b.length>0&&(b.forEach(L=>s.push({node:L,action:"remove"})),y.filter(L=>!b.includes(L)).length===0&&!v&&s.push({node:m,action:"remove"}))}let c=e.getExportDeclarations();for(let m of c){let g=m.getNamedExports(),v=g.filter(y=>M(y.getName(),n,r));v.length>0&&(v.forEach(b=>s.push({node:b,action:"remove"})),g.filter(b=>!v.includes(b)).length===0&&s.push({node:m,action:"remove"}))}let l=e.getVariableStatements();for(let m of l){let g=m.getDeclarations(),v=g.filter(y=>M(y.getName(),n,r));v.length>0&&(g.length===v.length?s.push({node:m,action:"remove"}):v.forEach(y=>s.push({node:y,action:"remove"})))}let p=e.getFunctions();for(let m of p){let g=m.getName();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}let w=e.getInterfaces();for(let m of w){let g=m.getName();M(g,n,r)&&s.push({node:m,action:"remove"})}let d=e.getTypeAliases();for(let m of d){let g=m.getName();M(g,n,r)&&s.push({node:m,action:"remove"})}let h=e.getDescendantsOfKind($.PropertySignature);for(let m of h){let g=m.getName();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}let f=e.getDescendantsOfKind($.JsxElement);for(let m of f){let g=m.getOpeningElement().getTagNameNode().getText();M(g,n,r)&&s.push({node:m,action:"replace",newText:""})}let x=e.getDescendantsOfKind($.JsxSelfClosingElement);for(let m of x){let g=m.getTagNameNode().getText();M(g,n,r)&&s.push({node:m,action:"replace",newText:""})}let k=e.getDescendantsOfKind($.PropertyAssignment);for(let m of k){let g=m.getName();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}let P=e.getDescendantsOfKind($.JsxAttribute);for(let m of P){let g=m.getNameNode().getText();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}let I=e.getDescendantsOfKind($.Parameter);for(let m of I){let g=m.getName();if(g&&M(g,n,r)){let v=m.getParent();if(v&&(Ue.isFunctionDeclaration(v)||Ue.isArrowFunction(v)||Ue.isFunctionExpression(v)||Ue.isMethodDeclaration(v))){let y=v.getParameters(),b=y.indexOf(m);if(b!==-1){if(b===y.length-1&&b>0){let S=m.getPreviousSibling();S?.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}else{let S=m.getNextSibling();S?.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}s.push({node:m,action:"remove"})}}}}let T=e.getDescendantsOfKind($.CallExpression);for(let m of T){let g=m.getArguments();for(let v=0;v<g.length;v++){let y=g[v],b=y.getText();if(M(b,n,r)){if(v===g.length-1){let S=y.getPreviousSibling();S&&S.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}else{let S=y.getNextSibling();S&&S.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}s.push({node:y,action:"remove"})}}}let C=e.getDescendantsOfKind($.BindingElement);for(let m of C){let g=m.getName();if(g&&M(g,n,r)){let v=m.getParent();if(v){let y=v.getDescendantsOfKind($.BindingElement);if(y.indexOf(m)===y.length-1){let S=m.getPreviousSibling();S?.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}else{let S=m.getNextSibling();S?.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}}s.push({node:m,action:"remove"})}}let F=e.getDescendantsOfKind($.Identifier);for(let m of F){let g=m.getText();if(M(g,n,r)){let v=m.getParent();if(v){let y=v.getKind();if(y===$.CallExpression){let b=v;b.getExpression()===m?s.push({node:b,action:"remove"}):b.getArguments().findIndex(ne=>ne===m)!==-1&&s.push({node:m,action:"remove"})}if(y===$.PropertyAccessExpression){let b=v;b.getName()===g&&s.push({node:b,action:"remove"})}if((y===$.VariableDeclaration||y===$.BinaryExpression||y===$.IfStatement||y===$.ConditionalExpression)&&s.push({node:m,action:"remove"}),y===$.PropertyAssignment){let b=v;b.getInitializer()===m&&s.push({node:b,action:"remove"})}}}}let U=e.getDescendantsOfKind($.ShorthandPropertyAssignment);for(let m of U){let g=m.getName();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}await Ur(e,t),s.sort((m,g)=>{let v=m.node.getStart?.()??0;return(g.node.getStart?.()??0)-v});for(let{node:m,action:g,newText:v}of s)try{if(m.wasForgotten?.()===!0)continue;g==="remove"?typeof m.remove=="function"&&m.remove():g==="replace"&&v!==void 0&&m.replaceWithText(v)}catch{}return e};import*as rn from"sass";async function on(e){try{return rn.compileString(e,{style:"expanded"}).css}catch(t){throw new Error(`Failed to compile SCSS to CSS: ${t instanceof Error?t.message:String(t)}`)}}import{Project as Mr,ScriptKind as Br}from"ts-morph";var Wr=new Mr({compilerOptions:{}});async function zr(e){let t=await Dr.mkdtemp(sn.join(Lr(),"tiptap-"));return sn.join(t,e)}async function an(e,t=[_e,Fe,De]){let n=me(e.config.resolvedPaths.cwd);if(e.filename.endsWith(".scss")&&n)return await on(e.raw);if(e.filename.endsWith(".scss")||e.filename.endsWith(".css")||e.filename.endsWith(".json"))return e.raw;let r=await zr(e.filename),s=Wr.createSourceFile(r,e.raw,{scriptKind:Br.TSX});for(let i of t)await i({sourceFile:s,...e});return e.transformJsx?await tn({sourceFile:s,...e}):s.getText()}import{confirm as Vr}from"@inquirer/prompts";async function vt(e,t,n){let r={filesCreated:[],filesUpdated:[],filesSkipped:[],errors:[]};if(!e?.length)return r;n={overwrite:!1,force:!1,silent:!1,...n};let s=A("Updating files.",{silent:n.silent})?.start();try{let[i,c]=await Promise.all([D(t.resolvedPaths.cwd),z(t.resolvedPaths.cwd)]);for(let l of e)try{if(!l.content)continue;let p;try{p=Hr(l,t,{isSrcDir:i?.isSrcDir,framework:i?.framework.name,commonRoot:qr(e.map(k=>k.path),l.path)})}catch(k){r.errors.push({file:l.path,error:`Failed to resolve file path: ${k instanceof Error?k.message:String(k)}`});continue}if(!p)continue;let w=Kr(l.path),d=J.dirname(p);t.tsx||(p=p.replace(/\.tsx?$/,k=>k===".tsx"?".jsx":".js")),me(t.resolvedPaths.cwd)&&p.endsWith(".scss")&&(p=p.replace(/\.scss$/,".css"));let f=!1;try{f=cn(p)}catch(k){r.errors.push({file:p,error:`Failed to check if file exists: ${k instanceof Error?k.message:String(k)}`});continue}let x;try{x=await an({filename:l.path,raw:l.content,config:t,transformJsx:!t.tsx,packageManager:c},[_e,Fe,De])}catch(k){r.errors.push({file:p,error:`Failed to transform content: ${k instanceof Error?k.message:String(k)}`});continue}if(f)try{let k=await Pt.readFile(p,"utf-8"),[P,I]=await Promise.all([ln(k),ln(x)]);if(P===I){r.filesSkipped.push(J.relative(t.resolvedPaths.cwd,p));continue}}catch(k){r.errors.push({file:p,error:`Failed to read or normalize existing file: ${k instanceof Error?k.message:String(k)}`});continue}if(f&&!n.overwrite){s?.stop(),n.rootSpinner&&n.rootSpinner?.stop();try{if(!await Vr({message:a.reset(`The file ${a.cyan(w)} already exists. Would you like to overwrite?`),theme:{prefix:a.cyan("?"),style:{message:P=>a.reset(P)}}})){r.filesSkipped.push(J.relative(t.resolvedPaths.cwd,p)),n.rootSpinner&&n.rootSpinner.start();continue}}catch(k){r.errors.push({file:p,error:`Failed to get user confirmation: ${k instanceof Error?k.message:String(k)}`});continue}finally{s?.start(),n.rootSpinner&&n.rootSpinner.start()}}try{cn(d)||await Pt.mkdir(d,{recursive:!0}),await Pt.writeFile(p,x,"utf-8"),f?r.filesUpdated.push(J.relative(t.resolvedPaths.cwd,p)):r.filesCreated.push(J.relative(t.resolvedPaths.cwd,p))}catch(k){r.errors.push({file:p,error:`Failed to write file: ${k instanceof Error?k.message:String(k)}`})}}catch(p){r.errors.push({file:l.path||"unknown",error:`Unexpected error processing file: ${p instanceof Error?p.message:String(p)}`})}}catch(i){o.error(`An error occurred while updating files: ${i instanceof Error?i.message:String(i)}`)}finally{if(!(r.filesCreated.length||r.filesUpdated.length)&&!r.filesSkipped.length&&s?.info("No files updated."),r.filesCreated.length){if(s?.stopAndPersist({symbol:a.cyan("\u2714"),text:`Created ${r.filesCreated.length} ${r.filesCreated.length===1?"file":"files"}:`}),!n.silent)for(let c of r.filesCreated)o.log(` - ${c}`)}else s?.stop();if(r.filesUpdated.length&&(A(`Updated ${r.filesUpdated.length} ${r.filesUpdated.length===1?"file":"files"}:`,{silent:n.silent})?.info(),!n.silent))for(let c of r.filesUpdated)o.log(` - ${c}`);if(r.filesSkipped.length&&(A(`Skipped ${r.filesSkipped.length} ${r.filesUpdated.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:n.silent})?.info(),!n.silent))for(let c of r.filesSkipped)o.log(` - ${c}`);if(r.errors.length&&(A(`Failed to process ${r.errors.length} ${r.errors.length===1?"file":"files"}:`,{silent:n.silent})?.fail(),!n.silent))for(let{file:c,error:l}of r.errors)o.error(` - ${c}: ${l}`);n.silent||o.break()}return r}function Jr(e,t,n){return n||(e.type==="registry:ui"?t.resolvedPaths.tiptapUi:e.type==="registry:ui-primitive"?t.resolvedPaths.tiptapUiPrimitives:e.type==="registry:ui-utils"?t.resolvedPaths.tiptapUiUtils:e.type==="registry:extension"?t.resolvedPaths.tiptapExtensions:e.type==="registry:node"?t.resolvedPaths.tiptapNodes:e.type==="registry:icon"?t.resolvedPaths.tiptapIcons:e.type==="registry:hook"?t.resolvedPaths.hooks:e.type==="registry:lib"?t.resolvedPaths.lib:e.type==="registry:context"?t.resolvedPaths.contexts:e.type==="registry:template"||e.type==="registry:component"?t.resolvedPaths.components:e.type==="registry:style"?t.resolvedPaths.styles:t.resolvedPaths.components)}function qr(e,t){let n=e.map(c=>c.replace(/^\//,"")),r=t.replace(/^\//,""),s=r.split("/").slice(0,-1).join("/");if(!s)return"";let i=s.split("/");for(let c=i.length;c>0;c--){let l=i.slice(0,c).join("/");if(n.some(w=>w!==r&&w.startsWith(l+"/")))return"/"+l}return"/"+s}async function ln(e){return e.replace(/\r\n/g,`
|
|
12
|
-
`).trim()}function Yr(e,t){if(!t)return"";if(t==="next-app")return e;if(t==="next-pages"){let n=e.replace(/^app\//,"pages/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}if(t==="react-router"){let n=e.replace(/^app\//,"app/routes/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}if(t==="laravel"){let n=e.replace(/^app\//,"resources/js/pages/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}return""}function Gr(e,t){let n=e.replace(/^\/|\/$/g,""),r=t.replace(/^\/|\/$/g,""),s=n.split("/"),i=r.split("/"),c=i[i.length-1],
|
|
11
|
+
`),_(t),[]}}async function Pr(e){let t=await yt(`${X}/api/registry/dependencies`,{method:"POST",agent:wt,headers:{"Content-Type":"application/json"},body:JSON.stringify({components:e})});if(!t.ok)throw new Error(`Failed to fetch registry dependencies: ${t.statusText}`);return await t.json()}async function Gt(e,t){try{if(!await Z())return null;e.includes("index")&&e.unshift("index");let r=await xt(e),s=await je(r),i=wr.array(ie).parse(s);if(!i)return null;let p=(await U(t.resolvedPaths.cwd))?.framework.name,l=ht.all(i.map(h=>h.dependencies??[])),w=ht.all(i.map(h=>h.devDependencies??[])),d=Tr(w,p);return qt.parse({dependencies:l,devDependencies:d,files:ht.all(i.map(h=>h.files??[]))})}catch(n){return _(n),null}}async function xt(e){return(await Pr(e)).map(r=>Ht(`components/${r}.json`))}function Ht(e){if(vr(e))return new URL(e).toString();if(!X)throw new Error("No registry URL found");if(e==="index.json")return`${X}/r/${e}`;if(e.startsWith("components/")){let t=e.replace("components/","").replace(".json","");return`${X}/api/registry/components/${t}`}return`${X}/${e}`}function vr(e){try{return new URL(e),!0}catch{return!1}}function Xt(){return new Map([["registry:ui","tiptapUi"],["registry:ui-primitive","tiptapUiPrimitives"],["registry:ui-utils","tiptapUiUtils"],["registry:extension","tiptapExtensions"],["registry:node","tiptapNodes"],["registry:context","contexts"],["registry:hook","hooks"],["registry:lib","lib"],["registry:context","components"],["registry:template","tiptapTemplates"],["registry:component","components"],["registry:icon","titpapIcons"],["registry:style","styles"]])}function Zt(e){let t=new Map;return e.forEach(n=>{n.registryDependencies&&n.registryDependencies.forEach(r=>{t.set(r,n)})}),t}function Tr(e,t){let n=Array.isArray(e)?e:[];if(!n.length)return[];let r=n.map(s=>String(s));if(t){let s=r.includes("sass"),i=r.includes("sass-embedded");if(s||i){let c=[...r],p=[f.astro.name,f.laravel.name,f.vite.name,f["tanstack-start"].name,f["react-router"].name],l=[f["next-app"].name,f["next-pages"].name];return p.includes(t)?c=c.filter(w=>w!=="sass"):l.includes(t)&&(c=c.filter(w=>w!=="sass-embedded")),c}}return r}import br from"ora";var Sr={frames:[`${a.cyan("\u2588")}`,`${a.cyan("\u2588")}`,`${a.cyan("\u2588")}`," "," "," "],interval:200};function C(e,t){return br({text:e,spinner:Sr,color:"cyan",isSilent:t?.silent})}import{detect as Ir}from"@antfu/ni";import Qt from"fs-extra";import en from"path";async function z(e,{withFallback:t}={withFallback:!1}){let n=await Ir({programmatic:!0,cwd:e});if(n==="deno"&&(n=void 0),n==="yarn@berry")return"yarn";if(n==="pnpm@6")return"pnpm";if(n==="bun")return"bun";if(!t)return n??"npm";let r=process.env.npm_config_user_agent||"";return r.startsWith("yarn")?"yarn":r.startsWith("pnpm")?"pnpm":r.startsWith("bun")?"bun":"npm"}function me(e){let t=Qt.existsSync(en.join(e,"bun.lock")),n=Qt.existsSync(en.join(e,"bunfig.toml"));return!!(t&&n)}import{execa as Cr}from"execa";async function kt(e,t,n){if(e=Array.from(new Set(e)),!e?.length)return;n={silent:!1,...n};let r=C("Installing dependencies.",{silent:n.silent}).start(),s=await z(t.resolvedPaths.cwd);await Cr(s,[s==="npm"?"install":"add",...s==="npm"?["--save"]:[],...e],{cwd:t.resolvedPaths.cwd}),r.stopAndPersist({symbol:a.cyan("\u2714")})}import{existsSync as cn,promises as Pt}from"fs";import J,{basename as Kr}from"path";import{promises as Ur}from"fs";import{tmpdir as Lr}from"os";import sn from"path";var _e=async({sourceFile:e,config:t,packageManager:n})=>{let r=e.getImportDeclarations();for(let s of r){let i=Ar(s.getModuleSpecifierValue(),t);me(t.resolvedPaths.cwd)&&i.endsWith(".scss")&&(i=i.replace(/\.scss$/,".css")),i&&s.setModuleSpecifier(i)}return e};function Ar(e,t){if(!e.startsWith("@/registry/")){let n=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${n}/`)}return e.match(/@\/registry\/tiptap-templates\/([^/]+)\/components\//)?e.replace(/@\/registry\/tiptap-templates\/([^/]+)\/components\//,`${t.aliases.components}/tiptap-templates/$1/`):e.match(/@\/registry\/tiptap-templates\/([^/]+)\/(?!components\/)/)?e.replace(/@\/registry\/tiptap-templates\/([^/]+)\//,`${t.aliases.components}/tiptap-templates/$1/`):t.aliases.components&&e.match(/@\/registry\/components/)?e.replace(/@\/registry\/components/,t.aliases.components):t.aliases.contexts&&e.match(/@\/registry\/contexts/)?e.replace(/@\/registry\/contexts/,t.aliases.contexts):t.aliases.tiptapExtensions&&e.match(/@\/registry\/tiptap-extension/)?e.replace(/@\/registry\/tiptap-extension/,t.aliases.tiptapExtensions):t.aliases.hooks&&e.match(/@\/registry\/hooks/)?e.replace(/@\/registry\/hooks/,t.aliases.hooks):t.aliases.tiptapIcons&&e.match(/@\/registry\/tiptap-icons/)?e.replace(/@\/registry\/tiptap-icons/,t.aliases.tiptapIcons):t.aliases.lib&&e.match(/@\/registry\/lib/)?e.replace(/@\/registry\/lib/,t.aliases.lib):t.aliases.tiptapNodes&&e.match(/@\/registry\/tiptap-node/)?e.replace(/@\/registry\/tiptap-node/,t.aliases.tiptapNodes):t.aliases.tiptapUiPrimitives&&e.match(/@\/registry\/tiptap-ui-primitive/)?e.replace(/@\/registry\/tiptap-ui-primitive/,t.aliases.tiptapUiPrimitives):t.aliases.tiptapUiUtils&&e.match(/@\/registry\/tiptap-ui-utils/)?e.replace(/@\/registry\/tiptap-ui-utils/,t.aliases.tiptapUiUtils):t.aliases.tiptapUi&&e.match(/@\/registry\/tiptap-ui/)?e.replace(/@\/registry\/tiptap-ui/,t.aliases.tiptapUi):t.aliases.styles&&e.match(/@\/registry\/styles/)?e.replace(/@\/registry\/styles/,t.aliases.styles):e.replace(/^@\/registry\/[^/]+(?:\/.*\/)?/,t.aliases.components+"/")}import{transformFromAstSync as Er}from"@babel/core";import{parse as $r}from"@babel/parser";import Rr from"@babel/plugin-transform-typescript";import*as Oe from"recast";var Nr={sourceType:"module",allowImportExportEverywhere:!0,allowReturnOutsideFunction:!0,startLine:1,tokens:!0,plugins:["asyncGenerators","bigInt","classPrivateMethods","classPrivateProperties","classProperties","classStaticBlock","decimal","decorators-legacy","doExpressions","dynamicImport","exportDefaultFrom","exportNamespaceFrom","functionBind","functionSent","importAssertions","importMeta","nullishCoalescingOperator","numericSeparator","objectRestSpread","optionalCatchBinding","optionalChaining",["pipelineOperator",{proposal:"minimal"}],["recordAndTuple",{syntaxType:"hash"}],"throwExpressions","topLevelAwait","v8intrinsic","typescript","jsx"]},tn=async({sourceFile:e,config:t})=>{let n=e.getFullText();if(t.tsx)return n;let r=Oe.parse(n,{parser:{parse:i=>$r(i,Nr)}}),s=Er(r,n,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Rr],configFile:!1});if(!s||!s.ast)throw new Error("Failed to transform JSX");return Oe.print(s.ast).code};import{SyntaxKind as jr}from"ts-morph";var _r=/^["']use client["']$/g,Fe=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let n=e.getFirstChildByKind(jr.ExpressionStatement);return n&&_r.test(n.getText())&&n.remove(),e};import{Node as De,SyntaxKind as $}from"ts-morph";var Or=[{name:"cta",matchType:"contains",caseSensitive:!1,onlyInFiles:["notion-like-editor.tsx"]},{name:"initialContent",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"JSONContent",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"onCreate",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]},{name:"getDocumentId",matchType:"exact",caseSensitive:!0,onlyInFiles:["notion-like-editor.tsx"]}];function M(e,t,n){return t.some(r=>{if(r.onlyInFiles&&!r.onlyInFiles.some(c=>n.endsWith(c)))return!1;let s=r.caseSensitive?e:e.toLowerCase(),i=r.caseSensitive?r.name:r.name.toLowerCase();switch(r.matchType){case"exact":return s===i;case"contains":return s.includes(i);case"startsWith":return s.startsWith(i);case"endsWith":return s.endsWith(i);case"regex":return r.pattern?new RegExp(r.pattern,r.caseSensitive?"":"i").test(s):!1;default:return!1}})}function Fr(e,t){let n=t.name;return n===f["next-app"].name||n===f["next-pages"].name?`NEXT_PUBLIC_${e}`:n===f.astro.name?`PUBLIC_${e}`:n===f.vite.name||n===f["tanstack-start"].name||n===f["react-router"].name?`VITE_${e}`:(n===f.laravel.name||n===f.manual.name,e)}function nn(e){return e.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_)/,"")}async function Dr(e,t){let n=await U(t.resolvedPaths.cwd);if(!n)return;let r=[],s=e.getDescendantsOfKind($.BinaryExpression);for(let p of s)if(p.getOperatorToken().getKind()===$.BarBarToken){let w=p.getLeft().getText();if(w.match(/^process\.env\.[A-Z_]+$/)){let d=w.match(/process\.env\.([A-Z_]+)/);if(d&&d[1]){let h=nn(d[1]),u=n.framework.name,k;u===f.astro.name?k=`import.meta.env.PUBLIC_${h}`:u===f.vite.name||u===f["tanstack-start"].name||u===f["react-router"].name?k=`import.meta.env.VITE_${h}`:u===f["next-app"].name||u===f["next-pages"].name?k=`process.env.NEXT_PUBLIC_${h}`:k=`process.env.${h}`;let P=p.getRight().getText(),x=`${k} || ${P}`;r.push({node:p,newText:x})}}}let i=e.getDescendantsOfKind($.CallExpression);for(let p of i){let w=p.getExpression().getText();if(w.match(/^alert$/)){let d=p.getArguments();if(d.length>0){let u=d[0].getText();if(u.includes("TIPTAP_COLLAB_TOKEN")||u.includes("TIPTAP_COLLAB_DOC_PREFIX")||u.includes("TIPTAP_AI_TOKEN")){let k=u,P=["TIPTAP_COLLAB_DOC_PREFIX","TIPTAP_COLLAB_APP_ID","TIPTAP_COLLAB_TOKEN","TIPTAP_AI_APP_ID","TIPTAP_AI_TOKEN","USE_JWT_TOKEN_API_ENDPOINT"];for(let x of P){let I=Fr(x,n.framework);k=k.replace(new RegExp(x,"g"),I)}if(k!==u){let x=`${w}(${k})`;r.push({node:p,newText:x})}}}}}let c=e.getDescendantsOfKind($.PropertyAccessExpression);for(let p of c){let l=p.getText();if(l.match(/^process\.env\.[A-Z_]+$/)){if(p.getParent()?.getKind()===$.BinaryExpression)continue;let d=l.match(/process\.env\.([A-Z_]+)/);if(d&&d[1]){let h=nn(d[1]),u=n.framework.name,k;u===f.astro.name?k=`import.meta.env.PUBLIC_${h}`:u===f.vite.name||u===f["tanstack-start"].name||u===f["react-router"].name?k=`import.meta.env.VITE_${h}`:u===f["next-app"].name||u===f["next-pages"].name?k=`process.env.NEXT_PUBLIC_${h}`:k=`process.env.${h}`,r.push({node:p,newText:k})}}}for(let{node:p,newText:l}of r)try{p.replaceWithText(l)}catch(w){console.warn(`Skipping transformation of node: ${w}`)}}var Ue=async({sourceFile:e,config:t})=>{let n=Or,r=e.getFilePath(),s=[],i=e.getImportDeclarations();for(let m of i){let g=m.getModuleSpecifierValue();if(n.some(S=>M(g,[S],r))){s.push({node:m,action:"remove"});continue}let v=m.getDefaultImport();if(v&&M(v.getText(),n,r)){s.push({node:m,action:"remove"});continue}let y=m.getNamedImports(),T=y.filter(S=>M(S.getName(),n,r));T.length>0&&(T.forEach(L=>s.push({node:L,action:"remove"})),y.filter(L=>!T.includes(L)).length===0&&!v&&s.push({node:m,action:"remove"}))}let c=e.getExportDeclarations();for(let m of c){let g=m.getNamedExports(),v=g.filter(y=>M(y.getName(),n,r));v.length>0&&(v.forEach(T=>s.push({node:T,action:"remove"})),g.filter(T=>!v.includes(T)).length===0&&s.push({node:m,action:"remove"}))}let p=e.getVariableStatements();for(let m of p){let g=m.getDeclarations(),v=g.filter(y=>M(y.getName(),n,r));v.length>0&&(g.length===v.length?s.push({node:m,action:"remove"}):v.forEach(y=>s.push({node:y,action:"remove"})))}let l=e.getFunctions();for(let m of l){let g=m.getName();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}let w=e.getInterfaces();for(let m of w){let g=m.getName();M(g,n,r)&&s.push({node:m,action:"remove"})}let d=e.getTypeAliases();for(let m of d){let g=m.getName();M(g,n,r)&&s.push({node:m,action:"remove"})}let h=e.getDescendantsOfKind($.PropertySignature);for(let m of h){let g=m.getName();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}let u=e.getDescendantsOfKind($.JsxElement);for(let m of u){let g=m.getOpeningElement().getTagNameNode().getText();M(g,n,r)&&s.push({node:m,action:"replace",newText:""})}let k=e.getDescendantsOfKind($.JsxSelfClosingElement);for(let m of k){let g=m.getTagNameNode().getText();M(g,n,r)&&s.push({node:m,action:"replace",newText:""})}let P=e.getDescendantsOfKind($.PropertyAssignment);for(let m of P){let g=m.getName();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}let x=e.getDescendantsOfKind($.JsxAttribute);for(let m of x){let g=m.getNameNode().getText();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}let I=e.getDescendantsOfKind($.Parameter);for(let m of I){let g=m.getName();if(g&&M(g,n,r)){let v=m.getParent();if(v&&(De.isFunctionDeclaration(v)||De.isArrowFunction(v)||De.isFunctionExpression(v)||De.isMethodDeclaration(v))){let y=v.getParameters(),T=y.indexOf(m);if(T!==-1){if(T===y.length-1&&T>0){let S=m.getPreviousSibling();S?.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}else{let S=m.getNextSibling();S?.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}s.push({node:m,action:"remove"})}}}}let b=e.getDescendantsOfKind($.CallExpression);for(let m of b){let g=m.getArguments();for(let v=0;v<g.length;v++){let y=g[v],T=y.getText();if(M(T,n,r)){if(v===g.length-1){let S=y.getPreviousSibling();S&&S.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}else{let S=y.getNextSibling();S&&S.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}s.push({node:y,action:"remove"})}}}let A=e.getDescendantsOfKind($.BindingElement);for(let m of A){let g=m.getName();if(g&&M(g,n,r)){let v=m.getParent();if(v){let y=v.getDescendantsOfKind($.BindingElement);if(y.indexOf(m)===y.length-1){let S=m.getPreviousSibling();S?.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}else{let S=m.getNextSibling();S?.getKind()===$.CommaToken&&s.push({node:S,action:"remove"})}}s.push({node:m,action:"remove"})}}let F=e.getDescendantsOfKind($.Identifier);for(let m of F){let g=m.getText();if(M(g,n,r)){let v=m.getParent();if(v){let y=v.getKind();if(y===$.CallExpression){let T=v;T.getExpression()===m?s.push({node:T,action:"remove"}):T.getArguments().findIndex(ne=>ne===m)!==-1&&s.push({node:m,action:"remove"})}if(y===$.PropertyAccessExpression){let T=v;T.getName()===g&&s.push({node:T,action:"remove"})}if((y===$.VariableDeclaration||y===$.BinaryExpression||y===$.IfStatement||y===$.ConditionalExpression)&&s.push({node:m,action:"remove"}),y===$.PropertyAssignment){let T=v;T.getInitializer()===m&&s.push({node:T,action:"remove"})}}}}let D=e.getDescendantsOfKind($.ShorthandPropertyAssignment);for(let m of D){let g=m.getName();g&&M(g,n,r)&&s.push({node:m,action:"remove"})}await Dr(e,t),s.sort((m,g)=>{let v=m.node.getStart?.()??0;return(g.node.getStart?.()??0)-v});for(let{node:m,action:g,newText:v}of s)try{if(m.wasForgotten?.()===!0)continue;g==="remove"?typeof m.remove=="function"&&m.remove():g==="replace"&&v!==void 0&&m.replaceWithText(v)}catch{}return e};import*as rn from"sass";async function on(e){try{return rn.compileString(e,{style:"expanded"}).css}catch(t){throw new Error(`Failed to compile SCSS to CSS: ${t instanceof Error?t.message:String(t)}`)}}import{Project as Mr,ScriptKind as Br}from"ts-morph";var Wr=new Mr({compilerOptions:{}});async function zr(e){let t=await Ur.mkdtemp(sn.join(Lr(),"tiptap-"));return sn.join(t,e)}async function an(e,t=[_e,Fe,Ue]){let n=me(e.config.resolvedPaths.cwd);if(e.filename.endsWith(".scss")&&n)return await on(e.raw);if(e.filename.endsWith(".scss")||e.filename.endsWith(".css")||e.filename.endsWith(".json"))return e.raw;let r=await zr(e.filename),s=Wr.createSourceFile(r,e.raw,{scriptKind:Br.TSX});for(let i of t)await i({sourceFile:s,...e});return e.transformJsx?await tn({sourceFile:s,...e}):s.getText()}import{confirm as Vr}from"@inquirer/prompts";async function vt(e,t,n){let r={filesCreated:[],filesUpdated:[],filesSkipped:[],errors:[]};if(!e?.length)return r;n={overwrite:!1,force:!1,silent:!1,...n};let s=C("Updating files.",{silent:n.silent})?.start();try{let[i,c]=await Promise.all([U(t.resolvedPaths.cwd),z(t.resolvedPaths.cwd)]);for(let p of e)try{if(!p.content)continue;let l;try{l=Hr(p,t,{isSrcDir:i?.isSrcDir,framework:i?.framework.name,commonRoot:qr(e.map(P=>P.path),p.path)})}catch(P){r.errors.push({file:p.path,error:`Failed to resolve file path: ${P instanceof Error?P.message:String(P)}`});continue}if(!l)continue;let w=Kr(p.path),d=J.dirname(l);t.tsx||(l=l.replace(/\.tsx?$/,P=>P===".tsx"?".jsx":".js")),me(t.resolvedPaths.cwd)&&l.endsWith(".scss")&&(l=l.replace(/\.scss$/,".css"));let u=!1;try{u=cn(l)}catch(P){r.errors.push({file:l,error:`Failed to check if file exists: ${P instanceof Error?P.message:String(P)}`});continue}let k;try{k=await an({filename:p.path,raw:p.content,config:t,transformJsx:!t.tsx,packageManager:c},[_e,Fe,Ue])}catch(P){r.errors.push({file:l,error:`Failed to transform content: ${P instanceof Error?P.message:String(P)}`});continue}if(u)try{let P=await Pt.readFile(l,"utf-8"),[x,I]=await Promise.all([ln(P),ln(k)]);if(x===I){r.filesSkipped.push(J.relative(t.resolvedPaths.cwd,l));continue}}catch(P){r.errors.push({file:l,error:`Failed to read or normalize existing file: ${P instanceof Error?P.message:String(P)}`});continue}if(u&&!n.overwrite){s?.stop(),n.rootSpinner&&n.rootSpinner?.stop();try{if(!await Vr({message:a.reset(`The file ${a.cyan(w)} already exists. Would you like to overwrite?`),theme:{prefix:a.cyan("?"),style:{message:x=>a.reset(x)}}})){r.filesSkipped.push(J.relative(t.resolvedPaths.cwd,l)),n.rootSpinner&&n.rootSpinner.start();continue}}catch(P){r.errors.push({file:l,error:`Failed to get user confirmation: ${P instanceof Error?P.message:String(P)}`});continue}finally{s?.start(),n.rootSpinner&&n.rootSpinner.start()}}try{cn(d)||await Pt.mkdir(d,{recursive:!0}),await Pt.writeFile(l,k,"utf-8"),u?r.filesUpdated.push(J.relative(t.resolvedPaths.cwd,l)):r.filesCreated.push(J.relative(t.resolvedPaths.cwd,l))}catch(P){r.errors.push({file:l,error:`Failed to write file: ${P instanceof Error?P.message:String(P)}`})}}catch(l){r.errors.push({file:p.path||"unknown",error:`Unexpected error processing file: ${l instanceof Error?l.message:String(l)}`})}}catch(i){o.error(`An error occurred while updating files: ${i instanceof Error?i.message:String(i)}`)}finally{if(!(r.filesCreated.length||r.filesUpdated.length)&&!r.filesSkipped.length&&s?.info("No files updated."),r.filesCreated.length){if(s?.stopAndPersist({symbol:a.cyan("\u2714"),text:`Created ${r.filesCreated.length} ${r.filesCreated.length===1?"file":"files"}:`}),!n.silent)for(let c of r.filesCreated)o.log(` - ${c}`)}else s?.stop();if(r.filesUpdated.length&&(C(`Updated ${r.filesUpdated.length} ${r.filesUpdated.length===1?"file":"files"}:`,{silent:n.silent})?.info(),!n.silent))for(let c of r.filesUpdated)o.log(` - ${c}`);if(r.filesSkipped.length&&(C(`Skipped ${r.filesSkipped.length} ${r.filesUpdated.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:n.silent})?.info(),!n.silent))for(let c of r.filesSkipped)o.log(` - ${c}`);if(r.errors.length&&(C(`Failed to process ${r.errors.length} ${r.errors.length===1?"file":"files"}:`,{silent:n.silent})?.fail(),!n.silent))for(let{file:c,error:p}of r.errors)o.error(` - ${c}: ${p}`);n.silent||o.break()}return r}function Jr(e,t,n){return n||(e.type==="registry:ui"?t.resolvedPaths.tiptapUi:e.type==="registry:ui-primitive"?t.resolvedPaths.tiptapUiPrimitives:e.type==="registry:ui-utils"?t.resolvedPaths.tiptapUiUtils:e.type==="registry:extension"?t.resolvedPaths.tiptapExtensions:e.type==="registry:node"?t.resolvedPaths.tiptapNodes:e.type==="registry:icon"?t.resolvedPaths.tiptapIcons:e.type==="registry:hook"?t.resolvedPaths.hooks:e.type==="registry:lib"?t.resolvedPaths.lib:e.type==="registry:context"?t.resolvedPaths.contexts:e.type==="registry:template"||e.type==="registry:component"?t.resolvedPaths.components:e.type==="registry:style"?t.resolvedPaths.styles:t.resolvedPaths.components)}function qr(e,t){let n=e.map(c=>c.replace(/^\//,"")),r=t.replace(/^\//,""),s=r.split("/").slice(0,-1).join("/");if(!s)return"";let i=s.split("/");for(let c=i.length;c>0;c--){let p=i.slice(0,c).join("/");if(n.some(w=>w!==r&&w.startsWith(p+"/")))return"/"+p}return"/"+s}async function ln(e){return e.replace(/\r\n/g,`
|
|
12
|
+
`).trim()}function Yr(e,t){if(!t)return"";if(t==="next-app")return e;if(t==="next-pages"){let n=e.replace(/^app\//,"pages/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}if(t==="react-router"){let n=e.replace(/^app\//,"app/routes/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}if(t==="laravel"){let n=e.replace(/^app\//,"resources/js/pages/");return n=n.replace(/\/page(\.[jt]sx?)$/,"$1"),n}return""}function Gr(e,t){let n=e.replace(/^\/|\/$/g,""),r=t.replace(/^\/|\/$/g,""),s=n.split("/"),i=r.split("/"),c=i[i.length-1],p=s.findIndex(l=>l===c);return p===-1?s[s.length-1]:s.slice(p+1).join("/")}function Hr(e,t,n){if(!e.target&&e.path.includes("tiptap-templates/")&&e.type!=="registry:page"){let i=e.path.match(/tiptap-templates\/([^/]+)\/(.*)/);if(i){let[,c,p]=i;if(p.startsWith("components/")){let l=p.replace("components/","");return J.join(t.resolvedPaths.components,"tiptap-templates",c,l)}return J.join(t.resolvedPaths.components,"tiptap-templates",c,p)}}if(e.target&&e.path.includes("tiptap-templates/")&&e.target.includes("/data/")){let i=e.path.match(/tiptap-templates\/([^/]+)\//);if(i){let c=i[1],p=e.target.split("/data/")[1];return J.join(t.resolvedPaths.components,"tiptap-templates",c,"data",p)}}if(e.target){if(e.target.startsWith("~/"))return J.join(t.resolvedPaths.cwd,e.target.replace("~/",""));let i=e.target;return e.type==="registry:page"&&(i=Yr(i,n.framework),!i)?"":n.isSrcDir?J.join(t.resolvedPaths.cwd,"src",i.replace("src/","")):J.join(t.resolvedPaths.cwd,i.replace("src/",""))}let r=Jr(e,t),s=Gr(e.path,r);return J.join(r,s)}import{z as Zr}from"zod";import{execa as Xr}from"execa";async function Tt(e,t,n){if(e=Array.from(new Set(e)),!e?.length)return;n={silent:!1,...n};let r=C("Installing development dependencies.",{silent:n.silent})?.start(),s=await z(t.resolvedPaths.cwd);r?.start(),await Xr(s,[s==="npm"?"install":"add",s==="npm"?"--save-dev":"-D",...e],{cwd:t.resolvedPaths.cwd}),r?.stopAndPersist({symbol:a.cyan("\u2714")})}async function Le(e,t,n){n={overwrite:!1,silent:!1,isNewProject:!1,...n};let r=await Bt(t);return r&&r.tiptapUi&&r.tiptapUi.resolvedPaths.cwd!==t.resolvedPaths.cwd?await eo(e,t,r,{...n}):await Qr(e,t,n)}async function Qr(e,t,n){let r=C("Checking registry",{silent:n.silent}).start(),s=await Gt(e,t);return s?(r.stopAndPersist({symbol:a.cyan("\u2714")}),await kt(s.dependencies,t,{silent:n.silent}),await Tt(s.devDependencies,t,{silent:n.silent}),await vt(s.files,t,{overwrite:n.overwrite,silent:n.silent})):(r?.fail(),_(new Error("Failed to fetch components from registry")))}async function eo(e,t,n,r){let s=C("Checking registry",{silent:r.silent}).start(),i=await xt(e),c=await je(i),p=Zr.array(ie).parse(c);if(!p.length)return s?.fail(),_(new Error("Failed to fetch components from registry"));s.stopAndPersist({symbol:a.cyan("\u2714")});let l=Zt(p),w=Xt(),d=[],h=[],u=[],k=C("Installing components")?.start();for(let x of p){let I=w.get(x.type),b=l.get(x.name);if(!I)continue;let A=(x.type==="registry:ui"||b?.type==="registry:ui")&&n.tiptapUi||t;if(!A.resolvedPaths.tiptapUi)continue;let F=gt(t.resolvedPaths.cwd,A.resolvedPaths.tiptapUi),D=await ut(F,A.resolvedPaths.cwd)??A.resolvedPaths.cwd;await kt(x.dependencies||[],A,{silent:!0}),await Tt(x.devDependencies||[],A,{silent:!0});let m=await vt(x.files||[],A,{overwrite:r.overwrite,silent:!0,rootSpinner:k});if(m.errors&&m.errors.length>0){C(`Encountered ${m.errors.length} errors:`,{silent:r.silent})?.fail();for(let{file:g,error:v}of m.errors)o.error(` - ${g}: ${v}`)}d.push(...m.filesCreated.map(g=>de.relative(F,de.join(D,g)))),h.push(...m.filesUpdated.map(g=>de.relative(F,de.join(D,g)))),u.push(...m.filesSkipped.map(g=>de.relative(F,de.join(D,g))))}if(k.stopAndPersist({symbol:a.cyan("\u2714")}),d.sort(),h.sort(),u.sort(),!(d.length||h.length)&&!u.length&&C("No files updated",{silent:r.silent})?.info(),d.length){C(`Created ${d.length} ${d.length===1?"file":"files"}:`,{silent:r.silent})?.stopAndPersist({symbol:a.cyan("\u2714")});for(let x of d)o.log(` - ${x}`)}if(h.length){C(`Updated ${h.length} ${h.length===1?"file":"files"}:`,{silent:r.silent})?.info();for(let x of h)o.log(` - ${x}`)}if(u.length){C(`Skipped ${u.length} ${u.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:r.silent})?.info();for(let x of u)o.log(` - ${x}`)}return{filesCreated:d,filesUpdated:h,filesSkipped:u}}function fe(e){return e.split(/[-_]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}import We from"node-fetch";import{HttpsProxyAgent as po}from"https-proxy-agent";import W from"fs-extra";import ae from"path";import to from"os";import{execa as ue}from"execa";import pn from"yaml";var Te="https://registry.tiptap.dev/",ce="//registry.tiptap.dev/:_authToken",ge="@tiptap-pro:registry";async function no(e){try{let t=ae.join(e,".gitignore"),n=".npmrc",r="";if(await W.pathExists(t)&&(r=await W.readFile(t,"utf8")),!r.split(`
|
|
13
13
|
`).some(c=>c.trim()===n||c.trim()==="/.npmrc"||c.trim()==="**/.npmrc")){let c=r.trim()?`${r}
|
|
14
14
|
|
|
15
15
|
# Authentication tokens
|
|
@@ -18,30 +18,30 @@ ${n}
|
|
|
18
18
|
${n}
|
|
19
19
|
`;await W.writeFile(t,c)}}catch(t){o.warn(`Could not update .gitignore: ${t instanceof Error?t.message:"Unknown error"}`)}}async function Me(e,t,n){try{let r=!1;switch(t){case"npm":await ro(e,n),r=!0;break;case"yarn":await oo(e,n),r=await W.pathExists(ae.join(n,".npmrc"));break;case"pnpm":case"bun":await mn(ae.join(n,".npmrc"),e),r=!0;break}return r&&await no(n),!0}catch(r){return o.error(`Error saving auth token: ${r instanceof Error?r.message:"Unknown error"}`),!1}}async function ro(e,t){await ue("npm",["config","set",ge,Te,"--location=project"],{cwd:t}),await ue("npm",["config","set",ce,e,"--location=project"],{cwd:t})}async function oo(e,t){try{let{stdout:n}=await ue("yarn",["--version"],{cwd:t});n.startsWith("1.")?(await ue("yarn",["config","set",ge,Te,"--location=project"],{cwd:t}),await ue("yarn",["config","set",ce,e,"--location=project"],{cwd:t})):await so(e,t)}catch{await mn(ae.join(t,".npmrc"),e)}}async function so(e,t){let n=ae.join(t,".yarnrc.yml"),r={};if(W.existsSync(n)){let s=await W.readFile(n,"utf8");try{r=pn.parse(s)||{}}catch{}}r.npmScopes||(r.npmScopes={}),r.npmScopes["tiptap-pro"]={npmRegistryServer:Te,npmAuthToken:e},await W.writeFile(n,pn.stringify(r))}async function mn(e,t){let n="";W.existsSync(e)&&(n=await W.readFile(e,"utf8"));let{lines:r,processedKeys:s}=io(n,t);s.has(ge)||r.push(`${ge}=${Te}`),s.has(ce)||r.push(`${ce}=${t}`),r.length>0&&r[r.length-1]!==""&&r.push(""),await W.writeFile(e,r.join(`
|
|
20
20
|
`))}function io(e,t){let n=[],r=new Set,s=e.split(`
|
|
21
|
-
`);for(let i of s){let c=i.trim();if(!c){n.push(i);continue}if(c.startsWith("#")){n.push(i);continue}let
|
|
22
|
-
`).filter(r=>r.startsWith("//registry.tiptap.dev/:_authToken="));return t.length===0?null:t[0].split("=")[1]?.trim()||null}var ze=`${X}/api/cli/v1`,Ke=process.env.https_proxy?new po(process.env.https_proxy):void 0;async function fn({email:e,password:t,packageManager:n,writeConfig:r=!0,cwd:s}){let i=
|
|
21
|
+
`);for(let i of s){let c=i.trim();if(!c){n.push(i);continue}if(c.startsWith("#")){n.push(i);continue}let p=i.indexOf("=");if(p!==-1){let l=i.substring(0,p).trim();l===ge?(n.push(`${ge}=${Te}`),r.add(l)):l===ce?(n.push(`${ce}=${t}`),r.add(l)):n.push(i)}else n.push(i)}return{lines:n,processedKeys:r}}async function Be(e,t){try{let n=await ao(t);return n||(e==="npm"?await co(t):await lo())}catch{return null}}async function ao(e){let t=ae.join(e,".npmrc");if(W.existsSync(t)){let n=await W.readFile(t,"utf8");return dn(n)}return null}async function co(e){let{stdout:t}=await ue("npm",["config","get",ce],{cwd:e});return t&&t!=="undefined"?t.trim():null}async function lo(){let e=ae.join(to.homedir(),".npmrc");if(W.existsSync(e)){let t=await W.readFile(e,"utf8");return dn(t)}return null}function dn(e){let t=e.split(`
|
|
22
|
+
`).filter(r=>r.startsWith("//registry.tiptap.dev/:_authToken="));return t.length===0?null:t[0].split("=")[1]?.trim()||null}var ze=`${X}/api/cli/v1`,Ke=process.env.https_proxy?new po(process.env.https_proxy):void 0;async function fn({email:e,password:t,packageManager:n,writeConfig:r=!0,cwd:s}){let i=C("Authenticating with Tiptap registry...")?.start();try{if(!e||!t)return i?.fail("Authentication failed"),{success:!1,error:"Invalid credentials"};let c=await mo(e,t),p=[],l=await We(`${ze}/plans`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c.bearerToken}`},agent:Ke});return l.ok?(p=(await l.json()).map(d=>d.name),p.length?(N.setBearerToken(c.bearerToken,{email:e,plans:p}),N.setAuthToken(c.authToken),r&&!await Me(c.authToken,n,s)?(i?.fail("Failed to save authentication token"),{success:!1,error:"Could not save authentication token"}):(i?.stopAndPersist({symbol:a.cyan("\u2714"),text:"Authentication successful"}),{success:!0,tokens:c})):(i?.fail("Authentication failed (no active plans)"),{success:!1,error:"No active plans found for user"})):(i?.fail("Authentication failed (could not load user plans)"),{success:!1,error:`Failed to fetch user plans: ${l.status}`})}catch(c){return i?.fail("Authentication failed"),{success:!1,error:c instanceof Error?c.message:"Unknown error during authentication"}}}async function mo(e,t){let n=await We(`${ze}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:t}),agent:Ke});if(!n.ok)throw new Error(`Error ${n.status}: ${n.statusText}`);let r=await n.json();return{bearerToken:r.token,authToken:r.authToken}}async function be(){try{let e=N.getBearerToken();if(!e)return{authenticated:!1};if(!N.isValidToken())return{authenticated:!1};let t=[];try{let s=await We(`${ze}/plans`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},agent:Ke});if(!s.ok)return N.clear(),{authenticated:!1};t=(await s.json()).map(p=>p.name);let c=N.getUserInfo();N.setBearerToken(e,{email:c.email,plans:t})}catch{return N.clear(),{authenticated:!1}}let n=N.getUserInfo(),r=N.getTokenExpiration();return{authenticated:!0,user:n.email||"unknown user",plans:t,expires:r,token:e}}catch(e){return o.error(`Auth status check error: ${e instanceof Error?e.message:"Unknown error"}`),{authenticated:!1}}}async function un(){try{let e=N.getBearerToken();return e&&((await We(`${ze}/logout`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},agent:Ke})).ok||o.warn("Logout API call failed, but clearing local tokens anyway")),N.clear(),{success:!0}}catch(e){return N.clear(),{success:!1,error:e instanceof Error?e.message:"Unknown error during logout"}}}import{Command as Se}from"commander";import{execa as fo}from"execa";import{z as he}from"zod";import{confirm as uo,input as go,password as ho}from"@inquirer/prompts";var gn=he.object({cwd:he.string(),email:he.string().optional(),password:he.string().optional(),writeConfig:he.boolean().optional(),showMessage:he.boolean().default(!0)}),yo=(e,t={})=>go({message:a.reset(e),required:t.required??!0,validate:t.validate??(n=>n?!0:"This field is required"),theme:{prefix:{done:a.cyan("\u2714"),idle:"?"}}}),wo=(e,t={})=>ho({message:a.reset(e),validate:t.validate??(n=>n?!0:"This field is required"),mask:"*",theme:{prefix:{done:a.cyan("\u2714"),idle:"?"}}}),Ie=(e,t=!0)=>uo({message:a.reset(e),default:t,theme:{prefix:{done:a.cyan("\u2714"),idle:"?"}}});function xo(e){switch(e){case"npm":return".npmrc (via npm config)";case"yarn":return".yarnrc.yml or .npmrc (depending on Yarn version)";case"pnpm":case"bun":return".npmrc";default:return"configuration file"}}async function ko(e,t,n){o.log(`To use this token, add it to your project's package manager configuration in ${a.cyan(n)}:`),e==="npm"?(o.log("Run these commands in your project directory:"),o.log(" npm config set @tiptap-pro:registry https://registry.tiptap.dev/"),o.log(` npm config set //registry.tiptap.dev/:_authToken ${t}`),o.log(`
|
|
23
23
|
Or add to your project's .npmrc file:`),o.log(" @tiptap-pro:registry=https://registry.tiptap.dev/"),o.log(` //registry.tiptap.dev/:_authToken=${t}`)):e==="yarn"?await Po(n)?(o.log("Run these commands in your project directory:"),o.log(" yarn config set @tiptap-pro:registry https://registry.tiptap.dev/"),o.log(` yarn config set //registry.tiptap.dev/:_authToken ${t}`)):(o.log("Add to your project's .yarnrc.yml file:"),o.log(`npmScopes:
|
|
24
24
|
tiptap-pro:
|
|
25
25
|
npmRegistryServer: "https://registry.tiptap.dev/"
|
|
26
26
|
npmAuthToken: "${t}"`)):(e==="pnpm"||e==="bun")&&(o.log("Add to your project's .npmrc file:"),o.log(a.cyan(`@tiptap-pro:registry=https://registry.tiptap.dev/
|
|
27
|
-
//registry.tiptap.dev/:_authToken=${t}`)))}async function Po(e){try{return(await fo("yarn",["--version"],{cwd:e})).stdout.startsWith("1.")}catch{return!1}}async function bt(e){let{email:t,password:n,writeConfig:r,showMessage:s}=e,{cwd:i}=e;t||(t=await yo("Email:",{validate:
|
|
28
|
-
Registry auth token saved to project directory for ${a.cyan(c)}`),o.log(`.npmrc file saved at: ${a.cyan(i)}`),o.log(`Project path: ${a.cyan(i)}`)):
|
|
29
|
-
Registry Auth Token: ${a.cyan(l.tokens.authToken)}`),o.log("This token should be added to your project's configuration:"),await ko(c,l.tokens.authToken,i)),s&&o.log("Bearer token saved globally for CLI authentication"),!0):(o.error("Authentication failed: "+l.error),!1)}async function vo(e){let t=await z(e),n=await be();if(n.authenticated){if(o.success(`Authenticated as ${a.cyan(n.user??"unknown user")}`),n.plans&&n.plans.length>0?n.plans.length===1?o.log(`Plan: ${a.cyan(n.plans[0])}`):o.log(`Plans: ${a.cyan(n.plans.join(", "))}`):o.log(`Plans: ${a.cyan("No active plans")}`),n.expires){let s=new Date(n.expires),i=new Date,c=Math.ceil((s.getTime()-i.getTime())/(1e3*60*60*24));c>30?o.log(`Token expires: ${a.cyan(s.toDateString())} (${c} days)`):c>0?o.log(`Token expires: ${a.yellow(s.toDateString())} (${c} days)`):o.log(`Token expires: ${a.red("Expired")}`)}if(n.token){let s=n.token.substring(0,10)+"...";o.log(`Bearer token: ${a.cyan(s)}`)}let r=await Be(t,e);if(r){let s=r.substring(0,10)+"...";o.log(`Registry token: ${a.cyan(s)}`)}else o.log(`Registry token: ${a.yellow("Not configured for this project")}`),o.log(`Run ${a.cyan("@tiptap/cli login --write-config")} to configure for this project`)}else o.log("Not authenticated with Tiptap registry"),o.log(`Run ${a.cyan("@tiptap/cli login")} to authenticate`)}var hn=new Se().command("login").description("log in to your Tiptap Cloud account").option("-e, --email <email>","your account email").option("-p, --password <password>","your account password").option("--write-config","write the auth token to your package manager config",void 0).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{try{let t=gn.parse(e);await bt(t)}catch(t){_(t)}}),yn=new Se().command("status").description("review your Tiptap Cloud authentication status").description("log out from your Tiptap registry account").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{let t=gn.parse(e),{cwd:n}=t;try{await vo(n)}catch(r){_(r)}}),wn=new Se().command("logout").description("log out from your Tiptap registry account").action(async()=>{try{let e=A("Logging out...")?.start(),t=await un();t.success?e?.stopAndPersist({symbol:a.cyan("\u2714"),text:"Successfully logged out"}):(e?.fail("Logout failed"),o.error("Logout failed: "+t.error))}catch(e){_(e)}});async function To(){o.log(""),o.log(a.yellow("\u{1F4CB} Tiptap Pro License Information")),o.log("");let e=N.hasAcceptedLicense(),t=N.getUserInfo();e?(o.log(`${a.cyan("\u2714")} Pro License and Terms of Service accepted`),t.email&&o.log(` Accepted by: ${a.cyan(t.email)}`),o.log("")):(o.log(a.yellow("\u26A0 Pro License and Terms of Service not yet accepted")),o.log(" License acceptance is required for using paid components"),o.log("")),o.log("License Details:"),o.log(` \u2022 Pro License: ${a.cyan("https://tiptap.dev/pro-license")}`),o.log(` \u2022 Terms of Service: ${a.cyan("https://tiptap.dev/terms-of-service")}`),o.log(""),o.log("About Paid Components:"),o.log(" Some paid UI components or templates are limited to specific plans."),o.log(" The license is valid during your trial period and active subscription."),o.log(""),e&&(o.log(a.gray("Available commands:")),o.log(a.gray(` \u2022 ${a.cyan("tiptap license forget me")} - Reset license acceptance`)),o.log(""))}async function bo(){if(!N.hasAcceptedLicense()){o.log(a.yellow("\u26A0 License has not been accepted yet"));return}await Ie("Are you sure you want to reset your license acceptance?",!1)?(N.clearLicenseAcceptance(),o.log(`${a.cyan("\u2714")} License acceptance has been reset`),o.log(" You will need to accept the license again when installing paid components")):o.log("License acceptance reset cancelled")}var xn=new Se().command("license").description("display Tiptap Pro license information and acceptance status").action(async()=>{try{await To()}catch(e){_(e)}}).addCommand(new Se().command("forget me").description("reset license acceptance status").action(async()=>{try{await bo()}catch(e){_(e)}}));function So(e){return e.some(t=>t.plans&&t.plans.some(n=>Re.includes(n)))}async function Io(e){if(e.filter(n=>n.plans&&n.plans.some(r=>Re.includes(r))).length===0)return!0;if(N.hasAcceptedLicense())return o.log(`${a.cyan("\u2714")} Pro license accepted`),!0;o.log(""),o.log(a.yellow("\u{1F4CB} License Agreement")),o.log(""),o.log("Integrating paid components requires accepting:"),o.log(` \u2022 Pro License: ${a.cyan("https://tiptap.dev/pro-license")}`),o.log(` \u2022 Terms of Service: ${a.cyan("https://tiptap.dev/terms-of-service")}`),o.log(""),o.log(a.gray(" Valid during trial and active subscription")),o.log("");try{return await Ie("Do you accept the Pro license and terms of service?",!1)?(N.setLicenseAccepted(),o.log(`${a.cyan("\u2714")} License accepted`),!0):(o.log(a.gray("License not accepted")),o.log(a.gray("Tip: You can still install free components")),!1)}catch{return o.log(a.gray("License acceptance cancelled")),!1}}async function ye(e,t){try{if(!So(e))return!0;if((await be()).authenticated){let s=await z(t);await Co(s,t)||await Ao(s,t)}else{if(o.log(""),o.log(a.yellow("\u{1F510} Authentication Required")),o.log(""),o.log("Pro components require authentication."),o.log(`Run ${a.cyan("tiptap login")} or create an account at ${a.cyan("https://cloud.tiptap.dev")}`),o.log(""),!await Ie("Would you like to login now?",!0))return o.log(""),o.log(a.gray("Authentication cancelled")),o.log(a.gray("Tip: You can still install free components")),!1;if(!await bt({cwd:t,writeConfig:!0,showMessage:!1}))return!1}return!!await Io(e)}catch(n){return o.error(`Authentication check failed: ${n instanceof Error?n.message:"Unknown error"}`),!1}}async function Co(e,t){try{return!!await Be(e,t)}catch{return!1}}async function Ao(e,t){let n=A("Creating registry configuration...")?.start();try{if(!(await be()).authenticated)return n?.fail("Cannot create configuration - user not authenticated"),!1;let s=N.getAuthToken();if(!s)return n?.fail("No authentication token found"),!1;if(!await Me(s,e,t))return n?.fail("Failed to save authentication token"),!1;n?.stopAndPersist({symbol:a.cyan("\u2714"),text:".npmrc created successfully"})}catch(r){n?.fail("Failed to create registry configuration"),o.error(`Configuration error: ${r instanceof Error?r.message:"Unknown error"}`)}}import Ve from"process";function kn(){return Ve.stdout.columns||80}function Pn(e,t,n){let r=n?.borderColor||"gray",s=n?.padding!==!1,i="",c="",l="",p="",w="-",d="",h=kn(),f=Math.min(h-4,80),x=a[r],k=x(i+w.repeat(f-2)+c),P=x(l+w.repeat(f-2)+p),I=x(d),T=[];s&&T.push(""),T.push(k),T.push(`${I}${" ".repeat(f-2)}${I}`);let C=Math.floor((f-4-St(e).length)/2),F=e.padStart(C+St(e).length).padEnd(f-4);return T.push(`${I} ${F} ${I}`),T.push(`${I}${" ".repeat(f-2)}${I}`),t.forEach(U=>{let m=St(U).length,g=f-4-m,v=U+" ".repeat(Math.max(0,g));T.push(`${I} ${v} ${I}`)}),t.length>0&&T.push(`${I}${" ".repeat(f-2)}${I}`),T.push(P),s&&T.push(""),T}function Je(e,t){let n=t?[t]:[];return Pn(`${e}`,n,{borderColor:"gray"})}function qe(e,t){return Pn(`\u26A0\uFE0F ${e}`,t,{borderColor:"yellow"})}function G(e){e.forEach(t=>o.log(t))}function St(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function Ye(e,t){let n=[];return n.push(""),n.push(a.cyan(e)),n.push(""),t.forEach(r=>{n.push(` \u2022 ${r}`)}),n.push(""),n}function Ge(){Ve.stdout.write("\x1B[2J\x1B[0f"),Ve.platform==="win32"&&Ve.stdout.write("\x1B[2J\x1B[3J\x1B[H")}function It(){let e=Math.min(kn()-4,80);return a.gray("-".repeat(e))}import{existsSync as vn}from"fs";import Tn from"path";function bn(e){let t=e.name;return t===u["next-app"].name||t===u["next-pages"].name?"NEXT_PUBLIC_":t===u.astro.name?"PUBLIC_":t===u.vite.name||t===u["tanstack-start"].name||t===u["react-router"].name?"VITE_":(t===u.laravel.name||t===u.manual.name,"")}function Sn(e){if(!e?.resolvedPaths?.styles)return"scss";let t=e.resolvedPaths.styles,n=Tn.join(t,"_variables.scss"),r=Tn.join(t,"_variables.css");return vn(r)?"css":(vn(n),"scss")}function In(e,t){let n=e?.name||"unknown",r=t?.resolvedPaths?.styles?.includes("/src/"),s=t?.resolvedPaths?.components?.includes("/src/"),i="your main CSS file",c="./styles/";switch(n){case u["next-app"].name:s?(i="src/app/globals.css",c="../styles/"):r?(i="app/globals.css",c="../src/styles/"):(i="app/globals.css",c="../styles/");break;case u["next-pages"].name:s||r?(i="src/styles/globals.css",c="./"):(i="styles/globals.css",c="./");break;case u.vite.name:i="src/index.css",c="./styles/";break;case u["react-router"].name:i="src/index.css",c="./styles/";break;case u["tanstack-start"].name:i="src/index.css",c="./styles/";break;case u.astro.name:r?(i="src/layouts/Layout.astro",c="../styles/"):(i="src/layouts/Layout.astro",c="../../styles/");break;case u.laravel.name:i="resources/css/app.css",c="../styles/";break;case u.manual.name:default:s||r?(i="src/index.css",c="./styles/"):(i="your main CSS file",c="./styles/");break}return{cssFile:i,importPath:c}}function we(e,t){let n=Sn(t),{cssFile:r,importPath:s}=In(e,t),i=["The editor requires these style imports:","",`Add to ${a.cyan(r)}:`,"",a.yellow(` @import '${s}_variables.${n}';`),a.yellow(` @import '${s}_keyframe-animations.${n}';`),"","Without these imports, the editor will not display correctly.","",`Setup guide: ${a.cyan("https://tiptap.dev/docs/ui-components/getting-started/style")}`],c=qe("Action Required: Import Styles",i);G(c)}function He(e){let t=bn(e),n=["The Notion-like template requires environment variables for collaborative features:","",a.yellow(`${t}TIPTAP_COLLAB_DOC_PREFIX`)+" - Document prefix (required)",a.yellow(`${t}TIPTAP_COLLAB_APP_ID`)+" - Document Server App ID (required)",a.yellow(`${t}TIPTAP_COLLAB_TOKEN`)+" - JWT token for collaboration (required)",a.yellow(`${t}TIPTAP_AI_APP_ID`)+" - AI App ID (required)",a.yellow(`${t}TIPTAP_AI_TOKEN`)+" - JWT token for AI (required)","","Get these credentials from your account at cloud.tiptap.dev","",`Setup guide: ${a.cyan("https://tiptap.dev/docs/ui-components/templates/notion-like-editor")}`],r=qe("Action Required: Environment Setup",n);G(r)}function Xe(e,t){let n=bn(e),r=Sn(t),{cssFile:s,importPath:i}=In(e,t),c=["The Notion-like template is a complete editor application that requires","additional configuration before it can be used:","",a.cyan("1. Import Required Styles"),` Add to ${a.yellow(s)}:`,a.gray(` @import '${i}_variables.${r}';`),a.gray(` @import '${i}_keyframe-animations.${r}';`),"",a.cyan("2. Add Environment Variables (for collaborative features)")," Add to your .env file:",a.gray(` ${n}TIPTAP_COLLAB_DOC_PREFIX - Document prefix`),a.gray(` ${n}TIPTAP_COLLAB_APP_ID - Document Server App ID`),a.gray(` ${n}TIPTAP_COLLAB_TOKEN - JWT token for collaboration`),a.gray(` ${n}TIPTAP_AI_APP_ID - AI App ID`),a.gray(` ${n}TIPTAP_AI_TOKEN - JWT token for AI`),"",`Get credentials at ${a.cyan("https://cloud.tiptap.dev")}`,`Setup guide: ${a.cyan("https://tiptap.dev/docs/ui-components/templates/notion-like-editor")}`],l=qe("Next Steps: Configure your Editor",c);G(l)}function Ze(){o.log(""),o.log(a.cyan("\u2192 Table Node integration guide:")),o.log(` ${a.dim("https://tiptap.dev/docs/ui-components/node-components/table-node#usage")}`),o.log("")}import{existsSync as Qe,promises as Cn}from"fs";import j from"path";function Eo(e){if(!e?.resolvedPaths?.styles)return"scss";let t=e.resolvedPaths.styles,n=j.join(t,"_variables.scss"),r=j.join(t,"_variables.css");return Qe(r)?"css":(Qe(n),"scss")}function $o(e,t){let n=e.name,r=t.resolvedPaths.cwd,s=t.resolvedPaths.components?.includes("/src/"),i=t.resolvedPaths.styles?.includes("/src/"),c=[];switch(n){case u["next-app"].name:s?c=[j.join(r,"src/app/globals.css"),j.join(r,"src/app/globals.scss")]:c=[j.join(r,"app/globals.css"),j.join(r,"app/globals.scss")];break;case u["next-pages"].name:s?c=[j.join(r,"src/styles/globals.css"),j.join(r,"src/styles/globals.scss")]:c=[j.join(r,"styles/globals.css"),j.join(r,"styles/globals.scss")];break;case u.vite.name:case u["react-router"].name:case u["tanstack-start"].name:c=[j.join(r,"src/index.css"),j.join(r,"src/main.css"),j.join(r,"src/App.css")];break;case u.astro.name:c=[j.join(r,"src/styles/main.css"),j.join(r,"src/styles/global.css")];break;case u.laravel.name:c=[j.join(r,"resources/css/app.css")];break;case u.manual.name:default:s||i?c=[j.join(r,"src/index.css"),j.join(r,"src/main.css"),j.join(r,"src/App.css"),j.join(r,"src/styles/main.css")]:c=[j.join(r,"index.css"),j.join(r,"main.css"),j.join(r,"styles/main.css")];break}for(let l of c)if(Qe(l))return l;return c[0]||null}function Ro(e,t){let n=j.dirname(e),r=j.relative(n,t);return r=r.replace(/\\/g,"/"),r.startsWith(".")||(r="./"+r),r.endsWith("/")||(r+="/"),r}function No(e,t){let n=new RegExp(`@import\\s+['"].*_variables\\.${t}['"]`,"i"),r=new RegExp(`@import\\s+['"].*_keyframe-animations\\.${t}['"]`,"i");return n.test(e)&&r.test(e)}async function Q(e,t,n){try{if(![...e.filesCreated||[],...e.filesUpdated||[],...e.filesSkipped||[]].some(h=>h.includes("_variables.")||h.includes("_keyframe-animations.")))return{success:!0,message:"No style files to import"};let i=Eo(t),c=$o(n,t);if(!c)return{success:!1,message:"Could not determine main CSS file location"};if(!Qe(c))return{success:!1,message:`Main CSS file not found at ${c}`};let l=await Cn.readFile(c,"utf-8");if(No(l,i))return{success:!0,message:"Style imports already exist",filePath:c};let p=Ro(c,t.resolvedPaths.styles),d=`${[`@import '${p}_variables.${i}';`,`@import '${p}_keyframe-animations.${i}';`].join(`
|
|
27
|
+
//registry.tiptap.dev/:_authToken=${t}`)))}async function Po(e){try{return(await fo("yarn",["--version"],{cwd:e})).stdout.startsWith("1.")}catch{return!1}}async function bt(e){let{email:t,password:n,writeConfig:r,showMessage:s}=e,{cwd:i}=e;t||(t=await yo("Email:",{validate:l=>l?!0:"Please enter your email"})),n||(n=await wo("Password:",{validate:l=>l?!0:"Please enter your password"})),(!t||!n)&&(o.error("Authentication cancelled"),process.exit(0));let c=await z(i);if(r===void 0){let l=xo(c);r=await Ie(`Would you like to save the auth token to your ${l}?`),r===void 0&&(o.error("Authentication cancelled"),process.exit(0))}let p=await fn({email:t,password:n,packageManager:c,writeConfig:r??!1,cwd:i});return p.success&&p.tokens?(r&&s?(o.log(`
|
|
28
|
+
Registry auth token saved to project directory for ${a.cyan(c)}`),o.log(`.npmrc file saved at: ${a.cyan(i)}`),o.log(`Project path: ${a.cyan(i)}`)):p.tokens.authToken&&s&&(o.log(`
|
|
29
|
+
Registry Auth Token: ${a.cyan(p.tokens.authToken)}`),o.log("This token should be added to your project's configuration:"),await ko(c,p.tokens.authToken,i)),s&&o.log("Bearer token saved globally for CLI authentication"),!0):(o.error("Authentication failed: "+p.error),!1)}async function vo(e){let t=await z(e),n=await be();if(n.authenticated){if(o.success(`Authenticated as ${a.cyan(n.user??"unknown user")}`),n.plans&&n.plans.length>0?n.plans.length===1?o.log(`Plan: ${a.cyan(n.plans[0])}`):o.log(`Plans: ${a.cyan(n.plans.join(", "))}`):o.log(`Plans: ${a.cyan("No active plans")}`),n.expires){let s=new Date(n.expires),i=new Date,c=Math.ceil((s.getTime()-i.getTime())/(1e3*60*60*24));c>30?o.log(`Token expires: ${a.cyan(s.toDateString())} (${c} days)`):c>0?o.log(`Token expires: ${a.yellow(s.toDateString())} (${c} days)`):o.log(`Token expires: ${a.red("Expired")}`)}if(n.token){let s=n.token.substring(0,10)+"...";o.log(`Bearer token: ${a.cyan(s)}`)}let r=await Be(t,e);if(r){let s=r.substring(0,10)+"...";o.log(`Registry token: ${a.cyan(s)}`)}else o.log(`Registry token: ${a.yellow("Not configured for this project")}`),o.log(`Run ${a.cyan("@tiptap/cli login --write-config")} to configure for this project`)}else o.log("Not authenticated with Tiptap registry"),o.log(`Run ${a.cyan("@tiptap/cli login")} to authenticate`)}var hn=new Se().command("login").description("log in to your Tiptap Cloud account").option("-e, --email <email>","your account email").option("-p, --password <password>","your account password").option("--write-config","write the auth token to your package manager config",void 0).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{try{let t=gn.parse(e);await bt(t)}catch(t){_(t)}}),yn=new Se().command("status").description("review your Tiptap Cloud authentication status").description("log out from your Tiptap registry account").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{let t=gn.parse(e),{cwd:n}=t;try{await vo(n)}catch(r){_(r)}}),wn=new Se().command("logout").description("log out from your Tiptap registry account").action(async()=>{try{let e=C("Logging out...")?.start(),t=await un();t.success?e?.stopAndPersist({symbol:a.cyan("\u2714"),text:"Successfully logged out"}):(e?.fail("Logout failed"),o.error("Logout failed: "+t.error))}catch(e){_(e)}});async function To(){o.log(""),o.log(a.yellow("\u{1F4CB} Tiptap Pro License Information")),o.log("");let e=N.hasAcceptedLicense(),t=N.getUserInfo();e?(o.log(`${a.cyan("\u2714")} Pro License and Terms of Service accepted`),t.email&&o.log(` Accepted by: ${a.cyan(t.email)}`),o.log("")):(o.log(a.yellow("\u26A0 Pro License and Terms of Service not yet accepted")),o.log(" License acceptance is required for using paid components"),o.log("")),o.log("License Details:"),o.log(` \u2022 Pro License: ${a.cyan("https://tiptap.dev/pro-license")}`),o.log(` \u2022 Terms of Service: ${a.cyan("https://tiptap.dev/terms-of-service")}`),o.log(""),o.log("About Paid Components:"),o.log(" Some paid UI components or templates are limited to specific plans."),o.log(" The license is valid during your trial period and active subscription."),o.log(""),e&&(o.log(a.gray("Available commands:")),o.log(a.gray(` \u2022 ${a.cyan("tiptap license forget me")} - Reset license acceptance`)),o.log(""))}async function bo(){if(!N.hasAcceptedLicense()){o.log(a.yellow("\u26A0 License has not been accepted yet"));return}await Ie("Are you sure you want to reset your license acceptance?",!1)?(N.clearLicenseAcceptance(),o.log(`${a.cyan("\u2714")} License acceptance has been reset`),o.log(" You will need to accept the license again when installing paid components")):o.log("License acceptance reset cancelled")}var xn=new Se().command("license").description("display Tiptap Pro license information and acceptance status").action(async()=>{try{await To()}catch(e){_(e)}}).addCommand(new Se().command("forget me").description("reset license acceptance status").action(async()=>{try{await bo()}catch(e){_(e)}}));function So(e){return e.some(t=>t.plans&&t.plans.some(n=>Re.includes(n)))}async function Io(e){if(e.filter(n=>n.plans&&n.plans.some(r=>Re.includes(r))).length===0)return!0;if(N.hasAcceptedLicense())return o.log(`${a.cyan("\u2714")} Pro license accepted`),!0;o.log(""),o.log(a.yellow("\u{1F4CB} License Agreement")),o.log(""),o.log("Integrating paid components requires accepting:"),o.log(` \u2022 Pro License: ${a.cyan("https://tiptap.dev/pro-license")}`),o.log(` \u2022 Terms of Service: ${a.cyan("https://tiptap.dev/terms-of-service")}`),o.log(""),o.log(a.gray(" Valid during trial and active subscription")),o.log("");try{return await Ie("Do you accept the Pro license and terms of service?",!1)?(N.setLicenseAccepted(),o.log(`${a.cyan("\u2714")} License accepted`),!0):(o.log(a.gray("License not accepted")),o.log(a.gray("Tip: You can still install free components")),!1)}catch{return o.log(a.gray("License acceptance cancelled")),!1}}async function ye(e,t){try{if(!So(e))return!0;if((await be()).authenticated){let s=await z(t);await Co(s,t)||await Ao(s,t)}else{if(o.log(""),o.log(a.yellow("\u{1F510} Authentication Required")),o.log(""),o.log("Pro components require authentication."),o.log(`Run ${a.cyan("tiptap login")} or create an account at ${a.cyan("https://cloud.tiptap.dev")}`),o.log(""),!await Ie("Would you like to login now?",!0))return o.log(""),o.log(a.gray("Authentication cancelled")),o.log(a.gray("Tip: You can still install free components")),!1;if(!await bt({cwd:t,writeConfig:!0,showMessage:!1}))return!1}return!!await Io(e)}catch(n){return o.error(`Authentication check failed: ${n instanceof Error?n.message:"Unknown error"}`),!1}}async function Co(e,t){try{return!!await Be(e,t)}catch{return!1}}async function Ao(e,t){let n=C("Creating registry configuration...")?.start();try{if(!(await be()).authenticated)return n?.fail("Cannot create configuration - user not authenticated"),!1;let s=N.getAuthToken();if(!s)return n?.fail("No authentication token found"),!1;if(!await Me(s,e,t))return n?.fail("Failed to save authentication token"),!1;n?.stopAndPersist({symbol:a.cyan("\u2714"),text:".npmrc created successfully"})}catch(r){n?.fail("Failed to create registry configuration"),o.error(`Configuration error: ${r instanceof Error?r.message:"Unknown error"}`)}}import Ve from"process";function kn(){return Ve.stdout.columns||80}function Pn(e,t,n){let r=n?.borderColor||"gray",s=n?.padding!==!1,i="",c="",p="",l="",w="-",d="",h=kn(),u=Math.min(h-4,80),k=a[r],P=k(i+w.repeat(u-2)+c),x=k(p+w.repeat(u-2)+l),I=k(d),b=[];s&&b.push(""),b.push(P),b.push(`${I}${" ".repeat(u-2)}${I}`);let A=Math.floor((u-4-St(e).length)/2),F=e.padStart(A+St(e).length).padEnd(u-4);return b.push(`${I} ${F} ${I}`),b.push(`${I}${" ".repeat(u-2)}${I}`),t.forEach(D=>{let m=St(D).length,g=u-4-m,v=D+" ".repeat(Math.max(0,g));b.push(`${I} ${v} ${I}`)}),t.length>0&&b.push(`${I}${" ".repeat(u-2)}${I}`),b.push(x),s&&b.push(""),b}function Je(e,t){let n=t?[t]:[];return Pn(`${e}`,n,{borderColor:"gray"})}function qe(e,t){return Pn(`\u26A0\uFE0F ${e}`,t,{borderColor:"yellow"})}function G(e){e.forEach(t=>o.log(t))}function St(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function Ye(e,t){let n=[];return n.push(""),n.push(a.cyan(e)),n.push(""),t.forEach(r=>{n.push(` \u2022 ${r}`)}),n.push(""),n}function Ge(){Ve.stdout.write("\x1B[2J\x1B[0f"),Ve.platform==="win32"&&Ve.stdout.write("\x1B[2J\x1B[3J\x1B[H")}function It(){let e=Math.min(kn()-4,80);return a.gray("-".repeat(e))}import{existsSync as vn}from"fs";import Tn from"path";function bn(e){let t=e.name;return t===f["next-app"].name||t===f["next-pages"].name?"NEXT_PUBLIC_":t===f.astro.name?"PUBLIC_":t===f.vite.name||t===f["tanstack-start"].name||t===f["react-router"].name?"VITE_":(t===f.laravel.name||t===f.manual.name,"")}function Sn(e){if(!e?.resolvedPaths?.styles)return"scss";let t=e.resolvedPaths.styles,n=Tn.join(t,"_variables.scss"),r=Tn.join(t,"_variables.css");return vn(r)?"css":(vn(n),"scss")}function In(e,t){let n=e?.name||"unknown",r=t?.resolvedPaths?.styles?.includes("/src/"),s=t?.resolvedPaths?.components?.includes("/src/"),i="your main CSS file",c="./styles/";switch(n){case f["next-app"].name:s?(i="src/app/globals.css",c="../styles/"):r?(i="app/globals.css",c="../src/styles/"):(i="app/globals.css",c="../styles/");break;case f["next-pages"].name:s||r?(i="src/styles/globals.css",c="./"):(i="styles/globals.css",c="./");break;case f.vite.name:i="src/index.css",c="./styles/";break;case f["react-router"].name:i="src/index.css",c="./styles/";break;case f["tanstack-start"].name:i="src/index.css",c="./styles/";break;case f.astro.name:r?(i="src/layouts/Layout.astro",c="../styles/"):(i="src/layouts/Layout.astro",c="../../styles/");break;case f.laravel.name:i="resources/css/app.css",c="../styles/";break;case f.manual.name:default:s||r?(i="src/index.css",c="./styles/"):(i="your main CSS file",c="./styles/");break}return{cssFile:i,importPath:c}}function we(e,t){let n=Sn(t),{cssFile:r,importPath:s}=In(e,t),i=["The editor requires these style imports:","",`Add to ${a.cyan(r)}:`,"",a.yellow(` @import '${s}_variables.${n}';`),a.yellow(` @import '${s}_keyframe-animations.${n}';`),"","Without these imports, the editor will not display correctly.","",`Setup guide: ${a.cyan("https://tiptap.dev/docs/ui-components/getting-started/style")}`],c=qe("Action Required: Import Styles",i);G(c)}function He(e){let t=bn(e),n=["The Notion-like template requires environment variables for collaborative features:","",a.yellow(`${t}TIPTAP_COLLAB_DOC_PREFIX`)+" - Document prefix (required)",a.yellow(`${t}TIPTAP_COLLAB_APP_ID`)+" - Document Server App ID (required)",a.yellow(`${t}TIPTAP_COLLAB_TOKEN`)+" - JWT token for collaboration (required)",a.yellow(`${t}TIPTAP_AI_APP_ID`)+" - AI App ID (required)",a.yellow(`${t}TIPTAP_AI_TOKEN`)+" - JWT token for AI (required)","","Get these credentials from your account at cloud.tiptap.dev","",`Setup guide: ${a.cyan("https://tiptap.dev/docs/ui-components/templates/notion-like-editor")}`],r=qe("Action Required: Environment Setup",n);G(r)}function Xe(e,t){let n=bn(e),r=Sn(t),{cssFile:s,importPath:i}=In(e,t),c=["The Notion-like template is a complete editor application that requires","additional configuration before it can be used:","",a.cyan("1. Import Required Styles"),` Add to ${a.yellow(s)}:`,a.gray(` @import '${i}_variables.${r}';`),a.gray(` @import '${i}_keyframe-animations.${r}';`),"",a.cyan("2. Add Environment Variables (for collaborative features)")," Add to your .env file:",a.gray(` ${n}TIPTAP_COLLAB_DOC_PREFIX - Document prefix`),a.gray(` ${n}TIPTAP_COLLAB_APP_ID - Document Server App ID`),a.gray(` ${n}TIPTAP_COLLAB_TOKEN - JWT token for collaboration`),a.gray(` ${n}TIPTAP_AI_APP_ID - AI App ID`),a.gray(` ${n}TIPTAP_AI_TOKEN - JWT token for AI`),"",`Get credentials at ${a.cyan("https://cloud.tiptap.dev")}`,`Setup guide: ${a.cyan("https://tiptap.dev/docs/ui-components/templates/notion-like-editor")}`],p=qe("Next Steps: Configure your Editor",c);G(p)}function Ze(){o.log(""),o.log(a.cyan("\u2192 Table Node integration guide:")),o.log(` ${a.dim("https://tiptap.dev/docs/ui-components/node-components/table-node#usage")}`),o.log("")}import{existsSync as Qe,promises as Cn}from"fs";import j from"path";function Eo(e){if(!e?.resolvedPaths?.styles)return"scss";let t=e.resolvedPaths.styles,n=j.join(t,"_variables.scss"),r=j.join(t,"_variables.css");return Qe(r)?"css":(Qe(n),"scss")}function $o(e,t){let n=e.name,r=t.resolvedPaths.cwd,s=t.resolvedPaths.components?.includes("/src/"),i=t.resolvedPaths.styles?.includes("/src/"),c=[];switch(n){case f["next-app"].name:s?c=[j.join(r,"src/app/globals.css"),j.join(r,"src/app/globals.scss")]:c=[j.join(r,"app/globals.css"),j.join(r,"app/globals.scss")];break;case f["next-pages"].name:s?c=[j.join(r,"src/styles/globals.css"),j.join(r,"src/styles/globals.scss")]:c=[j.join(r,"styles/globals.css"),j.join(r,"styles/globals.scss")];break;case f.vite.name:case f["react-router"].name:case f["tanstack-start"].name:c=[j.join(r,"src/index.css"),j.join(r,"src/main.css"),j.join(r,"src/App.css")];break;case f.astro.name:c=[j.join(r,"src/styles/main.css"),j.join(r,"src/styles/global.css")];break;case f.laravel.name:c=[j.join(r,"resources/css/app.css")];break;case f.manual.name:default:s||i?c=[j.join(r,"src/index.css"),j.join(r,"src/main.css"),j.join(r,"src/App.css"),j.join(r,"src/styles/main.css")]:c=[j.join(r,"index.css"),j.join(r,"main.css"),j.join(r,"styles/main.css")];break}for(let p of c)if(Qe(p))return p;return c[0]||null}function Ro(e,t){let n=j.dirname(e),r=j.relative(n,t);return r=r.replace(/\\/g,"/"),r.startsWith(".")||(r="./"+r),r.endsWith("/")||(r+="/"),r}function No(e,t){let n=new RegExp(`@import\\s+['"].*_variables\\.${t}['"]`,"i"),r=new RegExp(`@import\\s+['"].*_keyframe-animations\\.${t}['"]`,"i");return n.test(e)&&r.test(e)}async function Q(e,t,n){try{if(![...e.filesCreated||[],...e.filesUpdated||[],...e.filesSkipped||[]].some(h=>h.includes("_variables.")||h.includes("_keyframe-animations.")))return{success:!0,message:"No style files to import"};let i=Eo(t),c=$o(n,t);if(!c)return{success:!1,message:"Could not determine main CSS file location"};if(!Qe(c))return{success:!1,message:`Main CSS file not found at ${c}`};let p=await Cn.readFile(c,"utf-8");if(No(p,i))return{success:!0,message:"Style imports already exist",filePath:c};let l=Ro(c,t.resolvedPaths.styles),d=`${[`@import '${l}_variables.${i}';`,`@import '${l}_keyframe-animations.${i}';`].join(`
|
|
30
30
|
`)}
|
|
31
31
|
|
|
32
|
-
${
|
|
33
|
-
${a.dim(
|
|
34
|
-
${Ce.missingDirectory}`),process.exit(0)),!w)throw new Error(`Failed to read config at ${a.cyan(s.cwd)}.`);let d=await Le(s.components,w,s);if(!d)throw new Error("Component addition failed.");let h=(d.filesCreated?.length||0)+(d.filesUpdated?.length||0)+(d.filesSkipped?.length||0);if(d&&h>0){let
|
|
32
|
+
${p}`;return await Cn.writeFile(c,d,"utf-8"),{success:!0,message:"Style imports added",filePath:c}}catch(r){return o.error(`Failed to auto-import styles: ${r instanceof Error?r.message:String(r)}`),{success:!1,message:`Failed to auto-import styles: ${r instanceof Error?r.message:String(r)}`}}}function ee(e){if(!e.success){o.warn(a.yellow(`\u26A0 ${e.message}`));return}if(e.message==="No style files to import"||e.message==="Style imports already exist")return;let n=(e.filePath?j.relative(process.cwd(),e.filePath):"main CSS file").replace(/\.\.\//g,"");o.log(`${a.green("\u2714")} Style imports automatically added to ${a.cyan(n)}`),o.log("")}var Do=le.object({components:le.array(le.string()).optional(),cwd:le.string(),path:le.string().optional(),silent:le.boolean(),overwrite:le.boolean()}),Uo=1e3,Ce={emptyRegistry:a.red("\u274C No components or templates found"),operationCancelled:a.gray("Operation cancelled"),missingDirectory:a.red("\u274C Directory not found. Use init to initialize a project first.")},Ct={icon:{cursor:a.cyan("\u25B8"),checked:a.cyan("\u25C9"),unchecked:"\u25CB"},style:{highlight:e=>a.cyan(e),message:e=>e,answer:e=>""},prefix:{done:a.cyan("\u2714"),idle:a.cyan("?")}};function Lo(e,t){return t?e.filter(n=>t.includes(n.name)):e}function At(e){for(let t=0;t<e;t++)process.stdout.write("\x1B[1A"),process.stdout.write("\x1B[2K")}var Mo=e=>({templates:e.filter(t=>t.type==="registry:template"),newComponents:e.filter(t=>t.isNew===!0),ui:e.filter(t=>t.type==="registry:ui"),primitives:e.filter(t=>t.type==="registry:ui-primitive"),uiUtils:e.filter(t=>t.type==="registry:ui-utils"),nodes:e.filter(t=>t.type==="registry:node")});async function Bo(e,t=!0){let n="What would you like to integrate?",r=[],s=e.ui.length===0&&e.nodes.length===0&&e.newComponents.length===0;if(e.templates.length===0||r.push({name:"Templates - Full editor applications",value:"templates"}),s||r.push({name:"UI Components - Individual editor building blocks",value:"components"}),r.length===0)return o.break(),console.log(Ce.emptyRegistry),null;try{t&&console.log(It());let c=await Pe({message:a.reset(n),pageSize:Uo,theme:Ct,choices:r});return t&&console.log(It()),c}catch{return At(4),console.log(Ce.operationCancelled),null}}async function Wo(e,t){let n=[];if(!t)return n;let r=(i,c)=>{let p=i.filter(l=>t.includes(l.name));p.length>0&&(n.push(new xe("")),n.push(new xe(a.whiteBold(` ${c}`))),p.forEach(l=>{let w=l.plans&&l.plans.length?l.plans.includes("light")?"Open source (MIT)":"Start plan \u2022 Trial":"Free",h=fe(l.name).padEnd(35);n.push({name:`${h} ${a.dim(w)}`,value:l.name})}),n.push(new xe(" ")))};return((i,c)=>{let p=i.filter(l=>t.includes(l.name));p.length>0&&(n.push(new xe("")),n.push(new xe(a.whiteBold(` ${c}`))),p.forEach(l=>{let w=l.plans&&l.plans.length?l.plans.includes("light")?"Open source (MIT)":"Start plan \u2022 Trial":"Free",h=fe(l.name).padEnd(35),u=l.description?`
|
|
33
|
+
${a.dim(l.description)}`:"";n.push({name:`${h} ${a.dim(w)}${u}`,value:l.name})}),n.push(new xe(" ")))})(e.newComponents,"NEW COMPONENTS"),r(e.ui,"UI COMPONENTS"),r(e.nodes,"NODE COMPONENTS"),r(e.primitives,"PRIMITIVES"),n}async function zo(e,t){let n=await Wo(e,t);if(n.length===0)return[];try{o.log(""),o.log(a.cyan(" Press Space to select \u2022 A to toggle all \u2022 Enter to confirm"));let r=await Fo({message:"Choose UI components to install:",pageSize:20,choices:n,theme:Ct,validate:s=>s.length===0?"Select at least one component (use Space to select, then Enter to confirm)":!0});return r&&r.length>0&&(o.log(""),o.log(a.cyan("Selected components:")),r.forEach(s=>{o.log(` ${a.cyan("\u2022")} ${fe(s)}`)})),o.log(""),r||[]}catch{return At(25),console.log(Ce.operationCancelled),[]}}async function Ko(e){try{let t=e.map(r=>{let s=r.plans&&r.plans.length?r.plans.includes("light")?"Open source (MIT)":"Start plan \u2022 Trial":"Free",i=fe(r.name),c=r.description?` - ${r.description}`:"";return{name:`${`${i}${c}`.padEnd(50)} ${a.dim(s)}`,value:r.name}});o.log("");let n=await Pe({message:"Choose an editor template to install:",pageSize:20,choices:t,theme:Ct});return n&&(o.log(""),o.log(a.cyan("Selected template:")),o.log(` ${a.cyan("\u2022")} ${fe(n)}`)),o.log(""),n?[n]:[]}catch{return At(25),console.log(Ce.operationCancelled),[]}}async function Et(e,t=!0){if(e.components?.length)return e.components;let n;try{n=await Z()}catch(c){if(c instanceof Error&&c.message.includes("You are not authorized")){if(!await ye([{name:"unknown",plans:["start"]}],e.cwd))return o.error("Authentication failed. Cannot proceed with component selection."),[];try{n=await Z()}catch{return o.break(),_(new Error("[prompts] - Failed to fetch registry index after authentication.")),[]}}else return o.break(),_(c),[]}if(!n)return o.break(),_(new Error("[prompts] - Failed to fetch registry index.")),[];let r=Mo(n),s=await Bo(r,t);if(!s)return[];let i=n.filter(c=>!(c.hide??!1)).map(c=>c.name);switch(s){case"components":return await zo(r,i)||[];case"templates":{let c=Lo(r.templates,i);return await Ko(c)||[]}default:return[]}}var An=new _o().name("add").description("add Tiptap UI components or templates as source code to your project").argument("[components...]","the components to add").option("-o, --overwrite","overwrite existing files.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-p, --path <path>","the path to add the component to.").option("-s, --silent","mute output.",!1).action(async(e,t)=>{try{Ge();let n=Je("Tiptap UI Components","Install UI components or templates as editable source code in your project");G(n);let r=Ye("What are Tiptap UI Components?",["React UI components that help you develop an editor","They install as source code (not npm packages) in your src/components/","UI components are a foundation for customization rather than a fixed library"]);G(r),await Oo({message:a.reset(`Press ${a.cyan("Enter")} to add components or templates...`),theme:{prefix:{done:"",idle:""}}}),o.log(""),o.log(""),o.log("");let s=Do.parse({components:e,cwd:jo.resolve(t.cwd),...t});if(s.components?.length||(s.components=await Et(s)),!s.components?.length)return;let i=await Z();if(!i)throw new Error("Failed to fetch registry index.");let c=s.components.map(u=>{let k=i.find(P=>P.name===u);return{name:u,plans:k?.plans||[]}});await ye(c,s.cwd)||(o.error("Authentication failed. Cannot proceed with paid component download."),o.log("You can try again with only free components, or authenticate first."),process.exit(1));let{errors:l,config:w}=await zt(s);if(l["1"]&&(o.warn(`
|
|
34
|
+
${Ce.missingDirectory}`),process.exit(0)),!w)throw new Error(`Failed to read config at ${a.cyan(s.cwd)}.`);let d=await Le(s.components,w,s);if(!d)throw new Error("Component addition failed.");let h=(d.filesCreated?.length||0)+(d.filesUpdated?.length||0)+(d.filesSkipped?.length||0);if(d&&h>0){let u=[...d.filesCreated||[],...d.filesUpdated||[],...d.filesSkipped||[]],k=u.some(x=>x.includes("notion")),P=u.some(x=>x.includes("simple")&&x.includes("editor"));if(k){o.log(""),d.filesCreated.length>0?o.log(`${a.green("\u2714")} Notion template installed - ${d.filesCreated.length} files added to ${a.cyan("src/components/")}`):o.log(`${a.green("\u2714")} Notion template already installed - ${d.filesSkipped.length} files skipped`),o.log("");let x=await U(s.cwd);if(x){let I=await Q(d,w,x.framework);ee(I),I.success?He(x.framework):Xe(x.framework,w)}}else if(P){o.log(""),d.filesCreated.length>0?o.log(`${a.green("\u2714")} Simple editor template installed - ${d.filesCreated.length} files added to ${a.cyan("src/components/")}`):o.log(`${a.green("\u2714")} Simple editor template already installed - ${d.filesSkipped.length} files skipped`),o.log("");let x=await U(s.cwd);if(x){let I=await Q(d,w,x.framework);ee(I),I.success||we(x.framework,w)}}else{o.log(""),d.filesCreated.length>0?o.log(`${a.green("\u2714")} Components installed - ${d.filesCreated.length} files added to ${a.cyan("src/components/")}`):d.filesSkipped.length>0&&o.log(`${a.green("\u2714")} Components already installed - ${d.filesSkipped.length} files skipped`),o.log("");let x=await U(s.cwd);if(x){let b=await Q(d,w,x.framework);ee(b),b.success||we(x.framework,w)}s.components.includes("table-node")&&Ze()}}}catch(n){o.break(),_(n)}});import{Command as Vo}from"commander";var En=new Vo().name("info").description("get information about your project").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{o.info("> project info"),console.log(await U(e.cwd)),o.break();try{let t=await Y(e.cwd);o.info("> config"),console.log(t)}catch{o.info("")}});import On from"path";import{Command as ds}from"commander";import{confirm as fs,input as us}from"@inquirer/prompts";import{z as H}from"zod";import qo from"path";import Rn from"fs-extra";async function Nn(e){let t={};if(!Rn.existsSync(e.cwd)||!Rn.existsSync(qo.resolve(e.cwd,"package.json")))return t["1"]=!0,{errors:t,projectInfo:null};let n=C("Verifying framework.",{silent:e.silent}).start(),r=await U(e.cwd);(!r||r?.framework.name==="manual")&&(t["7"]=!0,n?.fail(),o.break(),r?.framework.links.installation&&o.error(`We could not detect a supported framework at ${a.cyan(e.cwd)}.
|
|
35
35
|
Visit ${a.cyan(r?.framework.links.installation)} to manually configure your project.
|
|
36
|
-
Once configured, you can use the cli to add components.`),o.break(),process.exit(0)),n?.stopAndPersist({symbol:a.cyan("\u2714"),text:`Verifying framework. Found ${a.cyan(r.framework.label)}.`});let s=
|
|
36
|
+
Once configured, you can use the cli to add components.`),o.break(),process.exit(0)),n?.stopAndPersist({symbol:a.cyan("\u2714"),text:`Verifying framework. Found ${a.cyan(r.framework.label)}.`});let s=C("Validating import alias.",{silent:e.silent}).start();return r?.aliasPrefix?s?.stopAndPersist({symbol:a.cyan("\u2714")}):(t["6"]=!0,s?.fail()),Object.keys(t).length>0&&(t["6"]&&(o.break(),o.error("No import alias found in your tsconfig.json file."),r?.framework.links.installation&&o.error(`Visit ${a.cyan(r?.framework.links.installation)} to learn how to set an import alias.`)),o.break(),process.exit(0)),{errors:t,projectInfo:r}}import Yo from"os";import te from"path";import K from"fs-extra";import{execa as q}from"execa";import{parse as Go}from"jsonc-parser";import{input as Ho}from"@inquirer/prompts";var Xo="https://codeload.github.com/shadcn-ui/ui/tar.gz/main",ke={next:"next",vite:"vite","next-monorepo":"next-monorepo"},Zo=(e,t="")=>Ho({message:a.reset(e),default:t,required:!0,validate:n=>n.length>128?"Name should be less than 128 characters.":!0,theme:{prefix:{done:a.cyan("\u2714"),idle:"?"}}}),Qo=async(e,t)=>{let n=`
|
|
37
37
|
${a.gray(" Use arrow-keys \u25B2\u25BC / [Return] to submit")}
|
|
38
|
-
`;return Pe({message:a.reset(e),instructions:n,theme:{icon:{cursor:a.cyan("\u276F")},prefix:{done:a.cyan("\u2714"),idle:"?"}},choices:t})};async function jn(e){let t={srcDir:!1,reactCompiler:!1,...e},n=t.framework&&ke[t.framework]?t.framework:"next",r="my-app",s="latest";if(!t.framework){let
|
|
38
|
+
`;return Pe({message:a.reset(e),instructions:n,theme:{icon:{cursor:a.cyan("\u276F")},prefix:{done:a.cyan("\u2714"),idle:"?"}},choices:t})};async function jn(e){let t={srcDir:!1,reactCompiler:!1,...e},n=t.framework&&ke[t.framework]?t.framework:"next",r="my-app",s="latest";if(!t.framework){let p=`The path ${a.cyan(t.cwd)} does not contain a package.json file. Would you like to start a new project?`;n=await Qo(p,[{name:"Next.js",value:"next"},{name:"Vite + React + TypeScript",value:"vite"}]),o.log("")}r=await Zo("What is your project named?",r);let i=await z(t.cwd,{withFallback:!0}),c=te.join(t.cwd,r);return await es(t.cwd,r),n===ke.next?await ts(c,{version:s,cwd:t.cwd,packageManager:i,srcDir:!!t.srcDir,reactCompiler:!!t.reactCompiler}):n===ke.vite?await ns(c,{cwd:t.cwd,packageManager:i,projectName:r}):n===ke["next-monorepo"]&&await as(c,{packageManager:i}),{projectPath:c,projectName:r,framework:n}}async function es(e,t){try{await K.access(e,K.constants.W_OK)}catch{o.break(),o.error(`The path ${a.cyan(e)} is not writable.`),o.error(`It is likely you do not have write permissions for this folder or the path ${a.cyan(e)} does not exist.`),o.break(),process.exit(0)}K.existsSync(te.resolve(e,t,"package.json"))&&(o.break(),o.error(`A project with the name ${a.cyan(t)} already exists.`),o.error("Please choose a different name and try again."),o.break(),process.exit(0))}async function ts(e,t){let n=C("Creating a new Next.js project. This may take a few minutes.").start(),r=["--tailwind","--eslint","--typescript","--app",t.srcDir?"--src-dir":"--no-src-dir","--no-import-alias",t.reactCompiler?"--react-compiler":"--no-react-compiler",`--use-${t.packageManager}`];(t.version.startsWith("15")||t.version.startsWith("latest")||t.version.startsWith("canary"))&&r.push("--turbopack");try{await q("npx",[`create-next-app@${t.version}`,e,"--silent",...r],{cwd:t.cwd}),await _n(e),n.stopAndPersist({symbol:a.cyan("\u2714")})}catch{n?.fail("Something went wrong creating a new Next.js project."),o.break(),o.error("Something went wrong creating a new Next.js project. Please try again."),process.exit(0)}}async function ns(e,t){let n=C("Creating a new Vite + React + TypeScript project. This may take a few minutes.").start();try{await q("npm",["create","vite@latest",t.projectName,"--","--template","react-ts"],{cwd:t.cwd}),await q(t.packageManager,["install"],{cwd:e}),await rs(e,t.packageManager),await _n(e),n.stopAndPersist({symbol:a.cyan("\u2714")})}catch(r){n?.fail("Something went wrong creating a new Vite project."),_(r)}}async function rs(e,t){try{await ss(e),await is(e),await os(e,t)}catch{o.warn("Failed to set up TypeScript path aliases, but project creation succeeded")}}async function os(e,t){try{await q(t,[t==="npm"?"install":"add",t==="npm"?"--save-dev":"-D","@types/node"],{cwd:e})}catch{o.warn("Failed to install @types/node, but project creation succeeded")}}async function ss(e){let t=async n=>{let r=te.join(e,n);if(!await K.pathExists(r))return;let s=await K.readFile(r,"utf-8"),i=Go(s);i.compilerOptions={...i.compilerOptions,baseUrl:".",paths:{...i.compilerOptions?.paths||{},"@/*":["./src/*"]}};let c=JSON.stringify(i,null,2);await K.writeFile(r,c)};await t("tsconfig.json"),await t("tsconfig.app.json")}async function is(e){let t=te.join(e,"vite.config.ts"),r=(await K.readFile(t,"utf-8")).replace("import { defineConfig } from 'vite'",`import { defineConfig } from 'vite'
|
|
39
39
|
import path from 'path'`).replace("plugins: [react()]",`plugins: [react()],
|
|
40
40
|
resolve: {
|
|
41
41
|
alias: {
|
|
42
42
|
'@': path.resolve(__dirname, './src')
|
|
43
43
|
}
|
|
44
|
-
}`);await K.writeFile(t,r)}async function as(e,t){let n=
|
|
44
|
+
}`);await K.writeFile(t,r)}async function as(e,t){let n=C("Creating a new Next.js monorepo. This may take a few minutes.").start();try{await cs(e),await q(t.packageManager,["install"],{cwd:e}),await ls(e),n?.stopAndPersist({symbol:a.cyan("\u2714"),text:`Created a new Next.js monorepo at ${a.cyan(e)}`})}catch(r){n?.fail("Something went wrong creating a new Next.js monorepo."),_(r)}}async function cs(e){let t=te.join(Yo.tmpdir(),`tiptap-framework-${Date.now()}`);await K.ensureDir(t);let n=await fetch(Xo);if(!n.ok)throw new Error(`Failed to download framework: ${n.statusText}`);let r=te.resolve(t,"framework.tar.gz");await K.writeFile(r,Buffer.from(await n.arrayBuffer())),await q("tar",["-xzf",r,"-C",t,"--strip-components=2","ui-main/templates/monorepo-next"]);let s=te.resolve(t,"monorepo-next");await K.move(s,e),await K.remove(t)}async function ls(e){let t=process.cwd();try{await q("git",["--version"],{cwd:e}),await q("git",["init"],{cwd:e}),await q("git",["add","-A"],{cwd:e}),await q("git",["commit","-m","Initial commit"],{cwd:e}),await q("cd",[t])}catch{o.warn("Failed to initialize git repository, but project creation succeeded")}}var ps=`# Simple template
|
|
45
45
|
|
|
46
46
|
Integrate the Tiptap open source editor with UI components and open source extensions.
|
|
47
47
|
|
|
@@ -345,5 +345,5 @@ The built-in AI tools let you:
|
|
|
345
345
|
|
|
346
346
|
## Extendability
|
|
347
347
|
|
|
348
|
-
This template is designed to grow with your needs. New Tiptap Cloud features will be seamlessly compatible with the same UI system\u2014no rewrites required.`;async function _n(e,t){let n=te.join(e,"README.md"),r={"simple-editor":ps,"notion-like-editor":ms},s=t&&t in r?r[t]:"";try{s.trim()&&await K.writeFile(n,s,"utf-8")}catch{}}var gs=H.object({cwd:H.string(),components:H.array(H.string()).optional(),silent:H.boolean(),isNewProject:H.boolean(),srcDir:H.boolean().optional(),reactCompiler:H.boolean().optional(),framework:H.string().optional().refine(e=>!e||ke[e],{message:"Invalid framework. Please use 'next' or 'vite'."})}),$t=(e,t=!0)=>fs({message:a.reset(e),default:t,theme:{prefix:{done:a.cyan("\u2714"),idle:"?"}}}),Fn=new ds().name("init").description("initialize your project and install Tiptap UI components as source code").argument("[components...]","the components to add").option("-f, --framework <framework>","the framework to use. (next, vite)").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-s, --silent","mute output.",!1).option("--src-dir","use the src directory when creating a new project (specific to next).",!1).option("--react-compiler","enable React Compiler when creating a new project (specific to next).",!1).action(async(e,t)=>{try{Ge();let n=Je("Tiptap UI Components","Install UI components or templates as editable source code in your project");G(n);let r=Ye("What are Tiptap UI Components?",["React UI components that help you develop an editor","They install as source code (not npm packages) in your src/components/","UI components are a foundation for customization rather than a fixed library"]);G(r),await us({message:a.reset(`Press ${a.cyan("Enter")} to initialize a project...`),theme:{prefix:{done:"",idle:""}}}),o.log("");let s=gs.parse({cwd:On.resolve(t.cwd),isNewProject:!1,components:e,...t}),i=await hs(s),c=(i?.filesCreated?.length||0)+(i?.filesUpdated?.length||0)+(i?.filesSkipped?.length||0);if(i&&c>0){let
|
|
348
|
+
This template is designed to grow with your needs. New Tiptap Cloud features will be seamlessly compatible with the same UI system\u2014no rewrites required.`;async function _n(e,t){let n=te.join(e,"README.md"),r={"simple-editor":ps,"notion-like-editor":ms},s=t&&t in r?r[t]:"";try{s.trim()&&await K.writeFile(n,s,"utf-8")}catch{}}var gs=H.object({cwd:H.string(),components:H.array(H.string()).optional(),silent:H.boolean(),isNewProject:H.boolean(),srcDir:H.boolean().optional(),reactCompiler:H.boolean().optional(),framework:H.string().optional().refine(e=>!e||ke[e],{message:"Invalid framework. Please use 'next' or 'vite'."})}),$t=(e,t=!0)=>fs({message:a.reset(e),default:t,theme:{prefix:{done:a.cyan("\u2714"),idle:"?"}}}),Fn=new ds().name("init").description("initialize your project and install Tiptap UI components as source code").argument("[components...]","the components to add").option("-f, --framework <framework>","the framework to use. (next, vite)").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-s, --silent","mute output.",!1).option("--src-dir","use the src directory when creating a new project (specific to next).",!1).option("--react-compiler","enable React Compiler when creating a new project (specific to next).",!1).action(async(e,t)=>{try{Ge();let n=Je("Tiptap UI Components","Install UI components or templates as editable source code in your project");G(n);let r=Ye("What are Tiptap UI Components?",["React UI components that help you develop an editor","They install as source code (not npm packages) in your src/components/","UI components are a foundation for customization rather than a fixed library"]);G(r),await us({message:a.reset(`Press ${a.cyan("Enter")} to initialize a project...`),theme:{prefix:{done:"",idle:""}}}),o.log("");let s=gs.parse({cwd:On.resolve(t.cwd),isNewProject:!1,components:e,...t}),i=await hs(s),c=(i?.filesCreated?.length||0)+(i?.filesUpdated?.length||0)+(i?.filesSkipped?.length||0);if(i&&c>0){let p=[...i.filesCreated||[],...i.filesUpdated||[],...i.filesSkipped||[]],l=p.some(d=>d.includes("notion")),w=p.some(d=>d.includes("simple")&&d.includes("editor"));if(l){o.log(""),i.filesCreated.length>0?o.log(`${a.green("\u2714")} Notion template installed - ${i.filesCreated.length} files added to ${a.cyan("src/components/")}`):o.log(`${a.green("\u2714")} Notion template already installed - ${i.filesSkipped.length} files skipped`),o.log("");let d=i.framework||i.projectInfo?.framework;if(d){let h=await Q({filesCreated:i.filesCreated,filesUpdated:i.filesUpdated,filesSkipped:i.filesSkipped},i.config,d);ee(h),h.success?He(d):Xe(d,i.config)}}else if(w){o.log(""),i.filesCreated.length>0?o.log(`${a.green("\u2714")} Simple editor template installed - ${i.filesCreated.length} files added to ${a.cyan("src/components/")}`):o.log(`${a.green("\u2714")} Simple editor template already installed - ${i.filesSkipped.length} files skipped`),o.log("");let d=i.framework||i.projectInfo?.framework;if(d){let h=await Q({filesCreated:i.filesCreated,filesUpdated:i.filesUpdated,filesSkipped:i.filesSkipped},i.config,d);ee(h),h.success||we(d,i.config)}}else{if(o.log(""),i.filesCreated.length>0?o.log(`${a.green("\u2714")} Components installed - ${i.filesCreated.length} files added to ${a.cyan("src/components/")}`):i.filesSkipped.length>0&&o.log(`${a.green("\u2714")} Components already installed - ${i.filesSkipped.length} files skipped`),o.log(""),i?.projectInfo?.framework){let h=await Q({filesCreated:i.filesCreated,filesUpdated:i.filesUpdated,filesSkipped:i.filesSkipped},i.config,i.projectInfo.framework);ee(h),h.success||we(i?.projectInfo?.framework,i.config)}i.selectedComponents?.includes("table-node")&&Ze()}}o.break()}catch(n){o.break(),_(n)}});async function hs(e){let{cwd:t,skipPreflight:n,components:r,silent:s}=e,i={...e},c,p=(b,A,F=[],D)=>({config:b,projectInfo:A,framework:c,selectedComponents:F,filesCreated:D?.filesCreated||[],filesUpdated:D?.filesUpdated||[],filesSkipped:D?.filesSkipped||[],errors:[]}),l;if(n)l=await U(t);else{let b=await Nn(e);if(b.errors["1"]){let{projectPath:F,framework:D}=await jn(e);F||process.exit(0),i={...i,cwd:F,isNewProject:!0},c=D,o.log("")}l=b.projectInfo}if(c==="next-monorepo"){let b=On.resolve(i.cwd,"apps/web"),A=await Y(b);return p(A,l)}let w=await Lt(i.cwd,l),d=w?await ws(w):await ys(await Y(i.cwd));o.log("");let h=r||[];if(!h.length){if(!await $t("Would you like to add a template or UI components to your project?")){let A=await re(i.cwd,d);return p(A,l)}if(h=await Et({...i,overwrite:!1},!0),!h.length){let A=await re(i.cwd,d);return p(A,l)}}let u;try{if(u=await Z(),!u)throw new Error("Failed to fetch registry index.")}catch(b){if(b instanceof Error&&b.message.includes("You are not authorized")){let A=h.map(D=>({name:D,plans:["start"]}));if(await ye(A,i.cwd)||(o.error("Authentication failed. Cannot proceed with paid component download."),o.log("You can try again with only free components, or authenticate first."),process.exit(1)),u=await Z(),!u)throw new Error("Failed to fetch registry index after authentication.")}else throw b}let k=h.map(b=>{let A=u.find(F=>F.name===b);return{name:b,plans:A?.plans||[]}});await ye(k,i.cwd)||(o.error("Authentication failed. Cannot proceed with paid component download."),o.log("You can try again with only free components, or authenticate first."),process.exit(1));let x=await re(i.cwd,d),I=await Le(h,x,{overwrite:!1,silent:s,isNewProject:i.isNewProject||l?.framework.name==="next-app"});return p(x,l,h,I||{filesCreated:[],filesUpdated:[],filesSkipped:[]})}async function ys(e=null){o.log(""),o.log(a.cyan("Project Configuration")),o.log("");let t=await $t(`Would you like to use ${a.cyan("TypeScript")} (recommended)?`,e?.tsx??!0),n=await $t(`Are you using ${a.cyan("React Server Components")}?`,e?.rsc??!0);return oe.parse({rsc:n,tsx:t,aliases:{components:ot,contexts:st,hooks:it,tiptapIcons:at,lib:$e,tiptapExtensions:ct,tiptapNodes:lt,tiptapUi:pt,tiptapUiPrimitives:mt,tiptapUiUtils:dt,styles:ft}})}async function ws(e){return oe.parse({rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases})}import{Command as ks}from"commander";var Dn={name:"@tiptap/cli",version:"3.11.0",description:"Tiptap CLI",publishConfig:{access:"public"},author:{name:"tiptap",url:"https://github.com/ueberdosis/tiptap"},files:["dist"],keywords:["cli","components","nextjs","react","templates","tiptap","@tiptap/cli","ui"],license:"SEE LICENSE IN LICENSE.md",type:"module",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"}},bin:"./dist/index.js",scripts:{dev:"tsup --watch",build:"tsup",typecheck:"tsc --noEmit",clean:"rm -rf dist","start:dev":"cross-env REGISTRY_URL=http://localhost:3000 node dist/index.js","start:prod":"cross-env REGISTRY_URL=https://template.tiptap.dev node dist/index.js",start:"node dist/index.js","pub:beta":"pnpm build && pnpm publish --no-git-checks --access public --tag beta","pub:release":"pnpm build && pnpm publish --access public"},dependencies:{"@antfu/ni":"^23.3.1","@babel/core":"^7.28.5","@babel/parser":"^7.28.5","@babel/plugin-transform-typescript":"^7.28.5","@inquirer/core":"^10.3.2","@inquirer/figures":"^1.0.15","@inquirer/prompts":"^7.10.1","@inquirer/type":"^3.0.10","ansi-escapes":"^7.2.0",chalk:"^5.6.2",commander:"^13.1.0",conf:"^14.0.0",cosmiconfig:"^9.0.0",deepmerge:"^4.3.1",execa:"^9.6.0","fast-glob":"^3.3.3","fs-extra":"^11.3.2","https-proxy-agent":"^7.0.6","jsonc-parser":"^3.3.1","node-fetch":"^3.3.2",ora:"^8.2.0",recast:"^0.23.11",sass:"^1.94.2","ts-morph":"^25.0.1","tsconfig-paths":"^4.2.0",yaml:"^2.8.1","yoctocolors-cjs":"^2.1.3",zod:"^3.25.76"},devDependencies:{"@babel/plugin-transform-typescript":"^7.26.5","@types/babel__core":"^7.20.5","@types/conf":"^3.0.3","@types/fs-extra":"^11.0.4","@types/prompts":"^2.4.9","cross-env":"^7.0.3",tsup:"^8.5.1","type-fest":"^4.41.0"}};process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function Ps(){let e=new ks().name("tiptap").description("add components and dependencies to your project").version(Dn.version||"1.0.0","-v, --version","display the CLI version number");e.addCommand(Fn).addCommand(An).addCommand(En).addCommand(hn).addCommand(wn).addCommand(yn).addCommand(xn),e.parse()}Ps();
|
|
349
349
|
//# sourceMappingURL=index.js.map
|