index.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. const typeChecker = (type) => {
  2. const typeString = "[object " + type + "]";
  3. return function (value) {
  4. return getClassName(value) === typeString;
  5. };
  6. };
  7. const getClassName = value => Object.prototype.toString.call(value);
  8. const comparable = (value) => {
  9. if (value instanceof Date) {
  10. return value.getTime();
  11. }
  12. else if (isArray(value)) {
  13. return value.map(comparable);
  14. }
  15. else if (value && typeof value.toJSON === "function") {
  16. return value.toJSON();
  17. }
  18. return value;
  19. };
  20. const isArray = typeChecker("Array");
  21. const isObject = typeChecker("Object");
  22. const isFunction = typeChecker("Function");
  23. const isVanillaObject = value => {
  24. return (value &&
  25. (value.constructor === Object ||
  26. value.constructor === Array ||
  27. value.constructor.toString() === "function Object() { [native code] }" ||
  28. value.constructor.toString() === "function Array() { [native code] }") &&
  29. !value.toJSON);
  30. };
  31. const equals = (a, b) => {
  32. if (a == null && a == b) {
  33. return true;
  34. }
  35. if (a === b) {
  36. return true;
  37. }
  38. if (Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) {
  39. return false;
  40. }
  41. if (isArray(a)) {
  42. if (a.length !== b.length) {
  43. return false;
  44. }
  45. for (let i = 0, { length } = a; i < length; i++) {
  46. if (!equals(a[i], b[i]))
  47. return false;
  48. }
  49. return true;
  50. }
  51. else if (isObject(a)) {
  52. if (Object.keys(a).length !== Object.keys(b).length) {
  53. return false;
  54. }
  55. for (const key in a) {
  56. if (!equals(a[key], b[key]))
  57. return false;
  58. }
  59. return true;
  60. }
  61. return false;
  62. };
  63. /**
  64. * Walks through each value given the context - used for nested operations. E.g:
  65. * { "person.address": { $eq: "blarg" }}
  66. */
  67. const walkKeyPathValues = (item, keyPath, next, depth, key, owner) => {
  68. const currentKey = keyPath[depth];
  69. // if array, then try matching. Might fall through for cases like:
  70. // { $eq: [1, 2, 3] }, [ 1, 2, 3 ].
  71. if (isArray(item) && isNaN(Number(currentKey))) {
  72. for (let i = 0, { length } = item; i < length; i++) {
  73. // if FALSE is returned, then terminate walker. For operations, this simply
  74. // means that the search critera was met.
  75. if (!walkKeyPathValues(item[i], keyPath, next, depth, i, item)) {
  76. return false;
  77. }
  78. }
  79. }
  80. if (depth === keyPath.length || item == null) {
  81. return next(item, key, owner, depth === 0);
  82. }
  83. return walkKeyPathValues(item[currentKey], keyPath, next, depth + 1, currentKey, item);
  84. };
  85. class BaseOperation {
  86. constructor(params, owneryQuery, options, name) {
  87. this.params = params;
  88. this.owneryQuery = owneryQuery;
  89. this.options = options;
  90. this.name = name;
  91. this.init();
  92. }
  93. init() { }
  94. reset() {
  95. this.done = false;
  96. this.keep = false;
  97. }
  98. }
  99. class GroupOperation extends BaseOperation {
  100. constructor(params, owneryQuery, options, children) {
  101. super(params, owneryQuery, options);
  102. this.children = children;
  103. }
  104. /**
  105. */
  106. reset() {
  107. this.keep = false;
  108. this.done = false;
  109. for (let i = 0, { length } = this.children; i < length; i++) {
  110. this.children[i].reset();
  111. }
  112. }
  113. /**
  114. */
  115. childrenNext(item, key, owner, root) {
  116. let done = true;
  117. let keep = true;
  118. for (let i = 0, { length } = this.children; i < length; i++) {
  119. const childOperation = this.children[i];
  120. if (!childOperation.done) {
  121. childOperation.next(item, key, owner, root);
  122. }
  123. if (!childOperation.keep) {
  124. keep = false;
  125. }
  126. if (childOperation.done) {
  127. if (!childOperation.keep) {
  128. break;
  129. }
  130. }
  131. else {
  132. done = false;
  133. }
  134. }
  135. this.done = done;
  136. this.keep = keep;
  137. }
  138. }
  139. class NamedGroupOperation extends GroupOperation {
  140. constructor(params, owneryQuery, options, children, name) {
  141. super(params, owneryQuery, options, children);
  142. this.name = name;
  143. }
  144. }
  145. class QueryOperation extends GroupOperation {
  146. constructor() {
  147. super(...arguments);
  148. this.propop = true;
  149. }
  150. /**
  151. */
  152. next(item, key, parent, root) {
  153. this.childrenNext(item, key, parent, root);
  154. }
  155. }
  156. class NestedOperation extends GroupOperation {
  157. constructor(keyPath, params, owneryQuery, options, children) {
  158. super(params, owneryQuery, options, children);
  159. this.keyPath = keyPath;
  160. this.propop = true;
  161. /**
  162. */
  163. this._nextNestedValue = (value, key, owner, root) => {
  164. this.childrenNext(value, key, owner, root);
  165. return !this.done;
  166. };
  167. }
  168. /**
  169. */
  170. next(item, key, parent) {
  171. walkKeyPathValues(item, this.keyPath, this._nextNestedValue, 0, key, parent);
  172. }
  173. }
  174. const createTester = (a, compare) => {
  175. if (a instanceof Function) {
  176. return a;
  177. }
  178. if (a instanceof RegExp) {
  179. return b => {
  180. const result = typeof b === "string" && a.test(b);
  181. a.lastIndex = 0;
  182. return result;
  183. };
  184. }
  185. const comparableA = comparable(a);
  186. return b => compare(comparableA, comparable(b));
  187. };
  188. class EqualsOperation extends BaseOperation {
  189. constructor() {
  190. super(...arguments);
  191. this.propop = true;
  192. }
  193. init() {
  194. this._test = createTester(this.params, this.options.compare);
  195. }
  196. next(item, key, parent) {
  197. if (!Array.isArray(parent) || parent.hasOwnProperty(key)) {
  198. if (this._test(item, key, parent)) {
  199. this.done = true;
  200. this.keep = true;
  201. }
  202. }
  203. }
  204. }
  205. const createEqualsOperation = (params, owneryQuery, options) => new EqualsOperation(params, owneryQuery, options);
  206. class NopeOperation extends BaseOperation {
  207. constructor() {
  208. super(...arguments);
  209. this.propop = true;
  210. }
  211. next() {
  212. this.done = true;
  213. this.keep = false;
  214. }
  215. }
  216. const numericalOperationCreator = (createNumericalOperation) => (params, owneryQuery, options, name) => {
  217. if (params == null) {
  218. return new NopeOperation(params, owneryQuery, options, name);
  219. }
  220. return createNumericalOperation(params, owneryQuery, options, name);
  221. };
  222. const numericalOperation = (createTester) => numericalOperationCreator((params, owneryQuery, options, name) => {
  223. const typeofParams = typeof comparable(params);
  224. const test = createTester(params);
  225. return new EqualsOperation(b => {
  226. return typeof comparable(b) === typeofParams && test(b);
  227. }, owneryQuery, options, name);
  228. });
  229. const createNamedOperation = (name, params, parentQuery, options) => {
  230. const operationCreator = options.operations[name];
  231. if (!operationCreator) {
  232. throwUnsupportedOperation(name);
  233. }
  234. return operationCreator(params, parentQuery, options, name);
  235. };
  236. const throwUnsupportedOperation = (name) => {
  237. throw new Error(`Unsupported operation: ${name}`);
  238. };
  239. const containsOperation = (query, options) => {
  240. for (const key in query) {
  241. if (options.operations.hasOwnProperty(key) || key.charAt(0) === "$")
  242. return true;
  243. }
  244. return false;
  245. };
  246. const createNestedOperation = (keyPath, nestedQuery, parentKey, owneryQuery, options) => {
  247. if (containsOperation(nestedQuery, options)) {
  248. const [selfOperations, nestedOperations] = createQueryOperations(nestedQuery, parentKey, options);
  249. if (nestedOperations.length) {
  250. throw new Error(`Property queries must contain only operations, or exact objects.`);
  251. }
  252. return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, selfOperations);
  253. }
  254. return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, [
  255. new EqualsOperation(nestedQuery, owneryQuery, options)
  256. ]);
  257. };
  258. const createQueryOperation = (query, owneryQuery = null, { compare, operations } = {}) => {
  259. const options = {
  260. compare: compare || equals,
  261. operations: Object.assign({}, operations || {})
  262. };
  263. const [selfOperations, nestedOperations] = createQueryOperations(query, null, options);
  264. const ops = [];
  265. if (selfOperations.length) {
  266. ops.push(new NestedOperation([], query, owneryQuery, options, selfOperations));
  267. }
  268. ops.push(...nestedOperations);
  269. if (ops.length === 1) {
  270. return ops[0];
  271. }
  272. return new QueryOperation(query, owneryQuery, options, ops);
  273. };
  274. const createQueryOperations = (query, parentKey, options) => {
  275. const selfOperations = [];
  276. const nestedOperations = [];
  277. if (!isVanillaObject(query)) {
  278. selfOperations.push(new EqualsOperation(query, query, options));
  279. return [selfOperations, nestedOperations];
  280. }
  281. for (const key in query) {
  282. if (options.operations.hasOwnProperty(key)) {
  283. const op = createNamedOperation(key, query[key], query, options);
  284. if (op) {
  285. if (!op.propop && parentKey && !options.operations[parentKey]) {
  286. throw new Error(`Malformed query. ${key} cannot be matched against property.`);
  287. }
  288. }
  289. // probably just a flag for another operation (like $options)
  290. if (op != null) {
  291. selfOperations.push(op);
  292. }
  293. }
  294. else if (key.charAt(0) === "$") {
  295. throwUnsupportedOperation(key);
  296. }
  297. else {
  298. nestedOperations.push(createNestedOperation(key.split("."), query[key], key, query, options));
  299. }
  300. }
  301. return [selfOperations, nestedOperations];
  302. };
  303. const createOperationTester = (operation) => (item, key, owner) => {
  304. operation.reset();
  305. operation.next(item, key, owner);
  306. return operation.keep;
  307. };
  308. const createQueryTester = (query, options = {}) => {
  309. return createOperationTester(createQueryOperation(query, null, options));
  310. };
  311. class $Ne extends BaseOperation {
  312. constructor() {
  313. super(...arguments);
  314. this.propop = true;
  315. }
  316. init() {
  317. this._test = createTester(this.params, this.options.compare);
  318. }
  319. reset() {
  320. super.reset();
  321. this.keep = true;
  322. }
  323. next(item) {
  324. if (this._test(item)) {
  325. this.done = true;
  326. this.keep = false;
  327. }
  328. }
  329. }
  330. // https://docs.mongodb.com/manual/reference/operator/query/elemMatch/
  331. class $ElemMatch extends BaseOperation {
  332. constructor() {
  333. super(...arguments);
  334. this.propop = true;
  335. }
  336. init() {
  337. if (!this.params || typeof this.params !== "object") {
  338. throw new Error(`Malformed query. $elemMatch must by an object.`);
  339. }
  340. this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options);
  341. }
  342. reset() {
  343. super.reset();
  344. this._queryOperation.reset();
  345. }
  346. next(item) {
  347. if (isArray(item)) {
  348. for (let i = 0, { length } = item; i < length; i++) {
  349. // reset query operation since item being tested needs to pass _all_ query
  350. // operations for it to be a success
  351. this._queryOperation.reset();
  352. const child = item[i];
  353. this._queryOperation.next(child, i, item, false);
  354. this.keep = this.keep || this._queryOperation.keep;
  355. }
  356. this.done = true;
  357. }
  358. else {
  359. this.done = false;
  360. this.keep = false;
  361. }
  362. }
  363. }
  364. class $Not extends BaseOperation {
  365. constructor() {
  366. super(...arguments);
  367. this.propop = true;
  368. }
  369. init() {
  370. this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options);
  371. }
  372. reset() {
  373. super.reset();
  374. this._queryOperation.reset();
  375. }
  376. next(item, key, owner, root) {
  377. this._queryOperation.next(item, key, owner, root);
  378. this.done = this._queryOperation.done;
  379. this.keep = !this._queryOperation.keep;
  380. }
  381. }
  382. class $Size extends BaseOperation {
  383. constructor() {
  384. super(...arguments);
  385. this.propop = true;
  386. }
  387. init() { }
  388. next(item) {
  389. if (isArray(item) && item.length === this.params) {
  390. this.done = true;
  391. this.keep = true;
  392. }
  393. // if (parent && parent.length === this.params) {
  394. // this.done = true;
  395. // this.keep = true;
  396. // }
  397. }
  398. }
  399. const assertGroupNotEmpty = (values) => {
  400. if (values.length === 0) {
  401. throw new Error(`$and/$or/$nor must be a nonempty array`);
  402. }
  403. };
  404. class $Or extends BaseOperation {
  405. constructor() {
  406. super(...arguments);
  407. this.propop = false;
  408. }
  409. init() {
  410. assertGroupNotEmpty(this.params);
  411. this._ops = this.params.map(op => createQueryOperation(op, null, this.options));
  412. }
  413. reset() {
  414. this.done = false;
  415. this.keep = false;
  416. for (let i = 0, { length } = this._ops; i < length; i++) {
  417. this._ops[i].reset();
  418. }
  419. }
  420. next(item, key, owner) {
  421. let done = false;
  422. let success = false;
  423. for (let i = 0, { length } = this._ops; i < length; i++) {
  424. const op = this._ops[i];
  425. op.next(item, key, owner);
  426. if (op.keep) {
  427. done = true;
  428. success = op.keep;
  429. break;
  430. }
  431. }
  432. this.keep = success;
  433. this.done = done;
  434. }
  435. }
  436. class $Nor extends $Or {
  437. constructor() {
  438. super(...arguments);
  439. this.propop = false;
  440. }
  441. next(item, key, owner) {
  442. super.next(item, key, owner);
  443. this.keep = !this.keep;
  444. }
  445. }
  446. class $In extends BaseOperation {
  447. constructor() {
  448. super(...arguments);
  449. this.propop = true;
  450. }
  451. init() {
  452. this._testers = this.params.map(value => {
  453. if (containsOperation(value, this.options)) {
  454. throw new Error(`cannot nest $ under ${this.name.toLowerCase()}`);
  455. }
  456. return createTester(value, this.options.compare);
  457. });
  458. }
  459. next(item, key, owner) {
  460. let done = false;
  461. let success = false;
  462. for (let i = 0, { length } = this._testers; i < length; i++) {
  463. const test = this._testers[i];
  464. if (test(item)) {
  465. done = true;
  466. success = true;
  467. break;
  468. }
  469. }
  470. this.keep = success;
  471. this.done = done;
  472. }
  473. }
  474. class $Nin extends BaseOperation {
  475. constructor(params, ownerQuery, options, name) {
  476. super(params, ownerQuery, options, name);
  477. this.propop = true;
  478. this._in = new $In(params, ownerQuery, options, name);
  479. }
  480. next(item, key, owner, root) {
  481. this._in.next(item, key, owner);
  482. if (isArray(owner) && !root) {
  483. if (this._in.keep) {
  484. this.keep = false;
  485. this.done = true;
  486. }
  487. else if (key == owner.length - 1) {
  488. this.keep = true;
  489. this.done = true;
  490. }
  491. }
  492. else {
  493. this.keep = !this._in.keep;
  494. this.done = true;
  495. }
  496. }
  497. reset() {
  498. super.reset();
  499. this._in.reset();
  500. }
  501. }
  502. class $Exists extends BaseOperation {
  503. constructor() {
  504. super(...arguments);
  505. this.propop = true;
  506. }
  507. next(item, key, owner) {
  508. if (owner.hasOwnProperty(key) === this.params) {
  509. this.done = true;
  510. this.keep = true;
  511. }
  512. }
  513. }
  514. class $And extends NamedGroupOperation {
  515. constructor(params, owneryQuery, options, name) {
  516. super(params, owneryQuery, options, params.map(query => createQueryOperation(query, owneryQuery, options)), name);
  517. this.propop = false;
  518. assertGroupNotEmpty(params);
  519. }
  520. next(item, key, owner, root) {
  521. this.childrenNext(item, key, owner, root);
  522. }
  523. }
  524. class $All extends NamedGroupOperation {
  525. constructor(params, owneryQuery, options, name) {
  526. super(params, owneryQuery, options, params.map(query => createQueryOperation(query, owneryQuery, options)), name);
  527. this.propop = true;
  528. }
  529. next(item, key, owner, root) {
  530. this.childrenNext(item, key, owner, root);
  531. }
  532. }
  533. const $eq = (params, owneryQuery, options) => new EqualsOperation(params, owneryQuery, options);
  534. const $ne = (params, owneryQuery, options, name) => new $Ne(params, owneryQuery, options, name);
  535. const $or = (params, owneryQuery, options, name) => new $Or(params, owneryQuery, options, name);
  536. const $nor = (params, owneryQuery, options, name) => new $Nor(params, owneryQuery, options, name);
  537. const $elemMatch = (params, owneryQuery, options, name) => new $ElemMatch(params, owneryQuery, options, name);
  538. const $nin = (params, owneryQuery, options, name) => new $Nin(params, owneryQuery, options, name);
  539. const $in = (params, owneryQuery, options, name) => {
  540. return new $In(params, owneryQuery, options, name);
  541. };
  542. const $lt = numericalOperation(params => b => b < params);
  543. const $lte = numericalOperation(params => b => b <= params);
  544. const $gt = numericalOperation(params => b => b > params);
  545. const $gte = numericalOperation(params => b => b >= params);
  546. const $mod = ([mod, equalsValue], owneryQuery, options) => new EqualsOperation(b => comparable(b) % mod === equalsValue, owneryQuery, options);
  547. const $exists = (params, owneryQuery, options, name) => new $Exists(params, owneryQuery, options, name);
  548. const $regex = (pattern, owneryQuery, options) => new EqualsOperation(new RegExp(pattern, owneryQuery.$options), owneryQuery, options);
  549. const $not = (params, owneryQuery, options, name) => new $Not(params, owneryQuery, options, name);
  550. const typeAliases = {
  551. number: v => typeof v === "number",
  552. string: v => typeof v === "string",
  553. bool: v => typeof v === "boolean",
  554. array: v => Array.isArray(v),
  555. null: v => v === null,
  556. timestamp: v => v instanceof Date
  557. };
  558. const $type = (clazz, owneryQuery, options) => new EqualsOperation(b => {
  559. if (typeof clazz === "string") {
  560. if (!typeAliases[clazz]) {
  561. throw new Error(`Type alias does not exist`);
  562. }
  563. return typeAliases[clazz](b);
  564. }
  565. return b != null ? b instanceof clazz || b.constructor === clazz : false;
  566. }, owneryQuery, options);
  567. const $and = (params, ownerQuery, options, name) => new $And(params, ownerQuery, options, name);
  568. const $all = (params, ownerQuery, options, name) => new $All(params, ownerQuery, options, name);
  569. const $size = (params, ownerQuery, options) => new $Size(params, ownerQuery, options, "$size");
  570. const $options = () => null;
  571. const $where = (params, ownerQuery, options) => {
  572. let test;
  573. if (isFunction(params)) {
  574. test = params;
  575. }
  576. else if (!process.env.CSP_ENABLED) {
  577. test = new Function("obj", "return " + params);
  578. }
  579. else {
  580. throw new Error(`In CSP mode, sift does not support strings in "$where" condition`);
  581. }
  582. return new EqualsOperation(b => test.bind(b)(b), ownerQuery, options);
  583. };
  584. var defaultOperations = /*#__PURE__*/Object.freeze({
  585. __proto__: null,
  586. $Size: $Size,
  587. $eq: $eq,
  588. $ne: $ne,
  589. $or: $or,
  590. $nor: $nor,
  591. $elemMatch: $elemMatch,
  592. $nin: $nin,
  593. $in: $in,
  594. $lt: $lt,
  595. $lte: $lte,
  596. $gt: $gt,
  597. $gte: $gte,
  598. $mod: $mod,
  599. $exists: $exists,
  600. $regex: $regex,
  601. $not: $not,
  602. $type: $type,
  603. $and: $and,
  604. $all: $all,
  605. $size: $size,
  606. $options: $options,
  607. $where: $where
  608. });
  609. const createDefaultQueryOperation = (query, ownerQuery, { compare, operations } = {}) => {
  610. return createQueryOperation(query, ownerQuery, {
  611. compare,
  612. operations: Object.assign({}, defaultOperations, operations || {})
  613. });
  614. };
  615. const createDefaultQueryTester = (query, options = {}) => {
  616. const op = createDefaultQueryOperation(query, null, options);
  617. return createOperationTester(op);
  618. };
  619. export default createDefaultQueryTester;
  620. export { $Size, $all, $and, $elemMatch, $eq, $exists, $gt, $gte, $in, $lt, $lte, $mod, $ne, $nin, $nor, $not, $options, $or, $regex, $size, $type, $where, EqualsOperation, createDefaultQueryOperation, createEqualsOperation, createOperationTester, createQueryOperation, createQueryTester };
  621. //# sourceMappingURL=index.js.map