@gadicc/loom 1.23.0 → 1.25.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 (35) hide show
  1. package/README.md +19 -2
  2. package/db/databaseTls.js +42 -0
  3. package/db/databaseTls.test.ts +171 -0
  4. package/db/neonFull.js +2 -4
  5. package/esm/_dnt.polyfills.d.ts +11 -0
  6. package/esm/_dnt.polyfills.d.ts.map +1 -1
  7. package/esm/_dnt.polyfills.js +14 -0
  8. package/esm/src/cli/filesR2Policy.d.ts +33 -0
  9. package/esm/src/cli/filesR2Policy.d.ts.map +1 -0
  10. package/esm/src/cli/filesR2Policy.js +130 -0
  11. package/esm/src/cli/mod.d.ts.map +1 -1
  12. package/esm/src/cli/mod.js +163 -60
  13. package/esm/src/cli/releaseConfig.d.ts +10 -0
  14. package/esm/src/cli/releaseConfig.d.ts.map +1 -0
  15. package/esm/src/cli/releaseConfig.js +22 -0
  16. package/esm/src/next/pwa/mod.d.ts +10 -2
  17. package/esm/src/next/pwa/mod.d.ts.map +1 -1
  18. package/esm/src/next/pwa/mod.js +142 -31
  19. package/package.json +2 -2
  20. package/script/_dnt.polyfills.d.ts +11 -0
  21. package/script/_dnt.polyfills.d.ts.map +1 -1
  22. package/script/_dnt.polyfills.js +14 -0
  23. package/script/src/cli/filesR2Policy.d.ts +33 -0
  24. package/script/src/cli/filesR2Policy.d.ts.map +1 -0
  25. package/script/src/cli/filesR2Policy.js +135 -0
  26. package/script/src/cli/mod.d.ts.map +1 -1
  27. package/script/src/cli/mod.js +163 -60
  28. package/script/src/cli/releaseConfig.d.ts +10 -0
  29. package/script/src/cli/releaseConfig.d.ts.map +1 -0
  30. package/script/src/cli/releaseConfig.js +26 -0
  31. package/script/src/next/pwa/mod.d.ts +10 -2
  32. package/script/src/next/pwa/mod.d.ts.map +1 -1
  33. package/script/src/next/pwa/mod.js +142 -31
  34. package/skills/loom-db/SKILL.md +5 -1
  35. package/skills/loom-files/SKILL.md +12 -1
@@ -51,13 +51,24 @@ function reportError(error, onError, logger) {
51
51
  (logger ?? console).error("[PWA] Service worker lifecycle error", error);
52
52
  }
53
53
  }
54
- async function canApplyUpdate(context, options) {
55
- return await (options.canReloadNow?.(context) ?? true);
54
+ const registrations = new WeakMap();
55
+ function registerOnce(serwist) {
56
+ let pending = registrations.get(serwist);
57
+ if (!pending) {
58
+ // React effects can remount while registration is still waiting for load.
59
+ pending = Promise.resolve().then(() => serwist.register());
60
+ registrations.set(serwist, pending);
61
+ void pending.catch(() => registrations.delete(serwist));
62
+ }
63
+ return pending;
56
64
  }
57
65
  /**
58
66
  * Registers Loom's Serwist lifecycle listeners and optional update polling.
59
67
  *
60
- * The returned cleanup function removes listeners and clears the polling timer.
68
+ * Cleanup removes this observer's listeners and polling without unregistering
69
+ * the worker or removing offline caches. Pending callbacks cannot activate or
70
+ * reload after cleanup. Registration is shared across effect remounts.
71
+ *
61
72
  * In `prompt` mode, a waiting worker is activated only after `canReloadNow` and
62
73
  * `confirmUpdate` both allow it; in `manual` mode Loom reports availability but
63
74
  * never activates the worker for the app.
@@ -71,8 +82,19 @@ function setupLoomPwaLifecycle(options = {}) {
71
82
  const logger = options.logger === false ? false : options.logger ?? console;
72
83
  const reload = options.reload ?? defaultReload;
73
84
  let disposed = false;
74
- let reloadOnNextControl = false;
85
+ let reloaded = false;
86
+ let reloadPending = false;
87
+ let approvedWorker;
88
+ let legacyApproval = false;
89
+ let registration;
75
90
  let updateInterval;
91
+ let updatePending = false;
92
+ let promptQueue = Promise.resolve();
93
+ const pendingWaiting = new WeakSet();
94
+ const decidedWaiting = new WeakSet();
95
+ const controller = () => navigator.serviceWorker.controller;
96
+ let previousController = controller();
97
+ let latestControl;
76
98
  const makeContext = (reason, event) => ({
77
99
  event,
78
100
  isUpdate: event.isUpdate ?? reason === "waiting",
@@ -80,77 +102,166 @@ function setupLoomPwaLifecycle(options = {}) {
80
102
  serwist,
81
103
  wasWaitingBeforeRegister: event.wasWaitingBeforeRegister,
82
104
  });
105
+ const failed = (error) => {
106
+ if (!disposed)
107
+ reportError(error, options.onError, options.logger);
108
+ };
83
109
  const deferUpdate = (context) => {
110
+ if (disposed)
111
+ return;
84
112
  options.onUpdateDeferred?.(context);
85
113
  logger && logger.info("[PWA] Update deferred.");
86
114
  };
115
+ const isCurrent = (worker) => !worker || controller() === worker ||
116
+ worker.state === "activating" || worker.state === "activated" ||
117
+ (worker.state !== "redundant" &&
118
+ (!registration || registration.waiting === worker));
119
+ const applyControl = async (context) => {
120
+ const current = controller();
121
+ const approved = approvedWorker
122
+ ? current === approvedWorker
123
+ : legacyApproval;
124
+ if (disposed || reloaded || reloadPending ||
125
+ (!approved && (updateMode !== "auto" || !context.isUpdate)))
126
+ return;
127
+ // Reserve before awaiting the app's guard; controller events can overlap.
128
+ reloadPending = true;
129
+ try {
130
+ const allowed = await (options.canReloadNow?.(context) ?? true);
131
+ if (disposed || reloaded || current !== controller())
132
+ return;
133
+ if (!allowed) {
134
+ deferUpdate(context);
135
+ return;
136
+ }
137
+ reloaded = true;
138
+ options.onUpdateActivated?.(context);
139
+ if (!disposed)
140
+ reload();
141
+ }
142
+ finally {
143
+ reloadPending = false;
144
+ }
145
+ };
87
146
  const handleWaiting = async (event) => {
147
+ const key = event.sw ?? event;
148
+ if (disposed || reloaded || decidedWaiting.has(key))
149
+ return;
88
150
  const context = makeContext("waiting", event);
89
151
  options.onUpdateAvailable?.(context);
152
+ if (disposed)
153
+ return;
90
154
  if (updateMode === "manual") {
91
155
  deferUpdate(context);
92
156
  return;
93
157
  }
94
- if (!(await canApplyUpdate(context, options))) {
158
+ const allowed = await (options.canReloadNow?.(context) ?? true);
159
+ if (disposed || reloaded)
160
+ return;
161
+ if (!allowed || !isCurrent(event.sw)) {
95
162
  deferUpdate(context);
96
163
  return;
97
164
  }
98
165
  const accepted = updateMode === "auto"
99
166
  ? true
100
167
  : await (options.confirmUpdate?.(context) ?? defaultConfirmUpdate());
101
- if (!accepted) {
168
+ if (disposed || reloaded)
169
+ return;
170
+ decidedWaiting.add(key);
171
+ if (!accepted || !isCurrent(event.sw)) {
102
172
  deferUpdate(context);
103
173
  return;
104
174
  }
105
- reloadOnNextControl = true;
175
+ approvedWorker = event.sw;
176
+ legacyApproval = !event.sw;
106
177
  options.onUpdateAccepted?.(context);
107
- await serwist.messageSkipWaiting();
108
- };
109
- const handleControlling = async (event) => {
110
- const context = makeContext("controlling", event);
111
- if (!context.isUpdate || (!reloadOnNextControl && updateMode !== "auto")) {
178
+ if (disposed || reloaded)
112
179
  return;
180
+ if (event.sw && controller() === event.sw) {
181
+ // Another tab may have activated the accepted worker during the prompt.
182
+ await applyControl(latestControl ?? makeContext("controlling", {
183
+ type: "controlling",
184
+ isUpdate: true,
185
+ sw: event.sw,
186
+ }));
113
187
  }
114
- if (!(await canApplyUpdate(context, options))) {
115
- deferUpdate(context);
116
- return;
188
+ else if (event.sw) {
189
+ // Serwist's messageSkipWaiting selects whichever worker is waiting now.
190
+ // Address the approved identity so a replacement cannot inherit consent.
191
+ if (event.sw.state !== "activating" && event.sw.state !== "activated") {
192
+ event.sw.postMessage({ type: "SKIP_WAITING" });
193
+ }
194
+ }
195
+ else {
196
+ // Preserve integrations that implement the original identity-free API.
197
+ await serwist.messageSkipWaiting();
117
198
  }
118
- options.onUpdateActivated?.(context);
119
- reload();
120
199
  };
121
200
  const waitingListener = (event) => {
122
- handleWaiting(event).catch((error) => reportError(error, options.onError, options.logger));
201
+ const key = event.sw ?? event;
202
+ if (disposed || reloaded || pendingWaiting.has(key))
203
+ return;
204
+ pendingWaiting.add(key);
205
+ // The shared confirmation UI has one dialog. Serialize different workers.
206
+ promptQueue = promptQueue.then(() => handleWaiting(event)).catch(failed)
207
+ .finally(() => pendingWaiting.delete(key));
123
208
  };
124
209
  const controllingListener = (event) => {
125
- handleControlling(event).catch((error) => reportError(error, options.onError, options.logger));
210
+ if (disposed)
211
+ return;
212
+ const current = controller();
213
+ const context = makeContext("controlling", event);
214
+ // Serwist snapshots isUpdate at registration, even on a first-install page
215
+ // that later receives updates. Its external event.sw can also be outdated.
216
+ context.isUpdate ||= Boolean(previousController && current !== previousController);
217
+ previousController = current;
218
+ latestControl = context;
219
+ void applyControl(context).catch(failed);
126
220
  };
127
221
  serwist.addEventListener("waiting", waitingListener);
128
222
  serwist.addEventListener("controlling", controllingListener);
223
+ const observeRegistration = (value) => {
224
+ if (disposed || !value)
225
+ return;
226
+ registration = value;
227
+ // Cached registration does not emit waiting again when an effect remounts.
228
+ if (value.waiting) {
229
+ waitingListener({
230
+ type: "waiting",
231
+ sw: value.waiting,
232
+ wasWaitingBeforeRegister: true,
233
+ });
234
+ }
235
+ };
129
236
  if (options.register ?? true) {
130
- serwist.register().catch((error) => reportError(error, options.onError, options.logger));
237
+ void registerOnce(serwist).then(observeRegistration).catch(failed);
131
238
  }
132
239
  if (options.updateCheckIntervalMs !== undefined &&
133
240
  options.updateCheckIntervalMs > 0) {
134
- navigator.serviceWorker.ready
135
- .then((registration) => {
136
- if (disposed) {
241
+ void navigator.serviceWorker.ready.then((value) => {
242
+ if (disposed)
137
243
  return;
138
- }
139
- logger &&
140
- logger.info(`[PWA] Will check for updates every ${options.updateCheckIntervalMs / 1000} seconds.`);
244
+ registration = value;
245
+ logger && logger.info(`[PWA] Will check for updates every ${options.updateCheckIntervalMs / 1000} seconds.`);
141
246
  updateInterval = setInterval(() => {
142
- registration.update().catch((error) => reportError(error, options.onError, options.logger));
247
+ if (disposed || updatePending)
248
+ return;
249
+ updatePending = true;
250
+ void Promise.resolve().then(() => {
251
+ if (!disposed)
252
+ return value.update();
253
+ }).catch(failed).finally(() => {
254
+ updatePending = false;
255
+ });
143
256
  }, options.updateCheckIntervalMs);
144
- })
145
- .catch((error) => reportError(error, options.onError, options.logger));
257
+ }).catch(failed);
146
258
  }
147
259
  return () => {
148
260
  disposed = true;
149
261
  serwist.removeEventListener("waiting", waitingListener);
150
262
  serwist.removeEventListener("controlling", controllingListener);
151
- if (updateInterval !== undefined) {
263
+ if (updateInterval !== undefined)
152
264
  clearInterval(updateInterval);
153
- }
154
265
  };
155
266
  }
156
267
  /**
@@ -71,7 +71,11 @@ Use this skill when working on the shared DB stack from a consuming app.
71
71
  - Confirm active Loom-managed feature schemas match their recorded hash in
72
72
  `loom.json` and are exported from the app-local schema barrel.
73
73
  - For Vercel production releases, confirm `vercel.json` disables automatic
74
- `main` deployments and GitHub Actions builds with Vercel production settings,
74
+ deployments for the configured production branch and GitHub Actions builds
75
+ with Vercel production settings. The branch defaults to `main`; apps using
76
+ another branch set `features.db.config.release.productionBranch` in
77
+ `loom.json` and match the Vercel project production branch, workflow trigger
78
+ and deployment fence. Workflows and `vercel.json` remain app-owned. The flow
75
79
  uploads a staged production deployment with `--prebuilt --prod --skip-domain`,
76
80
  runs `db:migrate`, and then promotes the staged deployment. Before adding
77
81
  build-only placeholders, preserve an untouched copy of the pulled env file for
@@ -56,7 +56,18 @@ Use this skill when working on the shared files feature from a consuming app.
56
56
  - Keep the default separate private Production and Preview buckets unless the
57
57
  app deliberately chooses `--shared-bucket`. Do not enable public development
58
58
  URLs, custom domains, browser-direct uploads, or CORS as part of standard
59
- setup.
59
+ setup. Apps with reviewed signers/finalizers may declare private
60
+ `directBrowserAccess:true` plus `directUpload.kind:presigned-put`, exact
61
+ Production/Preview HTTPS origins, explicit lowercase allowed headers, and
62
+ `maxAgeSeconds`. Keep `accessMode:private` and `publicUrl:null`. CORS does not
63
+ grant object access; app authorization and signed size/digest/expiry bounds
64
+ remain mandatory. See `docs/files-feature.md` for the complete fragment.
65
+ - Setup preserves a valid declared direct-upload policy and optional
66
+ `forcePathStyle` (omitted defaults false). With direct uploads declared, it
67
+ stops on missing/unverified CORS after retaining the bucket records. Apply
68
+ only a separately reviewed exact policy with Wrangler, then rerun setup.
69
+ Setup/check never apply CORS or enable public endpoints. A shared bucket's
70
+ rule contains the union of its declared environment origins.
60
71
  - Create an R2 Object Read & Write API token manually and scope it only to the
61
72
  configured bucket or buckets. Use `--configure-secrets` to let Vercel prompt
62
73
  for missing Production/Preview values without exposing them to Loom. Never