@snowplow/snowtype 0.7.1 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -4
- package/dist/index.js +76 -59
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -12,8 +12,6 @@ Useful scripts:
|
|
|
12
12
|
| build:production | Builds project for deployment |
|
|
13
13
|
| build | Builds project for local development |
|
|
14
14
|
| fix-version | Fix version |
|
|
15
|
-
| format:fix | Fix formatting issues |
|
|
16
|
-
| format | Check for any formatting issues |
|
|
17
15
|
| lint:fix | Fix for any lint issues |
|
|
18
16
|
| lint | Check for any lint issues |
|
|
19
17
|
| prebuild:production | Remove dist folder |
|
|
@@ -41,7 +39,7 @@ Edit file `snowtype.config.ts` adding data products or event specifications.
|
|
|
41
39
|
Then run:
|
|
42
40
|
|
|
43
41
|
```bash
|
|
44
|
-
npm run snowtype generate
|
|
42
|
+
npm run snowtype generate
|
|
45
43
|
```
|
|
46
44
|
|
|
47
45
|
This will run the app and generate output code using ts-node.
|
|
@@ -59,4 +57,4 @@ Notes:
|
|
|
59
57
|
|
|
60
58
|
```bash
|
|
61
59
|
npm i -D @snowplow/browser-tracker -w @snowplow/snowtype
|
|
62
|
-
```
|
|
60
|
+
```
|
package/dist/index.js
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);super(s),this.response={statusCode:n,body:o}}};function
|
|
3
|
-
${
|
|
1
|
+
"use strict";var vn=Object.create;var zt=Object.defineProperty;var wn=Object.getOwnPropertyDescriptor;var yn=Object.getOwnPropertyNames;var In=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var En=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yn(e))!xn.call(t,r)&&r!==n&&zt(t,r,{get:()=>e[r],enumerable:!(i=wn(e,r))||i.enumerable});return t};var h=(t,e,n)=>(n=t!=null?vn(In(t)):{},En(e||!t||!t.__esModule?zt(n,"default",{value:t,enumerable:!0}):n,t));var dn=h(require("process")),x=require("@commander-js/extra-typings");var I=require("@inquirer/prompts");var Cn={AuthError:"Authentication failed. Check if your API key and organization ID are correct.",ConfigAlreadyExists:"Snowtype config file already exists.",ConfigNotExists:"Snowtype config file does not exist in current directory. Start with running 'init'.",ConfigInvalid:"Snowtype config exists but it is invalid.",InternalError:"An internal error occured.",InvalidOption:"Invalid option provided.",MissingOptions:"Action called with no options.",WriteLockFile:"Failed writing lock file.",MissingLockFile:"Missing lockfile. You might need to run `snowtype generate` first.",GenerationFailed:"Something went wrong with code generation.",PatchingNotSupported:"Patching is only supported using a Snowtype config file in JSON format.",DevNotAllowed:"Code generation using schemas in DEV environment not allowed. Publish the schemas and retry."},Pn="Please report a bug.",S=class extends Error{code;constructor(e,n=""){let i=Cn[e].concat(n);super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e}},B=class extends S{constructor(){super("GenerationFailed")}},M=class extends S{constructor(){super("ConfigAlreadyExists")}},J=class extends S{constructor(){super("ConfigNotExists")}},q=class extends S{constructor(e){super("ConfigInvalid",e)}},K=class extends S{constructor(e){super("InternalError",e.concat(Pn))}},A=class extends S{constructor(e,n){let i=`Value ${n} is an invalid ${e}.`;super("InvalidOption",i)}},X=class extends S{constructor(){super("MissingOptions")}},D=class extends S{constructor(){super("AuthError")}},Y=class extends S{constructor(){super("WriteLockFile")}},Z=class extends S{constructor(){super("MissingLockFile")}},Q=class extends S{constructor(){super("PatchingNotSupported")}},tt=class extends S{constructor(){super("DevNotAllowed")}};var Ht=h(require("got"));async function Bt({schema:t}){return(await(0,Ht.default)(`https://raw.githubusercontent.com/snowplow/iglu-central/master/schemas/${t.replace("iglu:","")}`)).body}var pt=h(require("got"));var Zt=require("js-sha256"),Et=h(require("assert"));var u=h(require("joi")),ot=require("@snowplow/snowtype-core");var xt=h(require("assert"));var _="snowtype.config",et=".js",nt=".ts",it=".json",Jt=Object.freeze([et,nt,it]),rt=".snowtype-lock.json",qt="snowplow";var U={"google-tag-manager":[{value:"javascript-gtm",name:"JavaScript"}],"@snowplow/javascript-tracker":[{value:"javascript",name:"JavaScript"}],"@snowplow/browser-tracker":[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"}],"@snowplow/node-tracker":[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"}],"snowplow-android-tracker":[{value:"kotlin",name:"Kotlin"}],"snowplow-ios-tracker":[{value:"swift",name:"Swift"}],"snowplow-golang-tracker":[{value:"go",name:"Go"}],"@snowplow/react-native-tracker":[{value:"typescript",name:"TypeScript"}]},Kt={commands:{generate:{instructions:!1,validations:!1,disallowDevSchemas:!1},update:{maximumBump:"major",regenerateOnUpdate:!1},patch:{regenerateOnPatch:!1}}};var at=require("lodash");function Yt(t){let e=t.split("-");(0,xt.default)(e.length===3,"invalid SchemaVer"),(0,xt.default)(e.filter(n=>isNaN(parseInt(n))).length===0,"invalid SchemaVer")}function $(t){t.options=(0,at.merge)((0,at.cloneDeep)(Kt),t.options||{})}var Xt=new RegExp("^iglu:[a-zA-Z0-9-_.]+/[a-zA-Z0-9-_]+/[a-zA-Z0-9-_]+/[0-9]+-[0-9]+-[0-9]+$"),On=u.default.object().required().keys({tracker:u.default.string().required().valid(...ot.trackerTemplates),language:u.default.string().required().valid(...ot.languageIds),outpath:u.default.string().required(),organizationId:u.default.string().when("dataStructures",{is:u.default.array().min(1),then:u.default.required(),otherwise:u.default.optional()}).when("eventSpecificationIds",{is:u.default.array().min(1),then:u.default.required(),otherwise:u.default.optional()}).when("dataProductIds",{is:u.default.array().min(1),then:u.default.required(),otherwise:u.default.optional()}),igluCentralSchemas:u.default.array().optional().items(u.default.string().regex(Xt)),dataStructures:u.default.array().optional().items(u.default.string().regex(Xt)),eventSpecificationIds:u.default.array().optional().items(u.default.string()),dataProductIds:u.default.array().optional().items(u.default.string()),options:u.default.object().optional().keys({commands:u.default.object().optional().keys({generate:u.default.object().optional().keys({instructions:u.default.boolean().optional(),validations:u.default.boolean().optional(),disallowDevSchemas:u.default.boolean().optional()}),patch:u.default.object().optional().keys({regenerateOnPatch:u.default.boolean().optional()}),update:u.default.object().optional().keys({maximumBump:u.default.string().valid("major","minor","patch").optional(),regenerateOnUpdate:u.default.boolean().optional()})})})}),F=t=>{let e=On.validate(t,{abortEarly:!1,convert:!1});if(e.error)throw new q(e.error.annotate());return t};function Tn(t){let e=Zt.sha256.create();return e.update(t),e.hex()}function st(t,e){let{vendor:n,name:i,format:r}=C(t);return Tn(`${e}-${n}-${i}-${r}`)}function C(t){let e=t.replace("iglu:",""),[n,i,r,o]=e.split("/");return(0,Et.default)(typeof n=="string"&&typeof i=="string"&&typeof r=="string"&&typeof o=="string",`invalid iglu uri ${t}`),Yt(o),{vendor:n,name:i,format:r,version:o}}function Qt(t,{vendor:e,name:n,format:i,version:r}){let o=t.replace("iglu:",""),[s,a,c,p]=o.split("/");return`iglu:${e||s}/${n||a}/${i||c}/${r||p}`}function te(t){return t.some(e=>e.eventSchema.isEcomTemplateSchema)}function W(t){let[e,n,i]=t.split("-").map(r=>parseInt(r));return{model:e,revision:n,addition:i}}function ee(t,e,n=0){if(t===e&&n!==0)return"patch";let{model:i,revision:r,addition:o}=W(t),{model:s,revision:a,addition:c}=W(e);if(i!==s)return"major";if(r!==a)return"minor";if(o!==c)return"patch";(0,Et.default)(!1,"SchemaVer checking went wrong")}var ct=class extends Error{response;constructor(e){let n=e.response?.statusCode||0,{method:i,url:r}=e.options,o=e.response?.body||e.message,s=[[n,i,r].filter(Boolean).join(" "),o].filter(Boolean).join(`
|
|
2
|
+
`);super(s),this.response={statusCode:n,body:o}}};function ne(t){return!!Object.hasOwn(t||{},"response")}var R="0.8.1";var w=class{apiKey;organizationId;accessToken;apiUrl=process.env.SNOWPLOW_CONSOLE_API_URL||"https://console.snowplowanalytics.com/api/msc";constructor({apiKey:e,organizationId:n}){this.apiKey=e,this.organizationId=n}async fetchAccessToken(){if(this.accessToken)return this.accessToken;let e=`${this.apiUrl}/v1/organizations/${this.organizationId}/credentials/v2/token`,{accessToken:n}=await(0,pt.default)(e,{headers:{"X-API-Key":this.apiKey,"X-Snowtype":R}}).json();return this.accessToken=n,n}async fetchResource(e){let n=await this.fetchAccessToken();try{return await(0,pt.default)(e,{headers:{Authorization:"Bearer "+n,"X-Snowtype":R}}).json()}catch(i){throw ne(i)?new ct(i):i}}fetchSchemaVersion({schema:e,env:n="DEV"}){let{version:i}=C(e),r=st(e,this.organizationId),o=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${r}/versions/${i}?env=${n}`;return this.fetchResource(o)}fetchSchemaHash({schema:e}){let n=st(e,this.organizationId),i=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${n}`;return this.fetchResource(i)}async fetchDeployments({schema:e}){let n=st(e,this.organizationId),i=25,r=[],o=!0,s=0,a=c=>`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${n}/deployments?size=${i}&from=${c}`;for(;o;){let c=await this.fetchResource(a(s));s+=i,r=r.concat(c),c.length===0&&(o=!1)}return r}fetchEventSpecification({eventSpecificationId:e}){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/tracking-scenarios/v2/${e}`;return this.fetchResource(n)}async fetchImageVariant({imageId:e,imageVariant:n}){let i=`${this.apiUrl}/v1/organizations/${this.organizationId}/images/v1/${e}/${n}`,r=await this.fetchAccessToken();return(0,pt.default)(i,{headers:{Authorization:"Bearer "+r,"X-Snowtype":R}})}fetchDataProduct({dataProductId:e}){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-products/v1/${e}`;return this.fetchResource(n)}async authenticate(){try{return await this.fetchAccessToken(),!0}catch{return!1}}};var mt=require("process"),T=require("path"),v=require("fs");var kt=h(require("util")),At=require("tsx/cjs/api");var P=(()=>{let t="json";return{setFormat:i=>t=i,getFormat:()=>t}})();var b=require("@snowplow/snowtype-core");var dt=require("fs"),Ct=require("path");var ut=h(require("assert"));var ie=require("semver"),re="snowtype.config.json";function bn(t){(0,dt.writeFileSync)((0,Ct.resolve)(process.cwd(),`./${re}`),Ot(t))}function oe(t,e){try{let n=(0,dt.readFileSync)((0,Ct.resolve)(process.cwd(),`./${re}`),{encoding:"utf-8"}),i=JSON.parse(n);return i[t].some(o=>o===e)||i[t].push(e),bn(i),!0}catch(n){return console.error(n),!1}}var kn=(t,e)=>{let{model:n,revision:i,addition:r}=W(t.version),{model:o,revision:s,addition:a}=W(e.version);return(0,ut.default)(n!==void 0&&i!==void 0&&r!==void 0&&o!==void 0&&s!==void 0&&a!==void 0,`Invalid version number comparing (${t}, ${e})`),n>o?1:n<o?-1:i>s?1:i<s?-1:r>a?1:r<a?-1:t.patchLevel>e.patchLevel&&t.contentHash!==e.contentHash?1:e.patchLevel>t.patchLevel&&t.contentHash!==e.contentHash||t.env==="DEV"&&e.env==="PROD"?-1:t.env==="PROD"&&e.env==="DEV"?1:0};async function ae(t,e,n){return(await Promise.all(e.map(async r=>{let{version:o}=C(r),s=await t.fetchDeployments({schema:r}),a=An(s,o,n);a.sort(kn);let c=a.pop();if(!c)return null;let p={previous:r,next:Qt(r,{version:c.version}),nextEnv:c.env};return c.version!==o?{...p,nextReason:"version"}:c.patchLevel>0&&c.env==="DEV"?{...p,nextReason:"patch"}:null}))).flatMap(r=>r===null?[]:[r])}async function Pt(t,e){return Promise.all(e.map(async n=>{try{await t.fetchSchemaVersion({schema:n,env:"PROD"})}catch(i){if(i.response?.statusCode===404)try{return await t.fetchSchemaVersion({schema:n,env:"DEV"}),n}catch(r){if(r.response?.statusCode!==404)throw r}}return null})).then(n=>n.flatMap(i=>i!==null?[i]:[]))}async function se(t,e,n){let{eventSpecifications:i}=n,r={};return await Promise.all(e.map(async o=>{let s=i[o];if(!s)return o;let a=(await t.fetchEventSpecification({eventSpecificationId:o})).data[0];(0,ut.default)(!!a,`failed to fetch event spec ${o}`),(0,ut.default)(!!a.version,`event spec with no version ${o}`);let c=[a.event?.source,...a.entities?.tracked?.map(g=>g.source)||[]].flatMap(g=>typeof g=="string"?[g]:[]),p=await Pt(t,c);return(a.version||0)>s&&(r[o]={previous:s,next:a.version,devOnlySchema:p}),o})),r}function An(t,e,n){return t.filter(i=>$n(e,i.version)!==1).filter(i=>i.version!==e||i.patchLevel).map(i=>({...i,updateType:ee(i.version,e,i.patchLevel)})).filter(Dn(n))}function Dn(t){return({updateType:e})=>{switch(t){case"major":return!0;case"minor":return e==="patch"||e==="minor";case"patch":return e==="patch"}}}function $n(t,e){let n=t.replaceAll("-","."),i=e.replaceAll("-",".");return(0,ie.compare)(n,i)}var pe=require("cli-spinner"),f=h(require("chalk"));function ue(){let t=new pe.Spinner;return t.setSpinnerString(18),t}var Fn="https://snowplow.io",Rn="https://docs.snowplow.io/docs/collecting-data/code-generation/",G={SUCCESS:"\u2714",LOG:"\u2139",DEBUG:"\u27A4",ERROR:"\u2717",WARN:"\u26A0"},de={LINK:"#9911BB",OPTION:"#9911DD"};function ce(t){return f.default.hex(de.LINK).bold(t)}function O(t){return f.default.hex(de.OPTION).italic(t)}function gt(t,e){switch(t){case"h1":return f.default.bold.underline(e);default:return f.default.bold(e)}}function ge(){return`
|
|
3
|
+
${gt("h1","CLI Help")}
|
|
4
4
|
|
|
5
|
-
For more information visit the Snowplow website ${
|
|
5
|
+
For more information visit the Snowplow website ${ce(Fn)}
|
|
6
6
|
|
|
7
|
-
For details see the CLI documentation ${
|
|
7
|
+
For details see the CLI documentation ${ce(Rn)}
|
|
8
8
|
|
|
9
|
-
${
|
|
10
|
-
1. Use ${
|
|
11
|
-
2. Use ${
|
|
12
|
-
3. Use ${
|
|
9
|
+
${gt("h2","How to get started")}
|
|
10
|
+
1. Use ${f.default.cyanBright("snowtype init")} to initialize the setup.
|
|
11
|
+
2. Use ${f.default.cyanBright("snowtype patch")} to add a Data Structure or Event Specification.
|
|
12
|
+
3. Use ${f.default.cyanBright("snowtype generate")} to generate tracking code.
|
|
13
13
|
|
|
14
|
-
${
|
|
15
|
-
To learn more about each CLI command, use the ${
|
|
14
|
+
${gt("h2","Available commands")}
|
|
15
|
+
To learn more about each CLI command, use the ${O("--help")} option, for example, ${O("snowtype init --help")}.
|
|
16
16
|
|
|
17
|
-
${
|
|
17
|
+
${O("snowtype init")}
|
|
18
18
|
Initialize the setup of Snowtype code generation in a project. Creates the \`snowtype.config.json\` file.
|
|
19
19
|
|
|
20
|
-
${
|
|
20
|
+
${O("snowtype patch")}
|
|
21
21
|
Adds new Data Structures and Event Specifications in the \`snowtype.config.json\` file.
|
|
22
22
|
|
|
23
|
-
${
|
|
23
|
+
${O("snowtype generate")}
|
|
24
24
|
Generates tracking code based on configuration on the \`snowtype.config.json\` file.
|
|
25
25
|
|
|
26
|
-
${
|
|
26
|
+
${O("snowtype update")}
|
|
27
27
|
Checks for latest version updates in Data Structures and Event Specifications.
|
|
28
28
|
|
|
29
|
-
${
|
|
30
|
-
Use the ${
|
|
31
|
-
`}function
|
|
32
|
-
${
|
|
33
|
-
${
|
|
34
|
-
`}var
|
|
35
|
-
`));return[...
|
|
36
|
-
`)}`]},[])}function
|
|
37
|
-
`);return[...
|
|
38
|
-
`)}`]},[])}function
|
|
29
|
+
${gt("h2","Debug")}
|
|
30
|
+
Use the ${O("-v")} to output verbose logs
|
|
31
|
+
`}function le(t){let e=`${G.SUCCESS}: `;return f.default.cyanBright(e)+t}function lt(t){let e=`${G.WARN} Warning: `;return f.default.hex("#FFA500")(e)+t}function me(t){let e=`${G.LOG} ${t}`;return f.default.yellowBright(e)}function fe(t){let e=`${G.DEBUG} Debug: `;return f.default.magenta(e)+t}function he(t){let e=`${G.ERROR} Error: `;return f.default.redBright(e)+t}function Se(t,e){let n=`- ${t}`,i=`+ ${e}`;return`
|
|
32
|
+
${f.default.magenta(n)}
|
|
33
|
+
${f.default.cyanBright(i)}
|
|
34
|
+
`}var Ie=h(require("mime-types"));var ve=t=>(e,n)=>{Ln(e,n||"").forEach(t.warn)};function Ln(t,e){let n=jn(t.outdatedDsWarnings,e),i=Vn(t.hiddenDsWarnings,e);return n.concat(i)}function jn(t,e){return t.reduce((n,i)=>{let r=i.sources.map(o=>[`Source: ${o.source}`,`Latest Version: ${o.latestVersion}`].join(`
|
|
35
|
+
`));return[...n,`${["Outdated Data Structures detected:",`Data Product Id: ${e}`,`Event Specification Id: ${i.id}`,...r].join(`
|
|
36
|
+
`)}`]},[])}function Vn(t,e){return t.reduce((n,i)=>{let r=i.sources.map(o=>`Source: ${o.source}`).join(`
|
|
37
|
+
`);return[...n,`${["Hidden Data Structures detected:",`Data Product Id: ${e}`,`Event Specification Id: ${i.id}`,r].join(`
|
|
38
|
+
`)}`]},[])}var we=({metadataResponse:t,accumulatorMetadataWarnings:e,eventSpecificationId:n})=>t!==void 0?Tt({currentMetadata:e,eventSpecificationId:n,newMetadata:t}):Tt({currentMetadata:e,eventSpecificationId:n,newMetadata:{outdatedDsWarnings:[],hiddenDsWarnings:[],metrics:[]}});var Nn=["iglu:com.snowplowanalytics.snowplow/page_ping/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1","iglu:com.snowplowanalytics.snowplow/page_view/jsonschema/1-0-0","iglu:com.snowplowanalytics.mobile/screen_view/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/button_click/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/application_background/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/application_foreground/jsonschema/1-0-0","iglu:com.snowplowanalytics.mobile/application_install/jsonschema/1-0-0","iglu:com.snowplowanalytics.mobile/screen_end/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/custom_event/jsonschema/1-0-0"],Mn="iglu:com.snowplowanalytics.snowplow.ecommerce";async function xe(t,e){return(await Promise.all(e.map(i=>t.fetchDataProduct({dataProductId:i})))).flatMap(({data:[i]})=>i?i.trackingScenarios:[]).map(i=>i?.id).filter(i=>!!i)}function _n(t){let{original:e}=t,[n,i]=e.split("/").reverse();return{imageVariant:n,imageId:i}}async function Ee(t,e){let n=[];if(!(e&&e.length))return[];for(let i of e){let{description:r,appIds:o,url:s,variantUrls:a}=i,c={description:r,appIds:o,url:s};if(a){let{imageVariant:p,imageId:g}=_n(a),l=await t.fetchImageVariant({imageId:g,imageVariant:p});c.imageBuffer=l.rawBody,c.imageExtension=Ie.default.extension(l.headers["content-type"])||""}n.push(c)}return n}function Tt({currentMetadata:t,eventSpecificationId:e,newMetadata:n}){let i=(r,o)=>r.id>o.id?1:-1;return{...t,[e]:{hiddenDsWarnings:n.hiddenDsWarnings.sort(i).map(r=>({sources:r.sources})),outdatedDsWarnings:n.outdatedDsWarnings.sort(i).map(r=>({sources:r.sources}))}}}async function Ce(t,e,n){let i={};return{eventSpecificationsWithId:(await Promise.all(e.map(async o=>{let s=await t.fetchEventSpecification({eventSpecificationId:o}),a=s.data[0];if(typeof a>"u"||typeof a.event>"u")return[];if(!!s.metadata&&ve(n)(s.metadata,a.dataProductId),i=we({metadataResponse:s.metadata,accumulatorMetadataWarnings:i,eventSpecificationId:o}),Nn.includes(a.event.source))return n.warn("Currently you cannot generate code for `Standard` events. Skipping..."),[];let p=a.triggers,g=a.name,l=a.version,d=a.event.schema,m=await ye(t,a,a.event.source),E=a.entities?.tracked||[],j=await Promise.all(E.map(({source:It})=>ye(t,a,It)));return{eventSpecification:{name:g||"",id:o,dataProductId:a.dataProductId||"",dataProductName:""},version:l||0,eventSchema:m,entitiesSchemas:j,entities:E,triggers:p,propertyRules:d}}))).flat(),eventSpecificationsInputMetadata:i}}async function Pe(t){return await Promise.all(t.map(async n=>JSON.parse(await Bt({schema:n}))))}async function Oe(t,e){return await Promise.all(e.map(i=>t.fetchSchemaVersion({schema:i})))}async function Te(t,e){let n=e.flatMap(({eventSpecification:{dataProductId:s}})=>s?[s]:[]),r=(await Promise.all(n.map(async s=>(await t.fetchDataProduct({dataProductId:s})).data[0]))).filter(Un).reduce((s,a)=>(s[a.id]=a.name,s),{});return e.map(s=>({...s,eventSpecification:{...s.eventSpecification,dataProductName:r[s.eventSpecification.dataProductId]||""}}))}function Un(t){return!!t}async function ye(t,e,n){let i=e.event?.schema?.properties?.type?.enum?.[0];return n.match(Mn)?{self:C(n),isEcomTemplateSchema:i}:await t.fetchSchemaVersion({schema:n})}function be(t){return t.reduce((n,i)=>{let r=i.eventSpecification.id;return i.entities.forEach(({source:o,minCardinality:s,maxCardinality:a})=>{if(typeof s<"u"||typeof a<"u"){let c={minCardinality:s,maxCardinality:a};n[r]=n[r]||{},n[r][o]=c}}),n},{})}function Ae(t){return t.length!==0}function Ot(t){return JSON.stringify(t,null,2)}function De(t){let e={organizationId:t.organizationId,tracker:t.tracker,language:t.language,outpath:t.outpath};return Object.assign({igluCentralSchemas:[],dataStructures:[],eventSpecificationIds:[],dataProductIds:[]},e)}function Wn(t){switch(t){case"typescript":return`${_}${nt}`;case"javascript":return`${_}${et}`;case"json":return`${_}${it}`;default:return""}}var ke=t=>(0,v.existsSync)(t)&&!(0,v.lstatSync)(t).isDirectory(),Gn=t=>_+t,zn=t=>({isTS:t.endsWith(nt),isJSON:t.endsWith(it),isJS:t.endsWith(et)}),bt=t=>({configPath:t,...zn(t)});function ft(t){let e=(0,T.isAbsolute)(t)?t:(0,T.resolve)(process.cwd(),t);if(ke(e))return bt(e);if(!(0,v.existsSync)(e))throw new Error(`Can't find a root directory while resolving a config file path.
|
|
39
39
|
Provided path to resolve: ${t}
|
|
40
|
-
cwd: ${process.cwd()}`);let[n]=
|
|
40
|
+
cwd: ${process.cwd()}`);let[n]=Jt.map(i=>(0,T.resolve)(e,Gn(i))).filter(ke);return bt(typeof n!="string"?e:n)}function ht(t){let e=P.getFormat(),n=Wn(e),i=(0,T.resolve)((0,mt.cwd)(),n),r=`const config = ${kt.default.inspect(t,!1,null)}
|
|
41
41
|
`,o=`type SnowtypeConfig = {
|
|
42
42
|
tracker: "${b.trackerTemplates.join('" | "')}";
|
|
43
43
|
language: "${b.languageIds.join('" | "')}";
|
|
@@ -47,16 +47,32 @@ cwd: ${process.cwd()}`);let[n]=Kt.map(r=>(0,C.resolve)(e,Dn(r))).filter(ye);retu
|
|
|
47
47
|
dataStructures?: string[];
|
|
48
48
|
eventSpecificationIds?: string[];
|
|
49
49
|
dataProductIds?: string[];
|
|
50
|
+
options?: {
|
|
51
|
+
commands: {
|
|
52
|
+
generate?: {
|
|
53
|
+
instructions?: boolean;
|
|
54
|
+
validations?: boolean;
|
|
55
|
+
disallowDevSchemas?: boolean;
|
|
56
|
+
}
|
|
57
|
+
update?: {
|
|
58
|
+
regenerateOnUpdate?: boolean
|
|
59
|
+
maximumBump?: "major" | "minor" | "patch"
|
|
60
|
+
}
|
|
61
|
+
patch?: {
|
|
62
|
+
regenerateOnPatch?: boolean
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
50
66
|
}
|
|
51
|
-
`,s=`const config: SnowtypeConfig = ${
|
|
52
|
-
`,a="module.exports = config;",c="export default config;";return e==="json"?(0,
|
|
53
|
-
`))}function
|
|
54
|
-
`,
|
|
67
|
+
`,s=`const config: SnowtypeConfig = ${kt.default.inspect(t,!1,null)}
|
|
68
|
+
`,a="module.exports = config;",c="export default config;";return e==="json"?(0,v.writeFileSync)(i,Ot(t)):(0,v.writeFileSync)(i,(e==="typescript"?[o,s,c]:[r,a]).join(`
|
|
69
|
+
`))}function Dt(t){let e=(0,v.statSync)(t,{throwIfNoEntry:!1});return e===void 0?!1:e.isFile()}function $t(t){return(0,v.readFileSync)(t,{encoding:"utf-8"})}var Hn=async t=>(await(0,At.require)(t,__filename)).default;async function L(){let{configPath:t,isJS:e,isJSON:n,isTS:i}=ft((0,mt.cwd)()),r;return i?(r=await Hn(t),P.setFormat("typescript")):e?(r=(await import(t)).default,P.setFormat("javascript")):n&&(r=JSON.parse($t(t)),P.setFormat("json")),typeof r=="function"&&(r=await r()),r}function $e(t){return JSON.parse($t(t))}async function Fe(t){t.debug("Checking for existing configuration.."),await Ft(!0),t.success("Valid configuration found")}async function Ft(t){let{configPath:e,isJS:n,isJSON:i,isTS:r}=ft(process.cwd()),o=i===!0||r===!0||n===!0,s=r===!1&&n===!1&&i===!1,a;if(r?a=(await(0,At.require)(e,__filename)).default:n?a=(await import(e)).default:i&&(a=JSON.parse($t(e))),typeof a=="function"&&(a=await a()),t){if(s)throw new J;F(a)}else if(o)try{throw F(a),new M}catch(c){if(c instanceof M)throw c}}function Re(t){return{javascript:".js","javascript-gtm":".js",typescript:".ts",kotlin:".kt",swift:".swift",go:".go"}[t]||""}function Le(t,e){let n={eventSpecifications:{}};t.forEach(r=>{n.eventSpecifications[r.eventSpecification.id]=r.version});let i=(0,T.resolve)((0,mt.cwd)(),e,rt);try{(0,v.writeFileSync)(i,JSON.stringify(n,null,2))}catch{throw new Y}}function je(t,e,n){let i=Object.entries(t);i.length>0&&n.success("Available Event Specification Updates"),i.forEach(([r,o])=>{let s=`${r}: version ${o.previous}`,a=`${r}: version ${o.next}`;n.diff(s,a),o.devOnlySchema.length>0&&(n.warn("This Event Specification uses schema that are not in production."),n.warn(o.devOnlySchema.join(" ")))}),e.length>0&&n.success("Available Data Structures Updates"),e.forEach(r=>{let o=`${r.previous}`,s=`${r.next}`;if(n.diff(o,s),r.nextReason==="patch"&&n.warn("The most recent version of this schema has been patched. Possible update required."),r.nextEnv==="DEV"){let a=r.next.split("/").pop();n.warn(`This data structure version (${a}) is not in production.`)}})}function Ve(t){let e=t.optsWithGlobals();return{...e,apiKey:e.apiKey||process.env.SNOWPLOW_CONSOLE_API_KEY}}function z(t){return!!(Array.isArray(t)&&!t.length)}function Ne(t){return[...new Set(t)]}function Me(t){let e=Ne(t);return e.sort(),e}function Bn(t){return t.flatMap(e=>{let n=(0,b.joinIgluSchemaUrlParts)(e.eventSchema.self),i=e.entities.map(r=>r.source);return[n,...i]})}async function _e(t,e,n,i){let r=t.map(a=>(0,b.joinIgluSchemaUrlParts)(a.self)),o=Bn(e),s=await Pt(n,Ne([...r,...o]));if(s.length>0&&(console.log(`
|
|
70
|
+
`,lt(`Generating code using schemas in DEV environment, tracking against those will result in failed events. Schemas in DEV:
|
|
55
71
|
`+s.join(`
|
|
56
72
|
`)),`
|
|
57
|
-
`),
|
|
58
|
-
Find out more ${
|
|
59
|
-
`);let r=await
|
|
73
|
+
`),i))throw new tt}var Jn=["javascript","json","typescript"];function Ue(t){return t in U}function We(t,e){let n=U[t];return Array.isArray(n)?n.map(r=>r.value).includes(e):!1}function Ge(t){return Jn.includes(t)}function ze(){return{withVerbosity:e=>({success:i=>{console.log(le(i))},warn:i=>{console.log(lt(i))},log:i=>{console.log(me(i))},diff:(i,r)=>{console.log(Se(i,r))},debug:i=>{e===!0&&console.log(fe(JSON.stringify(i)))},error:i=>{console.log(he(i.message)),e===!0&&console.log(i)}})}}function y(t,e){return async(n,i)=>{let r=Ve(i),o=ze(),s=ue(),a=o.withVerbosity(r.verbose),c=r.apiKey;if(e!=="init")try{await Fe(a)}catch(p){He(p,a,s)}return t(c,a,s,n).then(()=>Be(s)).catch(p=>{He(p,a,s)})}}function He(t,e,n){throw Be(n),e.error(t),t}function Be(t){t.isSpinning()===!0&&t.stop(!0)}var Je=h(require("chalk"));var qn={type:"password",message:"Enter your Snowplow organization ID:",mask:!0,validate:Ae},Kn={type:"select",message:"Select the Snowplow Tracker to use:",choices:[{value:"google-tag-manager",name:"Google Tag Manager"},{value:"@snowplow/javascript-tracker",name:"JavaScript Tracker"},{value:"@snowplow/browser-tracker",name:"Browser Tracker"},{value:"@snowplow/node-tracker",name:"Node Tracker"},{value:"snowplow-android-tracker",name:"Android Tracker"},{value:"snowplow-ios-tracker",name:"iOS Tracker"},{value:"snowplow-golang-tracker",name:"Golang Tracker"},{value:"@snowplow/react-native-tracker",name:"React Native Tracker"}]},Xn={type:"select",message:"Select the format to use:",choices:[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"},{value:"json",name:"JSON"}]},Yn={type:"input",message:"Enter the directory for Snowtype output:",default:"./snowtype"},Zn=t=>({type:"select",message:"Select the language to use:",choices:t});async function Qn(t,e){e.debug("Checking for existing configuration file.."),await Ft(!1);let n=t.organizationId||await(0,I.password)(qn),i=t.tracker||await(0,I.select)(Kn);if(!Ue(i))throw new A("tracker",i);let r=U[i],o;if(r.length===1){let c=r[0];if(typeof c>"u")throw new K("Missing language entry.");o=c.value}else o=t.language||await(0,I.select)(Zn(r));if(!We(i,o))throw new A("language",o);let s=await(0,I.select)(Xn);if(!Ge(s))throw new A("format",s);P.setFormat(s);let a=t.outpath||await(0,I.input)(Yn);return e.debug("Assembling initialization options.."),{organizationId:n,tracker:i,language:o,format:s,outpath:a}}async function ti(t,e,n,i){t||e.warn(`No SNOWPLOW_CONSOLE_API_KEY detected. You might need to set this up before initializing.
|
|
74
|
+
Find out more ${Je.default.underline("https://docs.snowplow.io/docs/collecting-data/code-generation/using-the-cli/#authenticating-with-the-console")}
|
|
75
|
+
`);let r=await Qn(i,e);n.setSpinnerTitle("Initialising..."),n.isSpinning()===!1&&n.start(),e.debug("Creating configuration with options: ".concat(JSON.stringify(r)));let o=De(r);if(F(o),!await new w({apiKey:t,organizationId:o.organizationId}).authenticate())throw new D;e.success("Authentication succeeded"),ht(o),e.success("Configuration created")}var Rt=y(ti,"init");var pn=require("process"),un=require("path");var rn=require("process"),wt=require("path"),on=require("fs"),an=require("mkdirp"),sn=require("@snowplow/snowtype-core");var St=require("path"),qe=require("mkdirp"),jt=require("fs"),vt=require("@snowplow/snowtype-core");var ei="instructions.md",Ke="assets";async function Xe(t,e,n,i,r){qe.mkdirp.sync((0,St.resolve)(i,Ke));let o=[],s=oi(e,n,r),a=[];await Promise.all(e.map(async p=>{let g={triggers:await Ee(t,p.triggers),instructionsHeading:Lt(p.eventSpecification.name)};a.push(Lt(p.eventSpecification.name));let l=si(p.propertyRules),d=ci(p.entities);ii(p.eventSpecification.id,g,i),o.push(ni({eventStructure:p.eventSchema.self,entitiesStructures:p.entitiesSchemas?.map(m=>m.self)||[],name:p.eventSpecification.name,id:p.eventSpecification.id,dataProductId:p.eventSpecification.dataProductId,version:p.version,triggerInstructions:g.triggers,linkToCode:s[p.eventSpecification.id],formattedPropertyRules:l,formattedCardinalityRules:d,organizationId:t.organizationId}))}));let c=`
|
|
60
76
|
# Implementation instructions
|
|
61
77
|
|
|
62
78
|
_A guide on how to implement tracking for the generated Event Specifications._
|
|
@@ -67,56 +83,57 @@ ${a.map(p=>`- [${p.instructionsTitle}](#${p.instructionsLink})`).join(`
|
|
|
67
83
|
|
|
68
84
|
${o.join(`
|
|
69
85
|
`)}
|
|
70
|
-
`;(0,
|
|
71
|
-
## ${
|
|
86
|
+
`;(0,jt.writeFileSync)((0,St.resolve)(i,ei),c,"utf-8")}function ni({eventStructure:t,entitiesStructures:e,name:n,id:i,dataProductId:r,version:o,triggerInstructions:s,linkToCode:a,formattedPropertyRules:c,formattedCardinalityRules:p,organizationId:g}){let l="_N/A_";return`
|
|
87
|
+
## [${Lt(n).instructionsTitle}](${ri(g,r,i)})
|
|
72
88
|
|
|
73
89
|
| | |
|
|
74
90
|
| ----------- | ----------- |
|
|
75
|
-
| **Id** | ${
|
|
76
|
-
| **Version** | ${
|
|
77
|
-
| **
|
|
78
|
-
| **
|
|
79
|
-
| **
|
|
91
|
+
| **Id** | ${i} |
|
|
92
|
+
| **Version** | ${o} |
|
|
93
|
+
| **Data Product Id** | ${r} |
|
|
94
|
+
| **Event Data Structure** | ${t.name}/${t.version} |
|
|
95
|
+
| **Entity Data Structures** | ${e.map(d=>`${d.name}/${d.version}`).sort().join(", ")} |
|
|
96
|
+
| **Code** | [Link](./${a}) |
|
|
80
97
|
|
|
81
|
-
${
|
|
98
|
+
${c.length>0?`### Implementation Instructions for ${t.name} event properties
|
|
82
99
|
|
|
83
|
-
|
|
100
|
+
#### Property Rules
|
|
84
101
|
| Name | Required | Description | Exact value(s) expected |
|
|
85
102
|
| ----------- | ----------- | ----------- | ----------- |
|
|
86
|
-
${
|
|
103
|
+
${c.map(d=>Object.values(d).join(" | ")).join(`
|
|
87
104
|
`)}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
105
|
+
`:""}
|
|
106
|
+
${p.length>0?`
|
|
107
|
+
#### Entity Cardinality Rules
|
|
91
108
|
| Name | Required | Number of entities |
|
|
92
109
|
| ----------- | ----------- | ----------- |
|
|
93
|
-
${
|
|
110
|
+
${p.map(d=>Object.values(d).join(" | ")).join(`
|
|
94
111
|
`)}
|
|
95
|
-
|
|
112
|
+
`:""}
|
|
96
113
|
|
|
97
|
-
${
|
|
98
|
-
### Trigger ${
|
|
114
|
+
${s.map((d,m,E)=>`
|
|
115
|
+
### Trigger ${E.length!==1?m+1:""}
|
|
99
116
|
|
|
100
117
|
#### Screenshot
|
|
101
|
-
${
|
|
118
|
+
${d.imageBuffer?`[<img src="./assets/${i}_${m}.${d.imageExtension}" width="550"/>](./assets/${i}_${m}.${d.imageExtension})`:l}
|
|
102
119
|
|
|
103
120
|
#### In which application(s) does this trigger apply?
|
|
104
121
|
|
|
105
|
-
${
|
|
122
|
+
${d.appIds&&d.appIds.length?d.appIds.map(j=>"`"+j+"` "):l}
|
|
106
123
|
|
|
107
124
|
#### The URL of the page on which this event specification triggers:
|
|
108
125
|
|
|
109
|
-
${
|
|
126
|
+
${d.url||l}
|
|
110
127
|
|
|
111
128
|
#### Notes
|
|
112
129
|
|
|
113
|
-
${
|
|
114
|
-
`).join("")}`}function
|
|
130
|
+
${d.description||l}
|
|
131
|
+
`).join("")}`}function ii(t,e,n){e.triggers.forEach((i,r)=>{i.imageBuffer&&(0,jt.writeFileSync)((0,St.resolve)(n,Ke,t+"_"+r+"."+i.imageExtension),i.imageBuffer,"binary")})}function ri(t,e,n){return`https://console.snowplowanalytics.com/${t}/data-products/${e}/event-specifications/${n}`}function oi(t,e,n){let i=t.reduce((r,{eventSpecification:{id:o}})=>(r[o]="",r),{});return Object.keys(i).forEach(r=>{let o=e.findIndex(s=>s.match((0,vt.createEventSpecificationInstructionsIdentifier)(r)));i[r]=n+"#L"+o}),i}function Lt(t){let e=t;return{instructionsTitle:e,instructionsLink:ai(e)}}function ai(t){return t.toLowerCase().replace(/[^a-z\d\s-]/g," ").replace(/\s+/g," ").trim().replace(/-{2,}|\s/g,"-")}function si(t){return t?Object.entries(t.properties||{}).map(([e,n])=>{let i=t.required?.includes(e)?"\u2705":"\u274C",r=n.description||"-",o=n.enum?n.enum.map(s=>`\`${s}\``).join(" or "):"-";return{name:e,isRequired:i,description:r,expectedValues:o}}):[]}function ci(t){return t?t.map(({source:e,minCardinality:n,maxCardinality:i})=>{let{name:r}=(0,vt.splitIgluSchemaUrlParts)(e),o=typeof n<"u"&&n>0?"\u2705":"\u274C",s=pi(n,i);return{name:r,isRequired:o,formattedCardinalityValues:s}}):[]}function pi(t,e){return typeof t>"u"?"`any`":typeof e<"u"?t===e?`Exactly \`${t}\``:`Between \`${t}\` and \`${e}\``:`At least \`${t}\``}var cn=h(require("fs-extra"));var Ze=require("fs"),Qe=require("path"),tn=h(require("util"));function en(t,e,n,i){let r=e==="typescript"?"ts":"js";(0,Ze.writeFileSync)((0,Qe.resolve)(t,`validations.${r}`),`${r==="ts"?`
|
|
115
132
|
import { AnySchema } from "ajv";
|
|
116
133
|
export type CardinalityRule = { minCardinality?: number; maxCardinality?: number };
|
|
117
134
|
`:""}
|
|
118
|
-
export const entityRules${
|
|
135
|
+
export const entityRules${r==="ts"?": Record<string, Record<string, CardinalityRule>>":""} = ${Ye(i)}
|
|
119
136
|
|
|
120
|
-
export const schemasObject${
|
|
121
|
-
`),
|
|
122
|
-
`),await t.parseAsync(
|
|
137
|
+
export const schemasObject${r==="ts"?": Record<string, AnySchema>":""} = ${Ye(n)}`,"utf-8")}function Ye(t){return tn.default.inspect(t,{showHidden:!1,depth:null,maxArrayLength:null})}function nn(t){return Object.values(t).some(e=>e.properties?Object.values(e.properties).some(n=>Object.hasOwn(n||{},"pattern")):!1)}async function ui(t){let e=await L();return $(e),e.options.commands.generate={...e.options.commands.generate,...t},e}async function H(t,e,n,i){let{dataProductIds:r,dataStructures:o,igluCentralSchemas:s,eventSpecificationIds:a,language:c,tracker:p,outpath:g,organizationId:l,options:{commands:{generate:d}}}=await ui(i);n.setSpinnerTitle("Generating..."),n.isSpinning()===!1&&n.start(),z(o)&&z(s)&&z(a)&&z(r)&&e.warn("Data Structures, Schemas and Event Specifications are empty.");let m=new w({apiKey:t,organizationId:l});if(!await m.authenticate())throw new D;let j=await xe(m,r),It=Me([...j,...a]),{eventSpecificationsWithId:V,eventSpecificationsInputMetadata:ln}=await Ce(m,It,e),_t=await Te(m,V);te(V)&&p==="@snowplow/browser-tracker"&&e.log("You are generating Snowplow Ecommerce events. You would need to install `@snowplow/browser-plugin-snowplow-ecommerce`."),d.validations&&e.log("For validations to work properly you would need to install `ajv@8`, `ajv-formats@2` and `ajv-draft-04@1` on your project.");let mn=await Pe(s),Ut=await Oe(m,o),Wt=!!(p==="@snowplow/browser-tracker"&&c.match(/javascript|typescript/));await _e(Ut,_t,m,d.disallowDevSchemas);let fn={language:c,tracker:p,schemas:[...mn,...Ut],eventSpecifications:_t,validations:Wt&&d.validations,eventSpecificationsInputMetadata:ln},k=await(0,sn.generate)(fn);if(n.stop(!0),!k)throw new B;e.success("Code generated, writing...");let hn=k.lines.join(`
|
|
138
|
+
`),N=(0,wt.resolve)((0,rn.cwd)(),g);cn.default.removeSync((0,wt.resolve)(N)),an.mkdirp.sync(N);let Gt=qt+Re(c);if((0,on.writeFileSync)((0,wt.resolve)(N,Gt),hn),Le(V,g),Wt&&d.validations&&k.validationsSchemaObject){let Sn=be(V);en(N,c,k.validationsSchemaObject,Sn),nn(k.validationsSchemaObject)&&e.warn("Some schemas appear to have attributes that can have inconsistent validations between the pipeline and client-side validation. Read more at https://docs.snowplow.io/docs/collecting-data/code-generation/client-side-validation/#divergence-with-pipeline-validation")}d.instructions&&await Xe(m,V,k.lines,N,Gt)}var Vt=y(H,"generate");async function di(){let t=await L();return $(t),t}async function gi(t,e,n,i){let r=await di(),{options:{commands:{update:{maximumBump:o,regenerateOnUpdate:s},generate:a}}}=r;e.debug("Starting update process with options: ".concat(JSON.stringify(i)));let c=(0,un.resolve)((0,pn.cwd)(),r.outpath,rt),p=new w({apiKey:t,organizationId:r.organizationId});n.setSpinnerTitle("Checking for updates..."),n.isSpinning()===!1&&n.start();let g={};if(!Dt(c)&&r.eventSpecificationIds.length)throw new Z;if(Dt(c)&&r.eventSpecificationIds.length){let m=$e(c);g=await se(p,r.eventSpecificationIds,m)}let l=await ae(p,r.dataStructures,i.maximumBump||o);if((Object.entries(g).length>0||l.length>0)===!0){if(e.success("Available updates found!"),je(g,l,e),i.yes||s)return l.length>0&&(l.forEach(m=>{let E=r.dataStructures.indexOf(m.previous);r.dataStructures[E]=m.next}),ht(r)),e.debug("Applying the updates.."),H(t,e,n,a);e.log("No updates applied"),e.log("To apply the available updates automatically run `update` with the --yes flag"),e.log("(caution: will ovewrite the configuration file)")}else e.success("No updates found. Everything is up-to-date!");return Promise.resolve(void 0)}var Nt=y(gi,"update");async function li(t){if(Object.values(t).every(n=>Array.isArray(n)&&n.length===0))throw new X;let e=await L();return $(e),{patchOptions:t,generateOptions:e.options.commands.generate,regenerateOnPatch:e.options.commands.patch.regenerateOnPatch}}async function mi(t,e,n,i){let{isJSON:r}=ft(process.cwd());if(r===!1)throw new Q;let{patchOptions:o,generateOptions:s,regenerateOnPatch:a}=await li(i);return e.debug("Starting patch process with options: ".concat(JSON.stringify(o))),Object.entries(o).forEach(([p,g])=>{g.forEach(l=>{oe(p,l)})}),e.success("Configuration patched"),a?H(t,e,n,s):(e.log("Code is not generated yet for the patched configuration"),Promise.resolve(void 0))}var Mt=y(mi,"patch");var yt=require("@snowplow/snowtype-core");async function gn(){await import("dotenv/config");let t=new x.Command;t.exitOverride(),t.version(R,void 0,"Snowtype CLI version number").name("snowtype").description("The Snowtype CLI is a tool which aims to speed up tracking implementations, provide type safety and inline documentation for developers and ultimately reduce the number of erroneous events.").showHelpAfterError().configureHelp({showGlobalOptions:!0}).option("-k, --apiKey <string>","Snowplow Console API key").option("-v, --verbose","Enable verbose logging"),t.command("init").description("Initialize the setup of Snowtype code generation in a project. Creates the `snowtype.config.json` file.").option("-i, --organizationId <string>","organization ID").addOption(new x.Option("-t, --tracker <availableTrackers>","tracker to use").choices(yt.trackerTemplates)).addOption(new x.Option("-l, --language <availableLanguages>","language to use").choices(yt.languageIds)).option("-o, --outpath <string>","output path").action(Rt),t.command("update").description("Checks for latest version updates in Data Structures and Event Specifications.").option("-y, --yes","updates all to latest without asking (caution: will ovewrite the configuration file)").addOption(new x.Option("-m, --maximumBump <'patch' | 'minor' | 'major'>","the maximum SchemaVer update to show an available update notification. Defaults to 'major'").choices(["patch","minor","major"])).action(Nt),t.command("generate").option("--instructions","generate event specification instructions").option("--no-instructions","generate without instructions").option("--validations","add runtime validation using Ajv").option("--no-validations","generate without runtime validations").option("--disallowDevSchemas","disallow generation of code using schemas only deployed on DEV environment").description("Generates tracking code based on configuration on the `snowtype.config.json` file.").action(Vt),t.command("patch").description("Adds new Data Structures and Event Specifications in the `snowtype.config.json` file.").option("-p, --dataProductIds <dataProductIds...>","data product ID").option("-e, --eventSpecificationIds <eventSpecificationIds...>","tracking eventSpecification ID").option("-d, --dataStructures <dataStructures...>","data structure URI").option("-i, --igluCentralSchemas <igluCentralSchemas...>","iglu central URI").action(Mt),t.addHelpText("before",ge()).addHelpText("after",`
|
|
139
|
+
`),await t.parseAsync(dn.argv).catch(e=>{fi(e)})}function fi(t){if(!(t instanceof x.CommanderError&&["commander.help","commander.version","commander.helpDisplayed"].indexOf(t.code)>-1))throw t}gn().then(()=>{}).catch(()=>{process.exitCode=1});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@snowplow/snowtype",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"description": "A code generator CLI for faster and type-safe Snowplow tracking code",
|
|
5
5
|
"author": "Peter Perlepes <peter@snowplowanalytics.com>",
|
|
6
6
|
"homepage": "https://snowplow.io/",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"dependencies": {
|
|
14
14
|
"@commander-js/extra-typings": "^11.1.0",
|
|
15
15
|
"@inquirer/prompts": "^3.3.0",
|
|
16
|
-
"@snowplow/snowtype-core": "^0.
|
|
16
|
+
"@snowplow/snowtype-core": "^0.8.1",
|
|
17
17
|
"chalk": "^4.1.2",
|
|
18
18
|
"cli-spinner": "^0.2.10",
|
|
19
19
|
"dotenv": "^16.3.1",
|
|
@@ -21,8 +21,10 @@
|
|
|
21
21
|
"got": "^11",
|
|
22
22
|
"joi": "^17.6.0",
|
|
23
23
|
"js-sha256": "^0.10.1",
|
|
24
|
+
"lodash": "^4.17.21",
|
|
24
25
|
"mime-types": "^2.1.35",
|
|
25
26
|
"mkdirp": "^3.0.1",
|
|
27
|
+
"semver": "^7.6.3",
|
|
26
28
|
"tsx": "^4.9.3"
|
|
27
29
|
},
|
|
28
30
|
"devDependencies": {
|
|
@@ -31,6 +33,7 @@
|
|
|
31
33
|
"@types/fs-extra": "^11.0.4",
|
|
32
34
|
"@types/got": "^9.6.12",
|
|
33
35
|
"@types/jest": "^29.5.8",
|
|
36
|
+
"@types/lodash": "^4.17.7",
|
|
34
37
|
"@types/mime-types": "^2.1.4",
|
|
35
38
|
"@types/node": "^20.9.0",
|
|
36
39
|
"esbuild": "^0.19.11",
|
|
@@ -46,8 +49,6 @@
|
|
|
46
49
|
"build:production": "esbuild --bundle --packages=external --platform=node --target=es2022 --outdir=dist --minify src/index.ts",
|
|
47
50
|
"build": "tsc",
|
|
48
51
|
"fix-version": "node ./scripts/version.js",
|
|
49
|
-
"format:fix": "prettier --write src",
|
|
50
|
-
"format": "prettier --check src",
|
|
51
52
|
"lint:fix": "eslint src --fix",
|
|
52
53
|
"lint": "eslint src",
|
|
53
54
|
"prebuild:production": "npm run fix-version && rimraf ./dist",
|