@dittowords/cli 5.0.0 → 5.2.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.
Files changed (3) hide show
  1. package/README.md +6 -6
  2. package/bin/ditto.js +63 -63
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -40,14 +40,14 @@ The first time you run the CLI, a `ditto/` folder will be created if it doesn't
40
40
  The default file looks like this:
41
41
 
42
42
  ```yml
43
- projects: [],
44
- components: {
43
+ projects: []
44
+ variants: []
45
+ statuses: []
46
+ components:
45
47
  folders: []
46
- },
47
- variants: [],
48
48
  outputs:
49
- - format: json,
50
- framework: i18next
49
+ - format: json
50
+ framework: i18next
51
51
  ```
52
52
 
53
53
  For more information on configuring the CLI, see [this documentation section](https://developer.dittowords.com/cli-reference/configuration).
package/bin/ditto.js CHANGED
@@ -1,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f865a369-e1da-5321-ba25-1c81e1859ad2")}catch(e){}}();
4
- var Jr=Object.create;var se=Object.defineProperty;var Vr=Object.getOwnPropertyDescriptor;var Yr=Object.getOwnPropertyNames;var Br=Object.getPrototypeOf,qr=Object.prototype.hasOwnProperty;var Ze=t=>{throw TypeError(t)};var r=(t,e)=>se(t,"name",{value:e,configurable:!0});var Gr=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Yr(e))!qr.call(t,s)&&s!==o&&se(t,s,{get:()=>e[s],enumerable:!(n=Vr(e,s))||n.enumerable});return t};var l=(t,e,o)=>(o=t!=null?Jr(Br(t)):{},Gr(e||!t||!t.__esModule?se(o,"default",{value:t,enumerable:!0}):o,t));var He=(t,e,o)=>e.has(t)||Ze("Cannot "+o);var D=(t,e,o)=>(He(t,e,"read from private field"),o?o.call(t):e.get(t)),V=(t,e,o)=>e.has(t)?Ze("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,o),R=(t,e,o,n)=>(He(t,e,"write to private field"),n?n.call(t,o):e.set(t,o),o);var Or=l(require("@sentry/node"));var it="5.0.0";var U=require("commander");var ho=l(require("boxen")),Ut=l(require("chalk"));var fo=l(require("ora"));var so=l(require("axios"));var Y=l(require("fs")),to=l(require("path")),eo=l(require("url")),ct=l(require("js-yaml")),oo=l(require("@sentry/node"));var Xe=require("os"),at=l(require("path")),u=new class{get API_HOST(){return process.env.DITTO_API_HOST||"https://api.dittowords.com"}get CONFIG_FILE(){return process.env.DITTO_CONFIG_FILE||at.default.join((0,Xe.homedir)(),".config","ditto")}get PROJECT_CONFIG_FILE(){return at.default.normalize(at.default.join("ditto","config.yml"))}get TEXT_DIR(){return process.env.DITTO_TEXT_DIR||"ditto"}get TEXT_FILE(){return at.default.normalize(at.default.join(this.TEXT_DIR,"text.json"))}};function Qe(t){if(typeof t!="object")return{};let e={};for(let o in t){let n=o,s=t[n];e[n]=typeof s=="object"||Array.isArray(s)?JSON.stringify(s):s}return e}r(Qe,"createSentryContext");var zr={sources:{components:!0},variants:!0,format:"flat"},ro=ct.default.dump(zr);function vt(t,e){let o=to.default.dirname(t);Y.default.existsSync(o)||Y.default.mkdirSync(o),Y.default.existsSync(t)||Y.default.writeFileSync(t,e||"","utf-8")}r(vt,"createFileIfMissing");function Wr(t){return typeof t=="object"}r(Wr,"jsonIsConfigYAML");function Zr(t){return!!t&&typeof t=="object"&&Object.values(t).every(e=>e.every&&e.every(o=>typeof o=="object"&&Object.keys(o).includes("token")))}r(Zr,"jsonIsGlobalYAML");function ie(t=u.PROJECT_CONFIG_FILE,e={}){vt(t,ro);let o=Y.default.readFileSync(t,"utf8"),n=ct.default.load(o);return Wr(n)?n:e}r(ie,"readProjectConfigData");function jt(t=u.CONFIG_FILE,e={}){vt(t);let o=Y.default.readFileSync(t,"utf8"),n=ct.default.load(o);return Zr(n)?n:e}r(jt,"readGlobalConfigData");function Hr(t,e){vt(t,ro);let o=ie(t),n={...o,...e,sources:{...o.sources,...e.sources}},s=ct.default.dump(n);Y.default.writeFileSync(t,s,"utf8")}r(Hr,"writeProjectConfigData");function ae(t,e){vt(t);let o=jt(t),n=ct.default.dump({...o,...e});Y.default.writeFileSync(t,n,"utf8")}r(ae,"writeGlobalConfigData");function Bt(t){return t.includes("://")?eo.default.parse(t).hostname||"":t}r(Bt,"justTheHost");function Xr(t,e){let o=jt(t),n=Bt(e);o[n]=[],o[n][0]={token:""},ae(t,o)}r(Xr,"deleteToken");function Qr(t,e,o){let n=jt(t),s=Bt(e);n[s]=[],n[s][0]={token:o},ae(t,n)}r(Qr,"saveToken");function no(){return process.env.DITTO_API_KEY}r(no,"getTokenFromEnv");function Kr(t,e){let o=no();if(o)return o;let s=jt(t)[Bt(e)];if(!s)return;let{length:i}=s;return s[i-1].token}r(Kr,"getToken");var Ke=/-(\d+$)/;function tn(t,e){let o=e;if(t.has(o))for(;t.has(o);){let[n,s]=o.match(Ke)||[];s&&!isNaN(parseInt(s))?o=`${o.replace(Ke,"")}-${parseInt(s)+1}`:o=`${o}-1`}return o}r(tn,"dedupeProjectName");function en(t){let{sources:e,variants:o,format:n,status:s,richText:i,iosLocales:a,projects:c,components:m,disableJsDriver:g}=ie(t),f=e?.projects||[],d=new Set,S=[],x=!1;(f||[]).forEach(k=>{if(k.id&&k.name){if(k.id==="ditto_component_library"){x=!0;return}k.fileName=tn(d,k.name),d.add(k.fileName),S.push(k)}});let w=!!e?.components,_=typeof e?.components=="object"?e.components.root:void 0,P=typeof e?.components=="object"?e.components.folders:void 0,I={hasSourceData:!!S.length||w,validProjects:S,shouldFetchComponentLibrary:w,variants:o||!1,format:n,status:s,richText:i,hasTopLevelProjectsField:!!c,hasTopLevelComponentsField:!!m,hasComponentLibraryInProjects:x,componentRoot:_,componentFolders:P,localeByVariantApiId:a?a.reduce((k,nt)=>({...k,...nt}),{}):void 0,disableJsDriver:g};return oo.setContext("config",Qe(I)),I}r(en,"parseSourceInformation");var C={createFileIfMissing:vt,readProjectConfigData:ie,readGlobalConfigData:jt,writeGlobalConfigData:ae,writeProjectConfigData:Hr,justTheHost:Bt,saveToken:Qr,deleteToken:Xr,getToken:Kr,getTokenFromEnv:no,parseSourceInformation:en};function j(t){return so.default.create({baseURL:u.API_HOST,headers:{Authorization:`token ${t||C.getToken(u.CONFIG_FILE,u.API_HOST)}`,"x-ditto-cli":!0}})}r(j,"createApiClient");var q=l(require("chalk"));var on=r(t=>q.default.magenta(t),"errorText"),rn=r(t=>q.default.yellow(t),"warnText"),nn=r(t=>q.default.blueBright(t),"info"),sn=r(t=>q.default.green(t),"success"),an=r(t=>q.default.blueBright.underline(t),"url"),cn=r(t=>q.default.grey(t),"subtle"),pn=r(t=>q.default.white(t),"write"),ln=r(()=>console.log(`
5
- `),"nl"),p={errorText:on,warnText:rn,info:nn,success:sn,url:an,subtle:cn,write:pn,nl:ln};var ao=l(require("fs")),co=l(require("@sentry/node")),po=l(require("chalk")),lo=require("enquirer");var io=l(require("@sentry/node"));async function b(t,e=2){t&&console.log(`
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="aaa46c99-e8bb-5cdb-acf3-0f9f89d2c84a")}catch(e){}}();
4
+ var Jr=Object.create;var ne=Object.defineProperty;var Vr=Object.getOwnPropertyDescriptor;var Yr=Object.getOwnPropertyNames;var Br=Object.getPrototypeOf,qr=Object.prototype.hasOwnProperty;var ze=t=>{throw TypeError(t)};var n=(t,e)=>ne(t,"name",{value:e,configurable:!0});var Gr=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Yr(e))!qr.call(t,s)&&s!==o&&ne(t,s,{get:()=>e[s],enumerable:!(r=Vr(e,s))||r.enumerable});return t};var m=(t,e,o)=>(o=t!=null?Jr(Br(t)):{},Gr(e||!t||!t.__esModule?ne(o,"default",{value:t,enumerable:!0}):o,t));var Ze=(t,e,o)=>e.has(t)||ze("Cannot "+o);var D=(t,e,o)=>(Ze(t,e,"read from private field"),o?o.call(t):e.get(t)),V=(t,e,o)=>e.has(t)?ze("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,o),A=(t,e,o,r)=>(Ze(t,e,"write to private field"),r?r.call(t,o):e.set(t,o),o);var Or=m(require("@sentry/node"));var ct="5.2.0";var U=require("commander");var fo=m(require("boxen")),Ut=m(require("chalk"));var lo=m(require("ora"));var ro=m(require("axios"));var Y=m(require("fs")),Qe=m(require("path")),Ke=m(require("url")),mt=m(require("js-yaml")),to=m(require("@sentry/node"));var We=require("os"),pt=m(require("path")),u=new class{get API_HOST(){return process.env.DITTO_API_HOST||"https://api.dittowords.com"}get CONFIG_FILE(){return process.env.DITTO_CONFIG_FILE||pt.default.join((0,We.homedir)(),".config","ditto")}get PROJECT_CONFIG_FILE(){return pt.default.normalize(pt.default.join("ditto","config.yml"))}get TEXT_DIR(){return process.env.DITTO_TEXT_DIR||"ditto"}get TEXT_FILE(){return pt.default.normalize(pt.default.join(this.TEXT_DIR,"text.json"))}};function He(t){if(typeof t!="object")return{};let e={};for(let o in t){let r=o,s=t[r];e[r]=typeof s=="object"||Array.isArray(s)?JSON.stringify(s):s}return e}n(He,"createSentryContext");var zr={sources:{components:!0},variants:!0,format:"flat"},eo=mt.default.dump(zr);function jt(t,e){let o=Qe.default.dirname(t);Y.default.existsSync(o)||Y.default.mkdirSync(o),Y.default.existsSync(t)||Y.default.writeFileSync(t,e||"","utf-8")}n(jt,"createFileIfMissing");function Zr(t){return typeof t=="object"}n(Zr,"jsonIsConfigYAML");function Wr(t){return!!t&&typeof t=="object"&&Object.values(t).every(e=>e.every&&e.every(o=>typeof o=="object"&&Object.keys(o).includes("token")))}n(Wr,"jsonIsGlobalYAML");function se(t=u.PROJECT_CONFIG_FILE,e={}){jt(t,eo);let o=Y.default.readFileSync(t,"utf8"),r=mt.default.load(o);return Zr(r)?r:e}n(se,"readProjectConfigData");function Ft(t=u.CONFIG_FILE,e={}){jt(t);let o=Y.default.readFileSync(t,"utf8"),r=mt.default.load(o);return Wr(r)?r:e}n(Ft,"readGlobalConfigData");function Hr(t,e){jt(t,eo);let o=se(t),r={...o,...e,sources:{...o.sources,...e.sources}},s=mt.default.dump(r);Y.default.writeFileSync(t,s,"utf8")}n(Hr,"writeProjectConfigData");function ie(t,e){jt(t);let o=Ft(t),r=mt.default.dump({...o,...e});Y.default.writeFileSync(t,r,"utf8")}n(ie,"writeGlobalConfigData");function Bt(t){return t.includes("://")?Ke.default.parse(t).hostname||"":t}n(Bt,"justTheHost");function Xr(t,e){let o=Ft(t),r=Bt(e);o[r]=[],o[r][0]={token:""},ie(t,o)}n(Xr,"deleteToken");function Qr(t,e,o){let r=Ft(t),s=Bt(e);r[s]=[],r[s][0]={token:o},ie(t,r)}n(Qr,"saveToken");function oo(){return process.env.DITTO_API_KEY}n(oo,"getTokenFromEnv");function Kr(t,e){let o=oo();if(o)return o;let s=Ft(t)[Bt(e)];if(!s)return;let{length:i}=s;return s[i-1].token}n(Kr,"getToken");var Xe=/-(\d+$)/;function tn(t,e){let o=e;if(t.has(o))for(;t.has(o);){let[r,s]=o.match(Xe)||[];s&&!isNaN(parseInt(s))?o=`${o.replace(Xe,"")}-${parseInt(s)+1}`:o=`${o}-1`}return o}n(tn,"dedupeProjectName");function en(t){let{sources:e,variants:o,format:r,status:s,richText:i,iosLocales:a,projects:c,components:l,disableJsDriver:g}=se(t),f=e?.projects||[],d=new Set,C=[],x=!1;(f||[]).forEach(k=>{if(k.id&&k.name){if(k.id==="ditto_component_library"){x=!0;return}k.fileName=tn(d,k.name),d.add(k.fileName),C.push(k)}});let v=!!e?.components,R=typeof e?.components=="object"?e.components.root:void 0,P=typeof e?.components=="object"?e.components.folders:void 0,I={hasSourceData:!!C.length||v,validProjects:C,shouldFetchComponentLibrary:v,variants:o||!1,format:r,status:s,richText:i,hasTopLevelProjectsField:!!c,hasTopLevelComponentsField:!!l,hasComponentLibraryInProjects:x,componentRoot:R,componentFolders:P,localeByVariantApiId:a?a.reduce((k,it)=>({...k,...it}),{}):void 0,disableJsDriver:g};return to.setContext("config",He(I)),I}n(en,"parseSourceInformation");var S={createFileIfMissing:jt,readProjectConfigData:se,readGlobalConfigData:Ft,writeGlobalConfigData:ie,writeProjectConfigData:Hr,justTheHost:Bt,saveToken:Qr,deleteToken:Xr,getToken:Kr,getTokenFromEnv:oo,parseSourceInformation:en};function j(t){return ro.default.create({baseURL:u.API_HOST,headers:{Authorization:`token ${t||S.getToken(u.CONFIG_FILE,u.API_HOST)}`,"x-ditto-cli":!0}})}n(j,"createApiClient");var q=m(require("chalk"));var on=n(t=>q.default.magenta(t),"errorText"),rn=n(t=>q.default.yellow(t),"warnText"),nn=n(t=>q.default.blueBright(t),"info"),sn=n(t=>q.default.green(t),"success"),an=n(t=>q.default.blueBright.underline(t),"url"),cn=n(t=>q.default.grey(t),"subtle"),pn=n(t=>q.default.white(t),"write"),mn=n(()=>console.log(`
5
+ `),"nl"),p={errorText:on,warnText:rn,info:nn,success:sn,url:an,subtle:cn,write:pn,nl:mn};var so=m(require("fs")),io=m(require("@sentry/node")),ao=m(require("chalk")),co=require("enquirer");var no=m(require("@sentry/node"));async function b(t,e=2){t&&console.log(`
6
6
  ${t}
7
- `),await io.flush(),process.exit(e)}r(b,"quit");var mo=require("axios");var ce=r((t,e=u.API_HOST)=>{if(C.getTokenFromEnv())return!1;let o=t||u.CONFIG_FILE;if(!ao.default.existsSync(o))return!0;let n=C.readGlobalConfigData(o);return!n[C.justTheHost(e)]||n[C.justTheHost(e)][0].token===""},"needsToken");async function mn(t){let e=j(t),o="/token-check",n;try{n=await e.get(o)}catch(s){if(!(s instanceof mo.AxiosError))return{success:!1,output:[p.warnText("Sorry! We're having trouble reaching the Ditto API.")]};if(s.code==="ENOTFOUND")return{success:!1,output:[p.errorText(`Can't connect to API: ${p.url(u.API_HOST)}`)]};if(s.response?.status===401||s.response?.status===404)return{success:!1,output:[p.errorText("This API key isn't valid. Please try another.")]}}return typeof n=="string"?{success:!1,output:[n]}:n?.status===200?{success:!0}:{success:!1,output:[p.errorText("This API key isn't valid. Please try another.")]}}r(mn,"verifyTokenUsingTokenCheck");async function un(t){let e=await mn(t);return e.success?!0:e.output.join(`
8
- `)}r(un,"checkToken");async function fn(t){let e=p.info,o=p.url("https://app.dittowords.com/account/devtools"),n=`${po.default.bold(e("API Keys"))}`,s=t||`To get started, you'll need your Ditto API key. You can find this at: ${o} under "${n}".`;return console.log(s),(await(0,lo.prompt)({type:"input",name:"token",message:"What is your API key?",validate:r(a=>un(a),"validate")})).token}r(fn,"collectToken");var pt=r(async(t=null)=>{try{let e=await fn(t);return console.log(`Thanks for authenticating. We'll save the key to: ${p.info(u.CONFIG_FILE)}
9
- `),C.saveToken(u.CONFIG_FILE,u.API_HOST,e),e}catch(e){if(e===""){await b("",0);return}let o=co.captureException(e),n=`
10
-
11
- Error ID: ${p.info(o)}`;return await b(p.errorText("Something went wrong. Please contact support or try again later.")+n)}},"collectAndSaveToken");var uo=l(require("js-yaml"));var H=r((t=u.PROJECT_CONFIG_FILE)=>C.parseSourceInformation(t).validProjects,"getSelectedProjects"),lt=r((t=u.PROJECT_CONFIG_FILE)=>C.parseSourceInformation(t).shouldFetchComponentLibrary,"getIsUsingComponents");var pe=r(t=>{let e="https://app.dittowords.com";return t==="ditto_component_library"?`${e}/components`:`${e}/doc/${t}`},"getSourceUrl"),dn=r(t=>(t||[]).reduce((e,{name:o,id:n})=>e+(`
12
- - `+p.info(o)+" "+p.subtle(pe(n))),"")+`
13
- `,"projectsToText"),bt=dn;var{AutoComplete:gn}=require("enquirer");function hn(t){return t.name+" "+p.subtle(t.url||pe(t.id))}r(hn,"formatProjectChoice");function yn(t){if(!t)return null;let[,e,o]=t.split(/^(.*)\s.*http.*\/(\w+).*$/);return o==="all"?{name:e,id:"ditto_component_library"}:{name:e,id:o}}r(yn,"parseResponse");var xn=r(async({message:t,projects:e,limit:o=10})=>{p.write(`
14
- `);let n=e.map(hn),s=new gn({name:"project",message:t,limit:o,choices:n}),i;try{i=await s.run()}catch{i=null}return yn(i)},"promptForProject"),qt=xn;function Tn(t,e,o){if(o==="components"){C.writeProjectConfigData(t,{sources:{components:!0}});return}let n=[...H(t),{name:e,id:o}];C.writeProjectConfigData(t,{sources:{projects:n}})}r(Tn,"saveProject");var go=r(()=>!C.parseSourceInformation().hasSourceData,"needsSource");async function Sn(){C.deleteToken(u.CONFIG_FILE,u.API_HOST),await pt("Looks like the API key you have saved no longer works. Please enter another one.")}r(Sn,"askForAnotherToken");async function Cn(t,e){let o=j(),n=(0,fo.default)("Fetching sources in your workspace...");n.start();let s;try{s=await o.get("/v1/projects")}catch(c){throw n.stop(),c}let i=e.reduce((c,m)=>c.add(m.id.toString()),new Set),a=s.data.filter(({id:c})=>c!=="ditto_component_library"&&!i.has(c.toString()));return n.stop(),a}r(Cn,"listProjects");async function In(t,e){let o=H(),n=lt(),s=await Cn(t,o);return e&&!n&&(s=[{id:"ditto_component_library",name:"Ditto Component Library"},...s]),s?.length?qt({projects:s,message:"Choose the source you'd like to sync text from"}):(console.log("You're currently syncing all projects in your workspace."),console.log(p.warnText("Not seeing a project that you were expecting? Verify that developer mode is enabled on that project. More info: https://www.dittowords.com/docs/ditto-developer-mode")),null)}r(In,"collectSource");var Ft=r(async({components:t=!1}={components:!1})=>{try{let e=C.getToken(u.CONFIG_FILE,u.API_HOST),o=await In(e,t);if(!o){await b(null,0);return}console.log(`
7
+ `),await no.flush(),process.exit(e)}n(b,"quit");var po=require("axios");var ae=n((t,e=u.API_HOST)=>{if(S.getTokenFromEnv())return!1;let o=t||u.CONFIG_FILE;if(!so.default.existsSync(o))return!0;let r=S.readGlobalConfigData(o);return!r[S.justTheHost(e)]||r[S.justTheHost(e)][0].token===""},"needsToken");async function ln(t){let e=j(t),o="/token-check",r;try{r=await e.get(o)}catch(s){if(!(s instanceof po.AxiosError))return{success:!1,output:[p.warnText("Sorry! We're having trouble reaching the Ditto API.")]};if(s.code==="ENOTFOUND")return{success:!1,output:[p.errorText(`Can't connect to API: ${p.url(u.API_HOST)}`)]};if(s.response?.status===401||s.response?.status===404)return{success:!1,output:[p.errorText("This API key isn't valid. Please try another.")]}}return typeof r=="string"?{success:!1,output:[r]}:r?.status===200?{success:!0}:{success:!1,output:[p.errorText("This API key isn't valid. Please try another.")]}}n(ln,"verifyTokenUsingTokenCheck");async function un(t){let e=await ln(t);return e.success?!0:e.output.join(`
8
+ `)}n(un,"checkToken");async function fn(t){let e=p.info,o=p.url("https://app.dittowords.com/account/devtools"),r=`${ao.default.bold(e("API Keys"))}`,s=t||`To get started, you'll need your Ditto API key. You can find this at: ${o} under "${r}".`;return console.log(s),(await(0,co.prompt)({type:"input",name:"token",message:"What is your API key?",validate:n(a=>un(a),"validate")})).token}n(fn,"collectToken");var lt=n(async(t=null)=>{try{let e=await fn(t);return console.log(`Thanks for authenticating. We'll save the key to: ${p.info(u.CONFIG_FILE)}
9
+ `),S.saveToken(u.CONFIG_FILE,u.API_HOST,e),e}catch(e){if(e===""){await b("",0);return}let o=io.captureException(e),r=`
10
+
11
+ Error ID: ${p.info(o)}`;return await b(p.errorText("Something went wrong. Please contact support or try again later.")+r)}},"collectAndSaveToken");var mo=m(require("js-yaml"));var Q=n((t=u.PROJECT_CONFIG_FILE)=>S.parseSourceInformation(t).validProjects,"getSelectedProjects"),ut=n((t=u.PROJECT_CONFIG_FILE)=>S.parseSourceInformation(t).shouldFetchComponentLibrary,"getIsUsingComponents");var ce=n(t=>{let e="https://app.dittowords.com";return t==="ditto_component_library"?`${e}/components`:`${e}/doc/${t}`},"getSourceUrl"),dn=n(t=>(t||[]).reduce((e,{name:o,id:r})=>e+(`
12
+ - `+p.info(o)+" "+p.subtle(ce(r))),"")+`
13
+ `,"projectsToText"),bt=dn;var{AutoComplete:gn}=require("enquirer");function hn(t){return t.name+" "+p.subtle(t.url||ce(t.id))}n(hn,"formatProjectChoice");function yn(t){if(!t)return null;let[,e,o]=t.split(/^(.*)\s.*http.*\/(\w+).*$/);return o==="all"?{name:e,id:"ditto_component_library"}:{name:e,id:o}}n(yn,"parseResponse");var xn=n(async({message:t,projects:e,limit:o=10})=>{p.write(`
14
+ `);let r=e.map(hn),s=new gn({name:"project",message:t,limit:o,choices:r}),i;try{i=await s.run()}catch{i=null}return yn(i)},"promptForProject"),qt=xn;function Tn(t,e,o){if(o==="components"){S.writeProjectConfigData(t,{sources:{components:!0}});return}let r=[...Q(t),{name:e,id:o}];S.writeProjectConfigData(t,{sources:{projects:r}})}n(Tn,"saveProject");var uo=n(()=>!S.parseSourceInformation().hasSourceData,"needsSource");async function Cn(){S.deleteToken(u.CONFIG_FILE,u.API_HOST),await lt("Looks like the API key you have saved no longer works. Please enter another one.")}n(Cn,"askForAnotherToken");async function Sn(t,e){let o=j(),r=(0,lo.default)("Fetching sources in your workspace...");r.start();let s;try{s=await o.get("/v1/projects")}catch(c){throw r.stop(),c}let i=e.reduce((c,l)=>c.add(l.id.toString()),new Set),a=s.data.filter(({id:c})=>c!=="ditto_component_library"&&!i.has(c.toString()));return r.stop(),a}n(Sn,"listProjects");async function In(t,e){let o=Q(),r=ut(),s=await Sn(t,o);return e&&!r&&(s=[{id:"ditto_component_library",name:"Ditto Component Library"},...s]),s?.length?qt({projects:s,message:"Choose the source you'd like to sync text from"}):(console.log("You're currently syncing all projects in your workspace."),console.log(p.warnText("Not seeing a project that you were expecting? Verify that developer mode is enabled on that project. More info: https://www.dittowords.com/docs/ditto-developer-mode")),null)}n(In,"collectSource");var Ot=n(async({components:t=!1}={components:!1})=>{try{let e=S.getToken(u.CONFIG_FILE,u.API_HOST),o=await In(e,t);if(!o){await b(null,0);return}console.log(`
15
15
  Thanks for adding ${p.info(o.name)} to your selected sources.
16
16
  We saved your updated configuration to: ${p.info(u.PROJECT_CONFIG_FILE)}
17
- `),Tn(u.PROJECT_CONFIG_FILE,o.name,o.id)}catch(e){console.log(e),e.response&&e.response.status===404?(await Sn(),await Ft({components:t})):await b(null,2)}},"collectAndSaveSource");var wn=r((t,e)=>{let o="";return e&&(o+=`the ${p.info("Ditto Component Library")}`,(t||[]).length?o+=" and ":o+=".."),(t||[]).length&&(o+=`the following projects: ${bt(t)}
18
- `),o},"sourcesToText"),Gt=wn;var yo=r(()=>ce()||go(),"needsTokenOrSource");function vn(){let t=Ut.default.white(`${Ut.default.bold("Welcome to the",Ut.default.magentaBright("Ditto CLI"))}.
17
+ `),Tn(u.PROJECT_CONFIG_FILE,o.name,o.id)}catch(e){console.log(e),e.response&&e.response.status===404?(await Cn(),await Ot({components:t})):await b(null,2)}},"collectAndSaveSource");var vn=n((t,e)=>{let o="";return e&&(o+=`the ${p.info("Ditto Component Library")}`,(t||[]).length?o+=" and ":o+=".."),(t||[]).length&&(o+=`the following projects: ${bt(t)}
18
+ `),o},"sourcesToText"),Gt=vn;var go=n(()=>ae()||uo(),"needsTokenOrSource");function wn(){let t=Ut.default.white(`${Ut.default.bold("Welcome to the",Ut.default.magentaBright("Ditto CLI"))}.
19
19
 
20
- We're glad to have you here.`);console.log((0,ho.default)(t,{padding:1}))}r(vn,"welcome");var xo=r(async()=>{vn(),ce()&&await pt();let{hasSourceData:t,validProjects:e,shouldFetchComponentLibrary:o,hasTopLevelComponentsField:n,hasTopLevelProjectsField:s}=C.parseSourceInformation();if(s)return await b(`${p.errorText(`Support for ${p.warnText("projects")} as a top-level field has been removed; please configure ${p.warnText("sources.projects")} instead.`)}
21
- See ${p.url("https://github.com/dittowords/cli")} for more information.`);if(n)return await b(`${p.errorText("Support for `components` as a top-level field has been removed; please configure `sources.components` instead.")}
22
- See ${p.url("https://github.com/dittowords/cli")} for more information.`);if(!t){console.log(`Looks like there are no Ditto sources selected for your current directory: ${p.info(process.cwd())}.`),await Ft({initialize:!0,components:!0});return}let i="You're currently set up to sync text from "+Gt(e,o);console.log(i)},"init");var X=l(require("fs")),mt=l(require("path")),Po=l(require("ora")),Eo=l(require("@sentry/node"));var le=l(require("fs")),me=l(require("path"));function G(t){let e=t.split(/\s{1,}/g);return e=e.map(o=>o.replace(/[^a-zA-Z0-9-_.]/g,"").toLowerCase()),e=e.filter(o=>o!==""),e.join("-")}r(G,"cleanFileName");var zt=l(require("fs")),Wt=l(require("path"));function To(t=process.cwd()){let e=jn(t);return bn(e)}r(To,"determineModuleType");function jn(t){if(process.env.DITTO_MODULE_TYPE)return process.env.DITTO_MODULE_TYPE;for(;t;){let e=Wt.join(t,"package.json");if(zt.existsSync(e)){let o=zt.readFileSync(e,"utf8");try{let n=JSON.parse(o);if(n?.type)return n.type}catch{}return null}if(t==="/")break;t=Wt.dirname(t)}return null}r(jn,"getRawTypeFromPackageJson");function bn(t){let e=t?.toLowerCase()||"";return e==="commonjs"||e==="module"?e:"commonjs"}r(bn,"getTypeOrDefault");var So=l(require("fs")),Co=l(require("path"));function Fn(t){switch(t){case"flat":return"IJSONFlat";case"nested":return"IJSONNested";case"structured":return"IJSONStructured";case"icu":return"IJSONICU";default:return"_JSON"}}r(Fn,"getFormatString");function On(t,e){return e==="commonjs"?`export = ${t};`:`export default ${t};`}r(On,"getExportString");function Pn(t){return`
20
+ We're glad to have you here.`);console.log((0,fo.default)(t,{padding:1}))}n(wn,"welcome");var ho=n(async()=>{wn(),ae()&&await lt();let{hasSourceData:t,validProjects:e,shouldFetchComponentLibrary:o,hasTopLevelComponentsField:r,hasTopLevelProjectsField:s}=S.parseSourceInformation();if(s)return await b(`${p.errorText(`Support for ${p.warnText("projects")} as a top-level field has been removed; please configure ${p.warnText("sources.projects")} instead.`)}
21
+ See ${p.url("https://github.com/dittowords/cli")} for more information.`);if(r)return await b(`${p.errorText("Support for `components` as a top-level field has been removed; please configure `sources.components` instead.")}
22
+ See ${p.url("https://github.com/dittowords/cli")} for more information.`);if(!t){console.log(`Looks like there are no Ditto sources selected for your current directory: ${p.info(process.cwd())}.`),await Ot({initialize:!0,components:!0});return}let i="You're currently set up to sync text from "+Gt(e,o);console.log(i)},"init");var K=m(require("fs")),ft=m(require("path")),bo=m(require("ora")),Oo=m(require("@sentry/node"));var pe=m(require("fs")),me=m(require("path"));function G(t){let e=t.split(/\s{1,}/g);return e=e.map(o=>o.replace(/[^a-zA-Z0-9-_.]/g,"").toLowerCase()),e=e.filter(o=>o!==""),e.join("-")}n(G,"cleanFileName");var zt=m(require("fs")),Zt=m(require("path"));function yo(t=process.cwd()){let e=jn(t);return Fn(e)}n(yo,"determineModuleType");function jn(t){if(process.env.DITTO_MODULE_TYPE)return process.env.DITTO_MODULE_TYPE;for(;t;){let e=Zt.join(t,"package.json");if(zt.existsSync(e)){let o=zt.readFileSync(e,"utf8");try{let r=JSON.parse(o);if(r?.type)return r.type}catch{}return null}if(t==="/")break;t=Zt.dirname(t)}return null}n(jn,"getRawTypeFromPackageJson");function Fn(t){let e=t?.toLowerCase()||"";return e==="commonjs"||e==="module"?e:"commonjs"}n(Fn,"getTypeOrDefault");var xo=m(require("fs")),To=m(require("path"));function bn(t){switch(t){case"flat":return"IJSONFlat";case"nested":return"IJSONNested";case"structured":return"IJSONStructured";case"icu":return"IJSONICU";default:return"_JSON"}}n(bn,"getFormatString");function On(t,e){return e==="commonjs"?`export = ${t};`:`export default ${t};`}n(On,"getExportString");function Pn(t){return`
23
23
  interface IJSONFlat {
24
24
  [key: string]: string;
25
25
  }
@@ -41,87 +41,87 @@ type _JSON = IJSONFlat | IJSONStructured | IJSONNested;
41
41
 
42
42
  interface IDriverFile {
43
43
  [sourceKey: string]: {
44
- [variantKey: string]: ${Fn(t.format)};
44
+ [variantKey: string]: ${bn(t.format)};
45
45
  };
46
46
  }
47
47
 
48
48
  declare const driver: IDriverFile;
49
49
 
50
50
  ${On("driver",t.moduleType)}
51
- `.trim()}r(Pn,"getTypesString");function Io(t){let e=Pn(t);So.default.writeFileSync(Co.default.resolve(u.TEXT_DIR,"index.d.ts"),e+`
52
- `,"utf8")}r(Io,"generateJsDriverTypeFile");var En=r(t=>t==="ditto_component_library"?t:`project_${t}`,"stringifySourceId");function wo(t,e){let o=To(),n=kn(t),s=Dn(),i=[],a={},c={};n.forEach(f=>{var S;let d;if(f.type==="components")d=s.generate(f.fileName.split(".")[0]);else{let x=f.fileName.split(".")[0];d=s.generate(x.split("__")[0])}if(i.push(Nn(f.fileName,d,o)),f.type==="project"){let{variantApiId:x}=f,w=En(f.projectId);a[w]??(a[w]={}),a[w][x]=`{...${d}}`}else c[S=f.variantApiId]??(c[S]=[]),c[f.variantApiId].push(`...${d}`)}),Object.keys(c).forEach(f=>{a.ditto_component_library??(a.ditto_component_library={});let d="{";c[f].forEach((S,x)=>{d+=S,x<c[f].length-1&&(d+=", ")}),d+="}",a.ditto_component_library[f]=d});let m="";m+=i.join(`
51
+ `.trim()}n(Pn,"getTypesString");function Co(t){let e=Pn(t);xo.default.writeFileSync(To.default.resolve(u.TEXT_DIR,"index.d.ts"),e+`
52
+ `,"utf8")}n(Co,"generateJsDriverTypeFile");var En=n(t=>t==="ditto_component_library"?t:`project_${t}`,"stringifySourceId");function So(t,e){let o=yo(),r=kn(t),s=Dn(),i=[],a={},c={};r.forEach(f=>{var C;let d;if(f.type==="components")d=s.generate(f.fileName.split(".")[0]);else{let x=f.fileName.split(".")[0];d=s.generate(x.split("__")[0])}if(i.push(Nn(f.fileName,d,o)),f.type==="project"){let{variantApiId:x}=f,v=En(f.projectId);a[v]??(a[v]={}),a[v][x]=`{...${d}}`}else c[C=f.variantApiId]??(c[C]=[]),c[f.variantApiId].push(`...${d}`)}),Object.keys(c).forEach(f=>{a.ditto_component_library??(a.ditto_component_library={});let d="{";c[f].forEach((C,x)=>{d+=C,x<c[f].length-1&&(d+=", ")}),d+="}",a.ditto_component_library[f]=d});let l="";l+=i.join(`
53
53
  `)+`
54
54
 
55
- `,m+=`${An(o)}`,m+=`${JSON.stringify(a,null,2)}`.replace(/"\{/g,"{").replace(/\}"/g,"}");let g=me.default.resolve(u.TEXT_DIR,"index.js");return le.default.writeFileSync(g,m,{encoding:"utf8"}),Io({format:e,moduleType:o}),`Generated .js SDK driver at ${p.info(g)}`}r(wo,"generateJsDriver");function kn(t){let e=new Map;return t.forEach(n=>{!n.fileName||n.type==="components"||e.set(G(n.fileName),n.id)}),le.default.readdirSync(u.TEXT_DIR).filter(n=>me.default.extname(n)===".json").map(n=>{let s=n.split("__");if(s.length===3){let[,i,a]=s,[c]=a.split(".");return{type:"components",variantApiId:c,folderApiId:i,fileName:n}}if(s.length===2){let[i,a]=s,[c]=a.split("."),m=G(n.split("__")[0]);return{type:"project",projectId:e.get(m)||"",projectName:i,variantApiId:c,fileName:n}}throw new Error("Invalid JSON file generated: "+n)})}r(kn,"getFullyQualifiedJSONSources");function Dn(){let t=new Set;return{generate:r(e=>{let o=e.replace(/(\W|-)/g,"_"),n=o,s=1;for(;t.has(n);)n=`${o}${s}`,s++;return t.add(n),n},"generate")}}r(Dn,"createVariableNameGenerator");function An(t){if(t==="commonjs")return"module.exports = ";if(t==="module")return"export default ";throw new Error("Unknown module type: "+t)}r(An,"getExportPrefix");function Nn(t,e,o){if(o==="commonjs")return`const ${e} = require('./${t}');`;if(o==="module")return`import ${e} from './${t}';`;throw new Error("Unknown module type: "+o)}r(Nn,"getImportStatement");async function vo(t,e={}){let o=j();if(!t.variants)return null;let{shouldFetchComponentLibrary:n,validProjects:s}=t,i={params:{...e?.meta,showSampleData:e.includeSampleData}};s.length&&!n&&(i.params.projectIds=s.map(({id:c})=>c));let{data:a}=await o.get("/v1/variants",i);return a}r(vo,"fetchVariants");var ko=require("axios");async function Zt(t={}){let e=j(),o="/v1/component-folders";t.showSampleData===!0&&(o+="?showSampleData=true");let{data:n}=await e.get(o,{});return n}r(Zt,"fetchComponentFolders");var jo=l(require("path"));async function bo(t){let e=j(),o={variants:t.variants,localeByVariantId:t.localeByVariantApiId};t.componentFolders||t.componentRoot?(o.components={},t.componentFolders&&(o.components.folders=t.componentFolders),t.componentRoot&&(o.components.root=t.componentRoot)):t.shouldFetchComponentLibrary&&(o.components=!0),t.validProjects&&(o.projects=t.validProjects);let{data:n}=await e.post("/v1/ios/swift-driver",o),s=jo.default.join(u.TEXT_DIR,"Ditto.swift");return await Ot(s,n),`Successfully saved Swift driver to ${p.info("Ditto.swift")}`}r(bo,"generateSwiftDriver");var Ht=l(require("path")),E=l(require("fs"));var Rn=/\.(strings|stringsdict)$/;async function Fo(t){let e=E.default.readdirSync(u.TEXT_DIR),o={};for(let n of e){if(!Rn.test(n))continue;let[s,i]=n.split(".");if(!s.length)continue;let a=s.split("__"),c=a[0],m=a[a.length-1];if(!(c&&m))continue;let g=t&&t[m]?t[m]:m,f=`${g}.lproj`,d=Ht.default.join(u.TEXT_DIR,f);E.default.existsSync(d)||E.default.mkdirSync(d);let S=Ht.default.join(u.TEXT_DIR,n),x=Ht.default.join(d,`${c}.${i}`);_n(c,i,S,x),o[f]={mappedVariant:m===g?void 0:m}}return Object.keys(o).map(n=>{let s=`Successfully generated iOS bundle ${p.info(n)}`,i=o[n].mappedVariant;return i&&(s+=` ${p.subtle(`(mapped to variant '${i}')`)}`),s}).join(`
55
+ `,l+=`${An(o)}`,l+=`${JSON.stringify(a,null,2)}`.replace(/"\{/g,"{").replace(/\}"/g,"}");let g=me.default.resolve(u.TEXT_DIR,"index.js");return pe.default.writeFileSync(g,l,{encoding:"utf8"}),Co({format:e,moduleType:o}),`Generated .js SDK driver at ${p.info(g)}`}n(So,"generateJsDriver");function kn(t){let e=new Map;return t.forEach(r=>{!r.fileName||r.type==="components"||e.set(G(r.fileName),r.id)}),pe.default.readdirSync(u.TEXT_DIR).filter(r=>me.default.extname(r)===".json").map(r=>{let s=r.split("__");if(s.length===3){let[,i,a]=s,[c]=a.split(".");return{type:"components",variantApiId:c,folderApiId:i,fileName:r}}if(s.length===2){let[i,a]=s,[c]=a.split("."),l=G(r.split("__")[0]);return{type:"project",projectId:e.get(l)||"",projectName:i,variantApiId:c,fileName:r}}throw new Error("Invalid JSON file generated: "+r)})}n(kn,"getFullyQualifiedJSONSources");function Dn(){let t=new Set;return{generate:n(e=>{let o=e.replace(/(\W|-)/g,"_"),r=o,s=1;for(;t.has(r);)r=`${o}${s}`,s++;return t.add(r),r},"generate")}}n(Dn,"createVariableNameGenerator");function An(t){if(t==="commonjs")return"module.exports = ";if(t==="module")return"export default ";throw new Error("Unknown module type: "+t)}n(An,"getExportPrefix");function Nn(t,e,o){if(o==="commonjs")return`const ${e} = require('./${t}');`;if(o==="module")return`import ${e} from './${t}';`;throw new Error("Unknown module type: "+o)}n(Nn,"getImportStatement");async function Io(t,e={}){let o=j();if(!t.variants)return null;let{shouldFetchComponentLibrary:r,validProjects:s}=t,i={params:{...e?.meta,showSampleData:e.includeSampleData}};s.length&&!r&&(i.params.projectIds=s.map(({id:c})=>c));let{data:a}=await o.get("/v1/variants",i);return a}n(Io,"fetchVariants");var Po=require("axios");async function Wt(t={}){let e=j(),o="/v1/component-folders";t.showSampleData===!0&&(o+="?showSampleData=true");let{data:r}=await e.get(o,{});return r}n(Wt,"fetchComponentFolders");var vo=m(require("path"));async function wo(t){let e=j(),o={variants:t.variants,localeByVariantId:t.localeByVariantApiId};t.componentFolders||t.componentRoot?(o.components={},t.componentFolders&&(o.components.folders=t.componentFolders),t.componentRoot&&(o.components.root=t.componentRoot)):t.shouldFetchComponentLibrary&&(o.components=!0),t.validProjects&&(o.projects=t.validProjects);let{data:r}=await e.post("/v1/ios/swift-driver",o),s=vo.default.join(u.TEXT_DIR,"Ditto.swift");return await Pt(s,r),`Successfully saved Swift driver to ${p.info("Ditto.swift")}`}n(wo,"generateSwiftDriver");var Ht=m(require("path")),E=m(require("fs"));var Mn=/\.(strings|stringsdict)$/;async function jo(t){let e=E.default.readdirSync(u.TEXT_DIR),o={};for(let r of e){if(!Mn.test(r))continue;let[s,i]=r.split(".");if(!s.length)continue;let a=s.split("__"),c=a[0],l=a[a.length-1];if(!(c&&l))continue;let g=t&&t[l]?t[l]:l,f=`${g}.lproj`,d=Ht.default.join(u.TEXT_DIR,f);E.default.existsSync(d)||E.default.mkdirSync(d);let C=Ht.default.join(u.TEXT_DIR,r),x=Ht.default.join(d,`${c}.${i}`);Rn(c,i,C,x),o[f]={mappedVariant:l===g?void 0:l}}return Object.keys(o).map(r=>{let s=`Successfully generated iOS bundle ${p.info(r)}`,i=o[r].mappedVariant;return i&&(s+=` ${p.subtle(`(mapped to variant '${i}')`)}`),s}).join(`
56
56
  `)+`
57
- `}r(Fo,"generateIOSBundles");function _n(t,e,o,n){if(!E.default.existsSync(n))return E.default.renameSync(o,n);if(t!=="components")throw new Error("Bundle path for "+t+" already exists");if(e==="strings")return Mn(o,n);if(e==="stringsdict")return $n(o,n);throw new Error("Unsupported extension "+e)}r(_n,"handleBundleGeneration");function Mn(t,e){let o=E.default.readFileSync(t,"utf-8"),s=E.default.readFileSync(e,"utf-8")+`
58
- `+o;E.default.writeFileSync(e,s),E.default.unlinkSync(t)}r(Mn,"appendStringsFile");function $n(t,e){let n=E.default.readFileSync(t,"utf-8").split(`
57
+ `}n(jo,"generateIOSBundles");function Rn(t,e,o,r){if(!E.default.existsSync(r))return E.default.renameSync(o,r);if(t!=="components")throw new Error("Bundle path for "+t+" already exists");if(e==="strings")return _n(o,r);if(e==="stringsdict")return $n(o,r);throw new Error("Unsupported extension "+e)}n(Rn,"handleBundleGeneration");function _n(t,e){let o=E.default.readFileSync(t,"utf-8"),s=E.default.readFileSync(e,"utf-8")+`
58
+ `+o;E.default.writeFileSync(e,s),E.default.unlinkSync(t)}n(_n,"appendStringsFile");function $n(t,e){let r=E.default.readFileSync(t,"utf-8").split(`
59
59
  `).slice(3,-4),a=`<?xml version="1.0" encoding="utf-8"?>
60
60
  <plist version="1.0">
61
61
  <dict>
62
62
  ${[E.default.readFileSync(e,"utf-8").split(`
63
- `).slice(3,-4),n].join(`
63
+ `).slice(3,-4),r].join(`
64
64
  `)}
65
65
  </dict>
66
66
  </plist>
67
- `;E.default.writeFileSync(e,a),E.default.unlinkSync(t)}r($n,"appendStringsDictFile");var Ln=r(t=>t+(/[\r\n]$/.test(t)?"":`
68
- `),"ensureEndsWithNewLine"),Ot=r((t,e)=>new Promise(o=>X.default.writeFile(t,Ln(e),o)),"writeFile"),Jn=["flat","nested","structured","android","ios-strings","ios-stringsdict","icu"],Vn=["ios-strings","ios-stringsdict"],Do=["flat","nested","structured","icu"],Yn=r(t=>{let e=t.filter(o=>Do.includes(o));return e[e.length-1]||"flat"},"getJsonFormat"),Bn={flat:".json",nested:".json",structured:".json",android:".xml","ios-strings":".strings","ios-stringsdict":".stringsdict",icu:".json"},Xt=r(t=>{try{return Object.keys(JSON.parse(t)).some(e=>!e.startsWith("__variant"))}catch{return!1}},"getJsonFormatIsValid"),ue={flat:Xt,nested:Xt,structured:Xt,icu:Xt,android:r(t=>t.includes("<string"),"android"),"ios-strings":r(t=>t.includes('" = "'),"ios-strings"),"ios-stringsdict":r(t=>t.includes("<key>"),"ios-stringsdict")},qn=r(t=>{let e=(Array.isArray(t)?t:[t]).filter(o=>Jn.includes(o));return e.length?e:["flat"]},"getFormat"),fe=r(t=>Bn[t],"getFormatExtension"),Gn=["projects","exported_at"],Un=r(t=>{let e=Object.keys(t).filter(n=>!Gn.includes(n)).length>0,o=t.projects&&Object.keys(t.projects).length>0;return e||o},"hasVariantData");async function zn(){C.deleteToken(u.CONFIG_FILE,u.API_HOST),await pt("Looks like the API key you have saved no longer works. Please enter another one.")}r(zn,"askForAnotherToken");async function Oo(t,e){let{projects:o,format:n,status:s,richText:i,token:a}=e,c=j(),m={variant:t};return n&&(m.format=n),i&&(m.includeRichText=i.toString()),s&&(m.status=s),(await Promise.all(o.map(async f=>{let d={...m};f.status&&(d.status=f.status),f.exclude_components&&(d.exclude_components=String(f.exclude_components));let{data:S}=await c.get(`/v1/projects/${f.id}`,{params:d,headers:{Authorization:`token ${a}`}});if(!Un(S))return"";let x=fe(n),w=G(f.fileName+("__"+(t||"base"))+x),_=mt.default.join(u.TEXT_DIR,w),P=S;x===".json"&&(P=JSON.stringify(S,null,2));let M=ue[n];return M(P)?(await Ot(_,P),de(w)):""}))).join("")}r(Oo,"downloadAndSaveVariant");async function Wn(t){return(await Promise.all([Oo(null,t),...t.variants.map(({apiID:o})=>Oo(o,t))])).join("")}r(Wn,"downloadAndSaveVariants");async function Zn(t){let{projects:e,format:o,status:n,richText:s,token:i,options:a}=t,c=j(),m={...a?.meta};return o&&(m.format=o),s&&(m.includeRichText=s.toString()),n&&(m.status=n),(await Promise.all(e.map(async f=>{let d={...m};f.status&&(d.status=f.status),f.exclude_components&&(d.exclude_components=String(f.exclude_components));let{data:S}=await c.get(`/v1/projects/${f.id}`,{params:d,headers:{Authorization:`token ${i}`}}),x=fe(o),w=G(`${f.fileName}__base${x}`),_=mt.default.join(u.TEXT_DIR,w),P=S;x===".json"&&(P=JSON.stringify(S,null,2));let M=ue[o];return M(P)?(await Ot(_,P),de(w)):""}))).join("")}r(Zn,"downloadAndSaveBase");function de(t){return`Successfully saved to ${p.info(t)}
69
- `}r(de,"getSavedMessage");function Hn(){return X.default.existsSync(u.TEXT_DIR)||X.default.mkdirSync(u.TEXT_DIR),X.default.readdirSync(u.TEXT_DIR,{withFileTypes:!0}).forEach(e=>{if(e.isDirectory()&&/\.lproj$/.test(e.name))return X.default.rmSync(mt.default.resolve(u.TEXT_DIR,e.name),{recursive:!0,force:!0});if(e.isFile()&&/\.js(on)?|\.ts|\.xml|\.strings(dict)?$|\.swift$/.test(e.name))return X.default.unlinkSync(mt.default.resolve(u.TEXT_DIR,e.name))}),`Cleaning old output files..
70
- `}r(Hn,"cleanOutputFiles");async function Xn(t,e,o){let n=j(),{validProjects:s,format:i,shouldFetchComponentLibrary:a,status:c,richText:m,componentFolders:g,componentRoot:f,localeByVariantApiId:d,disableJsDriver:S}=t,x=qn(i),w=x.some(v=>Do.includes(v)),P=x.some(v=>Vn.includes(v))&&d,M=!P,I="",k=(0,Po.default)(I);k.start();let[nt,Pr]=await Promise.all([vo(t,o),Zt({})]),qe=Object.entries(Pr).reduce((v,[N,L])=>v.concat([{id:N,name:L}]),[]);try{I+=Hn(),I+=`
67
+ `;E.default.writeFileSync(e,a),E.default.unlinkSync(t)}n($n,"appendStringsDictFile");var Ln=n(t=>t+(/[\r\n]$/.test(t)?"":`
68
+ `),"ensureEndsWithNewLine"),Pt=n((t,e)=>new Promise(o=>K.default.writeFile(t,Ln(e),o)),"writeFile"),Jn=["flat","nested","structured","android","ios-strings","ios-stringsdict","icu"],Vn=["ios-strings","ios-stringsdict"],Eo=["flat","nested","structured","icu"],Yn=n(t=>{let e=t.filter(o=>Eo.includes(o));return e[e.length-1]||"flat"},"getJsonFormat"),Bn={flat:".json",nested:".json",structured:".json",android:".xml","ios-strings":".strings","ios-stringsdict":".stringsdict",icu:".json"},Xt=n(t=>{try{return Object.keys(JSON.parse(t)).some(e=>!e.startsWith("__variant"))}catch{return!1}},"getJsonFormatIsValid"),le={flat:Xt,nested:Xt,structured:Xt,icu:Xt,android:n(t=>t.includes("<string"),"android"),"ios-strings":n(t=>t.includes('" = "'),"ios-strings"),"ios-stringsdict":n(t=>t.includes("<key>"),"ios-stringsdict")},qn=n(t=>{let e=(Array.isArray(t)?t:[t]).filter(o=>Jn.includes(o));return e.length?e:["flat"]},"getFormat"),ue=n(t=>Bn[t],"getFormatExtension"),Gn=["projects","exported_at"],Un=n(t=>{let e=Object.keys(t).filter(r=>!Gn.includes(r)).length>0,o=t.projects&&Object.keys(t.projects).length>0;return e||o},"hasVariantData");async function zn(){S.deleteToken(u.CONFIG_FILE,u.API_HOST),await lt("Looks like the API key you have saved no longer works. Please enter another one.")}n(zn,"askForAnotherToken");async function Fo(t,e){let{projects:o,format:r,status:s,richText:i,token:a}=e,c=j(),l={variant:t};return r&&(l.format=r),i&&(l.includeRichText=i.toString()),s&&(l.status=s),(await Promise.all(o.map(async f=>{let d={...l};f.status&&(d.status=f.status),f.exclude_components&&(d.exclude_components=String(f.exclude_components));let{data:C}=await c.get(`/v1/projects/${f.id}`,{params:d,headers:{Authorization:`token ${a}`}});if(!Un(C))return"";let x=ue(r),v=G(f.fileName+("__"+(t||"base"))+x),R=ft.default.join(u.TEXT_DIR,v),P=C;x===".json"&&(P=JSON.stringify(C,null,2));let _=le[r];return _(P)?(await Pt(R,P),fe(v)):""}))).join("")}n(Fo,"downloadAndSaveVariant");async function Zn(t){return(await Promise.all([Fo(null,t),...t.variants.map(({apiID:o})=>Fo(o,t))])).join("")}n(Zn,"downloadAndSaveVariants");async function Wn(t){let{projects:e,format:o,status:r,richText:s,token:i,options:a}=t,c=j(),l={...a?.meta};return o&&(l.format=o),s&&(l.includeRichText=s.toString()),r&&(l.status=r),(await Promise.all(e.map(async f=>{let d={...l};f.status&&(d.status=f.status),f.exclude_components&&(d.exclude_components=String(f.exclude_components));let{data:C}=await c.get(`/v1/projects/${f.id}`,{params:d,headers:{Authorization:`token ${i}`}}),x=ue(o),v=G(`${f.fileName}__base${x}`),R=ft.default.join(u.TEXT_DIR,v),P=C;x===".json"&&(P=JSON.stringify(C,null,2));let _=le[o];return _(P)?(await Pt(R,P),fe(v)):""}))).join("")}n(Wn,"downloadAndSaveBase");function fe(t){return`Successfully saved to ${p.info(t)}
69
+ `}n(fe,"getSavedMessage");function Hn(){return K.default.existsSync(u.TEXT_DIR)||K.default.mkdirSync(u.TEXT_DIR),K.default.readdirSync(u.TEXT_DIR,{withFileTypes:!0}).forEach(e=>{if(e.isDirectory()&&/\.lproj$/.test(e.name))return K.default.rmSync(ft.default.resolve(u.TEXT_DIR,e.name),{recursive:!0,force:!0});if(e.isFile()&&/\.js(on)?|\.ts|\.xml|\.strings(dict)?$|\.swift$/.test(e.name))return K.default.unlinkSync(ft.default.resolve(u.TEXT_DIR,e.name))}),`Cleaning old output files..
70
+ `}n(Hn,"cleanOutputFiles");async function Xn(t,e,o){let r=j(),{validProjects:s,format:i,shouldFetchComponentLibrary:a,status:c,richText:l,componentFolders:g,componentRoot:f,localeByVariantApiId:d,disableJsDriver:C}=t,x=qn(i),v=x.some(w=>Eo.includes(w)),P=x.some(w=>Vn.includes(w))&&d,_=!P,I="",k=(0,bo.default)(I);k.start();let[it,Pr]=await Promise.all([Io(t,o),Wt({})]),Ye=Object.entries(Pr).reduce((w,[M,L])=>w.concat([{id:M,name:L}]),[]);try{I+=Hn(),I+=`
71
71
  Fetching the latest text from ${Gt(s,a)}
72
- `;let v=o?o.meta:{},N={id:"__root__",name:"Root",status:typeof t.componentRoot=="object"?t.componentRoot.status:void 0},L=[];if(g)switch(f){case void 0:case!1:L.push(...g);break;default:L.push(...g),L.push(N);break}else switch(f){case void 0:L.push(...qe),L.push(N);break;case!1:L.push(...qe);break;default:L.push(N);break}let Ge=[];async function Er($){let It=[{apiID:void 0},...nt||[]],wt=new URLSearchParams;o?.meta&&Object.entries(o.meta).forEach(([st,Z])=>wt.append(st,Z)),$&&wt.append("format",$),m&&wt.append("includeRichText",m.toString()),c&&wt.append("status",c);let Ue=[];It.forEach(({apiID:st})=>{Ue.push(...L.map(async Z=>{let oe=new URLSearchParams(wt);st&&oe.append("variant",st),Z.status&&oe.append("status",Z.status);let Nr=Z.id==="__root__"?"/v1/components?root_only=true":`/v1/component-folders/${Z.id}/components`,{data:ze}=await n.get(Nr,{params:oe}),We=fe($),Rr="components",_r=`__${G(Z.name)}`,Mr=`__${st||"base"}`,re=G(`${Rr}${_r}${Mr}${We}`),$r=mt.default.join(u.TEXT_DIR,re),ne=ze;We===".json"&&(ne=JSON.stringify(ze,null,2));let Lr=ue[$];return Lr(ne)?(await Ot($r,ne),Ge.push({type:"components",id:"ditto_component_library",name:"ditto_component_library",fileName:re,variant:st||"base"}),de(re)):""}))});let Ar=await Promise.all(Ue);M&&(I+=Ar.join(""))}if(r(Er,"fetchComponentLibrary"),a)for(let $ of x)await Er($);async function kr($){let It="";nt?It=await Wn({variants:nt,projects:s,format:$,status:c,richText:m,token:e}):It=await Zn({projects:s,format:$,status:c,richText:m,token:e,options:{meta:v}}),M&&(I+=It)}if(r(kr,"fetchProjects"),s.length)for(let $ of x)await kr($);let Dr=[...s,...Ge];return w&&!S&&(I+=wo(Dr,Yn(x))),P&&(I+=`iOS locale information detected, generating bundles..
72
+ `;let w=o?o.meta:{},M={id:"__root__",name:"Root",status:typeof t.componentRoot=="object"?t.componentRoot.status:void 0},L=[];if(g)switch(f){case void 0:case!1:L.push(...g);break;default:L.push(...g),L.push(M);break}else switch(f){case void 0:L.push(...Ye),L.push(M);break;case!1:L.push(...Ye);break;default:L.push(M);break}let Be=[];async function Er($){let vt=[{apiID:void 0},...it||[]],wt=new URLSearchParams;o?.meta&&Object.entries(o.meta).forEach(([at,X])=>wt.append(at,X)),$&&wt.append("format",$),l&&wt.append("includeRichText",l.toString()),c&&wt.append("status",c);let qe=[];vt.forEach(({apiID:at})=>{qe.push(...L.map(async X=>{let ee=new URLSearchParams(wt);at&&ee.append("variant",at),X.status&&ee.append("status",X.status);let Nr=X.id==="__root__"?"/v1/components?root_only=true":`/v1/component-folders/${X.id}/components`,{data:Ge}=await r.get(Nr,{params:ee}),Ue=ue($),Mr="components",Rr=`__${G(X.name)}`,_r=`__${at||"base"}`,oe=G(`${Mr}${Rr}${_r}${Ue}`),$r=ft.default.join(u.TEXT_DIR,oe),re=Ge;Ue===".json"&&(re=JSON.stringify(Ge,null,2));let Lr=le[$];return Lr(re)?(await Pt($r,re),Be.push({type:"components",id:"ditto_component_library",name:"ditto_component_library",fileName:oe,variant:at||"base"}),fe(oe)):""}))});let Ar=await Promise.all(qe);_&&(I+=Ar.join(""))}if(n(Er,"fetchComponentLibrary"),a)for(let $ of x)await Er($);async function kr($){let vt="";it?vt=await Zn({variants:it,projects:s,format:$,status:c,richText:l,token:e}):vt=await Wn({projects:s,format:$,status:c,richText:l,token:e,options:{meta:w}}),_&&(I+=vt)}if(n(kr,"fetchProjects"),s.length)for(let $ of x)await kr($);let Dr=[...s,...Be];return v&&!C&&(I+=So(Dr,Yn(x))),P&&(I+=`iOS locale information detected, generating bundles..
73
73
 
74
- `,I+=await Fo(d),I+=await bo(t)),I+=`
74
+ `,I+=await jo(d),I+=await wo(t)),I+=`
75
75
 
76
- ${p.success("Done")}!`,k.stop(),console.log(I)}catch(v){console.error(v),k.stop();let N=v.message;if(v.response&&v.response.status===404){await zn(),ge();return}return v.response&&v.response.status===401?(N="You don't have access to the selected projects",I=`${p.errorText(N)}.
77
- Choose others using the ${p.info("project")} command, or update your API key.`,console.log(I)):v.response&&v.response.status===403?(N="One or more of the requested projects don't have Developer Mode enabled",I=`${p.errorText(N)}.
78
- Please choose different projects using the ${p.info("project")} command, or turn on Developer Mode for all selected projects. Learn more here: ${p.subtle("https://www.dittowords.com/docs/ditto-developer-mode")}.`,console.log(I)):(v.response&&v.response.status===400&&(N="projects not found"),I=`We hit an error fetching text from the projects: ${p.errorText(N)}.
79
- Choose others using the ${p.info("project")} command.`,console.log(I))}}r(Xn,"downloadAndSave");var ge=r(async t=>{let e=t?t.meta:{},o=t?.includeSampleData||!1,n=C.getToken(u.CONFIG_FILE,u.API_HOST),s=C.parseSourceInformation();try{return await Xn(s,n,{meta:e,includeSampleData:o})}catch(i){let a=Eo.captureException(i),c=`
76
+ ${p.success("Done")}!`,k.stop(),console.log(I)}catch(w){console.error(w),k.stop();let M=w.message;if(w.response&&w.response.status===404){await zn(),de();return}return w.response&&w.response.status===401?(M="You don't have access to the selected projects",I=`${p.errorText(M)}.
77
+ Choose others using the ${p.info("project")} command, or update your API key.`,console.log(I)):w.response&&w.response.status===403?(M="One or more of the requested projects don't have Developer Mode enabled",I=`${p.errorText(M)}.
78
+ Please choose different projects using the ${p.info("project")} command, or turn on Developer Mode for all selected projects. Learn more here: ${p.subtle("https://www.dittowords.com/docs/ditto-developer-mode")}.`,console.log(I)):(w.response&&w.response.status===400&&(M="projects not found"),I=`We hit an error fetching text from the projects: ${p.errorText(M)}.
79
+ Choose others using the ${p.info("project")} command.`,console.log(I))}}n(Xn,"downloadAndSave");var de=n(async t=>{let e=t?t.meta:{},o=t?.includeSampleData||!1,r=S.getToken(u.CONFIG_FILE,u.API_HOST),s=S.parseSourceInformation();try{return await Xn(s,r,{meta:e,includeSampleData:o})}catch(i){let a=Oo.captureException(i),c=`
80
80
 
81
- Error ID: ${p.info(a)}`;return i instanceof ko.AxiosError?await b(p.errorText("Something went wrong connecting to Ditto servers. Please contact support or try again later.")+c):await b(p.errorText("Something went wrong. Please contact support or try again later.")+c)}},"pull");var Qn=r(async()=>{let t=H(),e=lt();try{e?t.length?console.log(`
81
+ Error ID: ${p.info(a)}`;return i instanceof Po.AxiosError?await b(p.errorText("Something went wrong connecting to Ditto servers. Please contact support or try again later.")+c):await b(p.errorText("Something went wrong. Please contact support or try again later.")+c)}},"pull");var Qn=n(async()=>{let t=Q(),e=ut();try{e?t.length?console.log(`
82
82
  You're currently syncing text from the ${p.info("Component Library")} and from the following projects: ${bt(t)}`):console.log(`
83
83
  You're currently only syncing text from the ${p.info("Component Library")}`):t.length&&console.log(`
84
- You're currently set up to sync text from the following projects: ${bt(t)}`),await Ft({components:!1})}catch(o){console.log(`
85
- Sorry, there was an error adding a project to your workspace: `,o),await b("Project selection was not updated.")}},"addProject"),Ao=Qn;async function Kn(){let t=H(),e=lt();if(!t.length&&!e){console.log(`
84
+ You're currently set up to sync text from the following projects: ${bt(t)}`),await Ot({components:!1})}catch(o){console.log(`
85
+ Sorry, there was an error adding a project to your workspace: `,o),await b("Project selection was not updated.")}},"addProject"),ko=Qn;async function Kn(){let t=Q(),e=ut();if(!t.length&&!e){console.log(`
86
86
  No projects found in your current configuration.
87
87
  Try adding one with: ${p.info("ditto-cli project add")}
88
- `);return}let o=await qt({projects:t,message:"Select a project to remove"});o&&(C.writeProjectConfigData(u.PROJECT_CONFIG_FILE,{components:e&&o.id!=="components",projects:t.filter(({id:n})=>n!==o.id)}),console.log(`
88
+ `);return}let o=await qt({projects:t,message:"Select a project to remove"});o&&(S.writeProjectConfigData(u.PROJECT_CONFIG_FILE,{components:e&&o.id!=="components",projects:t.filter(({id:r})=>r!==o.id)}),console.log(`
89
89
  ${p.info(o.name)} has been removed from your selected projects.
90
90
  We saved your updated configuration to: ${p.info(u.PROJECT_CONFIG_FILE)}
91
- `))}r(Kn,"removeProject");var No=Kn;var Pt=l(require("fs")),Ro=require("@babel/parser"),_o=l(require("@babel/traverse")),A=l(require("@babel/types")),Mo=require("@babel/core");async function ts(t,e,o){let n=await new Promise((a,c)=>Pt.default.readFile(t,"utf-8",(m,g)=>{m?c(m):a(g)})),s=(0,Ro.parse)(n,{sourceType:"module",plugins:["jsx","typescript"]});(0,_o.default)(s,{JSXText(a){let{searchString:c,replaceWith:m}=e,g=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(g,"gi").test(a.node.value)){if(o.lineNumbers&&a.node.loc&&!o.lineNumbers.includes(a.node.loc.start.line))return;let d=es(a.node.value,g),S=[];d.forEach(x=>{if(x.toLowerCase()===c.toLowerCase()){let w=A.jsxIdentifier("DittoComponent"),_=A.jsxAttribute(A.jsxIdentifier("componentId"),A.stringLiteral(m)),P=A.jsxOpeningElement(w,[_],!0),M=A.jsxElement(P,void 0,[],!0);S.push(M)}else S.push(A.jsxText(x))}),a.replaceWithMultiple(S)}}});let{code:i}=(0,Mo.transformFromAst)(s,n,{configFile:!1});await new Promise((a,c)=>Pt.default.writeFile(t,i,m=>{m?c(m):a(null)}))}r(ts,"replaceJSXTextInFile");function es(t,e){return t.split(new RegExp(`(${e})`,"gi")).filter(o=>o!=="")}r(es,"splitByCaseInsensitive");function $o(t,e){let o,n,s;try{let i=os(t);o=i.filePath,n=i.searchString,s=i.replaceWith}catch(i){console.error(i),console.error("Usage for replace: ditto-cli replace <file path> <search string> <replace with>");return}ts(o,{searchString:n,replaceWith:s},e)}r($o,"replace");function os(t){if(t.length!==3)throw new Error("The options array must contain <file path> <search string> <replace with>.");let e=t[0];if(!(Pt.default.existsSync(e)&&Pt.default.lstatSync(e).isFile()))throw new Error(`${e} is not a valid file path.`);return{filePath:e,searchString:t[1],replaceWith:t[2]}}r(os,"parseOptions");var Jo=l(require("fs")),Vo=l(require("glob")),Yo=require("@babel/parser"),Bo=l(require("@babel/traverse"));async function Lo(t={}){let e=j();if(t.componentFolder)try{let{data:o}=await e.get(`/v1/component-folders/${t.componentFolder}/components`,{});return o}catch{return console.log(`Failed to get components for ${t.componentFolder}. Please verify the folder's API ID.`),{}}else{let{data:o}=await e.get("/v1/components?format=structured",{});return o}}r(Lo,"fetchComponents");async function qo(t){let e=await Lo({...t.componentFolder?{componentFolder:t.componentFolder}:{}}),o=t.directory||".",n=await rs({directory:o,files:t.files,components:e});console.log(JSON.stringify(n,null,2))}r(qo,"generateSuggestions");async function rs(t){let e={},o=t.files||Vo.default.sync(`${t.directory}/**/*.+(jsx|tsx)`,{ignore:"**/node_modules/**"}),n=[];async function s(i){let a=await new Promise((m,g)=>Jo.default.readFile(i,"utf-8",(f,d)=>{f?g(f):m(d)})),c=(0,Yo.parse)(a,{sourceType:"module",plugins:["jsx","typescript"]});(0,Bo.default)(c,{JSXText(m){for(let[g,f]of Object.entries(t.components)){if(e[g]||(e[g]={apiId:g,...f,occurrences:{}}),!/^\s*$/.test(m.node.value)&&!/^\s*$/.test(f.text)&&m.node.value.includes(f.text)){let d=f.text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),S=new RegExp(d,"g"),x;for(;(x=S.exec(m.node.value))!==null;){let w=m.node.value.slice(0,x.index).split(`
92
- `);if(!m.node.loc)continue;let _=m.node.loc.start.line+w.length-1,M=a.split(`
93
- `)[_-1],I=ns(M,x.index,f.text,`${f.text}`);e[g].occurrences[i]||(e[g].occurrences[i]=[]),e[g].occurrences[i].push({lineNumber:_,preview:I})}}Object.keys(e[g].occurrences).length===0&&delete e[g]}}})}r(s,"handleFile");for(let i of o)n.push(s(i));return await Promise.all(n),e}r(rs,"findComponentsInJSXFiles");function ns(t,e,o,n){return t.substring(0,e)+t.substring(e,t.length).replace(o,n)}r(ns,"replaceAt");var ss=r(t=>{let e={};return Array.isArray(t)&&t.forEach(o=>{let[n,s]=o.split(":");e[n]=s}),e},"processMetaOption"),Go=ss;var Uo=l(require("form-data")),he=l(require("fs"));async function zo(t,e){let o=j();if(!he.default.existsSync(t))return console.error("Failed to import file: couldn't find file at path "+t),{componentsInserted:0,firstImportedId:"null"};let n=new Uo.default;n.append("import",he.default.createReadStream(t));let s={method:"POST",url:"/v1/components/file",params:{...e.csvColumnMapping?.name?{name:`[${e.csvColumnMapping.name}]`}:{},...e.csvColumnMapping?.text?{text:e.csvColumnMapping.text}:{},...e.csvColumnMapping?.notes?{notes:e.csvColumnMapping.notes}:{},...e.csvColumnMapping?.status?{status:e.csvColumnMapping.status}:{},...e.csvColumnMapping?.tags?{tags:e.csvColumnMapping.tags}:{},...e.csvColumnMapping?.componentId?{componentId:e.csvColumnMapping.componentId}:{}},headers:{"content-type":"multipart/form-data"},data:n};try{let{data:i}=await o(s);return i}catch(i){return console.error("Failed to import file."),console.error(i.response?.data?.message||i.message),{componentsInserted:0,firstImportedId:"null"}}}r(zo,"importComponents");async function Wo(t,e){if(t.endsWith(".csv")&&(!e.csvColumnMapping?.name||!e.csvColumnMapping?.text))throw new Error(".csv files require the --component-name and --text flags.");let o=await zo(t,e);console.log(JSON.stringify(o))}r(Wo,"importComponents");async function Zo(t){let e=await Zt(t);console.log(JSON.stringify(e))}r(Zo,"showComponentFolders");var is=["pull","none","project","project add","project remove"],as=[{name:"pull",description:"Sync copy from Ditto into the current working directory",flags:{"--sample-data":{description:"Include sample data. Currently only supports variants."}}},{name:"project",description:"Add a Ditto project to sync copy from",commands:[{name:"add",description:"Add a Ditto project to sync copy from"},{name:"remove",description:"Stop syncing copy from a Ditto project"}]},{name:"component-folders",description:"List component folders in your workspace. More information about component folders can be found here: https://www.dittowords.com/docs/component-folders.",flags:{"-s, --sample-data":{description:"Includes the sample components folder in the output"}}},{name:"generate-suggestions",description:"Find text that can be potentially replaced with Ditto text",flags:{"-d, --directory [value]":{description:"Directory to search for text"},"-f, --files [value]":{description:"Files to search for text (will override -d)",processor:r(t=>t.split(","),"processor")},"-cf, --component-folder [value]":{description:"Component folder to search for matches"}}},{name:"replace",description:"Find and replace Ditto text with code",flags:{"-ln, --line-numbers [value]":{description:"Only replace text on a specific line number",processor:r(t=>t.split(",").map(Number),"processor")}}},{name:"import-components",description:"Import components via a file. For more information please see: https://www.dittowords.com/docs/importing-string-files.",flags:{"-t, --text [value]":{description:"Text column index (.csv format only)"},"-n, --component-name [value]":{description:"Name column indexes (comma separated) (.csv format only)"},"-no, --notes [value]":{description:"Notes column index (.csv format only)"},"-t, --tags [value]":{description:"Tags column index (.csv format only)"},"-s, --status [value]":{description:"Status column index (.csv format only)"},"-c, --component-id [value]":{description:"Component ID column index (.csv format only)"}}}],cs=r(()=>{U.program.name("ditto-cli"),as.forEach(t=>{let e=U.program.command(t.name).description(t.description).action(o=>ye(t.name,o));t.flags&&Object.entries(t.flags).forEach(([o,{description:n,processor:s}])=>{s?e.option(o,n,s):e.option(o,n)}),"commands"in t&&t.commands&&t.commands.forEach(o=>{e.command(o.name).description(o.description).action((n,s)=>{if(t.name==="project"){let i=`${t.name} ${o.name}`;return ye(i,s)}})})})},"setupCommands"),ps=r(()=>{U.program.option("-l, --legacy","Run in legacy mode"),U.program.option("-m, --meta <data...>","Include arbitrary data in requests to the Ditto API. Ex: -m githubActionRequest:true trigger:manual"),U.program.version(it,"-v, --version","Output the current version")},"setupOptions"),ye=r(async(t,e)=>{let o=is.includes(t)&&yo();if(o)try{await xo()}catch{await b("Exiting Ditto CLI...");return}let{meta:n}=U.program.opts();switch(t){case"none":case"pull":return ge({meta:Go(n),includeSampleData:e.sampleData||!1});case"project":case"project add":return o?void 0:Ao();case"project remove":return No();case"component-folders":return Zo({showSampleData:e.sampleData});case"generate-suggestions":return qo({directory:e.directory,files:e.files,componentFolder:e.componentFolder});case"replace":return $o(e.args,{...e?.lineNumbers?{lineNumbers:e.lineNumbers}:{}});case"import-components":{if(e.args.length===0){console.info("Please provide a file path.");return}return Wo(e.args[0],{csvColumnMapping:{name:e.componentName,text:e.text,notes:e.notes,tags:e.tags,status:e.status,componentId:e.componentId}})}default:{await b("Exiting Ditto CLI...");return}}},"executeCommand"),ls=r(async()=>{if(cs(),ps(),process.argv.length<=2&&process.argv[1].includes("ditto-cli")){await ye("none",[]);return}U.program.parse(process.argv)},"legacyAppEntry"),Ho=ls;var br=l(require("@sentry/node")),Ct=require("commander");var ir=require("os"),ft=l(require("path")),ar=l(require("crypto"));var rr=require("zod"),nr=l(require("fs"));var ut=l(require("path")),z=l(require("fs")),xe=l(require("fs/promises"));function Et(t,e=""){let o=ut.default.dirname(t);return z.default.existsSync(o)||z.default.mkdirSync(o),z.default.existsSync(t)?!1:(ms(t,e),!0)}r(Et,"createFileIfMissingSync");function ms(t,e){z.default.existsSync(ut.default.dirname(t))||z.default.mkdirSync(ut.default.dirname(t),{recursive:!0}),z.default.writeFileSync(t,e,"utf-8")}r(ms,"writeFileSync");async function Xo(t,e){z.default.existsSync(ut.default.dirname(t))||await xe.default.mkdir(ut.default.dirname(t),{recursive:!0}),await xe.default.writeFile(t,e,"utf-8")}r(Xo,"writeFile");var Qo=r(t=>t+(/[\r\n]$/.test(t)?"":`
94
- `),"ensureEndsWithNewLine");var Ie=l(require("js-yaml"));var F=require("zod"),Qt=F.z.object({projects:F.z.array(F.z.object({id:F.z.string()})).optional(),components:F.z.object({folders:F.z.array(F.z.object({id:F.z.string(),excludeNestedFolders:F.z.boolean().optional()})).optional()}).optional(),variants:F.z.array(F.z.object({id:F.z.string()})).optional(),outDir:F.z.string().optional(),richText:F.z.union([F.z.literal("html"),F.z.literal(!1)]).optional()});var tr=require("zod");var J=require("zod");var Te=Qt.extend({format:J.z.literal("json"),framework:J.z.undefined()}).strict(),us=Te.extend({framework:J.z.literal("i18next"),type:J.z.literal("module").or(J.z.literal("commonjs")).optional()}).strict(),fs=Te.extend({framework:J.z.literal("vue-i18n"),type:J.z.literal("module").or(J.z.literal("commonjs")).optional()}).strict(),Ko=J.z.discriminatedUnion("framework",[Te,us,fs]);var er=tr.z.union([...Ko.options]);var Ce=class Ce extends Error{constructor({type:e,message:o,exitCode:n,data:s}){let i=o||"Something went wrong. Please contact support or try again later.";super(i),this.exitCode=n,this.type=e,this.data=s}};r(Ce,"DittoError");var Q=Ce;function or(t){return t instanceof Q}r(or,"isDittoError");function Se(t,e){return t.type===e}r(Se,"isDittoErrorType");var gs=Qt.extend({outputs:rr.z.array(er)}).strict(),we={projects:[],variants:[],components:{folders:[]},outputs:[{format:"json",framework:"i18next"}]};async function sr(t){let e=hs(t.config);y.setProjectConfig(e)}r(sr,"initProjectConfig");function hs(t=y.projectConfigFile,e=we){let o=e;try{Et(t,Ie.default.dump(e));let s=nr.default.readFileSync(t,"utf8");o=Ie.default.load(s)}catch(s){throw new Q({type:"ConfigYamlLoadError",data:{rawErrorMessage:s.message},message:"Could not load the project config file. Please check the file path and that it is a valid YAML file."})}let n=gs.safeParse(o);if(!n.success)throw new Q({type:"ConfigParseError",data:{formattedError:JSON.stringify(n.error.flatten(),null,2),messagePrefix:"There is an error in your project config file."}});return n.data}r(hs,"readProjectConfigData");var dt,W,kt,Dt,gt,At,K,Nt,je=class je{constructor(){V(this,dt);V(this,W);V(this,kt);V(this,Dt);V(this,gt);V(this,At);V(this,K);V(this,Nt);R(this,dt,process.env.DITTO_API_HOST||"https://api.dittowords.com"),R(this,W,process.env.DITTO_TOKEN),R(this,kt,process.env.DITTO_CONFIG_FILE||ft.default.join((0,ir.homedir)(),".config","ditto")),R(this,gt,process.env.DITTO_PROJECT_CONFIG_FILE||ft.default.normalize(ft.default.join("ditto","config.yml"))),R(this,Dt,ft.default.normalize(ft.default.dirname(D(this,gt)))),R(this,At,ar.default.randomUUID()),R(this,K,we),R(this,Nt,process.env.DITTO_OUT_DIR||this.projectConfigDir)}get apiHost(){return D(this,dt)}set apiHost(e){R(this,dt,e)}get apiToken(){return D(this,W)}get apiTokenOrThrow(){if(!D(this,W))throw new Error("No API Token found.");return D(this,W)}get configFile(){return D(this,kt)}get projectConfigFile(){return D(this,gt)}get clientId(){return D(this,At)}setApiToken(e){R(this,W,e)}get projectConfig(){return D(this,K)}setProjectConfig(e){R(this,K,e)}get selectedProjectConfigOutputs(){return D(this,K).outputs}get projectConfigDir(){return D(this,Dt)}get outDir(){return this.projectConfig.outDir||D(this,Nt)}};dt=new WeakMap,W=new WeakMap,kt=new WeakMap,Dt=new WeakMap,gt=new WeakMap,At=new WeakMap,K=new WeakMap,Nt=new WeakMap,r(je,"AppContext");var ve=je,ys=new ve,y=ys;var cr=l(require("axios"));function be(t){return function(e){return e.baseURL=y.apiHost,e.headers["x-ditto-client-id"]=y.clientId,e.headers["x-ditto-app"]="cli",e.headers.Authorization=t||y.apiToken,e}}r(be,"defaultInterceptor");var pr=cr.default.create({});pr.interceptors.request.use(be());var ht=pr;var dr=require("axios");var O=require("zod");var lr=O.z.object({id:O.z.string(),text:O.z.string(),richText:O.z.string().optional(),status:O.z.string(),notes:O.z.string(),tags:O.z.array(O.z.string()),variableIds:O.z.array(O.z.string()),variantId:O.z.string().nullable()}),xs=lr.extend({projectId:O.z.string()});function mr(t){return"projectId"in t}r(mr,"isTextItem");var ur=O.z.array(xs),Ts=lr.extend({folderId:O.z.string().nullable()}),fr=O.z.array(Ts);async function Fe(t){try{let e=await ht.get("/v2/textItems",{params:t});return ur.parse(e.data)}catch(e){if(!(e instanceof dr.AxiosError))throw new Error("Sorry! We're having trouble reaching the Ditto API. Please try again later.");if(e.response?.status===400){let o="Invalid project filters";throw e.response?.data?.message&&(o=e.response.data.message),new Error(`${o}. Please check your project filters and try again.`,{cause:e.response?.data})}throw e}}r(Fe,"fetchText");var gr=require("axios");async function Oe(t){try{let e=await ht.get("/v2/components",{params:t});return fr.parse(e.data)}catch(e){if(!(e instanceof gr.AxiosError))throw new Error("Sorry! We're having trouble reaching the Ditto API. Please try again later.");if(e.response?.status===400){let o="Invalid component filters";throw e.response?.data?.message&&(o=e.response.data.message),new Error(`${o}. Please check your component filters and try again.`,{cause:e.response?.data})}throw e}}r(Oe,"fetchComponents");var hr=require("axios"),h=require("zod");var Rt=h.z.object({id:h.z.string(),name:h.z.string()}),Ss=Rt.merge(h.z.object({type:h.z.literal("number"),data:h.z.object({example:h.z.union([h.z.number(),h.z.string()]),fallback:h.z.union([h.z.number(),h.z.string()]).optional()})})),Cs=Rt.merge(h.z.object({type:h.z.literal("string"),data:h.z.object({example:h.z.string(),fallback:h.z.string().optional()})})),Is=Rt.merge(h.z.object({type:h.z.literal("hyperlink"),data:h.z.object({text:h.z.string(),url:h.z.string()})})),ws=Rt.merge(h.z.object({type:h.z.literal("list"),data:h.z.array(h.z.string())})),vs=Rt.merge(h.z.object({type:h.z.literal("map"),data:h.z.record(h.z.string())})),js=h.z.discriminatedUnion("type",[Cs,Ss,Is,ws,vs]),bs=h.z.array(js);async function Pe(){try{let t=await ht.get("/v2/variables");return bs.parse(t.data)}catch(t){throw t instanceof hr.AxiosError?t:new Error("Sorry! We're having trouble reaching the Ditto API. Please try again later.")}}r(Pe,"fetchVariables");var B=l(require("chalk"));var Fs=r(t=>B.default.magenta(t),"errorText"),Os=r(t=>B.default.yellow(t),"warnText"),Ps=r(t=>B.default.blueBright(t),"info"),Es=r(t=>B.default.green(t),"success"),ks=r(t=>B.default.blueBright.underline(t),"url"),Ds=r(t=>B.default.grey(t),"subtle"),As=r(t=>B.default.white(t),"write"),Ns=r(t=>B.default.bold(t),"bold"),Rs=r(t=>console.log(t),"writeLine"),T={errorText:Fs,warnText:Os,info:Ps,success:Es,url:ks,subtle:Ds,write:As,writeLine:Rs,bold:Ns};var Ee=class Ee{constructor(e){this.filename=e.filename,this.path=e.path,this.extension=e.extension,this.content=e.content,this.metadata=e.metadata??{}}get fullPath(){return`${this.path}/${this.filename}.${this.extension}`}get filenameWithExtension(){return`${this.filename}.${this.extension}`}get formattedContent(){throw new Error("Not implemented")}};r(Ee,"OutputFile");var tt=Ee;var ke=class ke extends tt{constructor(e){super({filename:e.filename,path:e.path,extension:"json",content:e.content??{},metadata:e.metadata??{}})}get formattedContent(){return JSON.stringify(this.content,null,2)}};r(ke,"JSONOutputFile");var et=ke;var De=class De{constructor(e,o){this.output=e,this.projectConfig=o,this.outDir=e.outDir??y.outDir,this.outputJsonFiles={},this.variablesOutputFile=new et({filename:"variables",path:this.outDir})}async fetchAPIData(){return{}}async transformAPIData(e){return[]}async format(){let e=await this.fetchAPIData(),o=await this.transformAPIData(e);await this.writeFiles(o)}async writeFiles(e){await Promise.all(e.map(o=>Xo(o.fullPath,o.formattedContent).then(()=>{T.writeLine(`Successfully saved to ${T.info(o.fullPath)}`)})))}};r(De,"BaseFormatter");var _t=De;function yt(t,...e){if(e.length>5)throw new Error("Maximum of 5 mixins supported");return e.reduce((o,n)=>n(o),t)}r(yt,"applyMixins");var Ae=class Ae extends tt{constructor(o){super({filename:o.filename,path:o.path,extension:"js",content:o.content??"",metadata:o.metadata??{}});this.indentSpaces=2}get formattedContent(){return Qo(this.content??"")}};r(Ae,"JavascriptOutputFile");var ot=Ae;function Mt(t){var e;return e=class extends t{constructor(){super(...arguments);this.indentSpaces=2}sanitizeStringForJSVariableName(s){return s.replace(/[^a-zA-Z0-9]/g,"_")}formatNamedModules(s){return s.map(i=>i.alias?`${i.name} as ${i.alias}`:i.name).sort().join(", ")}codegenNamedImport(s,i){return`import { ${this.formatNamedModules(s)} } from "${i}";
91
+ `))}n(Kn,"removeProject");var Do=Kn;var Et=m(require("fs")),Ao=require("@babel/parser"),No=m(require("@babel/traverse")),N=m(require("@babel/types")),Mo=require("@babel/core");async function ts(t,e,o){let r=await new Promise((a,c)=>Et.default.readFile(t,"utf-8",(l,g)=>{l?c(l):a(g)})),s=(0,Ao.parse)(r,{sourceType:"module",plugins:["jsx","typescript"]});(0,No.default)(s,{JSXText(a){let{searchString:c,replaceWith:l}=e,g=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(g,"gi").test(a.node.value)){if(o.lineNumbers&&a.node.loc&&!o.lineNumbers.includes(a.node.loc.start.line))return;let d=es(a.node.value,g),C=[];d.forEach(x=>{if(x.toLowerCase()===c.toLowerCase()){let v=N.jsxIdentifier("DittoComponent"),R=N.jsxAttribute(N.jsxIdentifier("componentId"),N.stringLiteral(l)),P=N.jsxOpeningElement(v,[R],!0),_=N.jsxElement(P,void 0,[],!0);C.push(_)}else C.push(N.jsxText(x))}),a.replaceWithMultiple(C)}}});let{code:i}=(0,Mo.transformFromAst)(s,r,{configFile:!1});await new Promise((a,c)=>Et.default.writeFile(t,i,l=>{l?c(l):a(null)}))}n(ts,"replaceJSXTextInFile");function es(t,e){return t.split(new RegExp(`(${e})`,"gi")).filter(o=>o!=="")}n(es,"splitByCaseInsensitive");function Ro(t,e){let o,r,s;try{let i=os(t);o=i.filePath,r=i.searchString,s=i.replaceWith}catch(i){console.error(i),console.error("Usage for replace: ditto-cli replace <file path> <search string> <replace with>");return}ts(o,{searchString:r,replaceWith:s},e)}n(Ro,"replace");function os(t){if(t.length!==3)throw new Error("The options array must contain <file path> <search string> <replace with>.");let e=t[0];if(!(Et.default.existsSync(e)&&Et.default.lstatSync(e).isFile()))throw new Error(`${e} is not a valid file path.`);return{filePath:e,searchString:t[1],replaceWith:t[2]}}n(os,"parseOptions");var $o=m(require("fs")),Lo=m(require("glob")),Jo=require("@babel/parser"),Vo=m(require("@babel/traverse"));async function _o(t={}){let e=j();if(t.componentFolder)try{let{data:o}=await e.get(`/v1/component-folders/${t.componentFolder}/components`,{});return o}catch{return console.log(`Failed to get components for ${t.componentFolder}. Please verify the folder's API ID.`),{}}else{let{data:o}=await e.get("/v1/components?format=structured",{});return o}}n(_o,"fetchComponents");async function Yo(t){let e=await _o({...t.componentFolder?{componentFolder:t.componentFolder}:{}}),o=t.directory||".",r=await rs({directory:o,files:t.files,components:e});console.log(JSON.stringify(r,null,2))}n(Yo,"generateSuggestions");async function rs(t){let e={},o=t.files||Lo.default.sync(`${t.directory}/**/*.+(jsx|tsx)`,{ignore:"**/node_modules/**"}),r=[];async function s(i){let a=await new Promise((l,g)=>$o.default.readFile(i,"utf-8",(f,d)=>{f?g(f):l(d)})),c=(0,Jo.parse)(a,{sourceType:"module",plugins:["jsx","typescript"]});(0,Vo.default)(c,{JSXText(l){for(let[g,f]of Object.entries(t.components)){if(e[g]||(e[g]={apiId:g,...f,occurrences:{}}),!/^\s*$/.test(l.node.value)&&!/^\s*$/.test(f.text)&&l.node.value.includes(f.text)){let d=f.text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),C=new RegExp(d,"g"),x;for(;(x=C.exec(l.node.value))!==null;){let v=l.node.value.slice(0,x.index).split(`
92
+ `);if(!l.node.loc)continue;let R=l.node.loc.start.line+v.length-1,_=a.split(`
93
+ `)[R-1],I=ns(_,x.index,f.text,`${f.text}`);e[g].occurrences[i]||(e[g].occurrences[i]=[]),e[g].occurrences[i].push({lineNumber:R,preview:I})}}Object.keys(e[g].occurrences).length===0&&delete e[g]}}})}n(s,"handleFile");for(let i of o)r.push(s(i));return await Promise.all(r),e}n(rs,"findComponentsInJSXFiles");function ns(t,e,o,r){return t.substring(0,e)+t.substring(e,t.length).replace(o,r)}n(ns,"replaceAt");var ss=n(t=>{let e={};return Array.isArray(t)&&t.forEach(o=>{let[r,s]=o.split(":");e[r]=s}),e},"processMetaOption"),Bo=ss;var qo=m(require("form-data")),ge=m(require("fs"));async function Go(t,e){let o=j();if(!ge.default.existsSync(t))return console.error("Failed to import file: couldn't find file at path "+t),{componentsInserted:0,firstImportedId:"null"};let r=new qo.default;r.append("import",ge.default.createReadStream(t));let s={method:"POST",url:"/v1/components/file",params:{...e.csvColumnMapping?.name?{name:`[${e.csvColumnMapping.name}]`}:{},...e.csvColumnMapping?.text?{text:e.csvColumnMapping.text}:{},...e.csvColumnMapping?.notes?{notes:e.csvColumnMapping.notes}:{},...e.csvColumnMapping?.status?{status:e.csvColumnMapping.status}:{},...e.csvColumnMapping?.tags?{tags:e.csvColumnMapping.tags}:{},...e.csvColumnMapping?.componentId?{componentId:e.csvColumnMapping.componentId}:{}},headers:{"content-type":"multipart/form-data"},data:r};try{let{data:i}=await o(s);return i}catch(i){return console.error("Failed to import file."),console.error(i.response?.data?.message||i.message),{componentsInserted:0,firstImportedId:"null"}}}n(Go,"importComponents");async function Uo(t,e){if(t.endsWith(".csv")&&(!e.csvColumnMapping?.name||!e.csvColumnMapping?.text))throw new Error(".csv files require the --component-name and --text flags.");let o=await Go(t,e);console.log(JSON.stringify(o))}n(Uo,"importComponents");async function zo(t){let e=await Wt(t);console.log(JSON.stringify(e))}n(zo,"showComponentFolders");var is=["pull","none","project","project add","project remove"],as=[{name:"pull",description:"Sync copy from Ditto into the current working directory",flags:{"--sample-data":{description:"Include sample data. Currently only supports variants."}}},{name:"project",description:"Add a Ditto project to sync copy from",commands:[{name:"add",description:"Add a Ditto project to sync copy from"},{name:"remove",description:"Stop syncing copy from a Ditto project"}]},{name:"component-folders",description:"List component folders in your workspace. More information about component folders can be found here: https://www.dittowords.com/docs/component-folders.",flags:{"-s, --sample-data":{description:"Includes the sample components folder in the output"}}},{name:"generate-suggestions",description:"Find text that can be potentially replaced with Ditto text",flags:{"-d, --directory [value]":{description:"Directory to search for text"},"-f, --files [value]":{description:"Files to search for text (will override -d)",processor:n(t=>t.split(","),"processor")},"-cf, --component-folder [value]":{description:"Component folder to search for matches"}}},{name:"replace",description:"Find and replace Ditto text with code",flags:{"-ln, --line-numbers [value]":{description:"Only replace text on a specific line number",processor:n(t=>t.split(",").map(Number),"processor")}}},{name:"import-components",description:"Import components via a file. For more information please see: https://www.dittowords.com/docs/importing-string-files.",flags:{"-t, --text [value]":{description:"Text column index (.csv format only)"},"-n, --component-name [value]":{description:"Name column indexes (comma separated) (.csv format only)"},"-no, --notes [value]":{description:"Notes column index (.csv format only)"},"-t, --tags [value]":{description:"Tags column index (.csv format only)"},"-s, --status [value]":{description:"Status column index (.csv format only)"},"-c, --component-id [value]":{description:"Component ID column index (.csv format only)"}}}],cs=n(()=>{U.program.name("ditto-cli"),as.forEach(t=>{let e=U.program.command(t.name).description(t.description).action(o=>he(t.name,o));t.flags&&Object.entries(t.flags).forEach(([o,{description:r,processor:s}])=>{s?e.option(o,r,s):e.option(o,r)}),"commands"in t&&t.commands&&t.commands.forEach(o=>{e.command(o.name).description(o.description).action((r,s)=>{if(t.name==="project"){let i=`${t.name} ${o.name}`;return he(i,s)}})})})},"setupCommands"),ps=n(()=>{U.program.option("-l, --legacy","Run in legacy mode"),U.program.option("-m, --meta <data...>","Include arbitrary data in requests to the Ditto API. Ex: -m githubActionRequest:true trigger:manual"),U.program.version(ct,"-v, --version","Output the current version")},"setupOptions"),he=n(async(t,e)=>{let o=is.includes(t)&&go();if(o)try{await ho()}catch{await b("Exiting Ditto CLI...");return}let{meta:r}=U.program.opts();switch(t){case"none":case"pull":return de({meta:Bo(r),includeSampleData:e.sampleData||!1});case"project":case"project add":return o?void 0:ko();case"project remove":return Do();case"component-folders":return zo({showSampleData:e.sampleData});case"generate-suggestions":return Yo({directory:e.directory,files:e.files,componentFolder:e.componentFolder});case"replace":return Ro(e.args,{...e?.lineNumbers?{lineNumbers:e.lineNumbers}:{}});case"import-components":{if(e.args.length===0){console.info("Please provide a file path.");return}return Uo(e.args[0],{csvColumnMapping:{name:e.componentName,text:e.text,notes:e.notes,tags:e.tags,status:e.status,componentId:e.componentId}})}default:{await b("Exiting Ditto CLI...");return}}},"executeCommand"),ms=n(async()=>{if(cs(),ps(),process.argv.length<=2&&process.argv[1].includes("ditto-cli")){await he("none",[]);return}U.program.parse(process.argv)},"legacyAppEntry"),Zo=ms;var Fr=m(require("@sentry/node")),H=require("commander");var pr=require("os"),gt=m(require("path")),mr=m(require("crypto"));var ir=require("zod"),ar=m(require("fs"));var dt=m(require("path")),z=m(require("fs")),ye=m(require("fs/promises"));function kt(t,e=""){let o=dt.default.dirname(t);return z.default.existsSync(o)||z.default.mkdirSync(o),z.default.existsSync(t)?!1:(ls(t,e),!0)}n(kt,"createFileIfMissingSync");function ls(t,e){z.default.existsSync(dt.default.dirname(t))||z.default.mkdirSync(dt.default.dirname(t),{recursive:!0}),z.default.writeFileSync(t,e,"utf-8")}n(ls,"writeFileSync");async function Wo(t,e){z.default.existsSync(dt.default.dirname(t))||await ye.default.mkdir(dt.default.dirname(t),{recursive:!0}),await ye.default.writeFile(t,e,"utf-8")}n(Wo,"writeFile");var Ho=n(t=>t+(/[\r\n]$/.test(t)?"":`
94
+ `),"ensureEndsWithNewLine");var Se=m(require("js-yaml"));var F=require("zod");var O=require("zod");var Xo=O.z.enum(["NONE","WIP","REVIEW","FINAL"]),Qo=O.z.object({id:O.z.string(),text:O.z.string(),richText:O.z.string().optional(),status:O.z.string(),notes:O.z.string(),tags:O.z.array(O.z.string()),variableIds:O.z.array(O.z.string()),variantId:O.z.string().nullable()}),us=Qo.extend({projectId:O.z.string()});function Ko(t){return"projectId"in t}n(Ko,"isTextItem");var tr=O.z.array(us),fs=Qo.extend({folderId:O.z.string().nullable()}),er=O.z.array(fs);var Qt=F.z.object({projects:F.z.array(F.z.object({id:F.z.string()})).optional(),components:F.z.object({folders:F.z.array(F.z.object({id:F.z.string(),excludeNestedFolders:F.z.boolean().optional()})).optional()}).optional(),statuses:F.z.array(Xo).optional(),variants:F.z.array(F.z.object({id:F.z.string()})).optional(),outDir:F.z.string().optional(),richText:F.z.union([F.z.literal("html"),F.z.literal(!1)]).optional()});var rr=require("zod");var J=require("zod");var xe=Qt.extend({format:J.z.literal("json"),framework:J.z.undefined()}).strict(),ds=xe.extend({framework:J.z.literal("i18next"),type:J.z.literal("module").or(J.z.literal("commonjs")).optional()}).strict(),gs=xe.extend({framework:J.z.literal("vue-i18n"),type:J.z.literal("module").or(J.z.literal("commonjs")).optional()}).strict(),or=J.z.discriminatedUnion("framework",[xe,ds,gs]);var nr=rr.z.union([...or.options]);var Ce=class Ce extends Error{constructor({type:e,message:o,exitCode:r,data:s}){let i=o||"Something went wrong. Please contact support or try again later.";super(i),this.exitCode=r,this.type=e,this.data=s}};n(Ce,"DittoError");var tt=Ce;function sr(t){return t instanceof tt}n(sr,"isDittoError");function Te(t,e){return t.type===e}n(Te,"isDittoErrorType");var ys=Qt.extend({outputs:ir.z.array(nr)}).strict(),Ie={projects:[],variants:[],statuses:[],components:{folders:[]},outputs:[{format:"json",framework:"i18next"}]};async function cr(t){let e=xs(t.config);y.setProjectConfig(e)}n(cr,"initProjectConfig");function xs(t=y.projectConfigFile,e=Ie){let o=e;try{kt(t,Se.default.dump(e));let s=ar.default.readFileSync(t,"utf8");o=Se.default.load(s)}catch(s){throw new tt({type:"ConfigYamlLoadError",data:{rawErrorMessage:s.message},message:"Could not load the project config file. Please check the file path and that it is a valid YAML file."})}let r=ys.safeParse(o);if(!r.success)throw new tt({type:"ConfigParseError",data:{formattedError:JSON.stringify(r.error.flatten(),null,2),messagePrefix:"There is an error in your project config file."}});return r.data}n(xs,"readProjectConfigData");var ht,Z,Dt,At,yt,xt,et,Nt,we=class we{constructor(){V(this,ht);V(this,Z);V(this,Dt);V(this,At);V(this,yt);V(this,xt);V(this,et);V(this,Nt);A(this,ht,process.env.DITTO_API_HOST||"https://api.dittowords.com"),A(this,Z,process.env.DITTO_TOKEN),A(this,Dt,process.env.DITTO_CONFIG_FILE||gt.default.join((0,pr.homedir)(),".config","ditto")),A(this,yt,process.env.DITTO_PROJECT_CONFIG_FILE||gt.default.normalize(gt.default.join("ditto","config.yml"))),A(this,At,gt.default.normalize(gt.default.dirname(D(this,yt)))),A(this,xt,mr.default.randomUUID()),A(this,et,Ie),A(this,Nt,process.env.DITTO_OUT_DIR||this.projectConfigDir)}get apiHost(){return D(this,ht)}set apiHost(e){A(this,ht,e)}get apiToken(){return D(this,Z)}get apiTokenOrThrow(){if(!D(this,Z))throw new Error("No API Token found.");return D(this,Z)}get configFile(){return D(this,Dt)}get projectConfigFile(){return D(this,yt)}get clientId(){return D(this,xt)}setClientId(e){A(this,xt,e)}setApiToken(e){A(this,Z,e)}get projectConfig(){return D(this,et)}setProjectConfig(e){A(this,et,e)}get selectedProjectConfigOutputs(){return D(this,et).outputs}get projectConfigDir(){return D(this,At)}get outDir(){return this.projectConfig.outDir||D(this,Nt)}};ht=new WeakMap,Z=new WeakMap,Dt=new WeakMap,At=new WeakMap,yt=new WeakMap,xt=new WeakMap,et=new WeakMap,Nt=new WeakMap,n(we,"AppContext");var ve=we,Ts=new ve,y=Ts;var ur=require("axios");var lr=m(require("axios"));function Cs({token:t,meta:e}={}){return function(o){return o.baseURL=y.apiHost,o.headers["x-ditto-client-id"]=y.clientId,o.headers["x-ditto-app"]=e?.githubActionRequest==="true"?"github_action":"cli",o.headers.Authorization=t||y.apiToken,o}}n(Cs,"defaultInterceptor");var Ss=n(t=>{let e=lr.default.create({});return e.interceptors.request.use(Cs(t)),e},"getHttpClient"),W=Ss;async function je(t,e){try{let r=await W({meta:e}).get("/v2/textItems",{params:t});return tr.parse(r.data)}catch(o){if(!(o instanceof ur.AxiosError))throw new Error("Sorry! We're having trouble reaching the Ditto API. Please try again later.");if(o.response?.status===400){let r="Invalid project filters";throw o.response?.data?.message&&(r=o.response.data.message),new Error(`${r}. Please check your project filters and try again.`,{cause:o.response?.data})}throw o}}n(je,"fetchText");var fr=require("axios");async function Fe(t,e){try{let r=await W({meta:e}).get("/v2/components",{params:t});return er.parse(r.data)}catch(o){if(!(o instanceof fr.AxiosError))throw new Error("Sorry! We're having trouble reaching the Ditto API. Please try again later.");if(o.response?.status===400){let r="Invalid component filters";throw o.response?.data?.message&&(r=o.response.data.message),new Error(`${r}. Please check your component filters and try again.`,{cause:o.response?.data})}throw o}}n(Fe,"fetchComponents");var dr=require("axios"),h=require("zod");var Mt=h.z.object({id:h.z.string(),name:h.z.string()}),Is=Mt.merge(h.z.object({type:h.z.literal("number"),data:h.z.object({example:h.z.union([h.z.number(),h.z.string()]),fallback:h.z.union([h.z.number(),h.z.string()]).optional()})})),vs=Mt.merge(h.z.object({type:h.z.literal("string"),data:h.z.object({example:h.z.string(),fallback:h.z.string().optional()})})),ws=Mt.merge(h.z.object({type:h.z.literal("hyperlink"),data:h.z.object({text:h.z.string(),url:h.z.string()})})),js=Mt.merge(h.z.object({type:h.z.literal("list"),data:h.z.array(h.z.string())})),Fs=Mt.merge(h.z.object({type:h.z.literal("map"),data:h.z.record(h.z.string())})),bs=h.z.discriminatedUnion("type",[vs,Is,ws,js,Fs]),Os=h.z.array(bs);async function be(t){try{let o=await W({meta:t}).get("/v2/variables");return Os.parse(o.data)}catch(e){throw e instanceof dr.AxiosError?e:new Error("Sorry! We're having trouble reaching the Ditto API. Please try again later.")}}n(be,"fetchVariables");var B=m(require("chalk"));var Ps=n(t=>B.default.magenta(t),"errorText"),Es=n(t=>B.default.yellow(t),"warnText"),ks=n(t=>B.default.blueBright(t),"info"),Ds=n(t=>B.default.green(t),"success"),As=n(t=>B.default.blueBright.underline(t),"url"),Ns=n(t=>B.default.grey(t),"subtle"),Ms=n(t=>B.default.white(t),"write"),Rs=n(t=>B.default.bold(t),"bold"),_s=n(t=>console.log(t),"writeLine"),T={errorText:Ps,warnText:Es,info:ks,success:Ds,url:As,subtle:Ns,write:Ms,writeLine:_s,bold:Rs};var Oe=class Oe{constructor(e){this.filename=e.filename,this.path=e.path,this.extension=e.extension,this.content=e.content,this.metadata=e.metadata??{}}get fullPath(){return`${this.path}/${this.filename}.${this.extension}`}get filenameWithExtension(){return`${this.filename}.${this.extension}`}get formattedContent(){throw new Error("Not implemented")}};n(Oe,"OutputFile");var ot=Oe;var Pe=class Pe extends ot{constructor(e){super({filename:e.filename,path:e.path,extension:"json",content:e.content??{},metadata:e.metadata??{}})}get formattedContent(){return JSON.stringify(this.content,null,2)}};n(Pe,"JSONOutputFile");var rt=Pe;var Ee=class Ee{constructor(e,o,r){this.output=e,this.projectConfig=o,this.outDir=e.outDir??y.outDir,this.outputJsonFiles={},this.variablesOutputFile=new rt({filename:"variables",path:this.outDir}),this.meta=r}async fetchAPIData(){return{}}async transformAPIData(e){return[]}async format(){let e=await this.fetchAPIData(),o=await this.transformAPIData(e);await this.writeFiles(o)}async writeFiles(e){await Promise.all(e.map(o=>Wo(o.fullPath,o.formattedContent).then(()=>{T.writeLine(`Successfully saved to ${T.info(o.fullPath)}`)})))}};n(Ee,"BaseFormatter");var Rt=Ee;function Tt(t,...e){if(e.length>5)throw new Error("Maximum of 5 mixins supported");return e.reduce((o,r)=>r(o),t)}n(Tt,"applyMixins");var ke=class ke extends ot{constructor(o){super({filename:o.filename,path:o.path,extension:"js",content:o.content??"",metadata:o.metadata??{}});this.indentSpaces=2}get formattedContent(){return Ho(this.content??"")}};n(ke,"JavascriptOutputFile");var nt=ke;function _t(t){var e;return e=class extends t{constructor(){super(...arguments);this.indentSpaces=2}sanitizeStringForJSVariableName(s){return s.replace(/[^a-zA-Z0-9]/g,"_")}formatNamedModules(s){return s.map(i=>i.alias?`${i.name} as ${i.alias}`:i.name).sort().join(", ")}codegenNamedImport(s,i){return`import { ${this.formatNamedModules(s)} } from "${i}";
95
95
  `}codegenNamedRequire(s,i){return`const { ${this.formatNamedModules(s)} } = require("${i}");
96
96
  `}codegenDefaultImport(s,i){return`import ${s} from "${i}";
97
97
  `}codegenDefaultRequire(s,i){return`const ${s} = require("${i}");
98
- `}codegenDefaultExport(s){return`export default ${s};`}codegenCommonJSModuleExports(s){return`module.exports = ${s};`}codegenPad(s){return" ".repeat(s*this.indentSpaces)}},r(e,"JavascriptCodegenHelpers"),e}r(Mt,"javascriptCodegenMixin");var Ne=class Ne{constructor(e){this.output=e,this.outDir=e.outDir??y.outDir}get framework(){return this.output.framework}process(...e){throw new Error("Not implemented")}};r(Ne,"BaseFramework");var rt=Ne;var Re=class Re extends yt(rt,Mt){process(e){let o="commonjs";"type"in this.output&&this.output.type&&(o=this.output.type);let n=new ot({filename:"index",path:this.outDir}),s=Object.values(e).reduce((i,a)=>{let c=a.metadata.variantId;return i[c]??(i[c]=[]),i[c].push(a),i},{});return o==="module"?(n.content+=this.generateImportStatements(e),n.content+=`
99
- `,n.content+=this.codegenDefaultExport(this.generateExportedObjectString(s))):(n.content+=this.generateRequireStatements(e),n.content+=`
100
- `,n.content+=this.codegenCommonJSModuleExports(this.generateExportedObjectString(s))),[n]}generateImportStatements(e){let o="";for(let n of Object.values(e))o+=this.codegenDefaultImport(this.sanitizeStringForJSVariableName(n.filename),`./${n.filenameWithExtension}`);return o}generateRequireStatements(e){let o="";for(let n of Object.values(e))o+=this.codegenDefaultRequire(this.sanitizeStringForJSVariableName(n.filename),`./${n.filenameWithExtension}`);return o}generateExportedObjectString(e){let o=Object.keys(e),n=`{
101
- `;for(let s=0;s<o.length;s++){let i=o[s],a=e[i];n+=`${this.codegenPad(1)}"${i}": {
102
- `;for(let c of a)n+=`${this.codegenPad(2)}...${this.sanitizeStringForJSVariableName(c.filename)},
103
- `;n+=`${this.codegenPad(1)}}${s<o.length-1?`,
98
+ `}codegenDefaultExport(s){return`export default ${s};`}codegenCommonJSModuleExports(s){return`module.exports = ${s};`}codegenPad(s){return" ".repeat(s*this.indentSpaces)}},n(e,"JavascriptCodegenHelpers"),e}n(_t,"javascriptCodegenMixin");var De=class De{constructor(e){this.output=e,this.outDir=e.outDir??y.outDir}get framework(){return this.output.framework}process(...e){throw new Error("Not implemented")}};n(De,"BaseFramework");var st=De;var Ae=class Ae extends Tt(st,_t){process(e){let o="commonjs";"type"in this.output&&this.output.type&&(o=this.output.type);let r=new nt({filename:"index",path:this.outDir}),s=Object.values(e).reduce((i,a)=>{let c=a.metadata.variantId;return i[c]??(i[c]=[]),i[c].push(a),i},{});return o==="module"?(r.content+=this.generateImportStatements(e),r.content+=`
99
+ `,r.content+=this.codegenDefaultExport(this.generateExportedObjectString(s))):(r.content+=this.generateRequireStatements(e),r.content+=`
100
+ `,r.content+=this.codegenCommonJSModuleExports(this.generateExportedObjectString(s))),[r]}generateImportStatements(e){let o="";for(let r of Object.values(e))o+=this.codegenDefaultImport(this.sanitizeStringForJSVariableName(r.filename),`./${r.filenameWithExtension}`);return o}generateRequireStatements(e){let o="";for(let r of Object.values(e))o+=this.codegenDefaultRequire(this.sanitizeStringForJSVariableName(r.filename),`./${r.filenameWithExtension}`);return o}generateExportedObjectString(e){let o=Object.keys(e),r=`{
101
+ `;for(let s=0;s<o.length;s++){let i=o[s],a=e[i];r+=`${this.codegenPad(1)}"${i}": {
102
+ `;for(let c of a)r+=`${this.codegenPad(2)}...${this.sanitizeStringForJSVariableName(c.filename)},
103
+ `;r+=`${this.codegenPad(1)}}${s<o.length-1?`,
104
104
  `:`
105
- `}`}return n+="}",n}};r(Re,"I18NextFramework");var $t=Re;var _e=class _e extends yt(rt,Mt){process(e){for(let i of Object.values(e))for(let a in i.content){let c=i.content[a];typeof c=="string"&&(i.content[a]=c.replaceAll(/{{/g,"{").replaceAll(/}}/g,"}"))}let o="commonjs";"type"in this.output&&this.output.type&&(o=this.output.type);let n=new ot({filename:"index",path:this.outDir}),s=Object.values(e).reduce((i,a)=>{let c=a.metadata.variantId;return i[c]??(i[c]=[]),i[c].push(a),i},{});return o==="module"?(n.content+=this.generateImportStatements(e),n.content+=`
106
- `,n.content+=this.codegenDefaultExport(this.generateExportedObjectString(s))):(n.content+=this.generateRequireStatements(e),n.content+=`
107
- `,n.content+=this.codegenCommonJSModuleExports(this.generateExportedObjectString(s))),[n]}generateImportStatements(e){let o="";for(let n of Object.values(e))o+=this.codegenDefaultImport(this.sanitizeStringForJSVariableName(n.filename),`./${n.filenameWithExtension}`);return o}generateRequireStatements(e){let o="";for(let n of Object.values(e))o+=this.codegenDefaultRequire(this.sanitizeStringForJSVariableName(n.filename),`./${n.filenameWithExtension}`);return o}generateExportedObjectString(e){let o=Object.keys(e),n=`{
108
- `;for(let s=0;s<o.length;s++){let i=o[s],a=e[i];n+=`${this.codegenPad(1)}"${i}": {
109
- `;for(let c of a)n+=`${this.codegenPad(2)}...${this.sanitizeStringForJSVariableName(c.filename)},
110
- `;n+=`${this.codegenPad(1)}}${s<o.length-1?`,
105
+ `}`}return r+="}",r}};n(Ae,"I18NextFramework");var $t=Ae;var Ne=class Ne extends Tt(st,_t){process(e){for(let i of Object.values(e))for(let a in i.content){let c=i.content[a];typeof c=="string"&&(i.content[a]=c.replaceAll(/{{/g,"{").replaceAll(/}}/g,"}"))}let o="commonjs";"type"in this.output&&this.output.type&&(o=this.output.type);let r=new nt({filename:"index",path:this.outDir}),s=Object.values(e).reduce((i,a)=>{let c=a.metadata.variantId;return i[c]??(i[c]=[]),i[c].push(a),i},{});return o==="module"?(r.content+=this.generateImportStatements(e),r.content+=`
106
+ `,r.content+=this.codegenDefaultExport(this.generateExportedObjectString(s))):(r.content+=this.generateRequireStatements(e),r.content+=`
107
+ `,r.content+=this.codegenCommonJSModuleExports(this.generateExportedObjectString(s))),[r]}generateImportStatements(e){let o="";for(let r of Object.values(e))o+=this.codegenDefaultImport(this.sanitizeStringForJSVariableName(r.filename),`./${r.filenameWithExtension}`);return o}generateRequireStatements(e){let o="";for(let r of Object.values(e))o+=this.codegenDefaultRequire(this.sanitizeStringForJSVariableName(r.filename),`./${r.filenameWithExtension}`);return o}generateExportedObjectString(e){let o=Object.keys(e),r=`{
108
+ `;for(let s=0;s<o.length;s++){let i=o[s],a=e[i];r+=`${this.codegenPad(1)}"${i}": {
109
+ `;for(let c of a)r+=`${this.codegenPad(2)}...${this.sanitizeStringForJSVariableName(c.filename)},
110
+ `;r+=`${this.codegenPad(1)}}${s<o.length-1?`,
111
111
  `:`
112
- `}`}return n+="}",n}};r(_e,"VueI18nFramework");var Lt=_e;function yr(t){if(!t.framework)throw new Error("Only call this function with a framework output");let e=t.framework;switch(e){case"i18next":return new $t(t);case"vue-i18n":return new Lt(t);default:throw new Error(`Unsupported JSON framework: ${e}`)}}r(yr,"getFrameworkProcessor");var Me=class Me extends yt(_t){async fetchAPIData(){let e=await this.fetchTextItems(),o=await this.fetchComponents(),s=(await Pe()).reduce((i,a)=>(i[a.id]=a,i),{});return{textItems:e,variablesById:s,components:o}}async transformAPIData(e){for(let n=0;n<e.textItems.length;n++){let s=e.textItems[n];this.transformAPITextEntity(s,e.variablesById)}for(let n=0;n<e.components.length;n++){let s=e.components[n];this.transformAPITextEntity(s,e.variablesById)}let o=[...Object.values(this.outputJsonFiles),this.variablesOutputFile];return this.output.framework&&o.push(...yr(this.output).process(this.outputJsonFiles)),o}transformAPITextEntity(e,o){var m;let n=mr(e)?`${e.projectId}___${e.variantId||"base"}`:`components___${e.variantId||"base"}`;(m=this.outputJsonFiles)[n]??(m[n]=new et({filename:n,path:this.outDir,metadata:{variantId:e.variantId||"base"}}));let s=this.output.richText==="html",i=this.projectConfig.richText==="html"&&this.output.richText!==!1,c=(s||i)&&e.richText?e.richText:e.text;this.outputJsonFiles[n].content[e.id]=c;for(let g of e.variableIds){let f=o[g];this.variablesOutputFile.content[g]=f.data}}generateTextItemPullFilter(){let e={projects:this.projectConfig.projects,variants:this.projectConfig.variants};return this.output.projects&&(e.projects=this.output.projects),this.output.variants&&(e.variants=this.output.variants),e}generateComponentPullFilter(){let e={...this.projectConfig.components?.folders&&{folders:this.projectConfig.components.folders},variants:this.projectConfig.variants};return this.output.components&&(e.folders=this.output.components?.folders),this.output.variants&&(e.variants=this.output.variants),e}generateQueryParams(e){let o=e==="textItem"?this.generateTextItemPullFilter():this.generateComponentPullFilter(),n={filter:JSON.stringify(o)};return this.projectConfig.richText&&(n.richText=this.projectConfig.richText),this.output.richText&&(n.richText=this.output.richText),n}async fetchTextItems(){return!this.projectConfig.projects&&!this.output.projects?[]:await Fe(this.generateQueryParams("textItem"))}async fetchComponents(){return!this.projectConfig.components&&!this.output.components?[]:await Oe(this.generateQueryParams("component"))}};r(Me,"JSONFormatter");var Jt=Me;function $e(t,e){switch(t.format){case"json":return new Jt(t,e).format();default:throw new Error(`Unsupported output format: ${t}`)}}r($e,"handleOutput");var xr=r(async()=>{for(let t of y.selectedProjectConfigOutputs)await $e(t,y.projectConfig)},"pull");var Tr=l(require("@sentry/node"));async function xt(t,e=2){t&&T.writeLine(`
112
+ `}`}return r+="}",r}};n(Ne,"VueI18nFramework");var Lt=Ne;function gr(t){if(!t.framework)throw new Error("Only call this function with a framework output");let e=t.framework;switch(e){case"i18next":return new $t(t);case"vue-i18n":return new Lt(t);default:throw new Error(`Unsupported JSON framework: ${e}`)}}n(gr,"getFrameworkProcessor");var Me=class Me extends Tt(Rt){async fetchAPIData(){let e=await this.fetchTextItems(),o=await this.fetchComponents(),s=(await this.fetchVariables()).reduce((i,a)=>(i[a.id]=a,i),{});return{textItems:e,variablesById:s,components:o}}async transformAPIData(e){for(let r=0;r<e.textItems.length;r++){let s=e.textItems[r];this.transformAPITextEntity(s,e.variablesById)}for(let r=0;r<e.components.length;r++){let s=e.components[r];this.transformAPITextEntity(s,e.variablesById)}let o=[...Object.values(this.outputJsonFiles),this.variablesOutputFile];return this.output.framework&&o.push(...gr(this.output).process(this.outputJsonFiles)),o}transformAPITextEntity(e,o){var l;let r=Ko(e)?`${e.projectId}___${e.variantId||"base"}`:`components___${e.variantId||"base"}`;(l=this.outputJsonFiles)[r]??(l[r]=new rt({filename:r,path:this.outDir,metadata:{variantId:e.variantId||"base"}}));let s=this.output.richText==="html",i=this.projectConfig.richText==="html"&&this.output.richText!==!1,c=(s||i)&&e.richText?e.richText:e.text;this.outputJsonFiles[r].content[e.id]=c;for(let g of e.variableIds){let f=o[g];this.variablesOutputFile.content[g]=f.data}}generateTextItemPullFilter(){let e={projects:this.projectConfig.projects,variants:this.projectConfig.variants,statuses:this.projectConfig.statuses};return this.output.projects&&(e.projects=this.output.projects),this.output.variants&&(e.variants=this.output.variants),this.output.statuses&&(e.statuses=this.output.statuses),e}generateComponentPullFilter(){let e={...this.projectConfig.components?.folders&&{folders:this.projectConfig.components.folders},variants:this.projectConfig.variants,statuses:this.projectConfig.statuses};return this.output.components&&(e.folders=this.output.components?.folders),this.output.variants&&(e.variants=this.output.variants),this.output.statuses&&(e.statuses=this.output.statuses),e}generateQueryParams(e){let o=e==="textItem"?this.generateTextItemPullFilter():this.generateComponentPullFilter(),r={filter:JSON.stringify(o)};return this.projectConfig.richText&&(r.richText=this.projectConfig.richText),this.output.richText&&(r.richText=this.output.richText),r}async fetchTextItems(){return!this.projectConfig.projects&&!this.output.projects?[]:await je(this.generateQueryParams("textItem"),this.meta)}async fetchComponents(){return!this.projectConfig.components&&!this.output.components?[]:await Fe(this.generateQueryParams("component"),this.meta)}async fetchVariables(){return await be(this.meta)}};n(Me,"JSONFormatter");var Jt=Me;function Re(t,e,o){switch(t.format){case"json":return new Jt(t,e,o).format();default:throw new Error(`Unsupported output format: ${t}`)}}n(Re,"formatOutput");var hr=n(async t=>{for(let e of y.selectedProjectConfigOutputs)await Re(e,y.projectConfig,t)},"pull");var yr=m(require("@sentry/node"));async function Ct(t,e=2){t&&T.writeLine(`
113
113
  ${t}
114
- `),await Tr.flush(),process.exit(e)}r(xt,"quit");var jr=l(require("fs"));var Le=l(require("fs")),Je=l(require("js-yaml")),Tt=require("zod");var _s=Tt.z.record(Tt.z.string(),Tt.z.array(Tt.z.object({token:Tt.z.string()})));function Kt(t=y.configFile){Et(t);let e=Le.default.readFileSync(t,"utf8"),o=Je.default.load(e),n=_s.safeParse(o);return n.success?n.data:{}}r(Kt,"readGlobalConfigData");function Ms(t,e){Et(t);let o=Kt(t),n=Je.default.dump({...o,...e});Le.default.writeFileSync(t,n,"utf8")}r(Ms,"writeGlobalConfigData");function Sr(t,e,o){let n=Kt(t);n[e]=[{token:o}],Ms(t,n)}r(Sr,"saveToken");var vr=l(require("@sentry/node"));var te=l(require("axios"));async function Vt(t){try{let e=te.default.create({});return e.interceptors.request.use(be(t)),(await e.get("/token-check")).status===200?{success:!0}:{success:!1,output:[T.errorText("This API key isn't valid. Please try another.")]}}catch(e){return e instanceof te.AxiosError?e.code==="ENOTFOUND"?{success:!1,output:[T.errorText(`Can't connect to API: ${T.url(y.apiHost)}`)]}:e.response?.status===401||e.response?.status===404?{success:!1,output:[T.errorText("This API key isn't valid. Please try another.")]}:{success:!1,output:[T.errorText("Sorry! We're having trouble reaching the Ditto API. Please try again later.")]}:{success:!1,output:[T.warnText("Sorry! We're having trouble reaching the Ditto API. Please try again later.")]}}}r(Vt,"checkToken");var Ir=require("enquirer");var $s=r(async t=>{let e=await Vt(t);return e.success?!0:e.output?.join(`
115
- `)||"Invalid API key"},"validate");async function Ve(){return await(0,Ir.prompt)({type:"input",name:"token",message:"What is your API key?",validate:$s})}r(Ve,"promptForApiToken");async function Ye(){let e=`To get started, you'll need your Ditto API key. You can find this at: ${T.url("https://app.dittowords.com/developers/api-keys")}.`;return T.writeLine(e),(await Ve()).token}r(Ye,"collectToken");var wr=l(require("url"));function Yt(t){return t.includes("://")?wr.default.parse(t).hostname||"":t}r(Yt,"getURLHostname");async function St(t=y.apiHost){try{let e=await Ye();T.writeLine(`Thanks for authenticating. We'll save the key to: ${T.info(y.configFile)}
116
- `);let o=Yt(t);return Sr(y.configFile,o,e),y.setApiToken(e),e}catch(e){if(e==="")return await xt("",0),"";let o=vr.captureException(e),n=`
114
+ `),await yr.flush(),process.exit(e)}n(Ct,"quit");var wr=m(require("fs"));var _e=m(require("fs")),$e=m(require("js-yaml")),St=require("zod");var $s=St.z.record(St.z.string(),St.z.array(St.z.object({token:St.z.string()})));function Kt(t=y.configFile){kt(t);let e=_e.default.readFileSync(t,"utf8"),o=$e.default.load(e),r=$s.safeParse(o);return r.success?r.data:{}}n(Kt,"readGlobalConfigData");function Ls(t,e){kt(t);let o=Kt(t),r=$e.default.dump({...o,...e});_e.default.writeFileSync(t,r,"utf8")}n(Ls,"writeGlobalConfigData");function xr(t,e,o){let r=Kt(t);r[e]=[{token:o}],Ls(t,r)}n(xr,"saveToken");var vr=m(require("@sentry/node"));var Cr=require("axios");async function Vt(t){try{return(await W({token:t}).get("/token-check")).status===200?{success:!0}:{success:!1,output:[T.errorText("This API key isn't valid. Please try another.")]}}catch(e){return e instanceof Cr.AxiosError?e.code==="ENOTFOUND"?{success:!1,output:[T.errorText(`Can't connect to API: ${T.url(y.apiHost)}`)]}:e.response?.status===401||e.response?.status===404?{success:!1,output:[T.errorText("This API key isn't valid. Please try another.")]}:{success:!1,output:[T.errorText("Sorry! We're having trouble reaching the Ditto API. Please try again later.")]}:{success:!1,output:[T.warnText("Sorry! We're having trouble reaching the Ditto API. Please try again later.")]}}}n(Vt,"checkToken");var Sr=require("enquirer");var Js=n(async t=>{let e=await Vt(t);return e.success?!0:e.output?.join(`
115
+ `)||"Invalid API key"},"validate");async function Le(){return await(0,Sr.prompt)({type:"input",name:"token",message:"What is your API key?",validate:Js})}n(Le,"promptForApiToken");async function Je(){let e=`To get started, you'll need your Ditto API key. You can find this at: ${T.url("https://app.dittowords.com/developers/api-keys")}.`;return T.writeLine(e),(await Le()).token}n(Je,"collectToken");var Ir=m(require("url"));function Yt(t){return t.includes("://")?Ir.default.parse(t).hostname||"":t}n(Yt,"getURLHostname");async function It(t=y.apiHost){try{let e=await Je();T.writeLine(`Thanks for authenticating. We'll save the key to: ${T.info(y.configFile)}
116
+ `);let o=Yt(t);return xr(y.configFile,o,e),y.setApiToken(e),e}catch(e){if(e==="")return await Ct("",0),"";let o=vr.captureException(e),r=`
117
117
 
118
- Error ID: ${T.info(o)}`;return await xt(T.errorText("Something went wrong. Please contact support or try again later.")+n),""}}r(St,"collectAndSaveToken");async function ee(t){return(await Vt(t)).success?t:await St()}r(ee,"validateToken");async function Be(){if(y.apiToken)return await ee(y.apiToken);if(!jr.default.existsSync(y.configFile))return await St();let t=Kt(y.configFile),e=Yt(y.apiHost);return!t[e]||!t[e][0]||t[e][0].token===""?await St(e):await ee(t[e][0].token)}r(Be,"initAPIToken");var Ls=[{name:"pull",description:"Sync copy from Ditto",flags:{"-c, --config [value]":{description:"Relative path to the project config file. Defaults to `./ditto/config.yml`. Alternatively, you can set the DITTO_PROJECT_CONFIG_FILE environment variable."}}}],Js=r(()=>{Ct.program.name("ditto-cli"),Ls.forEach(t=>{let e=Ct.program.command(t.name).description(t.description).action(o=>Ys(t.name,o));t.flags&&Object.entries(t.flags).forEach(([o,{description:n,processor:s}])=>{s?e.option(o,n,s):e.option(o,n)})})},"setupCommands"),Vs=r(()=>{Ct.program.option("--legacy","Run in legacy mode"),Ct.program.version(it,"-v, --version","Output the current version")},"setupOptions"),Ys=r(async(t,e)=>{try{let o=e.opts(),n=await Be();switch(y.setApiToken(n),await sr(o),t){case"none":case"pull":return await xr();default:{await xt(`Invalid command: ${t}. Exiting Ditto CLI...`);return}}}catch(o){process.env.DEBUG==="true"&&console.error(T.info(`Development stack trace:
119
- `),o);let n,s,i="Something went wrong. Please contact support or try again later.";or(o)&&(s=o.exitCode,Se(o,"ConfigYamlLoadError")?i=o.message:Se(o,"ConfigParseError")&&(i=`${o.data.messagePrefix}
118
+ Error ID: ${T.info(o)}`;return await Ct(T.errorText("Something went wrong. Please contact support or try again later.")+r),""}}n(It,"collectAndSaveToken");async function te(t){return(await Vt(t)).success?t:await It()}n(te,"validateToken");async function Ve(){if(y.apiToken)return await te(y.apiToken);if(!wr.default.existsSync(y.configFile))return await It();let t=Kt(y.configFile),e=Yt(y.apiHost);return!t[e]||!t[e][0]||t[e][0].token===""?await It(e):await te(t[e][0].token)}n(Ve,"initAPIToken");var Vs=n(t=>{let e={};return Array.isArray(t)&&t.forEach(o=>{let r=o.split(":");if(r.length>2)return;let[s,i]=r;e[s]=i}),e},"processCommandMetaFlag"),jr=Vs;var Ys=[{name:"pull",description:"Sync copy from Ditto",flags:{"-c, --config [value]":{description:"Relative path to the project config file. Defaults to `./ditto/config.yml`. Alternatively, you can set the DITTO_PROJECT_CONFIG_FILE environment variable."}}}],Bs=n(()=>{H.program.name("ditto-cli"),Ys.forEach(t=>{let e=H.program.command(t.name).description(t.description).action(o=>Gs(t.name,o));t.flags&&Object.entries(t.flags).forEach(([o,{description:r,processor:s}])=>{s?e.option(o,r,s):e.option(o,r)})})},"setupCommands"),qs=n(()=>{H.program.option("--legacy","Run in legacy mode"),H.program.option("-m, --meta <data...>","Include arbitrary data in requests to the Ditto API. Ex: -m githubActionRequest:true trigger:manual"),H.program.version(ct,"-v, --version","Output the current version")},"setupOptions"),Gs=n(async(t,e)=>{try{let o=e.opts(),r=await Ve();y.setApiToken(r),await cr(o);let{meta:s}=H.program.opts();switch(t){case"none":case"pull":return await hr(jr(s));default:{await Ct(`Invalid command: ${t}. Exiting Ditto CLI...`);return}}}catch(o){process.env.DEBUG==="true"&&console.error(T.info(`Development stack trace:
119
+ `),o);let r,s,i="Something went wrong. Please contact support or try again later.";sr(o)&&(s=o.exitCode,Te(o,"ConfigYamlLoadError")?i=o.message:Te(o,"ConfigParseError")&&(i=`${o.data.messagePrefix}
120
120
 
121
- ${o.data.formattedError}`),n={extra:{message:i,...o.data||{}}});let a=br.captureException(o,n),c=`
121
+ ${o.data.formattedError}`),r={extra:{message:i,...o.data||{}}});let a=Fr.captureException(o,r),c=`
122
122
 
123
- Error ID: ${T.info(a)}`;return await xt(T.errorText(i)+c,s)}},"executeCommand"),Bs=r(async()=>{Js(),Vs(),Ct.program.parse(process.argv)},"appEntry"),Fr=Bs;var qs="production";Or.init({dsn:"https://9c1d99fa4267f54c6b914f720b4ed3a2@o979374.ingest.sentry.io/4505705213919232",environment:qs,release:it});var Gs=r(async()=>{process.argv.includes("--legacy")?(console.log(T.warnText(`
123
+ Error ID: ${T.info(a)}`;return await Ct(T.errorText(i)+c,s)}},"executeCommand"),Us=n(async()=>{Bs(),qs(),H.program.parse(process.argv)},"appEntry"),br=Us;var zs="production";Or.init({dsn:"https://9c1d99fa4267f54c6b914f720b4ed3a2@o979374.ingest.sentry.io/4505705213919232",environment:zs,release:ct});var Zs=n(async()=>{process.argv.includes("--legacy")?(console.log(T.warnText(`
124
124
  Ditto CLI is running in legacy mode. This mode is deprecated and will be removed in a future release.
125
- `)),Ho()):Fr()},"main");Gs();
125
+ `)),Zo()):br()},"main");Zs();
126
126
 
127
- //# debugId=f865a369-e1da-5321-ba25-1c81e1859ad2
127
+ //# debugId=aaa46c99-e8bb-5cdb-acf3-0f9f89d2c84a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dittowords/cli",
3
- "version": "5.0.0",
3
+ "version": "5.2.0",
4
4
  "description": "Command Line Interface for Ditto (dittowords.com).",
5
5
  "license": "MIT",
6
6
  "main": "bin/ditto.js",