@entrinsik/vite-plugin-informer 2.12.0 → 2.14.0-beta.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.
package/src/deploy.js CHANGED
@@ -71,19 +71,18 @@ export async function deploy({ baseUrl, apiKey, user, pass, distDir, name, descr
71
71
  };
72
72
  if (id) payload.id = id;
73
73
 
74
- try {
75
- console.log(`Creating new app "${name}"...`);
76
- entity = await api.post('apps', { ...payload, type: 'app' });
77
- apiPrefix = 'apps';
78
- } catch (e) {
79
- // If apps endpoint doesn't exist (404), fall back to legacy reports
80
- if (e.status === 404) {
81
- console.log('Apps API not available, using legacy reports API...');
82
- entity = await api.post('reports', { ...payload, type: 'magicReport' });
83
- apiPrefix = 'reports';
84
- } else {
85
- throw e;
86
- }
74
+ console.log(`Creating new app "${name}"...`);
75
+ entity = await api.post('apps', { ...payload, type: 'app' });
76
+ apiPrefix = 'apps';
77
+
78
+ // Null, not a throw: client.js turns a 404 into a null reply, so the
79
+ // legacy-reports fallback has to branch on the value. As a catch on
80
+ // `e.status === 404` it could never fire, and a genuine missing-apps-API
81
+ // surfaced as "Failed to create" instead of falling back.
82
+ if (entity === null) {
83
+ console.log('Apps API not available, using legacy reports API...');
84
+ entity = await api.post('reports', { ...payload, type: 'magicReport' });
85
+ apiPrefix = 'reports';
87
86
  }
88
87
 
89
88
  if (!entity || !entity.id) {
@@ -116,47 +115,70 @@ export async function deploy({ baseUrl, apiKey, user, pass, distDir, name, descr
116
115
  limit: 10
117
116
  });
118
117
 
119
- // 5. Clear existing files in one server-side transaction
120
- console.log('Clearing existing files...');
121
- await api.post(`${entityPath}/files/_clear`);
118
+ // 5. Open a staging library so the upload pass below doesn't touch what the
119
+ // app is currently serving.
120
+ console.log('Staging deploy...');
121
+ const stagingLibraryId = await openStagingDeploy(api, entityPath);
122
122
 
123
123
  // 6. Upload the app-library file set assembled in step 0: dist output at the
124
124
  // library root, plus informer.yaml / data-access.yaml and the
125
- // server/tools/mcp/migrations/webhooks/embeddings source trees, less any
125
+ // server/tools/mcp/cli/migrations/webhooks/embeddings source trees, less any
126
126
  // tree this server is too old to keep out of browsers (see compat.js).
127
127
  // Sourced from the shared collectAppFiles() so a deploy and a marketplace
128
128
  // publish package byte-identical contents.
129
- console.log('Uploading files...');
129
+ //
130
+ // Everything from here until the deploy completes runs inside the try, so
131
+ // nothing can leave the app staged: a live staging pointer redirects later
132
+ // content writes into a library nothing serves while reads keep returning
133
+ // the old build, and the routes that cannot redirect refuse with 409
134
+ // (I5-12961). `files` is declared outside the try so step 13 can still
135
+ // report on it once the staging lock has released.
130
136
  const files = plan.files;
137
+ let deployed = false;
138
+ const releaseStaging = installStagingSignalHandlers(api, entityPath, stagingLibraryId);
139
+ try {
140
+ console.log('Uploading files...');
131
141
 
132
- for (const { abs, rel } of files) {
133
- const content = await readFile(abs);
134
-
135
- if (content.length > CHUNK_THRESHOLD) {
136
- // Large file: chunked upload via Flow.js protocol
137
- await api.uploadChunked({
138
- entityPath,
139
- path: rel,
140
- buffer: content,
141
- filename: basename(abs)
142
- });
143
- console.log(` ${rel} (${formatSize(content.length)}, chunked)`);
144
- } else {
145
- // Small file: direct JSON upload
146
- const ext = '.' + rel.split('.').pop();
147
- const isText = TEXT_EXTENSIONS.has(ext.toLowerCase());
148
- const payload = isText
149
- ? { content: content.toString('utf8'), encoding: 'utf8' }
150
- : { content: content.toString('base64'), encoding: 'base64' };
151
-
152
- await api.put(`${entityPath}/contents/${rel}`, payload);
153
- console.log(` ${rel}`);
142
+ // Presented on every write so the server folds it into THIS deploy. A
143
+ // write that doesn't claim the staging library is refused rather than
144
+ // quietly joining it (see deploy-target.js). Empty on the _clear
145
+ // fallback, where there is no staging library to claim.
146
+ const claim = stagingLibraryId ? { stagingLibraryId } : {};
147
+
148
+ for (const { abs, rel } of files) {
149
+ const content = await readFile(abs);
150
+
151
+ if (content.length > CHUNK_THRESHOLD) {
152
+ // Large file: chunked upload via Flow.js protocol
153
+ await api.uploadChunked({
154
+ entityPath,
155
+ path: rel,
156
+ buffer: content,
157
+ filename: basename(abs),
158
+ stagingLibraryId
159
+ });
160
+ console.log(` ${rel} (${formatSize(content.length)}, chunked)`);
161
+ } else {
162
+ // Small file: direct JSON upload
163
+ const ext = '.' + rel.split('.').pop();
164
+ const isText = TEXT_EXTENSIONS.has(ext.toLowerCase());
165
+ const payload = isText
166
+ ? { content: content.toString('utf8'), encoding: 'utf8', ...claim }
167
+ : { content: content.toString('base64'), encoding: 'base64', ...claim };
168
+
169
+ await api.put(`${entityPath}/contents/${rel}`, payload);
170
+ console.log(` ${rel}`);
171
+ }
154
172
  }
155
- }
156
173
 
157
- // 12. Deploy: run migrations + scan/bundle server routes + webhooks + embeddings + tools + agents
158
- if (apiPrefix === 'apps') {
159
- await runServerDeploy(api, entityPath);
174
+ // 12. Deploy: run migrations + scan/bundle server routes + webhooks + embeddings + tools + agents
175
+ if (apiPrefix === 'apps') {
176
+ await runServerDeploy(api, entityPath, stagingLibraryId);
177
+ }
178
+ deployed = true;
179
+ } finally {
180
+ releaseStaging();
181
+ if (stagingLibraryId && !deployed) await discardStaging(api, entityPath, stagingLibraryId);
160
182
  }
161
183
 
162
184
  // 13. Print URL and return UUID for saving
@@ -170,6 +192,129 @@ export async function deploy({ baseUrl, apiKey, user, pass, distDir, name, descr
170
192
  return { id: entity.id, url: entityUrl };
171
193
  }
172
194
 
195
+ /**
196
+ * Discard this deploy's staged upload so a failure doesn't leave the app locked.
197
+ *
198
+ * Presents the id so a cleanup can never destroy a DIFFERENT deploy's in-flight
199
+ * upload, and is best-effort: the original failure is what the user needs to
200
+ * see, so a cleanup problem is reported but never replaces it.
201
+ *
202
+ * @param {Object} api - Informer API client
203
+ * @param {string} entityPath
204
+ * @param {string} stagingLibraryId
205
+ */
206
+ export async function discardStaging(api, entityPath, stagingLibraryId) {
207
+ try {
208
+ await api.del(`${entityPath}/files/_stage?stagingLibraryId=${encodeURIComponent(stagingLibraryId)}`);
209
+ console.log('Discarded the staged upload; the app is unchanged and editable.');
210
+ } catch (cleanupErr) {
211
+ console.log(`Could not discard the staged upload (${cleanupErr.message}).`);
212
+ console.log(`The app will keep redirecting content edits until it is cleared.`);
213
+ console.log(`Run: DELETE ${entityPath}/files/_stage`);
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Discard the staged upload if the process is interrupted.
219
+ *
220
+ * Ctrl-C during a long upload is an ordinary way to end a deploy, and without a
221
+ * handler it leaves the app staged with no cleanup at all. Returns a function
222
+ * that removes the handlers so a completed deploy doesn't keep them installed.
223
+ *
224
+ * @returns {Function} release
225
+ */
226
+ function installStagingSignalHandlers(api, entityPath, stagingLibraryId) {
227
+ if (!stagingLibraryId) return () => {};
228
+
229
+ // A second Ctrl-C during the cleanup await would re-enter and start a
230
+ // competing discard, so the first one wins and later signals exit at once.
231
+ let discarding = false;
232
+
233
+ const handlers = ['SIGINT', 'SIGTERM'].map((signal) => {
234
+ const handler = async () => {
235
+ if (discarding) {
236
+ console.log(`\nInterrupted again; exiting without waiting for the discard.`);
237
+ process.exit(130);
238
+ }
239
+ discarding = true;
240
+ console.log(`\nInterrupted (${signal}); discarding the staged upload...`);
241
+ await discardStaging(api, entityPath, stagingLibraryId);
242
+ process.exit(130);
243
+ };
244
+ process.on(signal, handler);
245
+ return { signal, handler };
246
+ });
247
+
248
+ return () => handlers.forEach(({ signal, handler }) => process.off(signal, handler));
249
+ }
250
+
251
+ /**
252
+ * POST `files/_stage`: open a staging library for this deploy.
253
+ *
254
+ * Everything uploaded afterwards lands in the staging library while the app
255
+ * goes on serving its current one; POST `_deploy`, given this library's id,
256
+ * then replaces the live library's files with the staged ones inside a single
257
+ * transaction. That is what keeps an app usable, and complete, for the
258
+ * whole length of its own deploy (I5-12961).
259
+ *
260
+ * Falls back to the old wipe-then-upload flow against a server with no _stage
261
+ * route. That flow is precisely what staging exists to avoid, so it announces
262
+ * itself rather than degrading silently.
263
+ *
264
+ * Note the null check rather than a try/catch: client.js turns a 404 into a
265
+ * `null` reply instead of throwing, so an unsupported route arrives here as a
266
+ * value, not an exception.
267
+ *
268
+ * @param {Object} api - Informer API client
269
+ * @param {string} entityPath - e.g. `apps/team:my-app`
270
+ * @returns {Promise<string|null>} staging library id to present at deploy time, or
271
+ * null when it fell back to _clear and there is nothing to promote
272
+ */
273
+ export async function openStagingDeploy(api, entityPath) {
274
+ let staged;
275
+ try {
276
+ staged = await api.post(`${entityPath}/files/_stage`);
277
+ } catch (err) {
278
+ // 409 means a previous deploy died and left its upload staged. The
279
+ // server refuses to stage over it (destroying it silently is how two
280
+ // deploys interleave), so the app stays locked until someone discards
281
+ // it — and this message is the only place that instruction appears.
282
+ if (err.status === 409) {
283
+ const base = api.baseUrl ? `${api.baseUrl}/api` : '<informer-url>/api';
284
+ throw new Error(
285
+ `${err.detail || 'This app already has a staged upload from an earlier deploy.'}\n\n`
286
+ + `A previous deploy did not finish and left its upload staged. Discard it, then re-run this deploy:\n`
287
+ + ` curl -u <user>:<pass> -X DELETE '${base}/${entityPath}/files/_stage'`
288
+ );
289
+ }
290
+ throw err;
291
+ }
292
+
293
+ // `null` means 404 and ONLY 404 — client.js returns it for a missing route
294
+ // and throws for every other non-ok status. Any other falsy-id reply is a
295
+ // server that DID stage, so it must not take the destructive branch.
296
+ if (staged === null) {
297
+ console.log(' Server does not support staged deploys; clearing files instead.');
298
+ console.log(' The app will be unavailable to its users until this deploy finishes.');
299
+ await api.post(`${entityPath}/files/_clear`);
300
+ return null;
301
+ }
302
+
303
+ if (!staged.id) {
304
+ // _stage SUCCEEDED, so the server has already pointed the app at a
305
+ // staging library this deploy cannot name. Clearing here would empty the
306
+ // live library while every upload silently redirected into that staging
307
+ // library, and the unclaimed deploy would then publish the empty one.
308
+ throw new Error(
309
+ `POST ${entityPath}/files/_stage succeeded but returned no library id `
310
+ + `(got: ${JSON.stringify(staged).slice(0, 200)}). The app now has a staging library `
311
+ + `this deploy cannot claim. Nothing was uploaded or cleared.`
312
+ );
313
+ }
314
+
315
+ return staged.id;
316
+ }
317
+
173
318
  /**
174
319
  * POST `_deploy`: run migrations, scan/bundle server routes, webhooks, tools and
175
320
  * agents, and claim the app as platform-managed.
@@ -179,8 +324,10 @@ export async function deploy({ baseUrl, apiKey, user, pass, distDir, name, descr
179
324
  *
180
325
  * @param {{post: (path: string, body?: unknown) => Promise<unknown>}} api
181
326
  * @param {string} entityPath e.g. `apps/my-app`
327
+ * @param {string} [stagingLibraryId] id returned by openStagingDeploy; presenting
328
+ * it is what authorises the server to promote that staged upload
182
329
  */
183
- export async function runServerDeploy(api, entityPath) {
330
+ export async function runServerDeploy(api, entityPath, stagingLibraryId) {
184
331
  try {
185
332
  console.log('Deploying...');
186
333
  // `managed: true` claims the app as platform-managed (origin
@@ -189,7 +336,13 @@ export async function runServerDeploy(api, entityPath) {
189
336
  // flag is absent, so the GO admin panel's Redeploy and the builder's
190
337
  // Save can share this route without converting user-built apps. See
191
338
  // app/routes/deploy.js.
192
- const result = await api.post(`${entityPath}/_deploy`, { managed: true });
339
+ // Presenting the staged id is what authorises the server to promote that
340
+ // upload. Omitting it (the _clear fallback path) leaves the server
341
+ // deploying the live library, which is the pre-staging behaviour.
342
+ const result = await api.post(`${entityPath}/_deploy`, {
343
+ managed: true,
344
+ ...(stagingLibraryId ? { stagingLibraryId } : {})
345
+ });
193
346
  if (result === null) {
194
347
  // api.post turns a 404 into null instead of throwing, so this is the
195
348
  // only place it can be caught. Files uploaded, but migrations, server
package/src/dev-bag.js CHANGED
@@ -74,7 +74,9 @@ export function buildDevUser(user) {
74
74
  *
75
75
  * @param {Object} opts
76
76
  * @param {string} opts.serverOrigin - Informer server origin
77
- * @param {string} opts.authHeader - Basic or Bearer auth header for /api calls
77
+ * @param {string|Function} opts.authHeader - Basic or Bearer auth header for
78
+ * /api calls, or a function answering the current one (a header from the
79
+ * CLI's sign-in is renewed, signed-in.js)
78
80
  * @param {string|null} opts.devWorkspaceId - workspace datasource id for query()
79
81
  * @param {string} opts.projectRoot - app project root
80
82
  * @param {Object} [opts.devBindings] - dev bindings for `target: app` / `target: pack` deps
@@ -90,6 +92,8 @@ export function buildDevUser(user) {
90
92
  * @returns {{ query: Function, apiFetch: Function, build: (opts?: { forwarding?: Object|null }) => Promise<{ manifest: Object, bag: Object }> }}
91
93
  */
92
94
  export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId, projectRoot, devBindings = {}, appToken = null, channels = createDevChannels(), logPrefix = '[app]', platform = devPlatform(), appId = null }) {
95
+ const header = () => (typeof authHeader === 'function' ? authHeader() : authHeader);
96
+
93
97
  // query() implementation — proxies to the workspace _sql endpoint
94
98
  async function query(sql, params) {
95
99
  if (!devWorkspaceId) {
@@ -98,7 +102,7 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
98
102
 
99
103
  const resp = await globalThis.fetch(`${serverOrigin}/api/datasources/${devWorkspaceId}/_sql`, {
100
104
  method: 'POST',
101
- headers: { 'Content-Type': 'application/json', Authorization: authHeader },
105
+ headers: { 'Content-Type': 'application/json', Authorization: header() },
102
106
  body: JSON.stringify({ sql, params: params || [] })
103
107
  });
104
108
 
@@ -178,7 +182,7 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
178
182
  }
179
183
 
180
184
  async function apiFetch(path, opts = {}) {
181
- return await fetchAs(authHeader, path, opts);
185
+ return await fetchAs(header(), path, opts);
182
186
  }
183
187
 
184
188
  // Cross-app request() targets /api/apps/<id>/view/_/<path>, whose auth accepts
@@ -188,11 +192,11 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
188
192
  // the app proxy's request() throws a pointed error instead of a bare 401.
189
193
  // appFetch also stamps x-informer-app-depth:1 so the target runs one hop deep
190
194
  // and enforces the same one-hop guard it does in production.
191
- const appAuth = appToken
195
+ const appAuth = () => (appToken
192
196
  ? `Bearer ${appToken}`
193
- : (authHeader && authHeader.startsWith('Bearer ') ? authHeader : null);
194
- const appFetch = appAuth
195
- ? async (path, opts = {}) => await fetchAs(appAuth, path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
197
+ : (header() && header().startsWith('Bearer ') ? header() : null));
198
+ const appFetch = appAuth()
199
+ ? async (path, opts = {}) => await fetchAs(appAuth(), path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
196
200
  : null;
197
201
 
198
202
  // notify/email — delivery is a console-logged no-op in dev, but the
@@ -222,7 +226,7 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
222
226
  async function build({ forwarding = null } = {}) {
223
227
  const manifest = await loadManifest(projectRoot);
224
228
  const deps = manifestBlock(manifest, 'dependencies');
225
- const context = buildDevContext({ deps, apiFetch, devBindings, appFetch, forwarding });
229
+ const context = buildDevContext({ deps, apiFetch, devBindings, appFetch, forwarding, serverOrigin });
226
230
  const env = manifestBlock(manifest, 'env');
227
231
 
228
232
  // emit() writes no app_event row in dev, but still relays a listed