@symbiotejs/symbiote 3.8.3 → 3.10.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 (137) hide show
  1. package/README.md +52 -2
  2. package/core/AppRouter.js +97 -58
  3. package/core/PubSub.js +42 -11
  4. package/core/Symbiote.js +90 -59
  5. package/core/itemizeProcessor-keyed.js +88 -188
  6. package/core/itemizeProcessor.js +1 -12
  7. package/core/itemizeSetup.js +26 -3
  8. package/core/ownElements.js +1 -4
  9. package/core/resolveTemplate.js +12 -0
  10. package/core/tpl-processors.js +3 -3
  11. package/docs/README.md +5 -4
  12. package/docs/html-app-vs-htmx.md +55 -0
  13. package/docs/lifecycle.md +2 -0
  14. package/docs/list-rendering.md +10 -2
  15. package/docs/properties.md +28 -1
  16. package/docs/pubsub.md +3 -0
  17. package/docs/routing.md +15 -4
  18. package/docs/security.md +41 -12
  19. package/docs/templates.md +29 -0
  20. package/html-app/BaseClass.js +203 -0
  21. package/html-app/README.md +369 -0
  22. package/html-app/action-data.js +168 -0
  23. package/html-app/actions.js +366 -0
  24. package/html-app/collection-actions.js +104 -0
  25. package/html-app/collection-data.js +234 -0
  26. package/html-app/collection-items.js +45 -0
  27. package/html-app/conditions.js +42 -0
  28. package/html-app/context-data.js +185 -0
  29. package/html-app/context-requests.js +374 -0
  30. package/html-app/context-storage.js +376 -0
  31. package/html-app/declarations.js +55 -0
  32. package/html-app/examples/assets/actions.html +56 -0
  33. package/html-app/examples/assets/collections.html +72 -0
  34. package/html-app/examples/assets/components.html +25 -0
  35. package/html-app/examples/assets/conditional.html +29 -0
  36. package/html-app/examples/assets/data.html +31 -0
  37. package/html-app/examples/assets/guide.html +4 -0
  38. package/html-app/examples/assets/imports.html +11 -0
  39. package/html-app/examples/assets/not-found.html +4 -0
  40. package/html-app/examples/assets/routes.json +58 -0
  41. package/html-app/examples/assets/routing.html +27 -0
  42. package/html-app/examples/assets/state.html +32 -0
  43. package/html-app/examples/assets/storage.html +28 -0
  44. package/html-app/examples/assets/tasks.json +25 -0
  45. package/html-app/examples/full-app.html +147 -0
  46. package/html-app/examples/todo-ref.html +37 -0
  47. package/html-app/fetch-source.js +147 -0
  48. package/html-app/fragment-content.js +29 -0
  49. package/html-app/fragment-source.js +169 -0
  50. package/html-app/index.js +34 -0
  51. package/html-app/initial-data.js +88 -0
  52. package/html-app/pub-map.js +93 -0
  53. package/html-app/router-data.js +50 -0
  54. package/html-app/router-navigation.js +70 -0
  55. package/html-app/storage-revisions.js +130 -0
  56. package/html-app/sym-collection.js +142 -0
  57. package/html-app/sym-component.js +20 -0
  58. package/html-app/sym-conditional.js +141 -0
  59. package/html-app/sym-context.js +176 -0
  60. package/html-app/sym-import.js +218 -0
  61. package/html-app/sym-router.js +107 -0
  62. package/package.json +18 -8
  63. package/scripts/check-html-app-package.js +117 -0
  64. package/scripts/check-html-app-size.js +91 -0
  65. package/scripts/update-exports.js +4 -0
  66. package/skills/symbiote/SKILL.md +197 -0
  67. package/skills/symbiote/agents/openai.yaml +3 -0
  68. package/types/core/AppRouter.d.ts +13 -4
  69. package/types/core/AppRouter.d.ts.map +1 -1
  70. package/types/core/PubSub.d.ts +1 -1
  71. package/types/core/PubSub.d.ts.map +1 -1
  72. package/types/core/Symbiote.d.ts +6 -2
  73. package/types/core/Symbiote.d.ts.map +1 -1
  74. package/types/core/itemizeProcessor-keyed.d.ts.map +1 -1
  75. package/types/core/itemizeProcessor.d.ts.map +1 -1
  76. package/types/core/itemizeSetup.d.ts +1 -0
  77. package/types/core/itemizeSetup.d.ts.map +1 -1
  78. package/types/core/ownElements.d.ts +1 -1
  79. package/types/core/ownElements.d.ts.map +1 -1
  80. package/types/core/resolveTemplate.d.ts +2 -0
  81. package/types/core/resolveTemplate.d.ts.map +1 -0
  82. package/types/html-app/BaseClass.d.ts +24 -0
  83. package/types/html-app/BaseClass.d.ts.map +1 -0
  84. package/types/html-app/action-data.d.ts +15 -0
  85. package/types/html-app/action-data.d.ts.map +1 -0
  86. package/types/html-app/actions.d.ts +104 -0
  87. package/types/html-app/actions.d.ts.map +1 -0
  88. package/types/html-app/collection-actions.d.ts +12 -0
  89. package/types/html-app/collection-actions.d.ts.map +1 -0
  90. package/types/html-app/collection-data.d.ts +13 -0
  91. package/types/html-app/collection-data.d.ts.map +1 -0
  92. package/types/html-app/collection-items.d.ts +7 -0
  93. package/types/html-app/collection-items.d.ts.map +1 -0
  94. package/types/html-app/conditions.d.ts +5 -0
  95. package/types/html-app/conditions.d.ts.map +1 -0
  96. package/types/html-app/context-data.d.ts +31 -0
  97. package/types/html-app/context-data.d.ts.map +1 -0
  98. package/types/html-app/context-requests.d.ts +97 -0
  99. package/types/html-app/context-requests.d.ts.map +1 -0
  100. package/types/html-app/context-storage.d.ts +102 -0
  101. package/types/html-app/context-storage.d.ts.map +1 -0
  102. package/types/html-app/declarations.d.ts +3 -0
  103. package/types/html-app/declarations.d.ts.map +1 -0
  104. package/types/html-app/fetch-source.d.ts +23 -0
  105. package/types/html-app/fetch-source.d.ts.map +1 -0
  106. package/types/html-app/fragment-content.d.ts +6 -0
  107. package/types/html-app/fragment-content.d.ts.map +1 -0
  108. package/types/html-app/fragment-source.d.ts +14 -0
  109. package/types/html-app/fragment-source.d.ts.map +1 -0
  110. package/types/html-app/index.d.ts +9 -0
  111. package/types/html-app/index.d.ts.map +1 -0
  112. package/types/html-app/initial-data.d.ts +8 -0
  113. package/types/html-app/initial-data.d.ts.map +1 -0
  114. package/types/html-app/pub-map.d.ts +19 -0
  115. package/types/html-app/pub-map.d.ts.map +1 -0
  116. package/types/html-app/router-data.d.ts +4 -0
  117. package/types/html-app/router-data.d.ts.map +1 -0
  118. package/types/html-app/router-navigation.d.ts +3 -0
  119. package/types/html-app/router-navigation.d.ts.map +1 -0
  120. package/types/html-app/storage-revisions.d.ts +11 -0
  121. package/types/html-app/storage-revisions.d.ts.map +1 -0
  122. package/types/html-app/sym-collection.d.ts +16 -0
  123. package/types/html-app/sym-collection.d.ts.map +1 -0
  124. package/types/html-app/sym-component.d.ts +5 -0
  125. package/types/html-app/sym-component.d.ts.map +1 -0
  126. package/types/html-app/sym-conditional.d.ts +10 -0
  127. package/types/html-app/sym-conditional.d.ts.map +1 -0
  128. package/types/html-app/sym-context.d.ts +16 -0
  129. package/types/html-app/sym-context.d.ts.map +1 -0
  130. package/types/html-app/sym-import.d.ts +19 -0
  131. package/types/html-app/sym-import.d.ts.map +1 -0
  132. package/types/html-app/sym-router.d.ts +12 -0
  133. package/types/html-app/sym-router.d.ts.map +1 -0
  134. package/docs/llms-index.md +0 -49
  135. package/llms-full.txt +0 -5432
  136. package/llms.txt +0 -49
  137. package/scripts/build-llms.js +0 -56
@@ -0,0 +1,45 @@
1
+ import { ownElements } from '../core/ownElements.js';
2
+ import { itemizeProcessor } from '../core/itemizeProcessor-keyed.js';
3
+ import { DICT } from '../core/dictionary.js';
4
+
5
+ /** @type {WeakMap<Element, import('./sym-collection.js').SymCollection>} */
6
+ let containers = new WeakMap();
7
+
8
+ /**
9
+ * Associate only this controller's own Itemize containers with its source.
10
+ * @param {Element | DocumentFragment} root
11
+ * @param {import('./sym-collection.js').SymCollection} owner
12
+ */
13
+ export function collectionItemsProcessor(root, owner) {
14
+ for (let element of ownElements(root, '[itemize]')) {
15
+ let reference = owner.Symbiote.parseProp(element.getAttribute('itemize'), owner);
16
+ if (reference?.ctx === owner.localCtx && reference.name === 'items') {
17
+ containers.set(element, owner);
18
+ }
19
+ }
20
+ itemizeProcessor(/** @type {DocumentFragment} */ (root), owner);
21
+ }
22
+
23
+ /** @param {Element} owner */
24
+ export function findCollectionItem(owner) {
25
+ let item = owner;
26
+ while (item) {
27
+ let collection = containers.get(item.parentElement);
28
+ if (collection) {
29
+ if (!collection.isConnected) {
30
+ break;
31
+ }
32
+ let id = Reflect.get(item, DICT.MCP_ITEM_KEY_KEY);
33
+ if (typeof id !== 'string') {
34
+ break;
35
+ }
36
+ return {
37
+ collection,
38
+ item,
39
+ id,
40
+ };
41
+ }
42
+ item = item.parentElement;
43
+ }
44
+ throw new TypeError('Item actions require an item in a sym-collection view.');
45
+ }
@@ -0,0 +1,42 @@
1
+ let behaviors = Object.freeze({
2
+ show: {
3
+ dom: false,
4
+ inverse: false,
5
+ },
6
+ hide: {
7
+ dom: false,
8
+ inverse: true,
9
+ },
10
+ 'dom-add': {
11
+ dom: true,
12
+ inverse: false,
13
+ },
14
+ 'dom-remove': {
15
+ dom: true,
16
+ inverse: true,
17
+ },
18
+ });
19
+
20
+ /**
21
+ * Conditions compare data values, never expressions.
22
+ * @param {unknown} value
23
+ * @param {string | null} expected
24
+ * @param {string} behavior
25
+ * @param {string | null} type
26
+ */
27
+ export function conditionState(value, expected, behavior = 'show', type = null) {
28
+ let mode = Object.hasOwn(behaviors, behavior) ? behaviors[behavior] : undefined;
29
+ if (!mode) {
30
+ throw new TypeError('Conditional behavior must be show, hide, dom-add or dom-remove.');
31
+ }
32
+ if (type !== null && (type !== 'string' || expected === null)) {
33
+ throw new TypeError('is-type supports string with an explicit is value.');
34
+ }
35
+ let match = expected === null ? !!value
36
+ : Object.is(value, type === 'string' ? expected
37
+ : expected === 'true' ? true : expected === 'false' ? false : expected);
38
+ return {
39
+ visible: mode.inverse ? !match : match,
40
+ dom: mode.dom,
41
+ };
42
+ }
@@ -0,0 +1,185 @@
1
+ import { isDataKey, initialDefaults } from './initial-data.js';
2
+ import { cloneData, validateJSON } from './collection-data.js';
3
+ import { SourceError } from './fetch-source.js';
4
+ import { validateValue } from './action-data.js';
5
+
6
+ export class ContextData {
7
+ keys = new Set();
8
+ bound = new Set();
9
+ edited = new Set();
10
+ /** @type {Map<string, Set<object>>} */
11
+ pending = new Map();
12
+ /** @type {Map<string, number>} */
13
+ versions = new Map();
14
+ revision = 0;
15
+ /** @type {number | null} */
16
+ savedRevision = null;
17
+ applying = false;
18
+
19
+ /** @param {import('./sym-context.js').SymContext} owner */
20
+ constructor(owner) {
21
+ this.owner = owner;
22
+ }
23
+
24
+ setup() {
25
+ for (let [
26
+ key,
27
+ value,
28
+ ] of Object.entries({
29
+ ...this.owner.init$,
30
+ ...initialDefaults.get(this.owner.localCtx),
31
+ })) {
32
+ if (isDataKey(key)) {
33
+ try {
34
+ validateJSON(value);
35
+ this.keys.add(key);
36
+ } catch {
37
+ // Native handlers and descriptors are controls, not public JSON data.
38
+ }
39
+ }
40
+ }
41
+ }
42
+
43
+ /** @param {Record<string, unknown>} values */
44
+ incoming(values) {
45
+ for (let [
46
+ key,
47
+ value,
48
+ ] of Object.entries(values)) {
49
+ if (!isDataKey(key)) {
50
+ continue;
51
+ }
52
+ if (!this.applying) {
53
+ this.bound.add(key);
54
+ }
55
+ try {
56
+ validateJSON(value);
57
+ this.keys.add(key);
58
+ } catch {
59
+ // Existing public fields remain selected so invalid writes fail visibly.
60
+ }
61
+ }
62
+ }
63
+
64
+ selected() {
65
+ let fields = this.owner.getAttribute('sync-keys');
66
+ return fields === null ? [
67
+ ...this.keys,
68
+ ] : fields.split(',').map((key) => key.trim()).filter(Boolean);
69
+ }
70
+
71
+ dirty() {
72
+ return this.selected().some((key) => this.edited.has(key) || this.pending.has(key));
73
+ }
74
+
75
+ /**
76
+ * @param {string} key
77
+ * @param {unknown} previous
78
+ * @param {unknown} value
79
+ */
80
+ changed(key, previous, value) {
81
+ if (!isDataKey(key) || Object.is(previous, value)) {
82
+ return;
83
+ }
84
+ if (!this.keys.has(key)) {
85
+ try {
86
+ validateJSON(value);
87
+ this.keys.add(key);
88
+ } catch {
89
+ return;
90
+ }
91
+ }
92
+ this.versions.set(key, (this.versions.get(key) ?? 0) + 1);
93
+ if (!this.applying) {
94
+ this.edited.add(key);
95
+ }
96
+ if (this.selected().includes(key)) {
97
+ this.revision++;
98
+ }
99
+ this.owner.requests.publish();
100
+ }
101
+
102
+ /**
103
+ * Protect a captured edit without publishing it before its debounce expires.
104
+ * @param {string} key
105
+ * @param {unknown} value
106
+ */
107
+ intent(key, value) {
108
+ validateJSON(value);
109
+ this.keys.add(key);
110
+ this.versions.set(key, (this.versions.get(key) ?? 0) + 1);
111
+ let token = {};
112
+ let pending = this.pending.get(key) ?? new Set();
113
+ pending.add(token);
114
+ this.pending.set(key, pending);
115
+ this.owner.requests.publish();
116
+ return {
117
+ remove: () => {
118
+ pending.delete(token);
119
+ if (!pending.size) {
120
+ this.pending.delete(key);
121
+ }
122
+ this.owner.requests.publish();
123
+ },
124
+ };
125
+ }
126
+
127
+ /** @param {string[]} [keys] */
128
+ snapshot(keys = this.selected()) {
129
+ if (!keys.length || new Set(keys).size !== keys.length
130
+ || keys.some((key) => !isDataKey(key) || !this.keys.has(key))) {
131
+ throw new SourceError('INVALID_DATA', 'Selected fields must be known public data fields.');
132
+ }
133
+ let data = Object.fromEntries(keys.map((key) => [
134
+ key,
135
+ this.owner.localCtx.read(key),
136
+ ]));
137
+ return {
138
+ data: cloneData(data),
139
+ revision: this.revision,
140
+ versions: new Map(keys.map((key) => [
141
+ key,
142
+ this.versions.get(key) ?? 0,
143
+ ])),
144
+ };
145
+ }
146
+
147
+ /**
148
+ * @param {number} revision
149
+ * @param {Map<string, number>} versions
150
+ */
151
+ acknowledge(revision, versions) {
152
+ this.savedRevision = revision;
153
+ for (let [
154
+ key,
155
+ version,
156
+ ] of versions) {
157
+ if ((this.versions.get(key) ?? 0) === version) {
158
+ this.edited.delete(key);
159
+ }
160
+ }
161
+ this.owner.requests.publish();
162
+ }
163
+
164
+ /** @param {Record<string, unknown>} data */
165
+ validate(data) {
166
+ for (let [
167
+ key,
168
+ value,
169
+ ] of Object.entries(data)) {
170
+ if (!isDataKey(key)) {
171
+ throw new SourceError('INVALID_DATA', 'Source keys must be public data fields.');
172
+ }
173
+ if (this.owner.localCtx.has(key)) {
174
+ let current = this.owner.localCtx.read(key);
175
+ validateJSON(current);
176
+ validateValue(current, value);
177
+ }
178
+ }
179
+ }
180
+
181
+ invalidate() {
182
+ this.savedRevision = null;
183
+ this.revision++;
184
+ }
185
+ }
@@ -0,0 +1,374 @@
1
+ import { PubSub } from '../core/PubSub.js';
2
+ import { fetchSource, parseResponseJSON, requestLimits, sourceURL, SourceError } from './fetch-source.js';
3
+ import { fragmentSource } from './fragment-source.js';
4
+ import { storageSignals } from './context-storage.js';
5
+ import { recordData, validateJSON } from './collection-data.js';
6
+
7
+ let requestKeys = Object.freeze([
8
+ 'loading',
9
+ 'saving',
10
+ 'busy',
11
+ 'dirty',
12
+ 'revision',
13
+ 'savedRevision',
14
+ 'loadError',
15
+ 'syncError',
16
+ 'loadErrorMessage',
17
+ 'syncErrorMessage',
18
+ ...storageSignals,
19
+ ]);
20
+
21
+ /** @type {WeakMap<PubSub, ContextRequests>} */
22
+ let providers = new WeakMap();
23
+
24
+ /**
25
+ * @param {string} name
26
+ */
27
+ export function contextRequests(name) {
28
+ let context = PubSub.getCtx(name, false);
29
+ let requests = context && providers.get(context);
30
+ if (!requests || !requests.owner.isConnected) {
31
+ throw new TypeError('Expected a connected sym-context provider: ' + name);
32
+ }
33
+ return requests;
34
+ }
35
+
36
+ /**
37
+ * Attach provider tracking when an authored action targets a late data field.
38
+ * @param {import('../core/parseProp.js').ParsedProp} target
39
+ */
40
+ export function observeDataTarget(target) {
41
+ let requests = providers.get(target.ctx);
42
+ if (requests?.ready && requests.owner.isConnected) {
43
+ requests.owner.watchData(target.name);
44
+ return requests.owner.contextData;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * @param {unknown} failure
50
+ * @param {'load' | 'sync'} operation
51
+ */
52
+ function requestError(failure, operation) {
53
+ return {
54
+ operation,
55
+ code: failure instanceof SourceError ? failure.code : 'INVALID_DATA',
56
+ message: failure instanceof Error ? failure.message : 'The request failed.',
57
+ status: failure instanceof SourceError ? failure.status : null,
58
+ };
59
+ }
60
+
61
+ export class ContextRequests {
62
+ ready = false;
63
+ connected = false;
64
+ loaded = false;
65
+ scheduled = false;
66
+ /** @type {AbortController | undefined} */
67
+ readController;
68
+ /** @type {AbortController | undefined} */
69
+ writeController;
70
+ /** @type {ReturnType<ContextRequests['performSync']> | undefined} */
71
+ saving;
72
+ /** @type {{ loading: boolean, saving: boolean, loadError: ReturnType<typeof requestError> | null, syncError: ReturnType<typeof requestError> | null }} */
73
+ state = {
74
+ loading: false,
75
+ saving: false,
76
+ loadError: null,
77
+ syncError: null,
78
+ };
79
+
80
+ /** @param {import('./sym-context.js').SymContext} owner */
81
+ constructor(owner) {
82
+ this.owner = owner;
83
+ }
84
+
85
+ setup() {
86
+ this.ready = true;
87
+ this.owner.contextData.setup();
88
+ providers.set(this.owner.localCtx, this);
89
+ this.owner.localCtx.add('__htmlAppRequest', {}, true);
90
+ for (let key of requestKeys) {
91
+ this.owner.localCtx.add('+' + key, () => this.owner.$.__htmlAppRequest[key], true);
92
+ }
93
+ this.publish();
94
+ }
95
+
96
+ publish() {
97
+ if (!this.ready) {
98
+ return;
99
+ }
100
+ this.owner.localCtx.pub('__htmlAppRequest', {
101
+ ...this.state,
102
+ ...this.owner.storage.status(),
103
+ busy: this.state.loading || this.state.saving,
104
+ dirty: this.owner.contextData.dirty(),
105
+ revision: this.owner.contextData.revision,
106
+ savedRevision: this.owner.contextData.savedRevision,
107
+ loadErrorMessage: this.state.loadError?.message ?? '',
108
+ syncErrorMessage: this.state.syncError?.message ?? '',
109
+ });
110
+ }
111
+
112
+ connect() {
113
+ this.connected = true;
114
+ if (!this.loaded) {
115
+ this.scheduleLoad();
116
+ }
117
+ }
118
+
119
+ disconnect() {
120
+ this.connected = false;
121
+ this.scheduled = false;
122
+ this.cancelRead();
123
+ this.cancelWrite();
124
+ }
125
+
126
+ destroy() {
127
+ this.disconnect();
128
+ providers.delete(this.owner.localCtx);
129
+ // Runtime signals are recreated on connection, rather than snapshotted as data.
130
+ for (let key of requestKeys) {
131
+ this.owner.localCtx.delete('+' + key);
132
+ }
133
+ this.ready = false;
134
+ }
135
+
136
+ /** @param {string} name */
137
+ configure(name) {
138
+ if (!this.ready) {
139
+ return;
140
+ }
141
+ this.cancelWrite();
142
+ if (name === 'src') {
143
+ this.cancelRead();
144
+ this.loaded = false;
145
+ this.scheduleLoad();
146
+ }
147
+ if ([
148
+ 'src',
149
+ 'sync',
150
+ 'sync-method',
151
+ 'sync-keys',
152
+ ].includes(name)) {
153
+ this.owner.contextData.invalidate();
154
+ }
155
+ this.publish();
156
+ }
157
+
158
+ cancelRead() {
159
+ this.readController?.abort();
160
+ this.readController = undefined;
161
+ this.state.loading = false;
162
+ this.publish();
163
+ }
164
+
165
+ cancelWrite() {
166
+ this.writeController?.abort();
167
+ this.writeController = undefined;
168
+ this.saving = undefined;
169
+ this.state.saving = false;
170
+ this.publish();
171
+ }
172
+
173
+ scheduleLoad() {
174
+ if (this.scheduled || !this.connected || !this.owner.getAttribute('src') || globalThis.__SYMBIOTE_SSR) {
175
+ return;
176
+ }
177
+ this.scheduled = true;
178
+ queueMicrotask(() => {
179
+ if (this.scheduled && this.connected) {
180
+ this.scheduled = false;
181
+ void this.load();
182
+ }
183
+ });
184
+ }
185
+
186
+ /** @param {'src' | 'sync'} name */
187
+ url(name) {
188
+ return sourceURL(this.owner.getAttribute(name) ?? '', fragmentSource(this.owner).url);
189
+ }
190
+
191
+ /**
192
+ * @param {'load' | 'sync'} operation
193
+ * @param {unknown} failure
194
+ */
195
+ fail(operation, failure) {
196
+ let error = requestError(failure, operation);
197
+ this.state[operation === 'load' ? 'loadError' : 'syncError'] = error;
198
+ this.publish();
199
+ this.owner.dispatchEvent(new CustomEvent('error', {
200
+ detail: error,
201
+ }));
202
+ return {
203
+ ok: false,
204
+ error,
205
+ };
206
+ }
207
+
208
+ /** @param {boolean} [overwrite] */
209
+ async load(overwrite = false) {
210
+ this.scheduled = false;
211
+ if (!this.connected || globalThis.__SYMBIOTE_SSR) {
212
+ return {
213
+ ok: false,
214
+ cancelled: true,
215
+ };
216
+ }
217
+ if (this.writeController) {
218
+ return this.fail('load', new SourceError('BUSY', 'A save is still pending.'));
219
+ }
220
+ this.cancelRead();
221
+ let controller = new AbortController();
222
+ this.readController = controller;
223
+ let versions = new Map(this.owner.contextData.versions);
224
+ this.state.loading = true;
225
+ this.state.loadError = null;
226
+ this.publish();
227
+ try {
228
+ let response = await fetchSource(this.url('src'), {
229
+ ...requestLimits(this.owner),
230
+ signal: controller.signal,
231
+ });
232
+ let data = recordData(parseResponseJSON(response));
233
+ if (this.readController !== controller || controller.signal.aborted || !this.owner.isConnected) {
234
+ return {
235
+ ok: false,
236
+ cancelled: true,
237
+ };
238
+ }
239
+ this.owner.contextData.validate(data);
240
+ /** @type {Record<string, unknown>} */
241
+ let accepted = {};
242
+ let retained = [];
243
+ for (let [
244
+ key,
245
+ value,
246
+ ] of Object.entries(data)) {
247
+ if (this.owner.contextData.bound.has(key)
248
+ || (!overwrite && (this.owner.contextData.edited.has(key)
249
+ || this.owner.contextData.pending.has(key) || this.owner.storage.restored.has(key)))
250
+ || (this.owner.contextData.versions.get(key) ?? 0) !== (versions.get(key) ?? 0)) {
251
+ retained.push(key);
252
+ } else {
253
+ accepted[key] = value;
254
+ }
255
+ }
256
+ this.owner.mergeSource(accepted);
257
+ if (this.readController !== controller || controller.signal.aborted || !this.owner.isConnected) {
258
+ return {
259
+ ok: false,
260
+ cancelled: true,
261
+ };
262
+ }
263
+ this.loaded = true;
264
+ let result = {
265
+ ok: true,
266
+ operation: 'load',
267
+ applied: Object.keys(accepted),
268
+ retained,
269
+ };
270
+ this.owner.dispatchEvent(new CustomEvent('load', {
271
+ detail: result,
272
+ }));
273
+ return result;
274
+ } catch (failure) {
275
+ if (this.readController !== controller || controller.signal.aborted) {
276
+ return {
277
+ ok: false,
278
+ cancelled: true,
279
+ };
280
+ }
281
+ return this.fail('load', failure);
282
+ } finally {
283
+ if (this.readController === controller) {
284
+ this.readController = undefined;
285
+ this.state.loading = false;
286
+ this.publish();
287
+ }
288
+ }
289
+ }
290
+
291
+ sync() {
292
+ if (this.saving) {
293
+ return this.saving;
294
+ }
295
+ let saving = this.performSync();
296
+ this.saving = saving;
297
+ void saving.finally(() => {
298
+ if (this.saving === saving) {
299
+ this.saving = undefined;
300
+ }
301
+ });
302
+ return saving;
303
+ }
304
+
305
+ async performSync() {
306
+ if (!this.connected || globalThis.__SYMBIOTE_SSR) {
307
+ return {
308
+ ok: false,
309
+ cancelled: true,
310
+ };
311
+ }
312
+ if (this.readController) {
313
+ return this.fail('sync', new SourceError('BUSY', 'A load is still pending.'));
314
+ }
315
+ let controller = new AbortController();
316
+ this.writeController = controller;
317
+ this.state.syncError = null;
318
+ try {
319
+ let method = (this.owner.getAttribute('sync-method') ?? 'PUT').toUpperCase();
320
+ if (![
321
+ 'PUT',
322
+ 'POST',
323
+ 'PATCH',
324
+ ].includes(method)) {
325
+ throw new SourceError('INVALID_CONFIG', 'sync-method must be PUT, POST or PATCH.');
326
+ }
327
+ let url = this.url('sync');
328
+ let snapshot = this.owner.contextData.snapshot();
329
+ let limits = requestLimits(this.owner);
330
+ this.state.saving = true;
331
+ this.publish();
332
+ let response = await fetchSource(url, {
333
+ ...limits,
334
+ signal: controller.signal,
335
+ method,
336
+ body: JSON.stringify(snapshot.data),
337
+ });
338
+ if (response.status !== 204) {
339
+ validateJSON(parseResponseJSON(response));
340
+ }
341
+ if (this.writeController !== controller || controller.signal.aborted || !this.owner.isConnected) {
342
+ return {
343
+ ok: false,
344
+ cancelled: true,
345
+ };
346
+ }
347
+ this.owner.contextData.acknowledge(snapshot.revision, snapshot.versions);
348
+ let result = {
349
+ ok: true,
350
+ operation: 'sync',
351
+ revision: snapshot.revision,
352
+ dirty: this.owner.contextData.dirty(),
353
+ };
354
+ this.owner.dispatchEvent(new CustomEvent('sync', {
355
+ detail: result,
356
+ }));
357
+ return result;
358
+ } catch (failure) {
359
+ if (this.writeController !== controller || controller.signal.aborted) {
360
+ return {
361
+ ok: false,
362
+ cancelled: true,
363
+ };
364
+ }
365
+ return this.fail('sync', failure);
366
+ } finally {
367
+ if (this.writeController === controller) {
368
+ this.writeController = undefined;
369
+ this.state.saving = false;
370
+ this.publish();
371
+ }
372
+ }
373
+ }
374
+ }