@ai-matrx/records 0.3.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.
@@ -0,0 +1,3003 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/core/index.ts
31
+ var core_exports = {};
32
+ __export(core_exports, {
33
+ ABSENCE_REASONS: () => ABSENCE_REASONS,
34
+ ACTOR_VOCABULARY: () => ACTOR_VOCABULARY,
35
+ COMPUTE_ON: () => COMPUTE_ON,
36
+ CONTEXT_POLICIES: () => CONTEXT_POLICIES,
37
+ DEFAULT_DOCUMENT_MAX_BYTES: () => DEFAULT_DOCUMENT_MAX_BYTES,
38
+ DEFAULT_PAGE_SIZE: () => DEFAULT_PAGE_SIZE,
39
+ DEFAULT_VALUE_MAX_BYTES: () => DEFAULT_VALUE_MAX_BYTES,
40
+ DELIVERIES: () => DELIVERIES,
41
+ DOORS: () => DOORS,
42
+ ENTITY_TOKENS: () => ENTITY_TOKENS,
43
+ FIELD_SENSITIVITIES: () => FIELD_SENSITIVITIES,
44
+ FIELD_SOURCES: () => FIELD_SOURCES,
45
+ FRESHNESS: () => FRESHNESS,
46
+ KERNEL_TABLES: () => KERNEL_TABLES,
47
+ MAPPED_SQLSTATES: () => MAPPED_SQLSTATES,
48
+ MERGE_FIELD_MODIFIERS: () => MERGE_FIELD_MODIFIERS,
49
+ MERGE_FIELD_SEMANTIC_TYPES: () => MERGE_FIELD_SEMANTIC_TYPES,
50
+ MERGE_FIELD_SOURCES: () => MERGE_FIELD_SOURCES,
51
+ ON_DELETE: () => ON_DELETE,
52
+ OVERRIDE_POLICIES: () => OVERRIDE_POLICIES,
53
+ PARITY_FIELD_TYPES: () => PARITY_FIELD_TYPES,
54
+ PER_VALUE_ACCESS_WORDS: () => PER_VALUE_ACCESS_WORDS,
55
+ RELATION_BINDINGS: () => RELATION_BINDINGS,
56
+ RELATION_CARDINALITIES: () => RELATION_CARDINALITIES,
57
+ RELATION_FLAVORS: () => RELATION_FLAVORS,
58
+ RETIRED_ACTOR_WORDS: () => RETIRED_ACTOR_WORDS,
59
+ RULE_NODE_KINDS: () => RULE_NODE_KINDS,
60
+ RULE_USES: () => RULE_USES,
61
+ STORAGE_MODES: () => STORAGE_MODES,
62
+ STORE_DOORS: () => STORE_DOORS,
63
+ STORE_KNOBS: () => STORE_KNOBS,
64
+ STORE_REFUSAL_CODES: () => STORE_REFUSAL_CODES,
65
+ TABLE_DISPLAYS: () => TABLE_DISPLAYS,
66
+ TABLE_ORIGINS: () => TABLE_ORIGINS,
67
+ TABLE_TYPES: () => TABLE_TYPES,
68
+ VALUE_ALTERNATE_KEYS: () => VALUE_ALTERNATE_KEYS,
69
+ VALUE_ENVELOPE_KEYS: () => VALUE_ENVELOPE_KEYS,
70
+ asWriteConflict: () => asWriteConflict,
71
+ cellText: () => cellText,
72
+ createRecordsClient: () => createRecordsClient,
73
+ doorAbsent: () => doorAbsent,
74
+ doorCensus: () => doorCensus,
75
+ doorExists: () => doorExists,
76
+ err: () => err,
77
+ exportCsv: () => exportCsv,
78
+ exportXlsx: () => exportXlsx,
79
+ importCsv: () => importCsv,
80
+ importXlsx: () => importXlsx,
81
+ intersectIds: () => intersectIds,
82
+ isRecordsErr: () => isRecordsErr,
83
+ mapPgError: () => mapPgError,
84
+ measureKey: () => measureKey,
85
+ ok: () => ok,
86
+ parseCsv: () => parseCsv,
87
+ planQuery: () => planQuery,
88
+ predictEnvelopeRefusal: () => predictEnvelopeRefusal,
89
+ predictSizeRefusal: () => predictSizeRefusal,
90
+ predictValueRefusals: () => predictValueRefusals,
91
+ predictWriteRefusals: () => predictWriteRefusals,
92
+ staleWriteDetail: () => staleWriteDetail,
93
+ toAoa: () => toAoa
94
+ });
95
+ module.exports = __toCommonJS(core_exports);
96
+
97
+ // src/vocabulary.ts
98
+ var TABLE_TYPES = [
99
+ "entity",
100
+ "detail",
101
+ "reference",
102
+ "ledger",
103
+ "restricted",
104
+ "system",
105
+ "deprecated"
106
+ ];
107
+ var TABLE_ORIGINS = ["standard", "custom"];
108
+ var RELATION_FLAVORS = ["owned", "referenced"];
109
+ var ON_DELETE = ["cascade", "set_null", "restrict"];
110
+ var RELATION_BINDINGS = ["live", "snapshot"];
111
+ var RELATION_CARDINALITIES = ["one", "many"];
112
+ var FIELD_SOURCES = ["manual", "formula", "agent", "synced"];
113
+ var COMPUTE_ON = ["read", "write"];
114
+ var FIELD_SENSITIVITIES = ["public", "internal", "confidential", "restricted"];
115
+ var DELIVERIES = ["inline", "on_demand", "auto"];
116
+ var CONTEXT_POLICIES = ["include", "summarize", "exclude", "on_request"];
117
+ var MERGE_FIELD_SOURCES = [
118
+ "literal",
119
+ "record",
120
+ "state",
121
+ "actor",
122
+ "platform",
123
+ "user_input",
124
+ "tool",
125
+ "derived"
126
+ ];
127
+ var MERGE_FIELD_SEMANTIC_TYPES = [
128
+ "value",
129
+ "reference",
130
+ "resolver",
131
+ "computed",
132
+ "collection"
133
+ ];
134
+ var MERGE_FIELD_MODIFIERS = [
135
+ "scoped",
136
+ "temporal",
137
+ "collection",
138
+ "live",
139
+ "fallback",
140
+ "formatted",
141
+ "required"
142
+ ];
143
+ var OVERRIDE_POLICIES = [
144
+ "must_supply",
145
+ "shown_overridable",
146
+ "shown_locked",
147
+ "server_fixed",
148
+ "derived"
149
+ ];
150
+ var FRESHNESS = ["live", "cached", "snapshot"];
151
+ var TABLE_DISPLAYS = ["list", "grid", "board", "calendar", "timeline"];
152
+
153
+ // src/aggregate.ts
154
+ function measureKey(measure) {
155
+ return measure.op === "count" ? "count" : `${measure.op}_${measure.key ?? ""}`;
156
+ }
157
+
158
+ // src/results.ts
159
+ function isRecordsErr(result) {
160
+ return result.ok === false;
161
+ }
162
+ var ok = (data) => ({ ok: true, data });
163
+ var err = (error) => ({ ok: false, error });
164
+
165
+ // src/store.generated.ts
166
+ var ACTOR_VOCABULARY = ["user", "agent", "system"];
167
+ var RETIRED_ACTOR_WORDS = { "ai": "agent", "code": "system", "human": "user" };
168
+ var ABSENCE_REASONS = ["never asked", "none", "refused", "conflicting"];
169
+ var VALUE_ENVELOPE_KEYS = ["ver", "src", "actor", "on_behalf_of", "at", "absent", "alternates", "dated"];
170
+ var VALUE_ALTERNATE_KEYS = ["value", "src", "rank"];
171
+ var STORAGE_MODES = ["light", "heavy"];
172
+ var RULE_USES = ["validate", "compute", "membership", "applicability"];
173
+ var PER_VALUE_ACCESS_WORDS = ["visibility", "access", "share", "acl", "permission", "permissions", "secret"];
174
+ var PARITY_FIELD_TYPES = [
175
+ { parity_type: "attachment", behavior: "relation", made_of: "REC-31: a File record reached through a relation, target the kernel `File` Table" },
176
+ { parity_type: "currency", behavior: "range", made_of: "FLD-N-1: a number whose UNIT is the currency and whose format is currency \u2014 on the Field, never in presentation" },
177
+ { parity_type: "datetime", behavior: "range", made_of: "a range of kind date or datetime \u2014 the dated modifier says the VALUES are dated, which is a different question" },
178
+ { parity_type: "email", behavior: "text", made_of: "text whose format is email" },
179
+ { parity_type: "formula", behavior: "formula", made_of: "FLD-9: a declared computation, on read or on write, evaluated by custom.rule_eval" },
180
+ { parity_type: "lookup", behavior: "formula", made_of: "a Value read THROUGH a relation \u2014 config.via names the relation field, config.pick the Value on the far side" },
181
+ { parity_type: "member", behavior: "relation", made_of: "a person: a relation whose target is the kernel `Person` Table" },
182
+ { parity_type: "multi_select", behavior: "list", made_of: "many choices from the same Table \u2014 the multi modifier, never a second behaviour" },
183
+ { parity_type: "percent", behavior: "range", made_of: "a number whose unit is % and whose format is percent" },
184
+ { parity_type: "phone", behavior: "text", made_of: "text whose format is phone" },
185
+ { parity_type: "rollup", behavior: "formula", made_of: "an aggregate ALONG a relation \u2014 config.via, config.of, config.agg; far-side ids are taken DISTINCT, so nothing is counted twice" },
186
+ { parity_type: "select", behavior: "list", made_of: "one choice from a Table shown as a list (FLD-5/FLD-6)" },
187
+ { parity_type: "url", behavior: "text", made_of: "text whose format is url, with the pattern Rule that makes the format enforceable" }
188
+ ];
189
+ var RULE_NODE_KINDS = [
190
+ { node: "add", evaluated_by: "W1-RULE" },
191
+ { node: "and", evaluated_by: "W1-RULE" },
192
+ { node: "concat", evaluated_by: "W1-RULE" },
193
+ { node: "const", evaluated_by: "W1-RULE" },
194
+ { node: "div", evaluated_by: "W1-RULE" },
195
+ { node: "eq", evaluated_by: "W1-RULE" },
196
+ { node: "field", evaluated_by: "W1-RULE" },
197
+ { node: "gt", evaluated_by: "W1-RULE" },
198
+ { node: "gte", evaluated_by: "W1-RULE" },
199
+ { node: "length", evaluated_by: "W1-RULE" },
200
+ { node: "lt", evaluated_by: "W1-RULE" },
201
+ { node: "lte", evaluated_by: "W1-RULE" },
202
+ { node: "matches", evaluated_by: "W1-RULE" },
203
+ { node: "merge_field", evaluated_by: "W5-MERGE-B" },
204
+ { node: "mul", evaluated_by: "W1-RULE" },
205
+ { node: "ne", evaluated_by: "W1-RULE" },
206
+ { node: "not", evaluated_by: "W1-RULE" },
207
+ { node: "or", evaluated_by: "W1-RULE" },
208
+ { node: "parent_field", evaluated_by: "W1-RULE-APPLY" },
209
+ { node: "present", evaluated_by: "W1-RULE" },
210
+ { node: "sub", evaluated_by: "W1-RULE" }
211
+ ];
212
+ var KERNEL_TABLES = [
213
+ { id: "11111111-0000-4000-8000-000000000002", name: "Field" },
214
+ { id: "11111111-0000-4000-8000-000000000006", name: "File" },
215
+ { id: "11111111-0000-4000-8000-000000000009", name: "Merge Field" },
216
+ { id: "11111111-0000-4000-8000-000000000004", name: "Organization" },
217
+ { id: "11111111-0000-4000-8000-000000000005", name: "Person" },
218
+ { id: "11111111-0000-4000-8000-000000000007", name: "Presentation" },
219
+ { id: "11111111-0000-4000-8000-000000000003", name: "Rule" },
220
+ { id: "11111111-0000-4000-8000-000000000001", name: "Table" },
221
+ { id: "11111111-0000-4000-8000-000000000008", name: "Widget" }
222
+ ];
223
+ var STORE_DOORS = [
224
+ { name: "absence_reasons", args: "", returns: "text[]", security: "invoker" },
225
+ { name: "actor_vocabulary", args: "", returns: "text[]", security: "invoker" },
226
+ { name: "actor_word", args: "p_declared text", returns: "text", security: "invoker" },
227
+ { name: "agent_context", args: "p_organization_id uuid, p_table_id uuid, p_limit integer DEFAULT 50", returns: "jsonb", security: "invoker" },
228
+ { name: "agg_assert_key", args: "p_key text", returns: "text", security: "invoker" },
229
+ { name: "agg_buckets", args: "", returns: "text[]", security: "invoker" },
230
+ { name: "agg_deliver", args: "p_organization_id uuid, p_rule_id uuid, p_record_id uuid, p_channel text, p_recipient_user_id uuid, p_event_key text, p_subject text, p_body text, p_payload jsonb DEFAULT '{}'::jsonb", returns: "uuid", security: "invoker" },
231
+ { name: "agg_digest_run", args: "p_organization_id uuid, p_rule_id uuid DEFAULT NULL::uuid, p_since timestamp with time zone DEFAULT NULL::timestamp with time zone", returns: "integer", security: "invoker" },
232
+ { name: "agg_explain", args: "p_organization_id uuid, p_table_id uuid, p_group_by jsonb DEFAULT '[]'::jsonb, p_measures jsonb DEFAULT '[]'::jsonb, p_bucket jsonb DEFAULT NULL::jsonb, p_filter jsonb DEFAULT '{}'::jsonb, p_required text DEFAULT 'viewer'::text", returns: "jsonb", security: "invoker" },
233
+ { name: "agg_operations", args: "", returns: "text[]", security: "invoker" },
234
+ { name: "agg_sql", args: "p_organization_id uuid, p_table_id uuid, p_group_by jsonb DEFAULT '[]'::jsonb, p_measures jsonb DEFAULT '[]'::jsonb, p_bucket jsonb DEFAULT NULL::jsonb, p_filter jsonb DEFAULT '{}'::jsonb, p_limit integer DEFAULT 200, p_required text DEFAULT 'viewer'::text", returns: "text", security: "invoker" },
235
+ { name: "agg_subscription_cadences", args: "", returns: "text[]", security: "invoker" },
236
+ { name: "agg_subscription_fire", args: "p_organization_id uuid, p_record_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_changed_field_ids jsonb DEFAULT '[]'::jsonb", returns: "integer", security: "invoker" },
237
+ { name: "agg_subscriptions", args: "p_organization_id uuid, p_saved_view_id uuid DEFAULT NULL::uuid, p_cadence text DEFAULT NULL::text", returns: "TABLE(rule_id uuid, saved_view_id uuid, cadence text, schedule text, channel text, recipient_user_id uuid, event_key text, name text)", security: "invoker" },
238
+ { name: "agg_value_sql", args: "p_key text", returns: "text", security: "invoker" },
239
+ { name: "agg_view_admits", args: "p_organization_id uuid, p_saved_view_id uuid, p_record_id uuid", returns: "boolean", security: "invoker" },
240
+ { name: "anon_capture", args: "p_organization_id uuid, p_client_key text, p_table_id uuid, p_payload jsonb, p_device text DEFAULT NULL::text, p_captured_at timestamp with time zone DEFAULT NULL::timestamp with time zone", returns: "uuid", security: "definer" },
241
+ { name: "anon_clear", args: "p_organization_id uuid, p_submission_id uuid", returns: "uuid", security: "definer" },
242
+ { name: "anon_inbound_land", args: "p_address text, p_secret text, p_payload jsonb, p_raw_payload jsonb DEFAULT '{}'::jsonb, p_client_key text DEFAULT NULL::text", returns: "uuid", security: "definer" },
243
+ { name: "anon_publish", args: "p_organization_id uuid, p_form_id uuid, p_published boolean DEFAULT true", returns: "timestamp with time zone", security: "definer" },
244
+ { name: "anon_rate_take", args: "p_organization_id uuid, p_form_id uuid, p_bucket text, p_token_id uuid DEFAULT NULL::uuid", returns: "integer", security: "definer" },
245
+ { name: "anon_token_issue", args: "p_organization_id uuid, p_mode text, p_allowed_origins jsonb, p_form_id uuid DEFAULT NULL::uuid, p_saved_view_id uuid DEFAULT NULL::uuid, p_record_id uuid DEFAULT NULL::uuid, p_expires_at timestamp with time zone DEFAULT NULL::timestamp with time zone", returns: "TABLE(token_id uuid, secret text)", security: "definer" },
246
+ { name: "anon_token_revoke", args: "p_organization_id uuid, p_token_id uuid", returns: "boolean", security: "definer" },
247
+ { name: "anon_token_verify", args: "p_secret text, p_origin text, p_required_mode text", returns: "TABLE(token_id uuid, organization_id uuid, form_id uuid, saved_view_id uuid, record_id uuid, mode text)", security: "definer" },
248
+ { name: "anon_write", args: "p_secret text, p_origin text, p_payload jsonb, p_client_key text DEFAULT NULL::text, p_raw_payload jsonb DEFAULT '{}'::jsonb", returns: "uuid", security: "definer" },
249
+ { name: "applicable_fields", args: "p_organization_id uuid, p_table_id uuid, p_record_type text DEFAULT NULL::text", returns: "SETOF custom.record", security: "definer" },
250
+ { name: "assert_client_may_reach", args: "p_organization_id uuid, p_door text", returns: "void", security: "invoker" },
251
+ { name: "assert_organization_wall", args: "p_kind text, p_organization_id uuid, p_row jsonb", returns: "void", security: "invoker" },
252
+ { name: "assert_store_door", args: "p_organization_id uuid, p_door text", returns: "void", security: "invoker" },
253
+ { name: "bump_epoch", args: "p_entity_type text, p_entity_id uuid, p_organization_id uuid DEFAULT NULL::uuid", returns: "bigint", security: "definer" },
254
+ { name: "cache_lookup", args: "p_container_type text, p_container_id uuid, p_item_type text, p_item_id uuid", returns: "permission_level", security: "definer" },
255
+ { name: "caller_role", args: "", returns: "name", security: "invoker" },
256
+ { name: "client_write_grants", args: "", returns: "TABLE(role_name text, object_name text, privilege text)", security: "invoker" },
257
+ { name: "computed_provenance", args: "p_organization_id uuid, p_record_id uuid", returns: "TABLE(field_key text, field_id uuid, value jsonb, rule_id uuid, rule_version integer, computed_at timestamp with time zone)", security: "invoker" },
258
+ { name: "containment_chain", args: "p_organization_id uuid, p_record_id uuid", returns: "TABLE(ancestor_id uuid, depth integer)", security: "invoker" },
259
+ { name: "containment_depth_ceiling", args: "p_organization_id uuid DEFAULT NULL::uuid", returns: "integer", security: "invoker" },
260
+ { name: "containment_edges", args: "p_organization_id uuid", returns: "TABLE(parent_id uuid, child_id uuid, via text)", security: "invoker" },
261
+ { name: "containment_parent", args: "p_data jsonb", returns: "uuid", security: "invoker" },
262
+ { name: "custom_fields_tables", args: "", returns: "TABLE(token text, schema_name text, table_name text)", security: "invoker" },
263
+ { name: "dependency_cycle", args: "p_organization_id uuid, p_row custom.record", returns: "text[]", security: "invoker" },
264
+ { name: "dependency_label", args: "p_organization_id uuid, p_node text", returns: "text", security: "invoker" },
265
+ { name: "derive_visibility", args: "p_container_type text, p_container_id uuid", returns: "TABLE(item_type text, item_id uuid, depth integer, max_level permission_level)", security: "definer" },
266
+ { name: "derived_value", args: "p_organization_id uuid, p_record_id uuid, p_field_data jsonb, p_values jsonb DEFAULT NULL::jsonb", returns: "jsonb", security: "invoker" },
267
+ { name: "derived_values", args: "p_organization_id uuid, p_record_id uuid", returns: "jsonb", security: "invoker" },
268
+ { name: "doc_content_hash", args: "p_body text", returns: "text", security: "invoker" },
269
+ { name: "doc_format_value", args: "p_field_data jsonb, p_value jsonb", returns: "text", security: "invoker" },
270
+ { name: "doc_render_body", args: "p_organization_id uuid, p_template_id uuid, p_record_id uuid", returns: "text", security: "invoker" },
271
+ { name: "doc_render_document", args: "p_organization_id uuid, p_template_id uuid, p_record_id uuid", returns: "uuid", security: "definer" },
272
+ { name: "doc_render_write", args: "p_organization_id uuid, p_template_id uuid, p_record_id uuid, p_table_id uuid, p_template_version integer, p_body text, p_content_hash text", returns: "uuid", security: "definer" },
273
+ { name: "doc_sign", args: "p_organization_id uuid, p_render_id uuid, p_field_key text, p_signer_name text, p_signer_user_id uuid DEFAULT NULL::uuid", returns: "uuid", security: "definer" },
274
+ { name: "doc_signature_field_ok", args: "p_field_data jsonb", returns: "boolean", security: "invoker" },
275
+ { name: "doc_signature_intact", args: "p_organization_id uuid, p_signature_id uuid", returns: "jsonb", security: "invoker" },
276
+ { name: "doc_signature_write", args: "p_organization_id uuid, p_render_id uuid, p_record_id uuid, p_field_key text, p_signer_name text, p_signer_user_id uuid, p_document_hash text, p_document_version integer", returns: "uuid", security: "definer" },
277
+ { name: "doc_template_save", args: "p_organization_id uuid, p_table_id uuid, p_name text, p_body text, p_template_id uuid DEFAULT NULL::uuid", returns: "uuid", security: "definer" },
278
+ { name: "doc_token_pattern", args: "", returns: "text", security: "invoker" },
279
+ { name: "doc_tokens", args: "p_body text", returns: "TABLE(ordinal integer, raw text, field_id uuid)", security: "invoker" },
280
+ { name: "doc_unresolved_tokens", args: "p_organization_id uuid, p_table_id uuid, p_body text", returns: "TABLE(raw text, field_id uuid, why text)", security: "invoker" },
281
+ { name: "export_records", args: "p_organization_id uuid, p_table_id uuid, p_limit integer DEFAULT 1000", returns: "TABLE(id uuid, document jsonb)", security: "invoker" },
282
+ { name: "external_foreign_table_findings", args: "", returns: "SETOF text", security: "definer" },
283
+ { name: "external_history_event", args: "p_organization_id uuid, p_link_id uuid, p_operation text", returns: "bigint", security: "definer" },
284
+ { name: "external_rows", args: "p_organization_id uuid, p_source_id uuid", returns: "SETOF jsonb", security: "definer" },
285
+ { name: "external_source_declare", args: "p_organization_id uuid, p_tier text, p_connection_token text, p_external_schema text, p_external_table text, p_link_template text", returns: "uuid", security: "definer" },
286
+ { name: "external_stub_upsert", args: "p_organization_id uuid, p_source_id uuid, p_table_id uuid, p_external_key text, p_link_url text, p_cached_title text", returns: "uuid", security: "definer" },
287
+ { name: "external_tier_contract", args: "", returns: "jsonb", security: "definer" },
288
+ { name: "external_write_through", args: "p_organization_id uuid, p_record_id uuid, p_patch jsonb", returns: "void", security: "definer" },
289
+ { name: "external_writes_set", args: "p_organization_id uuid, p_source_id uuid, p_enabled boolean", returns: "boolean", security: "definer" },
290
+ { name: "field_dependants", args: "p_organization_id uuid, p_field_id uuid", returns: "TABLE(kind text, dependant_id uuid, label text, how text)", security: "invoker" },
291
+ { name: "field_kernel_id", args: "", returns: "uuid", security: "invoker" },
292
+ { name: "field_options", args: "p_organization_id uuid, p_field_id uuid", returns: "SETOF custom.record", security: "invoker" },
293
+ { name: "field_rules", args: "p_field_data jsonb", returns: "TABLE(kind text, spec jsonb)", security: "invoker" },
294
+ { name: "file_kernel_id", args: "", returns: "uuid", security: "invoker" },
295
+ { name: "formula_value", args: "p_organization_id uuid, p_record_id uuid, p_field_data jsonb, p_values jsonb DEFAULT NULL::jsonb", returns: "jsonb", security: "invoker" },
296
+ { name: "has_visibility", args: "p_user_id uuid, p_type text, p_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level", returns: "boolean", security: "definer" },
297
+ { name: "has_visibility_at", args: "p_user_id uuid, p_type text, p_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level, p_organization_id uuid DEFAULT NULL::uuid, p_min_version bigint DEFAULT NULL::bigint", returns: "boolean", security: "definer" },
298
+ { name: "hidden_field_notice", args: "p_field custom.record, p_action text DEFAULT 'read'::text", returns: "jsonb", security: "invoker" },
299
+ { name: "home_add", args: "p_organization_id uuid, p_table_id uuid, p_home_record_id uuid", returns: "uuid", security: "invoker" },
300
+ { name: "home_relations", args: "", returns: "TABLE(table_id uuid, home_record_id uuid, organization_id uuid, relation_id uuid)", security: "invoker" },
301
+ { name: "index_payload", args: "p_organization_id uuid, p_table_id uuid, p_limit integer DEFAULT 1000", returns: "TABLE(id uuid, searchable text)", security: "invoker" },
302
+ { name: "intern_provenance", args: "p_data jsonb", returns: "jsonb", security: "invoker" },
303
+ { name: "io_changed_field_ids", args: "p_organization_id uuid, p_table_id uuid, p_old jsonb, p_new jsonb", returns: "jsonb", security: "invoker" },
304
+ { name: "io_changed_keys", args: "p_old jsonb, p_new jsonb", returns: "text[]", security: "invoker" },
305
+ { name: "io_comment_resolve", args: "p_organization_id uuid, p_comment_id uuid, p_resolved boolean DEFAULT true", returns: "boolean", security: "definer" },
306
+ { name: "io_comment_write", args: "p_organization_id uuid, p_record_id uuid, p_body text, p_anchor jsonb DEFAULT '{}'::jsonb, p_parent_comment_id uuid DEFAULT NULL::uuid", returns: "uuid", security: "definer" },
307
+ { name: "io_comments", args: "p_organization_id uuid, p_record_id uuid, p_include_resolved boolean DEFAULT false", returns: "TABLE(id uuid, body text, anchor jsonb, parent_comment_id uuid, created_by uuid, created_at timestamp with time zone, resolved_at timestamp with time zone, resolved_by uuid)", security: "definer" },
308
+ { name: "io_csv_escape", args: "p_value text, p_delimiter text DEFAULT ','::text", returns: "text", security: "invoker" },
309
+ { name: "io_csv_parse", args: "p_text text, p_delimiter text DEFAULT NULL::text", returns: "TABLE(row_number integer, cells text[])", security: "invoker" },
310
+ { name: "io_export", args: "p_organization_id uuid, p_table_id uuid, p_columns text[] DEFAULT NULL::text[], p_limit integer DEFAULT 10000, p_required text DEFAULT 'viewer'::text", returns: "jsonb", security: "definer" },
311
+ { name: "io_export_csv", args: "p_organization_id uuid, p_table_id uuid, p_columns text[] DEFAULT NULL::text[], p_limit integer DEFAULT 10000, p_delimiter text DEFAULT ','::text, p_required text DEFAULT 'viewer'::text", returns: "text", security: "definer" },
312
+ { name: "io_import_open", args: "p_organization_id uuid, p_table_id uuid, p_format text DEFAULT 'csv'::text, p_source_name text DEFAULT NULL::text, p_source_columns jsonb DEFAULT '[]'::jsonb", returns: "uuid", security: "definer" },
313
+ { name: "io_import_rows", args: "p_organization_id uuid, p_import_id uuid, p_rows jsonb, p_mapping jsonb DEFAULT '{}'::jsonb", returns: "jsonb", security: "definer" },
314
+ { name: "io_infer_type", args: "p_samples jsonb", returns: "text", security: "invoker" },
315
+ { name: "io_outbox_announce", args: "", returns: "trigger", security: "definer" },
316
+ { name: "io_outbox_drain", args: "p_organization_id uuid, p_consumer text, p_limit integer DEFAULT 100, p_event_key text DEFAULT 'records.changed'::text", returns: "TABLE(outbox_id uuid, record_id uuid, table_id uuid, operation text, changed_field_ids jsonb, actor jsonb, occurred_at timestamp with time zone)", security: "definer" },
317
+ { name: "io_outbox_release", args: "p_organization_id uuid, p_consumer text, p_older_than interval DEFAULT '00:15:00'::interval", returns: "integer", security: "definer" },
318
+ { name: "io_proposal_accept", args: "p_organization_id uuid, p_import_id uuid, p_column text, p_type text DEFAULT NULL::text, p_label text DEFAULT NULL::text", returns: "uuid", security: "definer" },
319
+ { name: "io_proposal_reject", args: "p_organization_id uuid, p_import_id uuid, p_column text", returns: "boolean", security: "definer" },
320
+ { name: "io_record_changed", args: "", returns: "trigger", security: "definer" },
321
+ { name: "io_restore", args: "p_organization_id uuid, p_record_id uuid, p_version integer", returns: "integer", security: "definer" },
322
+ { name: "io_revisions", args: "p_organization_id uuid, p_record_id uuid", returns: "TABLE(version integer, changed_at timestamp with time zone, changed_by uuid, summary text)", security: "definer" },
323
+ { name: "lookup_value", args: "p_organization_id uuid, p_record_id uuid, p_field_data jsonb", returns: "jsonb", security: "invoker" },
324
+ { name: "mask_document", args: "p_document jsonb, p_visible_keys text[], p_notices jsonb, p_by_id boolean DEFAULT false, p_key_ids jsonb DEFAULT '{}'::jsonb", returns: "jsonb", security: "invoker" },
325
+ { name: "mask_document", args: "p_document jsonb, p_visible_keys text[], p_notices jsonb, p_by_id boolean DEFAULT false, p_key_ids jsonb DEFAULT '{}'::jsonb, p_declared_keys text[] DEFAULT NULL::text[]", returns: "jsonb", security: "invoker" },
326
+ { name: "merge_field_kernel_id", args: "", returns: "uuid", security: "invoker" },
327
+ { name: "migrate_delete", args: "p_organization_id uuid, p_record_id uuid, p_note text DEFAULT NULL::text", returns: "jsonb", security: "invoker" },
328
+ { name: "migrate_demote", args: "p_organization_id uuid, p_table_id uuid, p_note text DEFAULT NULL::text", returns: "jsonb", security: "invoker" },
329
+ { name: "migrate_extract_parent", args: "p_organization_id uuid, p_id uuid, p_parent_table_id uuid, p_moved_keys text[], p_note text DEFAULT NULL::text", returns: "jsonb", security: "invoker" },
330
+ { name: "migrate_merge", args: "p_organization_id uuid, p_winner_id uuid, p_loser_id uuid, p_note text DEFAULT NULL::text", returns: "jsonb", security: "invoker" },
331
+ { name: "migrate_promote", args: "p_organization_id uuid, p_table_id uuid, p_note text DEFAULT NULL::text", returns: "jsonb", security: "invoker" },
332
+ { name: "migrate_purge", args: "p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_dry_run boolean DEFAULT true", returns: "jsonb", security: "invoker" },
333
+ { name: "migrate_rename", args: "p_organization_id uuid, p_id uuid, p_to text, p_note text DEFAULT NULL::text", returns: "jsonb", security: "invoker" },
334
+ { name: "migrate_reparent", args: "p_organization_id uuid, p_id uuid, p_parent_id uuid, p_note text DEFAULT NULL::text", returns: "jsonb", security: "invoker" },
335
+ { name: "migrate_retype", args: "p_organization_id uuid, p_id uuid, p_to text, p_note text DEFAULT NULL::text", returns: "jsonb", security: "invoker" },
336
+ { name: "migrate_split", args: "p_organization_id uuid, p_record_id uuid, p_moved_keys text[], p_note text DEFAULT NULL::text", returns: "jsonb", security: "invoker" },
337
+ { name: "organization_references", args: "p_kind text, p_organization_id uuid, p_row jsonb", returns: "TABLE(site text, what text, ref_id uuid, openable boolean)", security: "invoker" },
338
+ { name: "parity_field_types", args: "", returns: "TABLE(parity_type text, behavior text, made_of text)", security: "invoker" },
339
+ { name: "parity_type", args: "p_field_data jsonb", returns: "text", security: "invoker" },
340
+ { name: "parity_values", args: "p_organization_id uuid, p_record_id uuid", returns: "TABLE(field_key text, field_id uuid, parity_type text, behavior text, unit text, format text, value jsonb, value_version integer, actor text, written_at timestamp with time zone)", security: "invoker" },
341
+ { name: "per_value_access_words", args: "", returns: "text[]", security: "invoker" },
342
+ { name: "person_kernel_id", args: "", returns: "uuid", security: "invoker" },
343
+ { name: "promote_field", args: "p_organization_id uuid, p_table_id uuid, p_field_id uuid", returns: "jsonb", security: "invoker" },
344
+ { name: "promote_table", args: "p_organization_id uuid, p_table_id uuid", returns: "jsonb", security: "definer" },
345
+ { name: "promoted_field_cap", args: "", returns: "integer", security: "invoker" },
346
+ { name: "promoted_fields", args: "p_organization_id uuid, p_table_id uuid", returns: "TABLE(field_id uuid, field_key text, parity_type text, is_unique boolean, value_path text, index_arm text, index_expr text, index_name text, indexable boolean, why_not text)", security: "invoker" },
347
+ { name: "promoted_index_arm", args: "p_field_data jsonb", returns: "text", security: "invoker" },
348
+ { name: "promoted_index_ddl", args: "p_organization_id uuid, p_table_id uuid", returns: "TABLE(step integer, purpose text, statement text)", security: "invoker" },
349
+ { name: "promoted_index_expr", args: "p_field_data jsonb", returns: "text", security: "invoker" },
350
+ { name: "promoted_index_name", args: "p_table_id uuid, p_field_key text, p_unique boolean", returns: "text", security: "invoker" },
351
+ { name: "promoted_query_sql", args: "p_organization_id uuid, p_table_id uuid, p_field_key text", returns: "text", security: "invoker" },
352
+ { name: "promoted_read", args: "p_organization_id uuid, p_table_id uuid, p_field_key text, p_value text", returns: "SETOF uuid", security: "invoker" },
353
+ { name: "promoted_value_path", args: "p_field_data jsonb", returns: "text", security: "invoker" },
354
+ { name: "promotion_inline_ceiling", args: "", returns: "integer", security: "invoker" },
355
+ { name: "query_access_ids", args: "p_organization_id uuid, p_required text DEFAULT 'viewer'::text", returns: "uuid[]", security: "invoker" },
356
+ { name: "query_across_homes", args: "p_organization_id uuid, p_table_id uuid, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_required text DEFAULT 'viewer'::text", returns: "TABLE(record_id uuid, home_record_id uuid, data jsonb, created_at timestamp with time zone)", security: "invoker" },
357
+ { name: "query_by_coordinates", args: "p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_coordinates jsonb DEFAULT '[]'::jsonb, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_required text DEFAULT 'viewer'::text", returns: "TABLE(record_id uuid, table_id uuid, data jsonb, coordinates_matched integer)", security: "invoker" },
358
+ { name: "query_can_see", args: "p_organization_id uuid, p_record_id uuid, p_required text DEFAULT 'viewer'::text", returns: "boolean", security: "invoker" },
359
+ { name: "query_hot_paths", args: "", returns: "TABLE(name text, statement text)", security: "invoker" },
360
+ { name: "query_hot_paths_prepared", args: "", returns: "TABLE(name text, prepared boolean, generic_plans bigint)", security: "invoker" },
361
+ { name: "query_is_store_owner", args: "", returns: "boolean", security: "invoker" },
362
+ { name: "query_prepare_hot", args: "", returns: "integer", security: "invoker" },
363
+ { name: "query_principal", args: "", returns: "uuid", security: "invoker" },
364
+ { name: "query_record_as_of", args: "p_organization_id uuid, p_record_id uuid, p_recorded_at timestamp with time zone DEFAULT NULL::timestamp with time zone, p_world_on date DEFAULT NULL::date, p_required text DEFAULT 'viewer'::text", returns: "jsonb", security: "invoker" },
365
+ { name: "query_relation_edges", args: "p_organization_id uuid, p_flavor text DEFAULT NULL::text, p_role text DEFAULT NULL::text", returns: "TABLE(parent_id uuid, child_id uuid, role text, flavor text)", security: "invoker" },
366
+ { name: "query_rollup", args: "p_organization_id uuid, p_roots uuid[], p_flavor text DEFAULT NULL::text, p_role text DEFAULT NULL::text, p_max_depth integer DEFAULT 33, p_required text DEFAULT 'viewer'::text", returns: "TABLE(record_id uuid, depth integer)", security: "invoker" },
367
+ { name: "query_rollup_sum", args: "p_organization_id uuid, p_roots uuid[], p_field_key text, p_flavor text DEFAULT NULL::text, p_role text DEFAULT NULL::text, p_max_depth integer DEFAULT 33, p_required text DEFAULT 'viewer'::text", returns: "numeric", security: "invoker" },
368
+ { name: "query_table_as_of", args: "p_organization_id uuid, p_table_id uuid, p_recorded_at timestamp with time zone DEFAULT NULL::timestamp with time zone, p_world_on date DEFAULT NULL::date, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_required text DEFAULT 'viewer'::text", returns: "TABLE(record_id uuid, data jsonb)", security: "invoker" },
369
+ { name: "query_table_homes", args: "p_organization_id uuid, p_table_id uuid", returns: "SETOF uuid", security: "invoker" },
370
+ { name: "query_visible_ids", args: "p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_required text DEFAULT 'viewer'::text", returns: "SETOF uuid", security: "invoker" },
371
+ { name: "reachable_from", args: "p_organization_id uuid, p_roots uuid[]", returns: "TABLE(record_id uuid, depth integer, via text)", security: "invoker" },
372
+ { name: "read_paths_outside_the_door", args: "", returns: "TABLE(object_name text, why text)", security: "invoker" },
373
+ { name: "read_record", args: "p_organization_id uuid, p_record_id uuid, p_by_id boolean DEFAULT false", returns: "jsonb", security: "definer" },
374
+ { name: "read_records", args: "p_organization_id uuid, p_table_id uuid, p_by_id boolean DEFAULT false, p_limit integer DEFAULT 200, p_offset integer DEFAULT 0", returns: "TABLE(id uuid, document jsonb, level permission_level)", security: "definer" },
375
+ { name: "record_aggregate", args: "p_organization_id uuid, p_table_id uuid, p_group_by jsonb DEFAULT '[]'::jsonb, p_measures jsonb DEFAULT '[]'::jsonb, p_bucket jsonb DEFAULT NULL::jsonb, p_filter jsonb DEFAULT '{}'::jsonb, p_limit integer DEFAULT 200, p_required text DEFAULT 'viewer'::text", returns: "TABLE(groups jsonb, measures jsonb, row_count bigint)", security: "invoker" },
376
+ { name: "record_applicability", args: "p_organization_id uuid, p_record_id uuid", returns: "TABLE(rule_id uuid, rule_name text, rule_version integer, applies boolean, answer jsonb)", security: "invoker" },
377
+ { name: "record_delete", args: "p_organization_id uuid, p_record_id uuid", returns: "timestamp with time zone", security: "definer" },
378
+ { name: "record_reparent", args: "p_organization_id uuid, p_record_id uuid, p_parent_id uuid", returns: "void", security: "invoker" },
379
+ { name: "record_restore", args: "p_organization_id uuid, p_record_id uuid", returns: "void", security: "definer" },
380
+ { name: "record_update", args: "p_organization_id uuid, p_record_id uuid, p_patch jsonb, p_expected_version integer DEFAULT NULL::integer", returns: "integer", security: "definer" },
381
+ { name: "record_values", args: "p_organization_id uuid, p_record_id uuid", returns: "jsonb", security: "invoker" },
382
+ { name: "record_values_versioned", args: "p_organization_id uuid, p_record_id uuid", returns: "TABLE(field_key text, field_id uuid, value jsonb, value_version integer, source jsonb, absent_reason text, actor text, on_behalf_of text, written_at timestamp with time zone, alternates jsonb)", security: "invoker" },
383
+ { name: "record_write", args: "p_organization_id uuid, p_table_id uuid, p_data jsonb", returns: "uuid", security: "definer" },
384
+ { name: "relation_own", args: "p_organization_id uuid, p_owner_id uuid, p_target_id uuid", returns: "uuid", security: "invoker" },
385
+ { name: "relation_target_external", args: "p_connection_token text, p_external_table text, p_external_key text", returns: "jsonb", security: "definer" },
386
+ { name: "relation_target_ours", args: "p_entity_token text, p_row_id uuid", returns: "jsonb", security: "definer" },
387
+ { name: "relation_targets", args: "p_organization_id uuid, p_record_id uuid, p_via_key text", returns: "SETOF uuid", security: "invoker" },
388
+ { name: "reopen_declared_doors", args: "", returns: "TABLE(reopened text)", security: "definer" },
389
+ { name: "required_epoch", args: "p_container_type text, p_container_id uuid, p_item_type text, p_item_id uuid", returns: "bigint", security: "definer" },
390
+ { name: "resolve_first_match", args: "p_organization_id uuid, p_record_id uuid", returns: "jsonb", security: "invoker" },
391
+ { name: "resolve_id", args: "p_organization_id uuid, p_id uuid", returns: "uuid", security: "invoker" },
392
+ { name: "retired_actor_words", args: "", returns: "jsonb", security: "invoker" },
393
+ { name: "rollup_value", args: "p_organization_id uuid, p_record_id uuid, p_field_data jsonb", returns: "jsonb", security: "invoker" },
394
+ { name: "rule_applies", args: "p_organization_id uuid, p_rule_id uuid, p_record_id uuid", returns: "jsonb", security: "invoker" },
395
+ { name: "rule_context", args: "p_organization_id uuid, p_record_id uuid", returns: "jsonb", security: "invoker" },
396
+ { name: "rule_dependency_edges", args: "p_organization_id uuid, p_row custom.record DEFAULT NULL::custom.record", returns: "TABLE(needs text, needed text)", security: "invoker" },
397
+ { name: "rule_eval", args: "p_organization_id uuid, p_expr jsonb, p_values jsonb, p_context jsonb DEFAULT '{}'::jsonb", returns: "jsonb", security: "invoker" },
398
+ { name: "rule_field_key", args: "p_organization_id uuid, p_field_id uuid", returns: "text", security: "invoker" },
399
+ { name: "rule_field_label", args: "p_organization_id uuid, p_field_id uuid", returns: "text", security: "invoker" },
400
+ { name: "rule_kernel_id", args: "", returns: "uuid", security: "invoker" },
401
+ { name: "rule_members", args: "p_organization_id uuid, p_rule_id uuid", returns: "SETOF custom.record", security: "invoker" },
402
+ { name: "rule_membership", args: "p_organization_id uuid, p_rule_id uuid, p_record_id uuid", returns: "jsonb", security: "invoker" },
403
+ { name: "rule_node_kinds", args: "", returns: "TABLE(node text, evaluated_by text, note text)", security: "invoker" },
404
+ { name: "rule_run", args: "p_organization_id uuid, p_rule_id uuid, p_values jsonb, p_context jsonb DEFAULT '{}'::jsonb", returns: "jsonb", security: "invoker" },
405
+ { name: "rule_truth", args: "p_answer jsonb", returns: "boolean", security: "invoker" },
406
+ { name: "rule_uses", args: "", returns: "text[]", security: "invoker" },
407
+ { name: "rule_version", args: "p_organization_id uuid, p_rule_id uuid", returns: "integer", security: "invoker" },
408
+ { name: "size_refusal", args: "p_organization_id uuid, p_data jsonb", returns: "text", security: "invoker" },
409
+ { name: "source_next_pointer", args: "p_sources jsonb", returns: "text", security: "invoker" },
410
+ { name: "source_pointer", args: "p_sources jsonb, p_source jsonb", returns: "text", security: "invoker" },
411
+ { name: "stamp_value_envelopes", args: "p_data jsonb, p_actor text, p_on_behalf_of text, p_at timestamp with time zone", returns: "jsonb", security: "invoker" },
412
+ { name: "storage_modes", args: "", returns: "text[]", security: "invoker" },
413
+ { name: "store_is_open", args: "p_organization_id uuid DEFAULT NULL::uuid", returns: "boolean", security: "invoker" },
414
+ { name: "table_capacity", args: "p_organization_id uuid, p_table_id uuid", returns: "jsonb", security: "definer" },
415
+ { name: "table_declare", args: "p_organization_id uuid, p_spec jsonb", returns: "uuid", security: "definer" },
416
+ { name: "table_kernel_id", args: "", returns: "uuid", security: "invoker" },
417
+ { name: "table_record_ceiling", args: "", returns: "integer", security: "invoker" },
418
+ { name: "table_record_ceiling", args: "p_organization_id uuid", returns: "integer", security: "invoker" },
419
+ { name: "table_rules", args: "p_organization_id uuid, p_table_id uuid, p_use text, p_record_type text DEFAULT NULL::text", returns: "SETOF custom.record", security: "invoker" },
420
+ { name: "table_storage", args: "p_organization_id uuid, p_table_id uuid", returns: "text", security: "invoker" },
421
+ { name: "table_type_field", args: "p_organization_id uuid, p_table_id uuid", returns: "text", security: "invoker" },
422
+ { name: "tables_at_home", args: "p_organization_id uuid, p_home_ids uuid[]", returns: "TABLE(table_id uuid, home_record_id uuid, kind text)", security: "invoker" },
423
+ { name: "trg_associations_bump_visibility", args: "", returns: "trigger", security: "definer" },
424
+ { name: "validate_custom_fields", args: "p_token text, p_organization_id uuid, p_values jsonb", returns: "void", security: "invoker" },
425
+ { name: "validate_value_envelope", args: "p_organization_id uuid, p_fields custom.record[], p_data jsonb", returns: "void", security: "invoker" },
426
+ { name: "validate_values", args: "p_organization_id uuid, p_fields custom.record[], p_values jsonb, p_record_type text DEFAULT NULL::text", returns: "void", security: "invoker" },
427
+ { name: "value_alternate_keys", args: "", returns: "text[]", security: "invoker" },
428
+ { name: "value_envelope_keys", args: "", returns: "text[]", security: "invoker" },
429
+ { name: "value_envelope_ok", args: "p_data jsonb", returns: "boolean", security: "invoker" },
430
+ { name: "value_envelope_refusal", args: "p_data jsonb", returns: "text", security: "invoker" },
431
+ { name: "value_read", args: "p_organization_id uuid, p_record_id uuid, p_key text", returns: "TABLE(field_key text, field_id uuid, value jsonb, value_version integer, source jsonb, absent_reason text, actor text, on_behalf_of text, written_at timestamp with time zone, alternates jsonb)", security: "invoker" },
432
+ { name: "value_versions", args: "p_old jsonb, p_new jsonb", returns: "jsonb", security: "invoker" },
433
+ { name: "visibility_ancestors", args: "p_item_type text, p_item_id uuid", returns: "TABLE(container_type text, container_id uuid, depth integer, max_level permission_level)", security: "definer" },
434
+ { name: "visibility_cache_rebuild", args: "", returns: "integer", security: "definer" },
435
+ { name: "visibility_parity", args: "", returns: "TABLE(side text, container_type text, container_id uuid, item_type text, item_id uuid, stored_level permission_level, derived_level permission_level, reason text)", security: "definer" },
436
+ { name: "visibility_warm", args: "p_container_type text, p_container_id uuid", returns: "integer", security: "definer" },
437
+ { name: "visible_record_ids", args: "p_user_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level", returns: "TABLE(id uuid)", security: "definer" },
438
+ { name: "work_assignment_fields", args: "p_options_table_id uuid DEFAULT NULL::uuid", returns: "TABLE(key text, label text, spec jsonb)", security: "invoker" },
439
+ { name: "work_has_assignment", args: "p_organization_id uuid, p_table_id uuid", returns: "boolean", security: "invoker" },
440
+ { name: "work_instantiation_shape", args: "p_organization_id uuid, p_instantiation_id uuid", returns: "jsonb", security: "invoker" },
441
+ { name: "work_relation_kinds", args: "", returns: "TABLE(kind text, available boolean, why text)", security: "invoker" },
442
+ { name: "work_slot_expire", args: "p_organization_id uuid, p_table_id uuid", returns: "integer", security: "invoker" },
443
+ { name: "work_slot_hold", args: "p_organization_id uuid, p_table_id uuid, p_slot_key text, p_holder text, p_ttl interval DEFAULT '00:15:00'::interval", returns: "jsonb", security: "invoker" },
444
+ { name: "work_slot_holds", args: "p_organization_id uuid, p_table_id uuid", returns: "TABLE(hold_id uuid, slot_key text, holder text, expires_at timestamp with time zone, expired boolean)", security: "invoker" },
445
+ { name: "work_slot_index_name", args: "p_table_id uuid", returns: "text", security: "invoker" },
446
+ { name: "work_slot_release", args: "p_organization_id uuid, p_hold_id uuid", returns: "boolean", security: "invoker" },
447
+ { name: "work_slots_declare", args: "p_organization_id uuid, p_name text, p_slug text, p_home_id uuid DEFAULT NULL::uuid", returns: "jsonb", security: "invoker" },
448
+ { name: "work_states", args: "", returns: "TABLE(sort integer, name text, terminal boolean, next text[])", security: "invoker" },
449
+ { name: "work_take_assignment", args: "p_organization_id uuid, p_table_id uuid", returns: "jsonb", security: "invoker" },
450
+ { name: "work_template_declare", args: "p_organization_id uuid, p_name text, p_graph jsonb", returns: "uuid", security: "invoker" },
451
+ { name: "work_template_instantiate", args: "p_organization_id uuid, p_template_id uuid, p_overrides jsonb DEFAULT '{}'::jsonb", returns: "jsonb", security: "invoker" },
452
+ { name: "work_template_refusal", args: "p_graph jsonb", returns: "text", security: "invoker" },
453
+ { name: "work_template_shape", args: "p_organization_id uuid, p_template_id uuid", returns: "jsonb", security: "invoker" },
454
+ { name: "work_transition_refusal", args: "p_organization_id uuid, p_from_state_id uuid, p_to_state_id uuid", returns: "text", security: "invoker" },
455
+ { name: "work_whose_turn", args: "p_organization_id uuid, p_table_id uuid, p_include_finished boolean DEFAULT false", returns: "TABLE(record_id uuid, title text, assignee_id uuid, turn text, due_on timestamp with time zone, state text, status text, terminal boolean)", security: "invoker" }
456
+ ];
457
+ var STORE_KNOBS = [
458
+ { key: "accessible_entity_ids_guard", value: "false", type: "boolean" },
459
+ { key: "associations_guard", value: "false", type: "boolean" },
460
+ { key: "code_paths_enabled", value: "false", type: "boolean" },
461
+ { key: "containment_depth_ceiling", value: "16", type: "integer" },
462
+ { key: "document_max_bytes", value: "1048576", type: "integer" },
463
+ { key: "emergency_door_guard", value: "false", type: "boolean" },
464
+ { key: "emergency_door_sweep_enabled", value: "false", type: "boolean" },
465
+ { key: "entity_custom_fields_guard", value: "false", type: "boolean" },
466
+ { key: "entity_types_guard", value: "false", type: "boolean" },
467
+ { key: "external_principal_enabled", value: "false", type: "boolean" },
468
+ { key: "field_index_guard", value: "false", type: "boolean" },
469
+ { key: "field_sensitivity_levels", value: '{"edit": {"public": "editor", "internal": "editor", "restricted": "admin", "confidential": "admin"}, "read": {"public": "viewer", "internal": "viewer", "restricted": "admin", "confidential": "editor"}}', type: "json" },
470
+ { key: "member_default_level", value: '"viewer"', type: "string" },
471
+ { key: "row_versions_guard", value: "false", type: "boolean" },
472
+ { key: "sandbox_expanded_frame_height_px", value: "20000", type: "integer" },
473
+ { key: "sandbox_frame_height_px", value: "4000", type: "integer" },
474
+ { key: "sandbox_message_bytes", value: "65536", type: "integer" },
475
+ { key: "sandbox_org_components", value: "true", type: "boolean" },
476
+ { key: "signup_provisioning_guard", value: "false", type: "boolean" },
477
+ { key: "system_enabled", value: "false", type: "boolean" },
478
+ { key: "table_record_ceiling", value: "150000", type: "integer" },
479
+ { key: "value_max_bytes", value: "100000", type: "integer" },
480
+ { key: "world_publish_enabled", value: "false", type: "boolean" }
481
+ ];
482
+ var STORE_REFUSAL_CODES = [
483
+ { code: "02000", raised_by: "doc_render_body,doc_render_document,doc_sign,doc_signature_intact,doc_template_save,external_history_event,external_rows,external_stub_upsert,external_writes_set,migrate_delete,migrate_extract_parent,migrate_merge,migrate_rename,migrate_reparent,migrate_retype,migrate_split,read_record,record_delete,record_restore,record_update" },
484
+ { code: "0A000", raised_by: "external_rows,external_source_declare,external_write_through,promote_field,promoted_index_expr,promoted_query_sql,promoted_read,rule_eval,work_slots_declare" },
485
+ { code: "22004", raised_by: "_value_envelope,actor_word,agg_assert_key,agg_sql,anon_capture,anon_token_issue,anon_write,assert_client_may_reach,doc_render_write,doc_sign,doc_signature_write,doc_template_save,external_history_event,external_rows,external_source_declare,external_stub_upsert,external_write_through,external_writes_set,home_add,io_comment_write,io_import_open,io_outbox_drain,io_restore,migrate_purge,migrate_split,query_across_homes,query_by_coordinates,query_rollup,record_delete,record_reparent,record_restore,record_update,record_write,relation_own,table_declare,work_template_declare" },
486
+ { code: "22012", raised_by: "rule_eval" },
487
+ { code: "22023", raised_by: "_value_envelope,_work_shape_guard,actor_word,agg_assert_key,agg_sql,anon_token_issue,containment_parent,doc_render_body,doc_render_write,doc_signature_write,external_history_event,external_source_declare,external_stub_upsert,external_write_through,io_import_open,io_proposal_accept,migrate_merge,query_by_coordinates,query_rollup,record_update,rule_eval,rule_members,table_rules,work_slot_hold" },
488
+ { code: "23503", raised_by: "_containment_guard,_record_rule_uses,anon_publish,anon_rate_take,anon_token_issue,anon_write,assert_organization_wall,doc_sign,doc_template_save,home_add,io_comment_write,io_import_rows,io_proposal_accept,migrate_delete,migrate_demote,migrate_promote,promote_field,promote_table,record_applicability,record_reparent,relation_own,resolve_first_match,rule_applies,rule_eval,rule_members,rule_run,work_take_assignment,work_template_instantiate" },
489
+ { code: "23505", raised_by: "doc_sign,doc_signature_write,home_add,io_proposal_accept,work_slot_hold" },
490
+ { code: "23514", raised_by: "_containment_guard,_dated_values_guard,_derived_fields,_field_shape_guard,_field_type_parity_guard,_merge_field_shape_guard,_merge_field_temporal_guard,_promoted_field_cap_guard,_record_rule_uses,_rule_shape_guard,_rule_topology_guard,_table_shape_guard,_value_envelope,_work_shape_guard,doc_sign,doc_signature_write,doc_template_save,home_add,validate_value_envelope,validate_values,work_slots_declare,work_take_assignment,work_template_instantiate" },
491
+ { code: "40001", raised_by: "has_visibility_at" },
492
+ { code: "42501", raised_by: "_doc_render_immutable,_doc_signature_immutable,_field_definition_write,_field_write_door,_rule_definition_write,_store_door,anon_capture,anon_inbound_land,anon_publish,anon_token_issue,anon_token_verify,anon_write,assert_client_may_reach,assert_store_door,external_write_through,io_comment_resolve,io_comment_write,io_restore,migrate_purge,promote_table,read_record,read_records" },
493
+ { code: "53400", raised_by: "anon_rate_take,promote_field" },
494
+ { code: "PT409", raised_by: "record_update" }
495
+ ];
496
+ var ENTITY_TOKENS = [
497
+ "access_delta_probe",
498
+ "access_delta_run",
499
+ "access_request",
500
+ "account_addon",
501
+ "acquisition_block",
502
+ "activity",
503
+ "admin_audit_log",
504
+ "admin_email_log",
505
+ "admin_markdown_sample",
506
+ "admin_user",
507
+ "admission_config",
508
+ "agent",
509
+ "agent_card",
510
+ "agent_definition_version",
511
+ "agent_drift_alert",
512
+ "agent_exemplar",
513
+ "agent_mandate_note",
514
+ "agent_prompt_remediation",
515
+ "agent_provision_legacy",
516
+ "agent_run",
517
+ "agent_run_stage",
518
+ "agent_schedule",
519
+ "agent_schedule_claim",
520
+ "agent_shortcut",
521
+ "agent_surface_binding",
522
+ "agent_template",
523
+ "agent_usage",
524
+ "agent_user_kv",
525
+ "ai_api",
526
+ "ai_endpoint",
527
+ "ai_model",
528
+ "ai_model_alias",
529
+ "ai_offering",
530
+ "ai_provider",
531
+ "ai_setting",
532
+ "analysis_result",
533
+ "anon_form",
534
+ "anon_function_birth_grandfather",
535
+ "anon_hit",
536
+ "anon_inbound",
537
+ "anon_replay",
538
+ "anon_submission",
539
+ "anon_token",
540
+ "api_field_warning",
541
+ "api_request_log",
542
+ "app",
543
+ "app_config",
544
+ "app_config_history",
545
+ "app_definition_version",
546
+ "app_error",
547
+ "app_execution",
548
+ "app_instance",
549
+ "app_log",
550
+ "app_log_muted_pattern",
551
+ "app_log_norm_exception",
552
+ "app_rate_limit",
553
+ "app_setting",
554
+ "app_sync_status",
555
+ "approach",
556
+ "artifact",
557
+ "assessment",
558
+ "assessment_item",
559
+ "assessment_result",
560
+ "assignment_session",
561
+ "assist",
562
+ "assist_producer_policy",
563
+ "assist_producer_policy_history",
564
+ "association_type",
565
+ "assurance_level",
566
+ "attempt",
567
+ "audit_broken_functions",
568
+ "audit_canonical_findings",
569
+ "audit_exemption",
570
+ "audit_function_deps",
571
+ "audit_function_runtime_probe",
572
+ "audit_m2m_candidates",
573
+ "audit_refresh_log",
574
+ "audit_stale_registry",
575
+ "audit_unregistered_candidates",
576
+ "bak_assoc_file_processed_document_20260812",
577
+ "bak_assoc_type_file_processed_document_20260812",
578
+ "bak_organization_name_dd043",
579
+ "base_entity_template",
580
+ "batch_cost_event",
581
+ "batch_provider_batch",
582
+ "batch_work_item",
583
+ "billing_capability",
584
+ "billing_capability_limit",
585
+ "billing_connect_account",
586
+ "billing_customer",
587
+ "billing_plan",
588
+ "billing_plan_limit",
589
+ "billing_price",
590
+ "billing_product",
591
+ "billing_spend_guardrail",
592
+ "billing_stripe_event",
593
+ "billing_subscription",
594
+ "billing_usage_ledger",
595
+ "billing_user_plan",
596
+ "browser_account_binding",
597
+ "browser_action_event",
598
+ "browser_authenticator_window",
599
+ "browser_capture",
600
+ "browser_control_request",
601
+ "browser_handoff",
602
+ "browser_login_attempt",
603
+ "browser_login_recipe",
604
+ "browser_profile",
605
+ "browser_profile_checkpoint",
606
+ "browser_run",
607
+ "browser_site_observation",
608
+ "browser_site_policy",
609
+ "browser_stream_ticket",
610
+ "build_lock",
611
+ "calendar_event",
612
+ "canvas_comment",
613
+ "canvas_comment_like",
614
+ "canvas_item",
615
+ "canvas_item_state",
616
+ "canvas_like",
617
+ "canvas_score",
618
+ "canvas_view",
619
+ "capture_window",
620
+ "carrying_rule",
621
+ "catalog_entries_history",
622
+ "catalog_entry",
623
+ "category",
624
+ "change_type_default",
625
+ "chat_user_usage_summary",
626
+ "citations",
627
+ "class_purchase",
628
+ "classifier_revision_ledger",
629
+ "client_callable_door",
630
+ "client_callable_door_retirement",
631
+ "client_excluded_column_unregistered",
632
+ "cmp_entry",
633
+ "cmp_feedback",
634
+ "code_file",
635
+ "code_folder",
636
+ "code_repository",
637
+ "coding_session",
638
+ "coding_session_entry",
639
+ "comment",
640
+ "commerce_asset_allocation",
641
+ "commerce_asset_grading",
642
+ "commerce_asset_identifier",
643
+ "commerce_asset_lot_event",
644
+ "commerce_asset_mandate_result",
645
+ "commerce_asset_price_factor",
646
+ "commerce_asset_reshoot_request",
647
+ "commerce_asset_review",
648
+ "commerce_asset_unknown",
649
+ "commerce_certified_printer",
650
+ "commerce_cloud_sync_connection",
651
+ "commerce_ebay_business_policy",
652
+ "commerce_ebay_category",
653
+ "commerce_ebay_category_aspect",
654
+ "commerce_ebay_category_tree",
655
+ "commerce_ebay_custom_policy",
656
+ "commerce_ebay_inventory_item",
657
+ "commerce_ebay_inventory_item_group",
658
+ "commerce_ebay_inventory_item_group_member",
659
+ "commerce_ebay_inventory_location",
660
+ "commerce_ebay_listing",
661
+ "commerce_ebay_marketplace_policy",
662
+ "commerce_ebay_media_asset",
663
+ "commerce_ebay_notification_destination",
664
+ "commerce_ebay_notification_event",
665
+ "commerce_ebay_notification_subscription",
666
+ "commerce_ebay_notification_topic",
667
+ "commerce_ebay_offer",
668
+ "commerce_ebay_order",
669
+ "commerce_ebay_order_line_item",
670
+ "commerce_ebay_shipping_fulfillment",
671
+ "commerce_ebay_store_category",
672
+ "commerce_human_correction",
673
+ "commerce_intake_artifact",
674
+ "commerce_intake_asset",
675
+ "commerce_intake_batch",
676
+ "commerce_label_batch",
677
+ "commerce_label_code",
678
+ "commerce_marketplace_account",
679
+ "commerce_marketplace_account_deletion_audit",
680
+ "commerce_marketplace_api_call",
681
+ "commerce_marketplace_rate_budget",
682
+ "commerce_marketplace_site",
683
+ "commerce_marketplace_sync_run",
684
+ "commerce_prediction_outcome",
685
+ "commerce_print_order",
686
+ "commerce_product",
687
+ "commerce_product_channel_ref",
688
+ "commerce_product_media",
689
+ "commerce_product_variant",
690
+ "commerce_recall_audit",
691
+ "comparison_set",
692
+ "component_group",
693
+ "contact_medium",
694
+ "contact_submission",
695
+ "content_certification",
696
+ "content_ir_kind",
697
+ "content_ir_kind_component",
698
+ "content_ir_kind_component_incident",
699
+ "content_ir_kind_conformance",
700
+ "content_ir_kind_edge",
701
+ "content_ir_kind_example",
702
+ "content_ir_kind_instance",
703
+ "content_ir_kind_surface",
704
+ "context_access_log",
705
+ "context_item",
706
+ "context_item_suggestion",
707
+ "context_item_value",
708
+ "context_value_refs",
709
+ "conversation",
710
+ "conversation_value",
711
+ "courts",
712
+ "credential_attachment",
713
+ "credential_item",
714
+ "credential_mutation_receipt",
715
+ "crm_address",
716
+ "crm_affiliation",
717
+ "crm_blocklist_entry",
718
+ "crm_contact_candidate",
719
+ "crm_deal",
720
+ "crm_deal_stage_event",
721
+ "crm_enrichment_call",
722
+ "crm_interaction",
723
+ "crm_merge_candidate",
724
+ "crm_outreach_list",
725
+ "crm_outreach_list_member",
726
+ "crm_party_merge",
727
+ "crm_registry_ingest_run",
728
+ "crm_registry_source",
729
+ "crm_saved_view",
730
+ "crm_sending_event",
731
+ "crm_sending_identity",
732
+ "crm_sending_identity_check",
733
+ "crm_sending_policy",
734
+ "custom_entity_definition",
735
+ "custom_field_definition",
736
+ "custom_field_target",
737
+ "custom_record",
738
+ "cx_agent_memory",
739
+ "cx_agent_plan",
740
+ "cx_agent_task",
741
+ "cx_code_edit",
742
+ "cx_code_message_file",
743
+ "cx_conversation_documents",
744
+ "cx_media",
745
+ "cx_observational_memory",
746
+ "cx_observational_memory_event",
747
+ "cx_pending_injection",
748
+ "cx_request",
749
+ "cx_request_snapshot",
750
+ "cx_tool_trace",
751
+ "cx_user_request",
752
+ "cx_user_todo",
753
+ "dashboard_saved_view",
754
+ "data_rights_event",
755
+ "data_store",
756
+ "data_store_members",
757
+ "dataset",
758
+ "dd171_containment_baseline",
759
+ "dd175_cast",
760
+ "dd175_component_lane_baseline",
761
+ "ddl_guard_log",
762
+ "deck_suggestion",
763
+ "definer_class_exemption",
764
+ "definer_client_grant_grandfather",
765
+ "definer_grant_baseline",
766
+ "deprecated_relation",
767
+ "derive_run",
768
+ "dev_login_audit",
769
+ "dict_entry",
770
+ "dict_provider_publication",
771
+ "dict_setting",
772
+ "dm_conversation",
773
+ "dm_message",
774
+ "dm_participant",
775
+ "doc_render",
776
+ "doc_signature",
777
+ "dockets",
778
+ "domain_classification",
779
+ "edge_payload_kind",
780
+ "egress_device",
781
+ "egress_pairing",
782
+ "egress_ticket",
783
+ "emails",
784
+ "embedding_cache",
785
+ "embeddings_google_gemini_2_1536",
786
+ "embeddings_oai_3_small_1536",
787
+ "embeddings_voyage_4_large_1024",
788
+ "embeddings_voyage_code_3_1024",
789
+ "endpoint_family_sweep_state",
790
+ "engine_owner_task",
791
+ "entity_grant",
792
+ "entity_relationship",
793
+ "entity_type",
794
+ "esign_campaign",
795
+ "esign_campaign_member",
796
+ "esign_consent_disclosure",
797
+ "esign_envelope",
798
+ "esign_envelope_certificate",
799
+ "esign_envelope_document",
800
+ "esign_envelope_event",
801
+ "esign_envelope_external_ref",
802
+ "esign_envelope_signer",
803
+ "esign_provider",
804
+ "esign_provider_binding",
805
+ "esign_signing_key",
806
+ "execution_event_cursor",
807
+ "extension_auth_code",
808
+ "external_link",
809
+ "external_source",
810
+ "extract_sweep_state",
811
+ "fc_card",
812
+ "fc_detail",
813
+ "fc_set",
814
+ "feature_doc",
815
+ "feature_knob",
816
+ "feedback_comments",
817
+ "feedback_user_messages",
818
+ "field_component",
819
+ "file",
820
+ "file_analysis",
821
+ "file_entities",
822
+ "file_overrides",
823
+ "file_page_annotations",
824
+ "file_pages",
825
+ "file_rag_job",
826
+ "file_version",
827
+ "files_account_tier",
828
+ "files_machine_written_prefix",
829
+ "files_sync_mapping",
830
+ "files_user_account",
831
+ "flashcard_data",
832
+ "flashcard_history",
833
+ "flashcard_review",
834
+ "flashcard_set",
835
+ "flashcard_sets",
836
+ "flexible_data",
837
+ "folder",
838
+ "function_contract",
839
+ "game_badge",
840
+ "game_result",
841
+ "game_room",
842
+ "global_execution",
843
+ "global_execution_checkpoint",
844
+ "global_execution_control",
845
+ "global_execution_event",
846
+ "global_meter_entry",
847
+ "global_origin",
848
+ "global_request",
849
+ "google_document",
850
+ "growth_loop_event",
851
+ "growth_loop_run",
852
+ "growth_loop_stage_run",
853
+ "guardian_link",
854
+ "guest_conversion_audit",
855
+ "guest_execution_log",
856
+ "guest_executions",
857
+ "guided_checklist_run",
858
+ "heatmap_save",
859
+ "hindsight_enrollment",
860
+ "hindsight_finding",
861
+ "hindsight_regression_case",
862
+ "hindsight_replay",
863
+ "hindsight_replay_step",
864
+ "hindsight_review",
865
+ "hr_access_audit",
866
+ "hr_access_role",
867
+ "hr_accommodation_request",
868
+ "hr_ai_evidence",
869
+ "hr_alert_routing_rule",
870
+ "hr_application",
871
+ "hr_approval_authority",
872
+ "hr_approval_delegation",
873
+ "hr_asset",
874
+ "hr_asset_assignment",
875
+ "hr_attendance_exception",
876
+ "hr_auto_close_rule",
877
+ "hr_availability",
878
+ "hr_background_check",
879
+ "hr_benefits_event",
880
+ "hr_calculation_snapshot",
881
+ "hr_candidate",
882
+ "hr_candidate_conversion",
883
+ "hr_candidate_message",
884
+ "hr_careers_portal",
885
+ "hr_checklist_item",
886
+ "hr_checklist_run",
887
+ "hr_checklist_template",
888
+ "hr_checklist_template_item",
889
+ "hr_compensation",
890
+ "hr_corrective_action",
891
+ "hr_course",
892
+ "hr_course_version",
893
+ "hr_credential",
894
+ "hr_crew",
895
+ "hr_deduction_code",
896
+ "hr_department",
897
+ "hr_derived_grant",
898
+ "hr_disposition_event",
899
+ "hr_earning_code",
900
+ "hr_eeo_response",
901
+ "hr_emergency_contact",
902
+ "hr_employee",
903
+ "hr_employee_private",
904
+ "hr_employer_profile",
905
+ "hr_employment",
906
+ "hr_employment_pin",
907
+ "hr_engagement",
908
+ "hr_establishment",
909
+ "hr_external_identity",
910
+ "hr_field_policy",
911
+ "hr_holiday",
912
+ "hr_holiday_calendar",
913
+ "hr_i9",
914
+ "hr_i9_document",
915
+ "hr_incident",
916
+ "hr_incident_party",
917
+ "hr_interview",
918
+ "hr_interview_kit",
919
+ "hr_job_title",
920
+ "hr_jurisdiction",
921
+ "hr_jurisdiction_rule",
922
+ "hr_jurisdiction_rule_class",
923
+ "hr_jurisdiction_rule_org_decision",
924
+ "hr_jurisdiction_rule_test",
925
+ "hr_kiosk_device",
926
+ "hr_kiosk_session",
927
+ "hr_labor_target",
928
+ "hr_leave_case",
929
+ "hr_leave_enrollment",
930
+ "hr_leave_ledger",
931
+ "hr_leave_policy",
932
+ "hr_leave_request",
933
+ "hr_legal_hold",
934
+ "hr_legal_hold_item",
935
+ "hr_location",
936
+ "hr_new_hire_report",
937
+ "hr_offer",
938
+ "hr_opening",
939
+ "hr_overtime_alert",
940
+ "hr_overtime_alert_rule",
941
+ "hr_overtime_preapproval",
942
+ "hr_pay_group",
943
+ "hr_pay_period",
944
+ "hr_pay_period_employment",
945
+ "hr_payroll_export",
946
+ "hr_payroll_export_line",
947
+ "hr_position_assignment",
948
+ "hr_posting",
949
+ "hr_posting_publication",
950
+ "hr_provider_binding",
951
+ "hr_provider_event",
952
+ "hr_provisioning_result",
953
+ "hr_punch",
954
+ "hr_recalculation_batch",
955
+ "hr_record_class",
956
+ "hr_records_request",
957
+ "hr_reference_check",
958
+ "hr_reporting_line",
959
+ "hr_requisition",
960
+ "hr_restricted_note",
961
+ "hr_retention_rule",
962
+ "hr_role_assignment",
963
+ "hr_schedule",
964
+ "hr_schedule_change",
965
+ "hr_schedule_guidance",
966
+ "hr_schedule_template",
967
+ "hr_schedule_template_shift",
968
+ "hr_scorecard",
969
+ "hr_separation",
970
+ "hr_shift",
971
+ "hr_shift_claim",
972
+ "hr_staffing_requirement",
973
+ "hr_survey",
974
+ "hr_survey_invitation",
975
+ "hr_survey_question",
976
+ "hr_survey_response",
977
+ "hr_tax_registration",
978
+ "hr_tax_withholding",
979
+ "hr_time_adjustment",
980
+ "hr_training_assignment",
981
+ "hr_training_attempt",
982
+ "hr_transcript_entry",
983
+ "hr_verification_letter_request",
984
+ "hr_work_interval",
985
+ "hr_workflow_binding",
986
+ "hr_workflow_decision",
987
+ "hr_workflow_definition",
988
+ "hr_workflow_event",
989
+ "hr_workflow_failure",
990
+ "hr_workflow_flow_type",
991
+ "hr_workflow_instance",
992
+ "hr_workflow_step",
993
+ "hr_workflow_step_definition",
994
+ "hr_workweek",
995
+ "html_extraction",
996
+ "iam_access_audit",
997
+ "iam_api_key",
998
+ "iam_emergency_door_request",
999
+ "idempotency",
1000
+ "industry",
1001
+ "industry_curator",
1002
+ "infra_status",
1003
+ "ingest_runs",
1004
+ "integration_connection",
1005
+ "integration_connection_resource",
1006
+ "interview_decision_interview",
1007
+ "interview_decision_question",
1008
+ "interview_document_revision",
1009
+ "interview_hole",
1010
+ "interview_question",
1011
+ "interview_session",
1012
+ "interview_turn",
1013
+ "invitation",
1014
+ "invitation_code",
1015
+ "invitation_request",
1016
+ "io_comment",
1017
+ "io_contract",
1018
+ "io_import",
1019
+ "io_outbox",
1020
+ "item",
1021
+ "item_mastery",
1022
+ "judge_verdict",
1023
+ "jurisdiction_policy",
1024
+ "keyword_classification_queue",
1025
+ "kg_alert",
1026
+ "kg_chunk_entities",
1027
+ "kg_chunks",
1028
+ "kg_clusters",
1029
+ "kg_edges",
1030
+ "kg_entities",
1031
+ "kg_entity_aliases",
1032
+ "kg_suggestion_ack",
1033
+ "kg_sweep_queue",
1034
+ "kg_sweep_run",
1035
+ "kg_sweep_state",
1036
+ "kg_value_match",
1037
+ "knob_override",
1038
+ "knob_override_audit",
1039
+ "knob_rung_lock",
1040
+ "knob_scope_kind",
1041
+ "knob_write_door",
1042
+ "league_membership",
1043
+ "learn_doc",
1044
+ "library_doc",
1045
+ "lifecycle_archive",
1046
+ "lifecycle_archive_row",
1047
+ "lifecycle_audit",
1048
+ "lifecycle_entity_plan",
1049
+ "lifecycle_map_build",
1050
+ "lifecycle_reference_map",
1051
+ "lifecycle_run",
1052
+ "lifecycle_tier_ledger",
1053
+ "location",
1054
+ "mandate",
1055
+ "mandate_advance_batch_row",
1056
+ "mandate_binding",
1057
+ "mandate_binding_legacy",
1058
+ "mandate_legacy",
1059
+ "mandate_observation",
1060
+ "mandate_reference",
1061
+ "mandate_scan",
1062
+ "mandate_treatment",
1063
+ "marketing_initiative",
1064
+ "masterwork_corpus_item",
1065
+ "masterwork_run",
1066
+ "masterwork_run_kind",
1067
+ "masterwork_source",
1068
+ "math_course_structure",
1069
+ "math_problem",
1070
+ "matrx_action_ledger",
1071
+ "mcp_config",
1072
+ "mcp_server",
1073
+ "mcp_user_conn",
1074
+ "media_capture_handoff",
1075
+ "media_catalog_setting",
1076
+ "media_library_item",
1077
+ "media_selection_item",
1078
+ "media_selection_job",
1079
+ "media_source_library",
1080
+ "meet_call_invite",
1081
+ "meet_meeting",
1082
+ "meet_note",
1083
+ "meet_participant",
1084
+ "meet_recording",
1085
+ "meet_transcript_segment",
1086
+ "membership",
1087
+ "membership_grant",
1088
+ "merge_field_provenance",
1089
+ "message",
1090
+ "message_template",
1091
+ "meta_excluded_schema",
1092
+ "meta_table_stats_history",
1093
+ "metadata_reserved_keys",
1094
+ "microservice_project",
1095
+ "migration_log",
1096
+ "mtx_media_heal_queue",
1097
+ "mtx_public_url_guard",
1098
+ "ner_shadow",
1099
+ "note",
1100
+ "note_folder",
1101
+ "notification",
1102
+ "notification_channel_preference",
1103
+ "notification_event_override",
1104
+ "notification_event_type",
1105
+ "notification_preference",
1106
+ "notify_outsider_door_baseline",
1107
+ "oauth_handoff_claim",
1108
+ "opinion_clusters",
1109
+ "opinions",
1110
+ "ops_issue_class",
1111
+ "ops_issue_event",
1112
+ "ops_proof_check",
1113
+ "ops_proof_run",
1114
+ "ops_proof_scenario",
1115
+ "org_admin_audit",
1116
+ "org_change_policy",
1117
+ "org_context_ledger",
1118
+ "org_industries",
1119
+ "org_member_control",
1120
+ "org_module_config",
1121
+ "org_plan",
1122
+ "org_repair_0253_backup",
1123
+ "organization",
1124
+ "organization_preferences",
1125
+ "organization_visibility_version",
1126
+ "output_feedback",
1127
+ "outreach_acceptance",
1128
+ "page_extraction_job",
1129
+ "page_extraction_page_run",
1130
+ "page_extraction_results",
1131
+ "page_extraction_runs",
1132
+ "page_intent_queue",
1133
+ "page_mapping_queue",
1134
+ "part_config",
1135
+ "part_config_sub",
1136
+ "party",
1137
+ "party_contact_point",
1138
+ "path_drift_repair_2026_09",
1139
+ "pc_article",
1140
+ "pc_episode",
1141
+ "pc_show",
1142
+ "pc_studio_run",
1143
+ "pc_studio_run_asset",
1144
+ "pdf_consolidation_log",
1145
+ "pdf_redaction_audit",
1146
+ "pdf_redaction_key_escrow",
1147
+ "permission_grant",
1148
+ "plan_cms_fill_item",
1149
+ "plan_cms_fill_job",
1150
+ "plan_entity",
1151
+ "plan_node",
1152
+ "plan_node_artifact",
1153
+ "plan_node_step",
1154
+ "plan_profile",
1155
+ "platform_actor_session",
1156
+ "platform_actor_token",
1157
+ "platform_actor_token_event",
1158
+ "platform_continued_access",
1159
+ "platform_org_knob_override",
1160
+ "platform_outcome_event",
1161
+ "platform_outsider_consumer",
1162
+ "platform_reachability",
1163
+ "platform_reference_category",
1164
+ "platform_reference_declaration",
1165
+ "platform_repo",
1166
+ "platform_saved_view",
1167
+ "platform_schema",
1168
+ "platform_share_link",
1169
+ "platform_user_knob_override",
1170
+ "podcast_race",
1171
+ "policy_overlap_backup",
1172
+ "policy_overlap_probe",
1173
+ "processed_document",
1174
+ "processed_document_page",
1175
+ "product_capture_file",
1176
+ "product_capture_item",
1177
+ "product_capture_payload",
1178
+ "product_capture_product",
1179
+ "product_capture_question",
1180
+ "profile",
1181
+ "project",
1182
+ "prompt",
1183
+ "provider_account",
1184
+ "provider_account_credential",
1185
+ "provision",
1186
+ "provision_generate_target",
1187
+ "provision_grant",
1188
+ "provision_marker",
1189
+ "provision_rule_message",
1190
+ "provision_schema",
1191
+ "provision_shape_debt",
1192
+ "provision_spec",
1193
+ "provision_spec_grandfather",
1194
+ "provision_vocabulary",
1195
+ "purpose",
1196
+ "quiz_session",
1197
+ "rag_ingest_run",
1198
+ "rag_library_audit_log",
1199
+ "rate_limit_buckets",
1200
+ "recompute_queue",
1201
+ "record",
1202
+ "record_alias",
1203
+ "redaction_mapping",
1204
+ "research_analysis",
1205
+ "research_content",
1206
+ "research_context_bundle",
1207
+ "research_document",
1208
+ "research_intent",
1209
+ "research_keyword",
1210
+ "research_media",
1211
+ "research_source",
1212
+ "research_synthesis",
1213
+ "research_tag",
1214
+ "research_template",
1215
+ "research_topic",
1216
+ "retention_policy",
1217
+ "retrieval_audit",
1218
+ "review_queue",
1219
+ "route_manifest_entry",
1220
+ "row_version",
1221
+ "rulebook",
1222
+ "runtime_operation_stream",
1223
+ "runtime_operation_stream_batch",
1224
+ "sandbox_instance",
1225
+ "sch_agent_task",
1226
+ "sch_run",
1227
+ "sch_task",
1228
+ "sch_trigger",
1229
+ "schema_client_exposure",
1230
+ "schema_migration_ledger",
1231
+ "schema_migration_legacy",
1232
+ "schema_migration_slot_grandfather",
1233
+ "schema_templates",
1234
+ "scope",
1235
+ "scope_association_suggestion",
1236
+ "scope_dataset_instance",
1237
+ "scope_door_registry",
1238
+ "scope_item_value_suggestion",
1239
+ "scope_suggestion",
1240
+ "scope_type",
1241
+ "scrape_domain",
1242
+ "scrape_domain_settings",
1243
+ "scrape_failure_log",
1244
+ "scrape_parsed_page",
1245
+ "scrape_path_override",
1246
+ "scrape_path_pattern",
1247
+ "scrape_retry_queue",
1248
+ "seo_ai_capability",
1249
+ "seo_ai_visibility_citation",
1250
+ "seo_ai_visibility_claim",
1251
+ "seo_ai_visibility_panel",
1252
+ "seo_ai_visibility_response",
1253
+ "seo_ai_visibility_signal",
1254
+ "seo_backlink",
1255
+ "seo_backlink_change_event",
1256
+ "seo_backlink_dimension_snapshot",
1257
+ "seo_backlink_observation",
1258
+ "seo_backlink_snapshot",
1259
+ "seo_change_assessment",
1260
+ "seo_change_event",
1261
+ "seo_change_item",
1262
+ "seo_change_metric",
1263
+ "seo_change_set",
1264
+ "seo_change_theory",
1265
+ "seo_collection_run",
1266
+ "seo_competitor",
1267
+ "seo_competitor_observation",
1268
+ "seo_competitor_opportunity",
1269
+ "seo_coverage_mention",
1270
+ "seo_coverage_tracker",
1271
+ "seo_dimension_value_matcher",
1272
+ "seo_engine_schedule",
1273
+ "seo_geo_place",
1274
+ "seo_gsc_dig_rule",
1275
+ "seo_keyword",
1276
+ "seo_keyword_class_rule",
1277
+ "seo_keyword_edge",
1278
+ "seo_keyword_facet",
1279
+ "seo_keyword_market",
1280
+ "seo_keyword_market_observation",
1281
+ "seo_keyword_place",
1282
+ "seo_keyword_saved_view",
1283
+ "seo_keyword_topic",
1284
+ "seo_landscape_brief",
1285
+ "seo_link_gap_domain",
1286
+ "seo_link_gap_match",
1287
+ "seo_map_facet",
1288
+ "seo_map_facet_value",
1289
+ "seo_map_topic",
1290
+ "seo_page_measurement_health",
1291
+ "seo_page_performance",
1292
+ "seo_provider_call",
1293
+ "seo_provider_task",
1294
+ "seo_rank_observation",
1295
+ "seo_rank_target",
1296
+ "seo_raw_payload",
1297
+ "seo_referring_domain_profile",
1298
+ "seo_reputation_case",
1299
+ "seo_search_performance_daily",
1300
+ "seo_serp_mention",
1301
+ "seo_serp_opportunity",
1302
+ "seo_serp_result",
1303
+ "seo_serp_snapshot",
1304
+ "seo_site_geo_area",
1305
+ "seo_site_keyword_offering",
1306
+ "seo_site_keyword_value",
1307
+ "seo_site_offering_value",
1308
+ "seo_site_topic_value",
1309
+ "seo_site_value_combo",
1310
+ "seo_site_value_worth",
1311
+ "seo_site_vocabulary",
1312
+ "seo_source_request",
1313
+ "seo_starter_pack",
1314
+ "seo_starter_pack_item",
1315
+ "seo_story_angle",
1316
+ "seo_topic",
1317
+ "seo_topical_map",
1318
+ "seo_web_analytics_daily",
1319
+ "share_link",
1320
+ "shareable_resource_registry",
1321
+ "shared_canvas_item",
1322
+ "short_link",
1323
+ "shortcut_category",
1324
+ "skill",
1325
+ "skill_category",
1326
+ "skill_render_definition",
1327
+ "sms_consent",
1328
+ "sms_conversation",
1329
+ "sms_message",
1330
+ "sms_message_media",
1331
+ "sms_notification",
1332
+ "sms_notification_preference",
1333
+ "sms_phone_number",
1334
+ "sms_rate_limits",
1335
+ "sms_webhook_logs",
1336
+ "soft_delete_edge",
1337
+ "source_authority",
1338
+ "stage_dockets_966c18eca7",
1339
+ "stage_ref_kind",
1340
+ "stamped_write_table",
1341
+ "structure",
1342
+ "structured_list",
1343
+ "studio_cleaned_segments",
1344
+ "studio_concept_items",
1345
+ "studio_documents",
1346
+ "studio_module_segments",
1347
+ "studio_raw_segments",
1348
+ "studio_recording_chunks",
1349
+ "studio_recording_segments",
1350
+ "studio_run",
1351
+ "studio_session",
1352
+ "studio_session_settings",
1353
+ "study_attempt",
1354
+ "study_goal",
1355
+ "study_media",
1356
+ "study_plan",
1357
+ "study_plan_block",
1358
+ "study_plan_day",
1359
+ "study_reminder_context",
1360
+ "study_reminder_delivery",
1361
+ "study_session",
1362
+ "study_source_chunk",
1363
+ "study_streak",
1364
+ "study_structured_section",
1365
+ "superseded_policy",
1366
+ "surface",
1367
+ "system_announcement",
1368
+ "system_context_item",
1369
+ "system_error",
1370
+ "system_orgs",
1371
+ "system_personal_org_failure",
1372
+ "system_write_failure",
1373
+ "task",
1374
+ "task_user_state",
1375
+ "taxonomy_node",
1376
+ "template_context_items",
1377
+ "template_scope_types",
1378
+ "templates",
1379
+ "thread",
1380
+ "tool",
1381
+ "tool_binding",
1382
+ "tool_bundle",
1383
+ "tool_call",
1384
+ "tool_definition_version",
1385
+ "tool_executor",
1386
+ "tool_surface_defaults",
1387
+ "tool_test_sample",
1388
+ "tool_ui",
1389
+ "tool_ui_incident",
1390
+ "tool_ui_version",
1391
+ "topic_placement_queue",
1392
+ "transcript",
1393
+ "trigger_event",
1394
+ "udt_dataset_fields",
1395
+ "udt_dataset_row_versions",
1396
+ "udt_dataset_rows",
1397
+ "udt_dataset_template",
1398
+ "udt_dataset_template_fields",
1399
+ "udt_document",
1400
+ "udt_document_snapshot",
1401
+ "udt_structured_list_items",
1402
+ "udt_workbook_snapshot",
1403
+ "ui_client",
1404
+ "ui_surface_agent_pref",
1405
+ "ui_surface_agent_role",
1406
+ "ui_surface_client_tool",
1407
+ "ui_surface_config",
1408
+ "ui_surface_value",
1409
+ "ui_surface_write_target",
1410
+ "unsubscribe_token",
1411
+ "uploads_inflight",
1412
+ "user_achievement",
1413
+ "user_active_context",
1414
+ "user_analysis_preference",
1415
+ "user_bookmark",
1416
+ "user_email_preference",
1417
+ "user_entity_state",
1418
+ "user_feedback",
1419
+ "user_follows",
1420
+ "user_form_profile",
1421
+ "user_markdown_sample",
1422
+ "user_memory",
1423
+ "user_preference",
1424
+ "user_profile",
1425
+ "user_secret",
1426
+ "user_secret_audit",
1427
+ "user_secret_grant",
1428
+ "user_stat",
1429
+ "user_storage_usage",
1430
+ "user_surface_state",
1431
+ "visibility_cache",
1432
+ "visibility_epoch",
1433
+ "voice",
1434
+ "war_room",
1435
+ "wbx_capture",
1436
+ "wbx_demo",
1437
+ "wbx_guidance",
1438
+ "wbx_highlight",
1439
+ "wbx_pattern",
1440
+ "wbx_recipe",
1441
+ "wbx_screenshot",
1442
+ "wbx_seo_audit",
1443
+ "wc_claim",
1444
+ "wc_impairment_definition",
1445
+ "wc_injury",
1446
+ "wc_report",
1447
+ "web_analysis_item",
1448
+ "web_brand",
1449
+ "web_brand_asset",
1450
+ "web_brand_offering",
1451
+ "web_business_fact",
1452
+ "web_business_location",
1453
+ "web_channel_analytics_daily",
1454
+ "web_crawl_event",
1455
+ "web_crawl_preset",
1456
+ "web_crawl_schedule",
1457
+ "web_crawl_session",
1458
+ "web_crawl_url",
1459
+ "web_discovered_item",
1460
+ "web_finding",
1461
+ "web_gsc_page_stat",
1462
+ "web_link_edge",
1463
+ "web_listing_publisher",
1464
+ "web_location_listing",
1465
+ "web_offering_template",
1466
+ "web_page",
1467
+ "web_page_content",
1468
+ "web_page_evidence",
1469
+ "web_page_sitemap",
1470
+ "web_property",
1471
+ "web_provider",
1472
+ "web_result",
1473
+ "web_screenshot",
1474
+ "web_site",
1475
+ "web_site_endpoint_rule",
1476
+ "web_site_item_config",
1477
+ "web_site_offering",
1478
+ "web_sitemap",
1479
+ "web_snapshot",
1480
+ "web_tag_manager_snapshot",
1481
+ "web_youtube_video",
1482
+ "webhook_deliveries",
1483
+ "webhook_dispatch_state",
1484
+ "webhooks",
1485
+ "wf_node_data_slot",
1486
+ "work_claim",
1487
+ "work_item",
1488
+ "workbook",
1489
+ "worker_heartbeat",
1490
+ "workflow",
1491
+ "workflow_card",
1492
+ "workflow_checkpoint",
1493
+ "workflow_comparison",
1494
+ "workflow_definition_version",
1495
+ "workflow_idempotency",
1496
+ "workflow_job",
1497
+ "workflow_node_events",
1498
+ "workflow_node_outcome",
1499
+ "workflow_plan",
1500
+ "workflow_plan_event",
1501
+ "workflow_plan_sample",
1502
+ "workflow_recovery_audit",
1503
+ "workflow_run",
1504
+ "workflow_run_log",
1505
+ "workflow_runtime_surface",
1506
+ "workflow_template",
1507
+ "workflow_trigger",
1508
+ "workflow_trigger_fire",
1509
+ "workflow_work_item",
1510
+ "working_document",
1511
+ "write_guard_key",
1512
+ "youtube_quota_day",
1513
+ "youtube_search",
1514
+ "youtube_video"
1515
+ ];
1516
+
1517
+ // src/core/doors.ts
1518
+ var OWED_BY = {
1519
+ metadata_search: "W5-SRV / W5-AGENT \u2014 the agent surface's eight verbs",
1520
+ record_aggregate: "W5-SRV / W5-AGENT \u2014 `record_aggregate` is one of the eight verbs",
1521
+ field_propose: "W5-AGENT \u2014 AGT-4/AGT-8, the proposal and its approvers",
1522
+ table_propose: "W5-AGENT \u2014 AGT-8, the proposal and its approvers",
1523
+ merge_field_resolve: "W5-MERGE-B \u2014 the resolver's server half",
1524
+ record_query: "W1-INDEX / W5-SRV \u2014 the promoted-field query path",
1525
+ rule_declare: "W1-RULE \u2014 `custom.record_write` writes `data_class = 'record'`, so the ONE write door cannot make a Rule record; declaring a Rule (and therefore a DOOR-18 subscription) needs a door of its own"
1526
+ };
1527
+ var TRUST_SCHEMA = "iam";
1528
+ var TRUST_DOORS = {
1529
+ /** VIS-31. A signed-in outsider: an account with no NON-personal organization. */
1530
+ isExternalPrincipal: "is_external_principal",
1531
+ /** The same answer with the plain-English reason attached. */
1532
+ externalPrincipalCard: "external_principal_card",
1533
+ /** EXACTLY the resources Visibility gave that outsider — never "their organization's". */
1534
+ externalPrincipalReach: "external_principal_reach",
1535
+ /** VIS-32. A record or a view bound to a public address with a declared render mode. */
1536
+ publishBindingCreate: "publish_binding_create",
1537
+ publishBindingRevoke: "publish_binding_revoke",
1538
+ /** What a SIGNED-OUT visitor resolves. Returns nothing for an invented or revoked address. */
1539
+ resolvePublishBinding: "resolve_publish_binding",
1540
+ /** D-15. The one sentence that admits nothing was scanned — one function, so it cannot drift. */
1541
+ worldPublishGapNotice: "world_publish_gap_notice",
1542
+ publishToWorld: "publish_to_world",
1543
+ worldPublishAdmit: "world_publish_admit",
1544
+ claimWorldNamespace: "claim_world_namespace"
1545
+ };
1546
+ var DOOR_NAMES = new Set(STORE_DOORS.map((d) => d.name));
1547
+ function doorExists(name) {
1548
+ return DOOR_NAMES.has(name);
1549
+ }
1550
+ function doorAbsent(name) {
1551
+ const owed = OWED_BY[name];
1552
+ return {
1553
+ code: "door_absent",
1554
+ message: `The record store has no door \`custom.${name}\` yet, so this call was not made. Nothing was read and nothing was written.`,
1555
+ hint: owed ? `That door is ${owed}. Until it lands, this call refuses rather than guessing: an empty answer here would read like "there is nothing", which is a different sentence.` : `No lane in the build book claims this door. Either the name is wrong, or the door was removed from the store and this package has not been regenerated \u2014 run \`pnpm records:generate\`.`
1556
+ };
1557
+ }
1558
+ var DOORS = {
1559
+ // THE READ DOOR (DOOR-1). Every read of a record's values goes through these
1560
+ // two and nothing else: they resolve the reader from the session, ask
1561
+ // visibility once per set, and mask the fields this reader may not see with a
1562
+ // notice under `_hidden`. Selecting `custom.record` directly is the thing
1563
+ // they exist to replace — it returns rows and fields the store never agreed
1564
+ // this person could see.
1565
+ readRecord: "read_record",
1566
+ readRecords: "read_records",
1567
+ // DOOR-8, the two clocks. `p_recorded_at` is what the store SAID then;
1568
+ // `p_world_on` is what was TRUE of the world on that date, read out of dated
1569
+ // values. A client that answered either one itself would be guessing.
1570
+ queryRecordAsOf: "query_record_as_of",
1571
+ queryTableAsOf: "query_table_as_of",
1572
+ recordWrite: "record_write",
1573
+ recordUpdate: "record_update",
1574
+ recordDelete: "record_delete",
1575
+ recordRestore: "record_restore",
1576
+ recordValues: "record_values",
1577
+ recordValuesVersioned: "record_values_versioned",
1578
+ valueRead: "value_read",
1579
+ computedProvenance: "computed_provenance",
1580
+ recordApplicability: "record_applicability",
1581
+ applicableFields: "applicable_fields",
1582
+ fieldOptions: "field_options",
1583
+ parityValues: "parity_values",
1584
+ tableDeclare: "table_declare",
1585
+ tableCapacity: "table_capacity",
1586
+ tableStorage: "table_storage",
1587
+ promoteTable: "promote_table",
1588
+ promoteField: "promote_field",
1589
+ promotedFields: "promoted_fields",
1590
+ promotedRead: "promoted_read",
1591
+ relationTargets: "relation_targets",
1592
+ relationOwn: "relation_own",
1593
+ homeAdd: "home_add",
1594
+ recordReparent: "record_reparent",
1595
+ containmentChain: "containment_chain",
1596
+ storeIsOpen: "store_is_open",
1597
+ // DOOR-11. The record's own revision list. A screen that offers an optimistic
1598
+ // save needs the version it LOADED, and the read door answers documents, not
1599
+ // versions — so the version comes from here, once, for the one record being
1600
+ // edited, and never for a whole list.
1601
+ ioRevisions: "io_revisions",
1602
+ resolveFirstMatch: "resolve_first_match",
1603
+ // The kernels a package-owned Table needs to exist at all: a Home is a record
1604
+ // in the person kernel, a Field is a record in the field kernel (REC-1).
1605
+ personKernelId: "person_kernel_id",
1606
+ fieldKernelId: "field_kernel_id",
1607
+ ruleKernelId: "rule_kernel_id",
1608
+ // And the Table kernel, which is how `tableList` asks the READ DOOR for this
1609
+ // organization's Tables: a Table is a record like any other, so listing them
1610
+ // is `read_records(org, table_kernel_id())` and never a select on a table.
1611
+ tableKernelId: "table_kernel_id",
1612
+ // A saved view references its membership Rule, and the STORE decides who is
1613
+ // in it — the screen never re-implements the predicate.
1614
+ ruleMembers: "rule_members",
1615
+ ruleMembership: "rule_membership",
1616
+ ruleRun: "rule_run",
1617
+ ruleEval: "rule_eval",
1618
+ // The eighth verb (AGT-N-8): a grouped, bucketed, filtered count/sum/avg/
1619
+ // min/max computed INSIDE the read door's own query, so a chart shows exactly
1620
+ // the rows this person may see and never fetches the ones they may not.
1621
+ recordAggregate: "record_aggregate",
1622
+ aggOperations: "agg_operations",
1623
+ aggBuckets: "agg_buckets",
1624
+ // DOOR-18: a subscription is a Rule record carrying a `subscription` block
1625
+ // over a saved view. There is no subscription TABLE and no second notifier.
1626
+ aggSubscriptions: "agg_subscriptions",
1627
+ aggSubscriptionCadences: "agg_subscription_cadences",
1628
+ // The doc doors: a template is saved, a render is written once and frozen,
1629
+ // and a signature is checked against the exact bytes that were signed.
1630
+ docTemplateSave: "doc_template_save",
1631
+ docRenderBody: "doc_render_body",
1632
+ docRenderDocument: "doc_render_document",
1633
+ docTokens: "doc_tokens",
1634
+ docUnresolvedTokens: "doc_unresolved_tokens",
1635
+ docSign: "doc_sign",
1636
+ docSignatureIntact: "doc_signature_intact",
1637
+ // THE ANONYMOUS LANE (W4-ANON). It landed, and it landed as SEVEN doors
1638
+ // rather than the one this package had guessed at: a token is issued and
1639
+ // verified separately from the write it authorises, a form is published
1640
+ // separately from being declared, and an offline capture by a SIGNED-IN
1641
+ // person is a different door from a write by a stranger.
1642
+ //
1643
+ // This package used to name a door `anon_record_write`, which never existed —
1644
+ // so `FormRunner` told every person that the public link was "pending" for a
1645
+ // lane that had already shipped. A screen calling a live feature pending is
1646
+ // the same silent failure as a screen calling a missing one live, and the fix
1647
+ // is to name the doors the store actually has.
1648
+ anonTokenIssue: "anon_token_issue",
1649
+ anonTokenVerify: "anon_token_verify",
1650
+ anonTokenRevoke: "anon_token_revoke",
1651
+ /** The stranger's write. The TOKEN names the organization; a caller never does. */
1652
+ anonWrite: "anon_write",
1653
+ /** SCR-30. The signed-in OFFLINE path: the client mints the key, the store dedupes on it. */
1654
+ anonCapture: "anon_capture",
1655
+ anonPublish: "anon_publish",
1656
+ // WORK (W4-WORK): a template instantiated as real records, whose turn it is,
1657
+ // and a slot somebody is holding. `ChecklistRunner` and `BookingSlots` are
1658
+ // screens over these and hold no state of their own.
1659
+ workStates: "work_states",
1660
+ workTemplateDeclare: "work_template_declare",
1661
+ workTemplateInstantiate: "work_template_instantiate",
1662
+ workTemplateShape: "work_template_shape",
1663
+ /** Why a graph would be refused — asked BEFORE it is written, never after. */
1664
+ workTemplateRefusal: "work_template_refusal",
1665
+ workWhoseTurn: "work_whose_turn",
1666
+ workTakeAssignment: "work_take_assignment",
1667
+ workHasAssignment: "work_has_assignment",
1668
+ workAssignmentFields: "work_assignment_fields",
1669
+ workTransitionRefusal: "work_transition_refusal",
1670
+ workInstantiationShape: "work_instantiation_shape",
1671
+ workSlotsDeclare: "work_slots_declare",
1672
+ workSlotHold: "work_slot_hold",
1673
+ workSlotRelease: "work_slot_release",
1674
+ workSlotHolds: "work_slot_holds",
1675
+ workSlotExpire: "work_slot_expire",
1676
+ // Declared here BECAUSE they do not exist yet: naming them is what makes the
1677
+ // absence visible to `pnpm check:store-registry` and to the suite.
1678
+ metadataSearch: "metadata_search",
1679
+ ruleDeclare: "rule_declare",
1680
+ fieldPropose: "field_propose",
1681
+ tablePropose: "table_propose",
1682
+ mergeFieldResolve: "merge_field_resolve"
1683
+ };
1684
+ function doorCensus() {
1685
+ const present = [];
1686
+ const absent = [];
1687
+ for (const name of Object.values(DOORS)) {
1688
+ (doorExists(name) ? present : absent).push(name);
1689
+ }
1690
+ return { present: present.sort(), absent: absent.sort() };
1691
+ }
1692
+
1693
+ // src/core/pgError.ts
1694
+ var BY_SQLSTATE = {
1695
+ PT409: "stale_write",
1696
+ "42501": "door",
1697
+ "23514": "refused_by_rule",
1698
+ "22004": "invalid_argument",
1699
+ "22023": "invalid_argument",
1700
+ "02000": "not_found",
1701
+ "23503": "missing_reference",
1702
+ "23505": "already_exists",
1703
+ "0A000": "not_supported",
1704
+ "53400": "store_limit",
1705
+ "22012": "store_limit",
1706
+ // VIS: `custom.has_visibility_at` refuses to answer from a snapshot older
1707
+ // than a write this reader has already seen, rather than returning something
1708
+ // they just lost access to. It is retryable on a fresher connection, which is
1709
+ // a different instruction from every other refusal here.
1710
+ "40001": "stale_read",
1711
+ // PostgREST's own two: the store is not being SERVED, which is a different
1712
+ // thing from the store refusing. `custom` absent from `pgrst.db_schemas`, or
1713
+ // the grants not copied, land here.
1714
+ PGRST202: "store_not_served",
1715
+ PGRST205: "store_not_served",
1716
+ PGRST301: "door"
1717
+ };
1718
+ var MAPPED_SQLSTATES = Object.keys(BY_SQLSTATE);
1719
+ function parseDetail(details) {
1720
+ if (!details) return void 0;
1721
+ const trimmed = details.trim();
1722
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return details;
1723
+ try {
1724
+ return JSON.parse(trimmed);
1725
+ } catch {
1726
+ return details;
1727
+ }
1728
+ }
1729
+ function mapPgError(error, where) {
1730
+ const sqlstate = error.code ?? void 0;
1731
+ const code = (sqlstate ? BY_SQLSTATE[sqlstate] : void 0) ?? "internal";
1732
+ const mapped = {
1733
+ code,
1734
+ message: error.message,
1735
+ ...error.hint ? { hint: error.hint } : {},
1736
+ ...sqlstate ? { sqlstate } : {}
1737
+ };
1738
+ const detail = parseDetail(error.details);
1739
+ if (detail !== void 0) mapped.detail = detail;
1740
+ if (code === "internal") {
1741
+ mapped.hint = (mapped.hint ? `${mapped.hint} ` : "") + `(@ai-matrx/records did not recognise SQLSTATE ${sqlstate ?? "(none)"} from ${where}; the message above is the store's own and is the thing to act on.)`;
1742
+ }
1743
+ return mapped;
1744
+ }
1745
+ function staleWriteDetail(error) {
1746
+ if (error.code !== "stale_write") return null;
1747
+ const detail = error.detail;
1748
+ if (!detail || typeof detail.expected_version !== "number" || typeof detail.current_version !== "number") {
1749
+ return null;
1750
+ }
1751
+ return {
1752
+ expected_version: detail.expected_version,
1753
+ current_version: detail.current_version,
1754
+ contested_fields: detail.contested_fields ?? {}
1755
+ };
1756
+ }
1757
+
1758
+ // src/core/query.ts
1759
+ var DEFAULT_PAGE_SIZE = 50;
1760
+ function planQuery(query) {
1761
+ const relationCalls = (query.relations ?? []).map((coordinate) => ({
1762
+ door: "relation_targets",
1763
+ record_id: coordinate.record_id,
1764
+ via_key: coordinate.role ?? null
1765
+ }));
1766
+ const promotedCalls = (query.promoted ?? []).map((predicate) => ({
1767
+ door: "promoted_read",
1768
+ field_key: predicate.field_key,
1769
+ value: predicate.equals
1770
+ }));
1771
+ return {
1772
+ relationCalls,
1773
+ promotedCalls,
1774
+ read: {
1775
+ table_id: query.table_id,
1776
+ includeDeleted: query.includeDeleted ?? false,
1777
+ recordType: query.recordType ?? null,
1778
+ asOf: query.asOf ?? null,
1779
+ acrossHomes: query.acrossHomes ?? false,
1780
+ orderBy: {
1781
+ column: query.orderBy?.column ?? "created_at",
1782
+ ascending: query.orderBy?.ascending ?? false
1783
+ },
1784
+ limit: query.limit ?? DEFAULT_PAGE_SIZE,
1785
+ offset: query.offset ?? 0
1786
+ },
1787
+ intersects: relationCalls.length + promotedCalls.length > 0
1788
+ };
1789
+ }
1790
+ function intersectIds(sets) {
1791
+ if (sets.length === 0) return [];
1792
+ const [first, ...rest] = sets;
1793
+ const others = rest.map((s) => new Set(s));
1794
+ return first.filter((id) => others.every((set) => set.has(id)));
1795
+ }
1796
+
1797
+ // src/core/client.ts
1798
+ var DEFAULT_SCHEMA = "custom";
1799
+ function sink(config) {
1800
+ return config.onError ?? ((e) => (
1801
+ // The defined degradation, stated: loud, with the store's own words, and
1802
+ // naming where it happened. Never silence.
1803
+ console.error(`[@ai-matrx/records] ${e.where}: ${e.code} \u2014 ${e.message}${e.hint ? ` (${e.hint})` : ""}`)
1804
+ ));
1805
+ }
1806
+ function createRecordsClient(config) {
1807
+ const schema = config.schema ?? DEFAULT_SCHEMA;
1808
+ const org = config.organizationId;
1809
+ const scream = sink(config);
1810
+ async function callDoor(door, args, where) {
1811
+ if (!doorExists(door)) {
1812
+ const refusal = doorAbsent(door);
1813
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where });
1814
+ return err(refusal);
1815
+ }
1816
+ const response = await config.dataSource.rpc(`${door}`, args, { schema });
1817
+ if (response.error) {
1818
+ const refusal = mapPgError(response.error, where);
1819
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where });
1820
+ return err(refusal);
1821
+ }
1822
+ return ok(response.data);
1823
+ }
1824
+ async function trustDoor(door, args, where) {
1825
+ const response = await config.dataSource.rpc(door, args, { schema: TRUST_SCHEMA });
1826
+ if (response.error) {
1827
+ const refusal = mapPgError(response.error, where);
1828
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where });
1829
+ return err(refusal);
1830
+ }
1831
+ return ok(response.data);
1832
+ }
1833
+ function unfold(document) {
1834
+ const raw = document ?? {};
1835
+ const hidden = raw._hidden ?? {};
1836
+ const values = {};
1837
+ for (const [key, value] of Object.entries(raw)) {
1838
+ if (key === "_hidden") continue;
1839
+ values[key] = value;
1840
+ }
1841
+ return { document: values, hidden };
1842
+ }
1843
+ async function readValues(recordId) {
1844
+ return callDoor(
1845
+ DOORS.recordValuesVersioned,
1846
+ { p_organization_id: org, p_record_id: recordId },
1847
+ "recordRead"
1848
+ );
1849
+ }
1850
+ const client = {
1851
+ config,
1852
+ async recordWrite({ table_id, data }) {
1853
+ return callDoor(
1854
+ DOORS.recordWrite,
1855
+ { p_organization_id: org, p_table_id: table_id, p_data: data },
1856
+ "recordWrite"
1857
+ );
1858
+ },
1859
+ async recordUpdate({ record_id, patch, expectedVersion }) {
1860
+ const result = await callDoor(
1861
+ DOORS.recordUpdate,
1862
+ {
1863
+ p_organization_id: org,
1864
+ p_record_id: record_id,
1865
+ p_patch: patch,
1866
+ ...expectedVersion === void 0 ? {} : { p_expected_version: expectedVersion }
1867
+ },
1868
+ "recordUpdate"
1869
+ );
1870
+ return result;
1871
+ },
1872
+ async recordDelete({ record_id }) {
1873
+ return callDoor(
1874
+ DOORS.recordDelete,
1875
+ { p_organization_id: org, p_record_id: record_id },
1876
+ "recordDelete"
1877
+ );
1878
+ },
1879
+ async recordRestore({ record_id }) {
1880
+ return callDoor(
1881
+ DOORS.recordRestore,
1882
+ { p_organization_id: org, p_record_id: record_id },
1883
+ "recordRestore"
1884
+ );
1885
+ },
1886
+ async recordRead({ record_id, withComputed = false }) {
1887
+ const door = await callDoor(
1888
+ DOORS.readRecord,
1889
+ { p_organization_id: org, p_record_id: record_id },
1890
+ "recordRead"
1891
+ );
1892
+ if (!door.ok) return err(door.error);
1893
+ const { document, hidden } = unfold(door.data);
1894
+ let computed = [];
1895
+ if (withComputed) {
1896
+ const provenance = await callDoor(
1897
+ DOORS.computedProvenance,
1898
+ { p_organization_id: org, p_record_id: record_id },
1899
+ "recordRead.computed"
1900
+ );
1901
+ if (!provenance.ok) return err(provenance.error);
1902
+ computed = provenance.data ?? [];
1903
+ }
1904
+ return ok({ record_id, document, hidden, computed });
1905
+ },
1906
+ async list({ table_id, limit = 50, offset = 0 }) {
1907
+ const door = await callDoor(
1908
+ DOORS.readRecords,
1909
+ {
1910
+ p_organization_id: org,
1911
+ p_table_id: table_id,
1912
+ p_limit: limit,
1913
+ p_offset: offset
1914
+ },
1915
+ "list"
1916
+ );
1917
+ if (!door.ok) return err(door.error);
1918
+ const rows = (door.data ?? []).map((row) => {
1919
+ const { document, hidden } = unfold(row.document);
1920
+ return { id: row.id, document, level: row.level, hidden };
1921
+ });
1922
+ return ok({ rows, total: null });
1923
+ },
1924
+ async query(input) {
1925
+ const plan = planQuery(input);
1926
+ const sets = [];
1927
+ for (const call of plan.relationCalls) {
1928
+ const result = await callDoor(
1929
+ DOORS.relationTargets,
1930
+ { p_organization_id: org, p_record_id: call.record_id, p_via_key: call.via_key },
1931
+ "query.relations"
1932
+ );
1933
+ if (!result.ok) return err(result.error);
1934
+ sets.push(
1935
+ (result.data ?? []).map(
1936
+ (row) => typeof row === "string" ? row : row.relation_targets
1937
+ )
1938
+ );
1939
+ }
1940
+ for (const call of plan.promotedCalls) {
1941
+ const result = await callDoor(
1942
+ DOORS.promotedRead,
1943
+ {
1944
+ p_organization_id: org,
1945
+ p_table_id: plan.read.table_id,
1946
+ p_field_key: call.field_key,
1947
+ p_value: call.value
1948
+ },
1949
+ "query.promoted"
1950
+ );
1951
+ if (!result.ok) return err(result.error);
1952
+ sets.push(
1953
+ (result.data ?? []).map(
1954
+ (row) => typeof row === "string" ? row : row.promoted_read
1955
+ )
1956
+ );
1957
+ }
1958
+ const ids = plan.intersects ? intersectIds(sets) : null;
1959
+ if (ids !== null && ids.length === 0) {
1960
+ return ok({ rows: [], total: 0 });
1961
+ }
1962
+ if (plan.read.asOf) {
1963
+ const clock = plan.read.asOf.clock === "world" ? { p_world_on: plan.read.asOf.at.slice(0, 10) } : { p_recorded_at: plan.read.asOf.at };
1964
+ if (ids !== null) {
1965
+ const answers = await Promise.all(
1966
+ ids.slice(0, plan.read.limit).map(
1967
+ (id) => callDoor(
1968
+ DOORS.queryRecordAsOf,
1969
+ { p_organization_id: org, p_record_id: id, ...clock },
1970
+ "query.asOf"
1971
+ ).then((result) => ({ id, result }))
1972
+ )
1973
+ );
1974
+ const rows2 = [];
1975
+ for (const { id, result } of answers) {
1976
+ if (!result.ok) return err(result.error);
1977
+ if (result.data === null) continue;
1978
+ const { document, hidden } = unfold(result.data);
1979
+ rows2.push({ id, document, level: "viewer", hidden });
1980
+ }
1981
+ return ok({ rows: rows2, total: rows2.length });
1982
+ }
1983
+ const page = await callDoor(
1984
+ DOORS.queryTableAsOf,
1985
+ {
1986
+ p_organization_id: org,
1987
+ p_table_id: plan.read.table_id,
1988
+ ...clock,
1989
+ p_limit: plan.read.limit,
1990
+ p_offset: plan.read.offset
1991
+ },
1992
+ "query.asOf"
1993
+ );
1994
+ if (!page.ok) return err(page.error);
1995
+ const rows = (page.data ?? []).filter((row) => row.data !== null).map((row) => {
1996
+ const { document, hidden } = unfold(row.data);
1997
+ return { id: row.record_id, document, level: "viewer", hidden };
1998
+ });
1999
+ return ok({ rows, total: null });
2000
+ }
2001
+ if (ids !== null) {
2002
+ const answers = await Promise.all(
2003
+ ids.slice(0, plan.read.limit).map(
2004
+ (id) => callDoor(
2005
+ DOORS.readRecord,
2006
+ { p_organization_id: org, p_record_id: id },
2007
+ "query"
2008
+ ).then((result) => ({ id, result }))
2009
+ )
2010
+ );
2011
+ const rows = [];
2012
+ for (const { id, result } of answers) {
2013
+ if (!result.ok) {
2014
+ if (result.error.sqlstate === "02000") continue;
2015
+ return err(result.error);
2016
+ }
2017
+ const { document, hidden } = unfold(result.data);
2018
+ rows.push({ id, document, level: "viewer", hidden });
2019
+ }
2020
+ return ok({ rows, total: rows.length });
2021
+ }
2022
+ return client.list({
2023
+ table_id: plan.read.table_id,
2024
+ limit: plan.read.limit,
2025
+ offset: plan.read.offset
2026
+ });
2027
+ },
2028
+ async tableList() {
2029
+ const kernel = await callDoor(DOORS.tableKernelId, {}, "tableList.kernel");
2030
+ if (!kernel.ok) return err(kernel.error);
2031
+ const door = await callDoor(
2032
+ DOORS.readRecords,
2033
+ { p_organization_id: org, p_table_id: kernel.data, p_limit: 500, p_offset: 0 },
2034
+ "tableList"
2035
+ );
2036
+ if (!door.ok) return err(door.error);
2037
+ const tables = (door.data ?? []).map((row) => {
2038
+ const { document } = unfold(row.document);
2039
+ return { ...document, id: row.id, organization_id: org };
2040
+ });
2041
+ tables.sort((a, b) => (a.name ?? "").localeCompare(b.name ?? ""));
2042
+ return ok(tables);
2043
+ },
2044
+ async fields({ table_id, recordType }) {
2045
+ const applicable = await callDoor(
2046
+ DOORS.applicableFields,
2047
+ {
2048
+ p_organization_id: org,
2049
+ p_table_id: table_id,
2050
+ ...recordType === void 0 ? {} : { p_record_type: recordType }
2051
+ },
2052
+ "fields"
2053
+ );
2054
+ if (!applicable.ok) return err(applicable.error);
2055
+ const rows = applicable.data ?? [];
2056
+ return ok(
2057
+ rows.map((row) => ({ id: row.id, ...row.data }))
2058
+ );
2059
+ },
2060
+ async fieldOptions({ field_id }) {
2061
+ return callDoor(
2062
+ DOORS.fieldOptions,
2063
+ { p_organization_id: org, p_field_id: field_id },
2064
+ "fieldOptions"
2065
+ );
2066
+ },
2067
+ async tableCapacity({ table_id }) {
2068
+ return callDoor(
2069
+ DOORS.tableCapacity,
2070
+ { p_organization_id: org, p_table_id: table_id },
2071
+ "tableCapacity"
2072
+ );
2073
+ },
2074
+ async tableDeclare({ spec, homeId }) {
2075
+ return callDoor(
2076
+ DOORS.tableDeclare,
2077
+ { p_organization_id: org, p_spec: { ...spec, parent_id: homeId } },
2078
+ "tableDeclare"
2079
+ );
2080
+ },
2081
+ async personKernelId() {
2082
+ return callDoor(DOORS.personKernelId, {}, "personKernelId");
2083
+ },
2084
+ async fieldKernelId() {
2085
+ return callDoor(DOORS.fieldKernelId, {}, "fieldKernelId");
2086
+ },
2087
+ async ruleKernelId() {
2088
+ return callDoor(DOORS.ruleKernelId, {}, "ruleKernelId");
2089
+ },
2090
+ async ruleMembers({ rule_id }) {
2091
+ return callDoor(
2092
+ DOORS.ruleMembers,
2093
+ { p_organization_id: org, p_rule_id: rule_id },
2094
+ "ruleMembers"
2095
+ );
2096
+ },
2097
+ async ruleMembership({ rule_id, record_id }) {
2098
+ return callDoor(
2099
+ DOORS.ruleMembership,
2100
+ { p_organization_id: org, p_rule_id: rule_id, p_record_id: record_id },
2101
+ "ruleMembership"
2102
+ );
2103
+ },
2104
+ async ruleRun({ rule_id, values, context }) {
2105
+ return callDoor(
2106
+ DOORS.ruleRun,
2107
+ {
2108
+ p_organization_id: org,
2109
+ p_rule_id: rule_id,
2110
+ p_values: values,
2111
+ ...context === void 0 ? {} : { p_context: context }
2112
+ },
2113
+ "ruleRun"
2114
+ );
2115
+ },
2116
+ async ruleEval({ expr, values, context }) {
2117
+ return callDoor(
2118
+ DOORS.ruleEval,
2119
+ {
2120
+ p_organization_id: org,
2121
+ p_expr: expr,
2122
+ p_values: values,
2123
+ ...context === void 0 ? {} : { p_context: context }
2124
+ },
2125
+ "ruleEval"
2126
+ );
2127
+ },
2128
+ async recordAggregate({ table_id, groupBy, measures, bucket, filter, limit }) {
2129
+ return callDoor(
2130
+ DOORS.recordAggregate,
2131
+ {
2132
+ p_organization_id: org,
2133
+ p_table_id: table_id,
2134
+ p_group_by: groupBy ?? [],
2135
+ p_measures: measures ?? [],
2136
+ p_bucket: bucket ?? null,
2137
+ p_filter: filter ?? {},
2138
+ p_limit: limit ?? 200
2139
+ },
2140
+ "recordAggregate"
2141
+ );
2142
+ },
2143
+ async aggOperations() {
2144
+ return callDoor(DOORS.aggOperations, {}, "aggOperations");
2145
+ },
2146
+ async aggBuckets() {
2147
+ return callDoor(DOORS.aggBuckets, {}, "aggBuckets");
2148
+ },
2149
+ async aggSubscriptions(args) {
2150
+ return callDoor(
2151
+ DOORS.aggSubscriptions,
2152
+ {
2153
+ p_organization_id: org,
2154
+ p_saved_view_id: args?.saved_view_id ?? null,
2155
+ p_cadence: args?.cadence ?? null
2156
+ },
2157
+ "aggSubscriptions"
2158
+ );
2159
+ },
2160
+ async aggSubscriptionCadences() {
2161
+ return callDoor(DOORS.aggSubscriptionCadences, {}, "aggSubscriptionCadences");
2162
+ },
2163
+ async docTemplateSave({ table_id, name, body, template_id }) {
2164
+ return callDoor(
2165
+ DOORS.docTemplateSave,
2166
+ {
2167
+ p_organization_id: org,
2168
+ p_table_id: table_id,
2169
+ p_name: name,
2170
+ p_body: body,
2171
+ p_template_id: template_id ?? null
2172
+ },
2173
+ "docTemplateSave"
2174
+ );
2175
+ },
2176
+ async docRenderBody({ template_id, record_id }) {
2177
+ return callDoor(
2178
+ DOORS.docRenderBody,
2179
+ { p_organization_id: org, p_template_id: template_id, p_record_id: record_id },
2180
+ "docRenderBody"
2181
+ );
2182
+ },
2183
+ async docRenderDocument({ template_id, record_id }) {
2184
+ return callDoor(
2185
+ DOORS.docRenderDocument,
2186
+ { p_organization_id: org, p_template_id: template_id, p_record_id: record_id },
2187
+ "docRenderDocument"
2188
+ );
2189
+ },
2190
+ async docTokens({ body }) {
2191
+ return callDoor(DOORS.docTokens, { p_body: body }, "docTokens");
2192
+ },
2193
+ async docUnresolvedTokens({ table_id, body }) {
2194
+ return callDoor(
2195
+ DOORS.docUnresolvedTokens,
2196
+ { p_organization_id: org, p_table_id: table_id, p_body: body },
2197
+ "docUnresolvedTokens"
2198
+ );
2199
+ },
2200
+ async docSign({ render_id, field_key, signer_name, signer_user_id }) {
2201
+ return callDoor(
2202
+ DOORS.docSign,
2203
+ {
2204
+ p_organization_id: org,
2205
+ p_render_id: render_id,
2206
+ p_field_key: field_key,
2207
+ p_signer_name: signer_name,
2208
+ p_signer_user_id: signer_user_id ?? null
2209
+ },
2210
+ "docSign"
2211
+ );
2212
+ },
2213
+ async docTemplates({ table_id }) {
2214
+ const response = await config.dataSource.schema(schema).from("doc_template").select("*").eq("organization_id", org).eq("renders_table_id", table_id).order("name");
2215
+ if (response.error) {
2216
+ const refusal = mapPgError(response.error, "docTemplates");
2217
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where: "docTemplates" });
2218
+ return err(refusal);
2219
+ }
2220
+ return ok(response.data ?? []);
2221
+ },
2222
+ async docRenders({ record_id }) {
2223
+ const response = await config.dataSource.schema(schema).from("doc_render").select("*").eq("organization_id", org).eq("record_id", record_id).is("deleted_at", null).order("rendered_at", { ascending: false });
2224
+ if (response.error) {
2225
+ const refusal = mapPgError(response.error, "docRenders");
2226
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where: "docRenders" });
2227
+ return err(refusal);
2228
+ }
2229
+ return ok(response.data ?? []);
2230
+ },
2231
+ async docSignatures({ record_id }) {
2232
+ const response = await config.dataSource.schema(schema).from("doc_signature").select("*").eq("organization_id", org).eq("record_id", record_id).is("deleted_at", null).order("signed_at", { ascending: false });
2233
+ if (response.error) {
2234
+ const refusal = mapPgError(response.error, "docSignatures");
2235
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where: "docSignatures" });
2236
+ return err(refusal);
2237
+ }
2238
+ return ok(response.data ?? []);
2239
+ },
2240
+ async recordValuesVersioned({ record_id }) {
2241
+ return readValues(record_id);
2242
+ },
2243
+ async revisions({ record_id }) {
2244
+ return callDoor(
2245
+ DOORS.ioRevisions,
2246
+ { p_organization_id: org, p_record_id: record_id },
2247
+ "revisions"
2248
+ );
2249
+ },
2250
+ async docSignatureIntact({ signature_id }) {
2251
+ return callDoor(
2252
+ DOORS.docSignatureIntact,
2253
+ { p_organization_id: org, p_signature_id: signature_id },
2254
+ "docSignatureIntact"
2255
+ );
2256
+ },
2257
+ // ── the anonymous lane ───────────────────────────────────────────────
2258
+ async anonTokenIssue({ mode, allowedOrigins, formId, savedViewId, recordId, expiresAt }) {
2259
+ const answered = await callDoor(
2260
+ DOORS.anonTokenIssue,
2261
+ {
2262
+ p_organization_id: org,
2263
+ p_mode: mode,
2264
+ p_allowed_origins: allowedOrigins,
2265
+ p_form_id: formId ?? null,
2266
+ p_saved_view_id: savedViewId ?? null,
2267
+ p_record_id: recordId ?? null,
2268
+ p_expires_at: expiresAt ?? null
2269
+ },
2270
+ "anonTokenIssue"
2271
+ );
2272
+ if (!answered.ok) return answered;
2273
+ const pair = answered.data[0];
2274
+ if (!pair) {
2275
+ return err({
2276
+ code: "internal",
2277
+ message: "custom.anon_token_issue returned no token, which it cannot do \u2014 it either mints one or raises.",
2278
+ hint: "Nothing was issued. Do not retry blindly: something between this client and the store changed the answer's shape."
2279
+ });
2280
+ }
2281
+ return ok(pair);
2282
+ },
2283
+ async anonTokenVerify({ secret, origin, requiredMode }) {
2284
+ const answered = await callDoor(
2285
+ DOORS.anonTokenVerify,
2286
+ { p_secret: secret, p_origin: origin, p_required_mode: requiredMode ?? null },
2287
+ "anonTokenVerify"
2288
+ );
2289
+ if (!answered.ok) return answered;
2290
+ const binding = answered.data[0];
2291
+ if (!binding) {
2292
+ return err({
2293
+ code: "internal",
2294
+ message: "custom.anon_token_verify returned no binding, which it cannot do \u2014 it either answers or raises.",
2295
+ hint: "Treat this as unverified. It is reported rather than read as 'not valid', because those are different sentences."
2296
+ });
2297
+ }
2298
+ return ok(binding);
2299
+ },
2300
+ async anonTokenRevoke({ token_id }) {
2301
+ return callDoor(
2302
+ DOORS.anonTokenRevoke,
2303
+ { p_organization_id: org, p_token_id: token_id },
2304
+ "anonTokenRevoke"
2305
+ );
2306
+ },
2307
+ async anonWrite({ secret, origin, payload, clientKey, rawPayload }) {
2308
+ return callDoor(
2309
+ DOORS.anonWrite,
2310
+ {
2311
+ p_secret: secret,
2312
+ p_origin: origin,
2313
+ p_payload: payload,
2314
+ p_client_key: clientKey ?? null,
2315
+ p_raw_payload: rawPayload ?? {}
2316
+ },
2317
+ "anonWrite"
2318
+ );
2319
+ },
2320
+ async anonCapture({ table_id, clientKey, payload, device, capturedAt }) {
2321
+ return callDoor(
2322
+ DOORS.anonCapture,
2323
+ {
2324
+ p_organization_id: org,
2325
+ p_client_key: clientKey,
2326
+ p_table_id: table_id,
2327
+ p_payload: payload,
2328
+ p_device: device ?? null,
2329
+ p_captured_at: capturedAt ?? null
2330
+ },
2331
+ "anonCapture"
2332
+ );
2333
+ },
2334
+ async anonPublish({ form_id, published = true }) {
2335
+ return callDoor(
2336
+ DOORS.anonPublish,
2337
+ { p_organization_id: org, p_form_id: form_id, p_published: published },
2338
+ "anonPublish"
2339
+ );
2340
+ },
2341
+ // ── work ─────────────────────────────────────────────────────────────
2342
+ async workStates() {
2343
+ return callDoor(DOORS.workStates, {}, "workStates");
2344
+ },
2345
+ async workTemplateRefusal({ graph }) {
2346
+ return callDoor(DOORS.workTemplateRefusal, { p_graph: graph }, "workTemplateRefusal");
2347
+ },
2348
+ async workTemplateDeclare({ name, graph }) {
2349
+ return callDoor(
2350
+ DOORS.workTemplateDeclare,
2351
+ { p_organization_id: org, p_name: name, p_graph: graph },
2352
+ "workTemplateDeclare"
2353
+ );
2354
+ },
2355
+ async workTemplateInstantiate({ template_id, overrides }) {
2356
+ return callDoor(
2357
+ DOORS.workTemplateInstantiate,
2358
+ { p_organization_id: org, p_template_id: template_id, p_overrides: overrides ?? {} },
2359
+ "workTemplateInstantiate"
2360
+ );
2361
+ },
2362
+ async workTemplateShape({ template_id }) {
2363
+ return callDoor(
2364
+ DOORS.workTemplateShape,
2365
+ { p_organization_id: org, p_template_id: template_id },
2366
+ "workTemplateShape"
2367
+ );
2368
+ },
2369
+ async workInstantiationShape({ instantiation_id }) {
2370
+ return callDoor(
2371
+ DOORS.workInstantiationShape,
2372
+ { p_organization_id: org, p_instantiation_id: instantiation_id },
2373
+ "workInstantiationShape"
2374
+ );
2375
+ },
2376
+ async workWhoseTurn({ table_id, includeFinished = false }) {
2377
+ return callDoor(
2378
+ DOORS.workWhoseTurn,
2379
+ { p_organization_id: org, p_table_id: table_id, p_include_finished: includeFinished },
2380
+ "workWhoseTurn"
2381
+ );
2382
+ },
2383
+ async workHasAssignment({ table_id }) {
2384
+ return callDoor(
2385
+ DOORS.workHasAssignment,
2386
+ { p_organization_id: org, p_table_id: table_id },
2387
+ "workHasAssignment"
2388
+ );
2389
+ },
2390
+ async workAssignmentFields(args) {
2391
+ return callDoor(
2392
+ DOORS.workAssignmentFields,
2393
+ { p_options_table_id: args?.options_table_id ?? null },
2394
+ "workAssignmentFields"
2395
+ );
2396
+ },
2397
+ async workTakeAssignment({ table_id }) {
2398
+ return callDoor(
2399
+ DOORS.workTakeAssignment,
2400
+ { p_organization_id: org, p_table_id: table_id },
2401
+ "workTakeAssignment"
2402
+ );
2403
+ },
2404
+ async workTransitionRefusal({ from_state_id, to_state_id }) {
2405
+ return callDoor(
2406
+ DOORS.workTransitionRefusal,
2407
+ { p_organization_id: org, p_from_state_id: from_state_id, p_to_state_id: to_state_id },
2408
+ "workTransitionRefusal"
2409
+ );
2410
+ },
2411
+ async workSlotsDeclare({ name, slug, homeId }) {
2412
+ return callDoor(
2413
+ DOORS.workSlotsDeclare,
2414
+ { p_organization_id: org, p_name: name, p_slug: slug, p_home_id: homeId ?? null },
2415
+ "workSlotsDeclare"
2416
+ );
2417
+ },
2418
+ async workSlotHold({ table_id, slotKey, holder, ttl }) {
2419
+ return callDoor(
2420
+ DOORS.workSlotHold,
2421
+ {
2422
+ p_organization_id: org,
2423
+ p_table_id: table_id,
2424
+ p_slot_key: slotKey,
2425
+ p_holder: holder,
2426
+ ...ttl ? { p_ttl: ttl } : {}
2427
+ },
2428
+ "workSlotHold"
2429
+ );
2430
+ },
2431
+ async workSlotRelease({ hold_id }) {
2432
+ return callDoor(
2433
+ DOORS.workSlotRelease,
2434
+ { p_organization_id: org, p_hold_id: hold_id },
2435
+ "workSlotRelease"
2436
+ );
2437
+ },
2438
+ async workSlotHolds({ table_id }) {
2439
+ return callDoor(
2440
+ DOORS.workSlotHolds,
2441
+ { p_organization_id: org, p_table_id: table_id },
2442
+ "workSlotHolds"
2443
+ );
2444
+ },
2445
+ async workSlotExpire({ table_id }) {
2446
+ return callDoor(
2447
+ DOORS.workSlotExpire,
2448
+ { p_organization_id: org, p_table_id: table_id },
2449
+ "workSlotExpire"
2450
+ );
2451
+ },
2452
+ // ── the trust doors ──────────────────────────────────────────────────
2453
+ async isExternalPrincipal(args) {
2454
+ return trustDoor(
2455
+ TRUST_DOORS.isExternalPrincipal,
2456
+ { p_user_id: args?.user_id ?? null },
2457
+ "isExternalPrincipal"
2458
+ );
2459
+ },
2460
+ async externalPrincipalCard(args) {
2461
+ return trustDoor(
2462
+ TRUST_DOORS.externalPrincipalCard,
2463
+ { p_user_id: args?.user_id ?? null },
2464
+ "externalPrincipalCard"
2465
+ );
2466
+ },
2467
+ async externalPrincipalReach({ resourceType, user_id }) {
2468
+ return trustDoor(
2469
+ TRUST_DOORS.externalPrincipalReach,
2470
+ { p_resource_type: resourceType, p_user_id: user_id ?? null },
2471
+ "externalPrincipalReach"
2472
+ );
2473
+ },
2474
+ async publishBindingCreate({ slug, resourceType, resource_id, renderMode = "page" }) {
2475
+ return trustDoor(
2476
+ TRUST_DOORS.publishBindingCreate,
2477
+ {
2478
+ p_slug: slug,
2479
+ p_resource_type: resourceType,
2480
+ p_resource_id: resource_id,
2481
+ p_organization_id: org,
2482
+ p_render_mode: renderMode
2483
+ },
2484
+ "publishBindingCreate"
2485
+ );
2486
+ },
2487
+ async publishBindingRevoke({ slug }) {
2488
+ return trustDoor(TRUST_DOORS.publishBindingRevoke, { p_slug: slug }, "publishBindingRevoke");
2489
+ },
2490
+ async resolvePublishBinding({ slug }) {
2491
+ return trustDoor(
2492
+ TRUST_DOORS.resolvePublishBinding,
2493
+ { p_slug: slug },
2494
+ "resolvePublishBinding"
2495
+ );
2496
+ },
2497
+ async worldPublishGapNotice() {
2498
+ return trustDoor(TRUST_DOORS.worldPublishGapNotice, {}, "worldPublishGapNotice");
2499
+ },
2500
+ async publishToWorld({ resourceType, resource_id, discoverable = false }) {
2501
+ return trustDoor(
2502
+ TRUST_DOORS.publishToWorld,
2503
+ {
2504
+ p_resource_type: resourceType,
2505
+ p_resource_id: resource_id,
2506
+ p_organization_id: org,
2507
+ p_discoverable: discoverable
2508
+ },
2509
+ "publishToWorld"
2510
+ );
2511
+ },
2512
+ async ruleDeclare() {
2513
+ const refusal = doorAbsent(DOORS.ruleDeclare);
2514
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where: "ruleDeclare" });
2515
+ return err(refusal);
2516
+ },
2517
+ async metadataSearch() {
2518
+ const refusal = doorAbsent(DOORS.metadataSearch);
2519
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where: "metadataSearch" });
2520
+ return err(refusal);
2521
+ },
2522
+ async fieldPropose() {
2523
+ const refusal = doorAbsent(DOORS.fieldPropose);
2524
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where: "fieldPropose" });
2525
+ return err(refusal);
2526
+ },
2527
+ async tablePropose() {
2528
+ const refusal = doorAbsent(DOORS.tablePropose);
2529
+ scream({ code: refusal.code, message: refusal.message, ...refusal.hint ? { hint: refusal.hint } : {}, where: "tablePropose" });
2530
+ return err(refusal);
2531
+ },
2532
+ async promoteTable({ table_id }) {
2533
+ return callDoor(
2534
+ DOORS.promoteTable,
2535
+ { p_organization_id: org, p_table_id: table_id },
2536
+ "promoteTable"
2537
+ );
2538
+ },
2539
+ async promoteField({ table_id, field_id }) {
2540
+ return callDoor(
2541
+ DOORS.promoteField,
2542
+ { p_organization_id: org, p_table_id: table_id, p_field_id: field_id },
2543
+ "promoteField"
2544
+ );
2545
+ },
2546
+ async storeIsOpen() {
2547
+ return callDoor(DOORS.storeIsOpen, { p_organization_id: org }, "storeIsOpen");
2548
+ }
2549
+ };
2550
+ return client;
2551
+ }
2552
+ function asWriteConflict(error, recordId) {
2553
+ const detail = staleWriteDetail(error);
2554
+ if (!detail) return null;
2555
+ return {
2556
+ ...detail,
2557
+ record_id: recordId,
2558
+ message: error.message,
2559
+ hint: error.hint ?? ""
2560
+ };
2561
+ }
2562
+
2563
+ // src/core/validation.ts
2564
+ var DEFAULT_VALUE_MAX_BYTES = 1e5;
2565
+ var DEFAULT_DOCUMENT_MAX_BYTES = 1048576;
2566
+ var jsonType = (value) => {
2567
+ if (value === null) return "null";
2568
+ if (Array.isArray(value)) return "array";
2569
+ switch (typeof value) {
2570
+ case "string":
2571
+ return "string";
2572
+ case "number":
2573
+ return "number";
2574
+ case "boolean":
2575
+ return "boolean";
2576
+ case "object":
2577
+ return "object";
2578
+ default:
2579
+ return "null";
2580
+ }
2581
+ };
2582
+ function pgJsonbText(value) {
2583
+ if (value === null || value === void 0) return "null";
2584
+ if (Array.isArray(value)) return `[${value.map(pgJsonbText).join(", ")}]`;
2585
+ if (typeof value === "object") {
2586
+ const parts = Object.entries(value).map(
2587
+ ([k, v]) => `${JSON.stringify(k)}: ${pgJsonbText(v)}`
2588
+ );
2589
+ return `{${parts.join(", ")}}`;
2590
+ }
2591
+ return JSON.stringify(value);
2592
+ }
2593
+ var jsonBytes = (value) => new TextEncoder().encode(pgJsonbText(value)).length;
2594
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2595
+ function labelOf(field) {
2596
+ return field.label && field.label.length > 0 ? field.label : field.key;
2597
+ }
2598
+ function ruleRefusal(field, rule, item, values) {
2599
+ const label = labelOf(field);
2600
+ const base = { sqlstate: "23514", predicted_by: "custom.validate_values", field_key: field.key };
2601
+ const num = typeof item === "number" ? item : null;
2602
+ switch (rule.kind) {
2603
+ case "min":
2604
+ if (num !== null && num < Number(rule.value)) {
2605
+ return { ...base, message: `${label} has to be at least ${rule.value}`, hint: "FLD-3: an attached validation Rule, not a behavior." };
2606
+ }
2607
+ return null;
2608
+ case "max":
2609
+ if (num !== null && num > Number(rule.value)) {
2610
+ return { ...base, message: `${label} cannot be more than ${rule.value}`, hint: "FLD-3: an attached validation Rule, not a behavior." };
2611
+ }
2612
+ return null;
2613
+ case "length":
2614
+ if (typeof item === "string" && item.length > Number(rule.value)) {
2615
+ return { ...base, message: `${label} is longer than ${rule.value} characters`, hint: "FLD-3." };
2616
+ }
2617
+ return null;
2618
+ case "pattern":
2619
+ if (typeof item === "string" && !new RegExp(String(rule.value)).test(item)) {
2620
+ return { ...base, message: `${label} is not written the way this field expects`, hint: "FLD-3." };
2621
+ }
2622
+ return null;
2623
+ case "equals_field": {
2624
+ const other = values[String(rule.value)];
2625
+ if (other !== void 0 && other !== null && JSON.stringify(other) !== JSON.stringify(item)) {
2626
+ return {
2627
+ ...base,
2628
+ message: `${label} and ${rule.value} have to be the same`,
2629
+ hint: "FLD-3 / T8: a constraint across two fields is a Rule attached to one of them, never a behavior."
2630
+ };
2631
+ }
2632
+ return null;
2633
+ }
2634
+ case "differs_from_field": {
2635
+ const other = values[String(rule.value)];
2636
+ if (other !== void 0 && JSON.stringify(other) === JSON.stringify(item)) {
2637
+ return { ...base, message: `${label} and ${rule.value} have to be different`, hint: "FLD-3." };
2638
+ }
2639
+ return null;
2640
+ }
2641
+ default:
2642
+ return null;
2643
+ }
2644
+ }
2645
+ function predictValueRefusals(fields, values, recordType) {
2646
+ const found = [];
2647
+ for (const field of fields) {
2648
+ const label = labelOf(field);
2649
+ const base = { sqlstate: "23514", predicted_by: "custom.validate_values", field_key: field.key };
2650
+ const raw = values[field.key];
2651
+ const isEmpty = raw === void 0 || raw === null || field.multi && Array.isArray(raw) && raw.length === 0;
2652
+ if (isEmpty) {
2653
+ if (field.required) {
2654
+ found.push({
2655
+ ...base,
2656
+ message: `${label} is required`,
2657
+ hint: `REC-51: the field ${field.key} of this table.`
2658
+ });
2659
+ }
2660
+ continue;
2661
+ }
2662
+ if (field.type === "formula") {
2663
+ found.push({
2664
+ ...base,
2665
+ message: `${label} is worked out by the system, so it cannot be typed in`,
2666
+ hint: `FLD-9: this formula computes on ${field.compute_on ?? "write"}.`
2667
+ });
2668
+ continue;
2669
+ }
2670
+ let items;
2671
+ if (field.multi) {
2672
+ if (!Array.isArray(raw)) {
2673
+ found.push({ ...base, message: `${label} holds many values, so it takes a list`, hint: "FLD-2: the multi modifier." });
2674
+ continue;
2675
+ }
2676
+ items = raw;
2677
+ } else {
2678
+ if (Array.isArray(raw)) {
2679
+ found.push({ ...base, message: `${label} holds one value, and it was given a list`, hint: "FLD-2: multi is off for this field." });
2680
+ continue;
2681
+ }
2682
+ items = [raw];
2683
+ }
2684
+ for (const item of items) {
2685
+ if (field.type === "text" && typeof item !== "string") {
2686
+ found.push({ ...base, message: `${label} takes words, and it was given a ${jsonType(item)}`, hint: "FLD-1: text." });
2687
+ } else if (field.type === "range") {
2688
+ const kind = field.config?.["kind"] ?? "number";
2689
+ if (typeof item === "number") {
2690
+ } else if (typeof item === "string" && (kind === "date" || kind === "datetime")) {
2691
+ if (Number.isNaN(Date.parse(item))) {
2692
+ found.push({ ...base, message: `${label} takes a date, and ${item} is not one`, hint: "FLD-1: range, of kind date." });
2693
+ }
2694
+ } else {
2695
+ found.push({ ...base, message: `${label} takes a number, and it was given a ${jsonType(item)}`, hint: "FLD-1: range." });
2696
+ }
2697
+ } else if (field.type === "list") {
2698
+ if (typeof item !== "string") {
2699
+ found.push({
2700
+ ...base,
2701
+ message: `${label} takes one of its choices, and it was given a ${jsonType(item)}`,
2702
+ hint: "FLD-5 / FLD-6: a list field stores the id of the option RECORD, because every pick-list is already a Table."
2703
+ });
2704
+ } else if (!UUID.test(item)) {
2705
+ found.push({
2706
+ ...base,
2707
+ message: `${label} was given a choice that is not one of its choices`,
2708
+ hint: `REC-51: option membership. ${label} stores the id of an option record, and what it was given is not an id at all.`
2709
+ });
2710
+ }
2711
+ } else if (field.type === "relation") {
2712
+ if (typeof item !== "string") {
2713
+ found.push({ ...base, message: `${label} points at a record, and it was given a ${jsonType(item)}`, hint: "FLD-1: relation." });
2714
+ } else if (!UUID.test(item)) {
2715
+ found.push({
2716
+ ...base,
2717
+ message: `${label} points at something that is not there`,
2718
+ hint: `REC-51: ${label} stores the id of a record, and what it was given is not an id at all.`
2719
+ });
2720
+ }
2721
+ }
2722
+ for (const rule of field.rules ?? []) {
2723
+ const applies = !rule.applies_to_types || rule.applies_to_types.length === 0 || recordType !== void 0 && rule.applies_to_types.includes(recordType);
2724
+ if (!applies) continue;
2725
+ const refusal = ruleRefusal(field, rule, item, values);
2726
+ if (refusal) found.push(refusal);
2727
+ }
2728
+ }
2729
+ if (field.type === "relation" && field.multi && field.relation_max !== null) {
2730
+ const n = items.length;
2731
+ if (n > field.relation_max) {
2732
+ found.push({
2733
+ ...base,
2734
+ message: `${label} points at ${n} things, and it can point at ${field.relation_max} at most`,
2735
+ hint: "REC-51: relation_max."
2736
+ });
2737
+ }
2738
+ }
2739
+ }
2740
+ return found;
2741
+ }
2742
+ function predictSizeRefusal(document, limits = {}) {
2743
+ const valueMax = limits.value_max_bytes ?? DEFAULT_VALUE_MAX_BYTES;
2744
+ const docMax = limits.document_max_bytes ?? DEFAULT_DOCUMENT_MAX_BYTES;
2745
+ for (const [key, value] of Object.entries(document)) {
2746
+ if (key.startsWith("_")) continue;
2747
+ const bytes = jsonBytes(value);
2748
+ if (bytes > valueMax) {
2749
+ return {
2750
+ field_key: key,
2751
+ sqlstate: "23514",
2752
+ predicted_by: "custom.size_refusal",
2753
+ message: `${key} is ${bytes} bytes, and one value in a record holds at most ${valueMax}. Put the big thing in a file record and point the value at it - this store has a File table for exactly that.`
2754
+ };
2755
+ }
2756
+ }
2757
+ const total = jsonBytes(document);
2758
+ if (total > docMax) {
2759
+ return {
2760
+ sqlstate: "23514",
2761
+ predicted_by: "custom.size_refusal",
2762
+ message: `this record is ${total} bytes, and one record holds at most ${docMax}. Put the big things in file records and point the values at them - this store has a File table for exactly that.`
2763
+ };
2764
+ }
2765
+ return null;
2766
+ }
2767
+ function predictEnvelopeRefusal(document) {
2768
+ const say = (message) => ({
2769
+ message,
2770
+ sqlstate: "23514",
2771
+ predicted_by: "custom.value_envelope_refusal"
2772
+ });
2773
+ let sources = {};
2774
+ if (Object.prototype.hasOwnProperty.call(document, "_sources")) {
2775
+ const block2 = document._sources;
2776
+ if (jsonType(block2) !== "object") {
2777
+ return say(
2778
+ `this record's provenance block (_sources) must be an object of pointer -> source, and it is a ${jsonType(block2)}.`
2779
+ );
2780
+ }
2781
+ sources = block2;
2782
+ for (const pointer of Object.keys(sources)) {
2783
+ if (!/^s[0-9]+$/.test(pointer)) {
2784
+ return say(
2785
+ `"${pointer}" is not a provenance pointer. A pointer is interned by this store and looks like s1, s2, s3 \u2014 it is never a name a writer chooses.`
2786
+ );
2787
+ }
2788
+ if (jsonType(sources[pointer]) !== "object") {
2789
+ return say(
2790
+ `the source at ${pointer} must be an object describing where the value came from, and it is a ${jsonType(sources[pointer])}.`
2791
+ );
2792
+ }
2793
+ }
2794
+ const distinct = new Set(Object.values(sources).map((v) => JSON.stringify(v)));
2795
+ if (distinct.size !== Object.keys(sources).length) {
2796
+ return say(
2797
+ `the same source is written twice in this record's provenance block. A source is interned once per save and every value that came from it points at the one entry.`
2798
+ );
2799
+ }
2800
+ }
2801
+ if (!Object.prototype.hasOwnProperty.call(document, "_values")) return null;
2802
+ const block = document._values;
2803
+ if (jsonType(block) !== "object") {
2804
+ return say(
2805
+ `this record's value block (_values) must be an object of field key -> envelope, and it is a ${jsonType(block)}.`
2806
+ );
2807
+ }
2808
+ for (const [key, envUnknown] of Object.entries(block)) {
2809
+ if (jsonType(envUnknown) !== "object") {
2810
+ return say(`the envelope for ${key} must be an object, and it is a ${jsonType(envUnknown)}.`);
2811
+ }
2812
+ const env = envUnknown;
2813
+ for (const k of Object.keys(env)) {
2814
+ if (!VALUE_ENVELOPE_KEYS.includes(k)) {
2815
+ if (PER_VALUE_ACCESS_WORDS.includes(k)) {
2816
+ return say(
2817
+ `${key} cannot carry "${k}": visibility and access belong to a Field and to a Record, never to a single value. A value that must be secret goes in a contained record with its own visibility.`
2818
+ );
2819
+ }
2820
+ return say(
2821
+ `${key} carries "${k}", which is not part of a value envelope. An envelope holds ${VALUE_ENVELOPE_KEYS.join(", ")}.`
2822
+ );
2823
+ }
2824
+ }
2825
+ if ("absent" in env && env.absent !== null) {
2826
+ const absent = String(env.absent);
2827
+ if (!ABSENCE_REASONS.includes(absent)) {
2828
+ return say(
2829
+ `${key}: "${absent}" is not a reason a value can be missing. The reasons are ${ABSENCE_REASONS.join(", ")}.`
2830
+ );
2831
+ }
2832
+ if (key in document && document[key] !== null) {
2833
+ return say(`${key} both holds a value and says why it is missing ("${absent}"). It can be one or the other.`);
2834
+ }
2835
+ }
2836
+ if ("src" in env && env.src !== null) {
2837
+ if (typeof env.src !== "string") {
2838
+ return say(
2839
+ `${key}: its source must be a provenance pointer this store interned. Write the source itself and the store interns it; ${jsonType(env.src)} is not a pointer.`
2840
+ );
2841
+ }
2842
+ if (!(env.src in sources)) {
2843
+ return say(`${key} points at the source ${env.src}, and this record's provenance block has no such entry.`);
2844
+ }
2845
+ }
2846
+ if ("alternates" in env && env.alternates !== null) {
2847
+ if (!Array.isArray(env.alternates)) {
2848
+ return say(`${key}: its other candidate values must be a list, and it is a ${jsonType(env.alternates)}.`);
2849
+ }
2850
+ const ranks = [];
2851
+ for (const altUnknown of env.alternates) {
2852
+ if (jsonType(altUnknown) !== "object") {
2853
+ return say(`${key}: every other candidate is a value, a source and a rank, and one of them is a ${jsonType(altUnknown)}.`);
2854
+ }
2855
+ const alt = altUnknown;
2856
+ for (const k of Object.keys(alt)) {
2857
+ if (!VALUE_ALTERNATE_KEYS.includes(k)) {
2858
+ if (PER_VALUE_ACCESS_WORDS.includes(k)) {
2859
+ return say(
2860
+ `${key}: an alternate cannot carry "${k}" \u2014 visibility and access belong to a Field and to a Record, never to a single value.`
2861
+ );
2862
+ }
2863
+ return say(
2864
+ `${key}: an alternate carries "${k}", which is not part of one. An alternate holds ${VALUE_ALTERNATE_KEYS.join(", ")} \u2014 a rank, which is the order an organization's sources are trusted in, and never a score or a confidence a machine invented.`
2865
+ );
2866
+ }
2867
+ }
2868
+ if (!("value" in alt)) {
2869
+ return say(`${key}: an alternate with no value is not a candidate for anything.`);
2870
+ }
2871
+ const rank = alt["rank"];
2872
+ if (typeof rank !== "number" || !Number.isInteger(rank) || rank < 1) {
2873
+ return say(`${key}: every alternate carries a whole rank of 1 or more \u2014 the order its source is trusted in.`);
2874
+ }
2875
+ if (ranks.includes(rank)) {
2876
+ return say(`${key}: two alternates claim rank ${rank}. A rank is an order, so it is held by one candidate.`);
2877
+ }
2878
+ ranks.push(rank);
2879
+ if ("src" in alt && alt["src"] !== null) {
2880
+ if (typeof alt["src"] !== "string") {
2881
+ return say(`${key}: an alternate's source must be a provenance pointer this store interned, and it is a ${jsonType(alt["src"])}.`);
2882
+ }
2883
+ if (!(String(alt["src"]) in sources)) {
2884
+ return say(`${key}: an alternate points at the source ${String(alt["src"])}, and this record's provenance block has no such entry.`);
2885
+ }
2886
+ }
2887
+ }
2888
+ }
2889
+ }
2890
+ return null;
2891
+ }
2892
+ function predictWriteRefusals(args) {
2893
+ const { fields, document, recordType, limits } = args;
2894
+ const values = {};
2895
+ for (const [k, v] of Object.entries(document)) {
2896
+ if (!k.startsWith("_")) values[k] = v;
2897
+ }
2898
+ const found = [];
2899
+ const envelope = predictEnvelopeRefusal(document);
2900
+ if (envelope) found.push(envelope);
2901
+ const size = predictSizeRefusal(document, limits);
2902
+ if (size) found.push(size);
2903
+ found.push(...predictValueRefusals(fields, values, recordType));
2904
+ return found;
2905
+ }
2906
+
2907
+ // src/core/io.ts
2908
+ var escape = (value) => /[",\n\r]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
2909
+ function cellText(value) {
2910
+ if (!value) return "";
2911
+ if (value.absent_reason) return `(${value.absent_reason})`;
2912
+ const raw = value.value;
2913
+ if (raw === null || raw === void 0) return "";
2914
+ if (typeof raw === "string") return raw;
2915
+ return JSON.stringify(raw);
2916
+ }
2917
+ function headerFor(field) {
2918
+ return field.label && field.label.length > 0 ? field.label : field.key;
2919
+ }
2920
+ function exportCsv(fields, rows) {
2921
+ const lines = [fields.map((f) => escape(headerFor(f))).join(",")];
2922
+ for (const row of rows) {
2923
+ lines.push(fields.map((f) => escape(cellText(row[f.key]))).join(","));
2924
+ }
2925
+ return lines.join("\n");
2926
+ }
2927
+ function toAoa(fields, rows) {
2928
+ return [fields.map(headerFor), ...rows.map((row) => fields.map((f) => cellText(row[f.key])))];
2929
+ }
2930
+ async function exportXlsx(fields, rows, sheetLabel = "Records") {
2931
+ const XLSX = await import("xlsx");
2932
+ const worksheet = XLSX.utils.aoa_to_sheet(toAoa(fields, rows));
2933
+ const workbook = XLSX.utils.book_new();
2934
+ const name = sheetLabel.replace(/[\\/?*[\]:]/g, " ").trim().slice(0, 31) || "Data";
2935
+ XLSX.utils.book_append_sheet(workbook, worksheet, name);
2936
+ return XLSX.write(workbook, { type: "array", bookType: "xlsx", compression: true });
2937
+ }
2938
+ function matchField(header, fields) {
2939
+ const wanted = header.trim().toLowerCase();
2940
+ return fields.find((f) => f.key.toLowerCase() === wanted) ?? fields.find((f) => (f.label ?? "").toLowerCase() === wanted) ?? null;
2941
+ }
2942
+ function parseCsv(text) {
2943
+ const rows = [];
2944
+ let row = [];
2945
+ let cell = "";
2946
+ let quoted = false;
2947
+ for (let i = 0; i < text.length; i += 1) {
2948
+ const ch = text[i];
2949
+ if (quoted) {
2950
+ if (ch === '"') {
2951
+ if (text[i + 1] === '"') {
2952
+ cell += '"';
2953
+ i += 1;
2954
+ } else quoted = false;
2955
+ } else cell += ch;
2956
+ continue;
2957
+ }
2958
+ if (ch === '"') quoted = true;
2959
+ else if (ch === ",") {
2960
+ row.push(cell);
2961
+ cell = "";
2962
+ } else if (ch === "\n" || ch === "\r") {
2963
+ if (ch === "\r" && text[i + 1] === "\n") i += 1;
2964
+ row.push(cell);
2965
+ rows.push(row);
2966
+ row = [];
2967
+ cell = "";
2968
+ } else cell += ch;
2969
+ }
2970
+ if (cell.length > 0 || row.length > 0) {
2971
+ row.push(cell);
2972
+ rows.push(row);
2973
+ }
2974
+ return rows;
2975
+ }
2976
+ function importCsv(fields, text) {
2977
+ return fromMatrix(fields, parseCsv(text));
2978
+ }
2979
+ async function importXlsx(fields, bytes) {
2980
+ const XLSX = await import("xlsx");
2981
+ const workbook = XLSX.read(bytes, { type: "array" });
2982
+ const first = workbook.SheetNames[0];
2983
+ if (!first) return { columns: [], rows: [], unmapped: [] };
2984
+ const sheet = workbook.Sheets[first];
2985
+ if (!sheet) return { columns: [], rows: [], unmapped: [] };
2986
+ const matrix = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false, defval: "" });
2987
+ return fromMatrix(fields, matrix);
2988
+ }
2989
+ function fromMatrix(fields, matrix) {
2990
+ const [header, ...body] = matrix;
2991
+ if (!header) return { columns: [], rows: [], unmapped: [] };
2992
+ const columns = header.map((text) => ({ header: text, field: matchField(text, fields) }));
2993
+ const unmapped = columns.filter((c) => c.field === null).map((c) => c.header).filter((h) => h.trim().length > 0);
2994
+ const rows = body.filter((line) => line.some((cell) => String(cell ?? "").trim().length > 0)).map((line) => {
2995
+ const record = {};
2996
+ columns.forEach((column, index) => {
2997
+ if (column.field) record[column.field.key] = String(line[index] ?? "");
2998
+ });
2999
+ return record;
3000
+ });
3001
+ return { columns, rows, unmapped };
3002
+ }
3003
+ //# sourceMappingURL=index.cjs.map