Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
Latest commit
293 lines (247 loc) · 11.2 KB
/
Copy pathscript.js
File metadata and controls
293 lines (247 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#!/usr/bin/env node
/**
* Lytics Schema Setup — Final Script
* Prompts for account ID and API key, then creates fields + mappings and publishes.
*/
consthttps=require("https");
constfs=require("fs");
constpath=require("path");
constreadline=require("readline");
constdotenv=require("dotenv")
dotenv.config()
constBASE_URL="https://api.lytics.io/v2/schema";
constcolors={
reset: "\x1b[0m",
bright: "\x1b[1m",
green: "\x1b[32m",
red: "\x1b[31m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
cyan: "\x1b[36m",
};
functioncolorize(text,color){
return`${color}${text}${colors.reset}`;
}
// ──────────────────────────────────────────────
// Interactive prompt helpers
// ──────────────────────────────────────────────
functionprompt(question,hidden=false){
constrl=readline.createInterface({
input: process.stdin,
output: process.stdout,
});
returnnewPromise((resolve)=>{
if(hidden){
// Hide input for API key
process.stdout.write(question);
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.setEncoding("utf8");
letvalue="";
process.stdin.on("data",functionhandler(ch){
if(ch==="\r"||ch==="\n"){
process.stdin.setRawMode(false);
process.stdin.pause();
process.stdin.removeListener("data",handler);
rl.close();
process.stdout.write("\n");
resolve(value);
}elseif(ch===""){
process.exit();// Ctrl+C
}elseif(ch===""||ch==="\b"){
if(value.length>0){
value=value.slice(0,-1);
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write(question+"*".repeat(value.length));
}
}else{
value+=ch;
process.stdout.write("*");
}
});
}else{
rl.question(question,(answer)=>{
rl.close();
resolve(answer.trim());
});
}
});
}
asyncfunctiongetCredentials(){
console.log(`\n${colorize("🔧 Lytics Schema Setup",colors.bright)}`);
console.log(colorize("─".repeat(50),colors.cyan));
// Read credentials from environment (dotenv loads .env.local if present).
letaccountId=process.env.LYTICS_ACCOUNT_ID
lettoken=process.env.LYTICS_ACCESS_TOKEN
consttable="user";
if(accountId)console.log(` ${colorize("Account ID:",colors.cyan)}${colorize("(loaded)",colors.green)}`);
if(token)console.log(` ${colorize("API Key :",colors.cyan)}${colorize("(loaded)",colors.green)}`);
// Prompt for any missing values
if(!accountId){
accountId=awaitprompt(colorize(" Account ID : ",colors.cyan));
}
if(!token){
token=awaitprompt(colorize(" API Key : ",colors.cyan),true);
}
if(!accountId){
console.error(colorize("\n✗ Account ID is required.",colors.red));
process.exit(1);
}
if(!token){
console.error(colorize("\n✗ API Key is required.",colors.red));
process.exit(1);
}
return{ accountId, token, table };
}
// ──────────────────────────────────────────────
// HTTP helpers
// ──────────────────────────────────────────────
functionrequest(method,url,authToken,body,accountId){
returnnewPromise((resolve,reject)=>{
consturlObj=newURL(url);
if(accountId)urlObj.searchParams.set("account_id",accountId);
constpayload=body ? JSON.stringify(body) : "";
constoptions={
hostname: urlObj.hostname,
path: urlObj.pathname+urlObj.search,
method,
headers: {
Authorization: authToken,
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(payload),
},
};
constreq=https.request(options,(res)=>{
letdata="";
res.on("data",(chunk)=>(data+=chunk));
res.on("end",()=>{
letparsed;
try{parsed=JSON.parse(data);}catch{parsed=data;}
resolve({statusCode: res.statusCode,body: parsed});
});
});
req.on("error",reject);
if(payload)req.write(payload);
req.end();
});
}
constpost=(url,token,body,accountId)=>request("POST",url,token,body,accountId);
// ──────────────────────────────────────────────
// API calls
// ──────────────────────────────────────────────
functioncreateField(token,table,body,accountId){
returnpost(`${BASE_URL}/${table}/field`,token,body,accountId);
}
functioncreateMapping(token,table,body,accountId){
returnpost(`${BASE_URL}/${table}/mapping`,token,body,accountId);
}
functionpublishSchema(token,table,accountId){
returnpost(`${BASE_URL}/${table}/publish`,token,{
tag: "auto-publish",
description: "Auto-published schema changes via finalscript",
},accountId);
}
functionlogResult(ok,errorBody){
// console.log("🚀 ~ logResult ~ errorBody:", errorBody)
console.log(ok
? colorize("Done"," ✓ ",colors.green) :
`${colorize("Error:",colors.red)}${errorBody?.errors?.[0]?.message||"Unknown error"}`
);
}
// ──────────────────────────────────────────────
// Create all fields and mappings
// ──────────────────────────────────────────────
asyncfunctionrecreateEntries(token,table,entries,accountId){
console.log(`\n${colorize("🔧 Creating fields and mappings...",colors.bright)}`);
console.log(colorize("─".repeat(50),colors.cyan));
constresults=[];
for(leti=0;i<entries.length;i++){
const{field: fieldDef,mapping: mappingDef}=entries[i];
constfieldName=fieldDef?.id||`entry_${i+1}`;
constprogress=colorize(`[${i+1}/${entries.length}]`,colors.cyan);
console.log(`\n${progress} 📦 ${colorize(fieldName,colors.bright)}`);
letfieldResult=null;
if(fieldDef){
process.stdout.write(` ${colorize("→",colors.blue)} Creating field... `);
fieldResult=awaitcreateField(token,table,fieldDef,accountId);
logResult([200,201].includes(fieldResult.statusCode),fieldResult.body);
}
letmappingResult=null;
if(mappingDef){
process.stdout.write(` ${colorize("→",colors.blue)} Creating mapping... `);
mappingResult=awaitcreateMapping(token,table,mappingDef,accountId);
logResult([200,201].includes(mappingResult.statusCode),mappingResult.body);
}
results.push({ fieldName, fieldResult, mappingResult });
}
returnresults;
}
asyncfunctionpublishDraft(token,table,accountId){
console.log(`\n${colorize("─".repeat(50),colors.cyan)}`);
console.log(`${colorize("🚀 Publishing Schema...",colors.bright)}`);
constres=awaitpublishSchema(token,table,accountId);
constok=[200,201,204].includes(res.statusCode);
console.log(ok
? colorize("✓ Published successfully!",colors.green)
: colorize("✗ Publish failed",colors.red)
);
if(!ok){
console.log(`\n${colorize("Error:",colors.red)}${res.body?.errors?.[0]?.message||"Unknown error"}`);
console.log(`${colorize("💡 Tip:",colors.yellow)} Manually publish via Lytics UI:`);
console.log(` Conductor → Schema → Versions → Publish Changes`);
}
returnres;
}
functionprintSummary(results){
console.log(`\n${colorize("═".repeat(50),colors.cyan)}`);
console.log(`${colorize("📊 SUMMARY",colors.bright)}`);
console.log(`${colorize("═".repeat(50),colors.cyan)}`);
letsuccess=0,failed=0;
for(constrofresults){
constfOk=!r.fieldResult||[200,201].includes(r.fieldResult.statusCode);
constmOk=!r.mappingResult||[200,201].includes(r.mappingResult.statusCode);
if(fOk&&mOk){
console.log(` ${colorize("✓",colors.green)}${r.fieldName}`);
success++;
}else{
console.log(` ${colorize("✗",colors.red)}${r.fieldName}`);
failed++;
}
}
console.log(`\n${colorize(`Total: ${results.length}`,colors.cyan)} | ${colorize(`✓ Success: ${success}`,colors.green)} | ${colorize(`✗ Failed: ${failed}`,colors.red)}\n`);
}
// ──────────────────────────────────────────────
// Entry point
// ──────────────────────────────────────────────
asyncfunctionmain(){
const{ accountId, token, table }=awaitgetCredentials();
console.log(`\n${colorize("📍 Target:",colors.cyan)} table=${colorize(table,colors.bright)}, account=${colorize(accountId,colors.bright)}`);
// Load fields.json + mappings.json from same directory
letentries;
try{
constfields=JSON.parse(fs.readFileSync(path.resolve(__dirname,"fields.json"),"utf8"));
constmappings=JSON.parse(fs.readFileSync(path.resolve(__dirname,"mappings.json"),"utf8"));
constmappingsByField={};
for(constmofmappings)mappingsByField[m.field]=m;
entries=fields.map((f)=>({
field: f,
mapping: mappingsByField[f.id]||null,
}));
console.log(`${colorize("✓",colors.green)} Loaded ${colorize(String(entries.length),colors.bright)} entries from ${colorize("fields.json",colors.cyan)} + ${colorize("mappings.json",colors.cyan)}`);
}catch(err){
console.error(`${colorize("✗",colors.red)} Failed to load fields.json / mappings.json: ${err.message}`);
process.exit(1);
}
// Phase 1: create all fields and mappings
constresults=awaitrecreateEntries(token,table,entries,accountId);
// Phase 2: publish
awaitpublishDraft(token,table,accountId);
printSummary(results);
}
main().catch((err)=>{
console.error(`\n${colorize("✗ Fatal Error",colors.red)}`);
console.error(`${colorize("Message:",colors.red)}${err.message}`);
console.error(err.stack);
process.exit(1);
});