@univerjs-pro/bases 1.6.1 → 1.7.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/{config-BLXIbpvl.js → config-AfiyXtDJ.js} +1 -1
- package/lib/cjs/facade.js +1 -1
- package/lib/cjs/index.js +1 -1
- package/lib/cjs/worker.js +1 -1
- package/lib/{config-pca1eLu8.js → config-D64l6SYF.js} +1 -1
- package/lib/es/{config-pca1eLu8.js → config-D64l6SYF.js} +1 -1
- package/lib/es/facade.js +1 -1
- package/lib/es/index.js +1 -1
- package/lib/es/worker.js +1 -1
- package/lib/facade.js +1 -1
- package/lib/index.js +1 -1
- package/lib/types/commands/commands/update-base-field.command.d.ts +2 -0
- package/lib/types/controllers/base-active-dirty.controller.d.ts +1 -1
- package/lib/types/controllers/base-formula-calculation.controller.d.ts +1 -2
- package/lib/types/embed-host-anchor.d.ts +0 -9
- package/lib/types/facade/f-field.d.ts +2 -2
- package/lib/types/facade/f-table.d.ts +2 -2
- package/lib/types/fields/select-options.d.ts +19 -0
- package/lib/types/index.d.ts +1 -0
- package/lib/types/models/base-cell-data.d.ts +0 -1
- package/lib/types/ot/json1-op-factory.d.ts +1 -1
- package/lib/types/services/base-command.service.d.ts +1 -0
- package/lib/types/services/base-formula.service.d.ts +1 -1
- package/lib/types/services/base-performance.service.d.ts +0 -1
- package/lib/umd/facade.js +1 -1
- package/lib/umd/index.js +2 -2
- package/lib/worker.js +1 -1
- package/package.json +9 -10
- package/lib/types/commands/undo-redo.d.ts +0 -2
- package/lib/types/controllers/base-formula-optional-identifier.d.ts +0 -1
- package/lib/types/ot/json1-adapter.d.ts +0 -102
package/lib/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./config-BLXIbpvl.js");let t=require("@univerjs/core"),n=require("@univerjs-pro/engine-formula"),r=require("@univerjs/protocol"),i=require("@univerjs-pro/license"),a=require("@univerjs/rpc"),o=require("@univerjs/engine-formula");const s={table:e=>[`tables`,e],field:(e,t)=>[`tables`,e,`fields`,t],fieldOrder:(e,t)=>[`tables`,e,`fieldOrder`,t],record:(e,t)=>[`tables`,e,`records`,t],cell:(e,t,n)=>[`tables`,e,`records`,t,`values`,n],cellData:(e,t,n)=>[`tables`,e,`cellData`,String(t),String(n)],attachmentSet:(e,t)=>[`tables`,e,`resources`,`attachmentSets`,t],attachment:(e,t)=>[`tables`,e,`resources`,`attachments`,t],view:(e,t)=>[`tables`,e,`views`,t],viewFieldHidden:(e,t,n)=>[`tables`,e,`views`,t,`fieldSettings`,n,`hidden`]};var c=class{setBaseName(t,n){let r=this.renameFormulaUnitReferences(t,t.name,n);return e.M([this._replaceOptional([`name`],t.name,n),...r?[r]:[]])}renameFormulaUnitReferences(r,i,a){let o=Object.values(r.tables).flatMap(e=>Object.values(e.fields).flatMap(r=>{var o,c;if(r.type!==t.BaseFieldType.Formula)return[];let l=String(((o=r.config)==null?void 0:o.formula)??``),u=(0,n.refactorFormulaUnitQualifier)(l,i,a);return u===l?[]:[this._replaceOptional([...s.field(e.id,r.id),`config`,`formula`],(c=r.config)==null?void 0:c.formula,u)]}));return o.length>0?e.M(o):void 0}createTable(n,r,i=n.tableOrder.length){let a=(0,t.allocateBaseFormulaTableName)(r.name,(0,t.createBaseFormulaTableNameMap)(n).values(),r.formulaName),o=r.formulaName===a?r:{...r,formulaName:a};return e.M([...this._materializeFormulaTableNames(n),t.JSON1.insertOp(s.table(r.id),o),t.JSON1.insertOp([`tableOrder`,i],r.id)])}renameTable(n,r,i){let a=n.tables[r];return e.M([...this._materializeFormulaTableNames(n),t.JSON1.replaceOp([...s.table(r),`name`],a.name,i)])}deleteTable(n,r){let i=n.tables[r],a=n.tableOrder.indexOf(r);return e.M([...this._materializeFormulaTableNames(n,/* @__PURE__ */ new Set([r])),t.JSON1.removeOp(s.table(r),i),t.JSON1.removeOp([`tableOrder`,a],r)])}createRecord(e,t,n){return this.createRecords(e,t,[n])}createRecords(n,r,i){let a=n.tables[r],o=i.filter(e=>e&&!a.records[e.id]).map(e=>({...e,values:{...e.values,[t.BASE_RECORD_ID_FIELD_ID]:e.id}}));if(!o.length)return t.JSON1.replaceOp([...s.table(r),`records`],a.records,a.records);let c=new t.JSON1.WriteCursor,l=[...o].sort((e,t)=>e.id<t.id?-1:+(e.id>t.id)),u=[...s.table(r),`records`];c.descendPath(u);for(let e of l)c.descend(e.id),c.write(`i`,e),c.ascend();for(let e=0;e<u.length;e+=1)c.ascend();return e.M([c.get(),this._createRecordOrderOp(n,r,o)])}deleteRecord(e,t,n){return this.deleteRecords(e,t,[n])}deleteRecords(n,r,i){let a=n.tables[r],o=Array.from(new Set(i)).filter(e=>a.records[e]);if(!o.length)return t.JSON1.replaceOp([...s.table(r),`records`],a.records,a.records);let c=new Set(o),l=e.Z(a,o).map(e=>this.updateCell(n,r,e.recordId,e.fieldId,``));return e.M([this._deleteRecordsBaseOp(n,r,o,c),...l])}createDeleteRecordsUndoOp(t,n,r,i){let a=t.tables[r],o=Array.from(new Set(i)).filter(e=>a.records[e]),s=new Set(o),c=new e.j().invertOp(t,this._deleteRecordsBaseOp(t,r,o,s)),l=e.Z(a,o).map(e=>this.updateCell(n,r,e.recordId,e.fieldId,e.oldParentRecordId??``));return e.M([c,...l])}_deleteRecordsBaseOp(n,r,i,a){let o=n.tables[r],c=i.map(e=>{var t;return{recordId:e,index:((t=o.recordOrder)==null?void 0:t.indexOf(e))??-1}}).filter(e=>e.index>=0).sort((e,t)=>t.index-e.index);return e.M([...i.map(e=>t.JSON1.removeOp(s.record(r,e),o.records[e])),...c.map(({recordId:e,index:n})=>t.JSON1.removeOp([`tables`,r,`recordOrder`,n],e)),...this._deleteAttachmentResources(o,r,e=>{let t=e.slice(e.lastIndexOf(``)+1);return a.has(t)})])}duplicateRecord(e,n,r,i){return this.createRecord(e,n,{...i,values:{...e.tables[n].records[r].values,...i.values,[t.BASE_RECORD_ID_FIELD_ID]:i.id}})}updateRecordOrder(t,n,r,i){let a=t.tables[n],o=[...s.record(n,r),`orderKey`],c=Object.values(a.records).map(e=>e.id===r?{...e,orderKey:i}:e).sort((e,t)=>String(e.orderKey??e.id).localeCompare(String(t.orderKey??t.id))).map(e=>e.id),u=[...s.table(n),`recordOrder`],d=a.recordOrder,f=c.filter(e=>e!==r),p=d==null?void 0:d.filter(e=>e!==r),m=d!=null&&d.includes(r)&&(p==null?void 0:p.length)===f.length&&p.every((e,t)=>e===f[t])?l(u,d,c,r):this._replaceOptional(u,d,c);return e.M([this._replaceOptional(o,a.records[r].orderKey,i),m])}updateCell(t,n,r,i,a){var o,c;let l=t.tables[n],u=h(l,r,i)?l:e.N(l),d=(o=u.rowIndex)==null?void 0:o[r],f=(c=u.colIndex)==null?void 0:c[i];if(d==null||f==null){var p;return this._replaceOptional(s.cell(n,r,i),(p=t.tables[n])==null||(p=p.records[r])==null?void 0:p.values[i],a)}return this.setRangeValues(t,n,[{row:d,col:f,value:a}])}setRecordValues(t,n,r){let i=t.tables[n],a=r.every(e=>Object.keys(e.values).every(t=>h(i,e.recordId,t)))?i:e.N(i),o=r.flatMap(e=>Object.entries(e.values).flatMap(([t,n])=>{var r,i;let o=(r=a.rowIndex)==null?void 0:r[e.recordId],s=(i=a.colIndex)==null?void 0:i[t];return o==null||s==null?[]:[{row:o,col:s,value:n}]})),c=r.flatMap(e=>Object.entries(e.recordPatch??{}).map(([r,i])=>{var a;let o=[...s.record(n,e.recordId),r],c=(a=t.tables[n])==null||(a=a.records[e.recordId])==null?void 0:a[r];return this._replaceOptional(o,c,i)}));return e.M([this.setRangeValues(t,n,o),...c])}setRangeValues(n,r,i){let a=n.tables[r],o=i.every(e=>g(a,e.row,e.col))?a:e.N(a),c=/* @__PURE__ */ new Map,l=i.flatMap(n=>{var i,a,l,u;let d=(i=o.colId)==null?void 0:i[n.col],f=(a=o.rowId)==null?void 0:a[n.row],p=d?o.fields[d]:void 0;if(d===t.BASE_RECORD_ID_FIELD_ID||(p==null?void 0:p.type)===t.BaseFieldType.RecordId)throw Error(`[BaseJson1OpFactory]: cannot write record-id.`);let m=e.B(n.value,p),h=(l=o.cellData)==null||(l=l[n.row])==null?void 0:l[n.col],g=this._replaceOptional(s.cellData(r,n.row,n.col),h,m);if(!d||!f)return[g];let _=(u=o.records[f])==null?void 0:u.values[d],v=(p==null?void 0:p.type)===t.BaseFieldType.Attachment?e.z(n.value):e.V(n.value,m,p,o,f),y=[g,this._replaceOptional(s.cell(r,f,d),_,v)];return(p==null?void 0:p.type)===t.BaseFieldType.Attachment&&c.set(e.P(d,f),{recordId:f,fieldId:d,attachments:v}),y});return l.length?e.M([...l,...this._setAttachmentResources(o,r,Array.from(c.values()))]):t.JSON1.replaceOp([`tables`,r,`cellData`],o.cellData,o.cellData)}createField(n,r,i){let a=n.tables[r];if(a.fields[i.field.id]||a.fieldOrder.includes(i.field.id))return t.JSON1.replaceOp([`tables`,r,`fieldOrder`],a.fieldOrder,a.fieldOrder);let o=Math.max(1,i.index??a.fieldOrder.length),c=Object.values(a.views??{}).flatMap(e=>{var n;if(!e.fieldOrder||e.fieldOrder.includes(i.field.id))return[];let a=b(((n=i.viewIndexes)==null?void 0:n[e.id])??o,e.fieldOrder.length);return[t.JSON1.insertOp([...s.view(r,e.id),`fieldOrder`,a],i.field.id)]});return e.M([...i.field.type===t.BaseFieldType.Formula?this._materializeFormulaTableNames(n):[],t.JSON1.insertOp(s.field(r,i.field.id),i.field),t.JSON1.insertOp(s.fieldOrder(r,o),i.field.id),...c])}duplicateField(n,r,i,a){let o=n.tables[r];if(!o.fields[i]||o.fields[a.field.id]||o.fieldOrder.includes(a.field.id))return t.JSON1.replaceOp([`tables`,r,`fieldOrder`],o.fieldOrder,o.fieldOrder);let c=a.index??o.fieldOrder.indexOf(i)+1,l=o.fieldOrder.filter(e=>e!==a.field.id),u=v(l,a.field.id,c),d=Object.values(o.views??{}).flatMap(e=>{var t,n,o,u;let d=(t=e.fieldOrder)!=null&&t.length?e.fieldOrder:l;if(d.includes(a.field.id))return[];let f=v(d,a.field.id,((n=a.viewIndexes)==null?void 0:n[e.id])??c),p=(o=e.fieldSettings)==null?void 0:o[i];return[this._replaceOptional([...s.view(r,e.id),`fieldOrder`],e.fieldOrder,f),...p?[this._replaceOptional([...s.view(r,e.id),`fieldSettings`,a.field.id],(u=e.fieldSettings)==null?void 0:u[a.field.id],p)]:[]]}),f=Object.values(o.records).filter(e=>Object.prototype.hasOwnProperty.call(e.values,i)).map(e=>this._replaceOptional(s.cell(r,e.id,a.field.id),e.values[a.field.id],e.values[i]));return e.M([...a.field.type===t.BaseFieldType.Formula?this._materializeFormulaTableNames(n):[],t.JSON1.insertOp(s.field(r,a.field.id),a.field),t.JSON1.replaceOp([`tables`,r,`fieldOrder`],o.fieldOrder,u),...d,...f])}updateField(n,r,i,a){let o=n.tables[r].fields[i],c={...o,...a};Object.keys(a).forEach(e=>{a[e]===void 0&&delete c[e]});let l=u(n.tables[r],i,o,c);c=l.field;let d=s.field(r,i),f=o.type===c.type?this._patchProperties(d,o,{...a,...c.config===o.config?{}:{config:c.config},...c.defaultValue===o.defaultValue?{}:{defaultValue:c.defaultValue}}):t.JSON1.replaceOp(d,o,c);return c.type===t.BaseFieldType.Formula?e.M([...this._materializeFormulaTableNames(n),f,...this._setFormulaFieldCells(n,r,i,c)]):e.M([f,...l.patches.length?[this.setRangeValues(n,r,l.patches)]:[]])}changeFieldType(e,t,n,r){return this.updateField(e,t,n,r)}deleteField(n,r,i){let a=n.tables[r];if(!(a!=null&&a.fields[i])||a.primaryFieldId===i||i===t.BASE_RECORD_ID_FIELD_ID)return t.JSON1.replaceOp([`tables`,r,`fieldOrder`],a==null?void 0:a.fieldOrder,a==null?void 0:a.fieldOrder);let o=a.fieldOrder.indexOf(i),c=Object.values(a.views).flatMap(e=>{var n,a,o,c,l,u,d;let f=[],p=((n=e.fieldOrder)==null?void 0:n.indexOf(i))??-1;p>=0&&f.push(t.JSON1.removeOp([...s.view(r,e.id),`fieldOrder`,p],i));let m=(a=e.fieldSettings)==null?void 0:a[i];m!==void 0&&f.push(t.JSON1.removeOp([...s.view(r,e.id),`fieldSettings`,i],m));let h=e.filter?{...e.filter,conditions:e.filter.conditions.filter(e=>e.fieldId!==i)}:e.filter;h&&h.conditions.length!==((o=e.filter)==null?void 0:o.conditions.length)&&f.push(this._replaceOptional([...s.view(r,e.id),`filter`],e.filter,h));let g=(c=e.sort)==null?void 0:c.filter(e=>e.fieldId!==i);g&&g.length!==((l=e.sort)==null?void 0:l.length)&&f.push(this._replaceOptional([...s.view(r,e.id),`sort`],e.sort,g));let _=(u=e.group)==null?void 0:u.filter(e=>e.fieldId!==i);_&&_.length!==((d=e.group)==null?void 0:d.length)&&f.push(this._replaceOptional([...s.view(r,e.id),`group`],e.group,_));let v=y(e.config,i);return JSON.stringify(v)!==JSON.stringify(e.config)&&f.push(t.JSON1.replaceOp([...s.view(r,e.id),`config`],e.config,v)),f}),l=Object.values(a.records).flatMap(e=>Object.prototype.hasOwnProperty.call(e.values,i)?[t.JSON1.removeOp(s.cell(r,e.id,i),e.values[i])]:[]);return e.M([t.JSON1.removeOp(s.field(r,i),a.fields[i]),t.JSON1.removeOp(s.fieldOrder(r,o),i),...c,...l,...this._deleteAttachmentResources(a,r,e=>e.startsWith(`${i}`))])}moveField(e,n,r,i){let a=e.tables[n].fieldOrder;if(r===t.BASE_RECORD_ID_FIELD_ID||i.beforeFieldId===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseJson1OpFactory]: cannot move a field before record-id.`);let o=_(a,r,i);return l([`tables`,n,`fieldOrder`],a,o,r)}createView(n,r,i,a=n.tables[r].viewOrder.length){return e.M([t.JSON1.insertOp(s.view(r,i.id),i),t.JSON1.insertOp([`tables`,r,`viewOrder`,a],i.id)])}renameView(e,n,r,i){return t.JSON1.replaceOp([...s.view(n,r),`name`],e.tables[n].views[r].name,i)}deleteView(n,r,i){let a=n.tables[r],o=a.views[i],c=a.viewOrder.indexOf(i);return e.M([t.JSON1.removeOp(s.view(r,i),o),t.JSON1.removeOp([`tables`,r,`viewOrder`,c],i)])}moveView(e,t,n,r){let i=e.tables[t].viewOrder,a=_(i,n,{beforeFieldId:r.beforeViewId,afterFieldId:r.afterViewId});return l([`tables`,t,`viewOrder`],i,a,n)}updateViewConfig(e,t,n,r){let i=e.tables[t].views[n].config;return this._patchProperties([...s.view(t,n),`config`],i,r)}setViewFilter(e,t,n,r){return this._replaceOptional([...s.view(t,n),`filter`],e.tables[t].views[n].filter,r)}setViewSort(e,t,n,r){return this._replaceOptional([...s.view(t,n),`sort`],e.tables[t].views[n].sort,r)}setViewGroup(e,t,n,r){return this._replaceOptional([...s.view(t,n),`group`],e.tables[t].views[n].group,r)}setViewFieldVisible(e,t,n,r,i){return this._setViewFieldSetting(e,t,n,r,{hidden:!i})}setViewFieldWidth(e,t,n,r,i){return this._setViewFieldSetting(e,t,n,r,{width:i})}getViewFieldSettingHistory(e,n,r,i,a){var o;let c=(o=e.tables[n].views[r].fieldSettings)==null?void 0:o[i],l=[...s.view(n,r),`fieldSettings`,i],u=this._patchProperties(l,c??{},{...a});return{redo:u,undo:t.JSON1.type.invert(u)}}setViewFieldOrder(e,n,r,i,a){let o=e.tables[n].views[r],c=o.fieldOrder??e.tables[n].fieldOrder,u=_(c,i,a),d=[...s.view(n,r),`fieldOrder`];return o.fieldOrder?l(d,c,u,i):t.JSON1.insertOp(d,u)}_setViewFieldSetting(t,n,r,i,a){let o=t.tables[n].views[r].fieldSettings,c=[...s.view(n,r),`fieldSettings`];if(!o)return this._replaceOptional(c,o,{[i]:a});let l=o[i];return l?e.M(Object.entries(a).map(([e,t])=>this._replaceOptional([...c,i,e],l[e],t))):this._replaceOptional([...c,i],l,a)}_createRecordOrderOp(e,n,r){let i=e.tables[n],a=new Set(r.map(e=>e.id)),o=[...Object.values(i.records).filter(e=>!a.has(e.id)),...r].sort((e,t)=>String(e.orderKey??e.id).localeCompare(String(t.orderKey??t.id))).map(e=>e.id),c=[...s.table(n),`recordOrder`],l=o.filter(e=>!a.has(e));if(!i.recordOrder||i.recordOrder.length!==l.length||l.some((e,t)=>e!==i.recordOrder[t]))return this._replaceOptional(c,i.recordOrder,o);let u=new t.JSON1.WriteCursor;return u.descendPath(c),o.forEach((e,t)=>{a.has(e)&&(u.descend(t),u.write(`i`,e),u.ascend())}),u.get()}_materializeFormulaTableNames(e,n=/* @__PURE__ */ new Set){let r=(0,t.createBaseFormulaTableNameMap)(e);return Object.values(e.tables).filter(e=>!n.has(e.id)).sort((e,t)=>e.id.localeCompare(t.id)).flatMap(e=>{let t=r.get(e.id);return!t||e.formulaName===t?[]:[this._replaceOptional([...s.table(e.id),`formulaName`],e.formulaName,t)]})}_setFormulaFieldCells(t,n,r,i){var a,o;let c=e.N(t.tables[n]),l=String(((a=i.config)==null?void 0:a.formula)??``).trim(),u=(o=c.colIndex)==null?void 0:o[r];if(u==null)return[];let d=c.recordOrder??Object.keys(c.records),f=d.map(e=>{var t;return(t=c.rowIndex)==null?void 0:t[e]}).find(e=>e!=null);return d.flatMap(e=>{var t,i;let a=(t=c.rowIndex)==null?void 0:t[e];if(a==null)return[];let o=(i=c.cellData)==null||(i=i[a])==null?void 0:i[u],d=l?a===f?{f:l,si:r}:{si:r}:{v:null,t:null};return[this._replaceOptional(s.cellData(n,a,u),o,d)]})}_setAttachmentResources(n,r,i){var a;let o=new Map(Object.entries(((a=n.resources)==null?void 0:a.attachmentSets)??{})),c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u=i.map(({recordId:t,fieldId:i,attachments:a})=>{var u;let d=e.P(i,t),f=a.map((e,t)=>String(e.id??`${d}\u001F${t}`));return l.add(d),o.set(d,f),a.forEach((e,t)=>{let n=f[t];c.set(n,{...e,id:n})}),this._replaceOptional(s.attachmentSet(r,d),(u=n.resources)==null||(u=u.attachmentSets)==null?void 0:u[d],f)}),d=Array.from(c).map(([e,t])=>{var i;return this._replaceOptional(s.attachment(r,e),(i=n.resources)==null||(i=i.attachments)==null?void 0:i[e],t)}),f=new Set(Array.from(o.values()).flat()),p=new Set(Array.from(l).flatMap(e=>{var t;return((t=n.resources)==null||(t=t.attachmentSets)==null?void 0:t[e])??[]})),m=Array.from(p).flatMap(e=>{var i;let a=(i=n.resources)==null||(i=i.attachments)==null?void 0:i[e];return a!==void 0&&!f.has(e)?[t.JSON1.removeOp(s.attachment(r,e),a)]:[]});return[...u,...d,...m]}_deleteAttachmentResources(e,n,r){var i;let a=((i=e.resources)==null?void 0:i.attachmentSets)??{},o=Object.entries(a).filter(([e])=>r(e));if(!o.length)return[];let c=new Set(Object.entries(a).filter(([e])=>!r(e)).flatMap(([,e])=>e)),l=new Set(o.flatMap(([,e])=>e));return[...o.map(([e,r])=>t.JSON1.removeOp(s.attachmentSet(n,e),r)),...Array.from(l).flatMap(r=>{var i;let a=(i=e.resources)==null||(i=i.attachments)==null?void 0:i[r];return a!==void 0&&!c.has(r)?[t.JSON1.removeOp(s.attachment(n,r),a)]:[]})]}_replaceOptional(e,n,r){return n===void 0?t.JSON1.insertOp(e,r):t.JSON1.replaceOp(e,n,r)}_patchProperties(n,r,i){let a=Object.entries(i);return r?e.M(a.map(([e,i])=>{let a=r[e];return i===a?null:i===void 0?t.JSON1.removeOp([...n,e],a):this._replaceOptional([...n,e],a,i)})):t.JSON1.insertOp(n,Object.fromEntries(a.filter(([,e])=>e!==void 0)))}};function l(e,n,r,i){let a=n.indexOf(i),o=r.indexOf(i);return a===o?null:t.JSON1.moveOp([...e,a],[...e,o])}function u(n,r,i,a){var o;let s=a.type;if(i.type!==s||s!==t.BaseFieldType.SingleSelect&&s!==t.BaseFieldType.MultiSelect||d(a.config.optionSource))return{field:a,patches:[]};let c=f(i),l=f(a);if(![...c].some(e=>!l.has(e)))return{field:a,patches:[]};let u=p(a.defaultValue,l,s),h=m(u,a.defaultValue)?a:{...a,defaultValue:u},g=e.N(n),_=(o=g.colIndex)==null?void 0:o[r];return _==null?{field:h,patches:[]}:{field:h,patches:(g.recordOrder??[]).flatMap(e=>{var t,n;let i=(t=g.rowIndex)==null?void 0:t[e],a=(n=g.records[e])==null?void 0:n.values[r],o=p(a,l,s);return i==null||m(o,a)?[]:[{row:i,col:_,value:o??null}]})}}function d(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`field`}function f(e){var t;let n=Array.isArray((t=e.config)==null?void 0:t.options)?e.config.options:[];return new Set(n.flatMap(e=>{if(!e||typeof e!=`object`||!(`id`in e))return[];let t=String(e.id);return t?[t]:[]}))}function p(e,n,r){if(e==null||e===``)return e;if(r===t.BaseFieldType.SingleSelect)return n.has(String(e))?e:null;let i=Array.isArray(e)?e.map(String):String(e).split(`,`).map(e=>e.trim()).filter(Boolean),a=i.filter(e=>n.has(e));return a.length===i.length?e:Array.isArray(e)?a:String(e).includes(`,`)?a.join(`,`):a[0]??[]}function m(e,t){return JSON.stringify(e)===JSON.stringify(t)}function h(e,t,n){var r,i,a,o;let s=(r=e.rowIndex)==null?void 0:r[t],c=(i=e.colIndex)==null?void 0:i[n];return s!=null&&c!=null&&((a=e.rowId)==null?void 0:a[s])===t&&((o=e.colId)==null?void 0:o[c])===n&&e.cellData!=null}function g(e,t,n){var r,i;return((r=e.rowId)==null?void 0:r[t])!=null&&((i=e.colId)==null?void 0:i[n])!=null&&e.cellData!=null}function _(e,t,n){let r=e.filter(e=>e!==t),i=n.beforeFieldId?r.indexOf(n.beforeFieldId):n.afterFieldId?r.indexOf(n.afterFieldId)+1:r.length;return r.splice(i<0?r.length:i,0,t),r}function v(e,t,n){let r=e.filter(e=>e!==t);return r.splice(b(n,r.length),0,t),r}function y(e,t,n){if(Array.isArray(e))return n===`fieldIds`?e.filter(e=>e!==t):e.flatMap(e=>{if(e&&typeof e==`object`&&!Array.isArray(e)&&e.fieldId===t)return[];let n=y(e,t);return n===void 0?[]:[n]});if(!e||typeof e!=`object`)return n!=null&&n.endsWith(`FieldId`)&&e===t?void 0:e;let r=e;if(r.fieldId!==t)return Object.fromEntries(Object.entries(r).flatMap(([e,r])=>{if(e===t&&n===`fieldSettings`)return[];let i=y(r,t,e);return i===void 0?[]:[[e,i]]}))}function b(e,t){return Math.max(0,Math.min(e,t))}var x=class{constructor(n){this.unitId=n,e.b(this,`type`,r.UnitObject.Base),e.b(this,`subType`,r.UnitAction.Comment),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}`}},S=class{constructor(n){this.unitId=n,e.b(this,`type`,r.UnitObject.Base),e.b(this,`subType`,r.UnitAction.Copy),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}`}},C=class{constructor(n){this.unitId=n,e.b(this,`type`,r.UnitObject.Base),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}`}},w=class{constructor(n){this.unitId=n,e.b(this,`type`,r.UnitObject.Base),e.b(this,`subType`,r.UnitAction.Export),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}`}},T=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseDashboard),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}},E=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseField),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}},D=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseRecord),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}},ee=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseTable),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}},te=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseView),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}};const O=[r.UnitAction.Edit,r.UnitAction.Copy,r.UnitAction.Export,r.UnitAction.Comment],ne=/* @__PURE__ */ new Set([r.UnitObject.Base,r.UnitObject.BaseTable,r.UnitObject.BaseField,r.UnitObject.BaseRecord,r.UnitObject.BaseView,r.UnitObject.BaseDashboard]),k=`table/`,re=`field/`,ie=`record/`,ae=`view/`,oe=`dashboard/`;function A(e){return`${k}${encodeURIComponent(e)}`}function j(e,t){return`${re}${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function M(e,t){return`${ie}${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function N(e,t){return`${ae}${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function se(e){return`${oe}${encodeURIComponent(e)}`}function P(e,t,n){if(t===e)switch(n){case r.UnitAction.Edit:return new C(e);case r.UnitAction.Copy:return new S(e);case r.UnitAction.Export:return new w(e);case r.UnitAction.Comment:return new x(e);default:throw Error(`Unsupported Base permission action: ${n}`)}if(n!==r.UnitAction.Edit)throw Error(`Base object permissions only support Edit: ${t}`);if(t.startsWith(k))return new ee(e,t);if(t.startsWith(re))return new E(e,t);if(t.startsWith(ie))return new D(e,t);if(t.startsWith(ae))return new te(e,t);if(t.startsWith(oe))return new T(e,t);throw Error(`Unsupported Base permission object: ${t}`)}function F(e,t,n,r){var i;return((i=e.getPermissionPoint(P(t,n,r).id))==null?void 0:i.value)??!0}function ce(e,t,n,r,i){let a=P(t,n,r);e.getPermissionPoint(a.id)||e.addPermissionPoint(a),e.updatePermissionPoint(a.id,i)}function le(e,t,n,r){e.deletePermissionPoint(P(t,n,r).id)}function ue(e,t){e.getAllPermissionPoint().forEach((n,r)=>{n.subscribe(n=>{ne.has(n.type)&&`unitId`in n&&n.unitId===t&&e.deletePermissionPoint(r)}).unsubscribe()})}function de(e,t,n){return F(e,t,t,r.UnitAction.Edit)&&Array.from(n).every(n=>F(e,t,n,r.UnitAction.Edit))}const fe=(0,t.createIdentifier)(`base.permission.service`);let pe=class extends t.Disposable{constructor(n,r){super(),this._permissionService=n,this._instanceService=r,e.b(this,`_basePermissions`,/* @__PURE__ */ new Map),e.b(this,`_tablePermissions`,/* @__PURE__ */ new Map),e.b(this,`_fieldPermissions`,/* @__PURE__ */ new Map),e.b(this,`_recordPermissions`,/* @__PURE__ */ new Map),e.b(this,`_viewPermissions`,/* @__PURE__ */ new Map),e.b(this,`_tableBaseIds`,/* @__PURE__ */ new Map),this.disposeWithMe(this._instanceService.getTypeOfUnitDisposed$(t.UniverInstanceType.UNIVER_BASE).subscribe(e=>this._clearUnit(e.getUnitId())))}canCreateTable(e){var t;return this._canEdit(e,[])&&(((t=this._basePermissions.get(e))==null?void 0:t.createTable)??!0)}canEditTable(e){return this._canEditTable(e)}canDeleteTable(e){var t;return this._canEditTable(e)&&(((t=this._tablePermissions.get(e))==null?void 0:t.delete)??!0)}canCreateField(e){var t;return this._canEditTable(e)&&(((t=this._tablePermissions.get(e))==null?void 0:t.createField)??!0)}canEditField(e,t){var n;return this._canEditTable(e)&&this._canEdit(e,[j(e,t)])&&(((n=this._fieldPermissions.get(I(e,t)))==null?void 0:n.edit)??!0)}canDeleteField(e,t){var n;return this.canEditField(e,t)&&(((n=this._fieldPermissions.get(I(e,t)))==null?void 0:n.delete)??!0)}canCreateRecord(e){var t;return this._canEditTable(e)&&(((t=this._tablePermissions.get(e))==null?void 0:t.createRecord)??!0)}canEditRecord(e,t){var n;let r=this._recordPermissions.get(L(e,t));return this._canEdit(e,[A(e),M(e,t)])&&(((n=this._tablePermissions.get(e))==null?void 0:n.edit)??!0)&&((r==null?void 0:r.edit)??!0)&&((r==null?void 0:r.editCell)??!0)}canDeleteRecord(e,t){var n,r,i;return this._canEdit(e,[A(e),M(e,t)])&&(((n=this._tablePermissions.get(e))==null?void 0:n.edit)??!0)&&(((r=this._recordPermissions.get(L(e,t)))==null?void 0:r.edit)??!0)&&(((i=this._recordPermissions.get(L(e,t)))==null?void 0:i.delete)??!0)}canEditCell(e,t,n){var r,i,a;let o=this._fieldPermissions.get(I(e,n));return this._canEdit(e,[A(e),j(e,n),M(e,t)])&&(((r=this._tablePermissions.get(e))==null?void 0:r.edit)??!0)&&(((i=this._recordPermissions.get(L(e,t)))==null?void 0:i.edit)??!0)&&(((a=this._recordPermissions.get(L(e,t)))==null?void 0:a.editCell)??!0)&&((o==null?void 0:o.edit)??!0)&&((o==null?void 0:o.editCell)??!0)}canManageView(e,t){var n,r,i;return this._canEdit(e,[A(e),N(e,t)])&&(((n=this._tablePermissions.get(e))==null?void 0:n.edit)??!0)&&(((r=this._viewPermissions.get(he(e,t)))==null?void 0:r.edit)??!0)&&(((i=this._tablePermissions.get(e))==null?void 0:i.manageView)??!0)}setBasePermission(e,t){this._basePermissions.set(e,{...this._basePermissions.get(e),...t}),t.edit!==void 0&&ce(this._permissionService,e,e,r.UnitAction.Edit,t.edit)}setTablePermission(e,t){this._rememberTable(e),this._tablePermissions.set(e,{...this._tablePermissions.get(e),...t}),this._setObjectEdit(e,A(e),t.edit)}setFieldPermission(e,t,n){this._rememberTable(e);let r=I(e,t);this._fieldPermissions.set(r,{...this._fieldPermissions.get(r),...n}),this._setObjectEdit(e,j(e,t),n.edit)}setRecordPermission(e,t,n){this._rememberTable(e);let r=L(e,t);this._recordPermissions.set(r,{...this._recordPermissions.get(r),...n}),this._setObjectEdit(e,M(e,t),n.edit)}setViewPermission(e,t,n){this._rememberTable(e);let r=he(e,t);this._viewPermissions.set(r,{...this._viewPermissions.get(r),...n}),this._setObjectEdit(e,N(e,t),n.edit)}clearBasePermission(e){this._basePermissions.delete(e),le(this._permissionService,e,e,r.UnitAction.Edit)}clearTablePermission(e){this._tablePermissions.delete(e),this._clearObjectEdit(e,A(e))}clearFieldPermission(e,t){this._fieldPermissions.delete(I(e,t)),this._clearObjectEdit(e,j(e,t))}clearRecordPermission(e,t){this._recordPermissions.delete(L(e,t)),this._clearObjectEdit(e,M(e,t))}clearViewPermission(e,t){this._viewPermissions.delete(he(e,t)),this._clearObjectEdit(e,N(e,t))}getSnapshot(){return{bases:Object.fromEntries(this._basePermissions),tables:Object.fromEntries(this._tablePermissions),fields:Object.fromEntries(this._fieldPermissions),records:Object.fromEntries(this._recordPermissions),views:Object.fromEntries(this._viewPermissions)}}_canEditTable(e){var t;return this._canEdit(e,[A(e)])&&(((t=this._tablePermissions.get(e))==null?void 0:t.edit)??!0)}_canEdit(e,t){var n;let r=this._resolveBaseId(e);return!r||de(this._permissionService,r,t)&&(((n=this._basePermissions.get(r))==null?void 0:n.edit)??!0)}_setObjectEdit(e,t,n){if(n===void 0)return;let i=this._resolveBaseId(e);i&&ce(this._permissionService,i,t,r.UnitAction.Edit,n)}_clearObjectEdit(e,t){let n=this._resolveBaseId(e);n&&le(this._permissionService,n,t,r.UnitAction.Edit)}_resolveBaseId(e){var n;let r=this._instanceService.getUnit(e,t.UniverInstanceType.UNIVER_BASE);return r?r.getUnitId():(n=this._instanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).find(t=>!!t.getSnapshot().tables[e]))==null?void 0:n.getUnitId()}_rememberTable(e){let t=this._resolveBaseId(e);t&&this._tableBaseIds.set(e,t)}_clearUnit(e){this._basePermissions.delete(e),this._tableBaseIds.forEach((t,n)=>{t===e&&(this._tablePermissions.delete(n),me(this._fieldPermissions,`${n}\u001F`),me(this._recordPermissions,`${n}\u001F`),me(this._viewPermissions,`${n}\u001F`),this._tableBaseIds.delete(n))})}};pe=e.g([e._(0,t.IPermissionService),e._(1,t.IUniverInstanceService)],pe);function me(e,t){e.forEach((n,r)=>{r.startsWith(t)&&e.delete(r)})}function I(e,t){return`${e}\u001F${t}`}function L(e,t){return`${e}\u001F${t}`}function he(e,t){return`${e}\u001F${t}`}const R=(0,t.createIdentifier)(`base.command.service`);let z=class{constructor(t,n=ge(),r={}){this._permissionService=t,this._fieldRegistry=n,this._runtimeContext=r,e.b(this,`_factory`,new c),e.b(this,`_applier`,new e.j)}createTable(e,n,r){if(!this._permissionService.canCreateTable(e.getUnitId()))throw Error(`[BaseCommandService]: cannot create table.`);(0,t.assertBaseTableRecordIdentity)(n),this._apply(e,this._factory.createTable(e.getSnapshot(),n,r))}renameTable(e,t,n){if(!this._permissionService.canEditTable(t))throw Error(`[BaseCommandService]: cannot edit table.`);this._apply(e,this._factory.renameTable(e.getSnapshot(),t,n))}deleteTable(t,n){if(!this._permissionService.canDeleteTable(n))throw Error(`[BaseCommandService]: cannot delete table.`);let r=e.ct(t.getSnapshot(),n);if(r.length>0)throw Error(`[BaseCommandService]: cannot delete a RecordLink target table (${r.map(e=>`${e.tableId}.${e.fieldId}`).join(`, `)}).`);this._apply(t,this._factory.deleteTable(t.getSnapshot(),n))}updateCell(e,t,n,r,i){this._apply(e,this.createUpdateCellOp(e,t,n,r,i))}setRecordValues(e,t,n){this._apply(e,this.createSetRecordValuesOp(e,t,n))}createRecord(e,t,n){this._apply(e,this.createCreateRecordOp(e,t,n))}createUpdateCellOp(e,t,n,r,i){let a=e.getSnapshot(),o=this._normalizeCellValue(a,t,n,r,i),s=this._withModifiedSystemValues(a,t,n,{[r]:o});return this._factory.setRecordValues(a,t,[s])}createSetRecordValuesOp(e,t,n){let r=e.getSnapshot(),i=n.map(e=>this._withModifiedSystemValues(r,t,e.recordId,{...Object.fromEntries(Object.entries(e.values).map(([n,i])=>[n,this._normalizeCellValue(r,t,e.recordId,n,i)]))}));return this._factory.setRecordValues(r,t,i)}createCreateRecordOp(e,t,n){if(!this._permissionService.canCreateRecord(t))throw Error(`[BaseCommandService]: cannot create record.`);let r=e.getSnapshot(),i=this._createNumberingAllocators(r.tables[t]);return this._factory.createRecord(r,t,this._createRecordWithDefaults(r,t,n,i))}createBatchCreateRecordsOp(t,n,r){if(!this._permissionService.canCreateRecord(n))throw Error(`[BaseCommandService]: cannot create record.`);let i=t.getSnapshot();return e.H(`BaseCommand.createBatchCreateRecordsOp`,()=>{let e=this._createNumberingAllocators(i.tables[n]);return this._factory.createRecords(i,n,r.map(t=>this._createRecordWithDefaults(i,n,t,e)))},{existingRecords:Object.keys(i.tables[n].records).length,records:r.length})}createCreateFieldOp(t,n,r,i,a){if(!this._permissionService.canCreateField(n))throw Error(`[BaseCommandService]: cannot create field.`);let o=t.getSnapshot();if(this._assertFieldDefinition(o,r),i===0)throw Error(`[BaseCommandService]: cannot insert a field before record-id.`);let s=this._factory.createField(o,n,{field:r,index:i,viewIndexes:a}),c=this._createSystemFieldValuePatches(o,n,r);if(!c.length)return s;let l=this._applier.applyOp(o,s);return e.M([s,this._factory.setRecordValues(l,n,c)])}deleteRecord(e,t,n){if(!this._permissionService.canDeleteRecord(t,n))throw Error(`[BaseCommandService]: cannot delete record.`);this._apply(e,this._factory.deleteRecord(e.getSnapshot(),t,n))}duplicateRecord(e,n,r,i){if(!this._permissionService.canCreateRecord(n))throw Error(`[BaseCommandService]: cannot create record.`);this._apply(e,this._factory.duplicateRecord(e.getSnapshot(),n,r,{...i,values:{...i.values,[t.BASE_RECORD_ID_FIELD_ID]:i.id}}))}updateRecordOrder(e,t,n,r){if(!this._permissionService.canEditRecord(t,n))throw Error(`[BaseCommandService]: cannot edit record.`);this._apply(e,this._factory.updateRecordOrder(e.getSnapshot(),t,n,r))}createField(e,t,n,r,i){this._apply(e,this.createCreateFieldOp(e,t,n,r,i))}updateField(e,n,r,i){var a;if(!this._permissionService.canEditField(n,r))throw Error(`[BaseCommandService]: cannot edit field.`);let o=e.getSnapshot(),s=(a=o.tables[n])==null?void 0:a.fields[r];if(!s||r===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseCommandService]: cannot edit record-id.`);this._assertFieldDefinition(o,{...s,...i}),this._apply(e,this._factory.updateField(o,n,r,i))}changeFieldType(e,n,r,i){var a;if(!this._permissionService.canEditField(n,r))throw Error(`[BaseCommandService]: cannot edit field.`);let o=e.getSnapshot(),s=(a=o.tables[n])==null?void 0:a.fields[r];if(!s||r===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseCommandService]: cannot change record-id field type.`);this._assertFieldDefinition(o,{...s,...i}),this._apply(e,this._factory.changeFieldType(o,n,r,i))}deleteField(e,n,r){var i;if(((i=e.getSnapshot().tables[n])==null?void 0:i.primaryFieldId)===r||r===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseCommandService]: cannot delete primary field.`);if(!this._permissionService.canDeleteField(n,r))throw Error(`[BaseCommandService]: cannot delete field.`);this._apply(e,this._factory.deleteField(e.getSnapshot(),n,r))}moveField(e,n,r,i){if(!this._permissionService.canEditField(n,r))throw Error(`[BaseCommandService]: cannot edit field.`);if(r===t.BASE_RECORD_ID_FIELD_ID||i.beforeFieldId===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseCommandService]: cannot move a field before record-id.`);this._apply(e,this._factory.moveField(e.getSnapshot(),n,r,i))}createView(e,t,n,r){if(!this._permissionService.canManageView(t,n.id))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.createView(e.getSnapshot(),t,n,r))}renameView(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.renameView(e.getSnapshot(),t,n,r))}deleteView(e,t,n){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.deleteView(e.getSnapshot(),t,n))}moveView(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.moveView(e.getSnapshot(),t,n,r))}updateViewConfig(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.updateViewConfig(e.getSnapshot(),t,n,r))}setViewFilter(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewFilter(e.getSnapshot(),t,n,r))}setViewSort(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewSort(e.getSnapshot(),t,n,r))}setViewGroup(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewGroup(e.getSnapshot(),t,n,r))}setViewFieldVisible(e,t,n,r,i){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewFieldVisible(e.getSnapshot(),t,n,r,i))}setViewFieldWidth(e,t,n,r,i){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewFieldWidth(e.getSnapshot(),t,n,r,i))}setViewFieldOrder(e,t,n,r,i){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewFieldOrder(e.getSnapshot(),t,n,r,i))}_apply(e,t){let n=e.getSnapshot();e.setSnapshot(this._applier.applyOp(n,t))}_createRecordWithDefaults(n,r,i,a=this._createNumberingAllocators(n.tables[r])){let o=n.tables[r],s=i.createdBy??i.updatedBy??this._getCurrentUserId(),c={...i,createdBy:i.createdBy??s,updatedBy:i.updatedBy??s,values:{...i.values}};return c.values[t.BASE_RECORD_ID_FIELD_ID]=c.id,o.fieldOrder.forEach(n=>{let r=o.fields[n];if(r&&c.values[n]===void 0)switch(r.type){case t.BaseFieldType.Numbering:var i;c.values[n]=((i=a.get(n))==null?void 0:i())??this._createNumberingAllocator(o,n)();break;case t.BaseFieldType.CreatedBy:c.createdBy&&(c.values[n]=c.createdBy);break;case t.BaseFieldType.UpdatedBy:c.updatedBy&&(c.values[n]=c.updatedBy);break;case t.BaseFieldType.CreatedAt:c.values[n]=e.E(c.createdAt);break;case t.BaseFieldType.UpdatedAt:c.values[n]=e.E(c.updatedAt);break;default:{let e=r.defaultValue;e!=null&&e!==``&&!(Array.isArray(e)&&e.length===0)&&(c.values[n]=e)}}}),c}_withModifiedSystemValues(n,r,i,a){var o,s;let c=n.tables[r],l=((o=(s=this._runtimeContext).now)==null?void 0:o.call(s))??Date.now(),u=this._getCurrentUserId(),d={...a};return c.fieldOrder.forEach(n=>{let r=c.fields[n];r&&(r.type===t.BaseFieldType.UpdatedAt&&(d[n]=e.E(l)),r.type===t.BaseFieldType.UpdatedBy&&u&&(d[n]=u))}),{recordId:i,values:d,recordPatch:{updatedAt:l,...u?{updatedBy:u}:{}}}}_createSystemFieldValuePatches(e,n,r){let i=e.tables[n];return!i||!_e(r)?[]:r.type===t.BaseFieldType.Numbering?this._createNumberingFieldValuePatches(i,r.id):Object.values(i.records).flatMap(e=>{let t=this._getSystemFieldValue(r,e);return t===void 0?[]:[{recordId:e.id,values:{[r.id]:t}}]})}_getSystemFieldValue(n,r){switch(n.type){case t.BaseFieldType.CreatedBy:return r.createdBy??this._getCurrentUserId();case t.BaseFieldType.UpdatedBy:return r.updatedBy??this._getCurrentUserId();case t.BaseFieldType.CreatedAt:return e.E(r.createdAt??Date.now());case t.BaseFieldType.UpdatedAt:return e.E(r.updatedAt??Date.now());default:return}}_createNumberingAllocators(e){let n=/* @__PURE__ */ new Map;return e&&e.fieldOrder.forEach(r=>{let i=e.fields[r];(i==null?void 0:i.type)===t.BaseFieldType.Numbering&&n.set(r,this._createNumberingAllocator(e,r))}),n}_createNumberingAllocator(e,t){let n=Object.values(e.records).reduce((e,n)=>{let r=Number(n.values[t]);return Number.isFinite(r)?Math.max(e,r):e},0);return()=>String(++n)}_createNumberingFieldValuePatches(e,t){let n=this._getOrderedRecords(e),r=this._createNumberingAllocator(e,t);return n.flatMap(e=>this._isNonEmptyCellValue(e.values[t])?[]:[{recordId:e.id,values:{[t]:r()}}])}_getOrderedRecords(e){var t;let n=Object.values(e.records),r=new Map(n.map(e=>[e.id,e])),i=[],a=/* @__PURE__ */ new Set;(t=e.recordOrder)==null||t.forEach(e=>{let t=r.get(e);t&&(i.push(t),a.add(e))});let o=n.filter(e=>!a.has(e.id)).sort((e,t)=>String(e.orderKey??e.id).localeCompare(String(t.orderKey??t.id))||e.id.localeCompare(t.id));return[...i,...o]}_isNonEmptyCellValue(e){return e!=null&&e!==``&&!(Array.isArray(e)&&e.length===0)}_getCurrentUserId(){var e,t,n,r;return((e=(t=this._runtimeContext).getCurrentUserId)==null?void 0:e.call(t))??((n=(r=this._runtimeContext).getCurrentUser)==null||(n=n.call(r))==null?void 0:n.userID)??void 0}_normalizeCellValue(n,r,i,a,o){var s;if(!this._permissionService.canEditCell(r,i,a))throw Error(`[BaseCommandService]: cannot edit cell.`);let c=(s=n.tables[r])==null?void 0:s.fields[a];if(!c)throw Error(`[BaseCommandService]: field "${a}" does not exist.`);let l=this._fieldRegistry.get(c.type);if(c.readonly||c.system||!l.getCapabilities(c).editable)throw Error(`[BaseCommandService]: cannot edit readonly field.`);let u=l.normalize(o,c),d=l.validate(u,c);if(!d.valid)throw Error(d.reason??`[BaseCommandService]: invalid cell value.`);let f=c.type===t.BaseFieldType.RecordLink?e.mt(n,c,u):{valid:!0};if(!f.valid)throw Error(f.reason??`[BaseCommandService]: invalid RecordLink value.`);return u}_assertFieldDefinition(n,r){if(r.id===t.BASE_RECORD_ID_FIELD_ID||r.type===t.BaseFieldType.RecordId||(0,t.isBaseRecordIdFieldName)(r.name))throw Error(`[BaseCommandService]: record-id is reserved.`);let i=e.pt(n,r);if(!i.valid)throw Error(i.reason??`[BaseCommandService]: invalid field definition.`)}};z=e.g([e._(0,fe),e._(1,e.y)],z);function ge(){let t=new e.v;return e.x().forEach(e=>t.register(e)),t}function _e(e){return e.type===t.BaseFieldType.Numbering||e.type===t.BaseFieldType.CreatedBy||e.type===t.BaseFieldType.UpdatedBy||e.type===t.BaseFieldType.CreatedAt||e.type===t.BaseFieldType.UpdatedAt}const ve=t.regexp.createRegExpFromSafeFragment(String.raw`(?:^|\W)\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?(?:$|\W)`),ye=t.regexp.createRegExpFromSafeFragment(String.raw`(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?`,`gi`),be=/\{([^}]+)\}/g,xe=t.regexp.createRegExpFromSafeFragment(String.raw`\b([A-Z_][\w.]*)\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]`,`gi`),Se=t.regexp.createRegExpFromSafeFragment(String.raw`\b([A-Z_][\w.]*)\[@\[([^\]]+)\]\]`,`gi`),Ce=t.regexp.createRegExpFromSafeFragment(String.raw`\b([A-Z_][\w.]*)\[([^\[\]#]+)\]`,`gi`),we=t.regexp.createRegExpFromSafeFragment(String.raw`(^|[^\w\[])\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]`,`gi`),Te=t.regexp.createRegExpFromSafeFragment(String.raw`(^|[^\w\[])\[@\[([^\]]+)\]\](?!\])`,`g`),Ee=t.regexp.createRegExpFromSafeFragment(String.raw`(^|[^\w\[])\[@?([^\[\]#]+)\](?!\])`,`g`);var B=class{createSuperTableReference(e,t=e.id){var n;let r=((n=e.recordOrder)==null?void 0:n.length)??Object.values(e.records).length;return{sheetId:t,titleMap:new Map(e.fieldOrder.map((t,n)=>{var r;return[((r=e.fields[t])==null?void 0:r.name)??t,n]})),range:{startRow:0,endRow:Math.max(0,r-1),startColumn:0,endColumn:Math.max(0,e.fieldOrder.length-1)},showHeader:!1}}getSuperTableRegistrations(e,n){let r=[],i=n?new Set(n):null,a=(0,t.createBaseFormulaTableNameMap)(e);return Object.values(e.tables).filter(e=>!i||i.has(e.id)).forEach(e=>{let t=this.createSuperTableReference(e,e.id);r.push({tableId:e.id,tableName:a.get(e.id),reference:t})}),r}validateFormula(e,n,r={}){let i=e.trim();if(!i)return{valid:!0};if(Me(i))return{valid:!1,reason:`[BaseFormula]: A1 references and ranges are not supported in Base formulas.`};let a=r.snapshot?(0,t.createBaseFormulaTableNameMap)(r.snapshot):void 0;for(let e of je(i)){let t=ze(e,n,r.snapshot,a);if(!t.table)return{valid:!1,reason:`[BaseFormula]: table "${e.tableName}" does not exist. Use FBaseTable.getFormulaName() or getSchema().formulaName for structured references.`};if(!t.field)return{valid:!1,reason:`[BaseFormula]: field "${e.fieldName}" does not exist.`}}return{valid:!0}}getDependencies(e,t,n={}){let r=/* @__PURE__ */ new Set;for(let i of this.getStructuredDependencies(e,t,n))i.tableId===t.id&&r.add(i.fieldId);return Array.from(r)}getStructuredDependencies(e,n,r={}){let i=/* @__PURE__ */ new Map,a=r.snapshot?(0,t.createBaseFormulaTableNameMap)(r.snapshot):void 0;for(let t of je(e)){let e=ze(t,n,r.snapshot,a);if(!e.table||!e.field)continue;let o=`${e.table.id}\u001F${e.field.id}`;i.set(o,{tableId:e.table.id,fieldId:e.field.id})}return Array.from(i.values())}};function De(n,r){var i;let a=[],o=(i=r.unitData)==null?void 0:i[n.id];return o&&Object.entries(o).forEach(([r,i])=>{let o=n.tables[r];if(!o||!i)return;let s=e.N(o),c=[];new t.ObjectMatrix(i).forValue((e,t,n)=>{let r=Oe(s,e,t,n);r&&c.push(r)}),c.length&&a.push({unitId:n.id,tableId:r,patches:c})}),a}function Oe(t,n,r,i){var a,o,s;let c=(a=t.rowId)==null?void 0:a[n],l=(o=t.colId)==null?void 0:o[r];if(!c||!t.records[c]||!l)return null;let u=t.fields[l];if(!u||u.type!==`formula`)return null;let d=String(((s=u.config)==null?void 0:s.formula)??``).trim(),f=(i==null?void 0:i.v)??null,p={v:f,t:Ae(f),...n===0&&d?{f:d}:{},si:u.id};return ke(e.F(t,c,l),p)?null:{row:n,col:r,value:p}}function ke(e,t){return e!=null&&Object.is(e.v??null,t.v??null)&&e.t===t.t&&e.f===t.f&&e.si===t.si}function Ae(e){return typeof e==`number`?t.CellValueType.NUMBER:typeof e==`boolean`?t.CellValueType.BOOLEAN:typeof e==`string`?t.CellValueType.STRING:null}function je(e){let t=Pe(e,()=>``),n=/* @__PURE__ */ new Map,r=e=>{n.set(`${e.tableName??``}\u001F${e.fieldName}`,e)};for(let e of t.matchAll(be))r({fieldName:e[1],scope:`this-row`});t=t.replace(xe,(e,t,n,i)=>(r({tableName:t,fieldName:i,scope:n.toLowerCase()===`data`?`data`:`this-row`}),` `)),t=t.replace(Se,(e,t,n)=>(r({tableName:t,fieldName:n,scope:`this-row`}),` `)),t=t.replace(we,(e,t,n,i)=>(r({fieldName:i,scope:n.toLowerCase()===`data`?`data`:`this-row`}),`${t} `)),t=t.replace(Te,(e,t,n)=>(r({fieldName:n,scope:`this-row`}),`${t} `));for(let e of t.matchAll(Ce))r({tableName:e[1],fieldName:e[2]});for(let e of t.matchAll(Ee))r({fieldName:e[2],scope:`this-row`});return Array.from(n.values())}function Me(e){let t=Pe(e,()=>` `).replace(be,` `).replace(xe,` `).replace(Se,` `).replace(we,`$1 `).replace(Te,`$1 `).replace(Ce,` `).replace(Ee,`$1 `);return ve.test(t)}function Ne(e,t){return Le(Ie(e,t),t)}function Pe(e,t){return Fe(Ne(e,t),t)}function Fe(e,t){return e.replace(/"(?:""|[^"])*"/g,t)}function Ie(e,t){return ye.lastIndex=0,e.replace(ye,(n,r)=>Re(e,r)?n:t(n))}const V=/(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s!\[\]]+\[/g;function Le(e,t){let n=[];for(V.lastIndex=0;;){let t=V.exec(e);if(t==null)break;if(Re(e,t.index))continue;let r=V.lastIndex-1,i=0;for(let a=r;a<e.length;a++)if(e[a]===`[`&&i++,e[a]===`]`&&(i--,i===0)){n.push({start:t.index,end:a+1}),V.lastIndex=a+1;break}}if(n.length===0)return e;let r=``,i=0;for(let a of n)r+=e.slice(i,a.start),r+=t(e.slice(a.start,a.end)),i=a.end;return r+e.slice(i)}function Re(e,t){let n=!1;for(let r=0;r<t;r++)e[r]===`"`&&(n&&e[r+1]===`"`?r++:n=!n);return n}function ze(e,t,n,r){let i=Be(e.tableName,t,n,r);return{table:i,field:i?Object.values(i.fields).find(t=>t.name===e.fieldName):void 0}}function Be(e,n,r,i){if(!e)return n;if(!r){var a;let t=e.toLowerCase();return t===n.id.toLowerCase()||t===n.name.toLowerCase()||t===((a=n.formulaName)==null?void 0:a.toLowerCase())?n:void 0}let o=e.toLowerCase(),s=i??(0,t.createBaseFormulaTableNameMap)(r),c=Object.values(r.tables).filter(e=>{var t;return e.id.toLowerCase()===o||e.name.toLowerCase()===o||((t=s.get(e.id))==null?void 0:t.toLowerCase())===o||Ve(e.id).toLowerCase()===o});return c.length===1?c[0]:void 0}function Ve(e){return`_T_${Array.from(e,e=>{var t;return/[A-Za-z0-9]/.test(e)?e:`_x${((t=e.codePointAt(0))==null?void 0:t.toString(16))??`0`}_`}).join(``)}`}const He=new B;function Ue(e,n,r){var i;if(r.type!==t.BaseFieldType.Formula)return!0;let a=String(((i=r.config)==null?void 0:i.formula)??``),o=e.getSnapshot();return He.validateFormula(a,o.tables[n],{snapshot:o}).valid}function H(e,t,n){let r=e.getSnapshot().tables[t];if(!r)return!1;let{viewIds:i,fieldIds:a,recordIds:o}=n||{};if(i){for(let e of i)if(!r.views[e])return!1}if(a){for(let e of a)if(!r.fields[e])return!1}if(o){for(let e of o)if(!r.records[e])return!1}return!0}function U(n,r,i){if(i.id===t.BASE_RECORD_ID_FIELD_ID||i.type===t.BaseFieldType.RecordId||(0,t.isBaseRecordIdFieldName)(i.name)||!Ue(n,r,i))return!1;let a=n.getSnapshot();if(!e.pt(a,i).valid)return!1;if(i.type!==t.BaseFieldType.RecordLink)return!0;let o=e.lt(i);if(!o)return!1;if(o.relationRole===void 0)return!0;if(o.relationRole!==t.BaseRecordLinkRole.Parent||o.targetTableId!==r||o.multiple!==!1)return!1;let s=a.tables[r];return!Object.values(s.fields).some(n=>{var r;return n.id!==i.id&&n.type===t.BaseFieldType.RecordLink&&((r=e.lt(n))==null?void 0:r.relationRole)===t.BaseRecordLinkRole.Parent})}function W(n,r,i,a){var o;let s=n.getSnapshot(),c=(o=s.tables[r])==null?void 0:o.fields[i];if(!c||c.id===t.BASE_RECORD_ID_FIELD_ID||c.type===t.BaseFieldType.RecordId)return!1;if(c.type!==t.BaseFieldType.RecordLink)return!0;let l=Ke(a);return e.mt(s,c,l).valid}function We(e,n,r){let i=e.getSnapshot().tables[n];return!i||!(0,t.isValidBaseRecordId)(r.id)||i.records[r.id]||Object.prototype.hasOwnProperty.call(r.values,t.BASE_RECORD_ID_FIELD_ID)&&r.values[t.BASE_RECORD_ID_FIELD_ID]!==r.id?!1:Object.entries(r.values).every(([r,i])=>r===t.BASE_RECORD_ID_FIELD_ID||W(e,n,r,i))}function Ge(e){return{...e,values:{...e.values,[t.BASE_RECORD_ID_FIELD_ID]:e.id}}}function Ke(e){if(e&&typeof e==`object`&&!Array.isArray(e)&&`v`in e){let t=e.v;return t===void 0?null:t}return e}const G={id:`base.command.set-base-record-values`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,patches:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),l=s.map(e=>e.recordId),u=s.flatMap(e=>Object.keys(e.values));if(!c||!H(c,o,{recordIds:l,fieldIds:u})||s.some(e=>Object.entries(e.values).some(([e,t])=>!W(c,o,e,t))))return!1;let d=e.at(c.getSnapshot().tables[o],s),f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),m=n.get(R).createSetRecordValuesOp(c,o,s),h=new e.j().invertOp(c.getSnapshot(),m),g=r.ganttPredecessor,_={unitId:a,op:m,...g&&!g.onUndo?{ganttPredecessorAddition:g.addition}:{},trigger:d.length?G.id:void 0,hierarchyChanges:d.length?d:void 0,source:d.length?r.source??`ui`:void 0},v={..._,source:d.length?`redo`:void 0},y={unitId:a,op:h,...g!=null&&g.onUndo?{ganttPredecessorAddition:g.addition}:{},trigger:d.length?G.id:void 0,hierarchyChanges:d.length?d.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})):void 0,source:d.length?`undo`:void 0};return f.syncExecuteCommand(e.s.id,_)?(i.focusUnit(a),p.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:y}],redoMutations:[{id:e.s.id,params:v}]}),!0):!1}},qe={id:`base.command.add-gantt-predecessor`,type:t.CommandType.COMMAND,handler(e,t){return Ye(e,t,!1)}},Je={id:`base.command.remove-gantt-predecessor`,type:t.CommandType.COMMAND,handler(e,t){return Ye(e,t,!0)===!0}};function Ye(n,r,i){var a;if(!r)return!1;let{unitId:o,tableId:s,viewId:c,predecessorId:l,successorId:u}=r,d=n.get(t.IUniverInstanceService).getUnit(o,t.UniverInstanceType.UNIVER_BASE),f=d==null?void 0:d.getSnapshot().tables[s],p=f==null?void 0:f.views[c],m=p==null||(a=p.config)==null?void 0:a.dependencyFieldId,h=m?f==null?void 0:f.fields[m]:void 0,g=f==null?void 0:f.records[u];if(!f||!g||!i&&!f.records[l]||(p==null?void 0:p.type)!==t.BaseViewType.Gantt||!h||!e.st(s,h))return!1;let _=e.ut(g.values[h.id]),v=_.includes(l);if(i?!v:v)return!0;if(!i&&e.ot(l,u,e=>{var t;return(t=f.records[e])==null?void 0:t.values[h.id]}))return`cycle`;let y=i?_.filter(e=>e!==l):[..._,l],b=e.dt(y),x=[];for(let e of Object.values(f.records)){let t=i&&e.id===u?b:e.values[h.id];typeof t==`string`&&t&&x.push([e.id,t])}let S={tableId:s,fieldId:h.id,predecessorId:l,successorId:u,graph:x};return n.get(t.ICommandService).syncExecuteCommand(G.id,{unitId:o,tableId:s,viewId:c,patches:[{recordId:u,values:{[h.id]:b}}],ganttPredecessor:{addition:S,onUndo:i}})}function Xe(t,n,r,i){let a=t.getSnapshot().tables[n];if(!a)return null;let o=e.Q(a),s=o??e.nt(a),c=r.some(e=>Object.prototype.hasOwnProperty.call(e.values,s)),l=o?a.fields[o]:c?e.Y(a,s,i):null,u=[];for(let i of r){let r=i.values[s],a=l!==null&&Object.prototype.hasOwnProperty.call(i.values,s),o=Ke(r),c=null;if(a){if(typeof o!=`string`||!e.ft(o,!1).valid)return null;c=o}let d={};if(Object.entries(i.values).forEach(([e,t])=>{a&&e===s||(d[e]=t)}),!We(t,n,{...i,values:d}))return null;let f={...i.values};c!==null&&(f[s]=c),u.push(Ge({...i,values:f}))}return{records:u,hierarchyFieldToMaterialize:o?null:l,hierarchyChanges:e.it(a,u)}}const Ze={id:`base.command.batch-create-base-records`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,records:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),l=s.map(e=>e.id);if(!c||!H(c,o)||new Set(l).size!==l.length)return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=n.get(R),p=c.getSnapshot(),m=Xe(c,o,s);if(!m)return!1;let{records:h,hierarchyChanges:g,hierarchyFieldToMaterialize:_}=m,v=_?f.createCreateFieldOp(c,o,_,p.tables[o].fieldOrder.length):null,y=f.createBatchCreateRecordsOp(c,o,h),b=e.M([...v?[v]:[],y]),x=new e.j().invertOp(p,b),S={unitId:a,op:b,hierarchyChanges:g.length?g:void 0,source:g.length?r.source??`ui`:void 0},C={...S,source:g.length?`redo`:void 0},w={unitId:a,op:x,hierarchyChanges:g.length?g.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:null})):void 0,source:g.length?`undo`:void 0};return u.syncExecuteCommand(e.s.id,S)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:w}],redoMutations:[{id:e.s.id,params:C}]}),!0):!1}},Qe={id:`base.command.batch-delete-base-records`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,recordIds:s}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{recordIds:s}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=e.Z(f.tables[o],s),m=new c,h=new e.j,g=m.deleteRecords(f,o,s),_=h.applyOp(f,g),v=m.createDeleteRecordsUndoOp(f,_,o,s),y={unitId:a,op:g,hierarchyChanges:p,source:r.source??`ui`},b={...y,source:`redo`},x={unitId:a,op:v,hierarchyChanges:p.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})),source:`undo`};return u.syncExecuteCommand(e.s.id,y)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},$e={id:`base.command.change-base-field-type`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s,input:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||s===t.BASE_RECORD_ID_FIELD_ID||!H(u,o,{fieldIds:[s]}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot();if(!U(u,o,{...p.tables[o].fields[s],...l}))return!1;let m=new c().changeFieldType(p,o,s,l),h=new e.j().invertOp(p,m),g={unitId:a,op:m},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},K={id:`base.command.create-base-child-record`,type:t.CommandType.COMMAND,handler(n,r){var i;if(!r)return!1;let{unitId:a,tableId:o,parentRecordId:s}=r,l=n.get(t.IUniverInstanceService),u=l.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{recordIds:[s]}))throw new e.K(`missingRecord`);let d=u.getSnapshot(),f=d.tables[o],p=e.Q(f),m=p??r.fieldId??e.nt(f);if(p&&r.fieldId&&r.fieldId!==p||f.fields[m]&&!e.et(f,m))throw new e.K(`invalidField`);if((e.J(f,m).depthByRecordId.get(s)??0)+1>=5)throw new e.K(`maxDepth`);if(!We(u,o,r.record))return!1;let h=Ge({...r.record,values:{...r.record.values,[m]:e.dt([s])}}),g=n.get(R),_=new c,v=f.fields[m],y=v?((i=e.lt(v))==null?void 0:i.relationRole)===t.BaseRecordLinkRole.Parent?null:_.updateField(d,o,m,{config:{...v.config,relationRole:t.BaseRecordLinkRole.Parent}}):g.createCreateFieldOp(u,o,e.Y(f,m,r.parentFieldName),f.fieldOrder.length),b=g.createCreateRecordOp(u,o,h),x=e.M([...y?[y]:[],b]),S=new e.j().invertOp(d,x),C={tableId:o,fieldId:m,recordId:h.id,oldParentRecordId:null,parentRecordId:s},w={unitId:a,op:x,trigger:K.id,hierarchyChanges:[C],source:r.source??`ui`},T={...w,source:`redo`},E={unitId:a,op:S,trigger:K.id,hierarchyChanges:[{...C,oldParentRecordId:s,parentRecordId:null}],source:`undo`};return n.get(t.ICommandService).syncExecuteCommand(e.s.id,w)?(l.focusUnit(a),n.get(t.IUndoRedoService).pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:E}],redoMutations:[{id:e.s.id,params:T}]}),!0):!1}},et={id:`base.command.create-base-field`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,field:s,index:c,viewIndexes:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o)||u.getSnapshot().tables[o].fields[s.id]||c===0||!U(u,o,s))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=n.get(R).createCreateFieldOp(u,o,s,c,l),m=new e.j().invertOp(u.getSnapshot(),p),h={unitId:a,op:p},g={unitId:a,op:m};return d.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}},tt={id:`base.command.create-base-record`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,record:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c||!H(c,o))return!1;let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=n.get(R),f=c.getSnapshot(),p=Xe(c,o,[s]);if(!p)return!1;let[m]=p.records,{hierarchyChanges:h,hierarchyFieldToMaterialize:g}=p,_=g?d.createCreateFieldOp(c,o,g,f.tables[o].fieldOrder.length):null,v=d.createCreateRecordOp(c,o,m),y=e.M([..._?[_]:[],v]),b=new e.j().invertOp(f,y),x={unitId:a,op:y,hierarchyChanges:h.length?h:void 0,source:h.length?r.source??`ui`:void 0},S={...x,source:h.length?`redo`:void 0},C={unitId:a,op:b,hierarchyChanges:h.length?h.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:null})):void 0,source:h.length?`undo`:void 0};return l.syncExecuteCommand(e.s.id,x)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:C}],redoMutations:[{id:e.s.id,params:S}]}),!0):!1}};function q(e,n,r){if(!n.trim())return{valid:!1,reason:`Table name is required.`,error:`required`};if(n.length>31)return{valid:!1,reason:`Use 31 characters or fewer.`,error:`too-long`};if(n.startsWith(`'`)||n.endsWith(`'`))return{valid:!1,reason:`A table name cannot start or end with an apostrophe.`,error:`apostrophe`};if(/[:\\/?*\[\]]/.test(n))return{valid:!1,reason:`A table name cannot contain : \\ / ? * [ ].`,error:`invalid-characters`};if(!(0,t.nameCharacterCheck)(n))return{valid:!1,reason:`Choose another name.`,error:`invalid`};let i=n.toLowerCase();return Object.values(e.tables).some(e=>e.id!==r&&e.name.toLowerCase()===i)?{valid:!1,reason:`A table with this name already exists.`,error:`duplicate`}:{valid:!0}}function nt(e,t){let n=t.replace(/[:\\/?*\[\]]/g,` `).replace(/^'+|'+$/g,``).trim()||`Table`,r=1;for(;;){let t=r===1?``:` ${r}`,i=`${n.slice(0,31-t.length)}${t}`;if(q(e,i).valid)return i;r++}}const rt={id:`base.command.create-base-table`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,table:o,index:s}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||l.getSnapshot().tables[o.id]||!q(l.getSnapshot(),o.name).valid)return!1;try{(0,t.assertBaseTableRecordIdentity)(o)}catch{return!1}let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=new c().createTable(f,o,s),m=new e.j().invertOp(f,p),h={unitId:a,op:p},g={unitId:a,op:m};return u.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}};function it(e,t,n=[]){let r=/* @__PURE__ */ new Set([...Object.values(e.fields).filter(e=>e).map(e=>e.name),...n.map(e=>e.name)]);if(!r.has(t))return t;let i=2;for(;r.has(`${t} ${i}`);)i++;return`${t} ${i}`}function at(e,t){if(!e||!t.length)return;let n=[...e];return t.forEach(e=>{n.includes(e)||n.push(e)}),n}const ot={options:[{id:`todo`,name:`Todo`,color:`#BFDBFE`},{id:`doing`,name:`Doing`,color:`#FDE68A`},{id:`done`,name:`Done`,color:`#BBF7D0`}]},st={locale:`en-US`,pattern:`yyyy/mm/dd`,includeTime:!1,hourCycle:`h24`,defaultMode:`none`};function ct(n,r,i,a){var o;let s=new c,l=n.tables[r],u=l?{...i,fieldOrder:[t.BASE_RECORD_ID_FIELD_ID,...(i.fieldOrder??l.fieldOrder).filter(e=>e!==t.BASE_RECORD_ID_FIELD_ID)],fieldSettings:{...i.fieldSettings,[t.BASE_RECORD_ID_FIELD_ID]:{...(o=i.fieldSettings)==null?void 0:o[t.BASE_RECORD_ID_FIELD_ID],hidden:!0}}}:i;if(l&&u.type===`kanban`){let t=ut(l,u),i=t.changed?{...u,config:t.config,fieldOrder:t.fieldOrder??u.fieldOrder}:u;return e.M([...t.fields.map(e=>s.createField(n,r,{field:e})),s.createView(n,r,i,a)])}if(!l||u.type!==`calendar`&&u.type!==`gantt`)return s.createView(n,r,u,a);let d=lt(l,u),f=d.changed?{...u,config:d.config,fieldOrder:d.fieldOrder??u.fieldOrder}:u;return f.type===`gantt`&&(f={...f,config:{displayColor:{type:`custom`,color:`#3b82f6`},...f.config}},pt(u)&&(f=mt(l,f,d.fields))),e.M([...d.fields.map(e=>s.createField(n,r,{field:e})),s.createView(n,r,f,a)])}function lt(e,n,r=!1){var i,a;let o=e.fieldOrder.filter(t=>gt(e,t)),s=[],c={...n.config??{}},l=typeof c.startDateFieldId==`string`&>(e,c.startDateFieldId)?c.startDateFieldId:o[0],u=typeof c.endDateFieldId==`string`&>(e,c.endDateFieldId)&&c.endDateFieldId!==l?c.endDateFieldId:o.find(e=>e!==l);if(!l){let t=_t(e,s,n.type===`gantt`?`Start date`:`Date`);s.push(t),l=t.id}if((n.type===`gantt`||r)&&!u){let t=_t(e,s,`End date`);s.push(t),u=t.id}n.type===`calendar`&&!u&&delete c.endDateFieldId,c.startDateFieldId=l,n.type===`calendar`&&u&&(c.endDateFieldId=u),n.type===`gantt`&&(c.endDateFieldId=u??l);let d=at(n.fieldOrder,s.map(e=>e.id));return{changed:s.length>0||c.startDateFieldId!==((i=n.config)==null?void 0:i.startDateFieldId)||c.endDateFieldId!==((a=n.config)==null?void 0:a.endDateFieldId)||!(!d||t.Tools.diffValue(d,n.fieldOrder??[])),fields:s,config:c,fieldOrder:d}}function ut(e,n){var r;let i=[],a={...n.config??{}},o=typeof a.groupFieldId==`string`&&dt(e,a.groupFieldId)?a.groupFieldId:e.fieldOrder.find(t=>dt(e,t));if(!o){let t=ft(e,i);i.push(t),o=t.id}a.groupFieldId=o;let s=at(n.fieldOrder,i.map(e=>e.id));return{changed:i.length>0||a.groupFieldId!==((r=n.config)==null?void 0:r.groupFieldId)||!(!s||t.Tools.diffValue(s,n.fieldOrder??[])),fields:i,config:a,fieldOrder:s}}function dt(e,n){let r=n?e.fields[n]:null;return r?[t.BaseFieldType.SingleSelect,t.BaseFieldType.MultiSelect,t.BaseFieldType.Rating,t.BaseFieldType.Person,t.BaseFieldType.Group,t.BaseFieldType.Checkbox].includes(r.type):!1}function ft(e,n){return{id:`fld-${(0,t.generateRandomId)(8)}`,name:it(e,`Status`,n),type:t.BaseFieldType.SingleSelect,config:t.Tools.deepClone(ot)}}function pt(e){return Object.keys(e.config??{}).length===0&&Object.keys(e.fieldSettings??{}).length===0}function mt(e,t,n){let r={...t.config??{}},i=n.map(e=>e.id),a=[...e.fieldOrder,...i],o=typeof r.titleFieldId==`string`&&ht(e,n,r.titleFieldId)?r.titleFieldId:e.primaryFieldId,s=typeof r.startDateFieldId==`string`?r.startDateFieldId:``,c=typeof r.endDateFieldId==`string`?r.endDateFieldId:s,l=new Set([o,s,c].filter(t=>t&&ht(e,n,t))),u=Object.fromEntries(a.flatMap(t=>l.has(t)||!ht(e,n,t)?[]:[[t,{hidden:!0}]]));return{...t,config:{...r,titleFieldId:o},fieldSettings:u}}function ht(e,t,n){return!!(e.fields[n]??t.find(e=>e.id===n))&&!0}function gt(e,n){let r=n?e.fields[n]:null;return!!r&&r.type===t.BaseFieldType.Date&&r.readonly!==!0&&r.system!==!0}function _t(e,n,r){let i=/* @__PURE__ */ new Set([...Object.keys(e.fields),...n.map(e=>e.id)]),a=`fld-${(0,t.generateRandomId)(8)}`;for(;i.has(a);)a=`fld-${(0,t.generateRandomId)(8)}`;return{id:a,name:it(e,r,n),type:t.BaseFieldType.Date,config:{...st}}}const vt={id:`base.command.create-base-view`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,view:s,index:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o)||l.getSnapshot().tables[o].views[s.id])return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=ct(f,o,s,c),m=new e.j().invertOp(f,p),h={historyAction:`create-view`,unitId:a,op:p,viewType:s.type},g={historyAction:`delete-view`,unitId:a,op:m,viewType:s.type};return u.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}},yt={id:`base.command.delete-base-field`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l)return!1;let u=l.getSnapshot(),d=u.tables[o];if(!H(l,o,{fieldIds:[s]})||d.primaryFieldId===s||s===t.BASE_RECORD_ID_FIELD_ID)return!1;let f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),m=new c().deleteField(u,o,s),h=new e.j().invertOp(u,m),g={unitId:a,op:m},_={unitId:a,op:h};return f.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),p.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},bt={id:`base.command.delete-base-record`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,recordId:s}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{recordIds:[s]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=e.Z(f.tables[o],[s]),m=new c,h=new e.j,g=m.deleteRecord(f,o,s),_=h.applyOp(f,g),v=m.createDeleteRecordsUndoOp(f,_,o,[s]),y={unitId:a,op:g,hierarchyChanges:p,source:r.source??`ui`},b={...y,source:`redo`},x={unitId:a,op:v,hierarchyChanges:p.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})),source:`undo`};return u.syncExecuteCommand(e.s.id,y)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},xt={id:`base.command.delete-base-table`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o}=r,s=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!s||!H(s,o))return!1;let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=s.getSnapshot(),f=e.ct(d,o);if(f.length>0)return console.error(`[DeleteBaseTableCommand]: table "${o}" is referenced by ${f.map(e=>`${e.tableId}.${e.fieldId}`).join(`, `)}.`),!1;let p=new c().deleteTable(d,o),m=new e.j().invertOp(d,p),h={unitId:a,op:p},g={unitId:a,op:m};return l.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}},St={id:`base.command.delete-base-view`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{viewIds:[s]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=f.tables[o].views[s].type,m=new c().deleteView(f,o,s),h=new e.j().invertOp(f,m),g={historyAction:`delete-view`,unitId:a,op:m,viewType:p},_={historyAction:`create-view`,unitId:a,op:h,viewType:p};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Ct={id:`base.command.duplicate-base-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,sourceFieldId:s,field:l,index:u,viewIndexes:d}=r,f=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!f||!H(f,o,{fieldIds:[s]})||s===t.BASE_RECORD_ID_FIELD_ID||f.getSnapshot().tables[o].fields[l.id]||u===0||!U(f,o,l))return!1;let p=n.get(t.ICommandService),m=n.get(t.IUndoRedoService),h=f.getSnapshot(),g=new c().duplicateField(h,o,s,{field:l,index:u,viewIndexes:d}),_=new e.j().invertOp(h,g),v={unitId:a,op:g},y={unitId:a,op:_};return p.syncExecuteCommand(e.s.id,v)?(i.focusUnit(a),m.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:y}],redoMutations:[{id:e.s.id,params:v}]}),!0):!1}},wt={id:`base.command.duplicate-base-record`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,sourceRecordId:s,record:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{recordIds:[s]})||!We(u,o,l))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot(),m=Ge(l),h=e.it(p.tables[o],[m]),g=new c().duplicateRecord(p,o,s,m),_=new e.j().invertOp(p,g),v={unitId:a,op:g,hierarchyChanges:h.length?h:void 0,source:h.length?r.source??`ui`:void 0},y={...v,source:h.length?`redo`:void 0},b={unitId:a,op:_,hierarchyChanges:h.length?h.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:null})):void 0,source:h.length?`undo`:void 0};return d.syncExecuteCommand(e.s.id,v)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:b}],redoMutations:[{id:e.s.id,params:y}]}),!0):!1}},Tt={id:`base.command.ensure-base-temporal-view-date-fields`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,ensureEndDateField:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{viewIds:[s]}))return!1;let d=u.getSnapshot(),f=d.tables[o],p=f==null?void 0:f.views[s];if(!f||!p||p.type!==`calendar`&&p.type!==`gantt`)return!1;let m=lt(f,p,l===!0);if(!m.changed)return!1;let h=n.get(t.ICommandService),g=n.get(t.IUndoRedoService),_=new c,v=[...m.fields.map(e=>_.createField(d,r.tableId,{field:e})),Et([...Dt(r.tableId,r.viewId),`config`],p.config,m.config)];m.fieldOrder&&v.push(Et([...Dt(r.tableId,r.viewId),`fieldOrder`],p.fieldOrder,m.fieldOrder));let y=e.M(v),b=new e.j().invertOp(d,y),x={unitId:a,op:y},S={unitId:a,op:b};return h.syncExecuteCommand(e.s.id,x)?(i.focusUnit(a),g.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:S}],redoMutations:[{id:e.s.id,params:x}]}),!0):!1}};function Et(e,n,r){return n===void 0?t.JSON1.insertOp(e,r):t.JSON1.replaceOp(e,n,r)}function Dt(e,t){return[`tables`,e,`views`,t]}const Ot={id:`base.command.move-base-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s,target:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),d=l.beforeFieldId??l.afterFieldId;if(!u||!!l.beforeFieldId==!!l.afterFieldId||!d||d===s||s===t.BASE_RECORD_ID_FIELD_ID||l.beforeFieldId===t.BASE_RECORD_ID_FIELD_ID||!H(u,o,{fieldIds:[s,d]}))return!1;let f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),m=u.getSnapshot(),h=new c().moveField(m,o,s,l),g=new e.j().invertOp(m,h),_={unitId:a,op:h},v={unitId:a,op:g};return f.syncExecuteCommand(e.s.id,_)?(i.focusUnit(a),p.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:v}],redoMutations:[{id:e.s.id,params:_}]}),!0):!1}},J={id:`base.command.move-base-hierarchy-record`,type:t.CommandType.COMMAND,handler:(n,r)=>{var i;if(!r)return!1;let{unitId:a,tableId:o,recordId:s,parentRecordId:l,orderKey:u}=r,d=n.get(t.IUniverInstanceService),f=d.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!f||!H(f,o,{recordIds:[s,...l?[l]:[]]}))throw new e.K(`missingRecord`);let p=f.getSnapshot(),m=p.tables[o],h=e.Q(m),g=h??r.fieldId??e.nt(m);if(h&&r.fieldId&&r.fieldId!==h||m.fields[g]&&!e.et(m,g))throw new e.K(`invalidField`);let _=e.J(m,g),v=e.rt(_,s,l);if(!v.valid){let n=v.reason===t.BaseHierarchyInvalidReason.SelfParent?`selfParent`:v.reason===t.BaseHierarchyInvalidReason.Cycle?`cycle`:`maxDepth`;throw new e.K(n)}let y=_.parentByRecordId.get(s)??null,b=m.records[s].orderKey;if(y===l&&(u===void 0||u===b))return!0;let x=y!==l,S=u!==void 0&&u!==b,C=new c,w=[],T=m.fields[g],E=x&&(!T||((i=e.lt(T))==null?void 0:i.relationRole)!==t.BaseRecordLinkRole.Parent)?T?C.updateField(p,o,g,{config:{...T.config,relationRole:t.BaseRecordLinkRole.Parent}}):n.get(R).createCreateFieldOp(f,o,e.Y(m,g,r.parentFieldName),m.fieldOrder.length):null;E&&w.push(E),x&&w.push(C.updateCell(p,o,s,g,l?e.dt([l]):``)),S&&w.push(C.updateRecordOrder(p,o,s,u));let D=e.M(w),ee={tableId:o,fieldId:g,recordId:s,oldParentRecordId:y,parentRecordId:l},te={unitId:a,op:D,trigger:J.id,hierarchyChanges:[ee],source:r.source??`ui`},O={...te,source:`redo`};if(!n.get(t.ICommandService).syncExecuteCommand(e.s.id,te))return!1;let ne=f.getSnapshot(),k=[];x&&k.push(kt(ne,p,o,s,g)),S&&k.push(At(ne,p,o,s)),E&&k.push(new e.j().invertOp(p,E));let re={unitId:a,op:e.M(k),trigger:J.id,hierarchyChanges:[{...ee,oldParentRecordId:l,parentRecordId:y}],source:`undo`};return d.focusUnit(a),n.get(t.IUndoRedoService).pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:re}],redoMutations:[{id:e.s.id,params:O}]}),!0}};function kt(t,n,r,i,a){var o,c,l,u,d,f,p,m;let h=t.tables[r],g=n.tables[r],_=(o=h.rowIndex)==null?void 0:o[i],v=(c=h.colIndex)==null?void 0:c[a],y=(l=g.rowIndex)==null?void 0:l[i],b=(u=g.colIndex)==null?void 0:u[a],x=_==null||v==null||(d=h.cellData)==null||(d=d[_])==null?void 0:d[v],S=y==null||b==null||(f=g.cellData)==null||(f=f[y])==null?void 0:f[b],C=(p=h.records[i])==null?void 0:p.values[a],w=(m=g.records[i])==null?void 0:m.values[a],T=[],E=jt(_==null||v==null?null:s.cellData(r,_,v),x,S);E&&T.push(E);let D=jt(s.cell(r,i,a),C,w);return D&&T.push(D),e.M(T)}function At(t,n,r,i){var a,o;let c=t.tables[r],l=n.tables[r],u=[jt([...s.record(r,i),`orderKey`],(a=c.records[i])==null?void 0:a.orderKey,(o=l.records[i])==null?void 0:o.orderKey),jt([...s.table(r),`recordOrder`],c.recordOrder,l.recordOrder)].filter(e=>!!e);return e.M(u)}function jt(e,n,r){if(!e||n===void 0&&r===void 0)return null;let i=t.JSONX.getInstance();return r===void 0?i.removeOp(e,n):n===void 0?i.insertOp(e,r):i.replaceOp(e,n,r)}const Mt={id:`base.command.move-base-view`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,target:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),d=l.beforeViewId??l.afterViewId;if(!u||!d||d===s||!H(u,o,{viewIds:[s,d]}))return!1;let f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),m=u.getSnapshot(),h=new c().moveView(m,o,s,l),g=new e.j().invertOp(m,h),_={unitId:a,op:h},v={unitId:a,op:g};return f.syncExecuteCommand(e.s.id,_)?(i.focusUnit(a),p.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:v}],redoMutations:[{id:e.s.id,params:_}]}),!0):!1}},Nt={id:`base.command.rename-base-table`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,name:s}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o)||!q(l.getSnapshot(),s,o).valid)return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=new c().renameTable(f,o,s),m=new e.j().invertOp(f,p),h={unitId:a,op:p},g={unitId:a,op:m};return u.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}},Pt={id:`base.command.rename-base-view`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,name:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{viewIds:[s]}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot(),m=new c().renameView(p,o,s,l),h=new e.j().invertOp(p,m),g={unitId:a,op:m},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Ft={id:`base.command.set-base-kanban-group-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,fieldId:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{viewIds:[s],fieldIds:[l]}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot(),m=new c().updateViewConfig(p,o,s,{groupFieldId:l}),h=new e.j().invertOp(p,m),g={unitId:a,op:m},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},It={id:`base.command.set-base-name`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),a=i.getUnit(r.unitId,t.UniverInstanceType.UNIVER_BASE);if(!a)return!1;let o=a.getSnapshot().name;if(o===r.name)return!0;let s=new c,l=new e.j,u=[],d=[],f=[a,...i.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).filter(e=>e.getUnitId()!==r.unitId)];for(let t of f){let n=t.getSnapshot(),i=t===a?s.setBaseName(n,r.name):s.renameFormulaUnitReferences(n,o,r.name);i&&(u.push({id:e.s.id,params:{unitId:t.getUnitId(),op:i,trigger:It.id}}),d.unshift({id:e.s.id,params:{unitId:t.getUnitId(),op:l.invertOp(n,i),trigger:It.id}}))}let p=n.get(t.ICommandService),m=n.get(t.IUndoRedoService),h=m.__tempBatchingUndoRedo(r.unitId);try{return(0,t.sequenceExecute)(u,p).result?(i.focusUnit(r.unitId),m.pushUndoRedo({unitID:r.unitId,undoMutations:d,redoMutations:u}),!0):!1}finally{h.dispose()}}},Lt={type:t.CommandType.COMMAND,id:`base.command.set-permission`,async handler(e,n){if(!n||!O.includes(n.action)||n.objectId!==n.unitId&&n.action!==r.UnitAction.Edit||n.policy&&(![`all`,`owner`,`members`].includes(n.policy.edit)||n.policy.strategies.some(e=>!O.includes(e.action)||n.objectId!==n.unitId&&e.action!==r.UnitAction.Edit)))return!1;let i=P(n.unitId,n.objectId,n.action),a={unitId:n.unitId,objectId:n.objectId,objectType:i.type},o=e.get(t.ObjectPermissionService);return n.remove?await o.remove(a):n.policy?await o.save(a,n.policy):await o.setPoint(a,i,n.value),!0}},Rt={type:t.CommandType.COMMAND,id:`base.command.set-permissions`,async handler(e,n){if(!(n!=null&&n.unitId)||!Array.isArray(n.changes)||!n.changes.length||n.changes.some(e=>!(e!=null&&e.objectId)||e.objectId===n.unitId||e.policy!==null&&(!e.policy||![`all`,`owner`,`members`].includes(e.policy.edit)||!Array.isArray(e.policy.collaborators)||!Array.isArray(e.policy.strategies)||e.policy.strategies.some(e=>e.action!==r.UnitAction.Edit))))throw Error(`Invalid object permission batch.`);return e.get(t.ObjectPermissionService).saveMany(n.changes.map(e=>{let t=P(n.unitId,e.objectId,r.UnitAction.Edit);return{unitId:n.unitId,objectId:e.objectId,objectType:t.type,policy:e.policy}}))}};function zt(n,r){let i=e.N(t.Tools.deepClone(n)),a=/* @__PURE__ */ new Map;return r.forEach(t=>{var n,r;let o=`recordId`in t?t.recordId:(n=i.rowId)==null?void 0:n[t.row],s=`fieldId`in t?t.fieldId:(r=i.colId)==null?void 0:r[t.col],c=s?i.fields[s]:void 0;if(!o||!s||!c||!i.records[o])return;let l=e.B(t.value,c),u=e.V(t.value,l,c,i,o),d=a.get(o)??{};d[s]=u,a.set(o,d)}),[...a].map(([e,t])=>({recordId:e,values:t}))}const Bt={id:`base.command.set-base-range-values`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,patches:s}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=e.N(f.tables[o]),m=s.map(e=>{var t;return`recordId`in e?e.recordId:(t=p.rowId)==null?void 0:t[e.row]}).filter(e=>e!=null),h=s.map(e=>{var t;return`fieldId`in e?e.fieldId:(t=p.colId)==null?void 0:t[e.col]}).filter(e=>e!=null);if(m.length!==s.length||h.length!==s.length||!H(l,o,{recordIds:m,fieldIds:h})||s.some((e,t)=>!W(l,o,h[t],e.value)))return!1;let g=e.at(p,zt(p,s)),_=s.flatMap(e=>{var t,n;if(`row`in e)return[e];let r=(t=p.rowIndex)==null?void 0:t[e.recordId],i=(n=p.colIndex)==null?void 0:n[e.fieldId];return r==null||i==null?[]:[{row:r,col:i,value:e.value}]}),v=new c().setRangeValues(f,o,_),y=new e.j().invertOp(f,v),b={unitId:a,op:v,trigger:g.length?Bt.id:void 0,hierarchyChanges:g.length?g:void 0,source:g.length?`redo`:void 0},x={unitId:a,op:y,trigger:g.length?Bt.id:void 0,hierarchyChanges:g.length?g.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})):void 0,source:g.length?`undo`:void 0},S={...b,source:g.length?r.source??`ui`:void 0};return u.syncExecuteCommand(e.s.id,S)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},Vt={id:`base.command.set-base-table-hierarchy-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let{unitId:i,tableId:a,fieldId:o}=r,s=n.get(t.IUniverInstanceService),l=s.getUnit(i,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,a))return!1;let u=l.getSnapshot(),d=u.tables[a];if(o!==null&&!e.et(d,o))throw new e.K(`invalidField`);if(e.Q(d)===o)return!0;let f=new c,p=Object.values(d.fields).flatMap(n=>{if(!e.et(d,n.id))return[];let r=e.lt(n);if(!r)return[];let i=n.id===o;if(r.relationRole===t.BaseRecordLinkRole.Parent===i)return[];let s={...n.config,targetTableId:r.targetTableId,multiple:r.multiple};return i?s.relationRole=t.BaseRecordLinkRole.Parent:delete s.relationRole,[f.updateField(u,a,n.id,{config:s})]}),m=e.M(p),h=new e.j().invertOp(u,m),g={unitId:i,op:m},_={unitId:i,op:h};return n.get(t.ICommandService).syncExecuteCommand(e.s.id,g)?(s.focusUnit(i),n.get(t.IUndoRedoService).pushUndoRedo({unitID:i,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Ht={id:`base.command.set-base-view-field-order`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,fieldId:l,target:u}=r,d=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),f=u.beforeFieldId??u.afterFieldId;if(!d||!f||f===l||!H(d,o,{viewIds:[s],fieldIds:[l,f]}))return!1;let p=d.getSnapshot().tables[o],m=p.fields[l],h=p.fields[f];if(m.system===!0||m.type===t.BaseFieldType.RecordId||h.system===!0||h.type===t.BaseFieldType.RecordId)return!1;let g=n.get(t.ICommandService),_=n.get(t.IUndoRedoService),v=d.getSnapshot(),y=new c().setViewFieldOrder(v,o,s,l,u),b=new e.j().invertOp(v,y),x={unitId:a,op:y},S={unitId:a,op:b};return g.syncExecuteCommand(e.s.id,x)?(i.focusUnit(a),_.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:S}],redoMutations:[{id:e.s.id,params:x}]}),!0):!1}},Ut={id:`base.command.set-base-view-field-visible`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,fieldId:l,visible:u}=r,d=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!d||!H(d,o,{viewIds:[s],fieldIds:[l]}))return!1;let f=d.getSnapshot().tables[o].fields[l];if(f.system===!0||f.type===t.BaseFieldType.RecordId)return!1;let p=n.get(t.ICommandService),m=n.get(t.IUndoRedoService),h=d.getSnapshot(),g=new c,_=g.setViewFieldVisible(h,o,s,l,u),{undo:v,redo:y}=g.getViewFieldSettingHistory(h,o,s,l,{hidden:!u}),b={unitId:a,op:y},x={unitId:a,op:v};return p.syncExecuteCommand(e.s.id,{unitId:a,op:_})?(i.focusUnit(a),m.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},Wt={id:`base.command.set-base-view-field-width`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,fieldId:l,width:u}=r,d=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!d||!H(d,o,{viewIds:[s],fieldIds:[l]}))return!1;let f=d.getSnapshot().tables[o].fields[l];if(f.system===!0||f.type===t.BaseFieldType.RecordId)return!1;let p=n.get(t.ICommandService),m=n.get(t.IUndoRedoService),h=d.getSnapshot(),g=new c,_=g.setViewFieldWidth(h,o,s,l,u),{undo:v,redo:y}=g.getViewFieldSettingHistory(h,o,s,l,{width:u}),b={unitId:a,op:y},x={unitId:a,op:v};return p.syncExecuteCommand(e.s.id,{unitId:a,op:_})?(i.focusUnit(a),m.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},Gt={id:`base.command.set-base-view-filter`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,filter:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),d=(l==null?void 0:l.conditions.map(e=>e.fieldId))??[];if(!u||!H(u,o,{viewIds:[s],fieldIds:d}))return!1;let f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),m=u.getSnapshot(),h=new c().setViewFilter(m,o,s,l),g=new e.j().invertOp(m,h),_={unitId:a,op:h},v={unitId:a,op:g};return f.syncExecuteCommand(e.s.id,_)?(i.focusUnit(a),p.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:v}],redoMutations:[{id:e.s.id,params:_}]}),!0):!1}},Kt={id:`base.command.set-base-view-group`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,group:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{viewIds:[s],fieldIds:l.map(e=>e.fieldId)}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot(),m=new c().setViewGroup(p,o,s,l),h=new e.j().invertOp(p,m),g={unitId:a,op:m},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},qt={id:`base.command.set-base-view-sort`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,sort:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{viewIds:[s],fieldIds:l.map(e=>e.fieldId)}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot(),m=new c().setViewSort(p,o,s,l),h=new e.j().invertOp(p,m),g={unitId:a,op:m},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Jt={id:`base.command.update-base-cell`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,recordId:s,fieldId:c,value:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{recordIds:[s],fieldIds:[c]})||!W(u,o,c,l))return!1;let d=u.getSnapshot().tables[o],f=e.et(d,c)&&e.X(d).includes(c),p=f?e.J(d,c):null,m=(p==null?void 0:p.parentByRecordId.get(s))??null,h=f?e.ut(l)[0]??null:null;if(p){if(h&&!d.records[h])throw new e.K(`missingRecord`);let n=e.rt(p,s,h);if(!n.valid){let r=n.reason===t.BaseHierarchyInvalidReason.SelfParent?`selfParent`:n.reason===t.BaseHierarchyInvalidReason.Cycle?`cycle`:`maxDepth`;throw new e.K(r)}}let g=n.get(t.ICommandService),_=n.get(t.IUndoRedoService),v=n.get(R),y;try{y=v.createUpdateCellOp(u,o,s,c,l)}catch(e){return console.error(`Failed to create update cell operation:`,e),!1}let b=new e.j().invertOp(u.getSnapshot(),y),x=f&&m!==h?[{tableId:o,fieldId:c,recordId:s,oldParentRecordId:m,parentRecordId:h}]:void 0,S={unitId:a,op:y,trigger:x?Jt.id:void 0,hierarchyChanges:x,source:x?r.source??`ui`:void 0},C={...S,source:x?`redo`:void 0},w={unitId:a,op:b,trigger:x?Jt.id:void 0,hierarchyChanges:x==null?void 0:x.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})),source:x?`undo`:void 0};return g.syncExecuteCommand(e.s.id,S)?(i.getFocusedUnit()||i.focusUnit(a),_.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:w}],redoMutations:[{id:e.s.id,params:C}]}),!0):!1}},Yt={id:`base.command.update-base-field-description`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{fieldIds:[s]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=r.description.trim(),m=new c().updateField(f,o,s,{description:p}),h=new e.j().invertOp(l.getSnapshot(),m),g={unitId:a,op:m},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Xt={id:`base.command.update-base-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s,patch:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||s===t.BASE_RECORD_ID_FIELD_ID||!H(u,o,{fieldIds:[s]}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot();if(!U(u,o,{...p.tables[o].fields[s],...l}))return!1;let m=new c().updateField(p,o,s,l),h=new e.j().invertOp(p,m),g={unitId:a,op:m},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Zt={id:`base.command.update-base-kanban-config`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,patch:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{viewIds:[s]}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot(),m=new c().updateViewConfig(p,o,s,l),h=new e.j().invertOp(p,m),g={unitId:a,op:m},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Qt={id:`base.command.update-base-record-order`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,recordId:s,orderKey:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{recordIds:[s]}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot(),m=new c().updateRecordOrder(p,o,s,l),h=new e.j().invertOp(p,m),g={unitId:a,op:m},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}};let $t=/* @__PURE__ */ function(e){return e.Set=`set`,e.Add=`add`,e.Delete=`delete`,e.Clear=`clear`,e}({});const en={id:`base.command.update-base-view-conditional-color-rules`,type:t.CommandType.COMMAND,handler:(n,r)=>{var i;if(!r)return!1;let a=n.get(t.IUniverInstanceService),o=a.getUnit(r.unitId,t.UniverInstanceType.UNIVER_BASE);if(!o||!H(o,r.tableId,{viewIds:[r.viewId]}))return!1;let s=o.getSnapshot(),l=s.tables[r.tableId],u=tn(((i=l.views[r.viewId].config.conditionalColoring)==null?void 0:i.rules)??[],r);if(!u)return!1;nn(l,u);let d=new c().updateViewConfig(s,r.tableId,r.viewId,{conditionalColoring:u.length?{rules:u}:null}),f=new e.j().invertOp(s,d),p={unitId:r.unitId,op:d},m={unitId:r.unitId,op:f};return n.get(t.ICommandService).syncExecuteCommand(e.s.id,p)?(a.focusUnit(r.unitId),n.get(t.IUndoRedoService).pushUndoRedo({unitID:r.unitId,undoMutations:[{id:e.s.id,params:m}],redoMutations:[{id:e.s.id,params:p}]}),!0):!1}};function tn(e,n){switch(n.type){case`set`:return t.Tools.deepClone(n.rules);case`add`:return[...t.Tools.deepClone(e),t.Tools.deepClone(n.rule)];case`delete`:{let r=e.filter(e=>e.id!==n.ruleId);return r.length===e.length?null:t.Tools.deepClone(r)}case`clear`:return e.length?[]:null}}function nn(e,t){if(!Array.isArray(t))throw TypeError(`[UpdateBaseViewConditionalColorRulesCommand]: rules must be an array.`);let n=/* @__PURE__ */ new Set;for(let[r,i]of t.entries())an(e,i,rn(i,r,n))}function rn(e,n,r){if(!e||typeof e!=`object`)throw TypeError(`[UpdateBaseViewConditionalColorRulesCommand]: rule at index ${n} must be an object.`);let i=typeof e.id==`string`&&e.id.trim()?`"${e.id}"`:`at index ${n}`;if(typeof e.id!=`string`||!e.id.trim())throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} must have a non-empty id.`);if(r.has(e.id))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: duplicate rule id "${e.id}".`);r.add(e.id);let a=typeof e.color==`string`&&e.color.trim()?new t.ColorKit(e.color):null;if(!(a!=null&&a.isValid))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} must have a valid CSS color.`);return i}function an(n,r,i){let a=new Set(Object.values(t.BaseConditionalColorTarget)),o=new Set(Object.values(t.BaseConditionalColorOperator)),s=new Set(Object.values(t.BaseConditionalDateMode));if(!a.has(r.target))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} has unsupported target "${String(r.target)}".`);let c=typeof r.fieldId==`string`?n.fields[r.fieldId]:void 0;if(!c||c.system===!0||c.type===t.BaseFieldType.RecordId)throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} references missing or non-public field "${String(r.fieldId)}".`);if(!o.has(r.operator))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} has unsupported operator "${String(r.operator)}".`);if(r.dateMode!==void 0&&!s.has(r.dateMode))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} has unsupported date mode "${String(r.dateMode)}".`);if(r.target===t.BaseConditionalColorTarget.COLUMN)return;let l=e.S(c.type);if(!l.includes(r.operator))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} cannot use operator "${r.operator}" with field type "${c.type}". Allowed operators: ${l.join(`, `)}.`);if(r.dateMode!==void 0&&!e.C(c.type))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} can use dateMode only with Date, CreatedAt, or UpdatedAt fields.`)}const on={id:`base.command.update-base-view-config`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,patch:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{viewIds:[s]}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=u.getSnapshot(),m=new c().updateViewConfig(p,o,s,l),h=new e.j().invertOp(p,m),g={unitId:a,op:m},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},sn={id:`base.command.validate-formula`,type:t.CommandType.COMMAND,handler(e,n){if(!n)return{valid:!1,reason:`[BaseFormula]: validation parameters are required.`};let r=e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_BASE),i=r==null?void 0:r.getSnapshot(),a=i==null?void 0:i.tables[n.tableId];return!i||!a?{valid:!1,reason:`[BaseFormula]: table does not exist.`}:new B().validateFormula(n.formula,a,{snapshot:i})}};let Y=class extends t.ObjectPermissionRuleModel{constructor(e){super(e,`BASE_OBJECT_PERMISSION_PLUGIN`,t.UniverInstanceType.UNIVER_BASE,[r.UnitObject.BaseTable,r.UnitObject.BaseField,r.UnitObject.BaseRecord,r.UnitObject.BaseView,r.UnitObject.BaseDashboard])}};Y=e.g([e._(0,t.IResourceManagerService)],Y);const cn={id:`base.mutation.set-permission-rule`,type:t.CommandType.MUTATION,handler:(e,n)=>!n||!e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_BASE)?!1:e.get(Y).setRule(n.unitId,n.objectType,n.objectId,n.rule)},ln={id:`base.mutation.set-permission-rules`,type:t.CommandType.MUTATION,handler:(e,n)=>!n||!e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_BASE)?!1:e.get(Y).setRules(n.unitId,n.rules)};function un(e){let n=e.now??Date.now(),r=e.primaryFieldId??`${e.id}-field-name`,i=e.gridViewId??`${e.id}-view-grid`,a=e.recordCount??0,o=(0,t.createBaseRecordIdField)(),s={id:r,name:e.primaryFieldName??`Name`,type:t.BaseFieldType.Text,config:{placeholder:`bases.fieldConfig.textPlaceholder`}},c={},l=[],u={},d={},f={};for(let i=0;i<a;i++){let a=`${e.id}-record-${i+1}`;c[a]={id:a,values:{[t.BASE_RECORD_ID_FIELD_ID]:a,...e.recordNamePrefix?{[r]:`${e.recordNamePrefix} ${i+1}`}:{}},orderKey:String(i+1).padStart(4,`0`),createdAt:n,updatedAt:n},l.push(a),u[a]=i,d[i]=a,f[i]={0:{v:a,t:t.CellValueType.STRING}},e.recordNamePrefix&&(f[i][1]={v:`${e.recordNamePrefix} ${i+1}`,t:t.CellValueType.STRING})}let p={id:i,tableId:e.id,name:`Grid`,type:t.BaseViewType.Grid,fieldOrder:[t.BASE_RECORD_ID_FIELD_ID,r],fieldSettings:{[t.BASE_RECORD_ID_FIELD_ID]:{hidden:!0}},config:{frozenFieldCount:1}};return{id:e.id,name:e.name,primaryFieldId:r,fieldOrder:[t.BASE_RECORD_ID_FIELD_ID,r],fields:{[t.BASE_RECORD_ID_FIELD_ID]:o,[r]:s},records:c,recordOrder:l,rowIndex:u,rowId:d,colIndex:{[t.BASE_RECORD_ID_FIELD_ID]:0,[r]:1},colId:{0:t.BASE_RECORD_ID_FIELD_ID,1:r},cellData:f,views:{[i]:p},viewOrder:[i]}}const dn=`UNIVER_EMBED_BASES_TABLE`;function fn(e){let t=un({id:e.hostAnchorId,name:e.name??e.embedId,recordCount:0});return{...t,resources:{...t.resources??{},[dn]:hn(e)}}}function pn(n){return{id:e.s.id,params:{unitId:n.unitId,op:t.JSON1.type.compose(t.JSON1.insertOp([`tables`,n.table.id],n.table),t.JSON1.insertOp([`tableOrder`,n.index??n.snapshot.tableOrder.length],n.table.id)),trigger:`embed-ui`}}}function mn(n){let r=n.snapshot.tableOrder.indexOf(n.tableId);if(!(!n.snapshot.tables[n.tableId]||r<0))return{id:e.s.id,params:{unitId:n.unitId,op:t.JSON1.type.compose(t.JSON1.removeOp([`tables`,n.tableId],n.snapshot.tables[n.tableId]),t.JSON1.removeOp([`tableOrder`,r],n.tableId)),trigger:`embed-ui`}}}function hn(e){return{version:1,embedId:e.embedId,hostAnchorId:e.hostAnchorId,childUnitId:e.childUnitId,childType:e.childType}}function gn(e){let t=Math.max(0,Number(e.decimalPlaces??0)),n=e.useThousands===!1?`0`:`#,##0`,r=t?`.${`0`.repeat(t)}`:``,i=vn(e.abbreviation);return`${e.currencySymbol?yn(e.currencySymbol):``}${n}${r}${i}`}function _n(e,n){let r=gn(n),i=t.numfmt.format(r,e,{throws:!1});return bn(String(i),n.separatorStyle,n.locale)}function vn(e){return e===`K`?`,"K"`:e===`M`?`,,"M"`:e===`B`?`,,,"B"`:``}function yn(e){return/^[A-Z]+$/i.test(e)?`"${e}"`:e}function bn(e,t,n){let r=t===`local`?xn(n):t;return r===`periodComma`?e.replace(/,/g,`\0`).replace(/\./g,`,`).replace(/\0/g,`.`):r===`spaceComma`?e.replace(/,/g,` `).replace(/\./g,`,`):r===`spacePeriod`?e.replace(/,/g,` `):e}function xn(e){var t,n;let r=e||new Intl.NumberFormat().resolvedOptions().locale,i;try{i=new Intl.NumberFormat(r,{minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:!0}).formatToParts(1e6)}catch{return`commaPeriod`}let a=(t=i.find(e=>e.type===`group`))==null?void 0:t.value,o=(n=i.find(e=>e.type===`decimal`))==null?void 0:n.value,s=a===`\xA0`||a===` `?` `:a;return s===`.`&&o===`,`?`periodComma`:s===` `&&o===`,`?`spaceComma`:s===` `&&o===`.`?`spacePeriod`:`commaPeriod`}const Sn=[`count`,`filled`,`empty`,`unique`,`sum`,`average`,`min`,`max`],Cn=[`count`,`filled`,`empty`,`unique`],wn=[`sum`,`average`,`min`,`max`],Tn=[`min`,`max`],En=/* @__PURE__ */ new Set([t.BaseFieldType.Number,t.BaseFieldType.Currency,t.BaseFieldType.Progress,t.BaseFieldType.Rating]),Dn=/* @__PURE__ */ new Set([t.BaseFieldType.MultiSelect,t.BaseFieldType.Person,t.BaseFieldType.Group]),On=`General`;function kn(e){return typeof e==`string`&&Sn.includes(e)}function An(e){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(e=>kn(e[1])))}function jn(e){return En.has(e.type)?[...Cn,...wn]:e.type===t.BaseFieldType.Formula?[...Cn,...Kn(e)===`date`?Tn:wn]:Cn}function Mn(e,t){return jn(e).includes(t)}function Nn(e,t,n){if(!Mn(e,n))return null;let r=t.filter(t=>!Fn(e,t));switch(n){case`count`:return t.length;case`filled`:return r.length;case`empty`:return t.length-r.length;case`unique`:return new Set(r.map(t=>zn(e,t))).size;case`sum`:{let t=In(e,r);return t.length?Rn(t):null}case`average`:{let t=In(e,r);return t.length?Rn(t)/t.length:null}case`min`:{let t=In(e,r);return t.length?Math.min(...t):null}case`max`:{let t=In(e,r);return t.length?Math.max(...t):null}}}function Pn(n,r,i){if(i==null||!Number.isFinite(i))return`-`;if(Cn.includes(r))return String(i);switch(n.type){case t.BaseFieldType.Number:return _n(i,Un(n));case t.BaseFieldType.Currency:return _n(i,Wn(n));case t.BaseFieldType.Progress:return e.p(i,n.config);case t.BaseFieldType.Formula:return Gn(i,n);default:return Jn(i)}}function Fn(e,n){if(n==null)return!0;if(typeof n==`string`)return n.trim()===``;if(Array.isArray(n))return e.type===t.BaseFieldType.Attachment?!n.some(Hn):n.length===0;if(e.type===t.BaseFieldType.Link&&typeof n==`object`){let e=n;return[e.text,e.url].every(e=>e==null||String(e).trim()===``)}return!1}function In(e,t){let n=[];for(let r of t){let t=Ln(e,r);t!=null&&n.push(t)}return n}function Ln(e,n){if(typeof n==`number`)return Number.isFinite(n)?n:null;if(e.type!==t.BaseFieldType.Formula&&typeof n==`string`&&n.trim()!==``){let e=Number(n);return Number.isFinite(e)?e:null}return null}function Rn(e){let t=0,n=0;for(let r of e){let e=t+r;n+=Math.abs(t)>=Math.abs(r)?t-e+r:r-e+t,t=e}return t+n}function zn(e,t){return Dn.has(e.type)&&Array.isArray(t)?Vn([...new Set(t.map(e=>Vn(Bn(e))))].sort()):Vn(Bn(t))}function Bn(e){return Array.isArray(e)?e.map(Bn):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Bn(t)])):e}function Vn(e){return JSON.stringify(e)??`undefined`}function Hn(e){if(typeof e==`string`)return e.trim()!==``;if(!e||typeof e!=`object`)return!1;let t=e;return[t.id,t.name,t.source,t.url,t.thumbnail].some(e=>e!=null&&String(e).trim()!==``)}function Un(e){let t=X(e.config);return{decimalPlaces:Xn(t.decimalPlaces,0,20,2),separatorStyle:typeof t.separatorStyle==`string`?t.separatorStyle:`local`,locale:typeof t.locale==`string`?t.locale:void 0,useThousands:t.useThousands!==!1,abbreviation:typeof t.abbreviation==`string`?t.abbreviation:`none`}}function Wn(e){let t=X(e.config);return{...Un(e),currencySymbol:String(t.currencySymbol??`$`)}}function Gn(e,n){let r=qn(n);if(r===On)return Jn(e);try{return String(t.numfmt.format(r,e,{throws:!1}))}catch{return Jn(e)}}function Kn(e){let t=X(X(e.config).numfmt);return typeof t.type==`string`?t.type:`general`}function qn(e){let t=X(X(e.config).numfmt);return String(t.pattern??On).trim()||On}function Jn(e){return String(Number.isInteger(e)?e:Math.round((e+2**-52)*100)/100)}function X(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Yn(e){if(e==null||e===``)return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null}function Xn(e,t,n,r){let i=Yn(e);return i==null?r:Math.max(t,Math.min(n,Math.round(i)))}function Zn(e,n){let r=t.Tools.deepClone(e),i=n.includeRecords===!0,a=/* @__PURE__ */ new Map,o=n.createViewId??(()=>`view-${(0,t.generateRandomId)(8)}`),s=r.viewOrder;return n.regenerateViewIds&&(s=r.viewOrder.map(e=>{let t=o();return a.set(e,t),t})),{...r,id:n.id,name:n.name,records:i?r.records:{},recordOrder:i?r.recordOrder:[],rowIndex:i?r.rowIndex:{},rowId:i?r.rowId:{},cellData:i?r.cellData:{},resources:i?r.resources:{},viewOrder:s,views:Object.fromEntries(Object.entries(r.views??{}).map(([e,t])=>{let r=a.get(e)??(n.regenerateViewIds?o():e);return[r,{...t,id:r,tableId:n.id}]}))}}function Qn(t){return new e.j().getAffectedRanges(t)}function $n(e){return e.patches.map(t=>({unitId:e.unitId,sheetId:e.tableId,range:{startRow:t.row,endRow:t.row,startColumn:t.col,endColumn:t.col}}))}function er(e,t){return{[e]:Object.fromEntries(t.map(e=>[e,`1`]))}}let tr=class extends t.Disposable{constructor(e,t){super(),this._activeDirtyManagerService=e,this._univerInstanceService=t,this._initialize()}_initialize(){this._activeDirtyManagerService.register(e.s.id,{commandId:e.s.id,getDirtyData:e=>this._getJson1DirtyData(e.params)}),this.disposeWithMe((0,t.toDisposable)(()=>{this._activeDirtyManagerService.remove(e.s.id)}))}_getTable(e,n){let r=this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_BASE);return(r==null?void 0:r.getSnapshot().tables[n])??null}_getJson1DirtyData(e){if(e.trigger===`formula.mutation.set-formula-calculation-result`)return{};if(!e.unitId||!e.op)return{clearDependencyTreeCache:this._getAllBaseDependencyTreeCacheMap(),forceCalculation:!0};let t=Qn(e.op),n=this._getStructureDirtyTableIds(e.unitId,t);if(n.length)return{clearDependencyTreeCache:er(e.unitId,n),forceCalculation:!0};let r=Object.entries(this._groupCellInvalidations(e.unitId,t)).flatMap(([t,n])=>$n({unitId:e.unitId,tableId:t,patches:n}));return r.length?{dirtyRanges:r}:{}}_getStructureDirtyTableIds(e,t){let n=t.filter(e=>e.reason!==`cell`).flatMap(t=>t.tableId?[t.tableId]:this._getAllTableIds(e));return Array.from(new Set(n))}_groupCellInvalidations(e,t){let n=/* @__PURE__ */ new Set;return t.reduce((t,r)=>{let i=this._toDirtyRangePatch(e,r);if(!i)return t;let a=`${r.tableId}:${i.row}:${i.col}`;return n.has(a)||(n.add(a),t[r.tableId]=t[r.tableId]??[],t[r.tableId].push(i)),t},{})}_toDirtyRangePatch(t,n){if(n.reason!==`cell`)return null;if(n.row!=null&&n.column!=null)return{row:n.row,col:n.column,value:null};if(!n.recordId||!n.fieldId)return null;let r=this._getTable(t,n.tableId);if(!r)return null;let i=e.L(r,n.recordId,n.fieldId);return i?{row:i.row,col:i.col,value:null}:null}_getAllTableIds(e){let n=this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_BASE);return Object.values((n==null?void 0:n.getSnapshot().tables)??{}).map(e=>e.id)}_getAllBaseDependencyTreeCacheMap(){let e=this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).map(e=>er(e.getUnitId(),Object.keys(e.getSnapshot().tables)));return Object.assign({},...e)}};tr=e.g([e._(0,n.IActiveDirtyManagerService),e._(1,t.IUniverInstanceService)],tr);let nr=class extends t.Disposable{constructor(t,n,r,i){super(),this._commandService=t,this._univerInstanceService=n,this._formulaCalculationTriggerService=r,this._formulaCalculationSessionService=i,e.b(this,`_formulaService`,new B),e.b(this,`_registeredSuperTableNames`,/* @__PURE__ */ new Map),e.b(this,`_scheduledSuperTableSyncs`,/* @__PURE__ */ new Set),e.b(this,`_formulaSyncQueue`,Promise.resolve()),e.b(this,`_applyingFormulaResults`,!1),this._initialize()}_initialize(){this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).forEach(e=>{this._scheduleSuperTableSync(e)}),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(t.UniverInstanceType.UNIVER_BASE).subscribe(({unit:e})=>{this._scheduleSuperTableSync(e)})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(t.UniverInstanceType.UNIVER_BASE).subscribe(e=>{this._enqueueFormulaSync(()=>this._removeSuperTables(e.getUnitId()))})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>this._onCommandExecuted(e)))}_onCommandExecuted(r){if(r.id===n.SetFormulaCalculationResultMutation.id){ir(r.params)&&this._applyFormulaResult(r.params);return}if(this._applyingFormulaResults||r.id!==e.s.id)return;let i=rr(r.params)?r.params:void 0,a=i!=null&&i.unitId?[this._univerInstanceService.getUnit(i.unitId,t.UniverInstanceType.UNIVER_BASE)].filter(e=>!!e):this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE),o=i==null?void 0:i.op;a.forEach(e=>{let t=o?Qn(o):[];(!o||t.some(e=>e.reason!==`cell`))&&this._scheduleSuperTableSync(e)})}_scheduleSuperTableSync(e){let t=e.getUnitId();this._scheduledSuperTableSyncs.has(t)||(this._scheduledSuperTableSyncs.add(t),this._enqueueFormulaSync(async()=>{this._scheduledSuperTableSyncs.delete(t),await this._syncSuperTables(e)}))}async _syncSuperTables(e){let t=e.getUnitId(),r=this._formulaService.getSuperTableRegistrations(e.getSnapshot()),i=new Set(r.map(({tableName:e})=>e)),a=this._registeredSuperTableNames.get(t)??/* @__PURE__ */ new Set;for(let e of a)if(!i.has(e)&&!await this._executeSuperTableMutationWhileActive(n.RemoveSuperTableMutation.id,{unitId:t,tableName:e}))return;for(let{tableName:e,reference:i}of r)if(!await this._executeSuperTableMutationWhileActive(n.SetSuperTableMutation.id,{unitId:t,tableName:e,reference:i}))return;this._registeredSuperTableNames.set(t,i)}async _removeSuperTables(e){let t=this._registeredSuperTableNames.get(e)??/* @__PURE__ */ new Set;for(let r of t)if(!await this._executeSuperTableMutationWhileActive(n.RemoveSuperTableMutation.id,{unitId:e,tableName:r}))return;this._registeredSuperTableNames.delete(e)}async _executeSuperTableMutationWhileActive(e,t){return!this._disposed&&await this._commandService.executeCommand(e,t,{onlyLocal:!0})&&!this._disposed}_enqueueFormulaSync(e){this._formulaSyncQueue=this._formulaSyncQueue.then(e,e).catch(()=>void 0)}_applyFormulaResult(r){let i=this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE);if(!i.some(e=>{var t;return((t=r.unitData)==null?void 0:t[e.getUnitId()])!=null}))return;let a=i.flatMap(e=>De(e.getSnapshot(),r));if(!a.length){this._formulaCalculationSessionService.markResultApplied(o.FormulaResultApplicationType.BASE,r);return}let s=new c,l=a.flatMap(e=>$n({unitId:e.unitId,tableId:e.tableId,patches:e.patches}));this._applyingFormulaResults=!0,(async()=>{for(let r of a){let i=this._univerInstanceService.getUnit(r.unitId,t.UniverInstanceType.UNIVER_BASE);i&&await this._commandService.executeCommand(e.s.id,{unitId:r.unitId,op:s.setRangeValues(i.getSnapshot(),r.tableId,r.patches),trigger:n.SetFormulaCalculationResultMutation.id},{onlyLocal:!0})}await this._commandService.executeCommand(n.SetTriggerFormulaCalculationStartMutation.id,{dirtyRanges:l},{onlyLocal:!0})})().finally(()=>{this._applyingFormulaResults=!1,this._formulaCalculationSessionService.markResultApplied(o.FormulaResultApplicationType.BASE,r)})}};nr=e.g([e._(0,t.ICommandService),e._(1,t.IUniverInstanceService),e._(2,(0,t.Inject)(n.FormulaCalculationTriggerService)),e._(3,(0,t.Inject)(o.FormulaCalculationSessionService))],nr);function rr(e){return typeof e==`object`&&!!e&&`unitId`in e&&typeof e.unitId==`string`&&`op`in e&&Array.isArray(e.op)}function ir(e){return typeof e==`object`&&!!e&&`unitData`in e&&`unitOtherData`in e}const ar=/* @__PURE__ */ new Set([Lt.id,Rt.id,sn.id]);let or=class extends t.Disposable{constructor(e,n,r,i){super(),this._injector=e,this._commandService=n,this._permissionService=r,this._instanceService=i,this._instanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).forEach(e=>this._registerUnitPermissionPoints(e.getUnitId())),this.disposeWithMe(this._instanceService.getTypeOfUnitAdded$(t.UniverInstanceType.UNIVER_BASE).subscribe(({unit:e})=>this._registerUnitPermissionPoints(e.getUnitId()))),this.disposeWithMe(this._commandService.beforeCommandExecuted((e,t)=>this._check(e,t))),this.disposeWithMe(this._instanceService.getTypeOfUnitDisposed$(t.UniverInstanceType.UNIVER_BASE).subscribe(e=>{this._injector.get(t.ObjectPermissionService).clearUnit(e.getUnitId()),ue(this._permissionService,e.getUnitId())}))}_registerUnitPermissionPoints(e){O.forEach(t=>{let n=P(e,e,t);this._permissionService.getPermissionPoint(n.id)||this._permissionService.addPermissionPoint(n)}),this._injector.get(t.ObjectPermissionService).initializeUnit({unitId:e,objectId:e,objectType:r.UnitObject.Base})}_check(e,i){var a;if(i!=null&&i.fromCollab||i!=null&&i.fromChangeset)return;let o=vr(e.params)?e.params:void 0;if(i!=null&&i.onlyLocal&&e.id===`base.mutation.apply-base-json1`&&(o==null?void 0:o.trigger)===n.SetFormulaCalculationResultMutation.id)return;let s=cr(e.id),c=sr(o==null?void 0:o.unitId,i)??(s?(a=this._instanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_BASE))==null?void 0:a.getUnitId():void 0);if(!c||this._instanceService.getUnitType(c)!==t.UniverInstanceType.UNIVER_BASE)return;if(s){if(!F(this._permissionService,c,c,s))throw this._injector.get(t.ErrorService).emitPermissionDenied(c),new t.CustomCommandExecutionError(`Base ${r.UnitAction[s]} permission denied.`);return}if(ar.has(e.id)||!e.id.startsWith(`base.command.`)&&!e.id.startsWith(`base.mutation.`))return;let l=this._instanceService.getUnit(c,t.UniverInstanceType.UNIVER_BASE),u=l?lr(l,o??{},e.id):[];if(!l||!de(this._permissionService,c,u))throw this._injector.get(t.ErrorService).emitPermissionDenied(c,u),new t.CustomCommandExecutionError(`Base edit permission denied.`)}};or=e.g([e._(0,(0,t.Inject)(t.Injector)),e._(1,t.ICommandService),e._(2,t.IPermissionService),e._(3,t.IUniverInstanceService)],or);function sr(e,t){return typeof e==`string`?e:typeof(t==null?void 0:t.unitId)==`string`?t.unitId:void 0}function cr(e){if(e===`bases-exchange-client.operation.export-base`||e===`bases-exchange-client.operation.export-base-by-format`)return r.UnitAction.Export;if(e.startsWith(`thread-comment.command.`)||e.startsWith(`thread-comment.mutation.`))return r.UnitAction.Comment}function lr(e,t,n){if(n===`base.mutation.apply-base-json1`&&_r(t.op))return ur(e,t.op);let r=/* @__PURE__ */ new Set,i=mr(t,`table`),a=typeof t.tableId==`string`?t.tableId:i[0];if(i.forEach(e=>r.add(A(e))),!a)return[...r];let o=e.getSnapshot().tables[a],s=new Set(mr(t,`field`)),c=new Set(mr(t,`record`)),l=new Set(mr(t,`view`));return hr(o,t.patches,c,s),gr(t,s),s.forEach(e=>r.add(j(a,e))),c.forEach(e=>r.add(M(a,e))),l.forEach(e=>r.add(N(a,e))),[...r]}function ur(t,n){let r=t.getSnapshot(),i=new e.j().getAffectedRanges(n),a=dr(n),o=/* @__PURE__ */ new Set;return i.forEach(e=>{var t,n;let{tableId:i}=e;if(!i)return;o.add(A(i));let s=r.tables[i],c=e.recordId??(e.row==null||s==null||(t=s.rowId)==null?void 0:t[e.row]),l=e.fieldId??(e.column==null||s==null||(n=s.colId)==null?void 0:n[e.column]);c&&o.add(M(i,c)),l&&o.add(j(i,l)),e.viewId&&o.add(N(i,e.viewId)),(e.reason===`table`||a.has(i))&&s&&(Object.keys(s.fields).forEach(e=>o.add(j(i,e))),Object.keys(s.records).forEach(e=>o.add(M(i,e))),Object.keys(s.views).forEach(e=>o.add(N(i,e)))),e.reason===`record`&&s&&Object.keys(s.fields).forEach(e=>o.add(j(i,e)))}),i.length===0&&pr(n,`tableOrder`)&&Object.keys(r.tables).forEach(e=>o.add(A(e))),[...o]}function dr(e){let t=/* @__PURE__ */ new Set,n=e=>{Array.isArray(e)&&e.forEach((r,i)=>{r===`tables`&&typeof e[i+1]==`string`&&fr(e[i+2])&&t.add(e[i+1]),n(r)})};return n(e),t}function fr(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&(`i`in e||`r`in e||`p`in e||`d`in e||`es`in e||`ena`in e||`et`in e)}function pr(e,t){return Array.isArray(e)&&e.some(e=>e===t||pr(e,t))}function mr(e,t){let n=/* @__PURE__ */ new Set,r=`${t}Id`,i=`${t}Ids`,a=(e,o=``)=>{typeof e==`string`?o===r&&n.add(e):Array.isArray(e)?o===i?e.forEach(e=>{typeof e==`string`&&n.add(e)}):e.forEach(e=>a(e,o)):vr(e)&&Object.entries(e).forEach(([e,r])=>{e===`id`&&o===t&&typeof r==`string`?n.add(r):a(r,e)})};return a(e),[...n]}function hr(e,t,n,r){e&&Array.isArray(t)&&t.forEach(t=>{if(!vr(t))return;let i=t;if(typeof i.row==`number`){var a;let t=(a=e.rowId)==null?void 0:a[i.row];t&&n.add(t)}if(typeof i.col==`number`){var o;let t=(o=e.colId)==null?void 0:o[i.col];t&&r.add(t)}})}function gr(e,t,n=``){e&&typeof e==`object`&&(Array.isArray(e)?e.forEach(e=>gr(e,t,n)):vr(e)&&Object.entries(e).forEach(([e,r])=>{n===`values`&&t.add(e),gr(r,t,e)}))}function _r(e){return Array.isArray(e)}function vr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const yr=(0,t.createIdentifier)(`base.resource.service`);let br=class{constructor(e){this._univerInstanceService=e}getBase(e){return this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_BASE)??null}getAllBases(){return this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE)}createBase(e){return this._univerInstanceService.createUnit(t.UniverInstanceType.UNIVER_BASE,e)}};br=e.g([e._(0,t.IUniverInstanceService)],br);const xr=(0,t.createIdentifier)(`base.view-registry.service`);var Sr=class extends t.Disposable{constructor(...t){super(...t),e.b(this,`_plugins`,/* @__PURE__ */ new Map)}register(e){return this._plugins.set(e.type,e),(0,t.toDisposable)(()=>this._plugins.delete(e.type))}get(e){let t=this._plugins.get(e);if(!t)throw Error(`[BaseViewRegistryService]: view type "${e}" is not registered.`);return t}getAll(){return Array.from(this._plugins.values())}};const Cr=[e.s];let Z=class extends t.Plugin{constructor(n=e.r,r,i,a,o,s){super(),this._config=n,this._injector=r,this._commandService=i,this._univerInstanceService=a,this._configService=o,this._dataSyncPrimaryController=s,e.b(this,`_baseSyncDisposables`,/* @__PURE__ */ new Map);let{...c}=(0,t.merge)({},e.r,this._config);this._configService.setConfig(e.t,c),this._univerInstanceService.registerCtorForType(t.UniverInstanceType.UNIVER_BASE,t.BaseDataModel),this._initDependencies(),this._initCommands(),this._initRegistries(),this._initDataSync()}onStarting(){this._injector.add([Y]),this.disposeWithMe(this._injector.get(t.ICommandService).registerCommand(cn)),this.disposeWithMe(this._injector.get(t.ICommandService).registerCommand(ln)),this.disposeWithMe(this._injector.get(t.ObjectPermissionService).registerRuleModel(r.UnitObject.Base,this._injector.get(Y),cn.id,ln.id))}onReady(){(0,t.touchDependencies)(this._injector,[[br],[z],[tr]]),this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).forEach(e=>this._syncBaseUnit(e.getUnitId())),(0,t.touchDependencies)(this._injector,[[nr],[or]])}_initDependencies(){[[e.y,{useClass:e.v}],[xr,{useClass:Sr}],[e.u,{useClass:e.l}],[yr,{useClass:br}],[fe,{useClass:pe}],[R,{useClass:z}],[tr],[nr],[or]].forEach(e=>this._injector.add(e))}_initCommands(){[rt,Nt,xt,Jt,G,qe,Je,Bt,tt,K,Ze,bt,Qe,wt,Qt,J,et,Ct,Xt,Yt,$e,yt,Ot,sn,vt,Tt,Pt,It,St,Mt,on,en,Ft,Lt,Rt,Zt,Gt,qt,Kt,Vt,Ut,Wt,Ht,...Cr].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e))),Cr.forEach(e=>{var t;return(t=this._dataSyncPrimaryController)==null?void 0:t.registerSyncingMutations(e)})}_initDataSync(){this._dataSyncPrimaryController&&(this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(t.UniverInstanceType.UNIVER_BASE).subscribe(({unit:e})=>{this._syncBaseUnit(e.getUnitId())})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(t.UniverInstanceType.UNIVER_BASE).subscribe(e=>{var t;(t=this._baseSyncDisposables.get(e.getUnitId()))==null||t.dispose(),this._baseSyncDisposables.delete(e.getUnitId())})))}_syncBaseUnit(e){this._dataSyncPrimaryController&&!this._baseSyncDisposables.has(e)&&this._baseSyncDisposables.set(e,this._dataSyncPrimaryController.syncUnit(e))}_initRegistries(){let t=this._injector.get(e.y);e.x().forEach(e=>t.register(e));let n=this._injector.get(xr),r=this._injector.get(e.u);e.f().forEach(e=>{n.register(e),r.registerView(e)})}};e.b(Z,`pluginName`,`BASES_PLUGIN`),e.b(Z,`packageName`,e.a),e.b(Z,`version`,e.o),e.b(Z,`type`,t.UniverInstanceType.UNIVER_BASE),Z=e.g([(0,t.DependentOn)(i.UniverLicensePlugin,n.UniverProFormulaEnginePlugin),e._(1,(0,t.Inject)(t.Injector)),e._(2,t.ICommandService),e._(3,t.IUniverInstanceService),e._(4,t.IConfigService),e._(5,(0,t.Optional)(a.DataSyncPrimaryController))],Z);function wr(e){let t=Lr(e.query);if(!t)return{query:``,total:0,matches:[]};let n=[],r=[];for(let t=0;t<e.fieldIds.length;t++){if(!(t in e.fieldIds))continue;let n=e.table.fields[e.fieldIds[t]];n&&r.push({field:n,fieldIndex:t})}e.rows.forEach((e,i)=>{r.forEach(({field:r,fieldIndex:a})=>{let o=Tr(e.values[r.id],r);if(!o)return;let s=Ir(t,o.searchTexts);s<=0||n.push({recordId:e.recordId,fieldId:r.id,fieldType:r.type,text:o.displayText,score:s,rowIndex:i,fieldIndex:a})})}),n.sort((e,t)=>t.score-e.score||e.rowIndex-t.rowIndex||e.fieldIndex-t.fieldIndex);let i=e.limit==null?n:n.slice(0,Math.max(0,e.limit));return{query:t,total:n.length,matches:zr(i)}}function Tr(e,t){let n=[];for(let r of Dr(e,t)){let e=Lr(r);e&&n.push(e)}return n.length?{displayText:Er(e,t),searchTexts:Rr(n)}:null}function Er(e,n){switch(n.type){case t.BaseFieldType.SingleSelect:case t.BaseFieldType.MultiSelect:case t.BaseFieldType.Group:return Or(e,n).join(`, `);case t.BaseFieldType.Link:return jr(e);case t.BaseFieldType.Date:case t.BaseFieldType.CreatedAt:case t.BaseFieldType.UpdatedAt:return Mr(e,n);case t.BaseFieldType.Number:case t.BaseFieldType.Currency:return Nr(e,n);case t.BaseFieldType.Progress:return Pr(e,n);case t.BaseFieldType.Checkbox:return e?`Checked`:`Unchecked`;case t.BaseFieldType.Attachment:return Fr(e).join(`, `);default:return Q(e)}}function Dr(e,n){switch(n.type){case t.BaseFieldType.SingleSelect:case t.BaseFieldType.MultiSelect:case t.BaseFieldType.Group:{let t=Or(e,n);if(Array.isArray(e)){let n=[...t];for(let t=0;t<e.length;t++)t in e&&n.push(String(e[t]));return n}return e==null?t:[...t,String(e)]}case t.BaseFieldType.Link:{let t=Ar(e);return[t.text,t.url]}case t.BaseFieldType.Date:case t.BaseFieldType.CreatedAt:case t.BaseFieldType.UpdatedAt:return[Mr(e,n),Q(e)];case t.BaseFieldType.Number:case t.BaseFieldType.Currency:return[Nr(e,n),Q(e)];case t.BaseFieldType.Progress:return[Pr(e,n),Q(e)];case t.BaseFieldType.Checkbox:return e?[`Checked`,`Yes`,`True`]:[`Unchecked`,`No`,`False`];case t.BaseFieldType.Attachment:return Fr(e);default:return[Q(e)]}}function Or(e,t){var n;let r=Array.isArray((n=t.config)==null?void 0:n.options)?t.config.options:[],i=[];if(Array.isArray(e)){for(let t=0;t<e.length;t++){if(!(t in e))continue;let n=String(e[t]);n&&i.push(kr(r,n))}return i}if(e!=null){let t=String(e);t&&i.push(kr(r,t))}return i}function kr(e,t){for(let n of e){if(typeof n==`string`&&n===t)return n;if(n&&typeof n==`object`){let e=n;if(String(e.id??e.name??``)===t||String(e.name??``)===t)return String(e.name??e.id??t)}}return t}function Ar(e){if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e;return{text:String(t.text??t.url??``),url:String(t.url??``)}}return{text:Q(e),url:Q(e)}}function jr(e){let t=Ar(e);return t.text||t.url}function Mr(t,n){return typeof t!=`number`||!Number.isFinite(t)?``:e.D(t,n.config)}function Nr(e,t){let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)?_n(n,t.config):``}function Pr(t,n){let r=typeof t==`number`?t:Number(t);return Number.isFinite(r)?e.p(r,n.config):``}function Fr(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e,n=String(t.name??t.url??``).trim();return n?[n]:[]}):[]}function Q(e){if(e==null)return``;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return String(e);if(Array.isArray(e)){let t=[];for(let n=0;n<e.length;n++){if(!(n in e))continue;let r=Q(e[n]);r&&t.push(r)}return t.join(`, `)}if(typeof e==`object`){let t=e;return String(t.title??t.name??t.text??t.url??``).trim()}return String(e)}function Ir(e,t){let n=0;for(let r of t)r&&(r===e?n=Math.max(n,300):r.startsWith(e)?n=Math.max(n,250):r.includes(e)&&(n=Math.max(n,200)));return n}function Lr(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function Rr(e){return Array.from(new Set(e))}function zr(e){let t=[];for(let{rowIndex:n,fieldIndex:r,...i}of e)t.push(i);return t}function Br(e){return{compress:!0,kind:`base-range-values-v1`,u:e.unitId,t:e.tableId,p:e.patches.map(e=>[e.row,e.col,Wr(e.value)]),...e.trigger===void 0?{}:{g:e.trigger}}}function Vr(e){if(Zr(e,`base-range-values-v1`),!Hr(e)){if(!Xr(e))throw Error(`[BaseCompression]: invalid uncompressed range values payload.`);return e}return{unitId:e.u,tableId:e.t,patches:e.p.map(([e,t,n])=>({row:e,col:t,value:Gr(n)})),...e.g===void 0?{}:{trigger:e.g}}}function Hr(e){return!$(e)||e.compress!==!0||e.kind!==`base-range-values-v1`?!1:typeof e.u==`string`&&typeof e.t==`string`&&(e.g===void 0||typeof e.g==`string`)&&Array.isArray(e.p)&&e.p.every(e=>Array.isArray(e)&&e.length===3&&Number.isInteger(e[0])&&Number.isInteger(e[1]))}function Ur(e){return!$(e)||e.compress!==!0||e.kind!==`base-snapshot-v1`||!$(e.tables)?!1:Object.values(e.tables).every(e=>$(e)&&(e.cd===void 0||Array.isArray(e.cd)&&e.cd.every(e=>Array.isArray(e)&&e.length===3&&Number.isInteger(e[0])&&Number.isInteger(e[1])&&Yr(e[2]))))}function Wr(e){return Jr(e)?Kr(e):e}function Gr(e){return Yr(e)?qr(e):e}function Kr(e){return{c:1,...e.v===void 0?{}:{v:e.v},...e.t!==void 0&&e.t!==null?{t:e.t}:e.t===null?{t:null}:{},...e.f!==void 0&&e.f!==null?{f:e.f}:e.f===null?{f:null}:{},...e.si!==void 0&&e.si!==null?{si:e.si}:e.si===null?{si:null}:{},...e.p!==void 0&&e.p!==null?{p:e.p}:e.p===null?{p:null}:{}}}function qr(e){return{...e.v===void 0?{}:{v:e.v},...e.t===void 0?{}:{t:e.t},...e.f===void 0?{}:{f:e.f},...e.si===void 0?{}:{si:e.si},...e.p===void 0?{}:{p:e.p}}}function Jr(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&(Object.prototype.hasOwnProperty.call(e,`v`)||Object.prototype.hasOwnProperty.call(e,`t`)||Object.prototype.hasOwnProperty.call(e,`p`)||Object.prototype.hasOwnProperty.call(e,`f`)||Object.prototype.hasOwnProperty.call(e,`si`))}function Yr(e){return $(e)&&e.c===1}function Xr(e){return $(e)&&typeof e.unitId==`string`&&typeof e.tableId==`string`&&(e.trigger===void 0||typeof e.trigger==`string`)&&Array.isArray(e.patches)&&e.patches.every(e=>$(e)&&Number.isInteger(e.row)&&Number.isInteger(e.col)&&`value`in e)}function Zr(e,t){if($(e)&&e.compress===!0){if(e.kind!==t)throw Error(`[BaseCompression]: unsupported compressed payload kind "${String(e.kind)}".`);if(!(t===`base-range-values-v1`?Hr(e):Ur(e)))throw Error(`[BaseCompression]: invalid compressed payload "${t}".`)}}function $(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}const Qr=(0,t.createIdentifier)(`bases.sync-status.service`);exports.AddGanttPredecessorCommand=qe,exports.ApplyBaseJson1Mutation=e.s,exports.BASE_FIELD_STAT_TYPES=Sn,exports.BASE_HIERARCHY_MAX_LEVELS=e.U,exports.BASE_HIERARCHY_PARENT_FIELD_ID=e.W,exports.BASE_TABLE_NAME_REQUIREMENTS=`Base table names are exported as Excel worksheet names and must contain 1-31 characters, not start or end with an apostrophe, not contain : \\ / ? * [ ], and be unique (case-insensitive).`,exports.BASE_UNIT_PERMISSION_ACTIONS=O,exports.BaseConditionalColorRuleUpdateType=$t,exports.BaseEventSource=e.G,exports.BaseFormulaService=B,exports.BaseHierarchyError=e.K,exports.BaseHierarchyErrorCode=e.q,exports.BaseHistoryAction=e.c,exports.BaseJson1OpApplier=e.j,exports.BaseJson1OpFactory=c,exports.BatchCreateBaseRecordsCommand=Ze,exports.BatchDeleteBaseRecordsCommand=Qe,exports.ChangeBaseFieldTypeCommand=$e,exports.CreateBaseChildRecordCommand=K,exports.CreateBaseFieldCommand=et,exports.CreateBaseRecordCommand=tt,exports.CreateBaseTableCommand=rt,exports.CreateBaseViewCommand=vt,exports.DeleteBaseFieldCommand=yt,exports.DeleteBaseRecordCommand=bt,exports.DeleteBaseTableCommand=xt,exports.DeleteBaseViewCommand=St,exports.DuplicateBaseFieldCommand=Ct,exports.DuplicateBaseRecordCommand=wt,exports.EMBED_BASES_TABLE_RESOURCE_KEY=dn,exports.EnsureBaseTemporalViewDateFieldsCommand=Tt,exports.IBaseCommandService=R,exports.IBasePermissionService=fe,exports.IBaseProjectionService=e.u,exports.IBaseSyncStatusService=Qr,exports.IBaseViewRegistryService=xr,exports.MoveBaseFieldCommand=Ot,exports.MoveBaseHierarchyRecordCommand=J,exports.MoveBaseViewCommand=Mt,exports.RemoveGanttPredecessorCommand=Je,exports.RenameBaseTableCommand=Nt,exports.RenameBaseViewCommand=Pt,exports.SetBaseKanbanGroupFieldCommand=Ft,exports.SetBaseNameCommand=It,exports.SetBasePermissionCommand=Lt,exports.SetBasePermissionRuleMutation=cn,exports.SetBasePermissionRulesMutation=ln,exports.SetBasePermissionsCommand=Rt,exports.SetBaseRangeValuesCommand=Bt,exports.SetBaseRecordValuesCommand=G,exports.SetBaseTableHierarchyFieldCommand=Vt,exports.SetBaseViewFieldOrderCommand=Ht,exports.SetBaseViewFieldVisibleCommand=Ut,exports.SetBaseViewFieldWidthCommand=Wt,exports.SetBaseViewFilterCommand=Gt,exports.SetBaseViewGroupCommand=Kt,exports.SetBaseViewSortCommand=qt,Object.defineProperty(exports,"UniverBasesPlugin",{enumerable:!0,get:function(){return Z}}),exports.UpdateBaseCellCommand=Jt,exports.UpdateBaseFieldCommand=Xt,exports.UpdateBaseFieldDescriptionCommand=Yt,exports.UpdateBaseKanbanConfigCommand=Zt,exports.UpdateBaseRecordOrderCommand=Qt,exports.UpdateBaseViewConditionalColorRulesCommand=en,exports.UpdateBaseViewConfigCommand=on,exports.ValidateBaseFormulaCommand=sn,exports.baseDateSerialToDateMs=e.T,exports.buildBaseHierarchyIndex=e.J,exports.calculateBaseFieldStat=Nn,exports.canEditBaseTargets=de,exports.compressBaseRangeValuesPayload=Br,exports.copyBaseTableSnapshot=Zn,exports.createBaseHierarchyParentField=e.Y,exports.createDefaultBaseTableSnapshot=un,exports.createEmbedBasesTable=fn,exports.createEmbedBasesTableAddMutation=pn,exports.createEmbedBasesTableRemoveMutation=mn,exports.createUniqueBaseTableName=nt,exports.dateToExcelSerial=e.E,exports.decompressBaseRangeValuesPayload=Vr,exports.ensureBaseTableCellLayout=e.N,exports.findRecordLinkReferences=e.ct,exports.formatBaseDateValue=e.D,exports.formatBaseFieldStatValue=Pn,exports.formatBaseNumberValue=_n,exports.formatBaseProgressValue=e.p,exports.getActiveBaseHierarchyFieldIds=e.X,exports.getBaseCellFormulaValue=e.I,exports.getBaseCellValue=e.R,exports.getBaseConditionalColorOperators=e.S,exports.getBaseDashboardPermissionObjectId=se,exports.getBaseFieldPermissionObjectId=j,Object.defineProperty(exports,"getBaseFormulaTableName",{enumerable:!0,get:function(){return t.getBaseFormulaTableName}}),exports.getBaseHierarchyDeletePromotions=e.Z,exports.getBaseHierarchyFieldId=e.Q,exports.getBasePermissionValue=F,exports.getBaseProgressRange=e.m,exports.getBaseRecordPermissionObjectId=M,exports.getBaseTablePermissionObjectId=A,exports.getBaseViewPermissionObjectId=N,exports.getGanttWorkingDayVariance=e.d,exports.getRecordLinkFieldConfig=e.lt,exports.getSupportedBaseFieldStatTypes=jn,exports.getVisibleBaseHierarchyRows=e.$,exports.hasGanttPredecessorPath=e.ot,exports.inferBaseSeparatorStyle=xn,exports.isBaseConditionalColorDateField=e.C,exports.isBaseFieldStatEmptyValue=Fn,exports.isBaseFieldStatSupported=Mn,exports.isBaseFieldStatType=kn,exports.isBaseHierarchyField=e.et,exports.isCompressedBaseRangeValuesPayload=Hr,exports.isGanttPredecessorField=e.st,exports.matchesBaseCondition=e.w,exports.normalizeBaseDateFieldConfig=e.O,exports.normalizeBaseDateSerial=e.k,exports.normalizeBaseFieldStatsConfig=An,exports.normalizeBaseProgressDecimalPlaces=e.h,exports.parseRecordLinkIds=e.ut,exports.projectBaseHierarchy=e.tt,exports.resolveBaseDateFieldConfig=e.A,exports.resolveBaseHierarchyFieldId=e.nt,exports.resolveBaseRangeHierarchyPatches=zt,exports.searchBaseTable=wr,exports.serializeRecordLinkIds=e.dt,exports.setBasePermissionValue=ce,exports.traceBasePerformance=e.H,exports.uniqueFieldName=it,exports.validateBaseHierarchyMove=e.rt,exports.validateBaseHierarchyRecordCreations=e.it,exports.validateBaseHierarchyRecordPatches=e.at,exports.validateBaseTableName=q,exports.validateCanonicalRecordLinkValue=e.ft,exports.validateRecordLinkField=e.pt,exports.validateRecordLinkValue=e.mt;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./config-AfiyXtDJ.js");let t=require("@univerjs/core"),n=require("@univerjs/engine-formula"),r=require("@univerjs/protocol"),i=require("@univerjs-pro/license"),a=require("@univerjs/rpc");const o=[[`#ff6363`,`#ff7a1a`,`#f8b915`,`#84a600`,`#28b446`,`#2db6a3`,`#2aa6d9`,`#6786e8`,`#dd62ac`,`#9d6be8`,`#87909a`],[`#ffdada`,`#fee7c8`,`#fae9b9`,`#ddeb8b`,`#bdebc7`,`#b8e9e1`,`#b9e4ef`,`#b9cdf9`,`#f4cfe5`,`#dfd3f5`,`#e5e7eb`],[`#ffb8b8`,`#ffc184`,`#f9d46d`,`#bed64b`,`#7bd48b`,`#5ed8c7`,`#82cff0`,`#a8c0f3`,`#eda9cf`,`#c8b0ef`,`#d1d5db`],[`#f94144`,`#f25c05`,`#d89500`,`#718700`,`#20943d`,`#119b87`,`#1287b5`,`#3f72e8`,`#d24b99`,`#8b50e6`,`#5b6470`],[`#dc2f2f`,`#a63d00`,`#805300`,`#566600`,`#18851f`,`#0b6f63`,`#0b6388`,`#1d4ed8`,`#b02176`,`#6d28d9`,`#2f3640`]].flat();function s(e){var n;return e.type===t.BaseFieldType.SingleSelect&&((n=e.config)==null||(n=n.optionSource)==null?void 0:n.type)!==`field`}function c(e){return o[e%o.length]}function l(e,n){return{id:`opt-${(0,t.generateRandomId)(8)}`,name:e,color:c(n)}}var u=class{constructor(t){e.b(this,`ids`,/* @__PURE__ */ new Set),e.b(this,`byName`,/* @__PURE__ */ new Map),e.b(this,`added`,[]),e.b(this,`_size`,void 0);let n=Array.isArray(t)?t:[];this._size=n.length;for(let e of n){let t=typeof e==`string`?e:(e==null?void 0:e.name)??(e==null?void 0:e.label);if(typeof t==`string`){let n=String((e==null?void 0:e.id)??(e==null?void 0:e.value)??t);this.ids.add(n),this.byName.has(t)||this.byName.set(t,n)}}}resolveName(e){let t=this.byName.get(e);if(t!==void 0)return t;let n=l(e,this._size+this.added.length);return this.added.push(n),this.ids.add(n.id),this.byName.set(e,n.id),n.id}};function d(t,n,r){let i=e.R(t,n,r);return i==null||i===``?null:String(i).trim()}function f(e,t){let n=new u([]);for(let r of e.recordOrder??Object.keys(e.records)){let i=d(e,r,t);i&&n.resolveName(i)}return n.added}const p={table:e=>[`tables`,e],field:(e,t)=>[`tables`,e,`fields`,t],fieldOrder:(e,t)=>[`tables`,e,`fieldOrder`,t],record:(e,t)=>[`tables`,e,`records`,t],cell:(e,t,n)=>[`tables`,e,`records`,t,`values`,n],cellData:(e,t,n)=>[`tables`,e,`cellData`,String(t),String(n)],attachmentSet:(e,t)=>[`tables`,e,`resources`,`attachmentSets`,t],attachment:(e,t)=>[`tables`,e,`resources`,`attachments`,t],view:(e,t)=>[`tables`,e,`views`,t],viewFieldHidden:(e,t,n)=>[`tables`,e,`views`,t,`fieldSettings`,n,`hidden`]};var m=class{setBaseName(t,n){let r=this.renameFormulaUnitReferences(t,t.name,n);return e.M([this._replaceOptional([`name`],t.name,n),...r?[r]:[]])}renameFormulaUnitReferences(r,i,a){let o=Object.values(r.tables).flatMap(e=>Object.values(e.fields).flatMap(r=>{var o,s;if(r.type!==t.BaseFieldType.Formula)return[];let c=String(((o=r.config)==null?void 0:o.formula)??``),l=(0,n.refactorFormulaUnitQualifier)(c,i,a);return l===c?[]:[this._replaceOptional([...p.field(e.id,r.id),`config`,`formula`],(s=r.config)==null?void 0:s.formula,l)]}));return o.length>0?e.M(o):void 0}createTable(n,r,i=n.tableOrder.length){let a=(0,t.allocateBaseFormulaTableName)(r.name,(0,t.createBaseFormulaTableNameMap)(n).values(),r.formulaName),o=r.formulaName===a?r:{...r,formulaName:a};return e.M([...this._materializeFormulaTableNames(n),t.JSON1.insertOp(p.table(r.id),o),t.JSON1.insertOp([`tableOrder`,i],r.id)])}renameTable(n,r,i){let a=n.tables[r];return e.M([...this._materializeFormulaTableNames(n),t.JSON1.replaceOp([...p.table(r),`name`],a.name,i)])}deleteTable(n,r){let i=n.tables[r],a=n.tableOrder.indexOf(r);return e.M([...this._materializeFormulaTableNames(n,/* @__PURE__ */ new Set([r])),t.JSON1.removeOp(p.table(r),i),t.JSON1.removeOp([`tableOrder`,a],r)])}createRecord(e,t,n){return this.createRecords(e,t,[n])}createRecords(n,r,i){let a=n.tables[r],o=i.filter(e=>e&&!a.records[e.id]).map(e=>({...e,values:{...e.values,[t.BASE_RECORD_ID_FIELD_ID]:e.id}}));if(!o.length)return t.JSON1.replaceOp([...p.table(r),`records`],a.records,a.records);let s=new t.JSON1.WriteCursor,c=[...o].sort((e,t)=>e.id<t.id?-1:+(e.id>t.id)),l=[...p.table(r),`records`];s.descendPath(l);for(let e of c)s.descend(e.id),s.write(`i`,e),s.ascend();for(let e=0;e<l.length;e+=1)s.ascend();return e.M([s.get(),this._createRecordOrderOp(n,r,o)])}deleteRecord(e,t,n){return this.deleteRecords(e,t,[n])}deleteRecords(n,r,i){let a=n.tables[r],o=Array.from(new Set(i)).filter(e=>a.records[e]);if(!o.length)return t.JSON1.replaceOp([...p.table(r),`records`],a.records,a.records);let s=new Set(o),c=e.Z(a,o).map(e=>this.updateCell(n,r,e.recordId,e.fieldId,``));return e.M([this._deleteRecordsBaseOp(n,r,o,s),...c])}createDeleteRecordsUndoOp(t,n,r,i){let a=t.tables[r],o=Array.from(new Set(i)).filter(e=>a.records[e]),s=new Set(o),c=new e.j().invertOp(t,this._deleteRecordsBaseOp(t,r,o,s)),l=e.Z(a,o).map(e=>this.updateCell(n,r,e.recordId,e.fieldId,e.oldParentRecordId??``));return e.M([c,...l])}_deleteRecordsBaseOp(n,r,i,a){let o=n.tables[r],s=i.map(e=>{var t;return{recordId:e,index:((t=o.recordOrder)==null?void 0:t.indexOf(e))??-1}}).filter(e=>e.index>=0).sort((e,t)=>t.index-e.index);return e.M([...i.map(e=>t.JSON1.removeOp(p.record(r,e),o.records[e])),...s.map(({recordId:e,index:n})=>t.JSON1.removeOp([`tables`,r,`recordOrder`,n],e)),...this._deleteAttachmentResources(o,r,e=>{let t=e.slice(e.lastIndexOf(``)+1);return a.has(t)})])}duplicateRecord(e,n,r,i){return this.createRecord(e,n,{...i,values:{...e.tables[n].records[r].values,...i.values,[t.BASE_RECORD_ID_FIELD_ID]:i.id}})}updateRecordOrder(t,n,r,i){let a=t.tables[n],o=[...p.record(n,r),`orderKey`],s=Object.values(a.records).map(e=>e.id===r?{...e,orderKey:i}:e).sort((e,t)=>String(e.orderKey??e.id).localeCompare(String(t.orderKey??t.id))).map(e=>e.id),c=[...p.table(n),`recordOrder`],l=a.recordOrder,u=s.filter(e=>e!==r),d=l==null?void 0:l.filter(e=>e!==r),f=l!=null&&l.includes(r)&&(d==null?void 0:d.length)===u.length&&d.every((e,t)=>e===u[t])?h(c,l,s,r):this._replaceOptional(c,l,s);return e.M([this._replaceOptional(o,a.records[r].orderKey,i),f])}updateCell(t,n,r,i,a){var o,s;let c=t.tables[n],l=S(c,r,i)?c:e.N(c),u=(o=l.rowIndex)==null?void 0:o[r],d=(s=l.colIndex)==null?void 0:s[i];if(u==null||d==null){var f;return this._replaceOptional(p.cell(n,r,i),(f=t.tables[n])==null||(f=f.records[r])==null?void 0:f.values[i],a)}return this.setRangeValues(t,n,[{row:u,col:d,value:a}])}setRecordValues(t,n,r){let i=t.tables[n],a=r.every(e=>Object.keys(e.values).every(t=>S(i,e.recordId,t)))?i:e.N(i),o=r.flatMap(e=>Object.entries(e.values).flatMap(([t,n])=>{var r,i;let o=(r=a.rowIndex)==null?void 0:r[e.recordId],s=(i=a.colIndex)==null?void 0:i[t];return o==null||s==null?[]:[{row:o,col:s,value:n}]})),s=r.flatMap(e=>Object.entries(e.recordPatch??{}).map(([r,i])=>{var a;let o=[...p.record(n,e.recordId),r],s=(a=t.tables[n])==null||(a=a.records[e.recordId])==null?void 0:a[r];return this._replaceOptional(o,s,i)}));return e.M([this.setRangeValues(t,n,o),...s])}setRangeValues(n,r,i){let a=n.tables[r],o=i.every(e=>C(a,e.row,e.col))?a:e.N(a),s=/* @__PURE__ */ new Map,c=i.flatMap(n=>{var i,a,c,l;let u=(i=o.colId)==null?void 0:i[n.col],d=(a=o.rowId)==null?void 0:a[n.row],f=u?o.fields[u]:void 0;if(u===t.BASE_RECORD_ID_FIELD_ID||(f==null?void 0:f.type)===t.BaseFieldType.RecordId)throw Error(`[BaseJson1OpFactory]: cannot write record-id.`);let m=e.B(n.value,f),h=(c=o.cellData)==null||(c=c[n.row])==null?void 0:c[n.col],g=this._replaceOptional(p.cellData(r,n.row,n.col),h,m);if(!u||!d)return[g];let _=(l=o.records[d])==null?void 0:l.values[u],v=(f==null?void 0:f.type)===t.BaseFieldType.Attachment?e.z(n.value):e.V(n.value,m,f,o,d),y=[g,this._replaceOptional(p.cell(r,d,u),_,v)];return(f==null?void 0:f.type)===t.BaseFieldType.Attachment&&s.set(e.P(u,d),{recordId:d,fieldId:u,attachments:v}),y});return c.length?e.M([...c,...this._setAttachmentResources(o,r,Array.from(s.values()))]):t.JSON1.replaceOp([`tables`,r,`cellData`],o.cellData,o.cellData)}createField(n,r,i){let a=n.tables[r];if(a.fields[i.field.id]||a.fieldOrder.includes(i.field.id))return t.JSON1.replaceOp([`tables`,r,`fieldOrder`],a.fieldOrder,a.fieldOrder);let o=Math.max(1,i.index??a.fieldOrder.length),s=Object.values(a.views??{}).flatMap(e=>{var n;if(!e.fieldOrder||e.fieldOrder.includes(i.field.id))return[];let a=D(((n=i.viewIndexes)==null?void 0:n[e.id])??o,e.fieldOrder.length);return[t.JSON1.insertOp([...p.view(r,e.id),`fieldOrder`,a],i.field.id)]});return e.M([...i.field.type===t.BaseFieldType.Formula?this._materializeFormulaTableNames(n):[],t.JSON1.insertOp(p.field(r,i.field.id),i.field),t.JSON1.insertOp(p.fieldOrder(r,o),i.field.id),...s])}duplicateField(n,r,i,a){let o=n.tables[r];if(!o.fields[i]||o.fields[a.field.id]||o.fieldOrder.includes(a.field.id))return t.JSON1.replaceOp([`tables`,r,`fieldOrder`],o.fieldOrder,o.fieldOrder);let s=a.index??o.fieldOrder.indexOf(i)+1,c=o.fieldOrder.filter(e=>e!==a.field.id),l=T(c,a.field.id,s),u=Object.values(o.views??{}).flatMap(e=>{var t,n,o,l;let u=(t=e.fieldOrder)!=null&&t.length?e.fieldOrder:c;if(u.includes(a.field.id))return[];let d=T(u,a.field.id,((n=a.viewIndexes)==null?void 0:n[e.id])??s),f=(o=e.fieldSettings)==null?void 0:o[i];return[this._replaceOptional([...p.view(r,e.id),`fieldOrder`],e.fieldOrder,d),...f?[this._replaceOptional([...p.view(r,e.id),`fieldSettings`,a.field.id],(l=e.fieldSettings)==null?void 0:l[a.field.id],f)]:[]]}),d=Object.values(o.records).filter(e=>Object.prototype.hasOwnProperty.call(e.values,i)).map(e=>this._replaceOptional(p.cell(r,e.id,a.field.id),e.values[a.field.id],e.values[i]));return e.M([...a.field.type===t.BaseFieldType.Formula?this._materializeFormulaTableNames(n):[],t.JSON1.insertOp(p.field(r,a.field.id),a.field),t.JSON1.replaceOp([`tables`,r,`fieldOrder`],o.fieldOrder,l),...u,...d])}updateField(n,r,i,a,o){let s=n.tables[r].fields[i],c={...s,...a};Object.keys(a).forEach(e=>{a[e]===void 0&&delete c[e]});let l=n.tables[r];if(s.type===t.BaseFieldType.Text&&!v(c.config.optionSource)&&(c.type===t.BaseFieldType.SingleSelect||c.type===t.BaseFieldType.MultiSelect))return g(l,c,o);let u=_(l,i,s,c);c=u.field;let d=p.field(r,i),f=s.type===c.type?this._patchProperties(d,s,{...a,...c.config===s.config?{}:{config:c.config},...c.defaultValue===s.defaultValue?{}:{defaultValue:c.defaultValue}}):t.JSON1.replaceOp(d,s,c);return c.type===t.BaseFieldType.Formula?e.M([...this._materializeFormulaTableNames(n),f,...this._setFormulaFieldCells(n,r,i,c)]):e.M([f,...u.patches.length?[this.setRangeValues(n,r,u.patches)]:[]])}changeFieldType(e,t,n,r){return this.updateField(e,t,n,r)}deleteField(n,r,i){let a=n.tables[r];if(!(a!=null&&a.fields[i])||a.primaryFieldId===i||i===t.BASE_RECORD_ID_FIELD_ID)return t.JSON1.replaceOp([`tables`,r,`fieldOrder`],a==null?void 0:a.fieldOrder,a==null?void 0:a.fieldOrder);let o=a.fieldOrder.indexOf(i),s=Object.values(a.views).flatMap(e=>{var n,a,o,s,c,l,u;let d=[],f=((n=e.fieldOrder)==null?void 0:n.indexOf(i))??-1;f>=0&&d.push(t.JSON1.removeOp([...p.view(r,e.id),`fieldOrder`,f],i));let m=(a=e.fieldSettings)==null?void 0:a[i];m!==void 0&&d.push(t.JSON1.removeOp([...p.view(r,e.id),`fieldSettings`,i],m));let h=e.filter?{...e.filter,conditions:e.filter.conditions.filter(e=>e.fieldId!==i)}:e.filter;h&&h.conditions.length!==((o=e.filter)==null?void 0:o.conditions.length)&&d.push(this._replaceOptional([...p.view(r,e.id),`filter`],e.filter,h));let g=(s=e.sort)==null?void 0:s.filter(e=>e.fieldId!==i);g&&g.length!==((c=e.sort)==null?void 0:c.length)&&d.push(this._replaceOptional([...p.view(r,e.id),`sort`],e.sort,g));let _=(l=e.group)==null?void 0:l.filter(e=>e.fieldId!==i);_&&_.length!==((u=e.group)==null?void 0:u.length)&&d.push(this._replaceOptional([...p.view(r,e.id),`group`],e.group,_));let v=E(e.config,i);return JSON.stringify(v)!==JSON.stringify(e.config)&&d.push(t.JSON1.replaceOp([...p.view(r,e.id),`config`],e.config,v)),d}),c=Object.values(a.records).flatMap(e=>Object.prototype.hasOwnProperty.call(e.values,i)?[t.JSON1.removeOp(p.cell(r,e.id,i),e.values[i])]:[]);return e.M([t.JSON1.removeOp(p.field(r,i),a.fields[i]),t.JSON1.removeOp(p.fieldOrder(r,o),i),...s,...c,...this._deleteAttachmentResources(a,r,e=>e.startsWith(`${i}`))])}moveField(e,n,r,i){let a=e.tables[n].fieldOrder;if(r===t.BASE_RECORD_ID_FIELD_ID||i.beforeFieldId===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseJson1OpFactory]: cannot move a field before record-id.`);let o=w(a,r,i);return h([`tables`,n,`fieldOrder`],a,o,r)}createView(n,r,i,a=n.tables[r].viewOrder.length){return e.M([t.JSON1.insertOp(p.view(r,i.id),i),t.JSON1.insertOp([`tables`,r,`viewOrder`,a],i.id)])}renameView(e,n,r,i){return t.JSON1.replaceOp([...p.view(n,r),`name`],e.tables[n].views[r].name,i)}deleteView(n,r,i){let a=n.tables[r],o=a.views[i],s=a.viewOrder.indexOf(i);return e.M([t.JSON1.removeOp(p.view(r,i),o),t.JSON1.removeOp([`tables`,r,`viewOrder`,s],i)])}moveView(e,t,n,r){let i=e.tables[t].viewOrder,a=w(i,n,{beforeFieldId:r.beforeViewId,afterFieldId:r.afterViewId});return h([`tables`,t,`viewOrder`],i,a,n)}updateViewConfig(e,t,n,r){let i=e.tables[t].views[n].config;return this._patchProperties([...p.view(t,n),`config`],i,r)}setViewFilter(e,t,n,r){return this._replaceOptional([...p.view(t,n),`filter`],e.tables[t].views[n].filter,r)}setViewSort(e,t,n,r){return this._replaceOptional([...p.view(t,n),`sort`],e.tables[t].views[n].sort,r)}setViewGroup(e,t,n,r){return this._replaceOptional([...p.view(t,n),`group`],e.tables[t].views[n].group,r)}setViewFieldVisible(e,t,n,r,i){return this._setViewFieldSetting(e,t,n,r,{hidden:!i})}setViewFieldWidth(e,t,n,r,i){return this._setViewFieldSetting(e,t,n,r,{width:i})}getViewFieldSettingHistory(e,n,r,i,a){var o;let s=(o=e.tables[n].views[r].fieldSettings)==null?void 0:o[i],c=[...p.view(n,r),`fieldSettings`,i],l=this._patchProperties(c,s??{},{...a});return{redo:l,undo:t.JSON1.type.invert(l)}}setViewFieldOrder(e,n,r,i,a){let o=e.tables[n].views[r],s=o.fieldOrder??e.tables[n].fieldOrder,c=w(s,i,a),l=[...p.view(n,r),`fieldOrder`];return o.fieldOrder?h(l,s,c,i):t.JSON1.insertOp(l,c)}_setViewFieldSetting(t,n,r,i,a){let o=t.tables[n].views[r].fieldSettings,s=[...p.view(n,r),`fieldSettings`];if(!o)return this._replaceOptional(s,o,{[i]:a});let c=o[i];return c?e.M(Object.entries(a).map(([e,t])=>this._replaceOptional([...s,i,e],c[e],t))):this._replaceOptional([...s,i],c,a)}_createRecordOrderOp(e,n,r){let i=e.tables[n],a=new Set(r.map(e=>e.id)),o=[...Object.values(i.records).filter(e=>!a.has(e.id)),...r].sort((e,t)=>String(e.orderKey??e.id).localeCompare(String(t.orderKey??t.id))).map(e=>e.id),s=[...p.table(n),`recordOrder`],c=o.filter(e=>!a.has(e));if(!i.recordOrder||i.recordOrder.length!==c.length||c.some((e,t)=>e!==i.recordOrder[t]))return this._replaceOptional(s,i.recordOrder,o);let l=new t.JSON1.WriteCursor;return l.descendPath(s),o.forEach((e,t)=>{a.has(e)&&(l.descend(t),l.write(`i`,e),l.ascend())}),l.get()}_materializeFormulaTableNames(e,n=/* @__PURE__ */ new Set){let r=(0,t.createBaseFormulaTableNameMap)(e);return Object.values(e.tables).filter(e=>!n.has(e.id)).sort((e,t)=>e.id.localeCompare(t.id)).flatMap(e=>{let t=r.get(e.id);return!t||e.formulaName===t?[]:[this._replaceOptional([...p.table(e.id),`formulaName`],e.formulaName,t)]})}_setFormulaFieldCells(t,n,r,i){var a,o;let s=e.N(t.tables[n]),c=String(((a=i.config)==null?void 0:a.formula)??``).trim(),l=(o=s.colIndex)==null?void 0:o[r];if(l==null)return[];let u=s.recordOrder??Object.keys(s.records),d=u.map(e=>{var t;return(t=s.rowIndex)==null?void 0:t[e]}).find(e=>e!=null);return u.flatMap(e=>{var t,i;let a=(t=s.rowIndex)==null?void 0:t[e];if(a==null)return[];let o=(i=s.cellData)==null||(i=i[a])==null?void 0:i[l],u=c?a===d?{f:c,si:r}:{si:r}:{v:null,t:null};return[this._replaceOptional(p.cellData(n,a,l),o,u)]})}_setAttachmentResources(n,r,i){var a;let o=new Map(Object.entries(((a=n.resources)==null?void 0:a.attachmentSets)??{})),s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,l=i.map(({recordId:t,fieldId:i,attachments:a})=>{var l;let u=e.P(i,t),d=a.map((e,t)=>String(e.id??`${u}\u001F${t}`));return c.add(u),o.set(u,d),a.forEach((e,t)=>{let n=d[t];s.set(n,{...e,id:n})}),this._replaceOptional(p.attachmentSet(r,u),(l=n.resources)==null||(l=l.attachmentSets)==null?void 0:l[u],d)}),u=Array.from(s).map(([e,t])=>{var i;return this._replaceOptional(p.attachment(r,e),(i=n.resources)==null||(i=i.attachments)==null?void 0:i[e],t)}),d=new Set(Array.from(o.values()).flat()),f=new Set(Array.from(c).flatMap(e=>{var t;return((t=n.resources)==null||(t=t.attachmentSets)==null?void 0:t[e])??[]})),m=Array.from(f).flatMap(e=>{var i;let a=(i=n.resources)==null||(i=i.attachments)==null?void 0:i[e];return a!==void 0&&!d.has(e)?[t.JSON1.removeOp(p.attachment(r,e),a)]:[]});return[...l,...u,...m]}_deleteAttachmentResources(e,n,r){var i;let a=((i=e.resources)==null?void 0:i.attachmentSets)??{},o=Object.entries(a).filter(([e])=>r(e));if(!o.length)return[];let s=new Set(Object.entries(a).filter(([e])=>!r(e)).flatMap(([,e])=>e)),c=new Set(o.flatMap(([,e])=>e));return[...o.map(([e,r])=>t.JSON1.removeOp(p.attachmentSet(n,e),r)),...Array.from(c).flatMap(r=>{var i;let a=(i=e.resources)==null||(i=i.attachments)==null?void 0:i[r];return a!==void 0&&!s.has(r)?[t.JSON1.removeOp(p.attachment(n,r),a)]:[]})]}_replaceOptional(e,n,r){return n===void 0?t.JSON1.insertOp(e,r):t.JSON1.replaceOp(e,n,r)}_patchProperties(n,r,i){let a=Object.entries(i);return r?e.M(a.map(([e,i])=>{let a=r[e];return i===a?null:i===void 0?t.JSON1.removeOp([...n,e],a):this._replaceOptional([...n,e],a,i)})):t.JSON1.insertOp(n,Object.fromEntries(a.filter(([,e])=>e!==void 0)))}};function h(e,n,r,i){let a=n.indexOf(i),o=r.indexOf(i);return a===o?null:t.JSON1.moveOp([...e,a],[...e,o])}function g(n,r,i){var a;let o=Array.isArray(r.config.options)?r.config.options:[],s=new u(o),c=new Map(i),l=((a=n.colIndex)==null?void 0:a[r.id])!=null&&n.rowIndex?n:e.N(n),f=l.colIndex[r.id],m=/* @__PURE__ */ new Map;for(let e of l.recordOrder??[]){let n=d(l,e,r.id);if(n===null)continue;let i=c.get(n),a=i===void 0&&n?s.resolveName(n):i,o=a&&s.ids.has(a)?a:null;r.type===t.BaseFieldType.MultiSelect&&(o=o?[o]:[]),m.set(e,o)}let h=new t.JSON1.WriteCursor;h.descendPath(p.table(n.id));let g=Array.from(m.keys(),e=>String(l.rowIndex[e])).sort();h.at([`cellData`],t=>{for(let i of g){var n;let a=m.get(l.rowId[Number(i)]),o=(n=l.cellData)==null||(n=n[Number(i)])==null?void 0:n[f];t.at([i,String(f)],t=>{o!==void 0&&t.write(`r`,!0),t.write(`i`,e.B(a,r))})}});let _={...r,config:{...r.config,options:[...o,...s.added]}};return h.at([`fields`,r.id],e=>{e.write(`r`,!0),e.write(`i`,_)}),h.at([`records`],e=>{for(let t of Array.from(m.keys()).sort())e.at([t,`values`,r.id],e=>{l.records[t].values[r.id]!==void 0&&e.write(`r`,!0),e.write(`i`,m.get(t))})}),h.get()}function _(n,r,i,a){var o;let s=a.type;if(i.type!==s||s!==t.BaseFieldType.SingleSelect&&s!==t.BaseFieldType.MultiSelect||v(a.config.optionSource))return{field:a,patches:[]};let c=y(i),l=y(a);if(![...c].some(e=>!l.has(e)))return{field:a,patches:[]};let u=b(a.defaultValue,l,s),d=x(u,a.defaultValue)?a:{...a,defaultValue:u},f=e.N(n),p=(o=f.colIndex)==null?void 0:o[r];return p==null?{field:d,patches:[]}:{field:d,patches:(f.recordOrder??[]).flatMap(e=>{var t,n;let i=(t=f.rowIndex)==null?void 0:t[e],a=(n=f.records[e])==null?void 0:n.values[r],o=b(a,l,s);return i==null||x(o,a)?[]:[{row:i,col:p,value:o??null}]})}}function v(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`field`}function y(e){var t;let n=Array.isArray((t=e.config)==null?void 0:t.options)?e.config.options:[];return new Set(n.flatMap(e=>{if(!e||typeof e!=`object`||!(`id`in e))return[];let t=String(e.id);return t?[t]:[]}))}function b(e,n,r){if(e==null||e===``)return e;if(r===t.BaseFieldType.SingleSelect)return n.has(String(e))?e:null;let i=Array.isArray(e)?e.map(String):String(e).split(`,`).map(e=>e.trim()).filter(Boolean),a=i.filter(e=>n.has(e));return a.length===i.length?e:Array.isArray(e)?a:String(e).includes(`,`)?a.join(`,`):a[0]??[]}function x(e,t){return JSON.stringify(e)===JSON.stringify(t)}function S(e,t,n){var r,i,a,o;let s=(r=e.rowIndex)==null?void 0:r[t],c=(i=e.colIndex)==null?void 0:i[n];return s!=null&&c!=null&&((a=e.rowId)==null?void 0:a[s])===t&&((o=e.colId)==null?void 0:o[c])===n&&e.cellData!=null}function C(e,t,n){var r,i;return((r=e.rowId)==null?void 0:r[t])!=null&&((i=e.colId)==null?void 0:i[n])!=null&&e.cellData!=null}function w(e,t,n){let r=e.filter(e=>e!==t),i=n.beforeFieldId?r.indexOf(n.beforeFieldId):n.afterFieldId?r.indexOf(n.afterFieldId)+1:r.length;return r.splice(i<0?r.length:i,0,t),r}function T(e,t,n){let r=e.filter(e=>e!==t);return r.splice(D(n,r.length),0,t),r}function E(e,t,n){if(Array.isArray(e))return n===`fieldIds`?e.filter(e=>e!==t):e.flatMap(e=>{if(e&&typeof e==`object`&&!Array.isArray(e)&&e.fieldId===t)return[];let n=E(e,t);return n===void 0?[]:[n]});if(!e||typeof e!=`object`)return n!=null&&n.endsWith(`FieldId`)&&e===t?void 0:e;let r=e;if(r.fieldId!==t)return Object.fromEntries(Object.entries(r).flatMap(([e,r])=>{if(e===t&&n===`fieldSettings`)return[];let i=E(r,t,e);return i===void 0?[]:[[e,i]]}))}function D(e,t){return Math.max(0,Math.min(e,t))}var ee=class{constructor(n){this.unitId=n,e.b(this,`type`,r.UnitObject.Base),e.b(this,`subType`,r.UnitAction.Comment),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}`}},te=class{constructor(n){this.unitId=n,e.b(this,`type`,r.UnitObject.Base),e.b(this,`subType`,r.UnitAction.Copy),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}`}},ne=class{constructor(n){this.unitId=n,e.b(this,`type`,r.UnitObject.Base),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}`}},re=class{constructor(n){this.unitId=n,e.b(this,`type`,r.UnitObject.Base),e.b(this,`subType`,r.UnitAction.Export),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}`}},O=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseDashboard),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}},ie=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseField),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}},ae=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseRecord),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}},oe=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseTable),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}},se=class{constructor(n,i){this.unitId=n,this.objectId=i,e.b(this,`type`,r.UnitObject.BaseView),e.b(this,`subType`,r.UnitAction.Edit),e.b(this,`status`,t.PermissionStatus.INIT),e.b(this,`id`,void 0),e.b(this,`value`,!0),this.id=`${this.type}.${this.subType}_${n}_${i}`}};const k=[r.UnitAction.Edit,r.UnitAction.Copy,r.UnitAction.Export,r.UnitAction.Comment],ce=/* @__PURE__ */ new Set([r.UnitObject.Base,r.UnitObject.BaseTable,r.UnitObject.BaseField,r.UnitObject.BaseRecord,r.UnitObject.BaseView,r.UnitObject.BaseDashboard]),le=`table/`,ue=`field/`,de=`record/`,fe=`view/`,pe=`dashboard/`;function A(e){return`${le}${encodeURIComponent(e)}`}function j(e,t){return`${ue}${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function M(e,t){return`${de}${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function N(e,t){return`${fe}${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function me(e){return`${pe}${encodeURIComponent(e)}`}function P(e,t,n){if(t===e)switch(n){case r.UnitAction.Edit:return new ne(e);case r.UnitAction.Copy:return new te(e);case r.UnitAction.Export:return new re(e);case r.UnitAction.Comment:return new ee(e);default:throw Error(`Unsupported Base permission action: ${n}`)}if(n!==r.UnitAction.Edit)throw Error(`Base object permissions only support Edit: ${t}`);if(t.startsWith(le))return new oe(e,t);if(t.startsWith(ue))return new ie(e,t);if(t.startsWith(de))return new ae(e,t);if(t.startsWith(fe))return new se(e,t);if(t.startsWith(pe))return new O(e,t);throw Error(`Unsupported Base permission object: ${t}`)}function F(e,t,n,r){var i;return((i=e.getPermissionPoint(P(t,n,r).id))==null?void 0:i.value)??!0}function he(e,t,n,r,i){let a=P(t,n,r);e.getPermissionPoint(a.id)||e.addPermissionPoint(a),e.updatePermissionPoint(a.id,i)}function ge(e,t,n,r){e.deletePermissionPoint(P(t,n,r).id)}function _e(e,t){e.getAllPermissionPoint().forEach((n,r)=>{n.subscribe(n=>{ce.has(n.type)&&`unitId`in n&&n.unitId===t&&e.deletePermissionPoint(r)}).unsubscribe()})}function ve(e,t,n){return F(e,t,t,r.UnitAction.Edit)&&Array.from(n).every(n=>F(e,t,n,r.UnitAction.Edit))}const ye=(0,t.createIdentifier)(`base.permission.service`);let be=class extends t.Disposable{constructor(n,r){super(),this._permissionService=n,this._instanceService=r,e.b(this,`_basePermissions`,/* @__PURE__ */ new Map),e.b(this,`_tablePermissions`,/* @__PURE__ */ new Map),e.b(this,`_fieldPermissions`,/* @__PURE__ */ new Map),e.b(this,`_recordPermissions`,/* @__PURE__ */ new Map),e.b(this,`_viewPermissions`,/* @__PURE__ */ new Map),e.b(this,`_tableBaseIds`,/* @__PURE__ */ new Map),this.disposeWithMe(this._instanceService.getTypeOfUnitDisposed$(t.UniverInstanceType.UNIVER_BASE).subscribe(e=>this._clearUnit(e.getUnitId())))}canCreateTable(e){var t;return this._canEdit(e,[])&&(((t=this._basePermissions.get(e))==null?void 0:t.createTable)??!0)}canEditTable(e){return this._canEditTable(e)}canDeleteTable(e){var t;return this._canEditTable(e)&&(((t=this._tablePermissions.get(e))==null?void 0:t.delete)??!0)}canCreateField(e){var t;return this._canEditTable(e)&&(((t=this._tablePermissions.get(e))==null?void 0:t.createField)??!0)}canEditField(e,t){var n;return this._canEditTable(e)&&this._canEdit(e,[j(e,t)])&&(((n=this._fieldPermissions.get(I(e,t)))==null?void 0:n.edit)??!0)}canDeleteField(e,t){var n;return this.canEditField(e,t)&&(((n=this._fieldPermissions.get(I(e,t)))==null?void 0:n.delete)??!0)}canCreateRecord(e){var t;return this._canEditTable(e)&&(((t=this._tablePermissions.get(e))==null?void 0:t.createRecord)??!0)}canEditRecord(e,t){var n;let r=this._recordPermissions.get(L(e,t));return this._canEdit(e,[A(e),M(e,t)])&&(((n=this._tablePermissions.get(e))==null?void 0:n.edit)??!0)&&((r==null?void 0:r.edit)??!0)&&((r==null?void 0:r.editCell)??!0)}canDeleteRecord(e,t){var n,r,i;return this._canEdit(e,[A(e),M(e,t)])&&(((n=this._tablePermissions.get(e))==null?void 0:n.edit)??!0)&&(((r=this._recordPermissions.get(L(e,t)))==null?void 0:r.edit)??!0)&&(((i=this._recordPermissions.get(L(e,t)))==null?void 0:i.delete)??!0)}canEditCell(e,t,n){var r,i,a;let o=this._fieldPermissions.get(I(e,n));return this._canEdit(e,[A(e),j(e,n),M(e,t)])&&(((r=this._tablePermissions.get(e))==null?void 0:r.edit)??!0)&&(((i=this._recordPermissions.get(L(e,t)))==null?void 0:i.edit)??!0)&&(((a=this._recordPermissions.get(L(e,t)))==null?void 0:a.editCell)??!0)&&((o==null?void 0:o.edit)??!0)&&((o==null?void 0:o.editCell)??!0)}canManageView(e,t){var n,r,i;return this._canEdit(e,[A(e),N(e,t)])&&(((n=this._tablePermissions.get(e))==null?void 0:n.edit)??!0)&&(((r=this._viewPermissions.get(Se(e,t)))==null?void 0:r.edit)??!0)&&(((i=this._tablePermissions.get(e))==null?void 0:i.manageView)??!0)}setBasePermission(e,t){this._basePermissions.set(e,{...this._basePermissions.get(e),...t}),t.edit!==void 0&&he(this._permissionService,e,e,r.UnitAction.Edit,t.edit)}setTablePermission(e,t){this._rememberTable(e),this._tablePermissions.set(e,{...this._tablePermissions.get(e),...t}),this._setObjectEdit(e,A(e),t.edit)}setFieldPermission(e,t,n){this._rememberTable(e);let r=I(e,t);this._fieldPermissions.set(r,{...this._fieldPermissions.get(r),...n}),this._setObjectEdit(e,j(e,t),n.edit)}setRecordPermission(e,t,n){this._rememberTable(e);let r=L(e,t);this._recordPermissions.set(r,{...this._recordPermissions.get(r),...n}),this._setObjectEdit(e,M(e,t),n.edit)}setViewPermission(e,t,n){this._rememberTable(e);let r=Se(e,t);this._viewPermissions.set(r,{...this._viewPermissions.get(r),...n}),this._setObjectEdit(e,N(e,t),n.edit)}clearBasePermission(e){this._basePermissions.delete(e),ge(this._permissionService,e,e,r.UnitAction.Edit)}clearTablePermission(e){this._tablePermissions.delete(e),this._clearObjectEdit(e,A(e))}clearFieldPermission(e,t){this._fieldPermissions.delete(I(e,t)),this._clearObjectEdit(e,j(e,t))}clearRecordPermission(e,t){this._recordPermissions.delete(L(e,t)),this._clearObjectEdit(e,M(e,t))}clearViewPermission(e,t){this._viewPermissions.delete(Se(e,t)),this._clearObjectEdit(e,N(e,t))}getSnapshot(){return{bases:Object.fromEntries(this._basePermissions),tables:Object.fromEntries(this._tablePermissions),fields:Object.fromEntries(this._fieldPermissions),records:Object.fromEntries(this._recordPermissions),views:Object.fromEntries(this._viewPermissions)}}_canEditTable(e){var t;return this._canEdit(e,[A(e)])&&(((t=this._tablePermissions.get(e))==null?void 0:t.edit)??!0)}_canEdit(e,t){var n;let r=this._resolveBaseId(e);return!r||ve(this._permissionService,r,t)&&(((n=this._basePermissions.get(r))==null?void 0:n.edit)??!0)}_setObjectEdit(e,t,n){if(n===void 0)return;let i=this._resolveBaseId(e);i&&he(this._permissionService,i,t,r.UnitAction.Edit,n)}_clearObjectEdit(e,t){let n=this._resolveBaseId(e);n&&ge(this._permissionService,n,t,r.UnitAction.Edit)}_resolveBaseId(e){var n;let r=this._instanceService.getUnit(e,t.UniverInstanceType.UNIVER_BASE);return r?r.getUnitId():(n=this._instanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).find(t=>!!t.getSnapshot().tables[e]))==null?void 0:n.getUnitId()}_rememberTable(e){let t=this._resolveBaseId(e);t&&this._tableBaseIds.set(e,t)}_clearUnit(e){this._basePermissions.delete(e),this._tableBaseIds.forEach((t,n)=>{t===e&&(this._tablePermissions.delete(n),xe(this._fieldPermissions,`${n}\u001F`),xe(this._recordPermissions,`${n}\u001F`),xe(this._viewPermissions,`${n}\u001F`),this._tableBaseIds.delete(n))})}};be=e.g([e._(0,t.IPermissionService),e._(1,t.IUniverInstanceService)],be);function xe(e,t){e.forEach((n,r)=>{r.startsWith(t)&&e.delete(r)})}function I(e,t){return`${e}\u001F${t}`}function L(e,t){return`${e}\u001F${t}`}function Se(e,t){return`${e}\u001F${t}`}const R=(0,t.createIdentifier)(`base.command.service`);let z=class{constructor(t,n=Ce(),r={}){this._permissionService=t,this._fieldRegistry=n,this._runtimeContext=r,e.b(this,`_factory`,new m),e.b(this,`_applier`,new e.j)}createTable(e,n,r){if(!this._permissionService.canCreateTable(e.getUnitId()))throw Error(`[BaseCommandService]: cannot create table.`);(0,t.assertBaseTableRecordIdentity)(n),this._apply(e,this._factory.createTable(e.getSnapshot(),n,r))}renameTable(e,t,n){if(!this._permissionService.canEditTable(t))throw Error(`[BaseCommandService]: cannot edit table.`);this._apply(e,this._factory.renameTable(e.getSnapshot(),t,n))}deleteTable(t,n){if(!this._permissionService.canDeleteTable(n))throw Error(`[BaseCommandService]: cannot delete table.`);let r=e.ct(t.getSnapshot(),n);if(r.length>0)throw Error(`[BaseCommandService]: cannot delete a RecordLink target table (${r.map(e=>`${e.tableId}.${e.fieldId}`).join(`, `)}).`);this._apply(t,this._factory.deleteTable(t.getSnapshot(),n))}updateCell(e,t,n,r,i){this._apply(e,this.createUpdateCellOp(e,t,n,r,i))}setRecordValues(e,t,n){this._apply(e,this.createSetRecordValuesOp(e,t,n))}createRecord(e,t,n){this._apply(e,this.createCreateRecordOp(e,t,n))}createUpdateCellOp(e,t,n,r,i){return this.createSetRecordValuesOp(e,t,[{recordId:n,values:{[r]:i}}])}createSetRecordValuesOp(t,n,r){let i=t.getSnapshot(),a=r.map(e=>this._withModifiedSystemValues(i,n,e.recordId,{...Object.fromEntries(Object.entries(e.values).map(([t,r])=>[t,this._normalizeCellValue(i,n,e.recordId,t,r)]))})),o=this._resolveSingleSelectValues(i.tables[n],a);return e.M([o,this._factory.setRecordValues(i,n,a)])}createCreateRecordOp(e,t,n){return this.createBatchCreateRecordsOp(e,t,[n])}createBatchCreateRecordsOp(t,n,r){var i;if(!this._permissionService.canCreateRecord(n))throw Error(`[BaseCommandService]: cannot create record.`);let a=t.getSnapshot(),o=a.tables[n];return e.H(`BaseCommand.createBatchCreateRecordsOp`,()=>{let t=this._createNumberingAllocators(o),i=r.map(e=>this._createRecordWithDefaults(a,n,e,t)),s=this._resolveSingleSelectValues(o,i);return e.M([s,this._factory.createRecords(a,n,i)])},{existingRecords:((i=o.recordOrder)==null?void 0:i.length)??Object.keys(o.records).length,records:r.length})}createCreateFieldOp(t,n,r,i,a){if(!this._permissionService.canCreateField(n))throw Error(`[BaseCommandService]: cannot create field.`);let o=t.getSnapshot();if(this._assertFieldDefinition(o,r),i===0)throw Error(`[BaseCommandService]: cannot insert a field before record-id.`);let s=this._factory.createField(o,n,{field:r,index:i,viewIndexes:a}),c=this._createSystemFieldValuePatches(o,n,r);if(!c.length)return s;let l=this._applier.applyOp(o,s);return e.M([s,this._factory.setRecordValues(l,n,c)])}deleteRecord(e,t,n){if(!this._permissionService.canDeleteRecord(t,n))throw Error(`[BaseCommandService]: cannot delete record.`);this._apply(e,this._factory.deleteRecord(e.getSnapshot(),t,n))}duplicateRecord(e,n,r,i){if(!this._permissionService.canCreateRecord(n))throw Error(`[BaseCommandService]: cannot create record.`);this._apply(e,this._factory.duplicateRecord(e.getSnapshot(),n,r,{...i,values:{...i.values,[t.BASE_RECORD_ID_FIELD_ID]:i.id}}))}updateRecordOrder(e,t,n,r){if(!this._permissionService.canEditRecord(t,n))throw Error(`[BaseCommandService]: cannot edit record.`);this._apply(e,this._factory.updateRecordOrder(e.getSnapshot(),t,n,r))}createField(e,t,n,r,i){this._apply(e,this.createCreateFieldOp(e,t,n,r,i))}updateField(e,n,r,i){var a;if(!this._permissionService.canEditField(n,r))throw Error(`[BaseCommandService]: cannot edit field.`);let o=e.getSnapshot(),s=(a=o.tables[n])==null?void 0:a.fields[r];if(!s||r===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseCommandService]: cannot edit record-id.`);this._assertFieldDefinition(o,{...s,...i}),this._apply(e,this._factory.updateField(o,n,r,i))}changeFieldType(e,n,r,i){var a;if(!this._permissionService.canEditField(n,r))throw Error(`[BaseCommandService]: cannot edit field.`);let o=e.getSnapshot(),s=(a=o.tables[n])==null?void 0:a.fields[r];if(!s||r===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseCommandService]: cannot change record-id field type.`);this._assertFieldDefinition(o,{...s,...i}),this._apply(e,this._factory.changeFieldType(o,n,r,i))}deleteField(e,n,r){var i;if(((i=e.getSnapshot().tables[n])==null?void 0:i.primaryFieldId)===r||r===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseCommandService]: cannot delete primary field.`);if(!this._permissionService.canDeleteField(n,r))throw Error(`[BaseCommandService]: cannot delete field.`);this._apply(e,this._factory.deleteField(e.getSnapshot(),n,r))}moveField(e,n,r,i){if(!this._permissionService.canEditField(n,r))throw Error(`[BaseCommandService]: cannot edit field.`);if(r===t.BASE_RECORD_ID_FIELD_ID||i.beforeFieldId===t.BASE_RECORD_ID_FIELD_ID)throw Error(`[BaseCommandService]: cannot move a field before record-id.`);this._apply(e,this._factory.moveField(e.getSnapshot(),n,r,i))}createView(e,t,n,r){if(!this._permissionService.canManageView(t,n.id))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.createView(e.getSnapshot(),t,n,r))}renameView(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.renameView(e.getSnapshot(),t,n,r))}deleteView(e,t,n){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.deleteView(e.getSnapshot(),t,n))}moveView(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.moveView(e.getSnapshot(),t,n,r))}updateViewConfig(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.updateViewConfig(e.getSnapshot(),t,n,r))}setViewFilter(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewFilter(e.getSnapshot(),t,n,r))}setViewSort(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewSort(e.getSnapshot(),t,n,r))}setViewGroup(e,t,n,r){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewGroup(e.getSnapshot(),t,n,r))}setViewFieldVisible(e,t,n,r,i){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewFieldVisible(e.getSnapshot(),t,n,r,i))}setViewFieldWidth(e,t,n,r,i){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewFieldWidth(e.getSnapshot(),t,n,r,i))}setViewFieldOrder(e,t,n,r,i){if(!this._permissionService.canManageView(t,n))throw Error(`[BaseCommandService]: cannot manage view.`);this._apply(e,this._factory.setViewFieldOrder(e.getSnapshot(),t,n,r,i))}_apply(e,t){let n=e.getSnapshot();e.setSnapshot(this._applier.applyOp(n,t))}_resolveSingleSelectValues(n,r){let i=/* @__PURE__ */ new Map;for(let{values:e}of r)for(let[t,r]of Object.entries(e)){let a=n.fields[t];if(typeof r!=`string`||!a||!s(a))continue;let o=i.get(t);if(o||(o=new u(a.config.options),i.set(t,o)),!o.ids.has(r)){let n=r.trim();e[t]=n?o.resolveName(n):null}}let a=[];for(let[e,{added:r}]of i){if(!r.length)continue;let i=n.fields[e];if(i.system||i.readonly||!this._permissionService.canEditField(n.id,e))throw Error(`[BaseCommandService]: cannot create an option in this field.`);let o=[...p.field(n.id,e),`config`,`options`],s=i.config.options;if(Array.isArray(s)){let e=new t.JSON1.WriteCursor().descendPath(o);r.forEach((t,n)=>{e.at([s.length+n],e=>e.write(`i`,t))}),a.push(e.get())}else a.push(t.JSON1.insertOp(o,r))}return e.M(a)}_createRecordWithDefaults(n,r,i,a=this._createNumberingAllocators(n.tables[r])){let o=n.tables[r],s=i.createdBy??i.updatedBy??this._getCurrentUserId(),c={...i,createdBy:i.createdBy??s,updatedBy:i.updatedBy??s,values:{...i.values}};return c.values[t.BASE_RECORD_ID_FIELD_ID]=c.id,o.fieldOrder.forEach(n=>{let r=o.fields[n];if(r&&c.values[n]===void 0)switch(r.type){case t.BaseFieldType.Numbering:var i;c.values[n]=((i=a.get(n))==null?void 0:i())??this._createNumberingAllocator(o,n)();break;case t.BaseFieldType.CreatedBy:c.createdBy&&(c.values[n]=c.createdBy);break;case t.BaseFieldType.UpdatedBy:c.updatedBy&&(c.values[n]=c.updatedBy);break;case t.BaseFieldType.CreatedAt:c.values[n]=e.E(c.createdAt);break;case t.BaseFieldType.UpdatedAt:c.values[n]=e.E(c.updatedAt);break;default:{let e=r.defaultValue;e!=null&&e!==``&&!(Array.isArray(e)&&e.length===0)&&(c.values[n]=e)}}}),c}_withModifiedSystemValues(n,r,i,a){var o,s;let c=n.tables[r],l=((o=(s=this._runtimeContext).now)==null?void 0:o.call(s))??Date.now(),u=this._getCurrentUserId(),d={...a};return c.fieldOrder.forEach(n=>{let r=c.fields[n];r&&(r.type===t.BaseFieldType.UpdatedAt&&(d[n]=e.E(l)),r.type===t.BaseFieldType.UpdatedBy&&u&&(d[n]=u))}),{recordId:i,values:d,recordPatch:{updatedAt:l,...u?{updatedBy:u}:{}}}}_createSystemFieldValuePatches(e,n,r){let i=e.tables[n];return!i||!we(r)?[]:r.type===t.BaseFieldType.Numbering?this._createNumberingFieldValuePatches(i,r.id):Object.values(i.records).flatMap(e=>{let t=this._getSystemFieldValue(r,e);return t===void 0?[]:[{recordId:e.id,values:{[r.id]:t}}]})}_getSystemFieldValue(n,r){switch(n.type){case t.BaseFieldType.CreatedBy:return r.createdBy??this._getCurrentUserId();case t.BaseFieldType.UpdatedBy:return r.updatedBy??this._getCurrentUserId();case t.BaseFieldType.CreatedAt:return e.E(r.createdAt??Date.now());case t.BaseFieldType.UpdatedAt:return e.E(r.updatedAt??Date.now());default:return}}_createNumberingAllocators(e){let n=/* @__PURE__ */ new Map;return e&&e.fieldOrder.forEach(r=>{let i=e.fields[r];(i==null?void 0:i.type)===t.BaseFieldType.Numbering&&n.set(r,this._createNumberingAllocator(e,r))}),n}_createNumberingAllocator(e,t){let n=Object.values(e.records).reduce((e,n)=>{let r=Number(n.values[t]);return Number.isFinite(r)?Math.max(e,r):e},0);return()=>String(++n)}_createNumberingFieldValuePatches(e,t){let n=this._getOrderedRecords(e),r=this._createNumberingAllocator(e,t);return n.flatMap(e=>this._isNonEmptyCellValue(e.values[t])?[]:[{recordId:e.id,values:{[t]:r()}}])}_getOrderedRecords(e){var t;let n=Object.values(e.records),r=new Map(n.map(e=>[e.id,e])),i=[],a=/* @__PURE__ */ new Set;(t=e.recordOrder)==null||t.forEach(e=>{let t=r.get(e);t&&(i.push(t),a.add(e))});let o=n.filter(e=>!a.has(e.id)).sort((e,t)=>String(e.orderKey??e.id).localeCompare(String(t.orderKey??t.id))||e.id.localeCompare(t.id));return[...i,...o]}_isNonEmptyCellValue(e){return e!=null&&e!==``&&!(Array.isArray(e)&&e.length===0)}_getCurrentUserId(){var e,t,n,r;return((e=(t=this._runtimeContext).getCurrentUserId)==null?void 0:e.call(t))??((n=(r=this._runtimeContext).getCurrentUser)==null||(n=n.call(r))==null?void 0:n.userID)??void 0}_normalizeCellValue(n,r,i,a,o){var s;if(!this._permissionService.canEditCell(r,i,a))throw Error(`[BaseCommandService]: cannot edit cell.`);let c=(s=n.tables[r])==null?void 0:s.fields[a];if(!c)throw Error(`[BaseCommandService]: field "${a}" does not exist.`);let l=this._fieldRegistry.get(c.type);if(c.readonly||c.system||!l.getCapabilities(c).editable)throw Error(`[BaseCommandService]: cannot edit readonly field.`);let u=l.normalize(o,c),d=l.validate(u,c);if(!d.valid)throw Error(d.reason??`[BaseCommandService]: invalid cell value.`);let f=c.type===t.BaseFieldType.RecordLink?e.mt(n,c,u):{valid:!0};if(!f.valid)throw Error(f.reason??`[BaseCommandService]: invalid RecordLink value.`);return u}_assertFieldDefinition(n,r){if(r.id===t.BASE_RECORD_ID_FIELD_ID||r.type===t.BaseFieldType.RecordId||(0,t.isBaseRecordIdFieldName)(r.name))throw Error(`[BaseCommandService]: record-id is reserved.`);let i=e.pt(n,r);if(!i.valid)throw Error(i.reason??`[BaseCommandService]: invalid field definition.`)}};z=e.g([e._(0,ye),e._(1,e.y)],z);function Ce(){let t=new e.v;return e.x().forEach(e=>t.register(e)),t}function we(e){return e.type===t.BaseFieldType.Numbering||e.type===t.BaseFieldType.CreatedBy||e.type===t.BaseFieldType.UpdatedBy||e.type===t.BaseFieldType.CreatedAt||e.type===t.BaseFieldType.UpdatedAt}const Te=t.regexp.createRegExpFromSafeFragment(String.raw`(?:^|\W)\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?(?:$|\W)`),Ee=t.regexp.createRegExpFromSafeFragment(String.raw`(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?`,`gi`),De=/\{([^}]+)\}/g,Oe=t.regexp.createRegExpFromSafeFragment(String.raw`\b([A-Z_][\w.]*)\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]`,`gi`),ke=t.regexp.createRegExpFromSafeFragment(String.raw`\b([A-Z_][\w.]*)\[@\[([^\]]+)\]\]`,`gi`),Ae=t.regexp.createRegExpFromSafeFragment(String.raw`\b([A-Z_][\w.]*)\[([^\[\]#]+)\]`,`gi`),je=t.regexp.createRegExpFromSafeFragment(String.raw`(^|[^\w\[])\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]`,`gi`),Me=t.regexp.createRegExpFromSafeFragment(String.raw`(^|[^\w\[])\[@\[([^\]]+)\]\](?!\])`,`g`),Ne=t.regexp.createRegExpFromSafeFragment(String.raw`(^|[^\w\[])\[@?([^\[\]#]+)\](?!\])`,`g`);var B=class{createSuperTableReference(e,t=e.id){var n;let r=((n=e.recordOrder)==null?void 0:n.length)??Object.values(e.records).length;return{sheetId:t,titleMap:new Map(e.fieldOrder.map((t,n)=>{var r;return[((r=e.fields[t])==null?void 0:r.name)??t,n]})),range:{startRow:0,endRow:Math.max(0,r-1),startColumn:0,endColumn:Math.max(0,e.fieldOrder.length-1)},showHeader:!1}}getSuperTableRegistrations(e,n){let r=[],i=n?new Set(n):null,a=(0,t.createBaseFormulaTableNameMap)(e);return Object.values(e.tables).filter(e=>!i||i.has(e.id)).forEach(e=>{let t=this.createSuperTableReference(e,e.id);r.push({tableId:e.id,tableName:a.get(e.id),reference:t})}),r}validateFormula(e,n,r={}){let i=e.trim();if(!i)return{valid:!0};if(ze(i))return{valid:!1,reason:`[BaseFormula]: A1 references and ranges are not supported in Base formulas.`};let a=r.snapshot?(0,t.createBaseFormulaTableNameMap)(r.snapshot):void 0;for(let e of Re(i)){let t=Ke(e,n,r.snapshot,a);if(!t.table)return{valid:!1,reason:`[BaseFormula]: table "${e.tableName}" does not exist. Use FBaseTable.getFormulaName() or getSchema().formulaName for structured references.`};if(!t.field)return{valid:!1,reason:`[BaseFormula]: field "${e.fieldName}" does not exist.`}}return{valid:!0}}getDependencies(e,t,n={}){let r=/* @__PURE__ */ new Set;for(let i of this.getStructuredDependencies(e,t,n))i.tableId===t.id&&r.add(i.fieldId);return Array.from(r)}getStructuredDependencies(e,n,r={}){let i=/* @__PURE__ */ new Map,a=r.snapshot?(0,t.createBaseFormulaTableNameMap)(r.snapshot):void 0;for(let t of Re(e)){let e=Ke(t,n,r.snapshot,a);if(!e.table||!e.field)continue;let o=`${e.table.id}\u001F${e.field.id}`;i.set(o,{tableId:e.table.id,fieldId:e.field.id})}return Array.from(i.values())}};function Pe(n,r){var i;let a=[],o=(i=r.unitData)==null?void 0:i[n.id];return o&&Object.entries(o).forEach(([r,i])=>{let o=n.tables[r];if(!o||!i)return;let s=e.N(o),c=[];new t.ObjectMatrix(i).forValue((e,t,n)=>{let r=Fe(s,e,t,n);r&&c.push(r)}),c.length&&a.push({unitId:n.id,tableId:r,patches:c})}),a}function Fe(t,n,r,i){var a,o,s;let c=(a=t.rowId)==null?void 0:a[n],l=(o=t.colId)==null?void 0:o[r];if(!c||!t.records[c]||!l)return null;let u=t.fields[l];if(!u||u.type!==`formula`)return null;let d=String(((s=u.config)==null?void 0:s.formula)??``).trim(),f=(i==null?void 0:i.v)??null,p={v:f,t:Le(f),...n===0&&d?{f:d}:{},si:u.id};return Ie(e.F(t,c,l),p)?null:{row:n,col:r,value:p}}function Ie(e,t){return e!=null&&Object.is(e.v??null,t.v??null)&&e.t===t.t&&e.f===t.f&&e.si===t.si}function Le(e){return typeof e==`number`?t.CellValueType.NUMBER:typeof e==`boolean`?t.CellValueType.BOOLEAN:typeof e==`string`?t.CellValueType.STRING:null}function Re(e){let t=Ve(e,()=>``),n=/* @__PURE__ */ new Map,r=e=>{n.set(`${e.tableName??``}\u001F${e.fieldName}`,e)};for(let e of t.matchAll(De))r({fieldName:e[1],scope:`this-row`});t=t.replace(Oe,(e,t,n,i)=>(r({tableName:t,fieldName:i,scope:n.toLowerCase()===`data`?`data`:`this-row`}),` `)),t=t.replace(ke,(e,t,n)=>(r({tableName:t,fieldName:n,scope:`this-row`}),` `)),t=t.replace(je,(e,t,n,i)=>(r({fieldName:i,scope:n.toLowerCase()===`data`?`data`:`this-row`}),`${t} `)),t=t.replace(Me,(e,t,n)=>(r({fieldName:n,scope:`this-row`}),`${t} `));for(let e of t.matchAll(Ae))r({tableName:e[1],fieldName:e[2]});for(let e of t.matchAll(Ne))r({fieldName:e[2],scope:`this-row`});return Array.from(n.values())}function ze(e){let t=Ve(e,()=>` `).replace(De,` `).replace(Oe,` `).replace(ke,` `).replace(je,`$1 `).replace(Me,`$1 `).replace(Ae,` `).replace(Ne,`$1 `);return Te.test(t)}function Be(e,t){return We(Ue(e,t),t)}function Ve(e,t){return He(Be(e,t),t)}function He(e,t){return e.replace(/"(?:""|[^"])*"/g,t)}function Ue(e,t){return Ee.lastIndex=0,e.replace(Ee,(n,r)=>Ge(e,r)?n:t(n))}const V=/(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s!\[\]]+\[/g;function We(e,t){let n=[];for(V.lastIndex=0;;){let t=V.exec(e);if(t==null)break;if(Ge(e,t.index))continue;let r=V.lastIndex-1,i=0;for(let a=r;a<e.length;a++)if(e[a]===`[`&&i++,e[a]===`]`&&(i--,i===0)){n.push({start:t.index,end:a+1}),V.lastIndex=a+1;break}}if(n.length===0)return e;let r=``,i=0;for(let a of n)r+=e.slice(i,a.start),r+=t(e.slice(a.start,a.end)),i=a.end;return r+e.slice(i)}function Ge(e,t){let n=!1;for(let r=0;r<t;r++)e[r]===`"`&&(n&&e[r+1]===`"`?r++:n=!n);return n}function Ke(e,t,n,r){let i=qe(e.tableName,t,n,r);return{table:i,field:i?Object.values(i.fields).find(t=>t.name===e.fieldName):void 0}}function qe(e,n,r,i){if(!e)return n;if(!r){var a;let t=e.toLowerCase();return t===n.id.toLowerCase()||t===n.name.toLowerCase()||t===((a=n.formulaName)==null?void 0:a.toLowerCase())?n:void 0}let o=e.toLowerCase(),s=i??(0,t.createBaseFormulaTableNameMap)(r),c=Object.values(r.tables).filter(e=>{var t;return e.id.toLowerCase()===o||e.name.toLowerCase()===o||((t=s.get(e.id))==null?void 0:t.toLowerCase())===o||Je(e.id).toLowerCase()===o});return c.length===1?c[0]:void 0}function Je(e){return`_T_${Array.from(e,e=>{var t;return/[A-Za-z0-9]/.test(e)?e:`_x${((t=e.codePointAt(0))==null?void 0:t.toString(16))??`0`}_`}).join(``)}`}const Ye=new B;function Xe(e,n,r){var i;if(r.type!==t.BaseFieldType.Formula)return!0;let a=String(((i=r.config)==null?void 0:i.formula)??``),o=e.getSnapshot();return Ye.validateFormula(a,o.tables[n],{snapshot:o}).valid}function H(e,t,n){let r=e.getSnapshot().tables[t];if(!r)return!1;let{viewIds:i,fieldIds:a,recordIds:o}=n||{};if(i){for(let e of i)if(!r.views[e])return!1}if(a){for(let e of a)if(!r.fields[e])return!1}if(o){for(let e of o)if(!r.records[e])return!1}return!0}function U(n,r,i){if(i.id===t.BASE_RECORD_ID_FIELD_ID||i.type===t.BaseFieldType.RecordId||(0,t.isBaseRecordIdFieldName)(i.name)||!Xe(n,r,i))return!1;let a=n.getSnapshot();if(!e.pt(a,i).valid)return!1;if(i.type!==t.BaseFieldType.RecordLink)return!0;let o=e.lt(i);if(!o)return!1;if(o.relationRole===void 0)return!0;if(o.relationRole!==t.BaseRecordLinkRole.Parent||o.targetTableId!==r||o.multiple!==!1)return!1;let s=a.tables[r];return!Object.values(s.fields).some(n=>{var r;return n.id!==i.id&&n.type===t.BaseFieldType.RecordLink&&((r=e.lt(n))==null?void 0:r.relationRole)===t.BaseRecordLinkRole.Parent})}function W(n,r,i,a){var o;let s=n.getSnapshot(),c=(o=s.tables[r])==null?void 0:o.fields[i];if(!c||c.id===t.BASE_RECORD_ID_FIELD_ID||c.type===t.BaseFieldType.RecordId)return!1;if(c.type!==t.BaseFieldType.RecordLink)return!0;let l=$e(a);return e.mt(s,c,l).valid}function Ze(e,n,r){let i=e.getSnapshot().tables[n];return!i||!(0,t.isValidBaseRecordId)(r.id)||i.records[r.id]||Object.prototype.hasOwnProperty.call(r.values,t.BASE_RECORD_ID_FIELD_ID)&&r.values[t.BASE_RECORD_ID_FIELD_ID]!==r.id?!1:Object.entries(r.values).every(([r,i])=>r===t.BASE_RECORD_ID_FIELD_ID||W(e,n,r,i))}function Qe(e){return{...e,values:{...e.values,[t.BASE_RECORD_ID_FIELD_ID]:e.id}}}function $e(e){if(e&&typeof e==`object`&&!Array.isArray(e)&&`v`in e){let t=e.v;return t===void 0?null:t}return e}const G={id:`base.command.set-base-record-values`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,patches:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),l=s.map(e=>e.recordId),u=s.flatMap(e=>Object.keys(e.values));if(!c||!H(c,o,{recordIds:l,fieldIds:u})||s.some(e=>Object.entries(e.values).some(([e,t])=>!W(c,o,e,t))))return!1;let d=e.at(c.getSnapshot().tables[o],s),f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),m=n.get(R).createSetRecordValuesOp(c,o,s),h=new e.j().invertOp(c.getSnapshot(),m),g=r.ganttPredecessor,_={unitId:a,op:m,...g&&!g.onUndo?{ganttPredecessorAddition:g.addition}:{},trigger:d.length?G.id:void 0,hierarchyChanges:d.length?d:void 0,source:d.length?r.source??`ui`:void 0},v={..._,source:d.length?`redo`:void 0},y={unitId:a,op:h,...g!=null&&g.onUndo?{ganttPredecessorAddition:g.addition}:{},trigger:d.length?G.id:void 0,hierarchyChanges:d.length?d.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})):void 0,source:d.length?`undo`:void 0};return f.syncExecuteCommand(e.s.id,_)?(i.focusUnit(a),p.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:y}],redoMutations:[{id:e.s.id,params:v}]}),!0):!1}},et={id:`base.command.add-gantt-predecessor`,type:t.CommandType.COMMAND,handler(e,t){return nt(e,t,!1)}},tt={id:`base.command.remove-gantt-predecessor`,type:t.CommandType.COMMAND,handler(e,t){return nt(e,t,!0)===!0}};function nt(n,r,i){var a;if(!r)return!1;let{unitId:o,tableId:s,viewId:c,predecessorId:l,successorId:u}=r,d=n.get(t.IUniverInstanceService).getUnit(o,t.UniverInstanceType.UNIVER_BASE),f=d==null?void 0:d.getSnapshot().tables[s],p=f==null?void 0:f.views[c],m=p==null||(a=p.config)==null?void 0:a.dependencyFieldId,h=m?f==null?void 0:f.fields[m]:void 0,g=f==null?void 0:f.records[u];if(!f||!g||!i&&!f.records[l]||(p==null?void 0:p.type)!==t.BaseViewType.Gantt||!h||!e.st(s,h))return!1;let _=e.ut(g.values[h.id]),v=_.includes(l);if(i?!v:v)return!0;if(!i&&e.ot(l,u,e=>{var t;return(t=f.records[e])==null?void 0:t.values[h.id]}))return`cycle`;let y=i?_.filter(e=>e!==l):[..._,l],b=e.dt(y),x=[];for(let e of Object.values(f.records)){let t=i&&e.id===u?b:e.values[h.id];typeof t==`string`&&t&&x.push([e.id,t])}let S={tableId:s,fieldId:h.id,predecessorId:l,successorId:u,graph:x};return n.get(t.ICommandService).syncExecuteCommand(G.id,{unitId:o,tableId:s,viewId:c,patches:[{recordId:u,values:{[h.id]:b}}],ganttPredecessor:{addition:S,onUndo:i}})}function rt(t,n,r,i){let a=t.getSnapshot().tables[n];if(!a)return null;let o=e.Q(a),s=o??e.nt(a),c=r.some(e=>Object.prototype.hasOwnProperty.call(e.values,s)),l=o?a.fields[o]:c?e.Y(a,s,i):null,u=[];for(let i of r){let r=i.values[s],a=l!==null&&Object.prototype.hasOwnProperty.call(i.values,s),o=$e(r),c=null;if(a){if(typeof o!=`string`||!e.ft(o,!1).valid)return null;c=o}let d={};if(Object.entries(i.values).forEach(([e,t])=>{a&&e===s||(d[e]=t)}),!Ze(t,n,{...i,values:d}))return null;let f={...i.values};c!==null&&(f[s]=c),u.push(Qe({...i,values:f}))}return{records:u,hierarchyFieldToMaterialize:o?null:l,hierarchyChanges:e.it(a,u)}}const it={id:`base.command.batch-create-base-records`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,records:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),l=s.map(e=>e.id);if(!c||!H(c,o)||new Set(l).size!==l.length)return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=n.get(R),p=c.getSnapshot(),m=rt(c,o,s);if(!m)return!1;let{records:h,hierarchyChanges:g,hierarchyFieldToMaterialize:_}=m,v=_?f.createCreateFieldOp(c,o,_,p.tables[o].fieldOrder.length):null,y=f.createBatchCreateRecordsOp(c,o,h),b=e.M([...v?[v]:[],y]),x=new e.j().invertOp(p,b),S={unitId:a,op:b,hierarchyChanges:g.length?g:void 0,source:g.length?r.source??`ui`:void 0},C={...S,source:g.length?`redo`:void 0},w={unitId:a,op:x,hierarchyChanges:g.length?g.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:null})):void 0,source:g.length?`undo`:void 0};return u.syncExecuteCommand(e.s.id,S)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:w}],redoMutations:[{id:e.s.id,params:C}]}),!0):!1}},at={id:`base.command.batch-delete-base-records`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,recordIds:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c||!H(c,o,{recordIds:s}))return!1;let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=c.getSnapshot(),f=e.Z(d.tables[o],s),p=new m,h=new e.j,g=p.deleteRecords(d,o,s),_=h.applyOp(d,g),v=p.createDeleteRecordsUndoOp(d,_,o,s),y={unitId:a,op:g,hierarchyChanges:f,source:r.source??`ui`},b={...y,source:`redo`},x={unitId:a,op:v,hierarchyChanges:f.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})),source:`undo`};return l.syncExecuteCommand(e.s.id,y)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},ot={id:`base.command.change-base-field-type`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s,input:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||s===t.BASE_RECORD_ID_FIELD_ID||!H(l,o,{fieldIds:[s]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot();if(!U(l,o,{...f.tables[o].fields[s],...c}))return!1;let p=new m().changeFieldType(f,o,s,c),h=new e.j().invertOp(f,p),g={unitId:a,op:p},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},K={id:`base.command.create-base-child-record`,type:t.CommandType.COMMAND,handler(n,r){var i;if(!r)return!1;let{unitId:a,tableId:o,parentRecordId:s}=r,c=n.get(t.IUniverInstanceService),l=c.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{recordIds:[s]}))throw new e.K(`missingRecord`);let u=l.getSnapshot(),d=u.tables[o],f=e.Q(d),p=f??r.fieldId??e.nt(d);if(f&&r.fieldId&&r.fieldId!==f||d.fields[p]&&!e.et(d,p))throw new e.K(`invalidField`);if((e.J(d,p).depthByRecordId.get(s)??0)+1>=5)throw new e.K(`maxDepth`);if(!Ze(l,o,r.record))return!1;let h=Qe({...r.record,values:{...r.record.values,[p]:e.dt([s])}}),g=n.get(R),_=new m,v=d.fields[p],y=v?((i=e.lt(v))==null?void 0:i.relationRole)===t.BaseRecordLinkRole.Parent?null:_.updateField(u,o,p,{config:{...v.config,relationRole:t.BaseRecordLinkRole.Parent}}):g.createCreateFieldOp(l,o,e.Y(d,p,r.parentFieldName),d.fieldOrder.length),b=g.createCreateRecordOp(l,o,h),x=e.M([...y?[y]:[],b]),S=new e.j().invertOp(u,x),C={tableId:o,fieldId:p,recordId:h.id,oldParentRecordId:null,parentRecordId:s},w={unitId:a,op:x,trigger:K.id,hierarchyChanges:[C],source:r.source??`ui`},T={...w,source:`redo`},E={unitId:a,op:S,trigger:K.id,hierarchyChanges:[{...C,oldParentRecordId:s,parentRecordId:null}],source:`undo`};return n.get(t.ICommandService).syncExecuteCommand(e.s.id,w)?(c.focusUnit(a),n.get(t.IUndoRedoService).pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:E}],redoMutations:[{id:e.s.id,params:T}]}),!0):!1}},st={id:`base.command.create-base-field`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,field:s,index:c,viewIndexes:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o)||u.getSnapshot().tables[o].fields[s.id]||c===0||!U(u,o,s))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=n.get(R).createCreateFieldOp(u,o,s,c,l),m=new e.j().invertOp(u.getSnapshot(),p),h={unitId:a,op:p},g={unitId:a,op:m};return d.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}},ct={id:`base.command.create-base-record`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,record:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c||!H(c,o))return!1;let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=n.get(R),f=c.getSnapshot(),p=rt(c,o,[s]);if(!p)return!1;let[m]=p.records,{hierarchyChanges:h,hierarchyFieldToMaterialize:g}=p,_=g?d.createCreateFieldOp(c,o,g,f.tables[o].fieldOrder.length):null,v=d.createCreateRecordOp(c,o,m),y=e.M([..._?[_]:[],v]),b=new e.j().invertOp(f,y),x={unitId:a,op:y,hierarchyChanges:h.length?h:void 0,source:h.length?r.source??`ui`:void 0},S={...x,source:h.length?`redo`:void 0},C={unitId:a,op:b,hierarchyChanges:h.length?h.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:null})):void 0,source:h.length?`undo`:void 0};return l.syncExecuteCommand(e.s.id,x)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:C}],redoMutations:[{id:e.s.id,params:S}]}),!0):!1}};function q(e,n,r){if(!n.trim())return{valid:!1,reason:`Table name is required.`,error:`required`};if(n.length>31)return{valid:!1,reason:`Use 31 characters or fewer.`,error:`too-long`};if(n.startsWith(`'`)||n.endsWith(`'`))return{valid:!1,reason:`A table name cannot start or end with an apostrophe.`,error:`apostrophe`};if(/[:\\/?*\[\]]/.test(n))return{valid:!1,reason:`A table name cannot contain : \\ / ? * [ ].`,error:`invalid-characters`};if(!(0,t.nameCharacterCheck)(n))return{valid:!1,reason:`Choose another name.`,error:`invalid`};let i=n.toLowerCase();return Object.values(e.tables).some(e=>e.id!==r&&e.name.toLowerCase()===i)?{valid:!1,reason:`A table with this name already exists.`,error:`duplicate`}:{valid:!0}}function lt(e,t){let n=t.replace(/[:\\/?*\[\]]/g,` `).replace(/^'+|'+$/g,``).trim()||`Table`,r=1;for(;;){let t=r===1?``:` ${r}`,i=`${n.slice(0,31-t.length)}${t}`;if(q(e,i).valid)return i;r++}}const ut={id:`base.command.create-base-table`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,table:o,index:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c||c.getSnapshot().tables[o.id]||!q(c.getSnapshot(),o.name).valid)return!1;try{(0,t.assertBaseTableRecordIdentity)(o)}catch{return!1}let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=c.getSnapshot(),f=new m().createTable(d,o,s),p=new e.j().invertOp(d,f),h={unitId:a,op:f},g={unitId:a,op:p};return l.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}};function dt(e,t,n=[]){let r=/* @__PURE__ */ new Set([...Object.values(e.fields).filter(e=>e).map(e=>e.name),...n.map(e=>e.name)]);if(!r.has(t))return t;let i=2;for(;r.has(`${t} ${i}`);)i++;return`${t} ${i}`}function ft(e,t){if(!e||!t.length)return;let n=[...e];return t.forEach(e=>{n.includes(e)||n.push(e)}),n}const pt={options:[{id:`todo`,name:`Todo`,color:`#BFDBFE`},{id:`doing`,name:`Doing`,color:`#FDE68A`},{id:`done`,name:`Done`,color:`#BBF7D0`}]},mt={locale:`en-US`,pattern:`yyyy/mm/dd`,includeTime:!1,hourCycle:`h24`,defaultMode:`none`};function ht(n,r,i,a){var o;let s=new m,c=n.tables[r],l=c?{...i,fieldOrder:[t.BASE_RECORD_ID_FIELD_ID,...(i.fieldOrder??c.fieldOrder).filter(e=>e!==t.BASE_RECORD_ID_FIELD_ID)],fieldSettings:{...i.fieldSettings,[t.BASE_RECORD_ID_FIELD_ID]:{...(o=i.fieldSettings)==null?void 0:o[t.BASE_RECORD_ID_FIELD_ID],hidden:!0}}}:i;if(c&&l.type===`kanban`){let t=_t(c,l),i=t.changed?{...l,config:t.config,fieldOrder:t.fieldOrder??l.fieldOrder}:l;return e.M([...t.fields.map(e=>s.createField(n,r,{field:e})),s.createView(n,r,i,a)])}if(!c||l.type!==`calendar`&&l.type!==`gantt`)return s.createView(n,r,l,a);let u=gt(c,l),d=u.changed?{...l,config:u.config,fieldOrder:u.fieldOrder??l.fieldOrder}:l;return d.type===`gantt`&&(d={...d,config:{displayColor:{type:`custom`,color:`#3b82f6`},...d.config}},bt(l)&&(d=xt(c,d,u.fields))),e.M([...u.fields.map(e=>s.createField(n,r,{field:e})),s.createView(n,r,d,a)])}function gt(e,n,r=!1){var i,a;let o=e.fieldOrder.filter(t=>Ct(e,t)),s=[],c={...n.config??{}},l=typeof c.startDateFieldId==`string`&&Ct(e,c.startDateFieldId)?c.startDateFieldId:o[0],u=typeof c.endDateFieldId==`string`&&Ct(e,c.endDateFieldId)&&c.endDateFieldId!==l?c.endDateFieldId:o.find(e=>e!==l);if(!l){let t=wt(e,s,n.type===`gantt`?`Start date`:`Date`);s.push(t),l=t.id}if((n.type===`gantt`||r)&&!u){let t=wt(e,s,`End date`);s.push(t),u=t.id}n.type===`calendar`&&!u&&delete c.endDateFieldId,c.startDateFieldId=l,n.type===`calendar`&&u&&(c.endDateFieldId=u),n.type===`gantt`&&(c.endDateFieldId=u??l);let d=ft(n.fieldOrder,s.map(e=>e.id));return{changed:s.length>0||c.startDateFieldId!==((i=n.config)==null?void 0:i.startDateFieldId)||c.endDateFieldId!==((a=n.config)==null?void 0:a.endDateFieldId)||!(!d||t.Tools.diffValue(d,n.fieldOrder??[])),fields:s,config:c,fieldOrder:d}}function _t(e,n){var r;let i=[],a={...n.config??{}},o=typeof a.groupFieldId==`string`&&vt(e,a.groupFieldId)?a.groupFieldId:e.fieldOrder.find(t=>vt(e,t));if(!o){let t=yt(e,i);i.push(t),o=t.id}a.groupFieldId=o;let s=ft(n.fieldOrder,i.map(e=>e.id));return{changed:i.length>0||a.groupFieldId!==((r=n.config)==null?void 0:r.groupFieldId)||!(!s||t.Tools.diffValue(s,n.fieldOrder??[])),fields:i,config:a,fieldOrder:s}}function vt(e,n){let r=n?e.fields[n]:null;return r?[t.BaseFieldType.SingleSelect,t.BaseFieldType.MultiSelect,t.BaseFieldType.Rating,t.BaseFieldType.Person,t.BaseFieldType.Group,t.BaseFieldType.Checkbox].includes(r.type):!1}function yt(e,n){return{id:`fld-${(0,t.generateRandomId)(8)}`,name:dt(e,`Status`,n),type:t.BaseFieldType.SingleSelect,config:t.Tools.deepClone(pt)}}function bt(e){return Object.keys(e.config??{}).length===0&&Object.keys(e.fieldSettings??{}).length===0}function xt(e,t,n){let r={...t.config??{}},i=n.map(e=>e.id),a=[...e.fieldOrder,...i],o=typeof r.titleFieldId==`string`&&St(e,n,r.titleFieldId)?r.titleFieldId:e.primaryFieldId,s=typeof r.startDateFieldId==`string`?r.startDateFieldId:``,c=typeof r.endDateFieldId==`string`?r.endDateFieldId:s,l=new Set([o,s,c].filter(t=>t&&St(e,n,t))),u=Object.fromEntries(a.flatMap(t=>l.has(t)||!St(e,n,t)?[]:[[t,{hidden:!0}]]));return{...t,config:{...r,titleFieldId:o},fieldSettings:u}}function St(e,t,n){return!!(e.fields[n]??t.find(e=>e.id===n))&&!0}function Ct(e,n){let r=n?e.fields[n]:null;return!!r&&r.type===t.BaseFieldType.Date&&r.readonly!==!0&&r.system!==!0}function wt(e,n,r){let i=/* @__PURE__ */ new Set([...Object.keys(e.fields),...n.map(e=>e.id)]),a=`fld-${(0,t.generateRandomId)(8)}`;for(;i.has(a);)a=`fld-${(0,t.generateRandomId)(8)}`;return{id:a,name:dt(e,r,n),type:t.BaseFieldType.Date,config:{...mt}}}const Tt={id:`base.command.create-base-view`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,view:s,index:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o)||l.getSnapshot().tables[o].views[s.id])return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=ht(f,o,s,c),m=new e.j().invertOp(f,p),h={historyAction:`create-view`,unitId:a,op:p,viewType:s.type},g={historyAction:`delete-view`,unitId:a,op:m,viewType:s.type};return u.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}},Et={id:`base.command.delete-base-field`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c)return!1;let l=c.getSnapshot(),u=l.tables[o];if(!H(c,o,{fieldIds:[s]})||u.primaryFieldId===s||s===t.BASE_RECORD_ID_FIELD_ID)return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=new m().deleteField(l,o,s),h=new e.j().invertOp(l,p),g={unitId:a,op:p},_={unitId:a,op:h};return d.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Dt={id:`base.command.delete-base-record`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,recordId:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c||!H(c,o,{recordIds:[s]}))return!1;let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=c.getSnapshot(),f=e.Z(d.tables[o],[s]),p=new m,h=new e.j,g=p.deleteRecord(d,o,s),_=h.applyOp(d,g),v=p.createDeleteRecordsUndoOp(d,_,o,[s]),y={unitId:a,op:g,hierarchyChanges:f,source:r.source??`ui`},b={...y,source:`redo`},x={unitId:a,op:v,hierarchyChanges:f.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})),source:`undo`};return l.syncExecuteCommand(e.s.id,y)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},Ot={id:`base.command.delete-base-table`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o}=r,s=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!s||!H(s,o))return!1;let c=n.get(t.ICommandService),l=n.get(t.IUndoRedoService),u=s.getSnapshot(),d=e.ct(u,o);if(d.length>0)return console.error(`[DeleteBaseTableCommand]: table "${o}" is referenced by ${d.map(e=>`${e.tableId}.${e.fieldId}`).join(`, `)}.`),!1;let f=new m().deleteTable(u,o),p=new e.j().invertOp(u,f),h={unitId:a,op:f},g={unitId:a,op:p};return c.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),l.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}},kt={id:`base.command.delete-base-view`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c||!H(c,o,{viewIds:[s]}))return!1;let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=c.getSnapshot(),f=d.tables[o].views[s].type,p=new m().deleteView(d,o,s),h=new e.j().invertOp(d,p),g={historyAction:`delete-view`,unitId:a,op:p,viewType:f},_={historyAction:`create-view`,unitId:a,op:h,viewType:f};return l.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},At={id:`base.command.duplicate-base-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,sourceFieldId:s,field:c,index:l,viewIndexes:u}=r,d=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!d||!H(d,o,{fieldIds:[s]})||s===t.BASE_RECORD_ID_FIELD_ID||d.getSnapshot().tables[o].fields[c.id]||l===0||!U(d,o,c))return!1;let f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),h=d.getSnapshot(),g=new m().duplicateField(h,o,s,{field:c,index:l,viewIndexes:u}),_=new e.j().invertOp(h,g),v={unitId:a,op:g},y={unitId:a,op:_};return f.syncExecuteCommand(e.s.id,v)?(i.focusUnit(a),p.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:y}],redoMutations:[{id:e.s.id,params:v}]}),!0):!1}},jt={id:`base.command.duplicate-base-record`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,sourceRecordId:s,record:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{recordIds:[s]})||!Ze(l,o,c))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=Qe(c),h=e.it(f.tables[o],[p]),g=new m().duplicateRecord(f,o,s,p),_=new e.j().invertOp(f,g),v={unitId:a,op:g,hierarchyChanges:h.length?h:void 0,source:h.length?r.source??`ui`:void 0},y={...v,source:h.length?`redo`:void 0},b={unitId:a,op:_,hierarchyChanges:h.length?h.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:null})):void 0,source:h.length?`undo`:void 0};return u.syncExecuteCommand(e.s.id,v)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:b}],redoMutations:[{id:e.s.id,params:y}]}),!0):!1}},Mt={id:`base.command.ensure-base-temporal-view-date-fields`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,ensureEndDateField:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{viewIds:[s]}))return!1;let u=l.getSnapshot(),d=u.tables[o],f=d==null?void 0:d.views[s];if(!d||!f||f.type!==`calendar`&&f.type!==`gantt`)return!1;let p=gt(d,f,c===!0);if(!p.changed)return!1;let h=n.get(t.ICommandService),g=n.get(t.IUndoRedoService),_=new m,v=[...p.fields.map(e=>_.createField(u,r.tableId,{field:e})),Nt([...Pt(r.tableId,r.viewId),`config`],f.config,p.config)];p.fieldOrder&&v.push(Nt([...Pt(r.tableId,r.viewId),`fieldOrder`],f.fieldOrder,p.fieldOrder));let y=e.M(v),b=new e.j().invertOp(u,y),x={unitId:a,op:y},S={unitId:a,op:b};return h.syncExecuteCommand(e.s.id,x)?(i.focusUnit(a),g.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:S}],redoMutations:[{id:e.s.id,params:x}]}),!0):!1}};function Nt(e,n,r){return n===void 0?t.JSON1.insertOp(e,r):t.JSON1.replaceOp(e,n,r)}function Pt(e,t){return[`tables`,e,`views`,t]}const Ft={id:`base.command.move-base-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s,target:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),u=c.beforeFieldId??c.afterFieldId;if(!l||!!c.beforeFieldId==!!c.afterFieldId||!u||u===s||s===t.BASE_RECORD_ID_FIELD_ID||c.beforeFieldId===t.BASE_RECORD_ID_FIELD_ID||!H(l,o,{fieldIds:[s,u]}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=l.getSnapshot(),h=new m().moveField(p,o,s,c),g=new e.j().invertOp(p,h),_={unitId:a,op:h},v={unitId:a,op:g};return d.syncExecuteCommand(e.s.id,_)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:v}],redoMutations:[{id:e.s.id,params:_}]}),!0):!1}},It={id:`base.command.move-base-hierarchy-record`,type:t.CommandType.COMMAND,handler:(n,r)=>{var i;if(!r)return!1;let{unitId:a,tableId:o,recordId:s,parentRecordId:c,orderKey:l}=r,u=n.get(t.IUniverInstanceService),d=u.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!d||!H(d,o,{recordIds:[s,...c?[c]:[]]}))throw new e.K(`missingRecord`);let f=d.getSnapshot(),p=f.tables[o],h=e.Q(p),g=h??r.fieldId??e.nt(p);if(h&&r.fieldId&&r.fieldId!==h||p.fields[g]&&!e.et(p,g))throw new e.K(`invalidField`);let _=e.J(p,g),v=e.rt(_,s,c);if(!v.valid){let n=v.reason===t.BaseHierarchyInvalidReason.SelfParent?`selfParent`:v.reason===t.BaseHierarchyInvalidReason.Cycle?`cycle`:`maxDepth`;throw new e.K(n)}let y=_.parentByRecordId.get(s)??null,b=p.records[s].orderKey;if(y===c&&(l===void 0||l===b))return!0;let x=y!==c,S=l!==void 0&&l!==b,C=new m,w=[],T=p.fields[g],E=x&&(!T||((i=e.lt(T))==null?void 0:i.relationRole)!==t.BaseRecordLinkRole.Parent)?T?C.updateField(f,o,g,{config:{...T.config,relationRole:t.BaseRecordLinkRole.Parent}}):n.get(R).createCreateFieldOp(d,o,e.Y(p,g,r.parentFieldName),p.fieldOrder.length):null;E&&w.push(E),x&&w.push(C.updateCell(f,o,s,g,c?e.dt([c]):``)),S&&w.push(C.updateRecordOrder(f,o,s,l));let D=e.M(w),ee={tableId:o,fieldId:g,recordId:s,oldParentRecordId:y,parentRecordId:c},te={unitId:a,op:D,trigger:It.id,hierarchyChanges:[ee],source:r.source??`ui`},ne={...te,source:`redo`};if(!n.get(t.ICommandService).syncExecuteCommand(e.s.id,te))return!1;let re=d.getSnapshot(),O=[];x&&O.push(Lt(re,f,o,s,g)),S&&O.push(Rt(re,f,o,s)),E&&O.push(new e.j().invertOp(f,E));let ie={unitId:a,op:e.M(O),trigger:It.id,hierarchyChanges:[{...ee,oldParentRecordId:c,parentRecordId:y}],source:`undo`};return u.focusUnit(a),n.get(t.IUndoRedoService).pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:ie}],redoMutations:[{id:e.s.id,params:ne}]}),!0}};function Lt(t,n,r,i,a){var o,s,c,l,u,d,f,m;let h=t.tables[r],g=n.tables[r],_=(o=h.rowIndex)==null?void 0:o[i],v=(s=h.colIndex)==null?void 0:s[a],y=(c=g.rowIndex)==null?void 0:c[i],b=(l=g.colIndex)==null?void 0:l[a],x=_==null||v==null||(u=h.cellData)==null||(u=u[_])==null?void 0:u[v],S=y==null||b==null||(d=g.cellData)==null||(d=d[y])==null?void 0:d[b],C=(f=h.records[i])==null?void 0:f.values[a],w=(m=g.records[i])==null?void 0:m.values[a],T=[],E=zt(_==null||v==null?null:p.cellData(r,_,v),x,S);E&&T.push(E);let D=zt(p.cell(r,i,a),C,w);return D&&T.push(D),e.M(T)}function Rt(t,n,r,i){var a,o;let s=t.tables[r],c=n.tables[r],l=[zt([...p.record(r,i),`orderKey`],(a=s.records[i])==null?void 0:a.orderKey,(o=c.records[i])==null?void 0:o.orderKey),zt([...p.table(r),`recordOrder`],s.recordOrder,c.recordOrder)].filter(e=>!!e);return e.M(l)}function zt(e,n,r){if(!e||n===void 0&&r===void 0)return null;let i=t.JSONX.getInstance();return r===void 0?i.removeOp(e,n):n===void 0?i.insertOp(e,r):i.replaceOp(e,n,r)}const Bt={id:`base.command.move-base-view`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,target:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),u=c.beforeViewId??c.afterViewId;if(!l||!u||u===s||!H(l,o,{viewIds:[s,u]}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=l.getSnapshot(),h=new m().moveView(p,o,s,c),g=new e.j().invertOp(p,h),_={unitId:a,op:h},v={unitId:a,op:g};return d.syncExecuteCommand(e.s.id,_)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:v}],redoMutations:[{id:e.s.id,params:_}]}),!0):!1}},Vt={id:`base.command.rename-base-table`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,name:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c||!H(c,o)||!q(c.getSnapshot(),s,o).valid)return!1;let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=c.getSnapshot(),f=new m().renameTable(d,o,s),p=new e.j().invertOp(d,f),h={unitId:a,op:f},g={unitId:a,op:p};return l.syncExecuteCommand(e.s.id,h)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:g}],redoMutations:[{id:e.s.id,params:h}]}),!0):!1}},Ht={id:`base.command.rename-base-view`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,name:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{viewIds:[s]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=new m().renameView(f,o,s,c),h=new e.j().invertOp(f,p),g={unitId:a,op:p},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Ut={id:`base.command.set-base-kanban-group-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,fieldId:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{viewIds:[s],fieldIds:[c]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=new m().updateViewConfig(f,o,s,{groupFieldId:c}),h=new e.j().invertOp(f,p),g={unitId:a,op:p},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Wt={id:`base.command.set-base-name`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),a=i.getUnit(r.unitId,t.UniverInstanceType.UNIVER_BASE);if(!a)return!1;let o=a.getSnapshot().name;if(o===r.name)return!0;let s=new m,c=new e.j,l=[],u=[],d=[a,...i.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).filter(e=>e.getUnitId()!==r.unitId)];for(let t of d){let n=t.getSnapshot(),i=t===a?s.setBaseName(n,r.name):s.renameFormulaUnitReferences(n,o,r.name);i&&(l.push({id:e.s.id,params:{unitId:t.getUnitId(),op:i,trigger:Wt.id}}),u.unshift({id:e.s.id,params:{unitId:t.getUnitId(),op:c.invertOp(n,i),trigger:Wt.id}}))}let f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),h=p.__tempBatchingUndoRedo(r.unitId);try{return(0,t.sequenceExecute)(l,f).result?(i.focusUnit(r.unitId),p.pushUndoRedo({unitID:r.unitId,undoMutations:u,redoMutations:l}),!0):!1}finally{h.dispose()}}},Gt={type:t.CommandType.COMMAND,id:`base.command.set-permission`,async handler(e,n){if(!n||!k.includes(n.action)||n.objectId!==n.unitId&&n.action!==r.UnitAction.Edit||n.policy&&(![`all`,`owner`,`members`].includes(n.policy.edit)||n.policy.strategies.some(e=>!k.includes(e.action)||n.objectId!==n.unitId&&e.action!==r.UnitAction.Edit)))return!1;let i=P(n.unitId,n.objectId,n.action),a={unitId:n.unitId,objectId:n.objectId,objectType:i.type},o=e.get(t.ObjectPermissionService);return n.remove?await o.remove(a):n.policy?await o.save(a,n.policy):await o.setPoint(a,i,n.value),!0}},Kt={type:t.CommandType.COMMAND,id:`base.command.set-permissions`,async handler(e,n){if(!(n!=null&&n.unitId)||!Array.isArray(n.changes)||!n.changes.length||n.changes.some(e=>!(e!=null&&e.objectId)||e.objectId===n.unitId||e.policy!==null&&(!e.policy||![`all`,`owner`,`members`].includes(e.policy.edit)||!Array.isArray(e.policy.collaborators)||!Array.isArray(e.policy.strategies)||e.policy.strategies.some(e=>e.action!==r.UnitAction.Edit))))throw Error(`Invalid object permission batch.`);return e.get(t.ObjectPermissionService).saveMany(n.changes.map(e=>{let t=P(n.unitId,e.objectId,r.UnitAction.Edit);return{unitId:n.unitId,objectId:e.objectId,objectType:t.type,policy:e.policy}}))}};function qt(n,r){let i=e.N(t.Tools.deepClone(n)),a=/* @__PURE__ */ new Map;return r.forEach(t=>{var n,r;let o=`recordId`in t?t.recordId:(n=i.rowId)==null?void 0:n[t.row],s=`fieldId`in t?t.fieldId:(r=i.colId)==null?void 0:r[t.col],c=s?i.fields[s]:void 0;if(!o||!s||!c||!i.records[o])return;let l=e.B(t.value,c),u=e.V(t.value,l,c,i,o),d=a.get(o)??{};d[s]=u,a.set(o,d)}),[...a].map(([e,t])=>({recordId:e,values:t}))}const Jt={id:`base.command.set-base-range-values`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,patches:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c||!H(c,o))return!1;let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=c.getSnapshot(),f=e.N(d.tables[o]),p=s.map(e=>{var t;return`recordId`in e?e.recordId:(t=f.rowId)==null?void 0:t[e.row]}).filter(e=>e!=null),h=s.map(e=>{var t;return`fieldId`in e?e.fieldId:(t=f.colId)==null?void 0:t[e.col]}).filter(e=>e!=null);if(p.length!==s.length||h.length!==s.length||!H(c,o,{recordIds:p,fieldIds:h})||s.some((e,t)=>!W(c,o,h[t],e.value)))return!1;let g=e.at(f,qt(f,s)),_=s.flatMap(e=>{var t,n;if(`row`in e)return[e];let r=(t=f.rowIndex)==null?void 0:t[e.recordId],i=(n=f.colIndex)==null?void 0:n[e.fieldId];return r==null||i==null?[]:[{row:r,col:i,value:e.value}]}),v=new m().setRangeValues(d,o,_),y=new e.j().invertOp(d,v),b={unitId:a,op:v,trigger:g.length?Jt.id:void 0,hierarchyChanges:g.length?g:void 0,source:g.length?`redo`:void 0},x={unitId:a,op:y,trigger:g.length?Jt.id:void 0,hierarchyChanges:g.length?g.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})):void 0,source:g.length?`undo`:void 0},S={...b,source:g.length?r.source??`ui`:void 0};return l.syncExecuteCommand(e.s.id,S)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},Yt={id:`base.command.set-base-table-hierarchy-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let{unitId:i,tableId:a,fieldId:o}=r,s=n.get(t.IUniverInstanceService),c=s.getUnit(i,t.UniverInstanceType.UNIVER_BASE);if(!c||!H(c,a))return!1;let l=c.getSnapshot(),u=l.tables[a];if(o!==null&&!e.et(u,o))throw new e.K(`invalidField`);if(e.Q(u)===o)return!0;let d=new m,f=Object.values(u.fields).flatMap(n=>{if(!e.et(u,n.id))return[];let r=e.lt(n);if(!r)return[];let i=n.id===o;if(r.relationRole===t.BaseRecordLinkRole.Parent===i)return[];let s={...n.config,targetTableId:r.targetTableId,multiple:r.multiple};return i?s.relationRole=t.BaseRecordLinkRole.Parent:delete s.relationRole,[d.updateField(l,a,n.id,{config:s})]}),p=e.M(f),h=new e.j().invertOp(l,p),g={unitId:i,op:p},_={unitId:i,op:h};return n.get(t.ICommandService).syncExecuteCommand(e.s.id,g)?(s.focusUnit(i),n.get(t.IUndoRedoService).pushUndoRedo({unitID:i,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},Xt={id:`base.command.set-base-view-field-order`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,fieldId:c,target:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),d=l.beforeFieldId??l.afterFieldId;if(!u||!d||d===c||!H(u,o,{viewIds:[s],fieldIds:[c,d]}))return!1;let f=u.getSnapshot().tables[o],p=f.fields[c],h=f.fields[d];if(p.system===!0||p.type===t.BaseFieldType.RecordId||h.system===!0||h.type===t.BaseFieldType.RecordId)return!1;let g=n.get(t.ICommandService),_=n.get(t.IUndoRedoService),v=u.getSnapshot(),y=new m().setViewFieldOrder(v,o,s,c,l),b=new e.j().invertOp(v,y),x={unitId:a,op:y},S={unitId:a,op:b};return g.syncExecuteCommand(e.s.id,x)?(i.focusUnit(a),_.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:S}],redoMutations:[{id:e.s.id,params:x}]}),!0):!1}},Zt={id:`base.command.set-base-view-field-visible`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,fieldId:c,visible:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{viewIds:[s],fieldIds:[c]}))return!1;let d=u.getSnapshot().tables[o].fields[c];if(d.system===!0||d.type===t.BaseFieldType.RecordId)return!1;let f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),h=u.getSnapshot(),g=new m,_=g.setViewFieldVisible(h,o,s,c,l),{undo:v,redo:y}=g.getViewFieldSettingHistory(h,o,s,c,{hidden:!l}),b={unitId:a,op:y},x={unitId:a,op:v};return f.syncExecuteCommand(e.s.id,{unitId:a,op:_})?(i.focusUnit(a),p.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},Qt={id:`base.command.set-base-view-field-width`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,fieldId:c,width:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{viewIds:[s],fieldIds:[c]}))return!1;let d=u.getSnapshot().tables[o].fields[c];if(d.system===!0||d.type===t.BaseFieldType.RecordId)return!1;let f=n.get(t.ICommandService),p=n.get(t.IUndoRedoService),h=u.getSnapshot(),g=new m,_=g.setViewFieldWidth(h,o,s,c,l),{undo:v,redo:y}=g.getViewFieldSettingHistory(h,o,s,c,{width:l}),b={unitId:a,op:y},x={unitId:a,op:v};return f.syncExecuteCommand(e.s.id,{unitId:a,op:_})?(i.focusUnit(a),p.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:x}],redoMutations:[{id:e.s.id,params:b}]}),!0):!1}},$t={id:`base.command.set-base-view-filter`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,filter:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE),u=(c==null?void 0:c.conditions.map(e=>e.fieldId))??[];if(!l||!H(l,o,{viewIds:[s],fieldIds:u}))return!1;let d=n.get(t.ICommandService),f=n.get(t.IUndoRedoService),p=l.getSnapshot(),h=new m().setViewFilter(p,o,s,c),g=new e.j().invertOp(p,h),_={unitId:a,op:h},v={unitId:a,op:g};return d.syncExecuteCommand(e.s.id,_)?(i.focusUnit(a),f.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:v}],redoMutations:[{id:e.s.id,params:_}]}),!0):!1}},en={id:`base.command.set-base-view-group`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,group:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{viewIds:[s],fieldIds:c.map(e=>e.fieldId)}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=new m().setViewGroup(f,o,s,c),h=new e.j().invertOp(f,p),g={unitId:a,op:p},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},tn={id:`base.command.set-base-view-sort`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,sort:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{viewIds:[s],fieldIds:c.map(e=>e.fieldId)}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=new m().setViewSort(f,o,s,c),h=new e.j().invertOp(f,p),g={unitId:a,op:p},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},nn={id:`base.command.update-base-cell`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,recordId:s,fieldId:c,value:l}=r,u=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!u||!H(u,o,{recordIds:[s],fieldIds:[c]})||!W(u,o,c,l))return!1;let d=u.getSnapshot().tables[o],f=e.et(d,c)&&e.X(d).includes(c),p=f?e.J(d,c):null,m=(p==null?void 0:p.parentByRecordId.get(s))??null,h=f?e.ut(l)[0]??null:null;if(p){if(h&&!d.records[h])throw new e.K(`missingRecord`);let n=e.rt(p,s,h);if(!n.valid){let r=n.reason===t.BaseHierarchyInvalidReason.SelfParent?`selfParent`:n.reason===t.BaseHierarchyInvalidReason.Cycle?`cycle`:`maxDepth`;throw new e.K(r)}}let g=n.get(t.ICommandService),_=n.get(t.IUndoRedoService),v=n.get(R),y;try{y=v.createUpdateCellOp(u,o,s,c,l)}catch(e){return console.error(`Failed to create update cell operation:`,e),!1}let b=new e.j().invertOp(u.getSnapshot(),y),x=f&&m!==h?[{tableId:o,fieldId:c,recordId:s,oldParentRecordId:m,parentRecordId:h}]:void 0,S={unitId:a,op:y,trigger:x?nn.id:void 0,hierarchyChanges:x,source:x?r.source??`ui`:void 0},C={...S,source:x?`redo`:void 0},w={unitId:a,op:b,trigger:x?nn.id:void 0,hierarchyChanges:x==null?void 0:x.map(e=>({...e,oldParentRecordId:e.parentRecordId,parentRecordId:e.oldParentRecordId})),source:x?`undo`:void 0};return g.syncExecuteCommand(e.s.id,S)?(i.getFocusedUnit()||i.focusUnit(a),_.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:w}],redoMutations:[{id:e.s.id,params:C}]}),!0):!1}},rn={id:`base.command.update-base-field-description`,type:t.CommandType.COMMAND,handler(n,r){if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s}=r,c=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!c||!H(c,o,{fieldIds:[s]}))return!1;let l=n.get(t.ICommandService),u=n.get(t.IUndoRedoService),d=c.getSnapshot(),f=r.description.trim(),p=new m().updateField(d,o,s,{description:f}),h=new e.j().invertOp(c.getSnapshot(),p),g={unitId:a,op:p},_={unitId:a,op:h};return l.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),u.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},an={id:`base.command.update-base-field`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,fieldId:s,patch:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||s===t.BASE_RECORD_ID_FIELD_ID||!H(l,o,{fieldIds:[s]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot();if(!U(l,o,{...f.tables[o].fields[s],...c}))return!1;let p=new m().updateField(f,o,s,c,r.textOptionIds),h=new e.j().invertOp(f,p),g={unitId:a,op:p},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},on={id:`base.command.update-base-kanban-config`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,patch:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{viewIds:[s]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=new m().updateViewConfig(f,o,s,c),h=new e.j().invertOp(f,p),g={unitId:a,op:p},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},sn={id:`base.command.update-base-record-order`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,recordId:s,orderKey:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{recordIds:[s]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=new m().updateRecordOrder(f,o,s,c),h=new e.j().invertOp(f,p),g={unitId:a,op:p},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}};let cn=/* @__PURE__ */ function(e){return e.Set=`set`,e.Add=`add`,e.Delete=`delete`,e.Clear=`clear`,e}({});const ln={id:`base.command.update-base-view-conditional-color-rules`,type:t.CommandType.COMMAND,handler:(n,r)=>{var i;if(!r)return!1;let a=n.get(t.IUniverInstanceService),o=a.getUnit(r.unitId,t.UniverInstanceType.UNIVER_BASE);if(!o||!H(o,r.tableId,{viewIds:[r.viewId]}))return!1;let s=o.getSnapshot(),c=s.tables[r.tableId],l=un(((i=c.views[r.viewId].config.conditionalColoring)==null?void 0:i.rules)??[],r);if(!l)return!1;dn(c,l);let u=new m().updateViewConfig(s,r.tableId,r.viewId,{conditionalColoring:l.length?{rules:l}:null}),d=new e.j().invertOp(s,u),f={unitId:r.unitId,op:u},p={unitId:r.unitId,op:d};return n.get(t.ICommandService).syncExecuteCommand(e.s.id,f)?(a.focusUnit(r.unitId),n.get(t.IUndoRedoService).pushUndoRedo({unitID:r.unitId,undoMutations:[{id:e.s.id,params:p}],redoMutations:[{id:e.s.id,params:f}]}),!0):!1}};function un(e,n){switch(n.type){case`set`:return t.Tools.deepClone(n.rules);case`add`:return[...t.Tools.deepClone(e),t.Tools.deepClone(n.rule)];case`delete`:{let r=e.filter(e=>e.id!==n.ruleId);return r.length===e.length?null:t.Tools.deepClone(r)}case`clear`:return e.length?[]:null}}function dn(e,t){if(!Array.isArray(t))throw TypeError(`[UpdateBaseViewConditionalColorRulesCommand]: rules must be an array.`);let n=/* @__PURE__ */ new Set;for(let[r,i]of t.entries())pn(e,i,fn(i,r,n))}function fn(e,n,r){if(!e||typeof e!=`object`)throw TypeError(`[UpdateBaseViewConditionalColorRulesCommand]: rule at index ${n} must be an object.`);let i=typeof e.id==`string`&&e.id.trim()?`"${e.id}"`:`at index ${n}`;if(typeof e.id!=`string`||!e.id.trim())throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} must have a non-empty id.`);if(r.has(e.id))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: duplicate rule id "${e.id}".`);r.add(e.id);let a=typeof e.color==`string`&&e.color.trim()?new t.ColorKit(e.color):null;if(!(a!=null&&a.isValid))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} must have a valid CSS color.`);return i}function pn(n,r,i){let a=new Set(Object.values(t.BaseConditionalColorTarget)),o=new Set(Object.values(t.BaseConditionalColorOperator)),s=new Set(Object.values(t.BaseConditionalDateMode));if(!a.has(r.target))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} has unsupported target "${String(r.target)}".`);let c=typeof r.fieldId==`string`?n.fields[r.fieldId]:void 0;if(!c||c.system===!0||c.type===t.BaseFieldType.RecordId)throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} references missing or non-public field "${String(r.fieldId)}".`);if(!o.has(r.operator))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} has unsupported operator "${String(r.operator)}".`);if(r.dateMode!==void 0&&!s.has(r.dateMode))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} has unsupported date mode "${String(r.dateMode)}".`);if(r.target===t.BaseConditionalColorTarget.COLUMN)return;let l=e.S(c.type);if(!l.includes(r.operator))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} cannot use operator "${r.operator}" with field type "${c.type}". Allowed operators: ${l.join(`, `)}.`);if(r.dateMode!==void 0&&!e.C(c.type))throw Error(`[UpdateBaseViewConditionalColorRulesCommand]: rule ${i} can use dateMode only with Date, CreatedAt, or UpdatedAt fields.`)}const mn={id:`base.command.update-base-view-config`,type:t.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;let i=n.get(t.IUniverInstanceService),{unitId:a,tableId:o,viewId:s,patch:c}=r,l=i.getUnit(a,t.UniverInstanceType.UNIVER_BASE);if(!l||!H(l,o,{viewIds:[s]}))return!1;let u=n.get(t.ICommandService),d=n.get(t.IUndoRedoService),f=l.getSnapshot(),p=new m().updateViewConfig(f,o,s,c),h=new e.j().invertOp(f,p),g={unitId:a,op:p},_={unitId:a,op:h};return u.syncExecuteCommand(e.s.id,g)?(i.focusUnit(a),d.pushUndoRedo({unitID:a,undoMutations:[{id:e.s.id,params:_}],redoMutations:[{id:e.s.id,params:g}]}),!0):!1}},hn={id:`base.command.validate-formula`,type:t.CommandType.COMMAND,handler(e,n){if(!n)return{valid:!1,reason:`[BaseFormula]: validation parameters are required.`};let r=e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_BASE),i=r==null?void 0:r.getSnapshot(),a=i==null?void 0:i.tables[n.tableId];return!i||!a?{valid:!1,reason:`[BaseFormula]: table does not exist.`}:new B().validateFormula(n.formula,a,{snapshot:i})}};let J=class extends t.ObjectPermissionRuleModel{constructor(e){super(e,`BASE_OBJECT_PERMISSION_PLUGIN`,t.UniverInstanceType.UNIVER_BASE,[r.UnitObject.BaseTable,r.UnitObject.BaseField,r.UnitObject.BaseRecord,r.UnitObject.BaseView,r.UnitObject.BaseDashboard])}};J=e.g([e._(0,t.IResourceManagerService)],J);const gn={id:`base.mutation.set-permission-rule`,type:t.CommandType.MUTATION,handler:(e,n)=>!n||!e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_BASE)?!1:e.get(J).setRule(n.unitId,n.objectType,n.objectId,n.rule)},_n={id:`base.mutation.set-permission-rules`,type:t.CommandType.MUTATION,handler:(e,n)=>!n||!e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_BASE)?!1:e.get(J).setRules(n.unitId,n.rules)};function vn(e){let n=e.now??Date.now(),r=e.primaryFieldId??`${e.id}-field-name`,i=e.gridViewId??`${e.id}-view-grid`,a=e.recordCount??0,o=(0,t.createBaseRecordIdField)(),s={id:r,name:e.primaryFieldName??`Name`,type:t.BaseFieldType.Text,config:{placeholder:`bases.fieldConfig.textPlaceholder`}},c={},l=[],u={},d={},f={};for(let i=0;i<a;i++){let a=`${e.id}-record-${i+1}`;c[a]={id:a,values:{[t.BASE_RECORD_ID_FIELD_ID]:a,...e.recordNamePrefix?{[r]:`${e.recordNamePrefix} ${i+1}`}:{}},orderKey:String(i+1).padStart(4,`0`),createdAt:n,updatedAt:n},l.push(a),u[a]=i,d[i]=a,f[i]={0:{v:a,t:t.CellValueType.STRING}},e.recordNamePrefix&&(f[i][1]={v:`${e.recordNamePrefix} ${i+1}`,t:t.CellValueType.STRING})}let p={id:i,tableId:e.id,name:`Grid`,type:t.BaseViewType.Grid,fieldOrder:[t.BASE_RECORD_ID_FIELD_ID,r],fieldSettings:{[t.BASE_RECORD_ID_FIELD_ID]:{hidden:!0}},config:{frozenFieldCount:1}};return{id:e.id,name:e.name,primaryFieldId:r,fieldOrder:[t.BASE_RECORD_ID_FIELD_ID,r],fields:{[t.BASE_RECORD_ID_FIELD_ID]:o,[r]:s},records:c,recordOrder:l,rowIndex:u,rowId:d,colIndex:{[t.BASE_RECORD_ID_FIELD_ID]:0,[r]:1},colId:{0:t.BASE_RECORD_ID_FIELD_ID,1:r},cellData:f,views:{[i]:p},viewOrder:[i]}}const yn=`UNIVER_EMBED_BASES_TABLE`;function bn(e){let t=vn({id:e.hostAnchorId,name:e.name??e.embedId,recordCount:0});return{...t,resources:{...t.resources??{},[yn]:Cn(e)}}}function xn(n){return{id:e.s.id,params:{unitId:n.unitId,op:t.JSON1.type.compose(t.JSON1.insertOp([`tables`,n.table.id],n.table),t.JSON1.insertOp([`tableOrder`,n.index??n.snapshot.tableOrder.length],n.table.id)),trigger:`embed-ui`}}}function Sn(n){let r=n.snapshot.tableOrder.indexOf(n.tableId);if(!(!n.snapshot.tables[n.tableId]||r<0))return{id:e.s.id,params:{unitId:n.unitId,op:t.JSON1.type.compose(t.JSON1.removeOp([`tables`,n.tableId],n.snapshot.tables[n.tableId]),t.JSON1.removeOp([`tableOrder`,r],n.tableId)),trigger:`embed-ui`}}}function Cn(e){return{version:1,embedId:e.embedId,hostAnchorId:e.hostAnchorId,childUnitId:e.childUnitId,childType:e.childType}}function wn(e){let t=Math.max(0,Number(e.decimalPlaces??0)),n=e.useThousands===!1?`0`:`#,##0`,r=t?`.${`0`.repeat(t)}`:``,i=En(e.abbreviation);return`${e.currencySymbol?Dn(e.currencySymbol):``}${n}${r}${i}`}function Tn(e,n){let r=wn(n),i=t.numfmt.format(r,e,{throws:!1});return On(String(i),n.separatorStyle,n.locale)}function En(e){return e===`K`?`,"K"`:e===`M`?`,,"M"`:e===`B`?`,,,"B"`:``}function Dn(e){return/^[A-Z]+$/i.test(e)?`"${e}"`:e}function On(e,t,n){let r=t===`local`?kn(n):t;return r===`periodComma`?e.replace(/,/g,`\0`).replace(/\./g,`,`).replace(/\0/g,`.`):r===`spaceComma`?e.replace(/,/g,` `).replace(/\./g,`,`):r===`spacePeriod`?e.replace(/,/g,` `):e}function kn(e){var t,n;let r=e||new Intl.NumberFormat().resolvedOptions().locale,i;try{i=new Intl.NumberFormat(r,{minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:!0}).formatToParts(1e6)}catch{return`commaPeriod`}let a=(t=i.find(e=>e.type===`group`))==null?void 0:t.value,o=(n=i.find(e=>e.type===`decimal`))==null?void 0:n.value,s=a===`\xA0`||a===` `?` `:a;return s===`.`&&o===`,`?`periodComma`:s===` `&&o===`,`?`spaceComma`:s===` `&&o===`.`?`spacePeriod`:`commaPeriod`}const An=[`count`,`filled`,`empty`,`unique`,`sum`,`average`,`min`,`max`],jn=[`count`,`filled`,`empty`,`unique`],Mn=[`sum`,`average`,`min`,`max`],Nn=[`min`,`max`],Pn=/* @__PURE__ */ new Set([t.BaseFieldType.Number,t.BaseFieldType.Currency,t.BaseFieldType.Progress,t.BaseFieldType.Rating]),Fn=/* @__PURE__ */ new Set([t.BaseFieldType.MultiSelect,t.BaseFieldType.Person,t.BaseFieldType.Group]),In=`General`;function Ln(e){return typeof e==`string`&&An.includes(e)}function Rn(e){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(e=>Ln(e[1])))}function zn(e){return Pn.has(e.type)?[...jn,...Mn]:e.type===t.BaseFieldType.Formula?[...jn,...er(e)===`date`?Nn:Mn]:jn}function Bn(e,t){return zn(e).includes(t)}function Vn(e,t,n){if(!Bn(e,n))return null;let r=t.filter(t=>!Un(e,t));switch(n){case`count`:return t.length;case`filled`:return r.length;case`empty`:return t.length-r.length;case`unique`:return new Set(r.map(t=>qn(e,t))).size;case`sum`:{let t=Wn(e,r);return t.length?Kn(t):null}case`average`:{let t=Wn(e,r);return t.length?Kn(t)/t.length:null}case`min`:{let t=Wn(e,r);return t.length?Math.min(...t):null}case`max`:{let t=Wn(e,r);return t.length?Math.max(...t):null}}}function Hn(n,r,i){if(i==null||!Number.isFinite(i))return`-`;if(jn.includes(r))return String(i);switch(n.type){case t.BaseFieldType.Number:return Tn(i,Zn(n));case t.BaseFieldType.Currency:return Tn(i,Qn(n));case t.BaseFieldType.Progress:return e.p(i,n.config);case t.BaseFieldType.Formula:return $n(i,n);default:return nr(i)}}function Un(e,n){if(n==null)return!0;if(typeof n==`string`)return n.trim()===``;if(Array.isArray(n))return e.type===t.BaseFieldType.Attachment?!n.some(Xn):n.length===0;if(e.type===t.BaseFieldType.Link&&typeof n==`object`){let e=n;return[e.text,e.url].every(e=>e==null||String(e).trim()===``)}return!1}function Wn(e,t){let n=[];for(let r of t){let t=Gn(e,r);t!=null&&n.push(t)}return n}function Gn(e,n){if(typeof n==`number`)return Number.isFinite(n)?n:null;if(e.type!==t.BaseFieldType.Formula&&typeof n==`string`&&n.trim()!==``){let e=Number(n);return Number.isFinite(e)?e:null}return null}function Kn(e){let t=0,n=0;for(let r of e){let e=t+r;n+=Math.abs(t)>=Math.abs(r)?t-e+r:r-e+t,t=e}return t+n}function qn(e,t){return Fn.has(e.type)&&Array.isArray(t)?Yn([...new Set(t.map(e=>Yn(Jn(e))))].sort()):Yn(Jn(t))}function Jn(e){return Array.isArray(e)?e.map(Jn):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Jn(t)])):e}function Yn(e){return JSON.stringify(e)??`undefined`}function Xn(e){if(typeof e==`string`)return e.trim()!==``;if(!e||typeof e!=`object`)return!1;let t=e;return[t.id,t.name,t.source,t.url,t.thumbnail].some(e=>e!=null&&String(e).trim()!==``)}function Zn(e){let t=Y(e.config);return{decimalPlaces:ir(t.decimalPlaces,0,20,2),separatorStyle:typeof t.separatorStyle==`string`?t.separatorStyle:`local`,locale:typeof t.locale==`string`?t.locale:void 0,useThousands:t.useThousands!==!1,abbreviation:typeof t.abbreviation==`string`?t.abbreviation:`none`}}function Qn(e){let t=Y(e.config);return{...Zn(e),currencySymbol:String(t.currencySymbol??`$`)}}function $n(e,n){let r=tr(n);if(r===In)return nr(e);try{return String(t.numfmt.format(r,e,{throws:!1}))}catch{return nr(e)}}function er(e){let t=Y(Y(e.config).numfmt);return typeof t.type==`string`?t.type:`general`}function tr(e){let t=Y(Y(e.config).numfmt);return String(t.pattern??In).trim()||In}function nr(e){return String(Number.isInteger(e)?e:Math.round((e+2**-52)*100)/100)}function Y(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function rr(e){if(e==null||e===``)return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null}function ir(e,t,n,r){let i=rr(e);return i==null?r:Math.max(t,Math.min(n,Math.round(i)))}function ar(e,n){let r=t.Tools.deepClone(e),i=n.includeRecords===!0,a=/* @__PURE__ */ new Map,o=n.createViewId??(()=>`view-${(0,t.generateRandomId)(8)}`),s=r.viewOrder;return n.regenerateViewIds&&(s=r.viewOrder.map(e=>{let t=o();return a.set(e,t),t})),{...r,id:n.id,name:n.name,records:i?r.records:{},recordOrder:i?r.recordOrder:[],rowIndex:i?r.rowIndex:{},rowId:i?r.rowId:{},cellData:i?r.cellData:{},resources:i?r.resources:{},viewOrder:s,views:Object.fromEntries(Object.entries(r.views??{}).map(([e,t])=>{let r=a.get(e)??(n.regenerateViewIds?o():e);return[r,{...t,id:r,tableId:n.id}]}))}}function or(t){return new e.j().getAffectedRanges(t)}function sr(e){return e.patches.map(t=>({unitId:e.unitId,sheetId:e.tableId,range:{startRow:t.row,endRow:t.row,startColumn:t.col,endColumn:t.col}}))}function cr(e,t){return{[e]:Object.fromEntries(t.map(e=>[e,`1`]))}}let X=class extends t.Disposable{constructor(e,t){super(),this._activeDirtyManagerService=e,this._univerInstanceService=t,this._initialize()}_initialize(){this._activeDirtyManagerService.register(e.s.id,{commandId:e.s.id,getDirtyData:e=>this._getJson1DirtyData(e.params)}),this.disposeWithMe((0,t.toDisposable)(()=>{this._activeDirtyManagerService.remove(e.s.id)}))}_getTable(e,n){let r=this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_BASE);return(r==null?void 0:r.getSnapshot().tables[n])??null}_getJson1DirtyData(e){if(e.trigger===`formula.mutation.set-formula-calculation-result`)return{};if(!e.unitId||!e.op)return{clearDependencyTreeCache:this._getAllBaseDependencyTreeCacheMap(),forceCalculation:!0};let t=or(e.op),n=this._getStructureDirtyTableIds(e.unitId,t);if(n.length)return{clearDependencyTreeCache:cr(e.unitId,n),forceCalculation:!0};let r=Object.entries(this._groupCellInvalidations(e.unitId,t)).flatMap(([t,n])=>sr({unitId:e.unitId,tableId:t,patches:n}));return r.length?{dirtyRanges:r}:{}}_getStructureDirtyTableIds(e,t){let n=t.filter(e=>e.reason!==`cell`).flatMap(t=>t.tableId?[t.tableId]:this._getAllTableIds(e));return Array.from(new Set(n))}_groupCellInvalidations(e,t){let n=/* @__PURE__ */ new Set;return t.reduce((t,r)=>{let i=this._toDirtyRangePatch(e,r);if(!i)return t;let a=`${r.tableId}:${i.row}:${i.col}`;return n.has(a)||(n.add(a),t[r.tableId]=t[r.tableId]??[],t[r.tableId].push(i)),t},{})}_toDirtyRangePatch(t,n){if(n.reason!==`cell`)return null;if(n.row!=null&&n.column!=null)return{row:n.row,col:n.column,value:null};if(!n.recordId||!n.fieldId)return null;let r=this._getTable(t,n.tableId);if(!r)return null;let i=e.L(r,n.recordId,n.fieldId);return i?{row:i.row,col:i.col,value:null}:null}_getAllTableIds(e){let n=this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_BASE);return Object.values((n==null?void 0:n.getSnapshot().tables)??{}).map(e=>e.id)}_getAllBaseDependencyTreeCacheMap(){let e=this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).map(e=>cr(e.getUnitId(),Object.keys(e.getSnapshot().tables)));return Object.assign({},...e)}};X=e.g([e._(0,n.IActiveDirtyManagerService),e._(1,t.IUniverInstanceService)],X);let lr=class extends t.Disposable{constructor(t,n,r,i){super(),this._commandService=t,this._univerInstanceService=n,this._formulaCalculationTriggerService=r,this._formulaCalculationSessionService=i,e.b(this,`_formulaService`,new B),e.b(this,`_registeredSuperTableNames`,/* @__PURE__ */ new Map),e.b(this,`_scheduledSuperTableSyncs`,/* @__PURE__ */ new Set),e.b(this,`_formulaSyncQueue`,Promise.resolve()),e.b(this,`_applyingFormulaResults`,!1),this._initialize()}_initialize(){this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).forEach(e=>{this._scheduleSuperTableSync(e)}),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(t.UniverInstanceType.UNIVER_BASE).subscribe(({unit:e})=>{this._scheduleSuperTableSync(e)})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(t.UniverInstanceType.UNIVER_BASE).subscribe(e=>{this._enqueueFormulaSync(()=>this._removeSuperTables(e.getUnitId()))})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>this._onCommandExecuted(e)))}_onCommandExecuted(r){if(r.id===n.SetFormulaCalculationResultMutation.id){dr(r.params)&&this._applyFormulaResult(r.params);return}if(this._applyingFormulaResults||r.id!==e.s.id)return;let i=ur(r.params)?r.params:void 0,a=i!=null&&i.unitId?[this._univerInstanceService.getUnit(i.unitId,t.UniverInstanceType.UNIVER_BASE)].filter(e=>!!e):this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE),o=i==null?void 0:i.op;a.forEach(e=>{let t=o?or(o):[];(!o||t.some(e=>e.reason!==`cell`))&&this._scheduleSuperTableSync(e)})}_scheduleSuperTableSync(e){let t=e.getUnitId();this._scheduledSuperTableSyncs.has(t)||(this._scheduledSuperTableSyncs.add(t),this._enqueueFormulaSync(async()=>{this._scheduledSuperTableSyncs.delete(t),await this._syncSuperTables(e)}))}async _syncSuperTables(e){let t=e.getUnitId(),r=this._formulaService.getSuperTableRegistrations(e.getSnapshot()),i=new Set(r.map(({tableName:e})=>e)),a=this._registeredSuperTableNames.get(t)??/* @__PURE__ */ new Set;for(let e of a)if(!i.has(e)&&!await this._executeSuperTableMutationWhileActive(n.RemoveSuperTableMutation.id,{unitId:t,tableName:e}))return;for(let{tableName:e,reference:i}of r)if(!await this._executeSuperTableMutationWhileActive(n.SetSuperTableMutation.id,{unitId:t,tableName:e,reference:i}))return;this._registeredSuperTableNames.set(t,i)}async _removeSuperTables(e){let t=this._registeredSuperTableNames.get(e)??/* @__PURE__ */ new Set;for(let r of t)if(!await this._executeSuperTableMutationWhileActive(n.RemoveSuperTableMutation.id,{unitId:e,tableName:r}))return;this._registeredSuperTableNames.delete(e)}async _executeSuperTableMutationWhileActive(e,t){return!this._disposed&&await this._commandService.executeCommand(e,t,{onlyLocal:!0})&&!this._disposed}_enqueueFormulaSync(e){this._formulaSyncQueue=this._formulaSyncQueue.then(e,e).catch(()=>void 0)}_applyFormulaResult(r){let i=this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE);if(!i.some(e=>{var t;return((t=r.unitData)==null?void 0:t[e.getUnitId()])!=null}))return;let a=i.flatMap(e=>Pe(e.getSnapshot(),r));if(!a.length){this._formulaCalculationSessionService.markResultApplied(n.FormulaResultApplicationType.BASE,r);return}let o=new m,s=a.flatMap(e=>sr({unitId:e.unitId,tableId:e.tableId,patches:e.patches}));this._applyingFormulaResults=!0,(async()=>{for(let r of a){let i=this._univerInstanceService.getUnit(r.unitId,t.UniverInstanceType.UNIVER_BASE);i&&await this._commandService.executeCommand(e.s.id,{unitId:r.unitId,op:o.setRangeValues(i.getSnapshot(),r.tableId,r.patches),trigger:n.SetFormulaCalculationResultMutation.id},{onlyLocal:!0})}await this._commandService.executeCommand(n.SetTriggerFormulaCalculationStartMutation.id,{dirtyRanges:s},{onlyLocal:!0})})().finally(()=>{this._applyingFormulaResults=!1,this._formulaCalculationSessionService.markResultApplied(n.FormulaResultApplicationType.BASE,r)})}};lr=e.g([e._(0,t.ICommandService),e._(1,t.IUniverInstanceService),e._(2,(0,t.Inject)(n.FormulaCalculationTriggerService)),e._(3,(0,t.Inject)(n.FormulaCalculationSessionService))],lr);function ur(e){return typeof e==`object`&&!!e&&`unitId`in e&&typeof e.unitId==`string`&&`op`in e&&Array.isArray(e.op)}function dr(e){return typeof e==`object`&&!!e&&`unitData`in e&&`unitOtherData`in e}const fr=/* @__PURE__ */ new Set([Gt.id,Kt.id,hn.id]);let pr=class extends t.Disposable{constructor(e,n,r,i){super(),this._injector=e,this._commandService=n,this._permissionService=r,this._instanceService=i,this._instanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).forEach(e=>this._registerUnitPermissionPoints(e.getUnitId())),this.disposeWithMe(this._instanceService.getTypeOfUnitAdded$(t.UniverInstanceType.UNIVER_BASE).subscribe(({unit:e})=>this._registerUnitPermissionPoints(e.getUnitId()))),this.disposeWithMe(this._commandService.beforeCommandExecuted((e,t)=>this._check(e,t))),this.disposeWithMe(this._instanceService.getTypeOfUnitDisposed$(t.UniverInstanceType.UNIVER_BASE).subscribe(e=>{this._injector.get(t.ObjectPermissionService).clearUnit(e.getUnitId()),_e(this._permissionService,e.getUnitId())}))}_registerUnitPermissionPoints(e){k.forEach(t=>{let n=P(e,e,t);this._permissionService.getPermissionPoint(n.id)||this._permissionService.addPermissionPoint(n)}),this._injector.get(t.ObjectPermissionService).initializeUnit({unitId:e,objectId:e,objectType:r.UnitObject.Base})}_check(e,i){var a;if(i!=null&&i.fromCollab||i!=null&&i.fromChangeset)return;let o=Tr(e.params)?e.params:void 0;if(i!=null&&i.onlyLocal&&e.id===`base.mutation.apply-base-json1`&&(o==null?void 0:o.trigger)===n.SetFormulaCalculationResultMutation.id)return;let s=hr(e.id),c=mr(o==null?void 0:o.unitId,i)??(s?(a=this._instanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_BASE))==null?void 0:a.getUnitId():void 0);if(!c||this._instanceService.getUnitType(c)!==t.UniverInstanceType.UNIVER_BASE)return;if(s){if(!F(this._permissionService,c,c,s))throw this._injector.get(t.ErrorService).emitPermissionDenied(c),new t.CustomCommandExecutionError(`Base ${r.UnitAction[s]} permission denied.`);return}if(fr.has(e.id)||!e.id.startsWith(`base.command.`)&&!e.id.startsWith(`base.mutation.`))return;let l=this._instanceService.getUnit(c,t.UniverInstanceType.UNIVER_BASE),u=l?gr(l,o??{},e.id):[];if(!l||!ve(this._permissionService,c,u))throw this._injector.get(t.ErrorService).emitPermissionDenied(c,u),new t.CustomCommandExecutionError(`Base edit permission denied.`)}};pr=e.g([e._(0,(0,t.Inject)(t.Injector)),e._(1,t.ICommandService),e._(2,t.IPermissionService),e._(3,t.IUniverInstanceService)],pr);function mr(e,t){return typeof e==`string`?e:typeof(t==null?void 0:t.unitId)==`string`?t.unitId:void 0}function hr(e){if(e===`bases-exchange-client.operation.export-base`||e===`bases-exchange-client.operation.export-base-by-format`)return r.UnitAction.Export;if(e.startsWith(`thread-comment.command.`)||e.startsWith(`thread-comment.mutation.`))return r.UnitAction.Comment}function gr(e,t,n){if(n===`base.mutation.apply-base-json1`&&wr(t.op))return _r(e,t.op);let r=/* @__PURE__ */ new Set,i=xr(t,`table`),a=typeof t.tableId==`string`?t.tableId:i[0];if(i.forEach(e=>r.add(A(e))),!a)return[...r];let o=e.getSnapshot().tables[a],s=new Set(xr(t,`field`)),c=new Set(xr(t,`record`)),l=new Set(xr(t,`view`));return Sr(o,t.patches,c,s),Cr(t,s),s.forEach(e=>r.add(j(a,e))),c.forEach(e=>r.add(M(a,e))),l.forEach(e=>r.add(N(a,e))),[...r]}function _r(t,n){let r=t.getSnapshot(),i=new e.j().getAffectedRanges(n),a=vr(n),o=/* @__PURE__ */ new Set;return i.forEach(e=>{var t,n;let{tableId:i}=e;if(!i)return;o.add(A(i));let s=r.tables[i],c=e.recordId??(e.row==null||s==null||(t=s.rowId)==null?void 0:t[e.row]),l=e.fieldId??(e.column==null||s==null||(n=s.colId)==null?void 0:n[e.column]);c&&o.add(M(i,c)),l&&o.add(j(i,l)),e.viewId&&o.add(N(i,e.viewId)),(e.reason===`table`||a.has(i))&&s&&(Object.keys(s.fields).forEach(e=>o.add(j(i,e))),Object.keys(s.records).forEach(e=>o.add(M(i,e))),Object.keys(s.views).forEach(e=>o.add(N(i,e)))),e.reason===`record`&&s&&Object.keys(s.fields).forEach(e=>o.add(j(i,e)))}),i.length===0&&br(n,`tableOrder`)&&Object.keys(r.tables).forEach(e=>o.add(A(e))),[...o]}function vr(e){let t=/* @__PURE__ */ new Set,n=e=>{Array.isArray(e)&&e.forEach((r,i)=>{r===`tables`&&typeof e[i+1]==`string`&&yr(e[i+2])&&t.add(e[i+1]),n(r)})};return n(e),t}function yr(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&(`i`in e||`r`in e||`p`in e||`d`in e||`es`in e||`ena`in e||`et`in e)}function br(e,t){return Array.isArray(e)&&e.some(e=>e===t||br(e,t))}function xr(e,t){let n=/* @__PURE__ */ new Set,r=`${t}Id`,i=`${t}Ids`,a=(e,o=``)=>{typeof e==`string`?o===r&&n.add(e):Array.isArray(e)?o===i?e.forEach(e=>{typeof e==`string`&&n.add(e)}):e.forEach(e=>a(e,o)):Tr(e)&&Object.entries(e).forEach(([e,r])=>{e===`id`&&o===t&&typeof r==`string`?n.add(r):a(r,e)})};return a(e),[...n]}function Sr(e,t,n,r){e&&Array.isArray(t)&&t.forEach(t=>{if(!Tr(t))return;let i=t;if(typeof i.row==`number`){var a;let t=(a=e.rowId)==null?void 0:a[i.row];t&&n.add(t)}if(typeof i.col==`number`){var o;let t=(o=e.colId)==null?void 0:o[i.col];t&&r.add(t)}})}function Cr(e,t,n=``){e&&typeof e==`object`&&(Array.isArray(e)?e.forEach(e=>Cr(e,t,n)):Tr(e)&&Object.entries(e).forEach(([e,r])=>{n===`values`&&t.add(e),Cr(r,t,e)}))}function wr(e){return Array.isArray(e)}function Tr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Er=(0,t.createIdentifier)(`base.resource.service`);let Dr=class{constructor(e){this._univerInstanceService=e}getBase(e){return this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_BASE)??null}getAllBases(){return this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE)}createBase(e){return this._univerInstanceService.createUnit(t.UniverInstanceType.UNIVER_BASE,e)}};Dr=e.g([e._(0,t.IUniverInstanceService)],Dr);const Or=(0,t.createIdentifier)(`base.view-registry.service`);var kr=class extends t.Disposable{constructor(...t){super(...t),e.b(this,`_plugins`,/* @__PURE__ */ new Map)}register(e){return this._plugins.set(e.type,e),(0,t.toDisposable)(()=>this._plugins.delete(e.type))}get(e){let t=this._plugins.get(e);if(!t)throw Error(`[BaseViewRegistryService]: view type "${e}" is not registered.`);return t}getAll(){return Array.from(this._plugins.values())}};const Ar=[e.s];let Z=class extends t.Plugin{constructor(n=e.r,r,i,a,o,s){super(),this._config=n,this._injector=r,this._commandService=i,this._univerInstanceService=a,this._configService=o,this._dataSyncPrimaryController=s,e.b(this,`_baseSyncDisposables`,/* @__PURE__ */ new Map);let{...c}=(0,t.merge)({},e.r,this._config);this._configService.setConfig(e.t,c),this._univerInstanceService.registerCtorForType(t.UniverInstanceType.UNIVER_BASE,t.BaseDataModel),this._initDependencies(),this._initCommands(),this._initRegistries(),this._initDataSync()}onStarting(){this._injector.add([J]),this.disposeWithMe(this._injector.get(t.ICommandService).registerCommand(gn)),this.disposeWithMe(this._injector.get(t.ICommandService).registerCommand(_n)),this.disposeWithMe(this._injector.get(t.ObjectPermissionService).registerRuleModel(r.UnitObject.Base,this._injector.get(J),gn.id,_n.id))}onReady(){(0,t.touchDependencies)(this._injector,[[Dr],[z],[X]]),this._univerInstanceService.getAllUnitsForType(t.UniverInstanceType.UNIVER_BASE).forEach(e=>this._syncBaseUnit(e.getUnitId())),(0,t.touchDependencies)(this._injector,[[lr],[pr]])}_initDependencies(){[[e.y,{useClass:e.v}],[Or,{useClass:kr}],[e.u,{useClass:e.l}],[Er,{useClass:Dr}],[ye,{useClass:be}],[R,{useClass:z}],[X],[lr],[pr]].forEach(e=>this._injector.add(e))}_initCommands(){[ut,Vt,Ot,nn,G,et,tt,Jt,ct,K,it,Dt,at,jt,sn,It,st,At,an,rn,ot,Et,Ft,hn,Tt,Mt,Ht,Wt,kt,Bt,mn,ln,Ut,Gt,Kt,on,$t,tn,en,Yt,Zt,Qt,Xt,...Ar].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e))),Ar.forEach(e=>{var t;return(t=this._dataSyncPrimaryController)==null?void 0:t.registerSyncingMutations(e)})}_initDataSync(){this._dataSyncPrimaryController&&(this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(t.UniverInstanceType.UNIVER_BASE).subscribe(({unit:e})=>{this._syncBaseUnit(e.getUnitId())})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(t.UniverInstanceType.UNIVER_BASE).subscribe(e=>{var t;(t=this._baseSyncDisposables.get(e.getUnitId()))==null||t.dispose(),this._baseSyncDisposables.delete(e.getUnitId())})))}_syncBaseUnit(e){this._dataSyncPrimaryController&&!this._baseSyncDisposables.has(e)&&this._baseSyncDisposables.set(e,this._dataSyncPrimaryController.syncUnit(e))}_initRegistries(){let t=this._injector.get(e.y);e.x().forEach(e=>t.register(e));let n=this._injector.get(Or),r=this._injector.get(e.u);e.f().forEach(e=>{n.register(e),r.registerView(e)})}};e.b(Z,`pluginName`,`BASES_PLUGIN`),e.b(Z,`packageName`,e.a),e.b(Z,`version`,e.o),e.b(Z,`type`,t.UniverInstanceType.UNIVER_BASE),Z=e.g([(0,t.DependentOn)(i.UniverLicensePlugin,n.UniverFormulaEnginePlugin),e._(1,(0,t.Inject)(t.Injector)),e._(2,t.ICommandService),e._(3,t.IUniverInstanceService),e._(4,t.IConfigService),e._(5,(0,t.Optional)(a.DataSyncPrimaryController))],Z);function jr(e){let t=Wr(e.query);if(!t)return{query:``,total:0,matches:[]};let n=[],r=[];for(let t=0;t<e.fieldIds.length;t++){if(!(t in e.fieldIds))continue;let n=e.table.fields[e.fieldIds[t]];n&&r.push({field:n,fieldIndex:t})}e.rows.forEach((e,i)=>{r.forEach(({field:r,fieldIndex:a})=>{let o=Mr(e.values[r.id],r);if(!o)return;let s=Ur(t,o.searchTexts);s<=0||n.push({recordId:e.recordId,fieldId:r.id,fieldType:r.type,text:o.displayText,score:s,rowIndex:i,fieldIndex:a})})}),n.sort((e,t)=>t.score-e.score||e.rowIndex-t.rowIndex||e.fieldIndex-t.fieldIndex);let i=e.limit==null?n:n.slice(0,Math.max(0,e.limit));return{query:t,total:n.length,matches:Kr(i)}}function Mr(e,t){let n=[];for(let r of Pr(e,t)){let e=Wr(r);e&&n.push(e)}return n.length?{displayText:Nr(e,t),searchTexts:Gr(n)}:null}function Nr(e,n){switch(n.type){case t.BaseFieldType.SingleSelect:case t.BaseFieldType.MultiSelect:case t.BaseFieldType.Group:return Fr(e,n).join(`, `);case t.BaseFieldType.Link:return Rr(e);case t.BaseFieldType.Date:case t.BaseFieldType.CreatedAt:case t.BaseFieldType.UpdatedAt:return zr(e,n);case t.BaseFieldType.Number:case t.BaseFieldType.Currency:return Br(e,n);case t.BaseFieldType.Progress:return Vr(e,n);case t.BaseFieldType.Checkbox:return e?`Checked`:`Unchecked`;case t.BaseFieldType.Attachment:return Hr(e).join(`, `);default:return Q(e)}}function Pr(e,n){switch(n.type){case t.BaseFieldType.SingleSelect:case t.BaseFieldType.MultiSelect:case t.BaseFieldType.Group:{let t=Fr(e,n);if(Array.isArray(e)){let n=[...t];for(let t=0;t<e.length;t++)t in e&&n.push(String(e[t]));return n}return e==null?t:[...t,String(e)]}case t.BaseFieldType.Link:{let t=Lr(e);return[t.text,t.url]}case t.BaseFieldType.Date:case t.BaseFieldType.CreatedAt:case t.BaseFieldType.UpdatedAt:return[zr(e,n),Q(e)];case t.BaseFieldType.Number:case t.BaseFieldType.Currency:return[Br(e,n),Q(e)];case t.BaseFieldType.Progress:return[Vr(e,n),Q(e)];case t.BaseFieldType.Checkbox:return e?[`Checked`,`Yes`,`True`]:[`Unchecked`,`No`,`False`];case t.BaseFieldType.Attachment:return Hr(e);default:return[Q(e)]}}function Fr(e,t){var n;let r=Array.isArray((n=t.config)==null?void 0:n.options)?t.config.options:[],i=[];if(Array.isArray(e)){for(let t=0;t<e.length;t++){if(!(t in e))continue;let n=String(e[t]);n&&i.push(Ir(r,n))}return i}if(e!=null){let t=String(e);t&&i.push(Ir(r,t))}return i}function Ir(e,t){for(let n of e){if(typeof n==`string`&&n===t)return n;if(n&&typeof n==`object`){let e=n;if(String(e.id??e.name??``)===t||String(e.name??``)===t)return String(e.name??e.id??t)}}return t}function Lr(e){if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e;return{text:String(t.text??t.url??``),url:String(t.url??``)}}return{text:Q(e),url:Q(e)}}function Rr(e){let t=Lr(e);return t.text||t.url}function zr(t,n){return typeof t!=`number`||!Number.isFinite(t)?``:e.D(t,n.config)}function Br(e,t){let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)?Tn(n,t.config):``}function Vr(t,n){let r=typeof t==`number`?t:Number(t);return Number.isFinite(r)?e.p(r,n.config):``}function Hr(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e,n=String(t.name??t.url??``).trim();return n?[n]:[]}):[]}function Q(e){if(e==null)return``;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return String(e);if(Array.isArray(e)){let t=[];for(let n=0;n<e.length;n++){if(!(n in e))continue;let r=Q(e[n]);r&&t.push(r)}return t.join(`, `)}if(typeof e==`object`){let t=e;return String(t.title??t.name??t.text??t.url??``).trim()}return String(e)}function Ur(e,t){let n=0;for(let r of t)r&&(r===e?n=Math.max(n,300):r.startsWith(e)?n=Math.max(n,250):r.includes(e)&&(n=Math.max(n,200)));return n}function Wr(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function Gr(e){return Array.from(new Set(e))}function Kr(e){let t=[];for(let{rowIndex:n,fieldIndex:r,...i}of e)t.push(i);return t}function qr(e){return{compress:!0,kind:`base-range-values-v1`,u:e.unitId,t:e.tableId,p:e.patches.map(e=>[e.row,e.col,Zr(e.value)]),...e.trigger===void 0?{}:{g:e.trigger}}}function Jr(e){if(ii(e,`base-range-values-v1`),!Yr(e)){if(!ri(e))throw Error(`[BaseCompression]: invalid uncompressed range values payload.`);return e}return{unitId:e.u,tableId:e.t,patches:e.p.map(([e,t,n])=>({row:e,col:t,value:Qr(n)})),...e.g===void 0?{}:{trigger:e.g}}}function Yr(e){return!$(e)||e.compress!==!0||e.kind!==`base-range-values-v1`?!1:typeof e.u==`string`&&typeof e.t==`string`&&(e.g===void 0||typeof e.g==`string`)&&Array.isArray(e.p)&&e.p.every(e=>Array.isArray(e)&&e.length===3&&Number.isInteger(e[0])&&Number.isInteger(e[1]))}function Xr(e){return!$(e)||e.compress!==!0||e.kind!==`base-snapshot-v1`||!$(e.tables)?!1:Object.values(e.tables).every(e=>$(e)&&(e.cd===void 0||Array.isArray(e.cd)&&e.cd.every(e=>Array.isArray(e)&&e.length===3&&Number.isInteger(e[0])&&Number.isInteger(e[1])&&ni(e[2]))))}function Zr(e){return ti(e)?$r(e):e}function Qr(e){return ni(e)?ei(e):e}function $r(e){return{c:1,...e.v===void 0?{}:{v:e.v},...e.t!==void 0&&e.t!==null?{t:e.t}:e.t===null?{t:null}:{},...e.f!==void 0&&e.f!==null?{f:e.f}:e.f===null?{f:null}:{},...e.si!==void 0&&e.si!==null?{si:e.si}:e.si===null?{si:null}:{},...e.p!==void 0&&e.p!==null?{p:e.p}:e.p===null?{p:null}:{}}}function ei(e){return{...e.v===void 0?{}:{v:e.v},...e.t===void 0?{}:{t:e.t},...e.f===void 0?{}:{f:e.f},...e.si===void 0?{}:{si:e.si},...e.p===void 0?{}:{p:e.p}}}function ti(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&(Object.prototype.hasOwnProperty.call(e,`v`)||Object.prototype.hasOwnProperty.call(e,`t`)||Object.prototype.hasOwnProperty.call(e,`p`)||Object.prototype.hasOwnProperty.call(e,`f`)||Object.prototype.hasOwnProperty.call(e,`si`))}function ni(e){return $(e)&&e.c===1}function ri(e){return $(e)&&typeof e.unitId==`string`&&typeof e.tableId==`string`&&(e.trigger===void 0||typeof e.trigger==`string`)&&Array.isArray(e.patches)&&e.patches.every(e=>$(e)&&Number.isInteger(e.row)&&Number.isInteger(e.col)&&`value`in e)}function ii(e,t){if($(e)&&e.compress===!0){if(e.kind!==t)throw Error(`[BaseCompression]: unsupported compressed payload kind "${String(e.kind)}".`);if(!(t===`base-range-values-v1`?Yr(e):Xr(e)))throw Error(`[BaseCompression]: invalid compressed payload "${t}".`)}}function $(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}const ai=(0,t.createIdentifier)(`bases.sync-status.service`);exports.AddGanttPredecessorCommand=et,exports.ApplyBaseJson1Mutation=e.s,exports.BASE_FIELD_STAT_TYPES=An,exports.BASE_HIERARCHY_MAX_LEVELS=e.U,exports.BASE_HIERARCHY_PARENT_FIELD_ID=e.W,exports.BASE_TABLE_NAME_REQUIREMENTS=`Base table names are exported as Excel worksheet names and must contain 1-31 characters, not start or end with an apostrophe, not contain : \\ / ? * [ ], and be unique (case-insensitive).`,exports.BASE_UNIT_PERMISSION_ACTIONS=k,exports.BaseConditionalColorRuleUpdateType=cn,exports.BaseEventSource=e.G,exports.BaseFormulaService=B,exports.BaseHierarchyError=e.K,exports.BaseHierarchyErrorCode=e.q,exports.BaseHistoryAction=e.c,exports.BaseJson1OpApplier=e.j,exports.BaseJson1OpFactory=m,exports.BatchCreateBaseRecordsCommand=it,exports.BatchDeleteBaseRecordsCommand=at,exports.ChangeBaseFieldTypeCommand=ot,exports.CreateBaseChildRecordCommand=K,exports.CreateBaseFieldCommand=st,exports.CreateBaseRecordCommand=ct,exports.CreateBaseTableCommand=ut,exports.CreateBaseViewCommand=Tt,exports.DeleteBaseFieldCommand=Et,exports.DeleteBaseRecordCommand=Dt,exports.DeleteBaseTableCommand=Ot,exports.DeleteBaseViewCommand=kt,exports.DuplicateBaseFieldCommand=At,exports.DuplicateBaseRecordCommand=jt,exports.EMBED_BASES_TABLE_RESOURCE_KEY=yn,exports.EnsureBaseTemporalViewDateFieldsCommand=Mt,exports.IBaseCommandService=R,exports.IBasePermissionService=ye,exports.IBaseProjectionService=e.u,exports.IBaseSyncStatusService=ai,exports.IBaseViewRegistryService=Or,exports.MoveBaseFieldCommand=Ft,exports.MoveBaseHierarchyRecordCommand=It,exports.MoveBaseViewCommand=Bt,exports.RemoveGanttPredecessorCommand=tt,exports.RenameBaseTableCommand=Vt,exports.RenameBaseViewCommand=Ht,exports.SetBaseKanbanGroupFieldCommand=Ut,exports.SetBaseNameCommand=Wt,exports.SetBasePermissionCommand=Gt,exports.SetBasePermissionRuleMutation=gn,exports.SetBasePermissionRulesMutation=_n,exports.SetBasePermissionsCommand=Kt,exports.SetBaseRangeValuesCommand=Jt,exports.SetBaseRecordValuesCommand=G,exports.SetBaseTableHierarchyFieldCommand=Yt,exports.SetBaseViewFieldOrderCommand=Xt,exports.SetBaseViewFieldVisibleCommand=Zt,exports.SetBaseViewFieldWidthCommand=Qt,exports.SetBaseViewFilterCommand=$t,exports.SetBaseViewGroupCommand=en,exports.SetBaseViewSortCommand=tn,Object.defineProperty(exports,"UniverBasesPlugin",{enumerable:!0,get:function(){return Z}}),exports.UpdateBaseCellCommand=nn,exports.UpdateBaseFieldCommand=an,exports.UpdateBaseFieldDescriptionCommand=rn,exports.UpdateBaseKanbanConfigCommand=on,exports.UpdateBaseRecordOrderCommand=sn,exports.UpdateBaseViewConditionalColorRulesCommand=ln,exports.UpdateBaseViewConfigCommand=mn,exports.ValidateBaseFormulaCommand=hn,exports.baseDateSerialToDateMs=e.T,exports.buildBaseHierarchyIndex=e.J,exports.calculateBaseFieldStat=Vn,exports.canEditBaseTargets=ve,exports.compressBaseRangeValuesPayload=qr,exports.copyBaseTableSnapshot=ar,exports.createBaseHierarchyParentField=e.Y,exports.createBaseSelectOption=l,exports.createDefaultBaseTableSnapshot=vn,exports.createEmbedBasesTable=bn,exports.createEmbedBasesTableAddMutation=xn,exports.createEmbedBasesTableRemoveMutation=Sn,exports.createUniqueBaseTableName=lt,exports.dateToExcelSerial=e.E,exports.decompressBaseRangeValuesPayload=Jr,exports.ensureBaseTableCellLayout=e.N,exports.findRecordLinkReferences=e.ct,exports.formatBaseDateValue=e.D,exports.formatBaseFieldStatValue=Hn,exports.formatBaseNumberValue=Tn,exports.formatBaseProgressValue=e.p,exports.getActiveBaseHierarchyFieldIds=e.X,exports.getBaseCellFormulaValue=e.I,exports.getBaseCellValue=e.R,exports.getBaseConditionalColorOperators=e.S,exports.getBaseDashboardPermissionObjectId=me,exports.getBaseFieldPermissionObjectId=j,Object.defineProperty(exports,"getBaseFormulaTableName",{enumerable:!0,get:function(){return t.getBaseFormulaTableName}}),exports.getBaseHierarchyDeletePromotions=e.Z,exports.getBaseHierarchyFieldId=e.Q,exports.getBasePermissionValue=F,exports.getBaseProgressRange=e.m,exports.getBaseRecordPermissionObjectId=M,exports.getBaseSelectOptionColor=c,exports.getBaseTablePermissionObjectId=A,exports.getBaseTextFieldOptions=f,exports.getBaseViewPermissionObjectId=N,exports.getGanttWorkingDayVariance=e.d,exports.getRecordLinkFieldConfig=e.lt,exports.getSupportedBaseFieldStatTypes=zn,exports.getVisibleBaseHierarchyRows=e.$,exports.hasGanttPredecessorPath=e.ot,exports.inferBaseSeparatorStyle=kn,exports.isBaseConditionalColorDateField=e.C,exports.isBaseFieldStatEmptyValue=Un,exports.isBaseFieldStatSupported=Bn,exports.isBaseFieldStatType=Ln,exports.isBaseHierarchyField=e.et,exports.isCompressedBaseRangeValuesPayload=Yr,exports.isGanttPredecessorField=e.st,exports.isManualBaseSingleSelect=s,exports.matchesBaseCondition=e.w,exports.normalizeBaseDateFieldConfig=e.O,exports.normalizeBaseDateSerial=e.k,exports.normalizeBaseFieldStatsConfig=Rn,exports.normalizeBaseProgressDecimalPlaces=e.h,exports.parseRecordLinkIds=e.ut,exports.projectBaseHierarchy=e.tt,exports.resolveBaseDateFieldConfig=e.A,exports.resolveBaseHierarchyFieldId=e.nt,exports.resolveBaseRangeHierarchyPatches=qt,exports.searchBaseTable=jr,exports.serializeRecordLinkIds=e.dt,exports.setBasePermissionValue=he,exports.traceBasePerformance=e.H,exports.uniqueFieldName=dt,exports.validateBaseHierarchyMove=e.rt,exports.validateBaseHierarchyRecordCreations=e.it,exports.validateBaseHierarchyRecordPatches=e.at,exports.validateBaseTableName=q,exports.validateCanonicalRecordLinkValue=e.ft,exports.validateRecordLinkField=e.pt,exports.validateRecordLinkValue=e.mt;
|