Initial commit

This commit is contained in:
root
2025-12-21 09:53:16 -05:00
committed by Sebastian Krupinski
commit a7ccac98a2
43 changed files with 6391 additions and 0 deletions

18
src/main.ts Normal file
View File

@@ -0,0 +1,18 @@
import { useCollectionsStore } from '@/stores/collectionsStore'
import { useEntitiesStore } from '@/stores/entitiesStore'
import { useProvidersStore } from '@/stores/providersStore'
import { useServicesStore } from '@/stores/servicesStore'
/**
* People Manager Module Boot Script
*
* This script is executed when the people_manager module is loaded.
* It initializes the peopleStore which manages contacts and address books state.
*/
console.log('[PeopleManager] Booting People Manager module...')
console.log('[PeopleManager] People Manager module booted successfully')
// Export store for external use if needed
export { useCollectionsStore, useEntitiesStore, useProvidersStore, useServicesStore }

139
src/models/collection.ts Normal file
View File

@@ -0,0 +1,139 @@
/**
* Class model for Collection Interface
*/
import type {
CollectionInterface,
CollectionContentsInterface,
CollectionPermissionsInterface,
CollectionRolesInterface
} from "@/types/collection";
export class CollectionObject implements CollectionInterface {
_data!: CollectionInterface;
constructor() {
this._data = {
'@type': 'people:collection',
provider: null,
service: null,
in: null,
id: null,
label: null,
description: null,
priority: null,
visibility: null,
color: null,
enabled: false,
signature: null,
permissions: {},
roles: {},
contents: {},
};
}
fromJson(data: CollectionInterface) : CollectionObject {
this._data = data;
return this;
}
toJson(): CollectionInterface {
return this._data;
}
clone(): CollectionObject {
const cloned = new CollectionObject()
cloned._data = JSON.parse(JSON.stringify(this._data))
return cloned
}
/** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get provider(): string | null {
return this._data.provider
}
get service(): string | null {
return this._data.service
}
get in(): number | string | null {
return this._data.in
}
get id(): number | string | null {
return this._data.id
}
get signature(): string | null {
return this._data.signature
}
get permissions(): CollectionPermissionsInterface {
return this._data.permissions
}
get roles(): CollectionRolesInterface {
return this._data.roles
}
get contents(): CollectionContentsInterface {
return this._data.contents
}
/** Mutable Properties */
get label(): string | null {
return this._data.label
}
set label(value: string ) {
this._data.label = value
}
get description(): string | null {
return this._data.description
}
set description(value: string ) {
this._data.description = value
}
get priority(): number | null {
return this._data.priority
}
set priority(value: number ) {
this._data.priority = value
}
get visibility(): string | null {
return this._data.visibility
}
set visibility(value: string ) {
this._data.visibility = value
}
get color(): string | null {
return this._data.color
}
set color(value: string ) {
this._data.color = value
}
get enabled(): boolean {
return this._data.enabled
}
set enabled(value: boolean ) {
this._data.enabled = value
}
}

153
src/models/entity.ts Normal file
View File

@@ -0,0 +1,153 @@
/**
* Class model for Entity Interface
*/
import type { EntityInterface } from "@/types/entity";
import type { IndividualInterface } from "@/types/individual";
import type { OrganizationInterface } from "@/types/organization";
import type { GroupInterface } from "@/types/group";
import { IndividualObject } from "./individual";
import { OrganizationObject } from "./organization";
import { GroupObject } from "./group";
export class EntityObject implements EntityInterface {
_data!: EntityInterface;
constructor() {
this._data = {
'@type': 'people:entity',
version: 1,
in: null,
id: null,
createdOn: null,
createdBy: null,
modifiedOn: null,
modifiedBy: null,
signature: null,
data: null,
};
}
fromJson(data: EntityInterface) : EntityObject {
this._data = data;
if (data.data) {
const type = data.data.type;
if (type === 'organization') {
this._data.data = new OrganizationObject().fromJson(data.data as OrganizationInterface);
} else if (type === 'group') {
this._data.data = new GroupObject().fromJson(data.data as GroupInterface);
} else {
this._data.data = new IndividualObject().fromJson(data.data as IndividualInterface);
}
} else {
this._data.data = null;
}
return this;
}
toJson(): EntityInterface {
const json = { ...this._data };
if (this._data.data instanceof IndividualObject ||
this._data.data instanceof OrganizationObject ||
this._data.data instanceof GroupObject) {
json.data = this._data.data.toJson();
}
return json;
}
clone(): EntityObject {
const cloned = new EntityObject()
cloned._data = JSON.parse(JSON.stringify(this._data))
return cloned
}
/** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get in(): number | string | null {
return this._data.in;
}
get id(): number | string | null {
return this._data.id;
}
get version(): number {
return this._data.version;
}
get createdOn(): Date | null {
return this._data.createdOn;
}
get createdBy(): string | null {
return this._data.createdBy;
}
get modifiedOn(): Date | null {
return this._data.modifiedOn;
}
get modifiedBy(): string | null {
return this._data.modifiedBy;
}
get signature(): string | null {
return this._data.signature;
}
/** Mutable Properties */
set createdOn(value: Date | null) {
this._data.createdOn = value;
}
set createdBy(value: string | null) {
this._data.createdBy = value;
}
set modifiedOn(value: Date | null) {
this._data.modifiedOn = value;
}
set modifiedBy(value: string | null) {
this._data.modifiedBy = value;
}
set signature(value: string | null) {
this._data.signature = value;
}
get data(): IndividualObject | OrganizationObject | GroupObject | null {
if (this._data.data instanceof IndividualObject ||
this._data.data instanceof OrganizationObject ||
this._data.data instanceof GroupObject) {
return this._data.data;
}
if (this._data.data) {
const type = this._data.data.type;
let hydrated;
if (type === 'organization') {
hydrated = new OrganizationObject().fromJson(this._data.data as OrganizationInterface);
} else if (type === 'group') {
hydrated = new GroupObject().fromJson(this._data.data as GroupInterface);
} else {
hydrated = new IndividualObject().fromJson(this._data.data as IndividualInterface);
}
this._data.data = hydrated;
return hydrated;
}
return null;
}
set data(value: IndividualObject | OrganizationObject | GroupObject | null) {
this._data.data = value;
}
}

262
src/models/group.ts Normal file
View File

@@ -0,0 +1,262 @@
/**
* Class model for Group Interface
*/
import { reactive } from 'vue'
import { generateUrid, generateKey } from "../utils/key-generator";
import type {
GroupInterface,
GroupName,
GroupMember,
GroupVirtualLocation,
GroupMedia,
GroupNote
} from '@/types/group';
export class GroupObject implements GroupInterface {
_data: GroupInterface;
constructor() {
this._data = reactive({
type: 'group',
version: 1,
urid: generateUrid(),
created: null,
modified: null,
label: '',
names: {
full: null,
sort: null,
aliases: []
},
members: {},
virtualLocations: {},
media: {},
tags: [],
notes: {},
});
}
fromJson(data: GroupInterface): GroupObject {
// Normalize arrays to Records for properties that should be Record types
const normalized = {
...data,
members: Array.isArray(data.members) ? {} : (data.members || {}),
virtualLocations: Array.isArray(data.virtualLocations) ? {} : (data.virtualLocations || {}),
media: Array.isArray(data.media) ? {} : (data.media || {}),
notes: Array.isArray(data.notes) ? {} : (data.notes || {}),
};
this._data = reactive(normalized);
return this;
}
toJson(): GroupInterface {
return this._data;
}
clone(): GroupObject {
const cloned = new GroupObject()
cloned._data = JSON.parse(JSON.stringify(this._data))
return cloned
}
/** Immutable Properties */
get type(): string {
return this._data.type;
}
get version(): number {
return this._data.version;
}
get urid(): string | null {
return this._data.urid;
}
/** Mutable Properties */
get created(): Date | null {
return this._data.created;
}
set created(value: Date | null) {
this._data.created = value;
}
get modified(): Date | null {
return this._data.modified;
}
set modified(value: Date | null) {
this._data.modified = value;
}
get label(): string | null {
return this._data.label;
}
set label(value: string | null) {
this._data.label = value;
}
get names(): GroupName {
return this._data.names;
}
set names(value: GroupName) {
this._data.names = value;
}
get members(): Record<string, GroupMember> {
return this._data.members;
}
set members(value: Record<string, GroupMember>) {
this._data.members = value;
}
get virtualLocations(): Record<string, GroupVirtualLocation> {
return this._data.virtualLocations;
}
set virtualLocations(value: Record<string, GroupVirtualLocation>) {
this._data.virtualLocations = value;
}
get media(): Record<string, GroupMedia> {
return this._data.media;
}
set media(value: Record<string, GroupMedia>) {
this._data.media = value;
}
get tags(): string[] {
return this._data.tags;
}
set tags(value: string[]) {
this._data.tags = value;
}
get notes(): Record<string, GroupNote> {
return this._data.notes;
}
set notes(value: Record<string, GroupNote>) {
this._data.notes = value;
}
/**
* Mutation helpers for complex properties
*/
addMember(initial?: Partial<GroupMember>): string {
const members = this._data.members || (this._data.members = {});
const key = generateKey();
members[key] = {
entityId: null,
role: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeMember(key: string): void {
if (this._data.members) {
delete this._data.members[key];
}
}
addVirtualLocation(initial?: Partial<GroupVirtualLocation>): string {
const virtualLocations = this._data.virtualLocations || (this._data.virtualLocations = {});
const key = generateKey();
virtualLocations[key] = {
location: null,
label: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeVirtualLocation(key: string): void {
if (this._data.virtualLocations) {
delete this._data.virtualLocations[key];
}
}
addMedia(initial?: Partial<GroupMedia>): string {
const media = this._data.media || (this._data.media = {});
const key = generateKey();
media[key] = {
type: "logo",
kind: "logo",
uri: "",
mediaType: null,
contexts: null,
pref: null,
label: null,
...initial,
};
return key;
}
removeMedia(key: string): void {
if (this._data.media) {
delete this._data.media[key];
}
}
addNote(initial?: Partial<GroupNote>): string {
const notes = this._data.notes || (this._data.notes = {});
const key = generateKey();
notes[key] = {
content: null,
date: null,
authorUri: null,
authorName: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeNote(key: string): void {
if (this._data.notes) {
delete this._data.notes[key];
}
}
addTag(value: string): void {
const tags = this._data.tags || (this._data.tags = []);
tags.push(value);
}
removeTag(value: string): void {
const tags = this._data.tags;
const index = tags.indexOf(value);
if (index >= 0) {
tags.splice(index, 1);
}
}
addAlias(value: string): void {
const aliases = this._data.names.aliases || (this._data.names.aliases = []);
aliases.push(value);
}
removeAlias(value: string): void {
const aliases = this._data.names.aliases;
const index = aliases.indexOf(value);
if (index >= 0) {
aliases.splice(index, 1);
}
}
}

11
src/models/index.ts Normal file
View File

@@ -0,0 +1,11 @@
/**
* Central export point for all People Manager models
*/
export { CollectionObject } from './collection';
export { EntityObject } from './entity';
export { GroupObject } from './group';
export { IndividualObject } from './individual';
export { OrganizationObject } from './organization';
export { ProviderObject } from './provider';
export { ServiceObject } from './service';

483
src/models/individual.ts Normal file
View File

@@ -0,0 +1,483 @@
/**
* Class model for Individual Interface
*/
import { reactive } from 'vue'
import { generateUrid, generateKey } from "../utils/key-generator";
import type {
IndividualAnniversary,
IndividualCrypto,
IndividualEmail,
IndividualInterface,
IndividualLanguage,
IndividualMedia,
IndividualName,
IndividualNote,
IndividualOrganization,
IndividualPhone,
IndividualPhysicalLocation,
IndividualTitle,
IndividualVirtualLocation
} from "@/types/individual";
export class IndividualObject implements IndividualInterface {
_data: IndividualInterface;
constructor() {
this._data = reactive({
type: 'individual',
version: 1,
urid: generateUrid(),
created: null,
modified: null,
label: '',
names: {
family: null,
given: null,
additional: null,
prefix: null,
suffix: null,
phoneticFamily: null,
phoneticGiven: null,
phoneticAdditional: null,
aliases: []
},
titles: {},
anniversaries: [],
physicalLocations: {},
phones: {},
emails: {},
virtualLocations: {},
media: {},
organizations: {},
tags: [],
notes: {},
language: null,
languages: [],
crypto: {},
});
}
fromJson(data: IndividualInterface) : IndividualObject {
// Normalize arrays to Records for properties that should be Record types
const normalized = {
...data,
titles: Array.isArray(data.titles) ? {} : (data.titles || {}),
physicalLocations: Array.isArray(data.physicalLocations) ? {} : (data.physicalLocations || {}),
phones: Array.isArray(data.phones) ? {} : (data.phones || {}),
emails: Array.isArray(data.emails) ? {} : (data.emails || {}),
virtualLocations: Array.isArray(data.virtualLocations) ? {} : (data.virtualLocations || {}),
media: Array.isArray(data.media) ? {} : (data.media || {}),
notes: Array.isArray(data.notes) ? {} : (data.notes || {}),
crypto: Array.isArray(data.crypto) ? {} : (data.crypto || {}),
};
this._data = reactive(normalized);
return this;
}
toJson(): IndividualInterface {
return this._data;
}
clone(): IndividualObject {
const cloned = new IndividualObject()
cloned._data = JSON.parse(JSON.stringify(this._data))
return cloned
}
/** Immutable Properties */
get type(): string {
return this._data.type;
}
get version(): number {
return this._data.version;
}
get urid(): string | null {
return this._data.urid;
}
/** Mutable Properties */
get created(): Date | null {
return this._data.created;
}
set created(value: Date | null) {
this._data.created = value;
}
get modified(): Date | null {
return this._data.modified;
}
set modified(value: Date | null) {
this._data.modified = value;
}
get label(): string | null {
return this._data.label;
}
set label(value: string | null) {
this._data.label = value;
}
get names(): IndividualName {
return this._data.names;
}
set names(value: IndividualName) {
this._data.names = value;
}
get titles(): Record<string, IndividualTitle> {
return this._data.titles;
}
set titles(value: Record<string, IndividualTitle>) {
this._data.titles = value;
}
get anniversaries(): IndividualAnniversary[] {
return this._data.anniversaries;
}
set anniversaries(value: IndividualAnniversary[]) {
this._data.anniversaries = value;
}
get physicalLocations(): Record<string, IndividualPhysicalLocation> {
return this._data.physicalLocations;
}
set physicalLocations(value: Record<string, IndividualPhysicalLocation>) {
this._data.physicalLocations = value;
}
get phones(): Record<string, IndividualPhone> {
return this._data.phones;
}
set phones(value: Record<string, IndividualPhone>) {
this._data.phones = value;
}
get emails(): Record<string, IndividualEmail> {
return this._data.emails;
}
set emails(value: Record<string, IndividualEmail>) {
this._data.emails = value;
}
get virtualLocations(): Record<string, IndividualVirtualLocation> {
return this._data.virtualLocations;
}
set virtualLocations(value: Record<string, IndividualVirtualLocation>) {
this._data.virtualLocations = value;
}
get media(): Record<string, IndividualMedia> {
return this._data.media;
}
set media(value: Record<string, IndividualMedia>) {
this._data.media = value;
}
get organizations(): Record<string, IndividualOrganization> {
return this._data.organizations;
}
set organizations(value: Record<string, IndividualOrganization>) {
this._data.organizations = value;
}
get tags(): string[] {
return this._data.tags;
}
set tags(value: string[]) {
this._data.tags = value;
}
get notes(): Record<string, IndividualNote> {
return this._data.notes;
}
set notes(value: Record<string, IndividualNote>) {
this._data.notes = value;
}
get language(): string | null {
return this._data.language;
}
set language(value: string | null) {
this._data.language = value;
}
get languages(): IndividualLanguage[] {
return this._data.languages;
}
set languages(value: IndividualLanguage[]) {
this._data.languages = value;
}
get crypto(): Record<string, IndividualCrypto> {
return this._data.crypto;
}
set crypto(value: Record<string, IndividualCrypto>) {
this._data.crypto = value;
}
/**
* Mutation helpers for complex properties
*/
addTitle(initial?: Partial<IndividualTitle>): string {
if (!this._data.titles) {
this._data.titles = {};
}
const key = generateKey();
this._data.titles[key] = {
kind: null,
label: null,
relation: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeTitle(key: string): void {
if (this._data.titles) {
delete this._data.titles[key];
}
}
addAnniversary(initial?: Partial<IndividualAnniversary>): number {
const anniversaries = this._data.anniversaries || (this._data.anniversaries = []);
const entry: IndividualAnniversary = {
type: null,
when: null,
location: null,
...initial,
};
anniversaries.push(entry);
return anniversaries.length - 1;
}
removeAnniversary(index: number): void {
const anniversaries = this._data.anniversaries;
if (index >= 0 && index < anniversaries.length) {
anniversaries.splice(index, 1);
}
}
addPhysicalLocation(initial?: Partial<IndividualPhysicalLocation>): string {
const locations = this._data.physicalLocations || (this._data.physicalLocations = {});
const key = generateKey();
locations[key] = {
box: null,
unit: null,
street: null,
locality: null,
region: null,
code: null,
country: null,
label: null,
coordinates: null,
timeZone: null,
context: null,
priority: null,
...initial,
};
return key;
}
removePhysicalLocation(key: string): void {
if (this._data.physicalLocations) {
delete this._data.physicalLocations[key];
}
}
addPhone(initial?: Partial<IndividualPhone>): string {
const phones = this._data.phones || (this._data.phones = {});
const key = generateKey();
phones[key] = {
number: null,
label: null,
context: null,
priority: null,
...initial,
};
return key;
}
removePhone(key: string): void {
if (this._data.phones) {
delete this._data.phones[key];
}
}
addEmail(initial?: Partial<IndividualEmail>): string {
const emails = this._data.emails || (this._data.emails = {});
const key = generateKey();
emails[key] = {
address: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeEmail(key: string): void {
if (this._data.emails) {
delete this._data.emails[key];
}
}
addVirtualLocation(initial?: Partial<IndividualVirtualLocation>): string {
const virtualLocations = this._data.virtualLocations || (this._data.virtualLocations = {});
const key = generateKey();
virtualLocations[key] = {
location: null,
label: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeVirtualLocation(key: string): void {
if (this._data.virtualLocations) {
delete this._data.virtualLocations[key];
}
}
addMedia(initial?: Partial<IndividualMedia>): string {
const media = this._data.media || (this._data.media = {});
const key = generateKey();
media[key] = {
type: "photo",
kind: "photo",
uri: "",
mediaType: null,
contexts: null,
pref: null,
label: null,
...initial,
};
return key;
}
removeMedia(key: string): void {
if (this._data.media) {
delete this._data.media[key];
}
}
addOrganization(initial?: Partial<IndividualOrganization>): string {
const organizations = this._data.organizations || (this._data.organizations = {});
const key = generateKey();
organizations[key] = {
Label: null,
Units: [],
sortName: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeOrganization(key: string): void {
if (this._data.organizations) {
delete this._data.organizations[key];
}
}
addNote(initial?: Partial<IndividualNote>): string {
const notes = this._data.notes || (this._data.notes = {});
const key = generateKey();
notes[key] = {
content: null,
date: null,
authorUri: null,
authorName: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeNote(key: string): void {
if (this._data.notes) {
delete this._data.notes[key];
}
}
addLanguage(initial?: Partial<IndividualLanguage>): number {
const languages = this._data.languages || (this._data.languages = []);
const entry: IndividualLanguage = {
Data: null,
Id: null,
Priority: null,
Context: null,
...initial,
};
languages.push(entry);
return languages.length - 1;
}
removeLanguage(index: number): void {
const languages = this._data.languages;
if (index >= 0 && index < languages.length) {
languages.splice(index, 1);
}
}
addCrypto(initial?: Partial<IndividualCrypto>): string {
const cryptoEntries = this._data.crypto || (this._data.crypto = {});
const key = generateKey();
cryptoEntries[key] = {
data: null,
type: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeCrypto(key: string): void {
if (this._data.crypto) {
delete this._data.crypto[key];
}
}
addTag(value: string): void {
const tags = this._data.tags || (this._data.tags = []);
tags.push(value);
}
removeTag(value: string): void {
const tags = this._data.tags;
const index = tags.indexOf(value);
if (index >= 0) {
tags.splice(index, 1);
}
}
}

359
src/models/organization.ts Normal file
View File

@@ -0,0 +1,359 @@
/**
* Class model for Organization Interface
*/
import { reactive } from 'vue'
import { generateUrid, generateKey } from "../utils/key-generator";
import type {
OrganizationInterface,
OrganizationName,
OrganizationPhysicalLocation,
OrganizationPhone,
OrganizationEmail,
OrganizationVirtualLocation,
OrganizationMedia,
OrganizationNote,
OrganizationCrypto
} from "@/types/organization";
export class OrganizationObject implements OrganizationInterface {
_data: OrganizationInterface;
constructor() {
this._data = reactive({
type: 'organization',
version: 1,
urid: generateUrid(),
created: null,
modified: null,
label: '',
names: {
full: null,
sort: null,
aliases: []
},
physicalLocations: {},
phones: {},
emails: {},
virtualLocations: {},
media: {},
tags: [],
notes: {},
crypto: {},
});
}
fromJson(data: OrganizationInterface): OrganizationObject {
// Normalize arrays to Records for properties that should be Record types
const normalized = {
...data,
physicalLocations: Array.isArray(data.physicalLocations) ? {} : (data.physicalLocations || {}),
phones: Array.isArray(data.phones) ? {} : (data.phones || {}),
emails: Array.isArray(data.emails) ? {} : (data.emails || {}),
virtualLocations: Array.isArray(data.virtualLocations) ? {} : (data.virtualLocations || {}),
media: Array.isArray(data.media) ? {} : (data.media || {}),
notes: Array.isArray(data.notes) ? {} : (data.notes || {}),
crypto: Array.isArray(data.crypto) ? {} : (data.crypto || {}),
};
this._data = reactive(normalized);
return this;
}
toJson(): OrganizationInterface {
return this._data;
}
clone(): OrganizationObject {
const cloned = new OrganizationObject()
cloned._data = JSON.parse(JSON.stringify(this._data))
return cloned
}
/** Immutable Properties */
get type(): string {
return this._data.type;
}
get version(): number {
return this._data.version;
}
get urid(): string | null {
return this._data.urid;
}
/** Mutable Properties */
get created(): Date | null {
return this._data.created;
}
set created(value: Date | null) {
this._data.created = value;
}
get modified(): Date | null {
return this._data.modified;
}
set modified(value: Date | null) {
this._data.modified = value;
}
get label(): string | null {
return this._data.label;
}
set label(value: string | null) {
this._data.label = value;
}
get names(): OrganizationName {
return this._data.names;
}
set names(value: OrganizationName) {
this._data.names = value;
}
get physicalLocations(): Record<string, OrganizationPhysicalLocation> {
return this._data.physicalLocations;
}
set physicalLocations(value: Record<string, OrganizationPhysicalLocation>) {
this._data.physicalLocations = value;
}
get phones(): Record<string, OrganizationPhone> {
return this._data.phones;
}
set phones(value: Record<string, OrganizationPhone>) {
this._data.phones = value;
}
get emails(): Record<string, OrganizationEmail> {
return this._data.emails;
}
set emails(value: Record<string, OrganizationEmail>) {
this._data.emails = value;
}
get virtualLocations(): Record<string, OrganizationVirtualLocation> {
return this._data.virtualLocations;
}
set virtualLocations(value: Record<string, OrganizationVirtualLocation>) {
this._data.virtualLocations = value;
}
get media(): Record<string, OrganizationMedia> {
return this._data.media;
}
set media(value: Record<string, OrganizationMedia>) {
this._data.media = value;
}
get tags(): string[] {
return this._data.tags;
}
set tags(value: string[]) {
this._data.tags = value;
}
get notes(): Record<string, OrganizationNote> {
return this._data.notes;
}
set notes(value: Record<string, OrganizationNote>) {
this._data.notes = value;
}
get crypto(): Record<string, OrganizationCrypto> {
return this._data.crypto;
}
set crypto(value: Record<string, OrganizationCrypto>) {
this._data.crypto = value;
}
/**
* Mutation helpers for complex properties
*/
addPhysicalLocation(initial?: Partial<OrganizationPhysicalLocation>): string {
const locations = this._data.physicalLocations || (this._data.physicalLocations = {});
const key = generateKey();
locations[key] = {
box: null,
unit: null,
street: null,
locality: null,
region: null,
code: null,
country: null,
label: null,
coordinates: null,
timeZone: null,
context: null,
priority: null,
...initial,
};
return key;
}
removePhysicalLocation(key: string): void {
if (this._data.physicalLocations) {
delete this._data.physicalLocations[key];
}
}
addPhone(initial?: Partial<OrganizationPhone>): string {
const phones = this._data.phones || (this._data.phones = {});
const key = generateKey();
phones[key] = {
number: null,
label: null,
context: null,
priority: null,
...initial,
};
return key;
}
removePhone(key: string): void {
if (this._data.phones) {
delete this._data.phones[key];
}
}
addEmail(initial?: Partial<OrganizationEmail>): string {
const emails = this._data.emails || (this._data.emails = {});
const key = generateKey();
emails[key] = {
address: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeEmail(key: string): void {
if (this._data.emails) {
delete this._data.emails[key];
}
}
addVirtualLocation(initial?: Partial<OrganizationVirtualLocation>): string {
const virtualLocations = this._data.virtualLocations || (this._data.virtualLocations = {});
const key = generateKey();
virtualLocations[key] = {
location: null,
label: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeVirtualLocation(key: string): void {
if (this._data.virtualLocations) {
delete this._data.virtualLocations[key];
}
}
addMedia(initial?: Partial<OrganizationMedia>): string {
const media = this._data.media || (this._data.media = {});
const key = generateKey();
media[key] = {
type: "logo",
kind: "logo",
uri: "",
mediaType: null,
contexts: null,
pref: null,
label: null,
...initial,
};
return key;
}
removeMedia(key: string): void {
if (this._data.media) {
delete this._data.media[key];
}
}
addNote(initial?: Partial<OrganizationNote>): string {
const notes = this._data.notes || (this._data.notes = {});
const key = generateKey();
notes[key] = {
content: null,
date: null,
authorUri: null,
authorName: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeNote(key: string): void {
if (this._data.notes) {
delete this._data.notes[key];
}
}
addCrypto(initial?: Partial<OrganizationCrypto>): string {
const cryptoEntries = this._data.crypto || (this._data.crypto = {});
const key = generateKey();
cryptoEntries[key] = {
data: null,
type: null,
context: null,
priority: null,
...initial,
};
return key;
}
removeCrypto(key: string): void {
if (this._data.crypto) {
delete this._data.crypto[key];
}
}
addTag(value: string): void {
const tags = this._data.tags || (this._data.tags = []);
tags.push(value);
}
removeTag(value: string): void {
const tags = this._data.tags;
const index = tags.indexOf(value);
if (index >= 0) {
tags.splice(index, 1);
}
}
addAlias(value: string): void {
const aliases = this._data.names.aliases || (this._data.names.aliases = []);
aliases.push(value);
}
removeAlias(value: string): void {
const aliases = this._data.names.aliases;
const index = aliases.indexOf(value);
if (index >= 0) {
aliases.splice(index, 1);
}
}
}

61
src/models/provider.ts Normal file
View File

@@ -0,0 +1,61 @@
/**
* Class model for Provider Interface
*/
import type {
ProviderInterface,
ProviderCapabilitiesInterface
} from "@/types/provider";
export class ProviderObject implements ProviderInterface {
_data!: ProviderInterface;
constructor() {
this._data = {
'@type': 'people:provider',
id: '',
label: '',
capabilities: {},
};
}
fromJson(data: ProviderInterface): ProviderObject {
this._data = data;
return this;
}
toJson(): ProviderInterface {
return this._data;
}
capable(capability: keyof ProviderCapabilitiesInterface): boolean {
return !!(this._data.capabilities && this._data.capabilities[capability]);
}
capability(capability: keyof ProviderCapabilitiesInterface): any | null {
if (this._data.capabilities) {
return this._data.capabilities[capability];
}
return null;
}
/** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get id(): string {
return this._data.id;
}
get label(): string {
return this._data.label;
}
get capabilities(): ProviderCapabilitiesInterface {
return this._data.capabilities;
}
}

81
src/models/service.ts Normal file
View File

@@ -0,0 +1,81 @@
/**
* Class model for Service Interface
*/
import type {
ServiceInterface,
ServiceCapabilitiesInterface
} from "@/types/service";
export class ServiceObject implements ServiceInterface {
_data!: ServiceInterface;
constructor() {
this._data = {
'@type': 'people:service',
provider: '',
id: '',
label: '',
capabilities: {},
enabled: false,
};
}
fromJson(data: ServiceInterface): ServiceObject {
this._data = data;
return this;
}
toJson(): ServiceInterface {
return this._data;
}
capable(capability: keyof ServiceCapabilitiesInterface): boolean {
return !!(this._data.capabilities && this._data.capabilities[capability]);
}
capability(capability: keyof ServiceCapabilitiesInterface): any | null {
if (this._data.capabilities) {
return this._data.capabilities[capability];
}
return null;
}
/** Immutable Properties */
get '@type'(): string {
return this._data['@type'];
}
get provider(): string {
return this._data.provider;
}
get id(): string {
return this._data.id;
}
get capabilities(): ServiceCapabilitiesInterface | undefined {
return this._data.capabilities;
}
/** Mutable Properties */
get label(): string {
return this._data.label;
}
set label(value: string) {
this._data.label = value;
}
get enabled(): boolean {
return this._data.enabled;
}
set enabled(value: boolean) {
this._data.enabled = value;
}
}

View File

@@ -0,0 +1,84 @@
/**
* Collection management service
*/
import { transceivePost } from './transceive';
import type {
CollectionListRequest,
CollectionListResponse,
CollectionExtantRequest,
CollectionExtantResponse,
CollectionFetchRequest,
CollectionFetchResponse,
CollectionCreateRequest,
CollectionCreateResponse,
CollectionModifyRequest,
CollectionModifyResponse,
CollectionDestroyRequest,
CollectionDestroyResponse,
} from '../types/collection';
export const collectionService = {
/**
* List all available collections
*
* @param request - Collection list request parameters
* @returns Promise with collection list grouped by provider and service
*/
async list(request: CollectionListRequest = {}): Promise<CollectionListResponse> {
return await transceivePost<CollectionListRequest, CollectionListResponse>('collection.list', request);
},
/**
* Check which collections exist/are available
*
* @param request - Collection extant request with source selector
* @returns Promise with collection availability status
*/
async extant(request: CollectionExtantRequest): Promise<CollectionExtantResponse> {
return await transceivePost('collection.extant', request);
},
/**
* Fetch a specific collection
*
* @param request - Collection fetch request
* @returns Promise with collection details
*/
async fetch(request: CollectionFetchRequest): Promise<CollectionFetchResponse> {
return await transceivePost('collection.fetch', request);
},
/**
* Create a new collection
*
* @param request - Collection create request
* @returns Promise with created collection
*/
async create(request: CollectionCreateRequest): Promise<CollectionCreateResponse> {
return await transceivePost('collection.create', request);
},
/**
* Modify an existing collection
*
* @param request - Collection modify request
* @returns Promise with modified collection
*/
async modify(request: CollectionModifyRequest): Promise<CollectionModifyResponse> {
return await transceivePost('collection.modify', request);
},
/**
* Delete a collection
*
* @param request - Collection destroy request
* @returns Promise with deletion result
*/
async destroy(request: CollectionDestroyRequest): Promise<CollectionDestroyResponse> {
return await transceivePost('collection.destroy', request);
},
};
export default collectionService;

View File

@@ -0,0 +1,96 @@
/**
* Entity management service
*/
import { transceivePost } from './transceive';
import type {
EntityListRequest,
EntityListResponse,
EntityDeltaRequest,
EntityDeltaResponse,
EntityExtantRequest,
EntityExtantResponse,
EntityFetchRequest,
EntityFetchResponse,
EntityCreateRequest,
EntityCreateResponse,
EntityModifyRequest,
EntityModifyResponse,
EntityDestroyRequest,
EntityDestroyResponse,
} from '../types/entity';
export const entityService = {
/**
* List all available entities (events, tasks, journals)
*
* @param request - Entity list request parameters
* @returns Promise with entity list grouped by provider, service, and collection
*/
async list(request: EntityListRequest = {}): Promise<EntityListResponse> {
return await transceivePost<EntityListRequest, EntityListResponse>('entity.list', request);
},
/**
* Get delta changes for entities
*
* @param request - Entity delta request with source selector
* @returns Promise with delta changes (created, modified, deleted)
*/
async delta(request: EntityDeltaRequest): Promise<EntityDeltaResponse> {
return await transceivePost('entity.delta', request);
},
/**
* Check which entities exist/are available
*
* @param request - Entity extant request with source selector
* @returns Promise with entity availability status
*/
async extant(request: EntityExtantRequest): Promise<EntityExtantResponse> {
return await transceivePost('entity.extant', request);
},
/**
* Fetch specific entities
*
* @param request - Entity fetch request
* @returns Promise with entity details
*/
async fetch(request: EntityFetchRequest): Promise<EntityFetchResponse> {
return await transceivePost('entity.fetch', request);
},
/**
* Create a new entity
*
* @param request - Entity create request
* @returns Promise with created entity
*/
async create(request: EntityCreateRequest): Promise<EntityCreateResponse> {
return await transceivePost('entity.create', request);
},
/**
* Modify an existing entity
*
* @param request - Entity modify request
* @returns Promise with modified entity
*/
async modify(request: EntityModifyRequest): Promise<EntityModifyResponse> {
return await transceivePost('entity.modify', request);
},
/**
* Delete an entity
*
* @param request - Entity destroy request
* @returns Promise with deletion result
*/
async destroy(request: EntityDestroyRequest): Promise<EntityDestroyResponse> {
return await transceivePost('entity.destroy', request);
},
};
export default entityService;

16
src/services/index.ts Normal file
View File

@@ -0,0 +1,16 @@
/**
* Central export point for all People Manager services
*/
// Services
export { providerService } from './providerService';
export { serviceService } from './serviceService';
export { collectionService } from './collectionService';
export { entityService } from './entityService';
// Type exports
export type * from '../types/common';
export type * from '../types/provider';
export type * from '../types/service';
export type * from '../types/collection';
export type * from '../types/entity';

View File

@@ -0,0 +1,32 @@
/**
* Provider management service
*/
import { transceivePost } from './transceive';
import type { ProviderListResponse, ProviderExtantResponse } from '../types/provider';
import type { SourceSelector } from '../types/common';
export const providerService = {
/**
* List all available providers
*
* @returns Promise with provider list keyed by provider ID
*/
async list(): Promise<ProviderListResponse> {
return await transceivePost<{}, ProviderListResponse>('provider.list', {});
},
/**
* Check which providers exist/are available
*
* @param sources - Source selector with provider IDs to check
*
* @returns Promise with provider availability status
*/
async extant(sources: SourceSelector): Promise<ProviderExtantResponse> {
return await transceivePost('provider.extant', { sources });
},
};
export default providerService;

View File

@@ -0,0 +1,48 @@
/**
* Service management service
*/
import { transceivePost } from './transceive';
import type {
ServiceListRequest,
ServiceListResponse,
ServiceExtantRequest,
ServiceExtantResponse,
ServiceFetchRequest,
ServiceFetchResponse,
} from '../types/service';
export const serviceService = {
/**
* List all available services
*
* @param request - Service list request parameters
* @returns Promise with service list grouped by provider
*/
async list(request: ServiceListRequest = {}): Promise<ServiceListResponse> {
return await transceivePost<ServiceListRequest, ServiceListResponse>('service.list', request);
},
/**
* Check which services exist/are available
*
* @param request - Service extant request with source selector
* @returns Promise with service availability status
*/
async extant(request: ServiceExtantRequest): Promise<ServiceExtantResponse> {
return await transceivePost('service.extant', request);
},
/**
* Fetch a specific service
*
* @param request - Service fetch request with provider and service IDs
* @returns Promise with service details
*/
async fetch(request: ServiceFetchRequest): Promise<ServiceFetchResponse> {
return await transceivePost('service.fetch', request);
},
};
export default serviceService;

View File

@@ -0,0 +1,50 @@
/**
* API Client for People Manager
* Provides a centralized way to make API calls with envelope wrapping/unwrapping
*/
import { createFetchWrapper } from '@KTXC/utils/helpers/fetch-wrapper-core';
import type { ApiRequest, ApiResponse } from '../types/common';
const fetchWrapper = createFetchWrapper();
const API_URL = '/m/people_manager/v1';
const API_VERSION = 1;
/**
* Generate a unique transaction ID
*/
export function generateTransactionId(): string {
return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
}
/**
* Make an API call with automatic envelope wrapping and unwrapping
*
* @param operation - Operation name (e.g., 'provider.list', 'collection.fetch')
* @param data - Operation-specific request data
* @param user - Optional user identifier override
* @returns Promise with unwrapped response data
* @throws Error if the API returns an error status
*/
export async function transceivePost<TRequest, TResponse>(
operation: string,
data: TRequest,
user?: string
): Promise<TResponse> {
const request: ApiRequest<TRequest> = {
version: API_VERSION,
transaction: generateTransactionId(),
operation,
data,
user
};
const response: ApiResponse<TResponse> = await fetchWrapper.post(API_URL, request);
if (response.status === 'error') {
const errorMessage = `[${operation}] ${response.data.message}${response.data.code ? ` (code: ${response.data.code})` : ''}`;
throw new Error(errorMessage);
}
return response.data;
}

View File

@@ -0,0 +1,203 @@
/**
* People Manager - Collections Store
*/
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { collectionService } from '../services/collectionService';
import type {
SourceSelector,
ListFilter,
ListSort,
} from '../types/common';
import { CollectionObject } from '../models/collection';
import type { ServiceObject } from '../models/service';
import type { CollectionInterface } from '../types/collection';
export const useCollectionsStore = defineStore('collectionsStore', () => {
// State
const collections = ref<CollectionObject[]>([]);
// Actions
/**
* Retrieve collections from the server
*/
async function list(
sources?: SourceSelector,
filter?: ListFilter,
sort?: ListSort,
uid?: string
): Promise<CollectionObject[]> {
try {
const response = await collectionService.list({ sources, filter, sort, uid });
// Flatten the nested response into a flat array
const flatCollections: CollectionObject[] = [];
Object.entries(response).forEach(([_providerId, providerCollections]) => {
Object.entries(providerCollections).forEach(([_serviceId, serviceCollections]) => {
Object.values(serviceCollections).forEach((collection: CollectionInterface) => {
flatCollections.push(new CollectionObject().fromJson(collection));
});
});
});
console.debug('[People Manager](Store) - Successfully retrieved', flatCollections.length, 'collections:', flatCollections.map(c => ({
id: c.id,
label: c.label,
service: c.service,
provider: c.provider
})));
collections.value = flatCollections;
return flatCollections;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to retrieve collections:', error);
throw error;
}
}
/**
* Fetch a specific collection
*/
async function fetch(
provider: string,
service: string,
identifier: string | number,
uid?: string
): Promise<CollectionObject | null> {
try {
const response = await collectionService.fetch({ provider, service, identifier, uid });
return new CollectionObject().fromJson(response);
} catch (error: any) {
console.error('[People Manager](Store) - Failed to fetch collection:', error);
throw error;
}
}
/**
* Create a fresh collection object with default values
*/
function fresh(): CollectionObject {
return new CollectionObject();
}
/**
* Create a new collection
*/
async function create(
service: ServiceObject,
collection: CollectionObject,
options?: string[],
uid?: string
): Promise<CollectionObject | null> {
try {
if (service.provider === null || service.id === null) {
throw new Error('Invalid service object, must have a provider and identifier');
}
const response = await collectionService.create({
provider: service.provider,
service: service.id,
data: collection.toJson(),
options,
uid
});
const createdCollection = new CollectionObject().fromJson(response);
collections.value.push(createdCollection);
console.debug('[People Manager](Store) - Successfully created collection');
return createdCollection;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to create collection:', error);
throw error;
}
}
/**
* Modify an existing collection
*/
async function modify(
collection: CollectionObject,
uid?: string
): Promise<CollectionObject | null> {
try {
if (!collection.provider || !collection.service || !collection.id) {
throw new Error('Collection must have provider, service, and id');
}
const response = await collectionService.modify({
provider: collection.provider,
service: collection.service,
identifier: collection.id,
data: collection.toJson(),
uid
});
const modifiedCollection = new CollectionObject().fromJson(response);
const index = collections.value.findIndex(c => c.id === collection.id);
if (index !== -1) {
collections.value[index] = modifiedCollection;
}
console.debug('[People Manager](Store) - Successfully modified collection');
return modifiedCollection;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to modify collection:', error);
throw error;
}
}
/**
* Delete a collection
*/
async function destroy(
collection: CollectionObject,
uid?: string
): Promise<boolean> {
try {
if (!collection.provider || !collection.service || !collection.id) {
throw new Error('Collection must have provider, service, and id');
}
const response = await collectionService.destroy({
provider: collection.provider,
service: collection.service,
identifier: collection.id,
uid
});
if (response.success) {
const index = collections.value.findIndex(c => c.id === collection.id);
if (index !== -1) {
collections.value.splice(index, 1);
}
}
console.debug('[People Manager](Store) - Successfully destroyed collection');
return response.success;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to destroy collection:', error);
throw error;
}
}
return {
// State
collections,
// Actions
list,
fetch,
fresh,
create,
modify,
destroy,
};
});

276
src/stores/entitiesStore.ts Normal file
View File

@@ -0,0 +1,276 @@
/**
* People Manager - Entities Store
*/
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { entityService } from '../services/entityService';
import type {
SourceSelector,
ListFilter,
ListSort,
ListRange,
} from '../types/common';
import type {
EntityInterface,
} from '../types/entity';
import type { CollectionObject } from '../models/collection';
import { EntityObject } from '../models/entity'
import { IndividualObject } from '../models/individual';
import { OrganizationObject } from '../models/organization';
import { GroupObject } from '../models/group';
export const useEntitiesStore = defineStore('peopleEntitiesStore', () => {
// State
const entities = ref<EntityObject[]>([]);
// Actions
/**
* Reset the store to initial state
*/
function reset(): void {
entities.value = [];
}
/**
* List entities for all or specific collection
*/
async function list(
provider: string | null,
service: string | null,
collection: string | number | null,
filter?: ListFilter,
sort?: ListSort,
range?: ListRange,
uid?: string
): Promise<EntityObject[]> {
try {
// Validate hierarchical requirements
if (collection !== null && (service === null || provider === null)) {
throw new Error('Collection requires both service and provider');
}
if (service !== null && provider === null) {
throw new Error('Service requires provider');
}
// Build sources object level by level
const sources: SourceSelector = {};
if (provider !== null) {
if (service !== null) {
if (collection !== null) {
sources[provider] = { [service]: { [collection]: true } };
} else {
sources[provider] = { [service]: true };
}
} else {
sources[provider] = true;
}
}
// Transmit
const response = await entityService.list({ sources, filter, sort, range, uid });
// Flatten the nested response into a flat array
const flatEntities: EntityObject[] = [];
Object.entries(response).forEach(([, providerEntities]) => {
Object.entries(providerEntities).forEach(([, serviceEntities]) => {
Object.entries(serviceEntities).forEach(([, collectionEntities]) => {
Object.values(collectionEntities).forEach((entity: EntityInterface) => {
flatEntities.push(new EntityObject().fromJson(entity));
});
});
});
});
console.debug('[People Manager](Store) - Successfully retrieved', flatEntities.length, 'entities');
entities.value = flatEntities;
return flatEntities;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to retrieve entities:', error);
throw error;
}
}
/**
* Fetch entities for a specific collection
*/
async function fetch(
collection: CollectionObject,
identifiers: (string | number)[],
uid?: string
): Promise<EntityObject[]> {
try {
if (!collection.provider || !collection.service || !collection.id) {
throw new Error('Collection must have provider, service, and id');
}
const response = await entityService.fetch({
provider: collection.provider,
service: collection.service,
collection: collection.id,
identifiers,
uid
});
return Object.values(response).map(entity => new EntityObject().fromJson(entity));
} catch (error: any) {
console.error('[People Manager](Store) - Failed to fetch entities:', error);
throw error;
}
}
/**
* Create a fresh entity object
*/
function fresh(type: string): EntityObject {
const entity = new EntityObject();
if (type === 'organization') {
entity.data = new OrganizationObject();
} else if (type === 'group') {
entity.data = new GroupObject();
} else {
entity.data = new IndividualObject();
}
entity.data.created = new Date();
return entity;
}
/**
* Create a new entity
*/
async function create(
collection: CollectionObject,
entity: EntityObject,
options?: string[],
uid?: string
): Promise<EntityObject | null> {
try {
if (!collection.provider || !collection.service || !collection.id) {
throw new Error('Collection must have provider, service, and id');
}
const response = await entityService.create({
provider: collection.provider,
service: collection.service,
collection: collection.id,
data: entity.toJson(),
options,
uid
});
const createdEntity = new EntityObject().fromJson(response);
entities.value.push(createdEntity);
console.debug('[People Manager](Store) - Successfully created entity');
return createdEntity;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to create entity:', error);
throw error;
}
}
/**
* Modify an existing entity
*/
async function modify(
collection: CollectionObject,
entity: EntityObject,
uid?: string
): Promise<EntityObject | null> {
try {
if (!collection.provider || !collection.service || !collection.id) {
throw new Error('Collection must have provider, service, and id');
}
if (!entity.in || !entity.id) {
throw new Error('Invalid entity object, must have an collection and entity identifier');
}
if (collection.id !== entity.in) {
throw new Error('Invalid entity object, does not belong to the specified collection');
}
const response = await entityService.modify({
provider: collection.provider,
service: collection.service,
collection: collection.id,
identifier: entity.id,
data: entity.toJson(),
uid
});
const modifiedEntity = new EntityObject().fromJson(response);
const index = entities.value.findIndex(e => e.id === entity.id);
if (index !== -1) {
entities.value[index] = modifiedEntity;
}
console.debug('[People Manager](Store) - Successfully modified entity');
return modifiedEntity;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to modify entity:', error);
throw error;
}
}
/**
* Delete an entity
*/
async function destroy(
collection: CollectionObject,
entity: EntityObject,
uid?: string
): Promise<boolean> {
try {
if (!collection.provider || !collection.service || !collection.id) {
throw new Error('Collection must have provider, service, and id');
}
if (!entity.in || !entity.id) {
throw new Error('Invalid entity object, must have an collection and entity identifier');
}
if (collection.id !== entity.in) {
throw new Error('Invalid entity object, does not belong to the specified collection');
}
const response = await entityService.destroy({
provider: collection.provider,
service: collection.service,
collection: collection.id,
identifier: entity.id,
uid
});
if (response.success) {
const index = entities.value.findIndex(e => e.id === entity.id);
if (index !== -1) {
entities.value.splice(index, 1);
}
}
console.debug('[People Manager](Store) - Successfully destroyed entity');
return response.success;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to destroy entity:', error);
throw error;
}
}
return {
// State
entities,
// Actions
reset,
list,
fetch,
fresh,
create,
modify,
destroy,
}
});

8
src/stores/index.ts Normal file
View File

@@ -0,0 +1,8 @@
/**
* Central export point for all People Manager stores
*/
export { useCollectionsStore } from './collectionsStore';
export { useEntitiesStore } from './entitiesStore';
export { useProvidersStore } from './providersStore';
export { useServicesStore } from './servicesStore';

View File

@@ -0,0 +1,62 @@
/**
* People Manager - Providers Store
*/
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { providerService } from '../services/providerService';
import type {
SourceSelector,
ProviderInterface,
} from '../types';
export const useProvidersStore = defineStore('providersStore', () => {
// State
const providers = ref<Record<string, ProviderInterface>>({});
// Actions
/**
* List all available providers
*
* @returns Promise with provider list keyed by provider ID
*/
async function list(): Promise<Record<string, ProviderInterface>> {
try {
const response = await providerService.list();
console.debug('[People Manager](Store) - Successfully retrieved', Object.keys(response).length, 'providers:', Object.keys(response));
providers.value = response;
return response;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to retrieve providers:', error);
throw error;
}
}
/**
* Check which providers exist/are available
*
* @param sources - Source selector with provider IDs to check
* @returns Promise with provider availability status
*/
async function extant(sources: SourceSelector): Promise<Record<string, boolean>> {
try {
const response = await providerService.extant(sources);
return response;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to check provider existence:', error);
throw error;
}
}
return {
// State
providers,
// Actions
list,
extant,
};
});

View File

@@ -0,0 +1,95 @@
/**
* People Manager - Services Store
*/
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { serviceService } from '../services/serviceService';
import { ServiceObject } from '../models/service';
import type { ServiceInterface } from '../types/service';
import type {
SourceSelector,
ListFilter,
ListSort,
} from '../types/common';
export const useServicesStore = defineStore('peopleServicesStore', () => {
// State
const services = ref<ServiceObject[]>([]);
// Actions
/**
* Retrieve services from the server
*/
async function list(
sources?: SourceSelector,
filter?: ListFilter,
sort?: ListSort,
uid?: string
): Promise<ServiceObject[]> {
try {
const response = await serviceService.list({ sources, filter, sort, uid });
// Flatten the nested response into a flat array
const flatServices: ServiceObject[] = [];
Object.entries(response).forEach(([providerId, providerServices]) => {
Object.values(providerServices).forEach((service: ServiceInterface) => {
// Ensure provider is set on the service object
service.provider = service.provider || providerId;
flatServices.push(new ServiceObject().fromJson(service));
});
});
console.debug('[People Manager](Store) - Successfully retrieved', flatServices.length, 'services:', flatServices.map(s => ({
id: s.id,
label: s.label,
provider: s.provider
})));
services.value = flatServices;
return flatServices;
} catch (error: any) {
console.error('[People Manager](Store) - Failed to retrieve services:', error);
throw error;
}
}
/**
* Fetch a specific service
*
* @param provider - Provider identifier
* @param identifier - Service identifier
* @param uid - Optional user identifier
* @returns Promise with service object
*/
async function fetch(
provider: string,
identifier: string,
uid?: string
): Promise<ServiceObject | null> {
try {
const response = await serviceService.fetch({ provider, service: identifier, uid });
return new ServiceObject().fromJson(response);
} catch (error: any) {
console.error('[People Manager](Store) - Failed to fetch service:', error);
throw error;
}
}
/**
* Create a fresh service object with default values
*/
function fresh(): ServiceObject {
return new ServiceObject();
}
return {
// State
services,
// Actions
list,
fetch,
fresh,
};
});

161
src/types/collection.ts Normal file
View File

@@ -0,0 +1,161 @@
/**
* Collection-related type definitions for People Manager
*/
import type { ListFilter, ListSort, SourceSelector } from "./common";
/**
* Permission settings for a collection
*/
export interface CollectionPermissionInterface {
view: boolean;
create: boolean;
modify: boolean;
destroy: boolean;
share: boolean;
}
/**
* Permissions settings for multiple users in a collection
*/
export interface CollectionPermissionsInterface {
[userId: string]: CollectionPermissionInterface;
}
/**
* Role settings for a collection
*/
export interface CollectionRolesInterface {
individual?: boolean;
[roleType: string]: boolean | undefined;
}
/**
* Content type settings for a collection
*/
export interface CollectionContentsInterface {
individual?: boolean;
organization?: boolean;
group?: boolean;
[contentType: string]: boolean | undefined;
}
/**
* Represents a collection within a service
*/
export interface CollectionInterface {
'@type': string;
provider: string | null;
service: string | null;
in: number | string | null;
id: number | string | null;
label: string | null;
description: string | null;
priority: number | null;
visibility: string | null;
color: string | null;
enabled: boolean;
signature: string | null;
permissions: CollectionPermissionsInterface;
roles: CollectionRolesInterface;
contents: CollectionContentsInterface;
}
/**
* Request to collection list endpoint
*/
export interface CollectionListRequest {
sources?: SourceSelector;
filter?: ListFilter;
sort?: ListSort;
}
/**
* Response from collection list endpoint
*/
export interface CollectionListResponse {
[providerId: string]: {
[serviceId: string]: {
[collectionId: string]: CollectionInterface;
};
};
}
/**
* Request to collection extant endpoint
*/
export interface CollectionExtantRequest {
sources: SourceSelector;
}
/**
* Response from collection extant endpoint
*/
export interface CollectionExtantResponse {
[providerId: string]: {
[serviceId: string]: {
[collectionId: string]: boolean;
};
};
}
/**
* Request to collection fetch endpoint
*/
export interface CollectionFetchRequest {
provider: string;
service: string;
identifier: string | number;
}
/**
* Response from collection fetch endpoint
*/
export interface CollectionFetchResponse extends CollectionInterface {}
/**
* Request to collection create endpoint
*/
export interface CollectionCreateRequest {
provider: string;
service: string;
data: CollectionInterface;
options?: (string)[];
}
/**
* Response from collection create endpoint
*/
export interface CollectionCreateResponse extends CollectionInterface {}
/**
* Request to collection modify endpoint
*/
export interface CollectionModifyRequest {
provider: string;
service: string;
identifier: string | number;
data: CollectionInterface;
}
/**
* Response from collection modify endpoint
*/
export interface CollectionModifyResponse extends CollectionInterface {}
/**
* Request to collection destroy endpoint
*/
export interface CollectionDestroyRequest {
provider: string;
service: string;
identifier: string | number;
}
/**
* Response from collection destroy endpoint
*/
export interface CollectionDestroyResponse {
success: boolean;
}

107
src/types/common.ts Normal file
View File

@@ -0,0 +1,107 @@
/**
* Common types shared across People Manager services
*/
import type { FilterComparisonOperator, FilterConjunctionOperator } from './service';
/**
* Base API request envelope
*/
export interface ApiRequest<T = any> {
version: number;
transaction: string;
operation: string;
data: T;
user?: string;
}
/**
* Success response envelope
*/
export interface ApiSuccessResponse<T = any> {
version: number;
transaction: string;
operation: string;
status: 'success';
data: T;
}
/**
* Error response envelope
*/
export interface ApiErrorResponse {
version: number;
transaction: string;
operation: string;
status: 'error';
data: {
code: number;
message: string;
};
}
/**
* Combined response type
*/
export type ApiResponse<T = any> = ApiSuccessResponse<T> | ApiErrorResponse;
/**
* Source selector structure for hierarchical resource selection
* Structure: Provider -> Service -> Collection -> Entity
*
* Examples:
* - Simple boolean: { "local": true }
* - Nested services: { "system": { "personal": true, "recents": true } }
* - Collection IDs: { "system": { "personal": { "299": true, "176": true } } }
* - Entity IDs: { "system": { "personal": { "299": [1350, 1353, 5000] } } }
*/
export type SourceSelector = {
[provider: string]: boolean | ServiceSelector;
};
export type ServiceSelector = {
[service: string]: boolean | CollectionSelector;
};
export type CollectionSelector = {
[collection: string | number]: boolean | EntitySelector;
};
export type EntitySelector = (string | number)[];
/**
* Filter condition for building complex queries
*/
export interface FilterCondition {
attribute: string;
value: string | number | boolean | any[];
comparator?: FilterComparisonOperator;
conjunction?: FilterConjunctionOperator;
}
/**
* Filter criteria for list operations
* Can be simple key-value pairs or complex filter conditions
*/
export interface ListFilter {
label?: string;
[key: string]: any;
}
/**
* Sort options for list operations
*/
export interface ListSort {
[key: string]: boolean;
}
/**
* Range specification for pagination/limiting results
*/
export interface ListRange {
type: 'tally';
anchor: 'absolute' | 'relative';
position: number;
tally: number;
}

159
src/types/entity.ts Normal file
View File

@@ -0,0 +1,159 @@
import type { ListFilter, ListRange, ListSort, SourceSelector } from './common';
import type { IndividualInterface } from './individual';
import type { OrganizationInterface } from './organization';
import type { GroupInterface } from './group';
/**
* Entity-related type definitions for People Manager
*/
/**
* Represents a person entity (contact)
*/
export interface EntityInterface {
'@type': string;
version: number;
in: string | number | null;
id: string | number | null;
createdOn: Date | null;
createdBy: string | null;
modifiedOn: Date | null;
modifiedBy: string | null;
signature: string | null;
data: IndividualInterface | OrganizationInterface | GroupInterface | null;
}
/**
* Request to entity list endpoint
*/
export interface EntityListRequest {
sources?: SourceSelector;
filter?: ListFilter;
sort?: ListSort;
range?: ListRange;
}
/**
* Response from entity list endpoint
*/
export interface EntityListResponse {
[providerId: string]: {
[serviceId: string]: {
[collectionId: string]: {
[entityId: string]: EntityInterface;
};
};
};
}
/**
* Request to entity delta endpoint
*/
export interface EntityDeltaRequest {
sources: SourceSelector;
}
/**
* Response from entity delta endpoint
*/
export interface EntityDeltaResponse {
[providerId: string]: {
[serviceId: string]: {
[collectionId: string]: {
signature: string;
created?: {
[entityId: string]: EntityInterface;
};
modified?: {
[entityId: string]: EntityInterface;
};
deleted?: string[]; // Array of deleted entity IDs
};
};
};
}
/**
* Request to entity extant endpoint
*/
export interface EntityExtantRequest {
sources: SourceSelector;
}
/**
* Response from entity extant endpoint
*/
export interface EntityExtantResponse {
[providerId: string]: {
[serviceId: string]: {
[collectionId: string]: {
[entityId: string]: boolean;
};
};
};
}
/**
* Request to entity fetch endpoint
*/
export interface EntityFetchRequest {
provider: string;
service: string;
collection: string | number;
identifiers: (string | number)[];
}
/**
* Response from entity fetch endpoint
*/
export interface EntityFetchResponse extends Record<string, EntityInterface> {}
/**
* Request to entity create endpoint
*/
export interface EntityCreateRequest {
provider: string;
service: string;
collection: string | number;
data: EntityInterface;
options?: (string)[];
}
/**
* Response from entity create endpoint
*/
export interface EntityCreateResponse extends EntityInterface {}
/**
* Request to entity modify endpoint
*/
export interface EntityModifyRequest {
provider: string;
service: string;
collection: string | number;
identifier: string | number;
data: EntityInterface;
options?: (string)[];
}
/**
* Response from entity modify endpoint
*/
export interface EntityModifyResponse extends EntityInterface {}
/**
* Request to entity destroy endpoint
*/
export interface EntityDestroyRequest {
provider: string;
service: string;
collection: string | number;
identifier: string | number;
}
/**
* Response from entity destroy endpoint
*/
export interface EntityDestroyResponse {
success: boolean;
}

75
src/types/group.ts Normal file
View File

@@ -0,0 +1,75 @@
/**
* Group-related type definitions
*/
/**
* Group name information
*/
export interface GroupName {
full: string | null;
sort: string | null;
aliases: string[];
}
/**
* Group member reference
*/
export interface GroupMember {
entityId: string | number | null;
role: string | null;
context: string | null;
priority: number | null;
}
/**
* Group virtual location
*/
export interface GroupVirtualLocation {
location: string | null;
label: string | null;
context: string | null;
priority: number | null;
}
/**
* Group media
*/
export interface GroupMedia {
type: string;
kind: string; // 'logo', 'photo'
uri: string;
mediaType?: string | null;
contexts?: string[] | null;
pref?: number | null;
label?: string | null;
}
/**
* Group note
*/
export interface GroupNote {
content: string | null;
date: Date | null;
authorUri: string | null;
authorName: string | null;
context: string | null;
priority: number | null;
}
/**
* Data for a group entity
*/
export interface GroupInterface {
type: string;
version: number;
urid: string | null;
created: Date | null;
modified: Date | null;
label: string | null;
names: GroupName;
members: Record<string, GroupMember>;
virtualLocations: Record<string, GroupVirtualLocation>;
media: Record<string, GroupMedia>;
tags: string[];
notes: Record<string, GroupNote>;
}

12
src/types/index.ts Normal file
View File

@@ -0,0 +1,12 @@
/**
* Central export point for all People Manager types
*/
export type * from './collection';
export type * from './common';
export type * from './entity';
export type * from './group';
export type * from './individual';
export type * from './organization';
export type * from './provider';
export type * from './service';

176
src/types/individual.ts Normal file
View File

@@ -0,0 +1,176 @@
/**
* Serialized DateTime from backend
*/
/**
* Individual alias
*/
export interface IndividualAlias {
label: string | null;
context: string | null;
priority: number | null;
}
/**
* Individual name information
*/
export interface IndividualName {
family: string | null;
given: string | null;
additional: string | null;
prefix: string | null;
suffix: string | null;
phoneticFamily: string | null;
phoneticGiven: string | null;
phoneticAdditional: string | null;
aliases: IndividualAlias[];
}
/**
* Individual title
*/
export interface IndividualTitle {
kind: string | null; // 't' or 'r'
label: string | null;
relation: string | null;
context: string | null;
priority: number | null;
}
/**
* Individual anniversary
*/
export interface IndividualAnniversary {
type: string | null; // 'birth', 'death', 'nuptial'
when: Date | null;
location: string | null;
}
/**
* Individual physical location
*/
export interface IndividualPhysicalLocation {
box: string | null;
unit: string | null;
street: string | null;
locality: string | null;
region: string | null;
code: string | null;
country: string | null;
label: string | null;
coordinates: string | null;
timeZone: string | null;
context: string | null;
priority: number | null;
}
/**
* Individual phone
*/
export interface IndividualPhone {
number: string | null;
label: string | null;
context: string | null;
priority: number | null;
}
/**
* Individual email
*/
export interface IndividualEmail {
address: string | null;
context: string | null;
priority: number | null;
}
/**
* Individual virtual location
*/
export interface IndividualVirtualLocation {
location: string | null;
label: string | null;
context: string | null;
priority: number | null;
}
/**
* Individual organization
*/
export interface IndividualOrganization {
Label: string | null;
Units: string[];
sortName: string | null;
context: string | null;
priority: number | null;
}
/**
* Individual note
*/
export interface IndividualNote {
content: string | null;
date: Date | null;
authorUri: string | null;
authorName: string | null;
context: string | null;
priority: number | null;
}
/**
* Individual language
*/
export interface IndividualLanguage {
Data: string | null;
Id: string | null;
Priority: number | null;
Context: string | null;
}
/**
* Individual crypto
*/
export interface IndividualCrypto {
data: string | null;
type: string | null;
context: string | null;
priority: number | null;
}
/**
* Individual media
*/
export interface IndividualMedia {
type: string;
kind: string; // 'photo', 'sound', 'logo'
uri: string;
mediaType?: string | null;
contexts?: string[] | null;
pref?: number | null;
label?: string | null;
}
/**
* Data for an individual entity
*/
export interface IndividualInterface {
type: string;
version: number;
urid: string | null;
created: Date | null;
modified: Date | null;
label: string | null;
names: IndividualName;
titles: Record<string, IndividualTitle>;
anniversaries: IndividualAnniversary[];
physicalLocations: Record<string, IndividualPhysicalLocation>;
phones: Record<string, IndividualPhone>;
emails: Record<string, IndividualEmail>;
virtualLocations: Record<string, IndividualVirtualLocation>;
media: Record<string, IndividualMedia>;
organizations: Record<string, IndividualOrganization>;
tags: string[];
notes: Record<string, IndividualNote>;
language: string | null;
languages: IndividualLanguage[];
crypto: Record<string, IndividualCrypto>;
}

115
src/types/organization.ts Normal file
View File

@@ -0,0 +1,115 @@
/**
* Organization-related type definitions
*/
/**
* Organization name information
*/
export interface OrganizationName {
full: string | null;
sort: string | null;
aliases: string[];
}
/**
* Organization physical location
*/
export interface OrganizationPhysicalLocation {
box: string | null;
unit: string | null;
street: string | null;
locality: string | null;
region: string | null;
code: string | null;
country: string | null;
label: string | null;
coordinates: string | null;
timeZone: string | null;
context: string | null;
priority: number | null;
}
/**
* Organization phone
*/
export interface OrganizationPhone {
number: string | null;
label: string | null;
context: string | null;
priority: number | null;
}
/**
* Organization email
*/
export interface OrganizationEmail {
address: string | null;
context: string | null;
priority: number | null;
}
/**
* Organization virtual location
*/
export interface OrganizationVirtualLocation {
location: string | null;
label: string | null;
context: string | null;
priority: number | null;
}
/**
* Organization media
*/
export interface OrganizationMedia {
type: string;
kind: string; // 'logo', 'photo'
uri: string;
mediaType?: string | null;
contexts?: string[] | null;
pref?: number | null;
label?: string | null;
}
/**
* Organization note
*/
export interface OrganizationNote {
content: string | null;
date: Date | null;
authorUri: string | null;
authorName: string | null;
context: string | null;
priority: number | null;
}
/**
* Organization crypto
*/
export interface OrganizationCrypto {
data: string | null;
type: string | null;
context: string | null;
priority: number | null;
}
/**
* Data for an organization entity
*/
export interface OrganizationInterface {
type: string;
version: number;
urid: string | null;
created: Date | null;
modified: Date | null;
label: string | null;
names: OrganizationName;
physicalLocations: Record<string, OrganizationPhysicalLocation>;
phones: Record<string, OrganizationPhone>;
emails: Record<string, OrganizationEmail>;
virtualLocations: Record<string, OrganizationVirtualLocation>;
media: Record<string, OrganizationMedia>;
tags: string[];
notes: Record<string, OrganizationNote>;
crypto: Record<string, OrganizationCrypto>;
}

53
src/types/provider.ts Normal file
View File

@@ -0,0 +1,53 @@
/**
* Provider-specific types
*/
import type { SourceSelector } from "./common";
/**
* Provider capabilities
*/
export interface ProviderCapabilitiesInterface {
ServiceList?: boolean;
ServiceFetch?: boolean;
ServiceExtant?: boolean;
ServiceCreate?: boolean;
ServiceModify?: boolean;
ServiceDelete?: boolean;
[key: string]: boolean | undefined;
}
/**
* Provider information
*/
export interface ProviderInterface {
'@type': string;
id: string;
label: string;
capabilities: ProviderCapabilitiesInterface;
}
/**
* Request to provider list endpoint
*/
export interface ProviderListRequest {}
/**
* Response from provider list endpoint
*/
export interface ProviderListResponse {
[providerId: string]: ProviderInterface;
}
/**
* Request to provider extant endpoint
*/
export interface ProviderExtantRequest {
sources: SourceSelector;
}
/**
* Response from provider extant endpoint
*/
export interface ProviderExtantResponse {
[providerId: string]: boolean;
}

211
src/types/service.ts Normal file
View File

@@ -0,0 +1,211 @@
/**
* Service-related type definitions for People Manager
*/
import type { ListFilter, ListSort, SourceSelector } from "./common";
/**
* Filter comparison operators (bitmask values)
*/
export const FilterComparisonOperator = {
EQ: 1, // Equal
NEQ: 2, // Not Equal
GT: 4, // Greater Than
LT: 8, // Less Than
GTE: 16, // Greater Than or Equal
LTE: 32, // Less Than or Equal
IN: 64, // In Array
NIN: 128, // Not In Array
LIKE: 256, // Like (pattern matching)
NLIKE: 512, // Not Like
} as const;
export type FilterComparisonOperator = typeof FilterComparisonOperator[keyof typeof FilterComparisonOperator];
/**
* Filter conjunction operators
*/
export const FilterConjunctionOperator = {
NONE: '',
AND: 'AND',
OR: 'OR',
} as const;
export type FilterConjunctionOperator = typeof FilterConjunctionOperator[keyof typeof FilterConjunctionOperator];
/**
* Filter specification format
* Format: "type:length:defaultComparator:supportedComparators"
*
* Examples:
* - "s:200:256:771" = String field, max 200 chars, default LIKE, supports EQ|NEQ|LIKE|NLIKE
* - "a:10:64:192" = Array field, max 10 items, default IN, supports IN|NIN
* - "i:0:1:31" = Integer field, default EQ, supports EQ|NEQ|GT|LT|GTE|LTE
*
* Type codes:
* - s = string
* - i = integer
* - b = boolean
* - a = array
*
* Comparator values are bitmasks that can be combined
*/
export type FilterSpec = string;
/**
* Parsed filter specification
*/
export interface ParsedFilterSpec {
type: 'string' | 'integer' | 'boolean' | 'array';
length: number;
defaultComparator: FilterComparisonOperator;
supportedComparators: FilterComparisonOperator[];
}
/**
* Parse a filter specification string into its components
*
* @param spec - Filter specification string (e.g., "s:200:256:771")
* @returns Parsed filter specification object
*
* @example
* parseFilterSpec("s:200:256:771")
* // Returns: {
* // type: 'string',
* // length: 200,
* // defaultComparator: 256 (LIKE),
* // supportedComparators: [1, 2, 256, 512] (EQ, NEQ, LIKE, NLIKE)
* // }
*/
export function parseFilterSpec(spec: FilterSpec): ParsedFilterSpec {
const [typeCode, lengthStr, defaultComparatorStr, supportedComparatorsStr] = spec.split(':');
const typeMap: Record<string, ParsedFilterSpec['type']> = {
's': 'string',
'i': 'integer',
'b': 'boolean',
'a': 'array',
};
const type = typeMap[typeCode];
if (!type) {
throw new Error(`Invalid filter type code: ${typeCode}`);
}
const length = parseInt(lengthStr, 10);
const defaultComparator = parseInt(defaultComparatorStr, 10) as FilterComparisonOperator;
// Parse supported comparators from bitmask
const supportedComparators: FilterComparisonOperator[] = [];
const supportedBitmask = parseInt(supportedComparatorsStr, 10);
if (supportedBitmask !== 0) {
const allComparators = Object.values(FilterComparisonOperator).filter(v => typeof v === 'number') as number[];
for (const comparator of allComparators) {
if ((supportedBitmask & comparator) === comparator) {
supportedComparators.push(comparator as FilterComparisonOperator);
}
}
}
return {
type,
length,
defaultComparator,
supportedComparators,
};
}
/**
* Capabilities available for a service
*/
export interface ServiceCapabilitiesInterface {
// Collection capabilities
CollectionList?: boolean;
CollectionListFilter?: {
[key: string]: FilterSpec;
};
CollectionListSort?: string[];
CollectionExtant?: boolean;
CollectionFetch?: boolean;
CollectionCreate?: boolean;
CollectionModify?: boolean;
CollectionDestroy?: boolean;
// Entity capabilities
EntityList?: boolean;
EntityListFilter?: {
[key: string]: FilterSpec;
};
EntityListSort?: string[];
EntityListRange?: {
[rangeType: string]: string[]; // e.g., { "tally": ["absolute", "relative"] }
};
EntityDelta?: boolean;
EntityExtant?: boolean;
EntityFetch?: boolean;
EntityCreate?: boolean;
EntityModify?: boolean;
EntityDestroy?: boolean;
EntityCopy?: boolean;
EntityMove?: boolean;
}
/**
* Represents a service within a provider
*/
export interface ServiceInterface {
'@type': string;
provider: string;
id: string;
label: string;
capabilities?: ServiceCapabilitiesInterface;
enabled: boolean;
}
/**
* Request to service list endpoint
*/
export interface ServiceListRequest {
sources?: SourceSelector;
filter?: ListFilter;
sort?: ListSort;
}
/**
* Response from service list endpoint
*/
export interface ServiceListResponse {
[providerId: string]: {
[serviceId: string]: ServiceInterface;
};
}
/**
* Request to service extant endpoint
*/
export interface ServiceExtantRequest {
sources: SourceSelector;
}
/**
* Response from service extant endpoint
*/
export interface ServiceExtantResponse {
[providerId: string]: {
[serviceId: string]: boolean;
};
}
/**
* Request to service fetch endpoint
*/
export interface ServiceFetchRequest {
provider: string;
service: string;
}
/**
* Response from service fetch endpoint
*/
export interface ServiceFetchResponse extends ServiceInterface {}

View File

@@ -0,0 +1,31 @@
/**
* Utility functions for generating unique identifiers
*/
const globalCrypto = typeof globalThis !== "undefined" ? globalThis.crypto : undefined;
export const generateUrid = (): string => {
if (globalCrypto?.randomUUID) {
return globalCrypto.randomUUID();
}
const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
return template.replace(/[xy]/g, char => {
const randomNibble = Math.floor(Math.random() * 16);
const value = char === "x" ? randomNibble : (randomNibble & 0x3) | 0x8;
return value.toString(16);
});
};
export const generateKey = (): string => {
if (globalCrypto?.randomUUID) {
return globalCrypto.randomUUID().replace(/-/g, "");
}
if (globalCrypto?.getRandomValues) {
const [value] = globalCrypto.getRandomValues(new Uint32Array(1));
return value.toString(16);
}
return Math.random().toString(16).slice(2);
};

1
src/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />