@gct-paas/word 0.1.39 → 0.1.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -16765,7 +16765,7 @@ function speedometer(samplesCount, min) {
16765
16765
  let tail = 0;
16766
16766
  let firstSampleTS;
16767
16767
  min = min !== void 0 ? min : 1e3;
16768
- return function push(chunkLength) {
16768
+ return function push2(chunkLength) {
16769
16769
  const now2 = Date.now();
16770
16770
  const startedAt = timestamps[tail];
16771
16771
  if (!firstSampleTS) {
@@ -18618,7 +18618,7 @@ function setupPlatformAdapters(options) {
18618
18618
  triggerUtil.register({
18619
18619
  handle: triggerHandler
18620
18620
  });
18621
- plugins?.forEach((plugin) => plugin.install());
18621
+ plugins?.forEach((plugin2) => plugin2.install());
18622
18622
  }
18623
18623
  function setupVueRuntime(options) {
18624
18624
  const { app } = options;
@@ -35239,7 +35239,7 @@ var ResizeObserver$1 = (
35239
35239
  return (_a = observers.get(this))[method4].apply(_a, arguments);
35240
35240
  };
35241
35241
  });
35242
- var index = (function() {
35242
+ var index$1 = (function() {
35243
35243
  if (typeof global$1.ResizeObserver !== "undefined") {
35244
35244
  return global$1.ResizeObserver;
35245
35245
  }
@@ -35260,7 +35260,7 @@ function addResizeListener(element, fn) {
35260
35260
  if (isServer) return;
35261
35261
  if (!element.__resizeListeners__) {
35262
35262
  element.__resizeListeners__ = [];
35263
- element.__ro__ = new index(resizeHandler);
35263
+ element.__ro__ = new index$1(resizeHandler);
35264
35264
  element.__ro__.observe(element);
35265
35265
  }
35266
35266
  element.__resizeListeners__.push(fn);
@@ -41252,22 +41252,29 @@ class FieldBaseHandler {
41252
41252
  }
41253
41253
  static getNoValueLabel(ctx) {
41254
41254
  const { context, wr } = ctx;
41255
+ const widgetMeta = wr.widgetMeta;
41255
41256
  if (context.doc.mode === DocModeTypeConst.Print) {
41256
- return { label: wr.widgetMeta?.props.emptySymbol ?? "", type: "noneLabel" };
41257
- } else {
41258
- if (wr.widgetMeta?.props?.placeholder) {
41259
- return {
41260
- label: wr.widgetMeta.props.placeholder,
41261
- type: "placeholder"
41262
- };
41263
- } else if (wr.widgetMeta?.extra?.biz?.fieldIdentity?.label) {
41264
- return {
41265
- label: wr.widgetMeta.extra.biz.fieldIdentity.label,
41266
- type: "fieldName"
41267
- };
41268
- }
41257
+ return {
41258
+ label: widgetMeta?.props.emptySymbol ?? "",
41259
+ type: "noneLabel"
41260
+ };
41269
41261
  }
41270
- return {
41262
+ const candidates = [
41263
+ {
41264
+ label: widgetMeta?.props?.newSpecificConfig?.newPlaceholder,
41265
+ type: "placeholder"
41266
+ },
41267
+ {
41268
+ label: widgetMeta?.props?.placeholder,
41269
+ type: "placeholder"
41270
+ },
41271
+ {
41272
+ label: widgetMeta?.extra?.biz?.fieldIdentity?.label,
41273
+ type: "fieldName"
41274
+ }
41275
+ ];
41276
+ const matched = candidates.find((item) => item.label);
41277
+ return matched ?? {
41271
41278
  label: "--",
41272
41279
  type: "default"
41273
41280
  };
@@ -42524,7 +42531,7 @@ const FIELD_TYPE_TO_FW = {
42524
42531
  [FIELD_TYPE.INTEGER]: "fw:number",
42525
42532
  [FIELD_TYPE.LONG]: "fw:number",
42526
42533
  [FIELD_TYPE.DOUBLE]: "fw:double",
42527
- [FIELD_TYPE.DECIMAL]: "fw:double",
42534
+ [FIELD_TYPE.DECIMAL]: "fw:number",
42528
42535
  [FIELD_TYPE.BOOLEAN]: "fw:enum",
42529
42536
  [FIELD_TYPE.DATE]: "fw:date",
42530
42537
  [FIELD_TYPE.DATE_TIME]: "fw:date-time",
@@ -47621,21 +47628,31 @@ class DataManager {
47621
47628
  this.syncSubTableRowsToLayout();
47622
47629
  }
47623
47630
  /**
47624
- * 仅补齐检验表关联轴子表(如 f_jianyan2)到动态关联铺砖槽位数。
47625
- * 不处理检验项主体(f_jianyan1)与二维表,避免覆盖接口行或误扩纵向轴。
47631
+ * 按版面铺砖槽位补齐子表行数:
47632
+ * - 固定表:按槽位补齐自身子表行
47633
+ * - 二维/检验表:仅补齐关联轴(如 f_ewblink / f_jianyan2)
47634
+ * 不处理主体轴(如 f_ewb / f_jianyan1),避免覆盖接口行或误扩纵向轴。
47626
47635
  */
47627
47636
  syncSubTableRowsToLayout() {
47628
47637
  const listSubTables = this.doc?.model?.getSubTableInfoList;
47629
47638
  if (typeof listSubTables !== "function") return;
47630
- for (const info of listSubTables.call(this.doc.model)) {
47631
- if (info.subType !== "check-table-2d-link" || !info.field) continue;
47632
- const linkFieldKey = info.field;
47633
- const layoutRows = this.doc?.model?.getSubTableLayoutSlotCount(linkFieldKey) ?? 0;
47639
+ for (const info of listSubTables.call(this.doc?.model)) {
47640
+ if (!info.field) {
47641
+ continue;
47642
+ }
47643
+ const subTableKey = info.field;
47644
+ const layoutRows = this.doc?.model?.getSubTableLayoutSlotCount(subTableKey) ?? 0;
47634
47645
  if (layoutRows <= 0) continue;
47635
- const dataRows = this.countSubTableDataRows(linkFieldKey);
47646
+ const dataRows = this.countSubTableDataRows(subTableKey);
47636
47647
  const targetRows = Math.max(dataRows, layoutRows);
47637
47648
  if (targetRows <= dataRows) continue;
47638
- this.ensureCheckTableLinkLayoutRows(linkFieldKey, targetRows);
47649
+ if (["check-table-2d-link", "sub-table-2d-link"].includes(info.subType)) {
47650
+ this.ensureCheckTableLinkLayoutRows(subTableKey, targetRows);
47651
+ continue;
47652
+ }
47653
+ if (info.subType === "fixed-table") {
47654
+ this.ensureSubTableRowCount(subTableKey, targetRows, true);
47655
+ }
47639
47656
  }
47640
47657
  }
47641
47658
  /** 子表在 rawData 中的行数(支持尚未转成数组的 { data: [] } 接口形态,此时返回 0 且不在此阶段强转) */
@@ -48240,9 +48257,6 @@ class InteractionManager {
48240
48257
  this.batcher = new Transaction((q2) => {
48241
48258
  this.broadcastChange(q2.type, q2.prev, q2.reason);
48242
48259
  });
48243
- setTimeout(() => {
48244
- this.emitChange("panelData", null);
48245
- });
48246
48260
  }
48247
48261
  /** 获取 interaction */
48248
48262
  get(type4) {
@@ -48586,10 +48600,14 @@ function useInteraction(docRef) {
48586
48600
  "focusAnnotationId",
48587
48601
  "annotationList"
48588
48602
  ];
48603
+ const setState = (type4, value) => {
48604
+ state[type4] = value;
48605
+ };
48589
48606
  interactionTypes.forEach((type4) => {
48590
48607
  try {
48608
+ setState(type4, doc.interactionManager.get(type4));
48591
48609
  const off2 = doc.eventManager.eventBus.on(`${type4}:change`, (payload) => {
48592
- state[type4] = payload?.value ?? null;
48610
+ setState(type4, payload?.value);
48593
48611
  });
48594
48612
  unsubscribes.push(off2);
48595
48613
  } catch {
@@ -50303,13 +50321,15 @@ class DocModel {
50303
50321
  };
50304
50322
  });
50305
50323
  const table2DRegions = tables.filter((w2) => w2.has2DTable).flatMap((w2) => w2._2DTable).map((item) => {
50324
+ const crossKey = item.subFieldKey && item.linkFieldKey ? `${item.subFieldKey}:${item.linkFieldKey}` : void 0;
50306
50325
  const result = [];
50307
50326
  if (item.subFieldKey) {
50308
50327
  result.push({
50309
50328
  field: item.subFieldKey,
50310
50329
  key: "dyn",
50311
50330
  name: "二维表",
50312
- subType: "sub-table-2d"
50331
+ subType: "sub-table-2d",
50332
+ crossKey
50313
50333
  });
50314
50334
  }
50315
50335
  if (item.linkFieldKey) {
@@ -50317,19 +50337,22 @@ class DocModel {
50317
50337
  field: item.linkFieldKey,
50318
50338
  key: "newfixed",
50319
50339
  name: "二维表-关联",
50320
- subType: "sub-table-2d-link"
50340
+ subType: "sub-table-2d-link",
50341
+ crossKey
50321
50342
  });
50322
50343
  }
50323
50344
  return result;
50324
50345
  }).flat();
50325
50346
  const checkTableRegions = tables.filter((w2) => w2.hasCheckTable).flatMap((w2) => w2.checkTable).map((item) => {
50347
+ const crossKey = item.subFieldKey && item.linkFieldKey ? `${item.subFieldKey}:${item.linkFieldKey}` : void 0;
50326
50348
  const result = [];
50327
50349
  if (item.subFieldKey) {
50328
50350
  result.push({
50329
50351
  field: item.subFieldKey,
50330
50352
  key: "newfixed",
50331
50353
  name: "检验表-动态",
50332
- subType: "check-table-2d"
50354
+ subType: "check-table-2d",
50355
+ crossKey
50333
50356
  });
50334
50357
  }
50335
50358
  if (item.linkFieldKey) {
@@ -50337,7 +50360,8 @@ class DocModel {
50337
50360
  field: item.linkFieldKey,
50338
50361
  key: "newfixed",
50339
50362
  name: "检验表-关联",
50340
- subType: "check-table-2d-link"
50363
+ subType: "check-table-2d-link",
50364
+ crossKey
50341
50365
  });
50342
50366
  }
50343
50367
  return result;
@@ -50362,7 +50386,7 @@ class DocModel {
50362
50386
  const fillDirection = region.widgetMeta?.props?.fillDirection ?? "x";
50363
50387
  max = Math.max(max, countDataGroupSlots(region, region.itemRegion, fillDirection));
50364
50388
  }
50365
- for (const region of table.checkTable) {
50389
+ for (const region of [...table.checkTable, ...table._2DTable]) {
50366
50390
  if (!region.itemRegion) continue;
50367
50391
  const range3 = expandDataGroupRowRange(region, region.itemRegion);
50368
50392
  const fillDirection = region.widgetMeta?.props?.fillDirection ?? "x";
@@ -50374,17 +50398,6 @@ class DocModel {
50374
50398
  isLinkSubTableSubAxisOnly = true;
50375
50399
  }
50376
50400
  }
50377
- for (const region of table._2DTable) {
50378
- if (!region.itemRegion) continue;
50379
- const range3 = expandDataGroupRowRange(region, region.itemRegion);
50380
- const slots = countDataGroupSlots(range3, region.itemRegion);
50381
- if (region.linkFieldKey === subFieldKey) {
50382
- max = Math.max(max, slots);
50383
- }
50384
- if (region.subFieldKey === subFieldKey) {
50385
- isLinkSubTableSubAxisOnly = true;
50386
- }
50387
- }
50388
50401
  }
50389
50402
  if (max > 0) return max;
50390
50403
  if (isLinkSubTableSubAxisOnly) return 0;
@@ -51786,63 +51799,48 @@ function transformSourceDataList(data, dict = {}) {
51786
51799
  return list || [];
51787
51800
  }
51788
51801
  function conversionFormState(payload) {
51789
- const { interfaceData, masterSlaveList, widgetInstances } = payload || {};
51802
+ const { interfaceData, masterSlaveList, subTableInfoList } = payload || {};
51790
51803
  const formState = {};
51791
51804
  if (interfaceData && interfaceData.data) {
51792
51805
  merge(formState, transformSourceData(interfaceData.data, interfaceData.dict));
51793
51806
  }
51794
- let linkedKeyList = [];
51795
- if (widgetInstances) {
51796
- const linkedFieldList = widgetInstances.map(({ valuePath }) => {
51797
- if (valuePath.includes(":")) {
51798
- const { fieldKey, parentFieldKey, linkFieldKey } = parseValuePath(valuePath);
51799
- const linkedKey = `${parentFieldKey}:${linkFieldKey}`;
51800
- return {
51801
- fieldKey,
51802
- linkedKey
51803
- };
51804
- } else {
51805
- return null;
51806
- }
51807
- }).filter(Boolean);
51808
- Object.entries(groupBy$1(linkedFieldList, "linkedKey")).forEach(([linkedKey, fields]) => {
51809
- linkedKeyList.push(linkedKey);
51810
- const [parentFieldKey, linkFieldKey] = linkedKey.split(":");
51811
- const parentState = formState[parentFieldKey];
51812
- const keys2 = ["id_", "group_", ...fields.map((f) => f.fieldKey)];
51813
- formState[linkFieldKey]?.data.forEach((row) => {
51814
- row.__gw_x_uid = row.group_;
51815
- });
51816
- formState[linkedKey] = {
51817
- data: parentState?.data.map((row) => {
51818
- const { group_: g_ } = row;
51819
- const _row = pick(row, keys2);
51820
- if (g_) {
51821
- const [y2, x2] = g_.split(":");
51822
- _row.__gw_y_uid = y2;
51823
- _row.__gw_x_uid = x2;
51824
- }
51825
- return _row;
51826
- }) || [],
51827
- dict: parentState?.dict || []
51828
- };
51829
- const addedYUidList = [];
51830
- formState[parentFieldKey] = {
51831
- data: [],
51832
- dict: formState[parentFieldKey]?.dict || []
51833
- };
51834
- parentState?.data.forEach((row) => {
51835
- const yUid = row.group_.split(":")[0];
51836
- if (addedYUidList.includes(yUid)) return;
51837
- addedYUidList.push(yUid);
51838
- formState[parentFieldKey].data.push({
51839
- ...row,
51840
- __gw_y_uid: yUid
51841
- });
51807
+ const crossKeyList = Array.from(new Set(subTableInfoList.map((o) => o.crossKey).filter(Boolean)));
51808
+ crossKeyList.forEach((crossKey) => {
51809
+ const [parentFieldKey, linkFieldKey] = crossKey.split(":");
51810
+ const parentState = formState[parentFieldKey];
51811
+ formState[linkFieldKey]?.data.forEach((row) => {
51812
+ row.__gw_x_uid = row.group_;
51813
+ });
51814
+ formState[crossKey] = {
51815
+ data: parentState?.data.map((row) => {
51816
+ const { group_ } = row;
51817
+ const _row = { ...row };
51818
+ if (group_) {
51819
+ const [yid, xid] = group_.split(":");
51820
+ _row.__gw_y_uid = yid;
51821
+ _row.__gw_x_uid = xid;
51822
+ }
51823
+ return _row;
51824
+ }) || [],
51825
+ dict: parentState?.dict || []
51826
+ };
51827
+ const addedYids = [];
51828
+ formState[parentFieldKey] = {
51829
+ data: [],
51830
+ dict: formState[parentFieldKey]?.dict || []
51831
+ };
51832
+ parentState?.data.forEach((row) => {
51833
+ if (!row.group_?.includes(":")) return;
51834
+ const yid = row.group_.split(":")[0];
51835
+ if (addedYids.includes(yid)) return;
51836
+ addedYids.push(yid);
51837
+ formState[parentFieldKey].data.push({
51838
+ ...row,
51839
+ __gw_y_uid: yid
51842
51840
  });
51843
51841
  });
51844
- }
51845
- masterSlaveList.map((item) => item.key).concat(linkedKeyList).forEach((k) => {
51842
+ });
51843
+ masterSlaveList.map((item) => item.key).concat(crossKeyList).forEach((k) => {
51846
51844
  const subFormData = formState[k];
51847
51845
  if (subFormData) {
51848
51846
  formState[k] = transformSourceDataList([...subFormData.data], subFormData.dict);
@@ -51850,38 +51848,38 @@ function conversionFormState(payload) {
51850
51848
  });
51851
51849
  return formState;
51852
51850
  }
51853
- function getSubmitFormData(formData) {
51851
+ function resolveSubmitCrossKeys(formData, subTableInfoList) {
51852
+ if (subTableInfoList?.length) {
51853
+ const fromModel = [
51854
+ ...new Set(
51855
+ subTableInfoList.map((item) => item.crossKey).filter((key) => typeof key === "string" && key.length > 0)
51856
+ )
51857
+ ];
51858
+ if (fromModel.length) return fromModel;
51859
+ }
51860
+ return Object.keys(formData).filter((k) => k.includes(":"));
51861
+ }
51862
+ function getSubmitFormData(formData, subTableInfoList) {
51854
51863
  const _formData = { ...formData };
51855
- Object.keys(_formData).filter((k) => k.includes(":")).forEach((linkedKey) => {
51856
- const [subKey] = linkedKey.split(":");
51864
+ resolveSubmitCrossKeys(_formData, subTableInfoList).forEach((crossKey) => {
51865
+ const [subKey, linkKey] = crossKey.split(":");
51857
51866
  const subData = _formData[subKey] || [];
51858
- const crossData = _formData[linkedKey] || [];
51859
- if ([crossData, subData].every(Array.isArray)) {
51860
- const isCheckTable = subData[0] && Object.keys(subData[0]).includes("value_");
51861
- if (!isCheckTable) {
51862
- _formData[subKey] = [];
51863
- }
51864
- crossData.forEach((crossItem) => {
51865
- const { __gw_y_uid, __gw_x_uid } = crossItem;
51866
- const existedRow = subData.find((row) => row.__gw_y_uid === __gw_y_uid);
51867
- const newRowInfo = omit(crossItem, FILTER_KEYS);
51868
- const group_ = `${__gw_y_uid}:${__gw_x_uid}`;
51869
- if (!existedRow) return;
51870
- if (isCheckTable) {
51871
- Object.assign(existedRow, {
51872
- ...newRowInfo,
51873
- group_
51874
- });
51875
- } else {
51876
- _formData[subKey].push({
51877
- ...existedRow,
51878
- ...newRowInfo,
51879
- group_
51880
- });
51881
- }
51867
+ const linkData = _formData[linkKey] || [];
51868
+ const crossData = _formData[crossKey] || [];
51869
+ _formData[subKey] = [];
51870
+ subData.forEach((subRow) => {
51871
+ const { __gw_y_uid: yid } = subRow;
51872
+ linkData.forEach((linkRow) => {
51873
+ const { __gw_x_uid: xid } = linkRow;
51874
+ const crossRow = crossData.find((row) => row.__gw_y_uid === yid && row.__gw_x_uid === xid) || {};
51875
+ _formData[subKey].push({
51876
+ ...subRow,
51877
+ ...omit(crossRow, FILTER_KEYS),
51878
+ group_: `${yid}:${xid}`
51879
+ });
51882
51880
  });
51883
- }
51884
- delete _formData[linkedKey];
51881
+ });
51882
+ delete _formData[crossKey];
51885
51883
  });
51886
51884
  const realFormData = Object.keys(_formData).reduce((reducedData, fieldKey) => {
51887
51885
  const fieldValue = _formData[fieldKey];
@@ -52661,6 +52659,1750 @@ async function loadDataValuesByAutofillRules(record, ctx, instances, autofillRul
52661
52659
  { needReplacePathIndexPlaceholder: true, sourceValuePath }
52662
52660
  );
52663
52661
  }
52662
+ class Hooks {
52663
+ /**
52664
+ * @callback HookCallback
52665
+ * @this {*|Jsep} this
52666
+ * @param {Jsep} env
52667
+ * @returns: void
52668
+ */
52669
+ /**
52670
+ * Adds the given callback to the list of callbacks for the given hook.
52671
+ *
52672
+ * The callback will be invoked when the hook it is registered for is run.
52673
+ *
52674
+ * One callback function can be registered to multiple hooks and the same hook multiple times.
52675
+ *
52676
+ * @param {string|object} name The name of the hook, or an object of callbacks keyed by name
52677
+ * @param {HookCallback|boolean} callback The callback function which is given environment variables.
52678
+ * @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
52679
+ * @public
52680
+ */
52681
+ add(name2, callback, first) {
52682
+ if (typeof arguments[0] != "string") {
52683
+ for (let name3 in arguments[0]) {
52684
+ this.add(name3, arguments[0][name3], arguments[1]);
52685
+ }
52686
+ } else {
52687
+ (Array.isArray(name2) ? name2 : [name2]).forEach(function(name3) {
52688
+ this[name3] = this[name3] || [];
52689
+ if (callback) {
52690
+ this[name3][first ? "unshift" : "push"](callback);
52691
+ }
52692
+ }, this);
52693
+ }
52694
+ }
52695
+ /**
52696
+ * Runs a hook invoking all registered callbacks with the given environment variables.
52697
+ *
52698
+ * Callbacks will be invoked synchronously and in the order in which they were registered.
52699
+ *
52700
+ * @param {string} name The name of the hook.
52701
+ * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
52702
+ * @public
52703
+ */
52704
+ run(name2, env) {
52705
+ this[name2] = this[name2] || [];
52706
+ this[name2].forEach(function(callback) {
52707
+ callback.call(env && env.context ? env.context : env, env);
52708
+ });
52709
+ }
52710
+ }
52711
+ class Plugins {
52712
+ constructor(jsep2) {
52713
+ this.jsep = jsep2;
52714
+ this.registered = {};
52715
+ }
52716
+ /**
52717
+ * @callback PluginSetup
52718
+ * @this {Jsep} jsep
52719
+ * @returns: void
52720
+ */
52721
+ /**
52722
+ * Adds the given plugin(s) to the registry
52723
+ *
52724
+ * @param {object} plugins
52725
+ * @param {string} plugins.name The name of the plugin
52726
+ * @param {PluginSetup} plugins.init The init function
52727
+ * @public
52728
+ */
52729
+ register() {
52730
+ for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {
52731
+ plugins[_key] = arguments[_key];
52732
+ }
52733
+ plugins.forEach((plugin2) => {
52734
+ if (typeof plugin2 !== "object" || !plugin2.name || !plugin2.init) {
52735
+ throw new Error("Invalid JSEP plugin format");
52736
+ }
52737
+ if (this.registered[plugin2.name]) {
52738
+ return;
52739
+ }
52740
+ plugin2.init(this.jsep);
52741
+ this.registered[plugin2.name] = plugin2;
52742
+ });
52743
+ }
52744
+ }
52745
+ class Jsep {
52746
+ /**
52747
+ * @returns {string}
52748
+ */
52749
+ static get version() {
52750
+ return "1.4.0";
52751
+ }
52752
+ /**
52753
+ * @returns {string}
52754
+ */
52755
+ static toString() {
52756
+ return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
52757
+ }
52758
+ // ==================== CONFIG ================================
52759
+ /**
52760
+ * @method addUnaryOp
52761
+ * @param {string} op_name The name of the unary op to add
52762
+ * @returns {Jsep}
52763
+ */
52764
+ static addUnaryOp(op_name) {
52765
+ Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
52766
+ Jsep.unary_ops[op_name] = 1;
52767
+ return Jsep;
52768
+ }
52769
+ /**
52770
+ * @method jsep.addBinaryOp
52771
+ * @param {string} op_name The name of the binary op to add
52772
+ * @param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence
52773
+ * @param {boolean} [isRightAssociative=false] whether operator is right-associative
52774
+ * @returns {Jsep}
52775
+ */
52776
+ static addBinaryOp(op_name, precedence, isRightAssociative) {
52777
+ Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
52778
+ Jsep.binary_ops[op_name] = precedence;
52779
+ if (isRightAssociative) {
52780
+ Jsep.right_associative.add(op_name);
52781
+ } else {
52782
+ Jsep.right_associative.delete(op_name);
52783
+ }
52784
+ return Jsep;
52785
+ }
52786
+ /**
52787
+ * @method addIdentifierChar
52788
+ * @param {string} char The additional character to treat as a valid part of an identifier
52789
+ * @returns {Jsep}
52790
+ */
52791
+ static addIdentifierChar(char) {
52792
+ Jsep.additional_identifier_chars.add(char);
52793
+ return Jsep;
52794
+ }
52795
+ /**
52796
+ * @method addLiteral
52797
+ * @param {string} literal_name The name of the literal to add
52798
+ * @param {*} literal_value The value of the literal
52799
+ * @returns {Jsep}
52800
+ */
52801
+ static addLiteral(literal_name, literal_value) {
52802
+ Jsep.literals[literal_name] = literal_value;
52803
+ return Jsep;
52804
+ }
52805
+ /**
52806
+ * @method removeUnaryOp
52807
+ * @param {string} op_name The name of the unary op to remove
52808
+ * @returns {Jsep}
52809
+ */
52810
+ static removeUnaryOp(op_name) {
52811
+ delete Jsep.unary_ops[op_name];
52812
+ if (op_name.length === Jsep.max_unop_len) {
52813
+ Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
52814
+ }
52815
+ return Jsep;
52816
+ }
52817
+ /**
52818
+ * @method removeAllUnaryOps
52819
+ * @returns {Jsep}
52820
+ */
52821
+ static removeAllUnaryOps() {
52822
+ Jsep.unary_ops = {};
52823
+ Jsep.max_unop_len = 0;
52824
+ return Jsep;
52825
+ }
52826
+ /**
52827
+ * @method removeIdentifierChar
52828
+ * @param {string} char The additional character to stop treating as a valid part of an identifier
52829
+ * @returns {Jsep}
52830
+ */
52831
+ static removeIdentifierChar(char) {
52832
+ Jsep.additional_identifier_chars.delete(char);
52833
+ return Jsep;
52834
+ }
52835
+ /**
52836
+ * @method removeBinaryOp
52837
+ * @param {string} op_name The name of the binary op to remove
52838
+ * @returns {Jsep}
52839
+ */
52840
+ static removeBinaryOp(op_name) {
52841
+ delete Jsep.binary_ops[op_name];
52842
+ if (op_name.length === Jsep.max_binop_len) {
52843
+ Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
52844
+ }
52845
+ Jsep.right_associative.delete(op_name);
52846
+ return Jsep;
52847
+ }
52848
+ /**
52849
+ * @method removeAllBinaryOps
52850
+ * @returns {Jsep}
52851
+ */
52852
+ static removeAllBinaryOps() {
52853
+ Jsep.binary_ops = {};
52854
+ Jsep.max_binop_len = 0;
52855
+ return Jsep;
52856
+ }
52857
+ /**
52858
+ * @method removeLiteral
52859
+ * @param {string} literal_name The name of the literal to remove
52860
+ * @returns {Jsep}
52861
+ */
52862
+ static removeLiteral(literal_name) {
52863
+ delete Jsep.literals[literal_name];
52864
+ return Jsep;
52865
+ }
52866
+ /**
52867
+ * @method removeAllLiterals
52868
+ * @returns {Jsep}
52869
+ */
52870
+ static removeAllLiterals() {
52871
+ Jsep.literals = {};
52872
+ return Jsep;
52873
+ }
52874
+ // ==================== END CONFIG ============================
52875
+ /**
52876
+ * @returns {string}
52877
+ */
52878
+ get char() {
52879
+ return this.expr.charAt(this.index);
52880
+ }
52881
+ /**
52882
+ * @returns {number}
52883
+ */
52884
+ get code() {
52885
+ return this.expr.charCodeAt(this.index);
52886
+ }
52887
+ /**
52888
+ * @param {string} expr a string with the passed in express
52889
+ * @returns Jsep
52890
+ */
52891
+ constructor(expr) {
52892
+ this.expr = expr;
52893
+ this.index = 0;
52894
+ }
52895
+ /**
52896
+ * static top-level parser
52897
+ * @returns {jsep.Expression}
52898
+ */
52899
+ static parse(expr) {
52900
+ return new Jsep(expr).parse();
52901
+ }
52902
+ /**
52903
+ * Get the longest key length of any object
52904
+ * @param {object} obj
52905
+ * @returns {number}
52906
+ */
52907
+ static getMaxKeyLen(obj) {
52908
+ return Math.max(0, ...Object.keys(obj).map((k) => k.length));
52909
+ }
52910
+ /**
52911
+ * `ch` is a character code in the next three functions
52912
+ * @param {number} ch
52913
+ * @returns {boolean}
52914
+ */
52915
+ static isDecimalDigit(ch) {
52916
+ return ch >= 48 && ch <= 57;
52917
+ }
52918
+ /**
52919
+ * Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.
52920
+ * @param {string} op_val
52921
+ * @returns {number}
52922
+ */
52923
+ static binaryPrecedence(op_val) {
52924
+ return Jsep.binary_ops[op_val] || 0;
52925
+ }
52926
+ /**
52927
+ * Looks for start of identifier
52928
+ * @param {number} ch
52929
+ * @returns {boolean}
52930
+ */
52931
+ static isIdentifierStart(ch) {
52932
+ return ch >= 65 && ch <= 90 || // A...Z
52933
+ ch >= 97 && ch <= 122 || // a...z
52934
+ ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)] || // any non-ASCII that is not an operator
52935
+ Jsep.additional_identifier_chars.has(String.fromCharCode(ch));
52936
+ }
52937
+ /**
52938
+ * @param {number} ch
52939
+ * @returns {boolean}
52940
+ */
52941
+ static isIdentifierPart(ch) {
52942
+ return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
52943
+ }
52944
+ /**
52945
+ * throw error at index of the expression
52946
+ * @param {string} message
52947
+ * @throws
52948
+ */
52949
+ throwError(message) {
52950
+ const error = new Error(message + " at character " + this.index);
52951
+ error.index = this.index;
52952
+ error.description = message;
52953
+ throw error;
52954
+ }
52955
+ /**
52956
+ * Run a given hook
52957
+ * @param {string} name
52958
+ * @param {jsep.Expression|false} [node]
52959
+ * @returns {?jsep.Expression}
52960
+ */
52961
+ runHook(name2, node) {
52962
+ if (Jsep.hooks[name2]) {
52963
+ const env = {
52964
+ context: this,
52965
+ node
52966
+ };
52967
+ Jsep.hooks.run(name2, env);
52968
+ return env.node;
52969
+ }
52970
+ return node;
52971
+ }
52972
+ /**
52973
+ * Runs a given hook until one returns a node
52974
+ * @param {string} name
52975
+ * @returns {?jsep.Expression}
52976
+ */
52977
+ searchHook(name2) {
52978
+ if (Jsep.hooks[name2]) {
52979
+ const env = {
52980
+ context: this
52981
+ };
52982
+ Jsep.hooks[name2].find(function(callback) {
52983
+ callback.call(env.context, env);
52984
+ return env.node;
52985
+ });
52986
+ return env.node;
52987
+ }
52988
+ }
52989
+ /**
52990
+ * Push `index` up to the next non-space character
52991
+ */
52992
+ gobbleSpaces() {
52993
+ let ch = this.code;
52994
+ while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
52995
+ ch = this.expr.charCodeAt(++this.index);
52996
+ }
52997
+ this.runHook("gobble-spaces");
52998
+ }
52999
+ /**
53000
+ * Top-level method to parse all expressions and returns compound or single node
53001
+ * @returns {jsep.Expression}
53002
+ */
53003
+ parse() {
53004
+ this.runHook("before-all");
53005
+ const nodes = this.gobbleExpressions();
53006
+ const node = nodes.length === 1 ? nodes[0] : {
53007
+ type: Jsep.COMPOUND,
53008
+ body: nodes
53009
+ };
53010
+ return this.runHook("after-all", node);
53011
+ }
53012
+ /**
53013
+ * top-level parser (but can be reused within as well)
53014
+ * @param {number} [untilICode]
53015
+ * @returns {jsep.Expression[]}
53016
+ */
53017
+ gobbleExpressions(untilICode) {
53018
+ let nodes = [], ch_i, node;
53019
+ while (this.index < this.expr.length) {
53020
+ ch_i = this.code;
53021
+ if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
53022
+ this.index++;
53023
+ } else {
53024
+ if (node = this.gobbleExpression()) {
53025
+ nodes.push(node);
53026
+ } else if (this.index < this.expr.length) {
53027
+ if (ch_i === untilICode) {
53028
+ break;
53029
+ }
53030
+ this.throwError('Unexpected "' + this.char + '"');
53031
+ }
53032
+ }
53033
+ }
53034
+ return nodes;
53035
+ }
53036
+ /**
53037
+ * The main parsing function.
53038
+ * @returns {?jsep.Expression}
53039
+ */
53040
+ gobbleExpression() {
53041
+ const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
53042
+ this.gobbleSpaces();
53043
+ return this.runHook("after-expression", node);
53044
+ }
53045
+ /**
53046
+ * Search for the operation portion of the string (e.g. `+`, `===`)
53047
+ * Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
53048
+ * and move down from 3 to 2 to 1 character until a matching binary operation is found
53049
+ * then, return that binary operation
53050
+ * @returns {string|boolean}
53051
+ */
53052
+ gobbleBinaryOp() {
53053
+ this.gobbleSpaces();
53054
+ let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
53055
+ let tc_len = to_check.length;
53056
+ while (tc_len > 0) {
53057
+ if (Jsep.binary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
53058
+ this.index += tc_len;
53059
+ return to_check;
53060
+ }
53061
+ to_check = to_check.substr(0, --tc_len);
53062
+ }
53063
+ return false;
53064
+ }
53065
+ /**
53066
+ * This function is responsible for gobbling an individual expression,
53067
+ * e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
53068
+ * @returns {?jsep.BinaryExpression}
53069
+ */
53070
+ gobbleBinaryExpression() {
53071
+ let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
53072
+ left = this.gobbleToken();
53073
+ if (!left) {
53074
+ return left;
53075
+ }
53076
+ biop = this.gobbleBinaryOp();
53077
+ if (!biop) {
53078
+ return left;
53079
+ }
53080
+ biop_info = {
53081
+ value: biop,
53082
+ prec: Jsep.binaryPrecedence(biop),
53083
+ right_a: Jsep.right_associative.has(biop)
53084
+ };
53085
+ right = this.gobbleToken();
53086
+ if (!right) {
53087
+ this.throwError("Expected expression after " + biop);
53088
+ }
53089
+ stack = [left, biop_info, right];
53090
+ while (biop = this.gobbleBinaryOp()) {
53091
+ prec = Jsep.binaryPrecedence(biop);
53092
+ if (prec === 0) {
53093
+ this.index -= biop.length;
53094
+ break;
53095
+ }
53096
+ biop_info = {
53097
+ value: biop,
53098
+ prec,
53099
+ right_a: Jsep.right_associative.has(biop)
53100
+ };
53101
+ cur_biop = biop;
53102
+ const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
53103
+ while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
53104
+ right = stack.pop();
53105
+ biop = stack.pop().value;
53106
+ left = stack.pop();
53107
+ node = {
53108
+ type: Jsep.BINARY_EXP,
53109
+ operator: biop,
53110
+ left,
53111
+ right
53112
+ };
53113
+ stack.push(node);
53114
+ }
53115
+ node = this.gobbleToken();
53116
+ if (!node) {
53117
+ this.throwError("Expected expression after " + cur_biop);
53118
+ }
53119
+ stack.push(biop_info, node);
53120
+ }
53121
+ i = stack.length - 1;
53122
+ node = stack[i];
53123
+ while (i > 1) {
53124
+ node = {
53125
+ type: Jsep.BINARY_EXP,
53126
+ operator: stack[i - 1].value,
53127
+ left: stack[i - 2],
53128
+ right: node
53129
+ };
53130
+ i -= 2;
53131
+ }
53132
+ return node;
53133
+ }
53134
+ /**
53135
+ * An individual part of a binary expression:
53136
+ * e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
53137
+ * @returns {boolean|jsep.Expression}
53138
+ */
53139
+ gobbleToken() {
53140
+ let ch, to_check, tc_len, node;
53141
+ this.gobbleSpaces();
53142
+ node = this.searchHook("gobble-token");
53143
+ if (node) {
53144
+ return this.runHook("after-token", node);
53145
+ }
53146
+ ch = this.code;
53147
+ if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
53148
+ return this.gobbleNumericLiteral();
53149
+ }
53150
+ if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
53151
+ node = this.gobbleStringLiteral();
53152
+ } else if (ch === Jsep.OBRACK_CODE) {
53153
+ node = this.gobbleArray();
53154
+ } else {
53155
+ to_check = this.expr.substr(this.index, Jsep.max_unop_len);
53156
+ tc_len = to_check.length;
53157
+ while (tc_len > 0) {
53158
+ if (Jsep.unary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
53159
+ this.index += tc_len;
53160
+ const argument = this.gobbleToken();
53161
+ if (!argument) {
53162
+ this.throwError("missing unaryOp argument");
53163
+ }
53164
+ return this.runHook("after-token", {
53165
+ type: Jsep.UNARY_EXP,
53166
+ operator: to_check,
53167
+ argument,
53168
+ prefix: true
53169
+ });
53170
+ }
53171
+ to_check = to_check.substr(0, --tc_len);
53172
+ }
53173
+ if (Jsep.isIdentifierStart(ch)) {
53174
+ node = this.gobbleIdentifier();
53175
+ if (Jsep.literals.hasOwnProperty(node.name)) {
53176
+ node = {
53177
+ type: Jsep.LITERAL,
53178
+ value: Jsep.literals[node.name],
53179
+ raw: node.name
53180
+ };
53181
+ } else if (node.name === Jsep.this_str) {
53182
+ node = {
53183
+ type: Jsep.THIS_EXP
53184
+ };
53185
+ }
53186
+ } else if (ch === Jsep.OPAREN_CODE) {
53187
+ node = this.gobbleGroup();
53188
+ }
53189
+ }
53190
+ if (!node) {
53191
+ return this.runHook("after-token", false);
53192
+ }
53193
+ node = this.gobbleTokenProperty(node);
53194
+ return this.runHook("after-token", node);
53195
+ }
53196
+ /**
53197
+ * Gobble properties of of identifiers/strings/arrays/groups.
53198
+ * e.g. `foo`, `bar.baz`, `foo['bar'].baz`
53199
+ * It also gobbles function calls:
53200
+ * e.g. `Math.acos(obj.angle)`
53201
+ * @param {jsep.Expression} node
53202
+ * @returns {jsep.Expression}
53203
+ */
53204
+ gobbleTokenProperty(node) {
53205
+ this.gobbleSpaces();
53206
+ let ch = this.code;
53207
+ while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
53208
+ let optional;
53209
+ if (ch === Jsep.QUMARK_CODE) {
53210
+ if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
53211
+ break;
53212
+ }
53213
+ optional = true;
53214
+ this.index += 2;
53215
+ this.gobbleSpaces();
53216
+ ch = this.code;
53217
+ }
53218
+ this.index++;
53219
+ if (ch === Jsep.OBRACK_CODE) {
53220
+ node = {
53221
+ type: Jsep.MEMBER_EXP,
53222
+ computed: true,
53223
+ object: node,
53224
+ property: this.gobbleExpression()
53225
+ };
53226
+ if (!node.property) {
53227
+ this.throwError('Unexpected "' + this.char + '"');
53228
+ }
53229
+ this.gobbleSpaces();
53230
+ ch = this.code;
53231
+ if (ch !== Jsep.CBRACK_CODE) {
53232
+ this.throwError("Unclosed [");
53233
+ }
53234
+ this.index++;
53235
+ } else if (ch === Jsep.OPAREN_CODE) {
53236
+ node = {
53237
+ type: Jsep.CALL_EXP,
53238
+ "arguments": this.gobbleArguments(Jsep.CPAREN_CODE),
53239
+ callee: node
53240
+ };
53241
+ } else if (ch === Jsep.PERIOD_CODE || optional) {
53242
+ if (optional) {
53243
+ this.index--;
53244
+ }
53245
+ this.gobbleSpaces();
53246
+ node = {
53247
+ type: Jsep.MEMBER_EXP,
53248
+ computed: false,
53249
+ object: node,
53250
+ property: this.gobbleIdentifier()
53251
+ };
53252
+ }
53253
+ if (optional) {
53254
+ node.optional = true;
53255
+ }
53256
+ this.gobbleSpaces();
53257
+ ch = this.code;
53258
+ }
53259
+ return node;
53260
+ }
53261
+ /**
53262
+ * Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
53263
+ * keep track of everything in the numeric literal and then calling `parseFloat` on that string
53264
+ * @returns {jsep.Literal}
53265
+ */
53266
+ gobbleNumericLiteral() {
53267
+ let number4 = "", ch, chCode;
53268
+ while (Jsep.isDecimalDigit(this.code)) {
53269
+ number4 += this.expr.charAt(this.index++);
53270
+ }
53271
+ if (this.code === Jsep.PERIOD_CODE) {
53272
+ number4 += this.expr.charAt(this.index++);
53273
+ while (Jsep.isDecimalDigit(this.code)) {
53274
+ number4 += this.expr.charAt(this.index++);
53275
+ }
53276
+ }
53277
+ ch = this.char;
53278
+ if (ch === "e" || ch === "E") {
53279
+ number4 += this.expr.charAt(this.index++);
53280
+ ch = this.char;
53281
+ if (ch === "+" || ch === "-") {
53282
+ number4 += this.expr.charAt(this.index++);
53283
+ }
53284
+ while (Jsep.isDecimalDigit(this.code)) {
53285
+ number4 += this.expr.charAt(this.index++);
53286
+ }
53287
+ if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
53288
+ this.throwError("Expected exponent (" + number4 + this.char + ")");
53289
+ }
53290
+ }
53291
+ chCode = this.code;
53292
+ if (Jsep.isIdentifierStart(chCode)) {
53293
+ this.throwError("Variable names cannot start with a number (" + number4 + this.char + ")");
53294
+ } else if (chCode === Jsep.PERIOD_CODE || number4.length === 1 && number4.charCodeAt(0) === Jsep.PERIOD_CODE) {
53295
+ this.throwError("Unexpected period");
53296
+ }
53297
+ return {
53298
+ type: Jsep.LITERAL,
53299
+ value: parseFloat(number4),
53300
+ raw: number4
53301
+ };
53302
+ }
53303
+ /**
53304
+ * Parses a string literal, staring with single or double quotes with basic support for escape codes
53305
+ * e.g. `"hello world"`, `'this is\nJSEP'`
53306
+ * @returns {jsep.Literal}
53307
+ */
53308
+ gobbleStringLiteral() {
53309
+ let str = "";
53310
+ const startIndex = this.index;
53311
+ const quote = this.expr.charAt(this.index++);
53312
+ let closed = false;
53313
+ while (this.index < this.expr.length) {
53314
+ let ch = this.expr.charAt(this.index++);
53315
+ if (ch === quote) {
53316
+ closed = true;
53317
+ break;
53318
+ } else if (ch === "\\") {
53319
+ ch = this.expr.charAt(this.index++);
53320
+ switch (ch) {
53321
+ case "n":
53322
+ str += "\n";
53323
+ break;
53324
+ case "r":
53325
+ str += "\r";
53326
+ break;
53327
+ case "t":
53328
+ str += " ";
53329
+ break;
53330
+ case "b":
53331
+ str += "\b";
53332
+ break;
53333
+ case "f":
53334
+ str += "\f";
53335
+ break;
53336
+ case "v":
53337
+ str += "\v";
53338
+ break;
53339
+ default:
53340
+ str += ch;
53341
+ }
53342
+ } else {
53343
+ str += ch;
53344
+ }
53345
+ }
53346
+ if (!closed) {
53347
+ this.throwError('Unclosed quote after "' + str + '"');
53348
+ }
53349
+ return {
53350
+ type: Jsep.LITERAL,
53351
+ value: str,
53352
+ raw: this.expr.substring(startIndex, this.index)
53353
+ };
53354
+ }
53355
+ /**
53356
+ * Gobbles only identifiers
53357
+ * e.g.: `foo`, `_value`, `$x1`
53358
+ * Also, this function checks if that identifier is a literal:
53359
+ * (e.g. `true`, `false`, `null`) or `this`
53360
+ * @returns {jsep.Identifier}
53361
+ */
53362
+ gobbleIdentifier() {
53363
+ let ch = this.code, start = this.index;
53364
+ if (Jsep.isIdentifierStart(ch)) {
53365
+ this.index++;
53366
+ } else {
53367
+ this.throwError("Unexpected " + this.char);
53368
+ }
53369
+ while (this.index < this.expr.length) {
53370
+ ch = this.code;
53371
+ if (Jsep.isIdentifierPart(ch)) {
53372
+ this.index++;
53373
+ } else {
53374
+ break;
53375
+ }
53376
+ }
53377
+ return {
53378
+ type: Jsep.IDENTIFIER,
53379
+ name: this.expr.slice(start, this.index)
53380
+ };
53381
+ }
53382
+ /**
53383
+ * Gobbles a list of arguments within the context of a function call
53384
+ * or array literal. This function also assumes that the opening character
53385
+ * `(` or `[` has already been gobbled, and gobbles expressions and commas
53386
+ * until the terminator character `)` or `]` is encountered.
53387
+ * e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
53388
+ * @param {number} termination
53389
+ * @returns {jsep.Expression[]}
53390
+ */
53391
+ gobbleArguments(termination) {
53392
+ const args = [];
53393
+ let closed = false;
53394
+ let separator_count = 0;
53395
+ while (this.index < this.expr.length) {
53396
+ this.gobbleSpaces();
53397
+ let ch_i = this.code;
53398
+ if (ch_i === termination) {
53399
+ closed = true;
53400
+ this.index++;
53401
+ if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
53402
+ this.throwError("Unexpected token " + String.fromCharCode(termination));
53403
+ }
53404
+ break;
53405
+ } else if (ch_i === Jsep.COMMA_CODE) {
53406
+ this.index++;
53407
+ separator_count++;
53408
+ if (separator_count !== args.length) {
53409
+ if (termination === Jsep.CPAREN_CODE) {
53410
+ this.throwError("Unexpected token ,");
53411
+ } else if (termination === Jsep.CBRACK_CODE) {
53412
+ for (let arg = args.length; arg < separator_count; arg++) {
53413
+ args.push(null);
53414
+ }
53415
+ }
53416
+ }
53417
+ } else if (args.length !== separator_count && separator_count !== 0) {
53418
+ this.throwError("Expected comma");
53419
+ } else {
53420
+ const node = this.gobbleExpression();
53421
+ if (!node || node.type === Jsep.COMPOUND) {
53422
+ this.throwError("Expected comma");
53423
+ }
53424
+ args.push(node);
53425
+ }
53426
+ }
53427
+ if (!closed) {
53428
+ this.throwError("Expected " + String.fromCharCode(termination));
53429
+ }
53430
+ return args;
53431
+ }
53432
+ /**
53433
+ * Responsible for parsing a group of things within parentheses `()`
53434
+ * that have no identifier in front (so not a function call)
53435
+ * This function assumes that it needs to gobble the opening parenthesis
53436
+ * and then tries to gobble everything within that parenthesis, assuming
53437
+ * that the next thing it should see is the close parenthesis. If not,
53438
+ * then the expression probably doesn't have a `)`
53439
+ * @returns {boolean|jsep.Expression}
53440
+ */
53441
+ gobbleGroup() {
53442
+ this.index++;
53443
+ let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
53444
+ if (this.code === Jsep.CPAREN_CODE) {
53445
+ this.index++;
53446
+ if (nodes.length === 1) {
53447
+ return nodes[0];
53448
+ } else if (!nodes.length) {
53449
+ return false;
53450
+ } else {
53451
+ return {
53452
+ type: Jsep.SEQUENCE_EXP,
53453
+ expressions: nodes
53454
+ };
53455
+ }
53456
+ } else {
53457
+ this.throwError("Unclosed (");
53458
+ }
53459
+ }
53460
+ /**
53461
+ * Responsible for parsing Array literals `[1, 2, 3]`
53462
+ * This function assumes that it needs to gobble the opening bracket
53463
+ * and then tries to gobble the expressions as arguments.
53464
+ * @returns {jsep.ArrayExpression}
53465
+ */
53466
+ gobbleArray() {
53467
+ this.index++;
53468
+ return {
53469
+ type: Jsep.ARRAY_EXP,
53470
+ elements: this.gobbleArguments(Jsep.CBRACK_CODE)
53471
+ };
53472
+ }
53473
+ }
53474
+ const hooks = new Hooks();
53475
+ Object.assign(Jsep, {
53476
+ hooks,
53477
+ plugins: new Plugins(Jsep),
53478
+ // Node Types
53479
+ // ----------
53480
+ // This is the full set of types that any JSEP node can be.
53481
+ // Store them here to save space when minified
53482
+ COMPOUND: "Compound",
53483
+ SEQUENCE_EXP: "SequenceExpression",
53484
+ IDENTIFIER: "Identifier",
53485
+ MEMBER_EXP: "MemberExpression",
53486
+ LITERAL: "Literal",
53487
+ THIS_EXP: "ThisExpression",
53488
+ CALL_EXP: "CallExpression",
53489
+ UNARY_EXP: "UnaryExpression",
53490
+ BINARY_EXP: "BinaryExpression",
53491
+ ARRAY_EXP: "ArrayExpression",
53492
+ TAB_CODE: 9,
53493
+ LF_CODE: 10,
53494
+ CR_CODE: 13,
53495
+ SPACE_CODE: 32,
53496
+ PERIOD_CODE: 46,
53497
+ // '.'
53498
+ COMMA_CODE: 44,
53499
+ // ','
53500
+ SQUOTE_CODE: 39,
53501
+ // single quote
53502
+ DQUOTE_CODE: 34,
53503
+ // double quotes
53504
+ OPAREN_CODE: 40,
53505
+ // (
53506
+ CPAREN_CODE: 41,
53507
+ // )
53508
+ OBRACK_CODE: 91,
53509
+ // [
53510
+ CBRACK_CODE: 93,
53511
+ // ]
53512
+ QUMARK_CODE: 63,
53513
+ // ?
53514
+ SEMCOL_CODE: 59,
53515
+ // ;
53516
+ COLON_CODE: 58,
53517
+ // :
53518
+ // Operations
53519
+ // ----------
53520
+ // Use a quickly-accessible map to store all of the unary operators
53521
+ // Values are set to `1` (it really doesn't matter)
53522
+ unary_ops: {
53523
+ "-": 1,
53524
+ "!": 1,
53525
+ "~": 1,
53526
+ "+": 1
53527
+ },
53528
+ // Also use a map for the binary operations but set their values to their
53529
+ // binary precedence for quick reference (higher number = higher precedence)
53530
+ // see [Order of operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
53531
+ binary_ops: {
53532
+ "||": 1,
53533
+ "??": 1,
53534
+ "&&": 2,
53535
+ "|": 3,
53536
+ "^": 4,
53537
+ "&": 5,
53538
+ "==": 6,
53539
+ "!=": 6,
53540
+ "===": 6,
53541
+ "!==": 6,
53542
+ "<": 7,
53543
+ ">": 7,
53544
+ "<=": 7,
53545
+ ">=": 7,
53546
+ "<<": 8,
53547
+ ">>": 8,
53548
+ ">>>": 8,
53549
+ "+": 9,
53550
+ "-": 9,
53551
+ "*": 10,
53552
+ "/": 10,
53553
+ "%": 10,
53554
+ "**": 11
53555
+ },
53556
+ // sets specific binary_ops as right-associative
53557
+ right_associative: /* @__PURE__ */ new Set(["**"]),
53558
+ // Additional valid identifier chars, apart from a-z, A-Z and 0-9 (except on the starting char)
53559
+ additional_identifier_chars: /* @__PURE__ */ new Set(["$", "_"]),
53560
+ // Literals
53561
+ // ----------
53562
+ // Store the values to return for the various literals we may encounter
53563
+ literals: {
53564
+ "true": true,
53565
+ "false": false,
53566
+ "null": null
53567
+ },
53568
+ // Except for `this`, which is special. This could be changed to something like `'self'` as well
53569
+ this_str: "this"
53570
+ });
53571
+ Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
53572
+ Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
53573
+ const jsep = (expr) => new Jsep(expr).parse();
53574
+ const stdClassProps = Object.getOwnPropertyNames(class Test {
53575
+ });
53576
+ Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === void 0).forEach((m) => {
53577
+ jsep[m] = Jsep[m];
53578
+ });
53579
+ jsep.Jsep = Jsep;
53580
+ const CONDITIONAL_EXP = "ConditionalExpression";
53581
+ var ternary = {
53582
+ name: "ternary",
53583
+ init(jsep2) {
53584
+ jsep2.hooks.add("after-expression", function gobbleTernary(env) {
53585
+ if (env.node && this.code === jsep2.QUMARK_CODE) {
53586
+ this.index++;
53587
+ const test2 = env.node;
53588
+ const consequent = this.gobbleExpression();
53589
+ if (!consequent) {
53590
+ this.throwError("Expected expression");
53591
+ }
53592
+ this.gobbleSpaces();
53593
+ if (this.code === jsep2.COLON_CODE) {
53594
+ this.index++;
53595
+ const alternate = this.gobbleExpression();
53596
+ if (!alternate) {
53597
+ this.throwError("Expected expression");
53598
+ }
53599
+ env.node = {
53600
+ type: CONDITIONAL_EXP,
53601
+ test: test2,
53602
+ consequent,
53603
+ alternate
53604
+ };
53605
+ if (test2.operator && jsep2.binary_ops[test2.operator] <= 0.9) {
53606
+ let newTest = test2;
53607
+ while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
53608
+ newTest = newTest.right;
53609
+ }
53610
+ env.node.test = newTest.right;
53611
+ newTest.right = env.node;
53612
+ env.node = test2;
53613
+ }
53614
+ } else {
53615
+ this.throwError("Expected :");
53616
+ }
53617
+ }
53618
+ });
53619
+ }
53620
+ };
53621
+ jsep.plugins.register(ternary);
53622
+ const FSLASH_CODE = 47;
53623
+ const BSLASH_CODE = 92;
53624
+ var index = {
53625
+ name: "regex",
53626
+ init(jsep2) {
53627
+ jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
53628
+ if (this.code === FSLASH_CODE) {
53629
+ const patternIndex = ++this.index;
53630
+ let inCharSet = false;
53631
+ while (this.index < this.expr.length) {
53632
+ if (this.code === FSLASH_CODE && !inCharSet) {
53633
+ const pattern4 = this.expr.slice(patternIndex, this.index);
53634
+ let flags = "";
53635
+ while (++this.index < this.expr.length) {
53636
+ const code = this.code;
53637
+ if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
53638
+ flags += this.char;
53639
+ } else {
53640
+ break;
53641
+ }
53642
+ }
53643
+ let value;
53644
+ try {
53645
+ value = new RegExp(pattern4, flags);
53646
+ } catch (e) {
53647
+ this.throwError(e.message);
53648
+ }
53649
+ env.node = {
53650
+ type: jsep2.LITERAL,
53651
+ value,
53652
+ raw: this.expr.slice(patternIndex - 1, this.index)
53653
+ };
53654
+ env.node = this.gobbleTokenProperty(env.node);
53655
+ return env.node;
53656
+ }
53657
+ if (this.code === jsep2.OBRACK_CODE) {
53658
+ inCharSet = true;
53659
+ } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
53660
+ inCharSet = false;
53661
+ }
53662
+ this.index += this.code === BSLASH_CODE ? 2 : 1;
53663
+ }
53664
+ this.throwError("Unclosed Regex");
53665
+ }
53666
+ });
53667
+ }
53668
+ };
53669
+ const PLUS_CODE = 43;
53670
+ const MINUS_CODE = 45;
53671
+ const plugin = {
53672
+ name: "assignment",
53673
+ assignmentOperators: /* @__PURE__ */ new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
53674
+ updateOperators: [PLUS_CODE, MINUS_CODE],
53675
+ assignmentPrecedence: 0.9,
53676
+ init(jsep2) {
53677
+ const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
53678
+ plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
53679
+ jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
53680
+ const code = this.code;
53681
+ if (plugin.updateOperators.some((c2) => c2 === code && c2 === this.expr.charCodeAt(this.index + 1))) {
53682
+ this.index += 2;
53683
+ env.node = {
53684
+ type: "UpdateExpression",
53685
+ operator: code === PLUS_CODE ? "++" : "--",
53686
+ argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
53687
+ prefix: true
53688
+ };
53689
+ if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
53690
+ this.throwError(`Unexpected ${env.node.operator}`);
53691
+ }
53692
+ }
53693
+ });
53694
+ jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
53695
+ if (env.node) {
53696
+ const code = this.code;
53697
+ if (plugin.updateOperators.some((c2) => c2 === code && c2 === this.expr.charCodeAt(this.index + 1))) {
53698
+ if (!updateNodeTypes.includes(env.node.type)) {
53699
+ this.throwError(`Unexpected ${env.node.operator}`);
53700
+ }
53701
+ this.index += 2;
53702
+ env.node = {
53703
+ type: "UpdateExpression",
53704
+ operator: code === PLUS_CODE ? "++" : "--",
53705
+ argument: env.node,
53706
+ prefix: false
53707
+ };
53708
+ }
53709
+ }
53710
+ });
53711
+ jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
53712
+ if (env.node) {
53713
+ updateBinariesToAssignments(env.node);
53714
+ }
53715
+ });
53716
+ function updateBinariesToAssignments(node) {
53717
+ if (plugin.assignmentOperators.has(node.operator)) {
53718
+ node.type = "AssignmentExpression";
53719
+ updateBinariesToAssignments(node.left);
53720
+ updateBinariesToAssignments(node.right);
53721
+ } else if (!node.operator) {
53722
+ Object.values(node).forEach((val) => {
53723
+ if (val && typeof val === "object") {
53724
+ updateBinariesToAssignments(val);
53725
+ }
53726
+ });
53727
+ }
53728
+ }
53729
+ }
53730
+ };
53731
+ jsep.plugins.register(index, plugin);
53732
+ jsep.addUnaryOp("typeof");
53733
+ jsep.addUnaryOp("void");
53734
+ jsep.addLiteral("null", null);
53735
+ jsep.addLiteral("undefined", void 0);
53736
+ const BLOCKED_PROTO_PROPERTIES = /* @__PURE__ */ new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
53737
+ const SafeEval = {
53738
+ /**
53739
+ * @param {jsep.Expression} ast
53740
+ * @param {Record<string, any>} subs
53741
+ */
53742
+ evalAst(ast, subs) {
53743
+ switch (ast.type) {
53744
+ case "BinaryExpression":
53745
+ case "LogicalExpression":
53746
+ return SafeEval.evalBinaryExpression(ast, subs);
53747
+ case "Compound":
53748
+ return SafeEval.evalCompound(ast, subs);
53749
+ case "ConditionalExpression":
53750
+ return SafeEval.evalConditionalExpression(ast, subs);
53751
+ case "Identifier":
53752
+ return SafeEval.evalIdentifier(ast, subs);
53753
+ case "Literal":
53754
+ return SafeEval.evalLiteral(ast, subs);
53755
+ case "MemberExpression":
53756
+ return SafeEval.evalMemberExpression(ast, subs);
53757
+ case "UnaryExpression":
53758
+ return SafeEval.evalUnaryExpression(ast, subs);
53759
+ case "ArrayExpression":
53760
+ return SafeEval.evalArrayExpression(ast, subs);
53761
+ case "CallExpression":
53762
+ return SafeEval.evalCallExpression(ast, subs);
53763
+ case "AssignmentExpression":
53764
+ return SafeEval.evalAssignmentExpression(ast, subs);
53765
+ default:
53766
+ throw SyntaxError("Unexpected expression", ast);
53767
+ }
53768
+ },
53769
+ evalBinaryExpression(ast, subs) {
53770
+ const result = {
53771
+ "||": (a, b2) => a || b2(),
53772
+ "&&": (a, b2) => a && b2(),
53773
+ "|": (a, b2) => a | b2(),
53774
+ "^": (a, b2) => a ^ b2(),
53775
+ "&": (a, b2) => a & b2(),
53776
+ // eslint-disable-next-line eqeqeq -- API
53777
+ "==": (a, b2) => a == b2(),
53778
+ // eslint-disable-next-line eqeqeq -- API
53779
+ "!=": (a, b2) => a != b2(),
53780
+ "===": (a, b2) => a === b2(),
53781
+ "!==": (a, b2) => a !== b2(),
53782
+ "<": (a, b2) => a < b2(),
53783
+ ">": (a, b2) => a > b2(),
53784
+ "<=": (a, b2) => a <= b2(),
53785
+ ">=": (a, b2) => a >= b2(),
53786
+ "<<": (a, b2) => a << b2(),
53787
+ ">>": (a, b2) => a >> b2(),
53788
+ ">>>": (a, b2) => a >>> b2(),
53789
+ "+": (a, b2) => a + b2(),
53790
+ "-": (a, b2) => a - b2(),
53791
+ "*": (a, b2) => a * b2(),
53792
+ "/": (a, b2) => a / b2(),
53793
+ "%": (a, b2) => a % b2()
53794
+ }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
53795
+ return result;
53796
+ },
53797
+ evalCompound(ast, subs) {
53798
+ let last2;
53799
+ for (let i = 0; i < ast.body.length; i++) {
53800
+ if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
53801
+ i += 1;
53802
+ }
53803
+ const expr = ast.body[i];
53804
+ last2 = SafeEval.evalAst(expr, subs);
53805
+ }
53806
+ return last2;
53807
+ },
53808
+ evalConditionalExpression(ast, subs) {
53809
+ if (SafeEval.evalAst(ast.test, subs)) {
53810
+ return SafeEval.evalAst(ast.consequent, subs);
53811
+ }
53812
+ return SafeEval.evalAst(ast.alternate, subs);
53813
+ },
53814
+ evalIdentifier(ast, subs) {
53815
+ if (Object.hasOwn(subs, ast.name)) {
53816
+ return subs[ast.name];
53817
+ }
53818
+ throw ReferenceError(`${ast.name} is not defined`);
53819
+ },
53820
+ evalLiteral(ast) {
53821
+ return ast.value;
53822
+ },
53823
+ evalMemberExpression(ast, subs) {
53824
+ const prop = String(
53825
+ // NOTE: `String(value)` throws error when
53826
+ // value has overwritten the toString method to return non-string
53827
+ // i.e. `value = {toString: () => []}`
53828
+ ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name
53829
+ // `object.property` property is Identifier
53830
+ );
53831
+ const obj = SafeEval.evalAst(ast.object, subs);
53832
+ if (obj === void 0 || obj === null) {
53833
+ throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
53834
+ }
53835
+ if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
53836
+ throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
53837
+ }
53838
+ const result = obj[prop];
53839
+ if (typeof result === "function") {
53840
+ return result.bind(obj);
53841
+ }
53842
+ return result;
53843
+ },
53844
+ evalUnaryExpression(ast, subs) {
53845
+ const result = {
53846
+ "-": (a) => -SafeEval.evalAst(a, subs),
53847
+ "!": (a) => !SafeEval.evalAst(a, subs),
53848
+ "~": (a) => ~SafeEval.evalAst(a, subs),
53849
+ // eslint-disable-next-line no-implicit-coercion -- API
53850
+ "+": (a) => +SafeEval.evalAst(a, subs),
53851
+ typeof: (a) => typeof SafeEval.evalAst(a, subs),
53852
+ // eslint-disable-next-line no-void, sonarjs/void-use -- feature
53853
+ void: (a) => void SafeEval.evalAst(a, subs)
53854
+ }[ast.operator](ast.argument);
53855
+ return result;
53856
+ },
53857
+ evalArrayExpression(ast, subs) {
53858
+ return ast.elements.map((el) => SafeEval.evalAst(el, subs));
53859
+ },
53860
+ evalCallExpression(ast, subs) {
53861
+ const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
53862
+ const func = SafeEval.evalAst(ast.callee, subs);
53863
+ if (func === Function) {
53864
+ throw new Error("Function constructor is disabled");
53865
+ }
53866
+ return func(...args);
53867
+ },
53868
+ evalAssignmentExpression(ast, subs) {
53869
+ if (ast.left.type !== "Identifier") {
53870
+ throw SyntaxError("Invalid left-hand side in assignment");
53871
+ }
53872
+ const id = ast.left.name;
53873
+ const value = SafeEval.evalAst(ast.right, subs);
53874
+ subs[id] = value;
53875
+ return subs[id];
53876
+ }
53877
+ };
53878
+ class SafeScript {
53879
+ /**
53880
+ * @param {string} expr Expression to evaluate
53881
+ */
53882
+ constructor(expr) {
53883
+ this.code = expr;
53884
+ this.ast = jsep(this.code);
53885
+ }
53886
+ /**
53887
+ * @param {object} context Object whose items will be added
53888
+ * to evaluation
53889
+ * @returns {EvaluatedResult} Result of evaluated code
53890
+ */
53891
+ runInNewContext(context) {
53892
+ const keyMap = Object.assign(/* @__PURE__ */ Object.create(null), context);
53893
+ return SafeEval.evalAst(this.ast, keyMap);
53894
+ }
53895
+ }
53896
+ function push(arr, item) {
53897
+ arr = arr.slice();
53898
+ arr.push(item);
53899
+ return arr;
53900
+ }
53901
+ function unshift(item, arr) {
53902
+ arr = arr.slice();
53903
+ arr.unshift(item);
53904
+ return arr;
53905
+ }
53906
+ class NewError extends Error {
53907
+ /**
53908
+ * @param {AnyResult} value The evaluated scalar value
53909
+ */
53910
+ constructor(value) {
53911
+ super('JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)');
53912
+ this.avoidNew = true;
53913
+ this.value = value;
53914
+ this.name = "NewError";
53915
+ }
53916
+ }
53917
+ function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
53918
+ if (!(this instanceof JSONPath)) {
53919
+ try {
53920
+ return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
53921
+ } catch (e) {
53922
+ if (!e.avoidNew) {
53923
+ throw e;
53924
+ }
53925
+ return e.value;
53926
+ }
53927
+ }
53928
+ if (typeof opts === "string") {
53929
+ otherTypeCallback = callback;
53930
+ callback = obj;
53931
+ obj = expr;
53932
+ expr = opts;
53933
+ opts = null;
53934
+ }
53935
+ const optObj = opts && typeof opts === "object";
53936
+ opts = opts || {};
53937
+ this.json = opts.json || obj;
53938
+ this.path = opts.path || expr;
53939
+ this.resultType = opts.resultType || "value";
53940
+ this.flatten = opts.flatten || false;
53941
+ this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
53942
+ this.sandbox = opts.sandbox || {};
53943
+ this.eval = opts.eval === void 0 ? "safe" : opts.eval;
53944
+ this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
53945
+ this.parent = opts.parent || null;
53946
+ this.parentProperty = opts.parentProperty || null;
53947
+ this.callback = opts.callback || callback || null;
53948
+ this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
53949
+ throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.");
53950
+ };
53951
+ if (opts.autostart !== false) {
53952
+ const args = {
53953
+ path: optObj ? opts.path : expr
53954
+ };
53955
+ if (!optObj) {
53956
+ args.json = obj;
53957
+ } else if ("json" in opts) {
53958
+ args.json = opts.json;
53959
+ }
53960
+ const ret = this.evaluate(args);
53961
+ if (!ret || typeof ret !== "object") {
53962
+ throw new NewError(ret);
53963
+ }
53964
+ return ret;
53965
+ }
53966
+ }
53967
+ JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
53968
+ let currParent = this.parent, currParentProperty = this.parentProperty;
53969
+ let {
53970
+ flatten: flatten2,
53971
+ wrap
53972
+ } = this;
53973
+ this.currResultType = this.resultType;
53974
+ this.currEval = this.eval;
53975
+ this.currSandbox = this.sandbox;
53976
+ callback = callback || this.callback;
53977
+ this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
53978
+ json = json || this.json;
53979
+ expr = expr || this.path;
53980
+ if (expr && typeof expr === "object" && !Array.isArray(expr)) {
53981
+ if (!expr.path && expr.path !== "") {
53982
+ throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');
53983
+ }
53984
+ if (!Object.hasOwn(expr, "json")) {
53985
+ throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');
53986
+ }
53987
+ ({
53988
+ json
53989
+ } = expr);
53990
+ flatten2 = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten2;
53991
+ this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
53992
+ this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
53993
+ wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
53994
+ this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
53995
+ callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
53996
+ this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
53997
+ currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
53998
+ currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
53999
+ expr = expr.path;
54000
+ }
54001
+ currParent = currParent || null;
54002
+ currParentProperty = currParentProperty || null;
54003
+ if (Array.isArray(expr)) {
54004
+ expr = JSONPath.toPathString(expr);
54005
+ }
54006
+ if (!expr && expr !== "" || !json) {
54007
+ return void 0;
54008
+ }
54009
+ const exprList = JSONPath.toPathArray(expr);
54010
+ if (exprList[0] === "$" && exprList.length > 1) {
54011
+ exprList.shift();
54012
+ }
54013
+ this._hasParentSelector = null;
54014
+ const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea2) {
54015
+ return ea2 && !ea2.isParentSelector;
54016
+ });
54017
+ if (!result.length) {
54018
+ return wrap ? [] : void 0;
54019
+ }
54020
+ if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
54021
+ return this._getPreferredOutput(result[0]);
54022
+ }
54023
+ return result.reduce((rslt, ea2) => {
54024
+ const valOrPath = this._getPreferredOutput(ea2);
54025
+ if (flatten2 && Array.isArray(valOrPath)) {
54026
+ rslt = rslt.concat(valOrPath);
54027
+ } else {
54028
+ rslt.push(valOrPath);
54029
+ }
54030
+ return rslt;
54031
+ }, []);
54032
+ };
54033
+ JSONPath.prototype._getPreferredOutput = function(ea2) {
54034
+ const resultType = this.currResultType;
54035
+ switch (resultType) {
54036
+ case "all": {
54037
+ const path2 = Array.isArray(ea2.path) ? ea2.path : JSONPath.toPathArray(ea2.path);
54038
+ ea2.pointer = JSONPath.toPointer(path2);
54039
+ ea2.path = typeof ea2.path === "string" ? ea2.path : JSONPath.toPathString(ea2.path);
54040
+ return ea2;
54041
+ }
54042
+ case "value":
54043
+ case "parent":
54044
+ case "parentProperty":
54045
+ return ea2[resultType];
54046
+ case "path":
54047
+ return JSONPath.toPathString(ea2[resultType]);
54048
+ case "pointer":
54049
+ return JSONPath.toPointer(ea2.path);
54050
+ default:
54051
+ throw new TypeError("Unknown result type");
54052
+ }
54053
+ };
54054
+ JSONPath.prototype._handleCallback = function(fullRetObj, callback, type4) {
54055
+ if (callback) {
54056
+ const preferredOutput = this._getPreferredOutput(fullRetObj);
54057
+ fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
54058
+ callback(preferredOutput, type4, fullRetObj);
54059
+ }
54060
+ };
54061
+ JSONPath.prototype._trace = function(expr, val, path2, parent2, parentPropName, callback, hasArrExpr, literalPriority) {
54062
+ let retObj;
54063
+ if (!expr.length) {
54064
+ retObj = {
54065
+ path: path2,
54066
+ value: val,
54067
+ parent: parent2,
54068
+ parentProperty: parentPropName,
54069
+ hasArrExpr
54070
+ };
54071
+ this._handleCallback(retObj, callback, "value");
54072
+ return retObj;
54073
+ }
54074
+ const loc = expr[0], x2 = expr.slice(1);
54075
+ const ret = [];
54076
+ function addRet(elems) {
54077
+ if (Array.isArray(elems)) {
54078
+ elems.forEach((t) => {
54079
+ ret.push(t);
54080
+ });
54081
+ } else {
54082
+ ret.push(elems);
54083
+ }
54084
+ }
54085
+ if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
54086
+ addRet(this._trace(x2, val[loc], push(path2, loc), val, loc, callback, hasArrExpr));
54087
+ } else if (loc === "*") {
54088
+ this._walk(val, (m) => {
54089
+ addRet(this._trace(x2, val[m], push(path2, m), val, m, callback, true, true));
54090
+ });
54091
+ } else if (loc === "..") {
54092
+ addRet(this._trace(x2, val, path2, parent2, parentPropName, callback, hasArrExpr));
54093
+ this._walk(val, (m) => {
54094
+ if (typeof val[m] === "object") {
54095
+ addRet(this._trace(expr.slice(), val[m], push(path2, m), val, m, callback, true));
54096
+ }
54097
+ });
54098
+ } else if (loc === "^") {
54099
+ this._hasParentSelector = true;
54100
+ return {
54101
+ path: path2.slice(0, -1),
54102
+ expr: x2,
54103
+ isParentSelector: true
54104
+ };
54105
+ } else if (loc === "~") {
54106
+ retObj = {
54107
+ path: push(path2, loc),
54108
+ value: parentPropName,
54109
+ parent: parent2,
54110
+ parentProperty: null
54111
+ };
54112
+ this._handleCallback(retObj, callback, "property");
54113
+ return retObj;
54114
+ } else if (loc === "$") {
54115
+ addRet(this._trace(x2, val, path2, null, null, callback, hasArrExpr));
54116
+ } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
54117
+ addRet(this._slice(loc, x2, val, path2, parent2, parentPropName, callback));
54118
+ } else if (loc.indexOf("?(") === 0) {
54119
+ if (this.currEval === false) {
54120
+ throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
54121
+ }
54122
+ const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
54123
+ const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
54124
+ if (nested) {
54125
+ this._walk(val, (m) => {
54126
+ const npath = [nested[2]];
54127
+ const nvalue = nested[1] ? val[m][nested[1]] : val[m];
54128
+ const filterResults = this._trace(npath, nvalue, path2, parent2, parentPropName, callback, true);
54129
+ if (filterResults.length > 0) {
54130
+ addRet(this._trace(x2, val[m], push(path2, m), val, m, callback, true));
54131
+ }
54132
+ });
54133
+ } else {
54134
+ this._walk(val, (m) => {
54135
+ if (this._eval(safeLoc, val[m], m, path2, parent2, parentPropName)) {
54136
+ addRet(this._trace(x2, val[m], push(path2, m), val, m, callback, true));
54137
+ }
54138
+ });
54139
+ }
54140
+ } else if (loc[0] === "(") {
54141
+ if (this.currEval === false) {
54142
+ throw new Error("Eval [(expr)] prevented in JSONPath expression.");
54143
+ }
54144
+ addRet(this._trace(unshift(this._eval(loc, val, path2.at(-1), path2.slice(0, -1), parent2, parentPropName), x2), val, path2, parent2, parentPropName, callback, hasArrExpr));
54145
+ } else if (loc[0] === "@") {
54146
+ let addType = false;
54147
+ const valueType = loc.slice(1, -2);
54148
+ switch (valueType) {
54149
+ case "scalar":
54150
+ if (!val || !["object", "function"].includes(typeof val)) {
54151
+ addType = true;
54152
+ }
54153
+ break;
54154
+ case "boolean":
54155
+ case "string":
54156
+ case "undefined":
54157
+ case "function":
54158
+ if (typeof val === valueType) {
54159
+ addType = true;
54160
+ }
54161
+ break;
54162
+ case "integer":
54163
+ if (Number.isFinite(val) && !(val % 1)) {
54164
+ addType = true;
54165
+ }
54166
+ break;
54167
+ case "number":
54168
+ if (Number.isFinite(val)) {
54169
+ addType = true;
54170
+ }
54171
+ break;
54172
+ case "nonFinite":
54173
+ if (typeof val === "number" && !Number.isFinite(val)) {
54174
+ addType = true;
54175
+ }
54176
+ break;
54177
+ case "object":
54178
+ if (val && typeof val === valueType) {
54179
+ addType = true;
54180
+ }
54181
+ break;
54182
+ case "array":
54183
+ if (Array.isArray(val)) {
54184
+ addType = true;
54185
+ }
54186
+ break;
54187
+ case "other":
54188
+ addType = this.currOtherTypeCallback(val, path2, parent2, parentPropName);
54189
+ break;
54190
+ case "null":
54191
+ if (val === null) {
54192
+ addType = true;
54193
+ }
54194
+ break;
54195
+ /* c8 ignore next 2 */
54196
+ default:
54197
+ throw new TypeError("Unknown value type " + valueType);
54198
+ }
54199
+ if (addType) {
54200
+ retObj = {
54201
+ path: path2,
54202
+ value: val,
54203
+ parent: parent2,
54204
+ parentProperty: parentPropName
54205
+ };
54206
+ this._handleCallback(retObj, callback, "value");
54207
+ return retObj;
54208
+ }
54209
+ } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
54210
+ const locProp = loc.slice(1);
54211
+ addRet(this._trace(x2, val[locProp], push(path2, locProp), val, locProp, callback, hasArrExpr, true));
54212
+ } else if (loc.includes(",")) {
54213
+ const parts = loc.split(",");
54214
+ for (const part of parts) {
54215
+ addRet(this._trace(unshift(part, x2), val, path2, parent2, parentPropName, callback, true));
54216
+ }
54217
+ } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
54218
+ addRet(this._trace(x2, val[loc], push(path2, loc), val, loc, callback, hasArrExpr, true));
54219
+ }
54220
+ if (this._hasParentSelector) {
54221
+ for (let t = 0; t < ret.length; t++) {
54222
+ const rett = ret[t];
54223
+ if (rett && rett.isParentSelector) {
54224
+ const tmp = this._trace(rett.expr, val, rett.path, parent2, parentPropName, callback, hasArrExpr);
54225
+ if (Array.isArray(tmp)) {
54226
+ ret[t] = tmp[0];
54227
+ const tl = tmp.length;
54228
+ for (let tt2 = 1; tt2 < tl; tt2++) {
54229
+ t++;
54230
+ ret.splice(t, 0, tmp[tt2]);
54231
+ }
54232
+ } else {
54233
+ ret[t] = tmp;
54234
+ }
54235
+ }
54236
+ }
54237
+ }
54238
+ return ret;
54239
+ };
54240
+ JSONPath.prototype._walk = function(val, f) {
54241
+ if (Array.isArray(val)) {
54242
+ const n = val.length;
54243
+ for (let i = 0; i < n; i++) {
54244
+ f(i);
54245
+ }
54246
+ } else if (val && typeof val === "object") {
54247
+ Object.keys(val).forEach((m) => {
54248
+ f(m);
54249
+ });
54250
+ }
54251
+ };
54252
+ JSONPath.prototype._slice = function(loc, expr, val, path2, parent2, parentPropName, callback) {
54253
+ if (!Array.isArray(val)) {
54254
+ return void 0;
54255
+ }
54256
+ const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
54257
+ let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
54258
+ start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
54259
+ end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
54260
+ const ret = [];
54261
+ for (let i = start; i < end; i += step) {
54262
+ const tmp = this._trace(unshift(i, expr), val, path2, parent2, parentPropName, callback, true);
54263
+ tmp.forEach((t) => {
54264
+ ret.push(t);
54265
+ });
54266
+ }
54267
+ return ret;
54268
+ };
54269
+ JSONPath.prototype._eval = function(code, _v, _vname, path2, parent2, parentPropName) {
54270
+ this.currSandbox._$_parentProperty = parentPropName;
54271
+ this.currSandbox._$_parent = parent2;
54272
+ this.currSandbox._$_property = _vname;
54273
+ this.currSandbox._$_root = this.json;
54274
+ this.currSandbox._$_v = _v;
54275
+ const containsPath = code.includes("@path");
54276
+ if (containsPath) {
54277
+ this.currSandbox._$_path = JSONPath.toPathString(path2.concat([_vname]));
54278
+ }
54279
+ const scriptCacheKey = this.currEval + "Script:" + code;
54280
+ if (!JSONPath.cache[scriptCacheKey]) {
54281
+ let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
54282
+ if (containsPath) {
54283
+ script = script.replaceAll("@path", "_$_path");
54284
+ }
54285
+ if (this.currEval === "safe" || this.currEval === true || this.currEval === void 0) {
54286
+ JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
54287
+ } else if (this.currEval === "native") {
54288
+ JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
54289
+ } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
54290
+ const CurrEval = this.currEval;
54291
+ JSONPath.cache[scriptCacheKey] = new CurrEval(script);
54292
+ } else if (typeof this.currEval === "function") {
54293
+ JSONPath.cache[scriptCacheKey] = {
54294
+ runInNewContext: (context) => this.currEval(script, context)
54295
+ };
54296
+ } else {
54297
+ throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
54298
+ }
54299
+ }
54300
+ try {
54301
+ return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
54302
+ } catch (e) {
54303
+ if (this.ignoreEvalErrors) {
54304
+ return false;
54305
+ }
54306
+ throw new Error("jsonPath: " + e.message + ": " + code);
54307
+ }
54308
+ };
54309
+ JSONPath.cache = {};
54310
+ JSONPath.toPathString = function(pathArr) {
54311
+ const x2 = pathArr, n = x2.length;
54312
+ let p = "$";
54313
+ for (let i = 1; i < n; i++) {
54314
+ if (!/^(~|\^|@.*?\(\))$/u.test(x2[i])) {
54315
+ p += /^[0-9*]+$/u.test(x2[i]) ? "[" + x2[i] + "]" : "['" + x2[i] + "']";
54316
+ }
54317
+ }
54318
+ return p;
54319
+ };
54320
+ JSONPath.toPointer = function(pointer) {
54321
+ const x2 = pointer, n = x2.length;
54322
+ let p = "";
54323
+ for (let i = 1; i < n; i++) {
54324
+ if (!/^(~|\^|@.*?\(\))$/u.test(x2[i])) {
54325
+ p += "/" + x2[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
54326
+ }
54327
+ }
54328
+ return p;
54329
+ };
54330
+ JSONPath.toPathArray = function(expr) {
54331
+ const {
54332
+ cache
54333
+ } = JSONPath;
54334
+ if (cache[expr]) {
54335
+ return cache[expr].concat();
54336
+ }
54337
+ const subx = [];
54338
+ const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
54339
+ return "[#" + (subx.push($1) - 1) + "]";
54340
+ }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
54341
+ return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
54342
+ }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
54343
+ return ";" + ups.split("").join(";") + ";";
54344
+ }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
54345
+ const exprList = normalized.split(";").map(function(exp) {
54346
+ const match = exp.match(/#(\d+)/u);
54347
+ return !match || !match[1] ? exp : subx[match[1]];
54348
+ });
54349
+ cache[expr] = exprList;
54350
+ return cache[expr].concat();
54351
+ };
54352
+ JSONPath.prototype.safeVm = {
54353
+ Script: SafeScript
54354
+ };
54355
+ const moveToAnotherArray = function(source, target, conditionCb) {
54356
+ const il = source.length;
54357
+ for (let i = 0; i < il; i++) {
54358
+ const item = source[i];
54359
+ if (conditionCb(item)) {
54360
+ target.push(source.splice(i--, 1)[0]);
54361
+ }
54362
+ }
54363
+ };
54364
+ class Script {
54365
+ /**
54366
+ * @param {string} expr Expression to evaluate
54367
+ */
54368
+ constructor(expr) {
54369
+ this.code = expr;
54370
+ }
54371
+ /**
54372
+ * @param {object} context Object whose items will be added
54373
+ * to evaluation
54374
+ * @returns {EvaluatedResult} Result of evaluated code
54375
+ */
54376
+ runInNewContext(context) {
54377
+ let expr = this.code;
54378
+ const keys2 = Object.keys(context);
54379
+ const funcs = [];
54380
+ moveToAnotherArray(keys2, funcs, (key) => {
54381
+ return typeof context[key] === "function";
54382
+ });
54383
+ const values = keys2.map((vr) => {
54384
+ return context[vr];
54385
+ });
54386
+ const funcString = funcs.reduce((s, func) => {
54387
+ let fString = context[func].toString();
54388
+ if (!/function/u.test(fString)) {
54389
+ fString = "function " + fString;
54390
+ }
54391
+ return "var " + func + "=" + fString + ";" + s;
54392
+ }, "");
54393
+ expr = funcString + expr;
54394
+ if (!/(['"])use strict\1/u.test(expr) && !keys2.includes("arguments")) {
54395
+ expr = "var arguments = undefined;" + expr;
54396
+ }
54397
+ expr = expr.replace(/;\s*$/u, "");
54398
+ const lastStatementEnd = expr.lastIndexOf(";");
54399
+ const code = lastStatementEnd !== -1 ? expr.slice(0, lastStatementEnd + 1) + " return " + expr.slice(lastStatementEnd + 1) : " return " + expr;
54400
+ return new Function(...keys2, code)(...values);
54401
+ }
54402
+ }
54403
+ JSONPath.prototype.vm = {
54404
+ Script
54405
+ };
52664
54406
  const parseJsonSchema = (schema2, paramsConfig = /* @__PURE__ */ new Map()) => {
52665
54407
  if (!schema2 || typeof schema2 !== "object") return schema2;
52666
54408
  switch (schema2.type) {
@@ -52682,7 +54424,7 @@ const parseJsonSchema = (schema2, paramsConfig = /* @__PURE__ */ new Map()) => {
52682
54424
  };
52683
54425
  function processJsonSchemaSubModel0(mapItem, apiData) {
52684
54426
  return mapItem.fields.reduce((acc, { leftFieldKey, rightFieldKey }) => {
52685
- let value = get(apiData, `${rightFieldKey}.0`);
54427
+ let value = JSONPath({ path: rightFieldKey, json: apiData })?.[0];
52686
54428
  value = (Array.isArray(value) ? value[0] : value) ?? void 0;
52687
54429
  acc[leftFieldKey] = typeof value === "object" ? void 0 : value;
52688
54430
  return acc;
@@ -52690,7 +54432,7 @@ function processJsonSchemaSubModel0(mapItem, apiData) {
52690
54432
  }
52691
54433
  function processJsonSchemaSubModel1(mapItem, apiData) {
52692
54434
  const fieldValues = mapItem.fields.reduce((acc, { leftFieldKey, rightFieldKey }) => {
52693
- let value = get(apiData, rightFieldKey);
54435
+ let value = JSONPath({ path: rightFieldKey, json: apiData });
52694
54436
  let arr = Array.isArray(value) ? value.filter((v) => v != null && typeof v !== "object") : value != null && typeof value !== "object" ? [value] : [];
52695
54437
  acc[leftFieldKey] = arr;
52696
54438
  return acc;
@@ -98411,6 +100153,63 @@ async function waitForDataManagerSettle() {
98411
100153
  function syncInitRawDataSnapshot(doc) {
98412
100154
  doc.docRuntimeMeta.handleInfo.initRawDataSnapshot = cloneDeep(doc.dataManager.getRawData());
98413
100155
  }
100156
+ function useSpecificConfig(options) {
100157
+ const { widget, fieldInfo } = options;
100158
+ const resolvedFieldInfo = fieldInfo?.value ?? fieldInfo;
100159
+ const specificFieldConfig = resolvedFieldInfo?.specificConfig;
100160
+ const specificConfig = widget.widgetMeta?.props.newSpecificConfig;
100161
+ if (!specificConfig) return;
100162
+ const widgetMeta = widget.widgetMeta;
100163
+ const widgetType = widgetMeta?.type;
100164
+ switch (widgetType) {
100165
+ case "fw:input": {
100166
+ const fieldType = widgetMeta?.field?.fieldType;
100167
+ if (fieldType === FIELD_TYPE.RECORD_NO && specificFieldConfig?.signGenerate === "snRule") {
100168
+ Object.assign(specificConfig, {
100169
+ newDisabled: true,
100170
+ newPlaceholder: "记录单号自动生成,无需填写"
100171
+ });
100172
+ }
100173
+ break;
100174
+ }
100175
+ case "fw:number": {
100176
+ const { digits, rulesForRounding } = specificFieldConfig ?? {};
100177
+ if (digits !== void 0) {
100178
+ specificConfig.digits = digits;
100179
+ }
100180
+ specificConfig.rulesForRounding = rulesForRounding ?? 6;
100181
+ break;
100182
+ }
100183
+ }
100184
+ }
100185
+ function resolveFieldInfo(options) {
100186
+ if (options.fieldInfo) return options.fieldInfo;
100187
+ const runtime = options.ctx?.runtime;
100188
+ const field = options.widget?.widgetMeta?.field;
100189
+ const modelKey = getLastSegment(field?.modelLink);
100190
+ const fieldKey = getLastSegment(field?.fieldLink);
100191
+ if (!runtime || !modelKey || !fieldKey) return void 0;
100192
+ const list = runtime.getFieldList(modelKey) ?? [];
100193
+ return list.find((item) => item.key === fieldKey);
100194
+ }
100195
+ function applyWidgetRuntimeInitializer(options) {
100196
+ const fieldInfo = resolveFieldInfo(options);
100197
+ useSpecificConfig({
100198
+ ...options,
100199
+ fieldInfo
100200
+ });
100201
+ }
100202
+ function useWidgetInitializer(options) {
100203
+ const init2 = (isSupport) => {
100204
+ if (!isSupport) {
100205
+ return;
100206
+ }
100207
+ applyWidgetRuntimeInitializer(options);
100208
+ };
100209
+ return {
100210
+ init: init2
100211
+ };
100212
+ }
98414
100213
  function snapshotDocInfo(docInst) {
98415
100214
  return {
98416
100215
  pages: docInst?.pages ?? [],
@@ -98424,6 +100223,7 @@ async function initializeDocumentEngine(props, payload, result) {
98424
100223
  const { id, requestInfo, fillModeType, paramsConfig } = result;
98425
100224
  const mainModelKey = requestInfo.modelKey || payload.modelKey || "";
98426
100225
  const materialNo = paramsConfig?.materialNo || requestInfo.materialNo;
100226
+ await payload.ctx.runtime.ensureModelFieldsReady(mainModelKey);
98427
100227
  await addSubModelsToFieldScope(mainModelKey, payload.ctx);
98428
100228
  const masterSlaveList = payload.ctx.runtime.getMasterSlaveFieldList(mainModelKey);
98429
100229
  const cloneRuntimeJson = cloneDeep(JSON.parse(requestInfo.runtimeJson || "{}"));
@@ -98435,8 +100235,18 @@ async function initializeDocumentEngine(props, payload, result) {
98435
100235
  const runtimeJsonForModel = expandCheckTableRuntimeJson(cloneRuntimeJson, {
98436
100236
  itemCountByRegionId
98437
100237
  });
100238
+ const checkTableRegions = listCheckTableRegionsInRuntimeJson(runtimeJsonForModel);
100239
+ const linkFieldKey = checkTableRegions[0]?.linkFieldKey;
98438
100240
  const docModel = ModelConverter.toModel(runtimeJsonForModel);
98439
100241
  const instances = docModel.getWidgetInstances();
100242
+ if (fillModeType !== DocModeTypeConst.Edit) {
100243
+ instances.forEach((instance2) => {
100244
+ applyWidgetRuntimeInitializer({
100245
+ widget: instance2,
100246
+ ctx: payload.ctx
100247
+ });
100248
+ });
100249
+ }
98440
100250
  const defaultQueryIds = getDefaultQueryIdsByFieldType({
98441
100251
  materialNumber: paramsConfig?.materialNo || requestInfo.materialNo,
98442
100252
  productId: paramsConfig?.productId,
@@ -98451,8 +100261,6 @@ async function initializeDocumentEngine(props, payload, result) {
98451
100261
  defaultQueryIds,
98452
100262
  masterSlaveList
98453
100263
  );
98454
- const checkTableRegions = listCheckTableRegionsInRuntimeJson(runtimeJsonForModel);
98455
- const linkFieldKey = checkTableRegions[0]?.linkFieldKey;
98456
100264
  mergeCheckTableItemInfosIntoDefaults(defaultDataMap, runtimeJsonForModel, checkTableItemInfos, {
98457
100265
  layoutColumnCount: linkFieldKey ? docModel.getSubTableLayoutSlotCount(linkFieldKey) : 0
98458
100266
  });
@@ -98477,7 +100285,8 @@ async function initializeDocumentEngine(props, payload, result) {
98477
100285
  });
98478
100286
  const rawData = conversionFormState({
98479
100287
  masterSlaveList,
98480
- interfaceData
100288
+ interfaceData,
100289
+ subTableInfoList: docModel.getSubTableInfoList() ?? []
98481
100290
  });
98482
100291
  const docRuntimeMeta = {
98483
100292
  ...requestInfo,
@@ -98616,6 +100425,7 @@ function useDocumentFactory(props, payload) {
98616
100425
  } = freshExecute;
98617
100426
  const mainModelKey = requestInfo.modelKey || payload.modelKey || "";
98618
100427
  const materialNo = paramsConfig?.materialNo || props.materialNo;
100428
+ await payload.ctx.runtime.ensureModelFieldsReady(mainModelKey);
98619
100429
  const masterSlaveList = payload.ctx.runtime.getMasterSlaveFieldList(mainModelKey);
98620
100430
  const instances = doc.model?.getWidgetInstances() ?? [];
98621
100431
  const { initDocModelJson } = doc.docRuntimeMeta.handleInfo;
@@ -98644,7 +100454,7 @@ function useDocumentFactory(props, payload) {
98644
100454
  const rawData = conversionFormState({
98645
100455
  masterSlaveList,
98646
100456
  interfaceData,
98647
- instances
100457
+ subTableInfoList: doc.model?.getSubTableInfoList() ?? []
98648
100458
  });
98649
100459
  doc.dataManager.setRawData(rawData);
98650
100460
  await waitForDataManagerSettle();
@@ -99116,6 +100926,13 @@ class SuiteRuntime {
99116
100926
  getModel(modelKey) {
99117
100927
  return this.modelService.getModelSync(modelKey);
99118
100928
  }
100929
+ /**
100930
+ * 确保主模型字段已拉取并写入缓存(避免 preload 与文档 immediate 加载竞态)。
100931
+ */
100932
+ async ensureModelFieldsReady(modelKey) {
100933
+ if (!modelKey) return;
100934
+ await this.loadFieldList(modelKey);
100935
+ }
99119
100936
  getMasterSlaveFieldList(modelKey) {
99120
100937
  return this.fieldService.getFieldList(modelKey)?.filter((i) => i.type === FIELD_TYPE.MASTERSLAVE) || [];
99121
100938
  }
@@ -101068,30 +102885,6 @@ function useDependency(doc, widget, ctx) {
101068
102885
  initDependency
101069
102886
  };
101070
102887
  }
101071
- function useSpecificConfig(options) {
101072
- const { widget, fieldInfo } = options;
101073
- const widgetType = widget.widgetMeta?.type;
101074
- if (widgetType !== "fw:number") {
101075
- return;
101076
- }
101077
- const specificConfig = widget.widgetMeta.props.newSpecificConfig;
101078
- const digits = fieldInfo?.value?.specificConfig?.digits;
101079
- if (digits !== void 0) {
101080
- specificConfig.digits = digits;
101081
- }
101082
- specificConfig.rulesForRounding = fieldInfo?.value?.specificConfig?.rulesForRounding ?? 6;
101083
- }
101084
- function useWidgetInitializer(options) {
101085
- const init2 = (isSupport) => {
101086
- if (!isSupport) {
101087
- return;
101088
- }
101089
- useSpecificConfig(options);
101090
- };
101091
- return {
101092
- init: init2
101093
- };
101094
- }
101095
102888
  const _sfc_main$2Q = /* @__PURE__ */ defineComponent({
101096
102889
  __name: "overlay-render",
101097
102890
  props: {
@@ -101128,7 +102921,8 @@ const _sfc_main$2Q = /* @__PURE__ */ defineComponent({
101128
102921
  const { init: init2 } = useWidgetInitializer({
101129
102922
  doc: props.doc,
101130
102923
  widget: props.widget,
101131
- fieldInfo
102924
+ fieldInfo,
102925
+ ctx: designCtx
101132
102926
  });
101133
102927
  init2(props.isLastWidgetId);
101134
102928
  const { validateField } = createFormValidator();
@@ -104118,9 +105912,6 @@ function rowKey(row, fallbackIndex) {
104118
105912
  }
104119
105913
  return `idx:${fallbackIndex}`;
104120
105914
  }
104121
- function normalizeFormData(data) {
104122
- return getSubmitFormData(data || {});
104123
- }
104124
105915
  function getFieldMeta(metaMap, runtimePath) {
104125
105916
  if (!metaMap) return {};
104126
105917
  return metaMap.get(runtimePath) || {};
@@ -104220,8 +106011,8 @@ function buildWidgetFieldMetaMap(instances) {
104220
106011
  return map;
104221
106012
  }
104222
106013
  function buildFieldChangeList(params) {
104223
- const baseline = normalizeFormData(params.baselineData);
104224
- const current = normalizeFormData(params.currentData);
106014
+ const baseline = getSubmitFormData(params.baselineData || {}, params.subTableInfoList);
106015
+ const current = getSubmitFormData(params.currentData || {}, params.subTableInfoList);
104225
106016
  const changeList = [];
104226
106017
  const keys2 = /* @__PURE__ */ new Set([...Object.keys(baseline || {}), ...Object.keys(current || {})]);
104227
106018
  for (const fieldKey of keys2) {
@@ -104320,8 +106111,9 @@ function useDocOperations(docRef) {
104320
106111
  const baselineSnapshot = doc.dataManager.getRawData();
104321
106112
  const instances = doc.getWidgetInstances() ?? [];
104322
106113
  const widgetMetaMap = buildWidgetFieldMetaMap(instances);
106114
+ const subTableInfoList = doc.model?.getSubTableInfoList() ?? [];
104323
106115
  doc.setMode(DocModeTypeConst.Fill);
104324
- return { baselineSnapshot, widgetMetaMap };
106116
+ return { baselineSnapshot, widgetMetaMap, subTableInfoList };
104325
106117
  }
104326
106118
  async function computeBaselineChanges(ctx) {
104327
106119
  await Promise.resolve();
@@ -104333,7 +106125,8 @@ function useDocOperations(docRef) {
104333
106125
  return buildFieldChangeList({
104334
106126
  baselineData: ctx.baselineSnapshot,
104335
106127
  currentData,
104336
- widgetMetaMap: ctx.widgetMetaMap
106128
+ widgetMetaMap: ctx.widgetMetaMap,
106129
+ subTableInfoList: ctx.subTableInfoList
104337
106130
  });
104338
106131
  }
104339
106132
  function setAnnotation(ids, list) {
@@ -104432,6 +106225,13 @@ function useDocController(factory2, ops) {
104432
106225
  rawData() {
104433
106226
  return doc.dataManager.getRawData();
104434
106227
  },
106228
+ getSubmitFormData(formData) {
106229
+ const subTableInfoList = doc.model?.getSubTableInfoList() ?? [];
106230
+ return getSubmitFormData(
106231
+ formData ?? doc.dataManager.getRawData(),
106232
+ subTableInfoList
106233
+ );
106234
+ },
104435
106235
  setRawData(data, defaultDataMap) {
104436
106236
  doc.dataManager.setRawData(data, defaultDataMap);
104437
106237
  },
@@ -111347,7 +113147,8 @@ const _sfc_main$1X = /* @__PURE__ */ defineComponent({
111347
113147
  showDisabled,
111348
113148
  showReadonly,
111349
113149
  widgetProps,
111350
- widgetType
113150
+ widgetType,
113151
+ fieldMeta
111351
113152
  } = useWidgetStaticAttrs(props.widget);
111352
113153
  const CurrentComp = computed(() => {
111353
113154
  if (widgetType.value === "fw:file") {
@@ -111366,11 +113167,15 @@ const _sfc_main$1X = /* @__PURE__ */ defineComponent({
111366
113167
  const optionValue = computed(() => props.widget?.widgetOption?.value);
111367
113168
  const modelValue = computed({
111368
113169
  get() {
113170
+ let value;
111369
113171
  if (docInst.value.isInEditMode()) {
111370
- const value2 = docInst.value?.dataManager?.getDefault(runtimeValuePath.value);
111371
- return getValue$1(value2, isMultiple.value);
113172
+ value = docInst.value?.dataManager?.getDefault(runtimeValuePath.value);
113173
+ } else {
113174
+ value = docInst.value?.dataManager?.get(runtimeValuePath.value);
113175
+ }
113176
+ if (fieldMeta.value?.fieldType === FIELD_TYPE.BOOLEAN) {
113177
+ value = toBoolean(value);
111372
113178
  }
111373
- const value = docInst.value?.dataManager?.get(runtimeValuePath.value);
111374
113179
  return getValue$1(value, isMultiple.value);
111375
113180
  },
111376
113181
  set(v) {
@@ -111559,13 +113364,6 @@ const _sfc_main$1U = /* @__PURE__ */ defineComponent({
111559
113364
  () => props.modelId === interCtx.panelData?.modelId || props.modelId === interCtx.hoverModelId
111560
113365
  );
111561
113366
  const colors = computed(() => {
111562
- if (showRequired.value) {
111563
- return {
111564
- text: "#f26c6c",
111565
- line: "#f26c6c",
111566
- bg: isActive.value ? "rgba(255, 230, 230, 1)" : "rgba(255, 242, 242, 1)"
111567
- };
111568
- }
111569
113367
  if (showDisabled.value) {
111570
113368
  return {
111571
113369
  text: "#c9c9c9",
@@ -111580,6 +113378,13 @@ const _sfc_main$1U = /* @__PURE__ */ defineComponent({
111580
113378
  bg: isActive.value ? "#f5f7fa" : "#fafafa"
111581
113379
  };
111582
113380
  }
113381
+ if (showRequired.value) {
113382
+ return {
113383
+ text: "#f26c6c",
113384
+ line: "#f26c6c",
113385
+ bg: isActive.value ? "rgba(255, 230, 230, 1)" : "rgba(255, 242, 242, 1)"
113386
+ };
113387
+ }
111583
113388
  return {
111584
113389
  text: "#999999",
111585
113390
  line: "#999999",
@@ -122565,8 +124370,8 @@ const edhrSuitePlugin = {
122565
124370
  key: SUITE_KEY,
122566
124371
  install: installEdhrSuite
122567
124372
  };
122568
- function registerSuite(plugin) {
122569
- plugin.install();
124373
+ function registerSuite(plugin2) {
124374
+ plugin2.install();
122570
124375
  }
122571
124376
  const _hoisted_1$e = { class: "options-dropdown" };
122572
124377
  const _hoisted_2$9 = { class: "options-search" };
@@ -125086,7 +126891,6 @@ export {
125086
126891
  GctLayout,
125087
126892
  PageSizeEnumConst,
125088
126893
  edhrSuitePlugin,
125089
- getSubmitFormData,
125090
126894
  registerSuite,
125091
126895
  setupPlatformAdapters,
125092
126896
  setupVueRuntime,