/**
 * @license
 * Copyright 2022-2024 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { camelize } from "#general";
import { FieldValue } from "#model";
import { ServerNodeStore } from "#node/storage/ServerNodeStore.js";
import { BehaviorBacking } from "./BehaviorBacking.js";
class ServerBehaviorBacking extends BehaviorBacking {
  #store;
  get store() {
    if (!this.#store) {
      this.#store = this.#serverStore.endpointStores.storeForEndpoint(this.endpoint).storeForBehavior(this.type.id);
    }
    return this.#store;
  }
  invokeInitializer(behavior, options) {
    const finalizeState = () => {
      this.#applyTransitiveDefaults(behavior.state);
      const context = behavior.context;
      this.datasource.validate(context, behavior.state);
    };
    const promise = super.invokeInitializer(behavior, options);
    if (promise) {
      return promise.then(finalizeState);
    }
    finalizeState();
  }
  get #serverStore() {
    return this.endpoint.env.get(ServerNodeStore);
  }
  /**
   * Schema may specify that state fields default to the value of another field.  We apply these defaults after
   * initialization when the other field should be defined.
   */
  #applyTransitiveDefaults(state) {
    const schema = this.type.schema;
    if (!schema) {
      return;
    }
    for (const member of schema.activeMembers) {
      const name = camelize(member.name);
      if (state[name] === void 0) {
        const referenced = FieldValue.referenced(member.default);
        if (referenced) {
          const val = state[camelize(referenced)];
          if (val !== void 0) {
            state[name] = val;
          }
        }
      }
    }
  }
}
export {
  ServerBehaviorBacking
};
//# sourceMappingURL=ServerBehaviorBacking.js.map
