import { n as __exportAll } from "./chunk-YKewjYmz.js";
import { A as url, C as boolean, D as object, O as string, S as array, T as literal, _ as generateId, a as BaseDocumentHeaderSchema, b as _enum, c as baseCreateDocument, f as createAction, g as defaultBaseState, h as createState, j as datetime, l as baseLoadFromInput, m as createReducer, o as BaseDocumentStateSchema, s as baseActions, u as baseSaveToFileHandle, v as isDocumentAction, w as lazy, x as any } from "./dist-Dacf6lFH.js";
//#region document-models/chat/v1/gen/document-model.ts
const documentModel = {
	id: "powerchat/chat",
	name: "Chat",
	author: {
		name: "Powerhouse",
		website: "https://www.powerhouse.inc/"
	},
	extension: "pchat",
	description: "Chat message history for a PowerChat channel. Contains messages, reactions, and pins.",
	specifications: [{
		state: {
			local: {
				schema: "",
				examples: [],
				initialValue: ""
			},
			global: {
				schema: "enum AttachmentType {\n  IMAGE\n  GIF\n  LINK\n  FILE\n}\n\ntype Reaction {\n  id: OID!\n  emoji: String!\n  participantIds: [OID!]!\n}\n\ntype Attachment {\n  id: OID!\n  type: AttachmentType!\n  url: URL!\n  title: String\n  description: String\n  thumbnailUrl: String\n}\n\ntype Message {\n  id: OID!\n  authorId: OID!\n  content: String!\n  timestamp: DateTime!\n  edited: Boolean!\n  editedAt: DateTime\n  replyToId: OID\n  reactions: [Reaction!]!\n  attachments: [Attachment!]!\n}\n\ntype ChatState {\n  channelId: PHID\n  messages: [Message!]!\n  pinnedMessageIds: [String!]!\n}",
				examples: [],
				initialValue: "{\"channelId\": null, \"messages\": [], \"pinnedMessageIds\": []}"
			}
		},
		modules: [{
			id: "mod-config",
			name: "config",
			description: "Chat configuration operations",
			operations: [{
				id: "op-set-channel-id",
				name: "SET_CHANNEL_ID",
				description: "Links this chat to a channel document",
				schema: "input SetChannelIdInput {\n  channelId: PHID!\n}",
				template: "Links this chat to a channel document",
				reducer: "state.channelId = action.input.channelId;",
				errors: [],
				examples: [],
				scope: "global"
			}]
		}, {
			id: "mod-messages",
			name: "messages",
			description: "Message CRUD, pinning, and reaction operations",
			operations: [
				{
					id: "op-send-message",
					name: "SEND_MESSAGE",
					description: "Sends a new message to the chat",
					schema: "input AttachmentInput {\n  id: OID!\n  type: AttachmentType!\n  url: URL!\n  title: String\n  description: String\n  thumbnailUrl: String\n}\n\ninput SendMessageInput {\n  id: OID!\n  authorId: OID!\n  content: String!\n  timestamp: DateTime!\n  replyToId: OID\n  attachments: [AttachmentInput!]\n}",
					template: "Sends a new message to the chat",
					reducer: "state.messages.push({\n  id: action.input.id,\n  authorId: action.input.authorId,\n  content: action.input.content,\n  timestamp: action.input.timestamp,\n  edited: false,\n  editedAt: null,\n  replyToId: action.input.replyToId || null,\n  reactions: [],\n  attachments: (action.input.attachments || []).map(a => ({\n    id: a.id,\n    type: a.type,\n    url: a.url,\n    title: a.title || null,\n    description: a.description || null,\n    thumbnailUrl: a.thumbnailUrl || null,\n  })),\n});",
					errors: [],
					examples: [],
					scope: "global"
				},
				{
					id: "op-edit-message",
					name: "EDIT_MESSAGE",
					description: "Edits an existing message",
					schema: "input EditMessageInput {\n  messageId: OID!\n  content: String!\n  editedAt: DateTime!\n}",
					template: "Edits an existing message",
					reducer: "const message = state.messages.find(m => m.id === action.input.messageId);\nif (!message) {\n  throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);\n}\nmessage.content = action.input.content;\nmessage.edited = true;\nmessage.editedAt = action.input.editedAt;",
					errors: [{
						id: "err-msg-not-found-edit",
						name: "MessageNotFoundError",
						code: "MESSAGE_NOT_FOUND",
						description: "Message not found",
						template: ""
					}],
					examples: [],
					scope: "global"
				},
				{
					id: "op-delete-message",
					name: "DELETE_MESSAGE",
					description: "Deletes a message",
					schema: "input DeleteMessageInput {\n  messageId: OID!\n}",
					template: "Deletes a message",
					reducer: "const index = state.messages.findIndex(m => m.id === action.input.messageId);\nif (index === -1) {\n  throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);\n}\nconst pinnedIndex = state.pinnedMessageIds.indexOf(action.input.messageId);\nif (pinnedIndex !== -1) {\n  state.pinnedMessageIds.splice(pinnedIndex, 1);\n}\nstate.messages.splice(index, 1);",
					errors: [{
						id: "err-msg-not-found-delete",
						name: "MessageNotFoundError",
						code: "MESSAGE_NOT_FOUND",
						description: "Message not found",
						template: ""
					}],
					examples: [],
					scope: "global"
				},
				{
					id: "op-pin-message",
					name: "PIN_MESSAGE",
					description: "Pins a message",
					schema: "input PinMessageInput {\n  messageId: OID!\n}",
					template: "Pins a message",
					reducer: "const message = state.messages.find(m => m.id === action.input.messageId);\nif (!message) {\n  throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);\n}\nif (state.pinnedMessageIds.includes(action.input.messageId)) {\n  throw new MessageAlreadyPinnedError(`Message ${action.input.messageId} is already pinned`);\n}\nstate.pinnedMessageIds.push(action.input.messageId);",
					errors: [{
						id: "err-msg-not-found-pin",
						name: "MessageNotFoundError",
						code: "MESSAGE_NOT_FOUND",
						description: "Message not found",
						template: ""
					}, {
						id: "err-msg-already-pinned",
						name: "MessageAlreadyPinnedError",
						code: "MESSAGE_ALREADY_PINNED",
						description: "Message is already pinned",
						template: ""
					}],
					examples: [],
					scope: "global"
				},
				{
					id: "op-unpin-message",
					name: "UNPIN_MESSAGE",
					description: "Unpins a message",
					schema: "input UnpinMessageInput {\n  messageId: OID!\n}",
					template: "Unpins a message",
					reducer: "const index = state.pinnedMessageIds.indexOf(action.input.messageId);\nif (index === -1) {\n  throw new MessageNotPinnedError(`Message ${action.input.messageId} is not pinned`);\n}\nstate.pinnedMessageIds.splice(index, 1);",
					errors: [{
						id: "err-msg-not-pinned",
						name: "MessageNotPinnedError",
						code: "MESSAGE_NOT_PINNED",
						description: "Message is not pinned",
						template: ""
					}],
					examples: [],
					scope: "global"
				},
				{
					id: "op-add-reaction",
					name: "ADD_REACTION",
					description: "Adds an emoji reaction",
					schema: "input AddReactionInput {\n  id: OID!\n  messageId: OID!\n  emoji: String!\n  participantId: OID!\n}",
					template: "Adds an emoji reaction",
					reducer: "const message = state.messages.find(m => m.id === action.input.messageId);\nif (!message) {\n  throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);\n}\nconst existingReaction = message.reactions.find(r => r.emoji === action.input.emoji);\nif (existingReaction) {\n  if (!existingReaction.participantIds.includes(action.input.participantId)) {\n    existingReaction.participantIds.push(action.input.participantId);\n  }\n} else {\n  message.reactions.push({\n    id: action.input.id,\n    emoji: action.input.emoji,\n    participantIds: [action.input.participantId],\n  });\n}",
					errors: [{
						id: "err-msg-not-found-react",
						name: "MessageNotFoundError",
						code: "MESSAGE_NOT_FOUND",
						description: "Message not found",
						template: ""
					}],
					examples: [],
					scope: "global"
				},
				{
					id: "op-remove-reaction",
					name: "REMOVE_REACTION",
					description: "Removes an emoji reaction",
					schema: "input RemoveReactionInput {\n  messageId: OID!\n  emoji: String!\n  participantId: OID!\n}",
					template: "Removes an emoji reaction",
					reducer: "const message = state.messages.find(m => m.id === action.input.messageId);\nif (!message) {\n  throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);\n}\nconst reaction = message.reactions.find(r => r.emoji === action.input.emoji);\nif (reaction) {\n  const pidIndex = reaction.participantIds.indexOf(action.input.participantId);\n  if (pidIndex !== -1) {\n    reaction.participantIds.splice(pidIndex, 1);\n  }\n  if (reaction.participantIds.length === 0) {\n    const rIndex = message.reactions.indexOf(reaction);\n    message.reactions.splice(rIndex, 1);\n  }\n}",
					errors: [{
						id: "err-msg-not-found-unreact",
						name: "MessageNotFoundError",
						code: "MESSAGE_NOT_FOUND",
						description: "Message not found",
						template: ""
					}],
					examples: [],
					scope: "global"
				}
			]
		}],
		version: 1,
		changeLog: []
	}]
};
//#endregion
//#region document-models/chat/v1/src/reducers/config.ts
const chatConfigOperations = { setChannelIdOperation(state, action) {
	state.channelId = action.input.channelId;
} };
//#endregion
//#region document-models/chat/v1/gen/messages/error.ts
var MessageNotFoundError = class extends Error {
	errorCode = "MessageNotFoundError";
	constructor(message = "MessageNotFoundError") {
		super(message);
	}
};
var MessageAlreadyPinnedError = class extends Error {
	errorCode = "MessageAlreadyPinnedError";
	constructor(message = "MessageAlreadyPinnedError") {
		super(message);
	}
};
var MessageNotPinnedError = class extends Error {
	errorCode = "MessageNotPinnedError";
	constructor(message = "MessageNotPinnedError") {
		super(message);
	}
};
//#endregion
//#region document-models/chat/v1/src/reducers/messages.ts
const chatMessagesOperations = {
	sendMessageOperation(state, action) {
		state.messages.push({
			id: action.input.id,
			authorId: action.input.authorId,
			content: action.input.content,
			timestamp: action.input.timestamp,
			edited: false,
			editedAt: null,
			replyToId: action.input.replyToId || null,
			reactions: [],
			attachments: (action.input.attachments || []).map((a) => ({
				id: a.id,
				type: a.type,
				url: a.url,
				title: a.title || null,
				description: a.description || null,
				thumbnailUrl: a.thumbnailUrl || null
			}))
		});
	},
	editMessageOperation(state, action) {
		const message = state.messages.find((m) => m.id === action.input.messageId);
		if (!message) throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);
		message.content = action.input.content;
		message.edited = true;
		message.editedAt = action.input.editedAt;
	},
	deleteMessageOperation(state, action) {
		const index = state.messages.findIndex((m) => m.id === action.input.messageId);
		if (index === -1) throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);
		const pinnedIndex = state.pinnedMessageIds.indexOf(action.input.messageId);
		if (pinnedIndex !== -1) state.pinnedMessageIds.splice(pinnedIndex, 1);
		state.messages.splice(index, 1);
	},
	pinMessageOperation(state, action) {
		if (!state.messages.find((m) => m.id === action.input.messageId)) throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);
		if (state.pinnedMessageIds.includes(action.input.messageId)) throw new MessageAlreadyPinnedError(`Message ${action.input.messageId} is already pinned`);
		state.pinnedMessageIds.push(action.input.messageId);
	},
	unpinMessageOperation(state, action) {
		const index = state.pinnedMessageIds.indexOf(action.input.messageId);
		if (index === -1) throw new MessageNotPinnedError(`Message ${action.input.messageId} is not pinned`);
		state.pinnedMessageIds.splice(index, 1);
	},
	addReactionOperation(state, action) {
		const message = state.messages.find((m) => m.id === action.input.messageId);
		if (!message) throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);
		const existingReaction = message.reactions.find((r) => r.emoji === action.input.emoji);
		if (existingReaction) {
			if (!existingReaction.participantIds.includes(action.input.participantId)) existingReaction.participantIds.push(action.input.participantId);
		} else message.reactions.push({
			id: action.input.id,
			emoji: action.input.emoji,
			participantIds: [action.input.participantId]
		});
	},
	removeReactionOperation(state, action) {
		const message = state.messages.find((m) => m.id === action.input.messageId);
		if (!message) throw new MessageNotFoundError(`Message ${action.input.messageId} not found`);
		const reaction = message.reactions.find((r) => r.emoji === action.input.emoji);
		if (reaction) {
			const pidIndex = reaction.participantIds.indexOf(action.input.participantId);
			if (pidIndex !== -1) reaction.participantIds.splice(pidIndex, 1);
			if (reaction.participantIds.length === 0) {
				const rIndex = message.reactions.indexOf(reaction);
				message.reactions.splice(rIndex, 1);
			}
		}
	}
};
//#endregion
//#region document-models/chat/v1/gen/schema/zod.ts
const isDefinedNonNullAny = (v) => v !== void 0 && v !== null;
const definedNonNullAnySchema = any().refine((v) => isDefinedNonNullAny(v));
const AttachmentTypeSchema = _enum([
	"FILE",
	"GIF",
	"IMAGE",
	"LINK"
]);
function AddReactionInputSchema() {
	return object({
		emoji: string(),
		id: string(),
		messageId: string(),
		participantId: string()
	});
}
function AttachmentSchema() {
	return object({
		__typename: literal("Attachment").optional(),
		description: string().nullish(),
		id: string(),
		thumbnailUrl: string().nullish(),
		title: string().nullish(),
		type: AttachmentTypeSchema,
		url: url()
	});
}
function AttachmentInputSchema() {
	return object({
		description: string().nullish(),
		id: string(),
		thumbnailUrl: string().nullish(),
		title: string().nullish(),
		type: AttachmentTypeSchema,
		url: url()
	});
}
function ChatStateSchema() {
	return object({
		__typename: literal("ChatState").optional(),
		channelId: string().nullish(),
		messages: array(lazy(() => MessageSchema())),
		pinnedMessageIds: array(string())
	});
}
function DeleteMessageInputSchema() {
	return object({ messageId: string() });
}
function EditMessageInputSchema() {
	return object({
		content: string(),
		editedAt: datetime(),
		messageId: string()
	});
}
function MessageSchema() {
	return object({
		__typename: literal("Message").optional(),
		attachments: array(lazy(() => AttachmentSchema())),
		authorId: string(),
		content: string(),
		edited: boolean(),
		editedAt: datetime().nullish(),
		id: string(),
		reactions: array(lazy(() => ReactionSchema())),
		replyToId: string().nullish(),
		timestamp: datetime()
	});
}
function PinMessageInputSchema() {
	return object({ messageId: string() });
}
function ReactionSchema() {
	return object({
		__typename: literal("Reaction").optional(),
		emoji: string(),
		id: string(),
		participantIds: array(string())
	});
}
function RemoveReactionInputSchema() {
	return object({
		emoji: string(),
		messageId: string(),
		participantId: string()
	});
}
function SendMessageInputSchema() {
	return object({
		attachments: array(lazy(() => AttachmentInputSchema())).nullish(),
		authorId: string(),
		content: string(),
		id: string(),
		replyToId: string().nullish(),
		timestamp: datetime()
	});
}
function SetChannelIdInputSchema() {
	return object({ channelId: string() });
}
function UnpinMessageInputSchema() {
	return object({ messageId: string() });
}
//#endregion
//#region document-models/chat/v1/gen/reducer.ts
const stateReducer = (state, action, dispatch) => {
	if (isDocumentAction(action)) return state;
	switch (action.type) {
		case "SET_CHANNEL_ID":
			SetChannelIdInputSchema().parse(action.input);
			chatConfigOperations.setChannelIdOperation(state[action.scope], action, dispatch);
			break;
		case "SEND_MESSAGE":
			SendMessageInputSchema().parse(action.input);
			chatMessagesOperations.sendMessageOperation(state[action.scope], action, dispatch);
			break;
		case "EDIT_MESSAGE":
			EditMessageInputSchema().parse(action.input);
			chatMessagesOperations.editMessageOperation(state[action.scope], action, dispatch);
			break;
		case "DELETE_MESSAGE":
			DeleteMessageInputSchema().parse(action.input);
			chatMessagesOperations.deleteMessageOperation(state[action.scope], action, dispatch);
			break;
		case "PIN_MESSAGE":
			PinMessageInputSchema().parse(action.input);
			chatMessagesOperations.pinMessageOperation(state[action.scope], action, dispatch);
			break;
		case "UNPIN_MESSAGE":
			UnpinMessageInputSchema().parse(action.input);
			chatMessagesOperations.unpinMessageOperation(state[action.scope], action, dispatch);
			break;
		case "ADD_REACTION":
			AddReactionInputSchema().parse(action.input);
			chatMessagesOperations.addReactionOperation(state[action.scope], action, dispatch);
			break;
		case "REMOVE_REACTION":
			RemoveReactionInputSchema().parse(action.input);
			chatMessagesOperations.removeReactionOperation(state[action.scope], action, dispatch);
			break;
		default: return state;
	}
};
const reducer = createReducer(stateReducer);
//#endregion
//#region document-models/chat/v1/gen/config/creators.ts
var creators_exports$1 = /* @__PURE__ */ __exportAll({ setChannelId: () => setChannelId });
const setChannelId = (input) => createAction("SET_CHANNEL_ID", { ...input }, void 0, SetChannelIdInputSchema, "global");
//#endregion
//#region document-models/chat/v1/gen/messages/creators.ts
var creators_exports = /* @__PURE__ */ __exportAll({
	addReaction: () => addReaction,
	deleteMessage: () => deleteMessage,
	editMessage: () => editMessage,
	pinMessage: () => pinMessage,
	removeReaction: () => removeReaction,
	sendMessage: () => sendMessage,
	unpinMessage: () => unpinMessage
});
const sendMessage = (input, attachments) => createAction("SEND_MESSAGE", { ...input }, attachments, SendMessageInputSchema, "global");
const editMessage = (input) => createAction("EDIT_MESSAGE", { ...input }, void 0, EditMessageInputSchema, "global");
const deleteMessage = (input) => createAction("DELETE_MESSAGE", { ...input }, void 0, DeleteMessageInputSchema, "global");
const pinMessage = (input) => createAction("PIN_MESSAGE", { ...input }, void 0, PinMessageInputSchema, "global");
const unpinMessage = (input) => createAction("UNPIN_MESSAGE", { ...input }, void 0, UnpinMessageInputSchema, "global");
const addReaction = (input) => createAction("ADD_REACTION", { ...input }, void 0, AddReactionInputSchema, "global");
const removeReaction = (input) => createAction("REMOVE_REACTION", { ...input }, void 0, RemoveReactionInputSchema, "global");
//#endregion
//#region document-models/chat/v1/actions.ts
/** Actions for the Chat document model */
const actions = {
	...baseActions,
	...creators_exports$1,
	...creators_exports
};
//#endregion
//#region document-models/chat/v1/gen/document-type.ts
const chatDocumentType = "powerchat/chat";
//#endregion
//#region document-models/chat/v1/gen/document-schema.ts
/** Schema for validating the header object of a Chat document */
const ChatDocumentHeaderSchema = BaseDocumentHeaderSchema.extend({ documentType: literal(chatDocumentType) });
/** Schema for validating the state object of a Chat document */
const ChatPHStateSchema = BaseDocumentStateSchema.extend({ global: ChatStateSchema() });
const ChatDocumentSchema = object({
	header: ChatDocumentHeaderSchema,
	state: ChatPHStateSchema,
	initialState: ChatPHStateSchema
});
/** Simple helper function to check if a state object is a Chat document state object */
function isChatState(state) {
	return ChatPHStateSchema.safeParse(state).success;
}
/** Simple helper function to assert that a document state object is a Chat document state object */
function assertIsChatState(state) {
	ChatPHStateSchema.parse(state);
}
/** Simple helper function to check if a document is a Chat document */
function isChatDocument(document) {
	return ChatDocumentSchema.safeParse(document).success;
}
/** Simple helper function to assert that a document is a Chat document */
function assertIsChatDocument(document) {
	ChatDocumentSchema.parse(document);
}
//#endregion
//#region document-models/chat/v1/gen/utils.ts
const initialGlobalState = {
	channelId: null,
	messages: [],
	pinnedMessageIds: []
};
const initialLocalState = {};
const utils$1 = {
	fileExtension: "pchat",
	createState(state) {
		return {
			...defaultBaseState(),
			global: {
				...initialGlobalState,
				...state?.global
			},
			local: {
				...initialLocalState,
				...state?.local
			}
		};
	},
	createDocument(state) {
		const document = baseCreateDocument(utils$1.createState, state);
		document.header.documentType = chatDocumentType;
		document.header.id = generateId();
		return document;
	},
	saveToFileHandle(document, input) {
		return baseSaveToFileHandle(document, input);
	},
	loadFromInput(input) {
		return baseLoadFromInput(input, reducer);
	},
	isStateOfType(state) {
		return isChatState(state);
	},
	assertIsStateOfType(state) {
		return assertIsChatState(state);
	},
	isDocumentOfType(document) {
		return isChatDocument(document);
	},
	assertIsDocumentOfType(document) {
		return assertIsChatDocument(document);
	}
};
//#endregion
//#region document-models/chat/v1/src/utils.ts
var utils_exports = /* @__PURE__ */ __exportAll({});
//#endregion
//#region document-models/chat/v1/utils.ts
/** Utils for the Chat document model */
const utils = {
	...utils$1,
	...utils_exports
};
//#endregion
//#region document-models/chat/v1/module.ts
/** Document model module for the Chat document type */
const Chat = {
	version: 1,
	reducer,
	actions,
	utils,
	documentModel: createState(defaultBaseState(), documentModel)
};
//#endregion
export { ChatStateSchema as A, definedNonNullAnySchema as B, creators_exports$1 as C, AttachmentInputSchema as D, AddReactionInputSchema as E, ReactionSchema as F, documentModel as H, RemoveReactionInputSchema as I, SendMessageInputSchema as L, EditMessageInputSchema as M, MessageSchema as N, AttachmentSchema as O, PinMessageInputSchema as P, SetChannelIdInputSchema as R, unpinMessage as S, reducer as T, isDefinedNonNullAny as V, deleteMessage as _, utils$1 as a, removeReaction as b, ChatPHStateSchema as c, isChatDocument as d, isChatState as f, creators_exports as g, addReaction as h, initialLocalState as i, DeleteMessageInputSchema as j, AttachmentTypeSchema as k, assertIsChatDocument as l, actions as m, utils as n, ChatDocumentHeaderSchema as o, chatDocumentType as p, initialGlobalState as r, ChatDocumentSchema as s, Chat as t, assertIsChatState as u, editMessage as v, setChannelId as w, sendMessage as x, pinMessage as y, UnpinMessageInputSchema as z };

//# sourceMappingURL=module-CADVf4FS.js.map