The Token Document. Defines the DataSchema and common behaviors for a Token which are shared between both client and server.

Mixes

TokenData

Hierarchy (view full)

Constructors

  • Construct a Token document using provided data and context.

    Parameters

    Returns BaseToken

Properties

_source: object

The source data object for this DataModel instance. Once constructed, the source object is sealed such that no keys may be added nor removed.

parent: DataModel

An immutable reverse-reference to a parent DataModel to which this model belongs.

metadata: object = ...

Default metadata which applies to each instance of this Document type.

LOCALIZATION_PREFIXES: string[] = ...
DEFAULT_ICON: string = CONST.DEFAULT_TOKEN

The default icon used for newly created Token documents

Accessors

  • get id(): string
  • The canonical identifier for this Document.

    Returns string

  • get isEmbedded(): boolean
  • Test whether this Document is embedded within a parent Document

    Returns boolean

  • get uuid(): string
  • A Universally Unique Identifier (uuid) for this Document instance.

    Returns string

  • get schema(): SchemaField
  • Define the data schema for this document instance.

    Returns SchemaField

  • get invalid(): boolean
  • Is the current state of this DataModel invalid? The model is invalid if there is any unresolved failure.

    Returns boolean

  • get schema(): SchemaField
  • Ensure that all Document classes share the same schema of their base declaration.

    Returns SchemaField

  • get database(): DatabaseBackend
  • The database backend used to execute operations and handle results.

    Returns DatabaseBackend

  • get implementation(): typeof Document
  • Return a reference to the configured subclass of this base Document type.

    Returns typeof Document

  • get baseDocument(): typeof Document
  • The base document definition that this document class extends from.

    Returns typeof Document

  • get collectionName(): string
  • The named collection to which this Document belongs.

    Returns string

  • get documentName(): string
  • The canonical name of this Document type, for example "Actor".

    Returns string

  • get TYPES(): string[]
  • The allowed types which may exist for this Document class.

    Returns string[]

  • get hasTypeData(): boolean
  • Does this Document support additional subtypes?

    Returns boolean

  • get hierarchy(): Readonly<Record<string, any>>
  • The Embedded Document hierarchy for this Document.

    Returns Readonly<Record<string, any>>

Methods

  • Parameters

    • user: any
    • permission: any
    • __namedParameters: {
          exact: boolean;
      } = {}
      • exact: boolean

    Returns any

  • Update the DataModel locally by applying an object of changes to its source data. The provided changes are cleaned, validated, and stored to the source data object for this model. The source data is then re-initialized to apply those changes to the prepared data. The method returns an object of differential changes which modified the original data.

    Parameters

    • changes: {} = {}

      New values which should be applied to the data model

      • options: {} = {}

        Options which determine how the new data is merged

        Returns object

        An object containing the changed keys and values

      • Copy and transform the DataModel into a plain object. Draw the values of the extracted object from the data source (by default) otherwise from its transformed values.

        Parameters

        • source: boolean = true

          Draw values from the underlying data source rather than transformed values

        Returns any

        The extracted primitive object

      • Parameters

        • __namedParameters: {
              pack: any;
              parentCollection: any;
          } = {}
          • pack: any
          • parentCollection: any

        Returns void

      • Initialize the instance by copying data from the source object to instance attributes. This mirrors the workflow of SchemaField#initialize but with some added functionality.

        Parameters

        • options: {} = {}

          Options provided to the model constructor

          Returns void

        • Internal

          Identify the collection in a parent Document that this Document belongs to, if any.

          Parameters

          • Optional parentCollection: string

            An explicitly provided parent collection name.

          Returns string

        • Get the explicit permission level that a User has over this Document, a value in CONST.DOCUMENT_OWNERSHIP_LEVELS. This method returns the value recorded in Document ownership, regardless of the User's role. To test whether a user has a certain capability over the document, testUserPermission should be used.

          Parameters

          • Optional user: BaseUser

            The User being tested

          Returns number

          A numeric permission level from CONST.DOCUMENT_OWNERSHIP_LEVELS or null

        • Test whether a given User has permission to perform some action on this Document

          Parameters

          • user: BaseUser

            The User attempting modification

          • action: string

            The attempted action

          • Optional data: object = {}

            Data involved in the attempted action

          Returns boolean

          Does the User have permission?

        • Clone a document, creating a new document by combining current data with provided overrides. The cloned document is ephemeral and not yet saved to the database.

          Parameters

          • Optional data: Object = {}

            Additional data which overrides current document data at the time of creation

          • Optional context: DocumentConstructionContext = {}

            Additional context options passed to the create method

          Returns Document | Promise<Document>

          The cloned Document instance

        • For Documents which include game system data, migrate the system data object to conform to its latest data model. The data model is defined by the template.json specification included by the game system.

          Returns object

          The migrated system data object

        • Update this Document using incremental data, saving it to the database.

          Parameters

          • Optional data: object = {}

            Differential update data which modifies the existing values of this document

          • Optional operation: Partial<Omit<DatabaseUpdateOperation, "updates">> = {}

            Parameters of the update operation

          Returns Promise<Document>

          The updated Document instance

          See

          Document.updateDocuments

        • Delete this Document, removing it from the database.

          Parameters

          • Optional operation: Partial<Omit<DatabaseDeleteOperation, "ids">> = {}

            Parameters of the deletion operation

          Returns Promise<Document>

          The deleted Document instance

          See

          Document.deleteDocuments

        • Obtain a reference to the Array of source data within the data object for a certain embedded Document name

          Parameters

          • embeddedName: string

            The name of the embedded Document type

          Returns DocumentCollection

          The Collection instance of embedded Documents of the requested type

        • Get an embedded document by its id from a named collection in the parent document.

          Parameters

          • embeddedName: string

            The name of the embedded Document type

          • id: string

            The id of the child document to retrieve

          • Optional options: {
                strict: boolean;
                invalid: boolean;
            } = {}

            Additional options which modify how embedded documents are retrieved

            • strict: boolean

              Throw an Error if the requested id does not exist. See Collection#get

            • invalid: boolean

              Allow retrieving an invalid Embedded Document.

          Returns Document

          The retrieved embedded Document instance, or undefined

          Throws

          If the embedded collection does not exist, or if strict is true and the Embedded Document could not be found.

        • Create multiple embedded Document instances within this parent Document using provided input data.

          Parameters

          • embeddedName: string

            The name of the embedded Document type

          • data: object[] = []

            An array of data objects used to create multiple documents

          • Optional operation: DatabaseCreateOperation = {}

            Parameters of the database creation workflow

          Returns Promise<Document[]>

          An array of created Document instances

          See

          Document.createDocuments

        • Update multiple embedded Document instances within a parent Document using provided differential data.

          Parameters

          • embeddedName: string

            The name of the embedded Document type

          • updates: object[] = []

            An array of differential data objects, each used to update a single Document

          • Optional operation: DatabaseUpdateOperation = {}

            Parameters of the database update workflow

          Returns Promise<Document[]>

          An array of updated Document instances

          See

          Document.updateDocuments

        • Delete multiple embedded Document instances within a parent Document using provided string ids.

          Parameters

          • embeddedName: string

            The name of the embedded Document type

          • ids: string[]

            An array of string ids for each Document to be deleted

          • Optional operation: DatabaseDeleteOperation = {}

            Parameters of the database deletion workflow

          Returns Promise<Document[]>

          An array of deleted Document instances

          See

          Document.deleteDocuments

        • Iterate over all embedded Documents that are hierarchical children of this Document.

          Parameters

          • Optional _parentPath: string

            A parent field path already traversed

          Returns Generator<[string, Document], any, any>

        • Get the value of a "flag" for this document See the setFlag method for more details on flags

          Parameters

          • scope: string

            The flag scope which namespaces the key

          • key: string

            The flag key

          Returns any

          The flag value

        • Assign a "flag" to this document. Flags represent key-value type data which can be used to store flexible or arbitrary data required by either the core software, game systems, or user-created modules.

          Each flag should be set using a scope which provides a namespace for the flag to help prevent collisions.

          Flags set by the core software use the "core" scope. Flags set by game systems or modules should use the canonical name attribute for the module Flags set by an individual world should "world" as the scope.

          Flag values can assume almost any data type. Setting a flag value to null will delete that flag.

          Parameters

          • scope: string

            The flag scope which namespaces the key

          • key: string

            The flag key

          • value: any

            The flag value

          Returns Promise<Document>

          A Promise resolving to the updated document

        • Remove a flag assigned to the document

          Parameters

          • scope: string

            The flag scope which namespaces the key

          • key: string

            The flag key

          Returns Promise<Document>

          The updated document instance

        • Internal

          Pre-process a creation operation for a single Document instance. Pre-operation events only occur for the client which requested the operation.

          Modifications to the pending Document instance must be performed using Document#updateSource.

          Parameters

          • data: object

            The initial data object provided to the document creation request

          • options: object

            Additional options which modify the creation request

          • user: BaseUser

            The User requesting the document creation

          Returns Promise<boolean | void>

          Return false to exclude this Document from the creation operation

        • Internal

          Post-process a creation operation for a single Document instance. Post-operation events occur for all connected clients.

          Parameters

          • data: object

            The initial data object provided to the document creation request

          • options: object

            Additional options which modify the creation request

          • userId: string

            The id of the User requesting the document update

          Returns void

        • Internal

          Pre-process an update operation for a single Document instance. Pre-operation events only occur for the client which requested the operation.

          Parameters

          • changes: object

            The candidate changes to the Document

          • options: object

            Additional options which modify the update request

          • user: BaseUser

            The User requesting the document update

          Returns Promise<boolean | void>

          A return value of false indicates the update operation should be cancelled.

        • Internal

          Post-process an update operation for a single Document instance. Post-operation events occur for all connected clients.

          Parameters

          • changed: object

            The differential data that was changed relative to the documents prior values

          • options: object

            Additional options which modify the update request

          • userId: string

            The id of the User requesting the document update

          Returns void

        • Internal

          Pre-process a deletion operation for a single Document instance. Pre-operation events only occur for the client which requested the operation.

          Parameters

          • options: object

            Additional options which modify the deletion request

          • user: BaseUser

            The User requesting the document deletion

          Returns Promise<boolean | void>

          A return value of false indicates the deletion operation should be cancelled.

        • Internal

          Post-process a deletion operation for a single Document instance. Post-operation events occur for all connected clients.

          Parameters

          • options: object

            Additional options which modify the deletion request

          • userId: string

            The id of the User requesting the document update

          Returns void

        • Reset the state of this data instance back to mirror the contained source data, erasing any changes.

          Returns void

        • Validate the data contained in the document to check for type and content This function throws an error if data within the document is not valid

          Parameters

          • options: {
                changes: object;
                clean: boolean;
                fallback: boolean;
                dropInvalidEmbedded: boolean;
                strict: boolean;
                fields: boolean;
                joint: boolean;
            } = {}

            Optional parameters which customize how validation occurs.

            • changes: object

              A specific set of proposed changes to validate, rather than the full source data of the model.

            • clean: boolean

              If changes are provided, attempt to clean the changes before validating them?

            • fallback: boolean

              Allow replacement of invalid values with valid defaults?

            • dropInvalidEmbedded: boolean

              If true, invalid embedded documents will emit a warning and be placed in the invalidDocuments collection rather than causing the parent to be considered invalid.

            • strict: boolean

              Throw if an invalid value is encountered, otherwise log a warning?

            • fields: boolean

              Perform validation on individual fields?

            • joint: boolean

              Perform joint validation on the full data model? Joint validation will be performed by default if no changes are passed. Joint validation will be disabled by default if changes are passed. Joint validation can be performed on a complete set of changes (for example testing a complete data model) by explicitly passing true.

          Returns boolean

          An indicator for whether the document contains valid data

        • Extract the source data for the DataModel into a simple object format that can be serialized.

          Returns object

          The document source data expressed as a plain object

        • Protected

          Initialize the source data for a new DataModel instance. One-time migrations and initial cleaning operations are applied to the source data.

          Parameters

          • data: object | DataModel

            The candidate source data from which the model will be constructed

          • Optional options: object = {}

            Options provided to the model constructor

          Returns object

          Migrated and cleaned source data which will be stored to the model instance

        • Migrate candidate source data for this DataModel which may require initial cleaning or transformations.

          Parameters

          • data: any

            The candidate source data from which the model will be constructed

          Returns object

          Migrated source data, if necessary

        • Take data which conforms to the current data schema and add backwards-compatible accessors to it in order to support older code which uses this data.

          Parameters

          • data: any

            Data which matches the current schema

          • options: any

            Additional shimming options

          Returns object

          Data with added backwards-compatible properties

        • Test whether a given User has a sufficient role in order to create Documents of this type in general.

          Parameters

          • user: BaseUser

            The User being tested

          Returns boolean

          Does the User have a sufficient role to create?

        • Create multiple Documents using provided input data. Data is provided as an array of objects where each individual object becomes one new Document.

          Parameters

          • data: (object | Document)[] = []

            An array of data objects or existing Documents to persist.

          • Optional operation: Partial<Omit<DatabaseCreateOperation, "data">> = {}

            Parameters of the requested creation operation

          Returns Promise<Document[]>

          An array of created Document instances

          Example: Create a single Document

          const data = [{name: "New Actor", type: "character", img: "path/to/profile.jpg"}];
          const created = await Actor.createDocuments(data);

          Example: Create multiple Documents

          const data = [{name: "Tim", type: "npc"], [{name: "Tom", type: "npc"}];
          const created = await Actor.createDocuments(data);

          Example: Create multiple embedded Documents within a parent

          const actor = game.actors.getName("Tim");
          const data = [{name: "Sword", type: "weapon"}, {name: "Breastplate", type: "equipment"}];
          const created = await Item.createDocuments(data, {parent: actor});

          Example: Create a Document within a Compendium pack

          const data = [{name: "Compendium Actor", type: "character", img: "path/to/profile.jpg"}];
          const created = await Actor.createDocuments(data, {pack: "mymodule.mypack"});
        • Update multiple Document instances using provided differential data. Data is provided as an array of objects where each individual object updates one existing Document.

          Parameters

          • updates: object[] = []

            An array of differential data objects, each used to update a single Document

          • Optional operation: Partial<Omit<DatabaseUpdateOperation, "updates">> = {}

            Parameters of the database update operation

          Returns Promise<Document[]>

          An array of updated Document instances

          Example: Update a single Document

          const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}];
          const updated = await Actor.updateDocuments(updates);

          Example: Update multiple Documents

          const updates = [{_id: "12ekjf43kj2312ds", name: "Timothy"}, {_id: "kj549dk48k34jk34", name: "Thomas"}]};
          const updated = await Actor.updateDocuments(updates);

          Example: Update multiple embedded Documents within a parent

          const actor = game.actors.getName("Timothy");
          const updates = [{_id: sword.id, name: "Magic Sword"}, {_id: shield.id, name: "Magic Shield"}];
          const updated = await Item.updateDocuments(updates, {parent: actor});

          Example: Update Documents within a Compendium pack

          const actor = await pack.getDocument(documentId);
          const updated = await Actor.updateDocuments([{_id: actor.id, name: "New Name"}], {pack: "mymodule.mypack"});
        • Delete one or multiple existing Documents using an array of provided ids. Data is provided as an array of string ids for the documents to delete.

          Parameters

          • ids: string[] = []

            An array of string ids for the documents to be deleted

          • Optional operation: Partial<Omit<DatabaseDeleteOperation, "ids">> = {}

            Parameters of the database deletion operation

          Returns Promise<Document[]>

          An array of deleted Document instances

          Example: Delete a single Document

          const tim = game.actors.getName("Tim");
          const deleted = await Actor.deleteDocuments([tim.id]);

          Example: Delete multiple Documents

          const tim = game.actors.getName("Tim");
          const tom = game.actors.getName("Tom");
          const deleted = await Actor.deleteDocuments([tim.id, tom.id]);

          Example: Delete multiple embedded Documents within a parent

          const tim = game.actors.getName("Tim");
          const sword = tim.items.getName("Sword");
          const shield = tim.items.getName("Shield");
          const deleted = await Item.deleteDocuments([sword.id, shield.id], parent: actor});

          Example: Delete Documents within a Compendium pack

          const actor = await pack.getDocument(documentId);
          const deleted = await Actor.deleteDocuments([actor.id], {pack: "mymodule.mypack"});
        • Create a new Document using provided input data, saving it to the database.

          Parameters

          • Optional data: object | Document | (object | Document)[]

            Initial data used to create this Document, or a Document instance to persist.

          • Optional operation: Partial<Omit<DatabaseCreateOperation, "data">> = {}

            Parameters of the creation operation

          Returns Promise<Document | Document[]>

          The created Document instance

          See

          Document.createDocuments

          Example: Create a World-level Item

          const data = [{name: "Special Sword", type: "weapon"}];
          const created = await Item.create(data);

          Example: Create an Actor-owned Item

          const data = [{name: "Special Sword", type: "weapon"}];
          const actor = game.actors.getName("My Hero");
          const created = await Item.create(data, {parent: actor});

          Example: Create an Item in a Compendium pack

          const data = [{name: "Special Sword", type: "weapon"}];
          const created = await Item.create(data, {pack: "mymodule.mypack"});
        • Get a World-level Document of this type by its id.

          Parameters

          • documentId: string

            The Document ID

          • Optional operation: DatabaseGetOperation = {}

            Parameters of the get operation

          Returns any

          The retrieved Document, or null

        • A compatibility method that returns the appropriate name of an embedded collection within this Document.

          Parameters

          • name: string

            An existing collection name or a document name.

          Returns string

          The provided collection name if it exists, the first available collection for the document name provided, or null if no appropriate embedded collection could be found.

          Example: Passing an existing collection name.

          Actor.getCollectionName("items");
          // returns "items"

          Example: Passing a document name.

          Actor.getCollectionName("Item");
          // returns "items"
        • Internal

          Pre-process a creation operation, potentially altering its instructions or input data. Pre-operation events only occur for the client which requested the operation.

          This batch-wise workflow occurs after individual Document#_preCreate workflows and provides a final pre-flight check before a database operation occurs.

          Modifications to pending documents must mutate the documents array or alter individual document instances using Document#updateSource.

          Parameters

          • documents: Document[]

            Pending document instances to be created

          • operation: DatabaseCreateOperation

            Parameters of the database creation operation

          • user: BaseUser

            The User requesting the creation operation

          Returns Promise<boolean | void>

          Return false to cancel the creation operation entirely

        • Internal

          Post-process a creation operation, reacting to database changes which have occurred. Post-operation events occur for all connected clients.

          This batch-wise workflow occurs after individual Document#_onCreate workflows.

          Parameters

          • documents: Document[]

            The Document instances which were created

          • operation: DatabaseCreateOperation

            Parameters of the database creation operation

          • user: BaseUser

            The User who performed the creation operation

          Returns Promise<void>

        • Internal

          Pre-process an update operation, potentially altering its instructions or input data. Pre-operation events only occur for the client which requested the operation.

          This batch-wise workflow occurs after individual Document#_preUpdate workflows and provides a final pre-flight check before a database operation occurs.

          Modifications to the requested updates are performed by mutating the data array of the operation. Document#updateSource.

          Parameters

          • documents: Document[]

            Document instances to be updated

          • operation: DatabaseUpdateOperation

            Parameters of the database update operation

          • user: BaseUser

            The User requesting the update operation

          Returns Promise<boolean | void>

          Return false to cancel the update operation entirely

        • Internal

          Post-process an update operation, reacting to database changes which have occurred. Post-operation events occur for all connected clients.

          This batch-wise workflow occurs after individual Document#_onUpdate workflows.

          Parameters

          • documents: Document[]

            The Document instances which were updated

          • operation: DatabaseUpdateOperation

            Parameters of the database update operation

          • user: BaseUser

            The User who performed the update operation

          Returns Promise<void>

        • Internal

          Pre-process a deletion operation, potentially altering its instructions or input data. Pre-operation events only occur for the client which requested the operation.

          This batch-wise workflow occurs after individual Document#_preDelete workflows and provides a final pre-flight check before a database operation occurs.

          Modifications to the requested deletions are performed by mutating the operation object. Document#updateSource.

          Parameters

          • documents: Document[]

            Document instances to be deleted

          • operation: DatabaseDeleteOperation

            Parameters of the database update operation

          • user: BaseUser

            The User requesting the deletion operation

          Returns Promise<boolean | void>

          Return false to cancel the deletion operation entirely

        • Internal

          Post-process a deletion operation, reacting to database changes which have occurred. Post-operation events occur for all connected clients.

          This batch-wise workflow occurs after individual Document#_onDelete workflows.

          Parameters

          • documents: Document[]

            The Document instances which were deleted

          • operation: DatabaseDeleteOperation

            Parameters of the database deletion operation

          • user: BaseUser

            The User who performed the deletion operation

          Returns Promise<void>

        • Internal

          Define a simple migration from one field name to another. The value of the data can be transformed during the migration by an optional application function.

          Parameters

          • data: object

            The data object being migrated

          • oldKey: string

            The old field name

          • newKey: string

            The new field name

          • apply: any

            An application function, otherwise the old value is applied

          Returns boolean

          Whether a migration was applied.

        • Clean a data source object to conform to a specific provided schema.

          Parameters

          • Optional source: object = {}

            The source data object

          • Optional options: object = {}

            Additional options which are passed to field cleaning methods

          Returns object

          The cleaned source data

        • Evaluate joint validation rules which apply validation conditions across multiple fields of the model. Field-specific validation rules should be defined as part of the DataSchema for the model. This method allows for testing aggregate rules which impose requirements on the overall model.

          Parameters

          • data: object

            Candidate data for the model

          Returns any

          Throws

          An error if a validation failure is detected

        • Create a new instance of this DataModel from a source record. The source is presumed to be trustworthy and is not strictly validated.

          Parameters

          • source: object

            Initial document data which comes from a trusted source.

          • Optional context: any = {}

            Model construction context

          Returns DataModel

        • Create a DataModel instance using a provided serialized JSON string.

          Parameters

          • json: string

            Serialized document data in string format

          Returns DataModel

          A constructed data model instance

        • Wrap data migration in a try/catch which attempts it safely

          Parameters

          • source: object

            The candidate source data from which the model will be constructed

          Returns object

          Migrated source data, if necessary

        • Protected

          Parameters

          • oldKey: any
          • newKey: any
          • options: {} = {}

            Returns void

          • Validate the structure of the detection modes array

            Parameters

            • modes: object[]

              Configured detection modes

            Returns void

            Throws

            An error if the array is invalid

          • Private

            Is a user able to update an existing Token?

            Parameters

            • user: any
            • doc: any
            • data: any

            Returns any