@orieljs/live 0.1.0-alpha.12 → 0.1.0-alpha.14

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/dist/index.d.ts CHANGED
@@ -137,6 +137,8 @@ declare class Testable<C extends Component = Component> {
137
137
  html(): string;
138
138
  /** The effects of the last request. */
139
139
  effects(): LiveEffects;
140
+ /** The cookies the last request queued, by name; null for one it deleted. */
141
+ cookies(): Record<string, string | null>;
140
142
  /**
141
143
  * Sets public properties through an update. A file (a FakeFile) or an array of files is uploaded as `o:model` on a
142
144
  * file input does it: the upload rules, the temporary disk, then a TemporaryUploadedFile (or an array) in the
@@ -279,6 +281,11 @@ declare class LiveComponentManager implements LiveManager {
279
281
 
280
282
  /** The URI the client runtime posts updates to. */
281
283
  declare const UPDATE_URI = "/oriel/live/update";
284
+ /**
285
+ * Where the client gets a session before its first update when the page came without one (a page cached at a CDN):
286
+ * through the `web` middleware, so the answer sets the session and XSRF-TOKEN cookies (Sanctum's csrf-cookie route).
287
+ */
288
+ declare const SESSION_URI = "/oriel/live/session";
282
289
  /**
283
290
  * Binds the LiveManager and the PaginationState that WithPagination components answer, merges the `live` config,
284
291
  * registers POST /oriel/live/update (named `live.update`, in the `web` group: sessions and CSRF apply), the upload and
@@ -363,6 +370,12 @@ declare class FileNotPreviewableError extends LiveError {
363
370
  readonly name: string;
364
371
  constructor(extension: string);
365
372
  }
373
+ /** store() or temporaryUrl() on an upload that was stored already, so its temporary file has gone. */
374
+ declare class UploadAlreadyStoredError extends LiveError {
375
+ readonly path: string;
376
+ readonly name: string;
377
+ constructor(path: string);
378
+ }
366
379
  /** The errors an upload came back with (`_uploadErrored`): the component re-renders with them on the property. */
367
380
  declare class UploadValidationError extends LiveError {
368
381
  readonly errors: Record<string, string[]>;
@@ -427,11 +440,15 @@ declare class TemporaryUploadedFile implements UploadedFile {
427
440
  text(): Promise<string>;
428
441
  /** The file's bytes from the temporary disk, opened on the first read. */
429
442
  stream(): ReadableStream<Uint8Array>;
430
- /** Stores a copy under a random name in `directory`, on `disk` (by default the temporary disk, as Livewire's). */
443
+ /**
444
+ * Moves the file under a random name to `directory`, on `disk` (by default the temporary disk, as Livewire's), so no
445
+ * temporary copy is left behind: on a public disk it could be fetched at its address. An upload stores once.
446
+ */
431
447
  store(directory: string, disk?: string): Promise<string>;
448
+ /** store(), under the name you give it. */
432
449
  storeAs(directory: string, name: string, disk?: string): Promise<string>;
433
450
  exists(): Promise<boolean>;
434
- /** Removes the temporary file (a stored copy stays). */
451
+ /** Removes the temporary file, if it hasn't been stored. */
435
452
  delete(): Promise<boolean>;
436
453
  /** Whether temporaryUrl() serves this file: its type is in `live.temporary_file_upload.preview_mimes`. */
437
454
  isPreviewable(): boolean;
@@ -507,13 +524,18 @@ interface PaginationProps {
507
524
  paginator: PaginationSource;
508
525
  /** Classes for the <nav>, such as its layout ("flex gap-2"); in your file, so Tailwind generates them. */
509
526
  class?: string;
527
+ /** Classes for Previous, Next and the page buttons, the kits' `btn btn-secondary` unless you say; '' for none. */
528
+ buttonClass?: string;
529
+ /** Classes for the current page's button, the kits' `btn` unless you say; '' for none. */
530
+ currentClass?: string;
510
531
  }
511
532
  /**
512
533
  * Livewire's pagination links for a WithPagination component: `<Pagination paginator={posts} />` in render(). A
513
534
  * <nav aria-label="Pagination"> with « Previous, the page buttons and Next » as Live actions (previousPage,
514
535
  * gotoPage(n), nextPage), the current page marked aria-current="page", the ends disabled, the kits' theme classes
515
- * (btn, btn-secondary). Nothing when everything fits on one page. The address bar is left alone.
536
+ * (btn, btn-secondary) unless `buttonClass` and `currentClass` say otherwise. Nothing when everything fits on one page.
537
+ * The address bar is left alone.
516
538
  */
517
- declare function Pagination({ paginator, class: className }: PaginationProps): Htmlable;
539
+ declare function Pagination({ paginator, class: className, buttonClass, currentClass }: PaginationProps): Htmlable;
518
540
 
519
- export { Component, type ComponentResult, Computed, CorruptComponentPayloadError, ErrorBag, FileNotPreviewableError, InvalidLiveRequestError, InvalidUploadSignatureError, Live, LiveComponentManager, LiveComponentNotFoundError, LiveError, type LiveProps, LiveServiceProvider, Locked, MethodNotCallableError, On, PERSISTENT_MIDDLEWARE, PREVIEW_URI, type Paginated, Pagination, type PaginationProps, type PaginationSource, PendingEvent, type PersistentMiddleware, PropertyNotUpdatableError, TEMPORARY_UPLOAD_DEFAULTS, type TemporaryFileData, TemporaryFileNotFoundError, TemporaryUploadedFile, TestRequestScope, Testable, UPDATE_URI, UPLOAD_URI, UploadValidationError, WithFileUploads, WithPagination, componentFiles, componentName, describeComponent, live, persistentMiddleware };
541
+ export { Component, type ComponentResult, Computed, CorruptComponentPayloadError, ErrorBag, FileNotPreviewableError, InvalidLiveRequestError, InvalidUploadSignatureError, Live, LiveComponentManager, LiveComponentNotFoundError, LiveError, type LiveProps, LiveServiceProvider, Locked, MethodNotCallableError, On, PERSISTENT_MIDDLEWARE, PREVIEW_URI, type Paginated, Pagination, type PaginationProps, type PaginationSource, PendingEvent, type PersistentMiddleware, PropertyNotUpdatableError, SESSION_URI, TEMPORARY_UPLOAD_DEFAULTS, type TemporaryFileData, TemporaryFileNotFoundError, TemporaryUploadedFile, TestRequestScope, Testable, UPDATE_URI, UPLOAD_URI, UploadAlreadyStoredError, UploadValidationError, WithFileUploads, WithPagination, componentFiles, componentName, describeComponent, live, persistentMiddleware };
package/dist/index.js CHANGED
@@ -71,6 +71,14 @@ var FileNotPreviewableError = class extends LiveError {
71
71
  super(`File with extension "${extension}" is not previewable. See the live.temporary_file_upload.preview_mimes config.`);
72
72
  }
73
73
  };
74
+ var UploadAlreadyStoredError = class extends LiveError {
75
+ constructor(path) {
76
+ super(`This upload was stored already, at ${path}. Reset the property after storing it.`);
77
+ this.path = path;
78
+ }
79
+ path;
80
+ name = "UploadAlreadyStoredError";
81
+ };
74
82
  var UploadValidationError = class extends LiveError {
75
83
  constructor(errors) {
76
84
  super("The upload failed.");
@@ -203,6 +211,8 @@ var TemporaryUploadedFile = class {
203
211
  mimeType;
204
212
  size;
205
213
  #extension;
214
+ /** Where store() put it, once it has. */
215
+ #storedAt;
206
216
  constructor(data) {
207
217
  if (!isTemporaryFileData(data)) throw new LiveError("A temporary upload needs a stored name, a name, a size, a type and an extension.");
208
218
  this.filename = data.filename;
@@ -256,17 +266,34 @@ var TemporaryUploadedFile = class {
256
266
  }
257
267
  });
258
268
  }
259
- /** Stores a copy under a random name in `directory`, on `disk` (by default the temporary disk, as Livewire's). */
269
+ /**
270
+ * Moves the file under a random name to `directory`, on `disk` (by default the temporary disk, as Livewire's), so no
271
+ * temporary copy is left behind: on a public disk it could be fetched at its address. An upload stores once.
272
+ */
260
273
  store(directory, disk) {
261
- return container().make(FilesystemManager).disk(disk ?? uploadSetting("disk") ?? void 0).putFile(directory, this);
262
- }
263
- storeAs(directory, name, disk) {
264
- return container().make(FilesystemManager).disk(disk ?? uploadSetting("disk") ?? void 0).putFileAs(directory, this, name);
274
+ return this.storeAs(directory, this.hashName(), disk);
275
+ }
276
+ /** store(), under the name you give it. */
277
+ async storeAs(directory, name, disk) {
278
+ if (this.#storedAt !== void 0) throw new UploadAlreadyStoredError(this.#storedAt);
279
+ const target = container().make(FilesystemManager).disk(disk ?? uploadSetting("disk") ?? void 0);
280
+ const temporary = temporaryDisk();
281
+ let path;
282
+ if (target === temporary) {
283
+ const folder = directory.replace(/^\/+|\/+$/g, "");
284
+ path = folder === "" ? name : `${folder}/${name}`;
285
+ await target.move(this.path, path);
286
+ } else {
287
+ path = await target.putFileAs(directory, this, name);
288
+ await temporary.delete(this.path);
289
+ }
290
+ this.#storedAt = path;
291
+ return path;
265
292
  }
266
293
  exists() {
267
294
  return temporaryDisk().exists(this.path);
268
295
  }
269
- /** Removes the temporary file (a stored copy stays). */
296
+ /** Removes the temporary file, if it hasn't been stored. */
270
297
  delete() {
271
298
  return temporaryDisk().delete(this.path);
272
299
  }
@@ -279,6 +306,7 @@ var TemporaryUploadedFile = class {
279
306
  * at least 30 minutes away (Livewire's), so a re-render keeps the same link and the browser doesn't reload it.
280
307
  */
281
308
  temporaryUrl() {
309
+ if (this.#storedAt !== void 0) throw new UploadAlreadyStoredError(this.#storedAt);
282
310
  if (!this.isPreviewable()) throw new FileNotPreviewableError(this.#extension);
283
311
  const expires = new Date((Math.floor((Date.now() + 30 * 6e4) / HOUR) + 1) * HOUR - 1e3);
284
312
  return container().make(UrlGenerator).temporarySignedRoute("live.preview-file", expires, { filename: this.filename }, false);
@@ -625,7 +653,7 @@ import { inject as inject5 } from "@orieljs/container";
625
653
  // Testable.ts
626
654
  import { AssertionError } from "assert";
627
655
  import { isDeepStrictEqual } from "util";
628
- import { LiveManager as LiveManager2, Session, token } from "@orieljs/contracts";
656
+ import { CookieJar, LiveManager as LiveManager2, Session, token } from "@orieljs/contracts";
629
657
  import { Container, currentContainer as currentContainer2, inject as inject4 } from "@orieljs/container";
630
658
 
631
659
  // flash.ts
@@ -961,14 +989,24 @@ function currentSession() {
961
989
  return void 0;
962
990
  }
963
991
  }
992
+ function queuedCookies() {
993
+ const container2 = currentContainer2();
994
+ if (container2?.bound(CookieJar) !== true) return {};
995
+ try {
996
+ return Object.fromEntries(container2.make(CookieJar).queued().map((cookie) => [cookie.name, cookie.minutes < 0 ? null : cookie.value]));
997
+ } catch {
998
+ return {};
999
+ }
1000
+ }
964
1001
  var Testable = class _Testable {
965
- constructor(manager, scope, result) {
1002
+ constructor(manager, scope, result, cookies) {
966
1003
  this.manager = manager;
967
1004
  this.scope = scope;
968
1005
  this.#snapshot = JSON.stringify(result.snapshot);
969
1006
  this.#html = result.html ?? "";
970
1007
  this.#effects = result.effects;
971
1008
  this.#instance = result.instance;
1009
+ this.#cookies = cookies;
972
1010
  }
973
1011
  manager;
974
1012
  scope;
@@ -976,6 +1014,7 @@ var Testable = class _Testable {
976
1014
  #html;
977
1015
  #effects;
978
1016
  #instance;
1017
+ #cookies;
979
1018
  /**
980
1019
  * Mounts `component` with `params`, as `<Live component={…} {...params} />` would. A lazy component mounts at once
981
1020
  * (Livewire's withoutLazyLoading()); `{ lazy: true }` renders its placeholder, and `call('__lazyLoad', …)` loads it.
@@ -983,7 +1022,11 @@ var Testable = class _Testable {
983
1022
  static async create(component, params = {}) {
984
1023
  const scope = requestScope();
985
1024
  const manager = inject4(LiveManager2);
986
- return new _Testable(manager, scope, await scope(() => manager.mountComponent(component, { lazy: false, ...params })));
1025
+ const { result, cookies } = await scope(async () => {
1026
+ const result2 = await manager.mountComponent(component, { lazy: false, ...params });
1027
+ return { result: result2, cookies: queuedCookies() };
1028
+ });
1029
+ return new _Testable(manager, scope, result, cookies);
987
1030
  }
988
1031
  /** The component instance after the last request. */
989
1032
  instance() {
@@ -1001,6 +1044,10 @@ var Testable = class _Testable {
1001
1044
  effects() {
1002
1045
  return this.#effects;
1003
1046
  }
1047
+ /** The cookies the last request queued, by name; null for one it deleted. */
1048
+ cookies() {
1049
+ return { ...this.#cookies };
1050
+ }
1004
1051
  /**
1005
1052
  * Sets public properties through an update. A file (a FakeFile) or an array of files is uploaded as `o:model` on a
1006
1053
  * file input does it: the upload rules, the temporary disk, then a TemporaryUploadedFile (or an array) in the
@@ -1033,12 +1080,13 @@ var Testable = class _Testable {
1033
1080
  return this.#update({}, [{ method: "$refresh", params: [] }]);
1034
1081
  }
1035
1082
  async #update(updates, calls) {
1036
- const result = await this.scope(async () => {
1083
+ const { result, cookies } = await this.scope(async () => {
1037
1084
  const flashed = trackFlash(currentSession(), { saved: false });
1038
1085
  const updated = await this.manager.updateComponent(this.#snapshot, updates, calls);
1039
1086
  flashed(updated.effects.redirect !== void 0);
1040
- return updated;
1087
+ return { result: updated, cookies: queuedCookies() };
1041
1088
  });
1089
+ this.#cookies = cookies;
1042
1090
  this.#snapshot = JSON.stringify(result.snapshot);
1043
1091
  if (result.html !== void 0) this.#html = result.html;
1044
1092
  this.#effects = result.effects;
@@ -1880,6 +1928,7 @@ function registerLiveCommands(kernel, app) {
1880
1928
 
1881
1929
  // LiveServiceProvider.ts
1882
1930
  var UPDATE_URI = "/oriel/live/update";
1931
+ var SESSION_URI = "/oriel/live/session";
1883
1932
  var LiveServiceProvider = class extends ServiceProvider {
1884
1933
  register() {
1885
1934
  this.mergeConfigFrom({ class_path: this.app.appPath("Live"), layout: "components.layouts.app", persistent_middleware: [...PERSISTENT_MIDDLEWARE] }, "live");
@@ -1892,6 +1941,7 @@ var LiveServiceProvider = class extends ServiceProvider {
1892
1941
  if (this.app.bound(Router2)) {
1893
1942
  const router = this.app.make(Router2);
1894
1943
  router.post(UPDATE_URI, () => manager.handle(inject6(HttpRequest2))).middleware("web").name("live.update");
1944
+ router.get(SESSION_URI, () => new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } })).middleware("web").name("live.session");
1895
1945
  router.post(UPLOAD_URI, () => handleUpload(inject6(HttpRequest2))).middleware(uploadMiddleware()).name("live.upload-file");
1896
1946
  router.get(`${PREVIEW_URI}/{filename}`, (filename) => handlePreview(inject6(HttpRequest2), filename)).middleware("web").name("live.preview-file");
1897
1947
  }
@@ -1928,11 +1978,12 @@ function urlWindow(current, last, onEachSide) {
1928
1978
  if (current > last - size) return [...range(1, 2), "...", ...range(last - (size + (onEachSide - 1)), last)];
1929
1979
  return [...range(1, 2), "...", ...range(current - onEachSide, current + onEachSide), "...", ...range(last - 1, last)];
1930
1980
  }
1931
- function button(label, action, attributes = "") {
1981
+ var classAttribute = (classes) => classes === "" ? "" : ` class="${escapeAttribute(classes)}"`;
1982
+ function button(label, action, classes, attributes = "") {
1932
1983
  const live2 = action === void 0 ? " disabled" : ` o:click="${escapeAttribute(action)}"`;
1933
- return `<button type="button" class="btn btn-secondary"${attributes}${live2}>${escapeAttribute(label)}</button>`;
1984
+ return `<button type="button"${classAttribute(classes)}${attributes}${live2}>${escapeAttribute(label)}</button>`;
1934
1985
  }
1935
- function Pagination({ paginator, class: className }) {
1986
+ function Pagination({ paginator, class: className, buttonClass = "btn btn-secondary", currentClass = "btn" }) {
1936
1987
  if (typeof paginator.nextCursor === "function") {
1937
1988
  throw new LiveError("<Pagination> needs paginate() or simplePaginate(): a cursor paginator has no page numbers.");
1938
1989
  }
@@ -1940,18 +1991,17 @@ function Pagination({ paginator, class: className }) {
1940
1991
  const onFirst = paginator.onFirstPage();
1941
1992
  const hasMore = paginator.hasMorePages();
1942
1993
  if (onFirst && !hasMore) return { toHtml: () => "" };
1943
- const parts = [button("\xAB Previous", onFirst ? void 0 : "previousPage")];
1994
+ const parts = [button("\xAB Previous", onFirst ? void 0 : "previousPage", buttonClass)];
1944
1995
  if (typeof paginator.lastPage === "function") {
1945
1996
  const onEachSide = Number.isInteger(paginator.onEachSideCount) && paginator.onEachSideCount >= 0 ? paginator.onEachSideCount : 3;
1946
1997
  for (const page of urlWindow(current, paginator.lastPage(), onEachSide)) {
1947
1998
  if (page === "...") parts.push('<span aria-hidden="true">...</span>');
1948
- else if (page === current) parts.push(`<button type="button" class="btn" aria-current="page" disabled>${page}</button>`);
1949
- else parts.push(button(String(page), `gotoPage(${page})`, ` aria-label="Go to page ${page}"`));
1999
+ else if (page === current) parts.push(`<button type="button"${classAttribute(currentClass)} aria-current="page" disabled>${page}</button>`);
2000
+ else parts.push(button(String(page), `gotoPage(${page})`, buttonClass, ` aria-label="Go to page ${page}"`));
1950
2001
  }
1951
2002
  }
1952
- parts.push(button("Next \xBB", hasMore ? "nextPage" : void 0));
1953
- const classes = className === void 0 || className === "" ? "" : ` class="${escapeAttribute(className)}"`;
1954
- const html = `<nav aria-label="Pagination"${classes}>${parts.join("")}</nav>`;
2003
+ parts.push(button("Next \xBB", hasMore ? "nextPage" : void 0, buttonClass));
2004
+ const html = `<nav aria-label="Pagination"${classAttribute(className ?? "")}>${parts.join("")}</nav>`;
1955
2005
  return { toHtml: () => html };
1956
2006
  }
1957
2007
  export {
@@ -1975,6 +2025,7 @@ export {
1975
2025
  Pagination,
1976
2026
  PendingEvent,
1977
2027
  PropertyNotUpdatableError,
2028
+ SESSION_URI,
1978
2029
  TEMPORARY_UPLOAD_DEFAULTS,
1979
2030
  TemporaryFileNotFoundError,
1980
2031
  TemporaryUploadedFile,
@@ -1982,6 +2033,7 @@ export {
1982
2033
  Testable,
1983
2034
  UPDATE_URI,
1984
2035
  UPLOAD_URI,
2036
+ UploadAlreadyStoredError,
1985
2037
  UploadValidationError,
1986
2038
  WithFileUploads,
1987
2039
  WithPagination,