@rpgjs/server 5.0.0-alpha.18 → 5.0.0-alpha.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6099,23 +6099,29 @@ var createSyncClass$1 = /* @__PURE__ */ __name$5((currentClass, parentKey = null
6099
6099
  const signal = currentClass.$snapshot.get(key);
6100
6100
  const syncToClient = signal.options?.syncToClient ?? true;
6101
6101
  const persist2 = signal.options?.persist ?? true;
6102
+ const transform = signal.options?.transform;
6102
6103
  let signalValue = signal();
6104
+ if (transform) {
6105
+ signalValue = transform(signalValue);
6106
+ }
6103
6107
  if (isObject$2(signalValue) || Array.isArray(signalValue)) {
6104
6108
  signalValue = {
6105
6109
  ...signalValue
6106
6110
  };
6107
6111
  }
6112
+ const transformedValue = signalValue;
6108
6113
  const newPath = (path ? path + "." : "") + key;
6109
6114
  if (syncToClient) {
6110
- currentClass.$valuesChanges.set(newPath, signalValue);
6115
+ currentClass.$valuesChanges.set(newPath, transformedValue);
6111
6116
  }
6112
6117
  if (persist2) {
6113
- if (parentClass) currentClass.$valuesChanges.setPersist(path, signalValue);
6118
+ if (parentClass) currentClass.$valuesChanges.setPersist(path, transformedValue);
6114
6119
  }
6115
6120
  if (isComputed$1(signal)) {
6116
6121
  signal.observable.subscribe((newValue) => {
6117
6122
  if (syncToClient) {
6118
- currentClass.$valuesChanges.set(newPath, newValue);
6123
+ const transformedNewValue = transform ? transform(newValue) : newValue;
6124
+ currentClass.$valuesChanges.set(newPath, transformedNewValue);
6119
6125
  }
6120
6126
  });
6121
6127
  }
@@ -6123,7 +6129,7 @@ var createSyncClass$1 = /* @__PURE__ */ __name$5((currentClass, parentKey = null
6123
6129
  }
6124
6130
  }, "createSyncClass");
6125
6131
  var type$1 = /* @__PURE__ */ __name$5((_signal, path, options = {}, currentInstance) => {
6126
- const { syncToClient = true, persist: persist2 = true } = options;
6132
+ const { syncToClient = true, persist: persist2 = true, transform } = options;
6127
6133
  let init = true;
6128
6134
  const handleObjectSubject = /* @__PURE__ */ __name$5((value, propPath) => {
6129
6135
  const newPath = `${propPath}${value.key ? `.${value.key}` : ""}`;
@@ -6173,18 +6179,20 @@ var type$1 = /* @__PURE__ */ __name$5((_signal, path, options = {}, currentInsta
6173
6179
  }
6174
6180
  }, "handleArraySubject");
6175
6181
  const savePath = /* @__PURE__ */ __name$5((propPath, value) => {
6182
+ const transformedValue = transform && value !== DELETE_TOKEN$1 ? transform(value) : value;
6176
6183
  if (syncToClient) {
6177
- currentInstance.$valuesChanges.set(propPath, value);
6184
+ currentInstance.$valuesChanges.set(propPath, transformedValue);
6178
6185
  }
6179
6186
  if (persist2 && currentInstance.$path !== void 0) {
6180
- currentInstance.$valuesChanges.setPersist(value == DELETE_TOKEN$1 ? propPath : currentInstance.$path, value);
6187
+ currentInstance.$valuesChanges.setPersist(transformedValue == DELETE_TOKEN$1 ? propPath : currentInstance.$path, transformedValue);
6181
6188
  }
6182
6189
  }, "savePath");
6183
6190
  const setupSubscription = /* @__PURE__ */ __name$5((signal, signalPath) => {
6184
6191
  if (!isSignal$1(signal)) return;
6185
6192
  if (syncToClient && currentInstance.$valuesChanges) {
6186
6193
  const initialValue = signal();
6187
- currentInstance.$valuesChanges.set(signalPath, initialValue);
6194
+ const transformedInitialValue = transform ? transform(initialValue) : initialValue;
6195
+ currentInstance.$valuesChanges.set(signalPath, transformedInitialValue);
6188
6196
  }
6189
6197
  signal.options = options;
6190
6198
  signal.observable.subscribe((value) => {
@@ -6234,6 +6242,7 @@ function sync$1(options) {
6234
6242
  let classType;
6235
6243
  let persist2 = true;
6236
6244
  let syncToClient = true;
6245
+ let transform;
6237
6246
  if (typeof options === "function") {
6238
6247
  classType = options;
6239
6248
  } else if (typeof options === "object") {
@@ -6244,6 +6253,9 @@ function sync$1(options) {
6244
6253
  if (options.hasOwnProperty("syncToClient")) {
6245
6254
  syncToClient = options.syncToClient;
6246
6255
  }
6256
+ if (options.hasOwnProperty("transform")) {
6257
+ transform = options.transform;
6258
+ }
6247
6259
  }
6248
6260
  return function(target, propertyKey) {
6249
6261
  const privatePropertyKey = `__${propertyKey}`;
@@ -6254,7 +6266,8 @@ function sync$1(options) {
6254
6266
  this[privatePropertyKey] = type$1(newVal, propertyKey, {
6255
6267
  classType,
6256
6268
  persist: persist2,
6257
- syncToClient
6269
+ syncToClient,
6270
+ transform
6258
6271
  }, this);
6259
6272
  }, "setter");
6260
6273
  Object.defineProperty(target, propertyKey, {
@@ -8143,7 +8156,12 @@ async function testRoom(Room3, options = {}) {
8143
8156
  createClient: /* @__PURE__ */ __name$3(async (id2, opts) => {
8144
8157
  const client = await io.connection(server, id2, opts);
8145
8158
  return client;
8146
- }, "createClient")
8159
+ }, "createClient"),
8160
+ getServerUser: /* @__PURE__ */ __name$3(async (client, prop = "users") => {
8161
+ const privateId = client.conn.id;
8162
+ const session = await server.getSession(privateId);
8163
+ return server.subRoom[prop]()[session?.publicId];
8164
+ }, "getServerUser")
8147
8165
  };
8148
8166
  }
8149
8167
  __name$3(testRoom, "testRoom");
@@ -8156,6 +8174,10 @@ async function request(room, path, options = {
8156
8174
  return response2;
8157
8175
  }
8158
8176
  __name$3(request, "request");
8177
+ function tick(ms = 0) {
8178
+ return new Promise((resolve) => setTimeout(resolve, ms));
8179
+ }
8180
+ __name$3(tick, "tick");
8159
8181
 
8160
8182
  // src/mock.ts
8161
8183
  var MockPartyClient = class {
@@ -10922,23 +10944,29 @@ var createSyncClass = /* @__PURE__ */ __name$2((currentClass, parentKey = null,
10922
10944
  const signal = currentClass.$snapshot.get(key);
10923
10945
  const syncToClient = signal.options?.syncToClient ?? true;
10924
10946
  const persist2 = signal.options?.persist ?? true;
10947
+ const transform = signal.options?.transform;
10925
10948
  let signalValue = signal();
10949
+ if (transform) {
10950
+ signalValue = transform(signalValue);
10951
+ }
10926
10952
  if (isObject$1(signalValue) || Array.isArray(signalValue)) {
10927
10953
  signalValue = {
10928
10954
  ...signalValue
10929
10955
  };
10930
10956
  }
10957
+ const transformedValue = signalValue;
10931
10958
  const newPath = (path ? path + "." : "") + key;
10932
10959
  if (syncToClient) {
10933
- currentClass.$valuesChanges.set(newPath, signalValue);
10960
+ currentClass.$valuesChanges.set(newPath, transformedValue);
10934
10961
  }
10935
10962
  if (persist2) {
10936
- if (parentClass) currentClass.$valuesChanges.setPersist(path, signalValue);
10963
+ if (parentClass) currentClass.$valuesChanges.setPersist(path, transformedValue);
10937
10964
  }
10938
10965
  if (isComputed(signal)) {
10939
10966
  signal.observable.subscribe((newValue) => {
10940
10967
  if (syncToClient) {
10941
- currentClass.$valuesChanges.set(newPath, newValue);
10968
+ const transformedNewValue = transform ? transform(newValue) : newValue;
10969
+ currentClass.$valuesChanges.set(newPath, transformedNewValue);
10942
10970
  }
10943
10971
  });
10944
10972
  }
@@ -10946,7 +10974,7 @@ var createSyncClass = /* @__PURE__ */ __name$2((currentClass, parentKey = null,
10946
10974
  }
10947
10975
  }, "createSyncClass");
10948
10976
  var type = /* @__PURE__ */ __name$2((_signal, path, options = {}, currentInstance) => {
10949
- const { syncToClient = true, persist: persist2 = true } = options;
10977
+ const { syncToClient = true, persist: persist2 = true, transform } = options;
10950
10978
  let init = true;
10951
10979
  const handleObjectSubject = /* @__PURE__ */ __name$2((value, propPath) => {
10952
10980
  const newPath = `${propPath}${value.key ? `.${value.key}` : ""}`;
@@ -10996,18 +11024,20 @@ var type = /* @__PURE__ */ __name$2((_signal, path, options = {}, currentInstanc
10996
11024
  }
10997
11025
  }, "handleArraySubject");
10998
11026
  const savePath = /* @__PURE__ */ __name$2((propPath, value) => {
11027
+ const transformedValue = transform && value !== DELETE_TOKEN ? transform(value) : value;
10999
11028
  if (syncToClient) {
11000
- currentInstance.$valuesChanges.set(propPath, value);
11029
+ currentInstance.$valuesChanges.set(propPath, transformedValue);
11001
11030
  }
11002
11031
  if (persist2 && currentInstance.$path !== void 0) {
11003
- currentInstance.$valuesChanges.setPersist(value == DELETE_TOKEN ? propPath : currentInstance.$path, value);
11032
+ currentInstance.$valuesChanges.setPersist(transformedValue == DELETE_TOKEN ? propPath : currentInstance.$path, transformedValue);
11004
11033
  }
11005
11034
  }, "savePath");
11006
11035
  const setupSubscription = /* @__PURE__ */ __name$2((signal, signalPath) => {
11007
11036
  if (!isSignal(signal)) return;
11008
11037
  if (syncToClient && currentInstance.$valuesChanges) {
11009
11038
  const initialValue = signal();
11010
- currentInstance.$valuesChanges.set(signalPath, initialValue);
11039
+ const transformedInitialValue = transform ? transform(initialValue) : initialValue;
11040
+ currentInstance.$valuesChanges.set(signalPath, transformedInitialValue);
11011
11041
  }
11012
11042
  signal.options = options;
11013
11043
  signal.observable.subscribe((value) => {
@@ -11057,6 +11087,7 @@ function sync(options) {
11057
11087
  let classType;
11058
11088
  let persist2 = true;
11059
11089
  let syncToClient = true;
11090
+ let transform;
11060
11091
  if (typeof options === "function") {
11061
11092
  classType = options;
11062
11093
  } else if (typeof options === "object") {
@@ -11067,6 +11098,9 @@ function sync(options) {
11067
11098
  if (options.hasOwnProperty("syncToClient")) {
11068
11099
  syncToClient = options.syncToClient;
11069
11100
  }
11101
+ if (options.hasOwnProperty("transform")) {
11102
+ transform = options.transform;
11103
+ }
11070
11104
  }
11071
11105
  return function(target, propertyKey) {
11072
11106
  const privatePropertyKey = `__${propertyKey}`;
@@ -11077,7 +11111,8 @@ function sync(options) {
11077
11111
  this[privatePropertyKey] = type(newVal, propertyKey, {
11078
11112
  classType,
11079
11113
  persist: persist2,
11080
- syncToClient
11114
+ syncToClient,
11115
+ transform
11081
11116
  }, this);
11082
11117
  }, "setter");
11083
11118
  Object.defineProperty(target, propertyKey, {
@@ -11229,6 +11264,7 @@ class Item {
11229
11264
  };
11230
11265
  this.description.set(data.description);
11231
11266
  this.price.set(data.price);
11267
+ this.name.set(data.name);
11232
11268
  this.onAdd = data.onAdd?.bind(this) ?? (() => {
11233
11269
  });
11234
11270
  }
@@ -18459,6 +18495,16 @@ class WorldMapsManager {
18459
18495
  }
18460
18496
 
18461
18497
  const ModulesToken = "ModulesToken";
18498
+ function RpgModule(options) {
18499
+ return (target) => {
18500
+ if (options.hooks) {
18501
+ target.hooks = options.hooks;
18502
+ }
18503
+ for (let key in options) {
18504
+ target.prototype[key] = options[key];
18505
+ }
18506
+ };
18507
+ }
18462
18508
  class Hooks {
18463
18509
  constructor(modules, namespace) {
18464
18510
  this.modules = modules;
@@ -19183,29 +19229,136 @@ var __defProp$3 = Object.defineProperty;
19183
19229
  var __name = (target, value) => __defProp$3(target, "name", { value, configurable: true });
19184
19230
 
19185
19231
  // src/inject.ts
19186
- function provide(context, name, value) {
19187
- context.set("inject:" + name, value);
19232
+ var DEFAULT_INSTANCE_KEY = "__default__";
19233
+ function toTokenName(token) {
19234
+ return typeof token === "function" ? token.name : token;
19235
+ }
19236
+ __name(toTokenName, "toTokenName");
19237
+ function toInstanceKey(name) {
19238
+ return name ?? DEFAULT_INSTANCE_KEY;
19239
+ }
19240
+ __name(toInstanceKey, "toInstanceKey");
19241
+ function getRecord(context, token) {
19242
+ return context.get("inject:" + toTokenName(token));
19243
+ }
19244
+ __name(getRecord, "getRecord");
19245
+ function ensureRecord(context, token) {
19246
+ const key = "inject:" + toTokenName(token);
19247
+ let record = context.get(key);
19248
+ if (!record) {
19249
+ record = {
19250
+ multi: false,
19251
+ values: /* @__PURE__ */ new Map(),
19252
+ injected: /* @__PURE__ */ new Set()
19253
+ };
19254
+ }
19255
+ context.set(key, record);
19256
+ return record;
19257
+ }
19258
+ __name(ensureRecord, "ensureRecord");
19259
+ function provide(context, token, value, options = {}) {
19260
+ const record = ensureRecord(context, token);
19261
+ const instanceKey = toInstanceKey(options.name);
19262
+ if (options.multi) {
19263
+ record.multi = true;
19264
+ }
19265
+ if (!record.multi && instanceKey !== DEFAULT_INSTANCE_KEY) {
19266
+ record.multi = true;
19267
+ }
19268
+ record.values.set(instanceKey, value);
19188
19269
  return value;
19189
19270
  }
19190
19271
  __name(provide, "provide");
19191
- function isInjected(context, name) {
19192
- return context.get("injected:" + name) === true;
19272
+ function isInjected(context, token, options = {}) {
19273
+ const record = getRecord(context, token);
19274
+ if (!record) {
19275
+ return false;
19276
+ }
19277
+ if (options.name) {
19278
+ return record.injected.has(toInstanceKey(options.name));
19279
+ }
19280
+ if (record.multi) {
19281
+ return record.injected.size > 0;
19282
+ }
19283
+ return record.injected.has(DEFAULT_INSTANCE_KEY);
19193
19284
  }
19194
19285
  __name(isInjected, "isInjected");
19195
- function isProvided(context, name) {
19196
- return context.get("inject:" + name) !== void 0;
19286
+ function isProvided(context, token, options = {}) {
19287
+ const record = getRecord(context, token);
19288
+ if (!record) {
19289
+ return false;
19290
+ }
19291
+ if (options.name) {
19292
+ return record.values.has(toInstanceKey(options.name));
19293
+ }
19294
+ if (record.multi) {
19295
+ return record.values.size > 0;
19296
+ }
19297
+ return record.values.has(DEFAULT_INSTANCE_KEY);
19197
19298
  }
19198
19299
  __name(isProvided, "isProvided");
19199
- function inject$1(context, service, args = []) {
19200
- const isClass = typeof service === "function";
19201
- const name = isClass ? service.name : service;
19202
- const value = context.get("inject:" + name);
19203
- if (value) {
19204
- context.set("injected:" + name, true);
19205
- return value;
19300
+ function hasInstance(context, token, options = {}) {
19301
+ return isProvided(context, token, options);
19302
+ }
19303
+ __name(hasInstance, "hasInstance");
19304
+ function handleMissingInjection(token, options) {
19305
+ const name = toTokenName(token);
19306
+ if (options.name) {
19307
+ throw new Error(`Injection provider ${name} with name ${options.name} not found`);
19206
19308
  }
19207
19309
  throw new Error(`Injection provider ${name} not found`);
19208
19310
  }
19311
+ __name(handleMissingInjection, "handleMissingInjection");
19312
+ function markInjected(record, key) {
19313
+ record.injected.add(key);
19314
+ }
19315
+ __name(markInjected, "markInjected");
19316
+ function markAllInjected(record) {
19317
+ for (const key of record.values.keys()) {
19318
+ record.injected.add(key);
19319
+ }
19320
+ }
19321
+ __name(markAllInjected, "markAllInjected");
19322
+ function inject$1(context, token, options = {}) {
19323
+ const record = getRecord(context, token);
19324
+ if (!record) {
19325
+ if (options.optional) {
19326
+ return options.multi ? [] : void 0;
19327
+ }
19328
+ return handleMissingInjection(token, options);
19329
+ }
19330
+ if (options.name) {
19331
+ const instanceKey = toInstanceKey(options.name);
19332
+ if (!record.values.has(instanceKey)) {
19333
+ if (options.optional) {
19334
+ return void 0;
19335
+ }
19336
+ return handleMissingInjection(token, options);
19337
+ }
19338
+ const value2 = record.values.get(instanceKey);
19339
+ markInjected(record, instanceKey);
19340
+ return value2;
19341
+ }
19342
+ if (options.multi || record.multi) {
19343
+ if (record.values.size === 0) {
19344
+ if (options.optional) {
19345
+ return [];
19346
+ }
19347
+ return handleMissingInjection(token, options);
19348
+ }
19349
+ markAllInjected(record);
19350
+ return Array.from(record.values.values());
19351
+ }
19352
+ const value = record.values.get(DEFAULT_INSTANCE_KEY);
19353
+ if (value === void 0) {
19354
+ if (options.optional) {
19355
+ return void 0;
19356
+ }
19357
+ return handleMissingInjection(token, options);
19358
+ }
19359
+ markInjected(record, DEFAULT_INSTANCE_KEY);
19360
+ return value;
19361
+ }
19209
19362
  __name(inject$1, "inject");
19210
19363
  function override(providers, newProvider, options) {
19211
19364
  let { upsert = false, key } = options ?? {};
@@ -19312,6 +19465,20 @@ function mergeConfig(baseConfig, config) {
19312
19465
  __name(mergeConfig, "mergeConfig");
19313
19466
 
19314
19467
  // src/provider.ts
19468
+ function extractProvideOptions(source) {
19469
+ if (!source) {
19470
+ return void 0;
19471
+ }
19472
+ const { multi, name } = source;
19473
+ if (multi === void 0 && name === void 0) {
19474
+ return void 0;
19475
+ }
19476
+ return {
19477
+ multi,
19478
+ name
19479
+ };
19480
+ }
19481
+ __name(extractProvideOptions, "extractProvideOptions");
19315
19482
  function getDeps(provider) {
19316
19483
  if (typeof provider === "function") {
19317
19484
  return provider.deps ?? [];
@@ -19324,7 +19491,14 @@ function sortProviders(providers) {
19324
19491
  const map = /* @__PURE__ */ new Map();
19325
19492
  for (const p of providers) {
19326
19493
  const token = tokenName(typeof p === "function" ? p : p.provide);
19327
- map.set(token, p);
19494
+ const list = map.get(token);
19495
+ if (list) {
19496
+ list.push(p);
19497
+ } else {
19498
+ map.set(token, [
19499
+ p
19500
+ ]);
19501
+ }
19328
19502
  }
19329
19503
  const result = [];
19330
19504
  const visited = /* @__PURE__ */ new Set();
@@ -19336,13 +19510,15 @@ function sortProviders(providers) {
19336
19510
  throw new Error(`Circular dependency detected for provider ${name}`);
19337
19511
  }
19338
19512
  stack.add(name);
19339
- const provider = map.get(name);
19340
- if (provider) {
19341
- for (const dep of getDeps(provider)) {
19342
- visit(dep);
19513
+ const providersForToken = map.get(name);
19514
+ if (providersForToken) {
19515
+ for (const provider of providersForToken) {
19516
+ for (const dep of getDeps(provider)) {
19517
+ visit(dep);
19518
+ }
19519
+ result.push(provider);
19343
19520
  }
19344
19521
  visited.add(name);
19345
- result.push(provider);
19346
19522
  }
19347
19523
  stack.delete(name);
19348
19524
  }, "visit");
@@ -19359,11 +19535,15 @@ async function injector(context, providers) {
19359
19535
  for (const provider of providers) {
19360
19536
  let token;
19361
19537
  let instance;
19538
+ let options;
19362
19539
  if (typeof provider === "function") {
19363
19540
  token = provider;
19364
19541
  instance = new provider(context);
19542
+ const diOptions = extractProvideOptions(provider.diOptions ?? provider.di);
19543
+ options = diOptions;
19365
19544
  } else {
19366
19545
  token = provider.provide;
19546
+ options = extractProvideOptions(provider);
19367
19547
  const provideUserClass = provider.useClass;
19368
19548
  const isClass = typeof provideUserClass === "function";
19369
19549
  if (isClass) {
@@ -19379,8 +19559,7 @@ async function injector(context, providers) {
19379
19559
  instance = inject$1(context, provider.useExisting);
19380
19560
  }
19381
19561
  }
19382
- const name = typeof token === "function" ? token.name : token;
19383
- provide(context, name, instance);
19562
+ provide(context, token, instance, options);
19384
19563
  }
19385
19564
  }
19386
19565
  __name(injector, "injector");
@@ -21544,34 +21723,116 @@ function WithItemManager(Base) {
21544
21723
  /**
21545
21724
  * Add an item in the player's inventory. You can give more than one by specifying `nb`
21546
21725
  *
21547
- * `onAdd()` method is called on the ItemClass
21726
+ * Supports three ways to add items:
21727
+ * 1. **String**: Pass a string ID to retrieve the item from the database (requires item to be registered in `@RpgModule` database).
21728
+ * 2. **Class**: Pass an item class (e.g., `Potion`). The class will be instantiated and automatically added to the map's database if not already present.
21729
+ * 3. **Object**: Pass an item object with properties and hooks directly. The object will be automatically added to the map's database if not already present.
21730
+ *
21731
+ * For classes and objects, if they don't exist in the database, they are automatically added using `map.addInDatabase()`.
21732
+ * This allows dynamic item creation without requiring pre-registration in the module database.
21733
+ *
21734
+ * `onAdd()` method is called on the ItemClass or ItemObject
21548
21735
  *
21549
21736
  * @title Add Item
21550
21737
  * @method player.addItem(item,nb=1)
21551
- * @param {ItemClass} itemClass
21738
+ * @param {ItemClass | ItemObject | string} item - Item class, object, or string identifier
21552
21739
  * @param {number} [nb] Default 1
21553
- * @returns {{ nb: number, item: instance of ItemClass }}
21740
+ * @returns {Item} The item instance added to inventory
21554
21741
  * @memberof ItemManager
21555
21742
  * @example
21556
21743
  *
21557
21744
  * ```ts
21558
21745
  * import Potion from 'your-database/potion'
21746
+ *
21747
+ * // Using string ID (retrieves from database - item must be in @RpgModule database)
21748
+ * player.addItem('Potion', 5)
21749
+ *
21750
+ * // Using class (creates instance, auto-adds to map database if not present)
21559
21751
  * player.addItem(Potion, 5)
21752
+ *
21753
+ * // Using object directly (auto-adds to map database if not present)
21754
+ * player.addItem({
21755
+ * id: 'custom-potion',
21756
+ * name: 'Custom Potion',
21757
+ * description: 'A custom potion',
21758
+ * price: 150,
21759
+ * hpValue: 50,
21760
+ * consumable: true,
21761
+ * onAdd(player) {
21762
+ * console.log('Custom potion added!');
21763
+ * },
21764
+ * onUse(player) {
21765
+ * player.hp += 50;
21766
+ * }
21767
+ * }, 3)
21768
+ *
21769
+ * // Object without ID (auto-generates ID and adds to database)
21770
+ * player.addItem({
21771
+ * name: 'Dynamic Item',
21772
+ * price: 100,
21773
+ * onUse(player) {
21774
+ * console.log('Dynamic item used!');
21775
+ * }
21776
+ * })
21560
21777
  * ```
21561
21778
  */
21562
- addItem(itemId, nb = 1) {
21563
- const data = this.databaseById(itemId);
21564
- const item = this.items().find((it) => it.id() == itemId);
21779
+ addItem(item, nb = 1) {
21780
+ const map = this.getCurrentMap();
21781
+ if (!map) {
21782
+ throw new Error("Player must be on a map to add items");
21783
+ }
21784
+ let itemId;
21785
+ let data;
21786
+ let itemInstance = null;
21787
+ if (isString(item)) {
21788
+ itemId = item;
21789
+ data = this.databaseById(itemId);
21790
+ if (!data) {
21791
+ throw new Error(
21792
+ `The ID=${itemId} data is not found in the database. Add the data in the property "database"`
21793
+ );
21794
+ }
21795
+ } else if (typeof item === "function" || item.prototype) {
21796
+ itemId = item.name;
21797
+ const existingData = map.database()[itemId];
21798
+ if (existingData) {
21799
+ data = existingData;
21800
+ } else {
21801
+ map.addInDatabase(itemId, item);
21802
+ data = item;
21803
+ }
21804
+ itemInstance = new item();
21805
+ } else {
21806
+ const itemObj = item;
21807
+ itemId = itemObj.id || `item-${Date.now()}`;
21808
+ const existingData = map.database()[itemId];
21809
+ if (existingData) {
21810
+ data = { ...existingData, ...itemObj };
21811
+ map.addInDatabase(itemId, data, { force: true });
21812
+ } else {
21813
+ map.addInDatabase(itemId, itemObj);
21814
+ data = itemObj;
21815
+ }
21816
+ itemInstance = itemObj;
21817
+ }
21818
+ const existingItem = this.items().find((it) => it.id() == itemId);
21565
21819
  let instance;
21566
- if (item) {
21567
- instance = item;
21820
+ if (existingItem) {
21821
+ instance = existingItem;
21568
21822
  instance.quantity.update((it) => it + nb);
21569
21823
  } else {
21570
21824
  instance = new Item(data);
21571
21825
  instance.id.set(itemId);
21826
+ if (itemInstance) {
21827
+ instance._itemInstance = itemInstance;
21828
+ if (itemInstance.onAdd) {
21829
+ instance.onAdd = itemInstance.onAdd.bind(itemInstance);
21830
+ }
21831
+ }
21572
21832
  this.items().push(instance);
21573
21833
  }
21574
- this["execMethod"]("onAdd", [this], instance);
21834
+ const hookTarget = instance._itemInstance || instance;
21835
+ this["execMethod"]("onAdd", [this], hookTarget);
21575
21836
  return instance;
21576
21837
  }
21577
21838
  /**
@@ -21618,7 +21879,8 @@ function WithItemManager(Base) {
21618
21879
  } else {
21619
21880
  this.items()[itemIndex].quantity.update((it) => it - nb);
21620
21881
  }
21621
- this["execMethod"]("onRemove", [this], item);
21882
+ const hookTarget = item._itemInstance || item;
21883
+ this["execMethod"]("onRemove", [this], hookTarget);
21622
21884
  return this.items()[itemIndex];
21623
21885
  }
21624
21886
  /**
@@ -21628,7 +21890,7 @@ function WithItemManager(Base) {
21628
21890
  *
21629
21891
  * @title Buy Item
21630
21892
  * @method player.buyItem(item,nb=1)
21631
- * @param {ItemClass | string} itemClass string is item id
21893
+ * @param {ItemClass | string} itemClass Identifier of the object if the parameter is a string
21632
21894
  * @param {number} [nb] Default 1
21633
21895
  * @returns {{ nb: number, item: instance of ItemClass }}
21634
21896
  * @throws {ItemLog} haveNotPrice
@@ -21654,15 +21916,36 @@ function WithItemManager(Base) {
21654
21916
  * import Potion from 'your-database/potion'
21655
21917
  *
21656
21918
  * try {
21919
+ * // Using class
21657
21920
  * player.buyItem(Potion)
21921
+ *
21922
+ * // Using string ID
21923
+ * player.buyItem('Potion')
21658
21924
  * }
21659
21925
  * catch (err) {
21660
21926
  * console.log(err)
21661
21927
  * }
21662
21928
  * ```
21663
21929
  */
21664
- buyItem(itemId, nb = 1) {
21665
- const data = this.databaseById(itemId);
21930
+ buyItem(item, nb = 1) {
21931
+ let itemId;
21932
+ let data;
21933
+ if (isString(item)) {
21934
+ itemId = item;
21935
+ data = this.databaseById(itemId);
21936
+ } else if (typeof item === "function" || item.prototype) {
21937
+ itemId = item.name;
21938
+ data = this.databaseById(itemId);
21939
+ } else {
21940
+ const itemObj = item;
21941
+ itemId = itemObj.id || `item-${Date.now()}`;
21942
+ try {
21943
+ const dbData = this.databaseById(itemId);
21944
+ data = { ...dbData, ...itemObj };
21945
+ } catch {
21946
+ data = itemObj;
21947
+ }
21948
+ }
21666
21949
  if (!data.price) {
21667
21950
  throw ItemLog.haveNotPrice(itemId);
21668
21951
  }
@@ -21671,7 +21954,7 @@ function WithItemManager(Base) {
21671
21954
  throw ItemLog.notEnoughGold(itemId, nb);
21672
21955
  }
21673
21956
  this._gold.update((gold) => gold - totalPrice);
21674
- return this.addItem(itemId, nb);
21957
+ return this.addItem(item, nb);
21675
21958
  }
21676
21959
  /**
21677
21960
  * Sell an item and the player wins the amount of the item divided by 2
@@ -21680,7 +21963,7 @@ function WithItemManager(Base) {
21680
21963
  *
21681
21964
  * @title Sell Item
21682
21965
  * @method player.sellItem(item,nb=1)
21683
- * @param {ItemClass | string} itemClass string is item id
21966
+ * @param {ItemClass | string} itemClass Identifier of the object if the parameter is a string
21684
21967
  * @param {number} [nbToSell] Default 1
21685
21968
  * @returns {{ nb: number, item: instance of ItemClass }}
21686
21969
  * @throws {ItemLog} haveNotPrice
@@ -21715,16 +21998,20 @@ function WithItemManager(Base) {
21715
21998
  *
21716
21999
  * try {
21717
22000
  * player.addItem(Potion)
22001
+ * // Using class
21718
22002
  * player.sellItem(Potion)
22003
+ * // Using string ID
22004
+ * player.sellItem('Potion')
21719
22005
  * }
21720
22006
  * catch (err) {
21721
22007
  * console.log(err)
21722
22008
  * }
21723
22009
  * ```
21724
22010
  */
21725
- sellItem(itemId, nbToSell = 1) {
22011
+ sellItem(itemClass, nbToSell = 1) {
22012
+ const itemId = isString(itemClass) ? itemClass : itemClass.name;
21726
22013
  const data = this.databaseById(itemId);
21727
- const inventory = this.getItem(itemId);
22014
+ const inventory = this.getItem(itemClass);
21728
22015
  if (!inventory) {
21729
22016
  throw ItemLog.notInInventory(itemId);
21730
22017
  }
@@ -21736,7 +22023,7 @@ function WithItemManager(Base) {
21736
22023
  throw ItemLog.haveNotPrice(itemId);
21737
22024
  }
21738
22025
  this._gold.update((gold) => gold + data.price / 2 * nbToSell);
21739
- this.removeItem(itemId, nbToSell);
22026
+ this.removeItem(itemClass, nbToSell);
21740
22027
  return inventory;
21741
22028
  }
21742
22029
  getParamItem(name) {
@@ -21789,7 +22076,7 @@ function WithItemManager(Base) {
21789
22076
  *
21790
22077
  * @title Use an Item
21791
22078
  * @method player.useItem(item,nb=1)
21792
- * @param {ItemClass | string} itemClass string is item id
22079
+ * @param {ItemClass | string} itemClass Identifier of the object if the parameter is a string
21793
22080
  * @returns {{ nb: number, item: instance of ItemClass }}
21794
22081
  * @throws {ItemLog} restriction
21795
22082
  * If the player has the `Effect.CAN_NOT_ITEM` effect
@@ -21835,15 +22122,19 @@ function WithItemManager(Base) {
21835
22122
  *
21836
22123
  * try {
21837
22124
  * player.addItem(Potion)
22125
+ * // Using class
21838
22126
  * player.useItem(Potion)
22127
+ * // Using string ID
22128
+ * player.useItem('Potion')
21839
22129
  * }
21840
22130
  * catch (err) {
21841
22131
  * console.log(err)
21842
22132
  * }
21843
22133
  * ```
21844
22134
  */
21845
- useItem(itemId) {
21846
- const inventory = this.getItem(itemId);
22135
+ useItem(itemClass) {
22136
+ const itemId = isString(itemClass) ? itemClass : itemClass.name;
22137
+ const inventory = this.getItem(itemClass);
21847
22138
  if (this.hasEffect?.("CAN_NOT_ITEM" /* CAN_NOT_ITEM */)) {
21848
22139
  throw ItemLog.restriction(itemId);
21849
22140
  }
@@ -21855,15 +22146,16 @@ function WithItemManager(Base) {
21855
22146
  throw ItemLog.notUseItem(itemId);
21856
22147
  }
21857
22148
  const hitRate = item.hitRate ?? 1;
22149
+ const hookTarget = item._itemInstance || item;
21858
22150
  if (Math.random() > hitRate) {
21859
- this.removeItem(itemId);
21860
- this["execMethod"]("onUseFailed", [this], item);
22151
+ this.removeItem(itemClass);
22152
+ this["execMethod"]("onUseFailed", [this], hookTarget);
21861
22153
  throw ItemLog.chanceToUseFailed(itemId);
21862
22154
  }
21863
22155
  this.applyEffect?.(item);
21864
22156
  this.applyStates?.(this, item);
21865
- this["execMethod"]("onUse", [this], item);
21866
- this.removeItem(itemId);
22157
+ this["execMethod"]("onUse", [this], hookTarget);
22158
+ this.removeItem(itemClass);
21867
22159
  return inventory;
21868
22160
  }
21869
22161
  /**
@@ -21873,7 +22165,7 @@ function WithItemManager(Base) {
21873
22165
  *
21874
22166
  * @title Equip Weapon or Armor
21875
22167
  * @method player.equip(itemClass,equip=true)
21876
- * @param {ItemClass | string} itemClass string is item id
22168
+ * @param {ItemClass | string} itemClass Identifier of the object if the parameter is a string
21877
22169
  * @param {number} [equip] Equip the object if true or un-equipped if false
21878
22170
  * @returns {void}
21879
22171
  * @throws {ItemLog} notInInventory
@@ -21908,15 +22200,19 @@ function WithItemManager(Base) {
21908
22200
  *
21909
22201
  * try {
21910
22202
  * player.addItem(Sword)
22203
+ * // Using class
21911
22204
  * player.equip(Sword)
22205
+ * // Using string ID
22206
+ * player.equip('Sword')
21912
22207
  * }
21913
22208
  * catch (err) {
21914
22209
  * console.log(err)
21915
22210
  * }
21916
22211
  * ```
21917
22212
  */
21918
- equip(itemId, equip = true) {
21919
- const inventory = this.getItem(itemId);
22213
+ equip(itemClass, equip = true) {
22214
+ const itemId = isString(itemClass) ? itemClass : itemClass.name;
22215
+ const inventory = this.getItem(itemClass);
21920
22216
  if (!inventory) {
21921
22217
  throw ItemLog.notInInventory(itemId);
21922
22218
  }
@@ -21945,7 +22241,8 @@ function WithItemManager(Base) {
21945
22241
  } else {
21946
22242
  this.equipments().push(item);
21947
22243
  }
21948
- this["execMethod"]("onEquip", [this, equip], item);
22244
+ const hookTarget = item._itemInstance || item;
22245
+ this["execMethod"]("onEquip", [this, equip], hookTarget);
21949
22246
  }
21950
22247
  };
21951
22248
  }
@@ -23776,21 +24073,30 @@ context$1["side"] = "server";
23776
24073
  /** A special constant with type `never` */
23777
24074
  function $constructor(name, initializer, params) {
23778
24075
  function init(inst, def) {
23779
- var _a;
23780
- Object.defineProperty(inst, "_zod", {
23781
- value: inst._zod ?? {},
23782
- enumerable: false,
23783
- });
23784
- (_a = inst._zod).traits ?? (_a.traits = new Set());
24076
+ if (!inst._zod) {
24077
+ Object.defineProperty(inst, "_zod", {
24078
+ value: {
24079
+ def,
24080
+ constr: _,
24081
+ traits: new Set(),
24082
+ },
24083
+ enumerable: false,
24084
+ });
24085
+ }
24086
+ if (inst._zod.traits.has(name)) {
24087
+ return;
24088
+ }
23785
24089
  inst._zod.traits.add(name);
23786
24090
  initializer(inst, def);
23787
24091
  // support prototype modifications
23788
- for (const k in _.prototype) {
23789
- if (!(k in inst))
23790
- Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
24092
+ const proto = _.prototype;
24093
+ const keys = Object.keys(proto);
24094
+ for (let i = 0; i < keys.length; i++) {
24095
+ const k = keys[i];
24096
+ if (!(k in inst)) {
24097
+ inst[k] = proto[k].bind(inst);
24098
+ }
23791
24099
  }
23792
- inst._zod.constr = _;
23793
- inst._zod.def = def;
23794
24100
  }
23795
24101
  // doesn't work if Parent has a constructor with arguments
23796
24102
  const Parent = params?.Parent ?? Object;
@@ -23823,6 +24129,12 @@ class $ZodAsyncError extends Error {
23823
24129
  super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
23824
24130
  }
23825
24131
  }
24132
+ class $ZodEncodeError extends Error {
24133
+ constructor(name) {
24134
+ super(`Encountered unidirectional transform during encode: ${name}`);
24135
+ this.name = "ZodEncodeError";
24136
+ }
24137
+ }
23826
24138
  const globalConfig = {};
23827
24139
  function config(newConfig) {
23828
24140
  return globalConfig;
@@ -23900,9 +24212,6 @@ function defineLazy(object, key, getter) {
23900
24212
  configurable: true,
23901
24213
  });
23902
24214
  }
23903
- function objectClone(obj) {
23904
- return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
23905
- }
23906
24215
  function assignProp(target, prop, value) {
23907
24216
  Object.defineProperty(target, prop, {
23908
24217
  value,
@@ -23922,6 +24231,14 @@ function mergeDefs(...defs) {
23922
24231
  function esc(str) {
23923
24232
  return JSON.stringify(str);
23924
24233
  }
24234
+ function slugify(input) {
24235
+ return input
24236
+ .toLowerCase()
24237
+ .trim()
24238
+ .replace(/[^\w\s-]/g, "")
24239
+ .replace(/[\s_-]+/g, "-")
24240
+ .replace(/^-+|-+$/g, "");
24241
+ }
23925
24242
  const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
23926
24243
  function isObject(data) {
23927
24244
  return typeof data === "object" && data !== null && !Array.isArray(data);
@@ -23947,6 +24264,8 @@ function isPlainObject(o) {
23947
24264
  const ctor = o.constructor;
23948
24265
  if (ctor === undefined)
23949
24266
  return true;
24267
+ if (typeof ctor !== "function")
24268
+ return true;
23950
24269
  // modified prototype
23951
24270
  const prot = ctor.prototype;
23952
24271
  if (isObject(prot) === false)
@@ -23960,6 +24279,8 @@ function isPlainObject(o) {
23960
24279
  function shallowClone(o) {
23961
24280
  if (isPlainObject(o))
23962
24281
  return { ...o };
24282
+ if (Array.isArray(o))
24283
+ return [...o];
23963
24284
  return o;
23964
24285
  }
23965
24286
  const propertyKeyTypes = new Set(["string", "number", "symbol"]);
@@ -24045,6 +24366,11 @@ function extend(schema, shape) {
24045
24366
  if (!isPlainObject(shape)) {
24046
24367
  throw new Error("Invalid input to extend: expected a plain object");
24047
24368
  }
24369
+ const checks = schema._zod.def.checks;
24370
+ const hasChecks = checks && checks.length > 0;
24371
+ if (hasChecks) {
24372
+ throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");
24373
+ }
24048
24374
  const def = mergeDefs(schema._zod.def, {
24049
24375
  get shape() {
24050
24376
  const _shape = { ...schema._zod.def.shape, ...shape };
@@ -24055,6 +24381,21 @@ function extend(schema, shape) {
24055
24381
  });
24056
24382
  return clone(schema, def);
24057
24383
  }
24384
+ function safeExtend(schema, shape) {
24385
+ if (!isPlainObject(shape)) {
24386
+ throw new Error("Invalid input to safeExtend: expected a plain object");
24387
+ }
24388
+ const def = {
24389
+ ...schema._zod.def,
24390
+ get shape() {
24391
+ const _shape = { ...schema._zod.def.shape, ...shape };
24392
+ assignProp(this, "shape", _shape); // self-caching
24393
+ return _shape;
24394
+ },
24395
+ checks: schema._zod.def.checks,
24396
+ };
24397
+ return clone(schema, def);
24398
+ }
24058
24399
  function merge(a, b) {
24059
24400
  const def = mergeDefs(a._zod.def, {
24060
24401
  get shape() {
@@ -24145,6 +24486,8 @@ function required(Class, schema, mask) {
24145
24486
  }
24146
24487
  // invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
24147
24488
  function aborted(x, startIndex = 0) {
24489
+ if (x.aborted === true)
24490
+ return true;
24148
24491
  for (let i = startIndex; i < x.issues.length; i++) {
24149
24492
  if (x.issues[i]?.continue !== true) {
24150
24493
  return true;
@@ -24234,11 +24577,7 @@ function flattenError(error, mapper = (issue) => issue.message) {
24234
24577
  }
24235
24578
  return { formErrors, fieldErrors };
24236
24579
  }
24237
- function formatError(error, _mapper) {
24238
- const mapper = _mapper ||
24239
- function (issue) {
24240
- return issue.message;
24241
- };
24580
+ function formatError(error, mapper = (issue) => issue.message) {
24242
24581
  const fieldErrors = { _errors: [] };
24243
24582
  const processError = (error) => {
24244
24583
  for (const issue of error.issues) {
@@ -24329,6 +24668,34 @@ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
24329
24668
  : { success: true, data: result.value };
24330
24669
  };
24331
24670
  const safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError);
24671
+ const _encode = (_Err) => (schema, value, _ctx) => {
24672
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
24673
+ return _parse(_Err)(schema, value, ctx);
24674
+ };
24675
+ const _decode = (_Err) => (schema, value, _ctx) => {
24676
+ return _parse(_Err)(schema, value, _ctx);
24677
+ };
24678
+ const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
24679
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
24680
+ return _parseAsync(_Err)(schema, value, ctx);
24681
+ };
24682
+ const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
24683
+ return _parseAsync(_Err)(schema, value, _ctx);
24684
+ };
24685
+ const _safeEncode = (_Err) => (schema, value, _ctx) => {
24686
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
24687
+ return _safeParse(_Err)(schema, value, ctx);
24688
+ };
24689
+ const _safeDecode = (_Err) => (schema, value, _ctx) => {
24690
+ return _safeParse(_Err)(schema, value, _ctx);
24691
+ };
24692
+ const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
24693
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
24694
+ return _safeParseAsync(_Err)(schema, value, ctx);
24695
+ };
24696
+ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
24697
+ return _safeParseAsync(_Err)(schema, value, _ctx);
24698
+ };
24332
24699
 
24333
24700
  const cuid = /^[cC][^\s-]{8,}$/;
24334
24701
  const cuid2 = /^[0-9a-z]+$/;
@@ -24345,7 +24712,7 @@ const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9
24345
24712
  * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
24346
24713
  const uuid = (version) => {
24347
24714
  if (!version)
24348
- return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
24715
+ return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
24349
24716
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
24350
24717
  };
24351
24718
  /** Practical email validation */
@@ -24356,15 +24723,12 @@ function emoji() {
24356
24723
  return new RegExp(_emoji$1, "u");
24357
24724
  }
24358
24725
  const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
24359
- const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
24726
+ const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
24360
24727
  const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
24361
24728
  const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
24362
24729
  // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
24363
24730
  const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
24364
24731
  const base64url = /^[A-Za-z0-9_-]*$/;
24365
- // based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
24366
- // export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
24367
- const hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
24368
24732
  // https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
24369
24733
  const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
24370
24734
  // const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
@@ -24400,8 +24764,8 @@ const string$1 = (params) => {
24400
24764
  const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
24401
24765
  return new RegExp(`^${regex}$`);
24402
24766
  };
24403
- const integer = /^\d+$/;
24404
- const number$1 = /^-?\d+(?:\.\d+)?/i;
24767
+ const integer = /^-?\d+$/;
24768
+ const number$1 = /^-?\d+(?:\.\d+)?/;
24405
24769
  // regex for string with no uppercase letters
24406
24770
  const lowercase = /^[^A-Z]*$/;
24407
24771
  // regex for string with no lowercase letters
@@ -24853,8 +25217,8 @@ class Doc {
24853
25217
 
24854
25218
  const version = {
24855
25219
  major: 4,
24856
- minor: 0,
24857
- patch: 17,
25220
+ minor: 1,
25221
+ patch: 13,
24858
25222
  };
24859
25223
 
24860
25224
  const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
@@ -24868,7 +25232,6 @@ const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
24868
25232
  if (inst._zod.traits.has("$ZodCheck")) {
24869
25233
  checks.unshift(inst);
24870
25234
  }
24871
- //
24872
25235
  for (const ch of checks) {
24873
25236
  for (const fn of ch._zod.onattach) {
24874
25237
  fn(inst);
@@ -24925,7 +25288,47 @@ const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
24925
25288
  }
24926
25289
  return payload;
24927
25290
  };
25291
+ // const handleChecksResult = (
25292
+ // checkResult: ParsePayload,
25293
+ // originalResult: ParsePayload,
25294
+ // ctx: ParseContextInternal
25295
+ // ): util.MaybeAsync<ParsePayload> => {
25296
+ // // if the checks mutated the value && there are no issues, re-parse the result
25297
+ // if (checkResult.value !== originalResult.value && !checkResult.issues.length)
25298
+ // return inst._zod.parse(checkResult, ctx);
25299
+ // return originalResult;
25300
+ // };
25301
+ const handleCanaryResult = (canary, payload, ctx) => {
25302
+ // abort if the canary is aborted
25303
+ if (aborted(canary)) {
25304
+ canary.aborted = true;
25305
+ return canary;
25306
+ }
25307
+ // run checks first, then
25308
+ const checkResult = runChecks(payload, checks, ctx);
25309
+ if (checkResult instanceof Promise) {
25310
+ if (ctx.async === false)
25311
+ throw new $ZodAsyncError();
25312
+ return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
25313
+ }
25314
+ return inst._zod.parse(checkResult, ctx);
25315
+ };
24928
25316
  inst._zod.run = (payload, ctx) => {
25317
+ if (ctx.skipChecks) {
25318
+ return inst._zod.parse(payload, ctx);
25319
+ }
25320
+ if (ctx.direction === "backward") {
25321
+ // run canary
25322
+ // initial pass (no checks)
25323
+ const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
25324
+ if (canary instanceof Promise) {
25325
+ return canary.then((canary) => {
25326
+ return handleCanaryResult(canary, payload, ctx);
25327
+ });
25328
+ }
25329
+ return handleCanaryResult(canary, payload, ctx);
25330
+ }
25331
+ // forward
24929
25332
  const result = inst._zod.parse(payload, ctx);
24930
25333
  if (result instanceof Promise) {
24931
25334
  if (ctx.async === false)
@@ -25018,7 +25421,7 @@ const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => {
25018
25421
  code: "invalid_format",
25019
25422
  format: "url",
25020
25423
  note: "Invalid hostname",
25021
- pattern: hostname.source,
25424
+ pattern: def.hostname.source,
25022
25425
  input: payload.value,
25023
25426
  inst,
25024
25427
  continue: !def.abort,
@@ -25108,18 +25511,12 @@ const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def
25108
25511
  const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
25109
25512
  def.pattern ?? (def.pattern = ipv4);
25110
25513
  $ZodStringFormat.init(inst, def);
25111
- inst._zod.onattach.push((inst) => {
25112
- const bag = inst._zod.bag;
25113
- bag.format = `ipv4`;
25114
- });
25514
+ inst._zod.bag.format = `ipv4`;
25115
25515
  });
25116
25516
  const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
25117
25517
  def.pattern ?? (def.pattern = ipv6);
25118
25518
  $ZodStringFormat.init(inst, def);
25119
- inst._zod.onattach.push((inst) => {
25120
- const bag = inst._zod.bag;
25121
- bag.format = `ipv6`;
25122
- });
25519
+ inst._zod.bag.format = `ipv6`;
25123
25520
  inst._zod.check = (payload) => {
25124
25521
  try {
25125
25522
  // @ts-ignore
@@ -25145,8 +25542,11 @@ const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
25145
25542
  def.pattern ?? (def.pattern = cidrv6); // not used for validation
25146
25543
  $ZodStringFormat.init(inst, def);
25147
25544
  inst._zod.check = (payload) => {
25148
- const [address, prefix] = payload.value.split("/");
25545
+ const parts = payload.value.split("/");
25149
25546
  try {
25547
+ if (parts.length !== 2)
25548
+ throw new Error();
25549
+ const [address, prefix] = parts;
25150
25550
  if (!prefix)
25151
25551
  throw new Error();
25152
25552
  const prefixNum = Number(prefix);
@@ -25186,9 +25586,7 @@ function isValidBase64(data) {
25186
25586
  const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => {
25187
25587
  def.pattern ?? (def.pattern = base64);
25188
25588
  $ZodStringFormat.init(inst, def);
25189
- inst._zod.onattach.push((inst) => {
25190
- inst._zod.bag.contentEncoding = "base64";
25191
- });
25589
+ inst._zod.bag.contentEncoding = "base64";
25192
25590
  inst._zod.check = (payload) => {
25193
25591
  if (isValidBase64(payload.value))
25194
25592
  return;
@@ -25212,9 +25610,7 @@ function isValidBase64URL(data) {
25212
25610
  const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
25213
25611
  def.pattern ?? (def.pattern = base64url);
25214
25612
  $ZodStringFormat.init(inst, def);
25215
- inst._zod.onattach.push((inst) => {
25216
- inst._zod.bag.contentEncoding = "base64url";
25217
- });
25613
+ inst._zod.bag.contentEncoding = "base64url";
25218
25614
  inst._zod.check = (payload) => {
25219
25615
  if (isValidBase64URL(payload.value))
25220
25616
  return;
@@ -25298,9 +25694,9 @@ const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
25298
25694
  return payload;
25299
25695
  };
25300
25696
  });
25301
- const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
25697
+ const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => {
25302
25698
  $ZodCheckNumberFormat.init(inst, def);
25303
- $ZodNumber.init(inst, def); // no format checksp
25699
+ $ZodNumber.init(inst, def); // no format checks
25304
25700
  });
25305
25701
  const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => {
25306
25702
  $ZodType.init(inst, def);
@@ -25375,25 +25771,75 @@ function handlePropertyResult(result, final, key, input) {
25375
25771
  final.value[key] = result.value;
25376
25772
  }
25377
25773
  }
25774
+ function normalizeDef(def) {
25775
+ const keys = Object.keys(def.shape);
25776
+ for (const k of keys) {
25777
+ if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
25778
+ throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
25779
+ }
25780
+ }
25781
+ const okeys = optionalKeys(def.shape);
25782
+ return {
25783
+ ...def,
25784
+ keys,
25785
+ keySet: new Set(keys),
25786
+ numKeys: keys.length,
25787
+ optionalKeys: new Set(okeys),
25788
+ };
25789
+ }
25790
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
25791
+ const unrecognized = [];
25792
+ // iterate over input keys
25793
+ const keySet = def.keySet;
25794
+ const _catchall = def.catchall._zod;
25795
+ const t = _catchall.def.type;
25796
+ for (const key in input) {
25797
+ if (keySet.has(key))
25798
+ continue;
25799
+ if (t === "never") {
25800
+ unrecognized.push(key);
25801
+ continue;
25802
+ }
25803
+ const r = _catchall.run({ value: input[key], issues: [] }, ctx);
25804
+ if (r instanceof Promise) {
25805
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
25806
+ }
25807
+ else {
25808
+ handlePropertyResult(r, payload, key, input);
25809
+ }
25810
+ }
25811
+ if (unrecognized.length) {
25812
+ payload.issues.push({
25813
+ code: "unrecognized_keys",
25814
+ keys: unrecognized,
25815
+ input,
25816
+ inst,
25817
+ });
25818
+ }
25819
+ if (!proms.length)
25820
+ return payload;
25821
+ return Promise.all(proms).then(() => {
25822
+ return payload;
25823
+ });
25824
+ }
25378
25825
  const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
25379
25826
  // requires cast because technically $ZodObject doesn't extend
25380
25827
  $ZodType.init(inst, def);
25381
- const _normalized = cached(() => {
25382
- const keys = Object.keys(def.shape);
25383
- for (const k of keys) {
25384
- if (!def.shape[k]._zod.traits.has("$ZodType")) {
25385
- throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
25386
- }
25387
- }
25388
- const okeys = optionalKeys(def.shape);
25389
- return {
25390
- shape: def.shape,
25391
- keys,
25392
- keySet: new Set(keys),
25393
- numKeys: keys.length,
25394
- optionalKeys: new Set(okeys),
25395
- };
25396
- });
25828
+ // const sh = def.shape;
25829
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
25830
+ if (!desc?.get) {
25831
+ const sh = def.shape;
25832
+ Object.defineProperty(def, "shape", {
25833
+ get: () => {
25834
+ const newSh = { ...sh };
25835
+ Object.defineProperty(def, "shape", {
25836
+ value: newSh,
25837
+ });
25838
+ return newSh;
25839
+ },
25840
+ });
25841
+ }
25842
+ const _normalized = cached(() => normalizeDef(def));
25397
25843
  defineLazy(inst._zod, "propValues", () => {
25398
25844
  const shape = def.shape;
25399
25845
  const propValues = {};
@@ -25407,6 +25853,45 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
25407
25853
  }
25408
25854
  return propValues;
25409
25855
  });
25856
+ const isObject$1 = isObject;
25857
+ const catchall = def.catchall;
25858
+ let value;
25859
+ inst._zod.parse = (payload, ctx) => {
25860
+ value ?? (value = _normalized.value);
25861
+ const input = payload.value;
25862
+ if (!isObject$1(input)) {
25863
+ payload.issues.push({
25864
+ expected: "object",
25865
+ code: "invalid_type",
25866
+ input,
25867
+ inst,
25868
+ });
25869
+ return payload;
25870
+ }
25871
+ payload.value = {};
25872
+ const proms = [];
25873
+ const shape = value.shape;
25874
+ for (const key of value.keys) {
25875
+ const el = shape[key];
25876
+ const r = el._zod.run({ value: input[key], issues: [] }, ctx);
25877
+ if (r instanceof Promise) {
25878
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
25879
+ }
25880
+ else {
25881
+ handlePropertyResult(r, payload, key, input);
25882
+ }
25883
+ }
25884
+ if (!catchall) {
25885
+ return proms.length ? Promise.all(proms).then(() => payload) : payload;
25886
+ }
25887
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
25888
+ };
25889
+ });
25890
+ const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => {
25891
+ // requires cast because technically $ZodObject doesn't extend
25892
+ $ZodObject.init(inst, def);
25893
+ const superParse = inst._zod.parse;
25894
+ const _normalized = cached(() => normalizeDef(def));
25410
25895
  const generateFastpass = (shape) => {
25411
25896
  const doc = new Doc(["shape", "payload", "ctx"]);
25412
25897
  const normalized = _normalized.value;
@@ -25421,7 +25906,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
25421
25906
  ids[key] = `key_${counter++}`;
25422
25907
  }
25423
25908
  // A: preserve key order {
25424
- doc.write(`const newResult = {}`);
25909
+ doc.write(`const newResult = {};`);
25425
25910
  for (const key of normalized.keys) {
25426
25911
  const id = ids[key];
25427
25912
  const k = esc(key);
@@ -25434,6 +25919,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
25434
25919
  })));
25435
25920
  }
25436
25921
 
25922
+
25437
25923
  if (${id}.value === undefined) {
25438
25924
  if (${k} in input) {
25439
25925
  newResult[${k}] = undefined;
@@ -25441,6 +25927,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
25441
25927
  } else {
25442
25928
  newResult[${k}] = ${id}.value;
25443
25929
  }
25930
+
25444
25931
  `);
25445
25932
  }
25446
25933
  doc.write(`payload.value = newResult;`);
@@ -25467,63 +25954,16 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
25467
25954
  });
25468
25955
  return payload;
25469
25956
  }
25470
- const proms = [];
25471
25957
  if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
25472
25958
  // always synchronous
25473
25959
  if (!fastpass)
25474
25960
  fastpass = generateFastpass(def.shape);
25475
25961
  payload = fastpass(payload, ctx);
25962
+ if (!catchall)
25963
+ return payload;
25964
+ return handleCatchall([], input, payload, ctx, value, inst);
25476
25965
  }
25477
- else {
25478
- payload.value = {};
25479
- const shape = value.shape;
25480
- for (const key of value.keys) {
25481
- const el = shape[key];
25482
- const r = el._zod.run({ value: input[key], issues: [] }, ctx);
25483
- if (r instanceof Promise) {
25484
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
25485
- }
25486
- else {
25487
- handlePropertyResult(r, payload, key, input);
25488
- }
25489
- }
25490
- }
25491
- if (!catchall) {
25492
- return proms.length ? Promise.all(proms).then(() => payload) : payload;
25493
- }
25494
- const unrecognized = [];
25495
- // iterate over input keys
25496
- const keySet = value.keySet;
25497
- const _catchall = catchall._zod;
25498
- const t = _catchall.def.type;
25499
- for (const key of Object.keys(input)) {
25500
- if (keySet.has(key))
25501
- continue;
25502
- if (t === "never") {
25503
- unrecognized.push(key);
25504
- continue;
25505
- }
25506
- const r = _catchall.run({ value: input[key], issues: [] }, ctx);
25507
- if (r instanceof Promise) {
25508
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
25509
- }
25510
- else {
25511
- handlePropertyResult(r, payload, key, input);
25512
- }
25513
- }
25514
- if (unrecognized.length) {
25515
- payload.issues.push({
25516
- code: "unrecognized_keys",
25517
- keys: unrecognized,
25518
- input,
25519
- inst,
25520
- });
25521
- }
25522
- if (!proms.length)
25523
- return payload;
25524
- return Promise.all(proms).then(() => {
25525
- return payload;
25526
- });
25966
+ return superParse(payload, ctx);
25527
25967
  };
25528
25968
  });
25529
25969
  function handleUnionResults(results, final, inst, ctx) {
@@ -25695,9 +26135,12 @@ const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
25695
26135
  });
25696
26136
  const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
25697
26137
  $ZodType.init(inst, def);
25698
- inst._zod.parse = (payload, _ctx) => {
26138
+ inst._zod.parse = (payload, ctx) => {
26139
+ if (ctx.direction === "backward") {
26140
+ throw new $ZodEncodeError(inst.constructor.name);
26141
+ }
25699
26142
  const _out = def.transform(payload.value, payload);
25700
- if (_ctx.async) {
26143
+ if (ctx.async) {
25701
26144
  const output = _out instanceof Promise ? _out : Promise.resolve(_out);
25702
26145
  return output.then((output) => {
25703
26146
  payload.value = output;
@@ -25753,6 +26196,7 @@ const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
25753
26196
  return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
25754
26197
  });
25755
26198
  inst._zod.parse = (payload, ctx) => {
26199
+ // Forward direction (decode): allow null to pass through
25756
26200
  if (payload.value === null)
25757
26201
  return payload;
25758
26202
  return def.innerType._zod.run(payload, ctx);
@@ -25764,13 +26208,18 @@ const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
25764
26208
  inst._zod.optin = "optional";
25765
26209
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
25766
26210
  inst._zod.parse = (payload, ctx) => {
26211
+ if (ctx.direction === "backward") {
26212
+ return def.innerType._zod.run(payload, ctx);
26213
+ }
26214
+ // Forward direction (decode): apply defaults for undefined input
25767
26215
  if (payload.value === undefined) {
25768
26216
  payload.value = def.defaultValue;
25769
26217
  /**
25770
- * $ZodDefault always returns the default value immediately.
26218
+ * $ZodDefault returns the default value immediately in forward direction.
25771
26219
  * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
25772
26220
  return payload;
25773
26221
  }
26222
+ // Forward direction: continue with default handling
25774
26223
  const result = def.innerType._zod.run(payload, ctx);
25775
26224
  if (result instanceof Promise) {
25776
26225
  return result.then((result) => handleDefaultResult(result, def));
@@ -25789,6 +26238,10 @@ const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
25789
26238
  inst._zod.optin = "optional";
25790
26239
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
25791
26240
  inst._zod.parse = (payload, ctx) => {
26241
+ if (ctx.direction === "backward") {
26242
+ return def.innerType._zod.run(payload, ctx);
26243
+ }
26244
+ // Forward direction (decode): apply prefault for undefined input
25792
26245
  if (payload.value === undefined) {
25793
26246
  payload.value = def.defaultValue;
25794
26247
  }
@@ -25826,6 +26279,10 @@ const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
25826
26279
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
25827
26280
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
25828
26281
  inst._zod.parse = (payload, ctx) => {
26282
+ if (ctx.direction === "backward") {
26283
+ return def.innerType._zod.run(payload, ctx);
26284
+ }
26285
+ // Forward direction (decode): apply catch logic
25829
26286
  const result = def.innerType._zod.run(payload, ctx);
25830
26287
  if (result instanceof Promise) {
25831
26288
  return result.then((result) => {
@@ -25864,26 +26321,38 @@ const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
25864
26321
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
25865
26322
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
25866
26323
  inst._zod.parse = (payload, ctx) => {
26324
+ if (ctx.direction === "backward") {
26325
+ const right = def.out._zod.run(payload, ctx);
26326
+ if (right instanceof Promise) {
26327
+ return right.then((right) => handlePipeResult(right, def.in, ctx));
26328
+ }
26329
+ return handlePipeResult(right, def.in, ctx);
26330
+ }
25867
26331
  const left = def.in._zod.run(payload, ctx);
25868
26332
  if (left instanceof Promise) {
25869
- return left.then((left) => handlePipeResult(left, def, ctx));
26333
+ return left.then((left) => handlePipeResult(left, def.out, ctx));
25870
26334
  }
25871
- return handlePipeResult(left, def, ctx);
26335
+ return handlePipeResult(left, def.out, ctx);
25872
26336
  };
25873
26337
  });
25874
- function handlePipeResult(left, def, ctx) {
26338
+ function handlePipeResult(left, next, ctx) {
25875
26339
  if (left.issues.length) {
26340
+ // prevent further checks
26341
+ left.aborted = true;
25876
26342
  return left;
25877
26343
  }
25878
- return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);
26344
+ return next._zod.run({ value: left.value, issues: left.issues }, ctx);
25879
26345
  }
25880
26346
  const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
25881
26347
  $ZodType.init(inst, def);
25882
26348
  defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
25883
26349
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
25884
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
25885
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
26350
+ defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
26351
+ defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
25886
26352
  inst._zod.parse = (payload, ctx) => {
26353
+ if (ctx.direction === "backward") {
26354
+ return def.innerType._zod.run(payload, ctx);
26355
+ }
25887
26356
  const result = def.innerType._zod.run(payload, ctx);
25888
26357
  if (result instanceof Promise) {
25889
26358
  return result.then(handleReadonlyResult);
@@ -25927,9 +26396,10 @@ function handleRefineResult(result, payload, input, inst) {
25927
26396
  }
25928
26397
  }
25929
26398
 
26399
+ var _a;
25930
26400
  class $ZodRegistry {
25931
26401
  constructor() {
25932
- this._map = new Map();
26402
+ this._map = new WeakMap();
25933
26403
  this._idmap = new Map();
25934
26404
  }
25935
26405
  add(schema, ..._meta) {
@@ -25944,7 +26414,7 @@ class $ZodRegistry {
25944
26414
  return this;
25945
26415
  }
25946
26416
  clear() {
25947
- this._map = new Map();
26417
+ this._map = new WeakMap();
25948
26418
  this._idmap = new Map();
25949
26419
  return this;
25950
26420
  }
@@ -25976,7 +26446,8 @@ class $ZodRegistry {
25976
26446
  function registry() {
25977
26447
  return new $ZodRegistry();
25978
26448
  }
25979
- const globalRegistry = /*@__PURE__*/ registry();
26449
+ (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
26450
+ const globalRegistry = globalThis.__zod_globalRegistry;
25980
26451
 
25981
26452
  function _string(Class, params) {
25982
26453
  return new Class({
@@ -26382,6 +26853,10 @@ function _toLowerCase() {
26382
26853
  function _toUpperCase() {
26383
26854
  return _overwrite((input) => input.toUpperCase());
26384
26855
  }
26856
+ // slugify
26857
+ function _slugify() {
26858
+ return _overwrite((input) => slugify(input));
26859
+ }
26385
26860
  function _array(Class, element, params) {
26386
26861
  return new Class({
26387
26862
  type: "array",
@@ -26416,7 +26891,7 @@ function _superRefine(fn) {
26416
26891
  _issue.code ?? (_issue.code = "custom");
26417
26892
  _issue.input ?? (_issue.input = payload.value);
26418
26893
  _issue.inst ?? (_issue.inst = ch);
26419
- _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
26894
+ _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...
26420
26895
  payload.issues.push(issue(_issue));
26421
26896
  }
26422
26897
  };
@@ -26511,22 +26986,29 @@ const parse = /* @__PURE__ */ _parse(ZodRealError);
26511
26986
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
26512
26987
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
26513
26988
  const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
26989
+ // Codec functions
26990
+ const encode = /* @__PURE__ */ _encode(ZodRealError);
26991
+ const decode = /* @__PURE__ */ _decode(ZodRealError);
26992
+ const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
26993
+ const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
26994
+ const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
26995
+ const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
26996
+ const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
26997
+ const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
26514
26998
 
26515
26999
  const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
26516
27000
  $ZodType.init(inst, def);
26517
27001
  inst.def = def;
27002
+ inst.type = def.type;
26518
27003
  Object.defineProperty(inst, "_def", { value: def });
26519
27004
  // base methods
26520
27005
  inst.check = (...checks) => {
26521
- return inst.clone({
26522
- ...def,
27006
+ return inst.clone(mergeDefs(def, {
26523
27007
  checks: [
26524
27008
  ...(def.checks ?? []),
26525
27009
  ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
26526
27010
  ],
26527
- }
26528
- // { parent: true }
26529
- );
27011
+ }));
26530
27012
  };
26531
27013
  inst.clone = (def, params) => clone(inst, def, params);
26532
27014
  inst.brand = () => inst;
@@ -26540,6 +27022,15 @@ const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
26540
27022
  inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
26541
27023
  inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
26542
27024
  inst.spa = inst.safeParseAsync;
27025
+ // encoding/decoding
27026
+ inst.encode = (data, params) => encode(inst, data, params);
27027
+ inst.decode = (data, params) => decode(inst, data, params);
27028
+ inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
27029
+ inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
27030
+ inst.safeEncode = (data, params) => safeEncode(inst, data, params);
27031
+ inst.safeDecode = (data, params) => safeDecode(inst, data, params);
27032
+ inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
27033
+ inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
26543
27034
  // refinements
26544
27035
  inst.refine = (check, params) => inst.check(refine(check, params));
26545
27036
  inst.superRefine = (refinement) => inst.check(superRefine(refinement));
@@ -26608,6 +27099,7 @@ const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
26608
27099
  inst.normalize = (...args) => inst.check(_normalize(...args));
26609
27100
  inst.toLowerCase = () => inst.check(_toLowerCase());
26610
27101
  inst.toUpperCase = () => inst.check(_toUpperCase());
27102
+ inst.slugify = () => inst.check(_slugify());
26611
27103
  });
26612
27104
  const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
26613
27105
  $ZodString.init(inst, def);
@@ -26814,9 +27306,11 @@ function array(element, params) {
26814
27306
  return _array(ZodArray, element, params);
26815
27307
  }
26816
27308
  const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
26817
- $ZodObject.init(inst, def);
27309
+ $ZodObjectJIT.init(inst, def);
26818
27310
  ZodType.init(inst, def);
26819
- defineLazy(inst, "shape", () => def.shape);
27311
+ defineLazy(inst, "shape", () => {
27312
+ return def.shape;
27313
+ });
26820
27314
  inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
26821
27315
  inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });
26822
27316
  inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
@@ -26826,6 +27320,9 @@ const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
26826
27320
  inst.extend = (incoming) => {
26827
27321
  return extend(inst, incoming);
26828
27322
  };
27323
+ inst.safeExtend = (incoming) => {
27324
+ return safeExtend(inst, incoming);
27325
+ };
26829
27326
  inst.merge = (other) => merge(inst, other);
26830
27327
  inst.pick = (mask) => pick(inst, mask);
26831
27328
  inst.omit = (mask) => omit(inst, mask);
@@ -26835,10 +27332,7 @@ const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
26835
27332
  function object(shape, params) {
26836
27333
  const def = {
26837
27334
  type: "object",
26838
- get shape() {
26839
- assignProp(this, "shape", shape ? objectClone(shape) : {});
26840
- return this.shape;
26841
- },
27335
+ shape: shape ?? {},
26842
27336
  ...normalizeParams(params),
26843
27337
  };
26844
27338
  return new ZodObject(def);
@@ -26917,6 +27411,9 @@ const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
26917
27411
  $ZodTransform.init(inst, def);
26918
27412
  ZodType.init(inst, def);
26919
27413
  inst._zod.parse = (payload, _ctx) => {
27414
+ if (_ctx.direction === "backward") {
27415
+ throw new $ZodEncodeError(inst.constructor.name);
27416
+ }
26920
27417
  payload.addIssue = (issue$1) => {
26921
27418
  if (typeof issue$1 === "string") {
26922
27419
  payload.issues.push(issue(issue$1, payload.value, def));
@@ -27525,8 +28022,68 @@ let RpgMap = class extends RpgCommonMap {
27525
28022
  world.configure(maps);
27526
28023
  }
27527
28024
  }
27528
- addInDatabase(id, data) {
27529
- this.database()[id] = data;
28025
+ /**
28026
+ * Add data to the map's database
28027
+ *
28028
+ * This method allows you to dynamically add items, classes, or any data to the map's database.
28029
+ * By default, if an ID already exists, the operation is ignored to prevent overwriting existing data.
28030
+ *
28031
+ * @param id - Unique identifier for the data
28032
+ * @param data - The data to store (can be a class, object, or any value)
28033
+ * @param options - Optional configuration
28034
+ * @param options.force - If true, overwrites existing data even if ID already exists (default: false)
28035
+ * @returns true if data was added, false if ignored (ID already exists)
28036
+ *
28037
+ * @example
28038
+ * ```ts
28039
+ * // Add an item class to the database
28040
+ * map.addInDatabase('Potion', PotionClass);
28041
+ *
28042
+ * // Add an item object to the database
28043
+ * map.addInDatabase('custom-item', {
28044
+ * name: 'Custom Item',
28045
+ * price: 100
28046
+ * });
28047
+ *
28048
+ * // Force overwrite existing data
28049
+ * map.addInDatabase('Potion', UpdatedPotionClass, { force: true });
28050
+ * ```
28051
+ */
28052
+ addInDatabase(id, data, options) {
28053
+ const database = this.database();
28054
+ if (database[id] !== void 0 && !options?.force) {
28055
+ return false;
28056
+ }
28057
+ database[id] = data;
28058
+ return true;
28059
+ }
28060
+ /**
28061
+ * Remove data from the map's database
28062
+ *
28063
+ * This method allows you to remove items or data from the map's database.
28064
+ *
28065
+ * @param id - Unique identifier of the data to remove
28066
+ * @returns true if data was removed, false if ID didn't exist
28067
+ *
28068
+ * @example
28069
+ * ```ts
28070
+ * // Remove an item from the database
28071
+ * map.removeInDatabase('Potion');
28072
+ *
28073
+ * // Check if removal was successful
28074
+ * const removed = map.removeInDatabase('custom-item');
28075
+ * if (removed) {
28076
+ * console.log('Item removed successfully');
28077
+ * }
28078
+ * ```
28079
+ */
28080
+ removeInDatabase(id) {
28081
+ const database = this.database();
28082
+ if (database[id] === void 0) {
28083
+ return false;
28084
+ }
28085
+ delete database[id];
28086
+ return true;
27530
28087
  }
27531
28088
  /**
27532
28089
  * Creates a dynamic event on the map
@@ -28381,5 +28938,5 @@ function provideServerModules(modules) {
28381
28938
  });
28382
28939
  }
28383
28940
 
28384
- export { AGI, AGI_CURVE, ATK, ArraySubject$1 as ArraySubject, COEFFICIENT_ELEMENTS, Components, DAMAGE_CRITICAL, DAMAGE_GUARD, DAMAGE_PHYSIC, DAMAGE_SKILL, DEX, DEX_CURVE, DialogGui, DialogPosition, Frequency, Gui, INT, INT_CURVE, MAXHP, MAXHP_CURVE, MAXSP, MAXSP_CURVE, MenuGui, Move, NotificationGui, ObjectSubject$1 as ObjectSubject, PDEF, RpgEvent, RpgMap, RpgPlayer, RpgServerEngine, RpgShape, SDEF, STR, STR_CURVE, ShopGui, Speed, WithMoveManager, clearInject, computed$1 as computed, context, createServer, effect$1 as effect, inject, isArraySubject$1 as isArraySubject, isComputed$1 as isComputed, isObjectSubject$1 as isObjectSubject, isSignal$1 as isSignal, provideServerModules, setInject, signal$1 as signal, untracked$1 as untracked };
28941
+ export { AGI, AGI_CURVE, ATK, ArraySubject$1 as ArraySubject, COEFFICIENT_ELEMENTS, Components, DAMAGE_CRITICAL, DAMAGE_GUARD, DAMAGE_PHYSIC, DAMAGE_SKILL, DEX, DEX_CURVE, DialogGui, DialogPosition, Frequency, Gui, INT, INT_CURVE, MAXHP, MAXHP_CURVE, MAXSP, MAXSP_CURVE, MenuGui, Move, NotificationGui, ObjectSubject$1 as ObjectSubject, PDEF, RpgEvent, RpgMap, RpgModule, RpgPlayer, RpgServerEngine, RpgShape, SDEF, STR, STR_CURVE, ShopGui, Speed, WithMoveManager, clearInject, computed$1 as computed, context, createServer, effect$1 as effect, inject, isArraySubject$1 as isArraySubject, isComputed$1 as isComputed, isObjectSubject$1 as isObjectSubject, isSignal$1 as isSignal, provideServerModules, setInject, signal$1 as signal, untracked$1 as untracked };
28385
28942
  //# sourceMappingURL=index.js.map