@artemis-apps/app-react 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,147 @@
1
+ import { APP_PROTOCOL_PATHS, CORE_API_PATHS, ENTITY_PARAMS, EntityHandlerListSchema, EntityKindListSchema, EntitySharingSchema, EntityTypeListSchema, entityListSchema, entityResultSchema, fillPath, formatEntityListQuery, formatHandleQuery, formatOwnedId, formatPointer, } from '@artemis-apps/contracts';
2
+ import { appPath, fetchJson, fetchNoContent, readApiError, } from '@artemis-apps/web-kit';
3
+ /*
4
+ * The core's entity API, reached through the app's relay (`APP_PROTOCOL_PATHS.coreRelay`): the
5
+ * same for every app and every provider, this app's own included.
6
+ */
7
+ const API_PREFIX = '/api';
8
+ /**
9
+ * A core API path, as the web client reaches it through its server's relay: a path on the page's
10
+ * origin (under the app's base path), fit for `fetch` as for an `<img src>`.
11
+ */
12
+ export function relayed(corePath) {
13
+ return appPath(`${APP_PROTOCOL_PATHS.coreRelay}${corePath.slice(API_PREFIX.length)}`);
14
+ }
15
+ function withQuery(path, params) {
16
+ const query = new URLSearchParams(Object.entries(params).filter((entry) => entry[1] !== undefined)).toString();
17
+ return query ? `${path}?${query}` : path;
18
+ }
19
+ function entityPath({ type, providerId, ownerId, id }) {
20
+ return relayed(fillPath(CORE_API_PATHS.entity, { type, providerId, ownerId, entityId: id }));
21
+ }
22
+ const viaParam = (via) => ({
23
+ [ENTITY_PARAMS.via]: via ? formatPointer(via) : undefined,
24
+ });
25
+ export function fetchEntityTypes(signal) {
26
+ return fetchJson(relayed(CORE_API_PATHS.entityTypes), EntityTypeListSchema, { signal });
27
+ }
28
+ /** The apps handling actions on entities of the type (opening, previewing them...), by kind. */
29
+ export function fetchEntityHandlers(type, signal) {
30
+ return fetchJson(relayed(fillPath(CORE_API_PATHS.entityHandlers, { type })), EntityHandlerListSchema, { signal });
31
+ }
32
+ /** The kinds of entities of the type the apps support: their icons, and whether they have a template. */
33
+ export function fetchEntityKinds(type, signal) {
34
+ return fetchJson(relayed(fillPath(CORE_API_PATHS.entityKinds, { type })), EntityKindListSchema, {
35
+ signal,
36
+ });
37
+ }
38
+ /**
39
+ * The file name a `Content-Disposition` header gives (`filename*`, RFC 5987, before `filename`);
40
+ * `undefined` without one.
41
+ */
42
+ export function contentDispositionFileName(header) {
43
+ if (!header)
44
+ return undefined;
45
+ const extended = /filename\*\s*=\s*([^;]+)/i.exec(header)?.[1]?.trim();
46
+ if (extended) {
47
+ const encoded = extended.slice(extended.indexOf("''") + 2).replace(/^"|"$/g, '');
48
+ try {
49
+ return decodeURIComponent(encoded) || undefined;
50
+ }
51
+ catch {
52
+ // A malformed encoding: the plain `filename` may still do.
53
+ }
54
+ }
55
+ const plain = /filename\s*=\s*("((?:[^"\\]|\\.)*)"|[^;]+)/i.exec(header);
56
+ const name = plain?.[2]?.replace(/\\(.)/g, '$1') ?? plain?.[1]?.trim();
57
+ return name || undefined;
58
+ }
59
+ /**
60
+ * The blank template an app offers for new entities of a kind (`hasTemplate`), in the language
61
+ * spoken when the app has one per language: a file, named as the app names it (its extension
62
+ * is the one new entities take).
63
+ */
64
+ export async function fetchKindTemplate(type, appId, kind, locale, signal) {
65
+ const path = relayed(fillPath(CORE_API_PATHS.entityKindTemplate, { type, appId, kind }));
66
+ const response = await fetch(withQuery(path, { locale }), {
67
+ credentials: 'same-origin',
68
+ signal,
69
+ });
70
+ if (!response.ok)
71
+ throw await readApiError(response);
72
+ const blob = await response.blob();
73
+ const name = contentDispositionFileName(response.headers.get('content-disposition')) ?? kind;
74
+ return new File([blob], name, { type: blob.type });
75
+ }
76
+ /** Where a `page` action runs on an entity: the handling app's page, the entity in its query. */
77
+ export function handleUrl(handler, target) {
78
+ const query = formatHandleQuery({
79
+ providerId: target.providerId,
80
+ ownerId: target.ownerId,
81
+ id: target.id,
82
+ via: target.via ? formatPointer(target.via) : null,
83
+ kind: handler.kind,
84
+ });
85
+ return `${handler.url}?${query}`;
86
+ }
87
+ /** Every entity of a type the account reaches, from every provider. */
88
+ export function listEntities(type, data, { filter, params } = {}, signal) {
89
+ const query = formatEntityListQuery(filter, params);
90
+ const path = relayed(fillPath(CORE_API_PATHS.entities, { type }));
91
+ return fetchJson(query ? `${path}?${query}` : path, entityListSchema(data), { signal });
92
+ }
93
+ export function readEntity(target, data, signal) {
94
+ return fetchJson(withQuery(entityPath(target), viaParam(target.via)), entityResultSchema(data), {
95
+ signal,
96
+ });
97
+ }
98
+ export function createEntity({ type, providerId, parent, body }, data) {
99
+ const path = relayed(fillPath(CORE_API_PATHS.providerEntities, { type, providerId }));
100
+ return fetchJson(withQuery(path, {
101
+ [ENTITY_PARAMS.parent]: parent ? formatOwnedId(parent) : undefined,
102
+ ...viaParam(parent?.via ?? null),
103
+ }), entityResultSchema(data), { method: 'POST', body });
104
+ }
105
+ export function updateEntity(target, { body, parentId }, data) {
106
+ return fetchJson(withQuery(entityPath(target), { ...viaParam(target.via), [ENTITY_PARAMS.parent]: parentId }), entityResultSchema(data), { method: 'PATCH', body });
107
+ }
108
+ export function deleteEntity(target) {
109
+ return fetchNoContent(withQuery(entityPath(target), viaParam(target.via)), { method: 'DELETE' });
110
+ }
111
+ /** Where one of the type's own operations answers: for a link or a picture, or to call it. */
112
+ export function entityOperationUrl(target, operation) {
113
+ return withQuery(relayed(fillPath(CORE_API_PATHS.entityOperation, {
114
+ type: target.type,
115
+ providerId: target.providerId,
116
+ ownerId: target.ownerId,
117
+ entityId: target.id,
118
+ operation,
119
+ })), viaParam(target.via));
120
+ }
121
+ /** Calls one of the type's own operations that answers `204 No Content`. */
122
+ export function callEntityOperation(target, operation, { method = 'POST', body } = {}) {
123
+ return fetchNoContent(entityOperationUrl(target, operation), { method, body });
124
+ }
125
+ /** Calls one of the type's own operations that answers JSON. */
126
+ export function callEntityOperationJson(target, operation, schema, { method = 'POST', body } = {}) {
127
+ return fetchJson(entityOperationUrl(target, operation), schema, { method, body });
128
+ }
129
+ function sharesPath({ type, providerId, ownerId, id }) {
130
+ return relayed(fillPath(CORE_API_PATHS.entityShares, { type, providerId, ownerId, entityId: id }));
131
+ }
132
+ function sharePath({ type, providerId, ownerId, id }, accountId) {
133
+ return relayed(fillPath(CORE_API_PATHS.entityShare, { type, providerId, ownerId, entityId: id, accountId }));
134
+ }
135
+ export function fetchEntitySharing(target, signal) {
136
+ return fetchJson(withQuery(sharesPath(target), viaParam(target.via)), EntitySharingSchema, {
137
+ signal,
138
+ });
139
+ }
140
+ export function updateEntityShare(target, accountId, input) {
141
+ return fetchJson(withQuery(sharePath(target, accountId), viaParam(target.via)), EntitySharingSchema, { method: 'PUT', body: input });
142
+ }
143
+ export function deleteEntityShare(target, accountId) {
144
+ return fetchNoContent(withQuery(sharePath(target, accountId), viaParam(target.via)), {
145
+ method: 'DELETE',
146
+ });
147
+ }
@@ -0,0 +1,24 @@
1
+ import { type Entity } from '@artemis-apps/contracts';
2
+ import type * as React from 'react';
3
+ type SharedEntity = Pick<Entity, 'type' | 'providerId' | 'ownerId' | 'id' | 'access'>;
4
+ export interface EntityShareDialogProps {
5
+ open: boolean;
6
+ onOpenChange: (open: boolean) => void;
7
+ /** E.g. `Share “Work”`. */
8
+ title: string;
9
+ description?: React.ReactNode;
10
+ /** Extra information under the list, e.g. access inherited from a parent. */
11
+ note?: React.ReactNode;
12
+ entity: SharedEntity;
13
+ /** After any change: what the app's lists show may have changed. */
14
+ onChanged?: () => void;
15
+ /** Once the signed-in account left the entity: it no longer reaches it. */
16
+ onLeft?: () => void;
17
+ }
18
+ /**
19
+ * The share dialog of any entity, whatever its type and provider: who reaches it and with which
20
+ * level, kept by the core. Levels are worked out from the entity's type; an account shares only
21
+ * what it holds, and anyone may leave.
22
+ */
23
+ export declare function EntityShareDialog({ open, ...props }: EntityShareDialogProps): React.JSX.Element | null;
24
+ export {};
@@ -0,0 +1,101 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { grantableLevels, levelPermissions, SHARE_PERMISSION, shareLevelOf, typePermission, } from '@artemis-apps/contracts';
3
+ import { ShareDialog } from '@artemis-apps/ui';
4
+ import { useTranslator } from '@artemis-apps/web-kit';
5
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
6
+ import { useState } from 'react';
7
+ import { useAppSession } from '../use-app-session.js';
8
+ import { useDirectorySearch } from '../use-directory-search.js';
9
+ import { deleteEntityShare, fetchEntitySharing, updateEntityShare } from './entities.api.js';
10
+ import { entityKey, entityTarget, useEntityTypes } from './use-entities.js';
11
+ function toPerson(account) {
12
+ return {
13
+ id: account.id,
14
+ name: account.name,
15
+ email: account.email,
16
+ avatarSeed: account.avatar.kind === 'generated' ? account.avatar.seed : account.id,
17
+ avatarUrl: account.avatar.kind === 'file' ? account.avatar.url : undefined,
18
+ };
19
+ }
20
+ /** Mounted while open, so the search starts blank every time. */
21
+ function ShareDialogBody({ onOpenChange, title, description, note, entity, onChanged, onLeft, }) {
22
+ const session = useAppSession();
23
+ const translator = useTranslator();
24
+ const queryClient = useQueryClient();
25
+ const definition = useEntityTypes()?.get(entity.type);
26
+ const [search, setSearch] = useState('');
27
+ const directory = useDirectorySearch(search);
28
+ const target = entityTarget(entity);
29
+ const queryKey = ['entity-sharing', entity.type, entityKey(entity)];
30
+ const sharing = useQuery({
31
+ queryKey,
32
+ queryFn: ({ signal }) => fetchEntitySharing(target, signal),
33
+ });
34
+ const share = useMutation({
35
+ mutationFn: ({ accountId, level }) => updateEntityShare(target, accountId, {
36
+ permissions: definition ? levelPermissions(definition, level) : [],
37
+ }),
38
+ onSuccess: (updated) => {
39
+ queryClient.setQueryData(queryKey, updated);
40
+ onChanged?.();
41
+ },
42
+ });
43
+ const unshare = useMutation({
44
+ mutationFn: (accountId) => deleteEntityShare(target, accountId),
45
+ onSuccess: (_result, accountId) => {
46
+ queryClient.setQueryData(queryKey, (current) => current && {
47
+ ...current,
48
+ shares: current.shares.filter((entry) => entry.account.id !== accountId),
49
+ });
50
+ onChanged?.();
51
+ },
52
+ });
53
+ const data = sharing.data;
54
+ const held = data?.permissions ?? entity.access.permissions;
55
+ const grantable = definition ? grantableLevels(definition, held) : [];
56
+ const memberLevel = (permissions) => definition ? shareLevelOf(definition, permissions) : 'custom';
57
+ const members = data?.shares.map((entry) => ({
58
+ person: toPerson(entry.account),
59
+ level: memberLevel(entry.permissions),
60
+ }));
61
+ // A level nobody can pick still shows on the members holding it.
62
+ const shown = new Set([...grantable, ...(members ?? []).map((m) => m.level)]);
63
+ const levels = [...shown].map((level) => ({
64
+ value: level,
65
+ label: translator.shareLevelLabel(level),
66
+ description: translator.shareLevelDescription(level),
67
+ }));
68
+ const canShare = held.includes(SHARE_PERMISSION) &&
69
+ session.permissions.includes(typePermission(entity.type, SHARE_PERMISSION)) &&
70
+ grantable.length > 0;
71
+ const isGrantable = (level) => grantable.includes(level);
72
+ return (_jsx(ShareDialog, { open: true, onOpenChange: onOpenChange, title: title, description: description, note: note, currentPersonId: session.account.id, owner: data ? data.owner && toPerson(data.owner) : undefined, ownerLabel: translator.shareLevelLabel('owner'), members: members, levels: levels, canManage: canShare, loadError: sharing.error, changeError: share.error ?? unshare.error, saving: share.isPending || unshare.isPending, search: search, onSearchChange: setSearch, searchResults: directory.accounts?.map(toPerson), searchError: directory.error, onAdd: (person, level) => {
73
+ if (!isGrantable(level))
74
+ return;
75
+ unshare.reset();
76
+ share.mutate({ accountId: person.id, level }, { onSuccess: () => setSearch('') });
77
+ }, onChangeLevel: (accountId, level) => {
78
+ if (!isGrantable(level))
79
+ return;
80
+ unshare.reset();
81
+ share.mutate({ accountId, level });
82
+ }, onRemove: (accountId) => {
83
+ share.reset();
84
+ unshare.mutate(accountId, {
85
+ onSuccess: () => {
86
+ if (accountId !== session.account.id)
87
+ return;
88
+ onOpenChange(false);
89
+ onLeft?.();
90
+ },
91
+ });
92
+ } }));
93
+ }
94
+ /**
95
+ * The share dialog of any entity, whatever its type and provider: who reaches it and with which
96
+ * level, kept by the core. Levels are worked out from the entity's type; an account shares only
97
+ * what it holds, and anyone may leave.
98
+ */
99
+ export function EntityShareDialog({ open, ...props }) {
100
+ return open ? _jsx(ShareDialogBody, { ...props }) : null;
101
+ }
@@ -0,0 +1,140 @@
1
+ import { type Entity, type EntityHandler, type EntityKind, type EntityTypeDefinition, type ProviderSummary } from '@artemis-apps/contracts';
2
+ import { type QueryClient } from '@tanstack/react-query';
3
+ import type { z } from 'zod';
4
+ import { type EntityListOptions, type EntityTarget } from './entities.api.ts';
5
+ /** Query keys of the entity queries, to invalidate after a change. */
6
+ export declare const entityQueryKeys: {
7
+ types: readonly ['entity-types'];
8
+ handlers: (type: string) => readonly ['entity-types', string, 'handlers'];
9
+ kinds: (type: string) => readonly ['entity-types', string, 'kinds'];
10
+ /** Every list of a type, whatever its options. */
11
+ lists: (type: string) => readonly ['entities', string];
12
+ list: (type: string, options: EntityListOptions) => readonly ['entities', string, EntityListOptions];
13
+ };
14
+ /** Refetches every list of these types (after a creation, a change, a move). */
15
+ export declare function invalidateEntities(queryClient: QueryClient, ...types: string[]): Promise<void[]>;
16
+ /** Every entity type of the platform, by id: names, permissions, operations. */
17
+ export declare function useEntityTypes(): ReadonlyMap<string, EntityTypeDefinition> | undefined;
18
+ /**
19
+ * The apps handling actions on entities of the type, by action and kind: none while they load,
20
+ * or when the core can't tell.
21
+ */
22
+ export declare function useEntityHandlers(type: string): readonly EntityHandler[];
23
+ /**
24
+ * The kinds of entities of the type the apps support, app by app in the platform's order: their
25
+ * icons, and whether new ones can start from a template. None while they load, or when the core
26
+ * can't tell.
27
+ */
28
+ export declare function useEntityKinds(type: string): readonly EntityKind[];
29
+ /** Every entity of a type the account reaches, from every provider. */
30
+ export declare function useEntities<Data extends z.ZodType>(type: string, data: Data, options?: EntityListOptions, { enabled }?: {
31
+ enabled?: boolean;
32
+ }): import("@tanstack/react-query").UseQueryResult<{
33
+ providers: {
34
+ id: string;
35
+ name: string;
36
+ url: string;
37
+ iconUrl: string;
38
+ operations: string[];
39
+ available: boolean;
40
+ consented: boolean;
41
+ }[];
42
+ entities: (({
43
+ type: z.ZodString;
44
+ providerId: z.ZodString;
45
+ ownerId: z.ZodString;
46
+ id: z.ZodString;
47
+ parent: z.ZodNullable<z.ZodObject<{
48
+ type: z.ZodString;
49
+ id: z.ZodString;
50
+ }, z.core.$strip>>;
51
+ url: z.ZodNullable<z.ZodURL>;
52
+ createdAt: z.ZodNullable<z.ZodISODateTime>;
53
+ updatedAt: z.ZodNullable<z.ZodISODateTime>;
54
+ data: Data;
55
+ access: z.ZodObject<{
56
+ permissions: z.ZodArray<z.ZodString>;
57
+ via: z.ZodNullable<z.ZodObject<{
58
+ type: z.ZodString;
59
+ id: z.ZodString;
60
+ }, z.core.$strip>>;
61
+ }, z.core.$strip>;
62
+ } extends infer T_1 extends z.core.$ZodLooseShape ? { -readonly [k in keyof T_1 as {
63
+ type: z.ZodString;
64
+ providerId: z.ZodString;
65
+ ownerId: z.ZodString;
66
+ id: z.ZodString;
67
+ parent: z.ZodNullable<z.ZodObject<{
68
+ type: z.ZodString;
69
+ id: z.ZodString;
70
+ }, z.core.$strip>>;
71
+ url: z.ZodNullable<z.ZodURL>;
72
+ createdAt: z.ZodNullable<z.ZodISODateTime>;
73
+ updatedAt: z.ZodNullable<z.ZodISODateTime>;
74
+ data: Data;
75
+ access: z.ZodObject<{
76
+ permissions: z.ZodArray<z.ZodString>;
77
+ via: z.ZodNullable<z.ZodObject<{
78
+ type: z.ZodString;
79
+ id: z.ZodString;
80
+ }, z.core.$strip>>;
81
+ }, z.core.$strip>;
82
+ }[k] extends {
83
+ _zod: {
84
+ optout: "optional";
85
+ };
86
+ } ? never : k]: T_1[k]["_zod"]["output"]; } : never) & ({
87
+ type: z.ZodString;
88
+ providerId: z.ZodString;
89
+ ownerId: z.ZodString;
90
+ id: z.ZodString;
91
+ parent: z.ZodNullable<z.ZodObject<{
92
+ type: z.ZodString;
93
+ id: z.ZodString;
94
+ }, z.core.$strip>>;
95
+ url: z.ZodNullable<z.ZodURL>;
96
+ createdAt: z.ZodNullable<z.ZodISODateTime>;
97
+ updatedAt: z.ZodNullable<z.ZodISODateTime>;
98
+ data: Data;
99
+ access: z.ZodObject<{
100
+ permissions: z.ZodArray<z.ZodString>;
101
+ via: z.ZodNullable<z.ZodObject<{
102
+ type: z.ZodString;
103
+ id: z.ZodString;
104
+ }, z.core.$strip>>;
105
+ }, z.core.$strip>;
106
+ } extends infer T_2 extends z.core.$ZodLooseShape ? { -readonly [k in keyof T_2 as {
107
+ type: z.ZodString;
108
+ providerId: z.ZodString;
109
+ ownerId: z.ZodString;
110
+ id: z.ZodString;
111
+ parent: z.ZodNullable<z.ZodObject<{
112
+ type: z.ZodString;
113
+ id: z.ZodString;
114
+ }, z.core.$strip>>;
115
+ url: z.ZodNullable<z.ZodURL>;
116
+ createdAt: z.ZodNullable<z.ZodISODateTime>;
117
+ updatedAt: z.ZodNullable<z.ZodISODateTime>;
118
+ data: Data;
119
+ access: z.ZodObject<{
120
+ permissions: z.ZodArray<z.ZodString>;
121
+ via: z.ZodNullable<z.ZodObject<{
122
+ type: z.ZodString;
123
+ id: z.ZodString;
124
+ }, z.core.$strip>>;
125
+ }, z.core.$strip>;
126
+ }[k] extends {
127
+ _zod: {
128
+ optout: "optional";
129
+ };
130
+ } ? k : never]?: T_2[k]["_zod"]["output"] | undefined; } : never) extends infer T ? { [K in keyof T]: T[K]; } : never)[];
131
+ }, Error>;
132
+ /** An entity as operations name it. */
133
+ export declare function entityTarget(entity: Pick<Entity, 'type' | 'providerId' | 'ownerId' | 'id' | 'access'>): EntityTarget;
134
+ /** A key unique among the entities of a type, whatever their provider and owner. */
135
+ export declare function entityKey(entity: Pick<Entity, 'providerId' | 'ownerId' | 'id'>): string;
136
+ /**
137
+ * Whether an operation can be offered on an entity: its provider implements it, the account
138
+ * holds the permission it needs on the entity, and the app received that permission.
139
+ */
140
+ export declare function useEntityAbility(): (entity: Pick<Entity, 'type' | 'access'>, definition: Pick<EntityTypeDefinition, 'operations'> | undefined, provider: Pick<ProviderSummary, 'operations'> | undefined, operation: string) => boolean;
@@ -0,0 +1,92 @@
1
+ import { operationPermission, typePermission, } from '@artemis-apps/contracts';
2
+ import { useQuery } from '@tanstack/react-query';
3
+ import { useCallback } from 'react';
4
+ import { useAppSession } from '../use-app-session.js';
5
+ import { fetchEntityHandlers, fetchEntityKinds, fetchEntityTypes, listEntities, } from './entities.api.js';
6
+ /** How long types, handlers and kinds stay fresh: they change with enrollments only. */
7
+ const TYPES_STALE_TIME_MS = 10 * 60 * 1000;
8
+ /** Query keys of the entity queries, to invalidate after a change. */
9
+ export const entityQueryKeys = {
10
+ types: ['entity-types'],
11
+ handlers: (type) => ['entity-types', type, 'handlers'],
12
+ kinds: (type) => ['entity-types', type, 'kinds'],
13
+ /** Every list of a type, whatever its options. */
14
+ lists: (type) => ['entities', type],
15
+ list: (type, options) => ['entities', type, options],
16
+ };
17
+ /** Refetches every list of these types (after a creation, a change, a move). */
18
+ export function invalidateEntities(queryClient, ...types) {
19
+ return Promise.all(types.map((type) => queryClient.invalidateQueries({ queryKey: entityQueryKeys.lists(type) })));
20
+ }
21
+ /** Every entity type of the platform, by id: names, permissions, operations. */
22
+ export function useEntityTypes() {
23
+ const query = useQuery({
24
+ queryKey: entityQueryKeys.types,
25
+ queryFn: ({ signal }) => fetchEntityTypes(signal),
26
+ staleTime: TYPES_STALE_TIME_MS,
27
+ });
28
+ return query.data && new Map(query.data.types.map((type) => [type.id, type]));
29
+ }
30
+ const NO_HANDLERS = [];
31
+ /**
32
+ * The apps handling actions on entities of the type, by action and kind: none while they load,
33
+ * or when the core can't tell.
34
+ */
35
+ export function useEntityHandlers(type) {
36
+ const query = useQuery({
37
+ queryKey: entityQueryKeys.handlers(type),
38
+ queryFn: ({ signal }) => fetchEntityHandlers(type, signal),
39
+ staleTime: TYPES_STALE_TIME_MS,
40
+ });
41
+ return query.data?.handlers ?? NO_HANDLERS;
42
+ }
43
+ const NO_KINDS = [];
44
+ /**
45
+ * The kinds of entities of the type the apps support, app by app in the platform's order: their
46
+ * icons, and whether new ones can start from a template. None while they load, or when the core
47
+ * can't tell.
48
+ */
49
+ export function useEntityKinds(type) {
50
+ const query = useQuery({
51
+ queryKey: entityQueryKeys.kinds(type),
52
+ queryFn: ({ signal }) => fetchEntityKinds(type, signal),
53
+ staleTime: TYPES_STALE_TIME_MS,
54
+ });
55
+ return query.data?.kinds ?? NO_KINDS;
56
+ }
57
+ /** Every entity of a type the account reaches, from every provider. */
58
+ export function useEntities(type, data, options = {}, { enabled = true } = {}) {
59
+ return useQuery({
60
+ queryKey: entityQueryKeys.list(type, options),
61
+ queryFn: ({ signal }) => listEntities(type, data, options, signal),
62
+ enabled,
63
+ });
64
+ }
65
+ /** An entity as operations name it. */
66
+ export function entityTarget(entity) {
67
+ return {
68
+ type: entity.type,
69
+ providerId: entity.providerId,
70
+ ownerId: entity.ownerId,
71
+ id: entity.id,
72
+ via: entity.access.via,
73
+ };
74
+ }
75
+ /** A key unique among the entities of a type, whatever their provider and owner. */
76
+ export function entityKey(entity) {
77
+ return JSON.stringify([entity.providerId, entity.ownerId, entity.id]);
78
+ }
79
+ /**
80
+ * Whether an operation can be offered on an entity: its provider implements it, the account
81
+ * holds the permission it needs on the entity, and the app received that permission.
82
+ */
83
+ export function useEntityAbility() {
84
+ const session = useAppSession();
85
+ return useCallback((entity, definition, provider, operation) => {
86
+ const permission = definition && operationPermission(definition, operation);
87
+ return (permission !== undefined &&
88
+ provider?.operations.includes(operation) === true &&
89
+ entity.access.permissions.includes(permission) &&
90
+ session.permissions.includes(typePermission(entity.type, permission)));
91
+ }, [session.permissions]);
92
+ }
@@ -0,0 +1,10 @@
1
+ export { AppAccountMenu } from './app-account-menu.tsx';
2
+ export { AppLauncher } from './app-launcher.tsx';
3
+ export { callEntityOperation, callEntityOperationJson, createEntity, deleteEntity, type EntityCreation, type EntityListOptions, type EntityTarget, type EntityUpdate, entityOperationUrl, fetchEntityHandlers, fetchEntityKinds, fetchEntityTypes, fetchKindTemplate, handleUrl, listEntities, readEntity, relayed, updateEntity, } from './entities/entities.api.ts';
4
+ export { EntityShareDialog, type EntityShareDialogProps } from './entities/entity-share-dialog.tsx';
5
+ export { entityKey, entityQueryKeys, entityTarget, invalidateEntities, useEntities, useEntityAbility, useEntityHandlers, useEntityKinds, useEntityTypes, } from './entities/use-entities.ts';
6
+ export { PlatformProvider, type PlatformProviderProps } from './platform-provider.tsx';
7
+ export { type AuthenticatedAppSessionState, useAppSession, useHasPermission, } from './use-app-session.ts';
8
+ export { useDirectoryAccounts } from './use-directory-accounts.ts';
9
+ export { isCurrentAppEntry, useLauncher } from './use-launcher.ts';
10
+ export { useSignOut } from './use-sign-out.ts';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export { AppAccountMenu } from './app-account-menu.js';
2
+ export { AppLauncher } from './app-launcher.js';
3
+ export { callEntityOperation, callEntityOperationJson, createEntity, deleteEntity, entityOperationUrl, fetchEntityHandlers, fetchEntityKinds, fetchEntityTypes, fetchKindTemplate, handleUrl, listEntities, readEntity, relayed, updateEntity, } from './entities/entities.api.js';
4
+ export { EntityShareDialog } from './entities/entity-share-dialog.js';
5
+ export { entityKey, entityQueryKeys, entityTarget, invalidateEntities, useEntities, useEntityAbility, useEntityHandlers, useEntityKinds, useEntityTypes, } from './entities/use-entities.js';
6
+ export { PlatformProvider } from './platform-provider.js';
7
+ export { useAppSession, useHasPermission, } from './use-app-session.js';
8
+ export { useDirectoryAccounts } from './use-directory-accounts.js';
9
+ export { isCurrentAppEntry, useLauncher } from './use-launcher.js';
10
+ export { useSignOut } from './use-sign-out.js';
@@ -0,0 +1,10 @@
1
+ /** What the signed-in account can open, from the core through the app's relay. */
2
+ export declare function fetchLauncher(signal?: AbortSignal): Promise<{
3
+ entries: {
4
+ id: string;
5
+ kind: "account" | "admin" | "app";
6
+ name: string;
7
+ url: string;
8
+ iconUrl: string;
9
+ }[];
10
+ }>;
@@ -0,0 +1,7 @@
1
+ import { CORE_API_PATHS, LauncherSchema } from '@artemis-apps/contracts';
2
+ import { fetchJson } from '@artemis-apps/web-kit';
3
+ import { relayed } from './entities/entities.api.js';
4
+ /** What the signed-in account can open, from the core through the app's relay. */
5
+ export function fetchLauncher(signal) {
6
+ return fetchJson(relayed(CORE_API_PATHS.launcher), LauncherSchema, { signal });
7
+ }
@@ -0,0 +1,10 @@
1
+ import { type ReactNode } from 'react';
2
+ export interface PlatformProviderProps {
3
+ children: ReactNode;
4
+ }
5
+ /**
6
+ * Makes a web client an app of the platform: shows its manifest until an administrator enrolls
7
+ * it, sends the browser to sign in when needed, and renders `children` only for a signed-in account, in the account's language
8
+ * (the browser's until it is known). Must be rendered inside a `QueryClientProvider`.
9
+ */
10
+ export declare function PlatformProvider({ children }: PlatformProviderProps): import("react").JSX.Element;
@@ -0,0 +1,56 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { detectLocale } from '@artemis-apps/translations';
3
+ import { LocaleProvider, useSharedMessages } from '@artemis-apps/translations/react';
4
+ import { FullPageMessage, RetryMessage } from '@artemis-apps/ui';
5
+ import { navigateToUrl } from '@artemis-apps/web-kit';
6
+ import { useQuery } from '@tanstack/react-query';
7
+ import { useEffect } from 'react';
8
+ import { fetchAppSessionState } from './app-session.api.js';
9
+ import { sessionRedirectUrl } from './session-redirect.js';
10
+ import { UnenrolledPage } from './unenrolled-page.js';
11
+ import { AppSessionContext } from './use-app-session.js';
12
+ const APP_SESSION_QUERY_KEY = ['app-session'];
13
+ /** While unenrolled, the page asks this often whether an administrator enrolled the app. */
14
+ const ENROLLMENT_POLL_MS = 5000;
15
+ function useAppSessionState() {
16
+ return useQuery({
17
+ queryKey: APP_SESSION_QUERY_KEY,
18
+ queryFn: ({ signal }) => fetchAppSessionState(signal),
19
+ staleTime: Number.POSITIVE_INFINITY,
20
+ refetchInterval: (query) => query.state.data?.status === 'unenrolled' ? ENROLLMENT_POLL_MS : false,
21
+ });
22
+ }
23
+ /**
24
+ * Makes a web client an app of the platform: shows its manifest until an administrator enrolls
25
+ * it, sends the browser to sign in when needed, and renders `children` only for a signed-in account, in the account's language
26
+ * (the browser's until it is known). Must be rendered inside a `QueryClientProvider`.
27
+ */
28
+ export function PlatformProvider({ children }) {
29
+ const session = useAppSessionState();
30
+ const locale = session.data?.status === 'authenticated'
31
+ ? session.data.preferences.locale
32
+ : detectLocale(navigator.languages);
33
+ return (_jsx(LocaleProvider, { locale: locale, children: _jsx(PlatformGate, { children: children }) }));
34
+ }
35
+ function PlatformGate({ children }) {
36
+ const session = useAppSessionState();
37
+ const t = useSharedMessages();
38
+ const redirectUrl = session.data ? sessionRedirectUrl(session.data, window.location) : null;
39
+ useEffect(() => {
40
+ if (redirectUrl)
41
+ navigateToUrl(redirectUrl);
42
+ }, [redirectUrl]);
43
+ if (session.isError) {
44
+ return (_jsx(RetryMessage, { serviceName: t.platform.application, error: session.error, onRetry: () => session.refetch() }));
45
+ }
46
+ switch (session.data?.status) {
47
+ case undefined:
48
+ return _jsx(FullPageMessage, { loading: true, title: t.common.loading });
49
+ case 'unenrolled':
50
+ return _jsx(UnenrolledPage, { session: session.data });
51
+ case 'unauthenticated':
52
+ return _jsx(FullPageMessage, { loading: true, title: t.platform.redirectingToSignIn });
53
+ case 'authenticated':
54
+ return (_jsx(AppSessionContext.Provider, { value: session.data, children: children }));
55
+ }
56
+ }
@@ -0,0 +1,9 @@
1
+ import { type AppSessionState } from '@artemis-apps/contracts';
2
+ type CurrentLocation = Pick<Location, 'origin' | 'pathname' | 'search'>;
3
+ /**
4
+ * Where the browser must go before the app can render, or `null` when it renders here: once
5
+ * authenticated, or while unenrolled (the app shows its manifest).
6
+ * Sign-in comes back to the current page through `RETURN_TO_PARAM`.
7
+ */
8
+ export declare function sessionRedirectUrl(session: AppSessionState, location: CurrentLocation): string | null;
9
+ export {};
@@ -0,0 +1,18 @@
1
+ import { RETURN_TO_PARAM } from '@artemis-apps/contracts';
2
+ /**
3
+ * Where the browser must go before the app can render, or `null` when it renders here: once
4
+ * authenticated, or while unenrolled (the app shows its manifest).
5
+ * Sign-in comes back to the current page through `RETURN_TO_PARAM`.
6
+ */
7
+ export function sessionRedirectUrl(session, location) {
8
+ switch (session.status) {
9
+ case 'unauthenticated': {
10
+ const url = new URL(session.signInUrl, location.origin);
11
+ url.searchParams.set(RETURN_TO_PARAM, `${location.pathname}${location.search}`);
12
+ return url.href;
13
+ }
14
+ case 'unenrolled':
15
+ case 'authenticated':
16
+ return null;
17
+ }
18
+ }
@@ -0,0 +1,14 @@
1
+ import { type AppSessionState } from '@artemis-apps/contracts';
2
+ export interface UnenrolledPageProps {
3
+ session: Extract<AppSessionState, {
4
+ status: 'unenrolled';
5
+ }>;
6
+ }
7
+ /** Where the core reviews this app: its administration, told the app's URL (`ENROLL_PARAM`). */
8
+ export declare function enrollmentUrl(coreUrl: string, appUrl: string): string;
9
+ /**
10
+ * What an app shows until an administrator enrolls it: a link to its review in the core, which
11
+ * reads its manifest by itself, and the manifest, to paste when the core cannot reach the app.
12
+ * The session state is polled meanwhile: the page goes on by itself once enrolled.
13
+ */
14
+ export declare function UnenrolledPage({ session: { manifest, coreUrl } }: UnenrolledPageProps): import("react").JSX.Element;