@dittowords/cli 5.0.0-beta.1 → 5.0.0-beta.4

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