solid-logic 3.0.9-ea192f01 → 3.0.9-ed64096

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.
Files changed (81) hide show
  1. package/package.json +9 -3
  2. package/babel.config.js +0 -6
  3. package/eslint.config.js +0 -28
  4. package/jest.config.js +0 -17
  5. package/rollup.config.js +0 -29
  6. package/src/acl/aclLogic.ts +0 -156
  7. package/src/authSession/authSession.ts +0 -13
  8. package/src/authn/SolidAuthnLogic.ts +0 -126
  9. package/src/authn/authUtil.ts +0 -70
  10. package/src/chat/chatLogic.ts +0 -226
  11. package/src/inbox/inboxLogic.ts +0 -59
  12. package/src/index.ts +0 -21
  13. package/src/issuer/issuerLogic.ts +0 -40
  14. package/src/logic/CustomError.ts +0 -29
  15. package/src/logic/solidLogic.ts +0 -76
  16. package/src/logic/solidLogicSingleton.ts +0 -20
  17. package/src/profile/profileLogic.ts +0 -125
  18. package/src/typeIndex/typeIndexLogic.ts +0 -198
  19. package/src/types.ts +0 -122
  20. package/src/util/containerLogic.ts +0 -53
  21. package/src/util/debug.ts +0 -16
  22. package/src/util/ns.ts +0 -5
  23. package/src/util/utilityLogic.ts +0 -156
  24. package/src/util/utils.ts +0 -52
  25. package/src/versionInfo.ts +0 -32
  26. package/test/aclLogic.test.ts +0 -24
  27. package/test/authUtil.test.ts +0 -23
  28. package/test/chatLogic.test.ts +0 -322
  29. package/test/container.test.ts +0 -58
  30. package/test/helpers/dataSetup.ts +0 -135
  31. package/test/helpers/setup.ts +0 -22
  32. package/test/inboxLogic.test.ts +0 -209
  33. package/test/logic.test.ts +0 -29
  34. package/test/profileLogic.test.ts +0 -248
  35. package/test/solidAuthLogic.test.ts +0 -49
  36. package/test/typeIndexLogic.test.ts +0 -255
  37. package/test/utilityLogic.test.ts +0 -180
  38. package/test/utils.test.ts +0 -32
  39. package/timestamp.sh +0 -13
  40. package/tsconfig.json +0 -77
  41. package/tsconfig.test.json +0 -8
  42. /package/{lib → dist}/acl/aclLogic.d.ts +0 -0
  43. /package/{lib → dist}/acl/aclLogic.d.ts.map +0 -0
  44. /package/{lib → dist}/authSession/authSession.d.ts +0 -0
  45. /package/{lib → dist}/authSession/authSession.d.ts.map +0 -0
  46. /package/{lib → dist}/authn/SolidAuthnLogic.d.ts +0 -0
  47. /package/{lib → dist}/authn/SolidAuthnLogic.d.ts.map +0 -0
  48. /package/{lib → dist}/authn/authUtil.d.ts +0 -0
  49. /package/{lib → dist}/authn/authUtil.d.ts.map +0 -0
  50. /package/{lib → dist}/chat/chatLogic.d.ts +0 -0
  51. /package/{lib → dist}/chat/chatLogic.d.ts.map +0 -0
  52. /package/{lib → dist}/inbox/inboxLogic.d.ts +0 -0
  53. /package/{lib → dist}/inbox/inboxLogic.d.ts.map +0 -0
  54. /package/{lib → dist}/index.d.ts +0 -0
  55. /package/{lib → dist}/index.d.ts.map +0 -0
  56. /package/{lib → dist}/issuer/issuerLogic.d.ts +0 -0
  57. /package/{lib → dist}/issuer/issuerLogic.d.ts.map +0 -0
  58. /package/{lib → dist}/logic/CustomError.d.ts +0 -0
  59. /package/{lib → dist}/logic/CustomError.d.ts.map +0 -0
  60. /package/{lib → dist}/logic/solidLogic.d.ts +0 -0
  61. /package/{lib → dist}/logic/solidLogic.d.ts.map +0 -0
  62. /package/{lib → dist}/logic/solidLogicSingleton.d.ts +0 -0
  63. /package/{lib → dist}/logic/solidLogicSingleton.d.ts.map +0 -0
  64. /package/{lib → dist}/profile/profileLogic.d.ts +0 -0
  65. /package/{lib → dist}/profile/profileLogic.d.ts.map +0 -0
  66. /package/{lib → dist}/solid-logic.js +0 -0
  67. /package/{lib → dist}/solid-logic.js.map +0 -0
  68. /package/{lib → dist}/typeIndex/typeIndexLogic.d.ts +0 -0
  69. /package/{lib → dist}/typeIndex/typeIndexLogic.d.ts.map +0 -0
  70. /package/{lib → dist}/types.d.ts +0 -0
  71. /package/{lib → dist}/types.d.ts.map +0 -0
  72. /package/{lib → dist}/util/containerLogic.d.ts +0 -0
  73. /package/{lib → dist}/util/containerLogic.d.ts.map +0 -0
  74. /package/{lib → dist}/util/debug.d.ts +0 -0
  75. /package/{lib → dist}/util/debug.d.ts.map +0 -0
  76. /package/{lib → dist}/util/ns.d.ts +0 -0
  77. /package/{lib → dist}/util/ns.d.ts.map +0 -0
  78. /package/{lib → dist}/util/utilityLogic.d.ts +0 -0
  79. /package/{lib → dist}/util/utilityLogic.d.ts.map +0 -0
  80. /package/{lib → dist}/util/utils.d.ts +0 -0
  81. /package/{lib → dist}/util/utils.d.ts.map +0 -0
@@ -1,226 +0,0 @@
1
- import { NamedNode, Node, st, term } from 'rdflib'
2
- import { ChatLogic, CreatedPaneOptions, NewPaneOptions, Chat } from '../types'
3
- import { ns as namespace } from '../util/ns'
4
- import { determineChatContainer, newThing } from '../util/utils'
5
-
6
- const CHAT_LOCATION_IN_CONTAINER = 'index.ttl#this'
7
-
8
- export function createChatLogic(store, profileLogic): ChatLogic {
9
- const ns = namespace
10
-
11
- async function setAcl(
12
- chatContainer: NamedNode,
13
- me: NamedNode,
14
- invitee: NamedNode
15
- ): Promise<void> {
16
- // Some servers don't present a Link http response header
17
- // if the container doesn't exist yet, so refetch the container
18
- // now that it has been created:
19
- await store.fetcher.load(chatContainer)
20
-
21
- // FIXME: check the Why value on this quad:
22
- const chatAclDoc = store.any(
23
- chatContainer,
24
- new NamedNode('http://www.iana.org/assignments/link-relations/acl')
25
- )
26
- if (!chatAclDoc) {
27
- throw new Error('Chat ACL doc not found!')
28
- }
29
-
30
- const aclBody = `
31
- @prefix acl: <http://www.w3.org/ns/auth/acl#>.
32
- <#owner>
33
- a acl:Authorization;
34
- acl:agent <${me.value}>;
35
- acl:accessTo <.>;
36
- acl:default <.>;
37
- acl:mode
38
- acl:Read, acl:Write, acl:Control.
39
- <#invitee>
40
- a acl:Authorization;
41
- acl:agent <${invitee.value}>;
42
- acl:accessTo <.>;
43
- acl:default <.>;
44
- acl:mode
45
- acl:Read, acl:Append.
46
- `
47
- await store.fetcher.webOperation('PUT', chatAclDoc.value, {
48
- data: aclBody,
49
- contentType: 'text/turtle',
50
- })
51
- }
52
-
53
- async function addToPrivateTypeIndex(chatThing, me) {
54
- // Add to private type index
55
- const privateTypeIndex = store.any(
56
- me,
57
- ns.solid('privateTypeIndex')
58
- ) as NamedNode | null
59
- if (!privateTypeIndex) {
60
- throw new Error('Private type index not found!')
61
- }
62
- await store.fetcher.load(privateTypeIndex)
63
- const reg = newThing(privateTypeIndex)
64
- const ins = [
65
- st(
66
- reg,
67
- ns.rdf('type'),
68
- ns.solid('TypeRegistration'),
69
- privateTypeIndex.doc()
70
- ),
71
- st(
72
- reg,
73
- ns.solid('forClass'),
74
- ns.meeting('LongChat'),
75
- privateTypeIndex.doc()
76
- ),
77
- st(reg, ns.solid('instance'), chatThing, privateTypeIndex.doc()),
78
- ]
79
- await new Promise((resolve, reject) => {
80
- store.updater.update([], ins, function (_uri, ok, errm) {
81
- if (!ok) {
82
- reject(new Error(errm))
83
- } else {
84
- resolve(null)
85
- }
86
- })
87
- })
88
- }
89
-
90
- async function findChat(invitee: NamedNode): Promise<Chat> {
91
- const me = await profileLogic.loadMe()
92
- const podRoot = await profileLogic.getPodRoot(me)
93
- const chatContainer = determineChatContainer(invitee, podRoot)
94
- let exists = true
95
- try {
96
- await store.fetcher.load(
97
- new NamedNode(chatContainer.value + 'index.ttl#this')
98
- )
99
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
100
- } catch (e) {
101
- exists = false
102
- }
103
- return { me, chatContainer, exists }
104
- }
105
-
106
- async function createChatThing(
107
- chatContainer: NamedNode,
108
- me: NamedNode
109
- ): Promise<NamedNode> {
110
- const created = await mintNew({
111
- me,
112
- newBase: chatContainer.value,
113
- })
114
- return created.newInstance
115
- }
116
-
117
- function mintNew(newPaneOptions: NewPaneOptions): Promise<CreatedPaneOptions> {
118
- const kb = store
119
- const updater = kb.updater
120
- if (newPaneOptions.me && !newPaneOptions.me.uri) {
121
- throw new Error('chat mintNew: Invalid userid ' + newPaneOptions.me)
122
- }
123
-
124
- const newInstance = (newPaneOptions.newInstance =
125
- newPaneOptions.newInstance ||
126
- kb.sym(newPaneOptions.newBase + CHAT_LOCATION_IN_CONTAINER))
127
- const newChatDoc = newInstance.doc()
128
-
129
- kb.add(
130
- newInstance,
131
- ns.rdf('type'),
132
- ns.meeting('LongChat'),
133
- newChatDoc
134
- )
135
- kb.add(newInstance, ns.dc('title'), 'Chat channel', newChatDoc)
136
- kb.add(
137
- newInstance,
138
- ns.dc('created'),
139
- term<Node>(new Date(Date.now())),
140
- newChatDoc
141
- )
142
- if (newPaneOptions.me) {
143
- kb.add(newInstance, ns.dc('author'), newPaneOptions.me, newChatDoc)
144
- }
145
-
146
- return new Promise(function (resolve, reject) {
147
- updater?.put(
148
- newChatDoc,
149
- kb.statementsMatching(undefined, undefined, undefined, newChatDoc),
150
- 'text/turtle',
151
- function (uri2, ok, message) {
152
- if (ok) {
153
- resolve({
154
- ...newPaneOptions,
155
- newInstance,
156
- })
157
- } else {
158
- reject(
159
- new Error(
160
- 'FAILED to save new chat channel at: ' + uri2 + ' : ' + message
161
- )
162
- )
163
- }
164
- }
165
- )
166
- })
167
- }
168
-
169
- /**
170
- * Find (and optionally create) an individual chat between the current user and the given invitee
171
- * @param invitee - The person to chat with
172
- * @param createIfMissing - Whether the chat should be created, if missing
173
- * @returns null if missing, or a node referring to an already existing chat, or the newly created chat
174
- */
175
- async function getChat(
176
- invitee: NamedNode,
177
- createIfMissing = true
178
- ): Promise<NamedNode | null> {
179
- const { me, chatContainer, exists } = await findChat(invitee)
180
- if (exists) {
181
- return new NamedNode(chatContainer.value + CHAT_LOCATION_IN_CONTAINER)
182
- }
183
-
184
- if (createIfMissing) {
185
- const chatThing = await createChatThing(chatContainer, me)
186
- await sendInvite(invitee, chatThing)
187
- await setAcl(chatContainer, me, invitee)
188
- await addToPrivateTypeIndex(chatThing, me)
189
- return chatThing
190
- }
191
- return null
192
- }
193
-
194
- async function sendInvite(invitee: NamedNode, chatThing: NamedNode) {
195
- await store.fetcher.load(invitee.doc())
196
- const inviteeInbox = store.any(
197
- invitee,
198
- ns.ldp('inbox'),
199
- undefined,
200
- invitee.doc()
201
- )
202
- if (!inviteeInbox) {
203
- throw new Error(`Invitee inbox not found! ${invitee.value}`)
204
- }
205
- const inviteBody = `
206
- <> a <http://www.w3.org/ns/pim/meeting#LongChatInvite> ;
207
- ${ns.rdf('seeAlso')} <${chatThing.value}> .
208
- `
209
-
210
- const inviteResponse = await store.fetcher?.webOperation(
211
- 'POST',
212
- inviteeInbox.value,
213
- {
214
- data: inviteBody,
215
- contentType: 'text/turtle',
216
- }
217
- )
218
- const locationStr = inviteResponse?.headers.get('location')
219
- if (!locationStr) {
220
- throw new Error(`Invite sending returned a ${inviteResponse?.status}`)
221
- }
222
- }
223
- return {
224
- setAcl, addToPrivateTypeIndex, findChat, createChatThing, getChat, sendInvite, mintNew
225
- }
226
- }
@@ -1,59 +0,0 @@
1
- import { NamedNode } from 'rdflib'
2
- import { InboxLogic } from '../types'
3
- import { getArchiveUrl } from '../util/utils'
4
-
5
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
6
- export function createInboxLogic(store, profileLogic, utilityLogic, containerLogic, aclLogic): InboxLogic {
7
-
8
- async function createInboxFor(peerWebId: string, nick: string) {
9
- const myWebId: NamedNode = await profileLogic.loadMe()
10
- const podRoot: NamedNode = await profileLogic.getPodRoot(myWebId)
11
- const ourInbox = `${podRoot.value}p2p-inboxes/${encodeURIComponent(nick)}/`
12
- await containerLogic.createContainer(ourInbox)
13
- // const aclDocUrl = await aclLogic.findAclDocUrl(ourInbox);
14
- await utilityLogic.setSinglePeerAccess({
15
- ownerWebId: myWebId.value,
16
- peerWebId,
17
- accessToModes: 'acl:Append',
18
- target: ourInbox
19
- })
20
- return ourInbox
21
- }
22
-
23
- async function getNewMessages(
24
- user?: NamedNode
25
- ): Promise<NamedNode[]> {
26
- if (!user) {
27
- user = await profileLogic.loadMe()
28
- }
29
- const inbox = await profileLogic.getMainInbox(user)
30
- const urls = await containerLogic.getContainerMembers(inbox)
31
- return urls.filter(url => !containerLogic.isContainer(url))
32
- }
33
-
34
- async function markAsRead(url: string, date: Date) {
35
- const downloaded = await store.fetcher._fetch(url)
36
- if (downloaded.status !== 200) {
37
- throw new Error(`Not OK! ${url}`)
38
- }
39
- const archiveUrl = getArchiveUrl(url, date)
40
- const options = {
41
- method: 'PUT',
42
- body: await downloaded.text(),
43
- headers: [
44
- ['Content-Type', downloaded.headers.get('Content-Type') || 'application/octet-stream']
45
- ]
46
- }
47
- const uploaded = await store.fetcher._fetch(archiveUrl, options)
48
- if (uploaded.status.toString()[0] === '2') {
49
- await store.fetcher._fetch(url, {
50
- method: 'DELETE'
51
- })
52
- }
53
- }
54
- return {
55
- createInboxFor,
56
- getNewMessages,
57
- markAsRead
58
- }
59
- }
package/src/index.ts DELETED
@@ -1,21 +0,0 @@
1
- // Make these variables directly accessible as it is what you need most of the time
2
- // This also makes these variable globaly accesible in mashlib
3
- import { solidLogicSingleton } from './logic/solidLogicSingleton'
4
-
5
- const authn = solidLogicSingleton.authn
6
- const authSession = solidLogicSingleton.authn.authSession
7
- const store = solidLogicSingleton.store
8
-
9
- export { ACL_LINK } from './acl/aclLogic'
10
- export { offlineTestID, appContext } from './authn/authUtil'
11
- export { getSuggestedIssuers } from './issuer/issuerLogic'
12
- export type { AppDetails, SolidNamespace, AuthenticationContext, SolidLogic } from './types'
13
- export { UnauthorizedError, CrossOriginForbiddenError, SameOriginForbiddenError, NotFoundError, FetchError, NotEditableError, WebOperationError } from './logic/CustomError'
14
-
15
- export {
16
- solidLogicSingleton, // solidLogicSingleton is exported entirely because it is used in solid-panes
17
- store,
18
- authn,
19
- authSession
20
- }
21
-
@@ -1,40 +0,0 @@
1
- const DEFAULT_ISSUERS = [
2
- {
3
- name: 'Solid Community',
4
- uri: 'https://solidcommunity.net'
5
- },
6
- {
7
- name: 'Solid Web',
8
- uri: 'https://solidweb.org'
9
- },
10
- {
11
- name: 'Inrupt.net',
12
- uri: 'https://inrupt.net'
13
- },
14
- {
15
- name: 'pod.Inrupt.com',
16
- uri: 'https://login.inrupt.com'
17
- }
18
- ]
19
-
20
- /**
21
- * @returns - A list of suggested OIDC issuers
22
- */
23
- export function getSuggestedIssuers (): { name: string, uri: string }[] {
24
- // Suggest a default list of OIDC issuers
25
- const issuers = [...DEFAULT_ISSUERS]
26
-
27
- // Suggest the current host if not already included
28
- const { host, origin } = new URL(location.href)
29
- const hosts = issuers.map(({ uri }) => new URL(uri).host)
30
- if (!hosts.includes(host) && !hosts.some(existing => isSubdomainOf(host, existing))) {
31
- issuers.unshift({ name: host, uri: origin })
32
- }
33
-
34
- return issuers
35
- }
36
-
37
- function isSubdomainOf (subdomain: string, domain: string): boolean {
38
- const dot = subdomain.length - domain.length - 1
39
- return dot > 0 && subdomain[dot] === '.' && subdomain.endsWith(domain)
40
- }
@@ -1,29 +0,0 @@
1
- class CustomError extends Error {
2
- constructor(message?: string) {
3
- super(message)
4
- // see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html
5
- Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain
6
- this.name = new.target.name // stack traces display correctly now
7
- }
8
- }
9
-
10
- export class UnauthorizedError extends CustomError {}
11
-
12
- export class CrossOriginForbiddenError extends CustomError {}
13
-
14
- export class SameOriginForbiddenError extends CustomError {}
15
-
16
- export class NotFoundError extends CustomError {}
17
-
18
- export class NotEditableError extends CustomError { }
19
-
20
- export class WebOperationError extends CustomError {}
21
-
22
- export class FetchError extends CustomError {
23
- status: number
24
-
25
- constructor(status: number, message?: string) {
26
- super(message)
27
- this.status = status
28
- }
29
- }
@@ -1,76 +0,0 @@
1
- import { Session } from '@inrupt/solid-client-authn-browser'
2
- import * as rdf from 'rdflib'
3
- import { LiveStore, NamedNode, Statement } from 'rdflib'
4
- import { createAclLogic } from '../acl/aclLogic'
5
- import { SolidAuthnLogic } from '../authn/SolidAuthnLogic'
6
- import { createChatLogic } from '../chat/chatLogic'
7
- import { createInboxLogic } from '../inbox/inboxLogic'
8
- import { createProfileLogic } from '../profile/profileLogic'
9
- import { createTypeIndexLogic } from '../typeIndex/typeIndexLogic'
10
- import { createContainerLogic } from '../util/containerLogic'
11
- import { createUtilityLogic } from '../util/utilityLogic'
12
- import { AuthnLogic, SolidLogic } from '../types'
13
- import * as debug from '../util/debug'
14
- /*
15
- ** It is important to distinquish `fetch`, a function provided by the browser
16
- ** and `Fetcher`, a helper object for the rdflib Store which turns it
17
- ** into a `ConnectedStore` or a `LiveStore`. A Fetcher object is
18
- ** available at store.fetcher, and `fetch` function at `store.fetcher._fetch`,
19
- */
20
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
- export function createSolidLogic(specialFetch: { fetch: (url: any, requestInit: any) => any }, session: Session): SolidLogic {
22
-
23
- debug.log('SolidLogic: Unique instance created. There should only be one of these.')
24
- const store: LiveStore = rdf.graph() as LiveStore
25
- rdf.fetcher(store, {fetch: specialFetch.fetch}) // Attach a web I/O module, store.fetcher
26
- store.updater = new rdf.UpdateManager(store) // Add real-time live updates store.updater
27
- store.features = [] // disable automatic node merging on store load
28
-
29
- const authn: AuthnLogic = new SolidAuthnLogic(session)
30
-
31
- const acl = createAclLogic(store)
32
- const containerLogic = createContainerLogic(store)
33
- const utilityLogic = createUtilityLogic(store, acl, containerLogic)
34
- const profile = createProfileLogic(store, authn, utilityLogic)
35
- const chat = createChatLogic(store, profile)
36
- const inbox = createInboxLogic(store, profile, utilityLogic, containerLogic, acl)
37
- const typeIndex = createTypeIndexLogic(store, authn, profile, utilityLogic)
38
- debug.log('SolidAuthnLogic initialized')
39
-
40
- function load(doc: NamedNode | NamedNode[] | string) {
41
- return store.fetcher.load(doc)
42
- }
43
-
44
- // @@@@ use the one in rdflib.js when it is available and delete this
45
- function updatePromise(
46
- del: Array<Statement>,
47
- ins: Array<Statement> = []
48
- ): Promise<void> {
49
- return new Promise((resolve, reject) => {
50
- store.updater.update(del, ins, function (_uri, ok, errorBody) {
51
- if (!ok) {
52
- reject(new Error(errorBody))
53
- } else {
54
- resolve()
55
- }
56
- }) // callback
57
- }) // promise
58
- }
59
-
60
- function clearStore() {
61
- store.statements.slice().forEach(store.remove.bind(store))
62
- }
63
-
64
- return {
65
- store,
66
- authn,
67
- acl,
68
- inbox,
69
- chat,
70
- profile,
71
- typeIndex,
72
- load,
73
- updatePromise,
74
- clearStore
75
- }
76
- }
@@ -1,20 +0,0 @@
1
- import * as debug from '../util/debug'
2
- import { authSession } from '../authSession/authSession'
3
- import { createSolidLogic } from './solidLogic'
4
-
5
- const _fetch = async (url, requestInit) => {
6
- const omitCreds = requestInit && requestInit.credentials && requestInit.credentials == 'omit'
7
- if (authSession.info.webId && !omitCreds) { // see https://github.com/solidos/solidos/issues/114
8
- // In fact fetch should respect credentials omit itself
9
- return authSession.fetch(url, requestInit)
10
- } else {
11
- return window.fetch(url, requestInit)
12
- }
13
- }
14
-
15
- //this const makes solidLogicSingleton global accessible in mashlib
16
- const solidLogicSingleton = createSolidLogic({ fetch: _fetch }, authSession)
17
-
18
- debug.log('Unique quadstore initialized.')
19
-
20
- export { solidLogicSingleton }
@@ -1,125 +0,0 @@
1
- import { NamedNode } from 'rdflib'
2
- import { CrossOriginForbiddenError, FetchError, NotEditableError, SameOriginForbiddenError, UnauthorizedError, WebOperationError } from '../logic/CustomError'
3
- import * as debug from '../util/debug'
4
- import { ns as namespace } from '../util/ns'
5
- import { differentOrigin, suggestPreferencesFile } from '../util/utils'
6
- import { ProfileLogic } from '../types'
7
-
8
- export function createProfileLogic(store, authn, utilityLogic): ProfileLogic {
9
- const ns = namespace
10
-
11
- /**
12
- * loads the preference without throwing errors - if it can create it it does so.
13
- * remark: it still throws error if it cannot load profile.
14
- * @param user
15
- * @returns undefined if preferenceFile cannot be returned or NamedNode if it can find it or create it
16
- */
17
- async function silencedLoadPreferences(user: NamedNode): Promise <NamedNode | undefined> {
18
- try {
19
- return await loadPreferences(user)
20
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
21
- } catch (err) {
22
- return undefined
23
- }
24
- }
25
-
26
- /**
27
- * loads the preference without returning different errors if it cannot create or load it.
28
- * remark: it also throws error if it cannot load profile.
29
- * @param user
30
- * @returns undefined if preferenceFile cannot be an Error or NamedNode if it can find it or create it
31
- */
32
- async function loadPreferences (user: NamedNode): Promise <NamedNode> {
33
- await loadProfile(user)
34
-
35
- const possiblePreferencesFile = suggestPreferencesFile(user)
36
- let preferencesFile
37
- try {
38
- preferencesFile = await utilityLogic.followOrCreateLink(user, ns.space('preferencesFile') as NamedNode, possiblePreferencesFile, user.doc())
39
- } catch (err) {
40
- const message = `User ${user} has no pointer in profile to preferences file.`
41
- debug.warn(message)
42
- // we are listing the possible errors
43
- if (err instanceof NotEditableError) { throw err }
44
- if (err instanceof WebOperationError) { throw err }
45
- if (err instanceof UnauthorizedError) { throw err }
46
- if (err instanceof CrossOriginForbiddenError) { throw err }
47
- if (err instanceof SameOriginForbiddenError) { throw err }
48
- if (err instanceof FetchError) { throw err }
49
- throw err
50
- }
51
-
52
- try {
53
- await store.fetcher.load(preferencesFile as NamedNode)
54
- } catch (err) { // Maybe a permission problem or origin problem
55
- const msg = `Unable to load preference of user ${user}: ${err}`
56
- debug.warn(msg)
57
- if (err.response.status === 401) {
58
- throw new UnauthorizedError()
59
- }
60
- if (err.response.status === 403) {
61
- if (differentOrigin(preferencesFile)) {
62
- throw new CrossOriginForbiddenError()
63
- }
64
- throw new SameOriginForbiddenError()
65
- }
66
- /*if (err.response.status === 404) {
67
- throw new NotFoundError();
68
- }*/
69
- throw new Error(msg)
70
- }
71
- return preferencesFile as NamedNode
72
- }
73
-
74
- async function loadProfile (user: NamedNode):Promise <NamedNode> {
75
- if (!user) {
76
- throw new Error('loadProfile: no user given.')
77
- }
78
- try {
79
- await store.fetcher.load(user.doc())
80
- } catch (err) {
81
- throw new Error(`Unable to load profile of user ${user}: ${err}`)
82
- }
83
- return user.doc()
84
- }
85
-
86
- async function loadMe(): Promise<NamedNode> {
87
- const me = authn.currentUser()
88
- if (me === null) {
89
- throw new Error('Current user not found! Not logged in?')
90
- }
91
- await store.fetcher.load(me.doc())
92
- return me
93
- }
94
-
95
- function getPodRoot(user: NamedNode): NamedNode {
96
- const podRoot = findStorage(user)
97
- if (!podRoot) {
98
- throw new Error('User pod root not found!')
99
- }
100
- return podRoot as NamedNode
101
- }
102
-
103
- async function getMainInbox(user: NamedNode): Promise<NamedNode> {
104
- await store.fetcher.load(user)
105
- const mainInbox = store.any(user, ns.ldp('inbox'), undefined, user.doc())
106
- if (!mainInbox) {
107
- throw new Error('User main inbox not found!')
108
- }
109
- return mainInbox as NamedNode
110
- }
111
-
112
- function findStorage(me: NamedNode) {
113
- return store.any(me, ns.space('storage'), undefined, me.doc())
114
- }
115
-
116
- return {
117
- loadMe,
118
- getPodRoot,
119
- getMainInbox,
120
- findStorage,
121
- loadPreferences,
122
- loadProfile,
123
- silencedLoadPreferences
124
- }
125
- }