@orieljs/live 0.1.0-alpha.13 → 0.1.0-alpha.15

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
@@ -368,6 +370,12 @@ declare class FileNotPreviewableError extends LiveError {
368
370
  readonly name: string;
369
371
  constructor(extension: string);
370
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
+ }
371
379
  /** The errors an upload came back with (`_uploadErrored`): the component re-renders with them on the property. */
372
380
  declare class UploadValidationError extends LiveError {
373
381
  readonly errors: Record<string, string[]>;
@@ -432,11 +440,15 @@ declare class TemporaryUploadedFile implements UploadedFile {
432
440
  text(): Promise<string>;
433
441
  /** The file's bytes from the temporary disk, opened on the first read. */
434
442
  stream(): ReadableStream<Uint8Array>;
435
- /** 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
+ */
436
447
  store(directory: string, disk?: string): Promise<string>;
448
+ /** store(), under the name you give it. */
437
449
  storeAs(directory: string, name: string, disk?: string): Promise<string>;
438
450
  exists(): Promise<boolean>;
439
- /** Removes the temporary file (a stored copy stays). */
451
+ /** Removes the temporary file, if it hasn't been stored. */
440
452
  delete(): Promise<boolean>;
441
453
  /** Whether temporaryUrl() serves this file: its type is in `live.temporary_file_upload.preview_mimes`. */
442
454
  isPreviewable(): boolean;
@@ -512,13 +524,18 @@ interface PaginationProps {
512
524
  paginator: PaginationSource;
513
525
  /** Classes for the <nav>, such as its layout ("flex gap-2"); in your file, so Tailwind generates them. */
514
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;
515
531
  }
516
532
  /**
517
533
  * Livewire's pagination links for a WithPagination component: `<Pagination paginator={posts} />` in render(). A
518
534
  * <nav aria-label="Pagination"> with « Previous, the page buttons and Next » as Live actions (previousPage,
519
535
  * gotoPage(n), nextPage), the current page marked aria-current="page", the ends disabled, the kits' theme classes
520
- * (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.
521
538
  */
522
- declare function Pagination({ paginator, class: className }: PaginationProps): Htmlable;
539
+ declare function Pagination({ paginator, class: className, buttonClass, currentClass }: PaginationProps): Htmlable;
523
540
 
524
- 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, 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;
@@ -1930,11 +1978,12 @@ function urlWindow(current, last, onEachSide) {
1930
1978
  if (current > last - size) return [...range(1, 2), "...", ...range(last - (size + (onEachSide - 1)), last)];
1931
1979
  return [...range(1, 2), "...", ...range(current - onEachSide, current + onEachSide), "...", ...range(last - 1, last)];
1932
1980
  }
1933
- function button(label, action, attributes = "") {
1981
+ var classAttribute = (classes) => classes === "" ? "" : ` class="${escapeAttribute(classes)}"`;
1982
+ function button(label, action, classes, attributes = "") {
1934
1983
  const live2 = action === void 0 ? " disabled" : ` o:click="${escapeAttribute(action)}"`;
1935
- 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>`;
1936
1985
  }
1937
- function Pagination({ paginator, class: className }) {
1986
+ function Pagination({ paginator, class: className, buttonClass = "btn btn-secondary", currentClass = "btn" }) {
1938
1987
  if (typeof paginator.nextCursor === "function") {
1939
1988
  throw new LiveError("<Pagination> needs paginate() or simplePaginate(): a cursor paginator has no page numbers.");
1940
1989
  }
@@ -1942,18 +1991,17 @@ function Pagination({ paginator, class: className }) {
1942
1991
  const onFirst = paginator.onFirstPage();
1943
1992
  const hasMore = paginator.hasMorePages();
1944
1993
  if (onFirst && !hasMore) return { toHtml: () => "" };
1945
- const parts = [button("\xAB Previous", onFirst ? void 0 : "previousPage")];
1994
+ const parts = [button("\xAB Previous", onFirst ? void 0 : "previousPage", buttonClass)];
1946
1995
  if (typeof paginator.lastPage === "function") {
1947
1996
  const onEachSide = Number.isInteger(paginator.onEachSideCount) && paginator.onEachSideCount >= 0 ? paginator.onEachSideCount : 3;
1948
1997
  for (const page of urlWindow(current, paginator.lastPage(), onEachSide)) {
1949
1998
  if (page === "...") parts.push('<span aria-hidden="true">...</span>');
1950
- else if (page === current) parts.push(`<button type="button" class="btn" aria-current="page" disabled>${page}</button>`);
1951
- 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}"`));
1952
2001
  }
1953
2002
  }
1954
- parts.push(button("Next \xBB", hasMore ? "nextPage" : void 0));
1955
- const classes = className === void 0 || className === "" ? "" : ` class="${escapeAttribute(className)}"`;
1956
- 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>`;
1957
2005
  return { toHtml: () => html };
1958
2006
  }
1959
2007
  export {
@@ -1985,6 +2033,7 @@ export {
1985
2033
  Testable,
1986
2034
  UPDATE_URI,
1987
2035
  UPLOAD_URI,
2036
+ UploadAlreadyStoredError,
1988
2037
  UploadValidationError,
1989
2038
  WithFileUploads,
1990
2039
  WithPagination,