@composable-os/cli 0.1.0-beta.10 → 0.1.0-beta.13
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/dist/{accounts-X4CKM3HL.js → accounts-GOCNY6WI.js} +17 -14
- package/dist/app-RPRZMLU5.js +43 -0
- package/dist/app-upload-YJVEKZC6.js +198 -0
- package/dist/{blocks-YWDHEBOK.js → blocks-DE4RRWPJ.js} +207 -25
- package/dist/{chunk-VY64DMQO.js → chunk-2B6YUYZV.js} +23576 -11674
- package/dist/{run-RT2HVWMK.js → chunk-2CCHB37H.js} +9 -146
- package/dist/{chunk-DU6OIFOU.js → chunk-3OGDWKJ3.js} +530 -434
- package/dist/chunk-5D7BDF4Y.js +141 -0
- package/dist/{chunk-WO6D3XP3.js → chunk-6CM3WZG5.js} +13 -2470
- package/dist/chunk-CIBJGB5H.js +962 -0
- package/dist/chunk-EPDTPGZJ.js +330 -0
- package/dist/{chunk-LLULPZAJ.js → chunk-HAYF4G5V.js} +66 -23
- package/dist/chunk-HCG6T53D.js +61904 -0
- package/dist/chunk-JX4IFWNT.js +330 -0
- package/dist/{chunk-A4NTSYWV.js → chunk-KFHKNXGH.js} +786 -386
- package/dist/chunk-KMFMD52Z.js +13276 -0
- package/dist/{chunk-E4WCYTCT.js → chunk-LX2TTLVY.js} +174 -55
- package/dist/{chunk-GYTEW66E.js → chunk-O3R4FS2J.js} +1 -1
- package/dist/{chunk-LJFLENFC.js → chunk-Q6Y45DY6.js} +25 -2
- package/dist/{chunk-Y7JZFSTQ.js → chunk-QJZGYJVV.js} +823 -44
- package/dist/{chunk-6VXHPKGG.js → chunk-QQ3YSL5F.js} +172 -16
- package/dist/chunk-RGKJKC5T.js +876 -0
- package/dist/{chunk-IFG4FRW5.js → chunk-RSEWEFAV.js} +12 -2
- package/dist/{chunk-2ABSVMGB.js → chunk-SMJZIK2O.js} +1 -1
- package/dist/{chunk-CP6BXI6F.js → chunk-U72NEGCT.js} +8818 -3829
- package/dist/{chunk-WC5LHBBA.js → chunk-Z4IKF23A.js} +11 -7
- package/dist/chunk-Z7OVQ6BC.js +713 -0
- package/dist/{chunk-6UWRT4VM.js → chunk-ZJSFX4RD.js} +175 -3
- package/dist/{cli-2DFENR62.js → cli-OKQHHSOE.js} +17 -23
- package/dist/{cli-YIOVSKOD.js → cli-VYSD2S4Z.js} +231 -82
- package/dist/cli.js +5 -5
- package/dist/{client-repo-PRU3VCQQ.js → client-repo-NNUCHQ2Y.js} +7 -5
- package/dist/create.js +5 -5
- package/dist/{fields-2NC7LSYE.js → fields-GTHE6TTS.js} +27 -3
- package/dist/gateway-DPPEQZT4.js +25 -0
- package/dist/grants-6JY4XZO7.js +27 -0
- package/dist/invoke-MRONRZ5Q.js +33 -0
- package/dist/moves-UAUCMWL5.js +36 -0
- package/dist/{order-PUWD65BC.js → order-RKLGT74L.js} +2 -2
- package/dist/{person-WIQQ7ITU.js → person-YOZTFV4Q.js} +11 -11
- package/dist/plan-on-sale-H4F26YIN.js +26 -0
- package/dist/platform/migrations/0610_waitlists.sql +54 -0
- package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
- package/dist/platform/migrations/0650_person_links.sql +90 -0
- package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
- package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
- package/dist/platform/migrations/0730_practitioners.sql +79 -0
- package/dist/platform/migrations/0750_routine_mail.sql +98 -0
- package/dist/platform/migrations/0770_clear_fixed_role_grants.sql +64 -0
- package/dist/platform/migrations/0810_recurrence_exceptions.sql +66 -0
- package/dist/platform/migrations/0811_staff_time.sql +109 -0
- package/dist/platform/migrations/0812_staff_offers.sql +112 -0
- package/dist/platform/migrations/0813_pay_periods.sql +241 -0
- package/dist/platform/migrations/0814_staff_feed.sql +47 -0
- package/dist/platform/migrations/0815_checklists.sql +237 -0
- package/dist/platform/migrations/0816_checklist_schedules.sql +121 -0
- package/dist/platform/migrations/0817_checklist_day_window.sql +35 -0
- package/dist/platform/migrations/0850_agreements.sql +271 -0
- package/dist/platform/migrations/0851_agreement_acceptances.sql +387 -0
- package/dist/platform/migrations/0853_agreement_enforcement.sql +58 -0
- package/dist/platform/migrations/0854_agreement_copy.sql +149 -0
- package/dist/platform/migrations/0855_agreement_retention.sql +279 -0
- package/dist/platform/migrations/0856_subscription_cooling_off.sql +159 -0
- package/dist/platform/migrations/0857_agreement_copy_guardian.sql +337 -0
- package/dist/platform/migrations/0858_agreement_desk.sql +175 -0
- package/dist/platform/migrations/0910_routine_messages.sql +99 -0
- package/dist/platform/migrations/0911_texts.sql +60 -0
- package/dist/platform/migrations/0913_contact_consent.sql +93 -0
- package/dist/platform/migrations/0916_contact_mailbox_index.sql +29 -0
- package/dist/platform/migrations/0930_stock_movements.sql +95 -0
- package/dist/platform/migrations/0931_stock_low.sql +25 -0
- package/dist/platform/migrations/0932_order_delivery.sql +78 -0
- package/dist/platform/migrations/0950_order_adjustments.sql +111 -0
- package/dist/platform/migrations/0951_order_price_guards.sql +33 -0
- package/dist/platform/migrations/0952_order_paid_another_way.sql +194 -0
- package/dist/platform/migrations/0953_discount_uses.sql +183 -0
- package/dist/platform/migrations/0955_folded_addresses.sql +92 -0
- package/dist/platform/migrations/0970_published_text.sql +59 -0
- package/dist/platform/migrations/0971_publish_acks.sql +68 -0
- package/dist/platform/migrations/0990_customer_email_change.sql +65 -0
- package/dist/platform/migrations/1010_intake_links.sql +148 -0
- package/dist/platform/migrations/1030_invoices.sql +747 -0
- package/dist/platform/migrations/1031_invoice_orders.sql +327 -0
- package/dist/platform/migrations/1050_inbox_conversations.sql +83 -0
- package/dist/platform/migrations/1090_staff_hours.sql +43 -0
- package/dist/platform/migrations/1091_staff_time_margins.sql +12 -0
- package/dist/platform/migrations/1092_client_guard.sql +26 -0
- package/dist/platform/migrations/1095_thing_time.sql +70 -0
- package/dist/platform/migrations/1130_devices.sql +162 -0
- package/dist/platform/migrations/1135_person_codes.sql +88 -0
- package/dist/platform/migrations/1150_finance_periods.sql +316 -0
- package/dist/platform/migrations/1151_payouts.sql +202 -0
- package/dist/platform/migrations/1153_finance_money_dates.sql +18 -0
- package/dist/platform/migrations/1170_journeys.sql +318 -0
- package/dist/platform/migrations/1171_person_birthday.sql +52 -0
- package/dist/platform/migrations/1175_person_signals.sql +29 -0
- package/dist/platform/migrations/1190_restricted_values.sql +25 -0
- package/dist/platform/migrations/1230_note_levels.sql +113 -0
- package/dist/platform/migrations/1231_person_carers.sql +33 -0
- package/dist/platform/migrations/1232_note_kinds.sql +122 -0
- package/dist/platform/migrations/1270_time_entries.sql +145 -0
- package/dist/platform/migrations/1271_leave.sql +249 -0
- package/dist/platform/migrations/1273_time_entry_reopened.sql +21 -0
- package/dist/platform/migrations/1330_accounting.sql +260 -0
- package/dist/platform/migrations/1350_customer_feed.sql +24 -0
- package/dist/platform/migrations/1390_locations.sql +77 -0
- package/dist/platform/migrations/1410_outside_copy.sql +213 -0
- package/dist/platform/migrations/1430_inbox_activities.sql +231 -0
- package/dist/platform/migrations/1450_wrong_guesses.sql +23 -0
- package/dist/platform/sdk/acknowledge.ts +100 -0
- package/dist/platform/sdk/agreements.ts +185 -0
- package/dist/platform/sdk/allowance.ts +98 -8
- package/dist/platform/sdk/automation-check.ts +120 -9
- package/dist/platform/sdk/automation.ts +78 -10
- package/dist/platform/sdk/behaviour.ts +26 -6
- package/dist/platform/sdk/calendar-entry.ts +258 -0
- package/dist/platform/sdk/capacity.ts +103 -2
- package/dist/platform/sdk/checklists.ts +118 -0
- package/dist/platform/sdk/contract.ts +514 -27
- package/dist/platform/sdk/discount.ts +408 -0
- package/dist/platform/sdk/document.ts +4 -2
- package/dist/platform/sdk/field-types.ts +5 -0
- package/dist/platform/sdk/formula/compile.ts +10 -0
- package/dist/platform/sdk/index.ts +17 -0
- package/dist/platform/sdk/intake.ts +380 -0
- package/dist/platform/sdk/journey-signals.ts +215 -0
- package/dist/platform/sdk/manifest.ts +1313 -66
- package/dist/platform/sdk/mine.ts +161 -0
- package/dist/platform/sdk/occupies.ts +192 -0
- package/dist/platform/sdk/questions.ts +681 -0
- package/dist/platform/sdk/recurring.ts +90 -9
- package/dist/platform/sdk/restricted-fields.ts +129 -0
- package/dist/platform/sdk/rich-text.ts +112 -0
- package/dist/platform/sdk/routine-mail.ts +1272 -0
- package/dist/platform/sdk/runtime.ts +25 -12
- package/dist/platform/sdk/screens.ts +91 -0
- package/dist/platform/sdk/sellable.ts +595 -1
- package/dist/platform/sdk/slug.ts +7 -2
- package/dist/platform/sdk/staffed.ts +474 -0
- package/dist/platform/sdk/states.ts +220 -64
- package/dist/platform/sdk/stock.ts +332 -0
- package/dist/platform/sdk/team.ts +83 -0
- package/dist/platform/sdk/testing.ts +70 -6
- package/dist/platform/sdk/worked-on.ts +134 -0
- package/dist/{products-2H5DR232.js → products-GCQLSZ3U.js} +2 -2
- package/dist/run-7ID64RA6.js +65 -0
- package/dist/run-FH7OGGTV.js +131 -0
- package/dist/run-OYZIAP6M.js +3363 -0
- package/dist/{run-Y7T4TVOL.js → run-QOFRRSZV.js} +41 -60
- package/dist/{run-PZUCSDDL.js → run-TJAEWR5U.js} +21 -51
- package/dist/{src-XTOD7EXW.js → src-52VERUPK.js} +312 -4
- package/dist/src-PHRELWN5.js +40 -0
- package/dist/visibility-SZCINPP4.js +58 -0
- package/package.json +2 -2
- package/dist/chunk-6GDEDOV7.js +0 -157
- package/dist/chunk-6UPUF4ML.js +0 -29998
- package/dist/chunk-7CQGMVDO.js +0 -63
- package/dist/chunk-GYSGVT6R.js +0 -284
- package/dist/chunk-JJHHNV46.js +0 -227
- package/dist/chunk-K6T42YCH.js +0 -704
- package/dist/chunk-M7A6FR2Z.js +0 -2586
- package/dist/chunk-O2UIZHND.js +0 -249
- package/dist/chunk-Q4N55M2Z.js +0 -552
- package/dist/chunk-QGGJ2G6Z.js +0 -349
- package/dist/chunk-R4W5XAUD.js +0 -837
- package/dist/chunk-TQFGGSA4.js +0 -748
- package/dist/chunk-YJJHF65I.js +0 -759
- package/dist/chunk-Z3RMMB6S.js +0 -668
- package/dist/grants-QXMKYMGB.js +0 -32
- package/dist/invoke-I3NNNXVL.js +0 -39
- package/dist/plan-on-sale-NB774CQL.js +0 -26
- package/dist/src-GYS6NBQB.js +0 -44
- package/dist/visibility-DLGHU4YN.js +0 -33
package/dist/chunk-K6T42YCH.js
DELETED
|
@@ -1,704 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
newId
|
|
4
|
-
} from "./chunk-TQFGGSA4.js";
|
|
5
|
-
import {
|
|
6
|
-
ValidationError,
|
|
7
|
-
liveViewOf,
|
|
8
|
-
sql,
|
|
9
|
-
viewColumnOf,
|
|
10
|
-
visibleObject,
|
|
11
|
-
visibleSource
|
|
12
|
-
} from "./chunk-A4NTSYWV.js";
|
|
13
|
-
import {
|
|
14
|
-
getObject
|
|
15
|
-
} from "./chunk-IFG4FRW5.js";
|
|
16
|
-
import {
|
|
17
|
-
getField
|
|
18
|
-
} from "./chunk-Q4N55M2Z.js";
|
|
19
|
-
import {
|
|
20
|
-
documentRefs,
|
|
21
|
-
external_exports
|
|
22
|
-
} from "./chunk-CP6BXI6F.js";
|
|
23
|
-
|
|
24
|
-
// ../core/src/records/common.ts
|
|
25
|
-
var TRASH_RETENTION_DAYS = 30;
|
|
26
|
-
var DAY_MS = 864e5;
|
|
27
|
-
function restorableUntil(deletedAt) {
|
|
28
|
-
return new Date(Date.parse(deletedAt) + TRASH_RETENTION_DAYS * DAY_MS).toISOString();
|
|
29
|
-
}
|
|
30
|
-
function purgeCutoff(now) {
|
|
31
|
-
return new Date(Date.parse(now) - TRASH_RETENTION_DAYS * DAY_MS).toISOString();
|
|
32
|
-
}
|
|
33
|
-
var BATCH_MAX = 100;
|
|
34
|
-
var IN_LIST_CHUNK = 50;
|
|
35
|
-
function jsonList(values) {
|
|
36
|
-
return sql`(SELECT value FROM json_each(${JSON.stringify(values)}))`;
|
|
37
|
-
}
|
|
38
|
-
function chunk(items, size = IN_LIST_CHUNK) {
|
|
39
|
-
const chunks = [];
|
|
40
|
-
for (let i = 0; i < items.length; i += size) chunks.push(items.slice(i, i + size));
|
|
41
|
-
return chunks;
|
|
42
|
-
}
|
|
43
|
-
var blankToNull = (value) => value === void 0 ? void 0 : value === null || value === "" ? null : value;
|
|
44
|
-
async function assertUserExists(db, id, field2 = "ownerId") {
|
|
45
|
-
if (!id) return;
|
|
46
|
-
const user = await db.selectFrom("core_user").select("id").where("id", "=", id).executeTakeFirst();
|
|
47
|
-
if (!user) throw new ValidationError(`No user with id ${id}`, { field: field2 });
|
|
48
|
-
}
|
|
49
|
-
function withPrimary(items, what) {
|
|
50
|
-
const flagged = items.filter((item) => item.primary).length;
|
|
51
|
-
if (flagged > 1) throw new ValidationError(`Only one ${what} can be primary`);
|
|
52
|
-
return items.map((item, i) => ({ ...item, primary: flagged ? Boolean(item.primary) : i === 0 }));
|
|
53
|
-
}
|
|
54
|
-
function uniqueIds(ids) {
|
|
55
|
-
const unique = [...new Set(ids)];
|
|
56
|
-
if (unique.length !== ids.length) throw new ValidationError("An id is listed twice");
|
|
57
|
-
return unique;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// ../core/src/notifications/send.ts
|
|
61
|
-
var CORE_USER_FIELDS = /* @__PURE__ */ new Set(["ownerId", "assigneeId", "authorUserId", "createdBy"]);
|
|
62
|
-
var NO_MANAGER_NOTE = "Users have no manager field: sent to the admins instead";
|
|
63
|
-
async function adminUserIds(db) {
|
|
64
|
-
const rows = await db.selectFrom("core_user").select("id").where("role", "=", "admin").where("kind", "=", "human").orderBy("id").execute();
|
|
65
|
-
return rows.map((row) => row.id);
|
|
66
|
-
}
|
|
67
|
-
async function recordUser(db, record, fieldName, options) {
|
|
68
|
-
const object = getObject(record.object);
|
|
69
|
-
if (!object) {
|
|
70
|
-
throw new ValidationError(`Unknown object "${record.object}"`, { field: "to" });
|
|
71
|
-
}
|
|
72
|
-
const field2 = getField(object, fieldName);
|
|
73
|
-
const isUserField = field2 && (field2.fieldType === "user" || !field2.extension && CORE_USER_FIELDS.has(field2.name));
|
|
74
|
-
if (!field2 || !isUserField) {
|
|
75
|
-
throw new ValidationError(
|
|
76
|
-
`${object.label} has no user field "${fieldName}" (recipients name a user field of the record)`,
|
|
77
|
-
{ field: "to", object: record.object, recordField: fieldName }
|
|
78
|
-
);
|
|
79
|
-
}
|
|
80
|
-
const simulated = options.simulation?.record(record.object, record.id);
|
|
81
|
-
if (simulated) {
|
|
82
|
-
if (simulated.state === "deleted" || !simulated.record) {
|
|
83
|
-
return { userId: null, reason: `${object.label} ${record.id} is deleted` };
|
|
84
|
-
}
|
|
85
|
-
const values = simulated.record.values ?? simulated.record;
|
|
86
|
-
const value = values[field2.name];
|
|
87
|
-
return typeof value === "string" && value ? { userId: value } : {
|
|
88
|
-
userId: null,
|
|
89
|
-
reason: `${object.label} ${record.id} has no ${field2.label.toLowerCase()}`
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
const column = viewColumnOf(field2);
|
|
93
|
-
if (!column) throw new ValidationError(`${object.label}.${field2.name} cannot be read`);
|
|
94
|
-
const result = await sql`SELECT ${sql.ref(column)} AS v FROM ${sql.table(
|
|
95
|
-
object.source
|
|
96
|
-
)} WHERE id = ${record.id}`.execute(db);
|
|
97
|
-
const row = result.rows[0];
|
|
98
|
-
if (!row) return { userId: null, reason: `No ${object.label} with id ${record.id}` };
|
|
99
|
-
return typeof row.v === "string" && row.v ? { userId: row.v } : { userId: null, reason: `${object.label} ${record.id} has no ${field2.label.toLowerCase()}` };
|
|
100
|
-
}
|
|
101
|
-
async function resolveRecipients(db, to, options = {}) {
|
|
102
|
-
const ids = [];
|
|
103
|
-
const notes = [];
|
|
104
|
-
let admins = null;
|
|
105
|
-
const loadAdmins = async () => {
|
|
106
|
-
admins ??= await adminUserIds(db);
|
|
107
|
-
return admins;
|
|
108
|
-
};
|
|
109
|
-
for (const recipient of to) {
|
|
110
|
-
if ("userId" in recipient) {
|
|
111
|
-
ids.push(recipient.userId);
|
|
112
|
-
} else if ("role" in recipient) {
|
|
113
|
-
ids.push(...await loadAdmins());
|
|
114
|
-
} else if ("field" in recipient) {
|
|
115
|
-
const found = await recordUser(db, recipient.record, recipient.field, options);
|
|
116
|
-
if (found.userId) ids.push(found.userId);
|
|
117
|
-
else notes.push(`${found.reason}: nobody to notify`);
|
|
118
|
-
} else {
|
|
119
|
-
const found = await recordUser(db, recipient.record, recipient.managerOf, options);
|
|
120
|
-
if (!found.userId) notes.push(`${found.reason}`);
|
|
121
|
-
notes.push(NO_MANAGER_NOTE);
|
|
122
|
-
ids.push(...await loadAdmins());
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
const unique = [...new Set(ids)];
|
|
126
|
-
const people = unique.length ? await db.selectFrom("core_user").select("id").where("id", "in", jsonList(unique)).where("kind", "=", "human").execute() : [];
|
|
127
|
-
const known = new Set(people.map((p) => p.id));
|
|
128
|
-
const explicit = new Set(
|
|
129
|
-
to.flatMap((r) => "userId" in r ? [r.userId] : [])
|
|
130
|
-
);
|
|
131
|
-
for (const id of unique) {
|
|
132
|
-
if (known.has(id)) continue;
|
|
133
|
-
if (explicit.has(id)) {
|
|
134
|
-
throw new ValidationError(`No user with id ${id}`, { field: "to", userId: id });
|
|
135
|
-
}
|
|
136
|
-
notes.push(`User ${id} no longer exists: skipped`);
|
|
137
|
-
}
|
|
138
|
-
if (!to.length) notes.push("No recipients");
|
|
139
|
-
return { userIds: unique.filter((id) => known.has(id)), notes };
|
|
140
|
-
}
|
|
141
|
-
async function notifyStatements(db, input, now, options = {}) {
|
|
142
|
-
const { userIds, notes } = await resolveRecipients(db, input.to, options);
|
|
143
|
-
const source = JSON.stringify(
|
|
144
|
-
Object.fromEntries(Object.entries(input.source).filter(([, v]) => v !== void 0))
|
|
145
|
-
);
|
|
146
|
-
const link = input.link ? JSON.stringify(input.link) : null;
|
|
147
|
-
const statements = userIds.map(
|
|
148
|
-
(userId) => db.insertInto("core_notifications").orIgnore().values({
|
|
149
|
-
id: newId("notification"),
|
|
150
|
-
user_id: userId,
|
|
151
|
-
type: input.type,
|
|
152
|
-
title: input.title,
|
|
153
|
-
body: input.body ?? null,
|
|
154
|
-
link,
|
|
155
|
-
source,
|
|
156
|
-
dedupe_key: input.dedupeKey ?? null,
|
|
157
|
-
read_at: null,
|
|
158
|
-
created_at: now
|
|
159
|
-
})
|
|
160
|
-
);
|
|
161
|
-
return { statements, userIds, notes };
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// ../core/src/filter.ts
|
|
165
|
-
var FILTER_OPS = [
|
|
166
|
-
"eq",
|
|
167
|
-
"neq",
|
|
168
|
-
"lt",
|
|
169
|
-
"lte",
|
|
170
|
-
"gt",
|
|
171
|
-
"gte",
|
|
172
|
-
"between",
|
|
173
|
-
"in",
|
|
174
|
-
"not_in",
|
|
175
|
-
"contains",
|
|
176
|
-
"not_contains",
|
|
177
|
-
"starts_with",
|
|
178
|
-
"ends_with",
|
|
179
|
-
"is_null",
|
|
180
|
-
"is_not_null"
|
|
181
|
-
];
|
|
182
|
-
var FILTER_LIMITS = { maxDepth: 5, maxConditions: 100, maxListValues: 500 };
|
|
183
|
-
var conditionSchema = external_exports.object({
|
|
184
|
-
field: external_exports.string().min(1).max(64),
|
|
185
|
-
op: external_exports.enum(FILTER_OPS),
|
|
186
|
-
value: external_exports.unknown().optional()
|
|
187
|
-
}).strict();
|
|
188
|
-
var filterSchema = external_exports.lazy(
|
|
189
|
-
() => external_exports.union([
|
|
190
|
-
conditionSchema,
|
|
191
|
-
external_exports.object({ and: external_exports.array(filterSchema).max(FILTER_LIMITS.maxConditions) }).strict(),
|
|
192
|
-
external_exports.object({ or: external_exports.array(filterSchema).max(FILTER_LIMITS.maxConditions) }).strict()
|
|
193
|
-
])
|
|
194
|
-
);
|
|
195
|
-
var COMPARABLE = ["eq", "neq", "lt", "lte", "gt", "gte", "between", "in", "not_in"];
|
|
196
|
-
var NULLS = ["is_null", "is_not_null"];
|
|
197
|
-
var TEXT = [
|
|
198
|
-
"eq",
|
|
199
|
-
"neq",
|
|
200
|
-
"in",
|
|
201
|
-
"not_in",
|
|
202
|
-
"contains",
|
|
203
|
-
"not_contains",
|
|
204
|
-
"starts_with",
|
|
205
|
-
"ends_with"
|
|
206
|
-
];
|
|
207
|
-
var OPS_BY_TYPE = {
|
|
208
|
-
text: [...TEXT, ...NULLS],
|
|
209
|
-
number: [...COMPARABLE, ...NULLS],
|
|
210
|
-
date: [...COMPARABLE, ...NULLS],
|
|
211
|
-
datetime: [...COMPARABLE, ...NULLS],
|
|
212
|
-
boolean: ["eq", "neq", ...NULLS],
|
|
213
|
-
id: ["eq", "neq", "in", "not_in", ...NULLS],
|
|
214
|
-
enum: ["eq", "neq", "in", "not_in", ...NULLS],
|
|
215
|
-
json: []
|
|
216
|
-
};
|
|
217
|
-
var RELATED_OPS = [
|
|
218
|
-
"eq",
|
|
219
|
-
"neq",
|
|
220
|
-
"in",
|
|
221
|
-
"not_in",
|
|
222
|
-
"contains",
|
|
223
|
-
"not_contains",
|
|
224
|
-
"starts_with",
|
|
225
|
-
"ends_with",
|
|
226
|
-
...NULLS
|
|
227
|
-
];
|
|
228
|
-
var NEGATED = {
|
|
229
|
-
neq: "eq",
|
|
230
|
-
not_in: "in",
|
|
231
|
-
not_contains: "contains"
|
|
232
|
-
};
|
|
233
|
-
var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
234
|
-
var DATETIME_RE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})?)?$/;
|
|
235
|
-
function fail(path, reason) {
|
|
236
|
-
throw new ValidationError(`Invalid filter at ${path}: ${reason}`, { path, reason });
|
|
237
|
-
}
|
|
238
|
-
function scalar(field2, value, path) {
|
|
239
|
-
switch (field2.type) {
|
|
240
|
-
case "text":
|
|
241
|
-
if (typeof value !== "string") fail(path, `${field2.name} needs a string`);
|
|
242
|
-
if (value.length > 1e3) fail(path, "value is too long");
|
|
243
|
-
return value;
|
|
244
|
-
case "id":
|
|
245
|
-
if (typeof value !== "string" || value.length > 100) fail(path, `${field2.name} needs an id`);
|
|
246
|
-
return value;
|
|
247
|
-
case "number":
|
|
248
|
-
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
249
|
-
fail(path, `${field2.name} needs a number`);
|
|
250
|
-
}
|
|
251
|
-
return value;
|
|
252
|
-
case "boolean":
|
|
253
|
-
if (typeof value !== "boolean") fail(path, `${field2.name} needs true or false`);
|
|
254
|
-
return value ? 1 : 0;
|
|
255
|
-
case "date":
|
|
256
|
-
if (typeof value !== "string" || !DATE_RE.test(value)) {
|
|
257
|
-
fail(path, `${field2.name} needs a YYYY-MM-DD date`);
|
|
258
|
-
}
|
|
259
|
-
return value;
|
|
260
|
-
case "datetime":
|
|
261
|
-
if (typeof value !== "string" || !DATETIME_RE.test(value)) {
|
|
262
|
-
fail(path, `${field2.name} needs an ISO-8601 date or timestamp`);
|
|
263
|
-
}
|
|
264
|
-
return value;
|
|
265
|
-
case "enum":
|
|
266
|
-
if (typeof value !== "string" || !field2.enumValues?.includes(value)) {
|
|
267
|
-
fail(path, `${field2.name} must be one of ${field2.enumValues?.join(", ")}`);
|
|
268
|
-
}
|
|
269
|
-
return value;
|
|
270
|
-
case "json":
|
|
271
|
-
return fail(path, `${field2.name} cannot be filtered`);
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
function list(field2, value, path) {
|
|
275
|
-
if (!Array.isArray(value) || value.length === 0) fail(path, "needs a non-empty array");
|
|
276
|
-
if (value.length > FILTER_LIMITS.maxListValues) fail(path, "too many values");
|
|
277
|
-
return value.map((item, i) => scalar(field2, item, `${path}[${i}]`));
|
|
278
|
-
}
|
|
279
|
-
function escapeLike(value) {
|
|
280
|
-
return value.replace(/[\\%_]/g, (char) => `\\${char}`);
|
|
281
|
-
}
|
|
282
|
-
function comparison(field2, col, op, value, path) {
|
|
283
|
-
const nocase = field2.type === "text" ? sql` COLLATE NOCASE` : sql``;
|
|
284
|
-
switch (op) {
|
|
285
|
-
case "is_null":
|
|
286
|
-
return sql`${col} IS NULL`;
|
|
287
|
-
case "is_not_null":
|
|
288
|
-
return sql`${col} IS NOT NULL`;
|
|
289
|
-
case "eq":
|
|
290
|
-
return sql`${col} = ${scalar(field2, value, path)}${nocase}`;
|
|
291
|
-
case "neq":
|
|
292
|
-
return sql`(${col} IS NULL OR ${col} <> ${scalar(field2, value, path)}${nocase})`;
|
|
293
|
-
case "lt":
|
|
294
|
-
return sql`${col} < ${scalar(field2, value, path)}`;
|
|
295
|
-
case "lte":
|
|
296
|
-
return sql`${col} <= ${scalar(field2, value, path)}`;
|
|
297
|
-
case "gt":
|
|
298
|
-
return sql`${col} > ${scalar(field2, value, path)}`;
|
|
299
|
-
case "gte":
|
|
300
|
-
return sql`${col} >= ${scalar(field2, value, path)}`;
|
|
301
|
-
case "between": {
|
|
302
|
-
if (!Array.isArray(value) || value.length !== 2) fail(path, "between needs [low, high]");
|
|
303
|
-
const [low, high] = list(field2, value, path);
|
|
304
|
-
return sql`${col} BETWEEN ${low ?? null} AND ${high ?? null}`;
|
|
305
|
-
}
|
|
306
|
-
case "in":
|
|
307
|
-
return sql`${col}${nocase} IN (${sql.join(list(field2, value, path))})`;
|
|
308
|
-
case "not_in":
|
|
309
|
-
return sql`(${col} IS NULL OR ${col}${nocase} NOT IN (${sql.join(list(field2, value, path))}))`;
|
|
310
|
-
case "contains":
|
|
311
|
-
case "not_contains":
|
|
312
|
-
case "starts_with":
|
|
313
|
-
case "ends_with": {
|
|
314
|
-
const text = scalar(field2, value, path);
|
|
315
|
-
if (typeof text !== "string") fail(path, `${op} needs a string`);
|
|
316
|
-
const escaped = escapeLike(text);
|
|
317
|
-
const pattern = op === "starts_with" ? `${escaped}%` : op === "ends_with" ? `%${escaped}` : `%${escaped}%`;
|
|
318
|
-
const like = sql`${col} LIKE ${pattern} ESCAPE '\\'`;
|
|
319
|
-
return op === "not_contains" ? sql`(${col} IS NULL OR NOT (${like}))` : like;
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
function compileNode(object, node, alias, path, depth, state) {
|
|
324
|
-
if (depth > FILTER_LIMITS.maxDepth) fail(path, "filter is nested too deeply");
|
|
325
|
-
if ("and" in node || "or" in node) {
|
|
326
|
-
const isAnd = "and" in node;
|
|
327
|
-
const children = isAnd ? node.and : node.or;
|
|
328
|
-
const key = isAnd ? "and" : "or";
|
|
329
|
-
if (children.length === 0) return isAnd ? sql`1 = 1` : sql`1 = 0`;
|
|
330
|
-
const parts = children.map(
|
|
331
|
-
(child, i) => compileNode(object, child, alias, `${path}.${key}[${i}]`, depth + 1, state)
|
|
332
|
-
);
|
|
333
|
-
return sql`(${sql.join(parts, sql.raw(isAnd ? " AND " : " OR "))})`;
|
|
334
|
-
}
|
|
335
|
-
state.conditions += 1;
|
|
336
|
-
if (state.conditions > FILTER_LIMITS.maxConditions) fail(path, "too many conditions");
|
|
337
|
-
const { field: name, op, value } = node;
|
|
338
|
-
const field2 = object.fields.find((f) => f.name === name);
|
|
339
|
-
if (!field2) fail(path, `unknown field "${name}" on ${object.name}`);
|
|
340
|
-
if (!field2.filterable) fail(path, `${object.name}.${name} is not filterable`);
|
|
341
|
-
if (field2.related) {
|
|
342
|
-
if (!RELATED_OPS.includes(op) || !OPS_BY_TYPE[field2.type].includes(op)) {
|
|
343
|
-
fail(path, `${op} is not supported on ${object.name}.${name}`);
|
|
344
|
-
}
|
|
345
|
-
const r = field2.related;
|
|
346
|
-
const extra = r.where ? sql` AND ${sql.raw(r.where)}` : sql``;
|
|
347
|
-
const exists = (condition) => sql`EXISTS (SELECT 1 FROM ${sql.raw(r.from)} WHERE ${sql.raw(r.link)} = ${sql.ref(`${alias}.id`)}${extra}${condition ? sql` AND ${condition}` : sql``})`;
|
|
348
|
-
if (op === "is_not_null") return exists(null);
|
|
349
|
-
if (op === "is_null") return sql`NOT ${exists(null)}`;
|
|
350
|
-
const positive = NEGATED[op];
|
|
351
|
-
const col = sql.raw(r.column);
|
|
352
|
-
if (positive) {
|
|
353
|
-
return sql`NOT ${exists(comparison(field2, col, positive, value, path))}`;
|
|
354
|
-
}
|
|
355
|
-
return exists(comparison(field2, col, op, value, path));
|
|
356
|
-
}
|
|
357
|
-
if (!OPS_BY_TYPE[field2.type].includes(op)) {
|
|
358
|
-
fail(path, `${op} is not supported on ${field2.type} field ${object.name}.${name}`);
|
|
359
|
-
}
|
|
360
|
-
if (!field2.column) fail(path, `${object.name}.${name} has no column`);
|
|
361
|
-
if (!NULLS.includes(op) && value === void 0) fail(path, `${op} needs a value`);
|
|
362
|
-
return comparison(field2, sql.ref(`${alias}.${field2.column}`), op, value, path);
|
|
363
|
-
}
|
|
364
|
-
function compileFilter(object, filter, alias = object.source) {
|
|
365
|
-
const parsed = filterSchema.safeParse(filter);
|
|
366
|
-
if (!parsed.success) {
|
|
367
|
-
throw new ValidationError("Invalid filter", { issues: parsed.error.issues });
|
|
368
|
-
}
|
|
369
|
-
return compileNode(object, parsed.data, alias, "filter", 1, { conditions: 0 });
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// ../core/src/list.ts
|
|
373
|
-
var sortSchema = external_exports.object({
|
|
374
|
-
field: external_exports.string().min(1).max(64),
|
|
375
|
-
direction: external_exports.enum(["asc", "desc"]).default("asc")
|
|
376
|
-
});
|
|
377
|
-
var LIST_MAX_LIMIT = 200;
|
|
378
|
-
var LIST_DEFAULT_LIMIT = 50;
|
|
379
|
-
var listInputSchema = external_exports.object({
|
|
380
|
-
filter: filterSchema.optional().describe("Structured filter: { and | or: [...] } of { field, op, value }."),
|
|
381
|
-
sort: sortSchema.optional().describe("Sort field and direction. Defaults per object."),
|
|
382
|
-
cursor: external_exports.string().max(1e3).optional().describe("nextCursor from the previous page."),
|
|
383
|
-
limit: external_exports.number().int().min(1).max(LIST_MAX_LIMIT).default(LIST_DEFAULT_LIMIT),
|
|
384
|
-
fields: external_exports.array(external_exports.string().min(1).max(64)).max(100).optional().describe("Return only these fields of each item (id is always included).")
|
|
385
|
-
});
|
|
386
|
-
function pageSchema(item) {
|
|
387
|
-
return external_exports.object({ items: external_exports.array(item), nextCursor: external_exports.string().nullable() });
|
|
388
|
-
}
|
|
389
|
-
function base64UrlEncode(text) {
|
|
390
|
-
const bytes = new TextEncoder().encode(text);
|
|
391
|
-
let binary = "";
|
|
392
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
393
|
-
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
394
|
-
}
|
|
395
|
-
function base64UrlDecode(text) {
|
|
396
|
-
const padded = text.replace(/-/g, "+").replace(/_/g, "/");
|
|
397
|
-
const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
|
|
398
|
-
return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
|
|
399
|
-
}
|
|
400
|
-
function encodeCursor(payload) {
|
|
401
|
-
return base64UrlEncode(JSON.stringify(payload));
|
|
402
|
-
}
|
|
403
|
-
var cursorSchema = external_exports.object({
|
|
404
|
-
f: external_exports.string(),
|
|
405
|
-
d: external_exports.enum(["asc", "desc"]),
|
|
406
|
-
v: external_exports.union([external_exports.string(), external_exports.number(), external_exports.null()]),
|
|
407
|
-
id: external_exports.string()
|
|
408
|
-
});
|
|
409
|
-
function decodeCursor(cursor, sort) {
|
|
410
|
-
let payload;
|
|
411
|
-
try {
|
|
412
|
-
payload = cursorSchema.parse(JSON.parse(base64UrlDecode(cursor)));
|
|
413
|
-
} catch {
|
|
414
|
-
throw new ValidationError("Invalid cursor");
|
|
415
|
-
}
|
|
416
|
-
if (payload.f !== sort.field || payload.d !== sort.direction) {
|
|
417
|
-
throw new ValidationError("Cursor was issued for a different sort; start from the first page");
|
|
418
|
-
}
|
|
419
|
-
return payload;
|
|
420
|
-
}
|
|
421
|
-
function resolveSort(object, sort) {
|
|
422
|
-
const resolved = sort ?? object.defaultSort;
|
|
423
|
-
const field2 = object.fields.find((f) => f.name === resolved.field);
|
|
424
|
-
if (!field2) throw new ValidationError(`Unknown sort field "${resolved.field}"`);
|
|
425
|
-
if (!field2.sortable || !field2.column) {
|
|
426
|
-
throw new ValidationError(`${object.name}.${resolved.field} is not sortable`);
|
|
427
|
-
}
|
|
428
|
-
return { sort: resolved, field: field2 };
|
|
429
|
-
}
|
|
430
|
-
function sortExpression(field2, alias) {
|
|
431
|
-
const ref = sql.ref(`${alias}.${field2.column}`);
|
|
432
|
-
return field2.type === "text" ? sql`${ref} COLLATE NOCASE` : ref;
|
|
433
|
-
}
|
|
434
|
-
function afterCursor(field2, alias, cursor) {
|
|
435
|
-
const col = sortExpression(field2, alias);
|
|
436
|
-
const raw = sql.ref(`${alias}.${field2.column}`);
|
|
437
|
-
const id = sql.ref(`${alias}.id`);
|
|
438
|
-
if (field2.name === "id") {
|
|
439
|
-
return cursor.d === "asc" ? sql`${id} > ${cursor.id}` : sql`${id} < ${cursor.id}`;
|
|
440
|
-
}
|
|
441
|
-
if (cursor.d === "asc") {
|
|
442
|
-
return cursor.v === null ? sql`((${raw} IS NULL AND ${id} > ${cursor.id}) OR ${raw} IS NOT NULL)` : sql`(${col} > ${cursor.v} OR (${col} = ${cursor.v} AND ${id} > ${cursor.id}))`;
|
|
443
|
-
}
|
|
444
|
-
return cursor.v === null ? sql`(${raw} IS NULL AND ${id} < ${cursor.id})` : sql`(${col} < ${cursor.v} OR ${raw} IS NULL OR (${col} = ${cursor.v} AND ${id} < ${cursor.id}))`;
|
|
445
|
-
}
|
|
446
|
-
function indexOrdered(object, field2) {
|
|
447
|
-
return field2.name === "id" || field2.name === object.defaultSort.field;
|
|
448
|
-
}
|
|
449
|
-
async function pageByIds(base, ordered, alias, column, take) {
|
|
450
|
-
const keys = await ordered.clearSelect().select([sql.ref(`${alias}.id`).as("id"), sql.ref(`${alias}.${column}`).as("sort_value")]).limit(take).execute();
|
|
451
|
-
if (!keys.length) return [];
|
|
452
|
-
const ids = keys.map((k) => k.id);
|
|
453
|
-
const rows = await base.where(
|
|
454
|
-
sql`${sql.ref(`${alias}.id`)} IN (SELECT value FROM json_each(${JSON.stringify(ids)}))`
|
|
455
|
-
).execute();
|
|
456
|
-
const byId = new Map(rows.map((row) => [row.id, row]));
|
|
457
|
-
return ids.flatMap((id) => {
|
|
458
|
-
const row = byId.get(id);
|
|
459
|
-
return row ? [row] : [];
|
|
460
|
-
});
|
|
461
|
-
}
|
|
462
|
-
async function runListQuery(ctx, object, input) {
|
|
463
|
-
const query = ctx.db.selectFrom(visibleSource(ctx, object)).selectAll();
|
|
464
|
-
return pageQuery(query, visibleObject(ctx, object), input, object.source);
|
|
465
|
-
}
|
|
466
|
-
async function pageQuery(query, object, input, alias = object.source) {
|
|
467
|
-
const { sort, field: field2 } = resolveSort(object, input.sort);
|
|
468
|
-
let q = query;
|
|
469
|
-
if (input.filter) q = q.where(compileFilter(object, input.filter, alias));
|
|
470
|
-
if (input.cursor) q = q.where(afterCursor(field2, alias, decodeCursor(input.cursor, sort)));
|
|
471
|
-
const direction = sql.raw(sort.direction === "asc" ? "ASC" : "DESC");
|
|
472
|
-
if (field2.name !== "id") q = q.orderBy(sql`${sortExpression(field2, alias)} ${direction}`);
|
|
473
|
-
q = q.orderBy(sql`${sql.ref(`${alias}.id`)} ${direction}`);
|
|
474
|
-
const limit = input.limit ?? LIST_DEFAULT_LIMIT;
|
|
475
|
-
const rows = indexOrdered(object, field2) ? await q.limit(limit + 1).execute() : await pageByIds(query, q, alias, field2.column, limit + 1);
|
|
476
|
-
const page = rows.slice(0, limit);
|
|
477
|
-
const last = page.at(-1);
|
|
478
|
-
let nextCursor = null;
|
|
479
|
-
if (rows.length > limit && last) {
|
|
480
|
-
const value = last[field2.column];
|
|
481
|
-
nextCursor = encodeCursor({
|
|
482
|
-
f: sort.field,
|
|
483
|
-
d: sort.direction,
|
|
484
|
-
v: typeof value === "string" || typeof value === "number" ? value : null,
|
|
485
|
-
id: last.id
|
|
486
|
-
});
|
|
487
|
-
}
|
|
488
|
-
return { rows: page, nextCursor };
|
|
489
|
-
}
|
|
490
|
-
function selectFields(items, fields, allowed) {
|
|
491
|
-
if (!fields) return items;
|
|
492
|
-
const unknown = fields.filter((name) => !allowed.includes(name));
|
|
493
|
-
if (unknown.length) throw new ValidationError(`Unknown fields: ${unknown.join(", ")}`);
|
|
494
|
-
const keep = /* @__PURE__ */ new Set(["id", ...fields]);
|
|
495
|
-
return items.map(
|
|
496
|
-
(item) => Object.fromEntries(Object.entries(item).filter(([key]) => keep.has(key)))
|
|
497
|
-
);
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
// ../core/src/visibility/access.ts
|
|
501
|
-
var kinds = /* @__PURE__ */ new Map();
|
|
502
|
-
function registerAccessSource(kind, implementation) {
|
|
503
|
-
if (kind === "record") throw new Error("The record kind is the host's own");
|
|
504
|
-
kinds.set(kind, implementation);
|
|
505
|
-
}
|
|
506
|
-
function hasAccessSourceKind(kind) {
|
|
507
|
-
return kind === "record" || kinds.has(kind);
|
|
508
|
-
}
|
|
509
|
-
var kindOf = (source) => source.kind ?? "record";
|
|
510
|
-
function accessProblems(object) {
|
|
511
|
-
const declared = object.access;
|
|
512
|
-
if (!declared) return [];
|
|
513
|
-
if (!declared.sources.length) return ["access declares at least one source"];
|
|
514
|
-
const problems = [];
|
|
515
|
-
declared.sources.forEach((source, i) => {
|
|
516
|
-
const kind = kindOf(source);
|
|
517
|
-
const implementation = kind === "record" ? RECORD_KIND : kinds.get(kind);
|
|
518
|
-
if (!implementation) {
|
|
519
|
-
problems.push(`access.sources.${i}: the host has no source of kind "${kind}"`);
|
|
520
|
-
return;
|
|
521
|
-
}
|
|
522
|
-
for (const p of implementation.problems(object, source)) {
|
|
523
|
-
problems.push(`access.sources.${i}: ${p}`);
|
|
524
|
-
}
|
|
525
|
-
});
|
|
526
|
-
return problems;
|
|
527
|
-
}
|
|
528
|
-
async function holdsAccess(reader, object, ids, now = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
529
|
-
const principal = reader.principal;
|
|
530
|
-
if (principal.kind === "staff") return new Set(ids);
|
|
531
|
-
const definition = getObject(object.name) ?? object;
|
|
532
|
-
const declared = definition.access;
|
|
533
|
-
if (principal.kind !== "customer" || !declared || !ids.length) return /* @__PURE__ */ new Set();
|
|
534
|
-
const problems = accessProblems(definition);
|
|
535
|
-
if (problems.length) {
|
|
536
|
-
throw new Error(`${definition.name}: invalid access declaration: ${problems.join("; ")}`);
|
|
537
|
-
}
|
|
538
|
-
const query = {
|
|
539
|
-
db: reader.db,
|
|
540
|
-
personId: principal.personId,
|
|
541
|
-
now,
|
|
542
|
-
object: definition,
|
|
543
|
-
ids: [...new Set(ids)]
|
|
544
|
-
};
|
|
545
|
-
const held = /* @__PURE__ */ new Set();
|
|
546
|
-
for (const source of declared.sources) {
|
|
547
|
-
const kind = kindOf(source);
|
|
548
|
-
const implementation = kind === "record" ? RECORD_KIND : kinds.get(kind);
|
|
549
|
-
if (!implementation) continue;
|
|
550
|
-
const left = query.ids.filter((id) => !held.has(id));
|
|
551
|
-
if (!left.length) break;
|
|
552
|
-
for (const id of await implementation.holders({ ...query, ids: left }, source)) {
|
|
553
|
-
if (left.includes(id)) held.add(id);
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
return held;
|
|
557
|
-
}
|
|
558
|
-
var field = (object, name) => object.fields.find((f) => f.name === name);
|
|
559
|
-
function resolveRecordSource(object, source) {
|
|
560
|
-
const via = getObject(source.via);
|
|
561
|
-
if (!via || via.name === object.name || !object.extension || via.extension !== object.extension) {
|
|
562
|
-
return `via "${source.via}" must be another object of the same extension`;
|
|
563
|
-
}
|
|
564
|
-
const ownerField = via.customer ? field(via, via.customer.field) : void 0;
|
|
565
|
-
const owner = ownerField ? viewColumnOf(ownerField) : null;
|
|
566
|
-
if (!via.customer || !owner) return `via "${source.via}" must declare a customer`;
|
|
567
|
-
const pointerField = field(via, source.field);
|
|
568
|
-
const pointer = pointerField ? viewColumnOf(pointerField) : null;
|
|
569
|
-
if (!pointer || pointerField?.fieldType !== "relation" || pointerField.options?.many) {
|
|
570
|
-
return `field "${source.field}" must be a relation of ${via.name} to one record`;
|
|
571
|
-
}
|
|
572
|
-
let through = null;
|
|
573
|
-
if (source.through === void 0) {
|
|
574
|
-
if (pointerField.options?.to !== object.name) {
|
|
575
|
-
return `field "${source.field}" must be a relation of ${via.name} to one ${object.name}`;
|
|
576
|
-
}
|
|
577
|
-
} else {
|
|
578
|
-
const target = getObject(String(pointerField.options?.to));
|
|
579
|
-
const list2 = target ? field(target, source.through) : void 0;
|
|
580
|
-
const column = list2 ? viewColumnOf(list2) : null;
|
|
581
|
-
const lists = list2?.fieldType === "relation" && list2.options?.many === true && list2.options?.to === object.name || list2?.fieldType === "document";
|
|
582
|
-
if (!target || !list2 || !column || !lists) {
|
|
583
|
-
return `through "${source.through}" must be a many relation to ${object.name}, or a document naming it, on the record ${source.field} points to`;
|
|
584
|
-
}
|
|
585
|
-
const published = Boolean(
|
|
586
|
-
target.publishable && target.public && target.publishable.content.includes(list2.name)
|
|
587
|
-
);
|
|
588
|
-
through = { view: published ? liveViewOf(target.name) : target.source, column, field: list2 };
|
|
589
|
-
}
|
|
590
|
-
let state = null;
|
|
591
|
-
if (via.states) {
|
|
592
|
-
const stateField = field(via, via.states.field);
|
|
593
|
-
const column = stateField ? viewColumnOf(stateField) : null;
|
|
594
|
-
if (!column) return `${via.name} has no state column`;
|
|
595
|
-
if (!source.states?.length) return `${via.name} has states: name the ones that give access`;
|
|
596
|
-
state = { column, values: source.states };
|
|
597
|
-
} else if (source.states?.length) {
|
|
598
|
-
return `${via.name} has no states`;
|
|
599
|
-
}
|
|
600
|
-
let until = null;
|
|
601
|
-
if (source.until !== void 0) {
|
|
602
|
-
const untilField = field(via, source.until);
|
|
603
|
-
const column = untilField ? viewColumnOf(untilField) : null;
|
|
604
|
-
if (!column || untilField?.fieldType !== "date" && untilField?.fieldType !== "datetime") {
|
|
605
|
-
return `until "${source.until}" must be a date or datetime field of ${via.name}`;
|
|
606
|
-
}
|
|
607
|
-
until = { column, date: untilField.fieldType === "date" };
|
|
608
|
-
}
|
|
609
|
-
return { view: via.source, owner, pointer, state, until, through };
|
|
610
|
-
}
|
|
611
|
-
function pointersSql(resolved, query) {
|
|
612
|
-
const conditions = [
|
|
613
|
-
sql`${sql.ref(resolved.owner)} = ${query.personId}`,
|
|
614
|
-
sql`${sql.ref(resolved.pointer)} IS NOT NULL`
|
|
615
|
-
];
|
|
616
|
-
if (resolved.state) {
|
|
617
|
-
conditions.push(
|
|
618
|
-
sql`${sql.ref(resolved.state.column)} IN (${sql.join(resolved.state.values.map((v) => sql`${v}`))})`
|
|
619
|
-
);
|
|
620
|
-
}
|
|
621
|
-
if (resolved.until) {
|
|
622
|
-
const bound = resolved.until.date ? query.now.slice(0, 10) : query.now;
|
|
623
|
-
const op = resolved.until.date ? sql`>=` : sql`>`;
|
|
624
|
-
conditions.push(
|
|
625
|
-
sql`(${sql.ref(resolved.until.column)} IS NULL OR ${sql.ref(resolved.until.column)} = '' OR ${sql.ref(resolved.until.column)} ${op} ${bound})`
|
|
626
|
-
);
|
|
627
|
-
}
|
|
628
|
-
return sql`SELECT DISTINCT ${sql.ref(resolved.pointer)} AS id FROM ${sql.table(resolved.view)} WHERE ${sql.join(conditions, sql` AND `)}`;
|
|
629
|
-
}
|
|
630
|
-
var RECORD_KIND = {
|
|
631
|
-
problems(object, source) {
|
|
632
|
-
if (source.via === void 0) return ["a record source names via"];
|
|
633
|
-
const resolved = resolveRecordSource(object, source);
|
|
634
|
-
return typeof resolved === "string" ? [resolved] : [];
|
|
635
|
-
},
|
|
636
|
-
async holders(query, source) {
|
|
637
|
-
if (source.via === void 0) return /* @__PURE__ */ new Set();
|
|
638
|
-
const resolved = resolveRecordSource(query.object, source);
|
|
639
|
-
if (typeof resolved === "string") return /* @__PURE__ */ new Set();
|
|
640
|
-
const pointers = pointersSql(resolved, query);
|
|
641
|
-
if (!resolved.through) {
|
|
642
|
-
const rows2 = await sql`SELECT id FROM (${pointers}) WHERE id IN (${sql.join(
|
|
643
|
-
query.ids.map((id) => sql`${id}`)
|
|
644
|
-
)})`.execute(query.db);
|
|
645
|
-
return new Set(rows2.rows.map((r) => String(r.id)));
|
|
646
|
-
}
|
|
647
|
-
const { view, column, field: list2 } = resolved.through;
|
|
648
|
-
const rows = await sql`SELECT ${sql.ref(column)} AS value FROM ${sql.table(view)} WHERE id IN (${pointers})`.execute(
|
|
649
|
-
query.db
|
|
650
|
-
);
|
|
651
|
-
const wanted = new Set(query.ids);
|
|
652
|
-
const held = /* @__PURE__ */ new Set();
|
|
653
|
-
for (const { value } of rows.rows) {
|
|
654
|
-
for (const id of listed(list2, value, query.object.name)) if (wanted.has(id)) held.add(id);
|
|
655
|
-
}
|
|
656
|
-
return held;
|
|
657
|
-
}
|
|
658
|
-
};
|
|
659
|
-
function listed(list2, stored, object) {
|
|
660
|
-
let value = stored;
|
|
661
|
-
if (typeof stored === "string") {
|
|
662
|
-
try {
|
|
663
|
-
value = JSON.parse(stored);
|
|
664
|
-
} catch {
|
|
665
|
-
return [];
|
|
666
|
-
}
|
|
667
|
-
}
|
|
668
|
-
if (list2.fieldType === "relation") {
|
|
669
|
-
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
670
|
-
}
|
|
671
|
-
const schema = list2.options?.document?.schema;
|
|
672
|
-
if (!schema || value === null || value === void 0) return [];
|
|
673
|
-
return documentRefs(schema, value).filter((ref) => ref.to === object).map((ref) => ref.id);
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
export {
|
|
677
|
-
TRASH_RETENTION_DAYS,
|
|
678
|
-
restorableUntil,
|
|
679
|
-
purgeCutoff,
|
|
680
|
-
BATCH_MAX,
|
|
681
|
-
jsonList,
|
|
682
|
-
chunk,
|
|
683
|
-
blankToNull,
|
|
684
|
-
assertUserExists,
|
|
685
|
-
withPrimary,
|
|
686
|
-
uniqueIds,
|
|
687
|
-
notifyStatements,
|
|
688
|
-
filterSchema,
|
|
689
|
-
OPS_BY_TYPE,
|
|
690
|
-
compileFilter,
|
|
691
|
-
registerAccessSource,
|
|
692
|
-
hasAccessSourceKind,
|
|
693
|
-
holdsAccess,
|
|
694
|
-
sortSchema,
|
|
695
|
-
LIST_MAX_LIMIT,
|
|
696
|
-
listInputSchema,
|
|
697
|
-
pageSchema,
|
|
698
|
-
encodeCursor,
|
|
699
|
-
decodeCursor,
|
|
700
|
-
resolveSort,
|
|
701
|
-
runListQuery,
|
|
702
|
-
pageQuery,
|
|
703
|
-
selectFields
|
|
704
|
-
};
|