@enspirit/bmg-js 1.0.2 → 1.1.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.
Files changed (194) hide show
  1. package/README.md +3 -2
  2. package/dist/AsyncRelation/Base.d.ts +47 -0
  3. package/dist/AsyncRelation/index.d.ts +25 -0
  4. package/dist/Relation/Memory.d.ts +2 -1
  5. package/dist/Relation/index.d.ts +1 -1
  6. package/dist/async/Relation/Base.d.ts +47 -0
  7. package/dist/async/Relation/index.d.ts +25 -0
  8. package/dist/async/operators/_helpers.d.ts +16 -0
  9. package/dist/async/operators/autowrap.d.ts +7 -0
  10. package/dist/async/operators/constants.d.ts +6 -0
  11. package/dist/async/operators/cross_product.d.ts +9 -0
  12. package/dist/async/operators/extend.d.ts +7 -0
  13. package/dist/async/operators/group.d.ts +7 -0
  14. package/dist/async/operators/image.d.ts +8 -0
  15. package/dist/async/operators/index.d.ts +28 -0
  16. package/dist/async/operators/intersect.d.ts +7 -0
  17. package/dist/async/operators/isEqual.d.ts +7 -0
  18. package/dist/async/operators/join.d.ts +7 -0
  19. package/dist/async/operators/left_join.d.ts +8 -0
  20. package/dist/async/operators/matching.d.ts +7 -0
  21. package/dist/async/operators/minus.d.ts +7 -0
  22. package/dist/async/operators/not_matching.d.ts +7 -0
  23. package/dist/async/operators/one.d.ts +6 -0
  24. package/dist/async/operators/prefix.d.ts +6 -0
  25. package/dist/async/operators/project.d.ts +10 -0
  26. package/dist/async/operators/rename.d.ts +6 -0
  27. package/dist/async/operators/restrict.d.ts +14 -0
  28. package/dist/async/operators/suffix.d.ts +6 -0
  29. package/dist/async/operators/summarize.d.ts +8 -0
  30. package/dist/async/operators/toArray.d.ts +5 -0
  31. package/dist/async/operators/transform.d.ts +9 -0
  32. package/dist/async/operators/ungroup.d.ts +7 -0
  33. package/dist/async/operators/union.d.ts +6 -0
  34. package/dist/async/operators/unwrap.d.ts +6 -0
  35. package/dist/async/operators/wrap.d.ts +6 -0
  36. package/dist/async/operators/yByX.d.ts +7 -0
  37. package/dist/async/types.d.ts +58 -0
  38. package/dist/async-operators/_helpers.d.ts +16 -0
  39. package/dist/async-operators/autowrap.d.ts +7 -0
  40. package/dist/async-operators/constants.d.ts +6 -0
  41. package/dist/async-operators/cross_product.d.ts +9 -0
  42. package/dist/async-operators/extend.d.ts +7 -0
  43. package/dist/async-operators/group.d.ts +7 -0
  44. package/dist/async-operators/image.d.ts +8 -0
  45. package/dist/async-operators/index.d.ts +28 -0
  46. package/dist/async-operators/intersect.d.ts +7 -0
  47. package/dist/async-operators/isEqual.d.ts +7 -0
  48. package/dist/async-operators/join.d.ts +7 -0
  49. package/dist/async-operators/left_join.d.ts +8 -0
  50. package/dist/async-operators/matching.d.ts +7 -0
  51. package/dist/async-operators/minus.d.ts +7 -0
  52. package/dist/async-operators/not_matching.d.ts +7 -0
  53. package/dist/async-operators/one.d.ts +6 -0
  54. package/dist/async-operators/prefix.d.ts +6 -0
  55. package/dist/async-operators/project.d.ts +10 -0
  56. package/dist/async-operators/rename.d.ts +6 -0
  57. package/dist/async-operators/restrict.d.ts +14 -0
  58. package/dist/async-operators/suffix.d.ts +6 -0
  59. package/dist/async-operators/summarize.d.ts +8 -0
  60. package/dist/async-operators/toArray.d.ts +5 -0
  61. package/dist/async-operators/transform.d.ts +9 -0
  62. package/dist/async-operators/ungroup.d.ts +7 -0
  63. package/dist/async-operators/union.d.ts +6 -0
  64. package/dist/async-operators/unwrap.d.ts +6 -0
  65. package/dist/async-operators/wrap.d.ts +6 -0
  66. package/dist/async-operators/yByX.d.ts +7 -0
  67. package/dist/async-types.d.ts +58 -0
  68. package/dist/async.d.ts +4 -0
  69. package/dist/bmg.cjs +1 -1
  70. package/dist/bmg.cjs.map +1 -1
  71. package/dist/bmg.modern.js +1 -1
  72. package/dist/bmg.modern.js.map +1 -1
  73. package/dist/bmg.module.js +1 -1
  74. package/dist/bmg.module.js.map +1 -1
  75. package/dist/bmg.umd.js +1 -1
  76. package/dist/bmg.umd.js.map +1 -1
  77. package/dist/index.d.ts +14 -3
  78. package/dist/lib-definitions.d.ts +1 -1
  79. package/dist/operators/index.d.ts +1 -30
  80. package/dist/operators/isEqual.d.ts +1 -2
  81. package/dist/operators/isRelation.d.ts +2 -1
  82. package/dist/sync/Relation/Memory.d.ts +46 -0
  83. package/dist/sync/Relation/index.d.ts +1 -0
  84. package/dist/sync/operators/_helpers.d.ts +142 -0
  85. package/dist/sync/operators/allbut.d.ts +2 -0
  86. package/dist/sync/operators/autowrap.d.ts +2 -0
  87. package/dist/sync/operators/constants.d.ts +2 -0
  88. package/dist/sync/operators/cross_product.d.ts +3 -0
  89. package/dist/sync/operators/exclude.d.ts +2 -0
  90. package/dist/sync/operators/extend.d.ts +2 -0
  91. package/dist/sync/operators/group.d.ts +2 -0
  92. package/dist/sync/operators/image.d.ts +2 -0
  93. package/dist/sync/operators/index.d.ts +30 -0
  94. package/dist/sync/operators/intersect.d.ts +2 -0
  95. package/dist/sync/operators/isEqual.d.ts +1 -0
  96. package/dist/sync/operators/isRelation.d.ts +2 -0
  97. package/dist/sync/operators/join.d.ts +2 -0
  98. package/dist/sync/operators/left_join.d.ts +2 -0
  99. package/dist/sync/operators/matching.d.ts +2 -0
  100. package/dist/sync/operators/minus.d.ts +2 -0
  101. package/dist/sync/operators/not_matching.d.ts +2 -0
  102. package/dist/sync/operators/one.d.ts +2 -0
  103. package/dist/sync/operators/prefix.d.ts +2 -0
  104. package/dist/sync/operators/project.d.ts +2 -0
  105. package/dist/sync/operators/rename.d.ts +2 -0
  106. package/dist/sync/operators/restrict.d.ts +2 -0
  107. package/dist/sync/operators/suffix.d.ts +2 -0
  108. package/dist/sync/operators/summarize.d.ts +2 -0
  109. package/dist/sync/operators/transform.d.ts +2 -0
  110. package/dist/sync/operators/ungroup.d.ts +2 -0
  111. package/dist/sync/operators/union.d.ts +2 -0
  112. package/dist/sync/operators/unwrap.d.ts +2 -0
  113. package/dist/sync/operators/wrap.d.ts +2 -0
  114. package/dist/sync/operators/yByX.d.ts +2 -0
  115. package/dist/types.d.ts +7 -0
  116. package/dist/writer/Text.d.ts +40 -0
  117. package/dist/writer/index.d.ts +1 -0
  118. package/package.json +1 -1
  119. package/src/Relation/index.ts +2 -1
  120. package/src/async/Relation/Base.ts +245 -0
  121. package/src/async/Relation/index.ts +31 -0
  122. package/src/async/operators/_helpers.ts +60 -0
  123. package/src/async/operators/autowrap.ts +31 -0
  124. package/src/async/operators/constants.ts +26 -0
  125. package/src/async/operators/cross_product.ts +39 -0
  126. package/src/async/operators/extend.ts +36 -0
  127. package/src/async/operators/group.ts +61 -0
  128. package/src/async/operators/image.ts +42 -0
  129. package/src/async/operators/index.ts +28 -0
  130. package/src/async/operators/intersect.ts +28 -0
  131. package/src/async/operators/isEqual.ts +39 -0
  132. package/src/async/operators/join.ts +39 -0
  133. package/src/async/operators/left_join.ts +55 -0
  134. package/src/async/operators/matching.ts +39 -0
  135. package/src/async/operators/minus.ts +28 -0
  136. package/src/async/operators/not_matching.ts +39 -0
  137. package/src/async/operators/one.ts +25 -0
  138. package/src/async/operators/prefix.ts +15 -0
  139. package/src/async/operators/project.ts +64 -0
  140. package/src/async/operators/rename.ts +33 -0
  141. package/src/async/operators/restrict.ts +61 -0
  142. package/src/async/operators/suffix.ts +15 -0
  143. package/src/async/operators/summarize.ts +90 -0
  144. package/src/async/operators/toArray.ts +18 -0
  145. package/src/async/operators/transform.ts +43 -0
  146. package/src/async/operators/ungroup.ts +43 -0
  147. package/src/async/operators/union.ts +29 -0
  148. package/src/async/operators/unwrap.ts +31 -0
  149. package/src/async/operators/wrap.ts +32 -0
  150. package/src/async/operators/yByX.ts +19 -0
  151. package/src/async/types.ts +86 -0
  152. package/src/async.ts +4 -0
  153. package/src/index.ts +16 -3
  154. package/src/lib-definitions.ts +11 -0
  155. package/src/operators/index.ts +2 -31
  156. package/src/{Relation → sync/Relation}/Memory.ts +9 -1
  157. package/src/sync/Relation/index.ts +1 -0
  158. package/src/{operators → sync/operators}/_helpers.ts +1 -1
  159. package/src/{operators → sync/operators}/allbut.ts +1 -1
  160. package/src/{operators → sync/operators}/autowrap.ts +1 -1
  161. package/src/{operators → sync/operators}/constants.ts +1 -1
  162. package/src/{operators → sync/operators}/cross_product.ts +1 -1
  163. package/src/{operators → sync/operators}/exclude.ts +2 -2
  164. package/src/{operators → sync/operators}/extend.ts +1 -1
  165. package/src/{operators → sync/operators}/group.ts +2 -2
  166. package/src/{operators → sync/operators}/image.ts +2 -2
  167. package/src/sync/operators/index.ts +31 -0
  168. package/src/{operators → sync/operators}/intersect.ts +1 -1
  169. package/src/{operators → sync/operators}/isEqual.ts +1 -2
  170. package/src/sync/operators/isRelation.ts +6 -0
  171. package/src/{operators → sync/operators}/join.ts +1 -1
  172. package/src/{operators → sync/operators}/left_join.ts +1 -1
  173. package/src/{operators → sync/operators}/matching.ts +1 -1
  174. package/src/{operators → sync/operators}/minus.ts +1 -1
  175. package/src/{operators → sync/operators}/not_matching.ts +1 -1
  176. package/src/{operators → sync/operators}/one.ts +1 -1
  177. package/src/{operators → sync/operators}/prefix.ts +1 -1
  178. package/src/{operators → sync/operators}/project.ts +1 -1
  179. package/src/{operators → sync/operators}/rename.ts +1 -1
  180. package/src/{operators → sync/operators}/restrict.ts +2 -2
  181. package/src/{operators → sync/operators}/suffix.ts +1 -1
  182. package/src/{operators → sync/operators}/summarize.ts +1 -1
  183. package/src/{operators → sync/operators}/transform.ts +1 -1
  184. package/src/{operators → sync/operators}/ungroup.ts +1 -1
  185. package/src/{operators → sync/operators}/union.ts +1 -1
  186. package/src/{operators → sync/operators}/unwrap.ts +1 -1
  187. package/src/sync/operators/where.ts +1 -0
  188. package/src/{operators → sync/operators}/wrap.ts +1 -1
  189. package/src/{operators → sync/operators}/yByX.ts +1 -1
  190. package/src/types.ts +11 -0
  191. package/src/writer/Text.ts +305 -0
  192. package/src/writer/index.ts +1 -0
  193. package/src/operators/isRelation.ts +0 -5
  194. /package/{src/operators/where.ts → dist/sync/operators/where.d.ts} +0 -0
package/dist/bmg.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bmg.cjs","sources":["../src/support/toPredicateFunc.ts","../src/Relation/Memory.ts","../src/operators/isRelation.ts","../src/operators/_helpers.ts","../src/operators/restrict.ts","../src/operators/exclude.ts","../src/operators/constants.ts","../src/operators/rename.ts","../src/operators/prefix.ts","../src/operators/suffix.ts","../src/operators/project.ts","../src/operators/allbut.ts","../src/operators/extend.ts","../src/operators/union.ts","../src/operators/minus.ts","../src/operators/intersect.ts","../src/operators/matching.ts","../src/operators/not_matching.ts","../src/operators/join.ts","../src/operators/left_join.ts","../src/operators/cross_product.ts","../src/operators/image.ts","../src/operators/summarize.ts","../src/operators/group.ts","../src/operators/ungroup.ts","../src/operators/wrap.ts","../src/operators/unwrap.ts","../src/operators/autowrap.ts","../src/operators/transform.ts","../src/operators/isEqual.ts","../src/operators/one.ts","../src/operators/yByX.ts","../src/index.ts","../src/lib-definitions.ts"],"sourcesContent":["import { Predicate, PredicateFunc, Tuple } from '../types';\n\nexport const toPredicateFunc = (p: Predicate): PredicateFunc => {\n if (typeof(p) === 'function') {\n return p as PredicateFunc;\n } else {\n const expected = p as Tuple;\n return (t: Tuple) => {\n return Object.keys(expected).every(k => t[k] === expected[k])\n }\n }\n}\n","import {\n allbut,\n autowrap,\n constants,\n cross_product,\n exclude,\n extend,\n group,\n image,\n intersect,\n isEqual,\n join,\n left_join,\n matching,\n minus,\n not_matching,\n one,\n prefix,\n project,\n rename,\n restrict,\n suffix,\n summarize,\n where,\n transform,\n ungroup,\n union,\n unwrap,\n wrap,\n yByX,\n} from \"../operators\";\nimport type {\n AttrName,\n AutowrapOptions,\n Relation,\n RelationOperand,\n Transformation,\n Tuple,\n TypedPredicate,\n TypedExtension,\n RenameMap,\n Renamed,\n Prefixed,\n Suffixed,\n Joined,\n LeftJoined,\n Wrapped,\n Unwrapped,\n Ungrouped,\n AggregatorResults,\n TypedJoinKeysArray,\n TypedJoinKeysObject,\n} from \"../types\";\n\n/**\n * In-memory implementation of the Relation interface.\n *\n * @typeParam T - The tuple type for this relation. Defaults to `Tuple` (Record<string, unknown>).\n */\nexport class MemoryRelation<T = Tuple> implements Relation<T> {\n\n constructor(private tuples: T[]) {\n this.tuples = tuples;\n }\n\n // === Type-preserving operators ===\n\n restrict(p: TypedPredicate<T>): Relation<T> {\n return restrict(this as any, p as any) as unknown as Relation<T>;\n }\n\n where(p: TypedPredicate<T>): Relation<T> {\n return where(this as any, p as any) as unknown as Relation<T>;\n }\n\n exclude(p: TypedPredicate<T>): Relation<T> {\n return exclude(this as any, p as any) as unknown as Relation<T>;\n }\n\n // === Projection operators ===\n\n project<K extends keyof T>(attrs: K[]): Relation<Pick<T, K>> {\n return project(this as any, attrs as AttrName[]) as unknown as Relation<Pick<T, K>>;\n }\n\n allbut<K extends keyof T>(attrs: K[]): Relation<Omit<T, K>> {\n return allbut(this as any, attrs as AttrName[]) as unknown as Relation<Omit<T, K>>;\n }\n\n // === Extension operators ===\n\n extend<E extends Record<string, unknown>>(e: TypedExtension<T, E>): Relation<T & E> {\n return extend(this as any, e as any) as unknown as Relation<T & E>;\n }\n\n constants<C extends Tuple>(consts: C): Relation<T & C> {\n return constants(this as any, consts) as unknown as Relation<T & C>;\n }\n\n // === Rename operators ===\n\n rename<R extends RenameMap<T>>(r: R): Relation<Renamed<T, R>> {\n return rename(this as any, r as any) as unknown as Relation<Renamed<T, R>>;\n }\n\n prefix<P extends string, Ex extends keyof T = never>(pfx: P, options?: { except?: Ex[] }): Relation<Prefixed<T, P, Ex>> {\n return prefix(this as any, pfx, options as any) as unknown as Relation<Prefixed<T, P, Ex>>;\n }\n\n suffix<S extends string, Ex extends keyof T = never>(sfx: S, options?: { except?: Ex[] }): Relation<Suffixed<T, S, Ex>> {\n return suffix(this as any, sfx, options as any) as unknown as Relation<Suffixed<T, S, Ex>>;\n }\n\n // === Set operators ===\n\n union(right: RelationOperand<T>): Relation<T> {\n return union(this as any, right as any) as unknown as Relation<T>;\n }\n\n minus(right: RelationOperand<T>): Relation<T> {\n return minus(this as any, right as any) as unknown as Relation<T>;\n }\n\n intersect(right: RelationOperand<T>): Relation<T> {\n return intersect(this as any, right as any) as unknown as Relation<T>;\n }\n\n // === Semi-join operators ===\n\n matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T> {\n return matching(this as any, right as any, keys as any) as unknown as Relation<T>;\n }\n\n not_matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T> {\n return not_matching(this as any, right as any, keys as any) as unknown as Relation<T>;\n }\n\n // === Join operators ===\n\n join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<Joined<T, R>> {\n return join(this as any, right as any, keys as any) as unknown as Relation<Joined<T, R>>;\n }\n\n left_join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<LeftJoined<T, R>> {\n return left_join(this as any, right as any, keys as any) as unknown as Relation<LeftJoined<T, R>>;\n }\n\n cross_product<R>(right: RelationOperand<R>): Relation<T & R> {\n return cross_product(this as any, right as any) as unknown as Relation<T & R>;\n }\n\n cross_join<R>(right: RelationOperand<R>): Relation<T & R> {\n return cross_product(this as any, right as any) as unknown as Relation<T & R>;\n }\n\n // === Nesting operators ===\n\n image<R, As extends string>(right: RelationOperand<R>, as: As, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T & Record<As, Relation<Omit<R, keyof T & keyof R>>>> {\n return image(this as any, right as any, as, keys as any) as unknown as Relation<T & Record<As, Relation<Omit<R, keyof T & keyof R>>>>;\n }\n\n group<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Omit<T, K> & Record<As, Relation<Pick<T, K>>>> {\n return group(this as any, attrs as AttrName[], as) as unknown as Relation<Omit<T, K> & Record<As, Relation<Pick<T, K>>>>;\n }\n\n ungroup<K extends keyof T>(attr: K): Relation<Ungrouped<T, K>> {\n return ungroup(this as any, attr as AttrName) as unknown as Relation<Ungrouped<T, K>>;\n }\n\n wrap<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Wrapped<T, K, As>> {\n return wrap(this as any, attrs as AttrName[], as) as unknown as Relation<Wrapped<T, K, As>>;\n }\n\n unwrap<K extends keyof T>(attr: K): Relation<Unwrapped<T, K>> {\n return unwrap(this as any, attr as AttrName) as unknown as Relation<Unwrapped<T, K>>;\n }\n\n // === Aggregation ===\n\n summarize<By extends keyof T, Aggs extends Record<string, unknown>>(by: By[], aggs: Aggs): Relation<Pick<T, By> & AggregatorResults<Aggs>> {\n return summarize(this as any, by as AttrName[], aggs as any) as unknown as Relation<Pick<T, By> & AggregatorResults<Aggs>>;\n }\n\n // === Transform ===\n\n transform(t: Transformation): Relation<T> {\n return transform(this as any, t) as unknown as Relation<T>;\n }\n\n // === Dynamic ===\n\n autowrap(options?: AutowrapOptions): Relation<Tuple> {\n return autowrap(this as any, options) as Relation<Tuple>;\n }\n\n // === Non-relational ===\n\n one(): T {\n return one(this as any) as T;\n }\n\n toArray(): T[] {\n return this.tuples;\n }\n\n yByX<Y extends keyof T, X extends keyof T>(y: Y, x: X): Record<T[X] & PropertyKey, T[Y]> {\n return yByX(this as any, y as AttrName, x as AttrName) as Record<T[X] & PropertyKey, T[Y]>;\n }\n\n isEqual(right: any): boolean {\n return isEqual(this as any, right as any);\n }\n\n}\n","import { MemoryRelation } from \"@/Relation\";\n\nexport const isRelation = (op) => {\n return op != null && op.constructor === MemoryRelation;\n}\n","import { OperationalOperand, Relation, RelationOperand, Renaming, RenamingFunc, Tuple, JoinKeys, AttrName } from \"@/types\";\nimport { MemoryRelation } from '@/Relation';\nimport { isRelation } from \"./isRelation\";\n\nconst valueKey = (value: unknown): unknown => {\n if (isRelation(value)) {\n // For nested relations, convert to sorted array of tuple keys for comparison\n const tuples = (value as Relation).toArray();\n const keys = tuples.map(t => tupleKey(t)).sort();\n return keys;\n }\n return value;\n}\n\n/**\n * Generates a unique string key for a tuple, used for equality comparison and deduplication.\n * Handles nested relations by converting them to sorted tuple keys.\n *\n * @example\n * tupleKey({ name: 'Alice', age: 30 })\n * // => '[[\"age\",30],[\"name\",\"Alice\"]]'\n *\n * @example\n * tupleKey({ id: 1, items: Bmg([{ x: 1 }, { x: 2 }]) })\n * // => '[[\"id\",1],[\"items\",[...]]]' (nested relation converted to sorted keys)\n */\nexport const tupleKey = (tuple: Tuple): string => {\n const entries = Object.entries(tuple).map(([k, v]) => [k, valueKey(v)]);\n return JSON.stringify(entries.sort(([a], [b]) => (a as string).localeCompare(b as string)));\n}\n\n/**\n * Removes duplicate tuples from an array, preserving order of first occurrence.\n * Uses tupleKey() for equality comparison.\n *\n * @example\n * deduplicate([\n * { id: 1, name: 'Alice' },\n * { id: 2, name: 'Bob' },\n * { id: 1, name: 'Alice' }, // duplicate\n * ])\n * // => [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]\n */\nexport const deduplicate = (tuples: Tuple[]): Tuple[] => {\n const seen = new Set<string>();\n const result: Tuple[] = [];\n for (const tuple of tuples) {\n const key = tupleKey(tuple);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n return result;\n}\n\n/**\n * Converts a RelationOperand (Relation or Tuple[]) to an OperationalOperand\n * that provides a uniform interface for iteration and output.\n *\n * @example\n * // With array input, output remains array\n * const op = toOperationalOperand([{ id: 1 }]);\n * [...op.tuples()]; // => [{ id: 1 }]\n * op.output([{ id: 2 }]); // => [{ id: 2 }]\n *\n * @example\n * // With Relation input, output is a new Relation\n * const op = toOperationalOperand(Bmg([{ id: 1 }]));\n * [...op.tuples()]; // => [{ id: 1 }]\n * op.output([{ id: 2 }]); // => Bmg([{ id: 2 }])\n */\nexport const toOperationalOperand = (operand: RelationOperand): OperationalOperand => {\n if (Array.isArray(operand)) {\n return {\n tuples: () => operand,\n output: (tuples) => tuples,\n };\n } else if (isRelation(operand)) {\n return {\n tuples: () => (operand as Relation).toArray(),\n output: (tuples) => new MemoryRelation(tuples),\n };\n } else {\n throw `Unable to iterate ${operand}`\n }\n}\n\n/**\n * Converts a Renaming (object or function) to a RenamingFunc.\n *\n * @example\n * // Object renaming\n * const fn = toRenamingFunc({ name: 'fullName', age: 'years' });\n * fn('name'); // => 'fullName'\n * fn('age'); // => 'years'\n * fn('other'); // => 'other' (unchanged)\n *\n * @example\n * // Function renaming (passed through)\n * const fn = toRenamingFunc(attr => attr.toUpperCase());\n * fn('name'); // => 'NAME'\n */\nexport const toRenamingFunc = (renaming: Renaming): RenamingFunc => {\n if (typeof(renaming) === 'function') {\n return renaming;\n } else {\n return (attr) => renaming[attr] || attr;\n }\n}\n\nexport const error = (msg: string) => {\n throw(msg);\n}\n\n// Join helpers\n\n/**\n * Finds attribute names that exist in both left and right tuple arrays.\n * Used for natural joins when no explicit keys are provided.\n *\n * @example\n * const left = [{ id: 1, name: 'Alice', city: 'NYC' }];\n * const right = [{ city: 'NYC', country: 'USA' }];\n * getCommonAttrs(left, right);\n * // => ['city']\n *\n * @example\n * const left = [{ a: 1, b: 2 }];\n * const right = [{ b: 2, c: 3 }];\n * getCommonAttrs(left, right);\n * // => ['b']\n */\nexport const getCommonAttrs = (left: Tuple[], right: Tuple[]): AttrName[] => {\n if (left.length === 0 || right.length === 0) return [];\n const leftAttrs = new Set(Object.keys(left[0]));\n const rightAttrs = Object.keys(right[0]);\n return rightAttrs.filter(attr => leftAttrs.has(attr));\n}\n\n/**\n * Normalizes JoinKeys to a Record<AttrName, AttrName> mapping left attrs to right attrs.\n *\n * @example\n * // undefined => use common attributes\n * normalizeKeys(undefined, [{ id: 1, city: 'NYC' }], [{ city: 'NYC' }]);\n * // => { city: 'city' }\n *\n * @example\n * // Array of common attribute names\n * normalizeKeys(['city', 'country'], leftTuples, rightTuples);\n * // => { city: 'city', country: 'country' }\n *\n * @example\n * // Object mapping left attr to right attr\n * normalizeKeys({ city: 'location' }, leftTuples, rightTuples);\n * // => { city: 'location' }\n */\nexport const normalizeKeys = (keys: JoinKeys | undefined, leftTuples: Tuple[], rightTuples: Tuple[]): Record<AttrName, AttrName> => {\n if (!keys) {\n const common = getCommonAttrs(leftTuples, rightTuples);\n return common.reduce((acc, attr) => {\n acc[attr] = attr;\n return acc;\n }, {} as Record<AttrName, AttrName>);\n }\n if (Array.isArray(keys)) {\n return keys.reduce((acc, attr) => {\n acc[attr] = attr;\n return acc;\n }, {} as Record<AttrName, AttrName>);\n }\n return keys;\n}\n\n/**\n * Checks if two tuples match on the specified key mapping.\n *\n * @example\n * const keyMap = { city: 'location' };\n * tuplesMatch({ id: 1, city: 'NYC' }, { location: 'NYC', pop: 8 }, keyMap);\n * // => true (left.city === right.location)\n *\n * @example\n * const keyMap = { city: 'city' };\n * tuplesMatch({ city: 'NYC' }, { city: 'LA' }, keyMap);\n * // => false\n */\nexport const tuplesMatch = (left: Tuple, right: Tuple, keyMap: Record<AttrName, AttrName>): boolean => {\n for (const [leftAttr, rightAttr] of Object.entries(keyMap)) {\n if (left[leftAttr] !== right[rightAttr]) return false;\n }\n return true;\n}\n\n/**\n * Creates a string key from a tuple's join attributes for fast Set-based lookups.\n * Used by matching/not_matching for efficient semi-join operations.\n *\n * @example\n * const keyMap = { first: 'fname', last: 'lname' };\n *\n * // Left side uses left attr names (keys of keyMap)\n * matchKey({ id: 1, first: 'John', last: 'Doe' }, keyMap, 'left');\n * // => '\"John\"|\"Doe\"'\n *\n * // Right side uses right attr names (values of keyMap)\n * matchKey({ fname: 'John', lname: 'Doe', age: 30 }, keyMap, 'right');\n * // => '\"John\"|\"Doe\"'\n */\nexport const matchKey = (tuple: Tuple, keyMap: Record<AttrName, AttrName>, side: 'left' | 'right'): string => {\n const attrs = side === 'left' ? Object.keys(keyMap) : Object.values(keyMap);\n const values = attrs.map(attr => JSON.stringify(tuple[attr]));\n return values.join('|');\n}\n\n/**\n * Removes join key attributes from a right tuple when merging.\n * Used to avoid duplicate columns in join results.\n *\n * @example\n * const keyMap = { city: 'location' };\n * projectOutKeys({ location: 'NYC', country: 'USA', pop: 8 }, keyMap);\n * // => { country: 'USA', pop: 8 } (location removed)\n *\n * @example\n * const keyMap = { a: 'a', b: 'b' };\n * projectOutKeys({ a: 1, b: 2, c: 3 }, keyMap);\n * // => { c: 3 } (a and b removed)\n */\nexport const projectOutKeys = (tuple: Tuple, keyMap: Record<AttrName, AttrName>): Tuple => {\n const rightKeys = new Set(Object.values(keyMap));\n const result: Tuple = {};\n for (const [attr, value] of Object.entries(tuple)) {\n if (!rightKeys.has(attr)) {\n result[attr] = value;\n }\n }\n return result;\n}\n","import { toPredicateFunc } from \"../support/toPredicateFunc\";\nimport { RelationOperand, Predicate, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const restrict = (operand: RelationOperand, p: Predicate): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const f = toPredicateFunc(p)\n const kept: Tuple[] = [];\n for (const tuple of iterable) {\n if (f(tuple)) kept.push(tuple);\n }\n return op.output(kept)\n}\n","import { toPredicateFunc } from \"../support/toPredicateFunc\";\nimport { RelationOperand, Predicate, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const exclude = (operand: RelationOperand, p: Predicate): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const f = toPredicateFunc(p)\n const kept: Tuple[] = [];\n for (const tuple of iterable) {\n if (!f(tuple)) kept.push(tuple);\n }\n return op.output(kept)\n}\n","import { RelationOperand, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const constants = (operand: RelationOperand, consts: Tuple): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n result.push({ ...tuple, ...consts });\n }\n return op.output(result)\n}\n","import { RelationOperand, Renaming, Tuple } from \"../types\";\nimport { toOperationalOperand, toRenamingFunc } from \"./_helpers\";\n\nexport const rename = (operand: RelationOperand, renaming: Renaming): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const renamingFunc = toRenamingFunc(renaming)\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n const renamed = Object.keys(tuple).reduce((memo, attr) => {\n memo[renamingFunc(attr)] = tuple[attr];\n return memo;\n }, {})\n result.push(renamed);\n }\n return op.output(result)\n}\n","import { PrefixOptions, RelationOperand } from \"../types\";\nimport { rename } from \"./rename\";\n\nexport const prefix = (operand: RelationOperand, pfx: string, options?: PrefixOptions): RelationOperand => {\n const except = new Set(options?.except ?? []);\n return rename(operand, (attr) => except.has(attr) ? attr : `${pfx}${attr}`);\n}\n","import { RelationOperand, SuffixOptions } from \"../types\";\nimport { rename } from \"./rename\";\n\nexport const suffix = (operand: RelationOperand, sfx: string, options?: SuffixOptions): RelationOperand => {\n const except = new Set(options?.except ?? []);\n return rename(operand, (attr) => except.has(attr) ? attr : `${attr}${sfx}`);\n}\n","import { RelationOperand, AttrName, Tuple } from \"../types\";\nimport { toOperationalOperand, deduplicate } from \"./_helpers\";\n\nexport const project = (operand: RelationOperand, attrs: AttrName[]): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n const projected = attrs.reduce((memo, attr) => {\n if (attr in tuple) {\n memo[attr] = tuple[attr];\n }\n return memo;\n }, {} as Tuple);\n result.push(projected);\n }\n return op.output(deduplicate(result));\n}\n","import { RelationOperand, AttrName, Tuple } from \"../types\";\nimport { toOperationalOperand, deduplicate } from \"./_helpers\";\n\nexport const allbut = (operand: RelationOperand, attrs: AttrName[]): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const excluded = new Set(attrs);\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n const projected = Object.keys(tuple).reduce((memo, attr) => {\n if (!excluded.has(attr)) {\n memo[attr] = tuple[attr];\n }\n return memo;\n }, {} as Tuple);\n result.push(projected);\n }\n return op.output(deduplicate(result));\n}\n","import { RelationOperand, Extension, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const extend = (operand: RelationOperand, extension: Extension): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n const extended = { ...tuple };\n for (const [attr, spec] of Object.entries(extension)) {\n if (typeof spec === 'function') {\n extended[attr] = spec(tuple);\n } else {\n extended[attr] = tuple[spec];\n }\n }\n result.push(extended);\n }\n return op.output(result);\n}\n","import { RelationOperand, Tuple } from \"../types\";\nimport { toOperationalOperand, tupleKey } from \"./_helpers\";\n\nexport const union = (left: RelationOperand, right: RelationOperand): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const seen = new Set<string>();\n const result: Tuple[] = [];\n\n for (const tuple of opLeft.tuples()) {\n const key = tupleKey(tuple);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n\n for (const tuple of opRight.tuples()) {\n const key = tupleKey(tuple);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, Tuple } from \"../types\";\nimport { toOperationalOperand, tupleKey } from \"./_helpers\";\n\nexport const minus = (left: RelationOperand, right: RelationOperand): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n\n const rightKeys = new Set<string>();\n for (const tuple of opRight.tuples()) {\n rightKeys.add(tupleKey(tuple));\n }\n\n const seen = new Set<string>();\n const result: Tuple[] = [];\n for (const tuple of opLeft.tuples()) {\n const key = tupleKey(tuple);\n if (!rightKeys.has(key) && !seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, Tuple } from \"../types\";\nimport { toOperationalOperand, tupleKey } from \"./_helpers\";\n\nexport const intersect = (left: RelationOperand, right: RelationOperand): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n\n const rightKeys = new Set<string>();\n for (const tuple of opRight.tuples()) {\n rightKeys.add(tupleKey(tuple));\n }\n\n const seen = new Set<string>();\n const result: Tuple[] = [];\n for (const tuple of opLeft.tuples()) {\n const key = tupleKey(tuple);\n if (rightKeys.has(key) && !seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, JoinKeys, Tuple } from \"../types\";\nimport { toOperationalOperand, normalizeKeys, matchKey } from \"./_helpers\";\n\nexport const matching = (left: RelationOperand, right: RelationOperand, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n\n const rightKeys = new Set<string>();\n for (const tuple of rightTuples) {\n rightKeys.add(matchKey(tuple, keyMap, 'right'));\n }\n\n const result: Tuple[] = [];\n for (const tuple of leftTuples) {\n if (rightKeys.has(matchKey(tuple, keyMap, 'left'))) {\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, JoinKeys, Tuple } from \"../types\";\nimport { toOperationalOperand, normalizeKeys, matchKey } from \"./_helpers\";\n\nexport const not_matching = (left: RelationOperand, right: RelationOperand, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n\n const rightKeys = new Set<string>();\n for (const tuple of rightTuples) {\n rightKeys.add(matchKey(tuple, keyMap, 'right'));\n }\n\n const result: Tuple[] = [];\n for (const tuple of leftTuples) {\n if (!rightKeys.has(matchKey(tuple, keyMap, 'left'))) {\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, JoinKeys, Tuple, AttrName } from \"../types\";\nimport { toOperationalOperand, normalizeKeys, tuplesMatch, projectOutKeys } from \"./_helpers\";\n\nconst mergeTuples = (left: Tuple, right: Tuple, keyMap: Record<AttrName, AttrName>): Tuple => {\n return { ...left, ...projectOutKeys(right, keyMap) };\n}\n\nexport const join = (left: RelationOperand, right: RelationOperand, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n const result: Tuple[] = [];\n\n for (const leftTuple of leftTuples) {\n for (const rightTuple of rightTuples) {\n if (tuplesMatch(leftTuple, rightTuple, keyMap)) {\n result.push(mergeTuples(leftTuple, rightTuple, keyMap));\n }\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, JoinKeys, Tuple, AttrName } from \"../types\";\nimport { toOperationalOperand, normalizeKeys, tuplesMatch } from \"./_helpers\";\n\nconst getRightAttrs = (rightTuples: Tuple[], keyMap: Record<AttrName, AttrName>): AttrName[] => {\n if (rightTuples.length === 0) return [];\n const rightKeys = new Set(Object.values(keyMap));\n return Object.keys(rightTuples[0]).filter(attr => !rightKeys.has(attr));\n}\n\nconst mergeTuples = (left: Tuple, right: Tuple | null, rightAttrs: AttrName[]): Tuple => {\n const result = { ...left };\n for (const attr of rightAttrs) {\n result[attr] = right ? right[attr] : null;\n }\n return result;\n}\n\nexport const left_join = (left: RelationOperand, right: RelationOperand, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n const rightAttrs = getRightAttrs(rightTuples, keyMap);\n const result: Tuple[] = [];\n\n for (const leftTuple of leftTuples) {\n let matched = false;\n for (const rightTuple of rightTuples) {\n if (tuplesMatch(leftTuple, rightTuple, keyMap)) {\n result.push(mergeTuples(leftTuple, rightTuple, rightAttrs));\n matched = true;\n }\n }\n if (!matched) {\n result.push(mergeTuples(leftTuple, null, rightAttrs));\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, Tuple } from \"../types\";\nimport { toOperationalOperand, deduplicate } from \"./_helpers\";\n\nexport const cross_product = (left: RelationOperand, right: RelationOperand): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const result: Tuple[] = [];\n\n for (const l of leftTuples) {\n for (const r of rightTuples) {\n result.push({ ...r, ...l });\n }\n }\n\n return opLeft.output(deduplicate(result));\n}\n\nexport { cross_product as cross_join };\n","import { RelationOperand, JoinKeys, Tuple, AttrName } from \"../types\";\nimport { toOperationalOperand, normalizeKeys, tuplesMatch, projectOutKeys } from \"./_helpers\";\nimport { MemoryRelation } from \"@/Relation\";\n\nexport const image = (left: RelationOperand, right: RelationOperand, as: AttrName, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n const result: Tuple[] = [];\n\n for (const leftTuple of leftTuples) {\n const matches: Tuple[] = [];\n for (const rightTuple of rightTuples) {\n if (tuplesMatch(leftTuple, rightTuple, keyMap)) {\n matches.push(projectOutKeys(rightTuple, keyMap));\n }\n }\n result.push({\n ...leftTuple,\n [as]: new MemoryRelation(matches)\n });\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, AttrName, Tuple, Aggregator, Aggregators } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nconst groupKey = (tuple: Tuple, by: AttrName[]): string => {\n const keyParts = by.map(attr => JSON.stringify(tuple[attr]));\n return keyParts.join('|');\n}\n\nconst pickAttrs = (tuple: Tuple, attrs: AttrName[]): Tuple => {\n return attrs.reduce((acc, attr) => {\n acc[attr] = tuple[attr];\n return acc;\n }, {} as Tuple);\n}\n\nconst applyAggregator = (tuples: Tuple[], agg: Aggregator): unknown => {\n if (typeof agg === 'function') {\n return agg(tuples);\n }\n\n const spec = typeof agg === 'string' ? { op: agg, attr: '' } : agg;\n const { op, attr } = spec;\n\n switch (op) {\n case 'count':\n return tuples.length;\n\n case 'sum': {\n return tuples.reduce((sum, t) => sum + (Number(t[attr]) || 0), 0);\n }\n\n case 'min': {\n const values = tuples.map(t => t[attr]).filter(v => v !== undefined && v !== null);\n return values.length > 0 ? Math.min(...values.map(Number)) : null;\n }\n\n case 'max': {\n const values = tuples.map(t => t[attr]).filter(v => v !== undefined && v !== null);\n return values.length > 0 ? Math.max(...values.map(Number)) : null;\n }\n\n case 'avg': {\n const values = tuples.map(t => Number(t[attr])).filter(v => !isNaN(v));\n return values.length > 0 ? values.reduce((a, b) => a + b, 0) / values.length : null;\n }\n\n case 'collect': {\n return tuples.map(t => t[attr]);\n }\n\n default:\n throw new Error(`Unknown aggregator: ${op}`);\n }\n}\n\nexport const summarize = (\n operand: RelationOperand,\n by: AttrName[],\n aggs: Aggregators\n): RelationOperand => {\n const op = toOperationalOperand(operand);\n const tuples = [...op.tuples()];\n\n // Group tuples\n const groups = new Map<string, Tuple[]>();\n for (const tuple of tuples) {\n const key = groupKey(tuple, by);\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key)!.push(tuple);\n }\n\n // Apply aggregators to each group\n const result: Tuple[] = [];\n for (const groupTuples of groups.values()) {\n const row: Tuple = pickAttrs(groupTuples[0], by);\n for (const [resultAttr, agg] of Object.entries(aggs)) {\n row[resultAttr] = applyAggregator(groupTuples, agg);\n }\n result.push(row);\n }\n\n return op.output(result);\n}\n","import { RelationOperand, AttrName, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\nimport { MemoryRelation } from \"@/Relation\";\n\nconst groupKey = (tuple: Tuple, byAttrs: AttrName[]): string => {\n const keyParts = byAttrs.map(attr => JSON.stringify(tuple[attr]));\n return keyParts.join('|');\n}\n\nconst pickAttrs = (tuple: Tuple, attrs: AttrName[]): Tuple => {\n return attrs.reduce((acc, attr) => {\n acc[attr] = tuple[attr];\n return acc;\n }, {} as Tuple);\n}\n\nexport const group = (operand: RelationOperand, attrs: AttrName[], as: AttrName): RelationOperand => {\n const op = toOperationalOperand(operand);\n const tuples = [...op.tuples()];\n\n if (tuples.length === 0) {\n return op.output([]);\n }\n\n // Determine which attributes to keep at the top level (all except grouped ones)\n const allAttrs = Object.keys(tuples[0]);\n const groupedSet = new Set(attrs);\n const byAttrs = allAttrs.filter(a => !groupedSet.has(a));\n\n // Group tuples\n const groups = new Map<string, { base: Tuple, nested: Tuple[] }>();\n for (const tuple of tuples) {\n const key = groupKey(tuple, byAttrs);\n if (!groups.has(key)) {\n groups.set(key, {\n base: pickAttrs(tuple, byAttrs),\n nested: []\n });\n }\n groups.get(key)!.nested.push(pickAttrs(tuple, attrs));\n }\n\n // Build result with nested relations\n const result: Tuple[] = [];\n for (const { base, nested } of groups.values()) {\n result.push({\n ...base,\n [as]: new MemoryRelation(nested)\n });\n }\n\n return op.output(result);\n}\n","import { RelationOperand, AttrName, Tuple, Relation } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\nimport { isRelation } from \"./isRelation\";\n\nconst toTupleArray = (value: unknown): Tuple[] => {\n if (isRelation(value)) {\n return (value as Relation).toArray();\n }\n if (Array.isArray(value)) {\n return value;\n }\n throw new Error(`Value is not a relation or array`);\n}\n\nexport const ungroup = (operand: RelationOperand, attr: AttrName): RelationOperand => {\n const op = toOperationalOperand(operand);\n const tuples = [...op.tuples()];\n const result: Tuple[] = [];\n\n for (const tuple of tuples) {\n const nested = toTupleArray(tuple[attr]);\n\n // Get base attributes (all except the grouped one)\n const base: Tuple = {};\n for (const [key, value] of Object.entries(tuple)) {\n if (key !== attr) {\n base[key] = value;\n }\n }\n\n // Flatten each nested tuple\n for (const nestedTuple of nested) {\n result.push({\n ...base,\n ...nestedTuple\n });\n }\n }\n\n return op.output(result);\n}\n","import { RelationOperand, AttrName, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const wrap = (operand: RelationOperand, attrs: AttrName[], as: AttrName): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const wrappedSet = new Set(attrs);\n const result: Tuple[] = [];\n\n for (const tuple of iterable) {\n const wrapped: Tuple = {};\n const remaining: Tuple = {};\n\n for (const [key, value] of Object.entries(tuple)) {\n if (wrappedSet.has(key)) {\n wrapped[key] = value;\n } else {\n remaining[key] = value;\n }\n }\n\n result.push({\n ...remaining,\n [as]: wrapped\n });\n }\n\n return op.output(result);\n}\n","import { RelationOperand, AttrName, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const unwrap = (operand: RelationOperand, attr: AttrName): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n\n for (const tuple of iterable) {\n const wrapped = tuple[attr] as Tuple;\n if (typeof wrapped !== 'object' || wrapped === null || Array.isArray(wrapped)) {\n throw new Error(`Attribute '${attr}' is not a tuple (object)`);\n }\n\n const unwrapped: Tuple = {};\n for (const [key, value] of Object.entries(tuple)) {\n if (key !== attr) {\n unwrapped[key] = value;\n }\n }\n\n result.push({\n ...unwrapped,\n ...wrapped\n });\n }\n\n return op.output(result);\n}\n","import { AutowrapOptions, RelationOperand, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const autowrap = (operand: RelationOperand, options?: AutowrapOptions): RelationOperand => {\n const sep = options?.separator ?? '_';\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n\n for (const tuple of iterable) {\n const wrapped: Tuple = {};\n for (const [attr, value] of Object.entries(tuple)) {\n const parts = attr.split(sep);\n if (parts.length === 1) {\n wrapped[attr] = value;\n } else {\n const [prefix, ...rest] = parts;\n wrapped[prefix] = wrapped[prefix] ?? {};\n (wrapped[prefix] as Tuple)[rest.join(sep)] = value;\n }\n }\n result.push(wrapped);\n }\n\n return op.output(result);\n}\n","import { RelationOperand, Transformation, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const transform = (operand: RelationOperand, transformation: Transformation): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n\n for (const tuple of iterable) {\n const transformed: Tuple = {};\n\n for (const [attr, value] of Object.entries(tuple)) {\n transformed[attr] = applyTransformation(value, attr, transformation);\n }\n\n result.push(transformed);\n }\n\n return op.output(result);\n}\n\nconst applyTransformation = (value: unknown, attr: string, transformation: Transformation): unknown => {\n if (typeof transformation === 'function') {\n // Single function - apply to all values\n return transformation(value);\n } else if (Array.isArray(transformation)) {\n // Array of functions - chain them\n return transformation.reduce((v, fn) => fn(v), value);\n } else {\n // Object with attr-specific transformers\n const fn = transformation[attr];\n if (fn) {\n if (Array.isArray(fn)) {\n return fn.reduce((v, f) => f(v), value);\n }\n return fn(value);\n }\n return value;\n }\n}\n","import { RelationOperand } from \"../types\";\nimport { toOperationalOperand, tupleKey } from \"./_helpers\";\n\nexport const isEqual = (left: RelationOperand, right: RelationOperand): boolean => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n\n const leftKeys = new Set<string>();\n for (const tuple of opLeft.tuples()) {\n leftKeys.add(tupleKey(tuple));\n }\n\n const rightKeys = new Set<string>();\n for (const tuple of opRight.tuples()) {\n rightKeys.add(tupleKey(tuple));\n }\n\n if (leftKeys.size !== rightKeys.size) {\n return false;\n }\n\n for (const key of leftKeys) {\n if (!rightKeys.has(key)) {\n return false;\n }\n }\n\n return true;\n}\n","import { RelationOperand, Tuple } from \"../types\";\nimport { toOperationalOperand, error } from \"./_helpers\";\n\nexport const one = (operand: RelationOperand): Tuple => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n let tuple;\n for (const t of iterable) {\n if (tuple) {\n return error('More than one tuple found');\n } else {\n tuple = t;\n }\n }\n if (tuple) return tuple;\n return error('Relation is empty');\n}\n","import { AttrName, RelationOperand, Tuple } from \"../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const yByX = (operand: RelationOperand, y: AttrName, x: AttrName): Tuple => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const hash = {};\n for (const tuple of iterable) {\n hash[`${tuple[x]}`] = tuple[y];\n }\n return hash;\n}\n","export * from './operators';\nexport * from './types';\nexport { LIB_DEFINITIONS } from './lib-definitions';\n\nimport { MemoryRelation } from './Relation';\nimport { isRelation } from './operators';\n\n/**\n * Creates a new in-memory relation from an array of tuples.\n *\n * @typeParam T - The tuple type. Inferred from input or explicitly provided.\n *\n * @example\n * // Untyped usage (backwards compatible)\n * const r = Bmg([{ id: 1, name: 'Alice' }]);\n *\n * @example\n * // Typed usage with explicit type parameter\n * interface Person { id: number; name: string }\n * const r = Bmg<Person>([{ id: 1, name: 'Alice' }]);\n * r.project(['id']); // Autocomplete suggests 'id' | 'name'\n *\n * @example\n * // Type is inferred from input\n * const r = Bmg([{ id: 1, name: 'Alice' }] as const);\n */\nexport function Bmg<T>(tuples: T[]): MemoryRelation<T> {\n return new MemoryRelation<T>(tuples);\n}\n\nBmg.isRelation = isRelation;\n","// Auto-generated from types.ts\n// Run 'npm run generate:lib-definitions' to regenerate\n\nexport const LIB_DEFINITIONS = `\n/**\n * Type definitions for Bmg.js relational algebra library.\n *\n * This file defines all types needed for type-safe relational operations:\n * - Base types (AttrName, Tuple)\n * - Utility types for transformations (Renamed, Prefixed, Joined, etc.)\n * - The Relation interface with all operators\n * - Helper types for predicates, extensions, aggregators, etc.\n */\n\n// ============================================================================\n// Base Types\n// ============================================================================\n\n/** Attribute name in a tuple */\ntype AttrName = string\n\n/** A tuple is a record mapping attribute names to values */\ntype Tuple = Record<AttrName, unknown>\n\n// ============================================================================\n// Rename Types\n// ============================================================================\n\n/** Map from old attribute names to new attribute names */\ntype RenameMap<T> = { [K in keyof T]?: string };\n\n/** Transform tuple type by renaming keys according to RenameMap */\ntype Renamed<T, R extends RenameMap<T>> = {\n [K in keyof T as K extends keyof R ? (R[K] extends string ? R[K] : K) : K]: T[K];\n};\n\n// ============================================================================\n// Prefix/Suffix Types\n// ============================================================================\n\n/** Prefix all keys except those in Except */\ntype Prefixed<T, P extends string, Except extends keyof T = never> = {\n [K in keyof T as K extends Except ? K : \\`\\${P}\\${K & string}\\`]: T[K];\n};\n\n/** Suffix all keys except those in Except */\ntype Suffixed<T, S extends string, Except extends keyof T = never> = {\n [K in keyof T as K extends Except ? K : \\`\\${K & string}\\${S}\\`]: T[K];\n};\n\n// ============================================================================\n// Join Types\n// ============================================================================\n\n/** Extract common keys between two tuple types */\ntype CommonKeys<L, R> = Extract<keyof L, keyof R>;\n\n/** Result of inner join: L & R with R's common keys removed */\ntype Joined<L, R> = L & Omit<R, CommonKeys<L, R>>;\n\n/** Result of left join: L & optional R attributes (common keys removed) */\ntype LeftJoined<L, R> = L & Partial<Omit<R, CommonKeys<L, R>>>;\n\n/**\n * Typed join keys for array form: keys must exist on BOTH operands.\n * Example: suppliers.join(parts, ['city']) - 'city' must be a key of both.\n */\ntype TypedJoinKeysArray<L, R> = (keyof L & keyof R & string)[];\n\n/**\n * Typed join keys for object form: maps left keys to right keys.\n * Example: suppliers.join(parts, { sid: 'supplier_id' })\n * - Left key (sid) must exist on L\n * - Right key (supplier_id) must exist on R\n */\ntype TypedJoinKeysObject<L, R> = { [K in keyof L & string]?: keyof R & string };\n\n// ============================================================================\n// Wrap/Unwrap Types\n// ============================================================================\n\n/** Result of wrap: remove wrapped attrs, add nested object */\ntype Wrapped<T, K extends keyof T, As extends string> =\n Omit<T, K> & Record<As, Pick<T, K>>;\n\n/** Result of unwrap: remove object attr, spread its properties */\ntype Unwrapped<T, K extends keyof T> =\n T[K] extends Record<string, unknown> ? Omit<T, K> & T[K] : Omit<T, K>;\n\n/** Result of ungroup: remove relation attr, flatten its tuple type */\ntype Ungrouped<T, K extends keyof T> =\n T[K] extends Relation<infer N> ? Omit<T, K> & N : Omit<T, K>;\n\n// ============================================================================\n// Aggregator Types\n// ============================================================================\n\ntype AggregatorName = 'count' | 'sum' | 'min' | 'max' | 'avg' | 'collect'\ntype AggregatorSpec = { op: AggregatorName, attr: AttrName }\ntype AggregatorFunc = (tuples: Tuple[]) => unknown\ntype Aggregator = AggregatorName | AggregatorSpec | AggregatorFunc\ntype Aggregators = Record<AttrName, Aggregator>\n\n/** Infer result type from aggregator specification */\ntype AggregatorResult<A> =\n A extends 'count' ? number :\n A extends { op: 'count' } ? number :\n A extends { op: 'sum' | 'avg' | 'min' | 'max' } ? number | null :\n A extends { op: 'collect' } ? unknown[] :\n A extends (tuples: Tuple[]) => infer R ? R :\n unknown;\n\n/** Map aggregator definitions to their result types */\ntype AggregatorResults<Aggs extends Record<string, unknown>> = {\n [K in keyof Aggs]: AggregatorResult<Aggs[K]>;\n};\n\n// ============================================================================\n// Predicate Types\n// ============================================================================\n\n/** Predicate function that receives a typed tuple */\ntype TypedPredicateFunc<T> = (t: T) => boolean\n\n/** Predicate: either a partial tuple for equality matching, or a function */\ntype TypedPredicate<T> = Partial<T> | TypedPredicateFunc<T>\n\n// Legacy predicate types (for backwards compatibility with standalone operators)\ntype PredicateFunc = ((t: Tuple) => any)\ntype Predicate = Tuple | PredicateFunc\n\n// ============================================================================\n// Extension Types\n// ============================================================================\n\n/** Extension function that receives a typed tuple */\ntype TypedExtensionFunc<T, R> = (tuple: T) => R\n\n/** Extension definition: function returning value, or attribute name to copy */\ntype TypedExtension<T, E extends Record<string, unknown>> = {\n [K in keyof E]: TypedExtensionFunc<T, E[K]> | keyof T;\n}\n\ntype ExtensionFunc = (tuple: Tuple) => unknown\ntype Extension = Record<AttrName, ExtensionFunc | AttrName>\n\n// ============================================================================\n// Other Helper Types\n// ============================================================================\n\ninterface PrefixOptions {\n except?: AttrName[]\n}\n\ninterface SuffixOptions {\n except?: AttrName[]\n}\n\ninterface AutowrapOptions {\n separator?: string\n}\n\ntype Renaming = RenamingObj | RenamingFunc\ntype RenamingFunc = (attr: AttrName) => AttrName\ntype RenamingObj = Record<AttrName, AttrName>\n\ntype JoinKeys = AttrName[] | Record<AttrName, AttrName>\n\ntype TransformFunc = (value: unknown) => unknown\ntype Transformation = TransformFunc | TransformFunc[] | Record<AttrName, TransformFunc | TransformFunc[]>\n\n// ============================================================================\n// Relation Interface\n// ============================================================================\n\n/**\n * Relation interface with generic type parameter for tuple type.\n * Default parameter \\`Tuple\\` ensures backwards compatibility.\n *\n * @typeParam T - The tuple type for this relation. Defaults to \\`Tuple\\` (Record<string, unknown>).\n *\n * @example\n * // Untyped usage (backwards compatible)\n * const r = Bmg([{ id: 1 }]); // Relation<Tuple>\n *\n * @example\n * // Typed usage with full type safety\n * interface Person { id: number; name: string }\n * const r = Bmg<Person>([{ id: 1, name: 'Alice' }]);\n * r.project(['id']); // Relation<{ id: number }>\n */\ninterface Relation<T = Tuple> {\n // === Type-preserving operators ===\n\n restrict(p: TypedPredicate<T>): Relation<T>\n where(p: TypedPredicate<T>): Relation<T>\n exclude(p: TypedPredicate<T>): Relation<T>\n\n // === Projection operators ===\n\n project<K extends keyof T>(attrs: K[]): Relation<Pick<T, K>>\n allbut<K extends keyof T>(attrs: K[]): Relation<Omit<T, K>>\n\n // === Extension operators ===\n\n extend<E extends Record<string, unknown>>(e: TypedExtension<T, E>): Relation<T & E>\n constants<C extends Tuple>(consts: C): Relation<T & C>\n\n // === Rename operators ===\n\n rename<R extends RenameMap<T>>(r: R): Relation<Renamed<T, R>>\n prefix<P extends string, Ex extends keyof T = never>(pfx: P, options?: { except?: Ex[] }): Relation<Prefixed<T, P, Ex>>\n suffix<S extends string, Ex extends keyof T = never>(sfx: S, options?: { except?: Ex[] }): Relation<Suffixed<T, S, Ex>>\n\n // === Set operators (require same type) ===\n\n union(right: RelationOperand<T>): Relation<T>\n minus(right: RelationOperand<T>): Relation<T>\n intersect(right: RelationOperand<T>): Relation<T>\n\n // === Semi-join operators (preserve left type) ===\n\n matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T>\n not_matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T>\n\n // === Join operators ===\n\n join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<Joined<T, R>>\n left_join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<LeftJoined<T, R>>\n cross_product<R>(right: RelationOperand<R>): Relation<T & R>\n cross_join<R>(right: RelationOperand<R>): Relation<T & R>\n\n // === Nesting operators ===\n\n image<R, As extends string>(right: RelationOperand<R>, as: As, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T & Record<As, Relation<Omit<R, keyof T & keyof R>>>>\n group<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Omit<T, K> & Record<As, Relation<Pick<T, K>>>>\n ungroup<K extends keyof T>(attr: K): Relation<Ungrouped<T, K>>\n wrap<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Wrapped<T, K, As>>\n unwrap<K extends keyof T>(attr: K): Relation<Unwrapped<T, K>>\n\n // === Aggregation ===\n\n summarize<By extends keyof T, Aggs extends Aggregators>(by: By[], aggs: Aggs): Relation<Pick<T, By> & AggregatorResults<Aggs>>\n\n // === Transform ===\n\n transform(t: Transformation): Relation<T>\n\n // === Dynamic (loses type precision) ===\n\n autowrap(options?: AutowrapOptions): Relation<Tuple>\n\n // === Non-relational ===\n\n one(): T\n yByX<Y extends keyof T, X extends keyof T>(y: Y, x: X): Record<T[X] & PropertyKey, T[Y]>\n toArray(): T[]\n isEqual(right: any): boolean\n}\n\n// ============================================================================\n// Operands\n// ============================================================================\n\ntype RelationOperand<T = Tuple> = Relation<T> | T[]\n\ninterface OperationalOperand<T = Tuple> {\n tuples(): Iterable<T>\n output(tuples: T[]): RelationOperand<T>\n}\n\n// ============================================================================\n// Bmg Function Declaration\n// ============================================================================\n\n/** Create a relation from an array of tuples */\ndeclare function Bmg<T>(tuples: T[]): Relation<T>\ndeclare namespace Bmg {\n function isRelation(op: unknown): boolean\n}\n`\n"],"names":["toPredicateFunc","p","expected","t","Object","keys","every","k","MemoryRelation","tuples","this","_proto","prototype","restrict","where","exclude","project","attrs","allbut","extend","e","constants","consts","rename","r","prefix","pfx","options","suffix","sfx","union","right","minus","intersect","matching","not_matching","join","left_join","cross_product","cross_join","image","as","group","ungroup","attr","wrap","unwrap","summarize","by","aggs","transform","autowrap","one","toArray","yByX","y","x","isEqual","isRelation","op","constructor","tupleKey","tuple","entries","map","_ref","v","value","sort","JSON","stringify","_ref2","_ref3","localeCompare","deduplicate","_step","seen","Set","result","_iterator","_createForOfIteratorHelperLoose","done","key","has","add","push","toOperationalOperand","operand","Array","isArray","output","error","msg","normalizeKeys","leftTuples","rightTuples","reduce","acc","left","length","leftAttrs","filter","getCommonAttrs","tuplesMatch","keyMap","_i","_Object$entries","_Object$entries$_i","matchKey","side","values","projectOutKeys","rightKeys","_i2","_Object$entries2","_Object$entries2$_i","iterable","f","kept","_extends","renaming","renamingFunc","toRenamingFunc","_loop","renamed","memo","_options$except","except","projected","excluded","extension","extended","spec","opLeft","opRight","_step2","_iterator2","concat","mergeTuples","leftTuple","rightTuple","rightAttrs","getRightAttrs","_step3","matched","_iterator3","l","_extends2","matches","groupKey","pickAttrs","applyAggregator","agg","sum","Number","Math","min","apply","max","isNaN","a","b","Error","groups","Map","set","get","groupTuples","row","byAttrs","allAttrs","groupedSet","base","nested","_step2$value","toTupleArray","wrappedSet","wrapped","remaining","unwrapped","_options$separator","sep","separator","parts","split","_wrapped$prefix","rest","_arrayLikeToArray","slice","transformation","transformed","applyTransformation","fn","leftKeys","size","hash","Bmg"],"mappings":"4/BAEa,IAAAA,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4C,EAJ7B0D,EAAS/C,EAAqBY,GAC9BoC,EAAUhD,EAAqBvD,GAE/BkK,EAAW,IAAIpH,IACrBE,EAAAC,EAAoBqD,EAAO5H,YAAQkE,EAAAI,KAAAE,MACjCgH,EAAS7G,IAAIvB,EADCc,EAAAR,QAKhB,IADA,IACoCoE,EAD9BvB,EAAY,IAAInC,IACtB2D,EAAAxD,EAAoBsD,EAAQ7H,YAAQ8H,EAAAC,KAAAvD,MAClC+B,EAAU5B,IAAIvB,EADA0E,EAAApE,QAIhB,GAAI8H,EAASC,OAASlF,EAAUkF,KAC9B,OACD,EAED,QAA0BnD,EAA1BE,EAAAjE,EAAkBiH,KAAQlD,EAAAE,KAAAhE,MACxB,IAAK+B,EAAU7B,IADH4D,EAAA5E,OAEV,OAAO,EAIX,QACF,ECzBaf,EAAM,SAACmC,GAIlB,IAHA,IAEIzB,EACoBa,EAAxBI,EAAAC,EAHWM,EAAqBC,GACZ9E,YAEIkE,EAAAI,KAAAE,MAAE,KAAf9E,EAACwE,EAAAR,MACV,GAAIL,EACF,OAAO6B,EAAM,6BAEb7B,EAAQ3D,CAEX,CACD,OAAI2D,GACG6B,EAAM,oBACf,ECbarC,EAAO,SAACiC,EAA0BhC,EAAaC,GAI1D,IAHA,IAG4BmB,EADtBwH,EAAO,CAAE,EACfpH,EAAAC,EAHWM,EAAqBC,GACZ9E,YAEQkE,EAAAI,KAAAE,MAAE,KAAnBnB,EAAKa,EAAAR,MACdgI,EAAQrI,GAAAA,EAAMN,IAAQM,EAAMP,EAC7B,CACD,OAAO4I,CACT,ECeM,SAAUC,EAAO3L,GACrB,OAAW,IAAAD,EAAkBC,EAC/B,CAEA2L,EAAI1I,WAAaA,wCC0PhB"}
1
+ {"version":3,"file":"bmg.cjs","sources":["../src/support/toPredicateFunc.ts","../src/sync/operators/isRelation.ts","../src/writer/Text.ts","../src/sync/Relation/Memory.ts","../src/sync/operators/_helpers.ts","../src/sync/operators/restrict.ts","../src/sync/operators/exclude.ts","../src/sync/operators/constants.ts","../src/sync/operators/rename.ts","../src/sync/operators/prefix.ts","../src/sync/operators/suffix.ts","../src/sync/operators/project.ts","../src/sync/operators/allbut.ts","../src/sync/operators/extend.ts","../src/sync/operators/union.ts","../src/sync/operators/minus.ts","../src/sync/operators/intersect.ts","../src/sync/operators/matching.ts","../src/sync/operators/not_matching.ts","../src/sync/operators/join.ts","../src/sync/operators/left_join.ts","../src/sync/operators/cross_product.ts","../src/sync/operators/image.ts","../src/sync/operators/summarize.ts","../src/sync/operators/group.ts","../src/sync/operators/ungroup.ts","../src/sync/operators/wrap.ts","../src/sync/operators/unwrap.ts","../src/sync/operators/autowrap.ts","../src/sync/operators/transform.ts","../src/sync/operators/isEqual.ts","../src/sync/operators/one.ts","../src/sync/operators/yByX.ts","../src/index.ts","../src/lib-definitions.ts"],"sourcesContent":["import { Predicate, PredicateFunc, Tuple } from '../types';\n\nexport const toPredicateFunc = (p: Predicate): PredicateFunc => {\n if (typeof(p) === 'function') {\n return p as PredicateFunc;\n } else {\n const expected = p as Tuple;\n return (t: Tuple) => {\n return Object.keys(expected).every(k => t[k] === expected[k])\n }\n }\n}\n","import { MemoryRelation } from \"@/sync/Relation\";\nimport { Relation } from \"@/types\";\n\nexport const isRelation = (op: unknown): op is Relation => {\n return op != null && (op as object).constructor === MemoryRelation;\n}\n","import { Relation, Tuple } from '../types';\nimport { isRelation } from '../sync/operators/isRelation';\n\n/**\n * Options for text rendering\n */\nexport interface TextOptions {\n /** Format string for floating point numbers (default: '%.3f' style) */\n floatPrecision?: number;\n /** Maximum width to trim output at */\n trimAt?: number;\n}\n\n// Type guards\nconst isTupleLike = (t: unknown): t is Tuple =>\n t !== null && typeof t === 'object' && !Array.isArray(t);\n\nconst isRelationLike = (r: unknown): r is Relation | Tuple[] =>\n isRelation(r) || (Array.isArray(r) && r.every(isTupleLike));\n\n/**\n * Utility function to get max of two nullable numbers\n */\nconst max = (x: number | null, y: number | null): number => {\n if (x === null) return y ?? 0;\n if (y === null) return x;\n return x > y ? x : y;\n};\n\n/**\n * Represents a single cell in the table\n */\nclass Cell {\n private value: unknown;\n private renderer: TextWriter;\n private _textRendering: string | null = null;\n private _minWidth: number | null = null;\n\n constructor(renderer: TextWriter, value: unknown) {\n this.renderer = renderer;\n this.value = value;\n }\n\n get minWidth(): number {\n if (this._minWidth === null) {\n this._minWidth = this.renderingLines().reduce(\n (maxLen, line) => max(maxLen, line.length),\n 0\n );\n }\n return this._minWidth;\n }\n\n renderingLines(size?: number): string[] {\n if (size === undefined) {\n return this.textRendering.split('\\n');\n } else if (typeof this.value === 'number') {\n // Right-align numbers\n return this.renderingLines().map(l => l.padStart(size));\n } else {\n // Left-align other values\n return this.renderingLines().map(l => l.padEnd(size));\n }\n }\n\n get textRendering(): string {\n if (this._textRendering === null) {\n this._textRendering = this.computeTextRendering();\n }\n return this._textRendering;\n }\n\n private computeTextRendering(): string {\n const value = this.value;\n\n if (value === null) {\n return '[null]';\n }\n if (value === undefined) {\n return '[undefined]';\n }\n if (typeof value === 'symbol') {\n return value.toString();\n }\n if (typeof value === 'number') {\n if (Number.isInteger(value)) {\n return String(value);\n }\n const precision = this.renderer.options.floatPrecision ?? 3;\n return value.toFixed(precision);\n }\n if (isRelationLike(value)) {\n return this.renderer.render(value, '');\n }\n if (Array.isArray(value)) {\n return this.arrayRendering(value);\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n return String(value);\n }\n\n private arrayRendering(value: unknown[]): string {\n if (value.length > 0 && isTupleLike(value[0])) {\n return this.renderer.render(value as Tuple[], '');\n }\n if (value.length === 0) {\n return '[]';\n }\n const values = value.map(x => {\n const cell = new Cell(this.renderer, x);\n return cell.textRendering;\n });\n const totalLength = values.reduce((sum, s) => sum + s.length, 0);\n if (totalLength < 20) {\n return '[' + values.join(', ') + ']';\n } else {\n return '[' + values.join(',\\n ') + ']';\n }\n }\n}\n\n/**\n * Represents a row of cells in the table\n */\nclass Row {\n private cells: Cell[];\n\n constructor(renderer: TextWriter, values: unknown[]) {\n this.cells = values.map(v => new Cell(renderer, v));\n }\n\n minWidths(): number[] {\n return this.cells.map(cell => cell.minWidth);\n }\n\n renderingLines(sizes: number[]): string[] {\n let nbLines = 0;\n const byCell = this.cells.map((cell, i) => {\n const lines = cell.renderingLines(sizes[i]);\n nbLines = max(nbLines, lines.length);\n return lines;\n });\n\n const grid: string[] = [];\n for (let lineI = 0; lineI < nbLines; lineI++) {\n const lineContent = byCell\n .map((cellLines, i) => cellLines[lineI] ?? ' '.repeat(sizes[i]))\n .join(' | ');\n grid.push('| ' + lineContent + ' |');\n }\n\n return grid.length === 0 ? ['| |'] : grid;\n }\n}\n\n/**\n * Represents the entire table structure\n */\nclass Table {\n private renderer: TextWriter;\n private header: Row;\n private rows: Row[];\n private _sizes: number[] | null = null;\n private _sep: string | null = null;\n\n constructor(renderer: TextWriter, records: unknown[][], attributes: string[]) {\n this.renderer = renderer;\n this.header = new Row(renderer, attributes);\n this.rows = records.map(r => new Row(renderer, r));\n }\n\n get sizes(): number[] {\n if (this._sizes === null) {\n const headerWidths = this.header.minWidths();\n this._sizes = this.rows.reduce((memo, row) => {\n const rowWidths = row.minWidths();\n return memo.map((w, i) => max(w, rowWidths[i] ?? 0));\n }, headerWidths);\n }\n return this._sizes;\n }\n\n get sep(): string {\n if (this._sep === null) {\n this._sep = '+-' + this.sizes.map(s => '-'.repeat(s)).join('-+-') + '-+';\n }\n return this._sep;\n }\n\n *eachLine(): Generator<string> {\n const trimAt = this.renderer.options.trimAt;\n\n if (trimAt !== undefined) {\n for (const line of this.eachLineRaw()) {\n yield line.substring(0, trimAt);\n }\n } else {\n yield* this.eachLineRaw();\n }\n }\n\n private *eachLineRaw(): Generator<string> {\n yield this.sep;\n yield this.header.renderingLines(this.sizes)[0];\n yield this.sep;\n for (const row of this.rows) {\n for (const line of row.renderingLines(this.sizes)) {\n yield line;\n }\n }\n yield this.sep;\n }\n\n *[Symbol.iterator](): Generator<string> {\n for (const line of this.eachLine()) {\n yield line.trimEnd() + '\\n';\n }\n }\n\n toString(): string {\n let result = '';\n for (const line of this) {\n result += line;\n }\n return result;\n }\n}\n\n/**\n * Text writer for rendering relations as ASCII tables\n */\nexport class TextWriter {\n readonly options: TextOptions;\n\n constructor(options: TextOptions = {}) {\n this.options = options;\n }\n\n /**\n * Renders a relation or tuple array to an ASCII table string\n */\n render(input: Relation | Tuple[] | Tuple, output: string = ''): string {\n for (const line of this.eachLine(input)) {\n output += line;\n }\n return output;\n }\n\n *eachLine(input: Relation | Tuple[] | Tuple): Generator<string> {\n // Handle single tuple\n let tuples: Tuple[];\n if (isTupleLike(input) && !isRelation(input)) {\n tuples = [input];\n } else if (isRelation(input)) {\n tuples = input.toArray();\n } else {\n tuples = input;\n }\n\n // Collect all attribute names across all tuples\n const attrs = tuples.reduce((memo: string[], tuple) => {\n for (const key of Object.keys(tuple)) {\n if (!memo.includes(key)) {\n memo.push(key);\n }\n }\n return memo;\n }, []);\n\n // Build records array (values in attribute order)\n const records = tuples.map(t => attrs.map(a => t[a]));\n\n const table = new Table(this, records, attrs);\n yield* table;\n }\n}\n\n/**\n * Renders a relation as an ASCII table string\n *\n * @param operand - The relation or tuple array to render\n * @param options - Text rendering options\n * @returns ASCII table string representation\n *\n * @example\n * const r = Bmg([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);\n * console.log(toText(r));\n * // +----+-------+\n * // | id | name |\n * // +----+-------+\n * // | 1 | Alice |\n * // | 2 | Bob |\n * // +----+-------+\n */\nexport const toText = (\n operand: Relation | Tuple[] | Tuple,\n options: TextOptions = {}\n): string => {\n return new TextWriter(options).render(operand);\n};\n","import {\n allbut,\n autowrap,\n constants,\n cross_product,\n exclude,\n extend,\n group,\n image,\n intersect,\n isEqual,\n join,\n left_join,\n matching,\n minus,\n not_matching,\n one,\n prefix,\n project,\n rename,\n restrict,\n suffix,\n summarize,\n where,\n transform,\n ungroup,\n union,\n unwrap,\n wrap,\n yByX,\n} from \"../operators\";\nimport type {\n AttrName,\n AutowrapOptions,\n Relation,\n RelationOperand,\n TextOptions,\n Transformation,\n Tuple,\n TypedPredicate,\n TypedExtension,\n RenameMap,\n Renamed,\n Prefixed,\n Suffixed,\n Joined,\n LeftJoined,\n Wrapped,\n Unwrapped,\n Ungrouped,\n AggregatorResults,\n TypedJoinKeysArray,\n TypedJoinKeysObject,\n} from \"../../types\";\nimport { toText } from \"../../writer\";\n\n/**\n * In-memory implementation of the Relation interface.\n *\n * @typeParam T - The tuple type for this relation. Defaults to `Tuple` (Record<string, unknown>).\n */\nexport class MemoryRelation<T = Tuple> implements Relation<T> {\n\n constructor(private tuples: T[]) {\n this.tuples = tuples;\n }\n\n // === Type-preserving operators ===\n\n restrict(p: TypedPredicate<T>): Relation<T> {\n return restrict(this as any, p as any) as unknown as Relation<T>;\n }\n\n where(p: TypedPredicate<T>): Relation<T> {\n return where(this as any, p as any) as unknown as Relation<T>;\n }\n\n exclude(p: TypedPredicate<T>): Relation<T> {\n return exclude(this as any, p as any) as unknown as Relation<T>;\n }\n\n // === Projection operators ===\n\n project<K extends keyof T>(attrs: K[]): Relation<Pick<T, K>> {\n return project(this as any, attrs as AttrName[]) as unknown as Relation<Pick<T, K>>;\n }\n\n allbut<K extends keyof T>(attrs: K[]): Relation<Omit<T, K>> {\n return allbut(this as any, attrs as AttrName[]) as unknown as Relation<Omit<T, K>>;\n }\n\n // === Extension operators ===\n\n extend<E extends Record<string, unknown>>(e: TypedExtension<T, E>): Relation<T & E> {\n return extend(this as any, e as any) as unknown as Relation<T & E>;\n }\n\n constants<C extends Tuple>(consts: C): Relation<T & C> {\n return constants(this as any, consts) as unknown as Relation<T & C>;\n }\n\n // === Rename operators ===\n\n rename<R extends RenameMap<T>>(r: R): Relation<Renamed<T, R>> {\n return rename(this as any, r as any) as unknown as Relation<Renamed<T, R>>;\n }\n\n prefix<P extends string, Ex extends keyof T = never>(pfx: P, options?: { except?: Ex[] }): Relation<Prefixed<T, P, Ex>> {\n return prefix(this as any, pfx, options as any) as unknown as Relation<Prefixed<T, P, Ex>>;\n }\n\n suffix<S extends string, Ex extends keyof T = never>(sfx: S, options?: { except?: Ex[] }): Relation<Suffixed<T, S, Ex>> {\n return suffix(this as any, sfx, options as any) as unknown as Relation<Suffixed<T, S, Ex>>;\n }\n\n // === Set operators ===\n\n union(right: RelationOperand<T>): Relation<T> {\n return union(this as any, right as any) as unknown as Relation<T>;\n }\n\n minus(right: RelationOperand<T>): Relation<T> {\n return minus(this as any, right as any) as unknown as Relation<T>;\n }\n\n intersect(right: RelationOperand<T>): Relation<T> {\n return intersect(this as any, right as any) as unknown as Relation<T>;\n }\n\n // === Semi-join operators ===\n\n matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T> {\n return matching(this as any, right as any, keys as any) as unknown as Relation<T>;\n }\n\n not_matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T> {\n return not_matching(this as any, right as any, keys as any) as unknown as Relation<T>;\n }\n\n // === Join operators ===\n\n join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<Joined<T, R>> {\n return join(this as any, right as any, keys as any) as unknown as Relation<Joined<T, R>>;\n }\n\n left_join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<LeftJoined<T, R>> {\n return left_join(this as any, right as any, keys as any) as unknown as Relation<LeftJoined<T, R>>;\n }\n\n cross_product<R>(right: RelationOperand<R>): Relation<T & R> {\n return cross_product(this as any, right as any) as unknown as Relation<T & R>;\n }\n\n cross_join<R>(right: RelationOperand<R>): Relation<T & R> {\n return cross_product(this as any, right as any) as unknown as Relation<T & R>;\n }\n\n // === Nesting operators ===\n\n image<R, As extends string>(right: RelationOperand<R>, as: As, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T & Record<As, Relation<Omit<R, keyof T & keyof R>>>> {\n return image(this as any, right as any, as, keys as any) as unknown as Relation<T & Record<As, Relation<Omit<R, keyof T & keyof R>>>>;\n }\n\n group<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Omit<T, K> & Record<As, Relation<Pick<T, K>>>> {\n return group(this as any, attrs as AttrName[], as) as unknown as Relation<Omit<T, K> & Record<As, Relation<Pick<T, K>>>>;\n }\n\n ungroup<K extends keyof T>(attr: K): Relation<Ungrouped<T, K>> {\n return ungroup(this as any, attr as AttrName) as unknown as Relation<Ungrouped<T, K>>;\n }\n\n wrap<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Wrapped<T, K, As>> {\n return wrap(this as any, attrs as AttrName[], as) as unknown as Relation<Wrapped<T, K, As>>;\n }\n\n unwrap<K extends keyof T>(attr: K): Relation<Unwrapped<T, K>> {\n return unwrap(this as any, attr as AttrName) as unknown as Relation<Unwrapped<T, K>>;\n }\n\n // === Aggregation ===\n\n summarize<By extends keyof T, Aggs extends Record<string, unknown>>(by: By[], aggs: Aggs): Relation<Pick<T, By> & AggregatorResults<Aggs>> {\n return summarize(this as any, by as AttrName[], aggs as any) as unknown as Relation<Pick<T, By> & AggregatorResults<Aggs>>;\n }\n\n // === Transform ===\n\n transform(t: Transformation): Relation<T> {\n return transform(this as any, t) as unknown as Relation<T>;\n }\n\n // === Dynamic ===\n\n autowrap(options?: AutowrapOptions): Relation<Tuple> {\n return autowrap(this as any, options) as Relation<Tuple>;\n }\n\n // === Non-relational ===\n\n one(): T {\n return one(this as any) as T;\n }\n\n toArray(): T[] {\n return this.tuples;\n }\n\n yByX<Y extends keyof T, X extends keyof T>(y: Y, x: X): Record<T[X] & PropertyKey, T[Y]> {\n return yByX(this as any, y as AttrName, x as AttrName) as Record<T[X] & PropertyKey, T[Y]>;\n }\n\n isEqual(right: any): boolean {\n return isEqual(this as any, right as any);\n }\n\n // === Display ===\n\n toText(options?: TextOptions): string {\n return toText(this as any, options);\n }\n\n}\n","import { OperationalOperand, Relation, RelationOperand, Renaming, RenamingFunc, Tuple, JoinKeys, AttrName } from \"@/types\";\nimport { MemoryRelation } from '@/sync/Relation';\nimport { isRelation } from \"./isRelation\";\n\nconst valueKey = (value: unknown): unknown => {\n if (isRelation(value)) {\n // For nested relations, convert to sorted array of tuple keys for comparison\n const tuples = (value as Relation).toArray();\n const keys = tuples.map(t => tupleKey(t)).sort();\n return keys;\n }\n return value;\n}\n\n/**\n * Generates a unique string key for a tuple, used for equality comparison and deduplication.\n * Handles nested relations by converting them to sorted tuple keys.\n *\n * @example\n * tupleKey({ name: 'Alice', age: 30 })\n * // => '[[\"age\",30],[\"name\",\"Alice\"]]'\n *\n * @example\n * tupleKey({ id: 1, items: Bmg([{ x: 1 }, { x: 2 }]) })\n * // => '[[\"id\",1],[\"items\",[...]]]' (nested relation converted to sorted keys)\n */\nexport const tupleKey = (tuple: Tuple): string => {\n const entries = Object.entries(tuple).map(([k, v]) => [k, valueKey(v)]);\n return JSON.stringify(entries.sort(([a], [b]) => (a as string).localeCompare(b as string)));\n}\n\n/**\n * Removes duplicate tuples from an array, preserving order of first occurrence.\n * Uses tupleKey() for equality comparison.\n *\n * @example\n * deduplicate([\n * { id: 1, name: 'Alice' },\n * { id: 2, name: 'Bob' },\n * { id: 1, name: 'Alice' }, // duplicate\n * ])\n * // => [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]\n */\nexport const deduplicate = (tuples: Tuple[]): Tuple[] => {\n const seen = new Set<string>();\n const result: Tuple[] = [];\n for (const tuple of tuples) {\n const key = tupleKey(tuple);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n return result;\n}\n\n/**\n * Converts a RelationOperand (Relation or Tuple[]) to an OperationalOperand\n * that provides a uniform interface for iteration and output.\n *\n * @example\n * // With array input, output remains array\n * const op = toOperationalOperand([{ id: 1 }]);\n * [...op.tuples()]; // => [{ id: 1 }]\n * op.output([{ id: 2 }]); // => [{ id: 2 }]\n *\n * @example\n * // With Relation input, output is a new Relation\n * const op = toOperationalOperand(Bmg([{ id: 1 }]));\n * [...op.tuples()]; // => [{ id: 1 }]\n * op.output([{ id: 2 }]); // => Bmg([{ id: 2 }])\n */\nexport const toOperationalOperand = (operand: RelationOperand): OperationalOperand => {\n if (Array.isArray(operand)) {\n return {\n tuples: () => operand,\n output: (tuples) => tuples,\n };\n } else if (isRelation(operand)) {\n return {\n tuples: () => (operand as Relation).toArray(),\n output: (tuples) => new MemoryRelation(tuples),\n };\n } else {\n throw `Unable to iterate ${operand}`\n }\n}\n\n/**\n * Converts a Renaming (object or function) to a RenamingFunc.\n *\n * @example\n * // Object renaming\n * const fn = toRenamingFunc({ name: 'fullName', age: 'years' });\n * fn('name'); // => 'fullName'\n * fn('age'); // => 'years'\n * fn('other'); // => 'other' (unchanged)\n *\n * @example\n * // Function renaming (passed through)\n * const fn = toRenamingFunc(attr => attr.toUpperCase());\n * fn('name'); // => 'NAME'\n */\nexport const toRenamingFunc = (renaming: Renaming): RenamingFunc => {\n if (typeof(renaming) === 'function') {\n return renaming;\n } else {\n return (attr) => renaming[attr] || attr;\n }\n}\n\nexport const error = (msg: string) => {\n throw(msg);\n}\n\n// Join helpers\n\n/**\n * Finds attribute names that exist in both left and right tuple arrays.\n * Used for natural joins when no explicit keys are provided.\n *\n * @example\n * const left = [{ id: 1, name: 'Alice', city: 'NYC' }];\n * const right = [{ city: 'NYC', country: 'USA' }];\n * getCommonAttrs(left, right);\n * // => ['city']\n *\n * @example\n * const left = [{ a: 1, b: 2 }];\n * const right = [{ b: 2, c: 3 }];\n * getCommonAttrs(left, right);\n * // => ['b']\n */\nexport const getCommonAttrs = (left: Tuple[], right: Tuple[]): AttrName[] => {\n if (left.length === 0 || right.length === 0) return [];\n const leftAttrs = new Set(Object.keys(left[0]));\n const rightAttrs = Object.keys(right[0]);\n return rightAttrs.filter(attr => leftAttrs.has(attr));\n}\n\n/**\n * Normalizes JoinKeys to a Record<AttrName, AttrName> mapping left attrs to right attrs.\n *\n * @example\n * // undefined => use common attributes\n * normalizeKeys(undefined, [{ id: 1, city: 'NYC' }], [{ city: 'NYC' }]);\n * // => { city: 'city' }\n *\n * @example\n * // Array of common attribute names\n * normalizeKeys(['city', 'country'], leftTuples, rightTuples);\n * // => { city: 'city', country: 'country' }\n *\n * @example\n * // Object mapping left attr to right attr\n * normalizeKeys({ city: 'location' }, leftTuples, rightTuples);\n * // => { city: 'location' }\n */\nexport const normalizeKeys = (keys: JoinKeys | undefined, leftTuples: Tuple[], rightTuples: Tuple[]): Record<AttrName, AttrName> => {\n if (!keys) {\n const common = getCommonAttrs(leftTuples, rightTuples);\n return common.reduce((acc, attr) => {\n acc[attr] = attr;\n return acc;\n }, {} as Record<AttrName, AttrName>);\n }\n if (Array.isArray(keys)) {\n return keys.reduce((acc, attr) => {\n acc[attr] = attr;\n return acc;\n }, {} as Record<AttrName, AttrName>);\n }\n return keys;\n}\n\n/**\n * Checks if two tuples match on the specified key mapping.\n *\n * @example\n * const keyMap = { city: 'location' };\n * tuplesMatch({ id: 1, city: 'NYC' }, { location: 'NYC', pop: 8 }, keyMap);\n * // => true (left.city === right.location)\n *\n * @example\n * const keyMap = { city: 'city' };\n * tuplesMatch({ city: 'NYC' }, { city: 'LA' }, keyMap);\n * // => false\n */\nexport const tuplesMatch = (left: Tuple, right: Tuple, keyMap: Record<AttrName, AttrName>): boolean => {\n for (const [leftAttr, rightAttr] of Object.entries(keyMap)) {\n if (left[leftAttr] !== right[rightAttr]) return false;\n }\n return true;\n}\n\n/**\n * Creates a string key from a tuple's join attributes for fast Set-based lookups.\n * Used by matching/not_matching for efficient semi-join operations.\n *\n * @example\n * const keyMap = { first: 'fname', last: 'lname' };\n *\n * // Left side uses left attr names (keys of keyMap)\n * matchKey({ id: 1, first: 'John', last: 'Doe' }, keyMap, 'left');\n * // => '\"John\"|\"Doe\"'\n *\n * // Right side uses right attr names (values of keyMap)\n * matchKey({ fname: 'John', lname: 'Doe', age: 30 }, keyMap, 'right');\n * // => '\"John\"|\"Doe\"'\n */\nexport const matchKey = (tuple: Tuple, keyMap: Record<AttrName, AttrName>, side: 'left' | 'right'): string => {\n const attrs = side === 'left' ? Object.keys(keyMap) : Object.values(keyMap);\n const values = attrs.map(attr => JSON.stringify(tuple[attr]));\n return values.join('|');\n}\n\n/**\n * Removes join key attributes from a right tuple when merging.\n * Used to avoid duplicate columns in join results.\n *\n * @example\n * const keyMap = { city: 'location' };\n * projectOutKeys({ location: 'NYC', country: 'USA', pop: 8 }, keyMap);\n * // => { country: 'USA', pop: 8 } (location removed)\n *\n * @example\n * const keyMap = { a: 'a', b: 'b' };\n * projectOutKeys({ a: 1, b: 2, c: 3 }, keyMap);\n * // => { c: 3 } (a and b removed)\n */\nexport const projectOutKeys = (tuple: Tuple, keyMap: Record<AttrName, AttrName>): Tuple => {\n const rightKeys = new Set(Object.values(keyMap));\n const result: Tuple = {};\n for (const [attr, value] of Object.entries(tuple)) {\n if (!rightKeys.has(attr)) {\n result[attr] = value;\n }\n }\n return result;\n}\n","import { toPredicateFunc } from \"../../support/toPredicateFunc\";\nimport { RelationOperand, Predicate, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const restrict = (operand: RelationOperand, p: Predicate): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const f = toPredicateFunc(p)\n const kept: Tuple[] = [];\n for (const tuple of iterable) {\n if (f(tuple)) kept.push(tuple);\n }\n return op.output(kept)\n}\n","import { toPredicateFunc } from \"../../support/toPredicateFunc\";\nimport { RelationOperand, Predicate, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const exclude = (operand: RelationOperand, p: Predicate): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const f = toPredicateFunc(p)\n const kept: Tuple[] = [];\n for (const tuple of iterable) {\n if (!f(tuple)) kept.push(tuple);\n }\n return op.output(kept)\n}\n","import { RelationOperand, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const constants = (operand: RelationOperand, consts: Tuple): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n result.push({ ...tuple, ...consts });\n }\n return op.output(result)\n}\n","import { RelationOperand, Renaming, Tuple } from \"../../types\";\nimport { toOperationalOperand, toRenamingFunc } from \"./_helpers\";\n\nexport const rename = (operand: RelationOperand, renaming: Renaming): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const renamingFunc = toRenamingFunc(renaming)\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n const renamed = Object.keys(tuple).reduce((memo, attr) => {\n memo[renamingFunc(attr)] = tuple[attr];\n return memo;\n }, {})\n result.push(renamed);\n }\n return op.output(result)\n}\n","import { PrefixOptions, RelationOperand } from \"../../types\";\nimport { rename } from \"./rename\";\n\nexport const prefix = (operand: RelationOperand, pfx: string, options?: PrefixOptions): RelationOperand => {\n const except = new Set(options?.except ?? []);\n return rename(operand, (attr) => except.has(attr) ? attr : `${pfx}${attr}`);\n}\n","import { RelationOperand, SuffixOptions } from \"../../types\";\nimport { rename } from \"./rename\";\n\nexport const suffix = (operand: RelationOperand, sfx: string, options?: SuffixOptions): RelationOperand => {\n const except = new Set(options?.except ?? []);\n return rename(operand, (attr) => except.has(attr) ? attr : `${attr}${sfx}`);\n}\n","import { RelationOperand, AttrName, Tuple } from \"../../types\";\nimport { toOperationalOperand, deduplicate } from \"./_helpers\";\n\nexport const project = (operand: RelationOperand, attrs: AttrName[]): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n const projected = attrs.reduce((memo, attr) => {\n if (attr in tuple) {\n memo[attr] = tuple[attr];\n }\n return memo;\n }, {} as Tuple);\n result.push(projected);\n }\n return op.output(deduplicate(result));\n}\n","import { RelationOperand, AttrName, Tuple } from \"../../types\";\nimport { toOperationalOperand, deduplicate } from \"./_helpers\";\n\nexport const allbut = (operand: RelationOperand, attrs: AttrName[]): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const excluded = new Set(attrs);\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n const projected = Object.keys(tuple).reduce((memo, attr) => {\n if (!excluded.has(attr)) {\n memo[attr] = tuple[attr];\n }\n return memo;\n }, {} as Tuple);\n result.push(projected);\n }\n return op.output(deduplicate(result));\n}\n","import { RelationOperand, Extension, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const extend = (operand: RelationOperand, extension: Extension): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n for (const tuple of iterable) {\n const extended = { ...tuple };\n for (const [attr, spec] of Object.entries(extension)) {\n if (typeof spec === 'function') {\n extended[attr] = spec(tuple);\n } else {\n extended[attr] = tuple[spec];\n }\n }\n result.push(extended);\n }\n return op.output(result);\n}\n","import { RelationOperand, Tuple } from \"../../types\";\nimport { toOperationalOperand, tupleKey } from \"./_helpers\";\n\nexport const union = (left: RelationOperand, right: RelationOperand): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const seen = new Set<string>();\n const result: Tuple[] = [];\n\n for (const tuple of opLeft.tuples()) {\n const key = tupleKey(tuple);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n\n for (const tuple of opRight.tuples()) {\n const key = tupleKey(tuple);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, Tuple } from \"../../types\";\nimport { toOperationalOperand, tupleKey } from \"./_helpers\";\n\nexport const minus = (left: RelationOperand, right: RelationOperand): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n\n const rightKeys = new Set<string>();\n for (const tuple of opRight.tuples()) {\n rightKeys.add(tupleKey(tuple));\n }\n\n const seen = new Set<string>();\n const result: Tuple[] = [];\n for (const tuple of opLeft.tuples()) {\n const key = tupleKey(tuple);\n if (!rightKeys.has(key) && !seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, Tuple } from \"../../types\";\nimport { toOperationalOperand, tupleKey } from \"./_helpers\";\n\nexport const intersect = (left: RelationOperand, right: RelationOperand): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n\n const rightKeys = new Set<string>();\n for (const tuple of opRight.tuples()) {\n rightKeys.add(tupleKey(tuple));\n }\n\n const seen = new Set<string>();\n const result: Tuple[] = [];\n for (const tuple of opLeft.tuples()) {\n const key = tupleKey(tuple);\n if (rightKeys.has(key) && !seen.has(key)) {\n seen.add(key);\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, JoinKeys, Tuple } from \"../../types\";\nimport { toOperationalOperand, normalizeKeys, matchKey } from \"./_helpers\";\n\nexport const matching = (left: RelationOperand, right: RelationOperand, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n\n const rightKeys = new Set<string>();\n for (const tuple of rightTuples) {\n rightKeys.add(matchKey(tuple, keyMap, 'right'));\n }\n\n const result: Tuple[] = [];\n for (const tuple of leftTuples) {\n if (rightKeys.has(matchKey(tuple, keyMap, 'left'))) {\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, JoinKeys, Tuple } from \"../../types\";\nimport { toOperationalOperand, normalizeKeys, matchKey } from \"./_helpers\";\n\nexport const not_matching = (left: RelationOperand, right: RelationOperand, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n\n const rightKeys = new Set<string>();\n for (const tuple of rightTuples) {\n rightKeys.add(matchKey(tuple, keyMap, 'right'));\n }\n\n const result: Tuple[] = [];\n for (const tuple of leftTuples) {\n if (!rightKeys.has(matchKey(tuple, keyMap, 'left'))) {\n result.push(tuple);\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, JoinKeys, Tuple, AttrName } from \"../../types\";\nimport { toOperationalOperand, normalizeKeys, tuplesMatch, projectOutKeys } from \"./_helpers\";\n\nconst mergeTuples = (left: Tuple, right: Tuple, keyMap: Record<AttrName, AttrName>): Tuple => {\n return { ...left, ...projectOutKeys(right, keyMap) };\n}\n\nexport const join = (left: RelationOperand, right: RelationOperand, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n const result: Tuple[] = [];\n\n for (const leftTuple of leftTuples) {\n for (const rightTuple of rightTuples) {\n if (tuplesMatch(leftTuple, rightTuple, keyMap)) {\n result.push(mergeTuples(leftTuple, rightTuple, keyMap));\n }\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, JoinKeys, Tuple, AttrName } from \"../../types\";\nimport { toOperationalOperand, normalizeKeys, tuplesMatch } from \"./_helpers\";\n\nconst getRightAttrs = (rightTuples: Tuple[], keyMap: Record<AttrName, AttrName>): AttrName[] => {\n if (rightTuples.length === 0) return [];\n const rightKeys = new Set(Object.values(keyMap));\n return Object.keys(rightTuples[0]).filter(attr => !rightKeys.has(attr));\n}\n\nconst mergeTuples = (left: Tuple, right: Tuple | null, rightAttrs: AttrName[]): Tuple => {\n const result = { ...left };\n for (const attr of rightAttrs) {\n result[attr] = right ? right[attr] : null;\n }\n return result;\n}\n\nexport const left_join = (left: RelationOperand, right: RelationOperand, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n const rightAttrs = getRightAttrs(rightTuples, keyMap);\n const result: Tuple[] = [];\n\n for (const leftTuple of leftTuples) {\n let matched = false;\n for (const rightTuple of rightTuples) {\n if (tuplesMatch(leftTuple, rightTuple, keyMap)) {\n result.push(mergeTuples(leftTuple, rightTuple, rightAttrs));\n matched = true;\n }\n }\n if (!matched) {\n result.push(mergeTuples(leftTuple, null, rightAttrs));\n }\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, Tuple } from \"../../types\";\nimport { toOperationalOperand, deduplicate } from \"./_helpers\";\n\nexport const cross_product = (left: RelationOperand, right: RelationOperand): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const result: Tuple[] = [];\n\n for (const l of leftTuples) {\n for (const r of rightTuples) {\n result.push({ ...r, ...l });\n }\n }\n\n return opLeft.output(deduplicate(result));\n}\n\nexport { cross_product as cross_join };\n","import { RelationOperand, JoinKeys, Tuple, AttrName } from \"../../types\";\nimport { toOperationalOperand, normalizeKeys, tuplesMatch, projectOutKeys } from \"./_helpers\";\nimport { MemoryRelation } from \"@/sync/Relation\";\n\nexport const image = (left: RelationOperand, right: RelationOperand, as: AttrName, keys?: JoinKeys): RelationOperand => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n const leftTuples = [...opLeft.tuples()];\n const rightTuples = [...opRight.tuples()];\n const keyMap = normalizeKeys(keys, leftTuples, rightTuples);\n const result: Tuple[] = [];\n\n for (const leftTuple of leftTuples) {\n const matches: Tuple[] = [];\n for (const rightTuple of rightTuples) {\n if (tuplesMatch(leftTuple, rightTuple, keyMap)) {\n matches.push(projectOutKeys(rightTuple, keyMap));\n }\n }\n result.push({\n ...leftTuple,\n [as]: new MemoryRelation(matches)\n });\n }\n\n return opLeft.output(result);\n}\n","import { RelationOperand, AttrName, Tuple, Aggregator, Aggregators } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nconst groupKey = (tuple: Tuple, by: AttrName[]): string => {\n const keyParts = by.map(attr => JSON.stringify(tuple[attr]));\n return keyParts.join('|');\n}\n\nconst pickAttrs = (tuple: Tuple, attrs: AttrName[]): Tuple => {\n return attrs.reduce((acc, attr) => {\n acc[attr] = tuple[attr];\n return acc;\n }, {} as Tuple);\n}\n\nconst applyAggregator = (tuples: Tuple[], agg: Aggregator): unknown => {\n if (typeof agg === 'function') {\n return agg(tuples);\n }\n\n const spec = typeof agg === 'string' ? { op: agg, attr: '' } : agg;\n const { op, attr } = spec;\n\n switch (op) {\n case 'count':\n return tuples.length;\n\n case 'sum': {\n return tuples.reduce((sum, t) => sum + (Number(t[attr]) || 0), 0);\n }\n\n case 'min': {\n const values = tuples.map(t => t[attr]).filter(v => v !== undefined && v !== null);\n return values.length > 0 ? Math.min(...values.map(Number)) : null;\n }\n\n case 'max': {\n const values = tuples.map(t => t[attr]).filter(v => v !== undefined && v !== null);\n return values.length > 0 ? Math.max(...values.map(Number)) : null;\n }\n\n case 'avg': {\n const values = tuples.map(t => Number(t[attr])).filter(v => !isNaN(v));\n return values.length > 0 ? values.reduce((a, b) => a + b, 0) / values.length : null;\n }\n\n case 'collect': {\n return tuples.map(t => t[attr]);\n }\n\n default:\n throw new Error(`Unknown aggregator: ${op}`);\n }\n}\n\nexport const summarize = (\n operand: RelationOperand,\n by: AttrName[],\n aggs: Aggregators\n): RelationOperand => {\n const op = toOperationalOperand(operand);\n const tuples = [...op.tuples()];\n\n // Group tuples\n const groups = new Map<string, Tuple[]>();\n for (const tuple of tuples) {\n const key = groupKey(tuple, by);\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key)!.push(tuple);\n }\n\n // Apply aggregators to each group\n const result: Tuple[] = [];\n for (const groupTuples of groups.values()) {\n const row: Tuple = pickAttrs(groupTuples[0], by);\n for (const [resultAttr, agg] of Object.entries(aggs)) {\n row[resultAttr] = applyAggregator(groupTuples, agg);\n }\n result.push(row);\n }\n\n return op.output(result);\n}\n","import { RelationOperand, AttrName, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\nimport { MemoryRelation } from \"@/sync/Relation\";\n\nconst groupKey = (tuple: Tuple, byAttrs: AttrName[]): string => {\n const keyParts = byAttrs.map(attr => JSON.stringify(tuple[attr]));\n return keyParts.join('|');\n}\n\nconst pickAttrs = (tuple: Tuple, attrs: AttrName[]): Tuple => {\n return attrs.reduce((acc, attr) => {\n acc[attr] = tuple[attr];\n return acc;\n }, {} as Tuple);\n}\n\nexport const group = (operand: RelationOperand, attrs: AttrName[], as: AttrName): RelationOperand => {\n const op = toOperationalOperand(operand);\n const tuples = [...op.tuples()];\n\n if (tuples.length === 0) {\n return op.output([]);\n }\n\n // Determine which attributes to keep at the top level (all except grouped ones)\n const allAttrs = Object.keys(tuples[0]);\n const groupedSet = new Set(attrs);\n const byAttrs = allAttrs.filter(a => !groupedSet.has(a));\n\n // Group tuples\n const groups = new Map<string, { base: Tuple, nested: Tuple[] }>();\n for (const tuple of tuples) {\n const key = groupKey(tuple, byAttrs);\n if (!groups.has(key)) {\n groups.set(key, {\n base: pickAttrs(tuple, byAttrs),\n nested: []\n });\n }\n groups.get(key)!.nested.push(pickAttrs(tuple, attrs));\n }\n\n // Build result with nested relations\n const result: Tuple[] = [];\n for (const { base, nested } of groups.values()) {\n result.push({\n ...base,\n [as]: new MemoryRelation(nested)\n });\n }\n\n return op.output(result);\n}\n","import { RelationOperand, AttrName, Tuple, Relation } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\nimport { isRelation } from \"./isRelation\";\n\nconst toTupleArray = (value: unknown): Tuple[] => {\n if (isRelation(value)) {\n return (value as Relation).toArray();\n }\n if (Array.isArray(value)) {\n return value;\n }\n throw new Error(`Value is not a relation or array`);\n}\n\nexport const ungroup = (operand: RelationOperand, attr: AttrName): RelationOperand => {\n const op = toOperationalOperand(operand);\n const tuples = [...op.tuples()];\n const result: Tuple[] = [];\n\n for (const tuple of tuples) {\n const nested = toTupleArray(tuple[attr]);\n\n // Get base attributes (all except the grouped one)\n const base: Tuple = {};\n for (const [key, value] of Object.entries(tuple)) {\n if (key !== attr) {\n base[key] = value;\n }\n }\n\n // Flatten each nested tuple\n for (const nestedTuple of nested) {\n result.push({\n ...base,\n ...nestedTuple\n });\n }\n }\n\n return op.output(result);\n}\n","import { RelationOperand, AttrName, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const wrap = (operand: RelationOperand, attrs: AttrName[], as: AttrName): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const wrappedSet = new Set(attrs);\n const result: Tuple[] = [];\n\n for (const tuple of iterable) {\n const wrapped: Tuple = {};\n const remaining: Tuple = {};\n\n for (const [key, value] of Object.entries(tuple)) {\n if (wrappedSet.has(key)) {\n wrapped[key] = value;\n } else {\n remaining[key] = value;\n }\n }\n\n result.push({\n ...remaining,\n [as]: wrapped\n });\n }\n\n return op.output(result);\n}\n","import { RelationOperand, AttrName, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const unwrap = (operand: RelationOperand, attr: AttrName): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n\n for (const tuple of iterable) {\n const wrapped = tuple[attr] as Tuple;\n if (typeof wrapped !== 'object' || wrapped === null || Array.isArray(wrapped)) {\n throw new Error(`Attribute '${attr}' is not a tuple (object)`);\n }\n\n const unwrapped: Tuple = {};\n for (const [key, value] of Object.entries(tuple)) {\n if (key !== attr) {\n unwrapped[key] = value;\n }\n }\n\n result.push({\n ...unwrapped,\n ...wrapped\n });\n }\n\n return op.output(result);\n}\n","import { AutowrapOptions, RelationOperand, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const autowrap = (operand: RelationOperand, options?: AutowrapOptions): RelationOperand => {\n const sep = options?.separator ?? '_';\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n\n for (const tuple of iterable) {\n const wrapped: Tuple = {};\n for (const [attr, value] of Object.entries(tuple)) {\n const parts = attr.split(sep);\n if (parts.length === 1) {\n wrapped[attr] = value;\n } else {\n const [prefix, ...rest] = parts;\n wrapped[prefix] = wrapped[prefix] ?? {};\n (wrapped[prefix] as Tuple)[rest.join(sep)] = value;\n }\n }\n result.push(wrapped);\n }\n\n return op.output(result);\n}\n","import { RelationOperand, Transformation, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const transform = (operand: RelationOperand, transformation: Transformation): RelationOperand => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const result: Tuple[] = [];\n\n for (const tuple of iterable) {\n const transformed: Tuple = {};\n\n for (const [attr, value] of Object.entries(tuple)) {\n transformed[attr] = applyTransformation(value, attr, transformation);\n }\n\n result.push(transformed);\n }\n\n return op.output(result);\n}\n\nconst applyTransformation = (value: unknown, attr: string, transformation: Transformation): unknown => {\n if (typeof transformation === 'function') {\n // Single function - apply to all values\n return transformation(value);\n } else if (Array.isArray(transformation)) {\n // Array of functions - chain them\n return transformation.reduce((v, fn) => fn(v), value);\n } else {\n // Object with attr-specific transformers\n const fn = transformation[attr];\n if (fn) {\n if (Array.isArray(fn)) {\n return fn.reduce((v, f) => f(v), value);\n }\n return fn(value);\n }\n return value;\n }\n}\n","import { toOperationalOperand, tupleKey } from \"./_helpers\";\n\nexport const isEqual = (left: any, right: any): boolean => {\n const opLeft = toOperationalOperand(left);\n const opRight = toOperationalOperand(right);\n\n const leftKeys = new Set<string>();\n for (const tuple of opLeft.tuples()) {\n leftKeys.add(tupleKey(tuple));\n }\n\n const rightKeys = new Set<string>();\n for (const tuple of opRight.tuples()) {\n rightKeys.add(tupleKey(tuple));\n }\n\n if (leftKeys.size !== rightKeys.size) {\n return false;\n }\n\n for (const key of leftKeys) {\n if (!rightKeys.has(key)) {\n return false;\n }\n }\n\n return true;\n}\n","import { RelationOperand, Tuple } from \"../../types\";\nimport { toOperationalOperand, error } from \"./_helpers\";\n\nexport const one = (operand: RelationOperand): Tuple => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n let tuple;\n for (const t of iterable) {\n if (tuple) {\n return error('More than one tuple found');\n } else {\n tuple = t;\n }\n }\n if (tuple) return tuple;\n return error('Relation is empty');\n}\n","import { AttrName, RelationOperand, Tuple } from \"../../types\";\nimport { toOperationalOperand } from \"./_helpers\";\n\nexport const yByX = (operand: RelationOperand, y: AttrName, x: AttrName): Tuple => {\n const op = toOperationalOperand(operand);\n const iterable = op.tuples();\n const hash = {};\n for (const tuple of iterable) {\n hash[`${tuple[x]}`] = tuple[y];\n }\n return hash;\n}\n","export * from './sync/operators';\nexport * from './types';\nexport { LIB_DEFINITIONS } from './lib-definitions';\nexport { toText } from './writer';\n\nimport { MemoryRelation } from './sync/Relation';\nimport { isRelation } from './sync/operators';\n\n/**\n * Creates a new in-memory relation from an array of tuples.\n *\n * @typeParam T - The tuple type. Inferred from input or explicitly provided.\n *\n * @example\n * // Untyped usage (backwards compatible)\n * const r = Bmg([{ id: 1, name: 'Alice' }]);\n *\n * @example\n * // Typed usage with explicit type parameter\n * interface Person { id: number; name: string }\n * const r = Bmg<Person>([{ id: 1, name: 'Alice' }]);\n * r.project(['id']); // Autocomplete suggests 'id' | 'name'\n *\n * @example\n * // Type is inferred from input\n * const r = Bmg([{ id: 1, name: 'Alice' }] as const);\n */\nexport function Bmg<T>(tuples: T[]): MemoryRelation<T> {\n return new MemoryRelation<T>(tuples);\n}\n\nBmg.isRelation = isRelation;\n\n/**\n * DEE - The relation with no attributes and exactly one tuple.\n * This is the identity element for natural join.\n */\nexport const DEE = new MemoryRelation<Record<string, never>>([{}]);\n\n/**\n * DUM - The relation with no attributes and no tuples.\n * This is the identity element for union.\n */\nexport const DUM = new MemoryRelation<Record<string, never>>([]);\n","// Auto-generated from types.ts\n// Run 'npm run generate:lib-definitions' to regenerate\n\nexport const LIB_DEFINITIONS = `\n/**\n * Type definitions for Bmg.js relational algebra library.\n *\n * This file defines all types needed for type-safe relational operations:\n * - Base types (AttrName, Tuple)\n * - Utility types for transformations (Renamed, Prefixed, Joined, etc.)\n * - The Relation interface with all operators\n * - Helper types for predicates, extensions, aggregators, etc.\n */\n\n// ============================================================================\n// Base Types\n// ============================================================================\n\n/** Attribute name in a tuple */\ntype AttrName = string\n\n/** A tuple is a record mapping attribute names to values */\ntype Tuple = Record<AttrName, unknown>\n\n// ============================================================================\n// Rename Types\n// ============================================================================\n\n/** Map from old attribute names to new attribute names */\ntype RenameMap<T> = { [K in keyof T]?: string };\n\n/** Transform tuple type by renaming keys according to RenameMap */\ntype Renamed<T, R extends RenameMap<T>> = {\n [K in keyof T as K extends keyof R ? (R[K] extends string ? R[K] : K) : K]: T[K];\n};\n\n// ============================================================================\n// Prefix/Suffix Types\n// ============================================================================\n\n/** Prefix all keys except those in Except */\ntype Prefixed<T, P extends string, Except extends keyof T = never> = {\n [K in keyof T as K extends Except ? K : \\`\\${P}\\${K & string}\\`]: T[K];\n};\n\n/** Suffix all keys except those in Except */\ntype Suffixed<T, S extends string, Except extends keyof T = never> = {\n [K in keyof T as K extends Except ? K : \\`\\${K & string}\\${S}\\`]: T[K];\n};\n\n// ============================================================================\n// Join Types\n// ============================================================================\n\n/** Extract common keys between two tuple types */\ntype CommonKeys<L, R> = Extract<keyof L, keyof R>;\n\n/** Result of inner join: L & R with R's common keys removed */\ntype Joined<L, R> = L & Omit<R, CommonKeys<L, R>>;\n\n/** Result of left join: L & optional R attributes (common keys removed) */\ntype LeftJoined<L, R> = L & Partial<Omit<R, CommonKeys<L, R>>>;\n\n/**\n * Typed join keys for array form: keys must exist on BOTH operands.\n * Example: suppliers.join(parts, ['city']) - 'city' must be a key of both.\n */\ntype TypedJoinKeysArray<L, R> = (keyof L & keyof R & string)[];\n\n/**\n * Typed join keys for object form: maps left keys to right keys.\n * Example: suppliers.join(parts, { sid: 'supplier_id' })\n * - Left key (sid) must exist on L\n * - Right key (supplier_id) must exist on R\n */\ntype TypedJoinKeysObject<L, R> = { [K in keyof L & string]?: keyof R & string };\n\n// ============================================================================\n// Wrap/Unwrap Types\n// ============================================================================\n\n/** Result of wrap: remove wrapped attrs, add nested object */\ntype Wrapped<T, K extends keyof T, As extends string> =\n Omit<T, K> & Record<As, Pick<T, K>>;\n\n/** Result of unwrap: remove object attr, spread its properties */\ntype Unwrapped<T, K extends keyof T> =\n T[K] extends Record<string, unknown> ? Omit<T, K> & T[K] : Omit<T, K>;\n\n/** Result of ungroup: remove relation attr, flatten its tuple type */\ntype Ungrouped<T, K extends keyof T> =\n T[K] extends Relation<infer N> ? Omit<T, K> & N : Omit<T, K>;\n\n// ============================================================================\n// Aggregator Types\n// ============================================================================\n\ntype AggregatorName = 'count' | 'sum' | 'min' | 'max' | 'avg' | 'collect'\ntype AggregatorSpec = { op: AggregatorName, attr: AttrName }\ntype AggregatorFunc = (tuples: Tuple[]) => unknown\ntype Aggregator = AggregatorName | AggregatorSpec | AggregatorFunc\ntype Aggregators = Record<AttrName, Aggregator>\n\n/** Infer result type from aggregator specification */\ntype AggregatorResult<A> =\n A extends 'count' ? number :\n A extends { op: 'count' } ? number :\n A extends { op: 'sum' | 'avg' | 'min' | 'max' } ? number | null :\n A extends { op: 'collect' } ? unknown[] :\n A extends (tuples: Tuple[]) => infer R ? R :\n unknown;\n\n/** Map aggregator definitions to their result types */\ntype AggregatorResults<Aggs extends Record<string, unknown>> = {\n [K in keyof Aggs]: AggregatorResult<Aggs[K]>;\n};\n\n// ============================================================================\n// Predicate Types\n// ============================================================================\n\n/** Predicate function that receives a typed tuple */\ntype TypedPredicateFunc<T> = (t: T) => boolean\n\n/** Predicate: either a partial tuple for equality matching, or a function */\ntype TypedPredicate<T> = Partial<T> | TypedPredicateFunc<T>\n\n// Legacy predicate types (for backwards compatibility with standalone operators)\ntype PredicateFunc = ((t: Tuple) => any)\ntype Predicate = Tuple | PredicateFunc\n\n// ============================================================================\n// Extension Types\n// ============================================================================\n\n/** Extension function that receives a typed tuple */\ntype TypedExtensionFunc<T, R> = (tuple: T) => R\n\n/** Extension definition: function returning value, or attribute name to copy */\ntype TypedExtension<T, E extends Record<string, unknown>> = {\n [K in keyof E]: TypedExtensionFunc<T, E[K]> | keyof T;\n}\n\ntype ExtensionFunc = (tuple: Tuple) => unknown\ntype Extension = Record<AttrName, ExtensionFunc | AttrName>\n\n// ============================================================================\n// Other Helper Types\n// ============================================================================\n\ninterface PrefixOptions {\n except?: AttrName[]\n}\n\ninterface TextOptions {\n /** Precision for floating point numbers (default: 3) */\n floatPrecision?: number;\n /** Maximum width to trim output at */\n trimAt?: number;\n}\n\ninterface SuffixOptions {\n except?: AttrName[]\n}\n\ninterface AutowrapOptions {\n separator?: string\n}\n\ntype Renaming = RenamingObj | RenamingFunc\ntype RenamingFunc = (attr: AttrName) => AttrName\ntype RenamingObj = Record<AttrName, AttrName>\n\ntype JoinKeys = AttrName[] | Record<AttrName, AttrName>\n\ntype TransformFunc = (value: unknown) => unknown\ntype Transformation = TransformFunc | TransformFunc[] | Record<AttrName, TransformFunc | TransformFunc[]>\n\n// ============================================================================\n// Relation Interface\n// ============================================================================\n\n/**\n * Relation interface with generic type parameter for tuple type.\n * Default parameter \\`Tuple\\` ensures backwards compatibility.\n *\n * @typeParam T - The tuple type for this relation. Defaults to \\`Tuple\\` (Record<string, unknown>).\n *\n * @example\n * // Untyped usage (backwards compatible)\n * const r = Bmg([{ id: 1 }]); // Relation<Tuple>\n *\n * @example\n * // Typed usage with full type safety\n * interface Person { id: number; name: string }\n * const r = Bmg<Person>([{ id: 1, name: 'Alice' }]);\n * r.project(['id']); // Relation<{ id: number }>\n */\ninterface Relation<T = Tuple> {\n // === Type-preserving operators ===\n\n restrict(p: TypedPredicate<T>): Relation<T>\n where(p: TypedPredicate<T>): Relation<T>\n exclude(p: TypedPredicate<T>): Relation<T>\n\n // === Projection operators ===\n\n project<K extends keyof T>(attrs: K[]): Relation<Pick<T, K>>\n allbut<K extends keyof T>(attrs: K[]): Relation<Omit<T, K>>\n\n // === Extension operators ===\n\n extend<E extends Record<string, unknown>>(e: TypedExtension<T, E>): Relation<T & E>\n constants<C extends Tuple>(consts: C): Relation<T & C>\n\n // === Rename operators ===\n\n rename<R extends RenameMap<T>>(r: R): Relation<Renamed<T, R>>\n prefix<P extends string, Ex extends keyof T = never>(pfx: P, options?: { except?: Ex[] }): Relation<Prefixed<T, P, Ex>>\n suffix<S extends string, Ex extends keyof T = never>(sfx: S, options?: { except?: Ex[] }): Relation<Suffixed<T, S, Ex>>\n\n // === Set operators (require same type) ===\n\n union(right: RelationOperand<T>): Relation<T>\n minus(right: RelationOperand<T>): Relation<T>\n intersect(right: RelationOperand<T>): Relation<T>\n\n // === Semi-join operators (preserve left type) ===\n\n matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T>\n not_matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T>\n\n // === Join operators ===\n\n join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<Joined<T, R>>\n left_join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<LeftJoined<T, R>>\n cross_product<R>(right: RelationOperand<R>): Relation<T & R>\n cross_join<R>(right: RelationOperand<R>): Relation<T & R>\n\n // === Nesting operators ===\n\n image<R, As extends string>(right: RelationOperand<R>, as: As, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T & Record<As, Relation<Omit<R, keyof T & keyof R>>>>\n group<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Omit<T, K> & Record<As, Relation<Pick<T, K>>>>\n ungroup<K extends keyof T>(attr: K): Relation<Ungrouped<T, K>>\n wrap<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Wrapped<T, K, As>>\n unwrap<K extends keyof T>(attr: K): Relation<Unwrapped<T, K>>\n\n // === Aggregation ===\n\n summarize<By extends keyof T, Aggs extends Aggregators>(by: By[], aggs: Aggs): Relation<Pick<T, By> & AggregatorResults<Aggs>>\n\n // === Transform ===\n\n transform(t: Transformation): Relation<T>\n\n // === Dynamic (loses type precision) ===\n\n autowrap(options?: AutowrapOptions): Relation<Tuple>\n\n // === Non-relational ===\n\n one(): T\n yByX<Y extends keyof T, X extends keyof T>(y: Y, x: X): Record<T[X] & PropertyKey, T[Y]>\n toArray(): T[]\n isEqual(right: any): boolean\n\n // === Display ===\n\n toText(options?: TextOptions): string\n}\n\n// ============================================================================\n// Operands\n// ============================================================================\n\ntype RelationOperand<T = Tuple> = Relation<T> | T[]\n\ninterface OperationalOperand<T = Tuple> {\n tuples(): Iterable<T>\n output(tuples: T[]): RelationOperand<T>\n}\n\n// ============================================================================\n// Bmg Function Declaration\n// ============================================================================\n\n/** Create a relation from an array of tuples */\ndeclare function Bmg<T>(tuples: T[]): Relation<T>\ndeclare namespace Bmg {\n function isRelation(op: unknown): boolean\n}\n`\n"],"names":["toPredicateFunc","p","expected","t","Object","keys","every","k","isRelation","op","constructor","MemoryRelation","isTupleLike","Array","isArray","max","x","y","Cell","renderer","value","_textRendering","this","_minWidth","_proto","prototype","_createClass","renderingLines","size","undefined","textRendering","split","map","l","padStart","padEnd","computeTextRendering","r","toString","_this$renderer$option","Number","isInteger","String","precision","options","floatPrecision","toFixed","render","arrayRendering","Date","toISOString","JSON","stringify","_this","length","values","reduce","sum","s","join","key","get","maxLen","line","Row","cells","v","_proto2","minWidths","cell","minWidth","sizes","nbLines","byCell","i","lines","grid","_loop","lineI","lineContent","cellLines","_cellLines$lineI","repeat","push","Table","records","attributes","header","rows","_sizes","_sep","_proto3","eachLine","_regenerator","m","trimAt","_iterator","_step","w","_context","n","_createForOfIteratorHelperLoose","eachLineRaw","done","substring","d","_regeneratorValues","a","_iterator2","_step2","_iterator3","_step3","_context2","sep","row","Symbol","iterator","_callee","_iterator4","_step4","_context3","trimEnd","_step5","result","_iterator5","headerWidths","memo","rowWidths","_rowWidths$i","TextWriter","_proto4","input","output","_iterator6","_step6","tuples","attrs","table","_context4","toArray","tuple","_i","_Object$keys","includes","toText","operand","restrict","where","exclude","project","allbut","extend","e","constants","consts","rename","prefix","pfx","suffix","sfx","union","right","minus","intersect","matching","not_matching","left_join","cross_product","cross_join","image","as","group","ungroup","attr","wrap","unwrap","summarize","by","aggs","transform","autowrap","one","yByX","isEqual","tupleKey","entries","_ref","sort","_ref2","_ref3","localeCompare","deduplicate","seen","Set","has","add","toOperationalOperand","error","msg","normalizeKeys","leftTuples","rightTuples","acc","left","leftAttrs","filter","getCommonAttrs","tuplesMatch","keyMap","_Object$entries","_Object$entries$_i","matchKey","side","projectOutKeys","rightKeys","_i2","_Object$entries2","_Object$entries2$_i","iterable","f","kept","_extends","renaming","renamingFunc","toRenamingFunc","renamed","_options$except","except","projected","excluded","extension","extended","spec","opLeft","opRight","concat","mergeTuples","leftTuple","rightTuple","rightAttrs","getRightAttrs","matched","_extends2","matches","groupKey","pickAttrs","applyAggregator","agg","Math","min","apply","isNaN","b","Error","groups","Map","set","groupTuples","byAttrs","allAttrs","groupedSet","base","nested","_step2$value","toTupleArray","wrappedSet","wrapped","remaining","unwrapped","_options$separator","separator","parts","_wrapped$prefix","rest","_arrayLikeToArray","slice","transformation","transformed","applyTransformation","fn","leftKeys","hash","Bmg","DEE","DUM"],"mappings":"s2HAEa,IAAAA,EAAkB,SAACC,GAC9B,GAAkB,mBAAPA,EACT,OAAOA,EAEP,IAAMC,EAAWD,EACjB,OAAO,SAACE,GACN,OAAOC,OAAOC,KAAKH,GAAUI,MAAM,SAAAC,GAAC,OAAIJ,EAAEI,KAAOL,EAASK,EAAE,EAC9D,CAE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=>Object.keys(n).every(t=>e[t]===n[t])}};class n{constructor(e){this.tuples=void 0,this.tuples=e,this.tuples=e}restrict(e){return l(this,e)}where(e){return l(this,e)}exclude(e){return f(this,e)}project(e){return R(this,e)}allbut(e){return h(this,e)}extend(e){return x(this,e)}constants(e){return d(this,e)}rename(e){return T(this,e)}prefix(e,n){return g(this,e,n)}suffix(e,n){return m(this,e,n)}union(e){return A(this,e)}minus(e){return k(this,e)}intersect(e){return w(this,e)}matching(e,n){return b(this,e,n)}not_matching(e,n){return K(this,e,n)}join(e,n){return j(this,e,n)}left_join(e,n){return v(this,e,n)}cross_product(e){return S(this,e)}cross_join(e){return S(this,e)}image(e,n,t){return P(this,e,n,t)}group(e,n){return _(this,e,n)}ungroup(e){return U(this,e)}wrap(e,n){return C(this,e,n)}unwrap(e){return X(this,e)}summarize(e,n){return F(this,e,n)}transform(e){return z(this,e)}autowrap(e){return q(this,e)}one(){return I(this)}toArray(){return this.tuples}yByX(e,n){return W(this,e,n)}isEqual(e){return H(this,e)}}const t=e=>null!=e&&e.constructor===n,r=e=>{const n=Object.entries(e).map(([e,n])=>{return[e,(o=n,t(o)?o.toArray().map(e=>r(e)).sort():o)];var o});return JSON.stringify(n.sort(([e],[n])=>e.localeCompare(n)))},o=e=>{const n=new Set,t=[];for(const o of e){const e=r(o);n.has(e)||(n.add(e),t.push(o))}return t},s=e=>{if(Array.isArray(e))return{tuples:()=>e,output:e=>e};if(t(e))return{tuples:()=>e.toArray(),output:e=>new n(e)};throw`Unable to iterate ${e}`},a=e=>{throw e},i=(e,n,t)=>e?Array.isArray(e)?e.reduce((e,n)=>(e[n]=n,e),{}):e:((e,n)=>{if(0===e.length||0===n.length)return[];const t=new Set(Object.keys(e[0]));return Object.keys(n[0]).filter(e=>t.has(e))})(n,t).reduce((e,n)=>(e[n]=n,e),{}),u=(e,n,t)=>{for(const[r,o]of Object.entries(t))if(e[r]!==n[o])return!1;return!0},p=(e,n,t)=>("left"===t?Object.keys(n):Object.values(n)).map(n=>JSON.stringify(e[n])).join("|"),c=(e,n)=>{const t=new Set(Object.values(n)),r={};for(const[n,o]of Object.entries(e))t.has(n)||(r[n]=o);return r},l=(n,t)=>{const r=s(n),o=r.tuples(),a=e(t),i=[];for(const e of o)a(e)&&i.push(e);return r.output(i)},f=(n,t)=>{const r=s(n),o=r.tuples(),a=e(t),i=[];for(const e of o)a(e)||i.push(e);return r.output(i)};function y(){return y=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)({}).hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},y.apply(null,arguments)}const d=(e,n)=>{const t=s(e),r=t.tuples(),o=[];for(const e of r)o.push(y({},e,n));return t.output(o)},T=(e,n)=>{const t=s(e),r=t.tuples(),o=(e=>"function"==typeof e?e:n=>e[n]||n)(n),a=[];for(const e of r){const n=Object.keys(e).reduce((n,t)=>(n[o(t)]=e[t],n),{});a.push(n)}return t.output(a)},g=(e,n,t)=>{var r;const o=new Set(null!=(r=null==t?void 0:t.except)?r:[]);return T(e,e=>o.has(e)?e:`${n}${e}`)},m=(e,n,t)=>{var r;const o=new Set(null!=(r=null==t?void 0:t.except)?r:[]);return T(e,e=>o.has(e)?e:`${e}${n}`)},R=(e,n)=>{const t=s(e),r=t.tuples(),a=[];for(const e of r){const t=n.reduce((n,t)=>(t in e&&(n[t]=e[t]),n),{});a.push(t)}return t.output(o(a))},h=(e,n)=>{const t=s(e),r=t.tuples(),a=new Set(n),i=[];for(const e of r){const n=Object.keys(e).reduce((n,t)=>(a.has(t)||(n[t]=e[t]),n),{});i.push(n)}return t.output(o(i))},x=(e,n)=>{const t=s(e),r=t.tuples(),o=[];for(const e of r){const t=y({},e);for(const[r,o]of Object.entries(n))t[r]="function"==typeof o?o(e):e[o];o.push(t)}return t.output(o)},A=(e,n)=>{const t=s(e),o=s(n),a=new Set,i=[];for(const e of t.tuples()){const n=r(e);a.has(n)||(a.add(n),i.push(e))}for(const e of o.tuples()){const n=r(e);a.has(n)||(a.add(n),i.push(e))}return t.output(i)},k=(e,n)=>{const t=s(e),o=s(n),a=new Set;for(const e of o.tuples())a.add(r(e));const i=new Set,u=[];for(const e of t.tuples()){const n=r(e);a.has(n)||i.has(n)||(i.add(n),u.push(e))}return t.output(u)},w=(e,n)=>{const t=s(e),o=s(n),a=new Set;for(const e of o.tuples())a.add(r(e));const i=new Set,u=[];for(const e of t.tuples()){const n=r(e);a.has(n)&&!i.has(n)&&(i.add(n),u.push(e))}return t.output(u)},b=(e,n,t)=>{const r=s(e),o=s(n),a=[...r.tuples()],u=[...o.tuples()],c=i(t,a,u),l=new Set;for(const e of u)l.add(p(e,c,"right"));const f=[];for(const e of a)l.has(p(e,c,"left"))&&f.push(e);return r.output(f)},K=(e,n,t)=>{const r=s(e),o=s(n),a=[...r.tuples()],u=[...o.tuples()],c=i(t,a,u),l=new Set;for(const e of u)l.add(p(e,c,"right"));const f=[];for(const e of a)l.has(p(e,c,"left"))||f.push(e);return r.output(f)},O=(e,n,t)=>y({},e,c(n,t)),j=(e,n,t)=>{const r=s(e),o=s(n),a=[...r.tuples()],p=[...o.tuples()],c=i(t,a,p),l=[];for(const e of a)for(const n of p)u(e,n,c)&&l.push(O(e,n,c));return r.output(l)},E=(e,n,t)=>{const r=y({},e);for(const e of t)r[e]=n?n[e]:null;return r},v=(e,n,t)=>{const r=s(e),o=s(n),a=[...r.tuples()],p=[...o.tuples()],c=i(t,a,p),l=((e,n)=>{if(0===e.length)return[];const t=new Set(Object.values(n));return Object.keys(e[0]).filter(e=>!t.has(e))})(p,c),f=[];for(const e of a){let n=!1;for(const t of p)u(e,t,c)&&(f.push(E(e,t,l)),n=!0);n||f.push(E(e,null,l))}return r.output(f)},S=(e,n)=>{const t=s(e),r=s(n),a=[...t.tuples()],i=[...r.tuples()],u=[];for(const e of a)for(const n of i)u.push(y({},n,e));return t.output(o(u))},P=(e,t,r,o)=>{const a=s(e),p=s(t),l=[...a.tuples()],f=[...p.tuples()],d=i(o,l,f),T=[];for(const e of l){const t=[];for(const n of f)u(e,n,d)&&t.push(c(n,d));T.push(y({},e,{[r]:new n(t)}))}return a.output(T)},N=(e,n)=>n.map(n=>JSON.stringify(e[n])).join("|"),J=(e,n)=>n.reduce((n,t)=>(n[t]=e[t],n),{}),L=(e,n)=>{if("function"==typeof n)return n(e);const t="string"==typeof n?{op:n,attr:""}:n,{op:r,attr:o}=t;switch(r){case"count":return e.length;case"sum":return e.reduce((e,n)=>e+(Number(n[o])||0),0);case"min":{const n=e.map(e=>e[o]).filter(e=>null!=e);return n.length>0?Math.min(...n.map(Number)):null}case"max":{const n=e.map(e=>e[o]).filter(e=>null!=e);return n.length>0?Math.max(...n.map(Number)):null}case"avg":{const n=e.map(e=>Number(e[o])).filter(e=>!isNaN(e));return n.length>0?n.reduce((e,n)=>e+n,0)/n.length:null}case"collect":return e.map(e=>e[o]);default:throw new Error(`Unknown aggregator: ${r}`)}},F=(e,n,t)=>{const r=s(e),o=[...r.tuples()],a=new Map;for(const e of o){const t=N(e,n);a.has(t)||a.set(t,[]),a.get(t).push(e)}const i=[];for(const e of a.values()){const r=J(e[0],n);for(const[n,o]of Object.entries(t))r[n]=L(e,o);i.push(r)}return r.output(i)},B=(e,n)=>n.map(n=>JSON.stringify(e[n])).join("|"),$=(e,n)=>n.reduce((n,t)=>(n[t]=e[t],n),{}),_=(e,t,r)=>{const o=s(e),a=[...o.tuples()];if(0===a.length)return o.output([]);const i=Object.keys(a[0]),u=new Set(t),p=i.filter(e=>!u.has(e)),c=new Map;for(const e of a){const n=B(e,p);c.has(n)||c.set(n,{base:$(e,p),nested:[]}),c.get(n).nested.push($(e,t))}const l=[];for(const{base:e,nested:t}of c.values())l.push(y({},e,{[r]:new n(t)}));return o.output(l)},M=e=>{if(t(e))return e.toArray();if(Array.isArray(e))return e;throw new Error("Value is not a relation or array")},U=(e,n)=>{const t=s(e),r=[...t.tuples()],o=[];for(const e of r){const t=M(e[n]),r={};for(const[t,o]of Object.entries(e))t!==n&&(r[t]=o);for(const e of t)o.push(y({},r,e))}return t.output(o)},C=(e,n,t)=>{const r=s(e),o=r.tuples(),a=new Set(n),i=[];for(const e of o){const n={},r={};for(const[t,o]of Object.entries(e))a.has(t)?n[t]=o:r[t]=o;i.push(y({},r,{[t]:n}))}return r.output(i)},X=(e,n)=>{const t=s(e),r=t.tuples(),o=[];for(const e of r){const t=e[n];if("object"!=typeof t||null===t||Array.isArray(t))throw new Error(`Attribute '${n}' is not a tuple (object)`);const r={};for(const[t,o]of Object.entries(e))t!==n&&(r[t]=o);o.push(y({},r,t))}return t.output(o)},q=(e,n)=>{var t;const r=null!=(t=null==n?void 0:n.separator)?t:"_",o=s(e),a=o.tuples(),i=[];for(const e of a){const n={};for(const[t,o]of Object.entries(e)){const e=t.split(r);if(1===e.length)n[t]=o;else{var u;const[t,...s]=e;n[t]=null!=(u=n[t])?u:{},n[t][s.join(r)]=o}}i.push(n)}return o.output(i)},z=(e,n)=>{const t=s(e),r=t.tuples(),o=[];for(const e of r){const t={};for(const[r,o]of Object.entries(e))t[r]=D(o,r,n);o.push(t)}return t.output(o)},D=(e,n,t)=>{if("function"==typeof t)return t(e);if(Array.isArray(t))return t.reduce((e,n)=>n(e),e);{const r=t[n];return r?Array.isArray(r)?r.reduce((e,n)=>n(e),e):r(e):e}},H=(e,n)=>{const t=s(e),o=s(n),a=new Set;for(const e of t.tuples())a.add(r(e));const i=new Set;for(const e of o.tuples())i.add(r(e));if(a.size!==i.size)return!1;for(const e of a)if(!i.has(e))return!1;return!0},I=e=>{const n=s(e).tuples();let t;for(const e of n){if(t)return a("More than one tuple found");t=e}return t||a("Relation is empty")},W=(e,n,t)=>{const r=s(e).tuples(),o={};for(const e of r)o[`${e[t]}`]=e[n];return o},Y="\n/**\n * Type definitions for Bmg.js relational algebra library.\n *\n * This file defines all types needed for type-safe relational operations:\n * - Base types (AttrName, Tuple)\n * - Utility types for transformations (Renamed, Prefixed, Joined, etc.)\n * - The Relation interface with all operators\n * - Helper types for predicates, extensions, aggregators, etc.\n */\n\n// ============================================================================\n// Base Types\n// ============================================================================\n\n/** Attribute name in a tuple */\ntype AttrName = string\n\n/** A tuple is a record mapping attribute names to values */\ntype Tuple = Record<AttrName, unknown>\n\n// ============================================================================\n// Rename Types\n// ============================================================================\n\n/** Map from old attribute names to new attribute names */\ntype RenameMap<T> = { [K in keyof T]?: string };\n\n/** Transform tuple type by renaming keys according to RenameMap */\ntype Renamed<T, R extends RenameMap<T>> = {\n [K in keyof T as K extends keyof R ? (R[K] extends string ? R[K] : K) : K]: T[K];\n};\n\n// ============================================================================\n// Prefix/Suffix Types\n// ============================================================================\n\n/** Prefix all keys except those in Except */\ntype Prefixed<T, P extends string, Except extends keyof T = never> = {\n [K in keyof T as K extends Except ? K : `${P}${K & string}`]: T[K];\n};\n\n/** Suffix all keys except those in Except */\ntype Suffixed<T, S extends string, Except extends keyof T = never> = {\n [K in keyof T as K extends Except ? K : `${K & string}${S}`]: T[K];\n};\n\n// ============================================================================\n// Join Types\n// ============================================================================\n\n/** Extract common keys between two tuple types */\ntype CommonKeys<L, R> = Extract<keyof L, keyof R>;\n\n/** Result of inner join: L & R with R's common keys removed */\ntype Joined<L, R> = L & Omit<R, CommonKeys<L, R>>;\n\n/** Result of left join: L & optional R attributes (common keys removed) */\ntype LeftJoined<L, R> = L & Partial<Omit<R, CommonKeys<L, R>>>;\n\n/**\n * Typed join keys for array form: keys must exist on BOTH operands.\n * Example: suppliers.join(parts, ['city']) - 'city' must be a key of both.\n */\ntype TypedJoinKeysArray<L, R> = (keyof L & keyof R & string)[];\n\n/**\n * Typed join keys for object form: maps left keys to right keys.\n * Example: suppliers.join(parts, { sid: 'supplier_id' })\n * - Left key (sid) must exist on L\n * - Right key (supplier_id) must exist on R\n */\ntype TypedJoinKeysObject<L, R> = { [K in keyof L & string]?: keyof R & string };\n\n// ============================================================================\n// Wrap/Unwrap Types\n// ============================================================================\n\n/** Result of wrap: remove wrapped attrs, add nested object */\ntype Wrapped<T, K extends keyof T, As extends string> =\n Omit<T, K> & Record<As, Pick<T, K>>;\n\n/** Result of unwrap: remove object attr, spread its properties */\ntype Unwrapped<T, K extends keyof T> =\n T[K] extends Record<string, unknown> ? Omit<T, K> & T[K] : Omit<T, K>;\n\n/** Result of ungroup: remove relation attr, flatten its tuple type */\ntype Ungrouped<T, K extends keyof T> =\n T[K] extends Relation<infer N> ? Omit<T, K> & N : Omit<T, K>;\n\n// ============================================================================\n// Aggregator Types\n// ============================================================================\n\ntype AggregatorName = 'count' | 'sum' | 'min' | 'max' | 'avg' | 'collect'\ntype AggregatorSpec = { op: AggregatorName, attr: AttrName }\ntype AggregatorFunc = (tuples: Tuple[]) => unknown\ntype Aggregator = AggregatorName | AggregatorSpec | AggregatorFunc\ntype Aggregators = Record<AttrName, Aggregator>\n\n/** Infer result type from aggregator specification */\ntype AggregatorResult<A> =\n A extends 'count' ? number :\n A extends { op: 'count' } ? number :\n A extends { op: 'sum' | 'avg' | 'min' | 'max' } ? number | null :\n A extends { op: 'collect' } ? unknown[] :\n A extends (tuples: Tuple[]) => infer R ? R :\n unknown;\n\n/** Map aggregator definitions to their result types */\ntype AggregatorResults<Aggs extends Record<string, unknown>> = {\n [K in keyof Aggs]: AggregatorResult<Aggs[K]>;\n};\n\n// ============================================================================\n// Predicate Types\n// ============================================================================\n\n/** Predicate function that receives a typed tuple */\ntype TypedPredicateFunc<T> = (t: T) => boolean\n\n/** Predicate: either a partial tuple for equality matching, or a function */\ntype TypedPredicate<T> = Partial<T> | TypedPredicateFunc<T>\n\n// Legacy predicate types (for backwards compatibility with standalone operators)\ntype PredicateFunc = ((t: Tuple) => any)\ntype Predicate = Tuple | PredicateFunc\n\n// ============================================================================\n// Extension Types\n// ============================================================================\n\n/** Extension function that receives a typed tuple */\ntype TypedExtensionFunc<T, R> = (tuple: T) => R\n\n/** Extension definition: function returning value, or attribute name to copy */\ntype TypedExtension<T, E extends Record<string, unknown>> = {\n [K in keyof E]: TypedExtensionFunc<T, E[K]> | keyof T;\n}\n\ntype ExtensionFunc = (tuple: Tuple) => unknown\ntype Extension = Record<AttrName, ExtensionFunc | AttrName>\n\n// ============================================================================\n// Other Helper Types\n// ============================================================================\n\ninterface PrefixOptions {\n except?: AttrName[]\n}\n\ninterface SuffixOptions {\n except?: AttrName[]\n}\n\ninterface AutowrapOptions {\n separator?: string\n}\n\ntype Renaming = RenamingObj | RenamingFunc\ntype RenamingFunc = (attr: AttrName) => AttrName\ntype RenamingObj = Record<AttrName, AttrName>\n\ntype JoinKeys = AttrName[] | Record<AttrName, AttrName>\n\ntype TransformFunc = (value: unknown) => unknown\ntype Transformation = TransformFunc | TransformFunc[] | Record<AttrName, TransformFunc | TransformFunc[]>\n\n// ============================================================================\n// Relation Interface\n// ============================================================================\n\n/**\n * Relation interface with generic type parameter for tuple type.\n * Default parameter `Tuple` ensures backwards compatibility.\n *\n * @typeParam T - The tuple type for this relation. Defaults to `Tuple` (Record<string, unknown>).\n *\n * @example\n * // Untyped usage (backwards compatible)\n * const r = Bmg([{ id: 1 }]); // Relation<Tuple>\n *\n * @example\n * // Typed usage with full type safety\n * interface Person { id: number; name: string }\n * const r = Bmg<Person>([{ id: 1, name: 'Alice' }]);\n * r.project(['id']); // Relation<{ id: number }>\n */\ninterface Relation<T = Tuple> {\n // === Type-preserving operators ===\n\n restrict(p: TypedPredicate<T>): Relation<T>\n where(p: TypedPredicate<T>): Relation<T>\n exclude(p: TypedPredicate<T>): Relation<T>\n\n // === Projection operators ===\n\n project<K extends keyof T>(attrs: K[]): Relation<Pick<T, K>>\n allbut<K extends keyof T>(attrs: K[]): Relation<Omit<T, K>>\n\n // === Extension operators ===\n\n extend<E extends Record<string, unknown>>(e: TypedExtension<T, E>): Relation<T & E>\n constants<C extends Tuple>(consts: C): Relation<T & C>\n\n // === Rename operators ===\n\n rename<R extends RenameMap<T>>(r: R): Relation<Renamed<T, R>>\n prefix<P extends string, Ex extends keyof T = never>(pfx: P, options?: { except?: Ex[] }): Relation<Prefixed<T, P, Ex>>\n suffix<S extends string, Ex extends keyof T = never>(sfx: S, options?: { except?: Ex[] }): Relation<Suffixed<T, S, Ex>>\n\n // === Set operators (require same type) ===\n\n union(right: RelationOperand<T>): Relation<T>\n minus(right: RelationOperand<T>): Relation<T>\n intersect(right: RelationOperand<T>): Relation<T>\n\n // === Semi-join operators (preserve left type) ===\n\n matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T>\n not_matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T>\n\n // === Join operators ===\n\n join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<Joined<T, R>>\n left_join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<LeftJoined<T, R>>\n cross_product<R>(right: RelationOperand<R>): Relation<T & R>\n cross_join<R>(right: RelationOperand<R>): Relation<T & R>\n\n // === Nesting operators ===\n\n image<R, As extends string>(right: RelationOperand<R>, as: As, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T & Record<As, Relation<Omit<R, keyof T & keyof R>>>>\n group<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Omit<T, K> & Record<As, Relation<Pick<T, K>>>>\n ungroup<K extends keyof T>(attr: K): Relation<Ungrouped<T, K>>\n wrap<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Wrapped<T, K, As>>\n unwrap<K extends keyof T>(attr: K): Relation<Unwrapped<T, K>>\n\n // === Aggregation ===\n\n summarize<By extends keyof T, Aggs extends Aggregators>(by: By[], aggs: Aggs): Relation<Pick<T, By> & AggregatorResults<Aggs>>\n\n // === Transform ===\n\n transform(t: Transformation): Relation<T>\n\n // === Dynamic (loses type precision) ===\n\n autowrap(options?: AutowrapOptions): Relation<Tuple>\n\n // === Non-relational ===\n\n one(): T\n yByX<Y extends keyof T, X extends keyof T>(y: Y, x: X): Record<T[X] & PropertyKey, T[Y]>\n toArray(): T[]\n isEqual(right: any): boolean\n}\n\n// ============================================================================\n// Operands\n// ============================================================================\n\ntype RelationOperand<T = Tuple> = Relation<T> | T[]\n\ninterface OperationalOperand<T = Tuple> {\n tuples(): Iterable<T>\n output(tuples: T[]): RelationOperand<T>\n}\n\n// ============================================================================\n// Bmg Function Declaration\n// ============================================================================\n\n/** Create a relation from an array of tuples */\ndeclare function Bmg<T>(tuples: T[]): Relation<T>\ndeclare namespace Bmg {\n function isRelation(op: unknown): boolean\n}\n";function V(e){return new n(e)}V.isRelation=t;export{V as Bmg,Y as LIB_DEFINITIONS,h as allbut,q as autowrap,d as constants,S as cross_join,S as cross_product,f as exclude,x as extend,_ as group,P as image,w as intersect,H as isEqual,t as isRelation,j as join,v as left_join,b as matching,k as minus,K as not_matching,I as one,g as prefix,R as project,T as rename,l as restrict,m as suffix,F as summarize,z as transform,U as ungroup,A as union,X as unwrap,l as where,C as wrap,W as yByX};
1
+ const e=e=>{if("function"==typeof e)return e;{const n=e;return e=>Object.keys(n).every(t=>e[t]===n[t])}},n=e=>null!=e&&e.constructor===p,t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=(e,n)=>null===e?null!=n?n:0:null===n||e>n?e:n;class s{constructor(e,n){this.value=void 0,this.renderer=void 0,this._textRendering=null,this._minWidth=null,this.renderer=e,this.value=n}get minWidth(){return null===this._minWidth&&(this._minWidth=this.renderingLines().reduce((e,n)=>r(e,n.length),0)),this._minWidth}renderingLines(e){return void 0===e?this.textRendering.split("\n"):"number"==typeof this.value?this.renderingLines().map(n=>n.padStart(e)):this.renderingLines().map(n=>n.padEnd(e))}get textRendering(){return null===this._textRendering&&(this._textRendering=this.computeTextRendering()),this._textRendering}computeTextRendering(){const e=this.value;if(null===e)return"[null]";if(void 0===e)return"[undefined]";if("symbol"==typeof e)return e.toString();if("number"==typeof e){var r;if(Number.isInteger(e))return String(e);const n=null!=(r=this.renderer.options.floatPrecision)?r:3;return e.toFixed(n)}return n(s=e)||Array.isArray(s)&&s.every(t)?this.renderer.render(e,""):Array.isArray(e)?this.arrayRendering(e):e instanceof Date?e.toISOString():"object"==typeof e?JSON.stringify(e):String(e);var s}arrayRendering(e){if(e.length>0&&t(e[0]))return this.renderer.render(e,"");if(0===e.length)return"[]";const n=e.map(e=>new s(this.renderer,e).textRendering);return n.reduce((e,n)=>e+n.length,0)<20?"["+n.join(", ")+"]":"["+n.join(",\n ")+"]"}}class o{constructor(e,n){this.cells=void 0,this.cells=n.map(n=>new s(e,n))}minWidths(){return this.cells.map(e=>e.minWidth)}renderingLines(e){let n=0;const t=this.cells.map((t,s)=>{const o=t.renderingLines(e[s]);return n=r(n,o.length),o}),s=[];for(let r=0;r<n;r++){const n=t.map((n,t)=>{var s;return null!=(s=n[r])?s:" ".repeat(e[t])}).join(" | ");s.push("| "+n+" |")}return 0===s.length?["| |"]:s}}class i{constructor(e,n,t){this.renderer=void 0,this.header=void 0,this.rows=void 0,this._sizes=null,this._sep=null,this.renderer=e,this.header=new o(e,t),this.rows=n.map(n=>new o(e,n))}get sizes(){if(null===this._sizes){const e=this.header.minWidths();this._sizes=this.rows.reduce((e,n)=>{const t=n.minWidths();return e.map((e,n)=>{var s;return r(e,null!=(s=t[n])?s:0)})},e)}return this._sizes}get sep(){return null===this._sep&&(this._sep="+-"+this.sizes.map(e=>"-".repeat(e)).join("-+-")+"-+"),this._sep}*eachLine(){const e=this.renderer.options.trimAt;if(void 0!==e)for(const n of this.eachLineRaw())yield n.substring(0,e);else yield*this.eachLineRaw()}*eachLineRaw(){yield this.sep,yield this.header.renderingLines(this.sizes)[0],yield this.sep;for(const e of this.rows)for(const n of e.renderingLines(this.sizes))yield n;yield this.sep}*[Symbol.iterator](){for(const e of this.eachLine())yield e.trimEnd()+"\n"}toString(){let e="";for(const n of this)e+=n;return e}}class a{constructor(e={}){this.options=void 0,this.options=e}render(e,n=""){for(const t of this.eachLine(e))n+=t;return n}*eachLine(e){let r;r=t(e)&&!n(e)?[e]:n(e)?e.toArray():e;const s=r.reduce((e,n)=>{for(const t of Object.keys(n))e.includes(t)||e.push(t);return e},[]),o=r.map(e=>s.map(n=>e[n])),a=new i(this,o,s);yield*a}}const u=(e,n={})=>new a(n).render(e);class p{constructor(e){this.tuples=void 0,this.tuples=e,this.tuples=e}restrict(e){return T(this,e)}where(e){return T(this,e)}exclude(e){return R(this,e)}project(e){return O(this,e)}allbut(e){return K(this,e)}extend(e){return j(this,e)}constants(e){return A(this,e)}rename(e){return w(this,e)}prefix(e,n){return b(this,e,n)}suffix(e,n){return k(this,e,n)}union(e){return v(this,e)}minus(e){return S(this,e)}intersect(e){return E(this,e)}matching(e,n){return P(this,e,n)}not_matching(e,n){return N(this,e,n)}join(e,n){return _(this,e,n)}left_join(e,n){return F(this,e,n)}cross_product(e){return B(this,e)}cross_join(e){return B(this,e)}image(e,n,t){return z(this,e,n,t)}group(e,n){return I(this,e,n)}ungroup(e){return q(this,e)}wrap(e,n){return H(this,e,n)}unwrap(e){return Y(this,e)}summarize(e,n){return U(this,e,n)}transform(e){return G(this,e)}autowrap(e){return V(this,e)}one(){return ee(this)}toArray(){return this.tuples}yByX(e,n){return ne(this,e,n)}isEqual(e){return Z(this,e)}toText(e){return u(this,e)}}const c=e=>{const t=Object.entries(e).map(([e,t])=>{return[e,(r=t,n(r)?r.toArray().map(e=>c(e)).sort():r)];var r});return JSON.stringify(t.sort(([e],[n])=>e.localeCompare(n)))},l=e=>{const n=new Set,t=[];for(const r of e){const e=c(r);n.has(e)||(n.add(e),t.push(r))}return t},f=e=>{if(Array.isArray(e))return{tuples:()=>e,output:e=>e};if(n(e))return{tuples:()=>e.toArray(),output:e=>new p(e)};throw`Unable to iterate ${e}`},d=e=>{throw e},y=(e,n,t)=>e?Array.isArray(e)?e.reduce((e,n)=>(e[n]=n,e),{}):e:((e,n)=>{if(0===e.length||0===n.length)return[];const t=new Set(Object.keys(e[0]));return Object.keys(n[0]).filter(e=>t.has(e))})(n,t).reduce((e,n)=>(e[n]=n,e),{}),h=(e,n,t)=>{for(const[r,s]of Object.entries(t))if(e[r]!==n[s])return!1;return!0},g=(e,n,t)=>("left"===t?Object.keys(n):Object.values(n)).map(n=>JSON.stringify(e[n])).join("|"),m=(e,n)=>{const t=new Set(Object.values(n)),r={};for(const[n,s]of Object.entries(e))t.has(n)||(r[n]=s);return r},T=(n,t)=>{const r=f(n),s=r.tuples(),o=e(t),i=[];for(const e of s)o(e)&&i.push(e);return r.output(i)},R=(n,t)=>{const r=f(n),s=r.tuples(),o=e(t),i=[];for(const e of s)o(e)||i.push(e);return r.output(i)};function x(){return x=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)({}).hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},x.apply(null,arguments)}const A=(e,n)=>{const t=f(e),r=t.tuples(),s=[];for(const e of r)s.push(x({},e,n));return t.output(s)},w=(e,n)=>{const t=f(e),r=t.tuples(),s=(e=>"function"==typeof e?e:n=>e[n]||n)(n),o=[];for(const e of r){const n=Object.keys(e).reduce((n,t)=>(n[s(t)]=e[t],n),{});o.push(n)}return t.output(o)},b=(e,n,t)=>{var r;const s=new Set(null!=(r=null==t?void 0:t.except)?r:[]);return w(e,e=>s.has(e)?e:`${n}${e}`)},k=(e,n,t)=>{var r;const s=new Set(null!=(r=null==t?void 0:t.except)?r:[]);return w(e,e=>s.has(e)?e:`${e}${n}`)},O=(e,n)=>{const t=f(e),r=t.tuples(),s=[];for(const e of r){const t=n.reduce((n,t)=>(t in e&&(n[t]=e[t]),n),{});s.push(t)}return t.output(l(s))},K=(e,n)=>{const t=f(e),r=t.tuples(),s=new Set(n),o=[];for(const e of r){const n=Object.keys(e).reduce((n,t)=>(s.has(t)||(n[t]=e[t]),n),{});o.push(n)}return t.output(l(o))},j=(e,n)=>{const t=f(e),r=t.tuples(),s=[];for(const e of r){const t=x({},e);for(const[r,s]of Object.entries(n))t[r]="function"==typeof s?s(e):e[s];s.push(t)}return t.output(s)},v=(e,n)=>{const t=f(e),r=f(n),s=new Set,o=[];for(const e of t.tuples()){const n=c(e);s.has(n)||(s.add(n),o.push(e))}for(const e of r.tuples()){const n=c(e);s.has(n)||(s.add(n),o.push(e))}return t.output(o)},S=(e,n)=>{const t=f(e),r=f(n),s=new Set;for(const e of r.tuples())s.add(c(e));const o=new Set,i=[];for(const e of t.tuples()){const n=c(e);s.has(n)||o.has(n)||(o.add(n),i.push(e))}return t.output(i)},E=(e,n)=>{const t=f(e),r=f(n),s=new Set;for(const e of r.tuples())s.add(c(e));const o=new Set,i=[];for(const e of t.tuples()){const n=c(e);s.has(n)&&!o.has(n)&&(o.add(n),i.push(e))}return t.output(i)},P=(e,n,t)=>{const r=f(e),s=f(n),o=[...r.tuples()],i=[...s.tuples()],a=y(t,o,i),u=new Set;for(const e of i)u.add(g(e,a,"right"));const p=[];for(const e of o)u.has(g(e,a,"left"))&&p.push(e);return r.output(p)},N=(e,n,t)=>{const r=f(e),s=f(n),o=[...r.tuples()],i=[...s.tuples()],a=y(t,o,i),u=new Set;for(const e of i)u.add(g(e,a,"right"));const p=[];for(const e of o)u.has(g(e,a,"left"))||p.push(e);return r.output(p)},L=(e,n,t)=>x({},e,m(n,t)),_=(e,n,t)=>{const r=f(e),s=f(n),o=[...r.tuples()],i=[...s.tuples()],a=y(t,o,i),u=[];for(const e of o)for(const n of i)h(e,n,a)&&u.push(L(e,n,a));return r.output(u)},J=(e,n,t)=>{const r=x({},e);for(const e of t)r[e]=n?n[e]:null;return r},F=(e,n,t)=>{const r=f(e),s=f(n),o=[...r.tuples()],i=[...s.tuples()],a=y(t,o,i),u=((e,n)=>{if(0===e.length)return[];const t=new Set(Object.values(n));return Object.keys(e[0]).filter(e=>!t.has(e))})(i,a),p=[];for(const e of o){let n=!1;for(const t of i)h(e,t,a)&&(p.push(J(e,t,u)),n=!0);n||p.push(J(e,null,u))}return r.output(p)},B=(e,n)=>{const t=f(e),r=f(n),s=[...t.tuples()],o=[...r.tuples()],i=[];for(const e of s)for(const n of o)i.push(x({},n,e));return t.output(l(i))},z=(e,n,t,r)=>{const s=f(e),o=f(n),i=[...s.tuples()],a=[...o.tuples()],u=y(r,i,a),c=[];for(const e of i){const n=[];for(const t of a)h(e,t,u)&&n.push(m(t,u));c.push(x({},e,{[t]:new p(n)}))}return s.output(c)},M=(e,n)=>n.map(n=>JSON.stringify(e[n])).join("|"),W=(e,n)=>n.reduce((n,t)=>(n[t]=e[t],n),{}),$=(e,n)=>{if("function"==typeof n)return n(e);const t="string"==typeof n?{op:n,attr:""}:n,{op:r,attr:s}=t;switch(r){case"count":return e.length;case"sum":return e.reduce((e,n)=>e+(Number(n[s])||0),0);case"min":{const n=e.map(e=>e[s]).filter(e=>null!=e);return n.length>0?Math.min(...n.map(Number)):null}case"max":{const n=e.map(e=>e[s]).filter(e=>null!=e);return n.length>0?Math.max(...n.map(Number)):null}case"avg":{const n=e.map(e=>Number(e[s])).filter(e=>!isNaN(e));return n.length>0?n.reduce((e,n)=>e+n,0)/n.length:null}case"collect":return e.map(e=>e[s]);default:throw new Error(`Unknown aggregator: ${r}`)}},U=(e,n,t)=>{const r=f(e),s=[...r.tuples()],o=new Map;for(const e of s){const t=M(e,n);o.has(t)||o.set(t,[]),o.get(t).push(e)}const i=[];for(const e of o.values()){const r=W(e[0],n);for(const[n,s]of Object.entries(t))r[n]=$(e,s);i.push(r)}return r.output(i)},C=(e,n)=>n.map(n=>JSON.stringify(e[n])).join("|"),D=(e,n)=>n.reduce((n,t)=>(n[t]=e[t],n),{}),I=(e,n,t)=>{const r=f(e),s=[...r.tuples()];if(0===s.length)return r.output([]);const o=Object.keys(s[0]),i=new Set(n),a=o.filter(e=>!i.has(e)),u=new Map;for(const e of s){const t=C(e,a);u.has(t)||u.set(t,{base:D(e,a),nested:[]}),u.get(t).nested.push(D(e,n))}const c=[];for(const{base:e,nested:n}of u.values())c.push(x({},e,{[t]:new p(n)}));return r.output(c)},X=e=>{if(n(e))return e.toArray();if(Array.isArray(e))return e;throw new Error("Value is not a relation or array")},q=(e,n)=>{const t=f(e),r=[...t.tuples()],s=[];for(const e of r){const t=X(e[n]),r={};for(const[t,s]of Object.entries(e))t!==n&&(r[t]=s);for(const e of t)s.push(x({},r,e))}return t.output(s)},H=(e,n,t)=>{const r=f(e),s=r.tuples(),o=new Set(n),i=[];for(const e of s){const n={},r={};for(const[t,s]of Object.entries(e))o.has(t)?n[t]=s:r[t]=s;i.push(x({},r,{[t]:n}))}return r.output(i)},Y=(e,n)=>{const t=f(e),r=t.tuples(),s=[];for(const e of r){const t=e[n];if("object"!=typeof t||null===t||Array.isArray(t))throw new Error(`Attribute '${n}' is not a tuple (object)`);const r={};for(const[t,s]of Object.entries(e))t!==n&&(r[t]=s);s.push(x({},r,t))}return t.output(s)},V=(e,n)=>{var t;const r=null!=(t=null==n?void 0:n.separator)?t:"_",s=f(e),o=s.tuples(),i=[];for(const e of o){const n={};for(const[t,s]of Object.entries(e)){const e=t.split(r);if(1===e.length)n[t]=s;else{var a;const[t,...o]=e;n[t]=null!=(a=n[t])?a:{},n[t][o.join(r)]=s}}i.push(n)}return s.output(i)},G=(e,n)=>{const t=f(e),r=t.tuples(),s=[];for(const e of r){const t={};for(const[r,s]of Object.entries(e))t[r]=Q(s,r,n);s.push(t)}return t.output(s)},Q=(e,n,t)=>{if("function"==typeof t)return t(e);if(Array.isArray(t))return t.reduce((e,n)=>n(e),e);{const r=t[n];return r?Array.isArray(r)?r.reduce((e,n)=>n(e),e):r(e):e}},Z=(e,n)=>{const t=f(e),r=f(n),s=new Set;for(const e of t.tuples())s.add(c(e));const o=new Set;for(const e of r.tuples())o.add(c(e));if(s.size!==o.size)return!1;for(const e of s)if(!o.has(e))return!1;return!0},ee=e=>{const n=f(e).tuples();let t;for(const e of n){if(t)return d("More than one tuple found");t=e}return t||d("Relation is empty")},ne=(e,n,t)=>{const r=f(e).tuples(),s={};for(const e of r)s[`${e[t]}`]=e[n];return s},te="\n/**\n * Type definitions for Bmg.js relational algebra library.\n *\n * This file defines all types needed for type-safe relational operations:\n * - Base types (AttrName, Tuple)\n * - Utility types for transformations (Renamed, Prefixed, Joined, etc.)\n * - The Relation interface with all operators\n * - Helper types for predicates, extensions, aggregators, etc.\n */\n\n// ============================================================================\n// Base Types\n// ============================================================================\n\n/** Attribute name in a tuple */\ntype AttrName = string\n\n/** A tuple is a record mapping attribute names to values */\ntype Tuple = Record<AttrName, unknown>\n\n// ============================================================================\n// Rename Types\n// ============================================================================\n\n/** Map from old attribute names to new attribute names */\ntype RenameMap<T> = { [K in keyof T]?: string };\n\n/** Transform tuple type by renaming keys according to RenameMap */\ntype Renamed<T, R extends RenameMap<T>> = {\n [K in keyof T as K extends keyof R ? (R[K] extends string ? R[K] : K) : K]: T[K];\n};\n\n// ============================================================================\n// Prefix/Suffix Types\n// ============================================================================\n\n/** Prefix all keys except those in Except */\ntype Prefixed<T, P extends string, Except extends keyof T = never> = {\n [K in keyof T as K extends Except ? K : `${P}${K & string}`]: T[K];\n};\n\n/** Suffix all keys except those in Except */\ntype Suffixed<T, S extends string, Except extends keyof T = never> = {\n [K in keyof T as K extends Except ? K : `${K & string}${S}`]: T[K];\n};\n\n// ============================================================================\n// Join Types\n// ============================================================================\n\n/** Extract common keys between two tuple types */\ntype CommonKeys<L, R> = Extract<keyof L, keyof R>;\n\n/** Result of inner join: L & R with R's common keys removed */\ntype Joined<L, R> = L & Omit<R, CommonKeys<L, R>>;\n\n/** Result of left join: L & optional R attributes (common keys removed) */\ntype LeftJoined<L, R> = L & Partial<Omit<R, CommonKeys<L, R>>>;\n\n/**\n * Typed join keys for array form: keys must exist on BOTH operands.\n * Example: suppliers.join(parts, ['city']) - 'city' must be a key of both.\n */\ntype TypedJoinKeysArray<L, R> = (keyof L & keyof R & string)[];\n\n/**\n * Typed join keys for object form: maps left keys to right keys.\n * Example: suppliers.join(parts, { sid: 'supplier_id' })\n * - Left key (sid) must exist on L\n * - Right key (supplier_id) must exist on R\n */\ntype TypedJoinKeysObject<L, R> = { [K in keyof L & string]?: keyof R & string };\n\n// ============================================================================\n// Wrap/Unwrap Types\n// ============================================================================\n\n/** Result of wrap: remove wrapped attrs, add nested object */\ntype Wrapped<T, K extends keyof T, As extends string> =\n Omit<T, K> & Record<As, Pick<T, K>>;\n\n/** Result of unwrap: remove object attr, spread its properties */\ntype Unwrapped<T, K extends keyof T> =\n T[K] extends Record<string, unknown> ? Omit<T, K> & T[K] : Omit<T, K>;\n\n/** Result of ungroup: remove relation attr, flatten its tuple type */\ntype Ungrouped<T, K extends keyof T> =\n T[K] extends Relation<infer N> ? Omit<T, K> & N : Omit<T, K>;\n\n// ============================================================================\n// Aggregator Types\n// ============================================================================\n\ntype AggregatorName = 'count' | 'sum' | 'min' | 'max' | 'avg' | 'collect'\ntype AggregatorSpec = { op: AggregatorName, attr: AttrName }\ntype AggregatorFunc = (tuples: Tuple[]) => unknown\ntype Aggregator = AggregatorName | AggregatorSpec | AggregatorFunc\ntype Aggregators = Record<AttrName, Aggregator>\n\n/** Infer result type from aggregator specification */\ntype AggregatorResult<A> =\n A extends 'count' ? number :\n A extends { op: 'count' } ? number :\n A extends { op: 'sum' | 'avg' | 'min' | 'max' } ? number | null :\n A extends { op: 'collect' } ? unknown[] :\n A extends (tuples: Tuple[]) => infer R ? R :\n unknown;\n\n/** Map aggregator definitions to their result types */\ntype AggregatorResults<Aggs extends Record<string, unknown>> = {\n [K in keyof Aggs]: AggregatorResult<Aggs[K]>;\n};\n\n// ============================================================================\n// Predicate Types\n// ============================================================================\n\n/** Predicate function that receives a typed tuple */\ntype TypedPredicateFunc<T> = (t: T) => boolean\n\n/** Predicate: either a partial tuple for equality matching, or a function */\ntype TypedPredicate<T> = Partial<T> | TypedPredicateFunc<T>\n\n// Legacy predicate types (for backwards compatibility with standalone operators)\ntype PredicateFunc = ((t: Tuple) => any)\ntype Predicate = Tuple | PredicateFunc\n\n// ============================================================================\n// Extension Types\n// ============================================================================\n\n/** Extension function that receives a typed tuple */\ntype TypedExtensionFunc<T, R> = (tuple: T) => R\n\n/** Extension definition: function returning value, or attribute name to copy */\ntype TypedExtension<T, E extends Record<string, unknown>> = {\n [K in keyof E]: TypedExtensionFunc<T, E[K]> | keyof T;\n}\n\ntype ExtensionFunc = (tuple: Tuple) => unknown\ntype Extension = Record<AttrName, ExtensionFunc | AttrName>\n\n// ============================================================================\n// Other Helper Types\n// ============================================================================\n\ninterface PrefixOptions {\n except?: AttrName[]\n}\n\ninterface TextOptions {\n /** Precision for floating point numbers (default: 3) */\n floatPrecision?: number;\n /** Maximum width to trim output at */\n trimAt?: number;\n}\n\ninterface SuffixOptions {\n except?: AttrName[]\n}\n\ninterface AutowrapOptions {\n separator?: string\n}\n\ntype Renaming = RenamingObj | RenamingFunc\ntype RenamingFunc = (attr: AttrName) => AttrName\ntype RenamingObj = Record<AttrName, AttrName>\n\ntype JoinKeys = AttrName[] | Record<AttrName, AttrName>\n\ntype TransformFunc = (value: unknown) => unknown\ntype Transformation = TransformFunc | TransformFunc[] | Record<AttrName, TransformFunc | TransformFunc[]>\n\n// ============================================================================\n// Relation Interface\n// ============================================================================\n\n/**\n * Relation interface with generic type parameter for tuple type.\n * Default parameter `Tuple` ensures backwards compatibility.\n *\n * @typeParam T - The tuple type for this relation. Defaults to `Tuple` (Record<string, unknown>).\n *\n * @example\n * // Untyped usage (backwards compatible)\n * const r = Bmg([{ id: 1 }]); // Relation<Tuple>\n *\n * @example\n * // Typed usage with full type safety\n * interface Person { id: number; name: string }\n * const r = Bmg<Person>([{ id: 1, name: 'Alice' }]);\n * r.project(['id']); // Relation<{ id: number }>\n */\ninterface Relation<T = Tuple> {\n // === Type-preserving operators ===\n\n restrict(p: TypedPredicate<T>): Relation<T>\n where(p: TypedPredicate<T>): Relation<T>\n exclude(p: TypedPredicate<T>): Relation<T>\n\n // === Projection operators ===\n\n project<K extends keyof T>(attrs: K[]): Relation<Pick<T, K>>\n allbut<K extends keyof T>(attrs: K[]): Relation<Omit<T, K>>\n\n // === Extension operators ===\n\n extend<E extends Record<string, unknown>>(e: TypedExtension<T, E>): Relation<T & E>\n constants<C extends Tuple>(consts: C): Relation<T & C>\n\n // === Rename operators ===\n\n rename<R extends RenameMap<T>>(r: R): Relation<Renamed<T, R>>\n prefix<P extends string, Ex extends keyof T = never>(pfx: P, options?: { except?: Ex[] }): Relation<Prefixed<T, P, Ex>>\n suffix<S extends string, Ex extends keyof T = never>(sfx: S, options?: { except?: Ex[] }): Relation<Suffixed<T, S, Ex>>\n\n // === Set operators (require same type) ===\n\n union(right: RelationOperand<T>): Relation<T>\n minus(right: RelationOperand<T>): Relation<T>\n intersect(right: RelationOperand<T>): Relation<T>\n\n // === Semi-join operators (preserve left type) ===\n\n matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T>\n not_matching<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T>\n\n // === Join operators ===\n\n join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<Joined<T, R>>\n left_join<R>(right: RelationOperand<R>, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<LeftJoined<T, R>>\n cross_product<R>(right: RelationOperand<R>): Relation<T & R>\n cross_join<R>(right: RelationOperand<R>): Relation<T & R>\n\n // === Nesting operators ===\n\n image<R, As extends string>(right: RelationOperand<R>, as: As, keys?: TypedJoinKeysArray<T, R> | TypedJoinKeysObject<T, R>): Relation<T & Record<As, Relation<Omit<R, keyof T & keyof R>>>>\n group<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Omit<T, K> & Record<As, Relation<Pick<T, K>>>>\n ungroup<K extends keyof T>(attr: K): Relation<Ungrouped<T, K>>\n wrap<K extends keyof T, As extends string>(attrs: K[], as: As): Relation<Wrapped<T, K, As>>\n unwrap<K extends keyof T>(attr: K): Relation<Unwrapped<T, K>>\n\n // === Aggregation ===\n\n summarize<By extends keyof T, Aggs extends Aggregators>(by: By[], aggs: Aggs): Relation<Pick<T, By> & AggregatorResults<Aggs>>\n\n // === Transform ===\n\n transform(t: Transformation): Relation<T>\n\n // === Dynamic (loses type precision) ===\n\n autowrap(options?: AutowrapOptions): Relation<Tuple>\n\n // === Non-relational ===\n\n one(): T\n yByX<Y extends keyof T, X extends keyof T>(y: Y, x: X): Record<T[X] & PropertyKey, T[Y]>\n toArray(): T[]\n isEqual(right: any): boolean\n\n // === Display ===\n\n toText(options?: TextOptions): string\n}\n\n// ============================================================================\n// Operands\n// ============================================================================\n\ntype RelationOperand<T = Tuple> = Relation<T> | T[]\n\ninterface OperationalOperand<T = Tuple> {\n tuples(): Iterable<T>\n output(tuples: T[]): RelationOperand<T>\n}\n\n// ============================================================================\n// Bmg Function Declaration\n// ============================================================================\n\n/** Create a relation from an array of tuples */\ndeclare function Bmg<T>(tuples: T[]): Relation<T>\ndeclare namespace Bmg {\n function isRelation(op: unknown): boolean\n}\n";function re(e){return new p(e)}re.isRelation=n;const se=new p([{}]),oe=new p([]);export{re as Bmg,se as DEE,oe as DUM,te as LIB_DEFINITIONS,K as allbut,V as autowrap,A as constants,B as cross_join,B as cross_product,R as exclude,j as extend,I as group,z as image,E as intersect,Z as isEqual,n as isRelation,_ as join,F as left_join,P as matching,S as minus,N as not_matching,ee as one,b as prefix,O as project,w as rename,T as restrict,k as suffix,U as summarize,u as toText,G as transform,q as ungroup,v as union,Y as unwrap,T as where,H as wrap,ne as yByX};
2
2
  //# sourceMappingURL=bmg.modern.js.map