@snowplow/snowtype 0.10.0 → 0.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +54 -52
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -1,49 +1,50 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);super(
|
|
3
|
-
${
|
|
1
|
+
"use strict";var jn=Object.create;var Qt=Object.defineProperty;var Vn=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,Un=Object.prototype.hasOwnProperty;var Mn=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wn(e))!Un.call(t,o)&&o!==n&&Qt(t,o,{get:()=>e[o],enumerable:!(i=Vn(e,o))||i.enumerable});return t};var f=(t,e,n)=>(n=t!=null?jn(Nn(t)):{},Mn(e||!t||!t.__esModule?Qt(n,"default",{value:t,enumerable:!0}):n,t));var Cn=f(require("process")),D=require("@commander-js/extra-typings");var b=require("@inquirer/prompts");var _n={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.",AuthCredentialsMissing:"Required API key credentials not detected. Please refer to https://docs.snowplow.io/docs/collecting-data/code-generation/using-the-cli/#authenticating-with-the-console"},Gn="Please report a bug.",h=class extends Error{code;constructor(e,n=""){let i=_n[e].concat(n);super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e}},Z=class extends h{constructor(){super("GenerationFailed")}},z=class extends h{constructor(){super("ConfigAlreadyExists")}},Q=class extends h{constructor(){super("ConfigNotExists")}},tt=class extends h{constructor(e){super("ConfigInvalid",e)}},et=class extends h{constructor(e){super("InternalError",e.concat(Gn))}},L=class extends h{constructor(e,n){let i=`Value ${n} is an invalid ${e}.`;super("InvalidOption",i)}},nt=class extends h{constructor(){super("MissingOptions")}},j=class extends h{constructor(){super("AuthError")}},it=class extends h{constructor(){super("WriteLockFile")}},ot=class extends h{constructor(){super("MissingLockFile")}},rt=class extends h{constructor(){super("PatchingNotSupported")}},at=class extends h{constructor(){super("DevNotAllowed")}},st=class extends h{constructor(){super("AuthCredentialsMissing")}};var te=f(require("got"));async function ee({schema:t}){return(await(0,te.default)(`https://raw.githubusercontent.com/snowplow/iglu-central/master/schemas/${t.replace("iglu:","")}`)).body}var ht=f(require("got"));var pe=require("js-sha256"),Rt=f(require("assert"));var u=f(require("joi")),lt=require("@snowplow/snowtype-core");var kt=f(require("assert"));var B="snowtype.config",ct=".js",pt=".ts",ut=".json",ne=Object.freeze([ct,pt,ut]),dt=".snowtype-lock.json",ie="snowplow";var J={"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"}],"snowplow-flutter-tracker":[{value:"dart",name:"Dart"}]},oe={commands:{generate:{instructions:!1,validations:!1,disallowDevSchemas:!1,deprecateOnlyOnProdAvailableUpdates:!1},update:{maximumBump:"major",regenerateOnUpdate:!1,showOnlyProdUpdates:!1},patch:{regenerateOnPatch:!1}}},re=["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"],ae="iglu:com.snowplowanalytics.snowplow.ecommerce";var gt=require("lodash");function ce(t){let e=t.split("-");(0,kt.default)(e.length===3,"invalid SchemaVer"),(0,kt.default)(e.filter(n=>isNaN(parseInt(n))).length===0,"invalid SchemaVer")}function V(t){t.options=(0,gt.merge)((0,gt.cloneDeep)(oe),t.options||{})}var se=new RegExp("^iglu:[a-zA-Z0-9-_.]+/[a-zA-Z0-9-_]+/[a-zA-Z0-9-_]+/[0-9]+-[0-9]+-[0-9]+$"),Hn=u.default.object().required().keys({tracker:u.default.string().required().valid(...lt.trackerTemplates),language:u.default.string().required().valid(...lt.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(se)),repositories:u.default.array().optional().items(u.default.string()),dataStructures:u.default.array().optional().items(u.default.string().regex(se)),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(),deprecateOnlyOnProdAvailableUpdates: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(),showOnlyProdUpdates:u.default.boolean().optional()})})})}),W=t=>{let e=Hn.validate(t,{abortEarly:!1,convert:!1});if(e.error)throw new tt(e.error.annotate());return t};function zn(t){let e=pe.sha256.create();return e.update(t),e.hex()}function mt(t,e){let{vendor:n,name:i,format:o}=I(t);return zn(`${e}-${n}-${i}-${o}`)}function I(t){let e=t.replace("iglu:",""),[n,i,o,r]=e.split("/");return(0,Rt.default)(typeof n=="string"&&typeof i=="string"&&typeof o=="string"&&typeof r=="string",`invalid iglu uri ${t}`),ce(r),{vendor:n,name:i,format:o,version:r}}function ue(t,{vendor:e,name:n,format:i,version:o}){let r=t.replace("iglu:",""),[a,s,p,c]=r.split("/");return`iglu:${e||a}/${n||s}/${i||p}/${o||c}`}function de(t){return t.some(e=>e.eventSchema.isEcomTemplateSchema)}function K(t){let[e,n,i]=t.split("-").map(o=>parseInt(o));return{model:e,revision:n,addition:i}}function le(t,e,n=0){if(t===e&&n!==0)return"patch";let{model:i,revision:o,addition:r}=K(t),{model:a,revision:s,addition:p}=K(e);if(i!==a)return"major";if(o!==s)return"minor";if(r!==p)return"patch";(0,Rt.default)(!1,"SchemaVer checking went wrong")}var ft=class extends Error{response;constructor(e){let n=e.response?.statusCode||0,{method:i,url:o}=e.options,r=e.response?.body||e.message,a=[[n,i,o].filter(Boolean).join(" "),r].filter(Boolean).join(`
|
|
2
|
+
`);super(a),this.response={statusCode:n,body:r}}};function ge(t){return!!Object.hasOwn(t||{},"response")}var N="0.10.2";var P=class{apiKeyId;apiKey;organizationId;accessToken;apiUrl=process.env.SNOWPLOW_CONSOLE_API_URL||"https://console.snowplowanalytics.com/api/msc";constructor({apiKeyId:e,apiKey:n,organizationId:i}){this.apiKeyId=e,this.apiKey=n,this.organizationId=i}async fetchAccessToken(){if(this.accessToken)return this.accessToken;let e=`${this.apiUrl}/v1/organizations/${this.organizationId}/credentials/v3/token`,{accessToken:n}=await(0,ht.default)(e,{headers:{"X-API-Key-Id":this.apiKeyId,"X-API-Key":this.apiKey,"X-Snowtype":N}}).json();return this.accessToken=n,n}async fetchResource(e){let n=await this.fetchAccessToken();try{return await(0,ht.default)(e,{headers:{Authorization:"Bearer "+n,"X-Snowtype":N}}).json()}catch(i){throw ge(i)?new ft(i):i}}fetchSchemaVersion({schema:e,env:n="DEV"}){let{version:i}=I(e),o=mt(e,this.organizationId),r=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${o}/versions/${i}?env=${n}`;return this.fetchResource(r)}fetchSchemaHash({schema:e}){let n=mt(e,this.organizationId),i=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${n}`;return this.fetchResource(i)}async fetchDeployments({schema:e,deploymentEnv:n}){let i=mt(e,this.organizationId),o=25,r=[],a=!0,s=0,p=c=>`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${i}/deployments?size=${o}&from=${c}${n?`&env=${n}`:""}`;for(;a;){let c=await this.fetchResource(p(s));s+=o,r=r.concat(c),c.length===0&&(a=!1)}return r}fetchEventSpecification({eventSpecificationId:e}){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/event-specs/v1/${e}`;return this.fetchResource(n)}async fetchImageVariant({imageId:e,imageVariant:n}){let i=`${this.apiUrl}/v1/organizations/${this.organizationId}/images/v1/${e}/${n}`,o=await this.fetchAccessToken();return(0,ht.default)(i,{headers:{Authorization:"Bearer "+o,"X-Snowtype":N}})}fetchDataProduct({dataProductId:e}){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-products/v2/${e}`;return this.fetchResource(n)}async authenticate(){try{return await this.fetchAccessToken(),!0}catch{return!1}}};var E=require("path"),y=require("fs");var Wt=f(require("util")),Nt=require("tsx/cjs/api");var T=(()=>{let t="json";return{setFormat:i=>t=i,getFormat:()=>t}})();var C=require("@snowplow/snowtype-core");var vt=require("fs");var St=f(require("assert"));var me=require("semver");function fe(t,e,n){try{let i=(0,vt.readFileSync)(n,{encoding:"utf-8"}),o=JSON.parse(i);return o[t].some(a=>a===e)||o[t].push(e),(0,vt.writeFileSync)(n,Lt(o)),!0}catch(i){return console.error(i),!1}}var Bn=(t,e)=>{let{model:n,revision:i,addition:o}=K(t.version),{model:r,revision:a,addition:s}=K(e.version);return(0,St.default)(n!==void 0&&i!==void 0&&o!==void 0&&r!==void 0&&a!==void 0&&s!==void 0,`Invalid version number comparing (${t}, ${e})`),n>r?1:n<r?-1:i>a?1:i<a?-1:o>s?1:o<s?-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 he(t,e,n,i){return(await Promise.all(e.map(async r=>{let{version:a}=I(r),s=await t.fetchDeployments({schema:r,...i&&{deploymentEnv:"PROD"}}),p=Jn(s,a,n);p.sort(Bn);let c=p.pop();if(!c)return null;let d={previous:r,next:ue(r,{version:c.version}),nextEnv:c.env};return c.version!==a?{...d,nextReason:"version"}:c.patchLevel>0&&c.env==="DEV"?{...d,nextReason:"patch"}:null}))).flatMap(r=>r===null?[]:[r])}async function $t(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(o){if(o.response?.statusCode!==404)throw o}}return null})).then(n=>n.flatMap(i=>i!==null?[i]:[]))}async function Se(t,e,n){let{eventSpecifications:i}=n,o={};return await Promise.all(e.map(async r=>{let a=i[r];if(!a)return r;let s=(await t.fetchEventSpecification({eventSpecificationId:r})).data[0];(0,St.default)(!!s,`failed to fetch event spec ${r}`),(0,St.default)(!!s.version,`event spec with no version ${r}`);let p=[s.event?.source,...s.entities?.tracked?.map(d=>d.source)||[]].flatMap(d=>typeof d=="string"?[d]:[]),c=await $t(t,p);return(s.version||0)>a&&(o[r]={previous:a,next:s.version,devOnlySchema:c}),r})),o}function Jn(t,e,n){return t.filter(i=>Ft(e,i.version)!==1).filter(i=>i.version!==e||i.patchLevel).map(i=>({...i,updateType:le(i.version,e,i.patchLevel)})).filter(Kn(n))}function Kn(t){return({updateType:e})=>{switch(t){case"major":return!0;case"minor":return e==="patch"||e==="minor";case"patch":return e==="patch"}}}function Ft(t,e){let n=t.replaceAll("-","."),i=e.replaceAll("-",".");return(0,me.compare)(n,i)}var ye=require("cli-spinner"),S=f(require("chalk"));function we(){let t=new ye.Spinner;return t.setSpinnerString(18),t}var qn="https://snowplow.io",Xn="https://docs.snowplow.io/docs/collecting-data/code-generation/",q={SUCCESS:"\u2714",LOG:"\u2139",DEBUG:"\u27A4",ERROR:"\u2717",WARN:"\u26A0"},Ie={LINK:"#9911BB",OPTION:"#9911DD"};function ve(t){return S.default.hex(Ie.LINK).bold(t)}function k(t){return S.default.hex(Ie.OPTION).italic(t)}function yt(t,e){switch(t){case"h1":return S.default.bold.underline(e);default:return S.default.bold(e)}}function Ee(){return`
|
|
3
|
+
${yt("h1","CLI Help")}
|
|
4
4
|
|
|
5
|
-
For more information visit the Snowplow website ${ve(
|
|
5
|
+
For more information visit the Snowplow website ${ve(qn)}
|
|
6
6
|
|
|
7
|
-
For details see the CLI documentation ${ve(
|
|
7
|
+
For details see the CLI documentation ${ve(Xn)}
|
|
8
8
|
|
|
9
|
-
${
|
|
10
|
-
1. Use ${
|
|
11
|
-
2. Use ${
|
|
12
|
-
3. Use ${
|
|
9
|
+
${yt("h2","How to get started")}
|
|
10
|
+
1. Use ${S.default.cyanBright("snowtype init")} to initialize the setup.
|
|
11
|
+
2. Use ${S.default.cyanBright("snowtype patch")} to add a Data Structure or Event Specification.
|
|
12
|
+
3. Use ${S.default.cyanBright("snowtype generate")} to generate tracking code.
|
|
13
13
|
|
|
14
|
-
${
|
|
15
|
-
To learn more about each CLI command, use the ${
|
|
14
|
+
${yt("h2","Available commands")}
|
|
15
|
+
To learn more about each CLI command, use the ${k("--help")} option, for example, ${k("snowtype init --help")}.
|
|
16
16
|
|
|
17
|
-
${
|
|
17
|
+
${k("snowtype init")}
|
|
18
18
|
Initialize the setup of Snowtype code generation in a project. Creates the \`snowtype.config.json\` file.
|
|
19
19
|
|
|
20
|
-
${
|
|
20
|
+
${k("snowtype patch")}
|
|
21
21
|
Adds new Data Structures and Event Specifications in the \`snowtype.config.json\` file.
|
|
22
22
|
|
|
23
|
-
${
|
|
23
|
+
${k("snowtype generate")}
|
|
24
24
|
Generates tracking code based on configuration on the \`snowtype.config.json\` file.
|
|
25
25
|
|
|
26
|
-
${
|
|
26
|
+
${k("snowtype update")}
|
|
27
27
|
Checks for latest version updates in Data Structures and Event Specifications.
|
|
28
28
|
|
|
29
|
-
${
|
|
30
|
-
Use the ${
|
|
31
|
-
`}function xe(t){let e=`${
|
|
32
|
-
${
|
|
33
|
-
${
|
|
34
|
-
`}var
|
|
29
|
+
${yt("h2","Debug")}
|
|
30
|
+
Use the ${k("-v")} to output verbose logs
|
|
31
|
+
`}function xe(t){let e=`${q.SUCCESS}: `;return S.default.cyanBright(e)+t}function wt(t){let e=`${q.WARN} Warning: `;return S.default.hex("#FFA500")(e)+t}function Pe(t){let e=`${q.LOG} ${t}`;return S.default.yellowBright(e)}function Ce(t){let e=`${q.DEBUG} Debug: `;return S.default.magenta(e)+t}function Ae(t){let e=`${q.ERROR} Error: `;return S.default.redBright(e)+t}function Oe(t,e){let n=`- ${t}`,i=`+ ${e}`;return`
|
|
32
|
+
${S.default.magenta(n)}
|
|
33
|
+
${S.default.cyanBright(i)}
|
|
34
|
+
`}var Re=f(require("mime-types"));var be=t=>{let e={outdatedDsWarnings:[],hiddenDsWarnings:[],metrics:[]};return t.reduce((n,i)=>Yn({currentMetadata:n,eventSpecificationId:i.eventSpecification.id,newMetadata:i.metadata||e}),{})};function Yn({currentMetadata:t,eventSpecificationId:e,newMetadata:n}){let i=(o,r)=>o.id>r.id?1:-1;return{...t,[e]:{hiddenDsWarnings:n.hiddenDsWarnings.sort(i).map(o=>({sources:o.sources})),outdatedDsWarnings:n.outdatedDsWarnings.sort(i).map(o=>({sources:o.sources}))}}}var De=t=>(e,n)=>{Zn(e,n||"").forEach(t.warn)};function Zn(t,e){let n=Qn(t.outdatedDsWarnings,e),i=ti(t.hiddenDsWarnings,e);return n.concat(i)}function Qn(t,e){return t.reduce((n,i)=>{let o=i.sources.map(r=>[`Source: ${r.source}`,`Latest Version: ${r.latestVersion}`].join(`
|
|
35
35
|
`));return[...n,`${["Outdated Data Structures detected:",`Data Product Id: ${e}`,`Event Specification Id: ${i.id}`,...o].join(`
|
|
36
|
-
`)}`]},[])}function
|
|
36
|
+
`)}`]},[])}function ti(t,e){return t.reduce((n,i)=>{let o=i.sources.map(r=>`Source: ${r.source}`).join(`
|
|
37
37
|
`);return[...n,`${["Hidden Data Structures detected:",`Data Product Id: ${e}`,`Event Specification Id: ${i.id}`,o].join(`
|
|
38
|
-
`)}`]},[])}
|
|
38
|
+
`)}`]},[])}async function Te(t,e){let n=ni(t),i=await Promise.all(n.map(async r=>({schema:r,deployments:await e.fetchDeployments({schema:r,deploymentEnv:"PROD"})}))),o=ei(i);return ii(t,o)}var ei=t=>t.flatMap(({schema:e,deployments:n})=>{let{version:i}=I(e);return n.filter(r=>Ft(i,r.version)===-1).length===0?[]:[e]}),ni=t=>U(Object.entries(t).filter(([,e])=>e.outdatedDsWarnings.length!==0).flatMap(([,e])=>e.outdatedDsWarnings.flatMap(n=>n.sources.map(i=>i.source)))),ii=(t,e)=>Object.keys(t).reduce((n,i)=>{let o=t[i];if(o){let r=o.outdatedDsWarnings.flatMap(({sources:a})=>{let s=a.filter(p=>e.includes(p.source));return s.length>0?[{sources:s}]:[]});n[i]={...o,outdatedDsWarnings:r}}return n},{});async function It(t,e){return(await Promise.all(e.map(i=>t.fetchDataProduct({dataProductId:i})))).flatMap(({data:[i]})=>i?i.eventSpecs:[]).map(i=>i.id)}function oi(t){let{original:e}=t,[n,i]=e.split("/").reverse();return{imageVariant:n,imageId:i}}async function $e(t,e){let n=[];if(!(e&&e.length))return[];for(let i of e){let{description:o,appIds:r,url:a,variantUrls:s}=i,p={description:o,appIds:r,url:a};if(s){let{imageVariant:c,imageId:d}=oi(s),m=await t.fetchImageVariant({imageId:d,imageVariant:c});p.imageBuffer=m.rawBody,p.imageExtension=Re.default.extension(m.headers["content-type"])||""}n.push(p)}return n}async function Fe(t,e,n){return{eventSpecificationsWithId:(await Promise.all(e.map(async o=>{let r=await t.fetchEventSpecification({eventSpecificationId:o}),a=r.data[0];if(typeof a>"u"||typeof a.event>"u")return[];!!r.metadata&&De(n)(r.metadata,a.dataProductId);let p=jt(a.event.source);p&&n.warn("Currently code will not be generated for `Standard` events. Skipping...");let c=a.triggers,d=a.name,m=a.version,v=a.sourceApplications||[],l=a.event.schema,w=p?ai(a.event.source):await ke(t,a,a.event.source),g=a.entities?.tracked||[],G=await Promise.all(g.map(async({source:x,schema:H})=>({original:await ke(t,a,x),propertyRule:H})));return{eventSpecification:{name:d||"",id:o,dataProductId:a.dataProductId||"",dataProductName:""},version:m||0,eventSchema:w,entitiesSchemas:G,entities:g,triggers:c,propertyRules:l,sourceApplicationIds:v,metadata:r.metadata}}))).flat()}}async function Le(t){return await Promise.all(t.map(async n=>JSON.parse(await ee({schema:n}))))}async function je(t,e){return await Promise.all(e.map(i=>t.fetchSchemaVersion({schema:i})))}async function Ve(t,e){let n=e.flatMap(({eventSpecification:{dataProductId:r}})=>r?[r]:[]);return(await Promise.all(n.map(r=>t.fetchDataProduct({dataProductId:r})))).map(r=>r.data[0]&&{...r.data[0],sourceApplications:r.includes.sourceApplications||[]}).filter(ri)}function We(t,e){let n=t.reduce((o,r)=>(o[r.id]={...r},o),{});return e.map(o=>{let r=n[o.eventSpecification.dataProductId],a=o.sourceApplicationIds.flatMap(s=>r?.sourceApplications.find(p=>p.id===s)||[]);return{...o,eventSpecification:{...o.eventSpecification,dataProductName:r?.name||""},sourceApplications:a}})}function ri(t){return!!t}async function ke(t,e,n){let i=e.event?.schema?.properties?.type?.enum?.[0];return n.match(ae)?{self:I(n),isEcomTemplateSchema:i}:await t.fetchSchemaVersion({schema:n})}function Ne(t){return t.reduce((n,i)=>{let o=i.eventSpecification.id;return i.entities.forEach(({source:r,minCardinality:a,maxCardinality:s})=>{if(typeof a<"u"||typeof s<"u"){let p={minCardinality:a,maxCardinality:s};n[o]=n[o]||{},n[o][r]=p}}),n},{})}function ai(t){return{self:{...I(t)}}}var si="SNOWPLOW_CONSOLE_API_KEY_ID",ci="SNOWPLOW_CONSOLE_API_KEY";function _e(t){return t.length!==0}function Lt(t){return JSON.stringify(t,null,2)}function Ge(t){let e={organizationId:t.organizationId,tracker:t.tracker,language:t.language,outpath:t.outpath};return Object.assign({igluCentralSchemas:[],dataStructures:[],repositories:[],eventSpecificationIds:[],dataProductIds:[]},e)}function pi(t){switch(t){case"typescript":return`${B}${pt}`;case"javascript":return`${B}${ct}`;case"json":return`${B}${ut}`;default:return""}}var Ue=t=>(0,y.existsSync)(t)&&!(0,y.lstatSync)(t).isDirectory(),ui=t=>B+t,di=t=>({isTS:t.endsWith(pt),isJSON:t.endsWith(ut),isJS:t.endsWith(ct)}),Vt=t=>({configDir:(0,E.dirname)(t),configPath:t,...di(t)});function A(t){let e=(0,E.isAbsolute)(t)?t:(0,E.resolve)(process.cwd(),t);if(Ue(e))return Vt(e);if(!(0,y.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]=
|
|
41
|
-
`,
|
|
40
|
+
cwd: ${process.cwd()}`);let[n]=ne.map(i=>(0,E.resolve)(e,ui(i))).filter(Ue);return Vt(typeof n!="string"?e:n)}function Et(t,e){let n=T.getFormat(),i=pi(n),o=(0,E.resolve)(e,i),r=`const config = ${Wt.default.inspect(t,!1,null)}
|
|
41
|
+
`,a=`type SnowtypeConfig = {
|
|
42
42
|
tracker: "${C.trackerTemplates.join('" | "')}";
|
|
43
43
|
language: "${C.languageIds.join('" | "')}";
|
|
44
44
|
outpath: string;
|
|
45
45
|
organizationId?: string;
|
|
46
46
|
igluCentralSchemas?: string[];
|
|
47
|
+
repositories?: string[];
|
|
47
48
|
dataStructures?: string[];
|
|
48
49
|
eventSpecificationIds?: string[];
|
|
49
50
|
dataProductIds?: string[];
|
|
@@ -53,88 +54,89 @@ cwd: ${process.cwd()}`);let[n]=ee.map(i=>(0,k.resolve)(e,ii(i))).filter(_e);retu
|
|
|
53
54
|
instructions?: boolean;
|
|
54
55
|
validations?: boolean;
|
|
55
56
|
disallowDevSchemas?: boolean;
|
|
57
|
+
deprecateOnlyOnProdAvailableUpdates?: boolean
|
|
56
58
|
}
|
|
57
|
-
update?: {
|
|
59
|
+
update?: {
|
|
58
60
|
regenerateOnUpdate?: boolean;
|
|
59
61
|
maximumBump?: "major" | "minor" | "patch";
|
|
60
62
|
showOnlyProdUpdates?: boolean;
|
|
61
63
|
}
|
|
62
|
-
patch?: {
|
|
64
|
+
patch?: {
|
|
63
65
|
regenerateOnPatch?: boolean;
|
|
64
66
|
}
|
|
65
67
|
}
|
|
66
68
|
}
|
|
67
69
|
}
|
|
68
|
-
`,s=`const config: SnowtypeConfig = ${
|
|
69
|
-
`,
|
|
70
|
-
`))}function
|
|
71
|
-
`,
|
|
72
|
-
`+
|
|
70
|
+
`,s=`const config: SnowtypeConfig = ${Wt.default.inspect(t,!1,null)}
|
|
71
|
+
`,p="module.exports = config;",c="export default config;";return n==="json"?(0,y.writeFileSync)(o,Lt(t)):(0,y.writeFileSync)(o,(n==="typescript"?[a,s,c]:[r,p]).join(`
|
|
72
|
+
`))}function Ut(t){let e=(0,y.statSync)(t,{throwIfNoEntry:!1});return e===void 0?!1:e.isFile()}function Mt(t){return(0,y.readFileSync)(t,{encoding:"utf-8"})}var li=async t=>(await(0,Nt.require)(t,__filename)).default;async function M(t){let{configPath:e,isJS:n,isJSON:i,isTS:o}=A(t),r;return o?(r=await li(e),T.setFormat("typescript")):n?(r=(await import(e)).default,T.setFormat("javascript")):i&&(r=JSON.parse(Mt(e)),T.setFormat("json")),typeof r=="function"&&(r=await r()),r}function He(t){return JSON.parse(Mt(t))}async function ze(t,e){t.debug("Checking for existing configuration.."),await _t(!0,e),t.success("Valid configuration found")}async function _t(t,e){let{configPath:n,isJS:i,isJSON:o,isTS:r}=A(e),a=o===!0||r===!0||i===!0,s=r===!1&&i===!1&&o===!1,p;if(r?p=(await(0,Nt.require)(n,__filename)).default:i?p=(await import(n)).default:o&&(p=JSON.parse(Mt(n))),typeof p=="function"&&(p=await p()),t){if(s)throw new Q;W(p)}else if(a)try{throw W(p),new z}catch(c){if(c instanceof z)throw c}}function Be(t){return{javascript:".js","javascript-gtm":".js",typescript:".ts",kotlin:".kt",swift:".swift",go:".go",dart:".dart"}[t]||""}function Je(t,e){let n={eventSpecifications:{}};t.forEach(o=>{n.eventSpecifications[o.eventSpecification.id]=o.version});let i=(0,E.resolve)(e,dt);try{(0,y.writeFileSync)(i,JSON.stringify(n,null,2))}catch{throw new it}}function Ke(t,e,n){let i=Object.entries(t);i.length>0&&n.success("Available Event Specification Updates"),i.forEach(([o,r])=>{let a=`${o}: version ${r.previous}`,s=`${o}: version ${r.next}`;n.diff(a,s),r.devOnlySchema.length>0&&(n.warn("This Event Specification uses schema that are not in production."),n.warn(r.devOnlySchema.join(" ")))}),e.length>0&&n.success("Available Data Structures Updates"),e.forEach(o=>{let r=`${o.previous}`,a=`${o.next}`;if(n.diff(r,a),o.nextReason==="patch"&&n.warn("The most recent version of this schema has been patched. Possible update required."),o.nextEnv==="DEV"){let s=o.next.split("/").pop();n.warn(`This data structure version (${s}) is not in production.`)}})}function qe(t){let e=t.optsWithGlobals();return{...e,apiKeyId:e.apiKeyId||process.env[si],apiKey:e.apiKey||process.env[ci]}}function _(t){return!!(Array.isArray(t)&&!t.length)}function U(t){return[...new Set(t)]}function Xe(t){let e=U(t);return e.sort(),e}function gi(t){return t.flatMap(e=>{let n=(0,C.joinIgluSchemaUrlParts)(e.eventSchema.self),i=e.entities.map(o=>o.source);return[n,...i]})}async function Ye(t,e,n,i){let o=t.map(s=>(0,C.joinIgluSchemaUrlParts)(s.self)),r=gi(e),a=await $t(n,U([...o,...r]));if(a.length>0&&(console.log(`
|
|
73
|
+
`,wt(`Generating code using schemas in DEV environment, tracking against those will result in failed events. Schemas in DEV:
|
|
74
|
+
`+a.join(`
|
|
73
75
|
`)),`
|
|
74
|
-
`),i))throw new
|
|
76
|
+
`),i))throw new at}function jt(t){return re.includes(t)}function Me({self:t}){let e=(0,C.joinIgluSchemaUrlParts)(t);return jt(e)}function Ze(t){return{standardEventSpecs:t.filter(e=>Me(e.eventSchema)),customEventSpecs:t.filter(e=>!Me(e.eventSchema))}}function Qe(t,e,n){if(typeof t=="string"&&typeof e=="string"&&t&&e)return{apiKeyId:t,apiKey:e};throw n.error(new st),new Error}var mi=["javascript","json","typescript"];function tn(t){return t in J}function en(t,e){let n=J[t];return Array.isArray(n)?n.map(o=>o.value).includes(e):!1}function nn(t){return mi.includes(t)}function on(){return{withVerbosity:e=>({success:i=>{console.log(xe(i))},warn:i=>{console.log(wt(i))},log:i=>{console.log(Pe(i))},diff:(i,o)=>{console.log(Oe(i,o))},debug:i=>{e===!0&&console.log(Ce(JSON.stringify(i)))},error:i=>{console.log(Ae(i.message)),e===!0&&console.log(i)}})}}function O(t,e){return async(n,i)=>{let o=qe(i),r=on(),a=we(),s=r.withVerbosity(o.verbose),{apiKeyId:p,apiKey:c}=Qe(o.apiKeyId,o.apiKey,s);if(e!=="init")try{let d=n.config||process.cwd();await ze(s,d)}catch(d){rn(d,s,a)}return t({apiKeyId:p,apiKey:c},s,a,n).then(()=>an(a)).catch(d=>{rn(d,s,a)})}}function rn(t,e,n){throw an(n),e.error(t),t}function an(t){t.isSpinning()===!0&&t.stop(!0)}var fi={type:"password",message:"Enter your Snowplow organization ID:",mask:!0,validate:_e},hi={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"},{value:"snowplow-flutter-tracker",name:"Flutter Tracker"}]},Si={type:"select",message:"Select the format to use:",choices:[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"},{value:"json",name:"JSON"}]},vi={type:"input",message:"Enter the directory for Snowtype output:",default:"./snowtype"},yi=t=>({type:"select",message:"Select the language to use:",choices:t});async function wi(t,e){e.debug("Checking for existing configuration file.."),await _t(!1,process.cwd());let n=t.organizationId||await(0,b.password)(fi),i=t.tracker||await(0,b.select)(hi);if(!tn(i))throw new L("tracker",i);let o=J[i],r;if(o.length===1){let p=o[0];if(typeof p>"u")throw new et("Missing language entry.");r=p.value}else r=t.language||await(0,b.select)(yi(o));if(!en(i,r))throw new L("language",r);let a=await(0,b.select)(Si);if(!nn(a))throw new L("format",a);T.setFormat(a);let s=t.outpath||await(0,b.input)(vi);return e.debug("Assembling initialization options.."),{organizationId:n,tracker:i,language:r,format:a,outpath:s}}async function Ii(t,e,n,i){let o=await wi(i,e);n.setSpinnerTitle("Initialising..."),n.isSpinning()===!1&&n.start(),e.debug("Creating configuration with options: ".concat(JSON.stringify(o)));let r=Ge(o);if(W(r),!await new P({...t,organizationId:r.organizationId}).authenticate())throw new j;e.success("Authentication succeeded"),Et(r,process.cwd()),e.success("Configuration created")}var Gt=O(Ii,"init");var Pn=require("path");var Ot=require("path"),wn=require("fs"),In=require("mkdirp"),En=require("@snowplow/snowtype-core");var xt=require("path"),sn=require("mkdirp"),zt=require("fs"),Pt=require("@snowplow/snowtype-core");var Ei="instructions.md",cn="assets";async function pn(t,e,n,i,o){sn.mkdirp.sync((0,xt.resolve)(i,cn));let r=[],a=Ai(e,n,o),s=[];await Promise.all(e.map(async c=>{let d={triggers:await $e(t,c.triggers),instructionsHeading:Ht(c.eventSpecification.name)};s.push(Ht(c.eventSpecification.name));let m=bi(c.propertyRules),v=Di(c.entities);Pi(c.eventSpecification.id,d,i),r.push(xi({eventStructure:c.eventSchema.self,entitiesStructures:c.entitiesSchemas?.map(l=>l.original.self)||[],name:c.eventSpecification.name,id:c.eventSpecification.id,dataProductId:c.eventSpecification.dataProductId,version:c.version,triggerInstructions:d.triggers,linkToCode:a[c.eventSpecification.id],formattedPropertyRules:m,formattedCardinalityRules:v,organizationId:t.organizationId,sourceApplications:c.sourceApplications}))}));let p=`
|
|
75
77
|
# Implementation instructions
|
|
76
78
|
|
|
77
79
|
_A guide on how to implement tracking for the generated Event Specifications._
|
|
78
80
|
|
|
79
81
|
**Table of contents:**
|
|
80
|
-
${
|
|
82
|
+
${s.map(c=>`- [${c.instructionsTitle}](#${c.instructionsLink})`).join(`
|
|
81
83
|
`)}
|
|
82
84
|
|
|
83
85
|
${r.join(`
|
|
84
86
|
`)}
|
|
85
|
-
`;(0,
|
|
86
|
-
## [${
|
|
87
|
+
`;(0,zt.writeFileSync)((0,xt.resolve)(i,Ei),p,"utf-8")}function xi({eventStructure:t,entitiesStructures:e,name:n,id:i,dataProductId:o,version:r,triggerInstructions:a,linkToCode:s,formattedPropertyRules:p,formattedCardinalityRules:c,organizationId:d,sourceApplications:m}){let v="_N/A_";return`
|
|
88
|
+
## [${Ht(n).instructionsTitle}](${Ci(d,o,i)})
|
|
87
89
|
|
|
88
90
|
| | |
|
|
89
91
|
| ----------- | ----------- |
|
|
90
92
|
| **Id** | ${i} |
|
|
91
93
|
| **Version** | ${r} |
|
|
92
94
|
| **Data Product Id** | ${o} |
|
|
93
|
-
| **Source Application/s** | ${m.length?m.map(
|
|
95
|
+
| **Source Application/s** | ${m.length?m.map(l=>l.name).join(", "):"None selected"} |
|
|
94
96
|
| **Event Data Structure** | ${t.name}/${t.version} |
|
|
95
|
-
| **Entity Data Structures** | ${e.map(
|
|
96
|
-
| **Code** | ${
|
|
97
|
+
| **Entity Data Structures** | ${e.map(l=>`${l.name}/${l.version}`).sort().join(", ")} |
|
|
98
|
+
| **Code** | ${s} |
|
|
97
99
|
|
|
98
100
|
${p.length>0?`### Implementation Instructions for ${t.name} event properties
|
|
99
101
|
|
|
100
102
|
#### Property Rules
|
|
101
103
|
| Name | Required | Description | Exact value(s) expected |
|
|
102
104
|
| ----------- | ----------- | ----------- | ----------- |
|
|
103
|
-
${p.map(
|
|
105
|
+
${p.map(l=>Object.values(l).join(" | ")).join(`
|
|
104
106
|
`)}
|
|
105
107
|
`:""}
|
|
106
108
|
${c.length>0?`
|
|
107
109
|
#### Entity Cardinality Rules
|
|
108
110
|
| Name | Required | Number of entities |
|
|
109
111
|
| ----------- | ----------- | ----------- |
|
|
110
|
-
${c.map(
|
|
112
|
+
${c.map(l=>Object.values(l).join(" | ")).join(`
|
|
111
113
|
`)}
|
|
112
114
|
`:""}
|
|
113
115
|
|
|
114
|
-
${
|
|
115
|
-
### Trigger ${
|
|
116
|
+
${a.map((l,w,g)=>`
|
|
117
|
+
### Trigger ${g.length!==1?w+1:""}
|
|
116
118
|
|
|
117
119
|
#### Screenshot
|
|
118
|
-
${
|
|
120
|
+
${l.imageBuffer?`[<img src="./assets/${i}_${w}.${l.imageExtension}" width="550"/>](./assets/${i}_${w}.${l.imageExtension})`:v}
|
|
119
121
|
|
|
120
122
|
#### In which application(s) does this trigger apply?
|
|
121
123
|
|
|
122
|
-
${
|
|
124
|
+
${l.appIds&&l.appIds.length?l.appIds.map(G=>"`"+G+"` "):v}
|
|
123
125
|
|
|
124
126
|
#### The URL of the page on which this event specification triggers:
|
|
125
127
|
|
|
126
|
-
${
|
|
128
|
+
${l.url||v}
|
|
127
129
|
|
|
128
130
|
#### Notes
|
|
129
131
|
|
|
130
|
-
${
|
|
131
|
-
`).join("")}`}function
|
|
132
|
+
${l.description||v}
|
|
133
|
+
`).join("")}`}function Pi(t,e,n){e.triggers.forEach((i,o)=>{i.imageBuffer&&(0,zt.writeFileSync)((0,xt.resolve)(n,cn,t+"_"+o+"."+i.imageExtension),i.imageBuffer,"binary")})}function Ci(t,e,n){return`https://console.snowplowanalytics.com/${t}/data-products/${e}/event-specifications/${n}`}function Ai(t,e,n){let i=t.reduce((o,{eventSpecification:{id:r}})=>(o[r]="",o),{});return Object.keys(i).forEach(o=>{let r=e.findIndex(a=>a.match((0,Pt.createEventSpecificationInstructionsIdentifier)(o)));i[o]=r!==-1?`[Link](./${n+"#L"+r})`:"N/A"}),i}function Ht(t){let e=t;return{instructionsTitle:e,instructionsLink:Oi(e)}}function Oi(t){return t.toLowerCase().replace(/[^a-z\d\s-]/g," ").replace(/\s+/g," ").trim().replace(/-{2,}|\s/g,"-")}function bi(t){return t?Object.entries(t.properties||{}).map(e=>{let[n,i]=e,o=t.required?.includes(n)?"\u2705":"\u274C",r=i.description||"-",a=i.enum?i.enum.map(s=>`\`${s}\``).join(" or "):"-";return{name:n,isRequired:o,description:r,expectedValues:a}}):[]}function Di(t){return t?t.map(({source:e,minCardinality:n,maxCardinality:i})=>{let{name:o}=(0,Pt.splitIgluSchemaUrlParts)(e),r=typeof n<"u"&&n>0?"\u2705":"\u274C",a=Ti(n,i);return{name:o,isRequired:r,formattedCardinalityValues:a}}):[]}function Ti(t,e){return typeof t>"u"?"`any`":typeof e<"u"?t===e?`Exactly \`${t}\``:`Between \`${t}\` and \`${e}\``:`At least \`${t}\``}var xn=f(require("fs-extra"));var dn=require("fs"),ln=require("path"),gn=f(require("util"));function mn(t,e,n,i){let o=e==="typescript"?"ts":"js";(0,dn.writeFileSync)((0,ln.resolve)(t,`validations.${o}`),`${o==="ts"?`
|
|
132
134
|
import { AnySchema } from "ajv";
|
|
133
135
|
export type CardinalityRule = { minCardinality?: number; maxCardinality?: number };
|
|
134
136
|
type IgluUrl = string;
|
|
135
137
|
type EventSpecificationId = string;
|
|
136
138
|
`:""}
|
|
137
|
-
export const entityRules${o==="ts"?": Record<EventSpecificationId, Record<IgluUrl, CardinalityRule>>":""} = ${
|
|
138
|
-
export const schemasObject${o==="ts"?": Record<IgluUrl | EventSpecificationId, AnySchema | Record<IgluUrl, AnySchema>>":""} = ${
|
|
139
|
-
`),
|
|
140
|
-
`),await t.parseAsync(
|
|
139
|
+
export const entityRules${o==="ts"?": Record<EventSpecificationId, Record<IgluUrl, CardinalityRule>>":""} = ${un(i)}
|
|
140
|
+
export const schemasObject${o==="ts"?": Record<IgluUrl | EventSpecificationId, AnySchema | Record<IgluUrl, AnySchema>>":""} = ${un(n)}`,"utf-8")}function un(t){return gn.default.inspect(t,{showHidden:!1,depth:null,maxArrayLength:null})}function Bt(t){return Object.values(t).some(e=>ki(e)?Ri(e):Bt(e))}function ki(t){return typeof t=="object"&&t!==null&&Object.hasOwn(t,"$schema")}function Ri(t){return t.properties?Object.values(t.properties).some(e=>Object.hasOwn(e||{},"pattern")):!1}function fn(t,e){let n=Fi(t);$i(n,e)}function $i(t,e){Object.entries(t).map(([n,i])=>e.warn(`Event Specification ${n} includes entities that are also present in it's application context: ${i.join(", ")}`))}function Fi(t){let e={};return t.forEach(n=>{let i=n.entities.map(r=>r.source),o=n.sourceApplications.flatMap(r=>[...r.entities.enriched.map(a=>a.source),...r.entities.tracked.map(a=>a.source)]);i.forEach(r=>{o.includes(r)&&(e[n.eventSpecification.id]?e[n.eventSpecification.id]?.push(r):e[n.eventSpecification.id]=[r])})}),e}var Ct=f(require("fs/promises")),At=f(require("path")),hn=require("yaml");async function Sn(t,e=[]){let n=[];for(let i of e){let o=At.default.resolve(t,i),r=await vn(o),a=await Li(r);n.push(...a)}return n}async function Li(t){let e=[];for(let n of t){let{isJson:i}=yn(n),o=await Ct.default.readFile(n,{encoding:"utf-8"}),r=i?JSON.parse(o):(0,hn.parse)(o);ji(r)&&e.push(r.data)}return e}async function vn(t,e=[]){let n=await Ct.default.readdir(t);for(let i of n){let o=At.default.join(t,i),r=await Ct.default.stat(o),{isJson:a,isYaml:s}=yn(i);r.isDirectory()?e=await vn(o,e):(a||s)&&e.push(o)}return e}function ji(t){return typeof t=="object"&&t!==null&&"apiVersion"in t&&typeof t.apiVersion=="string"&&"resourceType"in t&&t.resourceType==="data-structure"}function yn(t){let e=At.default.extname(t);return e.match(/\.yml|\.yaml/)?{isYaml:!0,isJson:!1}:e.match(".json")?{isYaml:!1,isJson:!0}:{isYaml:!1,isJson:!1}}async function Vi(t){let{config:e,...n}=t,i=await M(e||process.cwd());return V(i),i.options.commands.generate={...i.options.commands.generate,...n},i}async function X(t,e,n,i){let{dataProductIds:o,dataStructures:r,igluCentralSchemas:a,eventSpecificationIds:s,repositories:p,language:c,tracker:d,outpath:m,organizationId:v,options:{commands:{generate:l}}}=await Vi(i),{configDir:w}=A(i.config||process.cwd());n.setSpinnerTitle("Generating..."),n.isSpinning()===!1&&n.start(),_(r)&&_(a)&&_(s)&&_(o)&&_(p)&&e.warn("Data Structures, Schemas and Event Specifications are empty.");let g=new P({...t,organizationId:v});if(!await g.authenticate())throw new j;let x=await It(g,o),H=Xe([...x,...s]),{eventSpecificationsWithId:R}=await Fe(g,H,e),Dt=be(R);l.deprecateOnlyOnProdAvailableUpdates&&(Dt=await Te(Dt,g));let On=await Ve(g,R),Y=We(On,R);fn(Y,e);let{customEventSpecs:bn,standardEventSpecs:Dn}=Ze(Y),Tn=Dn.flatMap(Tt=>Tt.entities.map(Ln=>Ln.source));de(R)&&d==="@snowplow/browser-tracker"&&e.log("You are generating Snowplow Ecommerce events. You would need to install `@snowplow/browser-plugin-snowplow-ecommerce`."),l.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 kn=await Le(a),Xt=await je(g,[...r,...Tn]),Rn=await Sn(w,p),Yt=!!(d==="@snowplow/browser-tracker"&&c.match(/javascript|typescript/));await Ye(Xt,Y,g,l.disallowDevSchemas);let $n={language:c,tracker:d,schemas:[...Rn,...kn,...Xt],eventSpecifications:bn,validations:Yt&&l.validations,eventSpecificationsInputMetadata:Dt},$=await(0,En.generate)($n);if(n.stop(!0),!$)throw new Z;e.success("Code generated, writing...");let Fn=$.lines.join(`
|
|
141
|
+
`),F=(0,Ot.resolve)(w,m);xn.default.removeSync((0,Ot.resolve)(F)),In.mkdirp.sync(F);let Zt=ie+Be(c);if((0,wn.writeFileSync)((0,Ot.resolve)(F,Zt),Fn),Je(R,F),Yt&&l.validations&&$.validationsSchemaObject){let Tt=Ne(R);mn(F,c,$.validationsSchemaObject,Tt),Bt($.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")}l.instructions&&await pn(g,Y,$.lines,F,Zt)}var Jt=O(X,"generate");async function Wi(t){let e=await M(t||process.cwd());return V(e),e}async function Ni(t,e,n,i){let o=await Wi(i.config),{options:{commands:{update:{maximumBump:r,regenerateOnUpdate:a,showOnlyProdUpdates:s},generate:p}}}=o;e.debug("Starting update process with options: ".concat(JSON.stringify(i)));let{configDir:c}=A(i.config||process.cwd()),d=(0,Pn.resolve)(c,o.outpath,dt),m=new P({...t,organizationId:o.organizationId});n.setSpinnerTitle("Checking for updates..."),n.isSpinning()===!1&&n.start();let v=await It(m,o.dataProductIds),l=U([...o.eventSpecificationIds,...v]),w={};if(!Ut(d)&&l.length>0)throw new ot;if(Ut(d)&&l.length>0){let x=He(d);w=await Se(m,l,x)}let g=await he(m,o.dataStructures,i.maximumBump||r,s);if((Object.entries(w).length>0||g.length>0)===!0){if(e.success("Available updates found!"),Ke(w,g,e),i.yes||a)return g.length>0&&(g.forEach(x=>{let H=o.dataStructures.indexOf(x.previous);o.dataStructures[H]=x.next}),Et(o,i.config||process.cwd())),e.debug("Applying the updates.."),X(t,e,n,{...p,...i.config&&{config:i.config}});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 Kt=O(Ni,"update");async function Ui(t){let{config:e,...n}=t;if(Object.values(n).every(o=>Array.isArray(o)&&o.length===0))throw new nt;let i=await M(e||process.cwd());return V(i),{patchOptions:n,generateOptions:i.options.commands.generate,regenerateOnPatch:i.options.commands.patch.regenerateOnPatch}}async function Mi(t,e,n,i){let{isJSON:o,configPath:r}=A(i.config||process.cwd());if(o===!1)throw new rt;let{patchOptions:a,generateOptions:s,regenerateOnPatch:p}=await Ui(i);return e.debug("Starting patch process with options: ".concat(JSON.stringify(a))),Object.entries(a).forEach(([d,m])=>{m.forEach(v=>{fe(d,v,r)})}),e.success("Configuration patched"),p?X(t,e,n,s):(e.log("Code is not generated yet for the patched configuration"),Promise.resolve(void 0))}var qt=O(Mi,"patch");var bt=require("@snowplow/snowtype-core");async function An(){await import("dotenv/config");let t=new D.Command;t.exitOverride(),t.version(N,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("-s, --apiKeyId <string>","Snowplow Console API key ID").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 D.Option("-t, --tracker <availableTrackers>","tracker to use").choices(bt.trackerTemplates)).addOption(new D.Option("-l, --language <availableLanguages>","language to use").choices(bt.languageIds)).option("-o, --outpath <string>","output path").action(Gt),t.command("update").description("Checks for latest version updates in Data Structures and Event Specifications.").option("-c, --config <string>","config file path").option("-y, --yes","updates all to latest without asking (caution: will ovewrite the configuration file)").addOption(new D.Option("-m, --maximumBump <'patch' | 'minor' | 'major'>","the maximum SchemaVer update to show an available update notification. Defaults to 'major'").choices(["patch","minor","major"])).action(Kt),t.command("generate").option("-c, --config <string>","config file path").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").option("--deprecateOnlyOnProdAvailableUpdates","show deprecation warnings only when there are PROD available schema updates").description("Generates tracking code based on configuration on the `snowtype.config.json` file.").action(Jt),t.command("patch").option("-c, --config <string>","config file path").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").option("-r, --repositories <repositories...>","repository path").action(qt),t.addHelpText("before",Ee()).addHelpText("after",`
|
|
142
|
+
`),await t.parseAsync(Cn.argv).catch(e=>{_i(e)})}function _i(t){if(!(t instanceof D.CommanderError&&["commander.help","commander.version","commander.helpDisplayed"].indexOf(t.code)>-1))throw t}An().then(()=>{}).catch(()=>{process.exitCode=1});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@snowplow/snowtype",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.2",
|
|
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.10.
|
|
16
|
+
"@snowplow/snowtype-core": "^0.10.2",
|
|
17
17
|
"chalk": "^4.1.2",
|
|
18
18
|
"cli-spinner": "^0.2.10",
|
|
19
19
|
"dotenv": "^16.3.1",
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"mime-types": "^2.1.35",
|
|
26
26
|
"mkdirp": "^3.0.1",
|
|
27
27
|
"semver": "^7.6.3",
|
|
28
|
-
"tsx": "^4.9.3"
|
|
28
|
+
"tsx": "^4.9.3",
|
|
29
|
+
"yaml": "^2.6.0"
|
|
29
30
|
},
|
|
30
31
|
"devDependencies": {
|
|
31
32
|
"@types/cli-spinner": "^0.2.3",
|