@g33ks/foundryvtt-mcp 2.1.0 → 2.2.1

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.
@@ -21,7 +21,7 @@ import { JournalConflictFile } from './journal-conflicts.js';
21
21
  import { JournalHistory } from './journal-history.js';
22
22
  import { conflictAuthor, JOURNAL_CONFLICT_SPEAKER, JournalWatch, journalConflictMessage, journalContribution, journalVersion, OVERWRITTEN_BY_CONNECTOR, RECENT_AUTOSAVE_MS, } from './journal-integrity.js';
23
23
  import { ACTIVE_EFFECT_MODES, OWNERSHIP_LEVELS, USER_ROLES, VISIBILITY_LEVELS } from './types.js';
24
- import { applyDocumentBroadcast, applyUserActivity, parseDocumentBatch, parseDocumentBroadcast, parseUserActivity, } from './world-cache.js';
24
+ import { applyDocumentBroadcast, applyUserActivity, mergePatch, parseDocumentBatch, parseDocumentBroadcast, parseUserActivity, } from './world-cache.js';
25
25
  /** Who overwrote a page when an editor autosave did: FoundryVTT does not say. */
26
26
  const EDITOR_AUTOSAVE_USER = 'editor-autosave (unknown user)';
27
27
  /** FoundryVTT document IDs are 16-character alphanumeric strings. */
@@ -81,6 +81,11 @@ const FOLDER_DOCUMENT_TYPES = [
81
81
  * preset touches the exact "blocking" (NORMAL) value, which is left to the
82
82
  * server's own schema default rather than guessed.
83
83
  */
84
+ /**
85
+ * The id FoundryVTT v14 gives the Level it creates with a new scene
86
+ * (`BaseScene.metadata.defaultLevelId`).
87
+ */
88
+ const DEFAULT_LEVEL_ID = 'defaultLevel0000';
84
89
  const WALL_TYPE_PRESETS = {
85
90
  wall: {},
86
91
  door: { door: 1, ds: 0 },
@@ -1334,6 +1339,10 @@ export class FoundryClient {
1334
1339
  isWriteEnabled() {
1335
1340
  return this.config.writeEnabled === true;
1336
1341
  }
1342
+ /** The folder `upload_asset` may read a `sourcePath` from; `undefined` when none is set. */
1343
+ uploadSourceDir() {
1344
+ return this.config.uploadSourceDir;
1345
+ }
1337
1346
  /**
1338
1347
  * Returns true if worldData is available (Socket.IO mode connected).
1339
1348
  */
@@ -1565,6 +1574,15 @@ export class FoundryClient {
1565
1574
  getWorldData() {
1566
1575
  return this.worldData;
1567
1576
  }
1577
+ /**
1578
+ * The version of a module installed in the world, from the cached world's
1579
+ * module list; `null` when the module or its version is not there.
1580
+ */
1581
+ installedModuleVersion(moduleId) {
1582
+ const modules = this.worldData?.modules;
1583
+ const entry = Array.isArray(modules) ? modules.find((m) => m.id === moduleId) : undefined;
1584
+ return typeof entry?.version === 'string' ? entry.version : null;
1585
+ }
1568
1586
  // ==========================================================================
1569
1587
  // Actor methods
1570
1588
  // ==========================================================================
@@ -1692,6 +1710,169 @@ export class FoundryClient {
1692
1710
  }
1693
1711
  return { success: true, updatedAttributes };
1694
1712
  }
1713
+ /**
1714
+ * The `system` data a token's actor actually has: the world actor's for a
1715
+ * linked token, or the base actor's merged with the token's own delta for an
1716
+ * unlinked one (each unlinked copy of a monster has its own HP).
1717
+ *
1718
+ * @returns undefined when the token or its actor isn't in the cache
1719
+ */
1720
+ getTokenActorSystem(tokenId, sceneId) {
1721
+ const found = this.findToken(tokenId, sceneId);
1722
+ if (!found) {
1723
+ return undefined;
1724
+ }
1725
+ const { token } = found;
1726
+ const actorId = typeof token.actorId === 'string' ? token.actorId : undefined;
1727
+ const base = actorId ? systemOf(this.getRawActor(actorId)) : undefined;
1728
+ if (token.actorLink === true) {
1729
+ return base;
1730
+ }
1731
+ const merged = base ? structuredClone(base) : {};
1732
+ const deltaSystem = isRecord(token.delta) ? token.delta.system : undefined;
1733
+ if (isRecord(deltaSystem)) {
1734
+ mergePatch(merged, structuredClone(deltaSystem));
1735
+ }
1736
+ return merged;
1737
+ }
1738
+ /**
1739
+ * A token and the actor it carries, checked.
1740
+ *
1741
+ * @param actorId - when given, must be the token's actor
1742
+ * @throws when the scene or the token isn't in the cache, the token has no
1743
+ * actor, or carries another actor
1744
+ */
1745
+ resolveTokenActor(tokenId, sceneId, actorId) {
1746
+ const found = this.findToken(tokenId, sceneId);
1747
+ if (!found) {
1748
+ if (sceneId && this.worldData && !this.worldData.scenes.some((s) => s._id === sceneId)) {
1749
+ throw new Error(`Scene not found: ${sceneId}`);
1750
+ }
1751
+ throw new Error(`Token not found: ${tokenId}${sceneId ? ` in scene ${sceneId}` : ''}`);
1752
+ }
1753
+ const tokenActorId = typeof found.token.actorId === 'string' && found.token.actorId
1754
+ ? found.token.actorId
1755
+ : undefined;
1756
+ if (!tokenActorId) {
1757
+ throw new Error(`Token ${tokenId} has no actor`);
1758
+ }
1759
+ if (actorId !== undefined && actorId !== tokenActorId) {
1760
+ throw new Error(`Token ${tokenId} carries actor ${tokenActorId}, not ${actorId}`);
1761
+ }
1762
+ return { ...found, actorId: tokenActorId, linked: found.token.actorLink === true };
1763
+ }
1764
+ /**
1765
+ * A token's actor's effects, as FoundryVTT shows them (see {@link mergeDeltaEntries}).
1766
+ *
1767
+ * @returns undefined when the token isn't in the cache
1768
+ */
1769
+ getTokenActorEffects(tokenId, sceneId) {
1770
+ const found = this.findToken(tokenId, sceneId);
1771
+ if (!found) {
1772
+ return undefined;
1773
+ }
1774
+ const base = this.tokenBaseActor(found.token)?.effects ?? [];
1775
+ return found.token.actorLink === true
1776
+ ? [...base]
1777
+ : mergeDeltaEntries(base, isRecord(found.token.delta) ? found.token.delta.effects : undefined);
1778
+ }
1779
+ /**
1780
+ * A token's actor's items, as FoundryVTT shows them (see {@link mergeDeltaEntries}).
1781
+ *
1782
+ * @returns undefined when the token isn't in the cache
1783
+ */
1784
+ getTokenActorItems(tokenId, sceneId) {
1785
+ const found = this.findToken(tokenId, sceneId);
1786
+ if (!found) {
1787
+ return undefined;
1788
+ }
1789
+ const base = this.tokenBaseActor(found.token)?.items ?? [];
1790
+ return found.token.actorLink === true
1791
+ ? [...base]
1792
+ : mergeDeltaEntries(base, isRecord(found.token.delta) ? found.token.delta.items : undefined);
1793
+ }
1794
+ /**
1795
+ * A token's actor, mapped like {@link getActor}: for an unlinked token, its
1796
+ * base actor with the system data of {@link getTokenActorSystem} (and the
1797
+ * delta's name, when it has one). Read from the cache.
1798
+ *
1799
+ * @throws when the token or its base actor isn't in the cache
1800
+ */
1801
+ getTokenActor(tokenId, sceneId) {
1802
+ const { token, actorId, linked } = this.resolveTokenActor(tokenId, sceneId);
1803
+ const base = this.getRawActor(actorId);
1804
+ if (!base) {
1805
+ throw new Error(`Actor not found: ${actorId}`);
1806
+ }
1807
+ if (linked) {
1808
+ return worldActorToFoundry(base);
1809
+ }
1810
+ const deltaName = isRecord(token.delta) ? token.delta.name : undefined;
1811
+ return worldActorToFoundry({
1812
+ ...base,
1813
+ ...(typeof deltaName === 'string' && deltaName ? { name: deltaName } : {}),
1814
+ system: this.getTokenActorSystem(tokenId, sceneId) ?? {},
1815
+ });
1816
+ }
1817
+ /** The world actor a token was made from, when it is cached. */
1818
+ tokenBaseActor(token) {
1819
+ return typeof token.actorId === 'string' ? this.getRawActor(token.actorId) : undefined;
1820
+ }
1821
+ /**
1822
+ * Patches attributes on one token's actor. WRITE — Socket.IO.
1823
+ *
1824
+ * A linked token shares its world actor, so this is {@link updateActorAttribute}.
1825
+ * An unlinked token's changes go to its ActorDelta, the way FoundryVTT's own
1826
+ * client sends them: an `ActorDelta` update parented to the token, with the
1827
+ * delta's id and `syntheticActorUpdate: true`. The base actor, and every other
1828
+ * token made from it, is untouched.
1829
+ */
1830
+ async updateTokenActorAttribute(sceneId, tokenId, patch) {
1831
+ this.assertWriteable();
1832
+ if (!FOUNDRY_ID_PATTERN.test(sceneId)) {
1833
+ throw new Error(`Invalid sceneId format: ${sceneId}`);
1834
+ }
1835
+ if (!FOUNDRY_ID_PATTERN.test(tokenId)) {
1836
+ throw new Error(`Invalid tokenId format: ${tokenId}`);
1837
+ }
1838
+ if (!isRecord(patch) || Object.keys(patch).length === 0) {
1839
+ throw new Error('patch is required and must contain at least one attribute path');
1840
+ }
1841
+ const found = this.findToken(tokenId, sceneId);
1842
+ if (!found) {
1843
+ throw new Error(`Token not found: ${tokenId} in scene ${sceneId}`);
1844
+ }
1845
+ const { token } = found;
1846
+ const actorId = typeof token.actorId === 'string' ? token.actorId : undefined;
1847
+ if (!actorId) {
1848
+ throw new Error(`Token ${tokenId} has no actor`);
1849
+ }
1850
+ if (token.actorLink === true) {
1851
+ return this.updateActorAttribute(actorId, patch);
1852
+ }
1853
+ const actor = await this.getActor(actorId);
1854
+ validateAttributePatch(patch, actor, this.getTokenActorSystem(tokenId, sceneId));
1855
+ const delta = token.delta;
1856
+ const deltaId = isRecord(delta) && typeof delta._id === 'string' ? delta._id : tokenId;
1857
+ const update = { _id: deltaId };
1858
+ for (const [path, value] of Object.entries(patch)) {
1859
+ update[`system.${path}`] = value;
1860
+ }
1861
+ await this.modifyDocument('ActorDelta', 'update', {
1862
+ updates: [update],
1863
+ parentUuid: `Scene.${sceneId}.Token.${tokenId}`,
1864
+ syntheticActorUpdate: true,
1865
+ diff: true,
1866
+ recursive: true,
1867
+ });
1868
+ const after = this.getTokenActorSystem(tokenId, sceneId);
1869
+ const updatedAttributes = {};
1870
+ for (const [path, value] of Object.entries(patch)) {
1871
+ const cached = after ? getDotPath(after, path) : undefined;
1872
+ updatedAttributes[path] = cached !== undefined ? cached : value;
1873
+ }
1874
+ return { success: true, updatedAttributes };
1875
+ }
1695
1876
  /**
1696
1877
  * Creates a new top-level Actor document in the world.
1697
1878
  *
@@ -1704,9 +1885,10 @@ export class FoundryClient {
1704
1885
  * @param type - game-system actor type (e.g. "character", "npc")
1705
1886
  * @param system - optional system-specific data merged into `actor.system`
1706
1887
  * @param folder - optional 16-char Folder document id to file the actor under
1888
+ * @param flags - optional module flags (`actor.flags`), keyed by module id
1707
1889
  * @returns the newly created actor document
1708
1890
  */
1709
- async createWorldActor(name, type, system, folder) {
1891
+ async createWorldActor(name, type, system, folder, flags) {
1710
1892
  this.assertWriteable();
1711
1893
  if (!name || typeof name !== 'string') {
1712
1894
  throw new Error('name is required and must be a string');
@@ -1717,6 +1899,9 @@ export class FoundryClient {
1717
1899
  if (folder !== undefined && !FOUNDRY_ID_PATTERN.test(folder)) {
1718
1900
  throw new Error(`Invalid folder format: ${folder}`);
1719
1901
  }
1902
+ if (flags !== undefined && (!isRecord(flags) || !Object.values(flags).every(isRecord))) {
1903
+ throw new Error('flags must be an object of per-module objects, e.g. {"my-module": {...}}');
1904
+ }
1720
1905
  const data = { name, type };
1721
1906
  if (system) {
1722
1907
  data.system = system;
@@ -1724,6 +1909,9 @@ export class FoundryClient {
1724
1909
  if (folder) {
1725
1910
  data.folder = folder;
1726
1911
  }
1912
+ if (flags) {
1913
+ data.flags = flags;
1914
+ }
1727
1915
  const result = await this.modifyDocument('Actor', 'create', { data: [data] });
1728
1916
  return result[0];
1729
1917
  }
@@ -2027,14 +2215,34 @@ export class FoundryClient {
2027
2215
  // ==========================================================================
2028
2216
  // Item mutation methods (WRITE — Socket.IO modifyDocument)
2029
2217
  // ==========================================================================
2218
+ /**
2219
+ * The parent of an item write: `Actor.<actorId>`, or, for one token, that
2220
+ * token's actor - its ActorDelta when unlinked (see {@link toDeltaParentUuid}).
2221
+ *
2222
+ * @throws when the token isn't in the cache or carries another actor
2223
+ */
2224
+ itemParentUuid(actorId, token) {
2225
+ if (!token) {
2226
+ return `Actor.${actorId}`;
2227
+ }
2228
+ if (!FOUNDRY_ID_PATTERN.test(token.sceneId)) {
2229
+ throw new Error(`Invalid sceneId format: ${token.sceneId}`);
2230
+ }
2231
+ if (!FOUNDRY_ID_PATTERN.test(token.tokenId)) {
2232
+ throw new Error(`Invalid tokenId format: ${token.tokenId}`);
2233
+ }
2234
+ return this.toDeltaParentUuid(`Scene.${token.sceneId}.Token.${token.tokenId}.Actor.${actorId}`);
2235
+ }
2030
2236
  /**
2031
2237
  * Creates a new item on an actor via the `modifyDocument` socket protocol.
2032
2238
  *
2033
2239
  * @param actorId - 16-char alphanumeric actor document id
2034
2240
  * @param source - inline item document or compendium source
2241
+ * @param token - one token whose actor gets the item instead (only that
2242
+ * token, for an unlinked one)
2035
2243
  * @returns the newly created item document
2036
2244
  */
2037
- async createActorItem(actorId, source) {
2245
+ async createActorItem(actorId, source, token) {
2038
2246
  this.assertWriteable();
2039
2247
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
2040
2248
  throw new Error(`Invalid actorId format: ${actorId}`);
@@ -2042,7 +2250,7 @@ export class FoundryClient {
2042
2250
  const itemData = source.type === 'inline' ? source.item : {};
2043
2251
  const result = await this.modifyDocument('Item', 'create', {
2044
2252
  data: [itemData],
2045
- parentUuid: `Actor.${actorId}`,
2253
+ parentUuid: this.itemParentUuid(actorId, token),
2046
2254
  });
2047
2255
  return result[0];
2048
2256
  }
@@ -2056,9 +2264,14 @@ export class FoundryClient {
2056
2264
  * @param actorId - 16-char alphanumeric actor document id
2057
2265
  * @param itemId - 16-char alphanumeric item document id
2058
2266
  * @param patch - shallow/nested JSON merge patch applied to `item.system`
2059
- * @returns the updated item document
2267
+ * @param token - one token whose actor's item to change instead; for an
2268
+ * unlinked token, an item it inherits is copied into its delta by the
2269
+ * server, so the base actor and its other tokens keep theirs
2270
+ * @returns the server's answer (only the changed fields) with the item's
2271
+ * `name` and `type` read back from the cache, which the answer has already
2272
+ * updated
2060
2273
  */
2061
- async updateActorItem(actorId, itemId, patch) {
2274
+ async updateActorItem(actorId, itemId, patch, token) {
2062
2275
  this.assertWriteable();
2063
2276
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
2064
2277
  throw new Error(`Invalid actorId format: ${actorId}`);
@@ -2068,19 +2281,27 @@ export class FoundryClient {
2068
2281
  }
2069
2282
  const result = await this.modifyDocument('Item', 'update', {
2070
2283
  updates: [{ _id: itemId, system: patch }],
2071
- parentUuid: `Actor.${actorId}`,
2284
+ parentUuid: this.itemParentUuid(actorId, token),
2072
2285
  diff: true,
2073
2286
  recursive: true,
2074
2287
  });
2075
- return result[0];
2288
+ const cached = (token
2289
+ ? this.getTokenActorItems(token.tokenId, token.sceneId)
2290
+ : this.getRawActor(actorId)?.items)?.find((item) => item._id === itemId);
2291
+ return {
2292
+ ...result[0],
2293
+ ...(cached ? { name: cached.name, type: cached.type } : {}),
2294
+ };
2076
2295
  }
2077
2296
  /**
2078
2297
  * Deletes an item owned by an actor via the `modifyDocument` socket protocol.
2079
2298
  *
2080
2299
  * @param actorId - 16-char alphanumeric actor document id
2081
2300
  * @param itemId - 16-char alphanumeric item document id
2301
+ * @param token - one token whose actor loses the item instead; for an
2302
+ * unlinked token, the server tombstones an inherited item in its delta
2082
2303
  */
2083
- async deleteActorItem(actorId, itemId) {
2304
+ async deleteActorItem(actorId, itemId, token) {
2084
2305
  this.assertWriteable();
2085
2306
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
2086
2307
  throw new Error(`Invalid actorId format: ${actorId}`);
@@ -2090,7 +2311,7 @@ export class FoundryClient {
2090
2311
  }
2091
2312
  await this.modifyDocument('Item', 'delete', {
2092
2313
  ids: [itemId],
2093
- parentUuid: `Actor.${actorId}`,
2314
+ parentUuid: this.itemParentUuid(actorId, token),
2094
2315
  });
2095
2316
  }
2096
2317
  // ==========================================================================
@@ -2202,6 +2423,11 @@ export class FoundryClient {
2202
2423
  parentUuid: `Combat.${combatId}`,
2203
2424
  });
2204
2425
  }
2426
+ // Begin the encounter as Foundry's own "Begin Combat" does (Combat#startCombat);
2427
+ // a combat left at round 0 hasn't started, and turn advances are meaningless.
2428
+ await this.modifyDocument('Combat', 'update', {
2429
+ updates: [{ _id: combatId, round: 1, turn: 0 }],
2430
+ });
2205
2431
  return { combatId, combatantCount: combatants.length };
2206
2432
  }
2207
2433
  // ==========================================================================
@@ -2335,14 +2561,45 @@ export class FoundryClient {
2335
2561
  });
2336
2562
  return result[0];
2337
2563
  }
2564
+ /**
2565
+ * Rewrites an unlinked token's synthetic-actor UUID to its ActorDelta UUID.
2566
+ *
2567
+ * FoundryVTT keeps an unlinked token's own items and effects on the token's
2568
+ * ActorDelta, and its client sends embedded writes for a token actor with
2569
+ * `parentUuid: "Scene.<sid>.Token.<tid>.ActorDelta.<did>"`
2570
+ * (ClientDatabaseBackend#adjustActorDeltaRequest). v14 rejects the
2571
+ * `...Token.<tid>.Actor.<aid>` form outright. The delta's id defaults to the
2572
+ * token's id. A linked token shares its world actor, so it gets
2573
+ * `Actor.<aid>`. Any other UUID is returned unchanged.
2574
+ *
2575
+ * @throws when the token isn't in the cache or carries another actor
2576
+ */
2577
+ toDeltaParentUuid(parentActorUuid) {
2578
+ const match = /^Scene\.([a-zA-Z0-9]{16})\.Token\.([a-zA-Z0-9]{16})\.Actor\.([a-zA-Z0-9]{16})$/.exec(parentActorUuid);
2579
+ if (!match) {
2580
+ return parentActorUuid;
2581
+ }
2582
+ const [, sceneId = '', tokenId = '', actorId = ''] = match;
2583
+ const { token, linked } = this.resolveTokenActor(tokenId, sceneId, actorId);
2584
+ if (linked) {
2585
+ return `Actor.${actorId}`;
2586
+ }
2587
+ const delta = token.delta;
2588
+ const deltaId = isRecord(delta) && typeof delta._id === 'string' ? delta._id : tokenId;
2589
+ return `Scene.${sceneId}.Token.${tokenId}.ActorDelta.${deltaId}`;
2590
+ }
2338
2591
  /**
2339
2592
  * Creates a status-effect `ActiveEffect` on a token's actor (FR-019).
2340
2593
  *
2341
- * `ActiveEffect` is an embedded document of `Actor`, so the create is sent with
2342
- * the actor's parent UUID:
2343
- * - `Actor.<id>` for a world-linked actor (`actorLink: true`)
2344
- * - `Scene.<sid>.Token.<tid>.Actor.<aid>` for an unlinked token's synthetic
2345
- * actor (the per-token delta).
2594
+ * `parentActorUuid` takes one of two forms:
2595
+ * - `Actor.<id>` for a world actor
2596
+ * - `Scene.<sid>.Token.<tid>.Actor.<aid>` for a token's actor.
2597
+ *
2598
+ * The create is sent with the parent {@link toDeltaParentUuid} makes of it:
2599
+ * `Actor.<aid>` for a world actor or a linked token, and
2600
+ * `Scene.<sid>.Token.<tid>.ActorDelta.<did>` for an unlinked token (its
2601
+ * per-token delta). A token that isn't cached or carries another actor is
2602
+ * refused before anything is sent.
2346
2603
  *
2347
2604
  * The effect carries a `statuses` array, matching how FoundryVTT v11+ models
2348
2605
  * conditions (`Actor#toggleStatusEffect` toggles by this field).
@@ -2363,13 +2620,17 @@ export class FoundryClient {
2363
2620
  const effectData = {
2364
2621
  name: options.name ?? statusId,
2365
2622
  statuses: [statusId],
2623
+ // ACTIVE_EFFECT_SHOW_ICON.ALWAYS, as ActiveEffect.fromStatusEffect sets.
2624
+ // The default (CONDITIONAL) only draws the token icon for temporary
2625
+ // effects, and since v14 a status alone no longer makes one temporary.
2626
+ showIcon: 2,
2366
2627
  };
2367
2628
  if (options.img) {
2368
2629
  effectData.img = options.img;
2369
2630
  }
2370
2631
  const result = await this.modifyDocument('ActiveEffect', 'create', {
2371
2632
  data: [effectData],
2372
- parentUuid: parentActorUuid,
2633
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2373
2634
  });
2374
2635
  return result[0];
2375
2636
  }
@@ -2391,7 +2652,7 @@ export class FoundryClient {
2391
2652
  }
2392
2653
  await this.modifyDocument('ActiveEffect', 'delete', {
2393
2654
  ids: [effectId],
2394
- parentUuid: parentActorUuid,
2655
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2395
2656
  });
2396
2657
  }
2397
2658
  /**
@@ -2424,6 +2685,12 @@ export class FoundryClient {
2424
2685
  }
2425
2686
  if (effect.statuses) {
2426
2687
  effectData.statuses = effect.statuses;
2688
+ if (effect.statuses.length > 0) {
2689
+ // ACTIVE_EFFECT_SHOW_ICON.ALWAYS, as createActorStatusEffect sets: since
2690
+ // v14 a status alone no longer makes the effect temporary, so the
2691
+ // default (CONDITIONAL) would hide its token icon.
2692
+ effectData.showIcon = 2;
2693
+ }
2427
2694
  }
2428
2695
  if (effect.duration) {
2429
2696
  effectData.duration = effect.duration;
@@ -2434,7 +2701,7 @@ export class FoundryClient {
2434
2701
  }
2435
2702
  const result = await this.modifyDocument('ActiveEffect', 'create', {
2436
2703
  data: [effectData],
2437
- parentUuid: parentActorUuid,
2704
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2438
2705
  });
2439
2706
  return result[0];
2440
2707
  }
@@ -2480,7 +2747,7 @@ export class FoundryClient {
2480
2747
  }
2481
2748
  const result = await this.modifyDocument('ActiveEffect', 'update', {
2482
2749
  updates: [update],
2483
- parentUuid: parentActorUuid,
2750
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2484
2751
  });
2485
2752
  return result[0];
2486
2753
  }
@@ -4048,6 +4315,19 @@ export class FoundryClient {
4048
4315
  }
4049
4316
  return size;
4050
4317
  }
4318
+ /**
4319
+ * The connected FoundryVTT generation (13, 14, ...), from the world's
4320
+ * `release`: v14 sends `generation` (and no `version`), earlier releases
4321
+ * a `version` such as "13.351". 0 when neither is known.
4322
+ */
4323
+ getCoreGeneration() {
4324
+ const release = this.worldData?.release ?? {};
4325
+ if (typeof release.generation === 'number') {
4326
+ return release.generation;
4327
+ }
4328
+ const major = Number.parseInt(String(release.version ?? ''), 10);
4329
+ return Number.isFinite(major) ? major : 0;
4330
+ }
4051
4331
  /**
4052
4332
  * Creates a new Scene document from a background image already present
4053
4333
  * under FoundryVTT's `Data` directory. Width/height default to the
@@ -4073,13 +4353,29 @@ export class FoundryClient {
4073
4353
  : this.requireImageSize(backgroundSrc);
4074
4354
  const width = options.width ?? size.width;
4075
4355
  const height = options.height ?? size.height;
4356
+ const backgroundColor = options.backgroundColor ?? '#999999';
4357
+ // v14 moved the background onto the scene's Levels: a scene created
4358
+ // without one has nothing to draw. The Foundry client adds a default
4359
+ // Level in Scene#_preCreate (client/documents/scene.mjs, 14.370:
4360
+ // 1009-1031), which a socket create never runs, so it is built here.
4361
+ const backgroundData = this.getCoreGeneration() >= 14
4362
+ ? {
4363
+ levels: [
4364
+ {
4365
+ _id: DEFAULT_LEVEL_ID,
4366
+ name: 'Level',
4367
+ background: { src: backgroundSrc, color: backgroundColor },
4368
+ },
4369
+ ],
4370
+ initialLevel: DEFAULT_LEVEL_ID,
4371
+ }
4372
+ : { background: { src: backgroundSrc }, backgroundColor };
4076
4373
  const data = {
4077
4374
  name,
4078
- background: { src: backgroundSrc },
4375
+ ...backgroundData,
4079
4376
  width,
4080
4377
  height,
4081
4378
  padding: options.padding ?? 0.25,
4082
- backgroundColor: options.backgroundColor ?? '#999999',
4083
4379
  grid: {
4084
4380
  type: options.gridType ?? 1,
4085
4381
  size: options.gridSize ?? 100,
@@ -5755,6 +6051,22 @@ function worldSceneToFoundry(s) {
5755
6051
  }
5756
6052
  return scene;
5757
6053
  }
6054
+ /**
6055
+ * An unlinked token's effects or items: the base actor's, each replaced by the
6056
+ * delta's entry with the same id, then the delta's own, without the entries
6057
+ * the delta tombstoned. Builds a new array and leaves the cache as it is.
6058
+ */
6059
+ function mergeDeltaEntries(base, delta) {
6060
+ const deltaEntries = Array.isArray(delta)
6061
+ ? delta.filter((entry) => isRecord(entry) && typeof entry._id === 'string')
6062
+ : [];
6063
+ const byId = new Map(deltaEntries.map((entry) => [entry._id, entry]));
6064
+ const baseIds = new Set(base.map((entry) => entry._id));
6065
+ return [
6066
+ ...base.map((entry) => byId.get(entry._id) ?? entry),
6067
+ ...deltaEntries.filter((entry) => !baseIds.has(entry._id)),
6068
+ ].filter((entry) => entry._tombstone !== true);
6069
+ }
5758
6070
  /**
5759
6071
  * Returns the `system` object of an actor-like document, accepting either the
5760
6072
  * raw REST/world document (`{ ..., system }`) or a cached {@link WorldActor}.