@warlock.js/notifications 5.22.1 → 5.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.d.mts CHANGED
@@ -16,13 +16,13 @@ import { BaseNotificationsRepository, NotificationModelClass, NotificationsFilte
16
16
  import { databaseChannel } from "./channels/database-channel.mjs";
17
17
  import { MailChannelConfig, mailChannel } from "./channels/mail-channel.mjs";
18
18
  import { ConfigureOptions, NotificationsListOptions, inApp } from "./in-app/in-app.mjs";
19
- import { notificationColumns } from "./migration/notification-columns.mjs";
19
+ import { NotificationColumnsOptions, NotificationIdType, notificationColumns } from "./migration/notification-columns.mjs";
20
20
  import { HeraldQueueOptions, heraldQueue } from "./queue/herald-queue.mjs";
21
21
  import { WorkerOptions, startNotificationsWorker } from "./queue/notifications-worker.mjs";
22
22
  import { DEFAULT_QUEUE_CHANNEL } from "./queue/load-herald.mjs";
23
23
  import { BullmqQueueOptions, NOTIFICATION_JOB_NAME, bullmqQueue } from "./queue/bullmq-queue.mjs";
24
24
  import { QueuePackageLoader, loadQueuePackage } from "./queue/load-queue.mjs";
25
25
  import { QueuePackageNotInstalledError } from "./queue/queue-package-not-installed.error.mjs";
26
- export { BaseNotificationsRepository, BullmqQueueOptions, Channel, ChannelMap, ChannelName, ChannelNotFoundError, ConfigureOptions, DEFAULT_QUEUE_CHANNEL, DatabaseNotification, DatabasePayload, DefinedNotification, HeraldQueueOptions, Id, MailChannelConfig, MailPayload, MissingRendererError, NOTIFICATION_JOB_NAME, NoQueueDispatcherError, Notifiable, NotificationChannels, NotificationColumnMap, NotificationColumnMapHost, NotificationConfig, NotificationContract, NotificationDef, NotificationEvents, NotificationInput, NotificationModelClass, NotificationsFilter, NotificationsListOptions, NotificationsNotConfiguredError, Notify, PreferenceProvider, QueueDispatcher, type QueuePackageLoader, QueuePackageNotInstalledError, RateLimiter, RenderContext, ResolvedNotificationColumnMap, SendOptions, UnresolvableRouteError, WorkerOptions, bullmqQueue, databaseChannel, defineChannel, defineNotification, getNotificationConfig, heraldQueue, inApp, loadQueuePackage, mailChannel, notificationColumns, notifications, notify, resetNotificationConfig, resolveColumnMap, setNotificationConfig, startNotificationsWorker };
26
+ export { BaseNotificationsRepository, BullmqQueueOptions, Channel, ChannelMap, ChannelName, ChannelNotFoundError, ConfigureOptions, DEFAULT_QUEUE_CHANNEL, DatabaseNotification, DatabasePayload, DefinedNotification, HeraldQueueOptions, Id, MailChannelConfig, MailPayload, MissingRendererError, NOTIFICATION_JOB_NAME, NoQueueDispatcherError, Notifiable, NotificationChannels, NotificationColumnMap, NotificationColumnMapHost, NotificationColumnsOptions, NotificationConfig, NotificationContract, NotificationDef, NotificationEvents, NotificationIdType, NotificationInput, NotificationModelClass, NotificationsFilter, NotificationsListOptions, NotificationsNotConfiguredError, Notify, PreferenceProvider, QueueDispatcher, type QueuePackageLoader, QueuePackageNotInstalledError, RateLimiter, RenderContext, ResolvedNotificationColumnMap, SendOptions, UnresolvableRouteError, WorkerOptions, bullmqQueue, databaseChannel, defineChannel, defineNotification, getNotificationConfig, heraldQueue, inApp, loadQueuePackage, mailChannel, notificationColumns, notifications, notify, resetNotificationConfig, resolveColumnMap, setNotificationConfig, startNotificationsWorker };
27
27
  import "./dispatch/define-channel.mjs";
28
28
  import "./types.mjs";
@@ -1 +1 @@
1
- import { notificationColumns } from "./notification-columns.mjs";
1
+ import { NotificationColumnsOptions, NotificationIdType, notificationColumns } from "./notification-columns.mjs";
@@ -2,12 +2,17 @@ import { NotificationColumnMapHost } from "../in-app/column-map.mjs";
2
2
  import { ColumnMap } from "@warlock.js/cascade";
3
3
 
4
4
  //#region ../notifications/src/migration/notification-columns.d.ts
5
+ type NotificationIdType = "uuid" | "bigint" | "integer" | "string";
6
+ type NotificationColumnsOptions = {
7
+ /** The type used for recipient and tenant identifiers. Defaults to UUID. */idType?: NotificationIdType;
8
+ };
5
9
  /**
6
10
  * Returns the column map for a notification table, named from the model's
7
11
  * `columnMap`. Without a model, falls back to the resolved defaults
8
12
  * (`user_id` recipient + `read_at` read-state).
9
13
  */
10
- declare function notificationColumns(model?: NotificationColumnMapHost): ColumnMap;
14
+ declare function notificationColumns(options?: NotificationColumnsOptions): ColumnMap;
15
+ declare function notificationColumns(model?: NotificationColumnMapHost, options?: NotificationColumnsOptions): ColumnMap;
11
16
  //#endregion
12
- export { notificationColumns };
17
+ export { NotificationColumnsOptions, NotificationIdType, notificationColumns };
13
18
  //# sourceMappingURL=notification-columns.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"notification-columns.d.mts","names":[],"sources":["../../../../../../../notifications/src/migration/notification-columns.ts"],"mappings":";;;;;;;;;iBAiCgB,mBAAA,CAAoB,KAAA,GAAQ,yBAAA,GAA4B,SAAS"}
1
+ {"version":3,"file":"notification-columns.d.mts","names":[],"sources":["../../../../../../../notifications/src/migration/notification-columns.ts"],"mappings":";;;;KA4BY,kBAAA;AAAA,KAEA,0BAAA;EAW2G,4EATrH,MAAA,GAAS,kBAAkB;AAAA;;;;;;iBAQb,mBAAA,CAAoB,OAAA,GAAU,0BAAA,GAA6B,SAAS;AAAA,iBACpE,mBAAA,CAAoB,KAAA,GAAQ,yBAAA,EAA2B,OAAA,GAAU,0BAAA,GAA6B,SAAA"}
@@ -1,5 +1,5 @@
1
1
  import { resolveColumnMap } from "../in-app/column-map.mjs";
2
- import { boolCol, json, string, text, timestamp, uuid } from "@warlock.js/cascade";
2
+ import { bigInteger, boolCol, integer, json, string, text, timestamp, uuid } from "@warlock.js/cascade";
3
3
 
4
4
  //#region ../notifications/src/migration/notification-columns.ts
5
5
  /**
@@ -27,15 +27,13 @@ import { boolCol, json, string, text, timestamp, uuid } from "@warlock.js/cascad
27
27
  * organization_id: uuid().references(Organization.table).notNullable(),
28
28
  * });
29
29
  */
30
- /**
31
- * Returns the column map for a notification table, named from the model's
32
- * `columnMap`. Without a model, falls back to the resolved defaults
33
- * (`user_id` recipient + `read_at` read-state).
34
- */
35
- function notificationColumns(model) {
30
+ function notificationColumns(modelOrOptions, options) {
31
+ const model = isNotificationColumnsOptions(modelOrOptions) ? void 0 : modelOrOptions;
32
+ const idType = (isNotificationColumnsOptions(modelOrOptions) ? modelOrOptions : options)?.idType ?? "uuid";
36
33
  const { recipient, tenant, readAt, isRead } = resolveColumnMap(model?.columnMap);
34
+ const idColumn = getIdColumn(idType);
37
35
  const columns = {
38
- [recipient]: uuid().index().notNullable(),
36
+ [recipient]: idColumn().index().notNullable(),
39
37
  type: string().index().notNullable(),
40
38
  title: string().notNullable(),
41
39
  body: text().nullable(),
@@ -43,10 +41,21 @@ function notificationColumns(model) {
43
41
  };
44
42
  if (readAt) columns[readAt] = timestamp().nullable();
45
43
  if (isRead) columns[isRead] = boolCol().default(false).index();
46
- if (tenant) columns[tenant] = uuid().index().notNullable();
44
+ if (tenant) columns[tenant] = idColumn().index().notNullable();
47
45
  columns.idempotency_key = string().nullable().unique();
48
46
  return columns;
49
47
  }
48
+ function isNotificationColumnsOptions(value) {
49
+ return "idType" in (value ?? {});
50
+ }
51
+ function getIdColumn(idType) {
52
+ switch (idType) {
53
+ case "bigint": return bigInteger;
54
+ case "integer": return integer;
55
+ case "string": return string;
56
+ default: return uuid;
57
+ }
58
+ }
50
59
 
51
60
  //#endregion
52
61
  export { notificationColumns };
@@ -1 +1 @@
1
- {"version":3,"file":"notification-columns.mjs","names":[],"sources":["../../../../../../../notifications/src/migration/notification-columns.ts"],"sourcesContent":["/**\n * Column factory for the notifications table, driven by the model's\n * `columnMap`. The recipient / read-state / tenant columns take the NAMES the\n * model declares, so the table, the repository, and the model accessors all\n * agree by construction. The stable lexical columns (`type`, `title`, `body`,\n * `payload`, `idempotency_key`) keep fixed names.\n *\n * Read-state follows the map's presence rules (see `NotificationColumnMap`):\n * `readAt` → a nullable timestamp, `isRead` → an indexed boolean, both → both.\n *\n * Spread + extend for app-specific extras (FK references, composite indexes).\n *\n * @example\n * import { Migration } from \"@warlock.js/cascade\";\n * import { notificationColumns } from \"@warlock.js/notifications\";\n * import { Notification } from \"../notification.model\";\n *\n * export default Migration.create(Notification, notificationColumns(Notification));\n *\n * @example // with extras (multi-tenant FK)\n * export default Migration.create(Notification, {\n * ...notificationColumns(Notification),\n * organization_id: uuid().references(Organization.table).notNullable(),\n * });\n */\nimport { boolCol, type ColumnMap, json, string, text, timestamp, uuid } from \"@warlock.js/cascade\";\nimport { type NotificationColumnMapHost, resolveColumnMap } from \"../in-app/column-map\";\n\n/**\n * Returns the column map for a notification table, named from the model's\n * `columnMap`. Without a model, falls back to the resolved defaults\n * (`user_id` recipient + `read_at` read-state).\n */\nexport function notificationColumns(model?: NotificationColumnMapHost): ColumnMap {\n const { recipient, tenant, readAt, isRead } = resolveColumnMap(model?.columnMap);\n\n const columns: ColumnMap = {\n [recipient]: uuid().index().notNullable(),\n type: string().index().notNullable(),\n title: string().notNullable(),\n body: text().nullable(),\n payload: json().nullable(),\n };\n\n if (readAt) {\n columns[readAt] = timestamp().nullable();\n }\n\n if (isRead) {\n columns[isRead] = boolCol().default(false).index();\n }\n\n if (tenant) {\n columns[tenant] = uuid().index().notNullable();\n }\n\n // Unique so a retried send can't insert a duplicate. Nullable: most rows\n // have no key (NULLs are distinct in a unique index). `createFor` does\n // find-or-create; this constraint is the race backstop.\n columns.idempotency_key = string().nullable().unique();\n\n return columns;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,oBAAoB,OAA8C;CAChF,MAAM,EAAE,WAAW,QAAQ,QAAQ,WAAW,iBAAiB,OAAO,SAAS;CAE/E,MAAM,UAAqB;GACxB,YAAY,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,YAAY;EACxC,MAAM,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,YAAY;EACnC,OAAO,OAAO,CAAC,CAAC,YAAY;EAC5B,MAAM,KAAK,CAAC,CAAC,SAAS;EACtB,SAAS,KAAK,CAAC,CAAC,SAAS;CAC3B;CAEA,IAAI,QACF,QAAQ,UAAU,UAAU,CAAC,CAAC,SAAS;CAGzC,IAAI,QACF,QAAQ,UAAU,QAAQ,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,MAAM;CAGnD,IAAI,QACF,QAAQ,UAAU,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,YAAY;CAM/C,QAAQ,kBAAkB,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,OAAO;CAErD,OAAO;AACT"}
1
+ {"version":3,"file":"notification-columns.mjs","names":[],"sources":["../../../../../../../notifications/src/migration/notification-columns.ts"],"sourcesContent":["/**\n * Column factory for the notifications table, driven by the model's\n * `columnMap`. The recipient / read-state / tenant columns take the NAMES the\n * model declares, so the table, the repository, and the model accessors all\n * agree by construction. The stable lexical columns (`type`, `title`, `body`,\n * `payload`, `idempotency_key`) keep fixed names.\n *\n * Read-state follows the map's presence rules (see `NotificationColumnMap`):\n * `readAt` → a nullable timestamp, `isRead` → an indexed boolean, both → both.\n *\n * Spread + extend for app-specific extras (FK references, composite indexes).\n *\n * @example\n * import { Migration } from \"@warlock.js/cascade\";\n * import { notificationColumns } from \"@warlock.js/notifications\";\n * import { Notification } from \"../notification.model\";\n *\n * export default Migration.create(Notification, notificationColumns(Notification));\n *\n * @example // with extras (multi-tenant FK)\n * export default Migration.create(Notification, {\n * ...notificationColumns(Notification),\n * organization_id: uuid().references(Organization.table).notNullable(),\n * });\n */\nimport { bigInteger, boolCol, type ColumnMap, integer, json, string, text, timestamp, uuid } from \"@warlock.js/cascade\";\nimport { type NotificationColumnMapHost, resolveColumnMap } from \"../in-app/column-map\";\n\nexport type NotificationIdType = \"uuid\" | \"bigint\" | \"integer\" | \"string\";\n\nexport type NotificationColumnsOptions = {\n /** The type used for recipient and tenant identifiers. Defaults to UUID. */\n idType?: NotificationIdType;\n};\n\n/**\n * Returns the column map for a notification table, named from the model's\n * `columnMap`. Without a model, falls back to the resolved defaults\n * (`user_id` recipient + `read_at` read-state).\n */\nexport function notificationColumns(options?: NotificationColumnsOptions): ColumnMap;\nexport function notificationColumns(model?: NotificationColumnMapHost, options?: NotificationColumnsOptions): ColumnMap;\nexport function notificationColumns(\n modelOrOptions?: NotificationColumnMapHost | NotificationColumnsOptions,\n options?: NotificationColumnsOptions,\n): ColumnMap {\n const model = isNotificationColumnsOptions(modelOrOptions) ? undefined : modelOrOptions;\n const idType = (isNotificationColumnsOptions(modelOrOptions) ? modelOrOptions : options)?.idType ?? \"uuid\";\n const { recipient, tenant, readAt, isRead } = resolveColumnMap(model?.columnMap);\n const idColumn = getIdColumn(idType);\n\n const columns: ColumnMap = {\n [recipient]: idColumn().index().notNullable(),\n type: string().index().notNullable(),\n title: string().notNullable(),\n body: text().nullable(),\n payload: json().nullable(),\n };\n\n if (readAt) {\n columns[readAt] = timestamp().nullable();\n }\n\n if (isRead) {\n columns[isRead] = boolCol().default(false).index();\n }\n\n if (tenant) {\n columns[tenant] = idColumn().index().notNullable();\n }\n\n // Unique so a retried send can't insert a duplicate. Nullable: most rows\n // have no key (NULLs are distinct in a unique index). `createFor` does\n // find-or-create; this constraint is the race backstop.\n columns.idempotency_key = string().nullable().unique();\n\n return columns;\n}\n\nfunction isNotificationColumnsOptions(\n value: NotificationColumnMapHost | NotificationColumnsOptions | undefined,\n): value is NotificationColumnsOptions {\n return \"idType\" in (value ?? {});\n}\n\nfunction getIdColumn(idType: NotificationIdType) {\n switch (idType) {\n case \"bigint\":\n return bigInteger;\n case \"integer\":\n return integer;\n case \"string\":\n return string;\n default:\n return uuid;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,oBACd,gBACA,SACW;CACX,MAAM,QAAQ,6BAA6B,cAAc,IAAI,SAAY;CACzE,MAAM,UAAU,6BAA6B,cAAc,IAAI,iBAAiB,QAAO,EAAG,UAAU;CACpG,MAAM,EAAE,WAAW,QAAQ,QAAQ,WAAW,iBAAiB,OAAO,SAAS;CAC/E,MAAM,WAAW,YAAY,MAAM;CAEnC,MAAM,UAAqB;GACxB,YAAY,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,YAAY;EAC5C,MAAM,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,YAAY;EACnC,OAAO,OAAO,CAAC,CAAC,YAAY;EAC5B,MAAM,KAAK,CAAC,CAAC,SAAS;EACtB,SAAS,KAAK,CAAC,CAAC,SAAS;CAC3B;CAEA,IAAI,QACF,QAAQ,UAAU,UAAU,CAAC,CAAC,SAAS;CAGzC,IAAI,QACF,QAAQ,UAAU,QAAQ,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,MAAM;CAGnD,IAAI,QACF,QAAQ,UAAU,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,YAAY;CAMnD,QAAQ,kBAAkB,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,OAAO;CAErD,OAAO;AACT;AAEA,SAAS,6BACP,OACqC;CACrC,OAAO,aAAa,SAAS,CAAC;AAChC;AAEA,SAAS,YAAY,QAA4B;CAC/C,QAAQ,QAAR;EACE,KAAK,UACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
@@ -54,12 +54,20 @@ var ArrayValidator = class extends BaseValidator {
54
54
  });
55
55
  }
56
56
  /** Array length must be greater than the given length */
57
+ min(min, errorMessage) {
58
+ return this.addRule(minLengthRule, errorMessage, { minLength: min });
59
+ }
60
+ /** @alias min */
57
61
  minLength(length, errorMessage) {
58
- return this.addRule(minLengthRule, errorMessage, { minLength: length });
62
+ return this.min(length, errorMessage);
59
63
  }
60
64
  /** Array length must be less than the given length */
65
+ max(max, errorMessage) {
66
+ return this.addRule(maxLengthRule, errorMessage, { maxLength: max });
67
+ }
68
+ /** @alias max */
61
69
  maxLength(length, errorMessage) {
62
- return this.addRule(maxLengthRule, errorMessage, { maxLength: length });
70
+ return this.max(length, errorMessage);
63
71
  }
64
72
  /** Array length must be of the given length */
65
73
  length(length, errorMessage) {
@@ -1 +1 @@
1
- {"version":3,"file":"array-validator.mjs","names":[],"sources":["../../../../../../../../../seal/src/validators/array-validator.ts"],"sourcesContent":["import { setKeyPath } from \"../helpers\";\r\nimport { flipArrayMutator, sortArrayMutator, uniqueArrayMutator } from \"../mutators\";\r\nimport {\r\n arrayRule,\r\n betweenLengthRule,\r\n lengthRule,\r\n maxLengthRule,\r\n minLengthRule,\r\n sortedArrayRule,\r\n uniqueArrayRule,\r\n} from \"../rules\";\r\nimport type { SchemaContext, ValidationResult } from \"../types\";\r\nimport { BaseValidator } from \"./base-validator\";\r\nimport { applyNullable, getRuleOptions } from \"../standard-schema/json-schema\";\r\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\r\n\r\n/**\r\n * Array validator class\r\n */\r\nexport class ArrayValidator extends BaseValidator {\r\n public constructor(\r\n public validator: BaseValidator,\r\n errorMessage?: string,\r\n ) {\r\n super();\r\n this.addMutableRule(arrayRule, errorMessage);\r\n }\r\n\r\n /**\r\n * Check if value is an array type\r\n */\r\n public matchesType(value: any): boolean {\r\n return Array.isArray(value);\r\n }\r\n\r\n /**\r\n * Clone the validator\r\n */\r\n public override clone(): this {\r\n const cloned = super.clone();\r\n\r\n cloned.validator = this.validator.clone();\r\n\r\n return cloned;\r\n }\r\n\r\n /** Reverse array order */\r\n public flip() {\r\n return this.addMutator(flipArrayMutator);\r\n }\r\n\r\n /** Reverse array order (alias) */\r\n public reverse() {\r\n return this.addMutator(flipArrayMutator);\r\n }\r\n\r\n /** Make it has only unique values */\r\n public onlyUnique() {\r\n return this.addMutator(uniqueArrayMutator);\r\n }\r\n\r\n /** Sort array */\r\n public sort(direction: \"asc\" | \"desc\" = \"asc\", key?: string) {\r\n return this.addMutator(sortArrayMutator, { direction, key });\r\n }\r\n\r\n /** Array length must be greater than the given length */\r\n public minLength(length: number, errorMessage?: string) {\r\n return this.addRule(minLengthRule, errorMessage, { minLength: length });\r\n }\r\n\r\n /** Array length must be less than the given length */\r\n public maxLength(length: number, errorMessage?: string) {\r\n return this.addRule(maxLengthRule, errorMessage, { maxLength: length });\r\n }\r\n\r\n /** Array length must be of the given length */\r\n public length(length: number, errorMessage?: string) {\r\n return this.addRule(lengthRule, errorMessage, { length });\r\n }\r\n\r\n /**\r\n * Array length must be between min and max (inclusive)\r\n *\r\n * @param min - Minimum length (inclusive)\r\n * @param max - Maximum length (inclusive)\r\n *\r\n * @example\r\n * ```ts\r\n * v.array(v.string()).between(1, 10) // Array must have 1 to 10 items\r\n * v.array(v.number()).lengthBetween(5, 20) // Same using alias\r\n * ```\r\n *\r\n * @category Validation Rule\r\n */\r\n public between(min: number, max: number, errorMessage?: string) {\r\n return this.addRule(betweenLengthRule, errorMessage, {\r\n minLength: min,\r\n maxLength: max,\r\n });\r\n }\r\n\r\n /**\r\n * Alias for between() - array length between min and max\r\n */\r\n public lengthBetween(min: number, max: number, errorMessage?: string) {\r\n return this.between(min, max, errorMessage);\r\n }\r\n\r\n /** Array must have unique values */\r\n public unique(errorMessage?: string) {\r\n return this.addRule(uniqueArrayRule, errorMessage);\r\n }\r\n\r\n /** Array must be sorted */\r\n public sorted(direction: \"asc\" | \"desc\" = \"asc\", errorMessage?: string) {\r\n return this.addRule(sortedArrayRule, errorMessage, { direction });\r\n }\r\n\r\n /** Mutate the data */\r\n public mutate(data: any, context: SchemaContext) {\r\n if (!Array.isArray(data)) return data;\r\n return super.mutate([...data], context);\r\n }\r\n\r\n /** Validate array\r\n *\r\n * Absent input (and absent without `.default()`) propagates as `data: undefined`\r\n * so the parent ObjectValidator can omit the key. Without this, optional array\r\n * fields would silently materialise as `[]` in the validated output.\r\n */\r\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\r\n // Apply default when absent, then mutate. Mirrors BaseValidator's\r\n // `valueForRules = data ?? this.getDefaultValue()` so `.default([...])`\r\n // works on arrays too.\r\n const valueForRules = data ?? this.getDefaultValue();\r\n const mutatedData = await this.mutate(valueForRules, context);\r\n\r\n const result = await super.validate(data, context);\r\n\r\n if (result.isValid === false) return result;\r\n\r\n // Nothing to iterate for absent (no default) or null (nullable) inputs —\r\n // propagate so the parent ObjectValidator can omit the key.\r\n if (mutatedData === undefined || mutatedData === null) return result;\r\n\r\n // Defensive: type rule (arrayRule) should have failed for non-arrays.\r\n if (!Array.isArray(mutatedData)) return result;\r\n\r\n const errors: ValidationResult[\"errors\"] = [];\r\n\r\n // Validate all items in parallel (consistent with ObjectValidator)\r\n const validationPromises = mutatedData.map(async (value: any, index: number) => {\r\n const childContext: SchemaContext = {\r\n ...context,\r\n parent: mutatedData,\r\n value,\r\n key: index.toString(),\r\n path: setKeyPath(context.path, index.toString()),\r\n };\r\n\r\n const childResult = await this.validator.validate(value, childContext);\r\n\r\n // Update mutated data with validated result\r\n mutatedData[index] = childResult.data;\r\n\r\n // Collect errors from this element\r\n if (childResult.isValid === false) {\r\n errors.push(...childResult.errors);\r\n }\r\n });\r\n\r\n await Promise.all(validationPromises);\r\n\r\n return {\r\n isValid: errors.length === 0,\r\n errors,\r\n data: await this.startTransformationPipeline(mutatedData, context),\r\n };\r\n }\r\n\r\n /**\r\n * @inheritdoc\r\n *\r\n * Recursively generates JSON Schema for the array items.\r\n *\r\n * @example\r\n * ```ts\r\n * v.array(v.string().min(1)).minLength(1).toJsonSchema(\"draft-2020-12\")\r\n * // → { type: \"array\", items: { type: \"string\", minLength: 1 }, minItems: 1 }\r\n * ```\r\n */\r\n public override toJsonSchema(target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\r\n const schema: JsonSchemaResult = {\r\n type: \"array\",\r\n items: this.validator.toJsonSchema(target),\r\n };\r\n\r\n const minOpts = getRuleOptions(this.rules, \"minLength\");\r\n if (minOpts?.minLength !== undefined) schema.minItems = minOpts.minLength;\r\n\r\n const maxOpts = getRuleOptions(this.rules, \"maxLength\");\r\n if (maxOpts?.maxLength !== undefined) schema.maxItems = maxOpts.maxLength;\r\n\r\n const betweenOpts = getRuleOptions(this.rules, \"betweenLength\");\r\n if (betweenOpts) {\r\n if (betweenOpts.minLength !== undefined) schema.minItems = betweenOpts.minLength;\r\n if (betweenOpts.maxLength !== undefined) schema.maxItems = betweenOpts.maxLength;\r\n }\r\n\r\n const lengthOpts = getRuleOptions(this.rules, \"length\");\r\n if (lengthOpts?.length !== undefined) {\r\n schema.minItems = lengthOpts.length;\r\n schema.maxItems = lengthOpts.length;\r\n }\r\n\r\n if (this.isNullable) applyNullable(schema, target);\r\n\r\n return schema;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;AAmBA,IAAa,iBAAb,cAAoC,cAAc;CAEvC;CADT,AAAO,YACL,AAAO,WACP,cACA;EACA,MAAM;EAHC;EAIP,KAAK,eAAe,WAAW,YAAY;CAC7C;;;;CAKA,AAAO,YAAY,OAAqB;EACtC,OAAO,MAAM,QAAQ,KAAK;CAC5B;;;;CAKA,AAAgB,QAAc;EAC5B,MAAM,SAAS,MAAM,MAAM;EAE3B,OAAO,YAAY,KAAK,UAAU,MAAM;EAExC,OAAO;CACT;;CAGA,AAAO,OAAO;EACZ,OAAO,KAAK,WAAW,gBAAgB;CACzC;;CAGA,AAAO,UAAU;EACf,OAAO,KAAK,WAAW,gBAAgB;CACzC;;CAGA,AAAO,aAAa;EAClB,OAAO,KAAK,WAAW,kBAAkB;CAC3C;;CAGA,AAAO,KAAK,YAA4B,OAAO,KAAc;EAC3D,OAAO,KAAK,WAAW,kBAAkB;GAAE;GAAW;EAAI,CAAC;CAC7D;;CAGA,AAAO,UAAU,QAAgB,cAAuB;EACtD,OAAO,KAAK,QAAQ,eAAe,cAAc,EAAE,WAAW,OAAO,CAAC;CACxE;;CAGA,AAAO,UAAU,QAAgB,cAAuB;EACtD,OAAO,KAAK,QAAQ,eAAe,cAAc,EAAE,WAAW,OAAO,CAAC;CACxE;;CAGA,AAAO,OAAO,QAAgB,cAAuB;EACnD,OAAO,KAAK,QAAQ,YAAY,cAAc,EAAE,OAAO,CAAC;CAC1D;;;;;;;;;;;;;;;CAgBA,AAAO,QAAQ,KAAa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AS,OAAO,WAAW;GAC3B;GACA,MAAM,MAAM,KAAK,4BAA4B,aAAa,OAAO;EACnE;CACF;;;;;;;;;;;;CAaA,AAAgB,aAAa,SAA2B,iBAAmC;EACzF,MAAM,SAA2B;GAC/B,MAAM;GACN,OAAO,KAAK,UAAU,aAAa,MAAM;EAC3C;EAEA,MAAM,UAAU,eAAe,KAAK,OAAO,WAAW;EACtD,IAAI,SAAS,cAAc,QAAW,OAAO,WAAW,QAAQ;EAEhE,MAAM,UAAU,eAAe,KAAK,OAAO,WAAW;EACtD,IAAI,SAAS,cAAc,QAAW,OAAO,WAAW,QAAQ;EAEhE,MAAM,cAAc,eAAe,KAAK,OAAO,eAAe;EAC9D,IAAI,aAAa;GACf,IAAI,YAAY,cAAc,QAAW,OAAO,WAAW,YAAY;GACvE,IAAI,YAAY,cAAc,QAAW,OAAO,WAAW,YAAY;EACzE;EAEA,MAAM,aAAa,eAAe,KAAK,OAAO,QAAQ;EACtD,IAAI,YAAY,WAAW,QAAW;GACpC,OAAO,WAAW,WAAW;GAC7B,OAAO,WAAW,WAAW;EAC/B;EAEA,IAAI,KAAK,YAAY,cAAc,QAAQ,MAAM;EAEjD,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"array-validator.mjs","names":[],"sources":["../../../../../../../../../seal/src/validators/array-validator.ts"],"sourcesContent":["import { setKeyPath } from \"../helpers\";\r\nimport { flipArrayMutator, sortArrayMutator, uniqueArrayMutator } from \"../mutators\";\r\nimport {\r\n arrayRule,\r\n betweenLengthRule,\r\n lengthRule,\r\n maxLengthRule,\r\n minLengthRule,\r\n sortedArrayRule,\r\n uniqueArrayRule,\r\n} from \"../rules\";\r\nimport type { SchemaContext, ValidationResult } from \"../types\";\r\nimport { BaseValidator } from \"./base-validator\";\r\nimport { applyNullable, getRuleOptions } from \"../standard-schema/json-schema\";\r\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\r\n\r\n/**\r\n * Array validator class\r\n */\r\nexport class ArrayValidator extends BaseValidator {\r\n public constructor(\r\n public validator: BaseValidator,\r\n errorMessage?: string,\r\n ) {\r\n super();\r\n this.addMutableRule(arrayRule, errorMessage);\r\n }\r\n\r\n /**\r\n * Check if value is an array type\r\n */\r\n public matchesType(value: any): boolean {\r\n return Array.isArray(value);\r\n }\r\n\r\n /**\r\n * Clone the validator\r\n */\r\n public override clone(): this {\r\n const cloned = super.clone();\r\n\r\n cloned.validator = this.validator.clone();\r\n\r\n return cloned;\r\n }\r\n\r\n /** Reverse array order */\r\n public flip() {\r\n return this.addMutator(flipArrayMutator);\r\n }\r\n\r\n /** Reverse array order (alias) */\r\n public reverse() {\r\n return this.addMutator(flipArrayMutator);\r\n }\r\n\r\n /** Make it has only unique values */\r\n public onlyUnique() {\r\n return this.addMutator(uniqueArrayMutator);\r\n }\r\n\r\n /** Sort array */\r\n public sort(direction: \"asc\" | \"desc\" = \"asc\", key?: string) {\r\n return this.addMutator(sortArrayMutator, { direction, key });\r\n }\r\n\r\n /** Array length must be greater than the given length */\n public min(min: number, errorMessage?: string) {\n return this.addRule(minLengthRule, errorMessage, { minLength: min });\n }\n\n /** @alias min */\n public minLength(length: number, errorMessage?: string) {\n return this.min(length, errorMessage);\n }\n\n /** Array length must be less than the given length */\n public max(max: number, errorMessage?: string) {\n return this.addRule(maxLengthRule, errorMessage, { maxLength: max });\n }\n\n /** @alias max */\n public maxLength(length: number, errorMessage?: string) {\n return this.max(length, errorMessage);\n }\n\r\n /** Array length must be of the given length */\r\n public length(length: number, errorMessage?: string) {\r\n return this.addRule(lengthRule, errorMessage, { length });\r\n }\r\n\r\n /**\r\n * Array length must be between min and max (inclusive)\r\n *\r\n * @param min - Minimum length (inclusive)\r\n * @param max - Maximum length (inclusive)\r\n *\r\n * @example\r\n * ```ts\r\n * v.array(v.string()).between(1, 10) // Array must have 1 to 10 items\r\n * v.array(v.number()).lengthBetween(5, 20) // Same using alias\r\n * ```\r\n *\r\n * @category Validation Rule\r\n */\r\n public between(min: number, max: number, errorMessage?: string) {\r\n return this.addRule(betweenLengthRule, errorMessage, {\r\n minLength: min,\r\n maxLength: max,\r\n });\r\n }\r\n\r\n /**\r\n * Alias for between() - array length between min and max\r\n */\r\n public lengthBetween(min: number, max: number, errorMessage?: string) {\r\n return this.between(min, max, errorMessage);\r\n }\r\n\r\n /** Array must have unique values */\r\n public unique(errorMessage?: string) {\r\n return this.addRule(uniqueArrayRule, errorMessage);\r\n }\r\n\r\n /** Array must be sorted */\r\n public sorted(direction: \"asc\" | \"desc\" = \"asc\", errorMessage?: string) {\r\n return this.addRule(sortedArrayRule, errorMessage, { direction });\r\n }\r\n\r\n /** Mutate the data */\r\n public mutate(data: any, context: SchemaContext) {\r\n if (!Array.isArray(data)) return data;\r\n return super.mutate([...data], context);\r\n }\r\n\r\n /** Validate array\r\n *\r\n * Absent input (and absent without `.default()`) propagates as `data: undefined`\r\n * so the parent ObjectValidator can omit the key. Without this, optional array\r\n * fields would silently materialise as `[]` in the validated output.\r\n */\r\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\r\n // Apply default when absent, then mutate. Mirrors BaseValidator's\r\n // `valueForRules = data ?? this.getDefaultValue()` so `.default([...])`\r\n // works on arrays too.\r\n const valueForRules = data ?? this.getDefaultValue();\r\n const mutatedData = await this.mutate(valueForRules, context);\r\n\r\n const result = await super.validate(data, context);\r\n\r\n if (result.isValid === false) return result;\r\n\r\n // Nothing to iterate for absent (no default) or null (nullable) inputs —\r\n // propagate so the parent ObjectValidator can omit the key.\r\n if (mutatedData === undefined || mutatedData === null) return result;\r\n\r\n // Defensive: type rule (arrayRule) should have failed for non-arrays.\r\n if (!Array.isArray(mutatedData)) return result;\r\n\r\n const errors: ValidationResult[\"errors\"] = [];\r\n\r\n // Validate all items in parallel (consistent with ObjectValidator)\r\n const validationPromises = mutatedData.map(async (value: any, index: number) => {\r\n const childContext: SchemaContext = {\r\n ...context,\r\n parent: mutatedData,\r\n value,\r\n key: index.toString(),\r\n path: setKeyPath(context.path, index.toString()),\r\n };\r\n\r\n const childResult = await this.validator.validate(value, childContext);\r\n\r\n // Update mutated data with validated result\r\n mutatedData[index] = childResult.data;\r\n\r\n // Collect errors from this element\r\n if (childResult.isValid === false) {\r\n errors.push(...childResult.errors);\r\n }\r\n });\r\n\r\n await Promise.all(validationPromises);\r\n\r\n return {\r\n isValid: errors.length === 0,\r\n errors,\r\n data: await this.startTransformationPipeline(mutatedData, context),\r\n };\r\n }\r\n\r\n /**\r\n * @inheritdoc\r\n *\r\n * Recursively generates JSON Schema for the array items.\r\n *\r\n * @example\r\n * ```ts\r\n * v.array(v.string().min(1)).minLength(1).toJsonSchema(\"draft-2020-12\")\r\n * // → { type: \"array\", items: { type: \"string\", minLength: 1 }, minItems: 1 }\r\n * ```\r\n */\r\n public override toJsonSchema(target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\r\n const schema: JsonSchemaResult = {\r\n type: \"array\",\r\n items: this.validator.toJsonSchema(target),\r\n };\r\n\r\n const minOpts = getRuleOptions(this.rules, \"minLength\");\r\n if (minOpts?.minLength !== undefined) schema.minItems = minOpts.minLength;\r\n\r\n const maxOpts = getRuleOptions(this.rules, \"maxLength\");\r\n if (maxOpts?.maxLength !== undefined) schema.maxItems = maxOpts.maxLength;\r\n\r\n const betweenOpts = getRuleOptions(this.rules, \"betweenLength\");\r\n if (betweenOpts) {\r\n if (betweenOpts.minLength !== undefined) schema.minItems = betweenOpts.minLength;\r\n if (betweenOpts.maxLength !== undefined) schema.maxItems = betweenOpts.maxLength;\r\n }\r\n\r\n const lengthOpts = getRuleOptions(this.rules, \"length\");\r\n if (lengthOpts?.length !== undefined) {\r\n schema.minItems = lengthOpts.length;\r\n schema.maxItems = lengthOpts.length;\r\n }\r\n\r\n if (this.isNullable) applyNullable(schema, target);\r\n\r\n return schema;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;AAmBA,IAAa,iBAAb,cAAoC,cAAc;CAEvC;CADT,AAAO,YACL,AAAO,WACP,cACA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OAAO,WAAW;EACtD,IAAI,SAAS,cAAc,QAAW,OAAO,WAAW,QAAQ;EAEhE,MAAM,UAAU,eAAe,KAAK,OAAO,WAAW;EACtD,IAAI,SAAS,cAAc,QAAW,OAAO,WAAW,QAAQ;EAEhE,MAAM,cAAc,eAAe,KAAK,OAAO,eAAe;EAC9D,IAAI,aAAa;GACf,IAAI,YAAY,cAAc,QAAW,OAAO,WAAW,YAAY;GACvE,IAAI,YAAY,cAAc,QAAW,OAAO,WAAW,YAAY;EACzE;EAEA,MAAM,aAAa,eAAe,KAAK,OAAO,QAAQ;EACtD,IAAI,YAAY,WAAW,QAAW;GACpC,OAAO,WAAW,WAAW;GAC7B,OAAO,WAAW,WAAW;EAC/B;EAEA,IAAI,KAAK,YAAY,cAAc,QAAQ,MAAM;EAEjD,OAAO;CACT;AACF"}
@@ -558,7 +558,7 @@ var BaseValidator = class {
558
558
  data: null
559
559
  };
560
560
  const valueForRules = data ?? this.getDefaultValue();
561
- const mutatedData = await this.mutate(valueForRules, context);
561
+ const mutatedData = this.isOptional && valueForRules === void 0 ? void 0 : await this.mutate(valueForRules, context);
562
562
  const errors = [];
563
563
  let isValid = true;
564
564
  const isFirstErrorOnly = context.configurations?.firstErrorOnly ?? true;
@@ -1 +1 @@
1
- {"version":3,"file":"base-validator.mjs","names":["defaultRequiredRule"],"sources":["../../../../../../../../../seal/src/validators/base-validator.ts"],"sourcesContent":["import { clone } from \"@mongez/reinforcements\";\nimport { validate } from \"../factory/validate\";\nimport { VALID_RULE, invalidRule } from \"../helpers/validation-helpers\";\nimport { isEmptyValue } from \"../helpers/is-empty-value\";\nimport { requiredRule as defaultRequiredRule } from \"../rules/core/required\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport { mapToStandardResult } from \"../standard-schema/map-result\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"../standard-schema/types\";\nimport type {\n ContextualSchemaRule,\n ContextualizedMutator,\n ContextualizedTransformer,\n Mutator,\n SchemaContext,\n SchemaRule,\n SchemaRuleOptions,\n SimpleTransformerCallback,\n TransformerCallback,\n ValidationAttributesList,\n ValidationResult,\n} from \"../types\";\n\n/**\n * Base validator class - foundation for all validators\n */\nexport class BaseValidator<TInput = unknown, TOutput = TInput> {\n public rules: ContextualSchemaRule[] = [];\n public mutators: ContextualizedMutator[] = [];\n protected defaultValue: any | (() => any);\n protected description?: string;\n protected shouldOmit = false;\n protected isNullable = false;\n protected isMutable = false;\n\n /**\n * Catch state — when `hasCatch` is true and validation fails, `catchValue`\n * (or its callback result) substitutes for the failed value, and the public\n * result reports `isValid: true` with no errors.\n *\n * See `.catch()` for semantics and the v1 scope (leaf-only).\n */\n protected catchValue:\n any | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>);\n protected hasCatch = false;\n\n /**\n * Whether the field is optional.\n * - false (default): field is required unless a requiredRule governs the condition.\n * - true: field can be absent or empty — set by calling .optional().\n *\n * Also used as a TypeScript literal brand via the optional() return type.\n */\n public isOptional = false;\n\n /**\n * The single required-condition rule for this field.\n * - null: field uses strict default (always required when not optional).\n * - set: the rule governs when the field is required (e.g., requiredIf).\n *\n * Stored separately from rules[] and prepended at validate() time.\n */\n public requiredRule: ContextualSchemaRule | null = this.createRule(defaultRequiredRule);\n\n /**\n * Pipeline to transform the mutated/original data before returning it\n */\n protected dataTransformers: ContextualizedTransformer[] = [];\n\n /**\n * Attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n */\n protected attributesText: ValidationAttributesList = {};\n\n /**\n * Attributed that will be always using the attribute translator\n */\n protected translatedAttributes: Record<string, string> = {};\n\n /**\n * Mark the validator as mutable\n */\n public get mutable() {\n this.isMutable = true;\n return this;\n }\n\n /**\n * Mark the validator as immutable\n */\n public get immutable() {\n this.isMutable = false;\n return this;\n }\n\n /**\n * Get the instance to apply changes to.\n * By default (immutable), returns a clone so the original is unchanged.\n * When `.mutable` is set, returns `this` to mutate in place.\n */\n protected get instance(): this {\n return this.isMutable ? this : this.clone();\n }\n\n /**\n * Get the default value\n * Supports lazy evaluation via callbacks\n */\n public getDefaultValue(): any {\n return typeof this.defaultValue === \"function\" ? this.defaultValue() : this.defaultValue;\n }\n\n /**\n * Allow null as a valid value.\n *\n * Brands the return type with `{ isNullable: true }` so `Infer<>` widens\n * the inferred output to include `| null`.\n */\n public nullable(): this & { isNullable: true } {\n const instance = this.instance;\n instance.isNullable = true;\n return instance as this & { isNullable: true };\n }\n\n /**\n * Explicitly disallow null values after calling nullable.\n *\n * Brands the return type with `{ isNullable: false }` to cancel any prior\n * `.nullable()` at the type level.\n */\n public notNullable(): this & { isNullable: false } {\n const instance = this.instance;\n instance.isNullable = false;\n return instance as this & { isNullable: false };\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addTransformer(transform: TransformerCallback, options: any = {}) {\n const instance = this.instance;\n instance.addMutableTransformer(transform, options);\n\n return instance;\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addMutableTransformer(transform: TransformerCallback, options: any = {}) {\n this.dataTransformers.push({\n transform,\n options,\n });\n }\n\n /**\n * Transform the output value - simple one-time transformation\n *\n * @param callback - Simple callback receiving data and context\n *\n * @example\n * ```ts\n * // Simple transformation\n * v.string().outputAs(data => data.toUpperCase())\n *\n * // With context\n * v.string().outputAs((data, context) => {\n * console.log(`Transforming ${context.path}`);\n * return data.toLowerCase();\n * })\n * ```\n */\n public outputAs(callback: SimpleTransformerCallback) {\n return this.addTransformer((data, { context }) => callback(data, context));\n }\n\n /**\n * Transform output to JSON string\n *\n * Works with any validator type (string, number, date, object, array, etc.)\n *\n * @param indent - Optional indentation for pretty printing (default: 0 for compact)\n *\n * @example\n * ```ts\n * // Compact JSON\n * v.object({ name: v.string() }).toJSON()\n * // Output: '{\"name\":\"John\"}'\n *\n * // Pretty-printed JSON\n * v.array(v.object({...})).toJSON(2)\n * // Output:\n * // [\n * // {\n * // \"name\": \"John\"\n * // }\n * // ]\n *\n * // Works with any type\n * v.string().toJSON() // '\"hello\"'\n * v.number().toJSON() // '42'\n * v.date().toJSON() // '\"2024-10-26T00:00:00.000Z\"'\n * ```\n *\n * @category Transformer\n */\n public toJSON(indent?: number) {\n return this.addTransformer((data, { options }) => JSON.stringify(data, null, options.indent), {\n indent: indent ?? 0,\n });\n }\n\n /**\n * Start data transformation pipeline\n * Context is passed at runtime, not stored\n */\n public async startTransformationPipeline(data: any, context: SchemaContext) {\n for (const transformer of this.dataTransformers) {\n data = await transformer.transform(data, {\n options: transformer.options,\n context,\n });\n }\n\n return data;\n }\n\n /**\n * Set attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n *\n * @example\n * v.string().attributes({\n * name: \"Name\",\n * email: \"Email\",\n * });\n * // Example 2: Add custom attributes for matches\n * v.string().matches(\"confirmPassword\").attributes({\n * matches: {\n * confirmPassword: \"Confirm Password\",\n * },\n * });\n */\n public attributes(attributes: Record<string, string | Record<string, string>>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.attributesText[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Define a lazy getter property for each attribute in the given object and use the config attribute translator\n */\n public transAttributes(attributes: Record<string, string>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.translatedAttributes[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Add description to the validator\n */\n public describe(description: string) {\n const instance = this.instance;\n instance.description = description;\n return instance;\n }\n\n /**\n * Check if this validator can handle the given value's type\n * Override this in specific validators to enable type-based routing in union validators\n *\n * Default: returns true (validator will attempt to validate any type)\n *\n * @param value - The value to check\n * @returns True if this validator can handle this type\n *\n * @example\n * ```ts\n * // StringValidator\n * public matchesType(value: any): boolean {\n * return typeof value === 'string';\n * }\n *\n * // Custom FileValidator\n * public matchesType(value: any): boolean {\n * return value instanceof UploadedFile;\n * }\n * ```\n */\n public matchesType(_value: any): boolean {\n return true; // Default: permissive, attempt to validate any type\n }\n\n /**\n * Create a copy of this validator with the same configuration\n * Copies all rules, mutators, transformers, default values, and settings\n *\n * @returns A new validator instance with copied configuration\n *\n * @example\n * ```ts\n * // Create reusable validator templates\n * const baseString = v.string().required().trim().min(3);\n * const emailField = baseString.clone().email();\n * const usernameField = baseString.clone().alphanumeric().max(20);\n *\n * // Works with all validators\n * const positiveInt = v.int().positive().required();\n * const ageField = positiveInt.clone().min(18).max(120);\n * ```\n */\n public clone(): this {\n // Create a new instance using Object.create to preserve the prototype chain\n const Constructor = this.constructor as new (...args: any[]) => this;\n const cloned = Object.create(Constructor.prototype);\n\n // Copy all BaseValidator properties\n cloned.rules = [...this.rules];\n cloned.mutators = [...this.mutators];\n cloned.dataTransformers = [...this.dataTransformers];\n cloned.defaultValue = this.defaultValue;\n cloned.shouldOmit = this.shouldOmit;\n cloned.description = this.description;\n cloned.attributesText = { ...this.attributesText };\n cloned.isNullable = this.isNullable;\n cloned.isOptional = this.isOptional;\n cloned.requiredRule = this.requiredRule; // same reference is fine — rule is treated as immutable\n cloned.catchValue = this.catchValue;\n cloned.hasCatch = this.hasCatch;\n\n return cloned;\n }\n\n /**\n * @deprecated This method is no longer needed and does nothing.\n * Empty values are now automatically skipped for validation rules by default.\n * Only presence validators (required, present, etc.) will check empty values.\n * You can safely remove this call from your code.\n */\n public ignoreEmptyValue(_ignoreEmptyValue = true) {\n // No-op for backward compatibility\n return this;\n }\n\n /**\n * Omit this field from the validated data output\n *\n * Field will still be validated but not included in the final result.\n * Useful for confirmation fields, captcha, terms acceptance, etc.\n *\n * @example\n * ```ts\n * v.object({\n * password: v.string().required(),\n * confirmPassword: v.string().required().sameAs(\"password\").omit(),\n * acceptTerms: v.boolean().required().omit(),\n * });\n * // Output: { password: \"...\" }\n * // confirmPassword and acceptTerms validated but omitted\n * ```\n */\n public omit() {\n const instance = this.instance;\n instance.shouldOmit = true;\n return instance;\n }\n\n /**\n * @alias omit\n */\n public exclude() {\n return this.omit();\n }\n\n /**\n * Check if this field should be omitted from the output\n */\n public isOmitted(): boolean {\n return this.shouldOmit;\n }\n\n /**\n * Add rule to the validator\n */\n public addRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.addMutableRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Set the required-condition rule for this field.\n *\n * Unlike addRule(), this does NOT push to rules[]. The rule is stored in the\n * dedicated `requiredRule` slot and is prepended to the validation pipeline\n * at runtime. Only one required rule can be active per field — this replaces\n * any previously set required rule.\n *\n * Also marks the field as not optional (isOptional = false).\n *\n * @example\n * ```ts\n * // Used internally by required(), requiredIf(), requiredWith(), etc.\n * BaseValidator.prototype.required = function(msg) {\n * return this.setRequiredRule(requiredRule, msg);\n * };\n * ```\n */\n public setRequiredRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.isOptional = false;\n instance.requiredRule = instance.createRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Add mutable rule\n */\n public addMutableRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = this.createRule(rule, errorMessage, options);\n\n this.rules.push(newRule);\n\n return newRule;\n }\n\n /**\n * Create new rule\n */\n protected createRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = {\n ...(clone(rule) as ContextualSchemaRule<T>),\n context: {\n errorMessage,\n options,\n attributesList: this.attributesText,\n translatedAttributes: this.translatedAttributes,\n translationParams: {},\n translatableParams: {},\n },\n };\n\n if (errorMessage) {\n newRule.errorMessage = errorMessage;\n }\n\n if (rule.sortOrder === undefined) {\n newRule.sortOrder = this.rules.length + 1;\n }\n\n return newRule;\n }\n\n /**\n * Use a custom or pre-built validation rule\n *\n * @param rule - The validation rule to apply\n * @param options - Rule options including errorMessage and any rule-specific options\n *\n * @example\n * ```ts\n * import { hexColorRule } from \"@warlock.js/seal\";\n *\n * v.string().useRule(hexColorRule, { errorMessage: \"Invalid color\" });\n * ```\n *\n * @example\n * ```ts\n * // With rule options\n * v.string().useRule(myCustomRule, {\n * customOption: true,\n * errorMessage: \"Custom validation failed\"\n * });\n * ```\n */\n public useRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n options?: T & { errorMessage?: string },\n ) {\n const { errorMessage, ...ruleOptions } = options || ({} as any);\n return this.addRule(rule, errorMessage, ruleOptions);\n }\n\n /**\n * Define custom rule\n */\n public refine(\n callback: (\n value: any,\n context: SchemaContext,\n ) => Promise<string | undefined> | string | undefined,\n ) {\n return this.addRule({\n name: \"custom\",\n async validate(value, context) {\n const result = await callback(value, context);\n if (result) {\n this.context.errorMessage = result;\n return invalidRule(this, context);\n }\n return VALID_RULE;\n },\n });\n }\n\n /**\n * Add mutator to the validator\n */\n public addMutator(mutator: Mutator, options: any = {}) {\n const instance = this.instance;\n instance.addMutableMutator(mutator, options);\n return instance;\n }\n\n /**\n * Add mutable mutator\n */\n public addMutableMutator(mutator: Mutator, options: any = {}) {\n this.mutators.push({\n mutate: mutator,\n context: {\n options,\n ctx: {} as any,\n },\n });\n }\n\n /**\n * Set default value for the field. The default is used when the input is\n * absent (`undefined`); it then flows through the rule pipeline.\n *\n * Brands the return type with `{ hasDefault: true }` so `Infer<>` treats\n * the field as guaranteed-present even when chained with `.optional()`.\n */\n public default(value: any): this & { hasDefault: true } {\n const instance = this.instance;\n instance.defaultValue = value;\n return instance as this & { hasDefault: true };\n }\n\n /**\n * Fallback to a value when validation fails.\n *\n * Complementary to `.default()`: `.default(x)` fires when input is **absent**,\n * `.catch(y)` fires when input is **present but invalid**. Combine them when\n * you want both behaviours: `.optional().default(x).catch(y)`.\n *\n * The fallback can be a value or a callback `(errors, originalInput) => fallback`.\n * The callback variant is the only side-channel for the swallowed errors —\n * use it to log/alert before the fallback substitutes.\n *\n * Brands the return type with `{ hasCatch: true }` so `Infer<>` treats the\n * field as guaranteed-present (the catch ensures a value will always exist).\n *\n * **Scope (v1).** Catch is honoured for **leaf validators** (string, number,\n * boolean, date, …) and for fields inside containers. It is a **no-op on\n * container validators themselves** (`v.object`, `v.array`, `v.record`,\n * `v.tuple`, `v.discriminatedUnion`) — those use their own iteration logic\n * that bypasses the catch hook in `BaseValidator.validate()`.\n *\n * @example\n * ```ts\n * v.int().min(0).catch(3) // bad number → 3\n * v.string().in([\"us\", \"eu\"]).catch(\"us\") // unknown enum → \"us\"\n * v.string().catch((errors, input) => {\n * console.warn(`bad user value: ${JSON.stringify(input)}`, errors);\n * return \"anonymous\";\n * })\n * ```\n */\n public catch(\n fallback:\n any | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>),\n ): this & { hasCatch: true } {\n const instance = this.instance;\n\n instance.catchValue = fallback;\n instance.hasCatch = true;\n\n return instance as this & { hasCatch: true };\n }\n\n /**\n * Mutate the data\n */\n public async mutate(data: any, context: SchemaContext) {\n let mutatedData = data;\n\n for (const mutator of this.mutators) {\n mutator.context.ctx = context;\n mutatedData = await mutator.mutate(mutatedData, mutator.context);\n }\n\n return mutatedData;\n }\n\n /**\n * Set the label for the validator that will be matching the :input attribute\n */\n public label(label: string) {\n const instance = this.instance;\n instance.attributesText.input = label;\n return instance;\n }\n\n /**\n * Validate the data\n */\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\n if (data === null && this.isNullable) {\n return { isValid: true, errors: [], data: null };\n }\n\n const valueForRules = data ?? this.getDefaultValue();\n const mutatedData = await this.mutate(valueForRules, context);\n\n const errors: ValidationResult[\"errors\"] = [];\n let isValid = true;\n const isFirstErrorOnly = context.configurations?.firstErrorOnly ?? true;\n\n const isEmpty = isEmptyValue(valueForRules);\n\n // D8 fix (design/core-defects-found.md): for an optional field, only a\n // truly ABSENT value (`valueForRules === undefined` — the key was\n // missing, or was `null`/`undefined` and got coalesced above) may skip\n // the value rules. A PRESENT-but-empty value (e.g. `\"\"` from `?page=`)\n // must still run them, so `v.int().optional()` given `\"\"` fails instead\n // of silently handing back a string that `Infer.Output`'s\n // `number | undefined` forbids. Non-optional fields are unaffected —\n // their `requiredRule` (not nulled out by `.optional()`) already rejects\n // `\"\"` before these rules matter.\n const skipEmptyRules = this.isOptional ? valueForRules === undefined : isEmpty;\n\n // Prepend the required-condition rule if set, so it always runs first.\n // requiredRule has requiresValue = false so it runs even on empty values.\n const rulesToRun = this.requiredRule ? [this.requiredRule, ...this.rules] : this.rules;\n\n for (const rule of rulesToRun) {\n if ((rule.requiresValue ?? true) && skipEmptyRules) continue;\n\n this.setRuleAttributesList(rule);\n\n const result = await rule.validate(mutatedData, context);\n\n if (result.isValid === false) {\n isValid = false;\n errors.push({\n type: rule.name,\n error: result.error,\n input: result.path ?? context.path,\n });\n\n if (isFirstErrorOnly) {\n break;\n }\n }\n }\n\n const result: ValidationResult = {\n isValid,\n errors,\n data:\n mutatedData !== undefined\n ? await this.startTransformationPipeline(mutatedData, context)\n : undefined,\n };\n\n // Catch fallback — only on the leaf path. Container validators override\n // validate() and don't run this hook on their own outcome, so catching\n // a whole object/array/record is a no-op in v1.\n if (result.isValid === false && this.hasCatch) {\n const fallback =\n typeof this.catchValue === \"function\"\n ? await this.catchValue(result.errors, data)\n : this.catchValue;\n\n return { isValid: true, errors: [], data: fallback };\n }\n\n return result;\n }\n\n /**\n * Set rule attributes list\n */\n protected setRuleAttributesList(rule: ContextualSchemaRule) {\n rule.context.attributesList =\n typeof this.attributesText[rule.name] === \"object\"\n ? (this.attributesText[rule.name] as ValidationAttributesList)\n : this.attributesText;\n }\n\n /**\n * Standard Schema V1 compliance.\n *\n * Allows this validator to be used with any Standard Schema-aware library\n * (OpenAI structured outputs, LangGraph, TanStack Form, Conform, Valibot adapters, etc.)\n * without extra adapters.\n *\n * Delegates to the `validate()` factory so all `configureSeal()` options\n * (translations, firstErrorOnly) are picked up automatically at call time.\n *\n * Includes Standard JSON Schema support via `jsonSchema.input()` / `jsonSchema.output()`.\n *\n * ## How Standard Schema libraries consume this\n *\n * You pass the **schema object itself** to the library — they internally read\n * `schema[\"~standard\"]`. Do NOT pass `schema[\"~standard\"]` directly.\n *\n * @example\n * ```ts\n * const schema = v.object({ name: v.string().required() });\n *\n * // TanStack Form — pass schema, library reads [\"~standard\"] internally\n * const form = useForm({ validators: { onChange: schema } });\n *\n * // Conform (Remix) — same pattern\n * const [form] = useForm({ onValidate({ formData }) {\n * return parseWithStandardSchema(formData, { schema });\n * }});\n *\n * // Direct validation (lower level — most apps don't need this)\n * const result = await schema[\"~standard\"].validate({ name: \"Hasan\" });\n * // → { value: { name: \"Hasan\" } } on success\n * // → { issues: [{ message: \"...\", path: [{ key: \"name\" }] }] } on failure\n *\n * // JSON Schema for OpenAI / LangChain tool calling\n * const parameters = schema[\"~standard\"].jsonSchema.input({ target: \"openai-strict\" });\n * // → { type: \"object\", properties: {...}, required: [...], additionalProperties: false }\n * ```\n *\n * @note Cross-field rules (sameAs, requiredIf, requiredWith) rely on sibling values\n * available in the full validation context. When called on a standalone scalar validator,\n * sibling data is absent and those rules will not evaluate correctly.\n * Always call on the parent ObjectValidator for full-payload validation.\n */\n get [\"~standard\"](): StandardJSONSchemaV1.Props<TInput, TOutput> {\n return {\n version: 1,\n vendor: \"seal\",\n types: undefined as unknown as StandardSchemaV1.Types<TInput, TOutput>,\n validate: async (value: unknown) => {\n const result = await validate(this, value);\n return mapToStandardResult(result) as StandardSchemaV1.Result<TOutput>;\n },\n jsonSchema: {\n input: (options) => this.toJsonSchema(options.target),\n output: (options) => this.toJsonSchema(options.target),\n },\n };\n }\n\n /**\n * Generate a JSON Schema representation of this validator.\n *\n * Supports targets: `\"draft-2020-12\"` (default), `\"draft-07\"`, `\"openapi-3.0\"`.\n *\n * Subclasses override this to describe their specific constraints.\n * The base implementation returns `{}` (permissive — accepts anything),\n * which is correct for validators with no representable JSON Schema constraints.\n *\n * @note Rules that cannot be expressed in JSON Schema are silently omitted:\n * - Cross-field rules: sameAs, requiredIf, requiredWith, requiredWithout\n * - Custom callbacks: refine()\n * - Framework-specific runtime rules (core/cascade plugins)\n * These rules still run normally at validation time — only absent from JSON Schema.\n *\n * @example\n * ```ts\n * v.string().min(3).max(50).toJsonSchema(\"draft-2020-12\")\n * // → { type: \"string\", minLength: 3, maxLength: 50 }\n *\n * v.object({ name: v.string().required(), age: v.int().optional() })\n * .toJsonSchema(\"draft-07\")\n * // → { type: \"object\", properties: { name: { type: \"string\" }, age: { type: \"integer\" } }, required: [\"name\"] }\n * ```\n */\n public toJsonSchema(_target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,IAAa,gBAAb,MAA+D;CAC7D,AAAO,QAAgC,CAAC;CACxC,AAAO,WAAoC,CAAC;CAC5C,AAAU;CACV,AAAU;CACV,AAAU,aAAa;CACvB,AAAU,aAAa;CACvB,AAAU,YAAY;;;;;;;;CAStB,AAAU;CAEV,AAAU,WAAW;;;;;;;;CASrB,AAAO,aAAa;;;;;;;;CASpB,AAAO,eAA4C,KAAK,WAAWA,YAAmB;;;;CAKtF,AAAU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AAK,MAAM,QAAQ,YAAY;GAC7B,KAAK,KAAK,iBAAiB,SAAS,gBAAgB;GAEpD,KAAK,sBAAsB,IAAI;GAE/B,MAAM,SAAS,MAAM,KAAK,SAAS,aAAa,OAAO;GAEvD,IAAI,OAAO,YAAY,OAAO;IAC5B,UAAU;IACV,OAAO,KAAK;KACV,MAAM,KAAK;KACX,OAAO,OAAO;KACd,OAAO,OAAO,QAAQ,QAAQ;IAChC,CAAC;IAED,IAAI,kBACF;GAEJ;EACF;EAEA,MAAM,SAA2B;GAC/B;GACA;GACA,MACE,gBAAgB,SACZ,MAAM,KAAK,4BAA4B,aAAa,OAAO,IAC3D;EACR;EAKA,IAAI,OAAO,YAAY,SAAS,KAAK,UAMnC,OAAO;GAAE,SAAS;GAAM,QAAQ,CAAC;GAAG,MAJlC,OAAO,KAAK,eAAe,aACvB,MAAM,KAAK,WAAW,OAAO,QAAQ,IAAI,IACzC,KAAK;EAEwC;EAGrD,OAAO;CACT;;;;CAKA,AAAU,sBAAsB,MAA4B;EAC1D,KAAK,QAAQ,iBACX,OAAO,KAAK,eAAe,KAAK,UAAU,WACrC,KAAK,eAAe,KAAK,QAC1B,KAAK;CACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CA,KAAK,eAA4D;EAC/D,OAAO;GACL,SAAS;GACT,QAAQ;GACR,OAAO;GACP,UAAU,OAAO,UAAmB;IAElC,OAAO,oBAAoB,MADN,SAAS,MAAM,KAAK,CACR;GACnC;GACA,YAAY;IACV,QAAQ,YAAY,KAAK,aAAa,QAAQ,MAAM;IACpD,SAAS,YAAY,KAAK,aAAa,QAAQ,MAAM;GACvD;EACF;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,aAAa,UAA4B,iBAAmC;EACjF,OAAO,CAAC;CACV;AACF"}
1
+ {"version":3,"file":"base-validator.mjs","names":["defaultRequiredRule"],"sources":["../../../../../../../../../seal/src/validators/base-validator.ts"],"sourcesContent":["import { clone } from \"@mongez/reinforcements\";\nimport { validate } from \"../factory/validate\";\nimport { VALID_RULE, invalidRule } from \"../helpers/validation-helpers\";\nimport { isEmptyValue } from \"../helpers/is-empty-value\";\nimport { requiredRule as defaultRequiredRule } from \"../rules/core/required\";\nimport type { JsonSchemaResult, JsonSchemaTarget } from \"../standard-schema/json-schema\";\nimport { mapToStandardResult } from \"../standard-schema/map-result\";\nimport type { StandardJSONSchemaV1, StandardSchemaV1 } from \"../standard-schema/types\";\nimport type {\n ContextualSchemaRule,\n ContextualizedMutator,\n ContextualizedTransformer,\n Mutator,\n SchemaContext,\n SchemaRule,\n SchemaRuleOptions,\n SimpleTransformerCallback,\n TransformerCallback,\n ValidationAttributesList,\n ValidationResult,\n} from \"../types\";\n\n/**\n * Base validator class - foundation for all validators\n */\nexport class BaseValidator<TInput = unknown, TOutput = TInput> {\n public rules: ContextualSchemaRule[] = [];\n public mutators: ContextualizedMutator[] = [];\n protected defaultValue: any | (() => any);\n protected description?: string;\n protected shouldOmit = false;\n protected isNullable = false;\n protected isMutable = false;\n\n /**\n * Catch state — when `hasCatch` is true and validation fails, `catchValue`\n * (or its callback result) substitutes for the failed value, and the public\n * result reports `isValid: true` with no errors.\n *\n * See `.catch()` for semantics and the v1 scope (leaf-only).\n */\n protected catchValue:\n any | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>);\n protected hasCatch = false;\n\n /**\n * Whether the field is optional.\n * - false (default): field is required unless a requiredRule governs the condition.\n * - true: field can be absent or empty — set by calling .optional().\n *\n * Also used as a TypeScript literal brand via the optional() return type.\n */\n public isOptional = false;\n\n /**\n * The single required-condition rule for this field.\n * - null: field uses strict default (always required when not optional).\n * - set: the rule governs when the field is required (e.g., requiredIf).\n *\n * Stored separately from rules[] and prepended at validate() time.\n */\n public requiredRule: ContextualSchemaRule | null = this.createRule(defaultRequiredRule);\n\n /**\n * Pipeline to transform the mutated/original data before returning it\n */\n protected dataTransformers: ContextualizedTransformer[] = [];\n\n /**\n * Attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n */\n protected attributesText: ValidationAttributesList = {};\n\n /**\n * Attributed that will be always using the attribute translator\n */\n protected translatedAttributes: Record<string, string> = {};\n\n /**\n * Mark the validator as mutable\n */\n public get mutable() {\n this.isMutable = true;\n return this;\n }\n\n /**\n * Mark the validator as immutable\n */\n public get immutable() {\n this.isMutable = false;\n return this;\n }\n\n /**\n * Get the instance to apply changes to.\n * By default (immutable), returns a clone so the original is unchanged.\n * When `.mutable` is set, returns `this` to mutate in place.\n */\n protected get instance(): this {\n return this.isMutable ? this : this.clone();\n }\n\n /**\n * Get the default value\n * Supports lazy evaluation via callbacks\n */\n public getDefaultValue(): any {\n return typeof this.defaultValue === \"function\" ? this.defaultValue() : this.defaultValue;\n }\n\n /**\n * Allow null as a valid value.\n *\n * Brands the return type with `{ isNullable: true }` so `Infer<>` widens\n * the inferred output to include `| null`.\n */\n public nullable(): this & { isNullable: true } {\n const instance = this.instance;\n instance.isNullable = true;\n return instance as this & { isNullable: true };\n }\n\n /**\n * Explicitly disallow null values after calling nullable.\n *\n * Brands the return type with `{ isNullable: false }` to cancel any prior\n * `.nullable()` at the type level.\n */\n public notNullable(): this & { isNullable: false } {\n const instance = this.instance;\n instance.isNullable = false;\n return instance as this & { isNullable: false };\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addTransformer(transform: TransformerCallback, options: any = {}) {\n const instance = this.instance;\n instance.addMutableTransformer(transform, options);\n\n return instance;\n }\n\n /**\n * Add transformer with optional options\n *\n * @param transform - The transformer callback function\n * @param options - Optional options to pass to the transformer\n *\n * @example\n * ```ts\n * // Without options\n * v.date().addTransformer(data => data.toISOString())\n *\n * // With options\n * v.date().addTransformer(\n * (data, { options }) => dayjs(data).format(options.format),\n * { format: 'YYYY-MM-DD' }\n * )\n * ```\n */\n public addMutableTransformer(transform: TransformerCallback, options: any = {}) {\n this.dataTransformers.push({\n transform,\n options,\n });\n }\n\n /**\n * Transform the output value - simple one-time transformation\n *\n * @param callback - Simple callback receiving data and context\n *\n * @example\n * ```ts\n * // Simple transformation\n * v.string().outputAs(data => data.toUpperCase())\n *\n * // With context\n * v.string().outputAs((data, context) => {\n * console.log(`Transforming ${context.path}`);\n * return data.toLowerCase();\n * })\n * ```\n */\n public outputAs(callback: SimpleTransformerCallback) {\n return this.addTransformer((data, { context }) => callback(data, context));\n }\n\n /**\n * Transform output to JSON string\n *\n * Works with any validator type (string, number, date, object, array, etc.)\n *\n * @param indent - Optional indentation for pretty printing (default: 0 for compact)\n *\n * @example\n * ```ts\n * // Compact JSON\n * v.object({ name: v.string() }).toJSON()\n * // Output: '{\"name\":\"John\"}'\n *\n * // Pretty-printed JSON\n * v.array(v.object({...})).toJSON(2)\n * // Output:\n * // [\n * // {\n * // \"name\": \"John\"\n * // }\n * // ]\n *\n * // Works with any type\n * v.string().toJSON() // '\"hello\"'\n * v.number().toJSON() // '42'\n * v.date().toJSON() // '\"2024-10-26T00:00:00.000Z\"'\n * ```\n *\n * @category Transformer\n */\n public toJSON(indent?: number) {\n return this.addTransformer((data, { options }) => JSON.stringify(data, null, options.indent), {\n indent: indent ?? 0,\n });\n }\n\n /**\n * Start data transformation pipeline\n * Context is passed at runtime, not stored\n */\n public async startTransformationPipeline(data: any, context: SchemaContext) {\n for (const transformer of this.dataTransformers) {\n data = await transformer.transform(data, {\n options: transformer.options,\n context,\n });\n }\n\n return data;\n }\n\n /**\n * Set attributes text to be replaced on translations\n * If the value is an object, it will be used as the attributes list for the rule\n * If the value is a string, it will be used as the attributes list for the rule\n *\n * @example\n * v.string().attributes({\n * name: \"Name\",\n * email: \"Email\",\n * });\n * // Example 2: Add custom attributes for matches\n * v.string().matches(\"confirmPassword\").attributes({\n * matches: {\n * confirmPassword: \"Confirm Password\",\n * },\n * });\n */\n public attributes(attributes: Record<string, string | Record<string, string>>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.attributesText[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Define a lazy getter property for each attribute in the given object and use the config attribute translator\n */\n public transAttributes(attributes: Record<string, string>) {\n const instance = this.instance;\n for (const [key, value] of Object.entries(attributes)) {\n instance.translatedAttributes[key] = value;\n }\n\n return instance;\n }\n\n /**\n * Add description to the validator\n */\n public describe(description: string) {\n const instance = this.instance;\n instance.description = description;\n return instance;\n }\n\n /**\n * Check if this validator can handle the given value's type\n * Override this in specific validators to enable type-based routing in union validators\n *\n * Default: returns true (validator will attempt to validate any type)\n *\n * @param value - The value to check\n * @returns True if this validator can handle this type\n *\n * @example\n * ```ts\n * // StringValidator\n * public matchesType(value: any): boolean {\n * return typeof value === 'string';\n * }\n *\n * // Custom FileValidator\n * public matchesType(value: any): boolean {\n * return value instanceof UploadedFile;\n * }\n * ```\n */\n public matchesType(_value: any): boolean {\n return true; // Default: permissive, attempt to validate any type\n }\n\n /**\n * Create a copy of this validator with the same configuration\n * Copies all rules, mutators, transformers, default values, and settings\n *\n * @returns A new validator instance with copied configuration\n *\n * @example\n * ```ts\n * // Create reusable validator templates\n * const baseString = v.string().required().trim().min(3);\n * const emailField = baseString.clone().email();\n * const usernameField = baseString.clone().alphanumeric().max(20);\n *\n * // Works with all validators\n * const positiveInt = v.int().positive().required();\n * const ageField = positiveInt.clone().min(18).max(120);\n * ```\n */\n public clone(): this {\n // Create a new instance using Object.create to preserve the prototype chain\n const Constructor = this.constructor as new (...args: any[]) => this;\n const cloned = Object.create(Constructor.prototype);\n\n // Copy all BaseValidator properties\n cloned.rules = [...this.rules];\n cloned.mutators = [...this.mutators];\n cloned.dataTransformers = [...this.dataTransformers];\n cloned.defaultValue = this.defaultValue;\n cloned.shouldOmit = this.shouldOmit;\n cloned.description = this.description;\n cloned.attributesText = { ...this.attributesText };\n cloned.isNullable = this.isNullable;\n cloned.isOptional = this.isOptional;\n cloned.requiredRule = this.requiredRule; // same reference is fine — rule is treated as immutable\n cloned.catchValue = this.catchValue;\n cloned.hasCatch = this.hasCatch;\n\n return cloned;\n }\n\n /**\n * @deprecated This method is no longer needed and does nothing.\n * Empty values are now automatically skipped for validation rules by default.\n * Only presence validators (required, present, etc.) will check empty values.\n * You can safely remove this call from your code.\n */\n public ignoreEmptyValue(_ignoreEmptyValue = true) {\n // No-op for backward compatibility\n return this;\n }\n\n /**\n * Omit this field from the validated data output\n *\n * Field will still be validated but not included in the final result.\n * Useful for confirmation fields, captcha, terms acceptance, etc.\n *\n * @example\n * ```ts\n * v.object({\n * password: v.string().required(),\n * confirmPassword: v.string().required().sameAs(\"password\").omit(),\n * acceptTerms: v.boolean().required().omit(),\n * });\n * // Output: { password: \"...\" }\n * // confirmPassword and acceptTerms validated but omitted\n * ```\n */\n public omit() {\n const instance = this.instance;\n instance.shouldOmit = true;\n return instance;\n }\n\n /**\n * @alias omit\n */\n public exclude() {\n return this.omit();\n }\n\n /**\n * Check if this field should be omitted from the output\n */\n public isOmitted(): boolean {\n return this.shouldOmit;\n }\n\n /**\n * Add rule to the validator\n */\n public addRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.addMutableRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Set the required-condition rule for this field.\n *\n * Unlike addRule(), this does NOT push to rules[]. The rule is stored in the\n * dedicated `requiredRule` slot and is prepended to the validation pipeline\n * at runtime. Only one required rule can be active per field — this replaces\n * any previously set required rule.\n *\n * Also marks the field as not optional (isOptional = false).\n *\n * @example\n * ```ts\n * // Used internally by required(), requiredIf(), requiredWith(), etc.\n * BaseValidator.prototype.required = function(msg) {\n * return this.setRequiredRule(requiredRule, msg);\n * };\n * ```\n */\n public setRequiredRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): this {\n const instance = this.instance;\n instance.isOptional = false;\n instance.requiredRule = instance.createRule(rule, errorMessage, options);\n return instance;\n }\n\n /**\n * Add mutable rule\n */\n public addMutableRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = this.createRule(rule, errorMessage, options);\n\n this.rules.push(newRule);\n\n return newRule;\n }\n\n /**\n * Create new rule\n */\n protected createRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n errorMessage?: string,\n options: T = {} as T,\n ): ContextualSchemaRule<T> {\n const newRule: ContextualSchemaRule<T> = {\n ...(clone(rule) as ContextualSchemaRule<T>),\n context: {\n errorMessage,\n options,\n attributesList: this.attributesText,\n translatedAttributes: this.translatedAttributes,\n translationParams: {},\n translatableParams: {},\n },\n };\n\n if (errorMessage) {\n newRule.errorMessage = errorMessage;\n }\n\n if (rule.sortOrder === undefined) {\n newRule.sortOrder = this.rules.length + 1;\n }\n\n return newRule;\n }\n\n /**\n * Use a custom or pre-built validation rule\n *\n * @param rule - The validation rule to apply\n * @param options - Rule options including errorMessage and any rule-specific options\n *\n * @example\n * ```ts\n * import { hexColorRule } from \"@warlock.js/seal\";\n *\n * v.string().useRule(hexColorRule, { errorMessage: \"Invalid color\" });\n * ```\n *\n * @example\n * ```ts\n * // With rule options\n * v.string().useRule(myCustomRule, {\n * customOption: true,\n * errorMessage: \"Custom validation failed\"\n * });\n * ```\n */\n public useRule<T extends SchemaRuleOptions = SchemaRuleOptions>(\n rule: SchemaRule<T>,\n options?: T & { errorMessage?: string },\n ) {\n const { errorMessage, ...ruleOptions } = options || ({} as any);\n return this.addRule(rule, errorMessage, ruleOptions);\n }\n\n /**\n * Define custom rule\n */\n public refine(\n callback: (\n value: any,\n context: SchemaContext,\n ) => Promise<string | undefined> | string | undefined,\n ) {\n return this.addRule({\n name: \"custom\",\n async validate(value, context) {\n const result = await callback(value, context);\n if (result) {\n this.context.errorMessage = result;\n return invalidRule(this, context);\n }\n return VALID_RULE;\n },\n });\n }\n\n /**\n * Add mutator to the validator\n */\n public addMutator(mutator: Mutator, options: any = {}) {\n const instance = this.instance;\n instance.addMutableMutator(mutator, options);\n return instance;\n }\n\n /**\n * Add mutable mutator\n */\n public addMutableMutator(mutator: Mutator, options: any = {}) {\n this.mutators.push({\n mutate: mutator,\n context: {\n options,\n ctx: {} as any,\n },\n });\n }\n\n /**\n * Set default value for the field. The default is used when the input is\n * absent (`undefined`); it then flows through the rule pipeline.\n *\n * Brands the return type with `{ hasDefault: true }` so `Infer<>` treats\n * the field as guaranteed-present even when chained with `.optional()`.\n */\n public default(value: any): this & { hasDefault: true } {\n const instance = this.instance;\n instance.defaultValue = value;\n return instance as this & { hasDefault: true };\n }\n\n /**\n * Fallback to a value when validation fails.\n *\n * Complementary to `.default()`: `.default(x)` fires when input is **absent**,\n * `.catch(y)` fires when input is **present but invalid**. Combine them when\n * you want both behaviours: `.optional().default(x).catch(y)`.\n *\n * The fallback can be a value or a callback `(errors, originalInput) => fallback`.\n * The callback variant is the only side-channel for the swallowed errors —\n * use it to log/alert before the fallback substitutes.\n *\n * Brands the return type with `{ hasCatch: true }` so `Infer<>` treats the\n * field as guaranteed-present (the catch ensures a value will always exist).\n *\n * **Scope (v1).** Catch is honoured for **leaf validators** (string, number,\n * boolean, date, …) and for fields inside containers. It is a **no-op on\n * container validators themselves** (`v.object`, `v.array`, `v.record`,\n * `v.tuple`, `v.discriminatedUnion`) — those use their own iteration logic\n * that bypasses the catch hook in `BaseValidator.validate()`.\n *\n * @example\n * ```ts\n * v.int().min(0).catch(3) // bad number → 3\n * v.string().in([\"us\", \"eu\"]).catch(\"us\") // unknown enum → \"us\"\n * v.string().catch((errors, input) => {\n * console.warn(`bad user value: ${JSON.stringify(input)}`, errors);\n * return \"anonymous\";\n * })\n * ```\n */\n public catch(\n fallback:\n any | ((errors: ValidationResult[\"errors\"], originalInput: any) => any | Promise<any>),\n ): this & { hasCatch: true } {\n const instance = this.instance;\n\n instance.catchValue = fallback;\n instance.hasCatch = true;\n\n return instance as this & { hasCatch: true };\n }\n\n /**\n * Mutate the data\n */\n public async mutate(data: any, context: SchemaContext) {\n let mutatedData = data;\n\n for (const mutator of this.mutators) {\n mutator.context.ctx = context;\n mutatedData = await mutator.mutate(mutatedData, mutator.context);\n }\n\n return mutatedData;\n }\n\n /**\n * Set the label for the validator that will be matching the :input attribute\n */\n public label(label: string) {\n const instance = this.instance;\n instance.attributesText.input = label;\n return instance;\n }\n\n /**\n * Validate the data\n */\n public async validate(data: any, context: SchemaContext): Promise<ValidationResult> {\n if (data === null && this.isNullable) {\n return { isValid: true, errors: [], data: null };\n }\n\n const valueForRules = data ?? this.getDefaultValue();\n // Optional fields with no resolved value are absent, not values to\n // transform. Skipping here protects every mutator while still allowing\n // defaults and present values through the normal mutation pipeline.\n const mutatedData =\n this.isOptional && valueForRules === undefined\n ? undefined\n : await this.mutate(valueForRules, context);\n\n const errors: ValidationResult[\"errors\"] = [];\n let isValid = true;\n const isFirstErrorOnly = context.configurations?.firstErrorOnly ?? true;\n\n const isEmpty = isEmptyValue(valueForRules);\n\n // D8 fix (design/core-defects-found.md): for an optional field, only a\n // truly ABSENT value (`valueForRules === undefined` — the key was\n // missing, or was `null`/`undefined` and got coalesced above) may skip\n // the value rules. A PRESENT-but-empty value (e.g. `\"\"` from `?page=`)\n // must still run them, so `v.int().optional()` given `\"\"` fails instead\n // of silently handing back a string that `Infer.Output`'s\n // `number | undefined` forbids. Non-optional fields are unaffected —\n // their `requiredRule` (not nulled out by `.optional()`) already rejects\n // `\"\"` before these rules matter.\n const skipEmptyRules = this.isOptional ? valueForRules === undefined : isEmpty;\n\n // Prepend the required-condition rule if set, so it always runs first.\n // requiredRule has requiresValue = false so it runs even on empty values.\n const rulesToRun = this.requiredRule ? [this.requiredRule, ...this.rules] : this.rules;\n\n for (const rule of rulesToRun) {\n if ((rule.requiresValue ?? true) && skipEmptyRules) continue;\n\n this.setRuleAttributesList(rule);\n\n const result = await rule.validate(mutatedData, context);\n\n if (result.isValid === false) {\n isValid = false;\n errors.push({\n type: rule.name,\n error: result.error,\n input: result.path ?? context.path,\n });\n\n if (isFirstErrorOnly) {\n break;\n }\n }\n }\n\n const result: ValidationResult = {\n isValid,\n errors,\n data:\n mutatedData !== undefined\n ? await this.startTransformationPipeline(mutatedData, context)\n : undefined,\n };\n\n // Catch fallback — only on the leaf path. Container validators override\n // validate() and don't run this hook on their own outcome, so catching\n // a whole object/array/record is a no-op in v1.\n if (result.isValid === false && this.hasCatch) {\n const fallback =\n typeof this.catchValue === \"function\"\n ? await this.catchValue(result.errors, data)\n : this.catchValue;\n\n return { isValid: true, errors: [], data: fallback };\n }\n\n return result;\n }\n\n /**\n * Set rule attributes list\n */\n protected setRuleAttributesList(rule: ContextualSchemaRule) {\n rule.context.attributesList =\n typeof this.attributesText[rule.name] === \"object\"\n ? (this.attributesText[rule.name] as ValidationAttributesList)\n : this.attributesText;\n }\n\n /**\n * Standard Schema V1 compliance.\n *\n * Allows this validator to be used with any Standard Schema-aware library\n * (OpenAI structured outputs, LangGraph, TanStack Form, Conform, Valibot adapters, etc.)\n * without extra adapters.\n *\n * Delegates to the `validate()` factory so all `configureSeal()` options\n * (translations, firstErrorOnly) are picked up automatically at call time.\n *\n * Includes Standard JSON Schema support via `jsonSchema.input()` / `jsonSchema.output()`.\n *\n * ## How Standard Schema libraries consume this\n *\n * You pass the **schema object itself** to the library — they internally read\n * `schema[\"~standard\"]`. Do NOT pass `schema[\"~standard\"]` directly.\n *\n * @example\n * ```ts\n * const schema = v.object({ name: v.string().required() });\n *\n * // TanStack Form — pass schema, library reads [\"~standard\"] internally\n * const form = useForm({ validators: { onChange: schema } });\n *\n * // Conform (Remix) — same pattern\n * const [form] = useForm({ onValidate({ formData }) {\n * return parseWithStandardSchema(formData, { schema });\n * }});\n *\n * // Direct validation (lower level — most apps don't need this)\n * const result = await schema[\"~standard\"].validate({ name: \"Hasan\" });\n * // → { value: { name: \"Hasan\" } } on success\n * // → { issues: [{ message: \"...\", path: [{ key: \"name\" }] }] } on failure\n *\n * // JSON Schema for OpenAI / LangChain tool calling\n * const parameters = schema[\"~standard\"].jsonSchema.input({ target: \"openai-strict\" });\n * // → { type: \"object\", properties: {...}, required: [...], additionalProperties: false }\n * ```\n *\n * @note Cross-field rules (sameAs, requiredIf, requiredWith) rely on sibling values\n * available in the full validation context. When called on a standalone scalar validator,\n * sibling data is absent and those rules will not evaluate correctly.\n * Always call on the parent ObjectValidator for full-payload validation.\n */\n get [\"~standard\"](): StandardJSONSchemaV1.Props<TInput, TOutput> {\n return {\n version: 1,\n vendor: \"seal\",\n types: undefined as unknown as StandardSchemaV1.Types<TInput, TOutput>,\n validate: async (value: unknown) => {\n const result = await validate(this, value);\n return mapToStandardResult(result) as StandardSchemaV1.Result<TOutput>;\n },\n jsonSchema: {\n input: (options) => this.toJsonSchema(options.target),\n output: (options) => this.toJsonSchema(options.target),\n },\n };\n }\n\n /**\n * Generate a JSON Schema representation of this validator.\n *\n * Supports targets: `\"draft-2020-12\"` (default), `\"draft-07\"`, `\"openapi-3.0\"`.\n *\n * Subclasses override this to describe their specific constraints.\n * The base implementation returns `{}` (permissive — accepts anything),\n * which is correct for validators with no representable JSON Schema constraints.\n *\n * @note Rules that cannot be expressed in JSON Schema are silently omitted:\n * - Cross-field rules: sameAs, requiredIf, requiredWith, requiredWithout\n * - Custom callbacks: refine()\n * - Framework-specific runtime rules (core/cascade plugins)\n * These rules still run normally at validation time — only absent from JSON Schema.\n *\n * @example\n * ```ts\n * v.string().min(3).max(50).toJsonSchema(\"draft-2020-12\")\n * // → { type: \"string\", minLength: 3, maxLength: 50 }\n *\n * v.object({ name: v.string().required(), age: v.int().optional() })\n * .toJsonSchema(\"draft-07\")\n * // → { type: \"object\", properties: { name: { type: \"string\" }, age: { type: \"integer\" } }, required: [\"name\"] }\n * ```\n */\n public toJsonSchema(_target: JsonSchemaTarget = \"draft-2020-12\"): JsonSchemaResult {\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,IAAa,gBAAb,MAA+D;CAC7D,AAAO,QAAgC,CAAC;CACxC,AAAO,WAAoC,CAAC;CAC5C,AAAU;CACV,AAAU;CACV,AAAU,aAAa;CACvB,AAAU,aAAa;CACvB,AAAU,YAAY;;;;;;;;CAStB,AAAU;CAEV,AAAU,WAAW;;;;;;;;CASrB,AAAO,aAAa;;;;;;;;CASpB,AAAO,eAA4C,KAAK,WAAWA,YAAmB;;;;CAKtF,AAAU,mBAAgD,CAAC;;;;;;CAO3D,AAAU,iBAA2C,CAAC;;;;CAKtD,AAAU,uBAA+C,CAAC;;;;CAK1D,IAAW,UAAU;EACnB,KAAK,YAAY;EACjB,OAAO;CACT;;;;CAKA,IAAW,YAAY;EACrB,KAAK,YAAY;EACjB,OAAO;CACT;;;;;;CAOA,IAAc,WAAiB;EAC7B,OAAO,KAAK,YAAY,OAAO,KAAK,MAAM;CAC5C;;;;;CAMA,AAAO,kBAAuB;EAC5B,OAAO,OAAO,KAAK,iBAAiB,aAAa,KAAK,aAAa,IAAI,KAAK;CAC9E;;;;;;;CAQA,AAAO,WAAwC;EAC7C,MAAM,WAAW,KAAK;EACtB,SAAS,aAAa;EACtB,OAAO;CACT;;;;;;;CAQA,AAAO,cAA4C;EACjD,MAAM,WAAW,KAAK;EACtB,SAAS,aAAa;EACtB,OAAO;CACT;;;;;;;;;;;;;;;;;;;CAoBA,AAAO,eAAe,WAAgC,UAAe,CAAC,GAAG;EACvE,MAAM,WAAW,KAAK;EACtB,SAAS,sBAAsB,WAAW,OAAO;EAEjD,OAAO;CACT;;;;;;;;;;;;;;;;;;;CAoBA,AAAO,sBAAsB,WAAgC,UAAe,CAAC,GAAG;EAC9E,KAAK,iB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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CA,KAAK,eAA4D;EAC/D,OAAO;GACL,SAAS;GACT,QAAQ;GACR,OAAO;GACP,UAAU,OAAO,UAAmB;IAElC,OAAO,oBAAoB,MADN,SAAS,MAAM,KAAK,CACR;GACnC;GACA,YAAY;IACV,QAAQ,YAAY,KAAK,aAAa,QAAQ,MAAM;IACpD,SAAS,YAAY,KAAK,aAAa,QAAQ,MAAM;GACvD;EACF;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BA,AAAO,aAAa,UAA4B,iBAAmC;EACjF,OAAO,CAAC;CACV;AACF"}
package/package.json CHANGED
@@ -5,16 +5,16 @@
5
5
  "environment": "server"
6
6
  },
7
7
  "dependencies": {
8
- "@warlock.js/cache": "5.22.1",
9
- "@warlock.js/cascade": "5.22.1",
10
- "@warlock.js/core": "5.22.1",
11
- "@warlock.js/logger": "5.22.1"
8
+ "@warlock.js/cache": "5.23.0",
9
+ "@warlock.js/cascade": "5.23.0",
10
+ "@warlock.js/core": "5.23.0",
11
+ "@warlock.js/logger": "5.23.0"
12
12
  },
13
13
  "optionalDependencies": {
14
- "@warlock.js/herald": "5.22.1"
14
+ "@warlock.js/herald": "5.23.0"
15
15
  },
16
16
  "peerDependencies": {
17
- "@warlock.js/queue": "5.22.1"
17
+ "@warlock.js/queue": "5.23.0"
18
18
  },
19
19
  "peerDependenciesMeta": {
20
20
  "@warlock.js/queue": {
@@ -35,7 +35,7 @@
35
35
  ],
36
36
  "author": "hassanzohdy",
37
37
  "license": "MIT",
38
- "version": "5.22.1",
38
+ "version": "5.23.0",
39
39
  "main": "./cjs/index.cjs",
40
40
  "module": "./esm/index.mjs",
41
41
  "types": "./esm/index.d.mts",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: write-notification-migration
3
- description: 'Create the notifications table with the `notificationColumns(Notification)` factory + cascade `Migration.create`. Column NAMES come from the model''s `columnMap` (recipient / tenant / readAt / isRead); the fixed columns are `type` / `title` / `body` / `payload` / `idempotency_key`. Read-state follows columnMap presence: `readAt` → nullable timestamp, `isRead` → indexed boolean, both → both. Defaults to `user_id` + `read_at` when no columnMap. Spread + extend for extras (FK references, composite indexes). Triggers: `notificationColumns`, `Migration.create` for notifications, "create the notifications table", "notification migration", "add organization_id to notifications", `is_read` column, `read_at` column, `idempotency_key` column; typical import `import { Migration } from "@warlock.js/cascade"; import { notificationColumns } from "@warlock.js/notifications"`. Skip: generic cascade migration writing — `@warlock.js/cascade/write-migration/SKILL.md`; the model itself — `@warlock.js/notifications/use-in-app/SKILL.md`.'
3
+ description: 'Create the notifications table with the `notificationColumns(Notification)` factory + cascade `Migration.create`. Column NAMES come from the model''s `columnMap` (recipient / tenant / readAt / isRead); the fixed columns are `type` / `title` / `body` / `payload` / `idempotency_key`. Set `{ idType: "bigint" }` for integer-key apps; UUID remains the default. Read-state follows columnMap presence: `readAt` → nullable timestamp, `isRead` → indexed boolean, both → both. Defaults to `user_id` + `read_at` when no columnMap. Spread + extend for extras (FK references, composite indexes). Triggers: `notificationColumns`, `Migration.create` for notifications, "create the notifications table", "notification migration", "add organization_id to notifications", `is_read` column, `read_at` column, `idempotency_key` column; typical import `import { Migration } from "@warlock.js/cascade"; import { notificationColumns } from "@warlock.js/notifications"`. Skip: generic cascade migration writing — `@warlock.js/cascade/write-migration/SKILL.md`; the model itself — `@warlock.js/notifications/use-in-app/SKILL.md`.'
4
4
  ---
5
5
 
6
6
  # Write the notifications migration
@@ -31,7 +31,17 @@ matching columns:
31
31
 
32
32
  The recipient / tenant / read-state column NAMES come from `columnMap`; `type` /
33
33
  `title` / `body` / `payload` / `idempotency_key` are fixed. `id` / `createdAt` /
34
- `updatedAt` are added automatically by cascade.
34
+ `updatedAt` are added automatically by cascade.
35
+
36
+ ## Match your app's identifier type
37
+
38
+ Recipient and tenant columns default to UUID. For applications whose primary keys
39
+ are `bigint`, `integer`, or strings, pass `idType`; it is applied to every
40
+ identifier column the factory creates:
41
+
42
+ ```ts
43
+ export default Migration.create(Notification, notificationColumns(Notification, { idType: "bigint" }));
44
+ ```
35
45
 
36
46
  ## With extras — spread + extend
37
47
 
@@ -42,8 +52,8 @@ import { Migration, string } from "@warlock.js/cascade";
42
52
  import { notificationColumns } from "@warlock.js/notifications";
43
53
  import { Notification } from "../notification.model";
44
54
 
45
- export default Migration.create(Notification, {
46
- ...notificationColumns(Notification),
55
+ export default Migration.create(Notification, {
56
+ ...notificationColumns(Notification, { idType: "bigint" }),
47
57
  category: string().index().nullable(),
48
58
  });
49
59
  ```
@@ -1,3 +0,0 @@
1
- const require_src = require('./src-DDFfLj-d.cjs');
2
-
3
- exports.RabbitMQDriver = require_src.RabbitMQDriver;