index.cjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. 'use strict';
  2. /**
  3. * @fileoverview Merge Strategy
  4. */
  5. //-----------------------------------------------------------------------------
  6. // Class
  7. //-----------------------------------------------------------------------------
  8. /**
  9. * Container class for several different merge strategies.
  10. */
  11. class MergeStrategy {
  12. /**
  13. * Merges two keys by overwriting the first with the second.
  14. * @param {*} value1 The value from the first object key.
  15. * @param {*} value2 The value from the second object key.
  16. * @returns {*} The second value.
  17. */
  18. static overwrite(value1, value2) {
  19. return value2;
  20. }
  21. /**
  22. * Merges two keys by replacing the first with the second only if the
  23. * second is defined.
  24. * @param {*} value1 The value from the first object key.
  25. * @param {*} value2 The value from the second object key.
  26. * @returns {*} The second value if it is defined.
  27. */
  28. static replace(value1, value2) {
  29. if (typeof value2 !== "undefined") {
  30. return value2;
  31. }
  32. return value1;
  33. }
  34. /**
  35. * Merges two properties by assigning properties from the second to the first.
  36. * @param {*} value1 The value from the first object key.
  37. * @param {*} value2 The value from the second object key.
  38. * @returns {*} A new object containing properties from both value1 and
  39. * value2.
  40. */
  41. static assign(value1, value2) {
  42. return Object.assign({}, value1, value2);
  43. }
  44. }
  45. /**
  46. * @fileoverview Validation Strategy
  47. */
  48. //-----------------------------------------------------------------------------
  49. // Class
  50. //-----------------------------------------------------------------------------
  51. /**
  52. * Container class for several different validation strategies.
  53. */
  54. class ValidationStrategy {
  55. /**
  56. * Validates that a value is an array.
  57. * @param {*} value The value to validate.
  58. * @returns {void}
  59. * @throws {TypeError} If the value is invalid.
  60. */
  61. static array(value) {
  62. if (!Array.isArray(value)) {
  63. throw new TypeError("Expected an array.");
  64. }
  65. }
  66. /**
  67. * Validates that a value is a boolean.
  68. * @param {*} value The value to validate.
  69. * @returns {void}
  70. * @throws {TypeError} If the value is invalid.
  71. */
  72. static boolean(value) {
  73. if (typeof value !== "boolean") {
  74. throw new TypeError("Expected a Boolean.");
  75. }
  76. }
  77. /**
  78. * Validates that a value is a number.
  79. * @param {*} value The value to validate.
  80. * @returns {void}
  81. * @throws {TypeError} If the value is invalid.
  82. */
  83. static number(value) {
  84. if (typeof value !== "number") {
  85. throw new TypeError("Expected a number.");
  86. }
  87. }
  88. /**
  89. * Validates that a value is a object.
  90. * @param {*} value The value to validate.
  91. * @returns {void}
  92. * @throws {TypeError} If the value is invalid.
  93. */
  94. static object(value) {
  95. if (!value || typeof value !== "object") {
  96. throw new TypeError("Expected an object.");
  97. }
  98. }
  99. /**
  100. * Validates that a value is a object or null.
  101. * @param {*} value The value to validate.
  102. * @returns {void}
  103. * @throws {TypeError} If the value is invalid.
  104. */
  105. static "object?"(value) {
  106. if (typeof value !== "object") {
  107. throw new TypeError("Expected an object or null.");
  108. }
  109. }
  110. /**
  111. * Validates that a value is a string.
  112. * @param {*} value The value to validate.
  113. * @returns {void}
  114. * @throws {TypeError} If the value is invalid.
  115. */
  116. static string(value) {
  117. if (typeof value !== "string") {
  118. throw new TypeError("Expected a string.");
  119. }
  120. }
  121. /**
  122. * Validates that a value is a non-empty string.
  123. * @param {*} value The value to validate.
  124. * @returns {void}
  125. * @throws {TypeError} If the value is invalid.
  126. */
  127. static "string!"(value) {
  128. if (typeof value !== "string" || value.length === 0) {
  129. throw new TypeError("Expected a non-empty string.");
  130. }
  131. }
  132. }
  133. /**
  134. * @fileoverview Object Schema
  135. */
  136. //-----------------------------------------------------------------------------
  137. // Types
  138. //-----------------------------------------------------------------------------
  139. /** @typedef {import("./types.ts").ObjectDefinition} ObjectDefinition */
  140. /** @typedef {import("./types.ts").PropertyDefinition} PropertyDefinition */
  141. //-----------------------------------------------------------------------------
  142. // Private
  143. //-----------------------------------------------------------------------------
  144. /**
  145. * Validates a schema strategy.
  146. * @param {string} name The name of the key this strategy is for.
  147. * @param {PropertyDefinition} definition The strategy for the object key.
  148. * @returns {void}
  149. * @throws {Error} When the strategy is missing a name.
  150. * @throws {Error} When the strategy is missing a merge() method.
  151. * @throws {Error} When the strategy is missing a validate() method.
  152. */
  153. function validateDefinition(name, definition) {
  154. let hasSchema = false;
  155. if (definition.schema) {
  156. if (typeof definition.schema === "object") {
  157. hasSchema = true;
  158. } else {
  159. throw new TypeError("Schema must be an object.");
  160. }
  161. }
  162. if (typeof definition.merge === "string") {
  163. if (!(definition.merge in MergeStrategy)) {
  164. throw new TypeError(
  165. `Definition for key "${name}" missing valid merge strategy.`,
  166. );
  167. }
  168. } else if (!hasSchema && typeof definition.merge !== "function") {
  169. throw new TypeError(
  170. `Definition for key "${name}" must have a merge property.`,
  171. );
  172. }
  173. if (typeof definition.validate === "string") {
  174. if (!(definition.validate in ValidationStrategy)) {
  175. throw new TypeError(
  176. `Definition for key "${name}" missing valid validation strategy.`,
  177. );
  178. }
  179. } else if (!hasSchema && typeof definition.validate !== "function") {
  180. throw new TypeError(
  181. `Definition for key "${name}" must have a validate() method.`,
  182. );
  183. }
  184. }
  185. //-----------------------------------------------------------------------------
  186. // Errors
  187. //-----------------------------------------------------------------------------
  188. /**
  189. * Error when an unexpected key is found.
  190. */
  191. class UnexpectedKeyError extends Error {
  192. /**
  193. * Creates a new instance.
  194. * @param {string} key The key that was unexpected.
  195. */
  196. constructor(key) {
  197. super(`Unexpected key "${key}" found.`);
  198. }
  199. }
  200. /**
  201. * Error when a required key is missing.
  202. */
  203. class MissingKeyError extends Error {
  204. /**
  205. * Creates a new instance.
  206. * @param {string} key The key that was missing.
  207. */
  208. constructor(key) {
  209. super(`Missing required key "${key}".`);
  210. }
  211. }
  212. /**
  213. * Error when a key requires other keys that are missing.
  214. */
  215. class MissingDependentKeysError extends Error {
  216. /**
  217. * Creates a new instance.
  218. * @param {string} key The key that was unexpected.
  219. * @param {Array<string>} requiredKeys The keys that are required.
  220. */
  221. constructor(key, requiredKeys) {
  222. super(`Key "${key}" requires keys "${requiredKeys.join('", "')}".`);
  223. }
  224. }
  225. /**
  226. * Wrapper error for errors occuring during a merge or validate operation.
  227. */
  228. class WrapperError extends Error {
  229. /**
  230. * Creates a new instance.
  231. * @param {string} key The object key causing the error.
  232. * @param {Error} source The source error.
  233. */
  234. constructor(key, source) {
  235. super(`Key "${key}": ${source.message}`, { cause: source });
  236. // copy over custom properties that aren't represented
  237. for (const sourceKey of Object.keys(source)) {
  238. if (!(sourceKey in this)) {
  239. this[sourceKey] = source[sourceKey];
  240. }
  241. }
  242. }
  243. }
  244. //-----------------------------------------------------------------------------
  245. // Main
  246. //-----------------------------------------------------------------------------
  247. /**
  248. * Represents an object validation/merging schema.
  249. */
  250. class ObjectSchema {
  251. /**
  252. * Track all definitions in the schema by key.
  253. * @type {Map<string, PropertyDefinition>}
  254. */
  255. #definitions = new Map();
  256. /**
  257. * Separately track any keys that are required for faster validtion.
  258. * @type {Map<string, PropertyDefinition>}
  259. */
  260. #requiredKeys = new Map();
  261. /**
  262. * Creates a new instance.
  263. * @param {ObjectDefinition} definitions The schema definitions.
  264. */
  265. constructor(definitions) {
  266. if (!definitions) {
  267. throw new Error("Schema definitions missing.");
  268. }
  269. // add in all strategies
  270. for (const key of Object.keys(definitions)) {
  271. validateDefinition(key, definitions[key]);
  272. // normalize merge and validate methods if subschema is present
  273. if (typeof definitions[key].schema === "object") {
  274. const schema = new ObjectSchema(definitions[key].schema);
  275. definitions[key] = {
  276. ...definitions[key],
  277. merge(first = {}, second = {}) {
  278. return schema.merge(first, second);
  279. },
  280. validate(value) {
  281. ValidationStrategy.object(value);
  282. schema.validate(value);
  283. },
  284. };
  285. }
  286. // normalize the merge method in case there's a string
  287. if (typeof definitions[key].merge === "string") {
  288. definitions[key] = {
  289. ...definitions[key],
  290. merge: MergeStrategy[
  291. /** @type {string} */ (definitions[key].merge)
  292. ],
  293. };
  294. }
  295. // normalize the validate method in case there's a string
  296. if (typeof definitions[key].validate === "string") {
  297. definitions[key] = {
  298. ...definitions[key],
  299. validate:
  300. ValidationStrategy[
  301. /** @type {string} */ (definitions[key].validate)
  302. ],
  303. };
  304. }
  305. this.#definitions.set(key, definitions[key]);
  306. if (definitions[key].required) {
  307. this.#requiredKeys.set(key, definitions[key]);
  308. }
  309. }
  310. }
  311. /**
  312. * Determines if a strategy has been registered for the given object key.
  313. * @param {string} key The object key to find a strategy for.
  314. * @returns {boolean} True if the key has a strategy registered, false if not.
  315. */
  316. hasKey(key) {
  317. return this.#definitions.has(key);
  318. }
  319. /**
  320. * Merges objects together to create a new object comprised of the keys
  321. * of the all objects. Keys are merged based on the each key's merge
  322. * strategy.
  323. * @param {...Object} objects The objects to merge.
  324. * @returns {Object} A new object with a mix of all objects' keys.
  325. * @throws {Error} If any object is invalid.
  326. */
  327. merge(...objects) {
  328. // double check arguments
  329. if (objects.length < 2) {
  330. throw new TypeError("merge() requires at least two arguments.");
  331. }
  332. if (
  333. objects.some(
  334. object => object === null || typeof object !== "object",
  335. )
  336. ) {
  337. throw new TypeError("All arguments must be objects.");
  338. }
  339. return objects.reduce((result, object) => {
  340. this.validate(object);
  341. for (const [key, strategy] of this.#definitions) {
  342. try {
  343. if (key in result || key in object) {
  344. const merge = /** @type {Function} */ (strategy.merge);
  345. const value = merge.call(
  346. this,
  347. result[key],
  348. object[key],
  349. );
  350. if (value !== undefined) {
  351. result[key] = value;
  352. }
  353. }
  354. } catch (ex) {
  355. throw new WrapperError(key, ex);
  356. }
  357. }
  358. return result;
  359. }, {});
  360. }
  361. /**
  362. * Validates an object's keys based on the validate strategy for each key.
  363. * @param {Object} object The object to validate.
  364. * @returns {void}
  365. * @throws {Error} When the object is invalid.
  366. */
  367. validate(object) {
  368. // check existing keys first
  369. for (const key of Object.keys(object)) {
  370. // check to see if the key is defined
  371. if (!this.hasKey(key)) {
  372. throw new UnexpectedKeyError(key);
  373. }
  374. // validate existing keys
  375. const definition = this.#definitions.get(key);
  376. // first check to see if any other keys are required
  377. if (Array.isArray(definition.requires)) {
  378. if (
  379. !definition.requires.every(otherKey => otherKey in object)
  380. ) {
  381. throw new MissingDependentKeysError(
  382. key,
  383. definition.requires,
  384. );
  385. }
  386. }
  387. // now apply remaining validation strategy
  388. try {
  389. const validate = /** @type {Function} */ (definition.validate);
  390. validate.call(definition, object[key]);
  391. } catch (ex) {
  392. throw new WrapperError(key, ex);
  393. }
  394. }
  395. // ensure required keys aren't missing
  396. for (const [key] of this.#requiredKeys) {
  397. if (!(key in object)) {
  398. throw new MissingKeyError(key);
  399. }
  400. }
  401. }
  402. }
  403. exports.MergeStrategy = MergeStrategy;
  404. exports.ObjectSchema = ObjectSchema;
  405. exports.ValidationStrategy = ValidationStrategy;