@plitzi/sdk-server 0.38.24 → 0.39.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 (233) hide show
  1. package/CHANGELOG.md +152 -1
  2. package/README.md +55 -9
  3. package/dist/actions.d.ts +4 -1
  4. package/dist/actions.js +3 -2
  5. package/dist/auth.d.ts +2 -2
  6. package/dist/auth.js +5 -4
  7. package/dist/core/auth/api/accounts.d.ts +11 -0
  8. package/dist/core/auth/api/accounts.js +175 -0
  9. package/dist/core/auth/api/admin.d.ts +41 -0
  10. package/dist/core/auth/api/admin.js +146 -0
  11. package/dist/core/auth/api/context.d.ts +119 -0
  12. package/dist/core/auth/api/context.js +262 -0
  13. package/dist/core/auth/api/factors.d.ts +31 -0
  14. package/dist/core/auth/api/factors.js +209 -0
  15. package/dist/core/auth/api/index.d.ts +94 -0
  16. package/dist/core/auth/api/index.js +43 -0
  17. package/dist/core/auth/api/profile.d.ts +43 -0
  18. package/dist/core/auth/api/profile.js +243 -0
  19. package/dist/core/auth/api/session.d.ts +62 -0
  20. package/dist/core/auth/api/session.js +312 -0
  21. package/dist/core/auth/{api.d.ts → api/types.d.ts} +41 -195
  22. package/dist/core/auth/api/values.d.ts +67 -0
  23. package/dist/core/auth/api/values.js +90 -0
  24. package/dist/core/auth/createAuth.d.ts +49 -39
  25. package/dist/core/auth/createAuth.js +21 -1
  26. package/dist/core/auth/oauth/client.d.ts +2 -2
  27. package/dist/core/auth/oauth/client.js +6 -1
  28. package/dist/core/auth/oauth/index.d.ts +30 -7
  29. package/dist/core/auth/oauth/index.js +33 -14
  30. package/dist/core/auth/oauth/providers/github.js +1 -1
  31. package/dist/core/auth/oauth/providers/google.js +1 -1
  32. package/dist/core/auth/oauth/providers/oidc.d.ts +40 -0
  33. package/dist/core/auth/oauth/providers/oidc.js +197 -0
  34. package/dist/core/auth/oauth/state.d.ts +2 -0
  35. package/dist/core/auth/oauth/state.js +2 -0
  36. package/dist/core/auth/oauth/types.d.ts +21 -3
  37. package/dist/core/auth/oauth/types.js +4 -1
  38. package/dist/core/auth/routes.js +1 -1
  39. package/dist/core/auth/tokens.d.ts +3 -1
  40. package/dist/core/auth/tokens.js +2 -1
  41. package/dist/core/configSeam.d.ts +0 -4
  42. package/dist/core/configSeam.js +12 -1
  43. package/dist/core/createServer.js +16 -4
  44. package/dist/core/freePort.d.ts +10 -0
  45. package/dist/core/freePort.js +39 -1
  46. package/dist/core/handlers/socialRouteHandlers.d.ts +9 -1
  47. package/dist/core/handlers/socialRouteHandlers.js +46 -12
  48. package/dist/core/health.d.ts +1 -0
  49. package/dist/core/health.js +2 -1
  50. package/dist/core/http/stages/authRoutes.d.ts +6 -0
  51. package/dist/core/http/stages/authRoutes.js +42 -1
  52. package/dist/core/http/stages/images.js +5 -3
  53. package/dist/core/http/stages/livePages.js +1 -1
  54. package/dist/core/server/fleet/relay.js +9 -1
  55. package/dist/core/server/fleet/stores.d.ts +7 -0
  56. package/dist/core/server/fleet/stores.js +15 -2
  57. package/dist/core/server/pageServer.js +5 -1
  58. package/dist/core/services/realtime.js +4 -2
  59. package/dist/core/services/registry.js +7 -1
  60. package/dist/core/services/robotsTxt.d.ts +16 -0
  61. package/dist/core/services/robotsTxt.js +50 -0
  62. package/dist/core/services/servedSpace.d.ts +8 -0
  63. package/dist/core/services/servedSpace.js +16 -0
  64. package/dist/core/services/sitemapXml.d.ts +7 -0
  65. package/dist/core/services/sitemapXml.js +37 -0
  66. package/dist/functions-api.d.ts +69 -2
  67. package/dist/helpers/fileStore.d.ts +60 -0
  68. package/dist/helpers/fileStore.js +127 -0
  69. package/dist/helpers/outboundGuard.d.ts +32 -3
  70. package/dist/helpers/outboundGuard.js +50 -5
  71. package/dist/hosts/project/agentRuns.d.ts +24 -0
  72. package/dist/hosts/project/agentRuns.js +107 -0
  73. package/dist/hosts/project/laterAsks.d.ts +41 -0
  74. package/dist/hosts/project/laterAsks.js +117 -0
  75. package/dist/hosts/project/plugins.js +11 -4
  76. package/dist/hosts/project/serveProject.d.ts +8 -1
  77. package/dist/hosts/project/serveProject.js +81 -24
  78. package/dist/hosts/project/spaceFailure.d.ts +4 -0
  79. package/dist/hosts/project/spaceFailure.js +10 -0
  80. package/dist/hosts/project/watchSpace.d.ts +5 -5
  81. package/dist/hosts/project/watchSpace.js +15 -6
  82. package/dist/index.js +2 -2
  83. package/dist/kernel.js +1 -1
  84. package/dist/modules/actions/connectorWrite.js +3 -1
  85. package/dist/modules/actions/index.js +1 -1
  86. package/dist/modules/actions/jobs/fileQueue.d.ts +34 -0
  87. package/dist/modules/actions/jobs/fileQueue.js +72 -0
  88. package/dist/modules/actions/jobs/index.js +3 -3
  89. package/dist/modules/actions/jobs/memoryQueue.js +6 -215
  90. package/dist/modules/actions/jobs/queueDocument.d.ts +14 -0
  91. package/dist/modules/actions/jobs/queueDocument.js +22 -0
  92. package/dist/modules/actions/jobs/queueRules.d.ts +39 -0
  93. package/dist/modules/actions/jobs/queueRules.js +270 -0
  94. package/dist/modules/actions/moduleFor.js +2 -0
  95. package/dist/modules/actions/runtime/fileKv.d.ts +3 -1
  96. package/dist/modules/actions/runtime/fileKv.js +12 -98
  97. package/dist/modules/actions/runtime/guards.d.ts +19 -1
  98. package/dist/modules/actions/runtime/guards.js +10 -1
  99. package/dist/modules/actions/runtime/kvChange.d.ts +40 -0
  100. package/dist/modules/actions/runtime/kvChange.js +23 -1
  101. package/dist/modules/actions/runtime/kvList.d.ts +4 -0
  102. package/dist/modules/actions/runtime/kvList.js +5 -1
  103. package/dist/modules/actions/runtime/kvStore.js +15 -1
  104. package/dist/modules/actions/runtime/namespaceKv.js +2 -0
  105. package/dist/modules/actions/runtime/renderResolver.js +31 -5
  106. package/dist/modules/actions/runtime/runAction.js +16 -6
  107. package/dist/modules/actions/runtime/scope.js +11 -0
  108. package/dist/modules/actions/runtime/taskContext.js +11 -32
  109. package/dist/modules/actions/tasks/auth.js +2 -0
  110. package/dist/modules/actions/tasks/connector.js +6 -2
  111. package/dist/modules/actions/tasks/flow.js +5 -0
  112. package/dist/modules/actions/tasks/http.js +2 -1
  113. package/dist/modules/actions/tasks/kv.js +5 -0
  114. package/dist/modules/actions/tasks/list.js +11 -2
  115. package/dist/modules/actions/tasks/transform.js +2 -0
  116. package/dist/modules/actions/transport/callHandler.js +25 -4
  117. package/dist/modules/actions/types.d.ts +46 -1
  118. package/dist/modules/connectors/engine.d.ts +7 -2
  119. package/dist/modules/connectors/engine.js +4 -4
  120. package/dist/modules/connectors/resolver.d.ts +2 -1
  121. package/dist/modules/connectors/resolver.js +3 -2
  122. package/dist/modules/functions/build.d.ts +7 -2
  123. package/dist/modules/functions/build.js +90 -6
  124. package/dist/modules/functions/capabilities.js +16 -0
  125. package/dist/modules/functions/context.js +6 -2
  126. package/dist/modules/functions/contract.d.ts +39 -1
  127. package/dist/modules/functions/driver.d.ts +2 -1
  128. package/dist/modules/functions/driver.js +35 -0
  129. package/dist/modules/functions/load.d.ts +1 -1
  130. package/dist/modules/functions/load.js +2 -2
  131. package/dist/modules/functions/manifest.js +7 -1
  132. package/dist/modules/functions/oauth.d.ts +1 -1
  133. package/dist/modules/functions/oauth.js +4 -4
  134. package/dist/modules/functions/protocol.d.ts +6 -0
  135. package/dist/modules/functions/sandbox/guest/bytes.d.ts +27 -0
  136. package/dist/modules/functions/sandbox/guest/bytes.js +108 -0
  137. package/dist/modules/functions/sandbox/guest/crypto.d.ts +47 -0
  138. package/dist/modules/functions/sandbox/guest/crypto.js +144 -0
  139. package/dist/modules/functions/sandbox/guest/events.d.ts +152 -0
  140. package/dist/modules/functions/sandbox/guest/events.js +143 -0
  141. package/dist/modules/functions/sandbox/guest/fetch.d.ts +305 -0
  142. package/dist/modules/functions/sandbox/guest/fetch.js +237 -0
  143. package/dist/modules/functions/sandbox/guest/index.d.ts +28 -0
  144. package/dist/modules/functions/sandbox/guest/index.js +130 -0
  145. package/dist/modules/functions/sandbox/{guest.d.ts → guest/types.d.ts} +5 -12
  146. package/dist/modules/functions/sandbox/isolate.js +20 -6
  147. package/dist/modules/functions/space.js +2 -8
  148. package/dist/modules/images/imageProxy.d.ts +3 -2
  149. package/dist/modules/images/imageProxy.js +2 -2
  150. package/dist/modules/mongo/jobQueue.js +0 -19
  151. package/dist/modules/mysql/accounts.js +12 -5
  152. package/dist/modules/mysql/jobs/index.d.ts +1 -1
  153. package/dist/modules/mysql/jobs/schema.d.ts +0 -6
  154. package/dist/modules/mysql/jobs/schema.js +2 -46
  155. package/dist/modules/mysql/schema.js +26 -1
  156. package/dist/modules/mysql/sessions.js +2 -1
  157. package/dist/modules/realtime/handlers.d.ts +9 -4
  158. package/dist/modules/realtime/handlers.js +20 -3
  159. package/dist/modules/realtime/hub.d.ts +4 -2
  160. package/dist/modules/realtime/hub.js +36 -4
  161. package/dist/modules/realtime/index.d.ts +14 -0
  162. package/dist/modules/realtime/index.js +14 -1
  163. package/dist/modules/realtime/presence.d.ts +33 -0
  164. package/dist/modules/realtime/presence.js +56 -0
  165. package/dist/modules/realtime/socket.d.ts +3 -1
  166. package/dist/modules/realtime/socket.js +2 -2
  167. package/dist/modules/rsc/connectorRscData.d.ts +6 -1
  168. package/dist/modules/rsc/connectorRscData.js +27 -6
  169. package/dist/modules/rsc/externalQueryReader.d.ts +28 -0
  170. package/dist/modules/rsc/externalQueryReader.js +43 -0
  171. package/dist/modules/rsc/handler.js +1 -1
  172. package/dist/modules/rsc/resolveRscData.d.ts +11 -1
  173. package/dist/modules/rsc/resolveRscData.js +86 -16
  174. package/dist/modules/runtime/inside.js +1 -1
  175. package/dist/modules/runtime/runner.js +2 -1
  176. package/dist/modules/sqlite/jobQueue.d.ts +35 -0
  177. package/dist/modules/sqlite/jobQueue.js +56 -0
  178. package/dist/modules/sqlite/kv.d.ts +1 -1
  179. package/dist/modules/sqlite/kv.js +2 -10
  180. package/dist/modules/sqlite/open.d.ts +3 -0
  181. package/dist/modules/sqlite/open.js +13 -0
  182. package/dist/modules/ssr/Component.d.ts +5 -1
  183. package/dist/modules/ssr/Component.js +3 -1
  184. package/dist/modules/ssr/applySSRResult.d.ts +8 -1
  185. package/dist/modules/ssr/applySSRResult.js +23 -3
  186. package/dist/modules/ssr/handler.js +30 -5
  187. package/dist/modules/ssr/prepareRender.js +27 -5
  188. package/dist/modules/ssr/preview.d.ts +2 -0
  189. package/dist/modules/ssr/preview.js +6 -3
  190. package/dist/modules/ssr/registerExternalPlugins.d.ts +2 -6
  191. package/dist/modules/ssr/registerExternalPlugins.js +2 -2
  192. package/dist/modules/ssr/resolvePageSeo.d.ts +11 -0
  193. package/dist/modules/ssr/resolvePageSeo.js +13 -2
  194. package/dist/modules/ssr/streamBody.js +2 -2
  195. package/dist/modules/ssr/views/template.ejs +21 -17
  196. package/dist/mysql.d.ts +1 -1
  197. package/dist/mysql.js +2 -2
  198. package/dist/plugins/manager.d.ts +5 -0
  199. package/dist/plugins/manager.js +9 -0
  200. package/dist/sqlite.d.ts +8 -1
  201. package/dist/sqlite.js +3 -1
  202. package/package.json +5 -5
  203. package/skills/plitzi-authoring/CHEATSHEET.md +6 -6
  204. package/skills/plitzi-authoring/SKILL.md +4 -2
  205. package/skills/plitzi-authoring/recipes/accordion.ts +2 -1
  206. package/skills/plitzi-authoring/recipes/carousel.ts +24 -3
  207. package/skills/plitzi-authoring/recipes/detail-page.ts +0 -1
  208. package/skills/plitzi-authoring/recipes/embed-and-svg.ts +3 -1
  209. package/skills/plitzi-authoring/recipes/filter-a-list.ts +0 -1
  210. package/skills/plitzi-authoring/recipes/show-data.ts +0 -1
  211. package/skills/plitzi-authoring/recipes/typed-data.ts +0 -1
  212. package/skills/plitzi-authoring/reference/accessibility.md +7 -2
  213. package/skills/plitzi-authoring/reference/auth.md +15 -4
  214. package/skills/plitzi-authoring/reference/authoring-errors.md +51 -10
  215. package/skills/plitzi-authoring/reference/colours-and-motion.md +7 -1
  216. package/skills/plitzi-authoring/reference/components.md +4 -1
  217. package/skills/plitzi-authoring/reference/data-and-visibility.md +31 -22
  218. package/skills/plitzi-authoring/reference/efficiency.md +2 -1
  219. package/skills/plitzi-authoring/reference/elements-and-styles.md +16 -15
  220. package/skills/plitzi-authoring/reference/flows.md +20 -8
  221. package/skills/plitzi-authoring/reference/kept-state.md +8 -0
  222. package/skills/plitzi-authoring/reference/layouts.md +18 -2
  223. package/skills/plitzi-authoring/reference/lists.md +20 -4
  224. package/skills/plitzi-authoring/reference/plugin-reach.md +12 -0
  225. package/skills/plitzi-authoring/reference/plugins.md +13 -2
  226. package/skills/plitzi-authoring/reference/realtime.md +8 -5
  227. package/skills/plitzi-authoring/reference/structure.md +17 -1
  228. package/skills/plitzi-authoring/reference/templates.md +11 -3
  229. package/skills/plitzi-authoring/reference/testing.md +82 -5
  230. package/skills/plitzi-authoring/reference/typed-sources.md +6 -0
  231. package/skills/plitzi-authoring/reference/validation.md +1 -1
  232. package/dist/core/auth/api.js +0 -1323
  233. package/dist/modules/functions/sandbox/guest.js +0 -662
@@ -1,42 +1,61 @@
1
1
  import { consoleLogger } from "../../helpers/serverLog.js";
2
2
  import { isFleetWorker } from "../../core/server/fleet/role.js";
3
+ import { fleetJobQueue, fleetKv } from "../../core/server/fleet/stores.js";
3
4
  import { oauthCallbackUrlOn } from "../../modules/functions/oauth.js";
4
5
  import { loadFunctions } from "../../modules/functions/load.js";
5
6
  import { createServer as createServer$1 } from "../../core/createServer.js";
6
7
  import { closeOnSignals } from "../../core/server/closeOnSignals.js";
7
- import { freePort } from "../../core/freePort.js";
8
+ import { reservePort } from "../../core/freePort.js";
8
9
  import { createCloudAdapters } from "../../adapters/cloudAdapters.js";
9
10
  import { createJsonAdapters } from "../../adapters/jsonAdapters.js";
11
+ import { createFileJobQueue } from "../../modules/actions/jobs/fileQueue.js";
10
12
  import { createFileKv } from "../../modules/actions/runtime/fileKv.js";
11
13
  import { credentialsFromEnv } from "../../modules/actions/runtime/credentials.js";
12
14
  import { reachOwnServer } from "../../modules/runtime/inside.js";
13
15
  import { loadRuntime, loadRuntimeModule } from "../../modules/runtime/bundle.js";
14
16
  import { serveRuntime } from "../../modules/runtime/stages.js";
17
+ import { runReportStage, runStatusStage, watchAgentRuns } from "./agentRuns.js";
18
+ import { watchLaterAsks } from "./laterAsks.js";
15
19
  import { projectPlugins, watchProjectPlugins } from "./plugins.js";
16
20
  import { createSpaceFailure } from "./spaceFailure.js";
17
21
  import { watchSpace } from "./watchSpace.js";
18
- import { fleetKv } from "../../core/server/fleet/stores.js";
22
+ import { isRecord } from "@plitzi/sdk-shared/helpers";
23
+ import { isIP } from "node:net";
19
24
  import { X509Certificate } from "node:crypto";
20
25
  import { hostname, networkInterfaces } from "node:os";
21
- import { isIP } from "node:net";
22
26
  import path from "node:path";
23
27
  import { EMPTY_SCHEMA } from "@plitzi/sdk-shared/schema";
24
28
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
25
29
  import { EMPTY_STYLE_SCHEMA } from "@plitzi/sdk-shared/style";
26
- import { DATA_DIR, DEV_SERVER_FILE, FUNCTIONS_DIR, KV_FILE, PROJECT_TMP, PUBLIC_DIR, RUNTIME_BUNDLE, RUNTIME_ENTRY, assertProjectLayout, layoutFindingText, localNetworkName, networkAddresses, projectModule, projectRoot } from "@plitzi/sdk-shared/project";
30
+ import { DATA_DIR, DEV_SERVER_FILE, FUNCTIONS_DIR, JOBS_FILE, KV_FILE, PROJECT_STATE, PROJECT_TMP, PUBLIC_DIR, RUNTIME_BUNDLE, RUNTIME_ENTRY, SERVER_RECORD_ENV, STATE_DIR_ENV, assertProjectLayout, layoutFindingText, localNetworkName, networkAddresses, projectMark, projectModule, projectRoot } from "@plitzi/sdk-shared/project";
31
+ import { RUN_REPORTS_ENV, RUN_STATUS_ENV } from "@plitzi/sdk-shared/runs";
27
32
  //#region src/hosts/project/serveProject.ts
28
33
  /**
29
34
  * The errors whose message is the whole report — every problem, where it is and what to write instead — and whose
30
35
  * stack would only point inside the SDK: the project's root, its layout, a space module with no space, a space that does
31
- * not author. Told by name, since each package that throws one carries its own copy of the class.
36
+ * not author, a state file another server of the folder holds. Told by name, since each package that throws one carries its own copy of the class.
32
37
  */
33
38
  var REPORTS = /* @__PURE__ */ new Set([
34
39
  "ProjectRootError",
35
40
  "ProjectLayoutError",
36
41
  "ProjectSpaceError",
37
- "SpaceRefusedError"
42
+ "SpaceRefusedError",
43
+ "SpacePreviewError",
44
+ "FileInUseError"
38
45
  ]);
39
- var isReport = (error) => error instanceof Error && REPORTS.has(error.name);
46
+ var isStartupReport = (error) => error instanceof Error && REPORTS.has(error.name);
47
+ /**
48
+ * A second server of the project, started while the first runs, said as what it is: the project already served, where,
49
+ * since when, and how to stop it — where it said a state file was in use by a process, with a stack (the maintainer: "debería
50
+ * ser más amigable"). Undefined for a holder that serves nothing, whose own report is said as it is.
51
+ */
52
+ var alreadyServed = (error) => {
53
+ const holder = Reflect.get(error, "holder");
54
+ if (error.name !== "FileInUseError" || !isRecord(holder) || typeof holder.serves !== "string") return;
55
+ const port = new URL(holder.serves).port;
56
+ const since = typeof holder.since === "string" ? holder.since.slice(11, 16) : "";
57
+ return [`This project is already running at ${holder.serves}${typeof holder.pid === "number" ? ` (process ${String(holder.pid)}${since ? `, since ${since} UTC` : ""})` : ""}.`, `Open it there — or stop it before starting another: Ctrl+C in its terminal, or plitzi server stop${port ? ` --port ${port}` : ""}.`].join("\n");
58
+ };
40
59
  var ENVIRONMENTS = [
41
60
  "main",
42
61
  "production",
@@ -154,7 +173,7 @@ var spaceToServe = async ({ space, cloud }, developing, root) => {
154
173
  } catch (error) {
155
174
  if (!developing) throw error;
156
175
  return {
157
- failure: isReport(error) ? error.message : error instanceof Error ? error.stack ?? error.message : String(error),
176
+ failure: isStartupReport(error) ? error.message : error instanceof Error ? error.stack ?? error.message : String(error),
158
177
  name: path.basename(root)
159
178
  };
160
179
  }
@@ -174,7 +193,8 @@ var startProject = async (options) => {
174
193
  });
175
194
  if (developing) for (const warning of layout) console.warn(`[layout] ${layoutFindingText(warning)}`);
176
195
  const host = process.env.HOST ?? "127.0.0.1";
177
- const port = process.env.PORT ? Number(process.env.PORT) : developing ? await freePort(8080, host) : 8080;
196
+ const reserved = !process.env.PORT && developing ? await reservePort(8080, host) : void 0;
197
+ const port = process.env.PORT ? Number(process.env.PORT) : reserved?.port ?? 8080;
178
198
  const tls = serverOptions.tls ?? tlsFromEnv(root);
179
199
  const scheme = tls ? "https" : "http";
180
200
  const localUrl = `${scheme}://${urlHost(localAddress(host))}:${String(port)}`;
@@ -225,14 +245,30 @@ var startProject = async (options) => {
225
245
  env: process.env,
226
246
  publicUrl
227
247
  });
248
+ const holder = `the server of "${name}", on port ${String(port)} (plitzi server stop --port ${String(port)} stops it)`;
228
249
  let keptKv;
229
- const kv = fleetKv(() => {
250
+ const stateDir = path.resolve(root, process.env[STATE_DIR_ENV] || PROJECT_STATE);
251
+ const kv = serverOptions.action?.kv ?? fleetKv(() => {
230
252
  keptKv = createFileKv({
231
- file: path.join(root, KV_FILE),
232
- owner: `the server of "${name}", on port ${String(port)}`
253
+ file: path.join(stateDir, path.basename(KV_FILE)),
254
+ owner: holder,
255
+ serves: localUrl
233
256
  });
234
257
  return keptKv;
235
258
  });
259
+ let keptJobs;
260
+ const jobsConfig = serverOptions.action?.jobs;
261
+ const jobs = jobsConfig === false ? false : {
262
+ ...jobsConfig,
263
+ queue: jobsConfig?.queue ?? fleetJobQueue(() => {
264
+ keptJobs = createFileJobQueue({
265
+ file: path.join(stateDir, path.basename(JOBS_FILE)),
266
+ owner: holder,
267
+ serves: localUrl
268
+ });
269
+ return keptJobs;
270
+ })
271
+ };
236
272
  const server = createServer$1({
237
273
  logLevel: process.argv.includes("--verbose") ? "info" : "warn",
238
274
  logger: consoleLogger,
@@ -241,7 +277,11 @@ var startProject = async (options) => {
241
277
  port,
242
278
  devMode: serverOptions.devMode ?? developing,
243
279
  livePages: serverOptions.livePages ?? serverOptions.devMode ?? developing,
244
- health: { name },
280
+ health: {
281
+ name,
282
+ instance: projectMark(root),
283
+ check: spaceFailure.health
284
+ },
245
285
  adapters,
246
286
  plugins: plugins.sources,
247
287
  publicDir: path.join(root, PUBLIC_DIR),
@@ -255,16 +295,24 @@ var startProject = async (options) => {
255
295
  signingSecret: process.env.PLITZI_SIGNING_SECRET,
256
296
  kv,
257
297
  ...serverOptions.action,
298
+ jobs,
258
299
  ...actions ? { lookups: actionLookups(actions, connectors, credentialsFromEnv()) } : {}
259
300
  }
260
301
  }, {
261
- preAuth: [spaceFailure.stage],
302
+ preAuth: [
303
+ spaceFailure.stage,
304
+ ...developing && process.env[RUN_STATUS_ENV] ? [runStatusStage(process.env[RUN_STATUS_ENV])] : [],
305
+ ...developing && process.env[RUN_REPORTS_ENV] ? [runReportStage(process.env[RUN_REPORTS_ENV])] : []
306
+ ],
262
307
  data: runtime ? [runtime.stage] : []
263
308
  });
264
309
  await server.listen(port, host);
310
+ reserved?.release();
265
311
  if (speaks) {
266
312
  mkdirSync(path.join(root, PROJECT_TMP), { recursive: true });
267
- writeFileSync(path.join(root, DEV_SERVER_FILE), `${JSON.stringify({
313
+ const record = process.env[SERVER_RECORD_ENV] || DEV_SERVER_FILE;
314
+ mkdirSync(path.dirname(path.join(root, record)), { recursive: true });
315
+ writeFileSync(path.join(root, record), `${JSON.stringify({
268
316
  name,
269
317
  port,
270
318
  url: localUrl,
@@ -280,16 +328,25 @@ var startProject = async (options) => {
280
328
  }
281
329
  if (reached.unnamed.length > 0) console.warn(`[tls] the certificate does not name ${reached.unnamed.join(", ")}: a device that opens it there is refused — \`plitzi cert\` makes one for this machine as it is now`);
282
330
  }
283
- const watching = developing ? [...held ? [watchSpace(root, (authored) => {
284
- held.documents = authored;
285
- spaceFailure.clear();
286
- server.updatePages(authored);
287
- })] : [], watchProjectPlugins(root, server, plugins)] : [];
331
+ const watching = developing ? [
332
+ ...held ? [watchSpace(root, (authored) => {
333
+ held.documents = authored;
334
+ spaceFailure.clear();
335
+ server.updatePages(authored);
336
+ }, (why) => {
337
+ if (held.documents) spaceFailure.stale(why);
338
+ else spaceFailure.fail(why);
339
+ })] : [],
340
+ watchProjectPlugins(root, server, plugins),
341
+ ...speaks ? [watchAgentRuns(root)] : [],
342
+ ...speaks && jobs !== false ? [watchLaterAsks(root, () => jobs.queue, SPACE_ID)] : []
343
+ ] : [];
288
344
  const close = async () => {
289
345
  watching.forEach((stop) => stop());
290
346
  await server.close();
291
347
  await runtime?.close();
292
348
  await keptKv?.close();
349
+ await keptJobs?.close();
293
350
  };
294
351
  const stopListening = closeOnSignals({ close });
295
352
  return {
@@ -321,7 +378,7 @@ var startProject = async (options) => {
321
378
  * - a signal closes it, finishing what runs.
322
379
  *
323
380
  * While developing (`NODE_ENV` other than `production`), a save to the space is authored again by the project's
324
- * `plitzi/author.ts`, in a process of its own, which hands the documents back over IPC: the server swaps them in memory
381
+ * `.plitzi/author.ts`, in a process of its own, which hands the documents back over IPC: the server swaps them in memory
325
382
  * and every open page loads again. A plugin folder added is registered, one removed turned off, and a plugin's
326
383
  * `functions/` loaded again; a folder it cannot build is said in the terminal, and the server goes on.
327
384
  */
@@ -329,11 +386,11 @@ var serveProject = async (options) => {
329
386
  try {
330
387
  return await startProject(options);
331
388
  } catch (error) {
332
- if (!isReport(error)) throw error;
333
- console.error(error.message);
389
+ if (!isStartupReport(error)) throw error;
390
+ console.error(alreadyServed(error) ?? error.message);
334
391
  process.exitCode = 1;
335
392
  process.exit(1);
336
393
  }
337
394
  };
338
395
  //#endregion
339
- export { serveProject };
396
+ export { alreadyServed, isStartupReport, serveProject };
@@ -3,6 +3,10 @@ export declare const createSpaceFailure: () => {
3
3
  stage: Stage;
4
4
  /** The space did not author: every page says why, until it does. */
5
5
  fail: (message: string) => void;
6
+ /** A save did not author: the last space that did is still served, and this is why it is not the saved one. */
7
+ stale: (message: string) => void;
8
+ /** What `/health` adds while a save has not authored: why the page is the space as it last authored. */
9
+ health: () => Record<string, unknown>;
6
10
  /** It authored: the pages are the space's again. */
7
11
  clear: () => void;
8
12
  };
@@ -1,5 +1,6 @@
1
1
  import { LIVE_PAGES_PATH } from "../../core/http/stages/livePages.js";
2
2
  import { escapeHtml } from "../../helpers/escapeHtml.js";
3
+ import { SPACE_FAILURE_META } from "@plitzi/sdk-shared/devTools";
3
4
  //#region src/hosts/project/spaceFailure.ts
4
5
  /**
5
6
  * The page a project's server answers with while its space does not author — while developing only.
@@ -15,6 +16,7 @@ var pageOf = (message) => `<!doctype html>
15
16
  <head>
16
17
  <meta charset="utf-8">
17
18
  <meta name="viewport" content="width=device-width, initial-scale=1">
19
+ <meta name="${SPACE_FAILURE_META}" content="1">
18
20
  <title>The space does not author</title>
19
21
  <style>
20
22
  :root { color-scheme: light dark; }
@@ -52,6 +54,7 @@ var pageOf = (message) => `<!doctype html>
52
54
  var asksForPage = (method, accept) => method === "GET" && [accept].flat().some((value) => value?.includes("text/html"));
53
55
  var createSpaceFailure = () => {
54
56
  let failure;
57
+ let stale;
55
58
  const stage = (ctx) => {
56
59
  if (failure === void 0 || !asksForPage(ctx.req.method, ctx.req.headers.accept)) return Promise.resolve(false);
57
60
  ctx.res.setStatus(503);
@@ -66,9 +69,16 @@ var createSpaceFailure = () => {
66
69
  fail: (message) => {
67
70
  failure = message;
68
71
  },
72
+ /** A save did not author: the last space that did is still served, and this is why it is not the saved one. */
73
+ stale: (message) => {
74
+ stale = message;
75
+ },
76
+ /** What `/health` adds while a save has not authored: why the page is the space as it last authored. */
77
+ health: () => stale === void 0 ? {} : { spaceStale: stale },
69
78
  /** It authored: the pages are the space's again. */
70
79
  clear: () => {
71
80
  failure = void 0;
81
+ stale = void 0;
72
82
  }
73
83
  };
74
84
  };
@@ -5,10 +5,10 @@ export type AuthoredDocuments = {
5
5
  style: Style;
6
6
  };
7
7
  /**
8
- * A save to the space, while developing: re-authored by the project's `plitzi/author.ts` in a process of its own — the
8
+ * A save to the space, while developing: re-authored by the project's `.plitzi/author.ts` in a process of its own — the
9
9
  * only way to read every file of it again, which an import never does twice — and handed over IPC (`--ipc`), so
10
- * `onAuthored` swaps the documents the server serves. What it refuses is printed by the script, and the page keeps
11
- * the last space that authored. Saves in quick succession author once; one during a run, once more after it. Answers
12
- * what stops watching.
10
+ * `onAuthored` swaps the documents the server serves. What it refuses is printed by the script, and handed to
11
+ * `onRefused`: the page keeps the last space that authored. Saves in quick succession author once; one during a run,
12
+ * once more after it. Answers what stops watching.
13
13
  */
14
- export declare const watchSpace: (root: string, onAuthored: (documents: AuthoredDocuments) => void) => (() => void);
14
+ export declare const watchSpace: (root: string, onAuthored: (documents: AuthoredDocuments) => void, onRefused: (why: string) => void) => (() => void);
@@ -15,14 +15,16 @@ var isAuthoredDocuments = (message) => isRecord(message) && isRecord(message.sch
15
15
  * its declaration — its component is swapped in the open pages by the server itself.
16
16
  */
17
17
  var authored = (file) => file !== "main.ts" && !/^(config|actions|connectors|functions|runtime)([\\/]|$)/.test(file) && (!/^plugins([\\/]|$)/.test(file) || path.basename(file) === "declaration.ts");
18
+ /** The most of what a refusing script printed that is kept to say why: its report starts with what matters. */
19
+ var SAID_MOST = 4e3;
18
20
  /**
19
- * A save to the space, while developing: re-authored by the project's `plitzi/author.ts` in a process of its own — the
21
+ * A save to the space, while developing: re-authored by the project's `.plitzi/author.ts` in a process of its own — the
20
22
  * only way to read every file of it again, which an import never does twice — and handed over IPC (`--ipc`), so
21
- * `onAuthored` swaps the documents the server serves. What it refuses is printed by the script, and the page keeps
22
- * the last space that authored. Saves in quick succession author once; one during a run, once more after it. Answers
23
- * what stops watching.
23
+ * `onAuthored` swaps the documents the server serves. What it refuses is printed by the script, and handed to
24
+ * `onRefused`: the page keeps the last space that authored. Saves in quick succession author once; one during a run,
25
+ * once more after it. Answers what stops watching.
24
26
  */
25
- var watchSpace = (root, onAuthored) => {
27
+ var watchSpace = (root, onAuthored, onRefused) => {
26
28
  let timer;
27
29
  let running;
28
30
  let again = false;
@@ -34,27 +36,34 @@ var watchSpace = (root, onAuthored) => {
34
36
  return;
35
37
  }
36
38
  let documents;
39
+ let said = "";
37
40
  const child = spawn(process.execPath, [path.join(root, AUTHOR_FILE), "--ipc"], {
38
41
  cwd: root,
39
42
  stdio: [
40
43
  "inherit",
41
44
  "inherit",
42
- "inherit",
45
+ "pipe",
43
46
  "ipc"
44
47
  ]
45
48
  });
46
49
  running = child;
50
+ child.stderr?.on("data", (chunk) => {
51
+ process.stderr.write(chunk);
52
+ said = `${said}${chunk.toString("utf8")}`.slice(0, SAID_MOST);
53
+ });
47
54
  child.on("message", (message) => {
48
55
  if (isAuthoredDocuments(message)) documents = message;
49
56
  });
50
57
  child.on("error", (error) => {
51
58
  console.error(`[author] ${AUTHOR_FILE} did not run: ${error.message}`);
59
+ onRefused(`${AUTHOR_FILE} did not run: ${error.message}`);
52
60
  });
53
61
  child.on("close", (code) => {
54
62
  running = void 0;
55
63
  if (stopped) return;
56
64
  if (code === 0 && documents) onAuthored(documents);
57
65
  else if (code === 0) console.error(`[author] ${AUTHOR_FILE} authored the space and handed nothing over: it is older than this server — npx plitzi upgrade files --write`);
66
+ else onRefused(said.trim() || `${AUTHOR_FILE} exited with ${String(code)} and said nothing`);
58
67
  if (again) {
59
68
  again = false;
60
69
  author();
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { consoleLogger, isLogged, logLevelOf, renderLogEvent, serverLog } from "./helpers/serverLog.js";
2
+ import { PREVIEW_TOKEN_PARAM } from "./core/previewToken.js";
3
+ import { createMemoryDraftStore, takeDraftOverride } from "./modules/ssr/preview.js";
2
4
  import { fetchConnectorRecords, rebaseMedia, writeConnectorRecord } from "./modules/connectors/engine.js";
3
5
  import { createMemoryPubSub } from "./modules/realtime/memoryPubSub.js";
4
6
  import { createConnectorResolver } from "./modules/connectors/resolver.js";
5
7
  import { resolveRscData } from "./modules/rsc/resolveRscData.js";
6
8
  import { loadFunctions, loadFunctionsSource, readFunctionsDir } from "./modules/functions/load.js";
7
- import { PREVIEW_TOKEN_PARAM } from "./core/previewToken.js";
8
- import { createMemoryDraftStore, takeDraftOverride } from "./modules/ssr/preview.js";
9
9
  import { resolveServices } from "./core/services/resolve.js";
10
10
  import { buildHealthPayload, registerHealthCheck } from "./core/health.js";
11
11
  import { createServer } from "./core/createServer.js";
package/dist/kernel.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { consoleLogger, isLogged, logLevelOf, renderLogEvent, serverLog } from "./helpers/serverLog.js";
2
2
  import { assertOutboundAllowed, isBlockedHost } from "./helpers/outboundGuard.js";
3
+ import { PREVIEW_TOKEN_PARAM } from "./core/previewToken.js";
3
4
  import { clientIp, parseRequest, readRawBody, requestOrigin } from "./core/requestParser.js";
4
5
  import { createHttpServer } from "./core/server/baseServer.js";
5
- import { PREVIEW_TOKEN_PARAM } from "./core/previewToken.js";
6
6
  import { makeHandler } from "./core/http/dispatcher.js";
7
7
  import { buildHealthPayload, registerHealthCheck } from "./core/health.js";
8
8
  import { healthStage } from "./core/http/stages/health.js";
@@ -1,4 +1,5 @@
1
1
  import { serverLog } from "../../helpers/serverLog.js";
2
+ import { privateOriginsOf } from "../../helpers/outboundGuard.js";
2
3
  import { writeConnectorRecord } from "../connectors/engine.js";
3
4
  //#region src/modules/actions/connectorWrite.ts
4
5
  var parseBody = (body) => {
@@ -66,7 +67,8 @@ var handleAction = async (req, res, config, lookups) => {
66
67
  resource,
67
68
  recordId: body.recordId,
68
69
  values: body.values,
69
- fetchImpl: lookups.fetchImpl
70
+ fetchImpl: lookups.fetchImpl,
71
+ outbound: { privateOrigins: privateOriginsOf(config.outbound?.privateOrigins) }
70
72
  });
71
73
  res.setStatus(200);
72
74
  res.setHeader("Content-Type", "application/json; charset=utf-8");
@@ -4,11 +4,11 @@ import "./jobs/scheduler.js";
4
4
  import "./runtime/errors.js";
5
5
  import "./jobs/worker.js";
6
6
  import { fleetStore } from "../../core/server/fleet/link.js";
7
+ import { KV_METHODS, createMemoryKv } from "./runtime/memoryKv.js";
7
8
  import { createActionJobs } from "./jobs/index.js";
8
9
  import { createRunGuards } from "./runtime/guards.js";
9
10
  import { createKvStore } from "./runtime/kvStore.js";
10
11
  import { resolveLimits } from "./runtime/limits.js";
11
- import { KV_METHODS, createMemoryKv } from "./runtime/memoryKv.js";
12
12
  import { namespaceKv, spaceKvPatterns } from "./runtime/namespaceKv.js";
13
13
  import "./runtime/precheck.js";
14
14
  import { createActionRunner } from "./runtime/runAction.js";
@@ -0,0 +1,34 @@
1
+ import { JobQueue } from '@plitzi/sdk-shared';
2
+ export type FileJobQueueOptions = {
3
+ /** The JSON file the queue lives in — created, with its folder, on the first change. */
4
+ file: string;
5
+ /** Who holds it, said to a second process that tries: `the server of "acme", on port 8080`. */
6
+ owner?: string;
7
+ /** Where the process that holds it answers, for a second one to be pointed there: `http://localhost:8080`. */
8
+ serves?: string;
9
+ /** How many finished jobs to keep before the oldest are dropped. Default 500. */
10
+ retainFinished?: number;
11
+ /** What the queue calls now, in epoch ms. */
12
+ clock?: () => number;
13
+ };
14
+ export type FileJobQueue = JobQueue & {
15
+ /** Resolves once everything changed so far is on disk: for a shutdown, or a test that reads the file. */
16
+ flush: () => Promise<void>;
17
+ /** Writes what is pending and lets go of the file, for the next process to take. */
18
+ close: () => Promise<void>;
19
+ };
20
+ /**
21
+ * The job queue in one JSON file: what `ctx.later`, a schedule's fires and a function's jobs wait in, surviving a
22
+ * restart — for a deployment with no database. A job due while the server was down runs once it is back; one a worker
23
+ * held when it went down is taken again, its attempt written `lost`.
24
+ *
25
+ * ```ts
26
+ * createServer({ action: { jobs: { queue: createFileJobQueue({ file: 'state/jobs.json' }) } } });
27
+ * ```
28
+ *
29
+ * The rules are the in-process queue's, to the letter (`queueRules`): the file is only where its state is kept, written
30
+ * whole after each change that changed something, as `createFileKv` writes its own. ONE process holds the file
31
+ * (`<file>.lock`); the workers of one server reach the primary's through the fleet (`fleetJobQueue`); replicas share
32
+ * `createSqliteJobQueue` (`@plitzi/sdk-server/sqlite`) or a database's queue.
33
+ */
34
+ export declare const createFileJobQueue: ({ file, owner, serves, retainFinished, clock }: FileJobQueueOptions) => FileJobQueue;
@@ -0,0 +1,72 @@
1
+ import { applyRule, changedBy, emptyState, queueOver, queueRules } from "./queueRules.js";
2
+ import { documentOf, stateOf } from "./queueDocument.js";
3
+ import { documentWriter, holdFile, letGo } from "../../../helpers/fileStore.js";
4
+ import fs from "node:fs";
5
+ //#region src/modules/actions/jobs/fileQueue.ts
6
+ var load = (file) => {
7
+ if (!fs.existsSync(file)) return emptyState();
8
+ const refuse = (why) => /* @__PURE__ */ new Error(`createFileJobQueue: ${file} is not a queue it wrote (${why}). Move it aside, or point \`file\` elsewhere.`);
9
+ let parsed;
10
+ try {
11
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
12
+ } catch (error) {
13
+ throw refuse(error instanceof Error ? error.message : String(error));
14
+ }
15
+ const state = stateOf(parsed);
16
+ if (typeof state === "string") throw refuse(state);
17
+ return state;
18
+ };
19
+ /**
20
+ * The job queue in one JSON file: what `ctx.later`, a schedule's fires and a function's jobs wait in, surviving a
21
+ * restart — for a deployment with no database. A job due while the server was down runs once it is back; one a worker
22
+ * held when it went down is taken again, its attempt written `lost`.
23
+ *
24
+ * ```ts
25
+ * createServer({ action: { jobs: { queue: createFileJobQueue({ file: 'state/jobs.json' }) } } });
26
+ * ```
27
+ *
28
+ * The rules are the in-process queue's, to the letter (`queueRules`): the file is only where its state is kept, written
29
+ * whole after each change that changed something, as `createFileKv` writes its own. ONE process holds the file
30
+ * (`<file>.lock`); the workers of one server reach the primary's through the fleet (`fleetJobQueue`); replicas share
31
+ * `createSqliteJobQueue` (`@plitzi/sdk-server/sqlite`) or a database's queue.
32
+ */
33
+ var createFileJobQueue = ({ file, owner, serves, retainFinished = 500, clock = Date.now }) => {
34
+ const lock = holdFile(file, {
35
+ owner,
36
+ serves
37
+ }, "createFileJobQueue");
38
+ let state;
39
+ try {
40
+ state = load(file);
41
+ } catch (error) {
42
+ letGo(lock);
43
+ throw error;
44
+ }
45
+ const rules = queueRules(state, {
46
+ retainFinished,
47
+ clock
48
+ });
49
+ const { changed, flush } = documentWriter({
50
+ file,
51
+ document: () => `${JSON.stringify(documentOf(state), null, 2)}\n`,
52
+ store: "createFileJobQueue",
53
+ what: "job queue file"
54
+ });
55
+ return {
56
+ ...queueOver((method, args) => {
57
+ const answer = applyRule(rules, method, args);
58
+ if (changedBy(method, answer)) changed();
59
+ return Promise.resolve(answer);
60
+ }),
61
+ flush,
62
+ close: async () => {
63
+ try {
64
+ await flush();
65
+ } finally {
66
+ letGo(lock);
67
+ }
68
+ }
69
+ };
70
+ };
71
+ //#endregion
72
+ export { createFileJobQueue };
@@ -1,8 +1,8 @@
1
- import { JOB_QUEUE_METHODS, createMemoryJobQueue } from "./memoryQueue.js";
1
+ import { createMemoryJobQueue } from "./memoryQueue.js";
2
2
  import { DEFAULT_MAX_ATTEMPTS, scheduleFor, scheduleJobId, schedulesFor } from "./schedules.js";
3
3
  import { createScheduler } from "./scheduler.js";
4
4
  import { createJobWorker } from "./worker.js";
5
- import { fleetStore } from "../../../core/server/fleet/link.js";
5
+ import { fleetJobQueue } from "../../../core/server/fleet/stores.js";
6
6
  //#region src/modules/actions/jobs/index.ts
7
7
  /**
8
8
  * The scheduling half of actions: a producer, a consumer and the store they meet in.
@@ -18,7 +18,7 @@ import { fleetStore } from "../../../core/server/fleet/link.js";
18
18
  * the primary's queue, and only one of them runs the scheduler and the jobs (`runsFleetJobs`).
19
19
  */
20
20
  var createActionJobs = (config, module, lookups, functionJobs) => {
21
- const queue = config.queue ?? fleetStore("actions.jobs", JOB_QUEUE_METHODS) ?? createMemoryJobQueue();
21
+ const queue = config.queue ?? fleetJobQueue(() => createMemoryJobQueue());
22
22
  const { produce = true, workers = 4 } = config;
23
23
  const scheduler = createScheduler({
24
24
  queue,