@cloudnux/local-cloud-provider 0.11.0 → 0.14.0

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 CHANGED
@@ -1,5 +1,6 @@
1
- // src/services/event-broker.ts
2
- import axios from "axios";
1
+ // src/logging/pretty-writer.ts
2
+ import chalk from "chalk";
3
+ import { EOL as EOL2 } from "os";
3
4
 
4
5
  // ../../../node_modules/lodash-es/_freeGlobal.js
5
6
  var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
@@ -963,20 +964,32 @@ var tokenUtils = {
963
964
  verifyAccessToken: verify
964
965
  };
965
966
 
966
- // ../../utils/src/logging/index.ts
967
- import chalk from "chalk";
968
- import { EOL } from "os";
969
-
970
967
  // ../../utils/src/logging/types.ts
971
968
  var logLevels = {
972
969
  fatal: -1,
973
970
  error: 0,
974
971
  warn: 1,
975
972
  info: 2,
976
- debug: 3
973
+ debug: 3,
974
+ trace: 4
977
975
  };
978
976
 
979
977
  // ../../utils/src/logging/error-to-string.ts
978
+ var safeJsonStringify = (value) => {
979
+ const seen = /* @__PURE__ */ new WeakSet();
980
+ return JSON.stringify(value, (key, currentValue) => {
981
+ if (key === "constructor") return void 0;
982
+ if (typeof currentValue === "object" && currentValue !== null) {
983
+ if (seen.has(currentValue)) return "[Circular]";
984
+ seen.add(currentValue);
985
+ }
986
+ return currentValue;
987
+ });
988
+ };
989
+ var hasOwnConstructorProp = (value) => {
990
+ if (typeof value !== "object" || value === null) return false;
991
+ return Object.prototype.hasOwnProperty.call(value, "constructor");
992
+ };
980
993
  var errorToString = (error) => {
981
994
  if (error === null) return "Null error";
982
995
  if (error === void 0) return "Undefined error";
@@ -986,13 +999,22 @@ var errorToString = (error) => {
986
999
  `Message: ${error.message}`,
987
1000
  `Stack: ${error.stack || "No stack trace available"}`,
988
1001
  // Handle additional properties that might exist on custom errors
989
- ...Object.entries(error).filter(([key]) => !["name", "message", "stack"].includes(key)).map(([key, value]) => `${key}: ${JSON.stringify(value)}`)
1002
+ ...Object.entries(error).filter(
1003
+ ([key, value]) => !["name", "message", "stack"].includes(key) && !hasOwnConstructorProp(value)
1004
+ ).map(([key, value]) => `${key}: ${safeJsonStringify(value)}`)
990
1005
  ].join("\n");
991
1006
  }
992
1007
  if (typeof error === "string") return error;
993
1008
  if (typeof error === "object") {
994
1009
  try {
995
- return JSON.stringify(error, null, 2);
1010
+ return JSON.stringify(
1011
+ error,
1012
+ (key, value) => {
1013
+ if (key === "constructor") return void 0;
1014
+ return value;
1015
+ },
1016
+ 2
1017
+ );
996
1018
  } catch {
997
1019
  return `[Object that cannot be stringified: ${Object.prototype.toString.call(error)}]`;
998
1020
  }
@@ -1000,64 +1022,130 @@ var errorToString = (error) => {
1000
1022
  return String(error);
1001
1023
  };
1002
1024
 
1025
+ // ../../utils/src/logging/writer.ts
1026
+ import { EOL } from "os";
1027
+ var jsonWriter = (entry) => {
1028
+ process.stdout.write(JSON.stringify(entry) + EOL);
1029
+ };
1030
+ var _writer = jsonWriter;
1031
+ function setWriter(writer) {
1032
+ _writer = writer;
1033
+ }
1034
+ function getWriter() {
1035
+ return _writer;
1036
+ }
1037
+
1003
1038
  // ../../utils/src/logging/index.ts
1004
- var currentLogLevel = logLevels[env("LOG_LEVEL")?.toLowerCase()] ?? logLevels.info;
1005
- var module = "default";
1006
- var requestId = "";
1007
- var logger = {
1008
- fatal: (message, meta) => {
1009
- if (currentLogLevel >= logLevels.fatal) {
1010
- console.error(
1011
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1012
- `${chalk.bgRed.white(" fatal ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1013
- errorToString(message),
1014
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1015
- );
1016
- }
1017
- },
1018
- error: (message, meta) => {
1019
- if (currentLogLevel >= logLevels.error) {
1020
- console.error(
1021
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1022
- `${chalk.bgRed.white(" error ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1023
- errorToString(message),
1024
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1025
- );
1026
- }
1027
- },
1028
- warn: (message, meta) => {
1029
- if (currentLogLevel >= logLevels.warn) {
1030
- console.warn(
1031
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1032
- `${chalk.bgYellow.black(" warn ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1033
- errorToString(message),
1034
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1035
- );
1036
- }
1037
- },
1038
- info: (message, meta) => {
1039
- if (currentLogLevel >= logLevels.info) {
1040
- console.info(
1041
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1042
- `${chalk.bgBlue.white(" info ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1043
- message,
1044
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1045
- );
1046
- }
1047
- },
1048
- debug: (message, meta) => {
1049
- if (currentLogLevel >= logLevels.debug) {
1050
- console.debug(
1051
- `[${(/* @__PURE__ */ new Date()).toTimeString()}]`,
1052
- `${chalk.bgWhite.black(" debug ")} - ${module || "unknown module"} - ${requestId || "no request ID"} - ${EOL}`,
1053
- message,
1054
- meta ? `${EOL}${JSON.stringify(meta, null, 2)}` : ""
1055
- );
1056
- }
1039
+ var levelValues = {
1040
+ fatal: 70,
1041
+ error: 60,
1042
+ warn: 50,
1043
+ info: 40,
1044
+ debug: 30,
1045
+ trace: 20
1046
+ };
1047
+ var currentLogLevel = 2;
1048
+ var _module = "default";
1049
+ var _requestId = "";
1050
+ function writeLine(level, mergeObject, msg, bindings) {
1051
+ getWriter()({
1052
+ level: levelValues[level],
1053
+ levelName: level,
1054
+ time: Date.now(),
1055
+ module: bindings.module || _module,
1056
+ reqId: bindings.reqId || _requestId,
1057
+ msg: level === "error" || level === "fatal" ? errorToString(msg) : msg,
1058
+ ...mergeObject ? { meta: mergeObject } : {}
1059
+ });
1060
+ }
1061
+ function createLogger(bindings = {}) {
1062
+ const currentLogLevelName = env("LOG_LEVEL")?.toLowerCase() ?? "info";
1063
+ currentLogLevel = logLevels[currentLogLevelName] ?? logLevels.info;
1064
+ return {
1065
+ level: currentLogLevelName,
1066
+ fatal: (mergeObject, msg) => {
1067
+ if (currentLogLevel >= logLevels.fatal) {
1068
+ typeof mergeObject === "string" || mergeObject instanceof Error ? writeLine("fatal", null, mergeObject, bindings) : writeLine("fatal", mergeObject, msg ?? "", bindings);
1069
+ }
1070
+ },
1071
+ error: (mergeObject, msg) => {
1072
+ if (currentLogLevel >= logLevels.error) {
1073
+ typeof mergeObject === "string" || mergeObject instanceof Error ? writeLine("error", null, mergeObject, bindings) : writeLine("error", mergeObject, msg ?? "", bindings);
1074
+ }
1075
+ },
1076
+ warn: (mergeObject, msg) => {
1077
+ if (currentLogLevel >= logLevels.warn) {
1078
+ typeof mergeObject === "string" ? writeLine("warn", null, mergeObject, bindings) : writeLine("warn", mergeObject, msg ?? "", bindings);
1079
+ }
1080
+ },
1081
+ info: (mergeObject, msg) => {
1082
+ if (currentLogLevel >= logLevels.info) {
1083
+ typeof mergeObject === "string" ? writeLine("info", null, mergeObject, bindings) : writeLine("info", mergeObject, msg ?? "", bindings);
1084
+ }
1085
+ },
1086
+ debug: (mergeObject, msg) => {
1087
+ if (currentLogLevel >= logLevels.debug) {
1088
+ typeof mergeObject === "string" ? writeLine("debug", null, mergeObject, bindings) : writeLine("debug", mergeObject, msg ?? "", bindings);
1089
+ }
1090
+ },
1091
+ trace: (mergeObject, msg) => {
1092
+ if (currentLogLevel >= logLevels.trace) {
1093
+ typeof mergeObject === "string" ? writeLine("trace", null, mergeObject, bindings) : writeLine("trace", mergeObject, msg ?? "", bindings);
1094
+ }
1095
+ },
1096
+ silent: () => {
1097
+ },
1098
+ child: (childBindings) => createLogger({ ...bindings, ...childBindings })
1099
+ };
1100
+ }
1101
+ var logger = createLogger();
1102
+
1103
+ // src/logging/pretty-writer.ts
1104
+ var levelColor = {
1105
+ fatal: chalk.bgRed.white,
1106
+ error: chalk.red,
1107
+ warn: chalk.yellow,
1108
+ info: chalk.cyan,
1109
+ debug: chalk.gray,
1110
+ trace: chalk.white
1111
+ };
1112
+ function formatTime(ms) {
1113
+ return new Date(ms).toTimeString().slice(0, 8);
1114
+ }
1115
+ function formatMeta(meta) {
1116
+ const { req, res, ...rest } = meta;
1117
+ const lines = [];
1118
+ if (req) {
1119
+ const reqParts = [`${req.method} ${req.url}`];
1120
+ if (req.remoteAddress) reqParts.push(`from ${req.remoteAddress}:${req.remotePort ?? ""}`);
1121
+ if (req.headers) reqParts.push(`headers=${JSON.stringify(req.headers, null, 2)}`);
1122
+ if (req.body !== void 0) reqParts.push(`body=${typeof req.body === "string" ? req.body : JSON.stringify(req.body, null, 2)}`);
1123
+ lines.push(chalk.dim(" req: " + reqParts.join(" ")));
1124
+ }
1125
+ if (res) {
1126
+ const resParts = [`${res.statusCode}`];
1127
+ if (res.headers) resParts.push(`headers=${JSON.stringify(res.headers, null, 2)}`);
1128
+ if (res.body !== void 0) resParts.push(`body=${typeof res.body === "string" ? res.body : JSON.stringify(res.body, null, 2)}`);
1129
+ lines.push(chalk.dim(" res: " + resParts.join(" ")));
1057
1130
  }
1131
+ if (Object.keys(rest).length) {
1132
+ lines.push(chalk.dim(" " + JSON.stringify(rest, null, 2)));
1133
+ }
1134
+ return lines.length ? EOL2 + lines.join(EOL2) : "";
1135
+ }
1136
+ var prettyWriter = (entry) => {
1137
+ const color = levelColor[entry.levelName] ?? chalk.white;
1138
+ const time = chalk.dim(formatTime(entry.time));
1139
+ const level = color(entry.levelName.toUpperCase().padEnd(5));
1140
+ const module = chalk.magenta(entry.module);
1141
+ const reqId = entry.reqId ? chalk.dim(`[${entry.reqId}]`) + " " : "";
1142
+ const meta = entry.meta ? formatMeta(entry.meta) : "";
1143
+ process.stdout.write(`${time} ${level} ${module} ${reqId}- ${entry.msg}${meta}${EOL2}`);
1058
1144
  };
1145
+ setWriter(prettyWriter);
1059
1146
 
1060
1147
  // src/services/event-broker.ts
1148
+ import axios from "axios";
1061
1149
  function createLocalEventBrokerService() {
1062
1150
  const baseURL = env("DEV_CLOUD_EVENT_BROKER_URL", "http://localhost:3000");
1063
1151
  function getQueueUrl(queueName) {
@@ -1085,6 +1173,8 @@ function createLocalEventBrokerService() {
1085
1173
  * @returns Promise resolving when publishing is complete
1086
1174
  */
1087
1175
  async publish(target, message, options) {
1176
+ if (!target)
1177
+ throw new Error("Target queue name or URL is required for publishing a message.");
1088
1178
  const queueUrl = getQueueUrl(target);
1089
1179
  const headers = {};
1090
1180
  if (options?.attributes) {
@@ -1251,7 +1341,7 @@ function createLocalStorageService() {
1251
1341
  await unlink(metadataPath);
1252
1342
  } catch (error) {
1253
1343
  if (error.code !== "ENOENT") {
1254
- logger.warn("Error deleting metadata file:", { error });
1344
+ logger.warn({ error }, "Error deleting metadata file:");
1255
1345
  }
1256
1346
  }
1257
1347
  } catch (error) {
@@ -1736,13 +1826,30 @@ function createLocalFunctionsService() {
1736
1826
  createEventRequest: (message) => {
1737
1827
  const eventRequest = {
1738
1828
  body: message.payload,
1739
- attributes: message.attributes,
1829
+ attributes: {
1830
+ ...message.attributes,
1831
+ messageId: message.id
1832
+ },
1740
1833
  requestId: message.id,
1741
1834
  timestamp: message.timestamp,
1742
1835
  attempts: message.attempts
1743
1836
  };
1744
1837
  return [eventRequest];
1745
1838
  },
1839
+ createWebSocketRequest: (connectionId, event, data, request) => {
1840
+ logger.info(request.params);
1841
+ const wsRequest = {
1842
+ connectionId,
1843
+ event,
1844
+ url: getFullUrlFromRequest(request),
1845
+ params: request.params,
1846
+ body: data,
1847
+ queryString: request.query,
1848
+ headers: request.headers,
1849
+ requestId: request.id
1850
+ };
1851
+ return [wsRequest];
1852
+ },
1746
1853
  buildHttpResponse: (context, _, reply) => {
1747
1854
  reply.headers(context.response.headers ?? {}).status(context.response.status).send(context.response.body);
1748
1855
  },
@@ -1752,26 +1859,21 @@ function createLocalFunctionsService() {
1752
1859
  }
1753
1860
  return context.response.body;
1754
1861
  },
1755
- buildEventResponse: (context) => {
1862
+ buildEventResponse: async (context) => {
1756
1863
  if (context.response.status === "error") {
1757
- throw new Error(JSON.stringify(context.response.body));
1864
+ const { messageId } = context.attributes();
1865
+ return { failureId: messageId };
1758
1866
  }
1759
- return context.response.body;
1760
- },
1761
- createWebSocketRequest: (connectionId, event, data) => {
1762
- const wsRequest = {
1763
- connectionId,
1764
- event,
1765
- path: "",
1766
- body: data
1767
- };
1768
- return [wsRequest];
1867
+ return void 0;
1769
1868
  },
1770
- buildWebSocketResponse: (context) => {
1869
+ buildWebSocketResponse: (context, _, __, ___, ____, reply) => {
1771
1870
  if (context.response.status === "error") {
1772
- throw new Error(JSON.stringify(context.response.body));
1871
+ if (reply) {
1872
+ return reply.status(context.response.statusCode ?? 500).send(context.response.body);
1873
+ }
1874
+ return void 0;
1773
1875
  }
1774
- return context.response.body;
1876
+ return void 0;
1775
1877
  }
1776
1878
  };
1777
1879
  }
@@ -1788,6 +1890,12 @@ function createLocalWebSocketService() {
1788
1890
  throw new Error("WebSocket plugin not initialized");
1789
1891
  }
1790
1892
  return _manager.sendToClient(connectionId, data);
1893
+ },
1894
+ async disconnect(connectionId) {
1895
+ if (!_manager) {
1896
+ throw new Error("WebSocket plugin not initialized");
1897
+ }
1898
+ return _manager.disconnect(connectionId);
1791
1899
  }
1792
1900
  };
1793
1901
  }
@@ -1800,22 +1908,15 @@ import fastifyPrintRoutes from "fastify-print-routes";
1800
1908
  function createRouter(options = {}) {
1801
1909
  const fastify = Fastify({
1802
1910
  maxParamLength: 1e3,
1803
- logger: options.logger ? {
1804
- transport: {
1805
- target: "pino-pretty",
1806
- options: {
1807
- colorize: true,
1808
- translateTime: "HH:MM:ss Z",
1809
- ignore: "pid,hostname"
1810
- }
1811
- }
1812
- } : void 0
1911
+ ...options.logger ? { loggerInstance: logger } : {}
1813
1912
  });
1814
1913
  fastify.register(fastifyRawBody, {
1815
1914
  field: "rawBody",
1816
1915
  encoding: "utf8"
1817
1916
  });
1818
- fastify.register(cors, {});
1917
+ fastify.register(cors, {
1918
+ "methods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]
1919
+ });
1819
1920
  fastify.register(fastifyPrintRoutes);
1820
1921
  fastify.addHook("onReady", () => {
1821
1922
  setWebSocketManager(fastify.websockets);