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