@ai-matrx/records 0.96.14 → 0.97.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/{client-D7bvxEZW.d.ts → client-MVuEbxKl.d.ts} +6 -0
  3. package/dist/{client-DKgbZUNt.d.cts → client-pFV_8AhM.d.cts} +6 -0
  4. package/dist/core/index.cjs +637 -3
  5. package/dist/core/index.cjs.map +1 -1
  6. package/dist/core/index.d.cts +3 -2
  7. package/dist/core/index.d.ts +3 -2
  8. package/dist/core/index.js +637 -3
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/data/index.cjs +634 -0
  11. package/dist/data/index.cjs.map +1 -1
  12. package/dist/data/index.d.cts +2 -1
  13. package/dist/data/index.d.ts +2 -1
  14. package/dist/data/index.js +634 -0
  15. package/dist/data/index.js.map +1 -1
  16. package/dist/{declareTable-VoNRi_j_.d.cts → declareTable-Bekj6UwK.d.cts} +1 -1
  17. package/dist/{declareTable-D_CiMnXM.d.ts → declareTable-C7zVyyLA.d.ts} +1 -1
  18. package/dist/doors-C43_5HjC.d.ts +487 -0
  19. package/dist/doors-CJPHsohF.d.cts +487 -0
  20. package/dist/questions/index.d.cts +2 -1
  21. package/dist/questions/index.d.ts +2 -1
  22. package/dist/react/index.cjs +637 -3
  23. package/dist/react/index.cjs.map +1 -1
  24. package/dist/react/index.d.cts +338 -5
  25. package/dist/react/index.d.ts +338 -5
  26. package/dist/react/index.js +637 -3
  27. package/dist/react/index.js.map +1 -1
  28. package/dist/scopes/index.cjs +729 -0
  29. package/dist/scopes/index.cjs.map +1 -0
  30. package/dist/scopes/index.d.cts +33 -0
  31. package/dist/scopes/index.d.ts +33 -0
  32. package/dist/scopes/index.js +706 -0
  33. package/dist/scopes/index.js.map +1 -0
  34. package/dist/setup/index.cjs +634 -0
  35. package/dist/setup/index.cjs.map +1 -1
  36. package/dist/setup/index.d.cts +2 -1
  37. package/dist/setup/index.d.ts +2 -1
  38. package/dist/setup/index.js +634 -0
  39. package/dist/setup/index.js.map +1 -1
  40. package/dist/typed-table/index.cjs +634 -0
  41. package/dist/typed-table/index.cjs.map +1 -1
  42. package/dist/typed-table/index.d.cts +3 -2
  43. package/dist/typed-table/index.d.ts +3 -2
  44. package/dist/typed-table/index.js +634 -0
  45. package/dist/typed-table/index.js.map +1 -1
  46. package/dist/views/index.d.cts +2 -1
  47. package/dist/views/index.d.ts +2 -1
  48. package/package.json +13 -3
@@ -258,7 +258,7 @@ __export(react_exports, {
258
258
  safeLinkHref: () => safeLinkHref,
259
259
  sameDocument: () => sameDocument,
260
260
  scopeChip: () => scopeChip,
261
- sha256Hex: () => sha256Hex,
261
+ sha256Hex: () => sha256Hex2,
262
262
  sheetSyncSpec: () => sheetSyncSpec,
263
263
  sourceArchivedOf: () => sourceArchivedOf,
264
264
  splitListCell: () => splitListCell,
@@ -880,6 +880,639 @@ function rememberedOpCount() {
880
880
  return defaultOpLedger.size;
881
881
  }
882
882
 
883
+ // src/scopes/codec.ts
884
+ var str = (v, fallback = "") => typeof v === "string" ? v : fallback;
885
+ var strOrNull = (v) => typeof v === "string" ? v : null;
886
+ var num = (v, fallback = 0) => {
887
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
888
+ return Number.isFinite(n) ? n : fallback;
889
+ };
890
+ function scopeTypeFromStore(row) {
891
+ const singular = row.label_singular ?? row.name ?? "";
892
+ return {
893
+ id: row.id,
894
+ organization_id: row.organization_id,
895
+ label_singular: singular,
896
+ label_plural: row.label_plural ?? singular,
897
+ icon: row.icon ?? "folder",
898
+ color: row.color ?? "",
899
+ slug: row.slug ?? null,
900
+ description: row.description ?? "",
901
+ sort_order: num(row.sort_order),
902
+ max_assignments_per_entity: row.max_assignments_per_entity ?? null,
903
+ default_variable_keys: Array.isArray(row.default_variable_keys) ? row.default_variable_keys : [],
904
+ created_by: row.created_by ?? null,
905
+ created_at: row.created_at ?? "",
906
+ updated_at: row.updated_at ?? ""
907
+ };
908
+ }
909
+ function scopeTypeLabelFromStore(t) {
910
+ const singular = t.label_singular ?? t.name ?? "";
911
+ return { id: t.id, label_singular: singular, label_plural: t.label_plural ?? singular, icon: t.icon ?? null, color: t.color ?? null };
912
+ }
913
+ function settingFromStore(value) {
914
+ if (!Array.isArray(value)) return value;
915
+ return value.map((el) => {
916
+ if (typeof el !== "string") return el;
917
+ const t = el.trim();
918
+ if (!(t.startsWith("{") && t.endsWith("}")) && !(t.startsWith("[") && t.endsWith("]"))) return el;
919
+ try {
920
+ return JSON.parse(t);
921
+ } catch {
922
+ return el;
923
+ }
924
+ });
925
+ }
926
+ function scopeFromStore(row) {
927
+ const settings = {};
928
+ for (const [k, v] of Object.entries(row.settings ?? {})) settings[k] = settingFromStore(v);
929
+ return {
930
+ id: row.id,
931
+ scope_type_id: row.scope_type_id,
932
+ organization_id: row.organization_id,
933
+ name: row.name ?? "",
934
+ description: row.description ?? "",
935
+ slug: row.slug ?? null,
936
+ sort_order: num(row.sort_order),
937
+ parent_scope_id: row.parent_scope_id ?? null,
938
+ settings,
939
+ created_by: row.created_by ?? null,
940
+ created_at: row.created_at ?? "",
941
+ updated_at: row.updated_at ?? ""
942
+ };
943
+ }
944
+ function scopeWithTypeFromStore(row) {
945
+ return { ...scopeFromStore(row), scope_type: row.scope_type ? scopeTypeLabelFromStore(row.scope_type) : null };
946
+ }
947
+ function archivedScopeTypeFromStore(row) {
948
+ const singular = row.label_singular ?? "";
949
+ return {
950
+ id: row.id,
951
+ organization_id: row.organization_id,
952
+ label_singular: singular,
953
+ label_plural: row.label_plural ?? singular,
954
+ icon: row.icon ?? "folder",
955
+ color: row.color ?? "",
956
+ archived_at: row.deleted_at ?? "",
957
+ created_by: row.created_by ?? null,
958
+ archived_scope_count: row.archived_scope_count ?? 0
959
+ };
960
+ }
961
+ var FILE_KERNEL_ID = "11111111-0000-4000-8000-000000000006";
962
+ var KINDS = /* @__PURE__ */ new Set([
963
+ "string",
964
+ "markdown",
965
+ "email",
966
+ "url",
967
+ "phone",
968
+ "color",
969
+ "number",
970
+ "percent",
971
+ "currency",
972
+ "boolean",
973
+ "date",
974
+ "datetime",
975
+ "time",
976
+ "object",
977
+ "array",
978
+ "reference",
979
+ "document"
980
+ ]);
981
+ function contextFieldKind(doc, carried) {
982
+ if (carried?.as_text && carried.value_type && KINDS.has(carried.value_type)) return carried.value_type;
983
+ const behavior = String(doc.type ?? "text");
984
+ const fmt = doc.format ? String(doc.format) : "";
985
+ const shown = doc.display_format && typeof doc.display_format === "object" ? String(doc.display_format.id ?? "") : "";
986
+ const kind = String(doc.config?.kind ?? "");
987
+ const multi = Boolean(doc.multi);
988
+ if (behavior === "boolean") return "boolean";
989
+ if (behavior === "relation") return doc.relation_target === FILE_KERNEL_ID && !multi ? "document" : "reference";
990
+ if (behavior === "range") {
991
+ if (kind === "date") return "date";
992
+ if (kind === "datetime") return "datetime";
993
+ if (fmt === "percent" || fmt === "currency") return fmt;
994
+ return "number";
995
+ }
996
+ if (behavior === "text") {
997
+ if (multi) return "array";
998
+ if (fmt === "json") return "object";
999
+ for (const word of [fmt, shown]) {
1000
+ if (word === "time" || word === "email" || word === "url" || word === "phone" || word === "color" || word === "markdown") return word;
1001
+ }
1002
+ }
1003
+ return "string";
1004
+ }
1005
+ var POLICIES = /* @__PURE__ */ new Set(["include", "on_request", "exclude"]);
1006
+ var SENSITIVITIES = /* @__PURE__ */ new Set(["public", "internal", "confidential", "restricted"]);
1007
+ function contextFieldFromStore(row) {
1008
+ const d = row.data ?? {};
1009
+ const key = str(d.key);
1010
+ const policy = str(d.context_policy, "include");
1011
+ const sensitivity = str(d.sensitivity, "internal");
1012
+ return {
1013
+ id: row.id,
1014
+ scope_type_id: row.scope_type_id,
1015
+ organization_id: row.organization_id,
1016
+ key,
1017
+ label: str(d.label, key),
1018
+ description: str(d.description),
1019
+ kind: contextFieldKind(d, row.carried),
1020
+ type: str(d.type, "text"),
1021
+ multi: Boolean(d.multi),
1022
+ format: strOrNull(d.format),
1023
+ config: d.config ?? {},
1024
+ relation_target: strOrNull(d.relation_target),
1025
+ // The store's sort counts the scope's own two columns first (custom._ctx_store_item: + 2).
1026
+ sort: Math.max(0, num(d.sort) - 2),
1027
+ context_policy: POLICIES.has(policy) ? policy : "include",
1028
+ sensitivity: SENSITIVITIES.has(sensitivity) ? sensitivity : "internal",
1029
+ source: str(d.source, "manual"),
1030
+ status: str(d.status, "active"),
1031
+ status_note: strOrNull(d.status_note),
1032
+ category: strOrNull(d.category),
1033
+ tags: Array.isArray(d.tags) ? d.tags : [],
1034
+ max_items: typeof d.max_items === "number" ? d.max_items : 1,
1035
+ custom_component: d.custom_component ?? null,
1036
+ reference_source: d.reference_source ?? null,
1037
+ allowed_scope_type_ids: Array.isArray(d.allowed_scope_type_ids) ? d.allowed_scope_type_ids : null,
1038
+ allowed_reference_types: Array.isArray(d.allowed_reference_types) ? d.allowed_reference_types : null,
1039
+ review_interval_days: typeof d.review_interval_days === "number" ? d.review_interval_days : null,
1040
+ depends_on: Array.isArray(d.depends_on) ? d.depends_on : [],
1041
+ version: num(row.version, 1),
1042
+ created_by: row.created_by ?? null,
1043
+ created_at: row.created_at ?? "",
1044
+ updated_at: row.updated_at ?? ""
1045
+ };
1046
+ }
1047
+ var POLICY_TO_DOOR = { include: "always", on_request: "on_demand", exclude: "never" };
1048
+ var SENSITIVITY_TO_DOOR = {
1049
+ public: "public",
1050
+ internal: "internal",
1051
+ confidential: "restricted",
1052
+ restricted: "privileged"
1053
+ };
1054
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1055
+ function referencesOf(row) {
1056
+ const v = row.value;
1057
+ const list = Array.isArray(v) ? v : v == null ? [] : [v];
1058
+ const labels = row.labels ?? {};
1059
+ const files = row.files ?? {};
1060
+ const toFile = row.field?.relation_target === FILE_KERNEL_ID;
1061
+ const out = [];
1062
+ for (const el of list) {
1063
+ let ref = null;
1064
+ if (typeof el === "string" && UUID.test(el)) ref = { id: el, type: toFile ? "file" : "scope" };
1065
+ else if (el && typeof el === "object" && typeof el.id === "string") {
1066
+ const token = String(el.token ?? "");
1067
+ const own = el.label;
1068
+ ref = { id: el.id, type: token === "dataset" ? "table" : token || (toFile ? "file" : "scope") };
1069
+ if (typeof own === "string" && own) ref.label = own;
1070
+ }
1071
+ if (!ref) continue;
1072
+ const label = labels[ref.id];
1073
+ if (label) ref.label = label;
1074
+ const fileId = files[ref.id];
1075
+ if (fileId) ref.file_id = fileId;
1076
+ out.push(ref);
1077
+ }
1078
+ return out;
1079
+ }
1080
+ function contextValueFromStore(row) {
1081
+ const kind = contextFieldKind(row.field ?? {}, row.field?.carried);
1082
+ const carriedText = Boolean(row.field?.carried?.as_text);
1083
+ const isRef = !carriedText && (kind === "reference" || kind === "document");
1084
+ return {
1085
+ scope_id: row.scope_id,
1086
+ field_id: row.context_item_id,
1087
+ key: row.key,
1088
+ kind,
1089
+ value: row.value ?? null,
1090
+ references: isRef ? referencesOf(row) : [],
1091
+ version: num(row.version, 1),
1092
+ set_at: row.set_at ?? null,
1093
+ source_type: row.source_type ?? null,
1094
+ authored_by: row.authored_by ?? null,
1095
+ whole_value: row.whole_value ?? null,
1096
+ incomplete: null
1097
+ };
1098
+ }
1099
+ async function sha256Hex(text2) {
1100
+ const subtle = globalThis.crypto?.subtle;
1101
+ if (!subtle) return null;
1102
+ const digest = await subtle.digest("SHA-256", new TextEncoder().encode(text2));
1103
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
1104
+ }
1105
+ async function completeWholeValues(values, read) {
1106
+ const texts = /* @__PURE__ */ new Map();
1107
+ await Promise.all(
1108
+ values.map(async (cell) => {
1109
+ const w = cell.whole_value;
1110
+ if (!w || w.in_value || typeof cell.value !== "string") return;
1111
+ const head = cell.value;
1112
+ const chars = typeof w.chars === "number" ? w.chars : null;
1113
+ const incomplete = (fileId, why) => {
1114
+ cell.incomplete = { head, chars, file_id: fileId, why };
1115
+ };
1116
+ if (!w.file_id) return incomplete(null, "The rest of this text is still being saved.");
1117
+ if (!read) return incomplete(w.file_id, "This place cannot open the file that holds the whole text.");
1118
+ if (!texts.has(w.file_id)) texts.set(w.file_id, read(w.file_id));
1119
+ try {
1120
+ const text2 = await texts.get(w.file_id);
1121
+ if (chars !== null && [...text2].length !== chars) {
1122
+ return incomplete(w.file_id, `The file holds ${[...text2].length} characters, not ${chars}.`);
1123
+ }
1124
+ if (w.sha256) {
1125
+ const sha = await sha256Hex(text2);
1126
+ if (sha === null) return incomplete(w.file_id, "This browser cannot check the file.");
1127
+ if (sha !== w.sha256) return incomplete(w.file_id, "The file's content is not the text the cell points at.");
1128
+ }
1129
+ cell.value = text2;
1130
+ } catch (thrown) {
1131
+ incomplete(w.file_id, thrown instanceof Error ? thrown.message : String(thrown));
1132
+ }
1133
+ })
1134
+ );
1135
+ }
1136
+ function definedOnly(fields) {
1137
+ const out = {};
1138
+ for (const [k, v] of Object.entries(fields)) if (v !== void 0) out[k] = v;
1139
+ return out;
1140
+ }
1141
+ function fieldSpecForDoor(spec) {
1142
+ return definedOnly({
1143
+ key: spec.key,
1144
+ display_name: spec.label,
1145
+ value_type: spec.kind,
1146
+ description: spec.description,
1147
+ category: spec.category,
1148
+ fetch_hint: spec.context_policy ? POLICY_TO_DOOR[spec.context_policy] : void 0,
1149
+ sensitivity: spec.sensitivity ? SENSITIVITY_TO_DOOR[spec.sensitivity] : void 0,
1150
+ tags: spec.tags,
1151
+ sort_order: spec.sort,
1152
+ status: spec.status,
1153
+ status_note: spec.status_note,
1154
+ custom_component: spec.custom_component,
1155
+ review_interval_days: spec.review_interval_days,
1156
+ allowed_reference_types: spec.allowed_reference_types,
1157
+ max_items: spec.max_items,
1158
+ allowed_scope_type_ids: spec.allowed_scope_type_ids,
1159
+ reference_source: spec.reference_source
1160
+ });
1161
+ }
1162
+ function referenceFence(references) {
1163
+ const kinds = [...new Set(references.map((r) => r.type))];
1164
+ const type = kinds.length === 1 ? kinds[0] : "mixed";
1165
+ const items = references.map((r) => {
1166
+ if (r.type === "file" && r.file_id) return r.label ? { file_id: r.file_id, label: r.label } : { file_id: r.file_id };
1167
+ const item2 = { id: r.id };
1168
+ if (r.label) item2.label = r.label;
1169
+ if (kinds.length > 1) item2.type = r.type;
1170
+ return item2;
1171
+ });
1172
+ return "```matrx\n" + JSON.stringify({ matrx_version: 1, kind: "reference", type, items }, null, 2) + "\n```";
1173
+ }
1174
+ function valuePayloadForDoor(write) {
1175
+ const base = definedOnly({
1176
+ scope_id: write.scope_id,
1177
+ context_item_id: write.field_id,
1178
+ source_type: write.source_type,
1179
+ change_summary: write.change_summary
1180
+ });
1181
+ const v = write.value;
1182
+ if (write.kind === "reference" || write.kind === "document") {
1183
+ if (write.references) return { ...base, value_text: write.references.length ? referenceFence(write.references) : null };
1184
+ if (write.kind === "document" && typeof v === "string") return { ...base, value_document_url: v || null };
1185
+ return { ...base, value_text: typeof v === "string" ? v || null : null };
1186
+ }
1187
+ if (v === null || v === void 0 || v === "") {
1188
+ return { ...base, value_text: null };
1189
+ }
1190
+ switch (write.kind) {
1191
+ case "number":
1192
+ case "percent":
1193
+ return typeof v === "number" ? { ...base, value_number: v } : { ...base, value_text: String(v) };
1194
+ case "currency":
1195
+ return typeof v === "object" ? { ...base, value_json: v } : typeof v === "number" ? { ...base, value_number: v } : { ...base, value_text: String(v) };
1196
+ case "boolean":
1197
+ return typeof v === "boolean" ? { ...base, value_boolean: v } : { ...base, value_text: String(v) };
1198
+ case "date":
1199
+ return { ...base, value_date: String(v) };
1200
+ case "datetime":
1201
+ return { ...base, value_timestamp: String(v) };
1202
+ case "time":
1203
+ return { ...base, value_time: String(v) };
1204
+ case "object":
1205
+ case "array":
1206
+ return typeof v === "object" ? { ...base, value_json: v } : { ...base, value_text: String(v) };
1207
+ default:
1208
+ return typeof v === "object" ? { ...base, value_json: v } : { ...base, value_text: String(v) };
1209
+ }
1210
+ }
1211
+
1212
+ // src/scopes/rules.ts
1213
+ function toSlug(name) {
1214
+ return name.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
1215
+ }
1216
+ function isValidSlug(s) {
1217
+ return /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(s);
1218
+ }
1219
+ var RESERVED_SCOPE_SLUGS = /* @__PURE__ */ new Set(["context-items", "scopes", "edit", "manage", "new", "settings"]);
1220
+ function isReservedSlug(s) {
1221
+ return RESERVED_SCOPE_SLUGS.has(s.toLowerCase().replace(/_/g, "-"));
1222
+ }
1223
+ function resolveSlug(supplied, fallbackName) {
1224
+ const slug = supplied?.trim() || toSlug(fallbackName);
1225
+ if (!slug || !isValidSlug(slug)) {
1226
+ return {
1227
+ ok: false,
1228
+ error: { code: "invalid_argument", message: "Use letters, numbers and single hyphens for the short name." }
1229
+ };
1230
+ }
1231
+ if (isReservedSlug(slug)) {
1232
+ return { ok: false, error: { code: "invalid_argument", message: `"${slug}" is a page name here. Pick another short name.` } };
1233
+ }
1234
+ return { ok: true, data: slug };
1235
+ }
1236
+
1237
+ // src/scopes/doors.ts
1238
+ var SCOPES_PER_CALL = 500;
1239
+ var SCOPE_TYPES_PER_FIELDS_CALL = 100;
1240
+ var SCOPES_PER_VALUES_CALL = 200;
1241
+ var TYPE_SCOPES_PAGE = 200;
1242
+ var ARCHIVED_SCOPES_PAGE = 200;
1243
+ var uniq = (ids) => [...new Set(ids.filter(Boolean))];
1244
+ async function inBatches(ids, size, call) {
1245
+ const unique = uniq(ids);
1246
+ const batches = [];
1247
+ for (let i = 0; i < unique.length; i += size) batches.push(unique.slice(i, i + size));
1248
+ const answers = await Promise.all(batches.map(call));
1249
+ const out = [];
1250
+ for (const a of answers) {
1251
+ if (!a.ok) return a;
1252
+ out.push(...a.data ?? []);
1253
+ }
1254
+ return { ok: true, data: out };
1255
+ }
1256
+ function noRow(door) {
1257
+ return { ok: false, error: { code: "internal", message: `${door} answered without the row it wrote.`, diagnostic: `@ai-matrx/records/scopes: ${door}` } };
1258
+ }
1259
+ var VALUE_DOOR_CODES = {
1260
+ unauthorized: "door",
1261
+ forbidden: "door",
1262
+ forbidden_org: "door",
1263
+ not_found: "not_found",
1264
+ invalid_argument: "invalid_argument",
1265
+ conflict: "stale_write",
1266
+ unavailable: "not_supported"
1267
+ };
1268
+ function createScopeDoors(call) {
1269
+ async function write(door, args) {
1270
+ const res = await call(door, args, `scopes.${door}`);
1271
+ if (!res.ok) return res;
1272
+ const row = res.data?.row;
1273
+ if (!row || typeof row !== "object") return noRow(door);
1274
+ return { ok: true, data: row };
1275
+ }
1276
+ async function archiveOrRestore(door, args, id) {
1277
+ const res = await call(door, args, `scopes.${door}`);
1278
+ return res.ok ? { ok: true, data: { id } } : res;
1279
+ }
1280
+ async function fieldById(scopeTypeId, fieldId, door) {
1281
+ const fields = await doors.fields([scopeTypeId]);
1282
+ if (!fields.ok) return fields;
1283
+ const field2 = fields.data.find((f2) => f2.id === fieldId);
1284
+ return field2 ? { ok: true, data: field2 } : noRow(door);
1285
+ }
1286
+ const doors = {
1287
+ async tree(organizationIds) {
1288
+ const ids = uniq(organizationIds);
1289
+ if (ids.length === 0) return { ok: true, data: [] };
1290
+ const res = await call("context_tree", { p_organization_ids: ids }, "scopes.tree");
1291
+ if (!res.ok) return res;
1292
+ const byType = /* @__PURE__ */ new Map();
1293
+ for (const s of res.data?.scopes ?? []) {
1294
+ const scope = scopeFromStore(s);
1295
+ const list = byType.get(scope.scope_type_id) ?? [];
1296
+ list.push(scope);
1297
+ byType.set(scope.scope_type_id, list);
1298
+ }
1299
+ return { ok: true, data: (res.data?.types ?? []).map((t) => ({ ...scopeTypeFromStore(t), scopes: byType.get(t.id) ?? [] })) };
1300
+ },
1301
+ async types(organizationIds, options) {
1302
+ const withCounts = options?.withCounts ?? true;
1303
+ const ids = uniq(organizationIds);
1304
+ if (ids.length === 0) return { ok: true, data: { types: [], counts: withCounts ? {} : null } };
1305
+ const res = await call("context_tree_types", { p_organization_ids: ids, p_with_counts: withCounts }, "scopes.types");
1306
+ if (!res.ok) return res;
1307
+ const rows = res.data?.types ?? [];
1308
+ const counts = withCounts ? {} : null;
1309
+ if (counts) for (const r of rows) counts[r.id] = Number(r.scope_count ?? 0);
1310
+ return { ok: true, data: { types: rows.map(scopeTypeFromStore), counts } };
1311
+ },
1312
+ async typeScopesPage(scopeTypeId, offset = 0, limit = TYPE_SCOPES_PAGE) {
1313
+ const res = await call(
1314
+ "context_tree_type_scopes",
1315
+ { p_scope_type_id: scopeTypeId, p_offset: offset, p_limit: limit },
1316
+ "scopes.typeScopesPage"
1317
+ );
1318
+ if (!res.ok) return res;
1319
+ return {
1320
+ ok: true,
1321
+ data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0), next_offset: res.data?.next_offset ?? null }
1322
+ };
1323
+ },
1324
+ async search(organizationIds, query, limit = 100) {
1325
+ const ids = uniq(organizationIds);
1326
+ const q = query.trim();
1327
+ if (ids.length === 0 || q === "") return { ok: true, data: { scopes: [], total: 0 } };
1328
+ const res = await call(
1329
+ "context_tree_search",
1330
+ { p_organization_ids: ids, p_query: q, p_limit: limit },
1331
+ "scopes.search"
1332
+ );
1333
+ if (!res.ok) return res;
1334
+ return { ok: true, data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0) } };
1335
+ },
1336
+ async scopes(ids) {
1337
+ const res = await inBatches(ids, SCOPES_PER_CALL, (batch) => call("context_scopes", { p_scope_ids: batch }, "scopes.scopes"));
1338
+ return res.ok ? { ok: true, data: res.data.map(scopeWithTypeFromStore) } : res;
1339
+ },
1340
+ async fields(scopeTypeIds) {
1341
+ const res = await inBatches(
1342
+ scopeTypeIds,
1343
+ SCOPE_TYPES_PER_FIELDS_CALL,
1344
+ (batch) => call("context_items", { p_scope_type_ids: batch }, "scopes.fields")
1345
+ );
1346
+ return res.ok ? { ok: true, data: res.data.map(contextFieldFromStore) } : res;
1347
+ },
1348
+ async values(scopeIds, options) {
1349
+ const res = await inBatches(
1350
+ scopeIds,
1351
+ SCOPES_PER_VALUES_CALL,
1352
+ (batch) => call("context_values", { p_scope_ids: batch }, "scopes.values")
1353
+ );
1354
+ if (!res.ok) return res;
1355
+ const cells = res.data.map(contextValueFromStore);
1356
+ await completeWholeValues(cells, options?.readFileText ?? null);
1357
+ return { ok: true, data: cells };
1358
+ },
1359
+ async archivedTypes(organizationId) {
1360
+ const res = await call("context_archived_types", { p_organization_id: organizationId }, "scopes.archivedTypes");
1361
+ return res.ok ? { ok: true, data: (res.data ?? []).map(archivedScopeTypeFromStore) } : res;
1362
+ },
1363
+ async archivedScopesOfType(organizationId, scopeTypeId, wanted) {
1364
+ const out = [];
1365
+ for (let offset = 0; out.length < wanted.size; offset += ARCHIVED_SCOPES_PAGE) {
1366
+ const res = await call(
1367
+ "read_records_archived",
1368
+ { p_organization_id: organizationId, p_table_id: scopeTypeId, p_lane: "org", p_by_id: false, p_limit: ARCHIVED_SCOPES_PAGE, p_offset: offset },
1369
+ "scopes.archivedScopesOfType"
1370
+ );
1371
+ if (!res.ok) return res;
1372
+ const rows = res.data ?? [];
1373
+ for (const r of rows) {
1374
+ if (!wanted.has(r.id)) continue;
1375
+ out.push({
1376
+ id: r.id,
1377
+ name: typeof r.document?.name === "string" ? r.document.name : null,
1378
+ slug: typeof r.document?.slug === "string" ? r.document.slug : null,
1379
+ archived_at: r.archived_at ?? null
1380
+ });
1381
+ }
1382
+ if (rows.length < ARCHIVED_SCOPES_PAGE) break;
1383
+ }
1384
+ return { ok: true, data: out };
1385
+ },
1386
+ async systemItems() {
1387
+ const res = await call("context_system_items", {}, "scopes.systemItems");
1388
+ return res.ok ? { ok: true, data: res.data ?? [] } : res;
1389
+ },
1390
+ async templates() {
1391
+ const res = await call("context_templates", {}, "scopes.templates");
1392
+ return res.ok ? { ok: true, data: res.data ?? [] } : res;
1393
+ },
1394
+ async createType(organizationId, spec) {
1395
+ const slug = resolveSlug(spec.slug, spec.label_plural || spec.label_singular || "");
1396
+ if (!slug.ok) return slug;
1397
+ const res = await write("context_type_write", {
1398
+ p_organization_id: organizationId,
1399
+ p_type_id: null,
1400
+ p_spec: definedOnly({
1401
+ label_singular: spec.label_singular,
1402
+ label_plural: spec.label_plural,
1403
+ icon: spec.icon ?? "folder",
1404
+ description: spec.description ?? "",
1405
+ sort_order: spec.sort_order ?? 0,
1406
+ max_assignments: spec.max_assignments_per_entity ?? void 0,
1407
+ default_variable_keys: spec.default_variable_keys ?? [],
1408
+ color: spec.color,
1409
+ slug: slug.data
1410
+ })
1411
+ });
1412
+ return res.ok ? { ok: true, data: scopeTypeFromStore(res.data) } : res;
1413
+ },
1414
+ async updateType(typeId, spec) {
1415
+ let slug;
1416
+ if (spec.slug !== void 0) {
1417
+ const resolved = resolveSlug(spec.slug, spec.label_plural ?? spec.label_singular ?? "");
1418
+ if (!resolved.ok) return resolved;
1419
+ slug = resolved.data;
1420
+ }
1421
+ const res = await write("context_type_write", {
1422
+ p_organization_id: null,
1423
+ p_type_id: typeId,
1424
+ p_spec: definedOnly({
1425
+ label_singular: spec.label_singular,
1426
+ label_plural: spec.label_plural,
1427
+ icon: spec.icon,
1428
+ description: spec.description,
1429
+ sort_order: spec.sort_order,
1430
+ max_assignments: spec.max_assignments_per_entity,
1431
+ color: spec.color,
1432
+ slug
1433
+ })
1434
+ });
1435
+ return res.ok ? { ok: true, data: scopeTypeFromStore(res.data) } : res;
1436
+ },
1437
+ archiveType: (typeId) => archiveOrRestore("context_type_archive", { p_type_id: typeId }, typeId),
1438
+ restoreType: (typeId) => archiveOrRestore("context_type_restore", { p_type_id: typeId }, typeId),
1439
+ async createScope(organizationId, typeId, spec) {
1440
+ const slug = resolveSlug(spec.slug, spec.name ?? "");
1441
+ if (!slug.ok) return slug;
1442
+ const res = await write("context_scope_write", {
1443
+ p_organization_id: organizationId,
1444
+ p_scope_id: null,
1445
+ p_type_id: typeId,
1446
+ p_spec: definedOnly({
1447
+ name: spec.name,
1448
+ parent_scope_id: spec.parent_scope_id,
1449
+ description: spec.description ?? "",
1450
+ settings: spec.settings ?? {},
1451
+ slug: slug.data,
1452
+ sort_order: spec.sort_order
1453
+ })
1454
+ });
1455
+ return res.ok ? { ok: true, data: scopeFromStore(res.data) } : res;
1456
+ },
1457
+ async updateScope(scopeId, spec) {
1458
+ let slug;
1459
+ if (spec.slug !== void 0) {
1460
+ const resolved = resolveSlug(spec.slug, spec.name ?? "");
1461
+ if (!resolved.ok) return resolved;
1462
+ slug = resolved.data;
1463
+ }
1464
+ const res = await write("context_scope_write", {
1465
+ p_organization_id: null,
1466
+ p_scope_id: scopeId,
1467
+ p_type_id: null,
1468
+ p_spec: definedOnly({ name: spec.name, description: spec.description, settings: spec.settings, slug, sort_order: spec.sort_order })
1469
+ });
1470
+ return res.ok ? { ok: true, data: scopeFromStore(res.data) } : res;
1471
+ },
1472
+ archiveScope: (scopeId) => archiveOrRestore("context_scope_archive", { p_scope_id: scopeId }, scopeId),
1473
+ restoreScope: (scopeId) => archiveOrRestore("context_scope_restore", { p_scope_id: scopeId }, scopeId),
1474
+ async createField(scopeTypeId, spec) {
1475
+ const res = await write("context_item_write", {
1476
+ p_item_id: null,
1477
+ p_scope_type_id: scopeTypeId,
1478
+ p_spec: fieldSpecForDoor({ kind: "string", description: "", context_policy: "on_request", sensitivity: "internal", tags: [], ...spec })
1479
+ });
1480
+ if (!res.ok) return res;
1481
+ return fieldById(scopeTypeId, String(res.data.id), "context_item_write");
1482
+ },
1483
+ async updateField(fieldId, scopeTypeId, spec) {
1484
+ const res = await write("context_item_write", { p_item_id: fieldId, p_scope_type_id: null, p_spec: fieldSpecForDoor(spec) });
1485
+ if (!res.ok) return res;
1486
+ return fieldById(scopeTypeId, fieldId, "context_item_write");
1487
+ },
1488
+ archiveField: (fieldId) => archiveOrRestore("context_item_archive", { p_item_id: fieldId }, fieldId),
1489
+ restoreField: (fieldId) => archiveOrRestore("context_item_restore", { p_item_id: fieldId }, fieldId),
1490
+ async writeValue(cell) {
1491
+ const res = await call(
1492
+ "context_value_write",
1493
+ { p_payload: { source_type: "ai_enriched", ...valuePayloadForDoor(cell) } },
1494
+ "scopes.writeValue"
1495
+ );
1496
+ if (!res.ok) return res;
1497
+ const envelope = res.data ?? {};
1498
+ if (!envelope.ok) {
1499
+ const code = VALUE_DOOR_CODES[envelope.error?.code ?? ""] ?? "internal";
1500
+ return { ok: false, error: { code, message: envelope.error?.message ?? "The value was not saved." } };
1501
+ }
1502
+ return {
1503
+ ok: true,
1504
+ data: {
1505
+ scope_id: cell.scope_id,
1506
+ field_id: cell.field_id,
1507
+ version: Number(envelope.data?.version ?? 1),
1508
+ source_type: String(envelope.data?.source_type ?? cell.source_type ?? "ai_enriched")
1509
+ }
1510
+ };
1511
+ }
1512
+ };
1513
+ return doors;
1514
+ }
1515
+
883
1516
  // src/choice.ts
884
1517
  var import_uuid2 = require("@ai-matrx/kit/uuid");
885
1518
  function optionKey(option) {
@@ -4930,6 +5563,7 @@ function createRecordsClient(given) {
4930
5563
  const unavailableReason = (error) => `${error.message}${error.hint ? ` ${error.hint}` : ""}`;
4931
5564
  const client = {
4932
5565
  config,
5566
+ scopes: createScopeDoors(callDoor),
4933
5567
  async recordWrite({ table_id, data }) {
4934
5568
  const result = await callDoor(
4935
5569
  DOORS.recordWrite,
@@ -11663,7 +12297,7 @@ function defineTypedTable(input) {
11663
12297
  fields: { ...input.fields },
11664
12298
  specs,
11665
12299
  canonicalSpec,
11666
- specHash: sha256Hex(canonicalSpec),
12300
+ specHash: sha256Hex2(canonicalSpec),
11667
12301
  graduatedTo: input.graduatedTo ? { token: input.graduatedTo.token, map: { ...input.graduatedTo.map } } : null,
11668
12302
  confidential: input.confidential ? {
11669
12303
  readers: input.confidential.readers.map((r) => ({ field: r.field, level: r.level, ...r.when ? { when: { ...r.when } } : {} })),
@@ -11738,7 +12372,7 @@ var K256 = new Uint32Array([
11738
12372
  3204031479,
11739
12373
  3329325298
11740
12374
  ]);
11741
- function sha256Hex(text2) {
12375
+ function sha256Hex2(text2) {
11742
12376
  const bytes = new TextEncoder().encode(text2);
11743
12377
  const bitLength = bytes.length * 8;
11744
12378
  const padded = new Uint8Array(bytes.length + 9 + 63 >> 6 << 6);