stdlib.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. import { describe, expect, test } from "bun:test"
  2. import { Effect, Schema } from "effect"
  3. import { CodeMode, Tool } from "../src/index.js"
  4. // Standard-library value types: Date, RegExp, Map, Set. Programs use them as ordinary JS;
  5. // intra-CodeMode checkpoints (Object.* helpers, spread, coercion inputs) preserve the live
  6. // values, while at the host boundary (final result, tool arguments, JSON.stringify) they
  7. // serialize exactly as JSON.stringify would: Date -> ISO string (invalid -> null),
  8. // URL -> href, and RegExp/Map/Set/URLSearchParams -> {}.
  9. const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} }))
  10. const value = async (code: string) => {
  11. const result = await run(code)
  12. if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
  13. return result.value
  14. }
  15. const error = async (code: string) => {
  16. const result = await run(code)
  17. if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`)
  18. return result.error
  19. }
  20. describe("Number and Math", () => {
  21. test("Math.random returns a number in [0, 1)", async () => {
  22. expect(await value(`const n = Math.random(); return typeof n === "number" && n >= 0 && n < 1`)).toBe(true)
  23. })
  24. test("Number exposes native non-finite constants", async () => {
  25. expect(
  26. await value(
  27. `return [Number.isNaN(Number.NaN), Number.POSITIVE_INFINITY === Infinity, Number.NEGATIVE_INFINITY === -Infinity]`,
  28. ),
  29. ).toEqual([true, true, true])
  30. })
  31. test("Number valueOf returns its primitive receiver", async () => {
  32. expect(await value(`return (42).valueOf()`)).toBe(42)
  33. })
  34. test("Number valueOf does not enable boxed numbers", async () => {
  35. expect((await error(`return new Number(42)`)).kind).toBe("UnsupportedSyntax")
  36. })
  37. })
  38. describe("Date", () => {
  39. test("Date.now() returns a number", async () => {
  40. expect(await value(`return typeof Date.now()`)).toBe("number")
  41. })
  42. test("epoch construction and ISO rendering", async () => {
  43. expect(await value(`return new Date(0).toISOString()`)).toBe("1970-01-01T00:00:00.000Z")
  44. })
  45. test("string parsing round-trips", async () => {
  46. expect(await value(`return new Date("2024-01-02T03:04:05.000Z").getTime()`)).toBe(1704164645000)
  47. expect(await value(`return Date.parse("2024-01-02T03:04:05.000Z")`)).toBe(1704164645000)
  48. })
  49. test("date arithmetic and comparison use the time value", async () => {
  50. expect(await value(`const a = new Date(1000); const b = new Date(3000); return b - a`)).toBe(2000)
  51. expect(await value(`const a = new Date(1000); const b = new Date(3000); return a < b`)).toBe(true)
  52. expect(await value(`return +new Date(42)`)).toBe(42)
  53. })
  54. test("UTC getters read calendar components", async () => {
  55. expect(
  56. await value(
  57. `const d = new Date("2024-03-05T06:07:08.009Z"); return [d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()]`,
  58. ),
  59. ).toEqual([2024, 2, 5, 6, 7, 8, 9])
  60. })
  61. test("invalid dates yield NaN times, guardable in-CodeMode", async () => {
  62. expect(await value(`return Number.isNaN(new Date("garbage").getTime())`)).toBe(true)
  63. expect(await value(`return new Date("garbage").toJSON()`)).toBeNull()
  64. })
  65. test("toISOString on an invalid date is a catchable error", async () => {
  66. expect(await value(`try { new Date("garbage").toISOString(); return "no" } catch { return "caught" }`)).toBe(
  67. "caught",
  68. )
  69. })
  70. test("template interpolation renders the ISO form", async () => {
  71. expect(await value("return `at ${new Date(0)}`")).toBe("at 1970-01-01T00:00:00.000Z")
  72. })
  73. test("dates serialize to ISO strings at the boundary, direct and nested", async () => {
  74. expect(await value(`return new Date(0)`)).toBe("1970-01-01T00:00:00.000Z")
  75. expect(await value(`return { when: new Date(0), tags: [new Date(1000)] }`)).toEqual({
  76. when: "1970-01-01T00:00:00.000Z",
  77. tags: ["1970-01-01T00:00:01.000Z"],
  78. })
  79. expect(await value(`return JSON.stringify({ d: new Date(0) })`)).toBe('{"d":"1970-01-01T00:00:00.000Z"}')
  80. })
  81. test("coercions: Number is the time, String is ISO, Boolean is true", async () => {
  82. expect(await value(`return Number(new Date(5))`)).toBe(5)
  83. expect(await value(`return String(new Date(0))`)).toBe("1970-01-01T00:00:00.000Z")
  84. expect(await value(`return Boolean(new Date(0))`)).toBe(true)
  85. })
  86. test("sorting dates with a numeric comparator", async () => {
  87. expect(
  88. await value(`
  89. const dates = [new Date(3000), new Date(1000), new Date(2000)]
  90. return dates.sort((a, b) => a - b).map((d) => d.getTime())
  91. `),
  92. ).toEqual([1000, 2000, 3000])
  93. })
  94. test("new Date(year, month, day) accepts component form", async () => {
  95. expect(await value(`const d = new Date(2024, 0, 2); return [d.getFullYear(), d.getMonth(), d.getDate()]`)).toEqual([
  96. 2024, 0, 2,
  97. ])
  98. })
  99. test("typeof and unknown properties are forgiving", async () => {
  100. expect(await value(`return typeof new Date(0)`)).toBe("object")
  101. expect(await value(`return new Date(0).nope === undefined`)).toBe(true)
  102. })
  103. })
  104. describe("RegExp", () => {
  105. test("literal test", async () => {
  106. expect(await value(`return /ab+c/.test("xabbbc")`)).toBe(true)
  107. expect(await value(`return /ab+c/.test("nope")`)).toBe(false)
  108. })
  109. test("exec exposes captures and index", async () => {
  110. expect(await value(`const m = /a(b+)/.exec("xxabbc"); return { full: m[0], group: m[1], index: m.index }`)).toEqual(
  111. {
  112. full: "abb",
  113. group: "bb",
  114. index: 2,
  115. },
  116. )
  117. expect(await value(`return /a/.exec("zzz")`)).toBeNull()
  118. })
  119. test("named groups read through", async () => {
  120. expect(
  121. await value(`const m = /(?<word>[a-z]+)-(?<num>\\d+)/.exec("id ab-42"); return m.groups.word + m.groups.num`),
  122. ).toBe("ab42")
  123. })
  124. test("global exec advances lastIndex across calls", async () => {
  125. expect(
  126. await value(`
  127. const r = /\\d+/g
  128. const first = r.exec("a1b22c")
  129. const second = r.exec("a1b22c")
  130. return [first[0], second[0]]
  131. `),
  132. ).toEqual(["1", "22"])
  133. })
  134. test("an unmatched string pattern returns null", async () => {
  135. expect(await value(`return "abc".match(/\\d/)`)).toBeNull()
  136. })
  137. test("matchAll materializes match arrays with captures", async () => {
  138. expect(await value(`return "a1b22".matchAll(/(\\d+)/g).map((m) => m[1])`)).toEqual(["1", "22"])
  139. })
  140. test("function replacers receive captures, offsets, input, and named groups", async () => {
  141. expect(
  142. await value(`
  143. const seen = []
  144. const output = "a1b22".replace(/(\\d)(\\d)?/g, (match, first, second, offset, input) => {
  145. seen.push([match, first, second === undefined, offset, input])
  146. return Number(match) * 2
  147. })
  148. return { output, seen }
  149. `),
  150. ).toEqual({
  151. output: "a2b44",
  152. seen: [
  153. ["1", "1", true, 1, "a1b22"],
  154. ["22", "2", false, 3, "a1b22"],
  155. ],
  156. })
  157. expect(
  158. await value(`
  159. return "red-blue".replace(
  160. /(?<left>[a-z]+)-(?<right>[a-z]+)/,
  161. (match, left, right, offset, input, groups) => groups.right + ":" + groups.left,
  162. )
  163. `),
  164. ).toBe("blue:red")
  165. })
  166. test("function replacers support string searches, zero-length matches, and result coercion", async () => {
  167. expect(await value(`return "banana".replace("na", (match, offset, input) => "[" + offset + "]")`)).toBe("ba[2]na")
  168. expect(await value(`return "ab".replaceAll("", (match, offset) => offset)`)).toBe("0a1b2")
  169. expect(await value(`return "😀".replaceAll(/(?:)/gu, (match, offset) => "[" + offset + "]")`)).toBe("[0]😀[2]")
  170. expect(
  171. await value(`return "123".replace(/\\d/g, (match) => match === "1" ? 7 : match === "2" ? null : { n: 3 })`),
  172. ).toBe("7null[object Object]")
  173. })
  174. test("function replacers can await effectful tool calls", async () => {
  175. const decorate = Tool.make({
  176. description: "Decorate a string",
  177. input: Schema.String,
  178. output: Schema.String,
  179. run: (input) => Effect.succeed(`[${input}]`),
  180. })
  181. const result = await Effect.runPromise(
  182. CodeMode.execute({
  183. tools: { host: { decorate } },
  184. code: `return "a1b22".replace(/\\d+/g, async (match) => await tools.host.decorate(match))`,
  185. }),
  186. )
  187. expect(result.ok && result.value).toBe("a[1]b[22]")
  188. const missingAwait = await Effect.runPromise(
  189. CodeMode.execute({
  190. tools: { host: { decorate } },
  191. code: `return "a1".replace(/\\d/, (match) => tools.host.decorate(match))`,
  192. }),
  193. )
  194. expect(!missingAwait.ok && missingAwait.error.kind).toBe("InvalidDataValue")
  195. expect(!missingAwait.ok && missingAwait.error.message).toContain("un-awaited Promise")
  196. })
  197. test("replaceAll without the g flag is a catchable error", async () => {
  198. expect(await value(`try { "a".replaceAll(/a/, "b"); return "no" } catch { return "caught" }`)).toBe("caught")
  199. })
  200. test("new RegExp constructs from strings; invalid patterns are catchable", async () => {
  201. expect(await value(`return new RegExp("a+", "i").test("AAA")`)).toBe(true)
  202. expect(await value(`try { new RegExp("("); return "no" } catch { return "caught" }`)).toBe("caught")
  203. expect(await value(`return [/a/ instanceof RegExp, /a/.source]`)).toEqual([true, "a"])
  204. })
  205. test("invalid patterns fail with actionable messages", async () => {
  206. const fromString = await error(`return "abc".match("(")`)
  207. expect(fromString.message).toContain('String.match received the string "("')
  208. expect(fromString.message).toContain("escape them with a backslash")
  209. const fromConstructor = await error(`return new RegExp("(")`)
  210. expect(fromConstructor.message).toContain('new RegExp(...) received "("')
  211. expect(fromConstructor.message).toContain("escape them with a backslash")
  212. const fromFlags = await error(`return new RegExp("a", "xz")`)
  213. expect(fromFlags.message).toContain('invalid flags "xz"')
  214. expect(fromFlags.message).toContain("Valid flags are")
  215. })
  216. test("missing g-flag errors say how to fix the call", async () => {
  217. expect((await error(`return "aa".replaceAll(/a/, "b")`)).message).toContain("write /a/g, or use String.replace")
  218. expect((await error(`return "aa".matchAll(/a/)`)).message).toContain("write /a/g, or use String.match")
  219. })
  220. test("a non-pattern argument names the expected shapes", async () => {
  221. const err = await error(`return "abc".match(42)`)
  222. expect(err.message).toContain("expects a regular expression")
  223. expect(err.message).toContain("not number")
  224. })
  225. test("source and flags properties read through", async () => {
  226. expect(await value(`const r = /ab/gi; return { source: r.source, flags: r.flags, global: r.global }`)).toEqual({
  227. source: "ab",
  228. flags: "gi",
  229. global: true,
  230. })
  231. })
  232. test("regexes serialize to {} at the boundary, like JSON", async () => {
  233. expect(await value(`return /a/`)).toEqual({})
  234. expect(await value(`return JSON.stringify({ r: /a/g })`)).toBe('{"r":{}}')
  235. })
  236. test("template interpolation renders the literal form", async () => {
  237. expect(await value("return `${/ab/g}`")).toBe("/ab/g")
  238. })
  239. })
  240. describe("URL and URI helpers", () => {
  241. test("encodes and decodes complete URIs and URI components", async () => {
  242. expect(
  243. await value(`
  244. return [
  245. encodeURI("https://example.test/a b?q=a/b"),
  246. encodeURIComponent("a b/c?"),
  247. decodeURI("https://example.test/a%20b?q=a/b"),
  248. decodeURIComponent("a%20b%2Fc%3F"),
  249. ["a b", "c/d"].map(encodeURIComponent),
  250. ]
  251. `),
  252. ).toEqual([
  253. "https://example.test/a%20b?q=a/b",
  254. "a%20b%2Fc%3F",
  255. "https://example.test/a b?q=a/b",
  256. "a b/c?",
  257. ["a%20b", "c%2Fd"],
  258. ])
  259. expect(
  260. await value(`try { decodeURIComponent("%zz"); return false } catch (error) { return error instanceof URIError }`),
  261. ).toBe(true)
  262. })
  263. test("resolves and mutates URLs with linked search parameters", async () => {
  264. expect(
  265. await value(`
  266. const url = new URL("../users?id=old#top", "https://user:pass@example.com:8443/api/v1/")
  267. url.pathname = "/items/a b"
  268. url.searchParams.set("id", "a b")
  269. url.searchParams.append("tag", "x/y")
  270. url.hash = "part 1"
  271. return {
  272. href: url.href,
  273. origin: url.origin,
  274. host: url.host,
  275. pathname: url.pathname,
  276. search: url.search,
  277. id: url.searchParams.get("id"),
  278. string: String(url),
  279. json: url.toJSON(),
  280. instances: [
  281. url instanceof URL,
  282. url.searchParams instanceof URLSearchParams,
  283. url.searchParams === url.searchParams,
  284. ],
  285. }
  286. `),
  287. ).toEqual({
  288. href: "https://user:pass@example.com:8443/items/a%20b?id=a+b&tag=x%2Fy#part%201",
  289. origin: "https://example.com:8443",
  290. host: "example.com:8443",
  291. pathname: "/items/a%20b",
  292. search: "?id=a+b&tag=x%2Fy",
  293. id: "a b",
  294. string: "https://user:pass@example.com:8443/items/a%20b?id=a+b&tag=x%2Fy#part%201",
  295. json: "https://user:pass@example.com:8443/items/a%20b?id=a+b&tag=x%2Fy#part%201",
  296. instances: [true, true, true],
  297. })
  298. })
  299. test("URLSearchParams supports records, pairs, mutation, callbacks, and materialization", async () => {
  300. expect(
  301. await value(`
  302. const params = new URLSearchParams([["tag", "b"], ["tag", "a"], ["q", "a b"]])
  303. const seen = []
  304. params.forEach((value, key) => seen.push(key + "=" + value))
  305. params.delete("tag", "b")
  306. params.append("tag", "c")
  307. params.sort()
  308. return {
  309. text: params.toString(),
  310. size: params.size,
  311. tags: params.getAll("tag"),
  312. has: params.has("tag", "c"),
  313. entries: Array.from(params),
  314. object: Object.fromEntries(params),
  315. record: new URLSearchParams({ page: 2, filter: "open" }).toString(),
  316. seen,
  317. }
  318. `),
  319. ).toEqual({
  320. text: "q=a+b&tag=a&tag=c",
  321. size: 3,
  322. tags: ["a", "c"],
  323. has: true,
  324. entries: [
  325. ["q", "a b"],
  326. ["tag", "a"],
  327. ["tag", "c"],
  328. ],
  329. object: { q: "a b", tag: "c" },
  330. record: "page=2&filter=open",
  331. seen: ["tag=b", "tag=a", "q=a b"],
  332. })
  333. })
  334. test("URL parsing failures are catchable and values use native JSON forms", async () => {
  335. expect(
  336. await value(`
  337. const parsed = URL.parse("/users", "https://example.test/api/")
  338. let invalidIsTypeError = false
  339. try { new URL("not relative without a base") } catch (error) { invalidIsTypeError = error instanceof TypeError }
  340. return {
  341. canParse: URL.canParse("/users", "https://example.test/api/"),
  342. cannotParse: URL.canParse("not relative without a base"),
  343. parsed: parsed.href,
  344. invalidIsTypeError,
  345. boundary: [new URL("https://example.test/a"), new URLSearchParams("q=one")],
  346. json: JSON.stringify({ url: new URL("https://example.test/a"), params: new URLSearchParams("q=one") }),
  347. }
  348. `),
  349. ).toEqual({
  350. canParse: true,
  351. cannotParse: false,
  352. parsed: "https://example.test/users",
  353. invalidIsTypeError: true,
  354. boundary: ["https://example.test/a", {}],
  355. json: '{"url":"https://example.test/a","params":{}}',
  356. })
  357. })
  358. test("distinguishes omitted URL arguments from explicit undefined", async () => {
  359. expect(
  360. await value(`
  361. function throwsTypeError(run) {
  362. try { run(); return false } catch (error) { return error instanceof TypeError }
  363. }
  364. const params = new URLSearchParams()
  365. const required = [
  366. () => params.append(),
  367. () => params.delete(),
  368. () => params.get(),
  369. () => params.getAll(),
  370. () => params.has(),
  371. () => params.set(),
  372. () => params.forEach(),
  373. ].map(throwsTypeError)
  374. params.append(undefined, undefined)
  375. return {
  376. construct: throwsTypeError(() => new URL()),
  377. canParse: throwsTypeError(() => URL.canParse()),
  378. parse: throwsTypeError(() => URL.parse()),
  379. explicitUndefined: new URL(undefined, "https://example.test/base/").href,
  380. params: params.toString(),
  381. required,
  382. }
  383. `),
  384. ).toEqual({
  385. construct: true,
  386. canParse: true,
  387. parse: true,
  388. explicitUndefined: "https://example.test/base/undefined",
  389. params: "undefined=undefined",
  390. required: [true, true, true, true, true, true, true],
  391. })
  392. })
  393. })
  394. describe("Map", () => {
  395. test("get/set/has/size with chaining", async () => {
  396. expect(
  397. await value(`
  398. const m = new Map()
  399. m.set("a", 1).set("b", 2)
  400. return { a: m.get("a"), b: m.get("b"), has: m.has("a"), miss: m.get("zz") === undefined, size: m.size }
  401. `),
  402. ).toEqual({ a: 1, b: 2, has: true, miss: true, size: 5 - 3 })
  403. })
  404. test("object keys use identity", async () => {
  405. expect(
  406. await value(`
  407. const key = { id: 1 }
  408. const m = new Map()
  409. m.set(key, "hit")
  410. return [m.get(key), m.get({ id: 1 }) === undefined]
  411. `),
  412. ).toEqual(["hit", true])
  413. })
  414. test("construction from entry pairs and another Map", async () => {
  415. expect(await value(`const m = new Map([["a", 1], ["b", 2]]); return m.get("b")`)).toBe(2)
  416. expect(
  417. await value(
  418. `const m = new Map([["a", 1]]); const n = new Map(m); n.set("b", 2); return [n.get("a"), n.get("b"), m.has("b")]`,
  419. ),
  420. ).toEqual([1, 2, false])
  421. expect((await error(`return new Map("nope")`)).message).toMatch(/\[key, value\] pairs/)
  422. expect((await error(`return new Map(["flat"])`)).message).toMatch(/\[key, value\] pairs/)
  423. })
  424. test("keys/values/entries return arrays", async () => {
  425. expect(
  426. await value(`
  427. const m = new Map([["a", 1], ["b", 2]])
  428. return { keys: m.keys(), values: m.values(), entries: m.entries() }
  429. `),
  430. ).toEqual({
  431. keys: ["a", "b"],
  432. values: [1, 2],
  433. entries: [
  434. ["a", 1],
  435. ["b", 2],
  436. ],
  437. })
  438. })
  439. test("Object.fromEntries(map) and Array.from(map)", async () => {
  440. expect(await value(`return Object.fromEntries(new Map([["a", 1], ["b", 2]]))`)).toEqual({ a: 1, b: 2 })
  441. expect(await value(`return Array.from(new Map([["a", 1]]))`)).toEqual([["a", 1]])
  442. })
  443. test("for...of iterates [key, value] pairs with destructuring", async () => {
  444. expect(
  445. await value(`
  446. const m = new Map([["a", 1], ["b", 2]])
  447. let total = 0
  448. let names = ""
  449. for (const [key, count] of m) { names += key; total += count }
  450. return names + total
  451. `),
  452. ).toBe("ab3")
  453. })
  454. test("spread produces entry pairs", async () => {
  455. expect(await value(`return [...new Map([["a", 1]])]`)).toEqual([["a", 1]])
  456. })
  457. test("forEach passes (value, key)", async () => {
  458. expect(
  459. await value(`
  460. const m = new Map([["a", 1], ["b", 2]])
  461. const seen = []
  462. m.forEach((count, key) => seen.push(key + count))
  463. return seen
  464. `),
  465. ).toEqual(["a1", "b2"])
  466. })
  467. test("delete and clear", async () => {
  468. expect(
  469. await value(`
  470. const m = new Map([["a", 1], ["b", 2]])
  471. const removed = m.delete("a")
  472. const missed = m.delete("zz")
  473. const sizeAfterDelete = m.size
  474. m.clear()
  475. return [removed, missed, sizeAfterDelete, m.size]
  476. `),
  477. ).toEqual([true, false, 1, 0])
  478. })
  479. test("counting idiom: grouped tallies", async () => {
  480. expect(
  481. await value(`
  482. const words = ["a", "b", "a", "c", "a"]
  483. const counts = new Map()
  484. for (const word of words) counts.set(word, (counts.get(word) ?? 0) + 1)
  485. return Object.fromEntries(counts)
  486. `),
  487. ).toEqual({ a: 3, b: 1, c: 1 })
  488. })
  489. test("maps serialize to {} at the boundary, like JSON", async () => {
  490. expect(await value(`return new Map([["a", 1]])`)).toEqual({})
  491. expect(await value(`return JSON.stringify(new Map([["a", 1]]))`)).toBe("{}")
  492. })
  493. test("console.log renders map contents for debugging", async () => {
  494. const result = await run(`console.log(new Map([["a", 1]])); return null`)
  495. expect(result.ok).toBe(true)
  496. expect(result.logs?.[0]).toBe(`Map(1) [["a",1]]`)
  497. })
  498. })
  499. describe("Set", () => {
  500. test("add/has/delete/size with chaining", async () => {
  501. expect(
  502. await value(`
  503. const s = new Set()
  504. s.add(1).add(2).add(1)
  505. const removed = s.delete(2)
  506. return [s.size, s.has(1), s.has(2), removed]
  507. `),
  508. ).toEqual([1, true, false, true])
  509. })
  510. test("dedupe idiom: [...new Set(items)]", async () => {
  511. expect(await value(`return [...new Set([1, 2, 2, 3, 1])]`)).toEqual([1, 2, 3])
  512. })
  513. test("construction from strings and other Sets", async () => {
  514. expect(await value(`return [...new Set("aba")]`)).toEqual(["a", "b"])
  515. expect(await value(`return Array.from(new Set(new Set([1, 2])))`)).toEqual([1, 2])
  516. })
  517. test("SameValueZero: NaN is findable", async () => {
  518. expect(await value(`const s = new Set([NaN]); return s.has(NaN)`)).toBe(true)
  519. })
  520. test("for...of iterates values", async () => {
  521. expect(
  522. await value(`
  523. let total = 0
  524. for (const n of new Set([1, 2, 3])) total += n
  525. return total
  526. `),
  527. ).toBe(6)
  528. })
  529. test("sets serialize to {} at the boundary, like JSON", async () => {
  530. expect(await value(`return { s: new Set([1]) }`)).toEqual({ s: {} })
  531. })
  532. })
  533. describe("stdlib integration", () => {
  534. test("Object.is uses SameValue semantics", async () => {
  535. expect(
  536. await value(`
  537. const object = {}
  538. return [
  539. Object.is(NaN, NaN),
  540. Object.is(0, -0),
  541. Object.is(object, object),
  542. Object.is({}, {}),
  543. ]
  544. `),
  545. ).toEqual([true, false, true, false])
  546. })
  547. test("Object.is rejects opaque runtime references", async () => {
  548. expect((await error(`return Object.is(Math.max, Math.max)`)).kind).toBe("InvalidDataValue")
  549. })
  550. test("Object values and entries accept arrays", async () => {
  551. expect(await value(`return [Object.values(["a", "b"]), Object.entries(["a", "b"])]`)).toEqual([
  552. ["a", "b"],
  553. [
  554. ["0", "a"],
  555. ["1", "b"],
  556. ],
  557. ])
  558. expect(await value(`const match = /a/.exec("ba"); return [Object.values(match), Object.entries(match)]`)).toEqual([
  559. ["a", 1],
  560. [
  561. ["0", "a"],
  562. ["index", 1],
  563. ],
  564. ])
  565. expect(await value(`return Object.keys(Object.values({ match: /a/.exec("ba") })[0])`)).toEqual(["0", "index"])
  566. })
  567. test("Object.fromEntries accepts every supported entry collection", async () => {
  568. expect(
  569. await value(`
  570. return [
  571. Object.fromEntries([["a", 1]]),
  572. Object.fromEntries(new Map([["b", 2]])),
  573. Object.fromEntries(new Set([["c", 3]])),
  574. Object.fromEntries(new URLSearchParams("d=4")),
  575. Object.fromEntries([{ 0: "e", 1: 5 }]),
  576. Object.fromEntries(new Set([[{}, 6], [new Date(0), 7], [null, 8], [undefined, 9]])),
  577. ]
  578. `),
  579. ).toEqual([
  580. { a: 1 },
  581. { b: 2 },
  582. { c: 3 },
  583. { d: "4" },
  584. { e: 5 },
  585. { "[object Object]": 6, "1970-01-01T00:00:00.000Z": 7, null: 8, undefined: 9 },
  586. ])
  587. expect(await value(`try { Object.fromEntries(new Set([Math.max])); return false } catch { return true }`)).toBe(
  588. true,
  589. )
  590. expect(
  591. await value(`try { Object.fromEntries(new Map([["fn", Math.max]])); return false } catch { return true }`),
  592. ).toBe(true)
  593. })
  594. test("deterministic Math methods match the host runtime", async () => {
  595. const result = await value(`
  596. return [
  597. Math.acos(0.5), Math.acosh(2), Math.asin(0.5), Math.asinh(2), Math.atan(1), Math.atan2(1, 2), Math.atanh(0.5),
  598. Math.cos(0.5), Math.cosh(0.5), Math.sin(0.5), Math.sinh(0.5), Math.tan(0.5), Math.tanh(0.5),
  599. Math.log1p(0.5), Math.expm1(0.5), Math.f16round(1.337), Math.fround(1.337), Math.clz32(1), Math.imul(2, 3),
  600. ]
  601. `)
  602. expect(result).toEqual([
  603. Math.acos(0.5),
  604. Math.acosh(2),
  605. Math.asin(0.5),
  606. Math.asinh(2),
  607. Math.atan(1),
  608. Math.atan2(1, 2),
  609. Math.atanh(0.5),
  610. Math.cos(0.5),
  611. Math.cosh(0.5),
  612. Math.sin(0.5),
  613. Math.sinh(0.5),
  614. Math.tan(0.5),
  615. Math.tanh(0.5),
  616. Math.log1p(0.5),
  617. Math.expm1(0.5),
  618. Math.f16round(1.337),
  619. Math.fround(1.337),
  620. Math.clz32(1),
  621. Math.imul(2, 3),
  622. ])
  623. })
  624. test("Object.assign mutates and returns its target", async () => {
  625. expect(
  626. await value(`
  627. const target = { a: 1 }
  628. const result = Object.assign(target, { b: 2 })
  629. return { target, result, same: target === result }
  630. `),
  631. ).toEqual({ target: { a: 1, b: 2 }, result: { a: 1, b: 2 }, same: true })
  632. expect(await value(`try { Object.assign(null, { a: 1 }); return false } catch { return true }`)).toBe(true)
  633. })
  634. test("assignment resolves and reads its left side before evaluating the right side", async () => {
  635. expect(await value(`let x = 1; x += (x = 5); return x`)).toBe(6)
  636. expect(await value(`let i = 0; const values = [9]; values[i++] = i; return [values, i]`)).toEqual([[1], 1])
  637. expect(await value(`let i = 0; const values = [10, 20]; values[i++] += i; return [values, i]`)).toEqual([
  638. [11, 20],
  639. 1,
  640. ])
  641. })
  642. test("typeof reports constructors as functions and never throws", async () => {
  643. expect(await value(`return typeof Map`)).toBe("function")
  644. expect(await value(`return typeof ((x) => x)`)).toBe("function")
  645. expect(await value(`return typeof Math`)).toBe("object")
  646. expect(await value(`return typeof tools`)).toBe("object")
  647. })
  648. test("negation works on any value", async () => {
  649. expect(await value(`return !new Map()`)).toBe(false)
  650. expect(await value(`const fn = () => 1; return !fn`)).toBe(false)
  651. })
  652. test("object spread of CodeMode values is a no-op, like JS", async () => {
  653. expect(await value(`return { ...new Map([["a", 1]]), kept: true }`)).toEqual({ kept: true })
  654. })
  655. test("dates inside Map values survive in-CodeMode reads", async () => {
  656. expect(
  657. await value(`
  658. const m = new Map([["start", new Date(1000)]])
  659. return m.get("start").getTime()
  660. `),
  661. ).toBe(1000)
  662. })
  663. test("instanceof recognizes the stdlib value types", async () => {
  664. expect(
  665. await value(
  666. `return [new Date(0) instanceof Date, /a/ instanceof RegExp, new Map() instanceof Map, new Set() instanceof Set]`,
  667. ),
  668. ).toEqual([true, true, true, true])
  669. expect(
  670. await value(`return [[1] instanceof Array, [1] instanceof Object, ({}) instanceof Object, 5 instanceof Object]`),
  671. ).toEqual([true, true, true, false])
  672. expect(await value(`return [new Map() instanceof Set, "s" instanceof Date]`)).toEqual([false, false])
  673. expect(
  674. await value(`const p = Promise.resolve(1); const isPromise = p instanceof Promise; await p; return isPromise`),
  675. ).toBe(true)
  676. })
  677. test("realistic pipeline: parse, extract with regex, dedupe, count by day", async () => {
  678. expect(
  679. await value(`
  680. const raw = '[{"at":"2024-01-01T05:00:00Z","tag":"a b"},{"at":"2024-01-01T09:00:00Z","tag":"b c"},{"at":"2024-01-02T01:00:00Z","tag":"a"}]'
  681. const rows = JSON.parse(raw)
  682. const tags = new Set()
  683. const byDay = new Map()
  684. for (const row of rows) {
  685. for (const m of row.tag.matchAll(/[a-z]+/g)) tags.add(m[0])
  686. const day = new Date(row.at).toISOString().slice(0, 10)
  687. byDay.set(day, (byDay.get(day) ?? 0) + 1)
  688. }
  689. return { tags: [...tags].sort((a, b) => (a < b ? -1 : 1)), byDay: Object.fromEntries(byDay) }
  690. `),
  691. ).toEqual({ tags: ["a", "b", "c"], byDay: { "2024-01-01": 2, "2024-01-02": 1 } })
  692. })
  693. })
  694. describe("CodeMode values at intra-CodeMode checkpoints", () => {
  695. test("Object.values/entries keep Dates usable", async () => {
  696. expect(await value(`return Object.values({ d: new Date(0) })[0].getTime()`)).toBe(0)
  697. expect(await value(`const [key, d] = Object.entries({ d: new Date(0) })[0]; return key + ":" + d.getTime()`)).toBe(
  698. "d:0",
  699. )
  700. })
  701. test("Object.values/entries preserve nested object identity", async () => {
  702. expect(
  703. await value(`
  704. const child = { selected: false }
  705. const rows = { a: child }
  706. Object.values(rows)[0].selected = true
  707. return child.selected
  708. `),
  709. ).toBe(true)
  710. expect(
  711. await value(`
  712. const child = { selected: false }
  713. const rows = { a: child }
  714. Object.entries(rows)[0][1].selected = true
  715. return child.selected
  716. `),
  717. ).toBe(true)
  718. })
  719. test("Object enumeration preserves promises and callable references", async () => {
  720. expect(
  721. await value(`
  722. const pending = Promise.resolve(1)
  723. const source = { pending }
  724. return [Object.keys(source), Object.hasOwn(source, "pending"), await Object.values(source)[0], await Object.entries(source)[0][1]]
  725. `),
  726. ).toEqual([["pending"], true, 1, 1])
  727. expect(await value(`return Object.values({ max: Math.max })[0](1, 2)`)).toBe(2)
  728. })
  729. test("Object enumeration rejects invalid receivers and gives promises an await hint", async () => {
  730. const diagnostic = await error(`return Object.keys(Promise.resolve({ a: 1 }))`)
  731. expect(diagnostic.kind).toBe("InvalidDataValue")
  732. expect(diagnostic.message).toContain("await")
  733. expect((await error(`return Object.keys(Math)`)).kind).toBe("InvalidDataValue")
  734. })
  735. test("Object.assign keeps Maps usable", async () => {
  736. expect(await value(`const merged = Object.assign({}, { m: new Map([["a", 1]]) }); return merged.m.get("a")`)).toBe(
  737. 1,
  738. )
  739. })
  740. test("object and array spread keep CodeMode values usable", async () => {
  741. expect(
  742. await value(`
  743. const src = { m: new Map([["a", 1]]) }
  744. const copy = { ...src }
  745. copy.m.set("b", 2)
  746. return [copy.m.get("a"), src.m.get("b")]
  747. `),
  748. ).toEqual([1, 2])
  749. expect(await value(`const list = [new Date(1000)]; const copy = [...list]; return copy[0].getTime()`)).toBe(1000)
  750. })
  751. test("Array.from over arrays keeps nested CodeMode values usable", async () => {
  752. expect(await value(`return Array.from([new Date(5)])[0].getTime()`)).toBe(5)
  753. })
  754. test("Array.from and Array.of preserve nested object identity", async () => {
  755. expect(
  756. await value(`
  757. const child = { selected: false }
  758. Array.from([child])[0].selected = true
  759. return child.selected
  760. `),
  761. ).toBe(true)
  762. expect(
  763. await value(`
  764. const child = { selected: false }
  765. Array.of(child)[0].selected = true
  766. return child.selected
  767. `),
  768. ).toBe(true)
  769. })
  770. test("Array.from and Array.of preserve promises and callable references", async () => {
  771. expect(
  772. await value(`
  773. const pending = Promise.resolve(1)
  774. return [await Array.from([pending])[0], await Array.of(pending)[0]]
  775. `),
  776. ).toEqual([1, 1])
  777. expect(await value(`return [Array.from([Math.max])[0](1, 2), Array.of(Math.max)[0](3, 4)]`)).toEqual([2, 4])
  778. })
  779. test("Array.from preserves identity across supported collection shapes", async () => {
  780. expect(
  781. await value(`
  782. const child = { selected: false }
  783. const fromArrayLike = Array.from({ 0: child, length: 1 })
  784. const fromMap = Array.from(new Map([["child", child]]))
  785. const fromSet = Array.from(new Set([child]))
  786. fromArrayLike[0].selected = true
  787. return [fromMap[0][1] === child, fromSet[0] === child, child.selected]
  788. `),
  789. ).toEqual([true, true, true])
  790. })
  791. test("Array.from rejects invalid receivers and gives promises an await hint", async () => {
  792. const diagnostic = await error(`return Array.from(Promise.resolve([1]))`)
  793. expect(diagnostic.kind).toBe("InvalidDataValue")
  794. expect(diagnostic.message).toContain("await")
  795. expect((await error(`return Array.from(() => 1)`)).kind).toBe("InvalidDataValue")
  796. })
  797. test("regexes stay callable through Object.values", async () => {
  798. expect(await value(`return Object.values({ r: /ab+/ })[0].test("abb")`)).toBe(true)
  799. })
  800. test("Object.* helpers see CodeMode values as empty objects, never internals", async () => {
  801. expect(await value(`return Object.keys(new Map([["a", 1]]))`)).toEqual([])
  802. expect(await value(`return Object.values(new Date(0))`)).toEqual([])
  803. expect(await value(`return Object.entries(new Set([1]))`)).toEqual([])
  804. expect(await value(`return Object.assign({}, new Map([["a", 1]]))`)).toEqual({})
  805. expect(await value(`return Object.hasOwn(new Date(0), "time")`)).toBe(false)
  806. })
  807. test("the host boundary still serializes JSON forms: results, JSON.stringify, and tool arguments", async () => {
  808. expect(await value(`return { d: new Date(0), m: new Map([["a", 1]]) }`)).toEqual({
  809. d: "1970-01-01T00:00:00.000Z",
  810. m: {},
  811. })
  812. expect(await value(`return JSON.stringify({ d: new Date(0) })`)).toBe('{"d":"1970-01-01T00:00:00.000Z"}')
  813. const observed: Array<unknown> = []
  814. const capture = Tool.make({
  815. description: "Capture the exact input the host receives",
  816. input: { type: "object" },
  817. run: (input) =>
  818. Effect.sync(() => {
  819. observed.push(input)
  820. return "ok"
  821. }),
  822. })
  823. const result = await Effect.runPromise(
  824. CodeMode.execute({
  825. tools: { host: { capture } },
  826. code: `return await tools.host.capture({ when: new Date(0), tags: new Map([["a", 1]]) })`,
  827. }),
  828. )
  829. expect(result.ok).toBe(true)
  830. expect(observed).toStrictEqual([{ when: "1970-01-01T00:00:00.000Z", tags: {} }])
  831. })
  832. })