@ancha-labs/cli 0.4.16 → 0.4.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/worker.mjs CHANGED
@@ -24332,10 +24332,10 @@ var init_better_stack = __esm({
24332
24332
  open4.add(entry2.source);
24333
24333
  }
24334
24334
  });
24335
- seed43.onCall.forEach((calendar3, i) => calendar3.users.forEach((user8, j) => {
24335
+ seed43.onCall.forEach((calendar4, i) => calendar4.users.forEach((user8, j) => {
24336
24336
  if (!people3.has(user8)) issue6(["onCall", i, "users", j], `${user8} is not a user`);
24337
24337
  }));
24338
- if (seed43.onCall.filter((calendar3) => calendar3.default).length > 1) issue6(["onCall"], "only one default calendar");
24338
+ if (seed43.onCall.filter((calendar4) => calendar4.default).length > 1) issue6(["onCall"], "only one default calendar");
24339
24339
  seed43.statusPages.forEach((page18, i) => {
24340
24340
  const names5 = new Set(page18.resources.map((resource2) => resource2.publicName));
24341
24341
  page18.resources.forEach((resource2, j) => {
@@ -31158,10 +31158,14 @@ var init_netsuite = __esm({
31158
31158
  id: id8.optional(),
31159
31159
  externalId: text11.optional(),
31160
31160
  fields: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
31161
- apply: external_exports.array(application).optional()
31161
+ apply: external_exports.array(application).optional(),
31162
+ credit: external_exports.array(application).optional()
31162
31163
  }).refine((check3) => check3.id === void 0 !== (check3.externalId === void 0), { message: "name the record with id or with externalId, not both", path: ["id"] });
31163
- NetsuiteUnchangedCheckSchema = external_exports.strictObject({ types: external_exports.array(external_exports.enum(netsuiteRecordTypes)).min(1) });
31164
- NetsuiteCountCheckSchema = external_exports.strictObject({ type: external_exports.enum(netsuiteRecordTypes), count: external_exports.number().int().min(0) });
31164
+ NetsuiteUnchangedCheckSchema = external_exports.strictObject({
31165
+ types: external_exports.array(external_exports.enum(netsuiteRecordTypes)).min(1),
31166
+ except: external_exports.array(external_exports.strictObject({ type: external_exports.enum(netsuiteRecordTypes), id: id8.optional(), externalId: text11.optional() }).refine((check3) => check3.id === void 0 !== (check3.externalId === void 0), { message: "name the record with id or with externalId, not both" })).optional()
31167
+ });
31168
+ NetsuiteCountCheckSchema = external_exports.strictObject({ type: external_exports.enum(netsuiteRecordTypes), count: external_exports.number().int().min(0), includeSettlement: external_exports.boolean().optional() });
31165
31169
  }
31166
31170
  });
31167
31171
 
@@ -40642,11 +40646,21 @@ var init_file = __esm({
40642
40646
  }
40643
40647
  });
40644
40648
 
40649
+ // packages/core/src/datasets/netsuite-pe/writes.ts
40650
+ var init_writes = __esm({
40651
+ "packages/core/src/datasets/netsuite-pe/writes.ts"() {
40652
+ "use strict";
40653
+ init_netsuite();
40654
+ init_evals();
40655
+ }
40656
+ });
40657
+
40645
40658
  // packages/core/src/datasets/netsuite-pe/evals.ts
40646
40659
  var init_evals = __esm({
40647
40660
  "packages/core/src/datasets/netsuite-pe/evals.ts"() {
40648
40661
  "use strict";
40649
40662
  init_netsuite();
40663
+ init_writes();
40650
40664
  init_netsuite_money();
40651
40665
  }
40652
40666
  });
@@ -103445,7 +103459,7 @@ function collectionWrite(kind, c, body6) {
103445
103459
  const result = create(c.env.ctx, kind, accountId(c), body6);
103446
103460
  return new Response(null, { status: 201, headers: { "x-restli-id": String(result.id), "x-restli-protocol-version": "2.0.0" } });
103447
103461
  }
103448
- function calendar(raw3) {
103462
+ function calendar2(raw3) {
103449
103463
  const match3 = /^\((?:year:(\d{4}),month:(\d{1,2}),day:(\d{1,2})|day:(\d{1,2}),month:(\d{1,2}),year:(\d{4}))\)$/.exec(raw3);
103450
103464
  if (!match3) invalid8("Date must be (year:YYYY,month:M,day:D) or (day:D,month:M,year:YYYY)");
103451
103465
  const y = match3[1] ?? match3[6], m = match3[2] ?? match3[5], d = match3[3] ?? match3[4], date10 = `${y}-${m.padStart(2, "0")}-${d.padStart(2, "0")}`;
@@ -103527,7 +103541,7 @@ var init_routes2 = __esm({
103527
103541
  if (!["DAILY", "ALL"].includes(q.get("timeGranularity") ?? "")) gap2(`timeGranularity ${q.get("timeGranularity")}`);
103528
103542
  const range2 = /^\(start:(\([^()]+\))(?:,end:(\([^()]+\)))?\)$/.exec(q.get("dateRange") ?? "");
103529
103543
  if (!range2) invalid8("dateRange requires start and optional end tuples");
103530
- const start = calendar(range2[1]), end = range2[2] ? calendar(range2[2]) : c.env.ctx.clock.now().toISOString().slice(0, 10);
103544
+ const start = calendar2(range2[1]), end = range2[2] ? calendar2(range2[2]) : c.env.ctx.clock.now().toISOString().slice(0, 10);
103531
103545
  if (end < start) invalid8("dateRange.end precedes start");
103532
103546
  const selectedFields2 = q.get("fields")?.split(",") ?? ["impressions", "clicks"];
103533
103547
  const allowed2 = ["pivotValues", "dateRange", "impressions", "clicks", "oneClickLeads", "costInLocalCurrency"];
@@ -134362,9 +134376,9 @@ function seed21(ctx) {
134362
134376
  entry2.resolved?.by ?? null
134363
134377
  );
134364
134378
  }
134365
- for (const calendar3 of input4.onCall) {
134366
- const users5 = calendar3.users.map((email11) => db3.prepare("SELECT id FROM bs_users WHERE email = ?").get(email11).id);
134367
- db3.prepare("INSERT INTO bs_calendars (id, name, is_default, users) VALUES (?, ?, ?, ?)").run(nextId3(ctx, "calendar"), calendar3.name, calendar3.default ? 1 : 0, JSON.stringify(users5));
134379
+ for (const calendar4 of input4.onCall) {
134380
+ const users5 = calendar4.users.map((email11) => db3.prepare("SELECT id FROM bs_users WHERE email = ?").get(email11).id);
134381
+ db3.prepare("INSERT INTO bs_calendars (id, name, is_default, users) VALUES (?, ?, ?, ?)").run(nextId3(ctx, "calendar"), calendar4.name, calendar4.default ? 1 : 0, JSON.stringify(users5));
134368
134382
  }
134369
134383
  for (const page18 of input4.statusPages) {
134370
134384
  const id14 = nextId3(ctx, "page");
@@ -134420,9 +134434,9 @@ function dumpState20(ctx) {
134420
134434
  resolvedBy: row2.resolved_by,
134421
134435
  ...row2.summary && { summary: row2.summary }
134422
134436
  })),
134423
- onCall: db3.prepare("SELECT * FROM bs_calendars ORDER BY rowid").all().map((calendar3) => ({
134424
- name: calendar3.name,
134425
- users: JSON.parse(calendar3.users).map((id14) => db3.prepare("SELECT email FROM bs_users WHERE id = ?").get(id14)?.email ?? id14)
134437
+ onCall: db3.prepare("SELECT * FROM bs_calendars ORDER BY rowid").all().map((calendar4) => ({
134438
+ name: calendar4.name,
134439
+ users: JSON.parse(calendar4.users).map((id14) => db3.prepare("SELECT email FROM bs_users WHERE id = ?").get(id14)?.email ?? id14)
134426
134440
  })),
134427
134441
  statusPages: db3.prepare("SELECT * FROM bs_pages ORDER BY rowid").all().map((page18) => ({
134428
134442
  id: page18.id,
@@ -148422,7 +148436,7 @@ function feeFor(series2, count4, price3, taker) {
148422
148436
  const exact = rate * series2.fee_multiplier * (count4 / 100) * (price3 / ONE) * (1 - price3 / ONE);
148423
148437
  return Math.ceil(exact * 100 - 1e-9) * 1e4;
148424
148438
  }
148425
- function ledger(ctx, now11) {
148439
+ function ledger2(ctx, now11) {
148426
148440
  const db3 = ctx.store.db, positions2 = /* @__PURE__ */ new Map();
148427
148441
  let cash = db3.prepare("SELECT COALESCE(SUM(amount), 0) AS total FROM kx_deposits WHERE at_ms <= ?").get(now11).total;
148428
148442
  for (const fill of db3.prepare("SELECT * FROM kx_fills WHERE created_ms <= ? ORDER BY created_ms, rowid").all(now11)) {
@@ -148460,7 +148474,7 @@ function ledger(ctx, now11) {
148460
148474
  return { cash, positions: positions2 };
148461
148475
  }
148462
148476
  function balances(ctx, now11) {
148463
- const { cash, positions: positions2 } = ledger(ctx, now11);
148477
+ const { cash, positions: positions2 } = ledger2(ctx, now11);
148464
148478
  const held = restingOrders(ctx, now11).reduce((total2, order5) => total2 + collateral(order5), 0);
148465
148479
  let value4 = 0;
148466
148480
  for (const entry2 of positions2.values()) if (entry2.position) value4 += Math.abs(entry2.position) * (entry2.position > 0 ? getMarket(ctx, entry2.ticker).last_price : ONE - getMarket(ctx, entry2.ticker).last_price);
@@ -148505,7 +148519,7 @@ function seed32(ctx) {
148505
148519
  });
148506
148520
  });
148507
148521
  input4.orders.forEach((entry2, i) => {
148508
- const id14 = seededUuid(`order:${i}`), created3 = at3(entry2.created), series2 = seriesOfMarket(ctx, getMarket(ctx, entry2.market)), positionBefore = ledger(ctx, created3).positions.get(entry2.market)?.position ?? 0;
148522
+ const id14 = seededUuid(`order:${i}`), created3 = at3(entry2.created), series2 = seriesOfMarket(ctx, getMarket(ctx, entry2.market)), positionBefore = ledger2(ctx, created3).positions.get(entry2.market)?.position ?? 0;
148509
148523
  const legacy2 = legacySide(entry2.side, positionBefore);
148510
148524
  db3.prepare(`INSERT INTO kx_orders (id, client_order_id, ticker, book_side, side, action, outcome_side, price, initial, filled, time_in_force, post_only, stp, cancel_on_pause, expiration_ms, created_ms, updated_ms, canceled_ms,
148511
148525
  taker_cost, maker_cost, taker_fees, maker_fees) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, 0, 'taker_at_cross', 0, NULL, ?, ?, ?, 0, 0, 0, 0)`).run(id14, entry2.clientOrderId ?? null, entry2.market, entry2.side, legacy2.side, legacy2.action, legacy2.outcome, price3(entry2.price), count4(entry2.count), entry2.timeInForce, created3, created3, entry2.canceled === void 0 ? null : at3(entry2.canceled));
@@ -148998,7 +149012,7 @@ function positions(call2) {
148998
149012
  choice2(settlement, "settlement_status", ["all", "settled", "unsettled"]);
148999
149013
  for (const name5 of counts) choice2(name5, "count_filter", ["position", "total_traded"]);
149000
149014
  const ticker2 = params10.get("ticker"), eventTicker = params10.get("event_ticker");
149001
- const entries3 = [...ledger(ctx, now11).positions.values()].filter((entry2) => {
149015
+ const entries3 = [...ledger2(ctx, now11).positions.values()].filter((entry2) => {
149002
149016
  const market2 = getMarket(ctx, entry2.ticker);
149003
149017
  return (settlement === "all" || settlement === "settled" === (entry2.settlement !== void 0)) && (!ticker2 || entry2.ticker === ticker2) && (!eventTicker || market2.event === eventTicker) && (!counts.length || counts.some((name5) => name5 === "position" ? entry2.position !== 0 : entry2.traded !== 0));
149004
149018
  });
@@ -149040,7 +149054,7 @@ function settlements(call2) {
149040
149054
  const ctx = call2.ctx, now11 = ctx.clock.nowMs(), params10 = query9(call2, ["limit", "cursor", "ticker", "event_ticker", "min_ts", "max_ts", "subaccount"]), ticker2 = params10.get("ticker"), eventTicker = params10.get("event_ticker");
149041
149055
  primary2(params10.get("subaccount"));
149042
149056
  const within2 = timeRange2(params10, "min_ts", "max_ts");
149043
- const rows7 = [...ledger(ctx, now11).positions.values()].filter((entry2) => entry2.settlement && (!ticker2 || entry2.ticker === ticker2) && (!eventTicker || getMarket(ctx, entry2.ticker).event === eventTicker) && within2(entry2.settlement.at)).sort((a, b) => b.settlement.at - a.settlement.at);
149057
+ const rows7 = [...ledger2(ctx, now11).positions.values()].filter((entry2) => entry2.settlement && (!ticker2 || entry2.ticker === ticker2) && (!eventTicker || getMarket(ctx, entry2.ticker).event === eventTicker) && within2(entry2.settlement.at)).sort((a, b) => b.settlement.at - a.settlement.at);
149044
149058
  const result = page14(call2, rows7, 200, 100);
149045
149059
  return json22({
149046
149060
  settlements: result.items.map((entry2) => ({
@@ -164013,7 +164027,7 @@ function bindValue(value4) {
164013
164027
  if (typeof value4 === "string") return value4 === "" ? null : value4;
164014
164028
  invalid24("Each params value must be a string or a number.");
164015
164029
  }
164016
- function calendar2(y, m, d) {
164030
+ function calendar3(y, m, d) {
164017
164031
  const date10 = /* @__PURE__ */ new Date(0);
164018
164032
  date10.setUTCFullYear(y, m - 1, d);
164019
164033
  date10.setUTCHours(0, 0, 0, 0);
@@ -164023,7 +164037,7 @@ function calendar2(y, m, d) {
164023
164037
  function isoDate(text24) {
164024
164038
  const match3 = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text24);
164025
164039
  if (!match3) invalid24("Expected a YYYY-MM-DD world date.");
164026
- calendar2(+match3[1], +match3[2], +match3[3]);
164040
+ calendar3(+match3[1], +match3[2], +match3[3]);
164027
164041
  return text24;
164028
164042
  }
164029
164043
  function dateModel(model) {
@@ -164062,7 +164076,7 @@ function parseDate2(value4, model) {
164062
164076
  const values2 = new Map(tokens3.map((t, i) => [t, match3[i + 1]]));
164063
164077
  if (!values2.has("YYYY") || !values2.has("DD") || !["MM", "MON", "MONTH"].some((t) => values2.has(t))) invalid24("TO_DATE requires year, month and day.", true);
164064
164078
  const month = values2.has("MM") ? Number(values2.get("MM")) : MONTHS2.findIndex((m) => values2.has("MON") ? m.slice(0, 3).toLowerCase() === values2.get("MON").toLowerCase() : m.toLowerCase() === values2.get("MONTH").toLowerCase()) + 1;
164065
- const date10 = calendar2(Number(values2.get("YYYY")), month, Number(values2.get("DD")));
164079
+ const date10 = calendar3(Number(values2.get("YYYY")), month, Number(values2.get("DD")));
164066
164080
  let hour2 = Number(values2.get("HH24") ?? values2.get("HH12") ?? values2.get("HH") ?? 0);
164067
164081
  const minute2 = Number(values2.get("MI") ?? 0), second = Number(values2.get("SS") ?? 0);
164068
164082
  if (values2.has("HH12") || values2.has("HH")) {
@@ -169067,15 +169081,29 @@ function record8(ctx, args) {
169067
169081
  }
169068
169082
  const applied = composite2 ? [...byLine.values()].sort((a, b) => a.doc - b.doc || a.line - b.line) : applications(ctx, id14).map((a) => ({ doc: a.doc, amount: a.amount })).sort((a, b) => a.doc - b.doc);
169069
169083
  const wanted = args.apply?.map((a) => composite2 ? { ...a, line: a.line ?? 0 } : { ...a }).sort((a, b) => a.doc - b.doc || (a.line ?? 0) - (b.line ?? 0));
169070
- return checkOutcome(matches8(actual, args.fields ?? {}) && (wanted === void 0 || isDeepStrictEqual(applied, wanted)), expected, JSON.stringify({ record: actual, apply: applied }));
169084
+ const creditLines = args.credit?.some((a) => a.line !== void 0);
169085
+ const credits = /* @__PURE__ */ new Map();
169086
+ for (const a of edges(ctx, id14).filter((a2) => a2.source !== id14)) {
169087
+ const key4 = creditLines ? `${a.source}:${a.sourceline}` : String(a.source);
169088
+ const item2 = credits.get(key4) ?? { doc: a.source, ...creditLines && { line: a.sourceline }, amount: 0 };
169089
+ item2.amount = Math.round((item2.amount + a.amount) * 100) / 100;
169090
+ credits.set(key4, item2);
169091
+ }
169092
+ const sort = (a, b) => a.doc - b.doc || (a.line ?? 0) - (b.line ?? 0);
169093
+ const credited = [...credits.values()].sort(sort);
169094
+ const wantedCredits = args.credit?.map((a) => creditLines ? { ...a, line: a.line ?? 0 } : { ...a }).sort(sort);
169095
+ const creditExpected = args.credit === void 0 ? "" : ` and credits ${JSON.stringify(args.credit)}`;
169096
+ return checkOutcome(matches8(actual, args.fields ?? {}) && (wanted === void 0 || isDeepStrictEqual(applied, wanted)) && (wantedCredits === void 0 || isDeepStrictEqual(credited, wantedCredits)), expected + creditExpected, JSON.stringify({ record: actual, apply: applied, credit: credited }));
169071
169097
  }
169072
169098
  function unchanged(ctx, args) {
169073
- const changes = sql(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype));
169099
+ const allowed2 = (args.except ?? []).map((r2) => ({ type: r2.type, id: r2.id ?? byExternalId(ctx, r2.type, r2.externalId) }));
169100
+ const changes = sql(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype) && !allowed2.some((r2) => r2.type === row2.recordtype && r2.id === row2.id));
169074
169101
  const types = args.types.length >= netsuiteRecordTypes.length && netsuiteRecordTypes.every((type) => args.types.includes(type)) ? "NetSuite records" : args.types.length > 4 ? `${args.types.slice(0, 3).join(", ")} and ${args.types.length - 3} more record types` : args.types.join(", ");
169075
- return checkOutcome(changes.length === 0, `no writes to ${types}`, changes.length ? JSON.stringify(changes) : "no committed writes");
169102
+ const except = args.except?.length ? ` except ${args.except.map((r2) => `${r2.type} ${r2.id ?? `eid:${r2.externalId}`}`).join(", ")}` : "";
169103
+ return checkOutcome(changes.length === 0, `no writes to ${types}${except}`, changes.length ? JSON.stringify(changes) : except ? "no other committed writes" : "no committed writes");
169076
169104
  }
169077
169105
  function count3(ctx, args) {
169078
- const actual = recordIds(ctx, args.type).length;
169106
+ const actual = args.includeSettlement && isTx(args.type) ? sql(ctx).prepare("SELECT COUNT(*) AS count FROM ns_transactions WHERE recordtype = ?").get(args.type).count : recordIds(ctx, args.type).length;
169079
169107
  return checkOutcome(actual === args.count, `${args.count} ${args.type} records`, `${actual} records`);
169080
169108
  }
169081
169109
  var init_checks13 = __esm({
@@ -95327,10 +95327,10 @@ var BetterStackSeedSchema = external_exports.strictObject({
95327
95327
  open2.add(entry2.source);
95328
95328
  }
95329
95329
  });
95330
- seed43.onCall.forEach((calendar3, i) => calendar3.users.forEach((user8, j) => {
95330
+ seed43.onCall.forEach((calendar4, i) => calendar4.users.forEach((user8, j) => {
95331
95331
  if (!people3.has(user8)) issue6(["onCall", i, "users", j], `${user8} is not a user`);
95332
95332
  }));
95333
- if (seed43.onCall.filter((calendar3) => calendar3.default).length > 1) issue6(["onCall"], "only one default calendar");
95333
+ if (seed43.onCall.filter((calendar4) => calendar4.default).length > 1) issue6(["onCall"], "only one default calendar");
95334
95334
  seed43.statusPages.forEach((page18, i) => {
95335
95335
  const names5 = new Set(page18.resources.map((resource2) => resource2.publicName));
95336
95336
  page18.resources.forEach((resource2, j) => {
@@ -102019,10 +102019,14 @@ var NetsuiteRecordCheckSchema = external_exports.strictObject({
102019
102019
  id: id8.optional(),
102020
102020
  externalId: text11.optional(),
102021
102021
  fields: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
102022
- apply: external_exports.array(application).optional()
102022
+ apply: external_exports.array(application).optional(),
102023
+ credit: external_exports.array(application).optional()
102023
102024
  }).refine((check3) => check3.id === void 0 !== (check3.externalId === void 0), { message: "name the record with id or with externalId, not both", path: ["id"] });
102024
- var NetsuiteUnchangedCheckSchema = external_exports.strictObject({ types: external_exports.array(external_exports.enum(netsuiteRecordTypes)).min(1) });
102025
- var NetsuiteCountCheckSchema = external_exports.strictObject({ type: external_exports.enum(netsuiteRecordTypes), count: external_exports.number().int().min(0) });
102025
+ var NetsuiteUnchangedCheckSchema = external_exports.strictObject({
102026
+ types: external_exports.array(external_exports.enum(netsuiteRecordTypes)).min(1),
102027
+ except: external_exports.array(external_exports.strictObject({ type: external_exports.enum(netsuiteRecordTypes), id: id8.optional(), externalId: text11.optional() }).refine((check3) => check3.id === void 0 !== (check3.externalId === void 0), { message: "name the record with id or with externalId, not both" })).optional()
102028
+ });
102029
+ var NetsuiteCountCheckSchema = external_exports.strictObject({ type: external_exports.enum(netsuiteRecordTypes), count: external_exports.number().int().min(0), includeSettlement: external_exports.boolean().optional() });
102026
102030
 
102027
102031
  // packages/core/src/scene/schema.ts
102028
102032
  var SUPPORTED_TWINS = ["slack", "github", "datadog", "pagerduty", "linkedin-ads", "salesforce", "gong", "hubspot", "ga4", "google-ads", "chatgpt-ads", "open-meteo", "google-drive", "gmail", "amazon-s3", "linear", "okta", "stripe", "clerk", "better-stack", "notion", "attio", "dropbox", "resend", "microsoft-word", "outlook", "shopify", "lob", "paypal", "jira", "kalshi", "intercom", "zendesk", "google-calendar", "twilio", "asana", "discord", "sentry", "airtable", "netsuite", "carrier-portal"];
@@ -123655,7 +123659,7 @@ var catalogRoutes3 = [
123655
123659
  return json8({ elements: entities.filter((e) => e.facet === q.get("facet")).map((e) => ({ urn: e.urn, facetUrn: e.facet, name: e.name })) });
123656
123660
  } }
123657
123661
  ];
123658
- function calendar(raw3) {
123662
+ function calendar2(raw3) {
123659
123663
  const match3 = /^\((?:year:(\d{4}),month:(\d{1,2}),day:(\d{1,2})|day:(\d{1,2}),month:(\d{1,2}),year:(\d{4}))\)$/.exec(raw3);
123660
123664
  if (!match3) invalid8("Date must be (year:YYYY,month:M,day:D) or (day:D,month:M,year:YYYY)");
123661
123665
  const y = match3[1] ?? match3[6], m = match3[2] ?? match3[5], d = match3[3] ?? match3[4], date10 = `${y}-${m.padStart(2, "0")}-${d.padStart(2, "0")}`;
@@ -123677,7 +123681,7 @@ var analyticsRoutes = [{ method: "GET", path: "/rest/adAnalytics", notes: "analy
123677
123681
  if (!["DAILY", "ALL"].includes(q.get("timeGranularity") ?? "")) gap2(`timeGranularity ${q.get("timeGranularity")}`);
123678
123682
  const range2 = /^\(start:(\([^()]+\))(?:,end:(\([^()]+\)))?\)$/.exec(q.get("dateRange") ?? "");
123679
123683
  if (!range2) invalid8("dateRange requires start and optional end tuples");
123680
- const start = calendar(range2[1]), end = range2[2] ? calendar(range2[2]) : c.env.ctx.clock.now().toISOString().slice(0, 10);
123684
+ const start = calendar2(range2[1]), end = range2[2] ? calendar2(range2[2]) : c.env.ctx.clock.now().toISOString().slice(0, 10);
123681
123685
  if (end < start) invalid8("dateRange.end precedes start");
123682
123686
  const selectedFields2 = q.get("fields")?.split(",") ?? ["impressions", "clicks"];
123683
123687
  const allowed2 = ["pivotValues", "dateRange", "impressions", "clicks", "oneClickLeads", "costInLocalCurrency"];
@@ -133855,9 +133859,9 @@ function seed21(ctx) {
133855
133859
  entry2.resolved?.by ?? null
133856
133860
  );
133857
133861
  }
133858
- for (const calendar3 of input4.onCall) {
133859
- const users5 = calendar3.users.map((email11) => db3.prepare("SELECT id FROM bs_users WHERE email = ?").get(email11).id);
133860
- db3.prepare("INSERT INTO bs_calendars (id, name, is_default, users) VALUES (?, ?, ?, ?)").run(nextId3(ctx, "calendar"), calendar3.name, calendar3.default ? 1 : 0, JSON.stringify(users5));
133862
+ for (const calendar4 of input4.onCall) {
133863
+ const users5 = calendar4.users.map((email11) => db3.prepare("SELECT id FROM bs_users WHERE email = ?").get(email11).id);
133864
+ db3.prepare("INSERT INTO bs_calendars (id, name, is_default, users) VALUES (?, ?, ?, ?)").run(nextId3(ctx, "calendar"), calendar4.name, calendar4.default ? 1 : 0, JSON.stringify(users5));
133861
133865
  }
133862
133866
  for (const page18 of input4.statusPages) {
133863
133867
  const id14 = nextId3(ctx, "page");
@@ -133913,9 +133917,9 @@ function dumpState20(ctx) {
133913
133917
  resolvedBy: row2.resolved_by,
133914
133918
  ...row2.summary && { summary: row2.summary }
133915
133919
  })),
133916
- onCall: db3.prepare("SELECT * FROM bs_calendars ORDER BY rowid").all().map((calendar3) => ({
133917
- name: calendar3.name,
133918
- users: JSON.parse(calendar3.users).map((id14) => db3.prepare("SELECT email FROM bs_users WHERE id = ?").get(id14)?.email ?? id14)
133920
+ onCall: db3.prepare("SELECT * FROM bs_calendars ORDER BY rowid").all().map((calendar4) => ({
133921
+ name: calendar4.name,
133922
+ users: JSON.parse(calendar4.users).map((id14) => db3.prepare("SELECT email FROM bs_users WHERE id = ?").get(id14)?.email ?? id14)
133919
133923
  })),
133920
133924
  statusPages: db3.prepare("SELECT * FROM bs_pages ORDER BY rowid").all().map((page18) => ({
133921
133925
  id: page18.id,
@@ -147336,7 +147340,7 @@ function feeFor(series2, count4, price3, taker) {
147336
147340
  const exact = rate * series2.fee_multiplier * (count4 / 100) * (price3 / ONE) * (1 - price3 / ONE);
147337
147341
  return Math.ceil(exact * 100 - 1e-9) * 1e4;
147338
147342
  }
147339
- function ledger(ctx, now11) {
147343
+ function ledger2(ctx, now11) {
147340
147344
  const db3 = ctx.store.db, positions2 = /* @__PURE__ */ new Map();
147341
147345
  let cash = db3.prepare("SELECT COALESCE(SUM(amount), 0) AS total FROM kx_deposits WHERE at_ms <= ?").get(now11).total;
147342
147346
  for (const fill of db3.prepare("SELECT * FROM kx_fills WHERE created_ms <= ? ORDER BY created_ms, rowid").all(now11)) {
@@ -147375,7 +147379,7 @@ function ledger(ctx, now11) {
147375
147379
  }
147376
147380
  var collateral = (order5) => (order5.initial - order5.filled) * (order5.book_side === "bid" ? order5.price : ONE - order5.price);
147377
147381
  function balances(ctx, now11) {
147378
- const { cash, positions: positions2 } = ledger(ctx, now11);
147382
+ const { cash, positions: positions2 } = ledger2(ctx, now11);
147379
147383
  const held = restingOrders(ctx, now11).reduce((total2, order5) => total2 + collateral(order5), 0);
147380
147384
  let value4 = 0;
147381
147385
  for (const entry2 of positions2.values()) if (entry2.position) value4 += Math.abs(entry2.position) * (entry2.position > 0 ? getMarket(ctx, entry2.ticker).last_price : ONE - getMarket(ctx, entry2.ticker).last_price);
@@ -147420,7 +147424,7 @@ function seed32(ctx) {
147420
147424
  });
147421
147425
  });
147422
147426
  input4.orders.forEach((entry2, i) => {
147423
- const id14 = seededUuid(`order:${i}`), created3 = at3(entry2.created), series2 = seriesOfMarket(ctx, getMarket(ctx, entry2.market)), positionBefore = ledger(ctx, created3).positions.get(entry2.market)?.position ?? 0;
147427
+ const id14 = seededUuid(`order:${i}`), created3 = at3(entry2.created), series2 = seriesOfMarket(ctx, getMarket(ctx, entry2.market)), positionBefore = ledger2(ctx, created3).positions.get(entry2.market)?.position ?? 0;
147424
147428
  const legacy2 = legacySide(entry2.side, positionBefore);
147425
147429
  db3.prepare(`INSERT INTO kx_orders (id, client_order_id, ticker, book_side, side, action, outcome_side, price, initial, filled, time_in_force, post_only, stp, cancel_on_pause, expiration_ms, created_ms, updated_ms, canceled_ms,
147426
147430
  taker_cost, maker_cost, taker_fees, maker_fees) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, 0, 'taker_at_cross', 0, NULL, ?, ?, ?, 0, 0, 0, 0)`).run(id14, entry2.clientOrderId ?? null, entry2.market, entry2.side, legacy2.side, legacy2.action, legacy2.outcome, price3(entry2.price), count4(entry2.count), entry2.timeInForce, created3, created3, entry2.canceled === void 0 ? null : at3(entry2.canceled));
@@ -147901,7 +147905,7 @@ function positions(call2) {
147901
147905
  choice2(settlement, "settlement_status", ["all", "settled", "unsettled"]);
147902
147906
  for (const name5 of counts) choice2(name5, "count_filter", ["position", "total_traded"]);
147903
147907
  const ticker2 = params10.get("ticker"), eventTicker = params10.get("event_ticker");
147904
- const entries3 = [...ledger(ctx, now11).positions.values()].filter((entry2) => {
147908
+ const entries3 = [...ledger2(ctx, now11).positions.values()].filter((entry2) => {
147905
147909
  const market2 = getMarket(ctx, entry2.ticker);
147906
147910
  return (settlement === "all" || settlement === "settled" === (entry2.settlement !== void 0)) && (!ticker2 || entry2.ticker === ticker2) && (!eventTicker || market2.event === eventTicker) && (!counts.length || counts.some((name5) => name5 === "position" ? entry2.position !== 0 : entry2.traded !== 0));
147907
147911
  });
@@ -147963,7 +147967,7 @@ function settlements(call2) {
147963
147967
  const ctx = call2.ctx, now11 = ctx.clock.nowMs(), params10 = query9(call2, ["limit", "cursor", "ticker", "event_ticker", "min_ts", "max_ts", "subaccount"]), ticker2 = params10.get("ticker"), eventTicker = params10.get("event_ticker");
147964
147968
  primary2(params10.get("subaccount"));
147965
147969
  const within = timeRange2(params10, "min_ts", "max_ts");
147966
- const rows7 = [...ledger(ctx, now11).positions.values()].filter((entry2) => entry2.settlement && (!ticker2 || entry2.ticker === ticker2) && (!eventTicker || getMarket(ctx, entry2.ticker).event === eventTicker) && within(entry2.settlement.at)).sort((a, b) => b.settlement.at - a.settlement.at);
147970
+ const rows7 = [...ledger2(ctx, now11).positions.values()].filter((entry2) => entry2.settlement && (!ticker2 || entry2.ticker === ticker2) && (!eventTicker || getMarket(ctx, entry2.ticker).event === eventTicker) && within(entry2.settlement.at)).sort((a, b) => b.settlement.at - a.settlement.at);
147967
147971
  const result = page14(call2, rows7, 200, 100);
147968
147972
  return json22({
147969
147973
  settlements: result.items.map((entry2) => ({
@@ -163417,7 +163421,7 @@ function bindValue(value4) {
163417
163421
  }
163418
163422
  var pad2 = (n2, width = 2) => String(n2).padStart(width, "0");
163419
163423
  var MONTHS2 = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
163420
- function calendar2(y, m, d) {
163424
+ function calendar3(y, m, d) {
163421
163425
  const date10 = /* @__PURE__ */ new Date(0);
163422
163426
  date10.setUTCFullYear(y, m - 1, d);
163423
163427
  date10.setUTCHours(0, 0, 0, 0);
@@ -163427,7 +163431,7 @@ function calendar2(y, m, d) {
163427
163431
  function isoDate(text23) {
163428
163432
  const match3 = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text23);
163429
163433
  if (!match3) invalid24("Expected a YYYY-MM-DD world date.");
163430
- calendar2(+match3[1], +match3[2], +match3[3]);
163434
+ calendar3(+match3[1], +match3[2], +match3[3]);
163431
163435
  return text23;
163432
163436
  }
163433
163437
  function dateModel(model) {
@@ -163467,7 +163471,7 @@ function parseDate2(value4, model) {
163467
163471
  const values2 = new Map(tokens3.map((t, i) => [t, match3[i + 1]]));
163468
163472
  if (!values2.has("YYYY") || !values2.has("DD") || !["MM", "MON", "MONTH"].some((t) => values2.has(t))) invalid24("TO_DATE requires year, month and day.", true);
163469
163473
  const month = values2.has("MM") ? Number(values2.get("MM")) : MONTHS2.findIndex((m) => values2.has("MON") ? m.slice(0, 3).toLowerCase() === values2.get("MON").toLowerCase() : m.toLowerCase() === values2.get("MONTH").toLowerCase()) + 1;
163470
- const date10 = calendar2(Number(values2.get("YYYY")), month, Number(values2.get("DD")));
163474
+ const date10 = calendar3(Number(values2.get("YYYY")), month, Number(values2.get("DD")));
163471
163475
  let hour2 = Number(values2.get("HH24") ?? values2.get("HH12") ?? values2.get("HH") ?? 0);
163472
163476
  const minute2 = Number(values2.get("MI") ?? 0), second = Number(values2.get("SS") ?? 0);
163473
163477
  if (values2.has("HH12") || values2.has("HH")) {
@@ -167308,15 +167312,29 @@ function record8(ctx, args) {
167308
167312
  }
167309
167313
  const applied = composite2 ? [...byLine.values()].sort((a, b) => a.doc - b.doc || a.line - b.line) : applications(ctx, id14).map((a) => ({ doc: a.doc, amount: a.amount })).sort((a, b) => a.doc - b.doc);
167310
167314
  const wanted = args.apply?.map((a) => composite2 ? { ...a, line: a.line ?? 0 } : { ...a }).sort((a, b) => a.doc - b.doc || (a.line ?? 0) - (b.line ?? 0));
167311
- return checkOutcome(matches8(actual, args.fields ?? {}) && (wanted === void 0 || isDeepStrictEqual(applied, wanted)), expected, JSON.stringify({ record: actual, apply: applied }));
167315
+ const creditLines = args.credit?.some((a) => a.line !== void 0);
167316
+ const credits = /* @__PURE__ */ new Map();
167317
+ for (const a of edges(ctx, id14).filter((a2) => a2.source !== id14)) {
167318
+ const key4 = creditLines ? `${a.source}:${a.sourceline}` : String(a.source);
167319
+ const item2 = credits.get(key4) ?? { doc: a.source, ...creditLines && { line: a.sourceline }, amount: 0 };
167320
+ item2.amount = Math.round((item2.amount + a.amount) * 100) / 100;
167321
+ credits.set(key4, item2);
167322
+ }
167323
+ const sort = (a, b) => a.doc - b.doc || (a.line ?? 0) - (b.line ?? 0);
167324
+ const credited = [...credits.values()].sort(sort);
167325
+ const wantedCredits = args.credit?.map((a) => creditLines ? { ...a, line: a.line ?? 0 } : { ...a }).sort(sort);
167326
+ const creditExpected = args.credit === void 0 ? "" : ` and credits ${JSON.stringify(args.credit)}`;
167327
+ return checkOutcome(matches8(actual, args.fields ?? {}) && (wanted === void 0 || isDeepStrictEqual(applied, wanted)) && (wantedCredits === void 0 || isDeepStrictEqual(credited, wantedCredits)), expected + creditExpected, JSON.stringify({ record: actual, apply: applied, credit: credited }));
167312
167328
  }
167313
167329
  function unchanged(ctx, args) {
167314
- const changes = sql(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype));
167330
+ const allowed2 = (args.except ?? []).map((r2) => ({ type: r2.type, id: r2.id ?? byExternalId(ctx, r2.type, r2.externalId) }));
167331
+ const changes = sql(ctx).prepare("SELECT recordtype, id, operation FROM ns_history ORDER BY ordinal").all().filter((row2) => args.types.includes(row2.recordtype) && !allowed2.some((r2) => r2.type === row2.recordtype && r2.id === row2.id));
167315
167332
  const types = args.types.length >= netsuiteRecordTypes.length && netsuiteRecordTypes.every((type) => args.types.includes(type)) ? "NetSuite records" : args.types.length > 4 ? `${args.types.slice(0, 3).join(", ")} and ${args.types.length - 3} more record types` : args.types.join(", ");
167316
- return checkOutcome(changes.length === 0, `no writes to ${types}`, changes.length ? JSON.stringify(changes) : "no committed writes");
167333
+ const except = args.except?.length ? ` except ${args.except.map((r2) => `${r2.type} ${r2.id ?? `eid:${r2.externalId}`}`).join(", ")}` : "";
167334
+ return checkOutcome(changes.length === 0, `no writes to ${types}${except}`, changes.length ? JSON.stringify(changes) : except ? "no other committed writes" : "no committed writes");
167317
167335
  }
167318
167336
  function count3(ctx, args) {
167319
- const actual = recordIds(ctx, args.type).length;
167337
+ const actual = args.includeSettlement && isTx(args.type) ? sql(ctx).prepare("SELECT COUNT(*) AS count FROM ns_transactions WHERE recordtype = ?").get(args.type).count : recordIds(ctx, args.type).length;
167320
167338
  return checkOutcome(actual === args.count, `${args.count} ${args.type} records`, `${actual} records`);
167321
167339
  }
167322
167340
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ancha-labs/cli",
3
- "version": "0.4.16",
3
+ "version": "0.4.17",
4
4
  "type": "module",
5
5
  "description": "Simulation playgrounds for agents: run your agent against stateful replicas of Slack, GitHub, Datadog and more, each attempt on a fresh cloud machine in your app.ancha.io workspace, or on your computer.",
6
6
  "bugs": {