@nocobase/database 2.1.0-beta.9 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/lib/collection.d.ts +14 -0
  2. package/lib/collection.js +13 -3
  3. package/lib/database.d.ts +1 -0
  4. package/lib/database.js +4 -0
  5. package/lib/eager-loading/eager-loading-tree.js +9 -4
  6. package/lib/errors/association-not-found-error.d.ts +11 -0
  7. package/lib/errors/association-not-found-error.js +44 -0
  8. package/lib/fields/password-field.d.ts +11 -3
  9. package/lib/fields/password-field.js +41 -21
  10. package/lib/fields/relation-field.js +1 -1
  11. package/lib/index.d.ts +3 -0
  12. package/lib/index.js +6 -0
  13. package/lib/interfaces/date-interface.d.ts +9 -0
  14. package/lib/interfaces/date-interface.js +27 -0
  15. package/lib/interfaces/datetime-interface.d.ts +3 -1
  16. package/lib/interfaces/datetime-interface.js +84 -9
  17. package/lib/interfaces/datetime-no-tz-interface.d.ts +9 -0
  18. package/lib/interfaces/datetime-no-tz-interface.js +16 -2
  19. package/lib/interfaces/time-interface.js +16 -0
  20. package/lib/interfaces/to-one-interface.js +1 -1
  21. package/lib/operators/date.js +12 -4
  22. package/lib/options-parser.d.ts +1 -0
  23. package/lib/options-parser.js +20 -4
  24. package/lib/query/builder.d.ts +17 -0
  25. package/lib/query/builder.js +268 -0
  26. package/lib/query/formatter.d.ts +29 -0
  27. package/lib/query/formatter.js +100 -0
  28. package/lib/query/formatters/mysql.d.ts +14 -0
  29. package/lib/query/formatters/mysql.js +70 -0
  30. package/lib/query/formatters/oracle.d.ts +14 -0
  31. package/lib/query/formatters/oracle.js +64 -0
  32. package/lib/query/formatters/postgres.d.ts +15 -0
  33. package/lib/query/formatters/postgres.js +70 -0
  34. package/lib/query/formatters/sqlite.d.ts +14 -0
  35. package/lib/query/formatters/sqlite.js +63 -0
  36. package/lib/query/having.d.ts +22 -0
  37. package/lib/query/having.js +112 -0
  38. package/lib/query/types.d.ts +40 -0
  39. package/lib/query/types.js +24 -0
  40. package/lib/repository.d.ts +4 -0
  41. package/lib/repository.js +23 -3
  42. package/lib/utils/field-validation.js +30 -0
  43. package/lib/view/field-type-map.d.ts +4 -4
  44. package/lib/view/field-type-map.js +4 -4
  45. package/package.json +4 -4
@@ -30,10 +30,23 @@ export type DumpRules = BuiltInGroup | ({
30
30
  group: BuiltInGroup | string;
31
31
  } & BaseDumpRules);
32
32
  export type MigrationRule = 'overwrite' | 'skip' | 'upsert' | 'schema-only' | 'insert-ignore' | (string & {}) | null;
33
+ /**
34
+ * `dataCategory = system` marks data that is foundational to system operation and should be treated as core runtime data.
35
+ * `dataCategory = business` marks data owned by plugin features and used as part of the plugin's business domain.
36
+ * `dataCategory = runtime` excludes the collection's data from backup snapshots.
37
+ */
38
+ export type DataCategory = 'system' | 'business' | 'runtime';
39
+ export type DataCategories = DataCategory | DataCategory[];
40
+ export declare const TAG: {
41
+ basic: string;
42
+ business: string;
43
+ ignoredBackup: string;
44
+ };
33
45
  export interface CollectionOptions extends Omit<ModelOptions, 'name' | 'hooks'> {
34
46
  name: string;
35
47
  title?: string;
36
48
  namespace?: string;
49
+ dataCategory?: DataCategories;
37
50
  migrationRules?: MigrationRule[];
38
51
  dumpRules?: DumpRules;
39
52
  tableName?: string;
@@ -81,6 +94,7 @@ export declare class Collection<TModelAttributes extends {} = any, TCreationAttr
81
94
  model: ModelStatic<Model>;
82
95
  repository: Repository<TModelAttributes, TCreationAttributes>;
83
96
  constructor(options: CollectionOptions, context: CollectionContext);
97
+ get dataCategory(): DataCategories;
84
98
  get underscored(): boolean;
85
99
  get filterTargetKey(): string | string[];
86
100
  get name(): string;
package/lib/collection.js CHANGED
@@ -45,7 +45,8 @@ var __decorateClass = (decorators, target, key, kind) => {
45
45
  };
46
46
  var collection_exports = {};
47
47
  __export(collection_exports, {
48
- Collection: () => Collection
48
+ Collection: () => Collection,
49
+ TAG: () => TAG
49
50
  });
50
51
  module.exports = __toCommonJS(collection_exports);
51
52
  var import_deepmerge = __toESM(require("deepmerge"));
@@ -89,6 +90,11 @@ function EnsureAtomicity(target, propertyKey, descriptor) {
89
90
  return descriptor;
90
91
  }
91
92
  __name(EnsureAtomicity, "EnsureAtomicity");
93
+ const TAG = {
94
+ basic: "basic",
95
+ business: "business",
96
+ ignoredBackup: "ignored:backup"
97
+ };
92
98
  const _Collection = class _Collection extends import_events.EventEmitter {
93
99
  options;
94
100
  context;
@@ -112,6 +118,9 @@ const _Collection = class _Collection extends import_events.EventEmitter {
112
118
  this.setRepository(options.repository);
113
119
  this.setSortable(options.sortable);
114
120
  }
121
+ get dataCategory() {
122
+ return this.options.dataCategory;
123
+ }
115
124
  get underscored() {
116
125
  return this.options.underscored;
117
126
  }
@@ -188,7 +197,7 @@ const _Collection = class _Collection extends import_events.EventEmitter {
188
197
  label: `${this.name}.${field.name}`,
189
198
  value: val
190
199
  });
191
- const { error } = joiSchema.validate(val, { convert: false });
200
+ const { error } = joiSchema.validate(val);
192
201
  if (error) {
193
202
  throw error;
194
203
  }
@@ -817,5 +826,6 @@ __decorateClass([
817
826
  let Collection = _Collection;
818
827
  // Annotate the CommonJS export names for ESM import in node:
819
828
  0 && (module.exports = {
820
- Collection
829
+ Collection,
830
+ TAG
821
831
  });
package/lib/database.d.ts CHANGED
@@ -45,6 +45,7 @@ export interface IDatabaseOptions extends Options {
45
45
  migrator?: any;
46
46
  usingBigIntForId?: boolean;
47
47
  underscored?: boolean;
48
+ rawTimezone?: string;
48
49
  logger?: LoggerOptions | Logger;
49
50
  customHooks?: any;
50
51
  instanceId?: string;
package/lib/database.js CHANGED
@@ -213,6 +213,9 @@ const _Database = class _Database extends import_events.EventEmitter {
213
213
  this.migrations = new import_migration.Migrations(context);
214
214
  this.sequelize.beforeDefine((model, opts2) => {
215
215
  if (this.options.tablePrefix) {
216
+ if (opts2.tableName && opts2["from"] === "dbsync") {
217
+ return;
218
+ }
216
219
  if (opts2.tableName && opts2.tableName.startsWith(this.options.tablePrefix)) {
217
220
  return;
218
221
  }
@@ -221,6 +224,7 @@ const _Database = class _Database extends import_events.EventEmitter {
221
224
  });
222
225
  this.collection({
223
226
  name: "migrations",
227
+ dataCategory: "system",
224
228
  autoGenId: false,
225
229
  timestamps: false,
226
230
  dumpRules: "required",
@@ -75,16 +75,20 @@ const queryParentSQL = /* @__PURE__ */ __name((options) => {
75
75
  const targetKeyField = collection.model.rawAttributes[targetKey].field;
76
76
  const queryInterface = db.sequelize.getQueryInterface();
77
77
  const q = queryInterface.quoteIdentifier.bind(queryInterface);
78
- return `WITH RECURSIVE cte AS (
78
+ const placeholders = nodeIds.map((_, index) => `$${index + 1}`).join(", ");
79
+ return {
80
+ sql: `WITH RECURSIVE cte AS (
79
81
  SELECT ${q(targetKeyField)}, ${q(foreignKeyField)}
80
82
  FROM ${tableName}
81
- WHERE ${q(targetKeyField)} IN ('${nodeIds.join("','")}')
83
+ WHERE ${q(targetKeyField)} IN (${placeholders})
82
84
  UNION ALL
83
85
  SELECT t.${q(targetKeyField)}, t.${q(foreignKeyField)}
84
86
  FROM ${tableName} AS t
85
87
  INNER JOIN cte ON t.${q(targetKeyField)} = cte.${q(foreignKeyField)}
86
88
  )
87
- SELECT ${q(targetKeyField)} AS ${q(targetKey)}, ${q(foreignKeyField)} AS ${q(foreignKey)} FROM cte`;
89
+ SELECT ${q(targetKeyField)} AS ${q(targetKey)}, ${q(foreignKeyField)} AS ${q(foreignKey)} FROM cte`,
90
+ bind: nodeIds
91
+ };
88
92
  }, "queryParentSQL");
89
93
  const _EagerLoadingTree = class _EagerLoadingTree {
90
94
  root;
@@ -305,7 +309,7 @@ const _EagerLoadingTree = class _EagerLoadingTree {
305
309
  });
306
310
  if (node.includeOption.recursively && instances.length > 0) {
307
311
  const targetKey = association.targetKey;
308
- const sql = queryParentSQL({
312
+ const { sql, bind } = queryParentSQL({
309
313
  db: this.db,
310
314
  collection: collection2,
311
315
  foreignKey,
@@ -313,6 +317,7 @@ const _EagerLoadingTree = class _EagerLoadingTree {
313
317
  nodeIds: instances.map((instance) => instance.get(targetKey))
314
318
  });
315
319
  const results = await this.db.sequelize.query(sql, {
320
+ bind,
316
321
  type: "SELECT",
317
322
  transaction
318
323
  });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ export declare class AssociationNotFoundError extends Error {
10
+ constructor(message: string);
11
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var association_not_found_error_exports = {};
29
+ __export(association_not_found_error_exports, {
30
+ AssociationNotFoundError: () => AssociationNotFoundError
31
+ });
32
+ module.exports = __toCommonJS(association_not_found_error_exports);
33
+ const _AssociationNotFoundError = class _AssociationNotFoundError extends Error {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = "AssociationNotFoundError";
37
+ }
38
+ };
39
+ __name(_AssociationNotFoundError, "AssociationNotFoundError");
40
+ let AssociationNotFoundError = _AssociationNotFoundError;
41
+ // Annotate the CommonJS export names for ESM import in node:
42
+ 0 && (module.exports = {
43
+ AssociationNotFoundError
44
+ });
@@ -7,6 +7,8 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
  import { DataTypes } from 'sequelize';
10
+ import type { UpdateOptions } from 'sequelize';
11
+ import { Model } from '../model';
10
12
  import { BaseColumnFieldOptions, Field } from './field';
11
13
  export interface PasswordFieldOptions extends BaseColumnFieldOptions {
12
14
  type: 'password';
@@ -19,11 +21,17 @@ export interface PasswordFieldOptions extends BaseColumnFieldOptions {
19
21
  */
20
22
  randomBytesSize?: number;
21
23
  }
24
+ type PasswordValue = string | number;
25
+ type BulkUpdateOptions = UpdateOptions<Record<string, unknown>> & {
26
+ attributes?: Record<string, unknown>;
27
+ };
22
28
  export declare class PasswordField extends Field {
23
29
  get dataType(): DataTypes.StringDataTypeConstructor;
24
- verify(password: string, hash: string): Promise<unknown>;
25
- hash(password: string): Promise<unknown>;
26
- init(): void;
30
+ listener: (instances: Model | Model[]) => Promise<void>;
31
+ bulkUpdateListener: (options: BulkUpdateOptions) => Promise<void>;
32
+ verify(password: PasswordValue, hash: string): Promise<boolean>;
33
+ hash(password: PasswordValue): Promise<string>;
27
34
  bind(): void;
28
35
  unbind(): void;
29
36
  }
37
+ export {};
@@ -47,58 +47,78 @@ const _PasswordField = class _PasswordField extends import_field.Field {
47
47
  get dataType() {
48
48
  return import_sequelize.DataTypes.STRING;
49
49
  }
50
+ listener = /* @__PURE__ */ __name(async (instances) => {
51
+ const { name } = this.options;
52
+ const fieldName = name;
53
+ instances = Array.isArray(instances) ? instances : [instances];
54
+ for (const instance of instances) {
55
+ if (!instance.changed(fieldName)) {
56
+ continue;
57
+ }
58
+ const value = instance.get(fieldName);
59
+ if (value !== null && value !== void 0 && value !== "") {
60
+ const password = typeof value === "number" ? value : String(value);
61
+ const hash = await this.hash(password);
62
+ instance.set(fieldName, hash);
63
+ } else {
64
+ instance.set(fieldName, instance.previous(fieldName));
65
+ }
66
+ }
67
+ }, "listener");
68
+ bulkUpdateListener = /* @__PURE__ */ __name(async (options) => {
69
+ var _a;
70
+ const { name } = this.options;
71
+ const fieldName = name;
72
+ const { attributes } = options;
73
+ if (!attributes || !Object.prototype.hasOwnProperty.call(attributes, fieldName)) {
74
+ return;
75
+ }
76
+ const value = attributes[fieldName];
77
+ if (value !== null && value !== void 0 && value !== "") {
78
+ const password = typeof value === "number" ? value : String(value);
79
+ attributes[fieldName] = await this.hash(password);
80
+ } else {
81
+ delete attributes[fieldName];
82
+ options.fields = (_a = options.fields) == null ? void 0 : _a.filter((field) => field !== fieldName);
83
+ }
84
+ }, "bulkUpdateListener");
50
85
  async verify(password, hash) {
51
- password = password || "";
86
+ const passwordString = password === null || password === void 0 ? "" : String(password);
52
87
  hash = hash || "";
53
88
  const { length = 64, randomBytesSize = 8 } = this.options;
54
89
  return new Promise((resolve, reject) => {
55
90
  const salt = hash.substring(0, randomBytesSize * 2);
56
91
  const key = hash.substring(randomBytesSize * 2);
57
- import_crypto.default.scrypt(password, salt, length / 2 - randomBytesSize, (err, derivedKey) => {
92
+ import_crypto.default.scrypt(passwordString, salt, length / 2 - randomBytesSize, (err, derivedKey) => {
58
93
  if (err) reject(err);
59
94
  resolve(key == derivedKey.toString("hex"));
60
95
  });
61
96
  });
62
97
  }
63
98
  async hash(password) {
99
+ const passwordString = String(password);
64
100
  const { length = 64, randomBytesSize = 8 } = this.options;
65
101
  return new Promise((resolve, reject) => {
66
102
  const salt = import_crypto.default.randomBytes(randomBytesSize).toString("hex");
67
- import_crypto.default.scrypt(password, salt, length / 2 - randomBytesSize, (err, derivedKey) => {
103
+ import_crypto.default.scrypt(passwordString, salt, length / 2 - randomBytesSize, (err, derivedKey) => {
68
104
  if (err) reject(err);
69
105
  resolve(salt + derivedKey.toString("hex"));
70
106
  });
71
107
  });
72
108
  }
73
- init() {
74
- const { name } = this.options;
75
- this.listener = async (instances) => {
76
- instances = Array.isArray(instances) ? instances : [instances];
77
- for (const instance of instances) {
78
- if (!instance.changed(name)) {
79
- continue;
80
- }
81
- const value = instance.get(name);
82
- if (value) {
83
- const hash = await this.hash(value);
84
- instance.set(name, hash);
85
- } else {
86
- instance.set(name, instance.previous(name));
87
- }
88
- }
89
- };
90
- }
91
109
  bind() {
92
110
  super.bind();
93
111
  this.on("beforeCreate", this.listener);
94
112
  this.on("beforeBulkCreate", this.listener);
95
113
  this.on("beforeUpdate", this.listener);
114
+ this.on("beforeBulkUpdate", this.bulkUpdateListener);
96
115
  }
97
116
  unbind() {
98
117
  super.unbind();
99
118
  this.off("beforeCreate", this.listener);
100
119
  this.off("beforeBulkCreate", this.listener);
101
120
  this.off("beforeUpdate", this.listener);
121
+ this.off("beforeBulkUpdate", this.bulkUpdateListener);
102
122
  }
103
123
  };
104
124
  __name(_PasswordField, "PasswordField");
@@ -43,7 +43,7 @@ const _RelationField = class _RelationField extends import_field.Field {
43
43
  return this.options.foreignKey;
44
44
  }
45
45
  get sourceKey() {
46
- return this.options.sourceKey || this.collection.model.primaryKeyAttribute;
46
+ return this.options.sourceKey || this.collection.filterTargetKey;
47
47
  }
48
48
  get targetKey() {
49
49
  return this.options.targetKey || this.TargetModel.primaryKeyAttribute;
package/lib/index.d.ts CHANGED
@@ -32,6 +32,9 @@ export * from './relation-repository/hasmany-repository';
32
32
  export * from './relation-repository/hasone-repository';
33
33
  export * from './relation-repository/multiple-relation-repository';
34
34
  export * from './relation-repository/single-relation-repository';
35
+ export * from './query/builder';
36
+ export * from './query/formatter';
37
+ export * from './query/types';
35
38
  export * from './repository';
36
39
  export * from './relation-repository/relation-repository';
37
40
  export { default as sqlParser, SQLParserTypes } from './sql-parser';
package/lib/index.js CHANGED
@@ -93,6 +93,9 @@ __reExport(src_exports, require("./relation-repository/hasmany-repository"), mod
93
93
  __reExport(src_exports, require("./relation-repository/hasone-repository"), module.exports);
94
94
  __reExport(src_exports, require("./relation-repository/multiple-relation-repository"), module.exports);
95
95
  __reExport(src_exports, require("./relation-repository/single-relation-repository"), module.exports);
96
+ __reExport(src_exports, require("./query/builder"), module.exports);
97
+ __reExport(src_exports, require("./query/formatter"), module.exports);
98
+ __reExport(src_exports, require("./query/types"), module.exports);
96
99
  __reExport(src_exports, require("./repository"), module.exports);
97
100
  __reExport(src_exports, require("./relation-repository/relation-repository"), module.exports);
98
101
  var import_sql_parser = __toESM(require("./sql-parser"));
@@ -157,6 +160,9 @@ var import_filter_include = require("./utils/filter-include");
157
160
  ...require("./relation-repository/hasone-repository"),
158
161
  ...require("./relation-repository/multiple-relation-repository"),
159
162
  ...require("./relation-repository/single-relation-repository"),
163
+ ...require("./query/builder"),
164
+ ...require("./query/formatter"),
165
+ ...require("./query/types"),
160
166
  ...require("./repository"),
161
167
  ...require("./relation-repository/relation-repository"),
162
168
  ...require("./update-associations"),
@@ -1,4 +1,13 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
1
9
  import { DatetimeInterface } from './datetime-interface';
2
10
  export declare class DateInterface extends DatetimeInterface {
11
+ toValue(value: any, ctx?: any): Promise<any>;
3
12
  toString(value: any, ctx?: any): any;
4
13
  }
@@ -31,7 +31,34 @@ __export(date_interface_exports, {
31
31
  });
32
32
  module.exports = __toCommonJS(date_interface_exports);
33
33
  var import_datetime_interface = require("./datetime-interface");
34
+ function pad2(value) {
35
+ return String(value).padStart(2, "0");
36
+ }
37
+ __name(pad2, "pad2");
38
+ function formatDateOnlyFromDate(date, timezone) {
39
+ const offsetMinutes = (0, import_datetime_interface.getTimeZoneOffsetMinutes)(timezone);
40
+ if (offsetMinutes == null) {
41
+ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
42
+ }
43
+ const shifted = new Date(date.getTime() + offsetMinutes * 60 * 1e3);
44
+ return `${shifted.getUTCFullYear()}-${pad2(shifted.getUTCMonth() + 1)}-${pad2(shifted.getUTCDate())}`;
45
+ }
46
+ __name(formatDateOnlyFromDate, "formatDateOnlyFromDate");
34
47
  const _DateInterface = class _DateInterface extends import_datetime_interface.DatetimeInterface {
48
+ async toValue(value, ctx) {
49
+ const normalized = await super.toValue(value, ctx);
50
+ if (!normalized) {
51
+ return normalized;
52
+ }
53
+ if (typeof normalized === "string" && /^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
54
+ return normalized;
55
+ }
56
+ const date = normalized instanceof Date ? normalized : new Date(normalized);
57
+ if (Number.isNaN(date.getTime())) {
58
+ return normalized;
59
+ }
60
+ return formatDateOnlyFromDate(date, (0, import_datetime_interface.resolveTimeZoneFromCtx)(ctx));
61
+ }
35
62
  toString(value, ctx) {
36
63
  return value;
37
64
  }
@@ -7,6 +7,8 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
  import { BaseInterface } from './base-interface';
10
+ export declare function getTimeZoneOffsetMinutes(timezone: string | number | null | undefined): number;
11
+ export declare function resolveTimeZoneFromCtx(ctx: any): any;
10
12
  export declare class DatetimeInterface extends BaseInterface {
11
13
  protected parseDateString(value: string): {
12
14
  year: string;
@@ -30,7 +32,7 @@ export declare class DatetimeInterface extends BaseInterface {
30
32
  hour?: string;
31
33
  minute?: string;
32
34
  second?: string;
33
- }): string;
35
+ }, ctx?: any): string;
34
36
  toValue(value: any, ctx?: any): Promise<any>;
35
37
  toString(value: any, ctx?: any): any;
36
38
  }
@@ -37,7 +37,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
37
37
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
38
  var datetime_interface_exports = {};
39
39
  __export(datetime_interface_exports, {
40
- DatetimeInterface: () => DatetimeInterface
40
+ DatetimeInterface: () => DatetimeInterface,
41
+ getTimeZoneOffsetMinutes: () => getTimeZoneOffsetMinutes,
42
+ resolveTimeZoneFromCtx: () => resolveTimeZoneFromCtx
41
43
  });
42
44
  module.exports = __toCommonJS(datetime_interface_exports);
43
45
  var import_base_interface = require("./base-interface");
@@ -54,13 +56,79 @@ function isNumeric(str) {
54
56
  return !isNaN(str) && !isNaN(parseFloat(str));
55
57
  }
56
58
  __name(isNumeric, "isNumeric");
59
+ function getTimeZoneOffsetMinutes(timezone) {
60
+ if (typeof timezone === "number" && Number.isFinite(timezone)) {
61
+ return timezone;
62
+ }
63
+ if (typeof timezone !== "string") {
64
+ return null;
65
+ }
66
+ const normalized = timezone.trim().toUpperCase();
67
+ if (!normalized) {
68
+ return null;
69
+ }
70
+ if (normalized === "Z" || normalized === "UTC") {
71
+ return 0;
72
+ }
73
+ const match = normalized.match(/^([+-])(\d{2})(?::?(\d{2}))?$/);
74
+ if (!match) {
75
+ return null;
76
+ }
77
+ const [, sign, hours, minutes = "00"] = match;
78
+ const totalMinutes = Number(hours) * 60 + Number(minutes);
79
+ return sign === "+" ? totalMinutes : -totalMinutes;
80
+ }
81
+ __name(getTimeZoneOffsetMinutes, "getTimeZoneOffsetMinutes");
57
82
  function resolveTimeZoneFromCtx(ctx) {
58
- if ((ctx == null ? void 0 : ctx.get) && (ctx == null ? void 0 : ctx.get("X-Timezone"))) {
59
- return ctx.get("X-Timezone");
83
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
84
+ let timezone;
85
+ if (typeof (ctx == null ? void 0 : ctx.get) === "function") {
86
+ timezone = ctx.get("X-Timezone") || ctx.get("x-timezone");
87
+ } else if (typeof ((_a = ctx == null ? void 0 : ctx.request) == null ? void 0 : _a.get) === "function") {
88
+ timezone = ctx.request.get("X-Timezone") || ctx.request.get("x-timezone");
89
+ }
90
+ timezone = timezone || ((_c = (_b = ctx == null ? void 0 : ctx.request) == null ? void 0 : _b.headers) == null ? void 0 : _c["x-timezone"]) || ((_e = (_d = ctx == null ? void 0 : ctx.request) == null ? void 0 : _d.headers) == null ? void 0 : _e["X-Timezone"]) || ((_g = (_f = ctx == null ? void 0 : ctx.request) == null ? void 0 : _f.header) == null ? void 0 : _g["x-timezone"]) || ((_i = (_h = ctx == null ? void 0 : ctx.request) == null ? void 0 : _h.header) == null ? void 0 : _i["X-Timezone"]) || ((_k = (_j = ctx == null ? void 0 : ctx.req) == null ? void 0 : _j.headers) == null ? void 0 : _k["x-timezone"]) || ((_m = (_l = ctx == null ? void 0 : ctx.req) == null ? void 0 : _l.headers) == null ? void 0 : _m["X-Timezone"]);
91
+ if (timezone !== void 0 && timezone !== null && timezone !== "") {
92
+ return timezone;
60
93
  }
61
- return 0;
94
+ return null;
62
95
  }
63
96
  __name(resolveTimeZoneFromCtx, "resolveTimeZoneFromCtx");
97
+ function toISOWithTimezone(dateInfo, timezone) {
98
+ const offsetMinutes = getTimeZoneOffsetMinutes(timezone);
99
+ if (offsetMinutes == null) {
100
+ return null;
101
+ }
102
+ const utcMillis = Date.UTC(
103
+ Number(dateInfo.year),
104
+ Number(dateInfo.month) - 1,
105
+ Number(dateInfo.day),
106
+ Number(dateInfo.hour || "00"),
107
+ Number(dateInfo.minute || "00"),
108
+ Number(dateInfo.second || "00"),
109
+ 0
110
+ ) - offsetMinutes * 60 * 1e3;
111
+ return new Date(utcMillis).toISOString();
112
+ }
113
+ __name(toISOWithTimezone, "toISOWithTimezone");
114
+ function excelSerialToISO(value, timezone) {
115
+ const wallClockUtcDate = (0, import_excel_date_to_js.getJsDateFromExcel)(value);
116
+ const offsetMinutes = getTimeZoneOffsetMinutes(timezone);
117
+ if (offsetMinutes == null) {
118
+ return wallClockUtcDate.toISOString();
119
+ }
120
+ const utcMillis = Date.UTC(
121
+ wallClockUtcDate.getUTCFullYear(),
122
+ wallClockUtcDate.getUTCMonth(),
123
+ wallClockUtcDate.getUTCDate(),
124
+ wallClockUtcDate.getUTCHours(),
125
+ wallClockUtcDate.getUTCMinutes(),
126
+ wallClockUtcDate.getUTCSeconds(),
127
+ wallClockUtcDate.getUTCMilliseconds()
128
+ ) - offsetMinutes * 60 * 1e3;
129
+ return new Date(utcMillis).toISOString();
130
+ }
131
+ __name(excelSerialToISO, "excelSerialToISO");
64
132
  const _DatetimeInterface = class _DatetimeInterface extends import_base_interface.BaseInterface {
65
133
  parseDateString(value) {
66
134
  const dateOnlyMatch = /^(\d{4})[-/]?(\d{2})[-/]?(\d{2})$/.exec(value);
@@ -75,7 +143,12 @@ const _DatetimeInterface = class _DatetimeInterface extends import_base_interfac
75
143
  }
76
144
  return null;
77
145
  }
78
- formatDateTimeToISO(dateInfo) {
146
+ formatDateTimeToISO(dateInfo, ctx) {
147
+ const timezone = resolveTimeZoneFromCtx(ctx);
148
+ const timezoneAwareISO = toISOWithTimezone(dateInfo, timezone);
149
+ if (timezoneAwareISO) {
150
+ return timezoneAwareISO;
151
+ }
79
152
  const { year, month, day, hour = "00", minute = "00", second = "00" } = dateInfo;
80
153
  const m = (0, import_dayjs.default)(`${year}-${month}-${day} ${hour}:${minute}:${second}.000`);
81
154
  return m.toISOString();
@@ -94,7 +167,7 @@ const _DatetimeInterface = class _DatetimeInterface extends import_base_interfac
94
167
  if (typeof value === "string") {
95
168
  const dateInfo = this.parseDateString(value);
96
169
  if (dateInfo) {
97
- return this.formatDateTimeToISO(dateInfo);
170
+ return this.formatDateTimeToISO(dateInfo, ctx);
98
171
  }
99
172
  }
100
173
  if (import_dayjs.default.isDayjs(value)) {
@@ -102,7 +175,7 @@ const _DatetimeInterface = class _DatetimeInterface extends import_base_interfac
102
175
  } else if (isDate(value)) {
103
176
  return value;
104
177
  } else if (isNumeric(value)) {
105
- return (0, import_excel_date_to_js.getJsDateFromExcel)(value).toISOString();
178
+ return excelSerialToISO(value, resolveTimeZoneFromCtx(ctx));
106
179
  } else if (typeof value === "string") {
107
180
  return value;
108
181
  }
@@ -110,7 +183,7 @@ const _DatetimeInterface = class _DatetimeInterface extends import_base_interfac
110
183
  }
111
184
  toString(value, ctx) {
112
185
  var _a, _b;
113
- const utcOffset = resolveTimeZoneFromCtx(ctx);
186
+ const utcOffset = resolveTimeZoneFromCtx(ctx) ?? 0;
114
187
  const props = ((_b = (_a = this.options) == null ? void 0 : _a.uiSchema) == null ? void 0 : _b["x-component-props"]) ?? {};
115
188
  const format = (0, import_utils.getDefaultFormat)(props);
116
189
  const m = (0, import_utils.str2moment)(value, { ...props, utcOffset });
@@ -121,5 +194,7 @@ __name(_DatetimeInterface, "DatetimeInterface");
121
194
  let DatetimeInterface = _DatetimeInterface;
122
195
  // Annotate the CommonJS export names for ESM import in node:
123
196
  0 && (module.exports = {
124
- DatetimeInterface
197
+ DatetimeInterface,
198
+ getTimeZoneOffsetMinutes,
199
+ resolveTimeZoneFromCtx
125
200
  });
@@ -1,3 +1,11 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
1
9
  import { DatetimeInterface } from './datetime-interface';
2
10
  export declare class DatetimeNoTzInterface extends DatetimeInterface {
3
11
  protected formatDateTimeToString(dateInfo: {
@@ -8,6 +16,7 @@ export declare class DatetimeNoTzInterface extends DatetimeInterface {
8
16
  minute?: string;
9
17
  second?: string;
10
18
  }): string;
19
+ protected formatExcelSerialToString(value: number | string): string;
11
20
  toValue(value: any, ctx?: any): Promise<any>;
12
21
  toString(value: any, ctx?: any): any;
13
22
  }
@@ -54,6 +54,10 @@ function isNumeric(str) {
54
54
  return !isNaN(str) && !isNaN(parseFloat(str));
55
55
  }
56
56
  __name(isNumeric, "isNumeric");
57
+ function pad2(value) {
58
+ return String(value).padStart(2, "0");
59
+ }
60
+ __name(pad2, "pad2");
57
61
  const _DatetimeNoTzInterface = class _DatetimeNoTzInterface extends import_datetime_interface.DatetimeInterface {
58
62
  formatDateTimeToString(dateInfo) {
59
63
  const { year, month, day, hour, minute, second } = dateInfo;
@@ -62,6 +66,17 @@ const _DatetimeNoTzInterface = class _DatetimeNoTzInterface extends import_datet
62
66
  }
63
67
  return `${year}-${month}-${day}`;
64
68
  }
69
+ formatExcelSerialToString(value) {
70
+ const date = (0, import_excel_date_to_js.getJsDateFromExcel)(value);
71
+ return this.formatDateTimeToString({
72
+ year: String(date.getUTCFullYear()),
73
+ month: pad2(date.getUTCMonth() + 1),
74
+ day: pad2(date.getUTCDate()),
75
+ hour: pad2(date.getUTCHours()),
76
+ minute: pad2(date.getUTCMinutes()),
77
+ second: pad2(date.getUTCSeconds())
78
+ });
79
+ }
65
80
  async toValue(value, ctx = {}) {
66
81
  if (!value) {
67
82
  return null;
@@ -77,8 +92,7 @@ const _DatetimeNoTzInterface = class _DatetimeNoTzInterface extends import_datet
77
92
  } else if (isDate(value)) {
78
93
  return value;
79
94
  } else if (isNumeric(value)) {
80
- const date = (0, import_excel_date_to_js.getJsDateFromExcel)(value);
81
- return date.toISOString();
95
+ return this.formatExcelSerialToString(value);
82
96
  } else if (typeof value === "string") {
83
97
  return value;
84
98
  }