@ai-matrx/records 0.96.13 → 0.97.0

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