@svgrid/enterprise 3.1.41 → 3.1.42

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.
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>SvGrid Studio - Designer</title>
7
- <script type="module" crossorigin src="./assets/index-OcSC-rI4.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-CZZrEXgj.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-Dd_uD5pT.js">
9
9
  <link rel="modulepreload" crossorigin href="./assets/index-client-CwjHmKgT.js">
10
10
  <link rel="modulepreload" crossorigin href="./assets/disclose-version-xihTtKlq.js">
@@ -48,7 +48,7 @@
48
48
  <link rel="stylesheet" crossorigin href="./assets/SvGridChart-BgLuPO7I.css">
49
49
  <link rel="stylesheet" crossorigin href="./assets/SvGridChartPanel-4Pc8y5yO.css">
50
50
  <link rel="stylesheet" crossorigin href="./assets/SvMenuList-B6nq5Yhh.css">
51
- <link rel="stylesheet" crossorigin href="./assets/index-axFTZtlf.css">
51
+ <link rel="stylesheet" crossorigin href="./assets/index-DY182YW4.css">
52
52
  </head>
53
53
  <body>
54
54
  <div id="app"></div>
@@ -106,6 +106,17 @@ import{safeColor}from"./palette";import{primaryOf}from"./base-tables";import{get
106
106
  </div>
107
107
  <textarea class="sv-fvb-input sv-baac-text" aria-label={bm('extras.message')} rows="3" value={action.text} placeholder={lookText} onchange={(e) => onChange({ ...action, text: e.currentTarget.value })}></textarea>
108
108
  <p class="sv-baac-hint">{bm(action.service === 'teams' ? 'extras.chatHintTeams' : action.service === 'googleChat' ? 'extras.chatHintGoogle' : 'extras.chatHintSlack')}</p>
109
+ {:else if action.type === 'textMessage'}
110
+ {#if !serverSide}<p class="sv-baac-hint sv-baac-bad">{bm('extras.textNeedsServer')}</p>{/if}
111
+ <div class="sv-baac-row">
112
+ <span class="sv-baac-label">{bm('extras.textBy')}</span>
113
+ <select class="sv-fvb-select" aria-label={bm('extras.textBy')} value={action.channel ?? 'sms'} onchange={(e) => onChange({ ...action, channel: e.currentTarget.value === 'viber' ? 'viber' : 'sms' })}>
114
+ <option value="sms">{bm('extras.textSms')}</option><option value="viber">{bm('extras.textViber')}</option>
115
+ </select>
116
+ </div>
117
+ <div class="sv-baac-row"><span class="sv-baac-label">{bm('extras.textTo')}</span><input class="sv-fvb-input" aria-label={bm('extras.textTo')} value={action.to} placeholder={bm('extras.textToPlaceholder')} onchange={(e) => onChange({ ...action, to: e.currentTarget.value })} /></div>
118
+ <textarea class="sv-fvb-input sv-baac-text" aria-label={bm('extras.textMessage')} rows="3" value={action.text} placeholder={lookText} onchange={(e) => onChange({ ...action, text: e.currentTarget.value })}></textarea>
119
+ <p class="sv-baac-hint">{bm('extras.textHint')}</p>
109
120
  {:else if action.type === 'if'}
110
121
  <p class="sv-baac-hint">{bm('extras.ifHint')}</p>
111
122
  <div class="sv-baac-cond">
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import{untrack}from"svelte";import{SvSwitchButton,announce}from"@svgrid/grid";import FilterPanel from"./viewbar/FilterPanel.svelte";import AutomationTrigger from"./AutomationTrigger.svelte";import AutomationActionEditor from"./AutomationAction.svelte";import{primaryOf,rowIdOf}from"./base-tables";import{actionLabel,tableFields,triggerText}from"./automations.svelte";import{actionChoices,actionKey,newAction,newAutomation,newTrigger}from"./automation-edit";import{bm,bmCount}from"./messages.svelte";let{tables,onChange,runner,serverRuns,onServer=false,runOnServer,records,webhookUrl,scriptsInPage=false,height="100%"}=$props();const snapshot=list=>JSON.parse(JSON.stringify(list));let lists=$state(Object.fromEntries(tables.map(t=>[t.id,snapshot(t.automations??[])])));const tableOf=id=>tables.find(t=>t.id===id);const entries=$derived(tables.flatMap(t=>(lists[t.id]??[]).map(a=>({table:t,a}))));let picked=$state(entries[0]?{table:entries[0].table.id,id:entries[0].a.id}:null);const current=$derived(entries.find(e=>e.table.id===picked?.table&&e.a.id===picked?.id)??null);let part=$state("trigger");let tab=$state("edit");let inserting=$state(null);const side=a=>onServer?"server":a.runOn??"browser";const ACTIONS=$derived(actionChoices());function save(tableId,next){lists={...lists,[tableId]:next};onChange(tableId,snapshot(next))}function patch(change){const c=current;if(!c)return;save(c.table.id,(lists[c.table.id]??[]).map(a=>a.id===c.a.id?{...a,...change}:a))}function pick(tableId,id){picked={table:tableId,id};part="trigger";tab="edit";inserting=null;tryError=""}function create(){const t=current?.table??tables[0];if(!t)return;const a=newAutomation(t);save(t.id,[...lists[t.id]??[],a]);pick(t.id,a.id)}let deleting=$state(false);function remove(){const c=current;if(!c)return;save(c.table.id,(lists[c.table.id]??[]).filter(a=>a.id!==c.a.id));deleting=false;const next=entries.find(e=>!(e.table.id===c.table.id&&e.a.id===c.a.id));picked=next?{table:next.table.id,id:next.a.id}:null;part="trigger"}function moveTo(tableId){const c=current;const to=tableOf(tableId);if(!c||!to||to.id===c.table.id)return;const actions=c.a.actions.map(x=>{if(x.type==="updateRecord")return{...x,values:{}};if(x.type==="createRecord")return{type:"createRecord",table:x.table,values:x.table===c.table.id?{}:x.values};if(x.type==="highlight")return{...x,fields:[]};if(x.type==="if")return{...x,condition:void 0,then:[],else:[]};if(x.type==="ai")return{...x,field:void 0};return x});const type=c.a.trigger.type;const moved={...c.a,trigger:newTrigger(type,to),condition:void 0,actions};save(c.table.id,(lists[c.table.id]??[]).filter(a=>a.id!==c.a.id));save(to.id,[...lists[to.id]??[],moved]);picked={table:to.id,id:moved.id}}const EMPTY={kind:"fieldFilter",conjunction:"and",conditions:[]};function standIn(t){const cols=[...tableFields(t).values()];return{internalColumns:cols.map(c=>({...c.def,id:c.id})),allColumns:cols.map(c=>({id:c.id})),hiddenColumns:{}}}const ctrl=$derived(current?standIn(current.table):null);function setCondition(f){patch({condition:f.conditions.length?f:void 0})}function setAction(i,next){const c=current;if(!c)return;const actions=[...c.a.actions];if(next)actions[i]=next;else actions.splice(i,1);patch({actions});if(!next)part=actions.length?Math.min(i,actions.length-1):"trigger"}function insert(at,value){const c=current;if(!c||!value)return;const actions=[...c.a.actions];actions.splice(at,0,newAction(value,c.table));patch({actions});inserting=null;part=at}function moveAction(i,dir){const c=current;if(!c)return;const actions=[...c.a.actions];const j=i+dir;if(j<0||j>=actions.length)return;[actions[i],actions[j]]=[actions[j],actions[i]];patch({actions});part=j;announce(bm("extras.stepMoved",{from:i+1,to:j+1}))}function summary(t,x){switch(x.type){case"updateRecord":{const names=Object.keys(x.values).map(id=>tableFields(t).get(id)?.header??id);return names.length?bm("extras.summarySet",{fields:names.join(", ")}):bm("extras.summaryNothing")}case"createRecord":return bm("extras.summaryCreate",{table:tableOf(x.table)?.name??x.table});case"notify":return x.message;case"highlight":return bm("extras.summaryColor");case"webhook":return`${x.method??"POST"} ${x.url}`;case"email":return x.to?bm("extras.summaryEmail",{to:x.to}):bm("extras.summaryNoTo");case"chat":return x.text||bm("extras.summaryNoText");case"repeat":return bm("extras.summaryRepeat",{table:tableOf(x.table)?.name??x.table,steps:bmCount("extras.stepCount",(x.actions??[]).length)});case"if":return bm("extras.summaryIf",{then:bmCount("extras.stepCount",(x.then??[]).length),otherwise:bmCount("extras.stepCount",(x.else??[]).length)});case"ai":return x.prompt||bm("extras.summaryNoText");case"script":return bm("extras.summaryScript",{lines:x.code.split("\n").filter(l=>l.trim()&&!l.trim().startsWith("//")).length});default:return""}}const whenText=(t,a)=>triggerText(t,{...a,condition:void 0});const ICONS={trigger:"M13 2 4 14h7l-1 8 9-12h-7l1-8z",condition:"M3 5h18l-7 8v6l-4 2v-8L3 5z",updateRecord:"M4 20h4L19 9l-4-4L4 16v4zM14 6l4 4",createRecord:"M4 4h16v16H4zM12 8v8M8 12h8",notify:"M6 16V11a6 6 0 0 1 12 0v5l2 2H4l2-2zM10 21h4",highlight:"M12 3s6 7 6 11a6 6 0 0 1-12 0c0-4 6-11 6-11z",webhook:"M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",run:"M7 4v16l13-8z",chat:"M4 5h16v11H9l-5 4V5z",repeat:"M17 2l3 3-3 3M4 11V9a4 4 0 0 1 4-4h12M7 22l-3-3 3-3M20 13v2a4 4 0 0 1-4 4H4",if:"M6 3v6a4 4 0 0 0 4 4h8M15 10l3 3-3 3M6 13v8",ai:"M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z",script:"M8 7l-5 5 5 5M16 7l5 5-5 5"};let tryRecord=$state("");let tryError=$state("");let testRows=$state.raw([]);const testTable=$derived(current?.table.id??"");$effect(()=>{const id=testTable;untrack(()=>{const t=tableOf(id);tryRecord="";testRows=[];if(!t)return;const take=rows=>{if(testTable!==id)return;testRows=rows;if(!tryRecord&&rows[0])tryRecord=rowIdOf(t,rows[0])};if(records)void records(t.id).then(take,()=>take([]));else if(t.source?.server&&runner)void runner.firstRecords(t.id,200).then(take);else take((t.data??[]).filter(Boolean).slice(0,200))})});const testChoices=$derived(current?testRows.map(r=>({id:rowIdOf(current.table,r),name:String(r[primaryOf(current.table)]??"")||bm("extras.noName")})):[]);const canTest=$derived(!!current&&(side(current.a)==="server"&&!!runOnServer||side(current.a)!=="server"&&!!runner));function test(){const c=current;if(!c)return;const a=JSON.parse(JSON.stringify(c.a));tryError="";if(side(a)==="server"&&runOnServer){runOnServer(a,c.table.id,tryRecord||null).then(()=>showRuns(),e=>{tryError=e instanceof Error?e.message:String(e);showRuns()});return}if(runner){void runner.runNow(a,c.table.id,tryRecord||null);showRuns()}}let fromServer=$state.raw([]);let serverError=$state("");let onlyThis=$state(true);function showRuns(){tab="runs";if(!serverRuns)return;serverRuns().then(r=>{fromServer=r;serverError=""},e=>serverError=e instanceof Error?e.message:String(e))}const allRuns=$derived([...(runner?.runs??[]).map(r=>({...r,side:"browser"})),...fromServer.map(r=>({...r,side:"server"}))].sort((x,y)=>y.at-x.at));const shownRuns=$derived(onlyThis&&current?allRuns.filter(r=>r.automationId===current.a.id):allRuns);const time=at=>new Date(at).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"});
2
+ import{untrack}from"svelte";import{SvSwitchButton,announce}from"@svgrid/grid";import FilterPanel from"./viewbar/FilterPanel.svelte";import AutomationTrigger from"./AutomationTrigger.svelte";import AutomationActionEditor from"./AutomationAction.svelte";import{primaryOf,rowIdOf}from"./base-tables";import{actionLabel,tableFields,triggerText}from"./automations.svelte";import{actionChoices,actionKey,newAction,newAutomation,newTrigger}from"./automation-edit";import{bm,bmCount}from"./messages.svelte";let{tables,onChange,runner,serverRuns,onServer=false,runOnServer,records,webhookUrl,scriptsInPage=false,height="100%"}=$props();const snapshot=list=>JSON.parse(JSON.stringify(list));let lists=$state(Object.fromEntries(tables.map(t=>[t.id,snapshot(t.automations??[])])));const tableOf=id=>tables.find(t=>t.id===id);const entries=$derived(tables.flatMap(t=>(lists[t.id]??[]).map(a=>({table:t,a}))));let picked=$state(entries[0]?{table:entries[0].table.id,id:entries[0].a.id}:null);const current=$derived(entries.find(e=>e.table.id===picked?.table&&e.a.id===picked?.id)??null);let part=$state("trigger");let tab=$state("edit");let inserting=$state(null);const side=a=>onServer?"server":a.runOn??"browser";const ACTIONS=$derived(actionChoices());function save(tableId,next){lists={...lists,[tableId]:next};onChange(tableId,snapshot(next))}function patch(change){const c=current;if(!c)return;save(c.table.id,(lists[c.table.id]??[]).map(a=>a.id===c.a.id?{...a,...change}:a))}function pick(tableId,id){picked={table:tableId,id};part="trigger";tab="edit";inserting=null;tryError=""}function create(){const t=current?.table??tables[0];if(!t)return;const a=newAutomation(t);save(t.id,[...lists[t.id]??[],a]);pick(t.id,a.id)}let deleting=$state(false);function remove(){const c=current;if(!c)return;save(c.table.id,(lists[c.table.id]??[]).filter(a=>a.id!==c.a.id));deleting=false;const next=entries.find(e=>!(e.table.id===c.table.id&&e.a.id===c.a.id));picked=next?{table:next.table.id,id:next.a.id}:null;part="trigger"}function moveTo(tableId){const c=current;const to=tableOf(tableId);if(!c||!to||to.id===c.table.id)return;const actions=c.a.actions.map(x=>{if(x.type==="updateRecord")return{...x,values:{}};if(x.type==="createRecord")return{type:"createRecord",table:x.table,values:x.table===c.table.id?{}:x.values};if(x.type==="highlight")return{...x,fields:[]};if(x.type==="if")return{...x,condition:void 0,then:[],else:[]};if(x.type==="ai")return{...x,field:void 0};return x});const type=c.a.trigger.type;const moved={...c.a,trigger:newTrigger(type,to),condition:void 0,actions};save(c.table.id,(lists[c.table.id]??[]).filter(a=>a.id!==c.a.id));save(to.id,[...lists[to.id]??[],moved]);picked={table:to.id,id:moved.id}}const EMPTY={kind:"fieldFilter",conjunction:"and",conditions:[]};function standIn(t){const cols=[...tableFields(t).values()];return{internalColumns:cols.map(c=>({...c.def,id:c.id})),allColumns:cols.map(c=>({id:c.id})),hiddenColumns:{}}}const ctrl=$derived(current?standIn(current.table):null);function setCondition(f){patch({condition:f.conditions.length?f:void 0})}function setAction(i,next){const c=current;if(!c)return;const actions=[...c.a.actions];if(next)actions[i]=next;else actions.splice(i,1);patch({actions});if(!next)part=actions.length?Math.min(i,actions.length-1):"trigger"}function insert(at,value){const c=current;if(!c||!value)return;const actions=[...c.a.actions];actions.splice(at,0,newAction(value,c.table));patch({actions});inserting=null;part=at}function moveAction(i,dir){const c=current;if(!c)return;const actions=[...c.a.actions];const j=i+dir;if(j<0||j>=actions.length)return;[actions[i],actions[j]]=[actions[j],actions[i]];patch({actions});part=j;announce(bm("extras.stepMoved",{from:i+1,to:j+1}))}function summary(t,x){switch(x.type){case"updateRecord":{const names=Object.keys(x.values).map(id=>tableFields(t).get(id)?.header??id);return names.length?bm("extras.summarySet",{fields:names.join(", ")}):bm("extras.summaryNothing")}case"createRecord":return bm("extras.summaryCreate",{table:tableOf(x.table)?.name??x.table});case"notify":return x.message;case"highlight":return bm("extras.summaryColor");case"webhook":return`${x.method??"POST"} ${x.url}`;case"email":return x.to?bm("extras.summaryEmail",{to:x.to}):bm("extras.summaryNoTo");case"chat":return x.text||bm("extras.summaryNoText");case"textMessage":return x.to?bm(x.channel==="viber"?"extras.summaryViber":"extras.summarySms",{to:x.to}):bm("extras.summaryNoPhone");case"repeat":return bm("extras.summaryRepeat",{table:tableOf(x.table)?.name??x.table,steps:bmCount("extras.stepCount",(x.actions??[]).length)});case"if":return bm("extras.summaryIf",{then:bmCount("extras.stepCount",(x.then??[]).length),otherwise:bmCount("extras.stepCount",(x.else??[]).length)});case"ai":return x.prompt||bm("extras.summaryNoText");case"script":return bm("extras.summaryScript",{lines:x.code.split("\n").filter(l=>l.trim()&&!l.trim().startsWith("//")).length});default:return""}}const whenText=(t,a)=>triggerText(t,{...a,condition:void 0});const ICONS={trigger:"M13 2 4 14h7l-1 8 9-12h-7l1-8z",condition:"M3 5h18l-7 8v6l-4 2v-8L3 5z",updateRecord:"M4 20h4L19 9l-4-4L4 16v4zM14 6l4 4",createRecord:"M4 4h16v16H4zM12 8v8M8 12h8",notify:"M6 16V11a6 6 0 0 1 12 0v5l2 2H4l2-2zM10 21h4",highlight:"M12 3s6 7 6 11a6 6 0 0 1-12 0c0-4 6-11 6-11z",webhook:"M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",run:"M7 4v16l13-8z",chat:"M4 5h16v11H9l-5 4V5z",textMessage:"M7 2h10a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1zM11 18h2",repeat:"M17 2l3 3-3 3M4 11V9a4 4 0 0 1 4-4h12M7 22l-3-3 3-3M20 13v2a4 4 0 0 1-4 4H4",if:"M6 3v6a4 4 0 0 0 4 4h8M15 10l3 3-3 3M6 13v8",ai:"M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z",script:"M8 7l-5 5 5 5M16 7l5 5-5 5"};let tryRecord=$state("");let tryError=$state("");let testRows=$state.raw([]);const testTable=$derived(current?.table.id??"");$effect(()=>{const id=testTable;untrack(()=>{const t=tableOf(id);tryRecord="";testRows=[];if(!t)return;const take=rows=>{if(testTable!==id)return;testRows=rows;if(!tryRecord&&rows[0])tryRecord=rowIdOf(t,rows[0])};if(records)void records(t.id).then(take,()=>take([]));else if(t.source?.server&&runner)void runner.firstRecords(t.id,200).then(take);else take((t.data??[]).filter(Boolean).slice(0,200))})});const testChoices=$derived(current?testRows.map(r=>({id:rowIdOf(current.table,r),name:String(r[primaryOf(current.table)]??"")||bm("extras.noName")})):[]);const canTest=$derived(!!current&&(side(current.a)==="server"&&!!runOnServer||side(current.a)!=="server"&&!!runner));function test(){const c=current;if(!c)return;const a=JSON.parse(JSON.stringify(c.a));tryError="";if(side(a)==="server"&&runOnServer){runOnServer(a,c.table.id,tryRecord||null).then(()=>showRuns(),e=>{tryError=e instanceof Error?e.message:String(e);showRuns()});return}if(runner){void runner.runNow(a,c.table.id,tryRecord||null);showRuns()}}let fromServer=$state.raw([]);let serverError=$state("");let onlyThis=$state(true);function showRuns(){tab="runs";if(!serverRuns)return;serverRuns().then(r=>{fromServer=r;serverError=""},e=>serverError=e instanceof Error?e.message:String(e))}const allRuns=$derived([...(runner?.runs??[]).map(r=>({...r,side:"browser"})),...fromServer.map(r=>({...r,side:"server"}))].sort((x,y)=>y.at-x.at));const shownRuns=$derived(onlyThis&&current?allRuns.filter(r=>r.automationId===current.a.id):allRuns);const time=at=>new Date(at).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"});
3
3
  </script>
4
4
 
5
5
  {#snippet mark(kind: string)}
@@ -201,5 +201,5 @@ import{untrack}from"svelte";import{SvSwitchButton,announce}from"@svgrid/grid";im
201
201
  </div>
202
202
 
203
203
  <style>
204
- .sv-bap{display:grid;grid-template-columns:280px minmax(0,1fr) 400px;min-height:0;font-size:13px;color:var(--sg-fg, #0f172a);background:var(--sg-bg, #fff)}.sv-bap:has(.sv-bap-history),.sv-bap:has(.sv-bap-none){grid-template-columns:280px minmax(0,1fr)}.sv-bap-list{display:flex;flex-direction:column;gap:8px;padding:12px;min-height:0;border-right:1px solid var(--sg-border, #e2e8f0)}.sv-bap-create{height:34px;border:0;border-radius:8px;background:var(--sg-accent, #2563eb);color:var(--sg-accent-fg, #fff);font:inherit;font-weight:600;cursor:pointer}.sv-bap-create:disabled{opacity:.5;cursor:default}.sv-bap-items{flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:2px}.sv-bap-item{display:flex;align-items:center;gap:6px;padding:4px 6px 4px 4px;border-radius:8px}.sv-bap-item.is-on{background:color-mix(in srgb,var(--sg-accent, #2563eb) 12%,transparent)}.sv-bap-pick{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px;padding:6px;border:0;background:none;color:inherit;font:inherit;text-align:left;cursor:pointer;border-radius:6px}.sv-bap-name{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sv-bap-when{font-size:12px;color:var(--sg-muted, #64748b);display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.sv-bap-runs{display:flex;align-items:center;justify-content:center;gap:6px;height:32px;border:1px solid var(--sg-border, #cbd5e1);border-radius:8px;background:none;color:inherit;font:inherit;cursor:pointer}.sv-bap-runs.is-on{border-color:var(--sg-accent, #2563eb);color:var(--sg-accent, #2563eb)}.sv-bap-count{min-width:18px;padding:0 5px;border-radius:999px;font-size:11px;font-weight:700;background:color-mix(in srgb,var(--sg-fg, #0f172a) 10%,transparent);text-align:center}.sv-bap-canvas{min-width:0;min-height:0;overflow:auto;padding:28px 20px 40px;background-color:color-mix(in srgb,var(--sg-fg, #0f172a) 3%,var(--sg-bg, #fff));background-image:radial-gradient(color-mix(in srgb,var(--sg-fg, #0f172a) 12%,transparent) 1px,transparent 1px);background-size:18px 18px}.sv-bap-none{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;text-align:center}.sv-bap-flow{display:flex;flex-direction:column;align-items:center;max-width:440px;margin:0 auto}.sv-bap-card{width:100%;display:flex;flex-direction:column;gap:4px;padding:14px 16px;border:1px solid var(--sg-border, #e2e8f0);border-radius:12px;background:var(--sg-bg, #fff);color:inherit;font:inherit;text-align:left;cursor:pointer;box-shadow:0 1px 2px #0f172a0f}.sv-bap-card:hover{border-color:color-mix(in srgb,var(--sg-accent, #2563eb) 45%,var(--sg-border, #e2e8f0))}.sv-bap-card.is-on{border-color:var(--sg-accent, #2563eb);box-shadow:0 0 0 3px color-mix(in srgb,var(--sg-accent, #2563eb) 18%,transparent)}.sv-bap-card.is-trigger{border-top:4px solid var(--sg-accent, #2563eb)}.sv-bap-card.is-condition.is-empty .sv-bap-title{color:var(--sg-muted, #64748b);font-weight:500}.sv-bap-kind{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:var(--sg-muted, #64748b)}.sv-bap-title{font-size:14px;font-weight:600;line-height:1.35}.sv-bap-sub{font-size:12px;color:var(--sg-muted, #64748b);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sv-bap-icon{flex:none;padding:4px;border-radius:6px;color:var(--sg-accent, #2563eb);background:color-mix(in srgb,var(--sg-accent, #2563eb) 12%,transparent)}.sv-bap-icon[data-kind=condition]{color:#7c3aed;background:color-mix(in srgb,#7c3aed 12%,transparent)}.sv-bap-icon[data-kind=email],.sv-bap-icon[data-kind=webhook]{color:#0d9488;background:color-mix(in srgb,#0d9488 12%,transparent)}.sv-bap-icon[data-kind=updateRecord],.sv-bap-icon[data-kind=createRecord]{color:#d97706;background:color-mix(in srgb,#d97706 12%,transparent)}.sv-bap-icon[data-kind=chat]{color:#0d9488;background:color-mix(in srgb,#0d9488 12%,transparent)}.sv-bap-icon[data-kind=if],.sv-bap-icon[data-kind=repeat]{color:#2563eb;background:color-mix(in srgb,#2563eb 12%,transparent)}.sv-bap-icon[data-kind=ai]{color:#7c3aed;background:color-mix(in srgb,#7c3aed 12%,transparent)}.sv-bap-icon[data-kind=script]{color:#334155;background:color-mix(in srgb,#334155 12%,transparent)}.sv-bap-name-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:end}.sv-bap-name-row>:global(:last-child){margin-bottom:6px}.sv-bap-n{display:inline-grid;place-items:center;width:18px;height:18px;border-radius:50%;font-size:10px;background:var(--sg-fg, #0f172a);color:var(--sg-bg, #fff);letter-spacing:0}.sv-bap-line{width:2px;height:14px;background:var(--sg-border, #cbd5e1)}.sv-bap-plus{width:24px;height:24px;border:1px solid var(--sg-border, #cbd5e1);border-radius:50%;background:var(--sg-bg, #fff);color:var(--sg-muted, #64748b);font:inherit;font-size:15px;line-height:1;cursor:pointer}.sv-bap-plus:hover{color:var(--sg-accent, #2563eb);border-color:var(--sg-accent, #2563eb)}.sv-bap-insert{margin-top:6px;max-width:260px}.sv-bap-add{max-width:260px}.sv-bap-settings{display:flex;flex-direction:column;gap:14px;min-height:0;overflow:auto;padding:16px;border-left:1px solid var(--sg-border, #e2e8f0)}.sv-bap-head{display:grid;gap:10px}.sv-bap-field{display:grid;gap:4px}.sv-bap-field>span{color:var(--sg-muted, #64748b);font-size:12px}.sv-bap-part{display:grid;grid-template-columns:minmax(0,1fr);gap:8px;padding:12px 14px;border:1px solid var(--sg-border, #e2e8f0);border-radius:10px}.sv-bap-part :global(.sv-ff-row),.sv-bap-part :global(.sv-ff-group .sv-ff-row){grid-template-columns:minmax(0,1fr) minmax(0,1fr) 28px}.sv-bap-part :global(.sv-ff-conj){grid-column:1 / -1;padding-top:0}.sv-bap-part :global(.sv-ff-value){grid-column:1 / 3}.sv-bap-part :global(.sv-ff-group){grid-column:1 / -1}.sv-bap-badge{margin:0;font-size:11px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:var(--sg-muted, #64748b)}.sv-bap-action-head{display:grid;grid-template-columns:minmax(0,1fr) 26px 26px 26px;gap:6px;align-items:center}.sv-bap-hint{margin:0;font-size:12px;color:var(--sg-muted, #64748b)}.sv-bap-bad{color:var(--sg-danger, #dc2626)}.sv-bap-foot{margin-top:auto;display:grid;gap:8px;padding-top:12px;border-top:1px solid var(--sg-border, #e2e8f0)}.sv-bap-test{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:8px;align-items:end}.sv-bap-delete{display:flex;align-items:center;gap:8px}.sv-bap-danger{border:0;background:none;padding:0;font:inherit;color:var(--sg-danger, #dc2626);cursor:pointer}.sv-bap-danger:hover{text-decoration:underline}.sv-bap-empty{margin:8px 4px;color:var(--sg-muted, #64748b);line-height:1.5}.sv-bap-history{min-width:0;min-height:0;overflow:auto;padding:16px 20px;display:flex;flex-direction:column;gap:10px}.sv-bap-history-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.sv-bap-history-head h3{margin:0 auto 0 0;font-size:15px}.sv-bap-check{display:inline-flex;align-items:center;gap:6px;color:var(--sg-muted, #64748b)}.sv-bap-run{padding:10px 12px;border:1px solid var(--sg-border, #e2e8f0);border-radius:8px}.sv-bap-run-head{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap}.sv-bap-status{font-size:11px;font-weight:700;padding:1px 7px;border-radius:999px;color:#fff;background:var(--sg-success, #16a34a)}.sv-bap-run[data-status=error] .sv-bap-status{background:var(--sg-danger, #dc2626)}.sv-bap-run[data-status=stopped] .sv-bap-status{background:var(--sg-warning, #d97706)}.sv-bap-tag{font-size:11px;font-weight:600;padding:0 6px;border-radius:4px;border:1px solid var(--sg-border, #cbd5e1);color:var(--sg-muted, #64748b)}.sv-bap-muted{color:var(--sg-muted, #64748b)}.sv-bap-time{margin-left:auto;font-variant-numeric:tabular-nums}.sv-bap-run ul{margin:6px 0 0;padding-left:18px}.sv-bap-run li>span{font-weight:600}.sv-bap-run li.is-error{color:var(--sg-danger, #dc2626)}@media(max-width:1200px){.sv-bap{grid-template-columns:230px minmax(0,1fr) 320px}.sv-bap:has(.sv-bap-history),.sv-bap:has(.sv-bap-none){grid-template-columns:230px minmax(0,1fr)}}@media(max-width:860px){.sv-bap,.sv-bap:has(.sv-bap-history),.sv-bap:has(.sv-bap-none){grid-template-columns:220px minmax(0,1fr)}.sv-bap-settings{grid-column:2;border-left:0;border-top:1px solid var(--sg-border, #e2e8f0)}}@media(max-width:720px){.sv-bap,.sv-bap:has(.sv-bap-history),.sv-bap:has(.sv-bap-none){grid-template-columns:minmax(0,1fr);height:auto!important}.sv-bap-list,.sv-bap-settings{grid-column:auto;border-right:0;border-left:0}.sv-bap-list{border-bottom:1px solid var(--sg-border, #e2e8f0)}}
204
+ .sv-bap{display:grid;grid-template-columns:280px minmax(0,1fr) 400px;min-height:0;font-size:13px;color:var(--sg-fg, #0f172a);background:var(--sg-bg, #fff)}.sv-bap:has(.sv-bap-history),.sv-bap:has(.sv-bap-none){grid-template-columns:280px minmax(0,1fr)}.sv-bap-list{display:flex;flex-direction:column;gap:8px;padding:12px;min-height:0;border-right:1px solid var(--sg-border, #e2e8f0)}.sv-bap-create{height:34px;border:0;border-radius:8px;background:var(--sg-accent, #2563eb);color:var(--sg-accent-fg, #fff);font:inherit;font-weight:600;cursor:pointer}.sv-bap-create:disabled{opacity:.5;cursor:default}.sv-bap-items{flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:2px}.sv-bap-item{display:flex;align-items:center;gap:6px;padding:4px 6px 4px 4px;border-radius:8px}.sv-bap-item.is-on{background:color-mix(in srgb,var(--sg-accent, #2563eb) 12%,transparent)}.sv-bap-pick{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px;padding:6px;border:0;background:none;color:inherit;font:inherit;text-align:left;cursor:pointer;border-radius:6px}.sv-bap-name{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sv-bap-when{font-size:12px;color:var(--sg-muted, #64748b);display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.sv-bap-runs{display:flex;align-items:center;justify-content:center;gap:6px;height:32px;border:1px solid var(--sg-border, #cbd5e1);border-radius:8px;background:none;color:inherit;font:inherit;cursor:pointer}.sv-bap-runs.is-on{border-color:var(--sg-accent, #2563eb);color:var(--sg-accent, #2563eb)}.sv-bap-count{min-width:18px;padding:0 5px;border-radius:999px;font-size:11px;font-weight:700;background:color-mix(in srgb,var(--sg-fg, #0f172a) 10%,transparent);text-align:center}.sv-bap-canvas{min-width:0;min-height:0;overflow:auto;padding:28px 20px 40px;background-color:color-mix(in srgb,var(--sg-fg, #0f172a) 3%,var(--sg-bg, #fff));background-image:radial-gradient(color-mix(in srgb,var(--sg-fg, #0f172a) 12%,transparent) 1px,transparent 1px);background-size:18px 18px}.sv-bap-none{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;text-align:center}.sv-bap-flow{display:flex;flex-direction:column;align-items:center;max-width:440px;margin:0 auto}.sv-bap-card{width:100%;display:flex;flex-direction:column;gap:4px;padding:14px 16px;border:1px solid var(--sg-border, #e2e8f0);border-radius:12px;background:var(--sg-bg, #fff);color:inherit;font:inherit;text-align:left;cursor:pointer;box-shadow:0 1px 2px #0f172a0f}.sv-bap-card:hover{border-color:color-mix(in srgb,var(--sg-accent, #2563eb) 45%,var(--sg-border, #e2e8f0))}.sv-bap-card.is-on{border-color:var(--sg-accent, #2563eb);box-shadow:0 0 0 3px color-mix(in srgb,var(--sg-accent, #2563eb) 18%,transparent)}.sv-bap-card.is-trigger{border-top:4px solid var(--sg-accent, #2563eb)}.sv-bap-card.is-condition.is-empty .sv-bap-title{color:var(--sg-muted, #64748b);font-weight:500}.sv-bap-kind{display:inline-flex;align-items:center;gap:6px;font-size:11px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:var(--sg-muted, #64748b)}.sv-bap-title{font-size:14px;font-weight:600;line-height:1.35}.sv-bap-sub{font-size:12px;color:var(--sg-muted, #64748b);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sv-bap-icon{flex:none;padding:4px;border-radius:6px;color:var(--sg-accent, #2563eb);background:color-mix(in srgb,var(--sg-accent, #2563eb) 12%,transparent)}.sv-bap-icon[data-kind=condition]{color:#7c3aed;background:color-mix(in srgb,#7c3aed 12%,transparent)}.sv-bap-icon[data-kind=email],.sv-bap-icon[data-kind=webhook]{color:#0d9488;background:color-mix(in srgb,#0d9488 12%,transparent)}.sv-bap-icon[data-kind=updateRecord],.sv-bap-icon[data-kind=createRecord]{color:#d97706;background:color-mix(in srgb,#d97706 12%,transparent)}.sv-bap-icon[data-kind=chat],.sv-bap-icon[data-kind=textMessage]{color:#0d9488;background:color-mix(in srgb,#0d9488 12%,transparent)}.sv-bap-icon[data-kind=if],.sv-bap-icon[data-kind=repeat]{color:#2563eb;background:color-mix(in srgb,#2563eb 12%,transparent)}.sv-bap-icon[data-kind=ai]{color:#7c3aed;background:color-mix(in srgb,#7c3aed 12%,transparent)}.sv-bap-icon[data-kind=script]{color:#334155;background:color-mix(in srgb,#334155 12%,transparent)}.sv-bap-name-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:end}.sv-bap-name-row>:global(:last-child){margin-bottom:6px}.sv-bap-n{display:inline-grid;place-items:center;width:18px;height:18px;border-radius:50%;font-size:10px;background:var(--sg-fg, #0f172a);color:var(--sg-bg, #fff);letter-spacing:0}.sv-bap-line{width:2px;height:14px;background:var(--sg-border, #cbd5e1)}.sv-bap-plus{width:24px;height:24px;border:1px solid var(--sg-border, #cbd5e1);border-radius:50%;background:var(--sg-bg, #fff);color:var(--sg-muted, #64748b);font:inherit;font-size:15px;line-height:1;cursor:pointer}.sv-bap-plus:hover{color:var(--sg-accent, #2563eb);border-color:var(--sg-accent, #2563eb)}.sv-bap-insert{margin-top:6px;max-width:260px}.sv-bap-add{max-width:260px}.sv-bap-settings{display:flex;flex-direction:column;gap:14px;min-height:0;overflow:auto;padding:16px;border-left:1px solid var(--sg-border, #e2e8f0)}.sv-bap-head{display:grid;gap:10px}.sv-bap-field{display:grid;gap:4px}.sv-bap-field>span{color:var(--sg-muted, #64748b);font-size:12px}.sv-bap-part{display:grid;grid-template-columns:minmax(0,1fr);gap:8px;padding:12px 14px;border:1px solid var(--sg-border, #e2e8f0);border-radius:10px}.sv-bap-part :global(.sv-ff-row),.sv-bap-part :global(.sv-ff-group .sv-ff-row){grid-template-columns:minmax(0,1fr) minmax(0,1fr) 28px}.sv-bap-part :global(.sv-ff-conj){grid-column:1 / -1;padding-top:0}.sv-bap-part :global(.sv-ff-value){grid-column:1 / 3}.sv-bap-part :global(.sv-ff-group){grid-column:1 / -1}.sv-bap-badge{margin:0;font-size:11px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:var(--sg-muted, #64748b)}.sv-bap-action-head{display:grid;grid-template-columns:minmax(0,1fr) 26px 26px 26px;gap:6px;align-items:center}.sv-bap-hint{margin:0;font-size:12px;color:var(--sg-muted, #64748b)}.sv-bap-bad{color:var(--sg-danger, #dc2626)}.sv-bap-foot{margin-top:auto;display:grid;gap:8px;padding-top:12px;border-top:1px solid var(--sg-border, #e2e8f0)}.sv-bap-test{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:8px;align-items:end}.sv-bap-delete{display:flex;align-items:center;gap:8px}.sv-bap-danger{border:0;background:none;padding:0;font:inherit;color:var(--sg-danger, #dc2626);cursor:pointer}.sv-bap-danger:hover{text-decoration:underline}.sv-bap-empty{margin:8px 4px;color:var(--sg-muted, #64748b);line-height:1.5}.sv-bap-history{min-width:0;min-height:0;overflow:auto;padding:16px 20px;display:flex;flex-direction:column;gap:10px}.sv-bap-history-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.sv-bap-history-head h3{margin:0 auto 0 0;font-size:15px}.sv-bap-check{display:inline-flex;align-items:center;gap:6px;color:var(--sg-muted, #64748b)}.sv-bap-run{padding:10px 12px;border:1px solid var(--sg-border, #e2e8f0);border-radius:8px}.sv-bap-run-head{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap}.sv-bap-status{font-size:11px;font-weight:700;padding:1px 7px;border-radius:999px;color:#fff;background:var(--sg-success, #16a34a)}.sv-bap-run[data-status=error] .sv-bap-status{background:var(--sg-danger, #dc2626)}.sv-bap-run[data-status=stopped] .sv-bap-status{background:var(--sg-warning, #d97706)}.sv-bap-tag{font-size:11px;font-weight:600;padding:0 6px;border-radius:4px;border:1px solid var(--sg-border, #cbd5e1);color:var(--sg-muted, #64748b)}.sv-bap-muted{color:var(--sg-muted, #64748b)}.sv-bap-time{margin-left:auto;font-variant-numeric:tabular-nums}.sv-bap-run ul{margin:6px 0 0;padding-left:18px}.sv-bap-run li>span{font-weight:600}.sv-bap-run li.is-error{color:var(--sg-danger, #dc2626)}@media(max-width:1200px){.sv-bap{grid-template-columns:230px minmax(0,1fr) 320px}.sv-bap:has(.sv-bap-history),.sv-bap:has(.sv-bap-none){grid-template-columns:230px minmax(0,1fr)}}@media(max-width:860px){.sv-bap,.sv-bap:has(.sv-bap-history),.sv-bap:has(.sv-bap-none){grid-template-columns:220px minmax(0,1fr)}.sv-bap-settings{grid-column:2;border-left:0;border-top:1px solid var(--sg-border, #e2e8f0)}}@media(max-width:720px){.sv-bap,.sv-bap:has(.sv-bap-history),.sv-bap:has(.sv-bap-none){grid-template-columns:minmax(0,1fr);height:auto!important}.sv-bap-list,.sv-bap-settings{grid-column:auto;border-right:0;border-left:0}.sv-bap-list{border-bottom:1px solid var(--sg-border, #e2e8f0)}}
205
205
  </style>
@@ -1,4 +1,4 @@
1
- import{CRON_PRESETS as i}from"../scheduling.js";import{primaryOf as n}from"./base-tables.js";import{listAutomationActions as s,tableFields as c}from"./automations.svelte.js";import{bm as r}from"./messages.svelte.js";export const COMPUTED_TYPES=new Set(["formula","lookup","rollup","count","button","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy"]),fieldsOf=e=>e?[...c(e).values()]:[],writableFields=e=>fieldsOf(e).filter(t=>!COMPUTED_TYPES.has(String(t.fieldType??""))),TRIGGER_CHOICES=[{value:"recordCreated",key:"extras.triggerCreated"},{value:"recordUpdated",key:"extras.triggerUpdated"},{value:"recordMatches",key:"extras.triggerMatches"},{value:"formSubmitted",key:"extras.triggerForm"},{value:"button",key:"extras.triggerButton"},{value:"scheduled",key:"extras.triggerScheduled"},{value:"webhookReceived",key:"extras.triggerWebhook"}];export function newWebhookToken(){const e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(t=>t.toString(16).padStart(2,"0")).join("")}export function newTrigger(e,t){switch(e){case"recordUpdated":return{type:e,fields:[]};case"formSubmitted":return{type:e};case"button":return{type:e,field:fieldsOf(t).find(a=>a.fieldType==="button")?.id??""};case"scheduled":return{type:e,cron:i[3].cron};case"webhookReceived":return{type:e,token:newWebhookToken()};default:return{type:e}}}export function actionChoices(e=0){const t=[{value:"updateRecord",label:r("extras.doUpdateRecord")},{value:"createRecord",label:r("extras.doCreateRecord")},{value:"repeat",label:r("extras.doRepeat")},{value:"if",label:r("extras.doIf")},{value:"notify",label:r("extras.actionNotify")},{value:"highlight",label:r("extras.doHighlight")},{value:"email",label:r("extras.actionEmail")},{value:"chat",label:r("extras.doChat")},{value:"webhook",label:r("extras.actionWebhook")},{value:"ai",label:r("extras.doAi")},{value:"script",label:r("extras.doScript")},...s().map(a=>({value:`run:${a.id}`,label:a.label}))];return e?t.filter(a=>a.value!=="script"&&a.value!=="highlight"&&(e<2||a.value!=="if"&&a.value!=="repeat")):t}export function newAction(e,t){if(e.startsWith("run:"))return{type:"run",action:e.slice(4)};switch(e){case"updateRecord":return{type:"updateRecord",values:{}};case"createRecord":return{type:"createRecord",table:t.id,values:{}};case"highlight":return{type:"highlight",background:"#fee2e2",color:"#991b1b"};case"webhook":return{type:"webhook",url:"https://",body:""};case"email":return{type:"email",to:"",subject:"",body:""};case"chat":return{type:"chat",service:"slack",url:"https://hooks.slack.com/services/",text:""};case"repeat":return{type:"repeat",table:t.id,limit:100,actions:[]};case"if":return{type:"if",then:[],else:[]};case"ai":return{type:"ai",prompt:""};case"script":return{type:"script",code:SCRIPT_START};default:return{type:"notify",message:"",severity:"info"}}}export const SCRIPT_START=`// The record that set it off: input.config() has its fields by name.
1
+ import{CRON_PRESETS as i}from"../scheduling.js";import{primaryOf as s}from"./base-tables.js";import{listAutomationActions as n,tableFields as c}from"./automations.svelte.js";import{bm as t}from"./messages.svelte.js";export const COMPUTED_TYPES=new Set(["formula","lookup","rollup","count","button","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy"]),fieldsOf=e=>e?[...c(e).values()]:[],writableFields=e=>fieldsOf(e).filter(r=>!COMPUTED_TYPES.has(String(r.fieldType??""))),TRIGGER_CHOICES=[{value:"recordCreated",key:"extras.triggerCreated"},{value:"recordUpdated",key:"extras.triggerUpdated"},{value:"recordMatches",key:"extras.triggerMatches"},{value:"formSubmitted",key:"extras.triggerForm"},{value:"button",key:"extras.triggerButton"},{value:"scheduled",key:"extras.triggerScheduled"},{value:"webhookReceived",key:"extras.triggerWebhook"}];export function newWebhookToken(){const e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(r=>r.toString(16).padStart(2,"0")).join("")}export function newTrigger(e,r){switch(e){case"recordUpdated":return{type:e,fields:[]};case"formSubmitted":return{type:e};case"button":return{type:e,field:fieldsOf(r).find(a=>a.fieldType==="button")?.id??""};case"scheduled":return{type:e,cron:i[3].cron};case"webhookReceived":return{type:e,token:newWebhookToken()};default:return{type:e}}}export function actionChoices(e=0){const r=[{value:"updateRecord",label:t("extras.doUpdateRecord")},{value:"createRecord",label:t("extras.doCreateRecord")},{value:"repeat",label:t("extras.doRepeat")},{value:"if",label:t("extras.doIf")},{value:"notify",label:t("extras.actionNotify")},{value:"highlight",label:t("extras.doHighlight")},{value:"email",label:t("extras.actionEmail")},{value:"chat",label:t("extras.doChat")},{value:"textMessage",label:t("extras.doText")},{value:"webhook",label:t("extras.actionWebhook")},{value:"ai",label:t("extras.doAi")},{value:"script",label:t("extras.doScript")},...n().map(a=>({value:`run:${a.id}`,label:a.label}))];return e?r.filter(a=>a.value!=="script"&&a.value!=="highlight"&&(e<2||a.value!=="if"&&a.value!=="repeat")):r}export function newAction(e,r){if(e.startsWith("run:"))return{type:"run",action:e.slice(4)};switch(e){case"updateRecord":return{type:"updateRecord",values:{}};case"createRecord":return{type:"createRecord",table:r.id,values:{}};case"highlight":return{type:"highlight",background:"#fee2e2",color:"#991b1b"};case"webhook":return{type:"webhook",url:"https://",body:""};case"email":return{type:"email",to:"",subject:"",body:""};case"chat":return{type:"chat",service:"slack",url:"https://hooks.slack.com/services/",text:""};case"textMessage":return{type:"textMessage",channel:"sms",to:"",text:""};case"repeat":return{type:"repeat",table:r.id,limit:100,actions:[]};case"if":return{type:"if",then:[],else:[]};case"ai":return{type:"ai",prompt:""};case"script":return{type:"script",code:SCRIPT_START};default:return{type:"notify",message:"",severity:"info"}}}export const SCRIPT_START=`// The record that set it off: input.config() has its fields by name.
2
2
  const config = input.config()
3
3
  console.log('Record', config.recordId)
4
4
 
@@ -9,4 +9,4 @@ console.log('Record', config.recordId)
9
9
 
10
10
  // Hand values to the next steps as {script.name}:
11
11
  // output.set('name', 'value')
12
- `,actionKey=e=>e.type==="run"?`run:${e.action}`:e.type;export function newAutomation(e){const t=fieldsOf(e),a=t.find(o=>o.id===n(e))??t[0];return{id:`auto-${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,name:r("extras.newAutomation"),enabled:!0,trigger:{type:"recordCreated"},actions:[{type:"notify",message:r("extras.newRecordMessage",{field:a?.header??r("extras.nameFallback")})}]}}
12
+ `,actionKey=e=>e.type==="run"?`run:${e.action}`:e.type;export function newAutomation(e){const r=fieldsOf(e),a=r.find(o=>o.id===s(e))??r[0];return{id:`auto-${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,name:t("extras.newAutomation"),enabled:!0,trigger:{type:"recordCreated"},actions:[{type:"notify",message:t("extras.newRecordMessage",{field:a?.header??t("extras.nameFallback")})}]}}
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Automation actions that leave the base: call a webhook, send an email.
2
+ * Automation actions that leave the base: call a webhook, send an email, a
3
+ * chat message or a text message.
3
4
  *
4
5
  * Both fill `{Field name}` tokens from the record. A webhook may also name
5
6
  * secrets, `{secret:SLACK_TOKEN}`, which only the server runner reads (from
@@ -28,6 +29,17 @@ export type EmailAction = {
28
29
  subject: string;
29
30
  body: string;
30
31
  };
32
+ /**
33
+ * A text message to phones, sent by the server runner's `sendText` (your SMS
34
+ * or Viber provider). `channel` "viber" asks for Viber, with an SMS to a phone
35
+ * that is not on Viber when the provider can send one. `to` and `text` name fields.
36
+ */
37
+ export type TextMessageAction = {
38
+ type: 'textMessage';
39
+ channel?: 'sms' | 'viber';
40
+ to: string;
41
+ text: string;
42
+ };
31
43
  /**
32
44
  * A message to a chat channel through its incoming webhook: Slack's
33
45
  * "Incoming Webhooks", a Teams channel's "Post to a channel when a webhook
@@ -70,4 +82,11 @@ export type OutgoingEmail = {
70
82
  text: string;
71
83
  };
72
84
  export declare function sendEmailAction(action: EmailAction, ctx: OutboundContext, send: ((email: OutgoingEmail) => Promise<unknown> | unknown) | undefined): Promise<string>;
85
+ /** A text message as `sendText` gets it: the phones as written, the text filled in. */
86
+ export type OutgoingText = {
87
+ to: string[];
88
+ text: string;
89
+ channel: 'sms' | 'viber';
90
+ };
91
+ export declare function sendTextAction(action: TextMessageAction, ctx: OutboundContext, send: ((message: OutgoingText) => Promise<unknown> | unknown) | undefined): Promise<string>;
73
92
  export {};
@@ -1 +1 @@
1
- export function chatPayload(t,e){return t==="teams"?{type:"message",attachments:[{contentType:"application/vnd.microsoft.card.adaptive",contentUrl:null,content:{$schema:"http://adaptivecards.io/schemas/adaptive-card.json",type:"AdaptiveCard",version:"1.4",body:[{type:"TextBlock",text:e,wrap:!0}]}}]}:{text:e}}export function chatHostOk(t,e){const o=e.hostname.toLowerCase();return e.protocol!=="https:"?!1:t==="slack"?o==="hooks.slack.com":t==="googleChat"?o==="chat.googleapis.com":/(^|\.)logic\.azure\.com$/.test(o)||/(^|\.)powerplatform\.com$/.test(o)||/(^|\.)webhook\.office\.com$/.test(o)}export async function sendChat(t,e){const o=i(t.url,e,encodeURIComponent);let s;try{s=new URL(o)}catch{throw new Error("The chat address is not a URL")}if(!chatHostOk(t.service,s))throw new Error(`That is not a ${t.service==="googleChat"?"Google Chat":t.service==="teams"?"Teams":"Slack"} webhook address`);const r=e.fill(t.text);if(!r.trim())throw new Error("The message is empty");const n=e.fetch??globalThis.fetch;if(!n)throw new Error("No fetch here to send the message with");const a=await n(o,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(chatPayload(t.service,r))});if(!a.ok)throw new Error(`${s.host} answered ${a.status}`);return r.length>120?r.slice(0,117)+"...":r}const p=/\{([^{}\n]+)\}/g,m=/^secret:([A-Za-z0-9_.-]+)$/;function y(t,e){if(!e.secret)throw new Error(`{secret:${t}} is read on the server only; run this automation on the server`);const o=e.secret(t);if(o==null)throw new Error(`No secret named ${t}`);return o}function i(t,e,o=r=>r,s=r=>r){return t.replace(p,(r,n)=>{const a=m.exec(n);if(a)return s(y(a[1],e));const h=e.fill(r);return h===r?r:o(h)})}const f=t=>JSON.stringify(t).slice(1,-1);export async function callWebhook(t,e){if(!(e.fetch??globalThis.fetch))throw new Error("No fetch here to call the webhook with");const o=i(t.url,e,encodeURIComponent);if(!/^https?:\/\//i.test(o))throw new Error("A webhook URL starts with https:// or http://");const r=(e.checkUrl?await e.checkUrl(new URL(o)):void 0)??e.fetch??globalThis.fetch,n={"content-type":"application/json"};for(const[u,w]of Object.entries(t.headers??{}))n[u.toLowerCase()]=i(w,e);const a=(n["content-type"]??"").includes("json"),h=t.body?.trim()?a?i(t.body,e,f,f):i(t.body,e):JSON.stringify({automation:e.automation,table:e.table,record:e.record?{id:e.record.id??null,...e.fields()}:null}),l=t.method??"POST",c=await r(o,{method:l,headers:n,body:h,...e.checkUrl?{redirect:"manual"}:{}}),d=(()=>{try{return new URL(o).host}catch{return o}})();if(!c.ok)throw new Error(`${l} ${d} answered ${c.status}${c.statusText?` ${c.statusText}`:""}`);return`${l} ${d}: ${c.status}`}export async function sendEmailAction(t,e,o){if(!o)throw new Error("Email is sent by the server runner; give createAutomationServer a sendEmail");const s=e.fill(t.to).split(/\s*[,;]\s*/).filter(Boolean);if(!s.length)throw new Error("No address to send to");return await o({to:s,subject:e.fill(t.subject),text:e.fill(t.body)}),`To ${s.join(", ")}: ${e.fill(t.subject)}`}
1
+ export function chatPayload(t,e){return t==="teams"?{type:"message",attachments:[{contentType:"application/vnd.microsoft.card.adaptive",contentUrl:null,content:{$schema:"http://adaptivecards.io/schemas/adaptive-card.json",type:"AdaptiveCard",version:"1.4",body:[{type:"TextBlock",text:e,wrap:!0}]}}]}:{text:e}}export function chatHostOk(t,e){const r=e.hostname.toLowerCase();return e.protocol!=="https:"?!1:t==="slack"?r==="hooks.slack.com":t==="googleChat"?r==="chat.googleapis.com":/(^|\.)logic\.azure\.com$/.test(r)||/(^|\.)powerplatform\.com$/.test(r)||/(^|\.)webhook\.office\.com$/.test(r)}export async function sendChat(t,e){const r=c(t.url,e,encodeURIComponent);let s;try{s=new URL(r)}catch{throw new Error("The chat address is not a URL")}if(!chatHostOk(t.service,s))throw new Error(`That is not a ${t.service==="googleChat"?"Google Chat":t.service==="teams"?"Teams":"Slack"} webhook address`);const o=e.fill(t.text);if(!o.trim())throw new Error("The message is empty");const n=e.fetch??globalThis.fetch;if(!n)throw new Error("No fetch here to send the message with");const a=await n(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(chatPayload(t.service,o))});if(!a.ok)throw new Error(`${s.host} answered ${a.status}`);return o.length>120?o.slice(0,117)+"...":o}const p=/\{([^{}\n]+)\}/g,m=/^secret:([A-Za-z0-9_.-]+)$/;function y(t,e){if(!e.secret)throw new Error(`{secret:${t}} is read on the server only; run this automation on the server`);const r=e.secret(t);if(r==null)throw new Error(`No secret named ${t}`);return r}function c(t,e,r=o=>o,s=o=>o){return t.replace(p,(o,n)=>{const a=m.exec(n);if(a)return s(y(a[1],e));const h=e.fill(o);return h===o?o:r(h)})}const d=t=>JSON.stringify(t).slice(1,-1);export async function callWebhook(t,e){if(!(e.fetch??globalThis.fetch))throw new Error("No fetch here to call the webhook with");const r=c(t.url,e,encodeURIComponent);if(!/^https?:\/\//i.test(r))throw new Error("A webhook URL starts with https:// or http://");const o=(e.checkUrl?await e.checkUrl(new URL(r)):void 0)??e.fetch??globalThis.fetch,n={"content-type":"application/json"};for(const[u,w]of Object.entries(t.headers??{}))n[u.toLowerCase()]=c(w,e);const a=(n["content-type"]??"").includes("json"),h=t.body?.trim()?a?c(t.body,e,d,d):c(t.body,e):JSON.stringify({automation:e.automation,table:e.table,record:e.record?{id:e.record.id??null,...e.fields()}:null}),l=t.method??"POST",i=await o(r,{method:l,headers:n,body:h,...e.checkUrl?{redirect:"manual"}:{}}),f=(()=>{try{return new URL(r).host}catch{return r}})();if(!i.ok)throw new Error(`${l} ${f} answered ${i.status}${i.statusText?` ${i.statusText}`:""}`);return`${l} ${f}: ${i.status}`}export async function sendEmailAction(t,e,r){if(!r)throw new Error("Email is sent by the server runner; give createAutomationServer a sendEmail");const s=e.fill(t.to).split(/\s*[,;]\s*/).filter(Boolean);if(!s.length)throw new Error("No address to send to");return await r({to:s,subject:e.fill(t.subject),text:e.fill(t.body)}),`To ${s.join(", ")}: ${e.fill(t.subject)}`}export async function sendTextAction(t,e,r){if(!r)throw new Error("Text messages are sent by the server runner; give createAutomationServer a sendText");const s=e.fill(t.to).split(/\s*[,;]\s*/).map(a=>a.trim()).filter(Boolean);if(!s.length)throw new Error("No phone number to send to");const o=e.fill(t.text).trim();if(!o)throw new Error("The message is empty");const n=t.channel==="viber"?"viber":"sms";return await r({to:s,text:o,channel:n}),`${n==="viber"?"Viber":"SMS"} to ${s.join(", ")}`}
@@ -1,6 +1,6 @@
1
1
  import { type BaseTable } from './base-tables.js';
2
2
  import { type AutomationRun } from './automations.svelte.js';
3
- import { type OutgoingEmail } from './automation-outbound.js';
3
+ import { type OutgoingEmail, type OutgoingText } from './automation-outbound.js';
4
4
  type Row = Record<string, unknown>;
5
5
  /** What `createKitHandlers` hands its `audit` hook, as far as this server reads it. */
6
6
  type AuditEntry = {
@@ -38,6 +38,8 @@ export type AutomationServerOptions = {
38
38
  resolveHost?: (host: string) => Promise<string[]>;
39
39
  /** Sends the "Send an email" action: your mail provider. */
40
40
  sendEmail?: (email: OutgoingEmail) => Promise<unknown> | unknown;
41
+ /** Sends the "Send a text message" action: your SMS or Viber provider. */
42
+ sendText?: (message: OutgoingText) => Promise<unknown> | unknown;
41
43
  /** "Show a notice" on the server: log it, push it to the people concerned. */
42
44
  notify?: (notice: AutomationNotice) => void;
43
45
  /** Each run as it finishes, with what each action did. */
@@ -1 +1 @@
1
- import{cronMatches as ue}from"../scheduling.js";import{primaryOf as H,rowIdOf as m,syncAllInverses as le}from"./base-tables.js";import{newRecordId as de}from"./field-ops.js";import{registerLinkedTable as he}from"./sources.svelte.js";import{MAX_DEPTH as Z,REPEAT_MOST as pe,actionLabel as me,automationsFor as we,triggerValues as ge,webhookValues as ye,fieldValueFrom as I,fillTokens as ee,matches as L,outbound as V,runAppAction as be,tableFields as M}from"./automations.svelte.js";import{callWebhook as ke,sendChat as ve,sendEmailAction as Se}from"./automation-outbound.js";import{checkedFetch as Ee}from"./automation-address.js";let $e=0;const Oe=1e4,_=(g,T)=>JSON.stringify(g??null)===JSON.stringify(T??null);export function createAutomationServer(g){const T=g.now??(()=>new Date),q=g.keepRuns??200;let S=g.tables.map(e=>({...e,data:[]})),F=null,j=!1;const R=new Map,te=(e,n)=>{const t=R.get(e)??new Set;R.set(e,t),t.add(n),t.size>Oe&&t.delete(t.values().next().value)},D=(e,n)=>!!R.get(e)?.delete(n),J=new WeakSet;let x=Promise.resolve();const P=[],z=new Map,K=e=>typeof g.secrets=="function"?g.secrets(e):g.secrets?.[e],Q=g.allowInternalWebhooks?null:e=>Ee(e,g.resolveHost,g.fetch),y=e=>S.find(n=>n.id===e),A=e=>{if(!e.source)throw new Error(`Table ${e.name} has no source`);return e.source};function $(e,n){S=S.map(t=>t.id===e?{...t,data:n(t.data)}:t);for(const t of S)S=le(S,t.id)}function O(){return F??(F=(async()=>{for(const e of S){const n=await A(e).load({whole:!0});$(e.id,()=>n)}for(const e of S){const n=e.id;he({id:n,name:e.name,rows:()=>y(n)?.data??[],getRowId:t=>m(y(n)??e,t),primaryField:H(e),fields:e.columns.filter(t=>t.field).map(t=>({field:String(t.field),header:String(t.header??t.field),fieldType:t.fieldType,fieldProps:t.fieldProps}))})}j=!0})().catch(e=>{throw F=null,e})),F}function B(e,n,t){const i=[];for(const r of M(e).values())_(n[r.field],t[r.field])||i.push(r.id);return i}async function C(e,n,t={}){await O();const i=y(e);if(!i)throw new Error(`No table "${e}"`);const r=l=>l?t.db===!1?l:A(i).toPage(l):null,a=r(n.after),c=r(n.before);if(!a){const l=String(c?.id??"");return $(e,h=>h.filter(u=>m(i,u)!==l)),te(e,l),[]}const s=String(a.id),o=i.data.find(l=>m(i,l)===s),w={...o??{},...a},d=!!o&&!B(i,o,w).length;if(o&&(d||t.first)){if(!t.first)return[];d||$(e,v=>v.map(G=>G===o?w:G));const l=y(e).data.find(v=>m(i,v)===s)??w;if(t.first.created)return E({type:"created",table:e,record:l});const h=t.first.values?r(t.first.values):{},u=[...M(i).values()].filter(v=>v.field in h).map(v=>v.id),k=Object.fromEntries(Object.keys(h).map(v=>[v,void 0]));return u.length?E({type:"updated",table:e,record:l,before:{...l,...k},fields:u}):[]}const p=c?{...o??{},...c}:o;$(e,l=>o?l.map(h=>h===o?w:h):[...l,w]);const f=y(e).data.find(l=>m(i,l)===s);if(!p)return D(e,s)?[]:E({type:"created",table:e,record:f});const b=B(i,p,f);return b.length?E({type:"updated",table:e,record:f,before:p,fields:b}):[]}async function U(e){await O();const n=y(e);if(!n)throw new Error(`No table "${e}"`);const t=await A(n).load({whole:!0}),i=new Map(n.data.map(a=>[m(n,a),a]));$(e,()=>t);const r=[];for(const a of y(e).data){const c=i.get(m(n,a));if(!c)D(e,m(n,a))||r.push(...await E({type:"created",table:e,record:a}));else{const s=B(n,c,a);s.length&&r.push(...await E({type:"updated",table:e,record:a,before:c,fields:s}))}}return r}function ne(e,n){const t=async r=>{if(r.action==="purge"){r.id!=null&&R.get(e)?.delete(String(r.id));return}const a=r.event&&typeof r.event=="object"?r.event:null;!j&&a&&J.add(a);const c=!j||!!a&&J.has(a);if(r.action==="delete"){await C(e,{before:{id:r.id},after:null},{db:!1});return}if(r.action==="restore"){await O(),r.id!=null&&await re(e,String(r.id));return}if(!r.result){await U(e);return}await C(e,{after:r.result},c?{first:{created:r.action==="create",...r.values?{values:r.values}:{}}}:{})};return Object.assign(async r=>{try{n&&await n(r)}finally{await t(r)}},{before:()=>O()})}async function re(e,n){const t=y(e);if(!t)return;D(e,n);const i=A(t),a=(i.read?await i.read([n]):(await i.load({whole:!0})).filter(c=>m(t,c)===n))[0];a&&$(e,c=>[...c.filter(s=>m(t,s)!==n),a])}async function ie(e,n,t){await O();const i=await X(e,n);return i?E({type:"form",table:e,record:i,view:t}):[]}async function oe(e,n,t){await O();const i=await X(e,n);return i?E({type:"button",table:e,record:i,field:t}):[]}async function X(e,n){const t=y(e);if(!t)return null;let i=t.data.find(r=>m(t,r)===n);return i||(await U(e),i=y(e).data.find(r=>m(t,r)===n)),i??null}async function ae(e,n){await O();const t=[];if(!e)return t;for(const i of S)for(const r of i.automations??[])!r.enabled||r.runOn!=="server"||r.trigger.type!=="webhookReceived"||r.trigger.token!==e||t.push(await N(r,i.id,null,0,ye(n)));return t}async function se(e=T()){await O();const n=`${e.getFullYear()}-${e.getMonth()}-${e.getDate()} ${e.getHours()}:${e.getMinutes()}`,t=[];for(const i of S)for(const r of i.automations??[]){if(!r.enabled||r.runOn!=="server"||r.trigger.type!=="scheduled")continue;const a=`${i.id}:${r.id}`;if(!(z.get(a)===n||!ue(r.trigger.cron,e)))if(z.set(a,n),!r.condition)t.push(await N(r,i.id,null,0));else for(const c of y(i.id).data)L(i,r.condition,c)&&t.push(await N(r,i.id,m(i,c),0))}return t}async function E(e){const n=y(e.table);if(!n)return[];const t="depth"in e?e.depth??0:0,i=[];for(const r of we(n,e,"server"))i.push(await N(r,n.id,m(n,e.record),t));return i}function N(e,n,t,i,r=new Map){const a=x.then(()=>ce(e,n,t,i,r));return x=a.catch(()=>{}),a}async function ce(e,n,t,i,r){const a=y(n),c=t==null?null:a.data.find(o=>m(a,o)===t)??null,s={id:++$e,automationId:e.id,name:e.name,table:a.name,record:c?String(c[H(a)]??t):null,at:T().getTime(),status:"ok",steps:[]};if(i>=Z)s.status="stopped",s.steps.push({action:"Stopped",detail:`Automations set each other off ${Z} times in a row; this one did not run, so they cannot loop.`});else{const o=[];await W(e,e.actions,n,t,i,o,s,r),Y(s);for(const w of o)w();return s}return Y(s),s}function Y(e){P.unshift(e),P.length>q&&(P.length=q),g.onRun?.(e)}async function W(e,n,t,i,r,a,c,s){for(const o of n)try{const w=y(t),d=i==null?null:w.data.find(f=>m(w,f)===i)??null;if(o.type==="if"){const f=d?L(w,o.condition,d):!o.condition?.conditions?.length;if(c.steps.push({action:"If",detail:f?"It matched: the Then steps ran":"It did not match: the Otherwise steps ran"}),!await W(e,(f?o.then:o.else)??[],t,i,r,a,c,s))return!1;continue}if(o.type==="repeat"){const f=y(o.table);if(!f)throw new Error(`No table "${o.table}"`);const b=Math.max(1,Math.min(pe,o.limit??100)),l=f.data.filter(u=>L(f,o.condition,u)).slice(0,b).map(u=>m(f,u));c.steps.push({action:"Find records",detail:`${l.length} in ${f.name}`});const h=ge(w,d,s);h.set("found",String(l.length));for(const u of l)if(!await W(e,o.actions??[],f.id,u,r,a,c,h))return!1;continue}const p=await fe(e,o,t,i,r,a,s);p&&c.steps.push(p)}catch(w){return c.status="error",c.steps.push({action:me(o),detail:"",error:w instanceof Error?w.message:String(w)}),!1}return!0}async function fe(e,n,t,i,r,a,c){const s=y(t),o=i==null?null:s.data.find(d=>m(s,d)===i)??null,w={tables:S,from:s,record:o,now:T(),values:c};switch(n.type){case"notify":{const d=ee(s,o,n.message,c);return g.notify?.({message:d,severity:n.severity??"info",automation:e.name,table:s.name,record:o}),{action:"Notice",detail:d}}case"highlight":return null;case"updateRecord":{if(!o||i==null)return{action:"Update record",detail:"No record to update"};const d=M(s),p={};for(const[u,k]of Object.entries(n.values)){const v=d.get(u);v&&(p[v.field]=I(s,v.def,k,w))}const f={...o,...p},b=Object.keys(p).filter(u=>!_(o[u],f[u]));if(!b.length)return{action:"Update record",detail:"Already set"};const l={};for(const u of b)l[u]=f[u];await A(s).update(i,l,o),$(t,u=>u.map(k=>k===o?f:k));const h=b.map(u=>[...d.values()].find(k=>k.field===u)?.id??u);return a.push(()=>E({type:"updated",table:t,record:y(t).data.find(u=>m(s,u)===i),before:o,fields:h,depth:r+1})),{action:"Update record",detail:b.map(u=>`${[...d.values()].find(k=>k.field===u)?.header??u}: ${String(f[u]??"")}`).join(", ")}}case"createRecord":{const d=y(n.table);if(!d)throw new Error(`No table "${n.table}"`);const p=M(d),f={id:de()};for(const[h,u]of Object.entries(n.values)){const k=p.get(h);k&&(f[k.field]=I(d,k.def,u,w))}if(n.linkField&&o){const h=p.get(n.linkField);h&&(f[h.field]=[m(s,o)])}const b=await A(d).insert(f),l={...f,id:String(b.id??f.id)};return $(d.id,h=>[...h,l]),a.push(()=>E({type:"created",table:d.id,record:l,depth:r+1})),{action:"Create record",detail:`${String(l[H(d)]??"")||"a record"} in ${d.name}`}}case"run":return be(e,n,s,o);case"webhook":return{action:"Webhook",detail:await ke(n,V(e,s,o,{secret:K,fetch:g.fetch,...Q?{checkUrl:Q}:{}},c))};case"email":return{action:"Email",detail:await Se(n,V(e,s,o,{},c),g.sendEmail)};case"chat":return{action:"Message",detail:await ve(n,V(e,s,o,{secret:K,fetch:g.fetch},c))};case"ai":{if(!g.ai)throw new Error("No AI model here: give createAutomationServer an ai");const d=ee(s,o,n.prompt,c).trim();if(!d)throw new Error("The prompt is empty");const p=String(await g.ai(d)).trim();c.set("ai",p);const f=n.field?M(s).get(n.field):void 0;if(f&&o&&i!=null&&!_(o[f.field],p)){await A(s).update(i,{[f.field]:p},o);const b={...o,[f.field]:p};$(t,l=>l.map(h=>h===o?b:h)),a.push(()=>E({type:"updated",table:t,record:b,before:o,fields:[f.id],depth:r+1}))}return{action:"AI",detail:p.length>160?p.slice(0,157)+"...":p}}case"script":throw new Error("A script runs in a browser, in the page of the person who made the change: set Runs in to The browser.");default:return null}}return{prime:O,recordChanged:C,tableChanged:U,audit:ne,formSubmitted:ie,buttonPressed:oe,webhookReceived:ae,tick:se,get runs(){return P},settled:()=>x.then(()=>{}),get tables(){return S}}}
1
+ import{cronMatches as ue}from"../scheduling.js";import{primaryOf as L,rowIdOf as m,syncAllInverses as le}from"./base-tables.js";import{newRecordId as de}from"./field-ops.js";import{registerLinkedTable as he}from"./sources.svelte.js";import{MAX_DEPTH as Z,REPEAT_MOST as pe,actionLabel as me,automationsFor as we,triggerValues as ge,webhookValues as ye,fieldValueFrom as I,fillTokens as ee,matches as V,outbound as N,runAppAction as be,tableFields as M}from"./automations.svelte.js";import{callWebhook as ke,sendChat as ve,sendEmailAction as Se,sendTextAction as Ee}from"./automation-outbound.js";import{checkedFetch as $e}from"./automation-address.js";let Oe=0;const Te=1e4,_=(w,A)=>JSON.stringify(w??null)===JSON.stringify(A??null);export function createAutomationServer(w){const A=w.now??(()=>new Date),q=w.keepRuns??200;let S=w.tables.map(e=>({...e,data:[]})),F=null,j=!1;const R=new Map,te=(e,n)=>{const t=R.get(e)??new Set;R.set(e,t),t.add(n),t.size>Te&&t.delete(t.values().next().value)},D=(e,n)=>!!R.get(e)?.delete(n),J=new WeakSet;let B=Promise.resolve();const P=[],z=new Map,K=e=>typeof w.secrets=="function"?w.secrets(e):w.secrets?.[e],Q=w.allowInternalWebhooks?null:e=>$e(e,w.resolveHost,w.fetch),y=e=>S.find(n=>n.id===e),T=e=>{if(!e.source)throw new Error(`Table ${e.name} has no source`);return e.source};function $(e,n){S=S.map(t=>t.id===e?{...t,data:n(t.data)}:t);for(const t of S)S=le(S,t.id)}function O(){return F??(F=(async()=>{for(const e of S){const n=await T(e).load({whole:!0});$(e.id,()=>n)}for(const e of S){const n=e.id;he({id:n,name:e.name,rows:()=>y(n)?.data??[],getRowId:t=>m(y(n)??e,t),primaryField:L(e),fields:e.columns.filter(t=>t.field).map(t=>({field:String(t.field),header:String(t.header??t.field),fieldType:t.fieldType,fieldProps:t.fieldProps}))})}j=!0})().catch(e=>{throw F=null,e})),F}function C(e,n,t){const i=[];for(const r of M(e).values())_(n[r.field],t[r.field])||i.push(r.id);return i}async function U(e,n,t={}){await O();const i=y(e);if(!i)throw new Error(`No table "${e}"`);const r=l=>l?t.db===!1?l:T(i).toPage(l):null,s=r(n.after),c=r(n.before);if(!s){const l=String(c?.id??"");return $(e,h=>h.filter(u=>m(i,u)!==l)),te(e,l),[]}const a=String(s.id),o=i.data.find(l=>m(i,l)===a),g={...o??{},...s},d=!!o&&!C(i,o,g).length;if(o&&(d||t.first)){if(!t.first)return[];d||$(e,v=>v.map(G=>G===o?g:G));const l=y(e).data.find(v=>m(i,v)===a)??g;if(t.first.created)return E({type:"created",table:e,record:l});const h=t.first.values?r(t.first.values):{},u=[...M(i).values()].filter(v=>v.field in h).map(v=>v.id),k=Object.fromEntries(Object.keys(h).map(v=>[v,void 0]));return u.length?E({type:"updated",table:e,record:l,before:{...l,...k},fields:u}):[]}const p=c?{...o??{},...c}:o;$(e,l=>o?l.map(h=>h===o?g:h):[...l,g]);const f=y(e).data.find(l=>m(i,l)===a);if(!p)return D(e,a)?[]:E({type:"created",table:e,record:f});const b=C(i,p,f);return b.length?E({type:"updated",table:e,record:f,before:p,fields:b}):[]}async function W(e){await O();const n=y(e);if(!n)throw new Error(`No table "${e}"`);const t=await T(n).load({whole:!0}),i=new Map(n.data.map(s=>[m(n,s),s]));$(e,()=>t);const r=[];for(const s of y(e).data){const c=i.get(m(n,s));if(!c)D(e,m(n,s))||r.push(...await E({type:"created",table:e,record:s}));else{const a=C(n,c,s);a.length&&r.push(...await E({type:"updated",table:e,record:s,before:c,fields:a}))}}return r}function ne(e,n){const t=async r=>{if(r.action==="purge"){r.id!=null&&R.get(e)?.delete(String(r.id));return}const s=r.event&&typeof r.event=="object"?r.event:null;!j&&s&&J.add(s);const c=!j||!!s&&J.has(s);if(r.action==="delete"){await U(e,{before:{id:r.id},after:null},{db:!1});return}if(r.action==="restore"){await O(),r.id!=null&&await re(e,String(r.id));return}if(!r.result){await W(e);return}await U(e,{after:r.result},c?{first:{created:r.action==="create",...r.values?{values:r.values}:{}}}:{})};return Object.assign(async r=>{try{n&&await n(r)}finally{await t(r)}},{before:()=>O()})}async function re(e,n){const t=y(e);if(!t)return;D(e,n);const i=T(t),s=(i.read?await i.read([n]):(await i.load({whole:!0})).filter(c=>m(t,c)===n))[0];s&&$(e,c=>[...c.filter(a=>m(t,a)!==n),s])}async function ie(e,n,t){await O();const i=await X(e,n);return i?E({type:"form",table:e,record:i,view:t}):[]}async function oe(e,n,t){await O();const i=await X(e,n);return i?E({type:"button",table:e,record:i,field:t}):[]}async function X(e,n){const t=y(e);if(!t)return null;let i=t.data.find(r=>m(t,r)===n);return i||(await W(e),i=y(e).data.find(r=>m(t,r)===n)),i??null}async function ae(e,n){await O();const t=[];if(!e)return t;for(const i of S)for(const r of i.automations??[])!r.enabled||r.runOn!=="server"||r.trigger.type!=="webhookReceived"||r.trigger.token!==e||t.push(await x(r,i.id,null,0,ye(n)));return t}async function se(e=A()){await O();const n=`${e.getFullYear()}-${e.getMonth()}-${e.getDate()} ${e.getHours()}:${e.getMinutes()}`,t=[];for(const i of S)for(const r of i.automations??[]){if(!r.enabled||r.runOn!=="server"||r.trigger.type!=="scheduled")continue;const s=`${i.id}:${r.id}`;if(!(z.get(s)===n||!ue(r.trigger.cron,e)))if(z.set(s,n),!r.condition)t.push(await x(r,i.id,null,0));else for(const c of y(i.id).data)V(i,r.condition,c)&&t.push(await x(r,i.id,m(i,c),0))}return t}async function E(e){const n=y(e.table);if(!n)return[];const t="depth"in e?e.depth??0:0,i=[];for(const r of we(n,e,"server"))i.push(await x(r,n.id,m(n,e.record),t));return i}function x(e,n,t,i,r=new Map){const s=B.then(()=>ce(e,n,t,i,r));return B=s.catch(()=>{}),s}async function ce(e,n,t,i,r){const s=y(n),c=t==null?null:s.data.find(o=>m(s,o)===t)??null,a={id:++Oe,automationId:e.id,name:e.name,table:s.name,record:c?String(c[L(s)]??t):null,at:A().getTime(),status:"ok",steps:[]};if(i>=Z)a.status="stopped",a.steps.push({action:"Stopped",detail:`Automations set each other off ${Z} times in a row; this one did not run, so they cannot loop.`});else{const o=[];await H(e,e.actions,n,t,i,o,a,r),Y(a);for(const g of o)g();return a}return Y(a),a}function Y(e){P.unshift(e),P.length>q&&(P.length=q),w.onRun?.(e)}async function H(e,n,t,i,r,s,c,a){for(const o of n)try{const g=y(t),d=i==null?null:g.data.find(f=>m(g,f)===i)??null;if(o.type==="if"){const f=d?V(g,o.condition,d):!o.condition?.conditions?.length;if(c.steps.push({action:"If",detail:f?"It matched: the Then steps ran":"It did not match: the Otherwise steps ran"}),!await H(e,(f?o.then:o.else)??[],t,i,r,s,c,a))return!1;continue}if(o.type==="repeat"){const f=y(o.table);if(!f)throw new Error(`No table "${o.table}"`);const b=Math.max(1,Math.min(pe,o.limit??100)),l=f.data.filter(u=>V(f,o.condition,u)).slice(0,b).map(u=>m(f,u));c.steps.push({action:"Find records",detail:`${l.length} in ${f.name}`});const h=ge(g,d,a);h.set("found",String(l.length));for(const u of l)if(!await H(e,o.actions??[],f.id,u,r,s,c,h))return!1;continue}const p=await fe(e,o,t,i,r,s,a);p&&c.steps.push(p)}catch(g){return c.status="error",c.steps.push({action:me(o),detail:"",error:g instanceof Error?g.message:String(g)}),!1}return!0}async function fe(e,n,t,i,r,s,c){const a=y(t),o=i==null?null:a.data.find(d=>m(a,d)===i)??null,g={tables:S,from:a,record:o,now:A(),values:c};switch(n.type){case"notify":{const d=ee(a,o,n.message,c);return w.notify?.({message:d,severity:n.severity??"info",automation:e.name,table:a.name,record:o}),{action:"Notice",detail:d}}case"highlight":return null;case"updateRecord":{if(!o||i==null)return{action:"Update record",detail:"No record to update"};const d=M(a),p={};for(const[u,k]of Object.entries(n.values)){const v=d.get(u);v&&(p[v.field]=I(a,v.def,k,g))}const f={...o,...p},b=Object.keys(p).filter(u=>!_(o[u],f[u]));if(!b.length)return{action:"Update record",detail:"Already set"};const l={};for(const u of b)l[u]=f[u];await T(a).update(i,l,o),$(t,u=>u.map(k=>k===o?f:k));const h=b.map(u=>[...d.values()].find(k=>k.field===u)?.id??u);return s.push(()=>E({type:"updated",table:t,record:y(t).data.find(u=>m(a,u)===i),before:o,fields:h,depth:r+1})),{action:"Update record",detail:b.map(u=>`${[...d.values()].find(k=>k.field===u)?.header??u}: ${String(f[u]??"")}`).join(", ")}}case"createRecord":{const d=y(n.table);if(!d)throw new Error(`No table "${n.table}"`);const p=M(d),f={id:de()};for(const[h,u]of Object.entries(n.values)){const k=p.get(h);k&&(f[k.field]=I(d,k.def,u,g))}if(n.linkField&&o){const h=p.get(n.linkField);h&&(f[h.field]=[m(a,o)])}const b=await T(d).insert(f),l={...f,id:String(b.id??f.id)};return $(d.id,h=>[...h,l]),s.push(()=>E({type:"created",table:d.id,record:l,depth:r+1})),{action:"Create record",detail:`${String(l[L(d)]??"")||"a record"} in ${d.name}`}}case"run":return be(e,n,a,o);case"webhook":return{action:"Webhook",detail:await ke(n,N(e,a,o,{secret:K,fetch:w.fetch,...Q?{checkUrl:Q}:{}},c))};case"email":return{action:"Email",detail:await Se(n,N(e,a,o,{},c),w.sendEmail)};case"textMessage":return{action:"Text message",detail:await Ee(n,N(e,a,o,{},c),w.sendText)};case"chat":return{action:"Message",detail:await ve(n,N(e,a,o,{secret:K,fetch:w.fetch},c))};case"ai":{if(!w.ai)throw new Error("No AI model here: give createAutomationServer an ai");const d=ee(a,o,n.prompt,c).trim();if(!d)throw new Error("The prompt is empty");const p=String(await w.ai(d)).trim();c.set("ai",p);const f=n.field?M(a).get(n.field):void 0;if(f&&o&&i!=null&&!_(o[f.field],p)){await T(a).update(i,{[f.field]:p},o);const b={...o,[f.field]:p};$(t,l=>l.map(h=>h===o?b:h)),s.push(()=>E({type:"updated",table:t,record:b,before:o,fields:[f.id],depth:r+1}))}return{action:"AI",detail:p.length>160?p.slice(0,157)+"...":p}}case"script":throw new Error("A script runs in a browser, in the page of the person who made the change: set Runs in to The browser.");default:return null}}return{prime:O,recordChanged:U,tableChanged:W,audit:ne,formSubmitted:ie,buttonPressed:oe,webhookReceived:ae,tick:se,get runs(){return P},settled:()=>B.then(()=>{}),get tables(){return S}}}
@@ -1,7 +1,7 @@
1
1
  import { type BaseTable } from './base-tables.js';
2
2
  import { type FieldFilter } from './filter-model.js';
3
3
  import type { FieldColumn } from './grid-access.js';
4
- import { type ChatAction, type EmailAction, type OutboundContext, type WebhookAction } from './automation-outbound.js';
4
+ import { type ChatAction, type EmailAction, type OutboundContext, type TextMessageAction, type WebhookAction } from './automation-outbound.js';
5
5
  import { type ScriptRecord } from './automation-script.js';
6
6
  type Row = Record<string, unknown>;
7
7
  type Def = Record<string, any>;
@@ -81,6 +81,8 @@ export type AutomationAction =
81
81
  | EmailAction
82
82
  /** A message to a Slack, Teams or Google Chat channel. */
83
83
  | ChatAction
84
+ /** A text message (SMS, or Viber) to phones (the server runner's `sendText`). */
85
+ | TextMessageAction
84
86
  /**
85
87
  * Find records of a table (those matching `condition`, at most `limit`) and
86
88
  * run `actions` for each: in them `{Field}` is the found record's, and
@@ -1 +1 @@
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{getFieldUsers}from"./sources.svelte.js";import{newRecordId}from"./field-ops.js";import{fieldText,fieldValue,linkNames}from"./base-alerts.js";import{callWebhook,sendChat,sendEmailAction}from"./automation-outbound.js";import{runScript}from"./automation-script.js";import{bm}from"./messages.svelte.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 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 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,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"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"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"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"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"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"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:tr.cron,condition:cond}):bm("extras.onSchedule",{cron: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{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";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 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 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,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"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"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"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"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:tr.cron,condition:cond}):bm("extras.onSchedule",{cron:tr.cron});case"webhookReceived":return bm("extras.whenWebhook")}}
@@ -24,7 +24,7 @@ export { baseFromDatabase, describeDatabase, createBaseEndpoint, baseFromEndpoin
24
24
  export { baseFromAirtable, airtableFormulaSupport, airtableColor, formulaFunctionsUsed, type AirtableSchema, type AirtableTable, type AirtableField, type AirtableView, type AirtableRecord, type AirtableRecords, type AirtableCollaborator, type AirtableImportOptions, type AirtableImport, type AirtableReportItem, type AirtableFormulaSupport, type AirtableFormulaStatus, type AirtableFormulaGroup } from './airtable.js';
25
25
  export { registerAutomationAction, listAutomationActions, MAX_DEPTH as AUTOMATION_MAX_DEPTH, type BaseAutomation, type AutomationTrigger, type AutomationAction, type AutomationRun, type AutomationStep, type AutomationActionContext, type RegisteredAutomationAction, type RunValues, REPEAT_MOST as AUTOMATION_REPEAT_MOST, allActions as allAutomationActions, scriptRecord, scriptInput, webhookValues, triggerValues, } from './automations.svelte.js';
26
26
  export { createAutomationServer, type AutomationServer, type AutomationServerOptions, type AutomationNotice } from './automation-server.js';
27
- export type { WebhookAction, EmailAction, OutgoingEmail, ChatAction } from './automation-outbound.js';
27
+ export type { WebhookAction, EmailAction, OutgoingEmail, ChatAction, TextMessageAction, OutgoingText } from './automation-outbound.js';
28
28
  export { chatPayload, chatHostOk } from './automation-outbound.js';
29
29
  export { runScript, SCRIPT_MAX_LENGTH, type ScriptBridge, type ScriptRecord, type ScriptResult, type ScriptOptions } from './automation-script.js';
30
30
  export { newWebhookToken } from './automation-edit.js';
@@ -226,6 +226,20 @@ export declare const EXTRAS_MESSAGES: {
226
226
  readonly 'extras.chatHintSlack': "In Slack: Apps, Incoming Webhooks, Add to a channel; paste the address it gives here.";
227
227
  readonly 'extras.chatHintTeams': "In Teams: the channel's Workflows, \"Post to a channel when a webhook request is received\"; paste the address it gives here.";
228
228
  readonly 'extras.chatHintGoogle': "In Google Chat: the space's Apps and integrations, Webhooks, Add webhook; paste the address it gives here.";
229
+ readonly 'extras.actionText': "Send a text message";
230
+ readonly 'extras.doText': "Send a text message (SMS or Viber)";
231
+ readonly 'extras.stepText': "Text message";
232
+ readonly 'extras.textNeedsServer': "Text messages are sent by the server: set Runs in to The server.";
233
+ readonly 'extras.textBy': "Send by";
234
+ readonly 'extras.textSms': "SMS";
235
+ readonly 'extras.textViber': "Viber (SMS if not on Viber)";
236
+ readonly 'extras.textTo': "To";
237
+ readonly 'extras.textToPlaceholder': "+359 88 123 4567, {Phone}";
238
+ readonly 'extras.textMessage': "Message";
239
+ readonly 'extras.textHint': "Phone numbers with their country code, or a phone field in braces; several apart with commas. The text names fields in braces.";
240
+ readonly 'extras.summarySms': "SMS to {to}";
241
+ readonly 'extras.summaryViber': "Viber to {to}";
242
+ readonly 'extras.summaryNoPhone': "No phone yet";
229
243
  readonly 'extras.ifHint': "When the record matches this condition the Then steps run, otherwise the Otherwise steps.";
230
244
  readonly 'extras.ifAlways': "No condition: Then always runs";
231
245
  readonly 'extras.then': "Then";
@@ -1 +1 @@
1
- export const EXTRAS_MESSAGES={"extras.whenCreated":"When a record is created","extras.whenCreatedWhere":"When a record is created, where {condition}","extras.whenRecordChanges":"When a record changes","extras.whenRecordChangesWhere":"When a record changes, where {condition}","extras.whenFieldsChange":"When {fields} changes","extras.whenFieldsChangeWhere":"When {fields} changes, where {condition}","extras.fieldsOr":" or ","extras.whenMatches":"When a record matches: {condition}","extras.noConditionYet":"no condition yet","extras.whenForm":"When a form is sent","extras.whenFormWhere":"When a form is sent, where {condition}","extras.whenPressed":"When {field} is pressed","extras.onSchedule":"On a schedule ({cron})","extras.onScheduleWhere":"On a schedule ({cron}), for records where {condition}","extras.actionUpdateRecord":"Update record","extras.actionCreateRecord":"Create record","extras.actionNotify":"Show a notice","extras.actionHighlight":"Color the record","extras.actionWebhook":"Call a webhook","extras.actionEmail":"Send an email","extras.stepStopped":"Stopped","extras.stepLoop":"Automations set each other off {max} times in a row; this one did not run, so they cannot loop.","extras.stepNotice":"Notice","extras.stepWebhook":"Webhook","extras.stepEmail":"Email","extras.stepNotRun":"Not run","extras.stepNoMatch":"The record does not match the condition","extras.stepDone":"Done","extras.noRecordToUpdate":"No record to update","extras.alreadySet":"Already set","extras.noTable":'No table "{table}"',"extras.noAction":'No action "{action}" is registered',"extras.aRecord":"a record","extras.createdIn":"{name} in {table}","extras.saidValue":"{field}: {value}","extras.saidChecked":"{field}: checked","extras.saidUnchecked":"{field}: unchecked","extras.saidEmpty":"empty","extras.title":"Automations in {table}","extras.listLabel":"Automations","extras.untitled":"Untitled","extras.switchOn":"{name} on","extras.noAutomations":"No automations yet. An automation does something when a record is added, changes or matches a condition.","extras.addAutomation":"+ New automation","extras.newAutomation":"New automation","extras.newRecordMessage":"New record: {{field}}","extras.nameFallback":"Name","extras.runs":"Runs","extras.clearRuns":"Clear this page's runs","extras.serverRunsFailed":"The server's runs did not load: {message}","extras.statusDone":"Done","extras.statusFailed":"Failed","extras.statusStopped":"Stopped","extras.runOn":"on {record}","extras.runIn":"in {table}","extras.serverTag":"Server","extras.noRuns":"Nothing has run yet. Runs show here with what each action did.","extras.name":"Name","extras.runsIn":"Runs in","extras.runsInBrowser":"This browser","extras.runsInServer":"The server","extras.serverHint":"Your server runs it (createAutomationServer): it hears changes from the database, whoever made them, reads secrets and sends email.","extras.browserHint":"It runs in the browser of the person who makes the change, right away.","extras.when":"When","extras.trigger":"Trigger","extras.triggerCreated":"A record is created","extras.triggerUpdated":"A record changes","extras.triggerMatches":"A record matches a condition","extras.triggerForm":"A form is sent","extras.triggerButton":"A button is pressed","extras.triggerScheduled":"At a scheduled time","extras.watchSome":"Only when one of these fields changes:","extras.watchAny":"Any field. Pick fields to watch only those:","extras.form":"Form","extras.anyForm":"Any form of this table","extras.buttonField":"Button field","extras.addButtonFirst":"Add a Button field to the table first.","extras.schedule":"Schedule","extras.customSchedule":"Custom","extras.cronExpression":"Cron expression","extras.scheduleHint":"Runs while the base is open in a browser. With a condition, it runs once for each record that matches at that time.","extras.condition":"Condition","extras.onlyWhere":"Only for records where","extras.startsToMatch":"Runs when a record starts to match","extras.addMatchCondition":"Add the condition a record has to start matching.","extras.everyRecord":"Every record. Add a condition to narrow it.","extras.do":"Do","extras.action":"Action","extras.doUpdateRecord":"Update the record","extras.doCreateRecord":"Create a record","extras.doHighlight":"Color the record while it matches","extras.moveUp":"Move up","extras.moveDown":"Move down","extras.moveStepUp":"Move step {step} up","extras.moveStepDown":"Move step {step} down","extras.removeStep":"Remove step {step}","extras.stepMoved":"Step {from} is now step {to}.","extras.removeAction":"Remove action","extras.message":"Message","extras.notifyPlaceholder":"{{field}} needs a look","extras.kind":"Kind","extras.severityInfo":"Info","extras.severitySuccess":"Success","extras.severityWarning":"Warning","extras.severityError":"Error","extras.notifyHint":"Name a field in braces for its value: {fields}.","extras.highlightNeedsCondition":"Colors records while they match the condition above; add one.","extras.fill":"Fill","extras.text":"Text","extras.sample":"Sample","extras.wholeRow":"Whole row","extras.in":"In","extras.table":"Table","extras.linkBack":"Link it back","extras.linkField":"Link field","extras.noLink":"No link","extras.through":"through {field}","extras.valueOf":"{field} value","extras.valuePlaceholder":"a value, or {Field}","extras.numberPlaceholder":"0, or 100% for a percent","extras.linkPlaceholder":"a record name, or {record}","extras.userPlaceholder":"a name","extras.doNotSet":"Do not set {field}","extras.remove":"Remove","extras.setField":"Set a field","extras.addSetField":"+ Set a field","extras.runsApp":"Runs {action}, an action the app registered.","extras.method":"Method","extras.url":"URL","extras.headers":"Headers","extras.body":"Body","extras.webhookHintServer":"Empty body: the record as JSON. {secret} is read on the server only.","extras.webhookHintBrowser":"Empty body: the record as JSON. {secret} is read on the server only; set Runs in to The server to use one.","extras.emailNeedsServer":"Email is sent by the server: set Runs in to The server.","extras.to":"To","extras.toPlaceholder":"team@example.com, {Owner email}","extras.subject":"Subject","extras.emailText":"Email text","extras.addAction":"Add an action","extras.addActionOption":"+ Add an action","extras.deleteIt":"Delete it?","extras.delete":"Delete","extras.keep":"Keep","extras.deleteAutomation":"Delete automation","extras.runsOnServer":"Runs on your server when its trigger happens.","extras.tryRecord":"Record to try it on","extras.noRecord":"No record","extras.runNow":"Run now","extras.pickAutomation":"Pick an automation, or add one.","extras.noName":"(no name)","extras.noRecordValue":"(no record)","extras.pageLabel":"Automations of the base","extras.createAutomation":"+ Create automation","extras.runHistory":"Run history","extras.pageEmpty":"No automations yet. An automation does something on its own: when a record is added or changes, a form is sent, a button is pressed or at a time you set.","extras.pickOne":"Pick an automation on the left, or create one.","extras.triggerCard":"Trigger","extras.whenIn":"{when}, in {table}","extras.conditionCard":"Only for records where","extras.conditionEvery":"Every record","extras.conditionCount.one":"{count} condition","extras.conditionCount.other":"{count} conditions","extras.addCondition":"+ Add a condition","extras.actionCard":"Action {n}","extras.insertAction":"Add an action here","extras.addActionPage":"+ Add an action","extras.flowLabel":"What {name} does","extras.summarySet":"Set {fields}","extras.summaryNothing":"No fields set yet","extras.summaryCreate":"A new record in {table}","extras.summaryEmail":"To {to}","extras.summaryNoTo":"No address yet","extras.summaryColor":"While it matches","extras.tableOfTrigger":"Table","extras.tableMoveHint":"Its trigger, condition and fields are for this table: a new table starts them again.","extras.settingsOf":"Settings","extras.testOn":"Test on","extras.test":"Test","extras.testRuns":"Its runs show in the run history.","extras.allRunsOf":"Runs of {name}","extras.allRuns":"All runs","extras.showAllRuns":"Show every automation's runs","extras.whenWebhook":"When a webhook is received","extras.triggerWebhook":"A webhook is received","extras.webhookAddress":"Webhook address","extras.webhookNoUrl":"This automation listens for the token {token}: give it to your server runner (webhookReceived).","extras.webhookHint":"Send a POST with a JSON body to this address. Its values are {webhook.name} in the steps ({webhook.order.id} inside objects). Anyone with the address can start the automation: keep it secret.","extras.newAddress":"Make a new address","extras.copy":"Copy","extras.copied":"Copied","extras.actionChat":"Send a message","extras.actionRepeat":"Find records","extras.actionIf":"If","extras.actionAi":"Ask AI","extras.actionScript":"Run a script","extras.doChat":"Send a Slack, Teams or Google Chat message","extras.doRepeat":"Find records and, for each, do","extras.doIf":"If a condition holds, do","extras.doAi":"Ask AI","extras.doScript":"Run a script","extras.stepChat":"Message","extras.stepIf":"If","extras.stepIfThen":"It matched: the Then steps ran","extras.stepIfElse":"It did not match: the Otherwise steps ran","extras.stepFound":"Find records","extras.foundIn":"{count} in {table}","extras.stepAi":"AI","extras.stepScript":"Script","extras.noAi":"No AI model is set up here.","extras.aiNoPrompt":"The prompt is empty.","extras.scriptFailed":"The script failed.","extras.noField":"No field named {field}.","extras.noRecordId":"No record {id}.","extras.stepKind":"{list}, step {n}","extras.addStep":"+ Add a step","extras.addStepTo":"Add a step to {list}","extras.chatApp":"Chat app","extras.chatUrl":"Webhook address","extras.chatHintSlack":"In Slack: Apps, Incoming Webhooks, Add to a channel; paste the address it gives here.","extras.chatHintTeams":`In Teams: the channel's Workflows, "Post to a channel when a webhook request is received"; paste the address it gives here.`,"extras.chatHintGoogle":"In Google Chat: the space's Apps and integrations, Webhooks, Add webhook; paste the address it gives here.","extras.ifHint":"When the record matches this condition the Then steps run, otherwise the Otherwise steps.","extras.ifAlways":"No condition: Then always runs","extras.then":"Then","extras.otherwise":"Otherwise","extras.findIn":"Find in","extras.whichRecords":"Records where","extras.atMost":"At most","extras.forEach":"For each record found","extras.repeatHint":"In these steps {Field} is the found record's field, {trigger.Field} the field of the record that set the automation off, and {found} how many were found.","extras.aiPrompt":"Prompt","extras.aiPlaceholder":"Write a two-line summary of {{field}} for a weekly report.","extras.aiInto":"Put the answer in","extras.aiNowhere":"No field (use {ai} in the next steps)","extras.aiHint":"Name fields in braces. The answer is {ai} in the next steps.","extras.scriptCode":"Script","extras.scriptNeedsBrowser":"A script runs in the browser: set Runs in to The browser.","extras.scriptHint":"JavaScript, as in Airtable: input.config() has the record's fields by name; base.getTable('Name') reads and changes a table (selectRecordsAsync, updateRecordAsync, createRecordAsync, deleteRecordAsync); output.set('name', value) is {script.name} in the next steps; fetch() calls https addresses that allow it. It runs in a sandbox for up to 30 seconds.","extras.scriptInPageHint":"It runs in the page of the person who made the change, with what they may do. A run with no one's page behind it (a schedule, a webhook, a change through the API) stops at this step and says so.","extras.summaryNoText":"Nothing written yet","extras.stepCount.one":"{count} step","extras.stepCount.other":"{count} steps","extras.summaryRepeat":"{steps} for each record in {table}","extras.summaryIf":"Then {then}; otherwise {otherwise}","extras.summaryScript":"{lines} lines"};
1
+ export const EXTRAS_MESSAGES={"extras.whenCreated":"When a record is created","extras.whenCreatedWhere":"When a record is created, where {condition}","extras.whenRecordChanges":"When a record changes","extras.whenRecordChangesWhere":"When a record changes, where {condition}","extras.whenFieldsChange":"When {fields} changes","extras.whenFieldsChangeWhere":"When {fields} changes, where {condition}","extras.fieldsOr":" or ","extras.whenMatches":"When a record matches: {condition}","extras.noConditionYet":"no condition yet","extras.whenForm":"When a form is sent","extras.whenFormWhere":"When a form is sent, where {condition}","extras.whenPressed":"When {field} is pressed","extras.onSchedule":"On a schedule ({cron})","extras.onScheduleWhere":"On a schedule ({cron}), for records where {condition}","extras.actionUpdateRecord":"Update record","extras.actionCreateRecord":"Create record","extras.actionNotify":"Show a notice","extras.actionHighlight":"Color the record","extras.actionWebhook":"Call a webhook","extras.actionEmail":"Send an email","extras.stepStopped":"Stopped","extras.stepLoop":"Automations set each other off {max} times in a row; this one did not run, so they cannot loop.","extras.stepNotice":"Notice","extras.stepWebhook":"Webhook","extras.stepEmail":"Email","extras.stepNotRun":"Not run","extras.stepNoMatch":"The record does not match the condition","extras.stepDone":"Done","extras.noRecordToUpdate":"No record to update","extras.alreadySet":"Already set","extras.noTable":'No table "{table}"',"extras.noAction":'No action "{action}" is registered',"extras.aRecord":"a record","extras.createdIn":"{name} in {table}","extras.saidValue":"{field}: {value}","extras.saidChecked":"{field}: checked","extras.saidUnchecked":"{field}: unchecked","extras.saidEmpty":"empty","extras.title":"Automations in {table}","extras.listLabel":"Automations","extras.untitled":"Untitled","extras.switchOn":"{name} on","extras.noAutomations":"No automations yet. An automation does something when a record is added, changes or matches a condition.","extras.addAutomation":"+ New automation","extras.newAutomation":"New automation","extras.newRecordMessage":"New record: {{field}}","extras.nameFallback":"Name","extras.runs":"Runs","extras.clearRuns":"Clear this page's runs","extras.serverRunsFailed":"The server's runs did not load: {message}","extras.statusDone":"Done","extras.statusFailed":"Failed","extras.statusStopped":"Stopped","extras.runOn":"on {record}","extras.runIn":"in {table}","extras.serverTag":"Server","extras.noRuns":"Nothing has run yet. Runs show here with what each action did.","extras.name":"Name","extras.runsIn":"Runs in","extras.runsInBrowser":"This browser","extras.runsInServer":"The server","extras.serverHint":"Your server runs it (createAutomationServer): it hears changes from the database, whoever made them, reads secrets and sends email.","extras.browserHint":"It runs in the browser of the person who makes the change, right away.","extras.when":"When","extras.trigger":"Trigger","extras.triggerCreated":"A record is created","extras.triggerUpdated":"A record changes","extras.triggerMatches":"A record matches a condition","extras.triggerForm":"A form is sent","extras.triggerButton":"A button is pressed","extras.triggerScheduled":"At a scheduled time","extras.watchSome":"Only when one of these fields changes:","extras.watchAny":"Any field. Pick fields to watch only those:","extras.form":"Form","extras.anyForm":"Any form of this table","extras.buttonField":"Button field","extras.addButtonFirst":"Add a Button field to the table first.","extras.schedule":"Schedule","extras.customSchedule":"Custom","extras.cronExpression":"Cron expression","extras.scheduleHint":"Runs while the base is open in a browser. With a condition, it runs once for each record that matches at that time.","extras.condition":"Condition","extras.onlyWhere":"Only for records where","extras.startsToMatch":"Runs when a record starts to match","extras.addMatchCondition":"Add the condition a record has to start matching.","extras.everyRecord":"Every record. Add a condition to narrow it.","extras.do":"Do","extras.action":"Action","extras.doUpdateRecord":"Update the record","extras.doCreateRecord":"Create a record","extras.doHighlight":"Color the record while it matches","extras.moveUp":"Move up","extras.moveDown":"Move down","extras.moveStepUp":"Move step {step} up","extras.moveStepDown":"Move step {step} down","extras.removeStep":"Remove step {step}","extras.stepMoved":"Step {from} is now step {to}.","extras.removeAction":"Remove action","extras.message":"Message","extras.notifyPlaceholder":"{{field}} needs a look","extras.kind":"Kind","extras.severityInfo":"Info","extras.severitySuccess":"Success","extras.severityWarning":"Warning","extras.severityError":"Error","extras.notifyHint":"Name a field in braces for its value: {fields}.","extras.highlightNeedsCondition":"Colors records while they match the condition above; add one.","extras.fill":"Fill","extras.text":"Text","extras.sample":"Sample","extras.wholeRow":"Whole row","extras.in":"In","extras.table":"Table","extras.linkBack":"Link it back","extras.linkField":"Link field","extras.noLink":"No link","extras.through":"through {field}","extras.valueOf":"{field} value","extras.valuePlaceholder":"a value, or {Field}","extras.numberPlaceholder":"0, or 100% for a percent","extras.linkPlaceholder":"a record name, or {record}","extras.userPlaceholder":"a name","extras.doNotSet":"Do not set {field}","extras.remove":"Remove","extras.setField":"Set a field","extras.addSetField":"+ Set a field","extras.runsApp":"Runs {action}, an action the app registered.","extras.method":"Method","extras.url":"URL","extras.headers":"Headers","extras.body":"Body","extras.webhookHintServer":"Empty body: the record as JSON. {secret} is read on the server only.","extras.webhookHintBrowser":"Empty body: the record as JSON. {secret} is read on the server only; set Runs in to The server to use one.","extras.emailNeedsServer":"Email is sent by the server: set Runs in to The server.","extras.to":"To","extras.toPlaceholder":"team@example.com, {Owner email}","extras.subject":"Subject","extras.emailText":"Email text","extras.addAction":"Add an action","extras.addActionOption":"+ Add an action","extras.deleteIt":"Delete it?","extras.delete":"Delete","extras.keep":"Keep","extras.deleteAutomation":"Delete automation","extras.runsOnServer":"Runs on your server when its trigger happens.","extras.tryRecord":"Record to try it on","extras.noRecord":"No record","extras.runNow":"Run now","extras.pickAutomation":"Pick an automation, or add one.","extras.noName":"(no name)","extras.noRecordValue":"(no record)","extras.pageLabel":"Automations of the base","extras.createAutomation":"+ Create automation","extras.runHistory":"Run history","extras.pageEmpty":"No automations yet. An automation does something on its own: when a record is added or changes, a form is sent, a button is pressed or at a time you set.","extras.pickOne":"Pick an automation on the left, or create one.","extras.triggerCard":"Trigger","extras.whenIn":"{when}, in {table}","extras.conditionCard":"Only for records where","extras.conditionEvery":"Every record","extras.conditionCount.one":"{count} condition","extras.conditionCount.other":"{count} conditions","extras.addCondition":"+ Add a condition","extras.actionCard":"Action {n}","extras.insertAction":"Add an action here","extras.addActionPage":"+ Add an action","extras.flowLabel":"What {name} does","extras.summarySet":"Set {fields}","extras.summaryNothing":"No fields set yet","extras.summaryCreate":"A new record in {table}","extras.summaryEmail":"To {to}","extras.summaryNoTo":"No address yet","extras.summaryColor":"While it matches","extras.tableOfTrigger":"Table","extras.tableMoveHint":"Its trigger, condition and fields are for this table: a new table starts them again.","extras.settingsOf":"Settings","extras.testOn":"Test on","extras.test":"Test","extras.testRuns":"Its runs show in the run history.","extras.allRunsOf":"Runs of {name}","extras.allRuns":"All runs","extras.showAllRuns":"Show every automation's runs","extras.whenWebhook":"When a webhook is received","extras.triggerWebhook":"A webhook is received","extras.webhookAddress":"Webhook address","extras.webhookNoUrl":"This automation listens for the token {token}: give it to your server runner (webhookReceived).","extras.webhookHint":"Send a POST with a JSON body to this address. Its values are {webhook.name} in the steps ({webhook.order.id} inside objects). Anyone with the address can start the automation: keep it secret.","extras.newAddress":"Make a new address","extras.copy":"Copy","extras.copied":"Copied","extras.actionChat":"Send a message","extras.actionRepeat":"Find records","extras.actionIf":"If","extras.actionAi":"Ask AI","extras.actionScript":"Run a script","extras.doChat":"Send a Slack, Teams or Google Chat message","extras.doRepeat":"Find records and, for each, do","extras.doIf":"If a condition holds, do","extras.doAi":"Ask AI","extras.doScript":"Run a script","extras.stepChat":"Message","extras.stepIf":"If","extras.stepIfThen":"It matched: the Then steps ran","extras.stepIfElse":"It did not match: the Otherwise steps ran","extras.stepFound":"Find records","extras.foundIn":"{count} in {table}","extras.stepAi":"AI","extras.stepScript":"Script","extras.noAi":"No AI model is set up here.","extras.aiNoPrompt":"The prompt is empty.","extras.scriptFailed":"The script failed.","extras.noField":"No field named {field}.","extras.noRecordId":"No record {id}.","extras.stepKind":"{list}, step {n}","extras.addStep":"+ Add a step","extras.addStepTo":"Add a step to {list}","extras.chatApp":"Chat app","extras.chatUrl":"Webhook address","extras.chatHintSlack":"In Slack: Apps, Incoming Webhooks, Add to a channel; paste the address it gives here.","extras.chatHintTeams":`In Teams: the channel's Workflows, "Post to a channel when a webhook request is received"; paste the address it gives here.`,"extras.chatHintGoogle":"In Google Chat: the space's Apps and integrations, Webhooks, Add webhook; paste the address it gives here.","extras.actionText":"Send a text message","extras.doText":"Send a text message (SMS or Viber)","extras.stepText":"Text message","extras.textNeedsServer":"Text messages are sent by the server: set Runs in to The server.","extras.textBy":"Send by","extras.textSms":"SMS","extras.textViber":"Viber (SMS if not on Viber)","extras.textTo":"To","extras.textToPlaceholder":"+359 88 123 4567, {Phone}","extras.textMessage":"Message","extras.textHint":"Phone numbers with their country code, or a phone field in braces; several apart with commas. The text names fields in braces.","extras.summarySms":"SMS to {to}","extras.summaryViber":"Viber to {to}","extras.summaryNoPhone":"No phone yet","extras.ifHint":"When the record matches this condition the Then steps run, otherwise the Otherwise steps.","extras.ifAlways":"No condition: Then always runs","extras.then":"Then","extras.otherwise":"Otherwise","extras.findIn":"Find in","extras.whichRecords":"Records where","extras.atMost":"At most","extras.forEach":"For each record found","extras.repeatHint":"In these steps {Field} is the found record's field, {trigger.Field} the field of the record that set the automation off, and {found} how many were found.","extras.aiPrompt":"Prompt","extras.aiPlaceholder":"Write a two-line summary of {{field}} for a weekly report.","extras.aiInto":"Put the answer in","extras.aiNowhere":"No field (use {ai} in the next steps)","extras.aiHint":"Name fields in braces. The answer is {ai} in the next steps.","extras.scriptCode":"Script","extras.scriptNeedsBrowser":"A script runs in the browser: set Runs in to The browser.","extras.scriptHint":"JavaScript, as in Airtable: input.config() has the record's fields by name; base.getTable('Name') reads and changes a table (selectRecordsAsync, updateRecordAsync, createRecordAsync, deleteRecordAsync); output.set('name', value) is {script.name} in the next steps; fetch() calls https addresses that allow it. It runs in a sandbox for up to 30 seconds.","extras.scriptInPageHint":"It runs in the page of the person who made the change, with what they may do. A run with no one's page behind it (a schedule, a webhook, a change through the API) stops at this step and says so.","extras.summaryNoText":"Nothing written yet","extras.stepCount.one":"{count} step","extras.stepCount.other":"{count} steps","extras.summaryRepeat":"{steps} for each record in {table}","extras.summaryIf":"Then {then}; otherwise {otherwise}","extras.summaryScript":"{lines} lines"};
@@ -375,6 +375,20 @@ export declare const BASE_MESSAGES: {
375
375
  readonly 'extras.chatHintSlack': "In Slack: Apps, Incoming Webhooks, Add to a channel; paste the address it gives here.";
376
376
  readonly 'extras.chatHintTeams': "In Teams: the channel's Workflows, \"Post to a channel when a webhook request is received\"; paste the address it gives here.";
377
377
  readonly 'extras.chatHintGoogle': "In Google Chat: the space's Apps and integrations, Webhooks, Add webhook; paste the address it gives here.";
378
+ readonly 'extras.actionText': "Send a text message";
379
+ readonly 'extras.doText': "Send a text message (SMS or Viber)";
380
+ readonly 'extras.stepText': "Text message";
381
+ readonly 'extras.textNeedsServer': "Text messages are sent by the server: set Runs in to The server.";
382
+ readonly 'extras.textBy': "Send by";
383
+ readonly 'extras.textSms': "SMS";
384
+ readonly 'extras.textViber': "Viber (SMS if not on Viber)";
385
+ readonly 'extras.textTo': "To";
386
+ readonly 'extras.textToPlaceholder': "+359 88 123 4567, {Phone}";
387
+ readonly 'extras.textMessage': "Message";
388
+ readonly 'extras.textHint': "Phone numbers with their country code, or a phone field in braces; several apart with commas. The text names fields in braces.";
389
+ readonly 'extras.summarySms': "SMS to {to}";
390
+ readonly 'extras.summaryViber': "Viber to {to}";
391
+ readonly 'extras.summaryNoPhone': "No phone yet";
378
392
  readonly 'extras.ifHint': "When the record matches this condition the Then steps run, otherwise the Otherwise steps.";
379
393
  readonly 'extras.ifAlways': "No condition: Then always runs";
380
394
  readonly 'extras.then': "Then";