grist-widget-sdk 0.2.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +730 -0
  2. package/LICENSE +15 -0
  3. package/README.md +249 -0
  4. package/dist/advanced.cjs +2749 -0
  5. package/dist/advanced.cjs.map +1 -0
  6. package/dist/advanced.d.cts +790 -0
  7. package/dist/advanced.d.ts +790 -0
  8. package/dist/advanced.js +825 -0
  9. package/dist/advanced.js.map +1 -0
  10. package/dist/chunk-64SVRWW7.js +758 -0
  11. package/dist/chunk-64SVRWW7.js.map +1 -0
  12. package/dist/chunk-BNBV24WM.js +479 -0
  13. package/dist/chunk-BNBV24WM.js.map +1 -0
  14. package/dist/chunk-ELGVOHFD.js +32 -0
  15. package/dist/chunk-ELGVOHFD.js.map +1 -0
  16. package/dist/chunk-GTTD5HPO.js +36 -0
  17. package/dist/chunk-GTTD5HPO.js.map +1 -0
  18. package/dist/chunk-JASMM2YC.js +243 -0
  19. package/dist/chunk-JASMM2YC.js.map +1 -0
  20. package/dist/chunk-PM3B4WYV.js +12 -0
  21. package/dist/chunk-PM3B4WYV.js.map +1 -0
  22. package/dist/chunk-QKXKZ27D.js +1189 -0
  23. package/dist/chunk-QKXKZ27D.js.map +1 -0
  24. package/dist/chunk-QZG7SNUG.js +463 -0
  25. package/dist/chunk-QZG7SNUG.js.map +1 -0
  26. package/dist/chunk-REV5AUXD.js +25 -0
  27. package/dist/chunk-REV5AUXD.js.map +1 -0
  28. package/dist/chunk-XE2SKNLH.js +1641 -0
  29. package/dist/chunk-XE2SKNLH.js.map +1 -0
  30. package/dist/create-grist-emulator-C_0I4wax.d.ts +80 -0
  31. package/dist/create-grist-emulator-DBS6gmiI.d.cts +80 -0
  32. package/dist/emulator/devtools.cjs +1367 -0
  33. package/dist/emulator/devtools.cjs.map +1 -0
  34. package/dist/emulator/devtools.d.cts +46 -0
  35. package/dist/emulator/devtools.d.ts +46 -0
  36. package/dist/emulator/devtools.js +480 -0
  37. package/dist/emulator/devtools.js.map +1 -0
  38. package/dist/emulator/testing.cjs +2061 -0
  39. package/dist/emulator/testing.cjs.map +1 -0
  40. package/dist/emulator/testing.d.cts +50 -0
  41. package/dist/emulator/testing.d.ts +50 -0
  42. package/dist/emulator/testing.js +124 -0
  43. package/dist/emulator/testing.js.map +1 -0
  44. package/dist/emulator/transports.cjs +1132 -0
  45. package/dist/emulator/transports.cjs.map +1 -0
  46. package/dist/emulator/transports.d.cts +37 -0
  47. package/dist/emulator/transports.d.ts +37 -0
  48. package/dist/emulator/transports.js +12 -0
  49. package/dist/emulator/transports.js.map +1 -0
  50. package/dist/emulator.cjs +1796 -0
  51. package/dist/emulator.cjs.map +1 -0
  52. package/dist/emulator.d.cts +107 -0
  53. package/dist/emulator.d.ts +107 -0
  54. package/dist/emulator.js +26 -0
  55. package/dist/emulator.js.map +1 -0
  56. package/dist/index.cjs +5511 -0
  57. package/dist/index.cjs.map +1 -0
  58. package/dist/index.d.cts +825 -0
  59. package/dist/index.d.ts +825 -0
  60. package/dist/index.js +2447 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/inline-CRwQQ-GW.d.cts +311 -0
  63. package/dist/inline-QitZwXKP.d.ts +311 -0
  64. package/dist/templates-BC7FoSdW.d.ts +24 -0
  65. package/dist/templates-DBq719O_.d.cts +24 -0
  66. package/dist/types-Fb2wplkv.d.cts +228 -0
  67. package/dist/types-Fb2wplkv.d.ts +228 -0
  68. package/dist/use-grist-widget-options-from-context-BFhQBGRY.d.ts +522 -0
  69. package/dist/use-grist-widget-options-from-context-qpFMdoBJ.d.cts +522 -0
  70. package/package.json +131 -0
@@ -0,0 +1,1641 @@
1
+ // src/sdk/helpers/grist-mappings.ts
2
+ function asColumnSpec(entry) {
3
+ return typeof entry === "string" ? { name: entry } : entry;
4
+ }
5
+ function validateColumnMappings(spec, mappings) {
6
+ const missing = [];
7
+ const emptyMultiples = [];
8
+ if (!spec) return { ok: true, pending: false, missing, emptyMultiples };
9
+ const m = mappings ?? {};
10
+ for (const raw of spec) {
11
+ const col = asColumnSpec(raw);
12
+ if (col.optional) continue;
13
+ const value = m[col.name];
14
+ if (col.allowMultiple) {
15
+ if (value === void 0) {
16
+ missing.push(col.name);
17
+ } else if (!Array.isArray(value) || value.length === 0) {
18
+ emptyMultiples.push(col.name);
19
+ }
20
+ } else {
21
+ if (value === void 0 || value === null || value === "") missing.push(col.name);
22
+ }
23
+ }
24
+ return {
25
+ ok: missing.length === 0 && emptyMultiples.length === 0,
26
+ pending: false,
27
+ missing,
28
+ emptyMultiples
29
+ };
30
+ }
31
+ var pendingColumnMappingStatus = {
32
+ ok: true,
33
+ pending: true,
34
+ missing: [],
35
+ emptyMultiples: []
36
+ };
37
+
38
+ // src/sdk/internal/handshake/access.ts
39
+ var ACCESS_RANK = {
40
+ none: 0,
41
+ "read table": 1,
42
+ full: 2
43
+ };
44
+ var GRIST_ACCESS_LEVELS = ["none", "read table", "full"];
45
+ function parseGristRequiredAccess(raw) {
46
+ if (!raw) return null;
47
+ return GRIST_ACCESS_LEVELS.includes(raw) ? raw : null;
48
+ }
49
+ function isAccessSufficient(granted, required) {
50
+ return ACCESS_RANK[granted] >= ACCESS_RANK[required];
51
+ }
52
+ function gristAccessLevelLabel(level) {
53
+ switch (level) {
54
+ case "none":
55
+ return "No document access";
56
+ case "read table":
57
+ return "Read selected table";
58
+ case "full":
59
+ return "Full document access";
60
+ }
61
+ }
62
+ function formatInsufficientAccessMessage(required, _granted) {
63
+ const need = gristAccessLevelLabel(required);
64
+ return `Set Access level to at least "${need}" in the Custom widget settings.`;
65
+ }
66
+
67
+ // src/sdk/internal/handshake/types.ts
68
+ var ZERO_GENERATION = 0;
69
+ function nextGeneration(current) {
70
+ return current + 1;
71
+ }
72
+ var MAPPING_SOURCE_PRIORITY = [
73
+ "section_api",
74
+ "stream_record",
75
+ "stream_records",
76
+ "stream_new_record"
77
+ ];
78
+ function initialGristSnapshot() {
79
+ return {
80
+ generation: ZERO_GENERATION,
81
+ lifecycle: { phase: "idle" },
82
+ link: { state: "connected", lastSuccessMs: null, missedPings: 0 },
83
+ authz: { state: "pending", declared: "read table" },
84
+ config: { mappings: { state: "not_declared" } },
85
+ sync: {
86
+ record: { state: "cold" },
87
+ records: { state: "cold" },
88
+ options: { state: "cold" },
89
+ newRecord: { state: "cold" },
90
+ currentTable: { state: "unknown" }
91
+ }
92
+ };
93
+ }
94
+
95
+ // src/sdk/internal/handshake/derive.ts
96
+ function deriveStatus(snapshot) {
97
+ const { lifecycle, authz, link } = snapshot;
98
+ if (lifecycle.phase === "idle" || lifecycle.phase === "detecting") return "booting";
99
+ if (lifecycle.phase === "negotiating") return "booting";
100
+ if (lifecycle.phase === "terminated") {
101
+ switch (lifecycle.reason.kind) {
102
+ case "script_timeout":
103
+ case "not_embedded":
104
+ return "unavailable";
105
+ case "host_rejected":
106
+ case "ready_failed":
107
+ case "ready_timeout":
108
+ case "manual_terminate":
109
+ return "error";
110
+ }
111
+ }
112
+ if (authz.state === "denied") return "error";
113
+ if (link.state === "lost") return "error";
114
+ return "ready";
115
+ }
116
+ function deriveErrorMessage(snapshot) {
117
+ if (snapshot.lifecycle.phase === "terminated") {
118
+ switch (snapshot.lifecycle.reason.kind) {
119
+ case "ready_failed":
120
+ return snapshot.lifecycle.reason.message;
121
+ case "ready_timeout":
122
+ return `Grist handshake timed out after ${snapshot.lifecycle.reason.afterMs}ms`;
123
+ case "host_rejected":
124
+ return snapshot.lifecycle.reason.message;
125
+ case "script_timeout":
126
+ return `Grist plugin API never loaded (${snapshot.lifecycle.reason.attempts} attempts)`;
127
+ case "not_embedded":
128
+ return "This page is not embedded in a Grist iframe";
129
+ case "manual_terminate":
130
+ return null;
131
+ }
132
+ }
133
+ if (snapshot.authz.state === "denied") {
134
+ return snapshot.authz.message ?? `Grist denied requested access (${snapshot.authz.declared})`;
135
+ }
136
+ if (snapshot.lifecycle.phase === "online" && snapshot.link.state === "lost") {
137
+ return `Grist link lost (${snapshot.link.missedPings} consecutive failures)`;
138
+ }
139
+ return null;
140
+ }
141
+ function deriveCapabilities(snapshot) {
142
+ const { lifecycle, authz, link, config, sync } = snapshot;
143
+ const online = lifecycle.phase === "online";
144
+ const granted = authz.state === "granted";
145
+ const grantedReadOrMore = granted && ACCESS_RANK[authz.level] >= ACCESS_RANK["read table"];
146
+ const grantedFull = granted && authz.level === "full";
147
+ const linkUsable = link.state !== "lost";
148
+ const canRead = online && linkUsable && grantedReadOrMore;
149
+ const canFetchTable = canRead && link.state === "connected";
150
+ const mappingsUsable = hasUsableMappings(config.mappings);
151
+ const missing = mappingsMissing(config.mappings);
152
+ const emptyMultiples = mappingsEmptyMultiples(config.mappings);
153
+ const canRender = canRead && mappingsUsable;
154
+ const canWriteRecords = canRender && grantedFull;
155
+ const canWriteSchema = canWriteRecords && sync.currentTable.state === "known";
156
+ const hasFreshSelection = canRead && sync.record.state === "hot" && config.mappings.state !== "invalidating";
157
+ return {
158
+ canRead,
159
+ canRender,
160
+ canWriteRecords,
161
+ canWriteSchema,
162
+ canFetchTable,
163
+ hasFreshSelection,
164
+ hasUsableMappings: mappingsUsable,
165
+ missingMappings: missing,
166
+ emptyMultipleMappings: emptyMultiples
167
+ };
168
+ }
169
+ function hasUsableMappings(state) {
170
+ if (state.state === "not_declared") return true;
171
+ if (state.state === "complete") return true;
172
+ if (state.state === "invalidating") {
173
+ return state.previous.state === "complete";
174
+ }
175
+ return false;
176
+ }
177
+ function mappingsMissing(state) {
178
+ if (state.state === "incomplete") return state.missing;
179
+ if (state.state === "invalidating" && state.previous.state === "incomplete") {
180
+ return state.previous.missing;
181
+ }
182
+ return EMPTY;
183
+ }
184
+ function mappingsEmptyMultiples(state) {
185
+ if (state.state === "incomplete") return state.emptyMultiples;
186
+ if (state.state === "invalidating" && state.previous.state === "incomplete") {
187
+ return state.previous.emptyMultiples;
188
+ }
189
+ return EMPTY;
190
+ }
191
+ var EMPTY = Object.freeze([]);
192
+ function extractResolvedMappings(state) {
193
+ switch (state.state) {
194
+ case "complete":
195
+ case "incomplete":
196
+ return state.mappings;
197
+ case "invalidating":
198
+ if (state.previous.state === "complete" || state.previous.state === "incomplete") {
199
+ return state.previous.mappings;
200
+ }
201
+ return null;
202
+ default:
203
+ return null;
204
+ }
205
+ }
206
+ function deriveColumnMappingStatus(mappingState, columns) {
207
+ if (!columns?.length) {
208
+ return { ok: true, pending: false, missing: [], emptyMultiples: [] };
209
+ }
210
+ switch (mappingState.state) {
211
+ case "not_declared":
212
+ return { ok: true, pending: false, missing: [], emptyMultiples: [] };
213
+ case "pending":
214
+ return pendingColumnMappingStatus;
215
+ case "unreported":
216
+ return pendingColumnMappingStatus;
217
+ case "complete":
218
+ return { ok: true, pending: false, missing: [], emptyMultiples: [] };
219
+ case "incomplete":
220
+ return {
221
+ ok: false,
222
+ pending: false,
223
+ missing: [...mappingState.missing],
224
+ emptyMultiples: [...mappingState.emptyMultiples]
225
+ };
226
+ case "invalidating":
227
+ return deriveColumnMappingStatus(mappingState.previous, columns);
228
+ }
229
+ }
230
+
231
+ // src/sdk/internal/handshake/actions.ts
232
+ function hasGenerationStamp(action) {
233
+ return "generation" in action && typeof action.generation === "number";
234
+ }
235
+
236
+ // src/sdk/internal/handshake/mapping-resolver.ts
237
+ var MappingResolver = class {
238
+ constructor(declared, generation) {
239
+ /** Latest accepted payload per source. */
240
+ this.payloads = /* @__PURE__ */ new Map();
241
+ /** Last resolved state, used to detect duplicate ingests. */
242
+ this.lastResolvedHash = null;
243
+ this.declared = declared;
244
+ this.currentGeneration = generation;
245
+ }
246
+ /**
247
+ * Replace the declared columns (e.g. user passed a new `columns` array to
248
+ * the provider). Clears accumulated payloads — they were validated against
249
+ * the previous declaration.
250
+ */
251
+ redeclare(declared, atGeneration) {
252
+ this.declared = declared;
253
+ this.currentGeneration = atGeneration;
254
+ this.payloads.clear();
255
+ this.lastResolvedHash = null;
256
+ }
257
+ /** Bump the active generation. Payloads from older generations are dropped. */
258
+ bumpGeneration(next) {
259
+ if (next <= this.currentGeneration) return;
260
+ this.currentGeneration = next;
261
+ for (const [src, p] of this.payloads) {
262
+ if (p.generation < next) this.payloads.delete(src);
263
+ }
264
+ this.lastResolvedHash = null;
265
+ }
266
+ /** Forget every payload and reset the hash. The declaration is preserved. */
267
+ reset() {
268
+ this.payloads.clear();
269
+ this.lastResolvedHash = null;
270
+ }
271
+ /** Cheap, deterministic snapshot for tests/debug. */
272
+ knownSources() {
273
+ return [...this.payloads.keys()];
274
+ }
275
+ /**
276
+ * Ingest one payload. Returns a {@link ResolveOutcome}:
277
+ * - `still_pending` — no payloads accepted yet.
278
+ * - `no_change/stale_*` — input generation is older than current.
279
+ * - `no_change/duplicate_payload` — input did not move the resolution.
280
+ * - `resolved` — new resolution differs from the previous one.
281
+ *
282
+ * Call {@link current} to read the latest resolution without affecting
283
+ * the duplicate-detection hash.
284
+ */
285
+ ingest(input) {
286
+ if (input.generation < this.currentGeneration) {
287
+ return { kind: "no_change", reason: "stale_generation" };
288
+ }
289
+ if (input.generation > this.currentGeneration) {
290
+ this.bumpGeneration(input.generation);
291
+ }
292
+ this.payloads.set(input.source, input);
293
+ const computed = this.compute();
294
+ if (computed === null) return { kind: "still_pending" };
295
+ const hash = computeMappingHash(
296
+ computed.mappings,
297
+ computed.state === "complete",
298
+ computed.source
299
+ );
300
+ if (hash === this.lastResolvedHash) {
301
+ return { kind: "no_change", reason: "duplicate_payload" };
302
+ }
303
+ this.lastResolvedHash = hash;
304
+ return { kind: "resolved", state: computed };
305
+ }
306
+ /**
307
+ * Return the resolver's current resolution (pure read). Equivalent to
308
+ * `ingest(...)` without mutating any state — used by tests and by the
309
+ * reducer when re-applying after `MAPPING_INVALIDATION_RESOLVE`.
310
+ */
311
+ current() {
312
+ const computed = this.compute();
313
+ if (computed === null) return { kind: "still_pending" };
314
+ return { kind: "resolved", state: computed };
315
+ }
316
+ /**
317
+ * Compute the current best mapping from accumulated payloads (pure).
318
+ *
319
+ * Priority: higher-priority sources **override** specific keys from
320
+ * lower-priority sources. Keys absent from a higher-priority source fall
321
+ * back to lower-priority sources. This matches the production behaviour
322
+ * where `sectionApi.mappings()` is authoritative for the keys it reports,
323
+ * but stream payloads can fill in keys the section_api hasn't reported yet.
324
+ */
325
+ compute() {
326
+ if (this.payloads.size === 0) return null;
327
+ const merged = {};
328
+ let latestReportedAt = 0;
329
+ const contributors = [];
330
+ for (const src of [...MAPPING_SOURCE_PRIORITY].reverse()) {
331
+ const p = this.payloads.get(src);
332
+ if (!p) continue;
333
+ contributors.push(src);
334
+ if (p.receivedAtMs > latestReportedAt) latestReportedAt = p.receivedAtMs;
335
+ if (p.payload === null) continue;
336
+ for (const [k, v] of Object.entries(p.payload)) {
337
+ merged[k] = v;
338
+ }
339
+ }
340
+ if (contributors.length === 0) return null;
341
+ const validation = validateColumnMappings(this.declared, merged);
342
+ const source = contributors.length === 1 ? contributors[0] : "merged";
343
+ if (validation.ok) {
344
+ return {
345
+ state: "complete",
346
+ declared: this.declared,
347
+ mappings: merged,
348
+ source,
349
+ reportedAtMs: latestReportedAt
350
+ };
351
+ }
352
+ return {
353
+ state: "incomplete",
354
+ declared: this.declared,
355
+ mappings: merged,
356
+ missing: validation.missing,
357
+ emptyMultiples: validation.emptyMultiples,
358
+ source,
359
+ reportedAtMs: latestReportedAt
360
+ };
361
+ }
362
+ };
363
+ function computeMappingHash(mappings, ok, source) {
364
+ const keys = Object.keys(mappings).sort();
365
+ const body = keys.map((k) => {
366
+ const v = mappings[k];
367
+ if (Array.isArray(v)) return `${k}=[${v.join(",")}]`;
368
+ return `${k}=${v ?? ""}`;
369
+ }).join("|");
370
+ return `${ok ? "OK" : "KO"}::${source}::${body}`;
371
+ }
372
+
373
+ // src/sdk/internal/handshake/reducer.ts
374
+ function createReducerContext() {
375
+ return { resolver: null };
376
+ }
377
+ var DEFAULT_REDUCER_CONFIG = {
378
+ staleAfterMissed: 1,
379
+ lostAfterMissed: 3
380
+ };
381
+ function gristReducer(snapshot, action, ctx, config = DEFAULT_REDUCER_CONFIG) {
382
+ if (hasGenerationStamp(action) && action.generation < snapshot.generation) {
383
+ return snapshot;
384
+ }
385
+ switch (action.type) {
386
+ // -- Lifecycle --------------------------------------------------------
387
+ case "DETECT_START":
388
+ return reduceDetectStart(snapshot, action.atMs);
389
+ case "DETECT_TICK":
390
+ return reduceDetectTick(snapshot, action.attempts);
391
+ case "DETECT_AVAILABLE":
392
+ return reduceDetectAvailable(snapshot, action.atMs);
393
+ case "DETECT_TIMEOUT":
394
+ return reduceTerminate(snapshot, {
395
+ kind: "script_timeout",
396
+ attempts: action.attempts
397
+ }, action.atMs);
398
+ case "NOT_EMBEDDED":
399
+ return reduceTerminate(snapshot, { kind: "not_embedded" }, action.atMs);
400
+ case "NEGOTIATE_START":
401
+ return reduceNegotiateStart(snapshot, action.access, action.atMs);
402
+ case "NEGOTIATE_SUCCESS":
403
+ return reduceNegotiateSuccess(snapshot, action.access, action.grantedLevel, action.atMs);
404
+ case "NEGOTIATE_FAIL":
405
+ return reduceTerminate(snapshot, action.reason, action.atMs);
406
+ case "TERMINATE":
407
+ return reduceTerminate(snapshot, action.reason, action.atMs);
408
+ case "AUTHZ_REPORT":
409
+ return reduceAuthzReport(snapshot, action.level, action.atMs);
410
+ // -- Link -------------------------------------------------------------
411
+ case "RPC_SUCCESS":
412
+ case "HEARTBEAT_OK":
413
+ return reduceLinkSuccess(snapshot, action.atMs);
414
+ case "RPC_FAILURE":
415
+ case "HEARTBEAT_FAIL":
416
+ return reduceLinkFailure(snapshot, action.atMs, config);
417
+ // -- Generation -------------------------------------------------------
418
+ case "BUMP_GENERATION":
419
+ return reduceBumpGeneration(snapshot, ctx);
420
+ // -- Config / mappings -----------------------------------------------
421
+ case "MAPPING_DECLARE":
422
+ case "MAPPING_REPORT":
423
+ case "MAPPING_INVALIDATE":
424
+ case "MAPPING_INVALIDATION_RESOLVE":
425
+ case "MAPPING_TIMEOUT":
426
+ return reduceMapping(snapshot, action, ctx);
427
+ // -- Sync -------------------------------------------------------------
428
+ case "STREAM_RECEIVED":
429
+ case "STREAM_WARMING":
430
+ case "STREAM_STALE":
431
+ return reduceStream(snapshot, action);
432
+ case "CURRENT_TABLE_KNOWN":
433
+ return updateSync(snapshot, {
434
+ ...snapshot.sync,
435
+ currentTable: { state: "known", tableId: action.tableId, refreshing: false }
436
+ });
437
+ case "CURRENT_TABLE_REFRESH_START":
438
+ if (snapshot.sync.currentTable.state !== "known") return snapshot;
439
+ return updateSync(snapshot, {
440
+ ...snapshot.sync,
441
+ currentTable: { ...snapshot.sync.currentTable, refreshing: true }
442
+ });
443
+ case "CURRENT_TABLE_ERROR":
444
+ return updateSync(snapshot, {
445
+ ...snapshot.sync,
446
+ currentTable: { state: "errored", message: action.message, sinceMs: action.atMs }
447
+ });
448
+ default: {
449
+ const _exhaustive = action;
450
+ void _exhaustive;
451
+ return snapshot;
452
+ }
453
+ }
454
+ }
455
+ function reduceDetectStart(snapshot, atMs) {
456
+ if (snapshot.lifecycle.phase !== "idle") return snapshot;
457
+ return {
458
+ ...snapshot,
459
+ lifecycle: { phase: "detecting", attempts: 0, startedAtMs: atMs }
460
+ };
461
+ }
462
+ function reduceDetectTick(snapshot, attempts) {
463
+ if (snapshot.lifecycle.phase !== "detecting") return snapshot;
464
+ if (attempts === snapshot.lifecycle.attempts) return snapshot;
465
+ return {
466
+ ...snapshot,
467
+ lifecycle: { ...snapshot.lifecycle, attempts }
468
+ };
469
+ }
470
+ function reduceDetectAvailable(snapshot, atMs) {
471
+ if (snapshot.lifecycle.phase !== "detecting" && snapshot.lifecycle.phase !== "idle") {
472
+ return snapshot;
473
+ }
474
+ return {
475
+ ...snapshot,
476
+ lifecycle: {
477
+ phase: "negotiating",
478
+ access: snapshot.authz.declared,
479
+ startedAtMs: atMs
480
+ }
481
+ };
482
+ }
483
+ function reduceNegotiateStart(snapshot, access, atMs) {
484
+ if (snapshot.lifecycle.phase === "terminated") return snapshot;
485
+ return {
486
+ ...snapshot,
487
+ authz: { state: "pending", declared: access },
488
+ lifecycle: snapshot.lifecycle.phase === "online" ? snapshot.lifecycle : { phase: "negotiating", access, startedAtMs: atMs }
489
+ };
490
+ }
491
+ function authzDeclared(snapshot) {
492
+ return snapshot.authz.declared;
493
+ }
494
+ function reduceAuthzReport(snapshot, level, _atMs) {
495
+ if (snapshot.lifecycle.phase !== "online") return snapshot;
496
+ const declared = authzDeclared(snapshot);
497
+ if (isAccessSufficient(level, declared)) {
498
+ const previousLevel = snapshot.authz.state === "granted" ? snapshot.authz.level : null;
499
+ const widened = previousLevel !== null && ACCESS_RANK[level] > ACCESS_RANK[previousLevel];
500
+ const nextAuthz2 = {
501
+ state: "granted",
502
+ level,
503
+ declared,
504
+ widened
505
+ };
506
+ if (snapshot.authz.state === "granted" && snapshot.authz.level === nextAuthz2.level && snapshot.authz.declared === nextAuthz2.declared && snapshot.authz.widened === nextAuthz2.widened) {
507
+ return snapshot;
508
+ }
509
+ return { ...snapshot, authz: nextAuthz2 };
510
+ }
511
+ const message = formatInsufficientAccessMessage(declared, level);
512
+ const nextAuthz = { state: "denied", declared, message };
513
+ if (snapshot.authz.state === "denied" && snapshot.authz.declared === nextAuthz.declared && snapshot.authz.message === nextAuthz.message) {
514
+ return snapshot;
515
+ }
516
+ return { ...snapshot, authz: nextAuthz };
517
+ }
518
+ function reduceNegotiateSuccess(snapshot, access, grantedLevel, atMs) {
519
+ if (snapshot.lifecycle.phase === "terminated") return snapshot;
520
+ const previousLevel = snapshot.authz.state === "granted" ? snapshot.authz.level : null;
521
+ const widened = previousLevel !== null && ACCESS_RANK[grantedLevel] > ACCESS_RANK[previousLevel];
522
+ return {
523
+ ...snapshot,
524
+ authz: {
525
+ state: "granted",
526
+ level: grantedLevel,
527
+ declared: access,
528
+ widened
529
+ },
530
+ lifecycle: snapshot.lifecycle.phase === "online" ? snapshot.lifecycle : { phase: "online", sinceMs: atMs, declaredAccess: access },
531
+ link: { state: "connected", lastSuccessMs: atMs, missedPings: 0 }
532
+ };
533
+ }
534
+ function reduceTerminate(snapshot, reason, atMs) {
535
+ if (snapshot.lifecycle.phase === "terminated") return snapshot;
536
+ const lifecycle = { phase: "terminated", reason, atMs };
537
+ return { ...snapshot, lifecycle };
538
+ }
539
+ function reduceLinkSuccess(snapshot, atMs) {
540
+ if (snapshot.lifecycle.phase !== "online") return snapshot;
541
+ const link = { state: "connected", lastSuccessMs: atMs, missedPings: 0 };
542
+ if (snapshot.link.state === link.state && snapshot.link.lastSuccessMs === link.lastSuccessMs && snapshot.link.missedPings === link.missedPings) {
543
+ return snapshot;
544
+ }
545
+ return { ...snapshot, link };
546
+ }
547
+ function reduceLinkFailure(snapshot, _atMs, config) {
548
+ if (snapshot.lifecycle.phase !== "online") return snapshot;
549
+ const missed = snapshot.link.missedPings + 1;
550
+ let state = snapshot.link.state;
551
+ if (missed >= config.lostAfterMissed) state = "lost";
552
+ else if (missed >= config.staleAfterMissed) state = "stale";
553
+ return {
554
+ ...snapshot,
555
+ link: { state, lastSuccessMs: snapshot.link.lastSuccessMs, missedPings: missed }
556
+ };
557
+ }
558
+ function reduceBumpGeneration(snapshot, ctx) {
559
+ const next = nextGeneration(snapshot.generation);
560
+ ctx.resolver?.bumpGeneration(next);
561
+ return {
562
+ ...snapshot,
563
+ generation: next,
564
+ // Marking streams as warming again ensures hooks treat the data as
565
+ // "in transit" until a fresh event arrives under the new generation.
566
+ sync: {
567
+ ...snapshot.sync,
568
+ record: degradeForRefresh(snapshot.sync.record, snapshot.generation),
569
+ records: degradeForRefresh(snapshot.sync.records, snapshot.generation),
570
+ options: degradeForRefresh(snapshot.sync.options, snapshot.generation),
571
+ newRecord: degradeForRefresh(snapshot.sync.newRecord, snapshot.generation)
572
+ }
573
+ };
574
+ }
575
+ function degradeForRefresh(freshness, prevGeneration) {
576
+ if (freshness.state === "hot" && freshness.generation === prevGeneration) {
577
+ return { state: "stale", lastEventMs: freshness.lastEventMs, reason: "host_quiet" };
578
+ }
579
+ return freshness;
580
+ }
581
+ function reduceMapping(snapshot, action, ctx) {
582
+ switch (action.type) {
583
+ case "MAPPING_DECLARE": {
584
+ if (action.declared.length === 0) {
585
+ if (snapshot.config.mappings.state === "not_declared") return snapshot;
586
+ ctx.resolver = null;
587
+ return {
588
+ ...snapshot,
589
+ config: { mappings: { state: "not_declared" } }
590
+ };
591
+ }
592
+ if (!ctx.resolver) {
593
+ ctx.resolver = new MappingResolver(action.declared, snapshot.generation);
594
+ } else {
595
+ ctx.resolver.redeclare(action.declared, snapshot.generation);
596
+ }
597
+ return {
598
+ ...snapshot,
599
+ config: {
600
+ mappings: {
601
+ state: "pending",
602
+ declared: action.declared,
603
+ declaredAtMs: action.atMs
604
+ }
605
+ }
606
+ };
607
+ }
608
+ case "MAPPING_REPORT": {
609
+ if (!ctx.resolver) return snapshot;
610
+ const outcome = ctx.resolver.ingest({
611
+ source: action.source,
612
+ payload: action.payload,
613
+ receivedAtMs: action.atMs,
614
+ generation: action.generation
615
+ });
616
+ if (outcome.kind !== "resolved") return snapshot;
617
+ return applyResolved(snapshot, outcome.state);
618
+ }
619
+ case "MAPPING_INVALIDATE": {
620
+ const previous = snapshot.config.mappings;
621
+ if (previous.state !== "complete" && previous.state !== "incomplete") {
622
+ return snapshot;
623
+ }
624
+ return {
625
+ ...snapshot,
626
+ config: {
627
+ mappings: {
628
+ state: "invalidating",
629
+ previous,
630
+ sinceMs: action.atMs
631
+ }
632
+ }
633
+ };
634
+ }
635
+ case "MAPPING_INVALIDATION_RESOLVE": {
636
+ if (snapshot.config.mappings.state !== "invalidating") return snapshot;
637
+ if (!ctx.resolver) {
638
+ return {
639
+ ...snapshot,
640
+ config: { mappings: snapshot.config.mappings.previous }
641
+ };
642
+ }
643
+ const outcome = ctx.resolver.current();
644
+ if (outcome.kind !== "resolved") {
645
+ return {
646
+ ...snapshot,
647
+ config: { mappings: snapshot.config.mappings.previous }
648
+ };
649
+ }
650
+ return applyResolved(snapshot, outcome.state);
651
+ }
652
+ case "MAPPING_TIMEOUT": {
653
+ const previous = snapshot.config.mappings;
654
+ if (previous.state !== "pending") return snapshot;
655
+ return {
656
+ ...snapshot,
657
+ config: {
658
+ mappings: {
659
+ state: "unreported",
660
+ declared: previous.declared,
661
+ afterMs: action.atMs - previous.declaredAtMs
662
+ }
663
+ }
664
+ };
665
+ }
666
+ }
667
+ }
668
+ function applyResolved(snapshot, resolved) {
669
+ const existing = snapshot.config.mappings;
670
+ if ((existing.state === "complete" || existing.state === "incomplete") && sameResolved(existing, resolved)) {
671
+ return snapshot;
672
+ }
673
+ return { ...snapshot, config: { mappings: resolved } };
674
+ }
675
+ function sameResolved(a, b) {
676
+ if (a.state !== b.state) return false;
677
+ if (a.state !== "complete" && a.state !== "incomplete") return false;
678
+ if (a.source !== b.source) return false;
679
+ const ak = Object.keys(a.mappings);
680
+ const bk = Object.keys(b.mappings);
681
+ if (ak.length !== bk.length) return false;
682
+ for (const k of ak) {
683
+ const av = a.mappings[k];
684
+ const bv = b.mappings[k];
685
+ if (Array.isArray(av) && Array.isArray(bv)) {
686
+ if (av.length !== bv.length) return false;
687
+ for (let i = 0; i < av.length; i++) if (av[i] !== bv[i]) return false;
688
+ } else if (av !== bv) {
689
+ return false;
690
+ }
691
+ }
692
+ return true;
693
+ }
694
+ function reduceStream(snapshot, action) {
695
+ if (action.type === "CURRENT_TABLE_KNOWN" || action.type === "CURRENT_TABLE_REFRESH_START" || action.type === "CURRENT_TABLE_ERROR") {
696
+ return snapshot;
697
+ }
698
+ const stream = action.stream;
699
+ const current = snapshot.sync[stream];
700
+ if (action.type === "STREAM_WARMING") {
701
+ if (current.state === "warming" || current.state === "hot") return snapshot;
702
+ return updateStream(snapshot, stream, { state: "warming", sinceMs: action.atMs });
703
+ }
704
+ if (action.type === "STREAM_STALE") {
705
+ if (current.state !== "hot") return snapshot;
706
+ return updateStream(snapshot, stream, {
707
+ state: "stale",
708
+ lastEventMs: current.lastEventMs,
709
+ reason: action.reason
710
+ });
711
+ }
712
+ if (current.state === "hot" && current.generation === action.generation && current.payloadHash === action.payloadHash) {
713
+ return snapshot;
714
+ }
715
+ return updateStream(snapshot, stream, {
716
+ state: "hot",
717
+ lastEventMs: action.atMs,
718
+ generation: action.generation,
719
+ payloadHash: action.payloadHash
720
+ });
721
+ }
722
+ function updateStream(snapshot, stream, next) {
723
+ return {
724
+ ...snapshot,
725
+ sync: { ...snapshot.sync, [stream]: next }
726
+ };
727
+ }
728
+ function updateSync(snapshot, sync) {
729
+ return { ...snapshot, sync };
730
+ }
731
+
732
+ // src/sdk/helpers/grist-widget-interaction.ts
733
+ function parseGristWidgetLinkingInfo(raw) {
734
+ if (!raw || typeof raw !== "object" || !("asTarget" in raw)) return void 0;
735
+ const linking = raw;
736
+ return {
737
+ asTarget: linking.asTarget == null ? null : String(linking.asTarget),
738
+ asSource: Boolean(linking.asSource)
739
+ };
740
+ }
741
+ function normalizeWidgetInteraction(interaction) {
742
+ if (!interaction || typeof interaction !== "object") return interaction;
743
+ const raw = interaction;
744
+ const access_level = typeof raw.access_level === "string" ? raw.access_level : typeof raw.accessLevel === "string" ? raw.accessLevel : void 0;
745
+ const linking = parseGristWidgetLinkingInfo(raw.linking);
746
+ return {
747
+ ...interaction,
748
+ ...access_level ? { access_level } : {},
749
+ ...linking ? { linking } : {}
750
+ };
751
+ }
752
+
753
+ // src/sdk/internal/ready-singleton.ts
754
+ var ACCESS_RANK2 = {
755
+ none: 0,
756
+ "read table": 1,
757
+ full: 2
758
+ };
759
+ var inFlight = null;
760
+ var lastAccess = null;
761
+ function shouldReinit(next) {
762
+ if (!lastAccess) return true;
763
+ return ACCESS_RANK2[next] > ACCESS_RANK2[lastAccess];
764
+ }
765
+ function ensureGristReady(payload) {
766
+ const access = payload.requiredAccess ?? "read table";
767
+ if (inFlight && !shouldReinit(access)) return inFlight;
768
+ lastAccess = access;
769
+ const next = Promise.resolve().then(() => {
770
+ const result = grist.ready(payload);
771
+ return result instanceof Promise ? result : Promise.resolve();
772
+ });
773
+ inFlight = next.catch((err) => {
774
+ inFlight = null;
775
+ lastAccess = null;
776
+ throw err;
777
+ });
778
+ return inFlight;
779
+ }
780
+ function resetGristReadySingleton() {
781
+ inFlight = null;
782
+ lastAccess = null;
783
+ }
784
+ var resetGristReadyCacheForTests = resetGristReadySingleton;
785
+
786
+ // src/sdk/internal/subscriptions.ts
787
+ var GristEvent = class {
788
+ constructor(bindOnce) {
789
+ this.bindOnce = bindOnce;
790
+ this.listeners = /* @__PURE__ */ new Set();
791
+ this.hasValue = false;
792
+ this.bind = null;
793
+ }
794
+ subscribe(listener) {
795
+ this.listeners.add(listener);
796
+ if (!this.bind) {
797
+ this.bind = () => {
798
+ this.bind = () => {
799
+ };
800
+ try {
801
+ this.bindOnce((value) => {
802
+ this.hasValue = true;
803
+ this.last = value;
804
+ for (const l of this.listeners) l(value);
805
+ });
806
+ } catch (err) {
807
+ if (typeof console !== "undefined") {
808
+ console.error("[lib/grist] failed to subscribe to Grist event:", err);
809
+ }
810
+ }
811
+ };
812
+ this.bind();
813
+ }
814
+ if (this.hasValue && this.last !== void 0) {
815
+ listener(this.last);
816
+ }
817
+ return () => {
818
+ this.listeners.delete(listener);
819
+ };
820
+ }
821
+ /** Last cached value (or `undefined` if no event has fired yet). */
822
+ peek() {
823
+ return this.last;
824
+ }
825
+ /** True once at least one event has fired. */
826
+ get ready() {
827
+ return this.hasValue;
828
+ }
829
+ /**
830
+ * Test helper: fan out a payload without calling `grist.on*`.
831
+ * Used to simulate hosts that reuse one record object and mutate it in place.
832
+ */
833
+ deliverForTests(value) {
834
+ this.hasValue = true;
835
+ this.last = value;
836
+ for (const l of this.listeners) l(value);
837
+ }
838
+ /**
839
+ * Test helper: forget the bound state and cached value. Lets a test swap
840
+ * `window.grist` (e.g. via the emulator's `dispose()` + `createGristEmulator()`)
841
+ * and re-bind cleanly on the next subscribe.
842
+ */
843
+ _resetForTests() {
844
+ this.listeners.clear();
845
+ this.hasValue = false;
846
+ this.last = void 0;
847
+ this.bind = null;
848
+ }
849
+ };
850
+ var recordEvent = new GristEvent((emit) => {
851
+ const deliver = (record, mappings) => {
852
+ emit({ record, mappings });
853
+ };
854
+ grist.onRecord(
855
+ (record, mappings) => {
856
+ deliver(record, mappings ?? null);
857
+ },
858
+ { keepEncoded: false }
859
+ );
860
+ const fetchSelectedRecord = grist.fetchSelectedRecord ?? grist.docApi?.fetchSelectedRecord;
861
+ if (typeof grist.on !== "function" || typeof fetchSelectedRecord !== "function") {
862
+ return;
863
+ }
864
+ let lastRowId;
865
+ grist.on("message", async (msg) => {
866
+ if (!msg || typeof msg !== "object") return;
867
+ const host = msg;
868
+ if (!host.tableId || typeof host.rowId !== "number") return;
869
+ if (host.rowId === lastRowId) return;
870
+ lastRowId = host.rowId;
871
+ try {
872
+ const record = await fetchSelectedRecord(host.rowId, { keepEncoded: false });
873
+ deliver(record, recordEvent.peek()?.mappings ?? null);
874
+ } catch (err) {
875
+ if (typeof console !== "undefined") {
876
+ console.error("[grist-widget-sdk] fetchSelectedRecord on cursor message failed:", err);
877
+ }
878
+ }
879
+ });
880
+ });
881
+ var recordsEvent = new GristEvent((emit) => {
882
+ grist.onRecords(
883
+ (records, mappings) => {
884
+ emit({ records, mappings: mappings ?? null });
885
+ },
886
+ { keepEncoded: false, format: "rows" }
887
+ );
888
+ });
889
+ var optionsEvent = new GristEvent((emit) => {
890
+ grist.onOptions((options, interaction) => {
891
+ const normalized = normalizeWidgetInteraction(
892
+ interaction ?? null
893
+ );
894
+ emit({
895
+ options: options ? { ...options } : null,
896
+ interaction: normalized
897
+ });
898
+ });
899
+ });
900
+ var newRecordEvent = new GristEvent((emit) => {
901
+ if (typeof grist.onNewRecord !== "function") return;
902
+ grist.onNewRecord((mappings) => {
903
+ emit({ mappings: mappings ?? null });
904
+ });
905
+ });
906
+ function resetGristEventsForTests() {
907
+ recordEvent._resetForTests();
908
+ recordsEvent._resetForTests();
909
+ optionsEvent._resetForTests();
910
+ newRecordEvent._resetForTests();
911
+ }
912
+
913
+ // src/sdk/internal/handshake/effects/detect.ts
914
+ var DEFAULT_POLL_SEQUENCE_MS = [
915
+ 200,
916
+ 200,
917
+ 400,
918
+ 400,
919
+ 800,
920
+ 1600,
921
+ 3200,
922
+ 5e3,
923
+ 5e3,
924
+ 5e3,
925
+ 5e3,
926
+ 5e3,
927
+ 5e3,
928
+ 5e3
929
+ ];
930
+ function defaultBudgetMs(hint) {
931
+ if (hint === "slow-2g" || hint === "2g") return 12e4;
932
+ if (hint === "3g") return 6e4;
933
+ return 3e4;
934
+ }
935
+ function startDetectEffect(env, dispatch, signal, options = {}) {
936
+ const sequence = options.pollSequenceMs ?? DEFAULT_POLL_SEQUENCE_MS;
937
+ const budgetMs = options.budgetMs ?? defaultBudgetMs(env.effectiveTypeHint());
938
+ const startedAt = env.now();
939
+ let attempts = 0;
940
+ let timer = null;
941
+ let cancelled = false;
942
+ signal.addEventListener("abort", () => {
943
+ cancelled = true;
944
+ if (timer !== null) env.clearTimeout(timer);
945
+ });
946
+ dispatch({ type: "DETECT_START", atMs: startedAt });
947
+ const tick = () => {
948
+ if (cancelled) return;
949
+ timer = null;
950
+ const probe = env.probeGrist();
951
+ if (probe !== null) {
952
+ if (probe.embedded) {
953
+ dispatch({ type: "DETECT_AVAILABLE", atMs: env.now() });
954
+ } else {
955
+ dispatch({ type: "NOT_EMBEDDED", atMs: env.now() });
956
+ }
957
+ return;
958
+ }
959
+ attempts += 1;
960
+ dispatch({ type: "DETECT_TICK", attempts, atMs: env.now() });
961
+ const elapsed = env.now() - startedAt;
962
+ if (elapsed >= budgetMs) {
963
+ dispatch({ type: "DETECT_TIMEOUT", attempts, atMs: env.now() });
964
+ return;
965
+ }
966
+ const next = sequence[Math.min(attempts - 1, sequence.length - 1)] ?? 1e3;
967
+ const remaining = budgetMs - elapsed;
968
+ timer = env.setTimeout(tick, Math.max(0, Math.min(next, remaining)));
969
+ };
970
+ tick();
971
+ return {
972
+ cancel() {
973
+ cancelled = true;
974
+ if (timer !== null) {
975
+ env.clearTimeout(timer);
976
+ timer = null;
977
+ }
978
+ }
979
+ };
980
+ }
981
+
982
+ // src/sdk/internal/handshake/effects/negotiate.ts
983
+ var DEFAULT_NEGOTIATE_TIMEOUT_MS = 3e4;
984
+ function startNegotiateEffect(env, dispatch, signal, payload, options = {}) {
985
+ const timeoutMs = options.timeoutMs ?? DEFAULT_NEGOTIATE_TIMEOUT_MS;
986
+ const access = payload.requiredAccess ?? "read table";
987
+ let settled = false;
988
+ let timer = null;
989
+ const settle = (next) => {
990
+ if (settled) return;
991
+ settled = true;
992
+ if (timer !== null) env.clearTimeout(timer);
993
+ if (signal.aborted) return;
994
+ next();
995
+ };
996
+ dispatch({ type: "NEGOTIATE_START", access, atMs: env.now() });
997
+ const grist2 = env.getGrist();
998
+ if (!grist2) {
999
+ settle(
1000
+ () => dispatch({
1001
+ type: "NEGOTIATE_FAIL",
1002
+ reason: { kind: "ready_failed", message: "grist global missing at negotiate" },
1003
+ atMs: env.now()
1004
+ })
1005
+ );
1006
+ return { cancel: () => settle(() => {
1007
+ }) };
1008
+ }
1009
+ timer = env.setTimeout(() => {
1010
+ if (settled) return;
1011
+ settle(
1012
+ () => dispatch({
1013
+ type: "NEGOTIATE_FAIL",
1014
+ reason: { kind: "ready_timeout", afterMs: timeoutMs },
1015
+ atMs: env.now()
1016
+ })
1017
+ );
1018
+ }, timeoutMs);
1019
+ const handleSuccess = (g) => {
1020
+ if (!g.docApi) {
1021
+ dispatch({
1022
+ type: "NEGOTIATE_FAIL",
1023
+ reason: { kind: "ready_failed", message: "grist.docApi missing after ready" },
1024
+ atMs: env.now()
1025
+ });
1026
+ return;
1027
+ }
1028
+ dispatch({
1029
+ type: "NEGOTIATE_SUCCESS",
1030
+ access,
1031
+ grantedLevel: access,
1032
+ // host doesn't report effective level; widen later via authz events
1033
+ atMs: env.now()
1034
+ });
1035
+ };
1036
+ const handleFailure = (err) => {
1037
+ const message = err instanceof Error ? err.message : String(err);
1038
+ const reason = { kind: "ready_failed", message };
1039
+ dispatch({ type: "NEGOTIATE_FAIL", reason, atMs: env.now() });
1040
+ };
1041
+ const readyImpl = options.readyImpl ?? ((p) => grist2.ready(p));
1042
+ try {
1043
+ const result = readyImpl(payload);
1044
+ if (result && typeof result.then === "function") {
1045
+ ;
1046
+ result.then(
1047
+ () => settle(() => handleSuccess(env.getGrist() ?? grist2)),
1048
+ (err) => settle(() => handleFailure(err))
1049
+ );
1050
+ } else {
1051
+ settle(() => handleSuccess(env.getGrist() ?? grist2));
1052
+ }
1053
+ } catch (err) {
1054
+ settle(() => handleFailure(err));
1055
+ }
1056
+ signal.addEventListener("abort", () => settle(() => {
1057
+ }));
1058
+ return { cancel: () => settle(() => {
1059
+ }) };
1060
+ }
1061
+
1062
+ // src/sdk/internal/handshake/effects/subscriptions.ts
1063
+ function defaultSubscriptionsBinder(ctx) {
1064
+ const offs = [];
1065
+ offs.push(
1066
+ recordEvent.subscribe((payload) => {
1067
+ const hash = quickHash("record", payload);
1068
+ dispatchStream(ctx, "record", hash);
1069
+ ctx.onRecordPayload?.(payload.mappings ?? null);
1070
+ })
1071
+ );
1072
+ offs.push(
1073
+ recordsEvent.subscribe((payload) => {
1074
+ const hash = quickHash("records", payload);
1075
+ dispatchStream(ctx, "records", hash);
1076
+ ctx.onRecordsPayload?.(payload.mappings ?? null);
1077
+ })
1078
+ );
1079
+ offs.push(
1080
+ optionsEvent.subscribe((payload) => {
1081
+ const hash = quickHash("options", payload);
1082
+ dispatchStream(ctx, "options", hash);
1083
+ const level = parseGristRequiredAccess(payload.interaction?.access_level);
1084
+ if (level !== null) {
1085
+ ctx.dispatch({
1086
+ type: "AUTHZ_REPORT",
1087
+ level,
1088
+ atMs: Date.now(),
1089
+ generation: ctx.getGeneration()
1090
+ });
1091
+ }
1092
+ ctx.onOptionsPayload?.(payload.options ?? null);
1093
+ })
1094
+ );
1095
+ offs.push(
1096
+ newRecordEvent.subscribe((payload) => {
1097
+ const hash = quickHash("newRecord", payload);
1098
+ dispatchStream(ctx, "newRecord", hash);
1099
+ ctx.onNewRecordPayload?.(payload.mappings ?? null);
1100
+ })
1101
+ );
1102
+ return {
1103
+ cancel() {
1104
+ for (const off of offs.splice(0)) off();
1105
+ }
1106
+ };
1107
+ }
1108
+ function dispatchStream(ctx, stream, payloadHash) {
1109
+ ctx.dispatch({
1110
+ type: "STREAM_RECEIVED",
1111
+ stream,
1112
+ payloadHash,
1113
+ atMs: Date.now(),
1114
+ generation: ctx.getGeneration()
1115
+ });
1116
+ }
1117
+ function quickHash(kind, payload) {
1118
+ return `${kind}::${stableSerialize(payload)}`;
1119
+ }
1120
+ function stableSerialize(value) {
1121
+ if (value === null) return "null";
1122
+ if (value === void 0) return "undefined";
1123
+ const t = typeof value;
1124
+ if (t === "number" || t === "string" || t === "boolean") return JSON.stringify(value);
1125
+ if (Array.isArray(value)) {
1126
+ return `[${value.map(stableSerialize).join(",")}]`;
1127
+ }
1128
+ if (t === "object") {
1129
+ const obj = value;
1130
+ const keys = Object.keys(obj).sort();
1131
+ const body = keys.map((k) => `${JSON.stringify(k)}:${stableSerialize(obj[k])}`).join(",");
1132
+ return `{${body}}`;
1133
+ }
1134
+ return String(value);
1135
+ }
1136
+
1137
+ // src/sdk/internal/handshake/effects/mappings.ts
1138
+ var DEFAULT_MAPPING_TIMEOUT_MS = 5e3;
1139
+ function startMappingsEffect(env, dispatch, signal, declared, getGeneration, options = {}) {
1140
+ let timeoutHandle = null;
1141
+ let cancelled = false;
1142
+ const startMs = env.now();
1143
+ dispatch({ type: "MAPPING_DECLARE", declared, atMs: startMs, generation: getGeneration() });
1144
+ if (declared.length === 0) {
1145
+ return {
1146
+ ingestStreamPayload: () => {
1147
+ },
1148
+ refetchSectionApi: async () => {
1149
+ },
1150
+ cancel: () => {
1151
+ }
1152
+ };
1153
+ }
1154
+ const timeoutMs = options.timeoutMs ?? DEFAULT_MAPPING_TIMEOUT_MS;
1155
+ timeoutHandle = env.setTimeout(() => {
1156
+ if (cancelled || signal.aborted) return;
1157
+ dispatch({ type: "MAPPING_TIMEOUT", atMs: env.now(), generation: getGeneration() });
1158
+ }, timeoutMs);
1159
+ signal.addEventListener("abort", () => {
1160
+ cancelled = true;
1161
+ if (timeoutHandle !== null) env.clearTimeout(timeoutHandle);
1162
+ });
1163
+ const ingestPayload = (source, raw) => {
1164
+ if (cancelled || signal.aborted) return;
1165
+ const payload = coerceMappingsPayload(raw);
1166
+ dispatch({
1167
+ type: "MAPPING_REPORT",
1168
+ source,
1169
+ payload,
1170
+ atMs: env.now(),
1171
+ generation: getGeneration()
1172
+ });
1173
+ };
1174
+ const refetchSectionApi = async () => {
1175
+ if (cancelled || signal.aborted) return;
1176
+ const grist2 = env.getGrist();
1177
+ const api = grist2?.sectionApi;
1178
+ if (!api || typeof api.mappings !== "function") return;
1179
+ try {
1180
+ const payload = await api.mappings();
1181
+ ingestPayload("section_api", payload);
1182
+ } catch {
1183
+ ingestPayload("section_api", null);
1184
+ }
1185
+ };
1186
+ void refetchSectionApi();
1187
+ return {
1188
+ ingestStreamPayload: (source, payload) => ingestPayload(source, payload),
1189
+ refetchSectionApi,
1190
+ cancel() {
1191
+ cancelled = true;
1192
+ if (timeoutHandle !== null) env.clearTimeout(timeoutHandle);
1193
+ }
1194
+ };
1195
+ }
1196
+ function coerceMappingsPayload(raw) {
1197
+ if (raw === null || raw === void 0) return null;
1198
+ if (typeof raw !== "object") return null;
1199
+ return raw;
1200
+ }
1201
+
1202
+ // src/sdk/internal/handshake/effects/heartbeat.ts
1203
+ var DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
1204
+ var DEFAULT_HEARTBEAT_PING_TIMEOUT_MS = 1e4;
1205
+ function startHeartbeatEffect(env, dispatch, signal, options = {}) {
1206
+ const intervalMs = options.intervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
1207
+ const pingTimeoutMs = options.pingTimeoutMs ?? DEFAULT_HEARTBEAT_PING_TIMEOUT_MS;
1208
+ const pauseWhenHidden = options.pauseWhenHidden ?? true;
1209
+ const probe = options.probe ?? defaultProbe(env);
1210
+ let cancelled = false;
1211
+ let paused = false;
1212
+ let intervalTimer = null;
1213
+ let inFlight2 = false;
1214
+ let inFlightTimeoutTimer = null;
1215
+ const clearInterval = () => {
1216
+ if (intervalTimer !== null) {
1217
+ env.clearTimeout(intervalTimer);
1218
+ intervalTimer = null;
1219
+ }
1220
+ };
1221
+ const clearInFlightTimeout = () => {
1222
+ if (inFlightTimeoutTimer !== null) {
1223
+ env.clearTimeout(inFlightTimeoutTimer);
1224
+ inFlightTimeoutTimer = null;
1225
+ }
1226
+ };
1227
+ const scheduleNext = (delay = intervalMs) => {
1228
+ clearInterval();
1229
+ if (cancelled || paused) return;
1230
+ intervalTimer = env.setTimeout(ping, delay);
1231
+ };
1232
+ const ping = () => {
1233
+ if (cancelled || paused) return;
1234
+ intervalTimer = null;
1235
+ if (inFlight2) {
1236
+ return;
1237
+ }
1238
+ inFlight2 = true;
1239
+ inFlightTimeoutTimer = env.setTimeout(() => {
1240
+ if (!inFlight2) return;
1241
+ inFlight2 = false;
1242
+ clearInFlightTimeout();
1243
+ if (!cancelled) {
1244
+ dispatch({ type: "HEARTBEAT_FAIL", atMs: env.now() });
1245
+ scheduleNext();
1246
+ }
1247
+ }, pingTimeoutMs);
1248
+ const handleOk = () => {
1249
+ if (!inFlight2) return;
1250
+ inFlight2 = false;
1251
+ clearInFlightTimeout();
1252
+ if (cancelled) return;
1253
+ dispatch({ type: "HEARTBEAT_OK", atMs: env.now() });
1254
+ scheduleNext();
1255
+ };
1256
+ const handleFail = () => {
1257
+ if (!inFlight2) return;
1258
+ inFlight2 = false;
1259
+ clearInFlightTimeout();
1260
+ if (cancelled) return;
1261
+ dispatch({ type: "HEARTBEAT_FAIL", atMs: env.now() });
1262
+ scheduleNext();
1263
+ };
1264
+ let result;
1265
+ try {
1266
+ result = probe();
1267
+ } catch {
1268
+ handleFail();
1269
+ return;
1270
+ }
1271
+ if (result && typeof result.then === "function") {
1272
+ ;
1273
+ result.then(handleOk, handleFail);
1274
+ } else {
1275
+ handleOk();
1276
+ }
1277
+ };
1278
+ const offVisibility = pauseWhenHidden && env.onVisibilityChange ? env.onVisibilityChange((visible) => {
1279
+ if (cancelled) return;
1280
+ if (visible) {
1281
+ if (paused) {
1282
+ paused = false;
1283
+ ping();
1284
+ }
1285
+ } else {
1286
+ paused = true;
1287
+ clearInterval();
1288
+ }
1289
+ }) : null;
1290
+ const offOnline = env.onOnline?.(() => {
1291
+ if (cancelled || paused) return;
1292
+ ping();
1293
+ }) ?? null;
1294
+ signal.addEventListener("abort", () => {
1295
+ cancelled = true;
1296
+ clearInterval();
1297
+ clearInFlightTimeout();
1298
+ inFlight2 = false;
1299
+ offVisibility?.();
1300
+ offOnline?.();
1301
+ });
1302
+ scheduleNext();
1303
+ return {
1304
+ cancel() {
1305
+ cancelled = true;
1306
+ clearInterval();
1307
+ clearInFlightTimeout();
1308
+ inFlight2 = false;
1309
+ offVisibility?.();
1310
+ offOnline?.();
1311
+ },
1312
+ recordRpcSuccess() {
1313
+ if (cancelled || paused) return;
1314
+ dispatch({ type: "RPC_SUCCESS", atMs: env.now() });
1315
+ scheduleNext();
1316
+ },
1317
+ recordRpcFailure() {
1318
+ if (cancelled || paused) return;
1319
+ dispatch({ type: "RPC_FAILURE", atMs: env.now(), kind: "other" });
1320
+ scheduleNext(Math.min(intervalMs, 1e3));
1321
+ },
1322
+ pingNow() {
1323
+ if (cancelled) return;
1324
+ ping();
1325
+ }
1326
+ };
1327
+ }
1328
+ function defaultProbe(env) {
1329
+ return async () => {
1330
+ const g = env.getGrist();
1331
+ if (!g) throw new Error("grist global missing");
1332
+ const docApi = g.docApi;
1333
+ if (!docApi || typeof docApi.getDocName !== "function") {
1334
+ throw new Error("grist.docApi.getDocName unavailable");
1335
+ }
1336
+ return docApi.getDocName();
1337
+ };
1338
+ }
1339
+
1340
+ // src/sdk/internal/handshake/authz-from-options-cache.ts
1341
+ function denyAuthzFromCachedOptionsIfInsufficient(snapshot, dispatch, env) {
1342
+ if (snapshot.lifecycle.phase !== "online") return;
1343
+ if (snapshot.authz.state === "denied") return;
1344
+ const payload = optionsEvent.peek();
1345
+ const level = parseGristRequiredAccess(payload?.interaction?.access_level);
1346
+ if (level === null) return;
1347
+ const declared = snapshot.authz.declared;
1348
+ if (isAccessSufficient(level, declared)) return;
1349
+ dispatch({
1350
+ type: "AUTHZ_REPORT",
1351
+ level,
1352
+ atMs: env.now(),
1353
+ generation: snapshot.generation
1354
+ });
1355
+ }
1356
+
1357
+ // src/sdk/internal/handshake/environment.ts
1358
+ function createBrowserEnvironment() {
1359
+ return {
1360
+ now: () => typeof performance !== "undefined" ? performance.now() : Date.now(),
1361
+ setTimeout: (cb, ms) => globalThis.setTimeout(cb, ms),
1362
+ clearTimeout: (h) => globalThis.clearTimeout(h),
1363
+ probeGrist() {
1364
+ if (typeof globalThis === "undefined") return null;
1365
+ const g = globalThis.grist;
1366
+ if (typeof g === "undefined") return null;
1367
+ const embedded2 = typeof window === "undefined" ? false : window.self !== window.top;
1368
+ return { embedded: embedded2 };
1369
+ },
1370
+ getGrist() {
1371
+ const g = globalThis.grist;
1372
+ return g ?? null;
1373
+ },
1374
+ effectiveTypeHint() {
1375
+ if (typeof navigator === "undefined") return null;
1376
+ const conn = navigator.connection;
1377
+ const t = conn?.effectiveType;
1378
+ if (t === "slow-2g" || t === "2g" || t === "3g" || t === "4g" || t === "5g") return t;
1379
+ return null;
1380
+ },
1381
+ onVisibilityChange(listener) {
1382
+ if (typeof document === "undefined") return () => {
1383
+ };
1384
+ const handler = () => listener(document.visibilityState === "visible");
1385
+ document.addEventListener("visibilitychange", handler);
1386
+ return () => document.removeEventListener("visibilitychange", handler);
1387
+ },
1388
+ onOnline(listener) {
1389
+ if (typeof window === "undefined") return () => {
1390
+ };
1391
+ const handler = () => listener();
1392
+ window.addEventListener("online", handler);
1393
+ return () => window.removeEventListener("online", handler);
1394
+ }
1395
+ };
1396
+ }
1397
+
1398
+ // src/sdk/internal/handshake/manager.ts
1399
+ function createGristHandshakeManager(options = {}) {
1400
+ const env = options.env ?? createBrowserEnvironment();
1401
+ const reducerConfig = {
1402
+ ...DEFAULT_REDUCER_CONFIG,
1403
+ ...options.reducerConfig ?? {}
1404
+ };
1405
+ let snapshot = initialGristSnapshot();
1406
+ const ctx = createReducerContext();
1407
+ const listeners = /* @__PURE__ */ new Set();
1408
+ let started = false;
1409
+ let abort = null;
1410
+ let detectHandle = null;
1411
+ let negotiateHandle = null;
1412
+ let subscriptionsHandle = null;
1413
+ let mappingsHandle = null;
1414
+ let heartbeatHandle = null;
1415
+ let recheckAuthzFromCacheAfterOnline = false;
1416
+ const declared = options.columns ?? [];
1417
+ const subscriptionsBinder = options.subscriptionsBinder ?? defaultSubscriptionsBinder;
1418
+ const notify = () => {
1419
+ for (const l of listeners) {
1420
+ try {
1421
+ l();
1422
+ } catch (err) {
1423
+ options.onError?.(err, "listener");
1424
+ }
1425
+ }
1426
+ };
1427
+ const dispatch = (action) => {
1428
+ const prev = snapshot;
1429
+ const next = gristReducer(prev, action, ctx, reducerConfig);
1430
+ if (next !== prev) {
1431
+ snapshot = next;
1432
+ onTransition(prev, next);
1433
+ notify();
1434
+ }
1435
+ };
1436
+ const onTransition = (prev, next) => {
1437
+ if (prev.lifecycle.phase !== "negotiating" && next.lifecycle.phase === "negotiating") {
1438
+ launchNegotiate();
1439
+ launchSubscriptions();
1440
+ }
1441
+ if (prev.lifecycle.phase !== "online" && next.lifecycle.phase === "online") {
1442
+ launchMappings();
1443
+ launchHeartbeat();
1444
+ if (recheckAuthzFromCacheAfterOnline) {
1445
+ recheckAuthzFromCacheAfterOnline = false;
1446
+ denyAuthzFromCachedOptionsIfInsufficient(next, dispatch, env);
1447
+ }
1448
+ }
1449
+ if (prev.lifecycle.phase === "online" && next.lifecycle.phase !== "online") {
1450
+ heartbeatHandle?.cancel();
1451
+ heartbeatHandle = null;
1452
+ }
1453
+ };
1454
+ const launchDetect = () => {
1455
+ if (!abort) return;
1456
+ detectHandle?.cancel();
1457
+ detectHandle = startDetectEffect(env, dispatch, abort.signal, options.detect);
1458
+ };
1459
+ const launchNegotiate = () => {
1460
+ if (!abort) return;
1461
+ negotiateHandle?.cancel();
1462
+ negotiateHandle = startNegotiateEffect(
1463
+ env,
1464
+ dispatch,
1465
+ abort.signal,
1466
+ buildReadyPayload(options),
1467
+ options.negotiate
1468
+ );
1469
+ };
1470
+ const launchSubscriptions = () => {
1471
+ if (!abort) return;
1472
+ if (subscriptionsHandle) return;
1473
+ subscriptionsHandle = subscriptionsBinder({
1474
+ dispatch,
1475
+ getGeneration: () => snapshot.generation,
1476
+ onRecordPayload: (m) => mappingsHandle?.ingestStreamPayload("stream_record", m),
1477
+ onRecordsPayload: (m) => mappingsHandle?.ingestStreamPayload("stream_records", m),
1478
+ onNewRecordPayload: (m) => mappingsHandle?.ingestStreamPayload("stream_new_record", m)
1479
+ });
1480
+ };
1481
+ const launchMappings = () => {
1482
+ if (!abort) return;
1483
+ launchSubscriptions();
1484
+ if (mappingsHandle) return;
1485
+ mappingsHandle = startMappingsEffect(
1486
+ env,
1487
+ dispatch,
1488
+ abort.signal,
1489
+ declared,
1490
+ () => snapshot.generation,
1491
+ options.mappings
1492
+ );
1493
+ };
1494
+ const launchHeartbeat = () => {
1495
+ if (!abort) return;
1496
+ if (options.heartbeat === false) return;
1497
+ if (heartbeatHandle) return;
1498
+ heartbeatHandle = startHeartbeatEffect(
1499
+ env,
1500
+ dispatch,
1501
+ abort.signal,
1502
+ options.heartbeat ?? {}
1503
+ );
1504
+ };
1505
+ const cancelAllEffects = () => {
1506
+ detectHandle?.cancel();
1507
+ detectHandle = null;
1508
+ negotiateHandle?.cancel();
1509
+ negotiateHandle = null;
1510
+ mappingsHandle?.cancel();
1511
+ mappingsHandle = null;
1512
+ heartbeatHandle?.cancel();
1513
+ heartbeatHandle = null;
1514
+ if (abort && !abort.signal.aborted) abort.abort();
1515
+ };
1516
+ const controls = {
1517
+ start() {
1518
+ if (started) return;
1519
+ started = true;
1520
+ abort = new AbortController();
1521
+ launchDetect();
1522
+ },
1523
+ stop() {
1524
+ if (!started) return;
1525
+ started = false;
1526
+ cancelAllEffects();
1527
+ subscriptionsHandle?.cancel();
1528
+ subscriptionsHandle = null;
1529
+ snapshot = initialGristSnapshot();
1530
+ notify();
1531
+ },
1532
+ reload() {
1533
+ if (!started) {
1534
+ controls.start();
1535
+ return;
1536
+ }
1537
+ recheckAuthzFromCacheAfterOnline = true;
1538
+ try {
1539
+ options.onBeforeReload?.();
1540
+ } catch (err) {
1541
+ options.onError?.(err, "onBeforeReload");
1542
+ }
1543
+ cancelAllEffects();
1544
+ dispatch({ type: "BUMP_GENERATION", atMs: env.now(), reason: "reload" });
1545
+ snapshot = {
1546
+ ...initialGristSnapshot(),
1547
+ generation: nextGeneration(snapshot.generation)
1548
+ };
1549
+ ctx.resolver = null;
1550
+ abort = new AbortController();
1551
+ launchDetect();
1552
+ notify();
1553
+ },
1554
+ restart() {
1555
+ controls.reload();
1556
+ if (typeof window !== "undefined" && typeof window.location?.reload === "function") {
1557
+ try {
1558
+ window.location.reload();
1559
+ } catch (err) {
1560
+ options.onError?.(err, "restart");
1561
+ }
1562
+ }
1563
+ },
1564
+ subscribe(listener) {
1565
+ listeners.add(listener);
1566
+ return () => listeners.delete(listener);
1567
+ },
1568
+ getSnapshot: () => snapshot,
1569
+ dispatch,
1570
+ recordRpcSuccess() {
1571
+ heartbeatHandle?.recordRpcSuccess();
1572
+ },
1573
+ recordRpcFailure() {
1574
+ heartbeatHandle?.recordRpcFailure();
1575
+ }
1576
+ };
1577
+ return controls;
1578
+ }
1579
+ function buildReadyPayload(options) {
1580
+ const payload = {
1581
+ requiredAccess: options.requiredAccess ?? "read table",
1582
+ columns: options.columns ?? []
1583
+ };
1584
+ if (options.allowSelectBy !== void 0) payload.allowSelectBy = options.allowSelectBy;
1585
+ if (options.hasCustomOptions !== void 0) payload.hasCustomOptions = options.hasCustomOptions;
1586
+ if (options.onEditOptions) payload.onEditOptions = options.onEditOptions;
1587
+ return payload;
1588
+ }
1589
+
1590
+ // src/sdk/internal/embedded-handshake-manager.ts
1591
+ var embedded = null;
1592
+ function acquireEmbeddedHandshakeManager(options) {
1593
+ if (!embedded) {
1594
+ embedded = {
1595
+ manager: createGristHandshakeManager(options),
1596
+ refCount: 0
1597
+ };
1598
+ embedded.manager.start();
1599
+ }
1600
+ embedded.refCount += 1;
1601
+ return embedded.manager;
1602
+ }
1603
+ function releaseEmbeddedHandshakeManager() {
1604
+ if (!embedded) return;
1605
+ embedded.refCount -= 1;
1606
+ if (embedded.refCount <= 0) {
1607
+ embedded.manager.stop();
1608
+ embedded = null;
1609
+ }
1610
+ }
1611
+ function resetEmbeddedHandshakeManagerForTests() {
1612
+ if (embedded) {
1613
+ embedded.manager.stop();
1614
+ embedded = null;
1615
+ }
1616
+ }
1617
+
1618
+ export {
1619
+ validateColumnMappings,
1620
+ gristAccessLevelLabel,
1621
+ initialGristSnapshot,
1622
+ deriveStatus,
1623
+ deriveErrorMessage,
1624
+ deriveCapabilities,
1625
+ extractResolvedMappings,
1626
+ deriveColumnMappingStatus,
1627
+ parseGristWidgetLinkingInfo,
1628
+ ensureGristReady,
1629
+ resetGristReadySingleton,
1630
+ resetGristReadyCacheForTests,
1631
+ recordEvent,
1632
+ recordsEvent,
1633
+ optionsEvent,
1634
+ newRecordEvent,
1635
+ resetGristEventsForTests,
1636
+ createGristHandshakeManager,
1637
+ acquireEmbeddedHandshakeManager,
1638
+ releaseEmbeddedHandshakeManager,
1639
+ resetEmbeddedHandshakeManagerForTests
1640
+ };
1641
+ //# sourceMappingURL=chunk-XE2SKNLH.js.map