@jsb188/graphql 1.1.11 → 1.1.13
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.
- package/LICENSE +21 -0
- package/audience.d.ts +205 -0
- package/cache/config.ts +65 -28
- package/cache/index.helpers.ts +96 -0
- package/cache/index.ts +364 -808
- package/cache/mounted-queries.ts +33 -0
- package/cache/optimistic-ui-runtime.ts +46 -0
- package/cache/optimistic-ui.ts +401 -0
- package/cache/persist.ts +107 -22
- package/cache/realtime-fence.ts +47 -0
- package/cache/realtime-live.ts +17 -0
- package/cache/store.ts +22 -64
- package/cache/value.helpers.ts +17 -0
- package/{drafts/store.ts → client/draft-persistence-indexed-db.ts} +19 -3
- package/{drafts/index.ts → client/draft-persistence.ts} +13 -39
- package/client/index.ts +4 -2
- package/client/request.helpers.ts +14 -0
- package/client/request.ts +122 -232
- package/client/storage-asset.ts +58 -0
- package/gql/fragments/accountAuthFragments.ts +0 -4
- package/gql/fragments/agentMemoryFragments.ts +5 -1
- package/gql/fragments/agentNoteFragments.ts +156 -0
- package/gql/fragments/aiChatFragments.ts +35 -11
- package/gql/fragments/aiChatLinkFragments.ts +8 -0
- package/gql/fragments/audienceFragments.ts +76 -0
- package/gql/fragments/dataTableFragments.ts +48 -80
- package/gql/fragments/emailFragments.ts +49 -21
- package/gql/fragments/emailOutreachFragments.ts +281 -0
- package/gql/fragments/fieldDocFragments.ts +222 -40
- package/gql/fragments/inboundContactFragments.ts +2 -0
- package/gql/fragments/libraryFragments.ts +120 -0
- package/gql/fragments/logFragments.ts +93 -2
- package/gql/fragments/organizationFragments.ts +12 -0
- package/gql/fragments/qrCodeFragments.ts +29 -0
- package/gql/fragments/scheduleFragments.ts +574 -145
- package/gql/fragments/sheetFragments.ts +86 -424
- package/gql/fragments/storageFragments.ts +25 -1
- package/gql/fragments/workWaitFragments.ts +13 -0
- package/gql/fragments/workflowFragments.ts +32 -4
- package/gql/mutations/agentMemoryMutations.ts +32 -0
- package/gql/mutations/agentNoteMutations.ts +64 -0
- package/gql/mutations/aiChatLinkMutations.ts +13 -0
- package/gql/mutations/aiChatMutations.ts +34 -4
- package/gql/mutations/audienceMutations.ts +58 -0
- package/gql/mutations/authMutations.ts +24 -28
- package/gql/mutations/billingMutations.ts +24 -0
- package/gql/mutations/contactMutations.ts +23 -0
- package/gql/mutations/dataTableMutations.ts +18 -75
- package/gql/mutations/emailMutations.ts +22 -0
- package/gql/mutations/emailOutreachMutations.ts +139 -0
- package/gql/mutations/fieldDocMutations.ts +162 -13
- package/gql/mutations/index.ts +10 -5
- package/gql/mutations/organizationMutations.ts +6 -0
- package/gql/mutations/qrCodeMutations.ts +20 -0
- package/gql/mutations/scheduleMutations.ts +389 -417
- package/gql/mutations/sheetMutations.ts +62 -118
- package/gql/mutations/storageMutations.ts +1 -1
- package/gql/mutations/workflowMutations.ts +94 -0
- package/gql/queries/agentMemoryQueries.ts +12 -2
- package/gql/queries/agentNoteQueries.ts +86 -0
- package/gql/queries/aiChatQueries.ts +63 -12
- package/gql/queries/audienceQueries.ts +104 -0
- package/gql/queries/authQueries.ts +20 -4
- package/gql/queries/billingQueries.ts +114 -9
- package/gql/queries/dataTableQueries.ts +43 -75
- package/gql/queries/emailOutreachQueries.ts +282 -0
- package/gql/queries/emailQueries.ts +48 -64
- package/gql/queries/emailReplyReportQueries.ts +127 -0
- package/gql/queries/fieldDocQueries.ts +128 -98
- package/gql/queries/inboundContactQueries.ts +15 -4
- package/gql/queries/index.ts +5 -3
- package/gql/queries/libraryQueries.ts +112 -0
- package/gql/queries/logQueries.ts +86 -12
- package/gql/queries/organizationQueries.ts +44 -12
- package/gql/queries/qrCodeQueries.ts +27 -0
- package/gql/queries/scheduleQueries.ts +401 -278
- package/gql/queries/sheetQueries.ts +94 -165
- package/gql/queries/storageQueries.ts +11 -4
- package/gql/queries/workflowQueries.ts +61 -12
- package/gql/reactivity.ts +98 -0
- package/gql/recordReads.ts +171 -0
- package/hooks/index.helpers.ts +52 -0
- package/hooks/index.ts +920 -715
- package/hooks/use-agentMemory-mtn.ts +29 -31
- package/hooks/use-agentMemory-qry.ts +15 -3
- package/hooks/use-agentNote-mtn.ts +89 -0
- package/hooks/use-agentNote-qry.ts +162 -0
- package/hooks/use-agentNote-recovery.helpers.ts +58 -0
- package/hooks/use-agentNote-recovery.ts +57 -0
- package/hooks/use-aiChat-mtn.ts +104 -115
- package/hooks/use-aiChat-qry.helpers.ts +124 -0
- package/hooks/use-aiChat-qry.ts +254 -387
- package/hooks/use-aiChat-stream-mtn.ts +14 -0
- package/hooks/use-audience-mtn.ts +170 -0
- package/hooks/use-audience-qry.helpers.ts +39 -0
- package/hooks/use-audience-qry.ts +245 -0
- package/hooks/use-auth-mtn.ts +30 -1
- package/hooks/use-billing-mtn.ts +31 -0
- package/hooks/use-billing-qry.ts +76 -0
- package/hooks/use-dataTable-mtn.ts +23 -115
- package/hooks/use-dataTable-qry.ts +69 -914
- package/hooks/use-email-mtn.ts +26 -0
- package/hooks/use-email-qry.helpers.ts +37 -0
- package/hooks/use-email-qry.ts +44 -174
- package/hooks/use-emailOutreach-mtn.ts +211 -0
- package/hooks/use-emailOutreach-qry.helpers.ts +25 -0
- package/hooks/use-emailOutreach-qry.ts +367 -0
- package/hooks/use-emailOutreachReplyReport-qry.ts +46 -0
- package/hooks/use-fieldDoc-mtn.ts +244 -32
- package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
- package/hooks/use-fieldDoc-qry.ts +134 -102
- package/hooks/use-inboundContact-qry.ts +7 -9
- package/hooks/use-library-qry.ts +233 -0
- package/hooks/use-log-mtn.ts +25 -12
- package/hooks/use-log-qry.ts +99 -46
- package/hooks/use-organization-qry.ts +16 -60
- package/hooks/use-qrCode-mtn.ts +40 -0
- package/hooks/use-qrCode-qry.ts +78 -0
- package/hooks/use-schedule-mtn.ts +231 -348
- package/hooks/use-schedule-qry.ts +208 -139
- package/hooks/use-schedule-reactive.ts +218 -0
- package/hooks/use-sheet-mtn.ts +91 -199
- package/hooks/use-sheet-qry.ts +88 -237
- package/hooks/use-storage-qry.ts +84 -61
- package/hooks/use-workflow-mtn.ts +84 -23
- package/hooks/use-workflow-qry.ts +60 -61
- package/libs/ai-chat-link-events.ts +78 -0
- package/libs/ai-chat-outgoing.helpers.ts +153 -0
- package/libs/ai-chat-outgoing.ts +11 -0
- package/libs/ai-chat-outgoing.types.ts +25 -0
- package/libs/ai-chat-run-realtime.ts +20 -0
- package/libs/ai-chat-submission-realtime.ts +150 -0
- package/libs/data-changes.helpers.ts +161 -0
- package/libs/data-changes.ts +382 -0
- package/libs/fragment-realtime-sequence.ts +55 -0
- package/libs/open-sheet.ts +138 -0
- package/libs/record-read.ts +327 -0
- package/libs/sheet-command-batch.ts +45 -0
- package/libs/sheet-realtime-packet.ts +53 -0
- package/libs/sheet-view-realtime-router.ts +99 -0
- package/loaders/emailPreference.ts +69 -0
- package/loaders/rest.ts +12 -0
- package/package.json +77 -25
- package/schedule.d.ts +1183 -0
- package/sse.helpers.ts +19 -0
- package/sse.ts +26 -115
- package/types.d.ts +48 -25
- package/cache/index.test.ts +0 -881
- package/client/data-table-realtime-subscriptions.test.ts +0 -740
- package/client/data-table-realtime-subscriptions.ts +0 -955
- package/client/data-table-realtime.test.ts +0 -792
- package/client/data-table-realtime.ts +0 -1218
- package/client/fragment-realtime-sequence.ts +0 -52
- package/client/open-sheet.ts +0 -137
- package/client/request-managed-session.test.ts +0 -574
- package/client/request-no-store.test.ts +0 -157
- package/client/sse-ticket.test.ts +0 -26
- package/deno.lock +0 -170
- package/deno.test.json +0 -10
- package/gql/fragments/agentDocFragments.ts +0 -46
- package/gql/fragments/billingFragments.ts +0 -14
- package/gql/fragments/campaignFragments.ts +0 -277
- package/gql/mutations/agentDocMutations.ts +0 -177
- package/gql/mutations/campaignMutations.ts +0 -215
- package/gql/queries/agentDocQueries.ts +0 -120
- package/gql/queries/appQueries.ts +0 -14
- package/gql/queries/campaignQueries.ts +0 -127
- package/hooks/use-agentDoc-mtn.ts +0 -285
- package/hooks/use-agentDoc-qry.ts +0 -208
- package/hooks/use-app-qry.ts +0 -22
- package/hooks/use-campaign-mtn.ts +0 -377
- package/hooks/use-campaign-qry.ts +0 -257
- package/loaders/campaign.ts +0 -137
- package/tsconfig.json +0 -13
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
const FRAGMENT_REALTIME_SEQUENCES = new Map<string, string>();
|
|
2
|
+
let fragmentRealtimeEpoch = 0;
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* Compare two unsigned decimal sequence strings without narrowing them to
|
|
6
|
+
* JavaScript's unsafe integer range.
|
|
7
|
+
*/
|
|
8
|
+
function compareFragmentRealtimeSequences(left: string, right: string) {
|
|
9
|
+
const normalizedLeft = left.replace(/^0+(?=\d)/, '');
|
|
10
|
+
const normalizedRight = right.replace(/^0+(?=\d)/, '');
|
|
11
|
+
|
|
12
|
+
if (normalizedLeft.length !== normalizedRight.length) {
|
|
13
|
+
return normalizedLeft.length > normalizedRight.length ? 1 : -1;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
return normalizedLeft === normalizedRight ? 0 : normalizedLeft > normalizedRight ? 1 : -1;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/*
|
|
20
|
+
* Check ordering without advancing the fence, for a thin change whose record
|
|
21
|
+
* is read through an authorized single-record read.
|
|
22
|
+
*/
|
|
23
|
+
export function isFragmentRealtimeSequenceCurrent(fragmentKey: string, sequence?: string) {
|
|
24
|
+
if (!sequence || !/^\d+$/.test(sequence)) {
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const currentSequence = FRAGMENT_REALTIME_SEQUENCES.get(fragmentKey);
|
|
29
|
+
if (currentSequence && compareFragmentRealtimeSequences(sequence, currentSequence) < 0) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/* Accept an update and advance its sequence only when its data can be applied. */
|
|
37
|
+
export function shouldApplyFragmentRealtimeSequence(fragmentKey: string, sequence?: string) {
|
|
38
|
+
if (!isFragmentRealtimeSequenceCurrent(fragmentKey, sequence)) return false;
|
|
39
|
+
if (sequence && /^\d+$/.test(sequence)) FRAGMENT_REALTIME_SEQUENCES.set(fragmentKey, sequence);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/* Bind asynchronous record reads to the current authorization/cache lifetime. */
|
|
44
|
+
export function getFragmentRealtimeEpoch() {
|
|
45
|
+
return fragmentRealtimeEpoch;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/*
|
|
49
|
+
* Clear fragment sequence fences when authorization-bound cache state is
|
|
50
|
+
* discarded.
|
|
51
|
+
*/
|
|
52
|
+
export function clearFragmentRealtimeSequences() {
|
|
53
|
+
fragmentRealtimeEpoch += 1;
|
|
54
|
+
FRAGMENT_REALTIME_SEQUENCES.clear();
|
|
55
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
SheetBootstrapGQL,
|
|
3
|
+
SheetJournalSeqInput,
|
|
4
|
+
SheetRealtimeCapabilityGQL,
|
|
5
|
+
SheetTabBootstrapGQL,
|
|
6
|
+
} from '@jsb188/mday/types/sheet.d.ts';
|
|
7
|
+
import { parseSheetJournalSeq } from '@jsb188/mday/utils/sheetSequence.ts';
|
|
8
|
+
import { graphqlRequestNoStore } from '../client/request.ts';
|
|
9
|
+
import { openSheetQry, renewSheetRealtimeCapabilityQry, syncSheetTabQry } from '../gql/queries/sheetQueries.ts';
|
|
10
|
+
|
|
11
|
+
/*
|
|
12
|
+
* Bootstrap contract 4 (DESIGN §1.3): openSheet negotiates the workbook and
|
|
13
|
+
* its selected tab, syncSheetTab one tab once the manifest is known. Both ask
|
|
14
|
+
* for the rows after the tab's applied `sinceSeq` (DELTA) and fall back to a
|
|
15
|
+
* snapshot plus its tail; there is no viewport and no base-snapshot proof.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export type FetchOpenSheetOnceParams = {
|
|
19
|
+
selectedTabId?: string | null;
|
|
20
|
+
sinceSeq?: SheetJournalSeqInput;
|
|
21
|
+
requireSnapshot?: boolean;
|
|
22
|
+
|
|
23
|
+
authToken?: string | null;
|
|
24
|
+
signal?: AbortSignal | null;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type FetchSyncSheetTabOnceParams = {
|
|
28
|
+
sinceSeq?: SheetJournalSeqInput;
|
|
29
|
+
requireSnapshot?: boolean;
|
|
30
|
+
minimumCellsRevision?: SheetJournalSeqInput;
|
|
31
|
+
minimumDesignRevision?: SheetJournalSeqInput;
|
|
32
|
+
|
|
33
|
+
authToken?: string | null;
|
|
34
|
+
signal?: AbortSignal | null;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/*
|
|
38
|
+
* Return the canonical openSheet variables of one fetch. Journal cursors are
|
|
39
|
+
* sent as canonical decimal strings; an absent or malformed one is null..
|
|
40
|
+
*/
|
|
41
|
+
export function getOpenSheetQueryVariables(sheetId: string, params: FetchOpenSheetOnceParams = {}) {
|
|
42
|
+
return {
|
|
43
|
+
sheetId,
|
|
44
|
+
selectedTabId: params.selectedTabId || null,
|
|
45
|
+
sinceSeq: parseSheetJournalSeq(params.sinceSeq),
|
|
46
|
+
requireSnapshot: Boolean(params.requireSnapshot),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/*
|
|
51
|
+
* Return the canonical syncSheetTab variables of one fetch.
|
|
52
|
+
*/
|
|
53
|
+
export function getSyncSheetTabQueryVariables(sheetId: string, sheetTabId: string, params: FetchSyncSheetTabOnceParams = {}) {
|
|
54
|
+
return {
|
|
55
|
+
sheetId,
|
|
56
|
+
sheetTabId,
|
|
57
|
+
sinceSeq: parseSheetJournalSeq(params.sinceSeq),
|
|
58
|
+
requireSnapshot: Boolean(params.requireSnapshot),
|
|
59
|
+
minimumCellsRevision: parseSheetJournalSeq(params.minimumCellsRevision),
|
|
60
|
+
minimumDesignRevision: parseSheetJournalSeq(params.minimumDesignRevision),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/*
|
|
65
|
+
* Return one no-store operation's field, throwing an AbortError for an
|
|
66
|
+
* aborted request and the normalized server error for a failed one.
|
|
67
|
+
*/
|
|
68
|
+
function getSheetBootstrapOperationResult<T>(
|
|
69
|
+
result: any,
|
|
70
|
+
operation: 'openSheet' | 'renewSheetRealtimeCapability' | 'syncSheetTab',
|
|
71
|
+
): T | null {
|
|
72
|
+
if (result?.aborted) {
|
|
73
|
+
throw new DOMException(`${operation} request was aborted.`, 'AbortError');
|
|
74
|
+
}
|
|
75
|
+
if (result?.error) {
|
|
76
|
+
throw result.error;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return result?.[operation] || null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/*
|
|
83
|
+
* Imperatively fetch one openSheet response exactly once without reading,
|
|
84
|
+
* writing, or joining the normalized GraphQL cache. Each invocation owns its
|
|
85
|
+
* network request and carries its authorization token only in request headers.
|
|
86
|
+
*/
|
|
87
|
+
export async function fetchOpenSheetOnce(sheetId: string, params: FetchOpenSheetOnceParams = {}): Promise<SheetBootstrapGQL | null> {
|
|
88
|
+
const result = await graphqlRequestNoStore(
|
|
89
|
+
openSheetQry,
|
|
90
|
+
getOpenSheetQueryVariables(sheetId, params),
|
|
91
|
+
{ authToken: params.authToken },
|
|
92
|
+
params.signal,
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
return getSheetBootstrapOperationResult<SheetBootstrapGQL>(result, 'openSheet');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/*
|
|
99
|
+
* Renew one Sheet's realtime capability without reading or writing the normalized GraphQL cache.
|
|
100
|
+
*/
|
|
101
|
+
export async function fetchSheetRealtimeCapabilityOnce(
|
|
102
|
+
sheetId: string,
|
|
103
|
+
params: {
|
|
104
|
+
authToken?: string | null;
|
|
105
|
+
|
|
106
|
+
signal?: AbortSignal | null;
|
|
107
|
+
} = {},
|
|
108
|
+
): Promise<SheetRealtimeCapabilityGQL | null> {
|
|
109
|
+
const result = await graphqlRequestNoStore(
|
|
110
|
+
renewSheetRealtimeCapabilityQry,
|
|
111
|
+
{
|
|
112
|
+
sheetId,
|
|
113
|
+
},
|
|
114
|
+
{ authToken: params.authToken },
|
|
115
|
+
params.signal,
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
return getSheetBootstrapOperationResult<SheetRealtimeCapabilityGQL>(result, 'renewSheetRealtimeCapability');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/*
|
|
122
|
+
* Synchronize one tab through the snapshot/delta negotiation without
|
|
123
|
+
* consulting or mutating the normalized GraphQL cache.
|
|
124
|
+
*/
|
|
125
|
+
export async function fetchSyncSheetTabOnce(
|
|
126
|
+
sheetId: string,
|
|
127
|
+
sheetTabId: string,
|
|
128
|
+
params: FetchSyncSheetTabOnceParams = {},
|
|
129
|
+
): Promise<SheetTabBootstrapGQL | null> {
|
|
130
|
+
const result = await graphqlRequestNoStore(
|
|
131
|
+
syncSheetTabQry,
|
|
132
|
+
getSyncSheetTabQueryVariables(sheetId, sheetTabId, params),
|
|
133
|
+
{ authToken: params.authToken },
|
|
134
|
+
params.signal,
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
return getSheetBootstrapOperationResult<SheetTabBootstrapGQL>(result, 'syncSheetTab');
|
|
138
|
+
}
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import type { WSDataChange } from '@jsb188/app/types/app.d.ts';
|
|
2
|
+
import { getAuthToken, getManagedAccessTokenBinding, managedAccessTokensShareBinding } from '@jsb188/app/utils/api.ts';
|
|
3
|
+
import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
|
|
4
|
+
import { DATA_TYPES, type DataTypeKey, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
|
|
5
|
+
import { getGraphQLCacheEpoch, loadFragment, updateFragment } from '../cache/index.ts';
|
|
6
|
+
import { keepNewerRealtimeFields } from '../cache/realtime-fence.ts';
|
|
7
|
+
import { graphqlRequestNoStore } from '../client/request.ts';
|
|
8
|
+
import { RECORD_READS, type RecordRead } from '../gql/recordReads.ts';
|
|
9
|
+
import type { UpdateObserversFn } from '../types.d.ts';
|
|
10
|
+
import { getFragmentRealtimeEpoch, isFragmentRealtimeSequenceCurrent } from './fragment-realtime-sequence.ts';
|
|
11
|
+
|
|
12
|
+
// One record a read serves; a log entry and its details are two targets of one request
|
|
13
|
+
type RecordReadTarget = { read: RecordRead; scope: Record<string, string> };
|
|
14
|
+
// A read that has not started yet; every thin change that arrives before it starts joins it
|
|
15
|
+
type RecordReadCycle = { promise: Promise<void>; resolve: () => void };
|
|
16
|
+
type RecordReadFlight = {
|
|
17
|
+
authToken: string | null;
|
|
18
|
+
epoch: number;
|
|
19
|
+
cacheEpoch: number;
|
|
20
|
+
readEpoch: number;
|
|
21
|
+
id: string;
|
|
22
|
+
query: any;
|
|
23
|
+
variables: Record<string, any>;
|
|
24
|
+
controller: AbortController;
|
|
25
|
+
targets: Map<string, RecordReadTarget>; // Fragment key → target
|
|
26
|
+
startedAt: number; // Start of the latest read; 0 before the first
|
|
27
|
+
running: boolean;
|
|
28
|
+
pending: RecordReadCycle | null;
|
|
29
|
+
timer: ReturnType<typeof setTimeout> | null;
|
|
30
|
+
updateObservers?: UpdateObserversFn;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const RECORD_READ_STATE = {
|
|
34
|
+
// Flight key (operation name and variables within one session) → flight; idle flights stay for their one-second spacing
|
|
35
|
+
flights: new Map<string, RecordReadFlight>(),
|
|
36
|
+
epoch: 0,
|
|
37
|
+
};
|
|
38
|
+
const FILE_CONSTANTS = { attempts: 3, timeoutMs: 10_000, minIntervalMs: 1000, pruneAbove: 500 };
|
|
39
|
+
|
|
40
|
+
/* Accept transparent token renewal only within the same authenticated session. */
|
|
41
|
+
function isRecordReadAuthenticationCurrent(authToken: string | null) {
|
|
42
|
+
const current = getAuthToken();
|
|
43
|
+
return authToken === current || !!(authToken && current && managedAccessTokensShareBinding(authToken, current));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/* Reject detached work after an authorization, cache or record read epoch, or the authenticated session, changed. */
|
|
47
|
+
function isRecordReadFlightCurrent(flight: RecordReadFlight) {
|
|
48
|
+
return (
|
|
49
|
+
flight.epoch === getFragmentRealtimeEpoch() &&
|
|
50
|
+
flight.cacheEpoch === getGraphQLCacheEpoch() &&
|
|
51
|
+
flight.readEpoch === RECORD_READ_STATE.epoch &&
|
|
52
|
+
!flight.controller.signal.aborted &&
|
|
53
|
+
isRecordReadAuthenticationCurrent(flight.authToken)
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/*
|
|
58
|
+
* Return the cache key of the record that owns the root a nested record is
|
|
59
|
+
* read through (the log entry of logEntryDetails), or null.
|
|
60
|
+
*/
|
|
61
|
+
function getRecordReadOwnerKey(read: RecordRead, id: string) {
|
|
62
|
+
if (!read.nested) return null;
|
|
63
|
+
for (const [type, candidate] of Object.entries(RECORD_READS)) {
|
|
64
|
+
if (candidate && !candidate.nested && candidate.query === read.query && candidate.root === read.root) {
|
|
65
|
+
const fragment = DATA_TYPES[type as DataTypeKey].fragment;
|
|
66
|
+
return fragment ? makeFragmentKey(fragment, id) : null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/* A deleted record, or a deleted owner of its root, must not be written by a late response. */
|
|
73
|
+
function isRecordReadTargetDeleted(fragmentKey: string, target: RecordReadTarget, id: string) {
|
|
74
|
+
if (loadFragment(fragmentKey)?.__deleted === true) return true;
|
|
75
|
+
const ownerKey = getRecordReadOwnerKey(target.read, id);
|
|
76
|
+
return !!ownerKey && loadFragment(ownerKey)?.__deleted === true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/* Return whether any record of a flight is still cached and not deleted, so its response could be written. */
|
|
80
|
+
function hasWritableRecordReadTarget(flight: RecordReadFlight) {
|
|
81
|
+
for (const [fragmentKey, target] of flight.targets) {
|
|
82
|
+
if (loadFragment(fragmentKey) && !isRecordReadTargetDeleted(fragmentKey, target, flight.id)) return true;
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/* Project the document's selected fields without normalizing unrelated nested entities. */
|
|
88
|
+
function projectRecordSelection(value: any, selections: readonly any[], definitions: readonly any[]): any {
|
|
89
|
+
if (value === null || value === undefined) return value;
|
|
90
|
+
if (Array.isArray(value)) return value.map((item) => projectRecordSelection(item, selections, definitions));
|
|
91
|
+
const result: Record<string, any> = {};
|
|
92
|
+
for (const selection of selections) {
|
|
93
|
+
if (selection.kind === 'FragmentSpread') {
|
|
94
|
+
const definition = definitions.find(
|
|
95
|
+
(candidate) => candidate.kind === 'FragmentDefinition' && candidate.name.value === selection.name.value,
|
|
96
|
+
);
|
|
97
|
+
if (definition) Object.assign(result, projectRecordSelection(value, definition.selectionSet.selections, definitions));
|
|
98
|
+
} else if (selection.kind === 'InlineFragment') {
|
|
99
|
+
Object.assign(result, projectRecordSelection(value, selection.selectionSet.selections, definitions));
|
|
100
|
+
} else if (selection.kind === 'Field') {
|
|
101
|
+
const key = selection.alias?.value || selection.name.value;
|
|
102
|
+
if (!Object.hasOwn(value, key)) continue;
|
|
103
|
+
result[key] = selection.selectionSet
|
|
104
|
+
? projectRecordSelection(value[key], selection.selectionSet.selections, definitions)
|
|
105
|
+
: value[key];
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/*
|
|
112
|
+
* Return one record's selected fields from a read's response, or null when
|
|
113
|
+
* the response holds no record with this id and organization (a null root,
|
|
114
|
+
* lost access, or another record).
|
|
115
|
+
*/
|
|
116
|
+
function getRecordReadValue(target: RecordReadTarget, data: any, id: string) {
|
|
117
|
+
const organizationId = target.scope.organizationId;
|
|
118
|
+
const root = data?.[target.read.root];
|
|
119
|
+
if (!root || String(root.id) !== id || (organizationId && root.organizationId && String(root.organizationId) !== organizationId)) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
const value = target.read.nested ? root[target.read.nested] : root;
|
|
123
|
+
if (
|
|
124
|
+
!value ||
|
|
125
|
+
String(value.id) !== id ||
|
|
126
|
+
(organizationId && value.organizationId && String(value.organizationId) !== organizationId)
|
|
127
|
+
) {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
const definitions = target.read.query.definitions;
|
|
131
|
+
const definition = definitions.find(
|
|
132
|
+
(candidate: any) => candidate.kind === 'FragmentDefinition' && candidate.name.value === target.read.fragment,
|
|
133
|
+
);
|
|
134
|
+
return definition ? projectRecordSelection(value, definition.selectionSet.selections, definitions) : null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/*
|
|
138
|
+
* Request a flight's record over HTTP without touching the query cache.
|
|
139
|
+
* Retries up to three times with backoff and a 10-second timeout per attempt;
|
|
140
|
+
* returns the response data and when its successful attempt started, or null.
|
|
141
|
+
*/
|
|
142
|
+
async function requestRecordRead(flight: RecordReadFlight) {
|
|
143
|
+
for (let attempt = 0; attempt < FILE_CONSTANTS.attempts && isRecordReadFlightCurrent(flight); attempt += 1) {
|
|
144
|
+
if (!hasWritableRecordReadTarget(flight)) return null;
|
|
145
|
+
const controller = new AbortController();
|
|
146
|
+
/* Propagate session cancellation to the currently active network attempt. */
|
|
147
|
+
const abort = () => controller.abort();
|
|
148
|
+
flight.controller.signal.addEventListener('abort', abort, { once: true });
|
|
149
|
+
const timeout = setTimeout(abort, FILE_CONSTANTS.timeoutMs);
|
|
150
|
+
const startedAt = Date.now();
|
|
151
|
+
let result: any;
|
|
152
|
+
try {
|
|
153
|
+
result = await graphqlRequestNoStore(
|
|
154
|
+
flight.query,
|
|
155
|
+
flight.variables,
|
|
156
|
+
{ shouldAcceptResult: () => isRecordReadFlightCurrent(flight) },
|
|
157
|
+
controller.signal,
|
|
158
|
+
);
|
|
159
|
+
} finally {
|
|
160
|
+
clearTimeout(timeout);
|
|
161
|
+
flight.controller.signal.removeEventListener('abort', abort);
|
|
162
|
+
}
|
|
163
|
+
if (!isRecordReadFlightCurrent(flight)) return null;
|
|
164
|
+
if (!result?.error && !result?.aborted && !result?.__clientResultRejected) return { data: result, startedAt };
|
|
165
|
+
// Authorization and missing reads are ambiguous; keep the cached record and never invent a tombstone
|
|
166
|
+
if ([20052, 20059, 20232].includes(Number(result?.error?.errorCode))) break;
|
|
167
|
+
if (attempt + 1 < FILE_CONSTANTS.attempts)
|
|
168
|
+
await new Promise((resolve) => setTimeout(resolve, 150 * 2 ** attempt + Math.floor(Math.random() * 100)));
|
|
169
|
+
}
|
|
170
|
+
if (isRecordReadFlightCurrent(flight))
|
|
171
|
+
console.warn('Unable to read a record a realtime change could not carry; keeping its cached value.');
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/*
|
|
176
|
+
* Merge a read's response into every record the flight serves. Fields that a
|
|
177
|
+
* realtime change wrote after the request started are kept; a record that left
|
|
178
|
+
* the cache is not created again, and a deleted one is not written.
|
|
179
|
+
*/
|
|
180
|
+
function applyRecordReadResponse(flight: RecordReadFlight, data: any, requestStartedAt: number) {
|
|
181
|
+
for (const [fragmentKey, target] of flight.targets) {
|
|
182
|
+
const value = getRecordReadValue(target, data, flight.id);
|
|
183
|
+
if (!value || isRecordReadTargetDeleted(fragmentKey, target, flight.id)) continue;
|
|
184
|
+
updateFragment(
|
|
185
|
+
fragmentKey,
|
|
186
|
+
(current: any) => keepNewerRealtimeFields(fragmentKey, value, current, requestStartedAt),
|
|
187
|
+
null,
|
|
188
|
+
false,
|
|
189
|
+
flight.updateObservers,
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/*
|
|
195
|
+
* Run a flight's pending read and merge its response, then schedule the read
|
|
196
|
+
* that thin changes queued while it ran.
|
|
197
|
+
*/
|
|
198
|
+
async function runRecordRead(flight: RecordReadFlight) {
|
|
199
|
+
const cycle = flight.pending;
|
|
200
|
+
if (!cycle || flight.running) return;
|
|
201
|
+
flight.pending = null;
|
|
202
|
+
if (!isRecordReadFlightCurrent(flight)) {
|
|
203
|
+
cycle.resolve();
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
flight.running = true;
|
|
207
|
+
flight.startedAt = Date.now();
|
|
208
|
+
try {
|
|
209
|
+
const response = await requestRecordRead(flight);
|
|
210
|
+
if (response && isRecordReadFlightCurrent(flight)) applyRecordReadResponse(flight, response.data, response.startedAt);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
console.warn('A record read failed; keeping the cached value.', error);
|
|
213
|
+
} finally {
|
|
214
|
+
flight.running = false;
|
|
215
|
+
cycle.resolve();
|
|
216
|
+
}
|
|
217
|
+
// A queued read always runs, so its promise settles; one queued in a discarded session or cache settles without a request
|
|
218
|
+
if (flight.pending) scheduleRecordRead(flight);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/*
|
|
222
|
+
* Start a flight's pending read once a second has passed since its previous
|
|
223
|
+
* read started, never sooner. A due read starts after the current task, so
|
|
224
|
+
* every change of one packet (a log entry and its details) joins it.
|
|
225
|
+
*/
|
|
226
|
+
function scheduleRecordRead(flight: RecordReadFlight) {
|
|
227
|
+
const wait = flight.startedAt + FILE_CONSTANTS.minIntervalMs - Date.now();
|
|
228
|
+
if (wait > 0) {
|
|
229
|
+
flight.timer = setTimeout(() => {
|
|
230
|
+
flight.timer = null;
|
|
231
|
+
scheduleRecordRead(flight);
|
|
232
|
+
}, wait);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
Promise.resolve().then(() => runRecordRead(flight));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/* Drop idle flights whose one-second spacing has passed, so the flight map stays small. */
|
|
239
|
+
function pruneRecordReadFlights(now: number) {
|
|
240
|
+
if (RECORD_READ_STATE.flights.size < FILE_CONSTANTS.pruneAbove) return;
|
|
241
|
+
for (const [key, flight] of RECORD_READ_STATE.flights) {
|
|
242
|
+
if (!flight.running && !flight.pending && now - flight.startedAt >= FILE_CONSTANTS.minIntervalMs) {
|
|
243
|
+
RECORD_READ_STATE.flights.delete(key);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/*
|
|
249
|
+
* Return the flight of one request in the current session. Records read by the
|
|
250
|
+
* same operation and variables (a log entry and its details) share it.
|
|
251
|
+
*/
|
|
252
|
+
function getRecordReadFlight(query: any, id: string, variables: Record<string, any>) {
|
|
253
|
+
const authToken = getAuthToken();
|
|
254
|
+
const epoch = getFragmentRealtimeEpoch();
|
|
255
|
+
const cacheEpoch = getGraphQLCacheEpoch();
|
|
256
|
+
const authScope = authToken ? getManagedAccessTokenBinding(authToken) || authToken : null;
|
|
257
|
+
const operationName = query.definitions.find((definition: any) => definition.kind === 'OperationDefinition')?.name?.value;
|
|
258
|
+
// Stable variables key: the definitions of one shared request may list their variables in any order
|
|
259
|
+
const key = JSON.stringify([epoch, cacheEpoch, authScope, operationName, makeGraphQLVariablesKey(variables)]);
|
|
260
|
+
let flight = RECORD_READ_STATE.flights.get(key);
|
|
261
|
+
if (!flight) {
|
|
262
|
+
pruneRecordReadFlights(Date.now());
|
|
263
|
+
flight = {
|
|
264
|
+
authToken,
|
|
265
|
+
epoch,
|
|
266
|
+
cacheEpoch,
|
|
267
|
+
readEpoch: RECORD_READ_STATE.epoch,
|
|
268
|
+
id,
|
|
269
|
+
query,
|
|
270
|
+
variables,
|
|
271
|
+
controller: new AbortController(),
|
|
272
|
+
targets: new Map(),
|
|
273
|
+
startedAt: 0,
|
|
274
|
+
running: false,
|
|
275
|
+
pending: null,
|
|
276
|
+
timer: null,
|
|
277
|
+
};
|
|
278
|
+
RECORD_READ_STATE.flights.set(key, flight);
|
|
279
|
+
}
|
|
280
|
+
return flight;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/*
|
|
284
|
+
* Read one record that a thin realtime change could not carry, through its
|
|
285
|
+
* type's record read. A change that arrives while a read of the record runs
|
|
286
|
+
* never cancels it: it queues exactly one more read, which starts no earlier
|
|
287
|
+
* than a second after the running one started. Returns a promise that settles
|
|
288
|
+
* when the read serving this change has finished, or null when no read was
|
|
289
|
+
* queued (no record read for the type, an older revision, or a missing
|
|
290
|
+
* scope value).
|
|
291
|
+
*/
|
|
292
|
+
export function queueRecordRead(change: WSDataChange, updateObservers?: UpdateObserversFn): Promise<void> | null {
|
|
293
|
+
const read = RECORD_READS[change.type as DataTypeKey];
|
|
294
|
+
const fragment = DATA_TYPES[change.type as DataTypeKey]?.fragment;
|
|
295
|
+
if (!read || !fragment || !change.id) return null;
|
|
296
|
+
const fragmentKey = makeFragmentKey(fragment, change.id);
|
|
297
|
+
if (!isFragmentRealtimeSequenceCurrent(change.revKey ? `${change.revKey}:${change.id}` : fragmentKey, change.rev)) return null;
|
|
298
|
+
const scope = change.scope || {};
|
|
299
|
+
const variables = read.variables(change.id, scope);
|
|
300
|
+
if (Object.values(variables).some((value) => value === undefined || value === null || value === '')) return null;
|
|
301
|
+
|
|
302
|
+
const flight = getRecordReadFlight(read.query, change.id, variables);
|
|
303
|
+
flight.targets.set(fragmentKey, { read, scope });
|
|
304
|
+
if (updateObservers) flight.updateObservers = updateObservers;
|
|
305
|
+
if (flight.pending) return flight.pending.promise;
|
|
306
|
+
|
|
307
|
+
let resolve!: () => void;
|
|
308
|
+
const promise = new Promise<void>((settle) => {
|
|
309
|
+
resolve = settle;
|
|
310
|
+
});
|
|
311
|
+
flight.pending = { promise, resolve };
|
|
312
|
+
// A running read schedules this one when it finishes
|
|
313
|
+
if (!flight.running) scheduleRecordRead(flight);
|
|
314
|
+
return promise;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/* Abort every record read and forget queued ones when the websocket or cache scope is discarded. */
|
|
318
|
+
export function clearRecordReads() {
|
|
319
|
+
RECORD_READ_STATE.epoch += 1;
|
|
320
|
+
for (const flight of RECORD_READ_STATE.flights.values()) {
|
|
321
|
+
flight.controller.abort();
|
|
322
|
+
if (flight.timer) clearTimeout(flight.timer);
|
|
323
|
+
flight.pending?.resolve();
|
|
324
|
+
flight.pending = null;
|
|
325
|
+
}
|
|
326
|
+
RECORD_READ_STATE.flights.clear();
|
|
327
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { SheetCommandBatchResultGQL, SheetCommandInput } from '@jsb188/mday/types/sheet.d.ts';
|
|
2
|
+
import type { SHEET_BOOTSTRAP_CONTRACT_VERSION } from '@jsb188/mday/utils/sheetBootstrap.ts';
|
|
3
|
+
import { graphqlRequestNoStore } from '../client/request.ts';
|
|
4
|
+
import { editSheetCommandBatchMtn } from '../gql/mutations/sheetMutations.ts';
|
|
5
|
+
|
|
6
|
+
/*
|
|
7
|
+
* The imperative editSheetCommandBatch request (wire contract v5, DESIGN
|
|
8
|
+
* §1.1) the Sheet outbox transport sends each sealed envelope through. It
|
|
9
|
+
* never reads or writes the normalized GraphQL cache: the authoritative
|
|
10
|
+
* patches it returns belong to the client's tab stores.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export type EditSheetCommandBatchVariables = {
|
|
14
|
+
contractVersion: typeof SHEET_BOOTSTRAP_CONTRACT_VERSION;
|
|
15
|
+
organizationId: string;
|
|
16
|
+
sheetId: string;
|
|
17
|
+
envelopeId: string;
|
|
18
|
+
clientId: string;
|
|
19
|
+
sessionId: string;
|
|
20
|
+
clientSeq: number;
|
|
21
|
+
commands: SheetCommandInput[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type EditSheetCommandBatchOutput = {
|
|
25
|
+
aborted?: boolean | null;
|
|
26
|
+
error?: unknown;
|
|
27
|
+
editSheetCommandBatch?: SheetCommandBatchResultGQL | null;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/*
|
|
31
|
+
* Send one sealed command envelope through the no-store transport and return
|
|
32
|
+
* its raw output. Server and GraphQL errors come back as `{ error }` and an
|
|
33
|
+
* aborted request as `{ aborted: true }`; neither is thrown.
|
|
34
|
+
*/
|
|
35
|
+
export async function requestEditSheetCommandBatch(
|
|
36
|
+
variables: EditSheetCommandBatchVariables,
|
|
37
|
+
options: { authToken?: string | null; signal?: AbortSignal | null } = {},
|
|
38
|
+
): Promise<EditSheetCommandBatchOutput> {
|
|
39
|
+
return (await graphqlRequestNoStore(
|
|
40
|
+
editSheetCommandBatchMtn,
|
|
41
|
+
variables,
|
|
42
|
+
{ authToken: options.authToken },
|
|
43
|
+
options.signal,
|
|
44
|
+
)) as EditSheetCommandBatchOutput;
|
|
45
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { WSDataUpdateObj } from '@jsb188/app/types/app.d.ts';
|
|
2
|
+
import { FRAGMENT_NAMES } from '@jsb188/mday/constants/graphqlReactivity.ts';
|
|
3
|
+
import { addFragmentToCache, updateFragment } from '../cache/index.ts';
|
|
4
|
+
import type { UpdateObserversFn } from '../types.d.ts';
|
|
5
|
+
import { mergeChangeData } from './data-changes.helpers.ts';
|
|
6
|
+
import { shouldApplyFragmentRealtimeSequence } from './fragment-realtime-sequence.ts';
|
|
7
|
+
import { routeSheetViewRealtimePacket } from './sheet-view-realtime-router.ts';
|
|
8
|
+
|
|
9
|
+
const FILE_CONSTANTS = {
|
|
10
|
+
// The fragments sheet journal packets carry; every other record reaches the client as a change
|
|
11
|
+
journalFragmentNames: new Set<string>([
|
|
12
|
+
FRAGMENT_NAMES.sheet,
|
|
13
|
+
FRAGMENT_NAMES.sheetManifest,
|
|
14
|
+
FRAGMENT_NAMES.sheetTab,
|
|
15
|
+
FRAGMENT_NAMES.sheetView,
|
|
16
|
+
]),
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/*
|
|
20
|
+
* Apply one sheet journal packet. SheetView packets go to their Sheet's tab
|
|
21
|
+
* stores; Sheet, SheetTab and SheetManifest fragments pass their revision
|
|
22
|
+
* fence and are merged into the cache, or stored when not cached yet. The
|
|
23
|
+
* observers of each fragment key and of the packet's reactiveFragmentKeys are
|
|
24
|
+
* notified.
|
|
25
|
+
*/
|
|
26
|
+
export function applySheetRealtimePacket(
|
|
27
|
+
wsData: Pick<WSDataUpdateObj, 'fragments' | 'reactiveFragmentKeys'>,
|
|
28
|
+
updateObservers: UpdateObserversFn,
|
|
29
|
+
) {
|
|
30
|
+
const { fragments, reactiveFragmentKeys } = wsData;
|
|
31
|
+
for (const fragment of fragments || []) {
|
|
32
|
+
if (!fragment?.name || !FILE_CONSTANTS.journalFragmentNames.has(fragment.name)) continue;
|
|
33
|
+
const { name, dataId, data, sequence, sequenceKey } = fragment;
|
|
34
|
+
// SheetView packets go straight to the Sheet's tab stores, never into the fragment cache.
|
|
35
|
+
// They route before the sequence gate because the chunks of one packet share a sequence.
|
|
36
|
+
if (name === FRAGMENT_NAMES.sheetView && routeSheetViewRealtimePacket(data)) continue;
|
|
37
|
+
|
|
38
|
+
const fragmentKey = `${name}:${dataId}`;
|
|
39
|
+
if (!shouldApplyFragmentRealtimeSequence(sequenceKey ? `${sequenceKey}:${dataId}` : fragmentKey, sequence)) continue;
|
|
40
|
+
const updatedKey = updateFragment(
|
|
41
|
+
fragmentKey,
|
|
42
|
+
(current: any) => mergeChangeData(current, data),
|
|
43
|
+
null,
|
|
44
|
+
false,
|
|
45
|
+
updateObservers,
|
|
46
|
+
reactiveFragmentKeys,
|
|
47
|
+
);
|
|
48
|
+
if (!updatedKey) {
|
|
49
|
+
addFragmentToCache(fragmentKey, data);
|
|
50
|
+
updateObservers({ fragmentIds: [fragmentKey, ...(reactiveFragmentKeys || [])] });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|