@powerhousedao/reactor-browser 6.2.3 → 6.3.0-dev.1

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 (87) hide show
  1. package/dist/{attachment-service-But1Xljo.d.ts → attachment-service-B-AmTrs2.d.ts} +605 -56
  2. package/dist/attachment-service-B-AmTrs2.d.ts.map +1 -0
  3. package/dist/auth-DRbzRdeC.d.ts +32 -0
  4. package/dist/auth-DRbzRdeC.d.ts.map +1 -0
  5. package/dist/{client-BiJAJ9dW.js → client-BFnMV-EO.js} +39 -22
  6. package/dist/client-BFnMV-EO.js.map +1 -0
  7. package/dist/{client-CngU4mtn.d.ts → client-BP0hXjqq.d.ts} +3 -2
  8. package/dist/client-BP0hXjqq.d.ts.map +1 -0
  9. package/dist/client-wwavHFfs.js +135 -0
  10. package/dist/client-wwavHFfs.js.map +1 -0
  11. package/dist/{dispatch-qRXS70fh.js → dispatch-Cylwl2Dk.js} +363 -44
  12. package/dist/dispatch-Cylwl2Dk.js.map +1 -0
  13. package/dist/{document-by-id-B_8DA4yZ.js → document-by-id-DdvqanGR.js} +2 -2
  14. package/dist/{document-by-id-B_8DA4yZ.js.map → document-by-id-DdvqanGR.js.map} +1 -1
  15. package/dist/document-model-modules-BG-61uke.js +710 -0
  16. package/dist/document-model-modules-BG-61uke.js.map +1 -0
  17. package/dist/{document-operations-Bt-1-ThH.js → document-operations-DRMMwmGZ.js} +2160 -181
  18. package/dist/document-operations-DRMMwmGZ.js.map +1 -0
  19. package/dist/global-iARBhxNI.d.ts +612 -0
  20. package/dist/global-iARBhxNI.d.ts.map +1 -0
  21. package/dist/{index-BABMK8cO.d.ts → index-CNS_9THu.d.ts} +14 -4
  22. package/dist/index-CNS_9THu.d.ts.map +1 -0
  23. package/dist/index.d.ts +560 -79
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +790 -317
  26. package/dist/index.js.map +1 -1
  27. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  28. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  29. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  30. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  31. package/dist/{relational-ChC_AWAK.js → relational-DZuyKp2y.js} +65 -5
  32. package/dist/relational-DZuyKp2y.js.map +1 -0
  33. package/dist/{renown-C9pYZRqf.js → renown-B3MUaiq7.js} +56 -25
  34. package/dist/renown-B3MUaiq7.js.map +1 -0
  35. package/dist/renown-CBoTdGrg.js +394 -0
  36. package/dist/renown-CBoTdGrg.js.map +1 -0
  37. package/dist/{client-VV9M73s_.js → schema-B5lftDPf.js} +295 -195
  38. package/dist/schema-B5lftDPf.js.map +1 -0
  39. package/dist/{types-B7-_l_wE.d.ts → schema-C6ECceaN.d.ts} +272 -82
  40. package/dist/schema-C6ECceaN.d.ts.map +1 -0
  41. package/dist/src/ai/index.d.ts +269 -24
  42. package/dist/src/ai/index.d.ts.map +1 -1
  43. package/dist/src/ai/index.js +1028 -168
  44. package/dist/src/ai/index.js.map +1 -1
  45. package/dist/src/analytics/index.js +3 -3
  46. package/dist/src/graphql/client.d.ts +2 -2
  47. package/dist/src/graphql/client.js +1 -1
  48. package/dist/src/graphql-client/entry.d.ts +6 -4
  49. package/dist/src/graphql-client/entry.js +4 -4
  50. package/dist/src/relational/index.d.ts +8 -1
  51. package/dist/src/relational/index.d.ts.map +1 -1
  52. package/dist/src/relational/index.js +1 -1
  53. package/dist/src/renown/index.d.ts +2 -2
  54. package/dist/src/renown/index.js +3 -3
  55. package/dist/src/rpc/index.d.ts +201 -144
  56. package/dist/src/rpc/index.d.ts.map +1 -1
  57. package/dist/src/rpc/index.js +562 -634
  58. package/dist/src/rpc/index.js.map +1 -1
  59. package/dist/switchboard-directory-vH6qtkh-.js +435 -0
  60. package/dist/switchboard-directory-vH6qtkh-.js.map +1 -0
  61. package/dist/switchboards-D-_JBUbF.d.ts +75 -0
  62. package/dist/switchboards-D-_JBUbF.d.ts.map +1 -0
  63. package/dist/types-BWx6FPO4.d.ts +63 -0
  64. package/dist/types-BWx6FPO4.d.ts.map +1 -0
  65. package/package.json +19 -17
  66. package/dist/attachment-service-But1Xljo.d.ts.map +0 -1
  67. package/dist/client-BiJAJ9dW.js.map +0 -1
  68. package/dist/client-CngU4mtn.d.ts.map +0 -1
  69. package/dist/client-VV9M73s_.js.map +0 -1
  70. package/dist/dispatch-qRXS70fh.js.map +0 -1
  71. package/dist/document-model-modules-D6I-UUXq.js +0 -386
  72. package/dist/document-model-modules-D6I-UUXq.js.map +0 -1
  73. package/dist/document-operations-Bt-1-ThH.js.map +0 -1
  74. package/dist/global-fql2bmb0.d.ts +0 -438
  75. package/dist/global-fql2bmb0.d.ts.map +0 -1
  76. package/dist/index-BABMK8cO.d.ts.map +0 -1
  77. package/dist/inspector-proxy-DCowaeeH.d.ts +0 -264
  78. package/dist/inspector-proxy-DCowaeeH.d.ts.map +0 -1
  79. package/dist/make-ph-event-functions-FzpvQtj6.js +0 -53
  80. package/dist/make-ph-event-functions-FzpvQtj6.js.map +0 -1
  81. package/dist/relational-ChC_AWAK.js.map +0 -1
  82. package/dist/renown-C9pYZRqf.js.map +0 -1
  83. package/dist/renown-Def5iO8k.js +0 -97
  84. package/dist/renown-Def5iO8k.js.map +0 -1
  85. package/dist/switchboard-CFyD_5_e.js +0 -323
  86. package/dist/switchboard-CFyD_5_e.js.map +0 -1
  87. package/dist/types-B7-_l_wE.d.ts.map +0 -1
@@ -0,0 +1,25 @@
1
+ import { IInspector, IInspectorAdmin, IReactorDbQuery } from "@powerhousedao/reactor";
2
+ import { MessageRouter, WorkerInspectorInfo, WorkerMigrationState } from "@powerhousedao/reactor/rpc";
3
+ //#region src/rpc/admin-client.d.ts
4
+ interface IWorkerAdminClient {
5
+ info(): Promise<WorkerInspectorInfo>;
6
+ restart(): Promise<void>;
7
+ clearStorage(): Promise<void>;
8
+ migrate(): Promise<void>;
9
+ getMigrationState(): WorkerMigrationState;
10
+ subscribeMigration(callback: () => void): () => void;
11
+ }
12
+ /** Worker lifecycle channel (info/restart/clearStorage/migrate) over the shared router. */
13
+ declare function createWorkerAdminClient(router: MessageRouter): IWorkerAdminClient;
14
+ //#endregion
15
+ //#region src/rpc/inspector-proxy.d.ts
16
+ /** `queryReactorDb` is the published name of `queryDb`. */
17
+ interface IInspectorProxy extends IInspector, IInspectorAdmin, IReactorDbQuery {
18
+ queryReactorDb(sql: string, params?: unknown[]): Promise<unknown[]>;
19
+ }
20
+ /** Every row of `INSPECTOR_OPS`; the host decides which tiers it serves. */
21
+ declare function createInspectorProxy(router: MessageRouter): IInspectorProxy;
22
+ //#endregion
23
+ export { createWorkerAdminClient as i, createInspectorProxy as n, IWorkerAdminClient as r, IInspectorProxy as t };
24
+ export {};
25
+ //# sourceMappingURL=inspector-proxy-DODqs15F.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inspector-proxy-DODqs15F.d.ts","names":[],"sources":["../src/rpc/admin-client.ts","../src/rpc/inspector-proxy.ts"],"mappings":";;;UAQiB;EACf,QAAQ,QAAQ;EAChB,WAAW;EACX,gBAAgB;EAChB,WAAW;EACX,qBAAqB;EACrB,mBAAmB;;;iBAIL,wBACd,QAAQ,gBACP;;;;UCVc,wBACP,YAAY,iBAAiB;EACrC,eAAe,aAAa,qBAAqB;;;iBAInC,qBAAqB,QAAQ,gBAAgB"}
@@ -0,0 +1,180 @@
1
+ import { createContext, useContext, useSyncExternalStore } from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { capitalCase } from "change-case";
4
+ //#region src/hooks/ph-store.tsx
5
+ const ALL_KEYS = Symbol("all keys");
6
+ const listenersByStore = /* @__PURE__ */ new WeakMap();
7
+ const windowBound = /* @__PURE__ */ new WeakSet();
8
+ const subscribeCache = /* @__PURE__ */ new WeakMap();
9
+ function notifyKey(listeners, key) {
10
+ for (const set of [listeners.get(key), listeners.get(ALL_KEYS)]) for (const listener of set ?? []) listener();
11
+ if (windowBound.has(listeners) && typeof key === "string") window.dispatchEvent(new CustomEvent(`ph:${key}Updated`));
12
+ }
13
+ function createPHStore(initial = {}) {
14
+ const listeners = /* @__PURE__ */ new Map();
15
+ const store = new Proxy({ ...initial }, {
16
+ set: (target, key, value) => {
17
+ if (Reflect.get(target, key) === value) return true;
18
+ Reflect.set(target, key, value);
19
+ notifyKey(listeners, key);
20
+ return true;
21
+ },
22
+ deleteProperty: (target, key) => {
23
+ Reflect.deleteProperty(target, key);
24
+ notifyKey(listeners, key);
25
+ return true;
26
+ }
27
+ });
28
+ listenersByStore.set(store, listeners);
29
+ return store;
30
+ }
31
+ function listenersOf(store) {
32
+ const listeners = listenersByStore.get(store);
33
+ if (!listeners) throw new Error("Not a store made by createPHStore");
34
+ return listeners;
35
+ }
36
+ /** Subscribes to changes of `key`, or of every key when omitted. */
37
+ function subscribePHStore(store, listener, key = ALL_KEYS) {
38
+ return subscribeOwn(store, listener, key);
39
+ }
40
+ function subscribeOwn(store, listener, key) {
41
+ const listeners = listenersOf(store);
42
+ const set = listeners.get(key) ?? /* @__PURE__ */ new Set();
43
+ listeners.set(key, set);
44
+ set.add(listener);
45
+ return () => {
46
+ set.delete(listener);
47
+ };
48
+ }
49
+ /** Notifies `key`'s listeners without a change, as re-setting a value does. */
50
+ function notifyPHStore(store, key) {
51
+ notifyKey(listenersOf(store), key);
52
+ }
53
+ /** A subscribe for `key`, stable per store as useSyncExternalStore expects. */
54
+ function getPHStoreSubscribe(store, key) {
55
+ const cacheKey = key ?? ALL_KEYS;
56
+ const cache = subscribeCache.get(store) ?? /* @__PURE__ */ new Map();
57
+ subscribeCache.set(store, cache);
58
+ let subscribe = cache.get(cacheKey);
59
+ if (!subscribe) {
60
+ subscribe = (listener) => subscribePHStore(store, listener, cacheKey);
61
+ cache.set(cacheKey, subscribe);
62
+ }
63
+ return subscribe;
64
+ }
65
+ let activeStore;
66
+ /** The store bound with {@link bindPHStoreToWindow}, if any. */
67
+ function getActivePHStore() {
68
+ return activeStore;
69
+ }
70
+ /** The app's state outside React: the bound store, else `window.ph`. */
71
+ function getPHStore() {
72
+ if (activeStore) return activeStore;
73
+ return typeof window === "undefined" ? void 0 : window.ph;
74
+ }
75
+ /** The bound store; otherwise binds `window.ph` if it is a store, else a new
76
+ * store that takes over a plain `window.ph`'s values. */
77
+ function ensurePHStore() {
78
+ if (activeStore) return activeStore;
79
+ const current = typeof window === "undefined" ? void 0 : window.ph;
80
+ const store = current && listenersByStore.has(current) ? current : createPHStore();
81
+ bindPHStoreToWindow(store);
82
+ return store;
83
+ }
84
+ /** Makes `store` the app's state and `window.ph`; values set on a plain
85
+ * `window.ph` carry over where `store` has none. */
86
+ function bindPHStoreToWindow(store) {
87
+ activeStore = store;
88
+ if (typeof window === "undefined") return;
89
+ const previous = window.ph;
90
+ const previousListeners = previous && listenersByStore.get(previous);
91
+ if (previousListeners) windowBound.delete(previousListeners);
92
+ else if (previous) {
93
+ for (const [key, value] of Object.entries(previous)) if (!(key in store)) Reflect.set(store, key, value);
94
+ }
95
+ windowBound.add(listenersOf(store));
96
+ window.ph = store;
97
+ }
98
+ const PHStoreContext = createContext(void 0);
99
+ /** Hooks below read from `store`; without a provider they read `window.ph`. */
100
+ function PHStoreProvider(props) {
101
+ return /* @__PURE__ */ jsx(PHStoreContext.Provider, {
102
+ value: props.store,
103
+ children: props.children
104
+ });
105
+ }
106
+ function usePHStore() {
107
+ return useContext(PHStoreContext);
108
+ }
109
+ //#endregion
110
+ //#region src/hooks/make-ph-event-functions.ts
111
+ const isServer = typeof window === "undefined";
112
+ const updatedEventName = (key) => `ph:${key}Updated`;
113
+ /** Calls `onChange` whenever `key` is set: through the bound store, or the
114
+ * `ph:<key>Updated` event on pages that bound none. */
115
+ function subscribeToPHValue(key, onChange) {
116
+ if (isServer) return () => {};
117
+ const store = getActivePHStore();
118
+ if (store) return subscribePHStore(store, onChange, key);
119
+ const eventName = updatedEventName(key);
120
+ window.addEventListener(eventName, onChange);
121
+ return () => window.removeEventListener(eventName, onChange);
122
+ }
123
+ function makePHEventFunctions(key) {
124
+ const setEventName = `ph:set${capitalCase(key)}`;
125
+ const updateEventName = updatedEventName(key);
126
+ function setValue(value) {
127
+ if (isServer) return;
128
+ const store = getActivePHStore();
129
+ if (store) {
130
+ const unchanged = store[key] === value;
131
+ store[key] = value;
132
+ if (unchanged) notifyPHStore(store, key);
133
+ return;
134
+ }
135
+ const event = new CustomEvent(setEventName, { detail: { [key]: value } });
136
+ window.dispatchEvent(event);
137
+ }
138
+ function dispatchUpdatedEvent() {
139
+ if (isServer) return;
140
+ const event = new CustomEvent(updateEventName);
141
+ window.dispatchEvent(event);
142
+ }
143
+ function handleSetValueEvent(event) {
144
+ if (isServer) return;
145
+ if (getActivePHStore()) {
146
+ setValue(event.detail[key]);
147
+ return;
148
+ }
149
+ (window.ph ??= {})[key] = event.detail[key];
150
+ dispatchUpdatedEvent();
151
+ }
152
+ function addEventHandler() {
153
+ if (isServer) return;
154
+ window.addEventListener(setEventName, handleSetValueEvent);
155
+ }
156
+ function subscribeToValue(onStoreChange) {
157
+ return subscribeToPHValue(key, onStoreChange);
158
+ }
159
+ function getSnapshot() {
160
+ if (isServer) return;
161
+ return getPHStore()?.[key];
162
+ }
163
+ function getServerSnapshot() {}
164
+ function useValue() {
165
+ const store = usePHStore();
166
+ const readStore = () => store?.[key];
167
+ return useSyncExternalStore(store ? getPHStoreSubscribe(store, key) : subscribeToValue, store ? readStore : getSnapshot, store ? readStore : getServerSnapshot);
168
+ }
169
+ return {
170
+ useValue,
171
+ setValue,
172
+ addEventHandler,
173
+ subscribeToValue,
174
+ getSnapshot
175
+ };
176
+ }
177
+ //#endregion
178
+ export { createPHStore as a, getPHStore as c, subscribePHStore as d, usePHStore as f, bindPHStoreToWindow as i, getPHStoreSubscribe as l, subscribeToPHValue as n, ensurePHStore as o, PHStoreProvider as r, getActivePHStore as s, makePHEventFunctions as t, notifyPHStore as u };
179
+
180
+ //# sourceMappingURL=make-ph-event-functions-B5GU5xcR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"make-ph-event-functions-B5GU5xcR.js","names":[],"sources":["../src/hooks/ph-store.tsx","../src/hooks/make-ph-event-functions.ts"],"sourcesContent":["import type { PHGlobal, PHGlobalKey } from \"@powerhousedao/reactor-browser\";\nimport type { ReactNode } from \"react\";\nimport { createContext, useContext } from \"react\";\n\n/** PH state of one app (or one server request); assigning a key notifies. */\nexport type PHStore = PHGlobal;\n\ntype Listeners = Map<PropertyKey, Set<() => void>>;\n\n// Listeners per key; ALL_KEYS hears every change.\nconst ALL_KEYS = Symbol(\"all keys\");\nconst listenersByStore = new WeakMap<PHStore, Listeners>();\n// Stores bound to window.ph; their changes also fire `ph:<key>Updated`.\nconst windowBound = new WeakSet<Listeners>();\nconst subscribeCache = new WeakMap<\n PHStore,\n Map<PropertyKey, (listener: () => void) => () => void>\n>();\n\nfunction notifyKey(listeners: Listeners, key: PropertyKey) {\n for (const set of [listeners.get(key), listeners.get(ALL_KEYS)]) {\n for (const listener of set ?? []) listener();\n }\n // Another bundled copy of reactor-browser subscribes through window events.\n if (windowBound.has(listeners) && typeof key === \"string\") {\n window.dispatchEvent(new CustomEvent(`ph:${key}Updated`));\n }\n}\n\nexport function createPHStore(initial: PHGlobal = {}): PHStore {\n const listeners: Listeners = new Map();\n const store = new Proxy<PHGlobal>(\n { ...initial },\n {\n set: (target, key, value) => {\n if (Reflect.get(target, key) === value) return true;\n Reflect.set(target, key, value);\n notifyKey(listeners, key);\n return true;\n },\n deleteProperty: (target, key) => {\n Reflect.deleteProperty(target, key);\n notifyKey(listeners, key);\n return true;\n },\n },\n );\n listenersByStore.set(store, listeners);\n return store;\n}\n\nfunction listenersOf(store: PHStore) {\n const listeners = listenersByStore.get(store);\n if (!listeners) throw new Error(\"Not a store made by createPHStore\");\n return listeners;\n}\n\n/** Subscribes to changes of `key`, or of every key when omitted. */\nexport function subscribePHStore(\n store: PHStore,\n listener: () => void,\n key: PHGlobalKey | typeof ALL_KEYS = ALL_KEYS,\n): () => void {\n return subscribeOwn(store, listener, key);\n}\n\nfunction subscribeOwn(store: PHStore, listener: () => void, key: PropertyKey) {\n const listeners = listenersOf(store);\n const set = listeners.get(key) ?? new Set();\n listeners.set(key, set);\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n}\n\n/** Notifies `key`'s listeners without a change, as re-setting a value does. */\nexport function notifyPHStore(store: PHStore, key: PHGlobalKey) {\n notifyKey(listenersOf(store), key);\n}\n\n/** A subscribe for `key`, stable per store as useSyncExternalStore expects. */\nexport function getPHStoreSubscribe(store: PHStore, key?: PHGlobalKey) {\n const cacheKey = key ?? ALL_KEYS;\n const cache =\n subscribeCache.get(store) ??\n new Map<PropertyKey, (listener: () => void) => () => void>();\n subscribeCache.set(store, cache);\n let subscribe = cache.get(cacheKey);\n if (!subscribe) {\n subscribe = (listener: () => void) =>\n subscribePHStore(store, listener, cacheKey);\n cache.set(cacheKey, subscribe);\n }\n return subscribe;\n}\n\nlet activeStore: PHStore | undefined;\n\n/** The store bound with {@link bindPHStoreToWindow}, if any. */\nexport function getActivePHStore() {\n return activeStore;\n}\n\n/** The app's state outside React: the bound store, else `window.ph`. */\nexport function getPHStore(): PHStore | undefined {\n if (activeStore) return activeStore;\n return typeof window === \"undefined\" ? undefined : window.ph;\n}\n\n/** The bound store; otherwise binds `window.ph` if it is a store, else a new\n * store that takes over a plain `window.ph`'s values. */\nexport function ensurePHStore(): PHStore {\n if (activeStore) return activeStore;\n const current = typeof window === \"undefined\" ? undefined : window.ph;\n const store =\n current && listenersByStore.has(current) ? current : createPHStore();\n bindPHStoreToWindow(store);\n return store;\n}\n\n/** Makes `store` the app's state and `window.ph`; values set on a plain\n * `window.ph` carry over where `store` has none. */\nexport function bindPHStoreToWindow(store: PHStore) {\n activeStore = store;\n if (typeof window === \"undefined\") return;\n const previous = window.ph;\n const previousListeners = previous && listenersByStore.get(previous);\n // A previously bound store is replaced, not merged.\n if (previousListeners) windowBound.delete(previousListeners);\n else if (previous) {\n for (const [key, value] of Object.entries(previous)) {\n if (!(key in store)) Reflect.set(store, key, value);\n }\n }\n windowBound.add(listenersOf(store));\n window.ph = store;\n}\n\nconst PHStoreContext = createContext<PHStore | undefined>(undefined);\n\n/** Hooks below read from `store`; without a provider they read `window.ph`. */\nexport function PHStoreProvider(props: {\n store: PHStore;\n children: ReactNode;\n}) {\n return (\n <PHStoreContext.Provider value={props.store}>\n {props.children}\n </PHStoreContext.Provider>\n );\n}\n\nexport function usePHStore() {\n return useContext(PHStoreContext);\n}\n","import type {\n PHGlobal,\n PHGlobalKey,\n SetEvent,\n} from \"@powerhousedao/reactor-browser\";\nimport { capitalCase } from \"change-case\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n getActivePHStore,\n getPHStore,\n getPHStoreSubscribe,\n notifyPHStore,\n subscribePHStore,\n usePHStore,\n} from \"./ph-store.js\";\n\n// guard condition for server side rendering\nconst isServer = typeof window === \"undefined\";\n\nconst updatedEventName = (key: PHGlobalKey) => `ph:${key}Updated`;\n\n/** Calls `onChange` whenever `key` is set: through the bound store, or the\n * `ph:<key>Updated` event on pages that bound none. */\nexport function subscribeToPHValue(key: PHGlobalKey, onChange: () => void) {\n if (isServer) return () => {};\n const store = getActivePHStore();\n if (store) return subscribePHStore(store, onChange, key);\n const eventName = updatedEventName(key);\n window.addEventListener(eventName, onChange);\n return () => window.removeEventListener(eventName, onChange);\n}\n\nexport function makePHEventFunctions<TKey extends PHGlobalKey>(key: TKey) {\n const setEventName = `ph:set${capitalCase(key)}` as const;\n const updateEventName = updatedEventName(key);\n\n function setValue(value: PHGlobal[TKey] | undefined) {\n if (isServer) {\n return;\n }\n const store = getActivePHStore();\n if (store) {\n const unchanged = store[key] === value;\n store[key] = value;\n // Re-setting a value still notifies, as the event path always has.\n if (unchanged) notifyPHStore(store, key);\n return;\n }\n const event = new CustomEvent(setEventName, {\n detail: { [key]: value },\n });\n window.dispatchEvent(event);\n }\n\n function dispatchUpdatedEvent() {\n if (isServer) {\n return;\n }\n const event = new CustomEvent(updateEventName);\n window.dispatchEvent(event);\n }\n\n function handleSetValueEvent(event: SetEvent<TKey>) {\n if (isServer) {\n return;\n }\n if (getActivePHStore()) {\n setValue(event.detail[key]);\n return;\n }\n // No bound store: the page keeps a plain `window.ph`.\n (window.ph ??= {})[key] = event.detail[key];\n dispatchUpdatedEvent();\n }\n\n // Only pages without a bound store need it; `ph:set*` events still apply.\n function addEventHandler() {\n if (isServer) {\n return;\n }\n window.addEventListener(setEventName, handleSetValueEvent as EventListener);\n }\n\n function subscribeToValue(onStoreChange: () => void) {\n return subscribeToPHValue(key, onStoreChange);\n }\n\n function getSnapshot() {\n if (isServer) {\n return undefined;\n }\n // Read before the first setValue is expected: subscribers mount before init.\n return getPHStore()?.[key];\n }\n\n function getServerSnapshot() {\n return undefined;\n }\n\n function useValue() {\n const store = usePHStore();\n const readStore = () => store?.[key];\n return useSyncExternalStore(\n store ? getPHStoreSubscribe(store, key) : subscribeToValue,\n store ? readStore : getSnapshot,\n store ? readStore : getServerSnapshot,\n );\n }\n\n return {\n useValue,\n setValue,\n addEventHandler,\n // Non-React access, e.g. Connect's boot wiring of the reactor worker.\n subscribeToValue,\n getSnapshot,\n };\n}\n"],"mappings":";;;;AAUA,MAAM,WAAW,OAAO,UAAU;AAClC,MAAM,mCAAmB,IAAI,QAA4B;AAEzD,MAAM,8BAAc,IAAI,QAAmB;AAC3C,MAAM,iCAAiB,IAAI,QAGzB;AAEF,SAAS,UAAU,WAAsB,KAAkB;CACzD,KAAK,MAAM,OAAO,CAAC,UAAU,IAAI,GAAG,GAAG,UAAU,IAAI,QAAQ,CAAC,GAC5D,KAAK,MAAM,YAAY,OAAO,CAAC,GAAG,SAAS;CAG7C,IAAI,YAAY,IAAI,SAAS,KAAK,OAAO,QAAQ,UAC/C,OAAO,cAAc,IAAI,YAAY,MAAM,IAAI,QAAQ,CAAC;AAE5D;AAEA,SAAgB,cAAc,UAAoB,CAAC,GAAY;CAC7D,MAAM,4BAAuB,IAAI,IAAI;CACrC,M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ationalDb } from "@powerhousedao/reactor";
2
1
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { HardenedPGliteDialect, createRelationalDb } from "@powerhousedao/reactor";
3
3
  import { Kysely } from "kysely";
4
4
  import { PGliteDialect } from "kysely-pglite-dialect";
5
5
  import deepEqual from "lodash.isequal";
@@ -32,16 +32,71 @@ function setPGliteDB(pglite) {
32
32
  window.dispatchEvent(new CustomEvent(PGLITE_UPDATE_EVENT));
33
33
  }
34
34
  //#endregion
35
+ //#region src/relational/utils/relational-dialect.ts
36
+ /** A query-only proxy (Connect's worker RPC) has no session here to harden; its worker does that. */
37
+ function relationalDialect(instance, options = {}) {
38
+ const session = instance;
39
+ if (typeof session.exec === "function" && typeof session.isInTransaction === "function") return new HardenedPGliteDialect(session, options);
40
+ return new PGliteDialect(instance);
41
+ }
42
+ const sharedByInstance = /* @__PURE__ */ new WeakMap();
43
+ function sharedFor(instance, options = {}) {
44
+ let shared = sharedByInstance.get(instance);
45
+ if (shared === void 0) {
46
+ const listeners = /* @__PURE__ */ new Set();
47
+ const created = {
48
+ listeners,
49
+ kysely: new Kysely({ dialect: relationalDialect(instance, {
50
+ ...options,
51
+ onPoisoned: (cause) => {
52
+ created.poisoned = cause;
53
+ for (const listener of [...listeners]) try {
54
+ listener(cause);
55
+ } catch (error) {
56
+ console.error("relational onPoisoned listener threw", error);
57
+ }
58
+ }
59
+ }) })
60
+ };
61
+ shared = created;
62
+ sharedByInstance.set(instance, shared);
63
+ }
64
+ return shared;
65
+ }
66
+ /** One Kysely, so one queue, per PGlite; `options` apply from the first caller, which creates it. */
67
+ function relationalKysely(instance, options = {}) {
68
+ return sharedFor(instance, options).kysely;
69
+ }
70
+ /**
71
+ * Tells `listener` once the shared session of `instance` is poisoned, however
72
+ * many consumers share it and whichever opened it first; a late subscriber is
73
+ * told at once. Returns the unsubscribe.
74
+ */
75
+ function subscribeRelationalPoisoned(instance, listener) {
76
+ const shared = sharedFor(instance);
77
+ if (shared.poisoned !== void 0) {
78
+ listener(shared.poisoned);
79
+ return () => void 0;
80
+ }
81
+ shared.listeners.add(listener);
82
+ return () => {
83
+ shared.listeners.delete(listener);
84
+ };
85
+ }
86
+ //#endregion
35
87
  //#region src/relational/hooks/useRelationalDb.ts
36
88
  function createRelationalDbWithLive(pgliteInstance) {
37
- const baseDb = new Kysely({ dialect: new PGliteDialect(pgliteInstance) });
89
+ const baseDb = relationalKysely(pgliteInstance);
38
90
  const relationalDBWithLive = createRelationalDb(baseDb);
39
91
  relationalDBWithLive.live = pgliteInstance.live;
40
92
  return relationalDBWithLive;
41
93
  }
42
- const useRelationalDb = () => {
94
+ const useRelationalDb = (options = {}) => {
43
95
  const pglite = usePGliteDB();
44
- return useMemo(() => {
96
+ const onPoisoned = useRef(options.onPoisoned);
97
+ onPoisoned.current = options.onPoisoned;
98
+ const wantsPoisoned = options.onPoisoned !== void 0;
99
+ const relationalDb = useMemo(() => {
45
100
  if (!pglite.db || pglite.isLoading || pglite.error) return {
46
101
  db: null,
47
102
  isLoading: pglite.isLoading,
@@ -53,6 +108,11 @@ const useRelationalDb = () => {
53
108
  error: null
54
109
  };
55
110
  }, [pglite]);
111
+ useEffect(() => {
112
+ if (!pglite.db || !wantsPoisoned) return;
113
+ return subscribeRelationalPoisoned(pglite.db, (cause) => onPoisoned.current?.(cause));
114
+ }, [pglite.db, wantsPoisoned]);
115
+ return relationalDb;
56
116
  };
57
117
  //#endregion
58
118
  //#region src/relational/hooks/useRelationalQuery.ts
@@ -133,4 +193,4 @@ function createProcessorQuery(ProcessorClass) {
133
193
  //#endregion
134
194
  export { setPGliteDB as i, useRelationalQuery as n, useRelationalDb as r, createProcessorQuery as t };
135
195
 
136
- //# sourceMappingURL=relational-ChC_AWAK.js.map
196
+ //# sourceMappingURL=relational-DZuyKp2y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relational-DZuyKp2y.js","names":[],"sources":["../src/pglite/usePGlite.ts","../src/relational/utils/relational-dialect.ts","../src/relational/hooks/useRelationalDb.ts","../src/relational/hooks/useRelationalQuery.ts","../src/relational/utils/createProcessorQuery.ts"],"sourcesContent":["import type { PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport { useEffect, useState } from \"react\";\n\nexport const PGLITE_UPDATE_EVENT = \"ph:pglite-update\";\n\nexport interface PGliteState {\n db: PGliteWithLive | null;\n isLoading: boolean;\n error: Error | null;\n}\n\nconst defaultPGliteState: PGliteState = {\n db: null,\n isLoading: true,\n error: null,\n};\n\nexport const usePGliteDB = () => {\n const [state, setState] = useState<PGliteState>(\n () => window.powerhouse?.pglite ?? defaultPGliteState,\n );\n\n useEffect(() => {\n const handlePgliteUpdate = () =>\n setState(window.powerhouse?.pglite ?? defaultPGliteState);\n\n window.addEventListener(PGLITE_UPDATE_EVENT, handlePgliteUpdate);\n\n return () =>\n window.removeEventListener(PGLITE_UPDATE_EVENT, handlePgliteUpdate);\n }, []);\n\n return state;\n};\n\nexport function setPGliteDB(pglite: Partial<PGliteState>): void {\n const currentPowerhouse = window.powerhouse ?? {};\n const currentPGliteState = window.powerhouse?.pglite ?? defaultPGliteState;\n\n window.powerhouse = {\n ...currentPowerhouse,\n pglite: {\n ...currentPGliteState,\n ...pglite,\n },\n };\n window.dispatchEvent(new CustomEvent(PGLITE_UPDATE_EVENT));\n}\n\nexport const useSetPGliteDB = () => setPGliteDB;\n\nexport const usePGlite = () => {\n const pglite = usePGliteDB();\n const setPGlite = useSetPGliteDB();\n\n return [pglite, setPGlite];\n};\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport {\n HardenedPGliteDialect,\n type HardenedPGliteDialectOptions,\n type PGliteSession,\n} from \"@powerhousedao/reactor\";\nimport { Kysely, type Dialect } from \"kysely\";\nimport { PGliteDialect } from \"kysely-pglite-dialect\";\n\n/** A query-only proxy (Connect's worker RPC) has no session here to harden; its worker does that. */\nexport function relationalDialect(\n instance: unknown,\n options: Partial<HardenedPGliteDialectOptions> = {},\n): Dialect {\n const session = instance as Partial<PGliteSession>;\n if (\n typeof session.exec === \"function\" &&\n typeof session.isInTransaction === \"function\"\n ) {\n return new HardenedPGliteDialect(session as PGliteSession, options);\n }\n return new PGliteDialect(instance as PGlite);\n}\n\ntype PoisonListener = (cause: Error) => void;\n\ntype SharedRelationalDb = {\n kysely: Kysely<unknown>;\n listeners: Set<PoisonListener>;\n poisoned?: Error;\n};\n\nconst sharedByInstance = new WeakMap<object, SharedRelationalDb>();\n\nfunction sharedFor(\n instance: object,\n options: Partial<Omit<HardenedPGliteDialectOptions, \"onPoisoned\">> = {},\n): SharedRelationalDb {\n let shared = sharedByInstance.get(instance);\n if (shared === undefined) {\n const listeners = new Set<PoisonListener>();\n const created: SharedRelationalDb = {\n listeners,\n kysely: new Kysely<unknown>({\n dialect: relationalDialect(instance, {\n ...options,\n onPoisoned: (cause) => {\n created.poisoned = cause;\n for (const listener of [...listeners]) {\n try {\n listener(cause);\n } catch (error) {\n console.error(\"relational onPoisoned listener threw\", error);\n }\n }\n },\n }),\n }),\n };\n shared = created;\n sharedByInstance.set(instance, shared);\n }\n return shared;\n}\n\n/** One Kysely, so one queue, per PGlite; `options` apply from the first caller, which creates it. */\nexport function relationalKysely<Schema>(\n instance: object,\n options: Partial<Omit<HardenedPGliteDialectOptions, \"onPoisoned\">> = {},\n): Kysely<Schema> {\n return sharedFor(instance, options).kysely as Kysely<Schema>;\n}\n\n/**\n * Tells `listener` once the shared session of `instance` is poisoned, however\n * many consumers share it and whichever opened it first; a late subscriber is\n * told at once. Returns the unsubscribe.\n */\nexport function subscribeRelationalPoisoned(\n instance: object,\n listener: PoisonListener,\n): () => void {\n const shared = sharedFor(instance);\n if (shared.poisoned !== undefined) {\n listener(shared.poisoned);\n return () => undefined;\n }\n shared.listeners.add(listener);\n return () => {\n shared.listeners.delete(listener);\n };\n}\n","import type { LiveNamespace, PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport { createRelationalDb } from \"@powerhousedao/reactor\";\nimport type { IRelationalDb as IRelationalDbCore } from \"@powerhousedao/shared/processors\";\nimport { useEffect, useMemo, useRef } from \"react\";\nimport { usePGliteDB } from \"../../pglite/usePGlite.js\";\nimport {\n relationalKysely,\n subscribeRelationalPoisoned,\n} from \"../utils/relational-dialect.js\";\n\n// Type for Relational DB instance enhanced with live capabilities\nexport type RelationalDbWithLive<Schema> = IRelationalDbCore<Schema> & {\n live: LiveNamespace;\n};\n\ninterface IRelationalDbState<Schema> {\n db: RelationalDbWithLive<Schema> | null;\n isLoading: boolean;\n error: Error | null;\n}\n\n// Custom initializer that creates enhanced Kysely instance with live capabilities\nfunction createRelationalDbWithLive<Schema>(\n pgliteInstance: PGliteWithLive,\n): RelationalDbWithLive<Schema> {\n const baseDb = relationalKysely<Schema>(pgliteInstance);\n const relationalDb = createRelationalDb(baseDb);\n\n // Inject the live namespace with proper typing\n const relationalDBWithLive =\n relationalDb as unknown as RelationalDbWithLive<Schema>;\n relationalDBWithLive.live = pgliteInstance.live;\n\n return relationalDBWithLive;\n}\n\nexport type RelationalDbOptions = {\n /**\n * Called once if the shared PGlite session becomes unusable; every hook that\n * passes one is told, and it unsubscribes on unmount. Recovery is the caller's.\n */\n onPoisoned?: (cause: Error) => void;\n};\n\nexport const useRelationalDb = <Schema>(\n options: RelationalDbOptions = {},\n): IRelationalDbState<Schema> => {\n const pglite = usePGliteDB();\n const onPoisoned = useRef(options.onPoisoned);\n onPoisoned.current = options.onPoisoned;\n const wantsPoisoned = options.onPoisoned !== undefined;\n\n const relationalDb = useMemo<IRelationalDbState<Schema>>(() => {\n if (!pglite.db || pglite.isLoading || pglite.error) {\n return {\n db: null,\n isLoading: pglite.isLoading,\n error: pglite.error,\n };\n }\n\n const db = createRelationalDbWithLive<Schema>(pglite.db);\n\n return {\n db,\n isLoading: false,\n error: null,\n };\n }, [pglite]);\n\n useEffect(() => {\n if (!pglite.db || !wantsPoisoned) return;\n return subscribeRelationalPoisoned(pglite.db, (cause) =>\n onPoisoned.current?.(cause),\n );\n }, [pglite.db, wantsPoisoned]);\n\n return relationalDb;\n};\n","import type { LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport type {\n IRelationalQueryBuilder,\n RelationalDbProcessorClass,\n} from \"@powerhousedao/shared/processors\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useRelationalDb } from \"./useRelationalDb.js\";\n\nexport type QueryCallbackReturnType = {\n sql: string;\n parameters?: readonly unknown[];\n};\n\nexport type useRelationalQueryOptions = {\n // Whether to hash the namespace to avoid namespace size limit. True by default\n hashNamespace?: boolean;\n};\n\nconst MAX_RETRIES = 5;\nconst RETRY_DELAY = 200;\n\nconst isRelationNotExistError = (error: unknown): boolean => {\n const errorMessage =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : String(error);\n\n return (\n errorMessage.toLowerCase().includes(\"relation\") &&\n errorMessage.toLowerCase().includes(\"does not exist\")\n );\n};\n\ntype LiveQueryType = {\n unsubscribe: () => void;\n};\n\nexport function useRelationalQuery<Schema, T = unknown, TParams = undefined>(\n ProcessorClass: RelationalDbProcessorClass<Schema>,\n driveId: string,\n queryCallback: (\n db: IRelationalQueryBuilder<Schema>,\n parameters?: TParams,\n ) => QueryCallbackReturnType,\n parameters?: TParams,\n _options?: useRelationalQueryOptions,\n) {\n const [result, setResult] = useState<LiveQueryResults<T> | null>(null);\n const [queryLoading, setQueryLoading] = useState(true);\n const [error, setError] = useState<Error | undefined>(undefined);\n const retryCount = useRef(0);\n const retryTimeoutRef = useRef<NodeJS.Timeout>(null);\n\n const relationalDb = useRelationalDb<Schema>();\n\n const executeLiveQuery = async (\n sql: string,\n queryParameters: readonly unknown[] | undefined,\n retryAttempt = 0,\n ): Promise<LiveQueryType | null> => {\n if (!relationalDb.db) {\n return null;\n }\n\n try {\n const live = await relationalDb.db.live.query<T>(\n sql,\n queryParameters ? [...queryParameters] : [],\n (result) => {\n setResult(result);\n setQueryLoading(false);\n retryCount.current = 0; // Reset retry count on success\n },\n );\n\n return live as LiveQueryType;\n } catch (err: unknown) {\n if (isRelationNotExistError(err) && retryAttempt < MAX_RETRIES) {\n return new Promise((resolve) => {\n retryTimeoutRef.current = setTimeout(() => {\n resolve(executeLiveQuery(sql, queryParameters, retryAttempt + 1));\n }, RETRY_DELAY);\n });\n }\n\n setQueryLoading(false);\n setError(err instanceof Error ? err : new Error(String(err)));\n return null;\n }\n };\n\n useEffect(() => {\n setError(undefined);\n setQueryLoading(true);\n retryCount.current = 0;\n\n if (!relationalDb.db) {\n return;\n }\n\n // Use the processor helper to obtain a typed namespaced query builder\n const db = ProcessorClass.query(driveId, relationalDb.db);\n\n const compiledQuery = queryCallback(db, parameters);\n const { sql, parameters: queryParameters } = compiledQuery;\n\n const liveQueryPromise = executeLiveQuery(sql, queryParameters);\n\n return () => {\n if (retryTimeoutRef.current) {\n clearTimeout(retryTimeoutRef.current);\n }\n void liveQueryPromise.then((live) => {\n if (live?.unsubscribe) {\n live.unsubscribe();\n }\n });\n };\n }, [relationalDb.db, ProcessorClass, driveId, queryCallback, parameters]);\n\n return {\n isLoading: relationalDb.isLoading || queryLoading,\n error: error || relationalDb.error,\n result,\n } as const;\n}\n","import type { LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport type {\n QueryCallbackReturnType,\n useRelationalQueryOptions,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n IRelationalQueryBuilder,\n RelationalDbProcessorClass,\n} from \"@powerhousedao/shared/processors\";\nimport type { CompiledQuery } from \"kysely\";\nimport deepEqual from \"lodash.isequal\";\nimport { useCallback, useMemo, useRef } from \"react\";\nimport { useRelationalQuery } from \"../hooks/useRelationalQuery.js\";\n\n// Custom hook for parameter memoization\nfunction useStableParams<T>(params: T): T {\n const prevParamsRef = useRef<T>(null);\n\n return useMemo(() => {\n if (!deepEqual(prevParamsRef.current, params)) {\n prevParamsRef.current = params;\n }\n return prevParamsRef.current as T;\n }, [params]);\n}\n\nexport function createProcessorQuery<TSchema>(\n ProcessorClass: RelationalDbProcessorClass<TSchema>,\n) {\n // Overload for queries without parameters\n function useQuery<\n TQueryBuilder extends (\n db: IRelationalQueryBuilder<TSchema>,\n ) => QueryCallbackReturnType,\n >(\n driveId: string,\n queryCallback: TQueryBuilder,\n ): {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any\n > | null;\n };\n\n // Overload for queries with parameters\n function useQuery<\n TParams,\n TQueryBuilder extends (\n db: IRelationalQueryBuilder<TSchema>,\n parameters: TParams,\n ) => QueryCallbackReturnType,\n >(\n driveId: string,\n queryCallback: TQueryBuilder,\n parameters: TParams,\n options?: useRelationalQueryOptions,\n ): {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any\n > | null;\n };\n\n function useQuery<\n TParams,\n TQueryBuilder extends (\n db: IRelationalQueryBuilder<TSchema>,\n parameters?: TParams,\n ) => QueryCallbackReturnType,\n >(\n driveId: string,\n queryCallback: TQueryBuilder,\n parameters?: TParams,\n options?: useRelationalQueryOptions,\n ): {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any\n > | null;\n } {\n type InferredResult =\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any;\n\n // Automatically memoize parameters using deep comparison\n const stableParams = useStableParams(parameters);\n\n // Memoize the callback to prevent infinite loops, updating when parameters change\n const memoizedCallback = useCallback(queryCallback, [stableParams]);\n\n return useRelationalQuery<TSchema, InferredResult, TParams>(\n ProcessorClass,\n driveId,\n memoizedCallback,\n stableParams,\n options,\n ) as {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<InferredResult> | null;\n };\n }\n\n return useQuery;\n}\n"],"mappings":";;;;;;AAGA,MAAa,sBAAsB;AAQnC,MAAM,qBAAkC;CACtC,IAAI;CACJ,WAAW;CACX,OAAO;AACT;AAEA,MAAa,oBAAoB;CAC/B,MAAM,CAAC,OAAO,YAAY,eAClB,OAAO,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;CACF,GAAG;EAAC,aAAa;EAAI;EAAgB;EAAS;EAAe;CAAU,CAAC;CAExE,OAAO;EACL,WAAW,aAAa,aAAa;EACrC,OAAO,SAAS,aAAa;EAC7B;CACF;AACF;;;AChHA,SAAS,gBAAmB,QAAc;CACxC,MAAM,gBAAgB,OAAU,IAAI;CAEpC,OAAO,cAAc;EACnB,IAAI,CAAC,UAAU,cAAc,SAAS,MAAM,GAC1C,cAAc,UAAU;EAE1B,OAAO,cAAc;CACvB,GAAG,CAAC,MAAM,CAAC;AACb;AAEA,SAAgB,qBACd,gBACA;CAqCA,SAAS,SAOP,SACA,eACA,YACA,SAOA;EAKA,MAAM,eAAe,gBAAgB,UAAU;EAK/C,OAAO,mBACL,gBACA,SAJuB,YAAY,eAAe,CAAC,YAAY,CAK/D,GACA,cACA,OACF;CAKF;CAEA,OAAO;AACT"}
@@ -1,8 +1,9 @@
1
- import { a as useRenown, c as RENOWN_INITIAL_UNKNOWN, i as useLoginStatus, l as RenownInitialUserProvider, n as setRenown, o as useUser, s as RENOWN_INITIAL_ANONYMOUS, t as addRenownEventHandler, u as useRenownInitialAuth } from "./renown-Def5iO8k.js";
2
- import { logger } from "document-model";
1
+ import { c as getPHStore } from "./make-ph-event-functions-B5GU5xcR.js";
2
+ import { R as setSearchParams, a as useRenown, c as RENOWN_INITIAL_UNKNOWN, i as useLoginStatus, l as RenownInitialUserProvider, n as setRenown, o as useUser, s as RENOWN_INITIAL_ANONYMOUS, t as addRenownEventHandler, u as useRenownInitialAuth, w as getPHNavigation } from "./renown-CBoTdGrg.js";
3
3
  import { Children, cloneElement, createContext, forwardRef, isValidElement, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
- import { BrowserKeyStorage, CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, DOMAIN_TYPE, ISSUER_TYPE, MissingSwitchboardError, RenownBuilder, RenownCryptoBuilder, VERIFIABLE_CREDENTIAL_EIP712_TYPE, readPersistedUser } from "@renown/sdk";
5
+ import { logger } from "document-model";
6
+ import { BrowserKeyStorage, CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, DOMAIN_TYPE, ISSUER_TYPE, MissingSwitchboardError, RenownBuilder, RenownCryptoBuilder, VERIFIABLE_CREDENTIAL_EIP712_TYPE, consoleLogin, createDelegation, decodeDelegation, readPersistedUser } from "@renown/sdk";
6
7
  import { LoginMethod, isWalletRedirectReturn, resolveAdapters } from "@renown/sdk/wallet";
7
8
  //#region src/renown/wallet-registry.ts
8
9
  let activeWalletController;
@@ -113,15 +114,41 @@ const RENOWN_RETURN_URL_STRIPPED_PARAMS = [
113
114
  ];
114
115
  //#endregion
115
116
  //#region src/renown/session.ts
117
+ /** The shell around this window, when it offers one. */
118
+ function desktopShell() {
119
+ if (typeof window === "undefined") return void 0;
120
+ return window.phDesktop;
121
+ }
122
+ async function signInThroughShell(renown, renownUrl, shell) {
123
+ try {
124
+ await consoleLogin(renown, {
125
+ renownUrl,
126
+ open: (url) => shell.openExternal(url),
127
+ onOpenFailed: (url) => {
128
+ logger.error("Could not open the sign-in page: @url", url);
129
+ }
130
+ });
131
+ notifyReactorClientCredentialsChanged();
132
+ } catch (error) {
133
+ logger.error(error instanceof Error ? error.message : String(error));
134
+ }
135
+ }
116
136
  function openRenown(documentId) {
117
- const renown = window.ph?.renown;
137
+ const renown = getPHStore()?.renown;
118
138
  let renownUrl = renown?.baseUrl;
119
139
  if (!renownUrl) {
120
140
  logger.warn("Renown instance not found, falling back to: @url", RENOWN_URL);
121
141
  renownUrl = RENOWN_URL;
122
142
  }
143
+ const shell = desktopShell();
123
144
  if (documentId) {
124
- window.open(`${renownUrl}/profile/${documentId}`, "_blank")?.focus();
145
+ const profile = `${renownUrl}/profile/${documentId}`;
146
+ if (shell) shell.openExternal(profile);
147
+ else window.open(profile, "_blank")?.focus();
148
+ return;
149
+ }
150
+ if (shell && renown) {
151
+ signInThroughShell(renown, renownUrl, shell);
125
152
  return;
126
153
  }
127
154
  const url = new URL(renownUrl);
@@ -135,7 +162,7 @@ function openRenown(documentId) {
135
162
  window.open(url, "_self")?.focus();
136
163
  }
137
164
  async function signIn(session) {
138
- const renown = window.ph?.renown;
165
+ const renown = getPHStore()?.renown;
139
166
  if (!renown) {
140
167
  logger.warn("Renown instance not found, cannot sign in");
141
168
  return;
@@ -150,7 +177,7 @@ let inFlightSignIn;
150
177
  let inFlightAddress;
151
178
  let lastSignedAddress;
152
179
  function notifyReactorClientCredentialsChanged() {
153
- (window.ph?.reactorClient)?.notifyCredentialsChanged?.();
180
+ (getPHStore()?.reactorClient)?.notifyCredentialsChanged?.();
154
181
  }
155
182
  async function completeSignIn(session) {
156
183
  const { address } = session;
@@ -179,21 +206,27 @@ function resetSignInGuard() {
179
206
  }
180
207
  function hasRedirectSignIn() {
181
208
  if (typeof window === "undefined") return false;
182
- return new URLSearchParams(window.location.search).has("user");
209
+ return new URLSearchParams(getPHNavigation().location().search).has("user");
210
+ }
211
+ function readDidFromUrl() {
212
+ if (typeof window === "undefined") return;
213
+ const { search } = getPHNavigation().location();
214
+ const userParam = new URLSearchParams(search).get("user");
215
+ return userParam ? decodeURIComponent(userParam) : void 0;
183
216
  }
184
- function consumeDidFromUrl() {
217
+ function clearUserParamFromUrl() {
185
218
  if (typeof window === "undefined") return;
186
- const userParam = new URLSearchParams(window.location.search).get("user");
187
- if (!userParam) return;
188
- const userDid = decodeURIComponent(userParam);
189
- const cleanUrl = new URL(window.location.href);
190
- cleanUrl.searchParams.delete("user");
191
- window.history.replaceState({}, "", cleanUrl.toString());
192
- return userDid;
219
+ const { search } = getPHNavigation().location();
220
+ if (!new URLSearchParams(search).has("user")) return;
221
+ setSearchParams((prev) => ({
222
+ ...prev,
223
+ user: void 0
224
+ }), { replace: true });
193
225
  }
194
226
  async function login(userDid, renown) {
195
227
  if (!renown) return;
196
- const did = userDid ?? consumeDidFromUrl();
228
+ const urlDid = readDidFromUrl();
229
+ const did = userDid ?? urlDid;
197
230
  try {
198
231
  const user = renown.user;
199
232
  if (user?.did && (user.did === did || !did)) return user;
@@ -203,6 +236,8 @@ async function login(userDid, renown) {
203
236
  return loggedIn;
204
237
  } catch (error) {
205
238
  logger.error(error instanceof Error ? error.message : JSON.stringify(error));
239
+ } finally {
240
+ if (urlDid) clearUserParamFromUrl();
206
241
  }
207
242
  }
208
243
  async function logout() {
@@ -211,14 +246,10 @@ async function logout() {
211
246
  } catch (error) {
212
247
  logger.error(error instanceof Error ? error.message : String(error));
213
248
  }
214
- await (window.ph?.renown)?.logout();
249
+ await (getPHStore()?.renown)?.logout();
215
250
  resetSignInGuard();
216
251
  notifyReactorClientCredentialsChanged();
217
- const url = new URL(window.location.href);
218
- if (url.searchParams.has("user")) {
219
- url.searchParams.delete("user");
220
- window.history.replaceState(null, "", url.toString());
221
- }
252
+ clearUserParamFromUrl();
222
253
  }
223
254
  //#endregion
224
255
  //#region src/renown/use-renown-auth.ts
@@ -1388,6 +1419,6 @@ function useRenownWalletAdapter(id) {
1388
1419
  return controller;
1389
1420
  }
1390
1421
  //#endregion
1391
- export { RENOWN_CHAIN_ID as A, logout as C, CREDENTIAL_TYPES as D, CREDENTIAL_SUBJECT_TYPE as E, RENOWN_RETURN_URL_STRIPPED_PARAMS as M, RENOWN_URL as N, DOMAIN_TYPE as O, VERIFIABLE_CREDENTIAL_EIP712_TYPE as P, login as S, CREDENTIAL_SCHEMA_EIP712_TYPE as T, RenownLogo as _, Renown as a, useRenownAuth as b, useRenownSessionSynced as c, RenownAuthButton as d, RenownUserButton as f, DisconnectIcon as g, CopyIcon as h, RenownWalletProvider as i, RENOWN_NETWORK_ID as j, ISSUER_TYPE as k, initConnectCrypto as l, ChevronDownIcon as m, useRenownLoginMethods as n, useRenownInit as o, RenownLoginButton as p, RenownProvider as r, useRenownSessionCookie as s, useRenownWalletAdapter as t, initRenownCrypto as u, SpinnerIcon as v, openRenown as w, useRenownAuthAsync as x, UserIcon as y };
1422
+ export { CREDENTIAL_TYPES as A, useRenownAuthAsync as C, openRenown as D, logout as E, RENOWN_RETURN_URL_STRIPPED_PARAMS as F, RENOWN_URL as I, VERIFIABLE_CREDENTIAL_EIP712_TYPE as L, ISSUER_TYPE as M, RENOWN_CHAIN_ID as N, CREDENTIAL_SCHEMA_EIP712_TYPE as O, RENOWN_NETWORK_ID as P, useRenownAuth as S, login as T, CopyIcon as _, RenownProvider as a, SpinnerIcon as b, useRenownInit as c, initConnectCrypto as d, initRenownCrypto as f, ChevronDownIcon as g, RenownLoginButton as h, useRenownLoginMethods as i, DOMAIN_TYPE as j, CREDENTIAL_SUBJECT_TYPE as k, useRenownSessionCookie as l, RenownUserButton as m, decodeDelegation as n, RenownWalletProvider as o, RenownAuthButton as p, useRenownWalletAdapter as r, Renown as s, createDelegation as t, useRenownSessionSynced as u, DisconnectIcon as v, desktopShell as w, UserIcon as x, RenownLogo as y };
1392
1423
 
1393
- //# sourceMappingURL=renown-C9pYZRqf.js.map
1424
+ //# sourceMappingURL=renown-B3MUaiq7.js.map