@svgrid/enterprise 3.1.74 → 3.1.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/cdn/svgrid-enterprise.svelte-external.js +2 -2
  2. package/dist/designer/assets/{index-C2M7tfqh.js → index-ZttiuDcp.js} +1 -1
  3. package/dist/designer/index.html +1 -1
  4. package/dist/fields/AutomationAction.svelte +2 -1
  5. package/dist/fields/AutomationGallery.svelte +152 -0
  6. package/dist/fields/AutomationGallery.svelte.d.ts +29 -0
  7. package/dist/fields/AutomationTrigger.svelte +10 -4
  8. package/dist/fields/AutomationTrigger.svelte.d.ts +5 -0
  9. package/dist/fields/SvBaseAutomations.svelte +46 -21
  10. package/dist/fields/SvBaseAutomations.svelte.d.ts +2 -0
  11. package/dist/fields/automation-edit.d.ts +6 -0
  12. package/dist/fields/automation-edit.js +2 -2
  13. package/dist/fields/automation-recipes.d.ts +85 -0
  14. package/dist/fields/automation-recipes.js +2 -0
  15. package/dist/fields/automations.svelte.d.ts +15 -2
  16. package/dist/fields/automations.svelte.js +6 -1
  17. package/dist/fields/builtin-types.js +1 -1
  18. package/dist/fields/filter-model.d.ts +5 -0
  19. package/dist/fields/filter-model.js +1 -1
  20. package/dist/fields/index.d.ts +1 -0
  21. package/dist/fields/index.js +1 -1
  22. package/dist/fields/messages/extras.d.ts +131 -0
  23. package/dist/fields/messages/extras.js +16 -1
  24. package/dist/fields/messages/viewbar.d.ts +4 -0
  25. package/dist/fields/messages/viewbar.js +1 -1
  26. package/dist/fields/messages.svelte.d.ts +135 -0
  27. package/dist/fields/rollups.d.ts +2 -0
  28. package/dist/fields/rollups.js +1 -1
  29. package/dist/fields/viewbar/ConditionValue.svelte +11 -2
  30. package/dist/node/studio.js +1 -1
  31. package/dist/version.d.ts +1 -1
  32. package/dist/version.js +1 -1
  33. package/dist/wc/{PageEditor-B_aDbCVD.js → PageEditor-uCGeOX5e.js} +1 -1
  34. package/dist/wc/embed-url-CozXxwvR.js +16 -0
  35. package/dist/wc/sv-base-element.js +102 -94
  36. package/package.json +1 -1
  37. package/dist/wc/embed-url-CGl6lpsT.js +0 -1
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Ready recipes for the Automations page: a sentence with blanks ("When
3
+ * **status** changes to **something**, notify **someone**"), each blank filled
4
+ * from the table (its status fields and their choices, its dates, its people,
5
+ * its e-mail and phone fields, the other tables). `buildRecipe` turns a filled
6
+ * recipe into an ordinary automation, made only of triggers and steps the
7
+ * editor already has, so the person can open it and change anything.
8
+ */
9
+ import { type BaseTable } from './base-tables.js';
10
+ import { type AutomationAction, type AutomationTrigger, type BaseAutomation } from './automations.svelte.js';
11
+ import { type FieldFilter } from './filter-model.js';
12
+ import type { FieldColumn } from './grid-access.js';
13
+ export type RecipeCategory = 'status' | 'created' | 'dates' | 'forms' | 'ai' | 'messages' | 'records' | 'connect';
14
+ /** The categories, in the order the gallery lists them. */
15
+ export declare const RECIPE_CATEGORIES: ReadonlyArray<RecipeCategory>;
16
+ /**
17
+ * What a blank asks for. Most are picked from the table; `days`, `url` and
18
+ * `emailTo` are typed (`emailTo` suggests the table's e-mail fields).
19
+ */
20
+ export type BlankKind = 'select' | 'choice' | 'checkbox' | 'date' | 'days' | 'who' | 'member' | 'personField' | 'creator' | 'emailField' | 'emailTo' | 'phoneField' | 'textField' | 'sourceField' | 'table' | 'button' | 'form' | 'every' | 'url';
21
+ /** A blank of a recipe: its name in the sentence, and, for a choice, the blank whose field it is a choice of. */
22
+ export type RecipeBlank = {
23
+ name: string;
24
+ kind: BlankKind;
25
+ of?: string;
26
+ };
27
+ export type RecipeValues = Record<string, string>;
28
+ type Built = {
29
+ trigger: AutomationTrigger;
30
+ condition?: FieldFilter;
31
+ actions: AutomationAction[];
32
+ };
33
+ export type Recipe = {
34
+ id: string;
35
+ categories: RecipeCategory[];
36
+ /** Shown first, in "Start with the basics". */
37
+ basic?: boolean;
38
+ blanks: RecipeBlank[];
39
+ build: (c: RecipeContext, v: RecipeValues) => Built;
40
+ };
41
+ /** What a recipe builds with: the table, the other tables, and words for its fields. */
42
+ export type RecipeContext = {
43
+ table: BaseTable;
44
+ tables: ReadonlyArray<BaseTable>;
45
+ field: (id: string) => FieldColumn | undefined;
46
+ /** `{Field name}`: the record's value, in a message or a value. */
47
+ token: (id: string) => string;
48
+ /** The record's name as a token. */
49
+ name: string;
50
+ };
51
+ export type BlankOption = {
52
+ value: string;
53
+ label: string;
54
+ };
55
+ export declare const RECIPES: ReadonlyArray<Recipe>;
56
+ export declare function recipeContext(table: BaseTable, tables: ReadonlyArray<BaseTable>): RecipeContext;
57
+ /**
58
+ * What a blank can be, on this table, with what the other blanks hold. A blank
59
+ * typed in (`days`, `url`, `emailTo`) gives suggestions only; `form` starts
60
+ * with "any form".
61
+ */
62
+ export declare function blankOptions(blank: RecipeBlank, table: BaseTable, tables: ReadonlyArray<BaseTable>, values?: RecipeValues): BlankOption[];
63
+ /** Blanks typed in rather than picked. */
64
+ export declare const TYPED: ReadonlySet<BlankKind>;
65
+ /** The first blank this table cannot fill (it has no field of that kind), or null. */
66
+ export declare function recipeMissing(r: Recipe, table: BaseTable, tables: ReadonlyArray<BaseTable>): BlankKind | null;
67
+ /** What each blank starts as: the first that fits, a status's choices after the first, "1" day. */
68
+ export declare function recipeStart(r: Recipe, table: BaseTable, tables: ReadonlyArray<BaseTable>): RecipeValues;
69
+ /** Whether every blank is filled. */
70
+ export declare function recipeFilled(r: Recipe, v: RecipeValues): boolean;
71
+ /** The sentence's parts: text, and blanks by name. */
72
+ export declare function recipeParts(r: Recipe): Array<{
73
+ text: string;
74
+ } | {
75
+ blank: RecipeBlank;
76
+ }>;
77
+ /** A blank's word on a card: "status", "something", "someone". */
78
+ export declare const blankWord: (b: RecipeBlank) => string;
79
+ /** The sentence with the blanks' words, for the cards and for search. */
80
+ export declare function recipeText(r: Recipe, label?: (b: RecipeBlank) => string): string;
81
+ /** Words naming a field kind a table lacks: "Needs a date field". */
82
+ export declare const missingWords: (kind: BlankKind) => string;
83
+ /** The automation a filled recipe makes, named by its sentence. */
84
+ export declare function buildRecipe(r: Recipe, table: BaseTable, tables: ReadonlyArray<BaseTable>, v: RecipeValues, id: string): BaseAutomation;
85
+ export {};
@@ -0,0 +1,2 @@
1
+ import{primaryOf as E}from"./base-tables.js";import{tableFields as F}from"./automations.svelte.js";import{COMPUTED_TYPES as A,newWebhookToken as $}from"./automation-edit.js";import{filterKindOf as B}from"./filter-model.js";import{getCurrentUser as _,getFieldUsers as M}from"./sources.svelte.js";import{cronWords as W}from"./cron-words.js";import{bm as b}from"./messages.svelte.js";export const RECIPE_CATEGORIES=["status","created","dates","forms","ai","messages","records","connect"];function p(t,e,i,r){const a=t.field(e),n=a&&B({...a.def,fieldType:a.fieldType})||"text";return r===void 0?{column:e,kind:n,op:i}:{column:e,kind:n,op:i,value:r}}const c=(...t)=>({kind:"fieldFilter",conjunction:"and",conditions:t}),S=(t,e,i)=>p(t,e,"is",i),P=(t,e,i)=>p(t,e,"isNot",i);function x(t,e,i){return i===0?p(t,e,"is",{mode:"today"}):p(t,e,"is",i>0?{mode:"daysFromNow",days:i}:{mode:"daysAgo",days:-i})}const w=(t,e="days")=>Math.max(1,Math.min(365,Math.floor(Number(t[e])||1))),T="0 8 * * *",f=(t,e)=>({type:"notify",message:t,...e?{to:[e]}:{}}),s=(t,e)=>b(t,e);function O(t,e){if(t)return[...F(t).values()].find(i=>i.fieldType==="link"&&i.def.fieldProps?.table===e.id)?.id}function N(t,e){const i=t.tables.find(o=>o.id===e),r=i&&i.id!==t.table.id?O(i,t.table):void 0,a=i?E(i):"",n={};return i&&i.id!==t.table.id&&a&&(n[a]=t.name),{type:"createRecord",table:e,values:n,...r?{linkField:r}:{}}}const D=t=>/chat\.googleapis\.com/i.test(t)?"googleChat":/(office|microsoft|logic\.azure|powerautomate|powerplatform)/i.test(t)?"teams":"slack",d={name:"status",kind:"select"},l={name:"value",kind:"choice",of:"status"},g={name:"who",kind:"who"},k={name:"date",kind:"date"},C={name:"days",kind:"days"},y=(t,e)=>({trigger:{type:"recordUpdated",fields:[e.status]},condition:c(S(t,e.status,e.value))});export const RECIPES=[{id:"statusNotify",categories:["status"],basic:!0,blanks:[d,l,g],build:(t,e)=>({...y(t,e),actions:[f(s("extras.recipeMsgNowIs",{name:t.name,field:t.token(e.status)}),e.who)]})},{id:"statusFromTo",categories:["status"],blanks:[d,{name:"from",kind:"choice",of:"status"},l,g],build:(t,e)=>({trigger:{type:"recordUpdated",fields:[e.status],from:c(S(t,e.status,e.from))},condition:c(S(t,e.status,e.value)),actions:[f(s("extras.recipeMsgFromTo",{name:t.name,from:e.from,to:e.value}),e.who)]})},{id:"statusAssign",categories:["status"],blanks:[d,l,{name:"member",kind:"member"},{name:"person",kind:"personField"}],build:(t,e)=>({...y(t,e),actions:[{type:"updateRecord",values:{[e.person]:M().find(i=>i.id===e.member)?.name??e.member}}]})},{id:"statusMove",categories:["status"],blanks:[d,l,{name:"status2",kind:"select"},{name:"value2",kind:"choice",of:"status2"}],build:(t,e)=>({...y(t,e),actions:[{type:"updateRecord",values:{[e.status2]:e.value2}}]})},{id:"statusStamp",categories:["status","dates"],blanks:[d,l,k],build:(t,e)=>({...y(t,e),actions:[{type:"updateRecord",values:{[e.date]:"today"}}]})},{id:"checkboxStatus",categories:["status"],blanks:[{name:"box",kind:"checkbox"},d,l],build:(t,e)=>({trigger:{type:"recordUpdated",fields:[e.box]},condition:c(p(t,e.box,"is",!0)),actions:[{type:"updateRecord",values:{[e.status]:e.value}}]})},{id:"createdNotify",categories:["created"],basic:!0,blanks:[g],build:(t,e)=>({trigger:{type:"recordCreated"},actions:[f(s("extras.recipeMsgNew",{name:t.name}),e.who)]})},{id:"createdCreator",categories:["created"],blanks:[{name:"creator",kind:"creator"},{name:"person",kind:"personField"}],build:(t,e)=>({trigger:{type:"recordCreated"},actions:[{type:"updateRecord",values:{[e.person]:t.token(e.creator)}}]})},{id:"createdStatus",categories:["created","status"],blanks:[d,l],build:(t,e)=>({trigger:{type:"recordCreated"},actions:[{type:"updateRecord",values:{[e.status]:e.value}}]})},{id:"createdDue",categories:["created","dates"],blanks:[k,C],build:(t,e)=>({trigger:{type:"recordCreated"},actions:[{type:"updateRecord",values:{[e.date]:`today+${w(e)}`}}]})},{id:"dateNotify",categories:["dates"],basic:!0,blanks:[k,g],build:(t,e)=>({trigger:{type:"scheduled",cron:T},condition:c(x(t,e.date,0)),actions:[f(s("extras.recipeMsgToday",{name:t.name,field:t.field(e.date)?.header??""}),e.who)]})},{id:"dateBeforeNotify",categories:["dates"],blanks:[C,k,g],build:(t,e)=>({trigger:{type:"scheduled",cron:T},condition:c(x(t,e.date,w(e))),actions:[f(s("extras.recipeMsgSoon",{name:t.name,field:t.field(e.date)?.header??"",date:t.token(e.date)}),e.who)]})},{id:"dateOverdue",categories:["dates","status"],blanks:[k,d,l,g],build:(t,e)=>({trigger:{type:"scheduled",cron:T},condition:c(x(t,e.date,-1),P(t,e.status,e.value)),actions:[f(s("extras.recipeMsgLate",{name:t.name,field:t.field(e.date)?.header??"",date:t.token(e.date)}),e.who)]})},{id:"dateStatus",categories:["dates","status"],blanks:[k,d,l],build:(t,e)=>({trigger:{type:"scheduled",cron:T},condition:c(x(t,e.date,0)),actions:[{type:"updateRecord",values:{[e.status]:e.value}}]})},{id:"dateBeforeEmail",categories:["dates","messages"],blanks:[C,k,{name:"email",kind:"emailField"}],build:(t,e)=>({trigger:{type:"scheduled",cron:T},condition:c(x(t,e.date,w(e)),p(t,e.email,"isNotEmpty")),actions:[{type:"email",to:t.token(e.email),subject:s("extras.recipeMailReminderSubject",{name:t.name}),body:s("extras.recipeMailReminderBody",{name:t.name,field:t.field(e.date)?.header??"",date:t.token(e.date)})}]})},{id:"dateBeforeText",categories:["dates","messages"],blanks:[C,k,{name:"phone",kind:"phoneField"}],build:(t,e)=>({trigger:{type:"scheduled",cron:T},condition:c(x(t,e.date,w(e)),p(t,e.phone,"isNotEmpty")),actions:[{type:"textMessage",channel:"sms",to:t.token(e.phone),text:s("extras.recipeTextReminder",{name:t.name,date:t.token(e.date)})}]})},{id:"everyRemind",categories:["dates"],blanks:[{name:"every",kind:"every"},g],build:(t,e)=>({trigger:{type:"scheduled",cron:e.every},actions:[f(s("extras.recipeMsgLook",{table:t.table.name}),e.who)]})},{id:"everyCreate",categories:["dates","records"],blanks:[{name:"every",kind:"every"},{name:"table",kind:"table"}],build:(t,e)=>({trigger:{type:"scheduled",cron:e.every},actions:[{type:"createRecord",table:e.table,values:{}}]})},{id:"formNotify",categories:["forms"],blanks:[{name:"form",kind:"form"},g],build:(t,e)=>({trigger:{type:"formSubmitted",...e.form?{view:e.form}:{}},actions:[f(s("extras.recipeMsgForm",{name:t.name}),e.who)]})},{id:"formEmail",categories:["forms","messages"],basic:!0,blanks:[{name:"form",kind:"form"},{name:"to",kind:"emailTo"}],build:(t,e)=>({trigger:{type:"formSubmitted",...e.form?{view:e.form}:{}},actions:[{type:"email",to:e.to,subject:s("extras.recipeMsgForm",{name:t.name}),body:s("extras.recipeMailFormBody",{table:t.table.name,name:t.name})}]})},{id:"formThanks",categories:["forms","messages"],blanks:[{name:"email",kind:"emailField"}],build:(t,e)=>({trigger:{type:"formSubmitted"},condition:c(p(t,e.email,"isNotEmpty")),actions:[{type:"email",to:t.token(e.email),subject:s("extras.recipeMailThanksSubject"),body:s("extras.recipeMailThanksBody",{name:t.name})}]})},{id:"buttonStatus",categories:["forms","status"],blanks:[{name:"button",kind:"button"},d,l],build:(t,e)=>({trigger:{type:"button",field:e.button},actions:[{type:"updateRecord",values:{[e.status]:e.value}}]})},{id:"buttonEmail",categories:["forms","messages"],blanks:[{name:"button",kind:"button"},{name:"email",kind:"emailField"}],build:(t,e)=>({trigger:{type:"button",field:e.button},actions:[{type:"email",to:t.token(e.email),subject:t.name,body:s("extras.recipeMailButtonBody",{name:t.name})}]})},{id:"aiWrite",categories:["ai","created"],blanks:[{name:"target",kind:"textField"},{name:"source",kind:"sourceField"}],build:(t,e)=>({trigger:{type:"recordCreated"},actions:[{type:"ai",prompt:s("extras.recipeAiWrite",{target:t.field(e.target)?.header??"",source:t.token(e.source)}),field:e.target}]})},{id:"aiSort",categories:["ai","created","status"],blanks:[d,{name:"source",kind:"sourceField"}],build:(t,e)=>{const i=t.field(e.status)?.def.fieldProps?.options??[];return{trigger:{type:"recordCreated"},actions:[{type:"ai",prompt:s("extras.recipeAiSort",{field:t.field(e.status)?.header??"",choices:i.map(r=>r.value).join(", "),source:t.token(e.source)}),field:e.status}]}}},{id:"aiFormSummary",categories:["ai","forms"],blanks:[{name:"target",kind:"textField"}],build:(t,e)=>{const i=[...F(t.table).values()].filter(r=>r.id!==e.target&&r.fieldType!=="button"&&r.fieldType!=="attachment").slice(0,12);return{trigger:{type:"formSubmitted"},actions:[{type:"ai",prompt:s("extras.recipeAiSummary",{answers:i.map(r=>`${r.header}: {${r.header}}`).join(`
2
+ `)}),field:e.target}]}}},{id:"aiReply",categories:["ai","status"],blanks:[d,l,{name:"target",kind:"textField"}],build:(t,e)=>({...y(t,e),actions:[{type:"ai",prompt:s("extras.recipeAiReply",{name:t.name}),field:e.target}]})},{id:"aiWeekly",categories:["ai","dates","messages"],blanks:[{name:"every",kind:"every"},{name:"to",kind:"emailTo"}],build:(t,e)=>({trigger:{type:"scheduled",cron:e.every},actions:[{type:"ai",prompt:s("extras.recipeAiWeekly"),base:!0},{type:"email",to:e.to,subject:s("extras.recipeMailWeeklySubject"),body:"{ai}"}]})},{id:"statusEmail",categories:["messages","status"],basic:!0,blanks:[d,l,{name:"email",kind:"emailField"}],build:(t,e)=>({...y(t,e),condition:c(S(t,e.status,e.value),p(t,e.email,"isNotEmpty")),actions:[{type:"email",to:t.token(e.email),subject:s("extras.recipeMailStatusSubject",{name:t.name,value:e.value}),body:s("extras.recipeMailStatusBody",{name:t.name,value:e.value})}]})},{id:"statusText",categories:["messages","status"],blanks:[d,l,{name:"phone",kind:"phoneField"}],build:(t,e)=>({...y(t,e),condition:c(S(t,e.status,e.value),p(t,e.phone,"isNotEmpty")),actions:[{type:"textMessage",channel:"sms",to:t.token(e.phone),text:s("extras.recipeTextStatus",{name:t.name,value:e.value})}]})},{id:"createdEmail",categories:["messages","created"],blanks:[{name:"to",kind:"emailTo"}],build:(t,e)=>({trigger:{type:"recordCreated"},actions:[{type:"email",to:e.to,subject:s("extras.recipeMailNewSubject",{name:t.name}),body:""}]})},{id:"createdChat",categories:["messages","connect"],blanks:[{name:"url",kind:"url"}],build:(t,e)=>({trigger:{type:"recordCreated"},actions:[{type:"chat",service:D(e.url),url:e.url,text:s("extras.recipeMsgNew",{name:t.name})}]})},{id:"statusCreate",categories:["records","status"],blanks:[d,l,{name:"table",kind:"table"}],build:(t,e)=>({...y(t,e),actions:[N(t,e.table)]})},{id:"createdCreate",categories:["records","created"],blanks:[{name:"table",kind:"table"}],build:(t,e)=>({trigger:{type:"recordCreated"},actions:[N(t,e.table)]})},{id:"webhookOut",categories:["connect"],blanks:[{name:"url",kind:"url"}],build:(t,e)=>({trigger:{type:"recordCreated"},actions:[{type:"webhook",url:e.url,body:""}]})},{id:"webhookIn",categories:["connect","records"],blanks:[],build:t=>({trigger:{type:"webhookReceived",token:$()},actions:[{type:"createRecord",table:t.table.id,values:{}}]})}];export function recipeContext(t,e){const i=F(t),r=a=>`{${i.get(a)?.header??a}}`;return{table:t,tables:e,field:a=>i.get(a),token:r,name:r(E(t))}}const I=t=>!A.has(String(t.fieldType??"")),u=(t,e)=>[...F(t).values()].filter(e).map(i=>({value:i.id,label:i.header})),U=["0 8 * * *","0 8 * * 1-5","0 8 * * 1","0 8 1 * *"];export function blankOptions(t,e,i,r={}){switch(t.kind){case"select":return u(e,a=>a.fieldType==="singleSelect");case"choice":{const a=t.of?r[t.of]:"";return((a?F(e).get(a):void 0)?.def.fieldProps?.options??[]).map(o=>({value:o.value,label:o.label||o.value}))}case"checkbox":return u(e,a=>a.fieldType==="checkbox");case"date":return u(e,a=>a.fieldType==="date");case"who":return[...u(e,a=>a.fieldType==="user"||a.fieldType==="createdBy").map(a=>({value:`field:${a.value}`,label:b("extras.blankTheField",{field:a.label})})),...M().map(a=>({value:a.id,label:a.name}))];case"member":return M().map(a=>({value:a.id,label:a.name}));case"personField":return u(e,a=>a.fieldType==="user");case"creator":return u(e,a=>a.fieldType==="createdBy");case"emailField":return u(e,a=>a.fieldType==="email");case"emailTo":{const a=_();return[...a?.email?[{value:a.email,label:b("extras.blankMe",{name:a.name})}]:[],...u(e,n=>n.fieldType==="email").map(n=>({value:`{${n.label}}`,label:b("extras.blankTheField",{field:n.label})})),...M().filter(n=>n.email&&n.email!==a?.email).map(n=>({value:n.email,label:n.name}))]}case"phoneField":return u(e,a=>a.fieldType==="phone");case"textField":return u(e,a=>I(a)&&(a.fieldType==="longText"||a.fieldType==="richText"||a.fieldType==="text"));case"sourceField":return u(e,a=>a.fieldType!=="button"&&a.fieldType!=="attachment"&&a.fieldType!=="checkbox");case"table":return i.map(a=>({value:a.id,label:a.name}));case"button":return u(e,a=>a.fieldType==="button");case"form":return[{value:"",label:b("extras.blankAnyForm")},...(e.views??[]).filter(a=>a.type==="form").map(a=>({value:a.id,label:a.name}))];case"every":return U.map(a=>({value:a,label:W(a)}));default:return[]}}export const TYPED=new Set(["days","url","emailTo"]);export function recipeMissing(t,e,i){for(const r of t.blanks)if(!(TYPED.has(r.kind)||r.kind==="choice"||r.kind==="form")&&!blankOptions(r,e,i).length)return r.kind;return null}export function recipeStart(t,e,i){const r={},a=new Set;for(const n of t.blanks){if(n.kind==="days"){r[n.name]="1";continue}if(n.kind==="url"||n.kind==="emailTo"){r[n.name]=n.kind==="emailTo"?blankOptions(n,e,i)[0]?.value??"":"";continue}const o=blankOptions(n,e,i,r),R=o.find(h=>!a.has(`${n.kind}:${h.value}`))??o[0],m=n.kind==="choice"&&n.name==="value"&&t.blanks.some(h=>h.name==="from")?o[1]??o[0]:R;r[n.name]=m?.value??"",m&&n.kind!=="choice"&&a.add(`${n.kind}:${m.value}`)}return r}export function recipeFilled(t,e){return t.blanks.every(i=>i.kind==="form"||(e[i.name]??"").trim()!=="")}export function recipeParts(t){const e=b(`extras.recipe_${t.id}`),i=[];let r=0;for(const a of e.matchAll(/\{(\w+)\}/g)){a.index>r&&i.push({text:e.slice(r,a.index)});const n=t.blanks.find(o=>o.name===a[1]);i.push(n?{blank:n}:{text:a[0]}),r=a.index+a[0].length}return r<e.length&&i.push({text:e.slice(r)}),i}export const blankWord=t=>b(`extras.blank_${t.kind}`);export function recipeText(t,e){return recipeParts(t).map(i=>"text"in i?i.text:e?.(i.blank)??blankWord(i.blank)).join("")}export const missingWords=t=>b(`extras.recipeNeeds_${t}`);export function buildRecipe(t,e,i,r,a){const n=recipeContext(e,i),o=t.build(n,r);return{id:a,name:recipeText(t,m=>{const h=r[m.name]??"";return m.kind==="days"?String(w(r,m.name)):TYPED.has(m.kind)?h:blankOptions(m,e,i,r).find(j=>j.value===h)?.label??blankWord(m)}),enabled:!0,trigger:o.trigger,...o.condition?{condition:o.condition}:{},actions:o.actions}}
@@ -10,10 +10,15 @@ export type AutomationTrigger =
10
10
  {
11
11
  type: 'recordCreated';
12
12
  }
13
- /** A record changes; with `fields`, only when one of them does. */
13
+ /**
14
+ * A record changes; with `fields`, only when one of them does; with `from`,
15
+ * only when the record matched it before the change ("Status changes from
16
+ * Waiting to Done": `from` Status is Waiting, the condition Status is Done).
17
+ */
14
18
  | {
15
19
  type: 'recordUpdated';
16
20
  fields?: string[];
21
+ from?: FieldFilter;
17
22
  }
18
23
  /** A record starts matching the condition (it did not before the change). */
19
24
  | {
@@ -128,7 +133,8 @@ export type AutomationAction =
128
133
  | {
129
134
  type: 'ai';
130
135
  prompt: string;
131
- field?: string;
136
+ field?: string; /** The server sends every table's records with the prompt. */
137
+ base?: boolean;
132
138
  }
133
139
  /**
134
140
  * Run JavaScript in a sandbox in the browser (automation-script.ts):
@@ -194,6 +200,13 @@ export declare function tableFields(t: BaseTable): Map<string, FieldColumn>;
194
200
  export type RunValues = Map<string, string>;
195
201
  /** `{Field name}` tokens of a template, filled from a record (and the run's `values`). A run with no record says so: the token is not for reading. */
196
202
  export declare function fillTokens(t: BaseTable, record: Row | null, template: string, values?: RunValues): string;
203
+ /**
204
+ * Every table's records as text, for an AI step sent the whole base: a heading
205
+ * per table, then a line per record ("- Name | Field: value | ..."), names for
206
+ * links and options. Past `most` characters each table keeps a fair share (what
207
+ * a small table leaves goes to the bigger ones) and says how many it shows. Files, buttons and empty values are left out.
208
+ */
209
+ export declare function baseText(tables: ReadonlyArray<BaseTable>, most?: number): string;
197
210
  /** The filter of a table's view, when it has one a record can be tested against. */
198
211
  export declare function viewFilterOf(t: BaseTable, viewId: string | undefined): FieldFilter | null;
199
212
  /** Whether a record matches a condition (no condition matches every record). */
@@ -1 +1,6 @@
1
- import{toast}from"@svgrid/grid";import{createScheduler}from"../scheduling.js";import{colId,primaryOf,rowIdOf,syncAllInverses}from"./base-tables.js";import{compileFieldFilter,describeFieldFilter}from"./filter-model.js";import{fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";import{noteChange}from"./activity.svelte.js";import{getCurrentUser,getFieldUsers}from"./sources.svelte.js";import{newRecordId}from"./field-ops.js";import{fieldText,fieldValue,linkNames}from"./base-alerts.js";import{callWebhook,sendChat,sendEmailAction,sendTextAction}from"./automation-outbound.js";import{runScript}from"./automation-script.js";import{bm}from"./messages.svelte.js";import{cronWords}from"./cron-words.js";const appActions=new Map;export function registerAutomationAction(id,action){appActions.set(id,action)}export function listAutomationActions(){return[...appActions].map(([id,a])=>({id,label:a.label}))}const readers=new WeakMap;export function tableFields(t){const hit=readers.get(t.columns);if(hit)return hit;const all=t.columns.map(d=>({...d,id:colId(d)}));const map=new Map;for(const d of t.columns){if(d.field==null)continue;const def=fillFieldColumn(d,all);map.set(colId(d),{id:colId(d),field:String(d.field),header:String(d.header??d.field),fieldType:d.fieldType,def,visible:true})}readers.set(t.columns,map);return map}const byName=(t,name)=>{const lower=name.trim().toLowerCase();for(const c of tableFields(t).values()){if(c.header.trim().toLowerCase()===lower||c.field.toLowerCase()===lower||c.id.toLowerCase()===lower)return c}return void 0};export function fillTokens(t,record,template,values){return template.replace(/\{([^{}\n]+)\}/g,(m,name)=>{const given=values?.get(name.trim().toLowerCase());if(given!==void 0)return given;const c=byName(t,name);return!c?m:record?fieldText(c,record):bm("extras.noRecordValue")})}export function viewFilterOf(t,viewId){const v=(t.views??[]).find(x=>x.id===viewId);const f=v?.state?.advancedFilter;return f&&typeof f==="object"&&f.kind==="fieldFilter"?f:null}export function matches(t,condition,record){if(!condition)return true;const fields=tableFields(t);const test=compileFieldFilter(condition,(row,id)=>{const c=fields.get(id);return c?fieldValue(c,row):row[id]},linkNames);return test?test(record):true}function stampModifiedTime(t,row,changedIds,at){for(const d of t.columns){if(d.fieldType!=="lastModifiedTime"||d.field==null||changedIds.includes(colId(d)))continue;const p=fieldPropsOf(d);if(p.watch==="specific"&&!changedIds.some(id=>(p.watchFields??[]).includes(id)))continue;row[String(d.field)]=at.toISOString()}}const DAY=864e5;const isoDay=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;export function fieldValueFrom(t,def,spec,ctx){const type=def.fieldType;if(typeof spec!=="string")return spec;const raw=spec.includes("{record}")?spec:fillTokens(ctx.from,ctx.record,spec,ctx.values);const text=raw.trim();if(text==="")return type==="checkbox"?false:type==="multiSelect"||type==="link"||type==="attachment"?[]:null;switch(type){case"checkbox":return/^(true|yes|1|checked|on)$/i.test(text);case"number":case"rating":case"duration":case"currency":case"percent":{const n=Number(text.replace(/[^0-9.+-eE]/g,""));return Number.isFinite(n)?text.endsWith("%")?n/100:n:null}case"multiSelect":return text.split(/\s*,\s*/).filter(Boolean);case"user":{const found=getFieldUsers().find(u=>u.id===text||u.name.toLocaleLowerCase()===text.toLocaleLowerCase());return found?found.id:text}case"date":{const m=/^(today|now)\s*(?:([+-])\s*(\d+))?$/i.exec(text);if(!m)return text;const shift=m[2]?(m[2]==="-"?-1:1)*Number(m[3])*DAY:0;const at=new Date(ctx.now.getTime()+shift);return m[1].toLowerCase()==="now"||def.fieldProps?.time?at.toISOString():isoDay(at)}case"link":{const target=ctx.tables.find(x=>x.id===def.fieldProps?.table);const out=[];for(const part of text.split(/\s*,\s*/)){if(part==="{record}"){if(ctx.record&&ctx.from.id===target?.id)out.push(rowIdOf(ctx.from,ctx.record));continue}const name=fillTokens(ctx.from,ctx.record,part,ctx.values).toLocaleLowerCase();const named=ctx.named?.get(name);if(named){out.push(named);continue}const hit=target?.data.find(r=>String(r?.[primaryOf(target)]??"").toLocaleLowerCase()===name);if(hit&&target)out.push(rowIdOf(target,hit))}return def.fieldProps?.multiple===false?out.slice(0,1):out}default:return raw}}export const MAX_DEPTH=4;export function pressedValues(){const me=getCurrentUser();const out=new Map;out.set("pressed.name",me?.name??"");out.set("pressed.email",me?.email??"");out.set("pressed.id",me?.id??"");return out}export const REPEAT_MOST=1e3;const SCRIPT_ROWS=5e3;const READ_AS_TEXT=new Set(["checkbox","number","rating","duration","currency","percent","multiSelect","user","date","link"]);export function scriptRecord(t,r){const values={};const texts={};let name="";for(const c of tableFields(t).values()){let v=r[c.field]??null;try{v=JSON.parse(JSON.stringify(v))}catch{v=null}values[c.header]=v;texts[c.header]=fieldText(c,r);if(c.field===primaryOf(t))name=texts[c.header]}return{id:rowIdOf(t,r),name,values,texts}}export function scriptInput(t,rec,values){const out={};if(rec){out.recordId=rowIdOf(t,rec);for(const c of tableFields(t).values())out[c.header]=fieldText(c,rec)}for(const[k,v]of values)out[k]=v;return out}export function webhookValues(body){const out=new Map;const walk=(v,path,depth)=>{if(out.size>=200)return;if(v!==null&&typeof v==="object"&&depth<5){for(const[k,x]of Object.entries(v).slice(0,100))walk(x,`${path}.${k.toLowerCase()}`,depth+1);if(path!=="webhook")out.set(path,JSON.stringify(v));return}out.set(path,v==null?"":typeof v==="string"?v:JSON.stringify(v))};walk(body,"webhook",0);out.set("webhook",typeof body==="string"?body:JSON.stringify(body??null));return out}export function triggerValues(t,rec,values){const out=new Map(values);if(rec)for(const c of tableFields(t).values())out.set(`trigger.${c.header.trim().toLowerCase()}`,fieldText(c,rec));return out}export function allActions(list){const out=[];for(const x of list){out.push(x);if(x.type==="if")out.push(...allActions(x.then??[]),...allActions(x.else??[]));if(x.type==="repeat")out.push(...allActions(x.actions??[]))}return out}const SHOW_BACKLOG=20;const CARRY_MOST=5e3;const FREE_EVERY=4096;let runSeq=0;export function createAutomationRunner(options){const now=options.now??(()=>new Date);let runs=$state.raw([]);let scheduler=null;let chain=Promise.resolve();let waiting=[];let head=0;let draining=false;let burst={done:0,total:0,at:0,told:0};let backlog=$state.raw(null);let measured=null;const record=run=>runs=[run,...runs].slice(0,100);const automationsOf=t=>(t.automations??[]).filter(a=>a.enabled&&a.runOn!=="server");const tableOf=id=>options.getTables()?.find(t=>t.id===id);const carried=new Map;const carriedFor=new Map;const carry=(key,row)=>{carried.set(key,row);carriedFor.set(key,(carriedFor.get(key)??0)+1)};const letGo=key=>{const left=(carriedFor.get(key)??1)-1;if(left>0)return void carriedFor.set(key,left);carriedFor.delete(key);carried.delete(key)};const recordNow=async(t,id)=>{const own=tableOf(t.id)??t;if(!own.source?.server)return own.data.find(r=>r&&rowIdOf(own,r)===id)??null;return carried.get(`${t.id}:${id}`)??await options.server?.read(t.id,id)??null};async function namesIn(target,values,ctx){const named=new Map;const fields=tableFields(target);for(const[id,spec]of Object.entries(values)){const def=fields.get(id)?.def;if(def?.fieldType!=="link"||typeof spec!=="string")continue;const to=(options.getTables()??[]).find(x=>x.id===def.fieldProps?.table);if(!to?.source?.server)continue;for(const part of spec.split(/\s*,\s*/)){const name=fillTokens(ctx.from,ctx.record,part);const hit=part==="{record}"?null:await options.server?.byName(to.id,name);if(hit)named.set(name.toLocaleLowerCase(),hit)}}return named}const setOff=(t,e)=>automationsFor(t,e,"browser");function handle(e){const t=tableOf(e.table);if(!t)return chain;const list=setOff(t,e);const depth="depth"in e?e.depth??0:0;const recordId=rowIdOf(t,e.record);for(const a of list){if(t.source?.server&&waiting.length-head<CARRY_MOST)carry(`${t.id}:${recordId}`,e.record);if(!draining&&head===waiting.length)burst={done:0,total:0,at:Date.now(),told:0};burst.total+=1;waiting.push({a,tableId:t.id,recordId,depth})}return list.length?drain():chain}function tell(){const clock=Date.now();if(burst.total<SHOW_BACKLOG||clock-burst.told<250)return;burst.told=clock;const seconds=(clock-burst.at)/1e3;if(burst.done>=SHOW_BACKLOG&&seconds>0)measured=burst.done/seconds;backlog={done:burst.done,total:burst.total,perSecond:burst.done>=SHOW_BACKLOG?measured:null}}function endBurst(left){const shown=backlog!=null||burst.total>=SHOW_BACKLOG;backlog=null;if(shown)options.onBurstEnd?.({done:burst.total-left,total:burst.total,left})}function drain(){if(draining)return chain;draining=true;tell();chain=chain.then(async()=>{let breath=Date.now();for(;;){if(head>=waiting.length){if(burst.total<SHOW_BACKLOG)break;await new Promise(r=>setTimeout(r,200));if(head>=waiting.length)break;continue}if(Date.now()-breath>40){await new Promise(r=>setTimeout(r));breath=Date.now();continue}const w=waiting[head];head+=1;if(head>=FREE_EVERY){waiting=waiting.slice(head);head=0}try{await runOne(w.a,w.tableId,w.recordId,w.depth)}catch(e){record({id:++runSeq,automationId:w.a.id,name:w.a.name,table:tableOf(w.tableId)?.name??w.tableId,record:w.recordId,at:now().getTime(),status:"error",steps:[{action:w.a.name,detail:"",error:e instanceof Error?e.message:String(e)}]})}if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`);burst.done+=1;tell()}waiting=[];head=0;draining=false;endBurst(0)});return chain}function stopRuns(){const left=waiting.length-head;if(!left)return 0;for(let i=head;i<waiting.length;i++){const w=waiting[i];if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`)}waiting=[];head=0;endBurst(left);burst={done:0,total:0,at:Date.now(),told:0};return left}async function runOne(a,tableId,recordId,depth){const t=tableOf(tableId);if(!t)return;const rec=recordId==null?null:await recordNow(t,recordId);const run={id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:rec?String(rec[primaryOf(t)]??recordId):null,at:now().getTime(),status:"ok",steps:[]};if(depth>=MAX_DEPTH){run.status="stopped";run.steps.push({action:bm("extras.stepStopped"),detail:bm("extras.stepLoop",{max:MAX_DEPTH})});record(run);return}await runList(a,a.actions,tableId,recordId,depth,run,a.trigger.type==="button"?pressedValues():new Map);record(run)}async function runList(a,list,tableId,recordId,depth,run,values){for(const action of list){try{if(action.type==="if"){const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const yes=!!t&&(rec?matches(t,action.condition,rec):!action.condition?.conditions?.length);run.steps.push({action:bm("extras.stepIf"),detail:bm(yes?"extras.stepIfThen":"extras.stepIfElse")});if(!await runList(a,(yes?action.then:action.else)??[],tableId,recordId,depth,run,values))return false;continue}if(action.type==="repeat"){if(!await runRepeat(a,action,tableId,recordId,depth,run,values))return false;continue}const step=await act(a,action,tableId,recordId,depth,values);if(step)run.steps.push(step)}catch(e){run.status="error";run.steps.push({action:actionLabel(action),detail:"",error:e instanceof Error?e.message:String(e)});return false}}return true}async function runRepeat(a,action,tableId,recordId,depth,run,values){const target=tableOf(action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const most=Math.max(1,Math.min(REPEAT_MOST,action.limit??100));const ids=[];if(target.source?.server){await options.server?.each(target.id,action.condition,async r=>{if(ids.length>=most)return;const id=rowIdOf(target,r);carry(`${target.id}:${id}`,r);ids.push(id)})}else{for(const r of target.data){if(ids.length>=most)break;if(r&&matches(target,action.condition,r))ids.push(rowIdOf(target,r))}}run.steps.push({action:bm("extras.stepFound"),detail:bm("extras.foundIn",{count:ids.length,table:target.name})});const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const inner=t?triggerValues(t,rec,values):new Map(values);inner.set("found",String(ids.length));try{for(const id of ids)if(!await runList(a,action.actions??[],target.id,id,depth,run,inner))return false}finally{if(target.source?.server)for(const id of ids)letGo(`${target.id}:${id}`)}return true}async function writeRecord(a,t,recordId,rec,patch,depth,at){const fields=tableFields(t);const before={...rec};const after={...rec,...patch};const changed=Object.keys(patch).filter(f=>JSON.stringify(before[f]??null)!==JSON.stringify(after[f]??null));if(!changed.length)return{changed,after};const changedIds=changed.map(f=>[...fields.values()].find(c=>c.field===f)?.id??f);stampModifiedTime(t,after,changedIds,at);if(t.source?.server){carried.set(`${t.id}:${recordId}`,after);await options.server?.update(t.id,recordId,Object.fromEntries(Object.keys(after).filter(k=>after[k]!==before[k]).map(k=>[k,after[k]])),before)}else{const tables=options.getTables()??[];let next=tables.map(x=>x.id===t.id?{...x,data:x.data.map(r=>r&&rowIdOf(t,r)===recordId?after:r)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}changed.forEach((f,i)=>noteChange({base:options.scope,tableId:t.id},recordId,changedIds[i],after[f],a.name));void handle({type:"updated",table:t.id,record:after,before,fields:changedIds,depth:depth+1});return{changed,after}}function addRecord(target,row,depth){const tables=options.getTables()??[];let next=tables.map(x=>x.id===target.id?{...x,data:[...x.data,row]}:x);next=syncAllInverses(next,target.id);options.apply(next,depth+1,target.id);void handle({type:"created",table:target.id,record:row,depth:depth+1})}function pageBridge(a,depth){const named=name=>{const t=(options.getTables()??[]).find(x=>x.name.trim().toLowerCase()===name.trim().toLowerCase());if(!t)throw new Error(bm("extras.noTable",{table:name}));return t};const rowsOf=async t=>{if(!t.source?.server)return t.data.filter(Boolean);const out=[];await options.server?.each(t.id,void 0,async r=>{if(out.length<SCRIPT_ROWS)out.push(r)});return out};const patchOf=(t,given)=>{const patch={};for(const[name,v]of Object.entries(given??{})){const c=byName(t,name);if(!c)throw new Error(bm("extras.noField",{field:name}));const type=String(c.fieldType??"");const text=typeof v==="string"?v:v&&typeof v==="object"&&!Array.isArray(v)&&"name"in v?String(v.name):null;patch[c.field]=text!==null&&READ_AS_TEXT.has(type)?fieldValueFrom(t,c.def,text.replace(/[{}]/g,""),{tables:options.getTables()??[],from:t,record:null,now:now()}):v}return patch};return{tables:()=>(options.getTables()??[]).map(t=>t.name),select:async name=>{const t=named(name);return(await rowsOf(t)).map(r=>scriptRecord(t,r))},update:async(name,id,given)=>{const t=named(name);const rec=await recordNow(t,id);if(!rec)throw new Error(bm("extras.noRecordId",{id}));await writeRecord(a,t,id,rec,patchOf(t,given),depth,now())},create:async(name,given)=>{const t=named(name);const row={id:newRecordId(),...patchOf(t,given)};addRecord(t,row,depth);return String(row.id)},remove:async(name,id)=>{const t=named(name);const tables=options.getTables()??[];options.apply(tables.map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==id)}:x),depth+1,t.id)}}}async function act(a,action,tableId,recordId,depth,values){const tables=options.getTables()??[];const t=tables.find(x=>x.id===tableId);const rec=recordId==null?null:await recordNow(t,recordId);const ctx={tables,from:t,record:rec,now:now(),values};switch(action.type){case"notify":{const message=fillTokens(t,rec,action.message,values);const sev=action.severity??"info";toast[sev](message);return{action:bm("extras.stepNotice"),detail:message}}case"highlight":return null;case"updateRecord":{if(!rec||recordId==null)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.noRecordToUpdate")};const fields=tableFields(t);const patch={};ctx.named=await namesIn(t,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)patch[c.field]=fieldValueFrom(t,c.def,spec,ctx)}const{changed,after}=await writeRecord(a,t,recordId,rec,patch,depth,ctx.now);if(!changed.length)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.alreadySet")};return{action:bm("extras.actionUpdateRecord"),detail:changed.map(f=>said([...fields.values()].find(c=>c.field===f),f,after)).join(", ")}}case"deleteRecord":{if(!rec||recordId==null)return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.noRecordToDelete")};const name=String(rec[primaryOf(t)]??"")||bm("extras.aRecord");if(t.source?.server){if(!options.server?.remove)throw new Error(bm("extras.cannotDeleteHere"));await options.server.remove(t.id,recordId,rec)}else{let next=(options.getTables()??[]).map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==recordId)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.deletedRecord",{name})}}case"createRecord":{const target=tables.find(x=>x.id===action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const fields=tableFields(target);const row={id:newRecordId()};ctx.named=await namesIn(target,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)row[c.field]=fieldValueFrom(target,c.def,spec,ctx)}if(action.linkField&&rec){const c=fields.get(action.linkField);if(c)row[c.field]=[rowIdOf(t,rec)]}addRecord(target,row,depth);const name=String(row[primaryOf(target)]??"")||bm("extras.aRecord");return{action:bm("extras.actionCreateRecord"),detail:bm("extras.createdIn",{name,table:target.name})}}case"run":return runAppAction(a,action,t,rec);case"webhook":return{action:bm("extras.stepWebhook"),detail:await callWebhook(action,outbound(a,t,rec,{},values))};case"email":return{action:bm("extras.stepEmail"),detail:await sendEmailAction(action,outbound(a,t,rec,{},values),void 0)};case"chat":return{action:bm("extras.stepChat"),detail:await sendChat(action,outbound(a,t,rec,{},values))};case"textMessage":return{action:bm("extras.stepText"),detail:await sendTextAction(action,outbound(a,t,rec,{},values),void 0)};case"ai":{if(!options.ai)throw new Error(bm("extras.noAi"));const prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));const answer=String(await options.ai(prompt)).trim();values.set("ai",answer);const c=action.field?tableFields(t).get(action.field):void 0;if(c&&rec&&recordId!=null)await writeRecord(a,t,recordId,rec,{[c.field]:answer},depth,ctx.now);return{action:bm("extras.stepAi"),detail:answer.length>160?answer.slice(0,157)+"...":answer}}case"script":{const result=await runScript(action.code,{input:scriptInput(t,rec,values),bridge:pageBridge(a,depth)});for(const[k,v]of Object.entries(result.output))values.set(`script.${k.toLowerCase()}`,typeof v==="string"?v:JSON.stringify(v));if(!result.ok)throw new Error(result.error??bm("extras.scriptFailed"));return{action:bm("extras.stepScript"),detail:result.logs.slice(-3).join(" | ")||bm("extras.stepDone")}}default:return null}}function schedule(){scheduler?.stop();scheduler=null;const list=options.getTables()??[];const due=[];for(const t of list)for(const a of automationsOf(t))if(a.trigger.type==="scheduled")due.push({id:`${t.id}:${a.id}`,cron:a.trigger.cron,table:t.id,automation:a});if(!due.length)return;scheduler=createScheduler({schedules:due,now,onFire:s=>void runScheduled(s.id)});scheduler.start()}function runScheduled(key){const[tableId,automationId]=key.split(":");const t=tableOf(tableId);const a=t?.automations?.find(x=>x.id===automationId);if(!t||!a)return chain;if(!a.condition)chain=chain.then(()=>runOne(a,t.id,null,0));else if(t.source?.server){chain=chain.then(()=>options.server?.each(t.id,a.condition,async r=>{const key2=`${t.id}:${rowIdOf(t,r)}`;carry(key2,r);await runOne(a,t.id,rowIdOf(t,r),0);letGo(key2)}))}else for(const r of t.data)if(r&&matches(t,a.condition,r))chain=chain.then(()=>runOne(a,t.id,rowIdOf(t,r),0));return chain}return{handle,stopRuns,get backlog(){return backlog},get waiting(){return waiting.length-head},get perSecond(){return measured},schedule,runScheduled,firstRecords:async(tableId,count)=>await options.server?.first(tableId,count)??[],runNow:(a,tableId,recordId)=>chain=chain.then(async()=>{const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;if(t&&rec&&a.condition&&!matches(t,a.condition,rec)){record({id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:String(rec[primaryOf(t)]??recordId),at:now().getTime(),status:"stopped",steps:[{action:bm("extras.stepNotRun"),detail:bm("extras.stepNoMatch")}]});return}return runOne(a,tableId,recordId,0)}),get runs(){return runs},clearRuns:()=>runs=[],settled:()=>chain,stop:()=>scheduler?.stop()}}function said(c,field,record){if(!c)return bm("extras.saidValue",{field,value:String(record[field]??"")});if(c.fieldType==="checkbox")return bm(record[c.field]?"extras.saidChecked":"extras.saidUnchecked",{field:c.header});return bm("extras.saidValue",{field:c.header,value:fieldText(c,record)||bm("extras.saidEmpty")})}export function automationsFor(t,e,side){return(t.automations??[]).filter(a=>{if(!a.enabled||a.runOn==="server"!==(side==="server"))return false;const tr=a.trigger;switch(tr.type){case"recordCreated":return e.type==="created"&&matches(t,a.condition,e.record);case"recordUpdated":return e.type==="updated"&&(!tr.fields?.length||tr.fields.some(f=>e.fields.includes(f)))&&matches(t,a.condition,e.record);case"recordMatches":if(!a.condition)return false;if(e.type==="created")return matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,a.condition,e.record)&&!matches(t,a.condition,e.before);return false;case"recordEntersView":{const f=viewFilterOf(t,tr.view);if(!f)return false;if(e.type==="created")return matches(t,f,e.record)&&matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,f,e.record)&&!matches(t,f,e.before)&&matches(t,a.condition,e.record);return false}case"formSubmitted":return e.type==="form"&&(!tr.view||tr.view===e.view)&&matches(t,a.condition,e.record);case"button":return e.type==="button"&&e.field===tr.field&&matches(t,a.condition,e.record);default:return false}})}export function outbound(a,t,rec,extra={},values){return{automation:a.name,table:t.name,record:rec,fill:template=>fillTokens(t,rec,template,values),fields:()=>{const out={};if(rec)for(const c of tableFields(t).values())out[c.header]=c.fieldType==="checkbox"?String(!!rec[c.field]):fieldText(c,rec);return out},...extra}}export async function runAppAction(a,action,t,rec){const app=appActions.get(action.action);if(!app)throw new Error(bm("extras.noAction",{action:action.action}));const out=await app.run({automation:a,table:t,record:rec,text:name=>fillTokens(t,rec,`{${name}}`),options:action.options??{}});return{action:app.label,detail:typeof out==="string"?out:bm("extras.stepDone")}}export function actionLabel(a){switch(a.type){case"updateRecord":return bm("extras.actionUpdateRecord");case"deleteRecord":return bm("extras.actionDeleteRecord");case"createRecord":return bm("extras.actionCreateRecord");case"notify":return bm("extras.actionNotify");case"highlight":return bm("extras.actionHighlight");case"run":return appActions.get(a.action)?.label??a.action;case"webhook":return bm("extras.actionWebhook");case"email":return bm("extras.actionEmail");case"chat":return bm("extras.actionChat");case"textMessage":return bm("extras.actionText");case"repeat":return bm("extras.actionRepeat");case"if":return bm("extras.actionIf");case"ai":return bm("extras.actionAi");case"script":return bm("extras.actionScript")}}export function triggerText(t,a){const name=id=>t?tableFields(t).get(id)?.header??id:id;const cond=a.condition?describeFieldFilter(a.condition,name):"";const where=cond&&cond!=="every record";const tr=a.trigger;switch(tr.type){case"recordCreated":return where?bm("extras.whenCreatedWhere",{condition:cond}):bm("extras.whenCreated");case"recordUpdated":{if(!tr.fields?.length)return where?bm("extras.whenRecordChangesWhere",{condition:cond}):bm("extras.whenRecordChanges");const fields=tr.fields.map(name).join(bm("extras.fieldsOr"));return where?bm("extras.whenFieldsChangeWhere",{fields,condition:cond}):bm("extras.whenFieldsChange",{fields})}case"recordMatches":return bm("extras.whenMatches",{condition:cond||bm("extras.noConditionYet")});case"recordEntersView":{const view=(t?.views??[]).find(v=>v.id===tr.view)?.name??bm("extras.aView");return where?bm("extras.whenEntersViewWhere",{view,condition:cond}):bm("extras.whenEntersView",{view})}case"formSubmitted":return where?bm("extras.whenFormWhere",{condition:cond}):bm("extras.whenForm");case"button":return bm("extras.whenPressed",{field:name(tr.field)});case"scheduled":return where?bm("extras.onScheduleWhere",{cron:cronWords(tr.cron),condition:cond}):bm("extras.onSchedule",{cron:cronWords(tr.cron)});case"webhookReceived":return bm("extras.whenWebhook")}}
1
+ import{toast}from"@svgrid/grid";import{createScheduler}from"../scheduling.js";import{colId,primaryOf,rowIdOf,syncAllInverses}from"./base-tables.js";import{compileFieldFilter,describeFieldFilter}from"./filter-model.js";import{fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";import{noteChange}from"./activity.svelte.js";import{getCurrentUser,getFieldUsers}from"./sources.svelte.js";import{newRecordId}from"./field-ops.js";import{fieldText,fieldValue,linkNames}from"./base-alerts.js";import{callWebhook,sendChat,sendEmailAction,sendTextAction}from"./automation-outbound.js";import{runScript}from"./automation-script.js";import{bm}from"./messages.svelte.js";import{cronWords}from"./cron-words.js";const appActions=new Map;export function registerAutomationAction(id,action){appActions.set(id,action)}export function listAutomationActions(){return[...appActions].map(([id,a])=>({id,label:a.label}))}const readers=new WeakMap;export function tableFields(t){const hit=readers.get(t.columns);if(hit)return hit;const all=t.columns.map(d=>({...d,id:colId(d)}));const map=new Map;for(const d of t.columns){if(d.field==null)continue;const def=fillFieldColumn(d,all);map.set(colId(d),{id:colId(d),field:String(d.field),header:String(d.header??d.field),fieldType:d.fieldType,def,visible:true})}readers.set(t.columns,map);return map}const byName=(t,name)=>{const lower=name.trim().toLowerCase();for(const c of tableFields(t).values()){if(c.header.trim().toLowerCase()===lower||c.field.toLowerCase()===lower||c.id.toLowerCase()===lower)return c}return void 0};export function fillTokens(t,record,template,values){return template.replace(/\{([^{}\n]+)\}/g,(m,name)=>{const given=values?.get(name.trim().toLowerCase());if(given!==void 0)return given;const c=byName(t,name);return!c?m:record?fieldText(c,record):bm("extras.noRecordValue")})}export function baseText(tables,most=6e4){const SKIP=new Set(["attachment","button","richText","createdBy","lastModifiedBy"]);const parts=tables.slice(0,20).map(t=>{const fields=[...tableFields(t).values()].filter(c=>!SKIP.has(String(c.fieldType??"text")));const lines=[];for(const r of t.data??[]){const cells=[];for(const c of fields){let v=fieldText(c,r);if(!v||c.fieldType==="checkbox"&&v==="false")continue;v=(v.length>300?v.slice(0,297)+"...":v).replace(/\s+/g," ");cells.push(c.field===t.primaryField?v:`${c.header}: ${v}`)}if(cells.length)lines.push("- "+cells.join(" | "))}return{name:t.name,lines}});const sizes=parts.map((p,i)=>({i,size:p.lines.reduce((n,line)=>n+line.length+1,0)})).sort((a,b)=>a.size-b.size);const budget=[];let left=most;sizes.forEach(({i,size},k)=>{budget[i]=Math.min(size,Math.floor(left/Math.max(1,sizes.length-k)));left-=budget[i]});return parts.map((p,i)=>{const kept=[];let size=0;for(const line of p.lines){if(size+line.length+1>budget[i])break;kept.push(line);size+=line.length+1}const left2=p.lines.length-kept.length;return`## ${p.name} (${p.lines.length} records${left2>0?`, the first ${kept.length} shown`:""})
2
+ ${kept.join("\n")}`}).join("\n\n")}export function viewFilterOf(t,viewId){const v=(t.views??[]).find(x=>x.id===viewId);const f=v?.state?.advancedFilter;return f&&typeof f==="object"&&f.kind==="fieldFilter"?f:null}export function matches(t,condition,record){if(!condition)return true;const fields=tableFields(t);const test=compileFieldFilter(condition,(row,id)=>{const c=fields.get(id);return c?fieldValue(c,row):row[id]},linkNames);return test?test(record):true}function stampModifiedTime(t,row,changedIds,at){for(const d of t.columns){if(d.fieldType!=="lastModifiedTime"||d.field==null||changedIds.includes(colId(d)))continue;const p=fieldPropsOf(d);if(p.watch==="specific"&&!changedIds.some(id=>(p.watchFields??[]).includes(id)))continue;row[String(d.field)]=at.toISOString()}}const DAY=864e5;const isoDay=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;export function fieldValueFrom(t,def,spec,ctx){const type=def.fieldType;if(typeof spec!=="string")return spec;const raw=spec.includes("{record}")?spec:fillTokens(ctx.from,ctx.record,spec,ctx.values);const text=raw.trim();if(text==="")return type==="checkbox"?false:type==="multiSelect"||type==="link"||type==="attachment"?[]:null;switch(type){case"checkbox":return/^(true|yes|1|checked|on)$/i.test(text);case"number":case"rating":case"duration":case"currency":case"percent":{const n=Number(text.replace(/[^0-9.+-eE]/g,""));return Number.isFinite(n)?text.endsWith("%")?n/100:n:null}case"multiSelect":return text.split(/\s*,\s*/).filter(Boolean);case"user":{const found=getFieldUsers().find(u=>u.id===text||u.name.toLocaleLowerCase()===text.toLocaleLowerCase());return found?found.id:text}case"date":{const m=/^(today|now)\s*(?:([+-])\s*(\d+))?$/i.exec(text);if(!m)return text;const shift=m[2]?(m[2]==="-"?-1:1)*Number(m[3])*DAY:0;const at=new Date(ctx.now.getTime()+shift);return m[1].toLowerCase()==="now"||def.fieldProps?.time?at.toISOString():isoDay(at)}case"link":{const target=ctx.tables.find(x=>x.id===def.fieldProps?.table);const out=[];for(const part of text.split(/\s*,\s*/)){if(part==="{record}"){if(ctx.record&&ctx.from.id===target?.id)out.push(rowIdOf(ctx.from,ctx.record));continue}const name=fillTokens(ctx.from,ctx.record,part,ctx.values).toLocaleLowerCase();const named=ctx.named?.get(name);if(named){out.push(named);continue}const hit=target?.data.find(r=>String(r?.[primaryOf(target)]??"").toLocaleLowerCase()===name);if(hit&&target)out.push(rowIdOf(target,hit))}return def.fieldProps?.multiple===false?out.slice(0,1):out}default:return raw}}export const MAX_DEPTH=4;export function pressedValues(){const me=getCurrentUser();const out=new Map;out.set("pressed.name",me?.name??"");out.set("pressed.email",me?.email??"");out.set("pressed.id",me?.id??"");return out}export const REPEAT_MOST=1e3;const SCRIPT_ROWS=5e3;const READ_AS_TEXT=new Set(["checkbox","number","rating","duration","currency","percent","multiSelect","user","date","link"]);export function scriptRecord(t,r){const values={};const texts={};let name="";for(const c of tableFields(t).values()){let v=r[c.field]??null;try{v=JSON.parse(JSON.stringify(v))}catch{v=null}values[c.header]=v;texts[c.header]=fieldText(c,r);if(c.field===primaryOf(t))name=texts[c.header]}return{id:rowIdOf(t,r),name,values,texts}}export function scriptInput(t,rec,values){const out={};if(rec){out.recordId=rowIdOf(t,rec);for(const c of tableFields(t).values())out[c.header]=fieldText(c,rec)}for(const[k,v]of values)out[k]=v;return out}export function webhookValues(body){const out=new Map;const walk=(v,path,depth)=>{if(out.size>=200)return;if(v!==null&&typeof v==="object"&&depth<5){for(const[k,x]of Object.entries(v).slice(0,100))walk(x,`${path}.${k.toLowerCase()}`,depth+1);if(path!=="webhook")out.set(path,JSON.stringify(v));return}out.set(path,v==null?"":typeof v==="string"?v:JSON.stringify(v))};walk(body,"webhook",0);out.set("webhook",typeof body==="string"?body:JSON.stringify(body??null));return out}export function triggerValues(t,rec,values){const out=new Map(values);if(rec)for(const c of tableFields(t).values())out.set(`trigger.${c.header.trim().toLowerCase()}`,fieldText(c,rec));return out}export function allActions(list){const out=[];for(const x of list){out.push(x);if(x.type==="if")out.push(...allActions(x.then??[]),...allActions(x.else??[]));if(x.type==="repeat")out.push(...allActions(x.actions??[]))}return out}const SHOW_BACKLOG=20;const CARRY_MOST=5e3;const FREE_EVERY=4096;let runSeq=0;export function createAutomationRunner(options){const now=options.now??(()=>new Date);let runs=$state.raw([]);let scheduler=null;let chain=Promise.resolve();let waiting=[];let head=0;let draining=false;let burst={done:0,total:0,at:0,told:0};let backlog=$state.raw(null);let measured=null;const record=run=>runs=[run,...runs].slice(0,100);const automationsOf=t=>(t.automations??[]).filter(a=>a.enabled&&a.runOn!=="server");const tableOf=id=>options.getTables()?.find(t=>t.id===id);const carried=new Map;const carriedFor=new Map;const carry=(key,row)=>{carried.set(key,row);carriedFor.set(key,(carriedFor.get(key)??0)+1)};const letGo=key=>{const left=(carriedFor.get(key)??1)-1;if(left>0)return void carriedFor.set(key,left);carriedFor.delete(key);carried.delete(key)};const recordNow=async(t,id)=>{const own=tableOf(t.id)??t;if(!own.source?.server)return own.data.find(r=>r&&rowIdOf(own,r)===id)??null;return carried.get(`${t.id}:${id}`)??await options.server?.read(t.id,id)??null};async function namesIn(target,values,ctx){const named=new Map;const fields=tableFields(target);for(const[id,spec]of Object.entries(values)){const def=fields.get(id)?.def;if(def?.fieldType!=="link"||typeof spec!=="string")continue;const to=(options.getTables()??[]).find(x=>x.id===def.fieldProps?.table);if(!to?.source?.server)continue;for(const part of spec.split(/\s*,\s*/)){const name=fillTokens(ctx.from,ctx.record,part);const hit=part==="{record}"?null:await options.server?.byName(to.id,name);if(hit)named.set(name.toLocaleLowerCase(),hit)}}return named}const setOff=(t,e)=>automationsFor(t,e,"browser");function handle(e){const t=tableOf(e.table);if(!t)return chain;const list=setOff(t,e);const depth="depth"in e?e.depth??0:0;const recordId=rowIdOf(t,e.record);for(const a of list){if(t.source?.server&&waiting.length-head<CARRY_MOST)carry(`${t.id}:${recordId}`,e.record);if(!draining&&head===waiting.length)burst={done:0,total:0,at:Date.now(),told:0};burst.total+=1;waiting.push({a,tableId:t.id,recordId,depth})}return list.length?drain():chain}function tell(){const clock=Date.now();if(burst.total<SHOW_BACKLOG||clock-burst.told<250)return;burst.told=clock;const seconds=(clock-burst.at)/1e3;if(burst.done>=SHOW_BACKLOG&&seconds>0)measured=burst.done/seconds;backlog={done:burst.done,total:burst.total,perSecond:burst.done>=SHOW_BACKLOG?measured:null}}function endBurst(left){const shown=backlog!=null||burst.total>=SHOW_BACKLOG;backlog=null;if(shown)options.onBurstEnd?.({done:burst.total-left,total:burst.total,left})}function drain(){if(draining)return chain;draining=true;tell();chain=chain.then(async()=>{let breath=Date.now();for(;;){if(head>=waiting.length){if(burst.total<SHOW_BACKLOG)break;await new Promise(r=>setTimeout(r,200));if(head>=waiting.length)break;continue}if(Date.now()-breath>40){await new Promise(r=>setTimeout(r));breath=Date.now();continue}const w=waiting[head];head+=1;if(head>=FREE_EVERY){waiting=waiting.slice(head);head=0}try{await runOne(w.a,w.tableId,w.recordId,w.depth)}catch(e){record({id:++runSeq,automationId:w.a.id,name:w.a.name,table:tableOf(w.tableId)?.name??w.tableId,record:w.recordId,at:now().getTime(),status:"error",steps:[{action:w.a.name,detail:"",error:e instanceof Error?e.message:String(e)}]})}if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`);burst.done+=1;tell()}waiting=[];head=0;draining=false;endBurst(0)});return chain}function stopRuns(){const left=waiting.length-head;if(!left)return 0;for(let i=head;i<waiting.length;i++){const w=waiting[i];if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`)}waiting=[];head=0;endBurst(left);burst={done:0,total:0,at:Date.now(),told:0};return left}async function runOne(a,tableId,recordId,depth){const t=tableOf(tableId);if(!t)return;const rec=recordId==null?null:await recordNow(t,recordId);const run={id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:rec?String(rec[primaryOf(t)]??recordId):null,at:now().getTime(),status:"ok",steps:[]};if(depth>=MAX_DEPTH){run.status="stopped";run.steps.push({action:bm("extras.stepStopped"),detail:bm("extras.stepLoop",{max:MAX_DEPTH})});record(run);return}await runList(a,a.actions,tableId,recordId,depth,run,a.trigger.type==="button"?pressedValues():new Map);record(run)}async function runList(a,list,tableId,recordId,depth,run,values){for(const action of list){try{if(action.type==="if"){const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const yes=!!t&&(rec?matches(t,action.condition,rec):!action.condition?.conditions?.length);run.steps.push({action:bm("extras.stepIf"),detail:bm(yes?"extras.stepIfThen":"extras.stepIfElse")});if(!await runList(a,(yes?action.then:action.else)??[],tableId,recordId,depth,run,values))return false;continue}if(action.type==="repeat"){if(!await runRepeat(a,action,tableId,recordId,depth,run,values))return false;continue}const step=await act(a,action,tableId,recordId,depth,values);if(step)run.steps.push(step)}catch(e){run.status="error";run.steps.push({action:actionLabel(action),detail:"",error:e instanceof Error?e.message:String(e)});return false}}return true}async function runRepeat(a,action,tableId,recordId,depth,run,values){const target=tableOf(action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const most=Math.max(1,Math.min(REPEAT_MOST,action.limit??100));const ids=[];if(target.source?.server){await options.server?.each(target.id,action.condition,async r=>{if(ids.length>=most)return;const id=rowIdOf(target,r);carry(`${target.id}:${id}`,r);ids.push(id)})}else{for(const r of target.data){if(ids.length>=most)break;if(r&&matches(target,action.condition,r))ids.push(rowIdOf(target,r))}}run.steps.push({action:bm("extras.stepFound"),detail:bm("extras.foundIn",{count:ids.length,table:target.name})});const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const inner=t?triggerValues(t,rec,values):new Map(values);inner.set("found",String(ids.length));try{for(const id of ids)if(!await runList(a,action.actions??[],target.id,id,depth,run,inner))return false}finally{if(target.source?.server)for(const id of ids)letGo(`${target.id}:${id}`)}return true}async function writeRecord(a,t,recordId,rec,patch,depth,at){const fields=tableFields(t);const before={...rec};const after={...rec,...patch};const changed=Object.keys(patch).filter(f=>JSON.stringify(before[f]??null)!==JSON.stringify(after[f]??null));if(!changed.length)return{changed,after};const changedIds=changed.map(f=>[...fields.values()].find(c=>c.field===f)?.id??f);stampModifiedTime(t,after,changedIds,at);if(t.source?.server){carried.set(`${t.id}:${recordId}`,after);await options.server?.update(t.id,recordId,Object.fromEntries(Object.keys(after).filter(k=>after[k]!==before[k]).map(k=>[k,after[k]])),before)}else{const tables=options.getTables()??[];let next=tables.map(x=>x.id===t.id?{...x,data:x.data.map(r=>r&&rowIdOf(t,r)===recordId?after:r)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}changed.forEach((f,i)=>noteChange({base:options.scope,tableId:t.id},recordId,changedIds[i],after[f],a.name));void handle({type:"updated",table:t.id,record:after,before,fields:changedIds,depth:depth+1});return{changed,after}}function addRecord(target,row,depth){const tables=options.getTables()??[];let next=tables.map(x=>x.id===target.id?{...x,data:[...x.data,row]}:x);next=syncAllInverses(next,target.id);options.apply(next,depth+1,target.id);void handle({type:"created",table:target.id,record:row,depth:depth+1})}function pageBridge(a,depth){const named=name=>{const t=(options.getTables()??[]).find(x=>x.name.trim().toLowerCase()===name.trim().toLowerCase());if(!t)throw new Error(bm("extras.noTable",{table:name}));return t};const rowsOf=async t=>{if(!t.source?.server)return t.data.filter(Boolean);const out=[];await options.server?.each(t.id,void 0,async r=>{if(out.length<SCRIPT_ROWS)out.push(r)});return out};const patchOf=(t,given)=>{const patch={};for(const[name,v]of Object.entries(given??{})){const c=byName(t,name);if(!c)throw new Error(bm("extras.noField",{field:name}));const type=String(c.fieldType??"");const text=typeof v==="string"?v:v&&typeof v==="object"&&!Array.isArray(v)&&"name"in v?String(v.name):null;patch[c.field]=text!==null&&READ_AS_TEXT.has(type)?fieldValueFrom(t,c.def,text.replace(/[{}]/g,""),{tables:options.getTables()??[],from:t,record:null,now:now()}):v}return patch};return{tables:()=>(options.getTables()??[]).map(t=>t.name),select:async name=>{const t=named(name);return(await rowsOf(t)).map(r=>scriptRecord(t,r))},update:async(name,id,given)=>{const t=named(name);const rec=await recordNow(t,id);if(!rec)throw new Error(bm("extras.noRecordId",{id}));await writeRecord(a,t,id,rec,patchOf(t,given),depth,now())},create:async(name,given)=>{const t=named(name);const row={id:newRecordId(),...patchOf(t,given)};addRecord(t,row,depth);return String(row.id)},remove:async(name,id)=>{const t=named(name);const tables=options.getTables()??[];options.apply(tables.map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==id)}:x),depth+1,t.id)}}}async function act(a,action,tableId,recordId,depth,values){const tables=options.getTables()??[];const t=tables.find(x=>x.id===tableId);const rec=recordId==null?null:await recordNow(t,recordId);const ctx={tables,from:t,record:rec,now:now(),values};switch(action.type){case"notify":{const message=fillTokens(t,rec,action.message,values);const sev=action.severity??"info";toast[sev](message);return{action:bm("extras.stepNotice"),detail:message}}case"highlight":return null;case"updateRecord":{if(!rec||recordId==null)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.noRecordToUpdate")};const fields=tableFields(t);const patch={};ctx.named=await namesIn(t,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)patch[c.field]=fieldValueFrom(t,c.def,spec,ctx)}const{changed,after}=await writeRecord(a,t,recordId,rec,patch,depth,ctx.now);if(!changed.length)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.alreadySet")};return{action:bm("extras.actionUpdateRecord"),detail:changed.map(f=>said([...fields.values()].find(c=>c.field===f),f,after)).join(", ")}}case"deleteRecord":{if(!rec||recordId==null)return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.noRecordToDelete")};const name=String(rec[primaryOf(t)]??"")||bm("extras.aRecord");if(t.source?.server){if(!options.server?.remove)throw new Error(bm("extras.cannotDeleteHere"));await options.server.remove(t.id,recordId,rec)}else{let next=(options.getTables()??[]).map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==recordId)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.deletedRecord",{name})}}case"createRecord":{const target=tables.find(x=>x.id===action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const fields=tableFields(target);const row={id:newRecordId()};ctx.named=await namesIn(target,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)row[c.field]=fieldValueFrom(target,c.def,spec,ctx)}if(action.linkField&&rec){const c=fields.get(action.linkField);if(c)row[c.field]=[rowIdOf(t,rec)]}addRecord(target,row,depth);const name=String(row[primaryOf(target)]??"")||bm("extras.aRecord");return{action:bm("extras.actionCreateRecord"),detail:bm("extras.createdIn",{name,table:target.name})}}case"run":return runAppAction(a,action,t,rec);case"webhook":return{action:bm("extras.stepWebhook"),detail:await callWebhook(action,outbound(a,t,rec,{},values))};case"email":return{action:bm("extras.stepEmail"),detail:await sendEmailAction(action,outbound(a,t,rec,{},values),void 0)};case"chat":return{action:bm("extras.stepChat"),detail:await sendChat(action,outbound(a,t,rec,{},values))};case"textMessage":return{action:bm("extras.stepText"),detail:await sendTextAction(action,outbound(a,t,rec,{},values),void 0)};case"ai":{if(!options.ai)throw new Error(bm("extras.noAi"));let prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));if(action.base)prompt+=`
3
+
4
+ Today is ${ctx.now.toDateString()}. The base now:
5
+
6
+ ${baseText(options.getTables()??[])}`;const answer=String(await options.ai(prompt)).trim();values.set("ai",answer);const c=action.field?tableFields(t).get(action.field):void 0;if(c&&rec&&recordId!=null)await writeRecord(a,t,recordId,rec,{[c.field]:answer},depth,ctx.now);return{action:bm("extras.stepAi"),detail:answer.length>160?answer.slice(0,157)+"...":answer}}case"script":{const result=await runScript(action.code,{input:scriptInput(t,rec,values),bridge:pageBridge(a,depth)});for(const[k,v]of Object.entries(result.output))values.set(`script.${k.toLowerCase()}`,typeof v==="string"?v:JSON.stringify(v));if(!result.ok)throw new Error(result.error??bm("extras.scriptFailed"));return{action:bm("extras.stepScript"),detail:result.logs.slice(-3).join(" | ")||bm("extras.stepDone")}}default:return null}}function schedule(){scheduler?.stop();scheduler=null;const list=options.getTables()??[];const due=[];for(const t of list)for(const a of automationsOf(t))if(a.trigger.type==="scheduled")due.push({id:`${t.id}:${a.id}`,cron:a.trigger.cron,table:t.id,automation:a});if(!due.length)return;scheduler=createScheduler({schedules:due,now,onFire:s=>void runScheduled(s.id)});scheduler.start()}function runScheduled(key){const[tableId,automationId]=key.split(":");const t=tableOf(tableId);const a=t?.automations?.find(x=>x.id===automationId);if(!t||!a)return chain;if(!a.condition)chain=chain.then(()=>runOne(a,t.id,null,0));else if(t.source?.server){chain=chain.then(()=>options.server?.each(t.id,a.condition,async r=>{const key2=`${t.id}:${rowIdOf(t,r)}`;carry(key2,r);await runOne(a,t.id,rowIdOf(t,r),0);letGo(key2)}))}else for(const r of t.data)if(r&&matches(t,a.condition,r))chain=chain.then(()=>runOne(a,t.id,rowIdOf(t,r),0));return chain}return{handle,stopRuns,get backlog(){return backlog},get waiting(){return waiting.length-head},get perSecond(){return measured},schedule,runScheduled,firstRecords:async(tableId,count)=>await options.server?.first(tableId,count)??[],runNow:(a,tableId,recordId)=>chain=chain.then(async()=>{const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;if(t&&rec&&a.condition&&!matches(t,a.condition,rec)){record({id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:String(rec[primaryOf(t)]??recordId),at:now().getTime(),status:"stopped",steps:[{action:bm("extras.stepNotRun"),detail:bm("extras.stepNoMatch")}]});return}return runOne(a,tableId,recordId,0)}),get runs(){return runs},clearRuns:()=>runs=[],settled:()=>chain,stop:()=>scheduler?.stop()}}function said(c,field,record){if(!c)return bm("extras.saidValue",{field,value:String(record[field]??"")});if(c.fieldType==="checkbox")return bm(record[c.field]?"extras.saidChecked":"extras.saidUnchecked",{field:c.header});return bm("extras.saidValue",{field:c.header,value:fieldText(c,record)||bm("extras.saidEmpty")})}export function automationsFor(t,e,side){return(t.automations??[]).filter(a=>{if(!a.enabled||a.runOn==="server"!==(side==="server"))return false;const tr=a.trigger;switch(tr.type){case"recordCreated":return e.type==="created"&&matches(t,a.condition,e.record);case"recordUpdated":return e.type==="updated"&&(!tr.fields?.length||tr.fields.some(f=>e.fields.includes(f)))&&(!tr.from||matches(t,tr.from,e.before))&&matches(t,a.condition,e.record);case"recordMatches":if(!a.condition)return false;if(e.type==="created")return matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,a.condition,e.record)&&!matches(t,a.condition,e.before);return false;case"recordEntersView":{const f=viewFilterOf(t,tr.view);if(!f)return false;if(e.type==="created")return matches(t,f,e.record)&&matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,f,e.record)&&!matches(t,f,e.before)&&matches(t,a.condition,e.record);return false}case"formSubmitted":return e.type==="form"&&(!tr.view||tr.view===e.view)&&matches(t,a.condition,e.record);case"button":return e.type==="button"&&e.field===tr.field&&matches(t,a.condition,e.record);default:return false}})}export function outbound(a,t,rec,extra={},values){return{automation:a.name,table:t.name,record:rec,fill:template=>fillTokens(t,rec,template,values),fields:()=>{const out={};if(rec)for(const c of tableFields(t).values())out[c.header]=c.fieldType==="checkbox"?String(!!rec[c.field]):fieldText(c,rec);return out},...extra}}export async function runAppAction(a,action,t,rec){const app=appActions.get(action.action);if(!app)throw new Error(bm("extras.noAction",{action:action.action}));const out=await app.run({automation:a,table:t,record:rec,text:name=>fillTokens(t,rec,`{${name}}`),options:action.options??{}});return{action:app.label,detail:typeof out==="string"?out:bm("extras.stepDone")}}export function actionLabel(a){switch(a.type){case"updateRecord":return bm("extras.actionUpdateRecord");case"deleteRecord":return bm("extras.actionDeleteRecord");case"createRecord":return bm("extras.actionCreateRecord");case"notify":return bm("extras.actionNotify");case"highlight":return bm("extras.actionHighlight");case"run":return appActions.get(a.action)?.label??a.action;case"webhook":return bm("extras.actionWebhook");case"email":return bm("extras.actionEmail");case"chat":return bm("extras.actionChat");case"textMessage":return bm("extras.actionText");case"repeat":return bm("extras.actionRepeat");case"if":return bm("extras.actionIf");case"ai":return bm("extras.actionAi");case"script":return bm("extras.actionScript")}}export function triggerText(t,a){const name=id=>t?tableFields(t).get(id)?.header??id:id;const cond=a.condition?describeFieldFilter(a.condition,name):"";const where=cond&&cond!=="every record";const tr=a.trigger;switch(tr.type){case"recordCreated":return where?bm("extras.whenCreatedWhere",{condition:cond}):bm("extras.whenCreated");case"recordUpdated":{const from=tr.from?.conditions.length?describeFieldFilter(tr.from,name):"";if(from)return where?bm("extras.whenChangesFromTo",{from,condition:cond}):bm("extras.whenChangesFrom",{from});if(!tr.fields?.length)return where?bm("extras.whenRecordChangesWhere",{condition:cond}):bm("extras.whenRecordChanges");const fields=tr.fields.map(name).join(bm("extras.fieldsOr"));return where?bm("extras.whenFieldsChangeWhere",{fields,condition:cond}):bm("extras.whenFieldsChange",{fields})}case"recordMatches":return bm("extras.whenMatches",{condition:cond||bm("extras.noConditionYet")});case"recordEntersView":{const view=(t?.views??[]).find(v=>v.id===tr.view)?.name??bm("extras.aView");return where?bm("extras.whenEntersViewWhere",{view,condition:cond}):bm("extras.whenEntersView",{view})}case"formSubmitted":return where?bm("extras.whenFormWhere",{condition:cond}):bm("extras.whenForm");case"button":return bm("extras.whenPressed",{field:name(tr.field)});case"scheduled":return where?bm("extras.onScheduleWhere",{cron:cronWords(tr.cron),condition:cond}):bm("extras.onSchedule",{cron:cronWords(tr.cron)});case"webhookReceived":return bm("extras.whenWebhook")}}
@@ -1 +1 @@
1
- import{fillFieldColumn as O}from"./registry.svelte.js";import Ae from"./RatingCell.svelte";import N from"./LinkCell.svelte";import Ve from"./AttachmentCell.svelte";import Fe from"./CheckboxCell.svelte";import re from"./PercentCell.svelte";import B from"./UserCell.svelte";import Ie from"./ButtonCell.svelte";import Le from"./BarcodeCell.svelte";import Oe from"./LinkedRecordsCell.svelte";import Ne from"./RichTextCell.svelte";import Be from"./RichHtmlCell.svelte";import{richPlain as A}from"./rich-html.js";import{toRichHtml as Re}from"./rich-html-write.js";import le from"./SelectCell.svelte";import Ee from"./ChecklistCell.svelte";import He from"./ColorCell.svelte";import{attachmentsText as Ue,parseAttachments as _e}from"./attachments.js";import{dateEditTokens as ze,dateFromParts as R,exactNumber as We,formatCurrency as ie,formatDate as E,formatDuration as ne,formatNumber as H,formatPercent as oe,numberFieldShape as ae,numberFromText as Ge,numberKind as je,parseDateText as $e,parseDuration as V,toNumber as U}from"./format.js";import{BRIGHT as se,CHECKBOX_ICONS as xe,RATING_ICONS as Ke}from"./palette.js";import{COMPUTED_TYPES as Ye,ROLLUPS as _,fieldNameMap as Xe}from"./rollups.js";import{sparklineValues as z,voteCount as ue,voteIds as Ze}from"./vote.js";import qe from"./VoteCell.svelte";import Je from"./TimerCell.svelte";import{timerSeconds as F,timerTotal as Qe}from"./timer.js";import et from"./SparklineCell.svelte";import{compileFormula as tt,isoDate as rt,selfReferenceError as lt}from"./formula.js";import{findFieldUser as ce,getCurrentUser as de,getFieldUsers as W,getLinkedTable as T,idOf as it,linkedRows as G,listLinkedTables as nt,liveLink as ot,recordsNaming as at,resolveLinkId as st,resolveLinkIds as ut}from"./sources.svelte.js";import{splitNames as j}from"./name-list.js";import{linkedFields as ct}from"./linked-fields.js";import{AI_FIELD_TYPE as dt}from"./ai-field.svelte.js";import{CHECKLIST_GROUPS as pe,checklistGroup as pt,checklistSortValue as ft,checklistText as mt,parseChecklist as gt,toChecklist as ht}from"./checklist.js";import{colorSortValue as bt,parseColor as $}from"./color-value.js";import{formatTimeOfDay as yt,parseTimeOfDay as fe,timeSeconds as kt}from"./time-of-day.js";import{bm as l}from"./messages.svelte.js";import{BUTTON_ACTIONS as Tt,buttonAction as b,fillButtonTokens as wt,isLinkTemplate as vt}from"./button.js";import{recordActionsFor as me}from"./record-actions.js";const St=new Set(["user","createdBy","lastModifiedBy"]);function Mt(e){const t=String(e.field??e.id),r=o=>o.length===1?o[0]:o;if(St.has(String(e.fieldType)))return o=>{const n=o?.[t];return n==null||n===""?n:r((Array.isArray(n)?n:[n]).map(a=>ce(a)?.name??a))};if(e.fieldType!=="link")return null;const i=e.fieldProps?.table;return o=>{const n=o?.[t],a=T(i);if(!a||n==null||n==="")return n;const p=x(a,a.primaryField),d=new Map(G(a,n).map(f=>[it(a,f),p(f)]));return r((Array.isArray(n)?n:[n]).map(f=>d.get(String(f))??f))}}const ge=new WeakMap;let M=0;function x(e,t){const r=n=>n?.[t];if(!e?.fields?.length)return r;let i=ge.get(e.fields);if(i||ge.set(e.fields,i=new Map),!i.has(t)){const n=ct(e).find(p=>p.def.field===t),a=n?.def.fieldType==="timer"?p=>F(p?.[t]):null;i.set(t,a??n?.def.fieldFn??null)}const o=i.get(t);return o?n=>{if(M>3)return r(n);M+=1;try{return o(n)}finally{M-=1}}:r}const s={text:"M4 6h16M4 12h10M4 18h7",longText:"M4 6h16M4 10h16M4 14h16M4 18h10",richText:"M6 4h7a4 4 0 0 1 0 8H6zM6 12h8a4 4 0 0 1 0 8H6zM6 4v16",vote:"M12 19V5M5 12l7-7 7 7",sparkline:"M3 17l5-6 4 4 8-9",number:"M9 4 7 20M17 4l-2 16M4 9h16M3 15h16",currency:"M12 3v18M16 7.5C16 5.6 14.2 4.5 12 4.5S8 5.6 8 7.5s1.8 2.7 4 3.5 4 1.6 4 3.5-1.8 3-4 3-4-1.1-4-3",percent:"M19 5 5 19M7 7h.01M17 17h.01",date:"M4 6h16v14H4zM4 10h16M8 3v4M16 3v4",duration:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4l3 2",timer:"M12 7a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM12 10v4l2.5 1.5M9.5 2.5h5M12 2.5V5",checkbox:"M4 4h16v16H4zM8 12l3 3 5-6",singleSelect:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM8 11l4 4 4-4",multiSelect:"M3 7h11M3 12h11M3 17h11M17 6l2 2 3-3M17 16l2 2 3-3",rating:"M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3 6.5 20.2l1-6.2L3 9.6l6.2-.9z",url:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",phone:"M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2",attachment:"M20 11.5 12.3 19a5 5 0 0 1-7.1-7.1l7.8-7.8a3.3 3.3 0 0 1 4.7 4.7L9.9 16.6a1.7 1.7 0 0 1-2.4-2.4l7.1-7",user:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0",createdTime:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4h4",modifiedTime:"M4 12a8 8 0 1 0 2.3-5.7M4 4v4h4M12 8v4l3 2",createdBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M19 15v6M16 18h6",modifiedBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M16 21l5-5-2-2-5 5v2z",autoNumber:"M5 7h3v10M11 9a2 2 0 1 1 4 0c0 2-4 3-4 6h4M18 7h2v10",barcode:"M4 5v14M7 5v14M10 5v14M13 5v14M15 5v14M18 5v14M20 5v14",button:"M4 7h16v10H4zM9 12h6",formula:"M7 20c2 0 2.5-2 3-5l2-10c.5-2 1.5-2 3-2M8 9h7",link:"M9 7H6a5 5 0 0 0 0 10h3M15 7h3a5 5 0 0 1 0 10h-3M8 12h8",lookup:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4M8 11h6",rollup:"M6 4h12L12 12l6 8H6",count:"M5 5h14v14H5zM9 9v6M12 9v6M15 9v6",checklist:"M3.5 6l1.5 1.5L7.5 5M3.5 12l1.5 1.5 2.5-2.5M3.5 18l1.5 1.5 2.5-2.5M11 6h9M11 12h9M11 18h9",color:"M12 3a9 9 0 1 0 0 18c1 0 1.6-.7 1.6-1.6 0-1-.8-1.4-.8-2.3 0-1 .8-1.7 1.8-1.7H17a4 4 0 0 0 4-4C21 6.6 17 3 12 3zM7.5 12h.01M9.5 7.5h.01M14.5 7.5h.01",timeOfDay:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l-3 2M12 3v2M21 12h-2M12 21v-2M3 12h2"},u=(e,t)=>({value:e,get label(){return l(t)}}),Ct={link:"fields.buttonActionLink",automation:"fields.buttonActionAutomation",update:"fields.buttonActionUpdate",template:"fields.buttonActionTemplate",recordAction:"fields.buttonActionRecordAction",copy:"fields.buttonActionCopy",duplicate:"fields.buttonActionDuplicate",delete:"fields.buttonActionDelete",open:"fields.buttonActionOpen"};function Pt(e){const t=!!e.ctrl?.props?.baseButton,r=b(e.props),i=o=>o===r||o==="link"||o==="copy"?!0:t?o==="template"?(e.ctrl?.props?.baseRecordTemplates?.()??[]).length>0:o==="recordAction"?me(e.ctrl?.props?.baseTableId).length>0:!0:!1;return Tt.filter(i).map(o=>u(o,Ct[o]))}const he=e=>e?{visible:e}:{},Dt={key:"separators",get label(){return l("fields.propSeparators")},kind:"choice",choices:[u("local","fields.choiceLocal"),{value:"comma-period",label:"1,000,000.00"},{value:"period-comma",label:"1.000.000,00"},{value:"space-comma",label:"1 000 000,00"},{value:"space-period",label:"1 000 000.00"}]},At={key:"showThousands",get label(){return l("fields.propShowThousands")},kind:"checkbox"},Vt=e=>({key:"abbreviation",get label(){return l("fields.propAbbreviation")},kind:"choice",choices:[u("none","fields.choiceNone"),u("thousand","fields.choiceThousand"),u("million","fields.choiceMillion"),u("billion","fields.choiceBillion")],...he(e)}),Ft={key:"allowNegative",get label(){return l("fields.propAllowNegative")},kind:"checkbox"},w={key:"default",get label(){return l("fields.propDefault")},kind:"default",get hint(){return l("fields.propDefaultHint")}},K=(e,t)=>Array.from({length:t-e+1},(r,i)=>{const o=e+i;return{value:String(o),label:o===0?"1":`1.${"0".repeat(o)}`}}),Y=(e,t)=>({key:"precision",get label(){return l("fields.propPrecision")},kind:"choice",choices:e,visible:t}),It=[u("local","fields.choiceLocal"),u("friendly","fields.choiceFriendly"),u("us","fields.choiceUs"),u("european","fields.choiceEuropean"),u("iso","fields.choiceIso")],I=e=>({key:"dateFormat",get label(){return l("fields.propDateFormat")},kind:"choice",choices:It,...he(e)}),be=[u("12hour","fields.choice12Hour"),u("24hour","fields.choice24Hour")],X=[{key:"time",get label(){return l("fields.propIncludeTime")},kind:"checkbox"},{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:be,visible:e=>!!e.time},{key:"gmt",get label(){return l("fields.propGmt")},kind:"checkbox",visible:e=>!!e.time},{key:"showTimeZone",get label(){return l("fields.propShowTimeZone")},kind:"checkbox",visible:e=>!!e.time}],Lt=e=>e.columns.filter(t=>t.fieldType==="link").map(t=>({value:String(t.id??t.field),label:String(t.header??t.field)})),Z={key:"linkField",get label(){return l("fields.propLinkField")},kind:"choice",choices:Lt,get hint(){return l("fields.propLinkFieldHint")}},Ot=e=>{const t=e.columns.find(o=>String(o.id??o.field)===e.props.linkField),r=T(t?.fieldProps?.table);return r?(r.fields??[{field:r.primaryField,header:r.primaryField}]).map(o=>({value:o.field,label:o.header})):[]},ye={key:"field",get label(){return l("fields.propLinkedField")},kind:"choice",choices:Ot,visible:e=>!!e.linkField},C={key:"color",get label(){return l("fields.propColor")},kind:"color",palette:se},ke={key:"options",get label(){return l("fields.propOptions")},kind:"options"},Te=(e,t=0)=>{const r=Number(e.precision);return Number.isInteger(r)&&r>=0&&r<=8?r:t},Nt=e=>({precision:e.format==="integer"?0:Te(e,e.format==="decimal"?1:0),separators:e.separators,showThousands:e.showThousands!==!1,abbreviation:e.abbreviation}),Bt=(e,t)=>r=>{const i=typeof r.rawInput=="string"?r.rawInput:r.newValue;if(typeof i=="number"||i==null)return i;if(String(i).trim()==="")return null;const o=Ge(String(i),e,t);return o??r.oldValue},Rt=(e,t)=>t.allowNegative===!1&&!e.validate?{rejectInvalid:!0,validate:r=>Number(r.value)<0?l("fields.negativeNotAllowed"):null}:{},Et=(e,t)=>{const r={precision:ae(e,t).places,separators:t.separators,showThousands:t.showThousands!==!1,abbreviation:e==="percent"?void 0:t.abbreviation};return i=>{const o=We(i.value);return o==null?"":e==="currency"?ie(o,{...r,symbol:t.symbol,symbolPosition:t.symbolPosition}):e==="percent"?oe(o,{...r,points:t.points}):H(o,r)}},q=(e,t,r)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",align:e.align??(r==="percent"&&t.showBar?"left":"right"),...Rt(e,t),valueParser:e.valueParser??Bt(r,t),formatter:e.formatter??Et(r,t),sortValue:e.sortValue??U}),P=e=>Array.isArray(e.options)?e.options.map(t=>({value:t.value,label:t.label??String(t.value),...t.color?{color:t.color}:{}})):[],we=(e,t)=>{const r=new Map;for(const n of P(e))r.set(String(n.value).toLowerCase(),n.value),r.set(String(n.label).toLowerCase(),n.value);const i=n=>r.get(n.toLowerCase()),o=r.size===0;return n=>{if(typeof n.rawInput!="string")return n.newValue;const a=t?j(n.rawInput):n.rawInput.split(/\n/).map(d=>d.trim()).filter(Boolean);if(o)return t?[...new Set(a)]:a[0]??null;const p=a.map(i).filter(d=>d!==void 0);return a.length&&!p.length?n.oldValue:t?[...new Set(p)]:a.length?i(a[0])===void 0?n.oldValue:i(a[0]):null}},ve=e=>{const t=new Map(P(e).map(r=>[String(r.value),r.label]));return r=>(Array.isArray(r.value)?r.value:r.value==null||r.value===""?[]:[r.value]).map(i=>t.get(String(i))??String(i)).join(", ")},Ht=e=>{const t=new Map(P(e).map((r,i)=>[String(r.value),i]));return r=>r==null||r===""?null:t.get(String(r))??t.size},Se=Xe,y=e=>({editable:e.editable??!1}),J=e=>t=>E(t.value,e),D=e=>e.oldValue!=null&&typeof e.oldValue!="string"&&String(e.oldValue)===e.newValue?e.oldValue:e.newValue,Ut=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;if(r==null||typeof r=="string"&&r.trim()==="")return null;if(r instanceof Date)return e.time?r.toISOString():R({y:r.getFullYear(),mo:r.getMonth()+1,d:r.getDate(),time:null},e);const i=String(r).trim();if(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/.test(i)){if(!e.time)return i.slice(0,10);if(i.length>10&&i[10]==="T")return i}const o=$e(i,e);return o?R(o,e,t.oldValue):t.oldValue},Q=e=>(Array.isArray(e)?e:e==null||e===""?[]:[e]).map(t=>ce(t)?.name??String(t)).join(", "),Me=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=W(),i=a=>{const p=a.toLowerCase();return r.find(f=>f.id.toLowerCase()===p||f.name.toLowerCase()===p||f.email?.toLowerCase()===p)?.id??(r.length?void 0:a)},o=e?j(t.rawInput):t.rawInput.split(/\n/).map(a=>a.trim()).filter(Boolean),n=o.map(i).filter(a=>a!==void 0);return o.length&&!n.length?t.oldValue:e?[...new Set(n)]:o.length?n[0]:null},_t=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=T(e.table);if(!r)return t.newValue;const i=j(t.rawInput),o=ut(r,i);if(r.records&&r.resolveNames&&t.data&&t.columnId){const n=i.filter(a=>st(r,a)==null);n.length&&r.resolveNames({row:t.data,columnId:t.columnId,multiple:e.multiple!==!1},n,o)}return i.length&&!o.length?t.oldValue:e.multiple===!1?o.slice(0,1):o},zt=e=>typeof e.rawInput=="string"?e.rawInput.trim()?gt(e.rawInput):null:Array.isArray(e.newValue)?ht(e.newValue):e.newValue??null,Wt=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=t.rawInput.trim();if(!r)return null;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=Number(e.max??5)?i:t.oldValue},Gt=e=>{const t=typeof e.rawInput=="string"?e.rawInput:e.newValue;return t==null||String(t).trim()===""?null:$(t)??e.oldValue},jt=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;return r==null||typeof r=="string"&&r.trim()===""?null:fe(r,{seconds:!!e.showSeconds})??t.oldValue};function ee(e,t){if(e==null)return"";if(Array.isArray(e))return e.map(r=>ee(r,t)).join(", ");if(e instanceof Date)return E(e,t);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(t.result==="currency"||t.result==="percent"||t.result==="number"){const r=t.result,i={...Nt(t),precision:ae(r,{precision:t.precision}).places};return r==="currency"?ie(e,{...i,symbol:t.symbol}):r==="percent"?oe(e,i):H(e,i)}return String(Math.round(e*1e10)/1e10)}if(t.result==="date"){const r=rt(String(e));if(r)return E(r,t)}return String(e)}const te=(e,t)=>{const r=t.columns.find(n=>String(n.id??n.field)===e.linkField);if(!r)return null;const i=r.fieldProps?.table,o=r.fieldProps?.inverse;return{key:String(r.field??r.id),get table(){return T(i)},rowsOf(n){const a=T(i),p=String(r.field??r.id);return a&&o&&!a.records&&n?.[p]===void 0?at(a,o,String(n?.id??"")):G(a,n?.[p])},get stored(){const n=T(i)?.records;return n&&o&&n.stores(o)?{records:n,field:o}:null}}},$t={SUM:"sum",AVERAGE:"avg",MIN:"min",MAX:"max",COUNT:"count"},Ce=new WeakMap;function Pe(e,t,r){const i=e?.table?.fields;if(!i)return;let o=Ce.get(i);o||Ce.set(i,o=new Map);const n=`${String(t)}|${r??""}`;if(o.has(n))return o.get(n);const a=i.find(d=>d.field===String(t)),p=a?.fieldType?O({field:a.field,fieldType:a.fieldType,fieldProps:{...a.fieldProps,...r==null?{}:{precision:r}}}).formatter:void 0;return o.set(n,p),p}const L=()=>new Date().toISOString(),xt=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0}),Kt=(e,t)=>{const r=i=>i?pe.indexOf(i):pe.length;return r(e)-r(t)},De=[{key:"watch",get label(){return l("fields.propWatch")},kind:"segmented",choices:[u("all","fields.choiceAllFields"),u("specific","fields.choiceSpecificFields")]},{key:"watchFields",get label(){return l("fields.propWatchFields")},kind:"columns",visible:e=>e.watch==="specific"}];export const BUILTIN_FIELD_TYPES=[{id:"text",get label(){return l("fields.typeText")},get description(){return l("fields.typeTextDescription")},icon:s.text,group:"basic",properties:[w],fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D})},{id:"longText",get label(){return l("fields.typeLongText")},get description(){return l("fields.typeLongTextDescription")},icon:s.longText,group:"basic",width:260,properties:[{key:"richText",get label(){return l("fields.propMarkdown")},kind:"checkbox",get hint(){return l("fields.propMarkdownHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldLongText",valueParser:e.valueParser??D}),cell:Ne,hasCell:e=>!!e.richText},{id:"richText",get label(){return l("fields.typeRichText")},get description(){return l("fields.typeRichTextDescription")},icon:s.richText,group:"basic",width:280,defaults:{toolbar:"standard"},properties:[{key:"toolbar",get label(){return l("fields.propToolbar")},kind:"segmented",choices:[u("standard","fields.choiceStandard"),u("full","fields.choiceFull")],get hint(){return l("fields.propToolbarHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldRichText",formatter:e.formatter??(t=>A(t.value)),sortComparator:e.sortComparator??((t,r)=>xt.compare(A(t),A(r))),valueParser:e.valueParser??(t=>Re(t.newValue))}),cell:Be},{id:"attachment",get label(){return l("fields.typeAttachment")},get description(){return l("fields.typeAttachmentDescription")},icon:s.attachment,group:"basic",width:180,defaults:{maxFiles:20},properties:[{key:"accept",get label(){return l("fields.propAccept")},kind:"text",get placeholder(){return l("fields.propAcceptPlaceholder")}},{key:"maxFiles",get label(){return l("fields.propMaxFiles")},kind:"number",min:1,max:100}],fill:(e,t)=>({...e,editorType:e.editorType??"attachment",formatter:e.formatter??(r=>Ue(r.value)),valueParser:e.valueParser??(r=>_e(r.newValue,t))}),cell:Ve},{id:"checkbox",get label(){return l("fields.typeCheckbox")},get description(){return l("fields.typeCheckboxDescription")},icon:s.checkbox,group:"basic",width:90,defaults:{icon:"check",color:"#20c933"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:xe},C,w],fill:e=>({...e,editorType:e.editorType??"checkbox",align:e.align??"center",toggleOnSecondClick:e.toggleOnSecondClick??!0}),cell:Fe},{id:"singleSelect",get label(){return l("fields.typeSingleSelect")},get description(){return l("fields.typeSingleSelectDescription")},icon:s.singleSelect,group:"basic",width:140,defaults:{options:[]},properties:[ke,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorOptions:e.editorOptions??P(t),formatter:e.formatter??ve(t),valueParser:e.valueParser??we(t,!1),sortValue:e.sortValue??Ht(t)}),cell:le},{id:"multiSelect",get label(){return l("fields.typeMultiSelect")},get description(){return l("fields.typeMultiSelectDescription")},icon:s.multiSelect,group:"basic",width:200,defaults:{options:[]},properties:[ke,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorMultiple:e.editorMultiple??!0,editorOptions:e.editorOptions??P(t),formatter:e.formatter??ve(t),valueParser:e.valueParser??we(t,!0)}),cell:le},{id:"user",get label(){return l("fields.typeUser")},get description(){return l("fields.typeUserDescription")},icon:s.user,group:"basic",width:170,properties:[{key:"multiple",get label(){return l("fields.propMultipleUsers")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",valueParser:e.valueParser??Me(!!t.multiple),editorMultiple:e.editorMultiple??!!t.multiple,editorOptions:e.editorOptions??W().map(r=>({value:r.id,label:r.name})),formatter:e.formatter??(r=>Q(r.value))}),cell:B},{id:"date",get label(){return l("fields.typeDate")},get description(){return l("fields.typeDateDescription")},icon:s.date,group:"basic",width:150,defaults:{dateFormat:"local",timeFormat:"12hour"},properties:[I(),...X,{key:"defaultToday",get label(){return l("fields.propDefaultToday")},kind:"checkbox"}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??(t.time?"date":"dateString"),editorType:e.editorType??"fieldDate",editorFormatString:e.editorFormatString??ze(t),formatter:e.formatter??J(t),valueParser:e.valueParser??Ut(t)}),newRowValue:({props:e})=>{if(!e.defaultToday)return;if(e.time)return L();const t=new Date;return R({y:t.getFullYear(),mo:t.getMonth()+1,d:t.getDate(),time:null},{})}},{id:"phone",get label(){return l("fields.typePhone")},get description(){return l("fields.typePhoneDescription")},icon:s.phone,group:"basic",fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"email",get label(){return l("fields.typeEmail")},get description(){return l("fields.typeEmailDescription")},icon:s.email,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"url",get label(){return l("fields.typeUrl")},get description(){return l("fields.typeUrlDescription")},icon:s.url,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"barcode",get label(){return l("fields.typeBarcode")},get description(){return l("fields.typeBarcodeDescription")},icon:s.barcode,group:"basic",width:160,fill:e=>({...e,editorType:e.editorType??"text",formatter:e.formatter??(t=>t.value&&typeof t.value=="object"?String(t.value.text??""):String(t.value??""))}),cell:Le},{id:"button",get label(){return l("fields.typeButton")},get description(){return l("fields.typeButtonDescription")},icon:s.button,group:"basic",width:120,defaults:{label:"Open",color:"#2d7ff9",action:"link"},properties:[{key:"label",get label(){return l("fields.propButtonLabel")},kind:"text",get placeholder(){return l("fields.propButtonLabelPlaceholder")}},{key:"color",get label(){return l("fields.propButtonStyle")},kind:"color",palette:se},{key:"action",get label(){return l("fields.propButtonAction")},kind:"choice",choices:Pt},{key:"url",get label(){return l("fields.propButtonUrl")},kind:"text",get placeholder(){return l("fields.propButtonUrlPlaceholder")},get hint(){return l("fields.propButtonUrlHint")},visible:e=>b(e)==="link"},{key:"values",get label(){return l("fields.propButtonValues")},kind:"recordValues",get hint(){return l("fields.propButtonValuesHint")},visible:e=>b(e)==="update"},{key:"template",get label(){return l("fields.propButtonTemplate")},kind:"choice",get hint(){return l("fields.propButtonTemplateHint")},visible:e=>b(e)==="template",choices:e=>(e.ctrl?.props?.baseRecordTemplates?.()??[]).map(t=>({value:t.id,label:t.name}))},{key:"recordAction",get label(){return l("fields.propButtonRecordAction")},kind:"choice",visible:e=>b(e)==="recordAction",choices:e=>me(e.ctrl?.props?.baseTableId).map(t=>({value:t.id,label:t.label}))},{key:"copy",get label(){return l("fields.propButtonCopy")},kind:"text",get placeholder(){return l("fields.propButtonCopyPlaceholder")},get hint(){return l("fields.propButtonCopyHint")},visible:e=>b(e)==="copy"},{key:"doneLabel",get label(){return l("fields.propButtonDoneLabel")},kind:"text",get placeholder(){return l("fields.propButtonDoneLabelPlaceholder")},get hint(){return l("fields.propButtonDoneLabelHint")},visible:e=>b(e)==="update"||b(e)==="template"},{key:"when",get label(){return l("fields.propButtonWhen")},kind:"filter",get hint(){return l("fields.propButtonWhenHint")}},{key:"who",get label(){return l("fields.propButtonWho")},kind:"people",get everyone(){return l("fields.buttonWhoEveryone")},get only(){return l("fields.whoOnly")},get hint(){return l("fields.propButtonWhoHint")}},{key:"ask",get label(){return l("fields.propButtonAsk")},kind:"checkbox",visible:e=>b(e)!=="delete"},{key:"askText",get label(){return l("fields.propButtonAskText")},kind:"text",get placeholder(){return l("fields.buttonAskDefault")},visible:e=>!!e.ask&&b(e)!=="delete"}],fill:(e,t,r)=>{const i=Se(r.columns),o=(d,f,h)=>{if(!d.trim())return null;if(!f)return m=>m?wt(d,m,i,h):"";const c=O({id:`${String(e.id??e.field)}__button`,field:`__button_${String(e.field??e.id)}`,fieldType:"formula",fieldProps:{formula:d}},r.columns).fieldFn;return m=>{if(!c||!m)return"";const g=c(m);return g==="#ERROR"?"":ee(g,{})}},n=String(t.url??""),a=String(t.copy??""),p=a.trim().startsWith("=");return{...e,...y(e),sortable:e.sortable??!1,__fieldNames:i,__buttonLink:o(n,!!n.trim()&&!vt(n),!0),__buttonCopy:o(p?a.trim().slice(1):a,p,!1)}},cell:Ie},{id:"checklist",get label(){return l("fields.typeChecklist")},get description(){return l("fields.typeChecklistDescription")},icon:s.checklist,group:"basic",width:150,fill:e=>({...e,editorType:e.editorType??"fieldChecklist",formatter:e.formatter??(t=>mt(t.value)),valueParser:e.valueParser??zt,sortValue:e.sortValue??ft,groupValue:e.groupValue??pt,groupOrder:e.groupOrder??Kt}),cell:Ee},{id:"color",get label(){return l("fields.typeColor")},get description(){return l("fields.typeColorDescription")},icon:s.color,group:"basic",width:130,properties:[w],fill:e=>({...e,editorType:e.editorType??"fieldColor",formatter:e.formatter??(t=>$(t.value)??String(t.value??"")),valueParser:e.valueParser??Gt,sortValue:e.sortValue??bt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:$(e.default),cell:He},{id:"number",get label(){return l("fields.typeNumber")},get description(){return l("fields.typeNumberDescription")},icon:s.number,group:"number",width:120,defaults:{format:"decimal",precision:1,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0,symbol:"$",symbolPosition:"before",showBar:!1,points:!1,step:1},properties:[{key:"format",get label(){return l("fields.propFormat")},kind:"segmented",choices:[u("integer","fields.choiceInteger"),u("decimal","fields.choiceDecimal"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent")],alsoSets:e=>({precision:e==="decimal"?1:e==="currency"?2:0})},{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$, €, £, ¥, CHF, kr",visible:e=>e.format==="currency"},{key:"symbolPosition",get label(){return l("fields.propSymbolPosition")},kind:"segmented",visible:e=>e.format==="currency",choices:[u("before","fields.choiceBefore"),u("after","fields.choiceAfter")]},Y(K(0,8),e=>e.format!=="integer"),{key:"step",get label(){return l("fields.propStep")},kind:"number",min:0,get hint(){return l("fields.propStepHint")}},Dt,At,Vt(e=>e.format!=="percent"),Ft,{key:"showBar",get label(){return l("fields.propShowBar")},kind:"checkbox",visible:e=>e.format==="percent"},{key:"points",get label(){return l("fields.propPoints")},kind:"checkbox",visible:e=>e.format==="percent"},w],fill:(e,t)=>q(e,t,je("number",t)),cell:re,hasCell:e=>e.format==="percent"&&!!e.showBar},{id:"currency",get label(){return l("fields.typeCurrency")},get description(){return l("fields.typeCurrencyDescription")},icon:s.currency,group:"number",width:120,defaults:{symbol:"$",symbolPosition:"before",precision:2,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0},editAs:{type:"number",props:{format:"currency"}},fill:(e,t)=>q(e,t,"currency")},{id:"percent",get label(){return l("fields.typePercent")},get description(){return l("fields.typePercentDescription")},icon:s.percent,group:"number",width:110,defaults:{precision:0,separators:"local",showThousands:!0,allowNegative:!0,points:!1},editAs:{type:"number",props:{format:"percent"}},fill:(e,t)=>q(e,t,"percent"),cell:re,hasCell:e=>!!e.showBar},{id:"duration",get label(){return l("fields.typeDuration")},get description(){return l("fields.typeDurationDescription")},icon:s.duration,group:"number",width:110,defaults:{durationFormat:"h:mm"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"},{value:"h:mm:ss.S",label:"h:mm:ss.S"},{value:"h:mm:ss.SS",label:"h:mm:ss.SS"},{value:"h:mm:ss.SSS",label:"h:mm:ss.SSS"}]}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",formatter:e.formatter??(r=>{const i=U(r.value);return i==null?"":ne(i,t.durationFormat)}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:typeof r.newValue=="number"?r.newValue:V(r.newValue))})},{id:"timeOfDay",get label(){return l("fields.typeTimeOfDay")},get description(){return l("fields.typeTimeOfDayDescription")},icon:s.timeOfDay,group:"number",width:120,defaults:{timeFormat:"12hour",showSeconds:!1},properties:[{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:be},{key:"showSeconds",get label(){return l("fields.propShowSeconds")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldTime",formatter:e.formatter??(r=>yt(r.value,t)),valueParser:e.valueParser??jt(t),sortValue:e.sortValue??kt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:fe(e.default,{seconds:!!e.showSeconds})},{id:"rating",get label(){return l("fields.typeRating")},get description(){return l("fields.typeRatingDescription")},icon:s.rating,group:"number",width:130,defaults:{max:5,icon:"star",color:"#fcb400"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Ke},C,{key:"max",get label(){return l("fields.propMaximum")},kind:"choice",choices:Array.from({length:10},(e,t)=>({value:String(t+1),label:String(t+1)}))}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",align:e.align??"left",editorType:e.editorType??"fieldRating",valueParser:e.valueParser??Wt(t)}),cell:Ae},{id:"timer",get label(){return l("fields.typeTimer")},get description(){return l("fields.typeTimerDescription")},icon:s.timer,group:"number",width:130,defaults:{durationFormat:"h:mm:ss"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"}]},C],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldTimer",align:e.align??"left",sortValue:e.sortValue??(r=>F(r)),formatter:e.formatter??(r=>{const i=F(r.value);return i==null?"":ne(i,t.durationFormat??"h:mm:ss")}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:r.newValue==null||r.newValue===""?null:typeof r.newValue=="number"||typeof r.newValue=="object"&&Qe(r.newValue)!=null?r.newValue:V(r.newValue))}),cell:Je},{id:"vote",get label(){return l("fields.typeVote")},get description(){return l("fields.typeVoteDescription")},icon:s.vote,group:"basic",width:100,defaults:{icon:"up"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"segmented",choices:[u("up","fields.choiceArrow"),u("thumb","fields.choiceThumb"),u("heart","fields.choiceHeart")]},C],fill:e=>({...e,editorType:e.editorType??"fieldVote",editorOptions:e.editorOptions??W().map(t=>({value:t.id,label:t.name})),align:e.align??"left",sortValue:e.sortValue??(t=>ue(t)),formatter:e.formatter??(t=>String(ue(t.value))),valueParser:e.valueParser??(t=>Ze(Me(!0)(t)))}),newRowValue:()=>[],cell:qe},{id:"sparkline",get label(){return l("fields.typeSparkline")},get description(){return l("fields.typeSparklineDescription")},icon:s.sparkline,group:"number",width:160,defaults:{chart:"line"},properties:[{key:"chart",get label(){return l("fields.propChart")},kind:"segmented",choices:[u("line","fields.choiceLine"),u("area","fields.choiceArea"),u("bar","fields.choiceColumns")]},C,{key:"showLast",get label(){return l("fields.propShowLast")},kind:"checkbox"}],fill:e=>({...e,formatter:e.formatter??(t=>z(t.value).join(", ")),valueParser:e.valueParser??(t=>{const r=z(t.newValue);return r.length?r:null}),sortValue:e.sortValue??(t=>z(t).at(-1)??null)}),cell:et},{id:"formula",get label(){return l("fields.typeFormula")},get description(){return l("fields.typeFormulaDescription")},icon:s.formula,group:"computed",width:160,defaults:{formula:"",result:"auto"},properties:[{key:"formula",get label(){return l("fields.propFormula")},kind:"formula"},{key:"result",get label(){return l("fields.propResult")},kind:"choice",choices:[u("auto","fields.choiceAsComputed"),u("number","fields.choiceNumber"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent"),u("date","fields.choiceDate")]},Y(K(0,8),e=>["number","currency","percent"].includes(e.result)),{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$",visible:e=>e.result==="currency"},I(e=>e.result==="date")],fill:(e,t,r)=>{const i=Se(r.columns),o=String(t.formula??""),n=String(e.field??e.id),a=new Set([n.toLowerCase(),typeof e.header=="string"?e.header.trim().toLowerCase():""].filter(Boolean)),p=c=>{const m=c.trim().toLowerCase(),g=i[m]??null;if(g===n||g==null&&a.has(m))throw lt(c);return g};let d=null;try{d=o.trim()?tt(o,p).fn:()=>null}catch{d=null}let f=null;const h=()=>{if(f)return f;f=new Map;for(const c of r.columns){if(c.fieldType==="richText"){const k=String(c.field??c.id);f.set(k,S=>A(S?.[k]));continue}if(c.fieldType==="timer"){const k=String(c.field??c.id);f.set(k,S=>F(S?.[k]));continue}const m=Mt(c);if(m){f.set(String(c.field??c.id),m);continue}if(!Ye.has(String(c.fieldType))||String(c.field??c.id)===n)continue;const g=O(c,r.columns);typeof g.fieldFn=="function"&&f.set(String(c.field??c.id),g.fieldFn)}return f},v=c=>{const m=h();return!m.size||!c?c:new Proxy(c,{get:(g,k)=>{const S=typeof k=="string"?m.get(k):void 0;if(!S||M>3)return g[k];M+=1;try{return S(g)}finally{M-=1}}})};return{...e,...y(e),fieldFn:c=>d?d(v(c)):"#ERROR",align:e.align??(["number","currency","percent"].includes(t.result)?"right":void 0),formatter:e.formatter??(c=>ee(c.value,t))}}},{id:"createdTime",get label(){return l("fields.typeCreatedTime")},get description(){return l("fields.typeCreatedTimeDescription")},icon:s.createdTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour"},properties:[I(),...X],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L(),onCreate:({rows:e})=>e.map(()=>L())},{id:"lastModifiedTime",get label(){return l("fields.typeLastModifiedTime")},get description(){return l("fields.typeLastModifiedTimeDescription")},icon:s.modifiedTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour",watch:"all"},properties:[...De,I(),...X],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L()},{id:"createdBy",get label(){return l("fields.typeCreatedBy")},get description(){return l("fields.typeCreatedByDescription")},icon:s.createdBy,group:"computed",width:160,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>de()?.id??null,cell:B},{id:"lastModifiedBy",get label(){return l("fields.typeLastModifiedBy")},get description(){return l("fields.typeLastModifiedByDescription")},icon:s.modifiedBy,group:"computed",width:160,defaults:{watch:"all"},properties:De,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>de()?.id??null,cell:B},{id:"autoNumber",get label(){return l("fields.typeAutoNumber")},get description(){return l("fields.typeAutoNumberDescription")},icon:s.autoNumber,group:"computed",width:100,fill:e=>({...e,...y(e),cellDataType:e.cellDataType??"number"}),newRowValue:({rows:e,field:t})=>e.reduce((r,i)=>Math.max(r,Number(i?.[t])||0),0)+1,onCreate:({rows:e})=>e.map((t,r)=>r+1)},{id:"link",get label(){return l("fields.typeLink")},get description(){return l("fields.typeLinkDescription")},icon:s.link,group:"relation",width:200,defaults:{multiple:!0},properties:[{key:"table",get label(){return l("fields.propTable")},kind:"choice",choices:()=>nt().map(e=>({value:e.id,label:e.name})),get hint(){return l("fields.propTableHint")},alsoSets:()=>({pickFrom:""})},{key:"multiple",get label(){return l("fields.propMultipleRecords")},kind:"checkbox"},{key:"pickFrom",get label(){return l("fields.propPickFrom")},kind:"choice",choices:e=>[{value:"",label:l("fields.pickFromAll")},...(T(e.props.table)?.views?.()??[]).filter(t=>!t.personal&&t.type!=="form").map(t=>({value:t.id,label:t.name}))],visible:e=>!!e.table,get hint(){return l("fields.propPickFromHint")}}],fill:(e,t)=>({...e,editorType:e.editorType??"fieldLink",formatter:e.formatter??(r=>{const i=T(t.table);return G(i,r.value).map(o=>String(o[i.primaryField]??"")).join(", ")}),valueParser:e.valueParser??_t(t),groupValue:e.groupValue??(r=>ot(t.table,r)),groupCopies:!0}),cell:Oe},{id:"lookup",get label(){return l("fields.typeLookup")},get description(){return l("fields.typeLookupDescription")},icon:s.lookup,group:"relation",width:180,properties:[Z,ye],fill:(e,t,r)=>{const i=te(t,r),o=n=>{const a=Pe(i,t.field);return String(a?a({value:n})??"":n)};return{...e,...y(e),fieldSource:()=>i?.table?.fields?.find(n=>n.field===String(t.field)),fieldFn:n=>{if(!i)return[];const a=x(i.table,String(t.field)),p=i.stored;return p?p.records.allLinkedTo(p.field,String(n?.id??"")).map(a):i.rowsOf(n).map(a)},formatter:e.formatter??(n=>Array.isArray(n.value)?n.value.filter(a=>a!=null&&a!=="").map(o).join(", "):n.value==null?"":o(n.value))}}},{id:"rollup",get label(){return l("fields.typeRollup")},get description(){return l("fields.typeRollupDescription")},icon:s.rollup,group:"relation",width:140,defaults:{aggregation:"SUM"},properties:[Z,ye,{key:"aggregation",get label(){return l("fields.propAggregation")},kind:"choice",choices:Object.keys(_).map(e=>({value:e,label:e}))},Y(K(0,8),e=>["SUM","AVERAGE","MIN","MAX"].includes(e.aggregation))],fill:(e,t,r)=>{const i=te(t,r),o=_[String(t.aggregation)]??_.SUM,n=["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL"].includes(String(t.aggregation)),a=["SUM","AVERAGE","MIN","MAX"].includes(String(t.aggregation)),p=d=>{const f=a?Pe(i,t.field,t.precision):void 0;return f?String(f({value:d})??""):H(d,{precision:Te(t,0)})};return{...e,...y(e),...n?{cellDataType:e.cellDataType??"number"}:{},align:e.align??(n?"right":void 0),fieldSource:()=>i?.table?.fields?.find(d=>d.field===String(t.field)),fieldFn:d=>{if(!i)return null;const f=x(i.table,String(t.field)),h=i.stored;if(h){const v=String(d?.id??""),c=$t[String(t.aggregation)];return c?h.records.total(h.field,v,String(t.field),c)??null:t.aggregation==="COUNTA"||t.aggregation==="COUNTALL"?h.records.total(h.field,v)??null:o(h.records.allLinkedTo(h.field,v).map(f))}return o(i.rowsOf(d).map(f))},formatter:e.formatter??(d=>{const f=n?U(d.value):typeof d.value=="number"?d.value:null;return f==null?String(d.value??""):p(f)})}}},{id:"count",get label(){return l("fields.typeCount")},get description(){return l("fields.typeCountDescription")},icon:s.count,group:"relation",width:90,properties:[Z],fill:(e,t,r)=>{const i=te(t,r);return{...e,...y(e),cellDataType:e.cellDataType??"number",formatter:o=>o.value==null?"":Number(o.value).toLocaleString(),fieldFn:o=>{if(!i)return 0;const n=i.stored;return n?n.records.total(n.field,String(o?.id??""))??null:i.rowsOf(o).length}}}},dt];
1
+ import{fillFieldColumn as O}from"./registry.svelte.js";import Ve from"./RatingCell.svelte";import N from"./LinkCell.svelte";import Fe from"./AttachmentCell.svelte";import Ie from"./CheckboxCell.svelte";import le from"./PercentCell.svelte";import B from"./UserCell.svelte";import Le from"./ButtonCell.svelte";import Oe from"./BarcodeCell.svelte";import Ne from"./LinkedRecordsCell.svelte";import Be from"./RichTextCell.svelte";import Re from"./RichHtmlCell.svelte";import{richPlain as A}from"./rich-html.js";import{toRichHtml as Ee}from"./rich-html-write.js";import ie from"./SelectCell.svelte";import He from"./ChecklistCell.svelte";import Ue from"./ColorCell.svelte";import{attachmentsText as _e,parseAttachments as ze}from"./attachments.js";import{dateEditTokens as We,dateFromParts as R,exactNumber as Ge,formatCurrency as ne,formatDate as E,formatDuration as oe,formatNumber as H,formatPercent as ae,numberFieldShape as se,numberFromText as je,numberKind as $e,parseDateText as xe,parseDuration as V,toNumber as U}from"./format.js";import{BRIGHT as ue,CHECKBOX_ICONS as Ke,RATING_ICONS as Xe}from"./palette.js";import{COMPUTED_TYPES as ce,ROLLUPS as _,fieldNameMap as Ye}from"./rollups.js";import{sparklineValues as z,voteCount as de,voteIds as Ze}from"./vote.js";import qe from"./VoteCell.svelte";import Je from"./TimerCell.svelte";import{timerSeconds as F,timerTotal as Qe}from"./timer.js";import et from"./SparklineCell.svelte";import{compileFormula as tt,isoDate as rt,selfReferenceError as lt}from"./formula.js";import{findFieldUser as pe,getCurrentUser as fe,getFieldUsers as W,getLinkedTable as T,idOf as it,linkedRows as G,listLinkedTables as nt,liveLink as ot,recordsNaming as at,resolveLinkId as st,resolveLinkIds as ut}from"./sources.svelte.js";import{splitNames as j}from"./name-list.js";import{linkedFields as ct}from"./linked-fields.js";import{AI_FIELD_TYPE as dt}from"./ai-field.svelte.js";import{CHECKLIST_GROUPS as me,checklistGroup as pt,checklistSortValue as ft,checklistText as mt,parseChecklist as gt,toChecklist as ht}from"./checklist.js";import{colorSortValue as bt,parseColor as $}from"./color-value.js";import{formatTimeOfDay as yt,parseTimeOfDay as ge,timeSeconds as kt}from"./time-of-day.js";import{bm as l}from"./messages.svelte.js";import{BUTTON_ACTIONS as Tt,buttonAction as b,fillButtonTokens as vt,isLinkTemplate as wt}from"./button.js";import{recordActionsFor as he}from"./record-actions.js";const St=new Set(["user","createdBy","lastModifiedBy"]);function Mt(e){const t=String(e.field??e.id),r=o=>o.length===1?o[0]:o;if(St.has(String(e.fieldType)))return o=>{const n=o?.[t];return n==null||n===""?n:r((Array.isArray(n)?n:[n]).map(a=>pe(a)?.name??a))};if(e.fieldType!=="link")return null;const i=e.fieldProps?.table;return o=>{const n=o?.[t],a=T(i);if(!a||n==null||n==="")return n;const d=x(a,a.primaryField),g=new Map(G(a,n).map(m=>[it(a,m),d(m)]));return r((Array.isArray(n)?n:[n]).map(m=>g.get(String(m))??m))}}const be=new WeakMap;let w=0;function x(e,t){const r=n=>n?.[t];if(!e?.fields?.length)return r;let i=be.get(e.fields);if(i||be.set(e.fields,i=new Map),!i.has(t)){const n=ct(e).find(d=>d.def.field===t),a=n?.def.fieldType==="timer"?d=>F(d?.[t]):null;i.set(t,a??n?.def.fieldFn??null)}const o=i.get(t);return o?n=>{if(w>3)return r(n);w+=1;try{return o(n)}finally{w-=1}}:r}const u={text:"M4 6h16M4 12h10M4 18h7",longText:"M4 6h16M4 10h16M4 14h16M4 18h10",richText:"M6 4h7a4 4 0 0 1 0 8H6zM6 12h8a4 4 0 0 1 0 8H6zM6 4v16",vote:"M12 19V5M5 12l7-7 7 7",sparkline:"M3 17l5-6 4 4 8-9",number:"M9 4 7 20M17 4l-2 16M4 9h16M3 15h16",currency:"M12 3v18M16 7.5C16 5.6 14.2 4.5 12 4.5S8 5.6 8 7.5s1.8 2.7 4 3.5 4 1.6 4 3.5-1.8 3-4 3-4-1.1-4-3",percent:"M19 5 5 19M7 7h.01M17 17h.01",date:"M4 6h16v14H4zM4 10h16M8 3v4M16 3v4",duration:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4l3 2",timer:"M12 7a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM12 10v4l2.5 1.5M9.5 2.5h5M12 2.5V5",checkbox:"M4 4h16v16H4zM8 12l3 3 5-6",singleSelect:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM8 11l4 4 4-4",multiSelect:"M3 7h11M3 12h11M3 17h11M17 6l2 2 3-3M17 16l2 2 3-3",rating:"M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3 6.5 20.2l1-6.2L3 9.6l6.2-.9z",url:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",phone:"M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2",attachment:"M20 11.5 12.3 19a5 5 0 0 1-7.1-7.1l7.8-7.8a3.3 3.3 0 0 1 4.7 4.7L9.9 16.6a1.7 1.7 0 0 1-2.4-2.4l7.1-7",user:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0",createdTime:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4h4",modifiedTime:"M4 12a8 8 0 1 0 2.3-5.7M4 4v4h4M12 8v4l3 2",createdBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M19 15v6M16 18h6",modifiedBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M16 21l5-5-2-2-5 5v2z",autoNumber:"M5 7h3v10M11 9a2 2 0 1 1 4 0c0 2-4 3-4 6h4M18 7h2v10",barcode:"M4 5v14M7 5v14M10 5v14M13 5v14M15 5v14M18 5v14M20 5v14",button:"M4 7h16v10H4zM9 12h6",formula:"M7 20c2 0 2.5-2 3-5l2-10c.5-2 1.5-2 3-2M8 9h7",link:"M9 7H6a5 5 0 0 0 0 10h3M15 7h3a5 5 0 0 1 0 10h-3M8 12h8",lookup:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4M8 11h6",rollup:"M6 4h12L12 12l6 8H6",count:"M5 5h14v14H5zM9 9v6M12 9v6M15 9v6",checklist:"M3.5 6l1.5 1.5L7.5 5M3.5 12l1.5 1.5 2.5-2.5M3.5 18l1.5 1.5 2.5-2.5M11 6h9M11 12h9M11 18h9",color:"M12 3a9 9 0 1 0 0 18c1 0 1.6-.7 1.6-1.6 0-1-.8-1.4-.8-2.3 0-1 .8-1.7 1.8-1.7H17a4 4 0 0 0 4-4C21 6.6 17 3 12 3zM7.5 12h.01M9.5 7.5h.01M14.5 7.5h.01",timeOfDay:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l-3 2M12 3v2M21 12h-2M12 21v-2M3 12h2"},c=(e,t)=>({value:e,get label(){return l(t)}}),Ct={link:"fields.buttonActionLink",automation:"fields.buttonActionAutomation",update:"fields.buttonActionUpdate",template:"fields.buttonActionTemplate",recordAction:"fields.buttonActionRecordAction",copy:"fields.buttonActionCopy",duplicate:"fields.buttonActionDuplicate",delete:"fields.buttonActionDelete",open:"fields.buttonActionOpen"};function Dt(e){const t=!!e.ctrl?.props?.baseButton,r=b(e.props),i=o=>o===r||o==="link"||o==="copy"?!0:t?o==="template"?(e.ctrl?.props?.baseRecordTemplates?.()??[]).length>0:o==="recordAction"?he(e.ctrl?.props?.baseTableId).length>0:!0:!1;return Tt.filter(i).map(o=>c(o,Ct[o]))}const ye=e=>e?{visible:e}:{},Pt={key:"separators",get label(){return l("fields.propSeparators")},kind:"choice",choices:[c("local","fields.choiceLocal"),{value:"comma-period",label:"1,000,000.00"},{value:"period-comma",label:"1.000.000,00"},{value:"space-comma",label:"1 000 000,00"},{value:"space-period",label:"1 000 000.00"}]},At={key:"showThousands",get label(){return l("fields.propShowThousands")},kind:"checkbox"},Vt=e=>({key:"abbreviation",get label(){return l("fields.propAbbreviation")},kind:"choice",choices:[c("none","fields.choiceNone"),c("thousand","fields.choiceThousand"),c("million","fields.choiceMillion"),c("billion","fields.choiceBillion")],...ye(e)}),Ft={key:"allowNegative",get label(){return l("fields.propAllowNegative")},kind:"checkbox"},v={key:"default",get label(){return l("fields.propDefault")},kind:"default",get hint(){return l("fields.propDefaultHint")}},K=(e,t)=>Array.from({length:t-e+1},(r,i)=>{const o=e+i;return{value:String(o),label:o===0?"1":`1.${"0".repeat(o)}`}}),X=(e,t)=>({key:"precision",get label(){return l("fields.propPrecision")},kind:"choice",choices:e,visible:t}),It=[c("local","fields.choiceLocal"),c("friendly","fields.choiceFriendly"),c("us","fields.choiceUs"),c("european","fields.choiceEuropean"),c("iso","fields.choiceIso")],I=e=>({key:"dateFormat",get label(){return l("fields.propDateFormat")},kind:"choice",choices:It,...ye(e)}),ke=[c("12hour","fields.choice12Hour"),c("24hour","fields.choice24Hour")],Y=[{key:"time",get label(){return l("fields.propIncludeTime")},kind:"checkbox"},{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:ke,visible:e=>!!e.time},{key:"gmt",get label(){return l("fields.propGmt")},kind:"checkbox",visible:e=>!!e.time},{key:"showTimeZone",get label(){return l("fields.propShowTimeZone")},kind:"checkbox",visible:e=>!!e.time}],Lt=e=>e.columns.filter(t=>t.fieldType==="link").map(t=>({value:String(t.id??t.field),label:String(t.header??t.field)})),Z={key:"linkField",get label(){return l("fields.propLinkField")},kind:"choice",choices:Lt,get hint(){return l("fields.propLinkFieldHint")}},Ot=e=>{const t=e.columns.find(o=>String(o.id??o.field)===e.props.linkField),r=T(t?.fieldProps?.table);return r?(r.fields??[{field:r.primaryField,header:r.primaryField}]).map(o=>({value:o.field,label:o.header})):[]},Te={key:"field",get label(){return l("fields.propLinkedField")},kind:"choice",choices:Ot,visible:e=>!!e.linkField},M={key:"color",get label(){return l("fields.propColor")},kind:"color",palette:ue},ve={key:"options",get label(){return l("fields.propOptions")},kind:"options"},we=(e,t=0)=>{const r=Number(e.precision);return Number.isInteger(r)&&r>=0&&r<=8?r:t},Nt=e=>({precision:e.format==="integer"?0:we(e,e.format==="decimal"?1:0),separators:e.separators,showThousands:e.showThousands!==!1,abbreviation:e.abbreviation}),Bt=(e,t)=>r=>{const i=typeof r.rawInput=="string"?r.rawInput:r.newValue;if(typeof i=="number"||i==null)return i;if(String(i).trim()==="")return null;const o=je(String(i),e,t);return o??r.oldValue},Rt=(e,t)=>t.allowNegative===!1&&!e.validate?{rejectInvalid:!0,validate:r=>Number(r.value)<0?l("fields.negativeNotAllowed"):null}:{},Et=(e,t)=>{const r={precision:se(e,t).places,separators:t.separators,showThousands:t.showThousands!==!1,abbreviation:e==="percent"?void 0:t.abbreviation};return i=>{const o=Ge(i.value);return o==null?"":e==="currency"?ne(o,{...r,symbol:t.symbol,symbolPosition:t.symbolPosition}):e==="percent"?ae(o,{...r,points:t.points}):H(o,r)}},q=(e,t,r)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",align:e.align??(r==="percent"&&t.showBar?"left":"right"),...Rt(e,t),valueParser:e.valueParser??Bt(r,t),formatter:e.formatter??Et(r,t),sortValue:e.sortValue??U}),C=e=>Array.isArray(e.options)?e.options.map(t=>({value:t.value,label:t.label??String(t.value),...t.color?{color:t.color}:{}})):[],Se=(e,t)=>{const r=new Map;for(const n of C(e))r.set(String(n.value).toLowerCase(),n.value),r.set(String(n.label).toLowerCase(),n.value);const i=n=>r.get(n.toLowerCase()),o=r.size===0;return n=>{if(typeof n.rawInput!="string")return n.newValue;const a=t?j(n.rawInput):n.rawInput.split(/\n/).map(g=>g.trim()).filter(Boolean);if(o)return t?[...new Set(a)]:a[0]??null;const d=a.map(i).filter(g=>g!==void 0);return a.length&&!d.length?n.oldValue:t?[...new Set(d)]:a.length?i(a[0])===void 0?n.oldValue:i(a[0]):null}},Me=e=>{const t=new Map(C(e).map(r=>[String(r.value),r.label]));return r=>(Array.isArray(r.value)?r.value:r.value==null||r.value===""?[]:[r.value]).map(i=>t.get(String(i))??String(i)).join(", ")},Ht=e=>{const t=new Map(C(e).map((r,i)=>[String(r.value),i]));return r=>r==null||r===""?null:t.get(String(r))??t.size},Ce=Ye,y=e=>({editable:e.editable??!1}),J=e=>t=>E(t.value,e),D=e=>e.oldValue!=null&&typeof e.oldValue!="string"&&String(e.oldValue)===e.newValue?e.oldValue:e.newValue,Ut=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;if(r==null||typeof r=="string"&&r.trim()==="")return null;if(r instanceof Date)return e.time?r.toISOString():R({y:r.getFullYear(),mo:r.getMonth()+1,d:r.getDate(),time:null},e);const i=String(r).trim();if(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/.test(i)){if(!e.time)return i.slice(0,10);if(i.length>10&&i[10]==="T")return i}const o=xe(i,e);return o?R(o,e,t.oldValue):t.oldValue},Q=e=>(Array.isArray(e)?e:e==null||e===""?[]:[e]).map(t=>pe(t)?.name??String(t)).join(", "),De=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=W(),i=a=>{const d=a.toLowerCase();return r.find(m=>m.id.toLowerCase()===d||m.name.toLowerCase()===d||m.email?.toLowerCase()===d)?.id??(r.length?void 0:a)},o=e?j(t.rawInput):t.rawInput.split(/\n/).map(a=>a.trim()).filter(Boolean),n=o.map(i).filter(a=>a!==void 0);return o.length&&!n.length?t.oldValue:e?[...new Set(n)]:o.length?n[0]:null},_t=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=T(e.table);if(!r)return t.newValue;const i=j(t.rawInput),o=ut(r,i);if(r.records&&r.resolveNames&&t.data&&t.columnId){const n=i.filter(a=>st(r,a)==null);n.length&&r.resolveNames({row:t.data,columnId:t.columnId,multiple:e.multiple!==!1},n,o)}return i.length&&!o.length?t.oldValue:e.multiple===!1?o.slice(0,1):o},zt=e=>typeof e.rawInput=="string"?e.rawInput.trim()?gt(e.rawInput):null:Array.isArray(e.newValue)?ht(e.newValue):e.newValue??null,Wt=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=t.rawInput.trim();if(!r)return null;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=Number(e.max??5)?i:t.oldValue},Gt=e=>{const t=typeof e.rawInput=="string"?e.rawInput:e.newValue;return t==null||String(t).trim()===""?null:$(t)??e.oldValue},jt=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;return r==null||typeof r=="string"&&r.trim()===""?null:ge(r,{seconds:!!e.showSeconds})??t.oldValue};function ee(e,t){if(e==null)return"";if(Array.isArray(e))return e.map(r=>ee(r,t)).join(", ");if(e instanceof Date)return E(e,t);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(t.result==="currency"||t.result==="percent"||t.result==="number"){const r=t.result,i={...Nt(t),precision:se(r,{precision:t.precision}).places};return r==="currency"?ne(e,{...i,symbol:t.symbol}):r==="percent"?ae(e,i):H(e,i)}return String(Math.round(e*1e10)/1e10)}if(t.result==="date"){const r=rt(String(e));if(r)return E(r,t)}return String(e)}const te=(e,t)=>{const r=t.columns.find(n=>String(n.id??n.field)===e.linkField);if(!r)return null;const i=r.fieldProps?.table,o=r.fieldProps?.inverse;return{key:String(r.field??r.id),get table(){return T(i)},rowsOf(n){const a=T(i),d=String(r.field??r.id);return a&&o&&!a.records&&n?.[d]===void 0?at(a,o,String(n?.id??"")):G(a,n?.[d])},get stored(){const n=T(i)?.records;return n&&o&&n.stores(o)?{records:n,field:o}:null}}},$t={SUM:"sum",AVERAGE:"avg",MIN:"min",MAX:"max",COUNT:"count"},Pe=new WeakMap;function re(e,t,r){const i=e?.table?.fields;if(!i)return;let o=Pe.get(i);o||Pe.set(i,o=new Map);const n=`${String(t)}|${r??""}`;if(o.has(n))return o.get(n);const a=i.find(g=>g.field===String(t)),d=a?.fieldType?O({field:a.field,fieldType:a.fieldType,fieldProps:{...a.fieldProps,...r==null?{}:{precision:r}}}).formatter:void 0;return o.set(n,d),d}const L=()=>new Date().toISOString(),xt=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0}),Kt=(e,t)=>{const r=i=>i?me.indexOf(i):me.length;return r(e)-r(t)},Ae=[{key:"watch",get label(){return l("fields.propWatch")},kind:"segmented",choices:[c("all","fields.choiceAllFields"),c("specific","fields.choiceSpecificFields")]},{key:"watchFields",get label(){return l("fields.propWatchFields")},kind:"columns",visible:e=>e.watch==="specific"}];export const BUILTIN_FIELD_TYPES=[{id:"text",get label(){return l("fields.typeText")},get description(){return l("fields.typeTextDescription")},icon:u.text,group:"basic",properties:[v],fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D})},{id:"longText",get label(){return l("fields.typeLongText")},get description(){return l("fields.typeLongTextDescription")},icon:u.longText,group:"basic",width:260,properties:[{key:"richText",get label(){return l("fields.propMarkdown")},kind:"checkbox",get hint(){return l("fields.propMarkdownHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldLongText",valueParser:e.valueParser??D}),cell:Be,hasCell:e=>!!e.richText},{id:"richText",get label(){return l("fields.typeRichText")},get description(){return l("fields.typeRichTextDescription")},icon:u.richText,group:"basic",width:280,defaults:{toolbar:"standard"},properties:[{key:"toolbar",get label(){return l("fields.propToolbar")},kind:"segmented",choices:[c("standard","fields.choiceStandard"),c("full","fields.choiceFull")],get hint(){return l("fields.propToolbarHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldRichText",formatter:e.formatter??(t=>A(t.value)),sortComparator:e.sortComparator??((t,r)=>xt.compare(A(t),A(r))),valueParser:e.valueParser??(t=>Ee(t.newValue))}),cell:Re},{id:"attachment",get label(){return l("fields.typeAttachment")},get description(){return l("fields.typeAttachmentDescription")},icon:u.attachment,group:"basic",width:180,defaults:{maxFiles:20},properties:[{key:"accept",get label(){return l("fields.propAccept")},kind:"text",get placeholder(){return l("fields.propAcceptPlaceholder")}},{key:"maxFiles",get label(){return l("fields.propMaxFiles")},kind:"number",min:1,max:100}],fill:(e,t)=>({...e,editorType:e.editorType??"attachment",formatter:e.formatter??(r=>_e(r.value)),valueParser:e.valueParser??(r=>ze(r.newValue,t))}),cell:Fe},{id:"checkbox",get label(){return l("fields.typeCheckbox")},get description(){return l("fields.typeCheckboxDescription")},icon:u.checkbox,group:"basic",width:90,defaults:{icon:"check",color:"#20c933"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Ke},M,v],fill:e=>({...e,editorType:e.editorType??"checkbox",align:e.align??"center",toggleOnSecondClick:e.toggleOnSecondClick??!0}),cell:Ie},{id:"singleSelect",get label(){return l("fields.typeSingleSelect")},get description(){return l("fields.typeSingleSelectDescription")},icon:u.singleSelect,group:"basic",width:140,defaults:{options:[]},properties:[ve,v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorOptions:e.editorOptions??C(t),formatter:e.formatter??Me(t),valueParser:e.valueParser??Se(t,!1),sortValue:e.sortValue??Ht(t)}),cell:ie},{id:"multiSelect",get label(){return l("fields.typeMultiSelect")},get description(){return l("fields.typeMultiSelectDescription")},icon:u.multiSelect,group:"basic",width:200,defaults:{options:[]},properties:[ve,v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorMultiple:e.editorMultiple??!0,editorOptions:e.editorOptions??C(t),formatter:e.formatter??Me(t),valueParser:e.valueParser??Se(t,!0)}),cell:ie},{id:"user",get label(){return l("fields.typeUser")},get description(){return l("fields.typeUserDescription")},icon:u.user,group:"basic",width:170,properties:[{key:"multiple",get label(){return l("fields.propMultipleUsers")},kind:"checkbox"},v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",valueParser:e.valueParser??De(!!t.multiple),editorMultiple:e.editorMultiple??!!t.multiple,editorOptions:e.editorOptions??W().map(r=>({value:r.id,label:r.name})),formatter:e.formatter??(r=>Q(r.value))}),cell:B},{id:"date",get label(){return l("fields.typeDate")},get description(){return l("fields.typeDateDescription")},icon:u.date,group:"basic",width:150,defaults:{dateFormat:"local",timeFormat:"12hour"},properties:[I(),...Y,{key:"defaultToday",get label(){return l("fields.propDefaultToday")},kind:"checkbox"}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??(t.time?"date":"dateString"),editorType:e.editorType??"fieldDate",editorFormatString:e.editorFormatString??We(t),formatter:e.formatter??J(t),valueParser:e.valueParser??Ut(t)}),newRowValue:({props:e})=>{if(!e.defaultToday)return;if(e.time)return L();const t=new Date;return R({y:t.getFullYear(),mo:t.getMonth()+1,d:t.getDate(),time:null},{})}},{id:"phone",get label(){return l("fields.typePhone")},get description(){return l("fields.typePhoneDescription")},icon:u.phone,group:"basic",fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"email",get label(){return l("fields.typeEmail")},get description(){return l("fields.typeEmailDescription")},icon:u.email,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"url",get label(){return l("fields.typeUrl")},get description(){return l("fields.typeUrlDescription")},icon:u.url,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"barcode",get label(){return l("fields.typeBarcode")},get description(){return l("fields.typeBarcodeDescription")},icon:u.barcode,group:"basic",width:160,fill:e=>({...e,editorType:e.editorType??"text",formatter:e.formatter??(t=>t.value&&typeof t.value=="object"?String(t.value.text??""):String(t.value??""))}),cell:Oe},{id:"button",get label(){return l("fields.typeButton")},get description(){return l("fields.typeButtonDescription")},icon:u.button,group:"basic",width:120,defaults:{label:"Open",color:"#2d7ff9",action:"link"},properties:[{key:"label",get label(){return l("fields.propButtonLabel")},kind:"text",get placeholder(){return l("fields.propButtonLabelPlaceholder")}},{key:"color",get label(){return l("fields.propButtonStyle")},kind:"color",palette:ue},{key:"action",get label(){return l("fields.propButtonAction")},kind:"choice",choices:Dt},{key:"url",get label(){return l("fields.propButtonUrl")},kind:"text",get placeholder(){return l("fields.propButtonUrlPlaceholder")},get hint(){return l("fields.propButtonUrlHint")},visible:e=>b(e)==="link"},{key:"values",get label(){return l("fields.propButtonValues")},kind:"recordValues",get hint(){return l("fields.propButtonValuesHint")},visible:e=>b(e)==="update"},{key:"template",get label(){return l("fields.propButtonTemplate")},kind:"choice",get hint(){return l("fields.propButtonTemplateHint")},visible:e=>b(e)==="template",choices:e=>(e.ctrl?.props?.baseRecordTemplates?.()??[]).map(t=>({value:t.id,label:t.name}))},{key:"recordAction",get label(){return l("fields.propButtonRecordAction")},kind:"choice",visible:e=>b(e)==="recordAction",choices:e=>he(e.ctrl?.props?.baseTableId).map(t=>({value:t.id,label:t.label}))},{key:"copy",get label(){return l("fields.propButtonCopy")},kind:"text",get placeholder(){return l("fields.propButtonCopyPlaceholder")},get hint(){return l("fields.propButtonCopyHint")},visible:e=>b(e)==="copy"},{key:"doneLabel",get label(){return l("fields.propButtonDoneLabel")},kind:"text",get placeholder(){return l("fields.propButtonDoneLabelPlaceholder")},get hint(){return l("fields.propButtonDoneLabelHint")},visible:e=>b(e)==="update"||b(e)==="template"},{key:"when",get label(){return l("fields.propButtonWhen")},kind:"filter",get hint(){return l("fields.propButtonWhenHint")}},{key:"who",get label(){return l("fields.propButtonWho")},kind:"people",get everyone(){return l("fields.buttonWhoEveryone")},get only(){return l("fields.whoOnly")},get hint(){return l("fields.propButtonWhoHint")}},{key:"ask",get label(){return l("fields.propButtonAsk")},kind:"checkbox",visible:e=>b(e)!=="delete"},{key:"askText",get label(){return l("fields.propButtonAskText")},kind:"text",get placeholder(){return l("fields.buttonAskDefault")},visible:e=>!!e.ask&&b(e)!=="delete"}],fill:(e,t,r)=>{const i=Ce(r.columns),o=(g,m,S)=>{if(!g.trim())return null;if(!m)return p=>p?vt(g,p,i,S):"";const s=O({id:`${String(e.id??e.field)}__button`,field:`__button_${String(e.field??e.id)}`,fieldType:"formula",fieldProps:{formula:g}},r.columns).fieldFn;return p=>{if(!s||!p)return"";const f=s(p);return f==="#ERROR"?"":ee(f,{})}},n=String(t.url??""),a=String(t.copy??""),d=a.trim().startsWith("=");return{...e,...y(e),sortable:e.sortable??!1,__fieldNames:i,__buttonLink:o(n,!!n.trim()&&!wt(n),!0),__buttonCopy:o(d?a.trim().slice(1):a,d,!1)}},cell:Le},{id:"checklist",get label(){return l("fields.typeChecklist")},get description(){return l("fields.typeChecklistDescription")},icon:u.checklist,group:"basic",width:150,fill:e=>({...e,editorType:e.editorType??"fieldChecklist",formatter:e.formatter??(t=>mt(t.value)),valueParser:e.valueParser??zt,sortValue:e.sortValue??ft,groupValue:e.groupValue??pt,groupOrder:e.groupOrder??Kt}),cell:He},{id:"color",get label(){return l("fields.typeColor")},get description(){return l("fields.typeColorDescription")},icon:u.color,group:"basic",width:130,properties:[v],fill:e=>({...e,editorType:e.editorType??"fieldColor",formatter:e.formatter??(t=>$(t.value)??String(t.value??"")),valueParser:e.valueParser??Gt,sortValue:e.sortValue??bt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:$(e.default),cell:Ue},{id:"number",get label(){return l("fields.typeNumber")},get description(){return l("fields.typeNumberDescription")},icon:u.number,group:"number",width:120,defaults:{format:"decimal",precision:1,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0,symbol:"$",symbolPosition:"before",showBar:!1,points:!1,step:1},properties:[{key:"format",get label(){return l("fields.propFormat")},kind:"segmented",choices:[c("integer","fields.choiceInteger"),c("decimal","fields.choiceDecimal"),c("currency","fields.choiceCurrency"),c("percent","fields.choicePercent")],alsoSets:e=>({precision:e==="decimal"?1:e==="currency"?2:0})},{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$, €, £, ¥, CHF, kr",visible:e=>e.format==="currency"},{key:"symbolPosition",get label(){return l("fields.propSymbolPosition")},kind:"segmented",visible:e=>e.format==="currency",choices:[c("before","fields.choiceBefore"),c("after","fields.choiceAfter")]},X(K(0,8),e=>e.format!=="integer"),{key:"step",get label(){return l("fields.propStep")},kind:"number",min:0,get hint(){return l("fields.propStepHint")}},Pt,At,Vt(e=>e.format!=="percent"),Ft,{key:"showBar",get label(){return l("fields.propShowBar")},kind:"checkbox",visible:e=>e.format==="percent"},{key:"points",get label(){return l("fields.propPoints")},kind:"checkbox",visible:e=>e.format==="percent"},v],fill:(e,t)=>q(e,t,$e("number",t)),cell:le,hasCell:e=>e.format==="percent"&&!!e.showBar},{id:"currency",get label(){return l("fields.typeCurrency")},get description(){return l("fields.typeCurrencyDescription")},icon:u.currency,group:"number",width:120,defaults:{symbol:"$",symbolPosition:"before",precision:2,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0},editAs:{type:"number",props:{format:"currency"}},fill:(e,t)=>q(e,t,"currency")},{id:"percent",get label(){return l("fields.typePercent")},get description(){return l("fields.typePercentDescription")},icon:u.percent,group:"number",width:110,defaults:{precision:0,separators:"local",showThousands:!0,allowNegative:!0,points:!1},editAs:{type:"number",props:{format:"percent"}},fill:(e,t)=>q(e,t,"percent"),cell:le,hasCell:e=>!!e.showBar},{id:"duration",get label(){return l("fields.typeDuration")},get description(){return l("fields.typeDurationDescription")},icon:u.duration,group:"number",width:110,defaults:{durationFormat:"h:mm"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"},{value:"h:mm:ss.S",label:"h:mm:ss.S"},{value:"h:mm:ss.SS",label:"h:mm:ss.SS"},{value:"h:mm:ss.SSS",label:"h:mm:ss.SSS"}]}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",formatter:e.formatter??(r=>{const i=U(r.value);return i==null?"":oe(i,t.durationFormat)}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:typeof r.newValue=="number"?r.newValue:V(r.newValue))})},{id:"timeOfDay",get label(){return l("fields.typeTimeOfDay")},get description(){return l("fields.typeTimeOfDayDescription")},icon:u.timeOfDay,group:"number",width:120,defaults:{timeFormat:"12hour",showSeconds:!1},properties:[{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:ke},{key:"showSeconds",get label(){return l("fields.propShowSeconds")},kind:"checkbox"},v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldTime",formatter:e.formatter??(r=>yt(r.value,t)),valueParser:e.valueParser??jt(t),sortValue:e.sortValue??kt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:ge(e.default,{seconds:!!e.showSeconds})},{id:"rating",get label(){return l("fields.typeRating")},get description(){return l("fields.typeRatingDescription")},icon:u.rating,group:"number",width:130,defaults:{max:5,icon:"star",color:"#fcb400"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Xe},M,{key:"max",get label(){return l("fields.propMaximum")},kind:"choice",choices:Array.from({length:10},(e,t)=>({value:String(t+1),label:String(t+1)}))}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",align:e.align??"left",editorType:e.editorType??"fieldRating",valueParser:e.valueParser??Wt(t)}),cell:Ve},{id:"timer",get label(){return l("fields.typeTimer")},get description(){return l("fields.typeTimerDescription")},icon:u.timer,group:"number",width:130,defaults:{durationFormat:"h:mm:ss"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"}]},M],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldTimer",align:e.align??"left",sortValue:e.sortValue??(r=>F(r)),formatter:e.formatter??(r=>{const i=F(r.value);return i==null?"":oe(i,t.durationFormat??"h:mm:ss")}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:r.newValue==null||r.newValue===""?null:typeof r.newValue=="number"||typeof r.newValue=="object"&&Qe(r.newValue)!=null?r.newValue:V(r.newValue))}),cell:Je},{id:"vote",get label(){return l("fields.typeVote")},get description(){return l("fields.typeVoteDescription")},icon:u.vote,group:"basic",width:100,defaults:{icon:"up"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"segmented",choices:[c("up","fields.choiceArrow"),c("thumb","fields.choiceThumb"),c("heart","fields.choiceHeart")]},M],fill:e=>({...e,editorType:e.editorType??"fieldVote",editorOptions:e.editorOptions??W().map(t=>({value:t.id,label:t.name})),align:e.align??"left",sortValue:e.sortValue??(t=>de(t)),formatter:e.formatter??(t=>String(de(t.value))),valueParser:e.valueParser??(t=>Ze(De(!0)(t)))}),newRowValue:()=>[],cell:qe},{id:"sparkline",get label(){return l("fields.typeSparkline")},get description(){return l("fields.typeSparklineDescription")},icon:u.sparkline,group:"number",width:160,defaults:{chart:"line"},properties:[{key:"chart",get label(){return l("fields.propChart")},kind:"segmented",choices:[c("line","fields.choiceLine"),c("area","fields.choiceArea"),c("bar","fields.choiceColumns")]},M,{key:"showLast",get label(){return l("fields.propShowLast")},kind:"checkbox"}],fill:e=>({...e,formatter:e.formatter??(t=>z(t.value).join(", ")),valueParser:e.valueParser??(t=>{const r=z(t.newValue);return r.length?r:null}),sortValue:e.sortValue??(t=>z(t).at(-1)??null)}),cell:et},{id:"formula",get label(){return l("fields.typeFormula")},get description(){return l("fields.typeFormulaDescription")},icon:u.formula,group:"computed",width:160,defaults:{formula:"",result:"auto"},properties:[{key:"formula",get label(){return l("fields.propFormula")},kind:"formula"},{key:"result",get label(){return l("fields.propResult")},kind:"choice",choices:[c("auto","fields.choiceAsComputed"),c("number","fields.choiceNumber"),c("currency","fields.choiceCurrency"),c("percent","fields.choicePercent"),c("date","fields.choiceDate")]},X(K(0,8),e=>["number","currency","percent"].includes(e.result)),{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$",visible:e=>e.result==="currency"},I(e=>e.result==="date")],fill:(e,t,r)=>{const i=Ce(r.columns),o=String(t.formula??""),n=String(e.field??e.id),a=new Set([n.toLowerCase(),typeof e.header=="string"?e.header.trim().toLowerCase():""].filter(Boolean)),d=s=>{const p=s.trim().toLowerCase(),f=i[p]??null;if(f===n||f==null&&a.has(p))throw lt(s);return f};let g=null;try{g=o.trim()?tt(o,d).fn:()=>null}catch{g=null}let m=null;const S=()=>{if(m)return m;m=new Map;for(const s of r.columns){if(s.fieldType==="richText"){const h=String(s.field??s.id);m.set(h,k=>A(k?.[h]));continue}if(s.fieldType==="timer"){const h=String(s.field??s.id);m.set(h,k=>F(k?.[h]));continue}const p=Mt(s);if(p){m.set(String(s.field??s.id),p);continue}if(!ce.has(String(s.fieldType))||String(s.field??s.id)===n)continue;const f=O(s,r.columns);typeof f.fieldFn=="function"&&m.set(String(s.field??s.id),f.fieldFn)}return m},P=s=>{const p=S();return!p.size||!s?s:new Proxy(s,{get:(f,h)=>{const k=typeof h=="string"?p.get(h):void 0;if(!k||w>3)return f[h];w+=1;try{return k(f)}finally{w-=1}}})};return{...e,...y(e),fieldFn:s=>g?g(P(s)):"#ERROR",align:e.align??(["number","currency","percent"].includes(t.result)?"right":void 0),formatter:e.formatter??(s=>ee(s.value,t))}}},{id:"createdTime",get label(){return l("fields.typeCreatedTime")},get description(){return l("fields.typeCreatedTimeDescription")},icon:u.createdTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour"},properties:[I(),...Y],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L(),onCreate:({rows:e})=>e.map(()=>L())},{id:"lastModifiedTime",get label(){return l("fields.typeLastModifiedTime")},get description(){return l("fields.typeLastModifiedTimeDescription")},icon:u.modifiedTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour",watch:"all"},properties:[...Ae,I(),...Y],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L()},{id:"createdBy",get label(){return l("fields.typeCreatedBy")},get description(){return l("fields.typeCreatedByDescription")},icon:u.createdBy,group:"computed",width:160,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>fe()?.id??null,cell:B},{id:"lastModifiedBy",get label(){return l("fields.typeLastModifiedBy")},get description(){return l("fields.typeLastModifiedByDescription")},icon:u.modifiedBy,group:"computed",width:160,defaults:{watch:"all"},properties:Ae,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>fe()?.id??null,cell:B},{id:"autoNumber",get label(){return l("fields.typeAutoNumber")},get description(){return l("fields.typeAutoNumberDescription")},icon:u.autoNumber,group:"computed",width:100,fill:e=>({...e,...y(e),cellDataType:e.cellDataType??"number"}),newRowValue:({rows:e,field:t})=>e.reduce((r,i)=>Math.max(r,Number(i?.[t])||0),0)+1,onCreate:({rows:e})=>e.map((t,r)=>r+1)},{id:"link",get label(){return l("fields.typeLink")},get description(){return l("fields.typeLinkDescription")},icon:u.link,group:"relation",width:200,defaults:{multiple:!0},properties:[{key:"table",get label(){return l("fields.propTable")},kind:"choice",choices:()=>nt().map(e=>({value:e.id,label:e.name})),get hint(){return l("fields.propTableHint")},alsoSets:()=>({pickFrom:""})},{key:"multiple",get label(){return l("fields.propMultipleRecords")},kind:"checkbox"},{key:"pickFrom",get label(){return l("fields.propPickFrom")},kind:"choice",choices:e=>[{value:"",label:l("fields.pickFromAll")},...(T(e.props.table)?.views?.()??[]).filter(t=>!t.personal&&t.type!=="form").map(t=>({value:t.id,label:t.name}))],visible:e=>!!e.table,get hint(){return l("fields.propPickFromHint")}}],fill:(e,t)=>({...e,editorType:e.editorType??"fieldLink",formatter:e.formatter??(r=>{const i=T(t.table);return G(i,r.value).map(o=>String(o[i.primaryField]??"")).join(", ")}),valueParser:e.valueParser??_t(t),groupValue:e.groupValue??(r=>ot(t.table,r)),groupCopies:!0}),cell:Ne},{id:"lookup",get label(){return l("fields.typeLookup")},get description(){return l("fields.typeLookupDescription")},icon:u.lookup,group:"relation",width:180,properties:[Z,Te],fill:(e,t,r)=>{const i=te(t,r),o=n=>{const a=re(i,t.field);return String(a?a({value:n})??"":n)};return{...e,...y(e),fieldSource:()=>i?.table?.fields?.find(n=>n.field===String(t.field)),fieldFn:n=>{if(!i)return[];const a=x(i.table,String(t.field)),d=i.stored;return d?d.records.allLinkedTo(d.field,String(n?.id??"")).map(a):i.rowsOf(n).map(a)},formatter:e.formatter??(n=>Array.isArray(n.value)?n.value.filter(a=>a!=null&&a!=="").map(o).join(", "):n.value==null?"":o(n.value))}}},{id:"rollup",get label(){return l("fields.typeRollup")},get description(){return l("fields.typeRollupDescription")},icon:u.rollup,group:"relation",width:140,defaults:{aggregation:"SUM"},properties:[Z,Te,{key:"aggregation",get label(){return l("fields.propAggregation")},kind:"choice",choices:Object.keys(_).map(e=>({value:e,label:e}))},X(K(0,8),e=>["SUM","AVERAGE","MIN","MAX"].includes(e.aggregation))],fill:(e,t,r)=>{const i=te(t,r),o=_[String(t.aggregation)]??_.SUM,n=String(i?.table?.fields?.find(s=>s.field===String(t.field))?.fieldType??""),a=["MIN","MAX"].includes(String(t.aggregation))&&["date","createdTime","lastModifiedTime"].includes(n),d=!a&&!ce.has(n),g=!a&&["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL"].includes(String(t.aggregation)),m=["SUM","AVERAGE","MIN","MAX"].includes(String(t.aggregation)),S=s=>{const p=m?re(i,t.field,t.precision):void 0;return p?String(p({value:s})??""):H(s,{precision:we(t,0)})},P=s=>{const p=re(i,t.field),f=s instanceof Date?s.toISOString():s;return String(p?p({value:f})??"":f??"")};return{...e,...y(e),...g?{cellDataType:e.cellDataType??"number"}:{},...a?{cellDataType:e.cellDataType??"dateString"}:{},align:e.align??(g?"right":void 0),fieldSource:()=>i?.table?.fields?.find(s=>s.field===String(t.field)),fieldFn:s=>{if(!i)return null;const p=x(i.table,String(t.field)),f=i.stored;if(f&&!d)return o(f.records.allLinkedTo(f.field,String(s?.id??"")).map(p));if(f){const h=String(s?.id??""),k=$t[String(t.aggregation)];return k?f.records.total(f.field,h,String(t.field),k)??null:t.aggregation==="COUNTA"||t.aggregation==="COUNTALL"?f.records.total(f.field,h)??null:o(f.records.allLinkedTo(f.field,h).map(p))}return o(i.rowsOf(s).map(p))},formatter:e.formatter??(s=>{if(a)return s.value==null||s.value===""?"":P(s.value);const p=g?U(s.value):typeof s.value=="number"?s.value:null;return p==null?String(s.value??""):S(p)})}}},{id:"count",get label(){return l("fields.typeCount")},get description(){return l("fields.typeCountDescription")},icon:u.count,group:"relation",width:90,properties:[Z],fill:(e,t,r)=>{const i=te(t,r);return{...e,...y(e),cellDataType:e.cellDataType??"number",formatter:o=>o.value==null?"":Number(o.value).toLocaleString(),fieldFn:o=>{if(!i)return 0;const n=i.stored;return n?n.records.total(n.field,String(o?.id??""))??null:i.rowsOf(o).length}}}},dt];
@@ -14,6 +14,11 @@ export type FilterOp = 'contains' | 'notContains' | 'is' | 'isNot' | 'isEmpty' |
14
14
  export type DateTarget = {
15
15
  mode: 'today' | 'tomorrow' | 'yesterday' | 'oneWeekAgo' | 'oneWeekFromNow' | 'oneMonthAgo' | 'oneMonthFromNow';
16
16
  }
17
+ /** A number of days from today, or before it: a reminder 3 days before a due date. */
18
+ | {
19
+ mode: 'daysFromNow' | 'daysAgo';
20
+ days: number;
21
+ }
17
22
  /** `at`: the moment that day starts for the viewer, for a field that holds moments, which a server has no zone to work out. */
18
23
  | {
19
24
  mode: 'exactDate';