@scout9/app 1.0.0-alpha.0.2.7 → 1.0.0-alpha.0.2.9

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.
@@ -23,7 +23,7 @@ var Stream = require('node:stream');
23
23
  var node_string_decoder = require('node:string_decoder');
24
24
  var readline = require('node:readline');
25
25
  var process$2 = require('node:process');
26
- var macros = require("./macros-eff64992.cjs");
26
+ var macros = require("./macros-44f1f872.cjs");
27
27
  var node_os = require('node:os');
28
28
  var promises = require('fs/promises');
29
29
 
@@ -35937,7 +35937,7 @@ function _loadUserPackageJson() {
35937
35937
  targetPkgUrl = isTest ? packageTestJsonUrl : packageJsonUrl;
35938
35938
  _context2.t0 = JSON;
35939
35939
  _context2.next = 10;
35940
- return fs__default["default"].readFile(new URL(targetPkgUrl, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('dev-170fa3f5.js', document.baseURI).href))), 'utf-8');
35940
+ return fs__default["default"].readFile(new URL(targetPkgUrl, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('dev-73437873.js', document.baseURI).href))), 'utf-8');
35941
35941
  case 10:
35942
35942
  _context2.t1 = _context2.sent;
35943
35943
  pkg = _context2.t0.parse.call(_context2.t0, _context2.t1);
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var spirits = require("./spirits-76855e30.cjs");
4
- var dev = require("./dev-170fa3f5.cjs");
5
- var macros = require("./macros-eff64992.cjs");
4
+ var dev = require("./dev-73437873.cjs");
5
+ var macros = require("./macros-44f1f872.cjs");
6
6
  var require$$0 = require('fs');
7
7
  var require$$2$1 = require('events');
8
8
  var require$$1 = require('path');
@@ -29483,7 +29483,7 @@ class Body {
29483
29483
  }
29484
29484
  const {
29485
29485
  toFormData
29486
- } = await Promise.resolve().then(function () { return require("./multipart-parser-bd1fae8a.cjs"); });
29486
+ } = await Promise.resolve().then(function () { return require("./multipart-parser-ca328d7d.cjs"); });
29487
29487
  return toFormData(this.body, ct);
29488
29488
  }
29489
29489
 
@@ -41892,7 +41892,7 @@ function _loadUserPackageJson() {
41892
41892
  targetPkgUrl = isTest ? packageTestJsonUrl : packageJsonUrl;
41893
41893
  _context.t0 = JSON;
41894
41894
  _context.next = 10;
41895
- return fs__default["default"].readFile(new URL(targetPkgUrl, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-44e73470.js', document.baseURI).href))), 'utf-8');
41895
+ return fs__default["default"].readFile(new URL(targetPkgUrl, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-08dc13e8.js', document.baseURI).href))), 'utf-8');
41896
41896
  case 10:
41897
41897
  _context.t1 = _context.sent;
41898
41898
  pkg = _context.t0.parse.call(_context.t0, _context.t1);
@@ -43098,7 +43098,7 @@ var ProjectFiles = /*#__PURE__*/function () {
43098
43098
  return ProjectFiles;
43099
43099
  }();
43100
43100
 
43101
- var __filename$1 = node_url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-44e73470.js', document.baseURI).href)));
43101
+ var __filename$1 = node_url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-08dc13e8.js', document.baseURI).href)));
43102
43102
  var __dirname$1 = path__default["default"].dirname(__filename$1);
43103
43103
  function zipDirectory(source, out) {
43104
43104
  var archive = archiver$1('tar', {
@@ -43313,7 +43313,7 @@ function _buildApp() {
43313
43313
  case 11:
43314
43314
  _context4.t0 = JSON;
43315
43315
  _context4.next = 14;
43316
- return fs__default["default"].readFile(new URL(templatePackagePath, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-44e73470.js', document.baseURI).href))), 'utf-8');
43316
+ return fs__default["default"].readFile(new URL(templatePackagePath, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-08dc13e8.js', document.baseURI).href))), 'utf-8');
43317
43317
  case 14:
43318
43318
  _context4.t1 = _context4.sent;
43319
43319
  packageTemplate = _context4.t0.parse.call(_context4.t0, _context4.t1);
package/dist/index.cjs CHANGED
@@ -2,10 +2,10 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var index = require("./index-44e73470.cjs");
6
- var dev = require("./dev-170fa3f5.cjs");
5
+ var index = require("./index-08dc13e8.cjs");
6
+ var dev = require("./dev-73437873.cjs");
7
7
  require("./spirits-76855e30.cjs");
8
- require("./macros-eff64992.cjs");
8
+ require("./macros-44f1f872.cjs");
9
9
  require('fs');
10
10
  require('events');
11
11
  require('path');
@@ -4242,7 +4242,7 @@ var WorkflowResponseMessageApiResponse = z.union([z.string(), z.object({
4242
4242
  /**
4243
4243
  * The workflow response object slot
4244
4244
  */
4245
- var InstructionSchema = z.union([z.string(), InstructionObjectSchema, z.array(z.string()), z.array(InstructionObjectSchema)]);
4245
+ var InstructionSchema = z.union([z.string(), InstructionObjectSchema, z.array(z.union([z.string(), InstructionObjectSchema]))]);
4246
4246
 
4247
4247
  /**
4248
4248
  * Base follow up schema to follow up with the client
@@ -2,9 +2,9 @@
2
2
 
3
3
  require('node:fs');
4
4
  require('node:path');
5
- var index = require("./index-44e73470.cjs");
5
+ var index = require("./index-08dc13e8.cjs");
6
6
  require("./spirits-76855e30.cjs");
7
- require("./dev-170fa3f5.cjs");
7
+ require("./dev-73437873.cjs");
8
8
  require('util');
9
9
  require('stream');
10
10
  require('path');
@@ -25,7 +25,7 @@ require('node:stream');
25
25
  require('node:string_decoder');
26
26
  require('node:readline');
27
27
  require('node:process');
28
- require("./macros-eff64992.cjs");
28
+ require("./macros-44f1f872.cjs");
29
29
  require('node:os');
30
30
  require('fs/promises');
31
31
  require('constants');
package/dist/schemas.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var macros = require("./macros-eff64992.cjs");
5
+ var macros = require("./macros-44f1f872.cjs");
6
6
 
7
7
 
8
8
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dev = require("./dev-170fa3f5.cjs");
5
+ var dev = require("./dev-73437873.cjs");
6
6
  require("./spirits-76855e30.cjs");
7
7
  require('util');
8
8
  require('stream');
@@ -26,7 +26,7 @@ require('node:stream');
26
26
  require('node:string_decoder');
27
27
  require('node:readline');
28
28
  require('node:process');
29
- require("./macros-eff64992.cjs");
29
+ require("./macros-44f1f872.cjs");
30
30
  require('node:os');
31
31
  require('fs/promises');
32
32
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scout9/app",
3
- "version": "1.0.0-alpha.0.2.7",
3
+ "version": "1.0.0-alpha.0.2.9",
4
4
  "description": "Build and deploy your Scout9 app for SMS auto replies",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -5,7 +5,8 @@ import bodyParser from 'body-parser';
5
5
  import colors from 'kleur';
6
6
  import { config as dotenv } from 'dotenv';
7
7
  import { Configuration, Scout9Api } from '@scout9/admin';
8
- import { EventResponse, WorkflowEventSchema, WorkflowResponseSchema } from '@scout9/app';
8
+ import { EventResponse } from '@scout9/app';
9
+ import { WorkflowEventSchema, WorkflowResponseSchema } from '@scout9/app/schemas';
9
10
  import path, { resolve } from 'node:path';
10
11
  import fs from 'node:fs';
11
12
  import https from 'node:https';
@@ -97,7 +98,7 @@ const handleError = (e, res = undefined) => {
97
98
  if ('stack' in e) {
98
99
  console.log(colors.grey(e.stack));
99
100
  }
100
- console.log(colors)
101
+ console.log(colors);
101
102
  if (res) {
102
103
  res.writeHead(code, {'Content-Type': 'application/json'});
103
104
  res.end(JSON.stringify({
@@ -108,6 +109,31 @@ const handleError = (e, res = undefined) => {
108
109
  }
109
110
  };
110
111
 
112
+ const handleZodError = ({error, res = undefined, code = 500, status, name, bodyLabel = 'Provided Input', body = undefined, action = ''}) => {
113
+ res?.writeHead?.(code, {'Content-Type': 'application/json'});
114
+ if (error instanceof ZodError) {
115
+ const formattedErrors = JSON.stringify(error.errors, null, 2);
116
+ res?.end?.(JSON.stringify({
117
+ status,
118
+ errors: formattedErrors
119
+ }));
120
+ console.log(colors.red(`${colors.bold(`${name}`)}:`));
121
+ if (body) {
122
+ console.log(colors.grey(`${bodyLabel}:`));
123
+ console.log(colors.grey(JSON.stringify(body, null, 2)));
124
+ }
125
+ console.log(colors.red(`${action}${formattedErrors}`));
126
+ } else {
127
+ console.error(error);
128
+ error.message = `${name}: ` + error.message;
129
+ res?.end?.(JSON.stringify({
130
+ status,
131
+ errors: [error.message]
132
+ }));
133
+ throw new Error(`${name}: Provided error was not a ZodError`);
134
+ }
135
+ };
136
+
111
137
  const makeRequest = async (options, maxRedirects = 10) => {
112
138
  return new Promise((resolve, reject) => {
113
139
 
@@ -168,34 +194,49 @@ if (dev) {
168
194
  // Root application POST endpoint will run the scout9 app
169
195
  app.post(dev ? '/dev/workflow' : '/', async (req, res) => {
170
196
  let workflowEvent;
197
+
171
198
  try {
172
199
  workflowEvent = WorkflowEventSchema.parse(req.body.event);
173
200
  globalThis.SCOUT9 = {
174
201
  ...workflowEvent,
175
- $convo: req.body.$convo,
176
- }
202
+ $convo: req.body.$convo
203
+ };
177
204
  } catch (error) {
178
205
  if (error instanceof ZodError) {
179
- const formattedErrors = error.format();
180
- res.writeHead(400, {'Content-Type': 'application/json'});
181
- res.end(JSON.stringify({
182
- status: 'Invalid WorkflowEvent',
183
- errors: formattedErrors
184
- }));
185
- console.log(colors.red(`${colors.bold(`Bad Input Event:`)}: Received: ${JSON.stringify(req.body.event, null, 2)}\n\nErrors:\n\n${JSON.stringify(formattedErrors, null, 2)}`));
206
+ handleZodError({
207
+ error,
208
+ name: 'Workflow Template Event Request Parse Error',
209
+ body: req.body.event,
210
+ bodyLabel: 'Provided WorkflowEvent',
211
+ code: 400,
212
+ res,
213
+ status: 'Invalid WorkflowEvent Input'
214
+ });
186
215
  } else {
187
216
  error.message = `Workflow Template Event Parse Error: ` + error.message;
188
217
  handleError(error, res);
189
218
  }
190
219
  return;
191
220
  }
221
+
192
222
  if (!workflowEvent) {
193
223
  handleError(new Error('No workflowEvent defined'), res);
194
224
  }
225
+ let response;
226
+ try {
227
+ response = await projectApp(workflowEvent);
228
+ } catch (error) {
229
+ error.message = `Workflow Template Runtime Error: ` + error.message;
230
+ handleError(error, res);
231
+ return;
232
+ }
233
+
234
+ if (!response) {
235
+ throw new Error('No response');
236
+ }
195
237
 
196
238
  try {
197
- const response = await projectApp(workflowEvent);
198
- const formattedResponse = WorkflowEventSchema.parse(response);
239
+ const formattedResponse = WorkflowResponseSchema.parse(response);
199
240
  if (dev) {
200
241
  console.log(colors.green(`Workflow Sending Response:`));
201
242
  console.log(colors.grey(JSON.stringify(formattedResponse, null, 2)));
@@ -204,15 +245,17 @@ app.post(dev ? '/dev/workflow' : '/', async (req, res) => {
204
245
  res.end(JSON.stringify(formattedResponse));
205
246
  } catch (error) {
206
247
  if (error instanceof ZodError) {
207
- const formattedErrors = error.format();
208
- res.writeHead(500, {'Content-Type': 'application/json'});
209
- res.end(JSON.stringify({
210
- status: 'Invalid WorkflowResponse',
211
- errors: formattedErrors
212
- }));
213
- console.log(colors.red(`${colors.bold(`Input Workflow Response`)}: Fix needed\n\n${JSON.stringify(formattedErrors, null, 2)}`));
248
+ handleZodError({
249
+ error,
250
+ name: 'Workflow Template Event Response Parse Error',
251
+ body: response,
252
+ bodyLabel: 'Provided WorkflowResponse',
253
+ code: 500,
254
+ res,
255
+ status: 'Invalid WorkflowResponse Output'
256
+ });
214
257
  } else {
215
- error.message = `Workflow Template Runtime Error: ` + error.message
258
+ error.message = `Workflow Template Runtime Parse Error: ` + error.message;
216
259
  handleError(error, res);
217
260
  }
218
261
  }
@@ -315,14 +358,17 @@ async function runEntityApi(req, res) {
315
358
  searchParams: req?.query || {}, body: req?.body || undefined,
316
359
  id: params.id
317
360
  });
318
- if (response instanceof EventResponse && !!response.body) {
361
+ if (response instanceof EventResponse || !!response.body) {
362
+ const data = response.body ?? response.data();
319
363
  res.writeHead(response.status || 200, {'Content-Type': 'application/json'});
320
- res.end(JSON.stringify(response.body));
364
+ res.end(JSON.stringify(data));
365
+ console.log(`${req.method} EntityApi.${params.id}:`);
366
+ console.log(colors.grey(JSON.stringify(data)));
321
367
  } else {
322
368
  throw new Error(`Invalid response: not an EventResponse`);
323
369
  }
324
370
  } catch (e) {
325
- console.error(e);
371
+ console.error(`${req.method} EntityApi Runtime Error`, e.message);
326
372
  res.writeHead(500, {'Content-Type': 'application/json'});
327
373
  res.end(JSON.stringify({error: e.message}));
328
374
  }
@@ -330,7 +376,7 @@ async function runEntityApi(req, res) {
330
376
 
331
377
  async function getFilesRecursive(dir) {
332
378
  let results = [];
333
- const list = await readdir(dir, { withFileTypes: true });
379
+ const list = await readdir(dir, {withFileTypes: true});
334
380
 
335
381
  for (const dirent of list) {
336
382
  const res = resolve(dir, dirent.name);
@@ -351,59 +397,77 @@ async function runCommandApi(req, res) {
351
397
  const commandsDir = resolve(__dirname, `./src/commands`);
352
398
 
353
399
  try {
354
- const files = await getFilesRecursive(commandsDir).then(files => files.map(file => file.replace(commandsDir, '.')).filter(file => params.every(p => file.includes(p))))
400
+ const files = await getFilesRecursive(commandsDir).then(files => files.map(file => file.replace(commandsDir, '.'))
401
+ .filter(file => params.every(p => file.includes(p))));
355
402
  file = files?.[0];
356
403
  } catch (e) {
357
- console.log('No commands found', e.message)
404
+ console.log('No commands found', e.message);
405
+ res.writeHead(404, {'Content-Type': 'application/json'});
406
+ res.end(JSON.stringify({error: `No commands found`}));
407
+ return;
358
408
  }
359
409
 
360
-
361
410
  if (!file) {
362
- throw new Error(`Unable to find command for ${url}`);
411
+ res.writeHead(404, {'Content-Type': 'application/json'});
412
+ res.end(JSON.stringify({error: `Unable to find command for ${url}`}));
413
+ return;
363
414
  }
364
415
 
365
416
  let mod;
366
417
  try {
367
- mod = await import(pathToFileURL(path.resolve(commandsDir, file)).href)
368
- console.log(mod);
418
+ mod = await import(pathToFileURL(path.resolve(commandsDir, file)).href);
369
419
  } catch (e) {
370
420
  if ('code' in e) {
371
421
  switch (e.code) {
372
422
  case 'ERR_MODULE_NOT_FOUND':
373
423
  case 'MODULE_NOT_FOUND':
374
424
  console.error(e);
375
- throw new Error(`Invalid command: no API method`);
425
+ res.writeHead(404, {'Content-Type': 'application/json'});
426
+ res.end(JSON.stringify({error: `Invalid command: no API method found`}));
427
+ return;
376
428
  }
377
429
  }
378
430
  console.error(e);
379
- throw new Error(`Invalid command: Internal system error`);
431
+ res.writeHead(500, {'Content-Type': 'application/json'});
432
+ res.end(JSON.stringify({error: `Invalid command: Internal system error: ${e?.message ?? ''}`}));
433
+ return;
380
434
  }
381
435
 
382
436
  if (!mod || !mod.default) {
383
- throw new Error(`Command file "${file}" does not export a default command function`);
437
+ res.writeHead(500, {'Content-Type': 'application/json'});
438
+ res.end(JSON.stringify({error: `Command file "${file}" does not export a default command function`}));
439
+ return;
384
440
  }
385
441
 
386
- console.log(mod);
387
-
388
442
  let result;
389
443
 
390
444
  try {
391
445
  result = await mod.default(body);
392
446
  } catch (e) {
393
447
  console.error('Failed to run command', e);
394
- throw new Error(`Failed to run command: ${e.message}`)
448
+ res.writeHead(500, {'Content-Type': 'application/json'});
449
+ res.end(JSON.stringify({error: `Failed to run command: ${e.message}`}));
450
+ return;
395
451
  }
396
452
 
453
+ let responseBody = {};
454
+ let code = 500;
397
455
  if (result) {
398
456
  if (typeof result === 'string') {
399
- return {message: result};
457
+ responseBody = {message: result};
458
+ code = 200;
400
459
  } else if (typeof result === 'object' && 'message' in result) {
401
- return result;
460
+ responseBody = result;
461
+ code = 200;
402
462
  } else {
403
- throw new Error(`Invalid Command Response, must either return a string or {"message": "<your message>"}`);
463
+ responseBody.error = `Invalid Command Response, must either return a string or {"message": "<your message>"}`;
404
464
  }
465
+ } else {
466
+ responseBody.error = `No command response provided`;
405
467
  }
406
- return {message: `${mod.default.name} Complete`};
468
+
469
+ res.writeHead(code, {'Content-Type': 'application/json'});
470
+ res.end(JSON.stringify(responseBody));
407
471
  }
408
472
 
409
473
  app.post('/commands/:command', runCommandApi);
@@ -473,7 +537,8 @@ if (dev) {
473
537
  for (const [key, value] of Object.entries(payload.context)) {
474
538
  fields += `\n\t\t${colors.bold(colors.white(key))}: ${colors.grey(JSON.stringify(value))}`;
475
539
  }
476
- console.log(`\tParsed in ${payload.ms}ms:${colors.grey(`${fields}`)}`);
540
+ console.log(`\tParsed in ${payload.ms}ms:${colors.grey(`${fields}`)}:`);
541
+ console.log(colors.grey(JSON.stringify(payload)));
477
542
  res.writeHead(200, {'Content-Type': 'application/json'});
478
543
  res.end(JSON.stringify(payload));
479
544
  } catch (e) {
@@ -77,8 +77,11 @@ export const WorkflowResponseMessageApiResponse = z.union([
77
77
  /**
78
78
  * The workflow response object slot
79
79
  */
80
- export const InstructionSchema = z.union([z.string(), InstructionObjectSchema, z.array(z.string()), z.array(
81
- InstructionObjectSchema)]);
80
+ export const InstructionSchema = z.union([
81
+ z.string(),
82
+ InstructionObjectSchema,
83
+ z.array(z.union([z.string(), InstructionObjectSchema]))
84
+ ]);
82
85
 
83
86
  /**
84
87
  * Base follow up schema to follow up with the client