@svgrid/enterprise 3.1.52 → 3.1.53

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.
@@ -1523,7 +1523,7 @@ ${F}
1523
1523
  @keyframes st-home-spin { to { transform: rotate(360deg); } }
1524
1524
  </style>
1525
1525
  `}}function vS(t){for(let a of t)hs(a);let r=new Map(t.map(a=>[a.name,a])),n=t.map(a=>{let l=ose(a,r);return{schema:sse(a,l),infos:l}});return{entries:n,seed:dse(n)}}function wD(t,r={}){let{entries:n,seed:a}=vS(t),{file:l,needs:i}=Ese(n,a,r.sources,r.supabaseConn,r.serverMemory),o=[pse(n),l];(i.supabase||r.supabaseAuth)&&!i.supabaseUrl&&(r.supabaseConn?.url||r.supabaseConn?.key)&&(i.supabaseUrl=r.supabaseConn.url,i.supabaseKey=r.supabaseConn.key),(i.supabase||r.supabaseAuth)&&o.push(Rse(i));for(let s of i.sqlRoutes)o.push(xse(s.schema,s.table,s.dialect,{access:r.accessEnabled,audit:r.auditEnabled,screenIds:r.screensByEntity?.get(s.schema.name)??[],triggers:r.triggers?.[s.schema.name],dbSchema:s.dbSchema,tenantField:r.tenantField&&r.tenantScoped?.(s.schema.name)!==!1?r.tenantField:void 0}));if(i.memoryRoutes.length){o.push(_se(i.memoryRoutes));for(let s of i.memoryRoutes)o.push(kse(s.schema,{access:r.accessEnabled,audit:r.auditEnabled,screenIds:r.screensByEntity?.get(s.schema.name)??[],triggers:r.triggers?.[s.schema.name],tenantField:r.tenantField&&r.tenantScoped?.(s.schema.name)!==!1?r.tenantField:void 0}))}return{files:o,prepared:n.map(s=>s.schema)}}function Dse(t){if(t.length===0)throw Error("emitStudioApp: no schemas to emit");let{files:r,prepared:n}=wD(t),a=n.map(i=>{let o=Ua(i);return{href:`/${o.route}`,label:o.label}}),l={path:"src/custom.css",description:"Your custom styles (imported after app.css so it overrides).",userOwned:!0,contents:`/* Your custom styles. Imported after app.css, so these rules override the defaults. */
1526
- `};return[...r,...n.map(i=>Ise(i)),bD(a),yD(a),l]}var Nse="3.1.52",Fse="3.0.37",bl=(t,r)=>t.some(n=>n.config.kind===r),xD=t=>`activeTab_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,ev=(t,r)=>`${t}-${r}`,kD=t=>`accOpen_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,tv=(t,r)=>`${t}-s${r}`,rv=t=>`md_${t.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function Ose(t){switch(t.type){case"number":{let r=t.decimals;return r==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${r}, maximumFractionDigits: ${r} } }`}case"currency":return`{ type: 'currency', currency: ${Jr(t.currency||"USD")} }`;case"percent":{let r=["type: 'percent'"];return t.valueIsPercentPoints&&r.push("valueIsPercentPoints: true"),t.decimals!=null&&r.push(`options: { minimumFractionDigits: ${t.decimals}, maximumFractionDigits: ${t.decimals} }`),`{ ${r.join(", ")} }`}case"date":case"datetime":return t.pattern?`{ type: '${t.type}', pattern: ${Jr(t.pattern)} }`:`{ type: '${t.type}' }`}}function Lse(t,r,n,a){if(r.config.kind!=="grid")return`schemaToColumns(${t})`;let l=r.config,i=r.id.replace(/-/g,"_"),o=l.columns.filter(b=>b.show),s=new Set(o.map(b=>b.field)),c=new Set,d=o.map(b=>{let w=a?.get(b.field);return{c:b,col:w&&!s.has(w)?w:b.field}}).filter(b=>!c.has(b.col)&&!!c.add(b.col)),u=l.editing==="inline"?"":", editable: false";if(d.length===0)return u?`schemaToColumns(${t}).map((c) => ({ ...c${u} }))`:`schemaToColumns(${t})`;let p=d.map(b=>`'${b.col}'`),f=d.map(({c:b,col:w})=>{let v=[];return b.header&&v.push(`header: ${JSON.stringify(b.header)}`),b.width!=null&&v.push(`width: ${b.width}`),b.align&&v.push(`align: '${b.align}'`),b.aggregate&&v.push(`aggregate: '${b.aggregate}'`),l.treeData&&b.field===l.treeData.labelField&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(treeCell_${i}, { value: ctx.getValue(), row: ctx.row.original })`):b.cellType&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(${AD(i,b.field)}, { value: ctx.getValue() })`):b.format&&v.push(`format: ${Ose(b.format)}`),v.length?`'${w}': { ${v.join(", ")} }`:null}).filter(b=>!!b),y=f.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${f.join(", ")} };`:"",h=f.length?", ...(ov[String(c.field)] ?? {})":"",_=`[${p.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${t});${y} return ${u||h?`${_}.map((c) => ({ ...c${u}${h} }))`:_} })()`}function nc(t,r){let n=[`grid-column: span ${Oie(t)}`,"min-width: 0"];r&&n.push(r);let a=zie(t.style);return a&&n.push(a),`style="${n.join("; ")}"`}var zse=t=>t&&t.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function Du(t,r){let n=[r,Fie(t)].filter(Boolean).join(" ");return n?` class="${n}"`:""}function Vy(t){let r=rS(t.className);return r?` ${r}`:""}function Pse(t){let r=_f(t);if(r==="grid"){let n=Qie(t),a=n.maxWidth?` max-width: ${n.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${n.rowGap}px ${n.colGap}px; align-items: ${n.align};${a} }
1526
+ `};return[...r,...n.map(i=>Ise(i)),bD(a),yD(a),l]}var Nse="3.1.53",Fse="3.0.37",bl=(t,r)=>t.some(n=>n.config.kind===r),xD=t=>`activeTab_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,ev=(t,r)=>`${t}-${r}`,kD=t=>`accOpen_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,tv=(t,r)=>`${t}-s${r}`,rv=t=>`md_${t.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function Ose(t){switch(t.type){case"number":{let r=t.decimals;return r==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${r}, maximumFractionDigits: ${r} } }`}case"currency":return`{ type: 'currency', currency: ${Jr(t.currency||"USD")} }`;case"percent":{let r=["type: 'percent'"];return t.valueIsPercentPoints&&r.push("valueIsPercentPoints: true"),t.decimals!=null&&r.push(`options: { minimumFractionDigits: ${t.decimals}, maximumFractionDigits: ${t.decimals} }`),`{ ${r.join(", ")} }`}case"date":case"datetime":return t.pattern?`{ type: '${t.type}', pattern: ${Jr(t.pattern)} }`:`{ type: '${t.type}' }`}}function Lse(t,r,n,a){if(r.config.kind!=="grid")return`schemaToColumns(${t})`;let l=r.config,i=r.id.replace(/-/g,"_"),o=l.columns.filter(b=>b.show),s=new Set(o.map(b=>b.field)),c=new Set,d=o.map(b=>{let w=a?.get(b.field);return{c:b,col:w&&!s.has(w)?w:b.field}}).filter(b=>!c.has(b.col)&&!!c.add(b.col)),u=l.editing==="inline"?"":", editable: false";if(d.length===0)return u?`schemaToColumns(${t}).map((c) => ({ ...c${u} }))`:`schemaToColumns(${t})`;let p=d.map(b=>`'${b.col}'`),f=d.map(({c:b,col:w})=>{let v=[];return b.header&&v.push(`header: ${JSON.stringify(b.header)}`),b.width!=null&&v.push(`width: ${b.width}`),b.align&&v.push(`align: '${b.align}'`),b.aggregate&&v.push(`aggregate: '${b.aggregate}'`),l.treeData&&b.field===l.treeData.labelField&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(treeCell_${i}, { value: ctx.getValue(), row: ctx.row.original })`):b.cellType&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(${AD(i,b.field)}, { value: ctx.getValue() })`):b.format&&v.push(`format: ${Ose(b.format)}`),v.length?`'${w}': { ${v.join(", ")} }`:null}).filter(b=>!!b),y=f.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${f.join(", ")} };`:"",h=f.length?", ...(ov[String(c.field)] ?? {})":"",_=`[${p.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${t});${y} return ${u||h?`${_}.map((c) => ({ ...c${u}${h} }))`:_} })()`}function nc(t,r){let n=[`grid-column: span ${Oie(t)}`,"min-width: 0"];r&&n.push(r);let a=zie(t.style);return a&&n.push(a),`style="${n.join("; ")}"`}var zse=t=>t&&t.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function Du(t,r){let n=[r,Fie(t)].filter(Boolean).join(" ");return n?` class="${n}"`:""}function Vy(t){let r=rS(t.className);return r?` ${r}`:""}function Pse(t){let r=_f(t);if(r==="grid"){let n=Qie(t),a=n.maxWidth?` max-width: ${n.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${n.rowGap}px ${n.colGap}px; align-items: ${n.align};${a} }
1527
1527
  @media (max-width: ${n.mobileBreakpoint}px) { .st-screen { grid-template-columns: 1fr; gap: 12px; } }
1528
1528
  `}if(r==="stack"){let n=eoe(t),a=n.maxWidth?` max-width: ${n.maxWidth}px;${n.align==="center"?" margin-inline: auto;":""}`:"",l=n.minHeight?`
1529
1529
  .st-stack > * { min-height: ${n.minHeight}px; }`:"",i=n.dividers?`
@@ -76332,7 +76332,7 @@ ${st}
76332
76332
  .st-home a { color: var(--sg-accent, #6366f1); font-weight: 600; }
76333
76333
  @keyframes st-home-spin { to { transform: rotate(360deg); } }
76334
76334
  </style>
76335
- `}}function o2e(a){for(let p of a)O4(p);let i=new Map(a.map(p=>[p.name,p])),l=a.map(p=>{let f=Epr(p,i);return{schema:wpr(p,f),infos:f}});return{entries:l,seed:Apr(l)}}function Jpr(a,i={}){let{entries:l,seed:p}=o2e(a),{file:f,needs:g}=qpr(l,p,i.sources,i.supabaseConn,i.serverMemory),_=[kpr(l),f];(g.supabase||i.supabaseAuth)&&!g.supabaseUrl&&(i.supabaseConn?.url||i.supabaseConn?.key)&&(g.supabaseUrl=i.supabaseConn.url,g.supabaseKey=i.supabaseConn.key),(g.supabase||i.supabaseAuth)&&_.push(Kpr(g));for(let S of g.sqlRoutes)_.push(Wpr(S.schema,S.table,S.dialect,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],dbSchema:S.dbSchema,tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}));if(g.memoryRoutes.length){_.push(Gpr(g.memoryRoutes));for(let S of g.memoryRoutes)_.push(zpr(S.schema,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}))}return{files:_,prepared:l.map(S=>S.schema)}}var Ypr="3.1.52",Zpr="3.0.37",hb=(a,i)=>a.some(l=>l.config.kind===i),Bit=a=>`activeTab_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,KZ=(a,i)=>`${a}-${i}`,Uit=a=>`accOpen_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,QZ=(a,i)=>`${a}-s${i}`,XZ=a=>`md_${a.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function eur(a){switch(a.type){case"number":{let i=a.decimals;return i==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${i}, maximumFractionDigits: ${i} } }`}case"currency":return`{ type: 'currency', currency: ${_u(a.currency||"USD")} }`;case"percent":{let i=["type: 'percent'"];return a.valueIsPercentPoints&&i.push("valueIsPercentPoints: true"),a.decimals!=null&&i.push(`options: { minimumFractionDigits: ${a.decimals}, maximumFractionDigits: ${a.decimals} }`),`{ ${i.join(", ")} }`}case"date":case"datetime":return a.pattern?`{ type: '${a.type}', pattern: ${_u(a.pattern)} }`:`{ type: '${a.type}' }`}}function tur(a,i,l,p){if(i.config.kind!=="grid")return`schemaToColumns(${a})`;let f=i.config,g=i.id.replace(/-/g,"_"),_=f.columns.filter(be=>be.show),S=new Set(_.map(be=>be.field)),A=new Set,k=_.map(be=>{let Be=p?.get(be.field);return{c:be,col:Be&&!S.has(Be)?Be:be.field}}).filter(be=>!A.has(be.col)&&!!A.add(be.col)),L=f.editing==="inline"?"":", editable: false";if(k.length===0)return L?`schemaToColumns(${a}).map((c) => ({ ...c${L} }))`:`schemaToColumns(${a})`;let F=k.map(be=>`'${be.col}'`),ee=k.map(({c:be,col:Be})=>{let Ue=[];return be.header&&Ue.push(`header: ${JSON.stringify(be.header)}`),be.width!=null&&Ue.push(`width: ${be.width}`),be.align&&Ue.push(`align: '${be.align}'`),be.aggregate&&Ue.push(`aggregate: '${be.aggregate}'`),f.treeData&&be.field===f.treeData.labelField&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(treeCell_${g}, { value: ctx.getValue(), row: ctx.row.original })`):be.cellType&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(${Qit(g,be.field)}, { value: ctx.getValue() })`):be.format&&Ue.push(`format: ${eur(be.format)}`),Ue.length?`'${Be}': { ${Ue.join(", ")} }`:null}).filter(be=>!!be),J=ee.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${ee.join(", ")} };`:"",te=ee.length?", ...(ov[String(c.field)] ?? {})":"",Ie=`[${F.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${a});${J} return ${L||te?`${Ie}.map((c) => ({ ...c${L}${te} }))`:Ie} })()`}function HF(a,i){let l=[`grid-column: span ${iM(a)}`,"min-width: 0"];i&&l.push(i);let p=fit(a.style);return p&&l.push(p),`style="${l.join("; ")}"`}var rur=a=>a&&a.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function L8(a,i){let l=[i,NH(a)].filter(Boolean).join(" ");return l?` class="${l}"`:""}function rfe(a){let i=LZ(a.className);return i?` ${i}`:""}function nur(a){let i=sR(a);if(i==="grid"){let l=VDe(a),p=l.maxWidth?` max-width: ${l.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${l.rowGap}px ${l.colGap}px; align-items: ${l.align};${p} }
76335
+ `}}function o2e(a){for(let p of a)O4(p);let i=new Map(a.map(p=>[p.name,p])),l=a.map(p=>{let f=Epr(p,i);return{schema:wpr(p,f),infos:f}});return{entries:l,seed:Apr(l)}}function Jpr(a,i={}){let{entries:l,seed:p}=o2e(a),{file:f,needs:g}=qpr(l,p,i.sources,i.supabaseConn,i.serverMemory),_=[kpr(l),f];(g.supabase||i.supabaseAuth)&&!g.supabaseUrl&&(i.supabaseConn?.url||i.supabaseConn?.key)&&(g.supabaseUrl=i.supabaseConn.url,g.supabaseKey=i.supabaseConn.key),(g.supabase||i.supabaseAuth)&&_.push(Kpr(g));for(let S of g.sqlRoutes)_.push(Wpr(S.schema,S.table,S.dialect,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],dbSchema:S.dbSchema,tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}));if(g.memoryRoutes.length){_.push(Gpr(g.memoryRoutes));for(let S of g.memoryRoutes)_.push(zpr(S.schema,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}))}return{files:_,prepared:l.map(S=>S.schema)}}var Ypr="3.1.53",Zpr="3.0.37",hb=(a,i)=>a.some(l=>l.config.kind===i),Bit=a=>`activeTab_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,KZ=(a,i)=>`${a}-${i}`,Uit=a=>`accOpen_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,QZ=(a,i)=>`${a}-s${i}`,XZ=a=>`md_${a.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function eur(a){switch(a.type){case"number":{let i=a.decimals;return i==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${i}, maximumFractionDigits: ${i} } }`}case"currency":return`{ type: 'currency', currency: ${_u(a.currency||"USD")} }`;case"percent":{let i=["type: 'percent'"];return a.valueIsPercentPoints&&i.push("valueIsPercentPoints: true"),a.decimals!=null&&i.push(`options: { minimumFractionDigits: ${a.decimals}, maximumFractionDigits: ${a.decimals} }`),`{ ${i.join(", ")} }`}case"date":case"datetime":return a.pattern?`{ type: '${a.type}', pattern: ${_u(a.pattern)} }`:`{ type: '${a.type}' }`}}function tur(a,i,l,p){if(i.config.kind!=="grid")return`schemaToColumns(${a})`;let f=i.config,g=i.id.replace(/-/g,"_"),_=f.columns.filter(be=>be.show),S=new Set(_.map(be=>be.field)),A=new Set,k=_.map(be=>{let Be=p?.get(be.field);return{c:be,col:Be&&!S.has(Be)?Be:be.field}}).filter(be=>!A.has(be.col)&&!!A.add(be.col)),L=f.editing==="inline"?"":", editable: false";if(k.length===0)return L?`schemaToColumns(${a}).map((c) => ({ ...c${L} }))`:`schemaToColumns(${a})`;let F=k.map(be=>`'${be.col}'`),ee=k.map(({c:be,col:Be})=>{let Ue=[];return be.header&&Ue.push(`header: ${JSON.stringify(be.header)}`),be.width!=null&&Ue.push(`width: ${be.width}`),be.align&&Ue.push(`align: '${be.align}'`),be.aggregate&&Ue.push(`aggregate: '${be.aggregate}'`),f.treeData&&be.field===f.treeData.labelField&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(treeCell_${g}, { value: ctx.getValue(), row: ctx.row.original })`):be.cellType&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(${Qit(g,be.field)}, { value: ctx.getValue() })`):be.format&&Ue.push(`format: ${eur(be.format)}`),Ue.length?`'${Be}': { ${Ue.join(", ")} }`:null}).filter(be=>!!be),J=ee.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${ee.join(", ")} };`:"",te=ee.length?", ...(ov[String(c.field)] ?? {})":"",Ie=`[${F.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${a});${J} return ${L||te?`${Ie}.map((c) => ({ ...c${L}${te} }))`:Ie} })()`}function HF(a,i){let l=[`grid-column: span ${iM(a)}`,"min-width: 0"];i&&l.push(i);let p=fit(a.style);return p&&l.push(p),`style="${l.join("; ")}"`}var rur=a=>a&&a.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function L8(a,i){let l=[i,NH(a)].filter(Boolean).join(" ");return l?` class="${l}"`:""}function rfe(a){let i=LZ(a.className);return i?` ${i}`:""}function nur(a){let i=sR(a);if(i==="grid"){let l=VDe(a),p=l.maxWidth?` max-width: ${l.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${l.rowGap}px ${l.colGap}px; align-items: ${l.align};${p} }
76336
76336
  @media (max-width: ${l.mobileBreakpoint}px) { .st-screen { grid-template-columns: 1fr; gap: 12px; } }
76337
76337
  `}if(i==="stack"){let l=Hue(a),p=l.maxWidth?` max-width: ${l.maxWidth}px;${l.align==="center"?" margin-inline: auto;":""}`:"",f=l.minHeight?`
76338
76338
  .st-stack > * { min-height: ${l.minHeight}px; }`:"",g=l.dividers?`
@@ -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-6EXkGGwz.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-DV6s9i9V.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">
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import{CRON_PRESETS}from"../scheduling";import{TRIGGER_CHOICES,fieldsOf,newTrigger,newWebhookToken,writableFields}from"./automation-edit";import{bm}from"./messages.svelte";let{automation,table,views=[],webhookUrl,onPatch}=$props();let copied=$state(false);async function copy(text){try{await navigator.clipboard.writeText(text);copied=true;setTimeout(()=>copied=false,1500)}catch{copied=false}}const forms=$derived(views.filter(v=>v.type==="form"));const buttons=$derived(fieldsOf(table).filter(c=>c.fieldType==="button"));function toggleWatched(id){if(automation.trigger.type!=="recordUpdated")return;const now=new Set(automation.trigger.fields??[]);if(now.has(id))now.delete(id);else now.add(id);onPatch({trigger:{type:"recordUpdated",fields:[...now]}})}
2
+ import{CRON_PRESETS}from"../scheduling";import{TRIGGER_CHOICES,fieldsOf,newTrigger,newWebhookToken,writableFields}from"./automation-edit";import{bm}from"./messages.svelte";import{cronWords}from"./cron-words";let{automation,table,views=[],webhookUrl,onPatch}=$props();let copied=$state(false);async function copy(text){try{await navigator.clipboard.writeText(text);copied=true;setTimeout(()=>copied=false,1500)}catch{copied=false}}const forms=$derived(views.filter(v=>v.type==="form"));const buttons=$derived(fieldsOf(table).filter(c=>c.fieldType==="button"));function toggleWatched(id){if(automation.trigger.type!=="recordUpdated")return;const now=new Set(automation.trigger.fields??[]);if(now.has(id))now.delete(id);else now.add(id);onPatch({trigger:{type:"recordUpdated",fields:[...now]}})}
3
3
  </script>
4
4
 
5
5
  <select class="sv-fvb-select sv-batr-type" aria-label={bm('extras.trigger')} value={automation.trigger.type} onchange={(e) => onPatch({ trigger: newTrigger(e.currentTarget.value as AutomationTrigger['type'], table) })}>
@@ -29,7 +29,7 @@ import{CRON_PRESETS}from"../scheduling";import{TRIGGER_CHOICES,fieldsOf,newTrigg
29
29
  {:else if automation.trigger.type === 'scheduled'}
30
30
  {@const cron = automation.trigger.cron}
31
31
  <select class="sv-fvb-select sv-batr-type" aria-label={bm('extras.schedule')} value={CRON_PRESETS.some((p) => p.cron === cron) ? cron : ''} onchange={(e) => e.currentTarget.value && onPatch({ trigger: { type: 'scheduled', cron: e.currentTarget.value } })}>
32
- {#each CRON_PRESETS as p (p.cron)}<option value={p.cron}>{p.label}</option>{/each}
32
+ {#each CRON_PRESETS as p (p.cron)}<option value={p.cron}>{cronWords(p.cron)}</option>{/each}
33
33
  <option value="">{bm('extras.customSchedule')}</option>
34
34
  </select>
35
35
  <input class="sv-fvb-input sv-batr-cron" aria-label={bm('extras.cronExpression')} value={cron} onchange={(e) => onPatch({ trigger: { type: 'scheduled', cron: e.currentTarget.value.trim() } })} />
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import{SvModal,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{triggerText}from"./automations.svelte";import{actionChoices,actionKey,newAction,newAutomation}from"./automation-edit";import{automationDrafter}from"./automation-drafter";import{bm}from"./messages.svelte";let{open=$bindable(false),table,tables,ctrl,views=[],runner,serverRuns,onServer=false,runOnServer,onChange}=$props();const side=a=>onServer?"server":a.runOn??"browser";let list=$state($state.snapshot(table.automations??[]));let selectedId=$state(list[0]?.id??null);let tab=$state("edit");const selected=$derived(list.find(a=>a.id===selectedId)??null);function save(next){list=next;onChange($state.snapshot(next))}function patch(change){if(!selected)return;save(list.map(a=>a.id===selected.id?{...a,...change}:a))}function add(){const a=newAutomation(table);save([...list,a]);selectedId=a.id;tab="edit"}const drafter=automationDrafter();let offer=$state(false);$effect(()=>{if(!open||!drafter)return;if(!drafter.available){offer=true;return}Promise.resolve().then(()=>drafter.available()).then(yes=>offer=!!yes,()=>offer=false)});let describeText=$state("");let describing=$state(false);let describeError=$state("");let describeQuestion=$state("");let drafted=$state(null);async function draftIt(){const text=describeText.trim();if(!drafter||!text||describing)return;describing=true;describeError="";describeQuestion="";try{const answer=await drafter.draft(text,table.id);if(answer.automation){const made=newAutomation(table);const a={...answer.automation,id:made.id,enabled:false};if(onServer)a.runOn="server";save([...list,a]);selectedId=a.id;tab="edit";drafted={id:a.id,words:answer.words??""};describeText="";announce(bm("extras.drafted"))}else{describeQuestion=answer.question||bm("extras.describeAgain")}}catch(e){describeError=e instanceof Error?e.message:String(e)}finally{describing=false}}let deleting=$state(null);function remove(id){const next=list.filter(a=>a.id!==id);save(next);selectedId=next[0]?.id??null}const EMPTY={kind:"fieldFilter",conjunction:"and",conditions:[]};function setCondition(f){patch({condition:f.conditions.length?f:void 0})}const ACTIONS=$derived(actionChoices());function setAction(i,next){if(!selected)return;const actions=[...selected.actions];if(next)actions[i]=next;else actions.splice(i,1);patch({actions})}function moveAction(i,dir){if(!selected)return;const actions=[...selected.actions];const j=i+dir;if(j<0||j>=actions.length)return;[actions[i],actions[j]]=[actions[j],actions[i]];patch({actions});announce(bm("extras.stepMoved",{from:i+1,to:j+1}))}let tryRecord=$state("");let serverRecords=$state.raw([]);$effect(()=>{if(table.source?.server)void runner.firstRecords(table.id,200).then(rows=>serverRecords=rows)});const records=$derived((table.source?.server?serverRecords:table.data.filter(Boolean).slice(0,200)).map(r=>({id:rowIdOf(table,r),name:String(r[primaryOf(table)]??"")||bm("extras.noName")})));let tryError=$state("");function tryNow(){if(!selected)return;const a=$state.snapshot(selected);tryError="";if(side(a)==="server"&&runOnServer){runOnServer(a,table.id,tryRecord||null).then(()=>showRuns(),e=>{tryError=e instanceof Error?e.message:String(e);showRuns()});return}void runner.runNow(a,table.id,tryRecord||null);tab="runs"}let fromServer=$state.raw([]);let serverError=$state("");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 time=at=>new Date(at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"});
2
+ import{SvModal,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{triggerText}from"./automations.svelte";import{actionChoices,actionKey,newAction,newAutomation}from"./automation-edit";import{automationDrafter}from"./automation-drafter";import{bm}from"./messages.svelte";let{open=$bindable(false),table,tables,ctrl,views=[],runner,serverRuns,onServer=false,runOnServer,onChange}=$props();const side=a=>onServer?"server":a.runOn??"browser";let list=$state($state.snapshot(table.automations??[]));let selectedId=$state(list[0]?.id??null);let tab=$state("edit");const selected=$derived(list.find(a=>a.id===selectedId)??null);function save(next){list=next;onChange($state.snapshot(next))}function patch(change){if(!selected)return;save(list.map(a=>a.id===selected.id?{...a,...change}:a))}function add(){const a=newAutomation(table);save([...list,a]);selectedId=a.id;tab="edit"}const drafter=automationDrafter();let offer=$state(false);$effect(()=>{if(!open||!drafter)return;if(!drafter.available){offer=true;return}Promise.resolve().then(()=>drafter.available()).then(yes=>offer=!!yes,()=>offer=false)});let describeText=$state("");let describing=$state(false);let describeError=$state("");let describeQuestion=$state("");let drafted=$state(null);async function draftIt(){const text=describeText.trim();if(!drafter||!text||describing)return;describing=true;describeError="";describeQuestion="";try{const answer=await drafter.draft(text,table.id);if(answer.automation){const made=newAutomation(table);const a={...answer.automation,id:made.id,enabled:false};if(onServer)a.runOn="server";save([...list,a]);selectedId=a.id;tab="edit";drafted={id:a.id,words:answer.words??""};announce(bm("extras.drafted"))}else{describeQuestion=answer.question||bm("extras.describeAgain")}}catch(e){describeError=e instanceof Error?e.message:String(e)}finally{describing=false}}let deleting=$state(null);function remove(id){const next=list.filter(a=>a.id!==id);save(next);selectedId=next[0]?.id??null}const EMPTY={kind:"fieldFilter",conjunction:"and",conditions:[]};function setCondition(f){patch({condition:f.conditions.length?f:void 0})}const ACTIONS=$derived(actionChoices());function setAction(i,next){if(!selected)return;const actions=[...selected.actions];if(next)actions[i]=next;else actions.splice(i,1);patch({actions})}function moveAction(i,dir){if(!selected)return;const actions=[...selected.actions];const j=i+dir;if(j<0||j>=actions.length)return;[actions[i],actions[j]]=[actions[j],actions[i]];patch({actions});announce(bm("extras.stepMoved",{from:i+1,to:j+1}))}let tryRecord=$state("");let serverRecords=$state.raw([]);$effect(()=>{if(table.source?.server)void runner.firstRecords(table.id,200).then(rows=>serverRecords=rows)});const records=$derived((table.source?.server?serverRecords:table.data.filter(Boolean).slice(0,200)).map(r=>({id:rowIdOf(table,r),name:String(r[primaryOf(table)]??"")||bm("extras.noName")})));let tryError=$state("");function tryNow(){if(!selected)return;const a=$state.snapshot(selected);tryError="";if(side(a)==="server"&&runOnServer){runOnServer(a,table.id,tryRecord||null).then(()=>showRuns(),e=>{tryError=e instanceof Error?e.message:String(e);showRuns()});return}void runner.runNow(a,table.id,tryRecord||null);tab="runs"}let fromServer=$state.raw([]);let serverError=$state("");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 time=at=>new Date(at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"});
3
3
  </script>
4
4
 
5
5
  <SvModal bind:open title={bm('extras.title', { table: table.name })} width={1000} resizable>
@@ -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{automationDrafter}from"./automation-drafter";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)}const drafter=automationDrafter();let offer=$state(false);$effect(()=>{if(!drafter)return;if(!drafter.available){offer=true;return}Promise.resolve().then(()=>drafter.available()).then(yes=>offer=!!yes,()=>offer=false)});let describeText=$state("");let describing=$state(false);let describeError=$state("");let describeQuestion=$state("");let drafted=$state(null);async function draftIt(){const text=describeText.trim();if(!drafter||!text||describing)return;describing=true;describeError="";describeQuestion="";try{const answer=await drafter.draft(text,"");const t=(answer.tableId?tableOf(answer.tableId):null)??current?.table??tables[0];if(answer.automation&&t){const a={...answer.automation,id:newAutomation(t).id,enabled:false};if(onServer)a.runOn="server";save(t.id,[...lists[t.id]??[],a]);pick(t.id,a.id);drafted={key:t.id+"/"+a.id,words:answer.words??""};describeText="";announce(bm("extras.drafted"))}else{describeQuestion=answer.question||bm("extras.describeAgain")}}catch(e){describeError=e instanceof Error?e.message:String(e)}finally{describing=false}}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"});
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{automationDrafter}from"./automation-drafter";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)}const drafter=automationDrafter();let offer=$state(false);$effect(()=>{if(!drafter)return;if(!drafter.available){offer=true;return}Promise.resolve().then(()=>drafter.available()).then(yes=>offer=!!yes,()=>offer=false)});let describeText=$state("");let describing=$state(false);let describeError=$state("");let describeQuestion=$state("");let drafted=$state(null);async function draftIt(){const text=describeText.trim();if(!drafter||!text||describing)return;describing=true;describeError="";describeQuestion="";try{const answer=await drafter.draft(text,"");const t=(answer.tableId?tableOf(answer.tableId):null)??current?.table??tables[0];if(answer.automation&&t){const a={...answer.automation,id:newAutomation(t).id,enabled:false};if(onServer)a.runOn="server";save(t.id,[...lists[t.id]??[],a]);pick(t.id,a.id);drafted={key:t.id+"/"+a.id,words:answer.words??""};announce(bm("extras.drafted"))}else{describeQuestion=answer.question||bm("extras.describeAgain")}}catch(e){describeError=e instanceof Error?e.message:String(e)}finally{describing=false}}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)}
@@ -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,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")}}
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";import{cronWords}from"./cron-words.js";const appActions=new Map;export function registerAutomationAction(id,action){appActions.set(id,action)}export function listAutomationActions(){return[...appActions].map(([id,a])=>({id,label:a.label}))}const readers=new WeakMap;export function tableFields(t){const hit=readers.get(t.columns);if(hit)return hit;const all=t.columns.map(d=>({...d,id:colId(d)}));const map=new Map;for(const d of t.columns){if(d.field==null)continue;const def=fillFieldColumn(d,all);map.set(colId(d),{id:colId(d),field:String(d.field),header:String(d.header??d.field),fieldType:d.fieldType,def,visible:true})}readers.set(t.columns,map);return map}const byName=(t,name)=>{const lower=name.trim().toLowerCase();for(const c of tableFields(t).values()){if(c.header.trim().toLowerCase()===lower||c.field.toLowerCase()===lower||c.id.toLowerCase()===lower)return c}return void 0};export function fillTokens(t,record,template,values){return template.replace(/\{([^{}\n]+)\}/g,(m,name)=>{const given=values?.get(name.trim().toLowerCase());if(given!==void 0)return given;const c=byName(t,name);return!c?m:record?fieldText(c,record):bm("extras.noRecordValue")})}export function 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:cronWords(tr.cron),condition:cond}):bm("extras.onSchedule",{cron:cronWords(tr.cron)});case"webhookReceived":return bm("extras.whenWebhook")}}
@@ -0,0 +1 @@
1
+ export declare function cronWords(cron: string): string;
@@ -0,0 +1 @@
1
+ import{bm as r}from"./messages.svelte.js";const i=(o,c)=>/^\d+$/.test(o)&&Number(o)<=c?Number(o):null;export function cronWords(o){const c=String(o??"").trim(),y=c.split(/\s+/),e=r("extras.cronOther",{cron:c});if(y.length!==5)return e;const[l,x,m,S,s]=y;if(S!=="*")return e;if(x==="*"&&m==="*"&&s==="*"){if(l==="*")return r("extras.cronEveryMinute");const a=/^\*\/(\d+)$/.exec(l);if(a)return r("extras.cronEveryMinutes",{n:Number(a[1])});const t=i(l,59);return t===0?r("extras.cronHourly"):t!=null?r("extras.cronHourlyAt",{minute:String(t).padStart(2,"0")}):e}const d=i(l,59),p=i(x,23);if(d==null||p==null)return e;const u=String(p).padStart(2,"0")+":"+String(d).padStart(2,"0");if(m==="*"){if(s==="*")return r("extras.cronDaily",{time:u});if(s==="1-5")return r("extras.cronWeekdays",{time:u});const a=s.split(",").map(n=>i(n,7));if(a.some(n=>n==null))return e;const t=[...new Set(a.map(n=>n%7))];return t.length===1?r("extras.cronWeekly"+t[0],{time:u}):r("extras.cronDays",{days:t.map(n=>r("extras.cronDay"+n)).join(", "),time:u})}const f=i(m,31);return f!=null&&f>=1&&s==="*"?r("extras.cronMonthly",{day:f,time:u}):e}
@@ -35,6 +35,7 @@ export { setViewActions, type ViewAction } from './view-actions.js';
35
35
  export type { RecordTemplate } from './base-tables.js';
36
36
  export { setRecordActions, type RecordAction, type RecordActionContext, type RecordActionRecord } from './record-actions.js';
37
37
  export { setAutomationDrafter, type AutomationDrafter, type AutomationDraft } from './automation-drafter.js';
38
+ export { cronWords } from './cron-words.js';
38
39
  export { setRecordComments, type RecordComment, type RecordCommentContext, type RecordCommentStore } from './activity.svelte.js';
39
40
  export { setCommentSnippets, type CommentSnippet, type CommentSnippets } from './comment-snippets.svelte.js';
40
41
  export { setFormSuggestions, type FormSuggestion, type FormSuggestions } from './form-suggestions.svelte.js';
@@ -1 +1 @@
1
- import{registerCellEditor as f,registerGridExtension as I,registerGridShortcuts as g}from"@svgrid/grid";import{nudgeEnterpriseFor as B}from"../license.js";import P from"./FieldCell.svelte";import L from"./RowAdder.svelte";import V from"./FootRowAdder.svelte";import H from"./AttachmentEditor.svelte";import K from"./FieldsHeaderEnd.svelte";import{askDeleteField as U,openFieldEditor as C,openRecord as _}from"./editor-request.svelte.js";import{enableAdvancedFilter as N,registerFilterKind as G}from"../advanced-filter-enable.js";import{compileFieldFilter as z,newCondition as h,resolveMeWith as $}from"./filter-model.js";import{hasBar as q,openBarPanel as w}from"./bar-request.svelte.js";import{groupRules as X,userSorts as j,writeSortState as W}from"./viewbar/sort-state.js";import{sortLabels as Y}from"./view-model.js";import{changesOf as J,noteChange as T}from"./activity.svelte.js";import{fieldUses as Q}from"./field-uses.js";import{getLinkedTable as Z}from"./sources.svelte.js";import{linkNames as ee,registerBaseCondition as oe}from"./base-alerts.js";import{duplicateField as re,hideField as ie,indexBeside as v,removeField as te}from"./field-ops.js";import{linkReaders as ne}from"./base-tables.js";import{viewOnlyItems as le}from"./base-share.js";import{canEditSchemaIn as se}from"./base-permissions.js";import{formulaReaders as de}from"./formula.js";import{BUILTIN_FIELD_TYPES as ae}from"./builtin-types.js";import{rowColorOf as me,rowColorRootClass as fe,tallRowClass as pe,rowMarkColor as ue,rowMarkLabel as ce}from"./row-colors.js";import{chooseRowColor as M}from"./row-color-choice.svelte.js";import{fieldPropsOf as A,fillFieldColumn as ge,getFieldType as x,isServerGroupRow as Ce,originalColumn as b,registerFieldType as be,typeDrawsCell as ye}from"./registry.svelte.js";import Fe from"./RatingEditor.svelte";import he from"./LinkPickerEditor.svelte";import we from"./DateEditor.svelte";import Te from"./SelectEditor.svelte";import ve from"./NumberEditor.svelte";import Me from"./LongTextEditor.svelte";import Ae from"./RichTextEditor.svelte";import xe from"./VoteEditor.svelte";import Ee from"./TimerEditor.svelte";import ke from"./ChecklistEditor.svelte";import Se from"./ColorEditor.svelte";import Re from"./TimeOfDayEditor.svelte";import De from"./RowHeader.svelte";import Oe from"./GroupHeader.svelte";import Ie from"./SummaryCell.svelte";import{getCurrentUser as E}from"./sources.svelte.js";import{fieldColumns as Be,gridOf as y,primaryIdOf as F,rememberGrid as Pe}from"./grid-access.js";import{bm as p}from"./messages.svelte.js";export{registerFieldType,getFieldType,listFieldTypes,fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";export{linkHref,linkText}from"./links.js";export{setFieldUsers,getFieldUsers,setCurrentUser,getCurrentUser,registerLinkedTable,unregisterLinkedTable,getLinkedTable,listLinkedTables}from"./sources.svelte.js";export{canEditField,defaultCanEditField,fieldEditors,setCanEditField,setFieldProtection}from"./field-access.svelte.js";import{protectionText as Le}from"./field-access.svelte.js";export{compileFormula,formulaError,FORMULA_FUNCTIONS,FormulaError}from"./formula.js";export{FORMULA_DOCS,syntaxArgs}from"./formula-docs.js";export{formatNumber,formatCurrency,formatPercent,formatDuration,parseDuration,formatDate}from"./format.js";export{timerRunning,timerSeconds,timerToggle,timerTotal}from"./timer.js";export{BRIGHT,OPTION_COLORS}from"./palette.js";export{convertValue,countCleared}from"./convert.js";export{openFieldEditor,closeFieldEditor,openRecord,closeRecord}from"./editor-request.svelte.js";export{setBarcodeScanner,barcodeScanSupported,scanBarcode}from"./barcode-scan.js";export{setDictation,dictationSupported,dictate}from"./dictation.svelte.js";export{default as SvBaseViewBar}from"./SvBaseViewBar.svelte";export{default as SvBaseForm}from"./SvBaseForm.svelte";export{default as SvBaseAutomations}from"./SvBaseAutomations.svelte";export{formPrefillLink,readFormPrefill}from"./form-logic.js";export{default as SvBase}from"./SvBase.svelte";export{addSubtasks,blankTable,newRecordId}from"./base-tables.js";export{baseSource,createBaseSync}from"./base-sync.js";export{baseFieldsFromSchema,baseTablesFromSchemas,baseSpecFromSchemas,baseTablesFromSpec}from"./base-schema.js";export{baseToSql,sqlName}from"./base-sql.js";export{applyBaseComments,withInverses}from"./base-schema.js";export{restoreItems,trashLabel}from"./base-trash.js";export{guessField,tableFromMatrix,recordsFromMatrix,matchColumns}from"./base-import.js";export{baseFromDatabase,describeDatabase,createBaseEndpoint,baseFromEndpoint,createBaseFeed,baseFromSupabase,isSecretColumn}from"./base-connect.js";export{baseFromAirtable,airtableFormulaSupport,airtableColor,formulaFunctionsUsed}from"./airtable.js";export{registerAutomationAction,listAutomationActions,MAX_DEPTH as AUTOMATION_MAX_DEPTH,REPEAT_MOST as AUTOMATION_REPEAT_MOST,allActions as allAutomationActions,scriptRecord,scriptInput,webhookValues,triggerValues}from"./automations.svelte.js";export{createAutomationServer}from"./automation-server.js";export{chatPayload,chatHostOk}from"./automation-outbound.js";export{runScript,SCRIPT_MAX_LENGTH}from"./automation-script.js";export{newWebhookToken}from"./automation-edit.js";export{setViewActions}from"./view-actions.js";export{setRecordActions}from"./record-actions.js";export{setAutomationDrafter}from"./automation-drafter.js";export{setRecordComments}from"./activity.svelte.js";export{setCommentSnippets}from"./comment-snippets.svelte.js";export{setFormSuggestions}from"./form-suggestions.svelte.js";export{setBaseMessages,baseMessages,BASE_MESSAGES}from"./messages.svelte.js";export{setRecordHistory,historyOf,loadHistory}from"./activity.svelte.js";export{setMentionHandler}from"./activity.svelte.js";export{mentionToken,mentionIds,mentionText,parseMentions,encodeMentions}from"./mentions.js";export{baseCondition,baseFilterOf}from"./base-alerts.js";export{compileFieldFilter,describeFieldFilter,filterKindOf,operatorsFor,ME}from"./filter-model.js";export{BUILTIN_FIELD_TYPES}from"./builtin-types.js";export{setAttachmentUploader,attachmentsFromText,attachmentsText,toAttachments}from"./attachments.js";const m={edit:"M4 20h4L19 9l-4-4L4 16zM14 6l4 4",left:"M10 6l-6 6 6 6M4 12h11M20 5v14",right:"M14 6l6 6-6 6M20 12H9M4 5v14",duplicate:"M8 8h12v12H8zM16 8V4H4v12h4",hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",remove:"M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",info:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 11v5M12 8h.01",lock:"M6 11h12v9H6zM8.5 11V8a3.5 3.5 0 0 1 7 0v3"};function Ve(o,r){const e=(o?.internalColumns??[]).find(d=>String(d.id??d.field)===r),i=e?.fieldType==="singleSelect"&&e.field?me(o)?.field===e.field?{key:"field-rowcolor",label:p("fields.menuStopColoring"),icon:m.color,run:()=>M(o,null)}:{key:"field-rowcolor",label:p("fields.menuColorRows"),icon:m.color,run:()=>M(o,{field:String(e.field),...o.props.rowColor?.target?{target:o.props.rowColor.target}:{}})}:null,t=F(o)===r,l=e&&q(o)?[...h(r,e)?[{key:"field-filter",label:p("fields.menuFilter"),icon:m.filter,separatorBefore:!0,run:()=>He(o,r,e)}]:[],...o.groupingControlsEnabled?[]:[{key:"field-group",label:p("fields.menuGroup"),icon:m.group,run:()=>Ke(o,r)}]]:[];return[...i?[i]:[],{key:"field-edit",label:p("fields.menuEdit"),icon:m.edit,run:()=>C({ctrl:o,mode:"edit",columnId:r})},...t?[]:[{key:"field-left",label:p("fields.menuInsertLeft"),icon:m.left,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"left")})}],{key:"field-right",label:p("fields.menuInsertRight"),icon:m.right,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"right")})},{key:"field-duplicate",label:p("fields.menuDuplicate"),icon:m.duplicate,run:()=>{o.props.baseRefuseDuplicate?.(r)||re(o,r)}},...t?[]:[{key:"field-move-left",label:p("fields.menuMoveLeft"),icon:m.left,disabled:!S(o,r,-1),run:()=>R(o,r,-1)},{key:"field-move-right",label:p("fields.menuMoveRight"),icon:m.right,disabled:!S(o,r,1),run:()=>R(o,r,1)}],...l,...Ye(o,r,e),...t?[]:[{key:"field-hide",label:p("fields.menuHide"),icon:m.hide,run:()=>ie(o,r)},{key:"field-delete",label:p("fields.menuDelete"),icon:m.remove,separatorBefore:!0,run:()=>e?.fieldType==="link"&&(e.fieldProps?.inverse&&Z(e.fieldProps.table)||ne({columns:o.internalColumns},e).length)||e&&de(o.internalColumns??[],e).length||Q(o,e).length?U({ctrl:o,columnId:r}):te(o,r)}]]}function k(o,r,e){const i=(o.allColumns??[]).map(l=>l.id),t=i[i.indexOf(r)+e];if(!(!t||t===F(o)||o.isColumnPinned?.(t)!==o.isColumnPinned?.(r)))return t}const S=(o,r,e)=>!!k(o,r,e);function R(o,r,e){const i=k(o,r,e);if(!i)return;const t=o.allColumns.map(n=>n.id),l=t.indexOf(r),d=t.indexOf(i);t[l]=i,t[d]=r;const a=o.grid.getAllColumns().map(n=>n.id),s=o.userColumnOrder??[];o.moveColumnsByUser(je(s.length?[...s,...a.filter(n=>!s.includes(n))]:a,t))}function He(o,r,e){const i=h(r,e);if(!i)return;const t=o.advancedFilter,l=t?.kind==="fieldFilter"?t:{kind:"fieldFilter",conjunction:"and",conditions:[]};o.buildApi().setAdvancedFilter({...l,conditions:[...l.conditions,i]}),w(o,"filter")}function Ke(o,r){const e=X(o);e.some(i=>i.id===r)||W(o.buildApi(),[...e,{id:r,desc:!1}],j(o)),w(o,"group")}function D(o,r,e,i,t){if(!r)return;const l=E()?.id,d=i??o.buildApi?.().getRowId?.(r),a=(s,n)=>{d!=null&&!t&&o.editedCellValues&&(o.editedCellValues={...o.editedCellValues,[`${d}:${s}`]:n})};for(const s of o?.internalColumns??[]){if(s.fieldType!=="lastModifiedTime"&&s.fieldType!=="lastModifiedBy")continue;const n=String(s.id??s.field);if(n===e||!s.field)continue;const u=A(b(s));u.watch==="specific"&&!(u.watchFields??[]).includes(e)||(s.fieldType==="lastModifiedTime"?a(n,r[s.field]=new Date().toISOString()):l!==void 0&&a(n,r[s.field]=l))}}export function baseReviewApplied(o){return(r,e,i)=>{const t=y(typeof o=="function"?o():o);if(!t)return;const l=t.buildApi?.(),d=l?.getOption?.("getRowId"),a=new Map;(i??l?.getData?.()??[]).forEach((n,u)=>a.set(String(d?d(n,u):u),n));const s=new Map((t.allColumns??[]).map(n=>[n.columnDef?.field,n.id]));for(const n of r){const u=a.get(n.rowId),c=s.get(n.field);!u||!c||(D(t,u,c),T(t,n.rowId,c,u[n.field],void 0,e==="undo"?void 0:n.source.label))}}}function Ue(o,r,e,i){if(!r)return;const t=(o?.allColumns??[]).find(c=>c.id===e)?.columnDef;if(!t?.field)return;const l=i??o.buildApi?.().getRowId?.(r);if(l==null)return;const d=String(l),a=r[t.field],s=o.history?.[o.historyPtr],n=[...J(o,d)].reverse().find(c=>c.columnId===e),u=s?.rowId===d&&s.columnId===e&&s.after===a?{from:s.before}:n?{from:n.value}:void 0;T(o,d,e,a,void 0,void 0,u)}function _e(o,r){if(o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.expandRows)return!1;const i=(e.allColumns??[]).find(l=>l.id===r.activeCell.columnId);if(i?.columnDef.editorType==="checkbox"||i?.columnDef.editorType==="fieldVote")return!1;const t=(e.allRows??[])[r.activeCell.rowIndex];return!t||e.isGroupRow?.(t)||Ce(t.original)?!1:(o.preventDefault(),_({ctrl:e,rowId:t.id}),!0)}function Ne(o,r){if(o.key!=="Enter"&&o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.baseDeleteSelection)return!1;const{rowIndex:i,colIndex:t}=r.activeCell,l=e.allColumns?.[t]?.columnDef.editorType,d=l==="checkbox";if(o.key===" "&&!d&&l!=="fieldVote")return!1;const a=r.ranges.at(-1);return o.key==="Enter"&&(r.ranges.length>1||a&&(a[0]!==a[2]||a[1]!==a[3]))||!e.isCellEditableAt(i,t)?!1:(o.preventDefault(),d?(e.toggleBooleanCell(i,t),!0):(r.startEditing(i,t),!!e.editingCell))}import{baseGridKey as Ge}from"./base-keys.svelte.js";import{treeGridKey as ze}from"./tree-edit.js";import{fillDownKey as $e}from"./base-fill.js";import{autoSumKey as qe,formatKey as Xe}from"./excel-habits.svelte.js";import{orderKeepingScreen as je}from"./column-order.js";let O=!1;export function enableFields(){if(O)return;O=!0;for(const e of ae)x(e.id)||be(e);I({column:(e,i)=>ge(e,i),cell:P,hasCell:e=>ye(e??{}),cellEdited:(e,i)=>{D(e,i.row,i.columnId,i.rowId,i.offGrid),Ue(e,i.row,i.columnId,i.rowId),We(e,i.row,i.columnId,i.rowId)},rangeAction:(e,i)=>e.props?.baseRangeAction?.(i)===!0,bodyEnd:L,footEnd:V,rowMarkColor:(e,i)=>ue(e,i),rowMarkLabel:(e,i)=>ce(e,i),headerIcon:e=>e?.fieldType?x(e.fieldType)?.icon:null,headerNote:e=>{if(!e?.fieldType)return null;const i=typeof e.description=="string"?e.description:"",t=Le(b(e),A(b(e)));return t?{text:i?`${t} ${i}`:t,icon:m.lock}:i?{text:i,icon:m.info}:null},sortLabels:e=>e?.fieldType?Y(e):null,lockColumn:(e,i)=>F(e)===i,rowHeader:e=>e?.props?.expandRows?De:null,groupRow:e=>!e?.props?.rowModel&&Be(e).some(i=>i.fieldType)?Oe:null,summaryCell:e=>e?.props?.rowModel?null:Ie,rootClass:e=>{Pe(e);const i=e?.advancedFilter?.kind==="fieldFilter"?"sv-fields-own-filter":"",t=i&&!e?.toolPanelEnabled&&!e?.chartingEnabled?"sv-fields-filter-only":"",l=e?.groupingColumns?.length?"sv-fields-grouped":"";return[fe(e),pe(e),i,t,l].filter(Boolean).join(" ")||null},headerEnd:K,columnMenuItems:(e,i)=>e?.props?.fieldMenu?le(e,Ve(e,i),!se(e)):[]});const o=e=>({value:e.value,typed:e.typed,columnDef:e.columnDef,columnId:e.columnId,row:e.row,onCommit:e.onCommit,onCancel:e.onCancel});f("fieldRating",{component:Fe,props:o,typeToEdit:e=>/^[0-9]$/.test(e)}),f("fieldLink",{component:he,props:o,typeToEdit:e=>e!==" "}),f("fieldNumber",{component:ve,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9.,:+\-(=]/.test(e)}),f("fieldLongText",{component:Me,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove})}),f("fieldSelect",{component:Te,props:e=>({...o(e),grid:e.grid,onChange:e.onChange,onCommitAndMove:e.onCommitAndMove})}),f("attachment",{component:H,props:e=>({value:e.value,columnDef:e.columnDef,columnId:e.columnId,row:e.row,onCommit:e.onCommit,onCancel:e.onCancel}),typeToEdit:!1});const r=e=>({...o(e),onCommitAndMove:e.onCommitAndMove});f("fieldChecklist",{component:ke,props:r}),f("fieldRichText",{component:Ae,props:r}),f("fieldVote",{component:xe,props:r,typeToEdit:e=>e===" "}),f("fieldTimer",{component:Ee,props:e=>({...r(e),rowId:e.rowId,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>e===" "||/[0-9:]/.test(e)}),f("fieldColor",{component:Se,props:r}),f("fieldTime",{component:Re,props:e=>({...r(e),onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9]/.test(e)}),f("fieldDate",{component:we,props:e=>({...r(e),onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9a-z]/i.test(e)}),G("fieldFilter",(e,i)=>z(e,i.getValue,ee)),$(()=>E()?.id),oe(),N(),g(_e,{id:"svgrid-fields-space"}),g(Ge,{id:"svgrid-fields-keys"}),g(Ne,{id:"svgrid-base-keys"}),g($e,{id:"svgrid-base-fill-down"}),g(qe,{id:"svgrid-base-autosum",priority:200}),g(Xe,{id:"svgrid-base-format-keys",priority:200}),g(ze,{id:"svgrid-base-tree"}),B("base","SvGrid Base")}export{inboxRecords,listColumns,listGroups,viewRecords}from"./list-view.js";import{aiFieldEdited as We,aiFieldMenuItems as Ye}from"./ai-field.svelte.js";export{generateAIField,regenerateAIFields,cancelAIField,pendingAIField,setAIFieldConcurrency}from"./ai-field.svelte.js";export{aiPromptError,readAIAnswer}from"./ai-prompt.js";export{moveTile,newTile,putTile,removeTile,tileResult,tileRows,tileTitle}from"./dashboard.js";export{sharedTables,sharedViews,shareOf}from"./base-share.js";export{recordsAsShown,downloadAsShown,filesFolders,safeFolder}from"./base-export.js";export{permittedTables,permittedRecords,permittedViews,tablePermissions,gridPermissions}from"./base-permissions.js";export{computeRecords,computeRecord,computedValues,computedFields,evaluateFilter,filterRecords}from"./base-compute.js";export{queryRecords,fieldFilterToSql,fieldFilterToPostgrest,supabaseFieldFilter,viewFilterOf}from"./base-query.js";export{searchBase}from"./base-search.js";export{toChecklist,parseChecklist,checklistText,checklistProgress}from"./checklist.js";export{parseColor}from"./color-value.js";export{parseTimeOfDay,formatTimeOfDay,timeSeconds}from"./time-of-day.js";
1
+ import{registerCellEditor as f,registerGridExtension as I,registerGridShortcuts as g}from"@svgrid/grid";import{nudgeEnterpriseFor as B}from"../license.js";import P from"./FieldCell.svelte";import L from"./RowAdder.svelte";import V from"./FootRowAdder.svelte";import H from"./AttachmentEditor.svelte";import K from"./FieldsHeaderEnd.svelte";import{askDeleteField as U,openFieldEditor as C,openRecord as _}from"./editor-request.svelte.js";import{enableAdvancedFilter as N,registerFilterKind as G}from"../advanced-filter-enable.js";import{compileFieldFilter as z,newCondition as h,resolveMeWith as $}from"./filter-model.js";import{hasBar as q,openBarPanel as w}from"./bar-request.svelte.js";import{groupRules as W,userSorts as X,writeSortState as j}from"./viewbar/sort-state.js";import{sortLabels as Y}from"./view-model.js";import{changesOf as J,noteChange as T}from"./activity.svelte.js";import{fieldUses as Q}from"./field-uses.js";import{getLinkedTable as Z}from"./sources.svelte.js";import{linkNames as ee,registerBaseCondition as oe}from"./base-alerts.js";import{duplicateField as re,hideField as ie,indexBeside as v,removeField as te}from"./field-ops.js";import{linkReaders as ne}from"./base-tables.js";import{viewOnlyItems as le}from"./base-share.js";import{canEditSchemaIn as se}from"./base-permissions.js";import{formulaReaders as de}from"./formula.js";import{BUILTIN_FIELD_TYPES as ae}from"./builtin-types.js";import{rowColorOf as me,rowColorRootClass as fe,tallRowClass as pe,rowMarkColor as ue,rowMarkLabel as ce}from"./row-colors.js";import{chooseRowColor as M}from"./row-color-choice.svelte.js";import{fieldPropsOf as A,fillFieldColumn as ge,getFieldType as x,isServerGroupRow as Ce,originalColumn as b,registerFieldType as be,typeDrawsCell as ye}from"./registry.svelte.js";import Fe from"./RatingEditor.svelte";import he from"./LinkPickerEditor.svelte";import we from"./DateEditor.svelte";import Te from"./SelectEditor.svelte";import ve from"./NumberEditor.svelte";import Me from"./LongTextEditor.svelte";import Ae from"./RichTextEditor.svelte";import xe from"./VoteEditor.svelte";import Ee from"./TimerEditor.svelte";import ke from"./ChecklistEditor.svelte";import Se from"./ColorEditor.svelte";import Re from"./TimeOfDayEditor.svelte";import De from"./RowHeader.svelte";import Oe from"./GroupHeader.svelte";import Ie from"./SummaryCell.svelte";import{getCurrentUser as E}from"./sources.svelte.js";import{fieldColumns as Be,gridOf as y,primaryIdOf as F,rememberGrid as Pe}from"./grid-access.js";import{bm as p}from"./messages.svelte.js";export{registerFieldType,getFieldType,listFieldTypes,fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";export{linkHref,linkText}from"./links.js";export{setFieldUsers,getFieldUsers,setCurrentUser,getCurrentUser,registerLinkedTable,unregisterLinkedTable,getLinkedTable,listLinkedTables}from"./sources.svelte.js";export{canEditField,defaultCanEditField,fieldEditors,setCanEditField,setFieldProtection}from"./field-access.svelte.js";import{protectionText as Le}from"./field-access.svelte.js";export{compileFormula,formulaError,FORMULA_FUNCTIONS,FormulaError}from"./formula.js";export{FORMULA_DOCS,syntaxArgs}from"./formula-docs.js";export{formatNumber,formatCurrency,formatPercent,formatDuration,parseDuration,formatDate}from"./format.js";export{timerRunning,timerSeconds,timerToggle,timerTotal}from"./timer.js";export{BRIGHT,OPTION_COLORS}from"./palette.js";export{convertValue,countCleared}from"./convert.js";export{openFieldEditor,closeFieldEditor,openRecord,closeRecord}from"./editor-request.svelte.js";export{setBarcodeScanner,barcodeScanSupported,scanBarcode}from"./barcode-scan.js";export{setDictation,dictationSupported,dictate}from"./dictation.svelte.js";export{default as SvBaseViewBar}from"./SvBaseViewBar.svelte";export{default as SvBaseForm}from"./SvBaseForm.svelte";export{default as SvBaseAutomations}from"./SvBaseAutomations.svelte";export{formPrefillLink,readFormPrefill}from"./form-logic.js";export{default as SvBase}from"./SvBase.svelte";export{addSubtasks,blankTable,newRecordId}from"./base-tables.js";export{baseSource,createBaseSync}from"./base-sync.js";export{baseFieldsFromSchema,baseTablesFromSchemas,baseSpecFromSchemas,baseTablesFromSpec}from"./base-schema.js";export{baseToSql,sqlName}from"./base-sql.js";export{applyBaseComments,withInverses}from"./base-schema.js";export{restoreItems,trashLabel}from"./base-trash.js";export{guessField,tableFromMatrix,recordsFromMatrix,matchColumns}from"./base-import.js";export{baseFromDatabase,describeDatabase,createBaseEndpoint,baseFromEndpoint,createBaseFeed,baseFromSupabase,isSecretColumn}from"./base-connect.js";export{baseFromAirtable,airtableFormulaSupport,airtableColor,formulaFunctionsUsed}from"./airtable.js";export{registerAutomationAction,listAutomationActions,MAX_DEPTH as AUTOMATION_MAX_DEPTH,REPEAT_MOST as AUTOMATION_REPEAT_MOST,allActions as allAutomationActions,scriptRecord,scriptInput,webhookValues,triggerValues}from"./automations.svelte.js";export{createAutomationServer}from"./automation-server.js";export{chatPayload,chatHostOk}from"./automation-outbound.js";export{runScript,SCRIPT_MAX_LENGTH}from"./automation-script.js";export{newWebhookToken}from"./automation-edit.js";export{setViewActions}from"./view-actions.js";export{setRecordActions}from"./record-actions.js";export{setAutomationDrafter}from"./automation-drafter.js";export{cronWords}from"./cron-words.js";export{setRecordComments}from"./activity.svelte.js";export{setCommentSnippets}from"./comment-snippets.svelte.js";export{setFormSuggestions}from"./form-suggestions.svelte.js";export{setBaseMessages,baseMessages,BASE_MESSAGES}from"./messages.svelte.js";export{setRecordHistory,historyOf,loadHistory}from"./activity.svelte.js";export{setMentionHandler}from"./activity.svelte.js";export{mentionToken,mentionIds,mentionText,parseMentions,encodeMentions}from"./mentions.js";export{baseCondition,baseFilterOf}from"./base-alerts.js";export{compileFieldFilter,describeFieldFilter,filterKindOf,operatorsFor,ME}from"./filter-model.js";export{BUILTIN_FIELD_TYPES}from"./builtin-types.js";export{setAttachmentUploader,attachmentsFromText,attachmentsText,toAttachments}from"./attachments.js";const m={edit:"M4 20h4L19 9l-4-4L4 16zM14 6l4 4",left:"M10 6l-6 6 6 6M4 12h11M20 5v14",right:"M14 6l6 6-6 6M20 12H9M4 5v14",duplicate:"M8 8h12v12H8zM16 8V4H4v12h4",hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",remove:"M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",info:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 11v5M12 8h.01",lock:"M6 11h12v9H6zM8.5 11V8a3.5 3.5 0 0 1 7 0v3"};function Ve(o,r){const e=(o?.internalColumns??[]).find(d=>String(d.id??d.field)===r),i=e?.fieldType==="singleSelect"&&e.field?me(o)?.field===e.field?{key:"field-rowcolor",label:p("fields.menuStopColoring"),icon:m.color,run:()=>M(o,null)}:{key:"field-rowcolor",label:p("fields.menuColorRows"),icon:m.color,run:()=>M(o,{field:String(e.field),...o.props.rowColor?.target?{target:o.props.rowColor.target}:{}})}:null,t=F(o)===r,l=e&&q(o)?[...h(r,e)?[{key:"field-filter",label:p("fields.menuFilter"),icon:m.filter,separatorBefore:!0,run:()=>He(o,r,e)}]:[],...o.groupingControlsEnabled?[]:[{key:"field-group",label:p("fields.menuGroup"),icon:m.group,run:()=>Ke(o,r)}]]:[];return[...i?[i]:[],{key:"field-edit",label:p("fields.menuEdit"),icon:m.edit,run:()=>C({ctrl:o,mode:"edit",columnId:r})},...t?[]:[{key:"field-left",label:p("fields.menuInsertLeft"),icon:m.left,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"left")})}],{key:"field-right",label:p("fields.menuInsertRight"),icon:m.right,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"right")})},{key:"field-duplicate",label:p("fields.menuDuplicate"),icon:m.duplicate,run:()=>{o.props.baseRefuseDuplicate?.(r)||re(o,r)}},...t?[]:[{key:"field-move-left",label:p("fields.menuMoveLeft"),icon:m.left,disabled:!S(o,r,-1),run:()=>R(o,r,-1)},{key:"field-move-right",label:p("fields.menuMoveRight"),icon:m.right,disabled:!S(o,r,1),run:()=>R(o,r,1)}],...l,...Ye(o,r,e),...t?[]:[{key:"field-hide",label:p("fields.menuHide"),icon:m.hide,run:()=>ie(o,r)},{key:"field-delete",label:p("fields.menuDelete"),icon:m.remove,separatorBefore:!0,run:()=>e?.fieldType==="link"&&(e.fieldProps?.inverse&&Z(e.fieldProps.table)||ne({columns:o.internalColumns},e).length)||e&&de(o.internalColumns??[],e).length||Q(o,e).length?U({ctrl:o,columnId:r}):te(o,r)}]]}function k(o,r,e){const i=(o.allColumns??[]).map(l=>l.id),t=i[i.indexOf(r)+e];if(!(!t||t===F(o)||o.isColumnPinned?.(t)!==o.isColumnPinned?.(r)))return t}const S=(o,r,e)=>!!k(o,r,e);function R(o,r,e){const i=k(o,r,e);if(!i)return;const t=o.allColumns.map(n=>n.id),l=t.indexOf(r),d=t.indexOf(i);t[l]=i,t[d]=r;const a=o.grid.getAllColumns().map(n=>n.id),s=o.userColumnOrder??[];o.moveColumnsByUser(Xe(s.length?[...s,...a.filter(n=>!s.includes(n))]:a,t))}function He(o,r,e){const i=h(r,e);if(!i)return;const t=o.advancedFilter,l=t?.kind==="fieldFilter"?t:{kind:"fieldFilter",conjunction:"and",conditions:[]};o.buildApi().setAdvancedFilter({...l,conditions:[...l.conditions,i]}),w(o,"filter")}function Ke(o,r){const e=W(o);e.some(i=>i.id===r)||j(o.buildApi(),[...e,{id:r,desc:!1}],X(o)),w(o,"group")}function D(o,r,e,i,t){if(!r)return;const l=E()?.id,d=i??o.buildApi?.().getRowId?.(r),a=(s,n)=>{d!=null&&!t&&o.editedCellValues&&(o.editedCellValues={...o.editedCellValues,[`${d}:${s}`]:n})};for(const s of o?.internalColumns??[]){if(s.fieldType!=="lastModifiedTime"&&s.fieldType!=="lastModifiedBy")continue;const n=String(s.id??s.field);if(n===e||!s.field)continue;const u=A(b(s));u.watch==="specific"&&!(u.watchFields??[]).includes(e)||(s.fieldType==="lastModifiedTime"?a(n,r[s.field]=new Date().toISOString()):l!==void 0&&a(n,r[s.field]=l))}}export function baseReviewApplied(o){return(r,e,i)=>{const t=y(typeof o=="function"?o():o);if(!t)return;const l=t.buildApi?.(),d=l?.getOption?.("getRowId"),a=new Map;(i??l?.getData?.()??[]).forEach((n,u)=>a.set(String(d?d(n,u):u),n));const s=new Map((t.allColumns??[]).map(n=>[n.columnDef?.field,n.id]));for(const n of r){const u=a.get(n.rowId),c=s.get(n.field);!u||!c||(D(t,u,c),T(t,n.rowId,c,u[n.field],void 0,e==="undo"?void 0:n.source.label))}}}function Ue(o,r,e,i){if(!r)return;const t=(o?.allColumns??[]).find(c=>c.id===e)?.columnDef;if(!t?.field)return;const l=i??o.buildApi?.().getRowId?.(r);if(l==null)return;const d=String(l),a=r[t.field],s=o.history?.[o.historyPtr],n=[...J(o,d)].reverse().find(c=>c.columnId===e),u=s?.rowId===d&&s.columnId===e&&s.after===a?{from:s.before}:n?{from:n.value}:void 0;T(o,d,e,a,void 0,void 0,u)}function _e(o,r){if(o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.expandRows)return!1;const i=(e.allColumns??[]).find(l=>l.id===r.activeCell.columnId);if(i?.columnDef.editorType==="checkbox"||i?.columnDef.editorType==="fieldVote")return!1;const t=(e.allRows??[])[r.activeCell.rowIndex];return!t||e.isGroupRow?.(t)||Ce(t.original)?!1:(o.preventDefault(),_({ctrl:e,rowId:t.id}),!0)}function Ne(o,r){if(o.key!=="Enter"&&o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.baseDeleteSelection)return!1;const{rowIndex:i,colIndex:t}=r.activeCell,l=e.allColumns?.[t]?.columnDef.editorType,d=l==="checkbox";if(o.key===" "&&!d&&l!=="fieldVote")return!1;const a=r.ranges.at(-1);return o.key==="Enter"&&(r.ranges.length>1||a&&(a[0]!==a[2]||a[1]!==a[3]))||!e.isCellEditableAt(i,t)?!1:(o.preventDefault(),d?(e.toggleBooleanCell(i,t),!0):(r.startEditing(i,t),!!e.editingCell))}import{baseGridKey as Ge}from"./base-keys.svelte.js";import{treeGridKey as ze}from"./tree-edit.js";import{fillDownKey as $e}from"./base-fill.js";import{autoSumKey as qe,formatKey as We}from"./excel-habits.svelte.js";import{orderKeepingScreen as Xe}from"./column-order.js";let O=!1;export function enableFields(){if(O)return;O=!0;for(const e of ae)x(e.id)||be(e);I({column:(e,i)=>ge(e,i),cell:P,hasCell:e=>ye(e??{}),cellEdited:(e,i)=>{D(e,i.row,i.columnId,i.rowId,i.offGrid),Ue(e,i.row,i.columnId,i.rowId),je(e,i.row,i.columnId,i.rowId)},rangeAction:(e,i)=>e.props?.baseRangeAction?.(i)===!0,bodyEnd:L,footEnd:V,rowMarkColor:(e,i)=>ue(e,i),rowMarkLabel:(e,i)=>ce(e,i),headerIcon:e=>e?.fieldType?x(e.fieldType)?.icon:null,headerNote:e=>{if(!e?.fieldType)return null;const i=typeof e.description=="string"?e.description:"",t=Le(b(e),A(b(e)));return t?{text:i?`${t} ${i}`:t,icon:m.lock}:i?{text:i,icon:m.info}:null},sortLabels:e=>e?.fieldType?Y(e):null,lockColumn:(e,i)=>F(e)===i,rowHeader:e=>e?.props?.expandRows?De:null,groupRow:e=>!e?.props?.rowModel&&Be(e).some(i=>i.fieldType)?Oe:null,summaryCell:e=>e?.props?.rowModel?null:Ie,rootClass:e=>{Pe(e);const i=e?.advancedFilter?.kind==="fieldFilter"?"sv-fields-own-filter":"",t=i&&!e?.toolPanelEnabled&&!e?.chartingEnabled?"sv-fields-filter-only":"",l=e?.groupingColumns?.length?"sv-fields-grouped":"";return[fe(e),pe(e),i,t,l].filter(Boolean).join(" ")||null},headerEnd:K,columnMenuItems:(e,i)=>e?.props?.fieldMenu?le(e,Ve(e,i),!se(e)):[]});const o=e=>({value:e.value,typed:e.typed,columnDef:e.columnDef,columnId:e.columnId,row:e.row,onCommit:e.onCommit,onCancel:e.onCancel});f("fieldRating",{component:Fe,props:o,typeToEdit:e=>/^[0-9]$/.test(e)}),f("fieldLink",{component:he,props:o,typeToEdit:e=>e!==" "}),f("fieldNumber",{component:ve,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9.,:+\-(=]/.test(e)}),f("fieldLongText",{component:Me,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove})}),f("fieldSelect",{component:Te,props:e=>({...o(e),grid:e.grid,onChange:e.onChange,onCommitAndMove:e.onCommitAndMove})}),f("attachment",{component:H,props:e=>({value:e.value,columnDef:e.columnDef,columnId:e.columnId,row:e.row,onCommit:e.onCommit,onCancel:e.onCancel}),typeToEdit:!1});const r=e=>({...o(e),onCommitAndMove:e.onCommitAndMove});f("fieldChecklist",{component:ke,props:r}),f("fieldRichText",{component:Ae,props:r}),f("fieldVote",{component:xe,props:r,typeToEdit:e=>e===" "}),f("fieldTimer",{component:Ee,props:e=>({...r(e),rowId:e.rowId,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>e===" "||/[0-9:]/.test(e)}),f("fieldColor",{component:Se,props:r}),f("fieldTime",{component:Re,props:e=>({...r(e),onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9]/.test(e)}),f("fieldDate",{component:we,props:e=>({...r(e),onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9a-z]/i.test(e)}),G("fieldFilter",(e,i)=>z(e,i.getValue,ee)),$(()=>E()?.id),oe(),N(),g(_e,{id:"svgrid-fields-space"}),g(Ge,{id:"svgrid-fields-keys"}),g(Ne,{id:"svgrid-base-keys"}),g($e,{id:"svgrid-base-fill-down"}),g(qe,{id:"svgrid-base-autosum",priority:200}),g(We,{id:"svgrid-base-format-keys",priority:200}),g(ze,{id:"svgrid-base-tree"}),B("base","SvGrid Base")}export{inboxRecords,listColumns,listGroups,viewRecords}from"./list-view.js";import{aiFieldEdited as je,aiFieldMenuItems as Ye}from"./ai-field.svelte.js";export{generateAIField,regenerateAIFields,cancelAIField,pendingAIField,setAIFieldConcurrency}from"./ai-field.svelte.js";export{aiPromptError,readAIAnswer}from"./ai-prompt.js";export{moveTile,newTile,putTile,removeTile,tileResult,tileRows,tileTitle}from"./dashboard.js";export{sharedTables,sharedViews,shareOf}from"./base-share.js";export{recordsAsShown,downloadAsShown,filesFolders,safeFolder}from"./base-export.js";export{permittedTables,permittedRecords,permittedViews,tablePermissions,gridPermissions}from"./base-permissions.js";export{computeRecords,computeRecord,computedValues,computedFields,evaluateFilter,filterRecords}from"./base-compute.js";export{queryRecords,fieldFilterToSql,fieldFilterToPostgrest,supabaseFieldFilter,viewFilterOf}from"./base-query.js";export{searchBase}from"./base-search.js";export{toChecklist,parseChecklist,checklistText,checklistProgress}from"./checklist.js";export{parseColor}from"./color-value.js";export{parseTimeOfDay,formatTimeOfDay,timeSeconds}from"./time-of-day.js";
@@ -17,8 +17,31 @@ export declare const EXTRAS_MESSAGES: {
17
17
  readonly 'extras.whenForm': "When a form is sent";
18
18
  readonly 'extras.whenFormWhere': "When a form is sent, where {condition}";
19
19
  readonly 'extras.whenPressed': "When {field} is pressed";
20
- readonly 'extras.onSchedule': "On a schedule ({cron})";
21
- readonly 'extras.onScheduleWhere': "On a schedule ({cron}), for records where {condition}";
20
+ readonly 'extras.onSchedule': "{cron}";
21
+ readonly 'extras.onScheduleWhere': "{cron}, for records where {condition}";
22
+ readonly 'extras.cronOther': "On a schedule ({cron})";
23
+ readonly 'extras.cronEveryMinute': "Every minute";
24
+ readonly 'extras.cronEveryMinutes': "Every {n} minutes";
25
+ readonly 'extras.cronHourly': "Every hour, on the hour";
26
+ readonly 'extras.cronHourlyAt': "Every hour at {minute} past";
27
+ readonly 'extras.cronDaily': "Every day at {time}";
28
+ readonly 'extras.cronWeekdays': "Every weekday at {time}";
29
+ readonly 'extras.cronWeekly0': "Every Sunday at {time}";
30
+ readonly 'extras.cronWeekly1': "Every Monday at {time}";
31
+ readonly 'extras.cronWeekly2': "Every Tuesday at {time}";
32
+ readonly 'extras.cronWeekly3': "Every Wednesday at {time}";
33
+ readonly 'extras.cronWeekly4': "Every Thursday at {time}";
34
+ readonly 'extras.cronWeekly5': "Every Friday at {time}";
35
+ readonly 'extras.cronWeekly6': "Every Saturday at {time}";
36
+ readonly 'extras.cronDays': "Every {days} at {time}";
37
+ readonly 'extras.cronDay0': "Sunday";
38
+ readonly 'extras.cronDay1': "Monday";
39
+ readonly 'extras.cronDay2': "Tuesday";
40
+ readonly 'extras.cronDay3': "Wednesday";
41
+ readonly 'extras.cronDay4': "Thursday";
42
+ readonly 'extras.cronDay5': "Friday";
43
+ readonly 'extras.cronDay6': "Saturday";
44
+ readonly 'extras.cronMonthly': "Day {day} of every month at {time}";
22
45
  readonly 'extras.actionUpdateRecord': "Update record";
23
46
  readonly 'extras.actionCreateRecord': "Create record";
24
47
  readonly 'extras.actionNotify': "Show a notice";
@@ -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.describeLabel":"Describe what should happen","extras.describePlaceholder":"For example: every Monday at 8:00, e-mail me the tasks that are not done","extras.describeButton":"Draft it","extras.describing":"Drafting...","extras.describeAgain":"Say a little more about what should happen, then try again.","extras.drafted":"Drafted from your words and switched off. Check each part, then switch it on.","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.notifyTo":"Also send it to the notifications of:","extras.notifyToField":"The people in {field}","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"};
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":"{cron}","extras.onScheduleWhere":"{cron}, for records where {condition}","extras.cronOther":"On a schedule ({cron})","extras.cronEveryMinute":"Every minute","extras.cronEveryMinutes":"Every {n} minutes","extras.cronHourly":"Every hour, on the hour","extras.cronHourlyAt":"Every hour at {minute} past","extras.cronDaily":"Every day at {time}","extras.cronWeekdays":"Every weekday at {time}","extras.cronWeekly0":"Every Sunday at {time}","extras.cronWeekly1":"Every Monday at {time}","extras.cronWeekly2":"Every Tuesday at {time}","extras.cronWeekly3":"Every Wednesday at {time}","extras.cronWeekly4":"Every Thursday at {time}","extras.cronWeekly5":"Every Friday at {time}","extras.cronWeekly6":"Every Saturday at {time}","extras.cronDays":"Every {days} at {time}","extras.cronDay0":"Sunday","extras.cronDay1":"Monday","extras.cronDay2":"Tuesday","extras.cronDay3":"Wednesday","extras.cronDay4":"Thursday","extras.cronDay5":"Friday","extras.cronDay6":"Saturday","extras.cronMonthly":"Day {day} of every month at {time}","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.describeLabel":"Describe what should happen","extras.describePlaceholder":"For example: every Monday at 8:00, e-mail me the tasks that are not done","extras.describeButton":"Draft it","extras.describing":"Drafting...","extras.describeAgain":"Say a little more about what should happen, then try again.","extras.drafted":"Drafted from your words and switched off. Check each part, then switch it on.","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.notifyTo":"Also send it to the notifications of:","extras.notifyToField":"The people in {field}","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"};
@@ -166,8 +166,31 @@ export declare const BASE_MESSAGES: {
166
166
  readonly 'extras.whenForm': "When a form is sent";
167
167
  readonly 'extras.whenFormWhere': "When a form is sent, where {condition}";
168
168
  readonly 'extras.whenPressed': "When {field} is pressed";
169
- readonly 'extras.onSchedule': "On a schedule ({cron})";
170
- readonly 'extras.onScheduleWhere': "On a schedule ({cron}), for records where {condition}";
169
+ readonly 'extras.onSchedule': "{cron}";
170
+ readonly 'extras.onScheduleWhere': "{cron}, for records where {condition}";
171
+ readonly 'extras.cronOther': "On a schedule ({cron})";
172
+ readonly 'extras.cronEveryMinute': "Every minute";
173
+ readonly 'extras.cronEveryMinutes': "Every {n} minutes";
174
+ readonly 'extras.cronHourly': "Every hour, on the hour";
175
+ readonly 'extras.cronHourlyAt': "Every hour at {minute} past";
176
+ readonly 'extras.cronDaily': "Every day at {time}";
177
+ readonly 'extras.cronWeekdays': "Every weekday at {time}";
178
+ readonly 'extras.cronWeekly0': "Every Sunday at {time}";
179
+ readonly 'extras.cronWeekly1': "Every Monday at {time}";
180
+ readonly 'extras.cronWeekly2': "Every Tuesday at {time}";
181
+ readonly 'extras.cronWeekly3': "Every Wednesday at {time}";
182
+ readonly 'extras.cronWeekly4': "Every Thursday at {time}";
183
+ readonly 'extras.cronWeekly5': "Every Friday at {time}";
184
+ readonly 'extras.cronWeekly6': "Every Saturday at {time}";
185
+ readonly 'extras.cronDays': "Every {days} at {time}";
186
+ readonly 'extras.cronDay0': "Sunday";
187
+ readonly 'extras.cronDay1': "Monday";
188
+ readonly 'extras.cronDay2': "Tuesday";
189
+ readonly 'extras.cronDay3': "Wednesday";
190
+ readonly 'extras.cronDay4': "Thursday";
191
+ readonly 'extras.cronDay5': "Friday";
192
+ readonly 'extras.cronDay6': "Saturday";
193
+ readonly 'extras.cronMonthly': "Day {day} of every month at {time}";
171
194
  readonly 'extras.actionUpdateRecord': "Update record";
172
195
  readonly 'extras.actionCreateRecord': "Create record";
173
196
  readonly 'extras.actionNotify': "Show a notice";