ras-stack 3.2.0 → 4.1.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 (89) hide show
  1. package/README.md +11 -10
  2. package/dist/auth/index.d.ts +1 -1
  3. package/dist/auth/index.js +1 -1
  4. package/dist/auth/index.js.map +1 -1
  5. package/dist/conformance/index.d.ts +0 -57
  6. package/dist/conformance/index.js +1 -257
  7. package/dist/conformance/index.js.map +1 -1
  8. package/dist/database/postgres.d.ts +0 -5
  9. package/dist/database/postgres.js +0 -34
  10. package/dist/database/postgres.js.map +1 -1
  11. package/dist/database/sqlite.d.ts +0 -3
  12. package/dist/database/sqlite.js +1 -22
  13. package/dist/database/sqlite.js.map +1 -1
  14. package/dist/email/index.d.ts +0 -11
  15. package/dist/email/index.js +6 -9
  16. package/dist/email/index.js.map +1 -1
  17. package/dist/posthog/client.d.ts +0 -6
  18. package/dist/posthog/client.js +1 -11
  19. package/dist/posthog/client.js.map +1 -1
  20. package/dist/posthog/config.d.ts +1 -0
  21. package/dist/posthog/config.js +2 -0
  22. package/dist/posthog/config.js.map +1 -1
  23. package/dist/posthog/index.d.ts +2 -2
  24. package/dist/posthog/index.js +2 -2
  25. package/dist/posthog/index.js.map +1 -1
  26. package/dist/posthog/proxy.d.ts +0 -1
  27. package/dist/posthog/proxy.js +1 -3
  28. package/dist/posthog/proxy.js.map +1 -1
  29. package/dist/posthog/react.d.ts +1 -2
  30. package/dist/posthog/react.js +1 -2
  31. package/dist/posthog/react.js.map +1 -1
  32. package/dist/posthog/request.d.ts +0 -3
  33. package/dist/posthog/request.js +3 -3
  34. package/dist/posthog/request.js.map +1 -1
  35. package/dist/posthog/server.d.ts +1 -3
  36. package/dist/posthog/server.js +2 -2
  37. package/dist/posthog/server.js.map +1 -1
  38. package/dist/preview/cloudflare.js +1 -1
  39. package/dist/preview/cloudflare.js.map +1 -1
  40. package/dist/preview/dokploy-cli.js +1 -1
  41. package/dist/preview/dokploy-cli.js.map +1 -1
  42. package/dist/preview/dokploy-preview.d.ts +102 -0
  43. package/dist/preview/dokploy-preview.js +377 -0
  44. package/dist/preview/dokploy-preview.js.map +1 -0
  45. package/dist/preview/dokploy.d.ts +2 -102
  46. package/dist/preview/dokploy.js +1 -376
  47. package/dist/preview/dokploy.js.map +1 -1
  48. package/dist/preview/github.js +1 -1
  49. package/dist/preview/github.js.map +1 -1
  50. package/dist/realtime/client.d.ts +1 -11
  51. package/dist/realtime/client.js +2 -98
  52. package/dist/realtime/client.js.map +1 -1
  53. package/dist/realtime/index.d.ts +0 -2
  54. package/dist/realtime/index.js +0 -1
  55. package/dist/realtime/index.js.map +1 -1
  56. package/dist/realtime/react.d.ts +1 -4
  57. package/dist/realtime/react.js +22 -26
  58. package/dist/realtime/react.js.map +1 -1
  59. package/dist/runtime/index.d.ts +2 -64
  60. package/dist/runtime/index.js +1 -255
  61. package/dist/runtime/index.js.map +1 -1
  62. package/dist/runtime/stack.d.ts +64 -0
  63. package/dist/runtime/stack.js +252 -0
  64. package/dist/runtime/stack.js.map +1 -0
  65. package/dist/server/errors.d.ts +0 -22
  66. package/dist/server/errors.js +0 -44
  67. package/dist/server/errors.js.map +1 -1
  68. package/dist/server/health.d.ts +7 -4
  69. package/dist/server/health.js +3 -7
  70. package/dist/server/health.js.map +1 -1
  71. package/dist/server/index.d.ts +2 -10
  72. package/dist/server/index.js +1 -5
  73. package/dist/server/index.js.map +1 -1
  74. package/dist/spacetime/index.d.ts +32 -0
  75. package/dist/spacetime/index.js +93 -0
  76. package/dist/spacetime/index.js.map +1 -0
  77. package/dist/tanstack/middleware.d.ts +0 -1
  78. package/dist/tanstack/middleware.js +2 -5
  79. package/dist/tanstack/middleware.js.map +1 -1
  80. package/dist/tanstack/server.d.ts +2 -11
  81. package/dist/tanstack/server.js +2 -6
  82. package/dist/tanstack/server.js.map +1 -1
  83. package/dist/uploads/index.d.ts +0 -6
  84. package/dist/uploads/index.js +0 -25
  85. package/dist/uploads/index.js.map +1 -1
  86. package/package.json +6 -18
  87. package/dist/server/rate-limit.d.ts +0 -30
  88. package/dist/server/rate-limit.js +0 -73
  89. package/dist/server/rate-limit.js.map +0 -1
@@ -0,0 +1,93 @@
1
+ export class SpacetimeRequestError extends Error {
2
+ status;
3
+ constructor(status, message) {
4
+ super(message);
5
+ this.status = status;
6
+ this.name = 'SpacetimeRequestError';
7
+ }
8
+ }
9
+ export function spacetimeDatabaseUrl(connection, path = '') {
10
+ const base = new URL(connection.url);
11
+ const internal = /^[a-z][a-z0-9-]{1,63}$/.test(connection.internalHost ?? '') && base.hostname === connection.internalHost;
12
+ const local = base.protocol === 'http:' && (['localhost', '127.0.0.1'].includes(base.hostname) || internal);
13
+ if ((!local && base.protocol !== 'https:') || base.username || base.password || base.search || base.hash || base.pathname !== '/') {
14
+ throw new Error('Invalid SpacetimeDB URL');
15
+ }
16
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(connection.database))
17
+ throw new Error('Invalid SpacetimeDB database name');
18
+ return new URL(`/v1/database/${connection.database}${path}`, base);
19
+ }
20
+ export async function callSpacetime(connection, name, arguments_, options = {}) {
21
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
22
+ throw new Error('Invalid SpacetimeDB procedure name');
23
+ return request(connection, spacetimeDatabaseUrl(connection, `/call/${name}`), name, {
24
+ method: 'POST',
25
+ headers: { 'content-type': 'application/json' },
26
+ body: JSON.stringify(arguments_),
27
+ timeoutMs: options.timeoutMs ?? 10_000,
28
+ });
29
+ }
30
+ /** `spacetime-environment` publish headers, which SpacetimeDB stores with the module and keeps across later publishes. */
31
+ export function moduleEnvironmentHeaders(environment) {
32
+ return Object.entries(environment).map(([key, value]) => {
33
+ // A bare header value is visible ASCII without quotes, commas, or backslashes.
34
+ if (!/^[!#-&(-+\--[\]-~]+$/.test(value))
35
+ throw new Error(`Invalid ${key} for the module environment`);
36
+ return ['spacetime-environment', `${key}=${value}`];
37
+ });
38
+ }
39
+ /**
40
+ * Publishes a JavaScript module through SpacetimeDB's migration planner: a missing database is created, an automatic
41
+ * migration is applied, and a migration that needs manual steps or would break clients unasked is refused before
42
+ * anything changes.
43
+ */
44
+ export async function publishSpacetimeModule(connection, module, options = {}) {
45
+ const timeoutMs = options.timeoutMs ?? 90_000;
46
+ const binary = { 'content-type': 'application/octet-stream' };
47
+ const plan = await request(connection, spacetimeDatabaseUrl(connection, '/pre_publish?host_type=Js'), 'pre_publish', {
48
+ method: 'POST',
49
+ headers: binary,
50
+ body: module,
51
+ timeoutMs,
52
+ allowNotFound: true,
53
+ });
54
+ const query = new URLSearchParams({ host_type: 'Js' });
55
+ if (plan.status !== 404) {
56
+ const result = (await plan.json());
57
+ if (result.ManualMigrate)
58
+ throw new Error(`SpacetimeDB database needs a manual migration: ${result.ManualMigrate.reason}`);
59
+ if (!result.AutoMigrate)
60
+ throw new Error('SpacetimeDB returned an unknown migration plan');
61
+ if (result.AutoMigrate.break_clients) {
62
+ if (!options.breakClients)
63
+ throw new Error('SpacetimeDB migration would break existing clients; pass breakClients to accept it');
64
+ query.set('policy', 'BreakClients');
65
+ query.set('token', result.AutoMigrate.token);
66
+ }
67
+ }
68
+ const environment = moduleEnvironmentHeaders(options.environment ?? {});
69
+ await request(connection, spacetimeDatabaseUrl(connection, `?${query}`), 'publish', {
70
+ method: 'PUT',
71
+ headers: [...Object.entries(binary), ...environment],
72
+ body: module,
73
+ timeoutMs,
74
+ });
75
+ }
76
+ async function request(connection, url, operation, init) {
77
+ const headers = new Headers(init.headers);
78
+ for (const [name, value] of Object.entries(connection.headers ?? {}))
79
+ headers.set(name, value);
80
+ headers.set('authorization', `Bearer ${connection.token}`);
81
+ const response = await (connection.fetch ?? fetch)(url, {
82
+ method: init.method,
83
+ headers,
84
+ body: init.body,
85
+ // A redirect would resend the bearer token to wherever it points.
86
+ redirect: 'manual',
87
+ signal: AbortSignal.timeout(init.timeoutMs),
88
+ });
89
+ if (response.ok || (init.allowNotFound && response.status === 404))
90
+ return response;
91
+ throw new SpacetimeRequestError(response.status, `SpacetimeDB ${operation} failed with HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);
92
+ }
93
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/spacetime/index.ts"],"names":[],"mappings":"AAWA,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAEnC,MAAM;IADjB,YACW,MAAc,EACvB,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAA;sBAHL,MAAM;QAIf,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAA;IACrC,CAAC;CACF;AAED,MAAM,UAAU,oBAAoB,CAAC,UAA0E,EAAE,IAAI,GAAG,EAAE;IACxH,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;IACpC,MAAM,QAAQ,GAAG,wBAAwB,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,IAAI,EAAE,CAAC,IAAI,IAAI,CAAC,QAAQ,KAAK,UAAU,CAAC,YAAY,CAAA;IAC1H,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,CAAA;IAC3G,IAAI,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,KAAK,GAAG,EAAE,CAAC;QAClI,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAA;IAC5C,CAAC;IACD,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,C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{\n /** Origin of the SpacetimeDB host. Plain HTTP is accepted only for loopback or `internalHost`. */\n url: string\n database: string\n token: string\n /** Sent with every request, for example Cloudflare Access service-token headers. */\n headers?: Record<string, string>\n internalHost?: string\n fetch?: typeof fetch\n}\n\nexport class SpacetimeRequestError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message)\n this.name = 'SpacetimeRequestError'\n }\n}\n\nexport function spacetimeDatabaseUrl(connection: Pick<SpacetimeConnection, 'url' | 'database' | 'internalHost'>, path = '') {\n const base = new URL(connection.url)\n const internal = /^[a-z][a-z0-9-]{1,63}$/.test(connection.internalHost ?? '') && base.hostname === connection.internalHost\n const local = base.protocol === 'http:' && (['localhost', '127.0.0.1'].includes(base.hostname) || internal)\n if ((!local && base.protocol !== 'https:') || base.username || base.password || base.search || base.hash || base.pathname !== '/') {\n throw new Error('Invalid SpacetimeDB URL')\n }\n if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(connection.database)) throw new Error('Invalid SpacetimeDB database name')\n return new URL(`/v1/database/${connection.database}${path}`, base)\n}\n\nexport async function callSpacetime(\n connection: SpacetimeConnection,\n name: string,\n arguments_: unknown[],\n options: { timeoutMs?: number } = {},\n) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error('Invalid SpacetimeDB procedure name')\n return request(connection, spacetimeDatabaseUrl(connection, `/call/${name}`), name, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(arguments_),\n timeoutMs: options.timeoutMs ?? 10_000,\n })\n}\n\n/** `spacetime-environment` publish headers, which SpacetimeDB stores with the module and keeps across later publishes. */\nexport function moduleEnvironmentHeaders(environment: Record<string, string>): [string, string][] {\n return Object.entries(environment).map(([key, value]) => {\n // A bare header value is visible ASCII without quotes, commas, or backslashes.\n if (!/^[!#-&(-+\\--[\\]-~]+$/.test(value)) throw new Error(`Invalid ${key} for the module environment`)\n return ['spacetime-environment', `${key}=${value}`]\n })\n}\n\nexport type PublishSpacetimeModuleOptions = {\n environment?: Record<string, string>\n /** Accept an automatic migration that changes the schema in ways existing clients cannot read. */\n breakClients?: boolean\n timeoutMs?: number\n}\n\n/**\n * Publishes a JavaScript module through SpacetimeDB's migration planner: a missing database is created, an automatic\n * migration is applied, and a migration that needs manual steps or would break clients unasked is refused before\n * anything changes.\n */\nexport async function publishSpacetimeModule(\n connection: SpacetimeConnection,\n module: Uint8Array<ArrayBuffer>,\n options: PublishSpacetimeModuleOptions = {},\n) {\n const timeoutMs = options.timeoutMs ?? 90_000\n const binary = { 'content-type': 'application/octet-stream' }\n const plan = await request(connection, spacetimeDatabaseUrl(connection, '/pre_publish?host_type=Js'), 'pre_publish', {\n method: 'POST',\n headers: binary,\n body: module,\n timeoutMs,\n allowNotFound: true,\n })\n const query = new URLSearchParams({ host_type: 'Js' })\n if (plan.status !== 404) {\n const result = (await plan.json()) as {\n AutoMigrate?: { token: string; break_clients: boolean }\n ManualMigrate?: { reason: string }\n }\n if (result.ManualMigrate) throw new Error(`SpacetimeDB database needs a manual migration: ${result.ManualMigrate.reason}`)\n if (!result.AutoMigrate) throw new Error('SpacetimeDB returned an unknown migration plan')\n if (result.AutoMigrate.break_clients) {\n if (!options.breakClients) throw new Error('SpacetimeDB migration would break existing clients; pass breakClients to accept it')\n query.set('policy', 'BreakClients')\n query.set('token', result.AutoMigrate.token)\n }\n }\n const environment = moduleEnvironmentHeaders(options.environment ?? {})\n await request(connection, spacetimeDatabaseUrl(connection, `?${query}`), 'publish', {\n method: 'PUT',\n headers: [...Object.entries(binary), ...environment],\n body: module,\n timeoutMs,\n })\n}\n\nasync function request(\n connection: SpacetimeConnection,\n url: URL,\n operation: string,\n init: { method: string; headers: HeadersInit; body: BodyInit; timeoutMs: number; allowNotFound?: boolean },\n) {\n const headers = new Headers(init.headers)\n for (const [name, value] of Object.entries(connection.headers ?? {})) headers.set(name, value)\n headers.set('authorization', `Bearer ${connection.token}`)\n const response = await (connection.fetch ?? fetch)(url, {\n method: init.method,\n headers,\n body: init.body,\n // A redirect would resend the bearer token to wherever it points.\n redirect: 'manual',\n signal: AbortSignal.timeout(init.timeoutMs),\n })\n if (response.ok || (init.allowNotFound && response.status === 404)) return response\n throw new SpacetimeRequestError(\n response.status,\n `SpacetimeDB ${operation} failed with HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`,\n )\n}\n"]}
@@ -1,5 +1,4 @@
1
1
  import { type CanonicalRedirectOptions } from '../server/canonical-host.js';
2
- export declare function canonicalHostRequest<T>(request: Request, next: () => T, options: CanonicalRedirectOptions): Response | T;
3
2
  export declare function canonicalHostMiddleware(resolveOptions: () => CanonicalRedirectOptions): import("@tanstack/react-start").RequestMiddlewareAfterServer<{}, undefined, undefined>;
4
3
  /** Names each server function for telemetry recorded while it runs, such as the RPC observer's span and metrics. */
5
4
  export declare function serverFunctionIdentityMiddleware(): import("@tanstack/react-start").FunctionMiddlewareAfterServer<{}, unknown, undefined, undefined, undefined, undefined, undefined>;
@@ -1,13 +1,10 @@
1
1
  import { createMiddleware } from '@tanstack/react-start';
2
2
  import { canonicalRedirect } from '../server/canonical-host.js';
3
3
  import { withServerFunction } from '../server/server-function.js';
4
- export function canonicalHostRequest(request, next, options) {
5
- const redirect = canonicalRedirect(request.url, options);
6
- return redirect ? Response.redirect(redirect, 301) : next();
7
- }
8
4
  export function canonicalHostMiddleware(resolveOptions) {
9
5
  return createMiddleware({ type: 'request' }).server(({ request, next }) => {
10
- return canonicalHostRequest(request, next, resolveOptions());
6
+ const redirect = canonicalRedirect(request.url, resolveOptions());
7
+ return redirect ? Response.redirect(redirect, 301) : next();
11
8
  });
12
9
  }
13
10
  /** Names each server function for telemetry recorded while it runs, such as the RPC observer's span and metrics. */
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/tanstack/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,EAAE,iBAAiB,EAAiC,MAAM,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AI,EAAE,CAAA;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,qCAAqC,CAAC,CAAC;gBAAE,MAAM,KAAK,CAAA;YAC7G,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,cAAc,EAAE,2BAA2B,EAAE,EAAE,CAAC,CAAA;QACzG,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { createMiddleware } from '@tanstack/react-start'\nimport { canonicalRedirect, type CanonicalRedirectOptions } from '../server/canonical-host.js'\nimport { withServerFunction } from '../server/server-function.js'\n\nexport function canonicalHostRequest<T>(request: Request, next: () => T, options: CanonicalRedirectOptions): Response | T {\n const redirect = canonicalRedirect(request.url, options)\n return redirect ? Response.redirect(redirect, 301) : next()\n}\n\nexport function canonicalHostMiddleware(resolveOptions: () => CanonicalRedirectOptions) {\n return createMiddleware({ type: 'request' }).server(({ request, next }) => {\n return canonicalHostRequest(request, next, resolveOptions())\n })\n}\n\n/** Names each server function for telemetry recorded while it runs, such as the RPC observer's span and metrics. */\nexport function serverFunctionIdentityMiddleware() {\n return createMiddleware({ type: 'function' }).server(({ serverFnMeta, next }) =>\n withServerFunction({ name: serverFnMeta.name, filename: serverFnMeta.filename }, next),\n )\n}\n\n/**\n * A tab opened before a deploy can call a server function the deploy removed. TanStack answers with a JSON 500 that\n * its client returns as a successful result, so this replaces it with a plain-text 404 the client throws with `message`.\n */\nexport function staleServerFunctionMiddleware(message: string) {\n return createMiddleware({ type: 'request' }).server(async ({ handlerType, next }) => {\n if (handlerType !== 'serverFn') return next()\n try {\n return await next()\n } catch (error) {\n if (!(error instanceof Error && error.message.startsWith('Server function info not found for '))) throw error\n return new Response(message, { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })\n }\n })\n}\n"]}
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;YACH,OAAO,MAAM,IAAI,EAAE,CAAA;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,qCAAqC,CAAC,CAAC;gBAAE,MAAM,KAAK,CAAA;YAC7G,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,cAAc,EAAE,2BAA2B,EAAE,EAAE,CAAC,CAAA;QACzG,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { createMiddleware } from '@tanstack/react-start'\nimport { canonicalRedirect, type CanonicalRedirectOptions } from '../server/canonical-host.js'\nimport { withServerFunction } from '../server/server-function.js'\n\nexport function canonicalHostMiddleware(resolveOptions: () => CanonicalRedirectOptions) {\n return createMiddleware({ type: 'request' }).server(({ request, next }) => {\n const redirect = canonicalRedirect(request.url, resolveOptions())\n return redirect ? Response.redirect(redirect, 301) : next()\n })\n}\n\n/** Names each server function for telemetry recorded while it runs, such as the RPC observer's span and metrics. */\nexport function serverFunctionIdentityMiddleware() {\n return createMiddleware({ type: 'function' }).server(({ serverFnMeta, next }) =>\n withServerFunction({ name: serverFnMeta.name, filename: serverFnMeta.filename }, next),\n )\n}\n\n/**\n * A tab opened before a deploy can call a server function the deploy removed. TanStack answers with a JSON 500 that\n * its client returns as a successful result, so this replaces it with a plain-text 404 the client throws with `message`.\n */\nexport function staleServerFunctionMiddleware(message: string) {\n return createMiddleware({ type: 'request' }).server(async ({ handlerType, next }) => {\n if (handlerType !== 'serverFn') return next()\n try {\n return await next()\n } catch (error) {\n if (!(error instanceof Error && error.message.startsWith('Server function info not found for '))) throw error\n return new Response(message, { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })\n }\n })\n}\n"]}
@@ -1,19 +1,10 @@
1
1
  import { type OriginOptions } from '../auth/origins.js';
2
- import { type HealthResponseOptions, type RpcOptions } from '../server/index.js';
3
- export { canonicalHostMiddleware, canonicalHostRequest, serverFunctionIdentityMiddleware } from './middleware.js';
2
+ import { type HealthResponseOptions } from '../server/health.js';
3
+ import { type RpcOptions } from '../server/rpc.js';
4
4
  export type TanStackRpcOptions = Omit<RpcOptions, 'getRequest'> & Pick<RpcOptions, 'getRequest'>;
5
5
  export declare function createTanStackRpc(options?: TanStackRpcOptions): {
6
6
  rpc: <T>(work: () => Promise<T> | T) => Promise<T>;
7
7
  mutationRpc: <T>(work: () => Promise<T> | T, request?: Request | undefined) => Promise<T>;
8
8
  };
9
9
  export declare function requireTanStackMutationOrigin(options?: OriginOptions, request?: Request): void;
10
- type RequestContext = {
11
- request: Request;
12
- };
13
- export declare function betterAuthHandlers(resolveAuth: () => {
14
- handler(request: Request): Response | Promise<Response>;
15
- }): {
16
- GET: ({ request }: RequestContext) => Promise<Response> | Response;
17
- POST: ({ request }: RequestContext) => Promise<Response> | Response;
18
- };
19
10
  export declare function tanStackHealthHandler(check: () => void | Promise<void>, options?: HealthResponseOptions): () => Promise<Response>;
@@ -1,17 +1,13 @@
1
1
  import { getRequest } from '@tanstack/react-start/server';
2
2
  import { requireSameOrigin } from '../auth/origins.js';
3
- import { createRpc, healthResponse } from '../server/index.js';
4
- export { canonicalHostMiddleware, canonicalHostRequest, serverFunctionIdentityMiddleware } from './middleware.js';
3
+ import { healthResponse } from '../server/health.js';
4
+ import { createRpc } from '../server/rpc.js';
5
5
  export function createTanStackRpc(options = {}) {
6
6
  return createRpc({ ...options, getRequest: options.getRequest ?? getRequest });
7
7
  }
8
8
  export function requireTanStackMutationOrigin(options = {}, request = getRequest()) {
9
9
  return requireSameOrigin(request, options);
10
10
  }
11
- export function betterAuthHandlers(resolveAuth) {
12
- const handle = ({ request }) => resolveAuth().handler(request);
13
- return { GET: handle, POST: handle };
14
- }
15
11
  export function tanStackHealthHandler(check, options = {}) {
16
12
  return () => healthResponse(check, options);
17
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/tanstack/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAA;AACzD,OAAO,EAAE,iBAAiB,EAAsB,MAAM,oBAAoB,CAAA;AAC1E,OAAO,EAAE,SAAS,EAAE,cAAc,EAA+C,MAAM,oBAAoB,CAAA;AAC3G,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,gCAAgC,EAAE,MAAM,iBAAiB,CAAA;AAIjH,MAAM,UAAU,iBAAiB,CAAC,OAAO,GAAuB,EAAE;IAChE,OAAO,SAAS,CAAC,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,UAAU,EAAE,CAAC,CAAA;AAChF,CAAC;AAED,MAAM,UAAU,6BAA6B,CAAC,OAAO,GAAkB,EAAE,EAAE,OAAO,GAAG,UAAU,EAAE;IAC/F,OAAO,iBAAiB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;AAC5C,CAAC;AAID,MAAM,UAAU,kBAAkB,CAAC,WAA8E;IAC/G,MAAM,MAAM,GAAG,CAAC,EAAE,OAAO,EAAkB,EAAE,EAAE,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;IAC9E,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,CAAA;AACtC,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAAiC,EAAE,OAAO,GAA0B,EAAE;IAC1G,OAAO,GAAG,EAAE,CAAC,cAAc,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;AAC7C,CAAC","sourcesContent":["import { getRequest } from '@tanstack/react-start/server'\nimport { requireSameOrigin, type OriginOptions } from '../auth/origins.js'\nimport { createRpc, healthResponse, type HealthResponseOptions, type RpcOptions } from '../server/index.js'\nexport { canonicalHostMiddleware, canonicalHostRequest, serverFunctionIdentityMiddleware } from './middleware.js'\n\nexport type TanStackRpcOptions = Omit<RpcOptions, 'getRequest'> & Pick<RpcOptions, 'getRequest'>\n\nexport function createTanStackRpc(options: TanStackRpcOptions = {}) {\n return createRpc({ ...options, getRequest: options.getRequest ?? getRequest })\n}\n\nexport function requireTanStackMutationOrigin(options: OriginOptions = {}, request = getRequest()) {\n return requireSameOrigin(request, options)\n}\n\ntype RequestContext = { request: Request }\n\nexport function betterAuthHandlers(resolveAuth: () => { handler(request: Request): Response | Promise<Response> }) {\n const handle = ({ request }: RequestContext) => resolveAuth().handler(request)\n return { GET: handle, POST: handle }\n}\n\nexport function tanStackHealthHandler(check: () => void | Promise<void>, options: HealthResponseOptions = {}) {\n return () => healthResponse(check, options)\n}\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/tanstack/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAA;AACzD,OAAO,EAAE,iBAAiB,EAAsB,MAAM,oBAAoB,CAAA;AAC1E,OAAO,EAAE,cAAc,EAA8B,MAAM,qBAAqB,CAAA;AAChF,OAAO,EAAE,SAAS,EAAmB,MAAM,kBAAkB,CAAA;AAI7D,MAAM,UAAU,iBAAiB,CAAC,OAAO,GAAuB,EAAE;IAChE,OAAO,SAAS,CAAC,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,UAAU,EAAE,CAAC,CAAA;AAChF,CAAC;AAED,MAAM,UAAU,6BAA6B,CAAC,OAAO,GAAkB,EAAE,EAAE,OAAO,GAAG,UAAU,EAAE;IAC/F,OAAO,iBAAiB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;AAC5C,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,KAAiC,EAAE,OAAO,GAA0B,EAAE;IAC1G,OAAO,GAAG,EAAE,CAAC,cAAc,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;AAC7C,CAAC","sourcesContent":["import { getRequest } from '@tanstack/react-start/server'\nimport { requireSameOrigin, type OriginOptions } from '../auth/origins.js'\nimport { healthResponse, type HealthResponseOptions } from '../server/health.js'\nimport { createRpc, type RpcOptions } from '../server/rpc.js'\n\nexport type TanStackRpcOptions = Omit<RpcOptions, 'getRequest'> & Pick<RpcOptions, 'getRequest'>\n\nexport function createTanStackRpc(options: TanStackRpcOptions = {}) {\n return createRpc({ ...options, getRequest: options.getRequest ?? getRequest })\n}\n\nexport function requireTanStackMutationOrigin(options: OriginOptions = {}, request = getRequest()) {\n return requireSameOrigin(request, options)\n}\n\nexport function tanStackHealthHandler(check: () => void | Promise<void>, options: HealthResponseOptions = {}) {\n return () => healthResponse(check, options)\n}\n"]}
@@ -27,9 +27,3 @@ export type TusUploadStartOptions = {
27
27
  };
28
28
  export declare function createTusUpload(options: TusUploadOptions): Upload;
29
29
  export declare function startTusUpload(upload: Upload, options?: boolean | TusUploadStartOptions): Promise<TusUploadResult>;
30
- export declare function uploadWithTus(options: TusUploadOptions, startOptions?: boolean | TusUploadStartOptions): Promise<TusUploadResult>;
31
- export declare function tusResponseMessage(error: unknown): string | undefined;
32
- export declare function tusResponse(error: unknown): {
33
- status: number | undefined;
34
- body: string;
35
- } | undefined;
@@ -77,31 +77,6 @@ export async function startTusUpload(upload, options = true) {
77
77
  signal?.removeEventListener('abort', abort);
78
78
  }
79
79
  }
80
- export function uploadWithTus(options, startOptions = true) {
81
- return startTusUpload(createTusUpload(options), startOptions);
82
- }
83
- export function tusResponseMessage(error) {
84
- const response = responseFromError(error);
85
- if (response)
86
- return response.body;
87
- const message = error instanceof Error ? error.message : undefined;
88
- return message ? /response text: ([^,]+)/.exec(message)?.[1]?.trim() : undefined;
89
- }
90
- export function tusResponse(error) {
91
- return responseFromError(error);
92
- }
93
- function responseFromError(error) {
94
- if (!error || typeof error !== 'object' || !('originalResponse' in error))
95
- return undefined;
96
- const response = error.originalResponse;
97
- if (!response || typeof response !== 'object' || !('getStatus' in response) || !('getBody' in response))
98
- return undefined;
99
- if (typeof response.getStatus !== 'function' || typeof response.getBody !== 'function')
100
- return undefined;
101
- const status = response.getStatus();
102
- const body = response.getBody();
103
- return { status: typeof status === 'number' ? status : undefined, body: typeof body === 'string' ? body : '' };
104
- }
105
80
  function tusAbortError() {
106
81
  return new DOMException('Upload cancelled', 'AbortError');
107
82
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/uploads/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,EAAsB,MAAM,eAAe,CAAA;AA4B1E,MAAM,UAAU,eAAe,CAAC,OAAyB;IACvD,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE;QAC9B,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,WAAW,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,WAAW,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QACnE,GAAG,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC;QAC5E,GAAG,CAAC,OAAO,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,OAAO,CAAC,WAAW,EAAE,CAAC;QAClF,GAAG,CAAC,OAAO,CAAC,0BAA0B,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,0BAA0B,EAAE,OAAO,CAAC,0BAA0B,EAAE,CAAC;QAC/H,aAAa,EAAE,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,EAAE;YACpD,MAAM,MAAM,GAAG,KAAK,CAAC,gBAAgB,EAAE,SAAS,EAAE,CAAA;YAClD,IAAI,OAAO,CAAC,WAAW,IAAI,CAAC,O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BAAkB,IAAI,KAAK,CAAC;QAAE,OAAO,SAAS,CAAA;IAC3F,MAAM,QAAQ,GAAG,KAAK,CAAC,gBAAgB,CAAA;IACvC,IAAI,CAAC,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,WAAW,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,SAAS,IAAI,QAAQ,CAAC;QAAE,OAAO,SAAS,CAAA;IACzH,IAAI,OAAO,QAAQ,CAAC,SAAS,KAAK,UAAU,IAAI,OAAO,QAAQ,CAAC,OAAO,KAAK,UAAU;QAAE,OAAO,SAAS,CAAA;IACxG,MAAM,MAAM,GAAY,QAAQ,CAAC,SAAS,EAAE,CAAA;IAC5C,MAAM,IAAI,GAAY,QAAQ,CAAC,OAAO,EAAE,CAAA;IACxC,OAAO,EAAE,MAAM,EAAE,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,EAAE,IAAI,EAAE,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAA;AAChH,CAAC;AAED,SAAS,aAAa;IACpB,OAAO,IAAI,YAAY,CAAC,kBAAkB,EAAE,YAAY,CAAC,CAAA;AAC3D,CAAC","sourcesContent":["import { defaultOptions, Upload, type UploadOptions } from 'tus-js-client'\n\nexport type TusUploadProgress = { sent: number; total: number; percent: number }\n\nexport type TusUploadOptions = {\n endpoint: string\n file: File\n metadata: Record<string, string>\n chunkSize?: number\n retryDelays?: readonly number[]\n fingerprint?: UploadOptions['fingerprint']\n removeFingerprintOnSuccess?: boolean\n shouldRetry?: (status: number | undefined, retryAttempt: number) => boolean\n onProgress?: (progress: TusUploadProgress) => void\n}\n\nexport type TusUploadResult = {\n responseBody: string\n responseStatus: number | undefined\n uploadUrl: string | null\n}\n\nexport type TusUploadStartOptions = {\n resume?: boolean\n signal?: AbortSignal\n terminateOnAbort?: boolean\n}\n\nexport function createTusUpload(options: TusUploadOptions) {\n return new Upload(options.file, {\n endpoint: options.endpoint,\n metadata: options.metadata,\n retryDelays: [...(options.retryDelays ?? [0, 1_000, 3_000, 5_000])],\n ...(options.chunkSize === undefined ? {} : { chunkSize: options.chunkSize }),\n ...(options.fingerprint === undefined ? {} : { fingerprint: options.fingerprint }),\n ...(options.removeFingerprintOnSuccess === undefined ? {} : { removeFingerprintOnSuccess: options.removeFingerprintOnSuccess }),\n onShouldRetry: (error, retryAttempt, uploadOptions) => {\n const status = error.originalResponse?.getStatus()\n if (options.shouldRetry && !options.shouldRetry(status, retryAttempt)) return false\n return defaultOptions.onShouldRetry?.(error, retryAttempt, uploadOptions) === true\n },\n onProgress: (sent, total) => options.onProgress?.({ sent, total, percent: total ? Math.round((sent / total) * 100) : 0 }),\n })\n}\n\nexport async function startTusUpload(upload: Upload, options: boolean | TusUploadStartOptions = true): Promise<TusUploadResult> {\n const { resume = true, signal, terminateOnAbort = false } = typeof options === 'boolean' ? { resume: options } : options\n if (signal?.aborted) throw tusAbortError()\n let rejectAbort: ((reason: unknown) => void) | undefined\n const aborted = signal\n ? new Promise<never>((_resolve, reject) => {\n rejectAbort = reject\n })\n : undefined\n const abort = () => {\n rejectAbort?.(tusAbortError())\n // Remote termination is best-effort after local cancellation has settled for the caller.\n void Promise.resolve()\n .then(() => upload.abort(terminateOnAbort))\n .catch(() => undefined)\n }\n signal?.addEventListener('abort', abort, { once: true })\n\n const run = async () => {\n if (resume) {\n const previous = await upload.findPreviousUploads()\n if (signal?.aborted) throw tusAbortError()\n if (previous[0]) upload.resumeFromPreviousUpload(previous[0])\n }\n\n return new Promise<TusUploadResult>((resolve, reject) => {\n const previousError = upload.options.onError\n const previousSuccess = upload.options.onSuccess\n upload.options.onError = (error) => {\n try {\n previousError?.(error)\n } finally {\n reject(error)\n }\n }\n upload.options.onSuccess = (event) => {\n try {\n previousSuccess?.(event)\n resolve({\n responseBody: event.lastResponse.getBody(),\n responseStatus: event.lastResponse.getStatus(),\n uploadUrl: upload.url,\n })\n } catch (error) {\n reject(error)\n }\n }\n upload.start()\n })\n }\n\n try {\n const result = run()\n return await (aborted ? Promise.race([result, aborted]) : result)\n } finally {\n signal?.removeEventListener('abort', abort)\n }\n}\n\nexport function uploadWithTus(options: TusUploadOptions, startOptions: boolean | TusUploadStartOptions = true) {\n return startTusUpload(createTusUpload(options), startOptions)\n}\n\nexport function tusResponseMessage(error: unknown) {\n const response = responseFromError(error)\n if (response) return response.body\n const message = error instanceof Error ? error.message : undefined\n return message ? /response text: ([^,]+)/.exec(message)?.[1]?.trim() : undefined\n}\n\nexport function tusResponse(error: unknown) {\n return responseFromError(error)\n}\n\nfunction responseFromError(error: unknown) {\n if (!error || typeof error !== 'object' || !('originalResponse' in error)) return undefined\n const response = error.originalResponse\n if (!response || typeof response !== 'object' || !('getStatus' in response) || !('getBody' in response)) return undefined\n if (typeof response.getStatus !== 'function' || typeof response.getBody !== 'function') return undefined\n const status: unknown = response.getStatus()\n const body: unknown = response.getBody()\n return { status: typeof status === 'number' ? status : undefined, body: typeof body === 'string' ? body : '' }\n}\n\nfunction tusAbortError() {\n return new DOMException('Upload cancelled', 'AbortError')\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/uploads/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,EAAsB,MAAM,eAAe,CAAA;AA4B1E,MAAM,UAAU,eAAe,CAAC,OAAyB;IACvD,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE;QAC9B,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,WAAW,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,WAAW,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QACnE,GAAG,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,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O,CAAC,OAAO,GAAG,CAAC,KAAK,EAAE,EAAE;gBACjC,IAAI,CAAC;oBACH,aAAa,EAAE,CAAC,KAAK,CAAC,CAAA;gBACxB,CAAC;wBAAS,CAAC;oBACT,MAAM,CAAC,KAAK,CAAC,CAAA;gBACf,CAAC;YACH,CAAC,CAAA;YACD,MAAM,CAAC,OAAO,CAAC,SAAS,GAAG,CAAC,KAAK,EAAE,EAAE;gBACnC,IAAI,CAAC;oBACH,eAAe,EAAE,CAAC,KAAK,CAAC,CAAA;oBACxB,OAAO,CAAC;wBACN,YAAY,EAAE,KAAK,CAAC,YAAY,CAAC,OAAO,EAAE;wBAC1C,cAAc,EAAE,KAAK,CAAC,YAAY,CAAC,SAAS,EAAE;wBAC9C,SAAS,EAAE,MAAM,CAAC,GAAG;qBACtB,CAAC,CAAA;gBACJ,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,MAAM,CAAC,KAAK,CAAC,CAAA;gBACf,CAAC;YACH,CAAC,CAAA;YACD,MAAM,CAAC,KAAK,EAAE,CAAA;QAChB,CAAC,CAAC,CAAA;IACJ,CAAC,CAAA;IAED,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,GAAG,EAAE,CAAA;QACpB,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;IACnE,CAAC;YAAS,CAAC;QACT,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IAC7C,CAAC;AACH,CAAC;AAED,SAAS,aAAa;IACpB,OAAO,IAAI,YAAY,CAAC,kBAAkB,EAAE,YAAY,CAAC,CAAA;AAC3D,CAAC","sourcesContent":["import { defaultOptions, Upload, type UploadOptions } from 'tus-js-client'\n\nexport type TusUploadProgress = { sent: number; total: number; percent: number }\n\nexport type TusUploadOptions = {\n endpoint: string\n file: File\n metadata: Record<string, string>\n chunkSize?: number\n retryDelays?: readonly number[]\n fingerprint?: UploadOptions['fingerprint']\n removeFingerprintOnSuccess?: boolean\n shouldRetry?: (status: number | undefined, retryAttempt: number) => boolean\n onProgress?: (progress: TusUploadProgress) => void\n}\n\nexport type TusUploadResult = {\n responseBody: string\n responseStatus: number | undefined\n uploadUrl: string | null\n}\n\nexport type TusUploadStartOptions = {\n resume?: boolean\n signal?: AbortSignal\n terminateOnAbort?: boolean\n}\n\nexport function createTusUpload(options: TusUploadOptions) {\n return new Upload(options.file, {\n endpoint: options.endpoint,\n metadata: options.metadata,\n retryDelays: [...(options.retryDelays ?? [0, 1_000, 3_000, 5_000])],\n ...(options.chunkSize === undefined ? {} : { chunkSize: options.chunkSize }),\n ...(options.fingerprint === undefined ? {} : { fingerprint: options.fingerprint }),\n ...(options.removeFingerprintOnSuccess === undefined ? {} : { removeFingerprintOnSuccess: options.removeFingerprintOnSuccess }),\n onShouldRetry: (error, retryAttempt, uploadOptions) => {\n const status = error.originalResponse?.getStatus()\n if (options.shouldRetry && !options.shouldRetry(status, retryAttempt)) return false\n return defaultOptions.onShouldRetry?.(error, retryAttempt, uploadOptions) === true\n },\n onProgress: (sent, total) => options.onProgress?.({ sent, total, percent: total ? Math.round((sent / total) * 100) : 0 }),\n })\n}\n\nexport async function startTusUpload(upload: Upload, options: boolean | TusUploadStartOptions = true): Promise<TusUploadResult> {\n const { resume = true, signal, terminateOnAbort = false } = typeof options === 'boolean' ? { resume: options } : options\n if (signal?.aborted) throw tusAbortError()\n let rejectAbort: ((reason: unknown) => void) | undefined\n const aborted = signal\n ? new Promise<never>((_resolve, reject) => {\n rejectAbort = reject\n })\n : undefined\n const abort = () => {\n rejectAbort?.(tusAbortError())\n // Remote termination is best-effort after local cancellation has settled for the caller.\n void Promise.resolve()\n .then(() => upload.abort(terminateOnAbort))\n .catch(() => undefined)\n }\n signal?.addEventListener('abort', abort, { once: true })\n\n const run = async () => {\n if (resume) {\n const previous = await upload.findPreviousUploads()\n if (signal?.aborted) throw tusAbortError()\n if (previous[0]) upload.resumeFromPreviousUpload(previous[0])\n }\n\n return new Promise<TusUploadResult>((resolve, reject) => {\n const previousError = upload.options.onError\n const previousSuccess = upload.options.onSuccess\n upload.options.onError = (error) => {\n try {\n previousError?.(error)\n } finally {\n reject(error)\n }\n }\n upload.options.onSuccess = (event) => {\n try {\n previousSuccess?.(event)\n resolve({\n responseBody: event.lastResponse.getBody(),\n responseStatus: event.lastResponse.getStatus(),\n uploadUrl: upload.url,\n })\n } catch (error) {\n reject(error)\n }\n }\n upload.start()\n })\n }\n\n try {\n const result = run()\n return await (aborted ? Promise.race([result, aborted]) : result)\n } finally {\n signal?.removeEventListener('abort', abort)\n }\n}\n\nfunction tusAbortError() {\n return new DOMException('Upload cancelled', 'AbortError')\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ras-stack",
3
- "version": "3.2.0",
3
+ "version": "4.1.0",
4
4
  "description": "Composable full-stack primitives shared across Richard Solomou's applications.",
5
5
  "keywords": [
6
6
  "authentication",
@@ -42,10 +42,6 @@
42
42
  "types": "./dist/email/index.d.ts",
43
43
  "default": "./dist/email/index.js"
44
44
  },
45
- "./build": {
46
- "types": "./dist/build/index.d.ts",
47
- "default": "./dist/build/index.js"
48
- },
49
45
  "./database": {
50
46
  "types": "./dist/database/index.d.ts",
51
47
  "default": "./dist/database/index.js"
@@ -70,10 +66,6 @@
70
66
  "types": "./dist/posthog/index.d.ts",
71
67
  "default": "./dist/posthog/index.js"
72
68
  },
73
- "./posthog/client": {
74
- "types": "./dist/posthog/client.d.ts",
75
- "default": "./dist/posthog/client.js"
76
- },
77
69
  "./posthog/proxy": {
78
70
  "types": "./dist/posthog/proxy.d.ts",
79
71
  "default": "./dist/posthog/proxy.js"
@@ -90,10 +82,6 @@
90
82
  "types": "./dist/preview/dokploy.d.ts",
91
83
  "default": "./dist/preview/dokploy.js"
92
84
  },
93
- "./preview/github": {
94
- "types": "./dist/preview/github.d.ts",
95
- "default": "./dist/preview/github.js"
96
- },
97
85
  "./realtime": {
98
86
  "types": "./dist/realtime/index.d.ts",
99
87
  "default": "./dist/realtime/index.js"
@@ -114,6 +102,10 @@
114
102
  "types": "./dist/runtime/index.d.ts",
115
103
  "default": "./dist/runtime/index.js"
116
104
  },
105
+ "./spacetime": {
106
+ "types": "./dist/spacetime/index.d.ts",
107
+ "default": "./dist/spacetime/index.js"
108
+ },
117
109
  "./tanstack/client": {
118
110
  "types": "./dist/tanstack/client.d.ts",
119
111
  "default": "./dist/tanstack/client.js"
@@ -129,10 +121,6 @@
129
121
  "./uploads": {
130
122
  "types": "./dist/uploads/index.d.ts",
131
123
  "default": "./dist/uploads/index.js"
132
- },
133
- "./changesets": {
134
- "types": "./dist/changesets/index.d.ts",
135
- "default": "./dist/changesets/index.js"
136
124
  }
137
125
  },
138
126
  "publishConfig": {
@@ -173,7 +161,7 @@
173
161
  "vite": "8.2.1",
174
162
  "vitest": "^4.1.10",
175
163
  "yaml": "^2.8.2",
176
- "ras-stack-config": "2.0.0"
164
+ "ras-stack-config": "3.0.0"
177
165
  },
178
166
  "peerDependencies": {
179
167
  "@libsql/client": ">=0.18 <1",
@@ -1,30 +0,0 @@
1
- import type { RateLimitRule } from '../auth/settings.js';
2
- export type RateLimitCounter = {
3
- count: number;
4
- resetAt: number;
5
- };
6
- export type RateLimitStore = {
7
- increment: (key: string, windowSeconds: number, now: number) => Promise<RateLimitCounter> | RateLimitCounter;
8
- };
9
- export type RateLimitDecision = {
10
- key: string;
11
- remaining: number;
12
- resetAt: number;
13
- };
14
- export type RateLimitOptions = {
15
- store: RateLimitStore;
16
- rule: RateLimitRule;
17
- identify: (request: Request) => string | undefined;
18
- scope?: string;
19
- onUnidentified?: 'reject' | 'allow';
20
- onUnavailable?: 'reject' | 'allow';
21
- now?: () => number;
22
- };
23
- export declare function createRateLimit(options: RateLimitOptions): (request: Request) => Promise<RateLimitDecision | undefined>;
24
- export declare function memoryRateLimitStore(options?: {
25
- maxKeys?: number;
26
- }): RateLimitStore;
27
- export declare function rateLimitTable(name: string): string;
28
- export declare function forwardedClientAddress(request: Request, options?: {
29
- trustForwardedHeaders?: boolean;
30
- }): string | undefined;
@@ -1,73 +0,0 @@
1
- import { InfrastructureError } from './errors.js';
2
- export function createRateLimit(options) {
3
- const scope = options.scope ?? 'default';
4
- const { window, max } = options.rule;
5
- if (!Number.isSafeInteger(window) || window < 1)
6
- throw new RangeError('rate limit window must be a positive integer');
7
- if (!Number.isSafeInteger(max) || max < 1)
8
- throw new RangeError('rate limit max must be a positive integer');
9
- return async function limit(request) {
10
- const now = Math.floor((options.now?.() ?? Date.now()) / 1000);
11
- const identity = options.identify(request);
12
- if (!identity) {
13
- if ((options.onUnidentified ?? 'reject') === 'allow')
14
- return undefined;
15
- throw rejection('unidentified client rejected', 403, window);
16
- }
17
- const key = `${scope}:${identity}`;
18
- let counter;
19
- try {
20
- counter = await options.store.increment(key, window, now);
21
- }
22
- catch (error) {
23
- if ((options.onUnavailable ?? 'reject') === 'allow')
24
- return undefined;
25
- // A store outage is infrastructure rather than a client fault, so it classifies with everything else that is retryable.
26
- throw new InfrastructureError('rate_limit_unavailable', 'rate limit is temporarily unavailable', { cause: error, retryable: true });
27
- }
28
- if (counter.count > max)
29
- throw rejection('rate limit exceeded', 429, Math.max(counter.resetAt - now, 1));
30
- return { key, remaining: max - counter.count, resetAt: counter.resetAt };
31
- };
32
- }
33
- // Counters live in one process, so this is for development and tests; replicas each enforce their own budget.
34
- export function memoryRateLimitStore(options = {}) {
35
- const maxKeys = options.maxKeys ?? 10_000;
36
- const counters = new Map();
37
- return {
38
- increment(key, windowSeconds, now) {
39
- const existing = counters.get(key);
40
- if (existing && existing.resetAt > now) {
41
- existing.count += 1;
42
- return existing;
43
- }
44
- if (counters.size >= maxKeys) {
45
- for (const [candidate, counter] of counters)
46
- if (counter.resetAt <= now)
47
- counters.delete(candidate);
48
- // Expiring nothing under a burst of distinct keys would otherwise grow the map without a bound.
49
- while (counters.size >= maxKeys)
50
- counters.delete(counters.keys().next().value);
51
- }
52
- const counter = { count: 1, resetAt: now + windowSeconds };
53
- counters.set(key, counter);
54
- return counter;
55
- },
56
- };
57
- }
58
- // Stores interpolate the table into SQL, and only better-sqlite3 lacks an identifier escape, so the name is validated for both.
59
- export function rateLimitTable(name) {
60
- if (!/^[a-z_][a-z\d_]*$/i.test(name))
61
- throw new Error('rate limit table must be an unquoted SQL identifier');
62
- return name;
63
- }
64
- // A forwarded address is only as trustworthy as the proxy that set it, so reading it stays opt-in.
65
- export function forwardedClientAddress(request, options = {}) {
66
- if (!options.trustForwardedHeaders)
67
- return undefined;
68
- return request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || undefined;
69
- }
70
- function rejection(message, status, retryAfterSeconds) {
71
- return new Response(message, { status, headers: { 'retry-after': String(retryAfterSeconds) } });
72
- }
73
- //# sourceMappingURL=rate-limit.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rate-limit.js","sourceRoot":"","sources":["../../src/server/rate-limit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AAoBjD,MAAM,UAAU,eAAe,CAAC,OAAyB;IACvD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,SAAS,CAAA;IACxC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,OAAO,CAAC,IAAI,CAAA;IACpC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC;QAAE,MAAM,IAAI,UAAU,CAAC,8CAA8C,CAAC,CAAA;IACrH,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC;QAAE,MAAM,IAAI,UAAU,CAAC,2CAA2C,CAAC,CAAA;IAE5G,OAAO,KAAK,UAAU,KAAK,CAAC,OAAgB;QAC1C,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,C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G;AACnG,MAAM,UAAU,sBAAsB,CAAC,OAAgB,EAAE,OAAO,GAAwC,EAAE;IACxG,IAAI,CAAC,OAAO,CAAC,qBAAqB;QAAE,OAAO,SAAS,CAAA;IACpD,OAAO,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,SAAS,CAAA;AACnF,CAAC;AAED,SAAS,SAAS,CAAC,OAAe,EAAE,MAAc,EAAE,iBAAyB;IAC3E,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,aAAa,EAAE,MAAM,CAAC,iBAAiB,CAAC,EAAE,EAAE,CAAC,CAAA;AACjG,CAAC","sourcesContent":["import type { RateLimitRule } from '../auth/settings.js'\nimport { InfrastructureError } from './errors.js'\n\nexport type RateLimitCounter = { count: number; resetAt: number }\n\nexport type RateLimitStore = {\n increment: (key: string, windowSeconds: number, now: number) => Promise<RateLimitCounter> | RateLimitCounter\n}\n\nexport type RateLimitDecision = { key: string; remaining: number; resetAt: number }\n\nexport type RateLimitOptions = {\n store: RateLimitStore\n rule: RateLimitRule\n identify: (request: Request) => string | undefined\n scope?: string\n onUnidentified?: 'reject' | 'allow'\n onUnavailable?: 'reject' | 'allow'\n now?: () => number\n}\n\nexport function createRateLimit(options: RateLimitOptions) {\n const scope = options.scope ?? 'default'\n const { window, max } = options.rule\n if (!Number.isSafeInteger(window) || window < 1) throw new RangeError('rate limit window must be a positive integer')\n if (!Number.isSafeInteger(max) || max < 1) throw new RangeError('rate limit max must be a positive integer')\n\n return async function limit(request: Request): Promise<RateLimitDecision | undefined> {\n const now = Math.floor((options.now?.() ?? Date.now()) / 1000)\n const identity = options.identify(request)\n if (!identity) {\n if ((options.onUnidentified ?? 'reject') === 'allow') return undefined\n throw rejection('unidentified client rejected', 403, window)\n }\n\n const key = `${scope}:${identity}`\n let counter: RateLimitCounter\n try {\n counter = await options.store.increment(key, window, now)\n } catch (error) {\n if ((options.onUnavailable ?? 'reject') === 'allow') return undefined\n // A store outage is infrastructure rather than a client fault, so it classifies with everything else that is retryable.\n throw new InfrastructureError('rate_limit_unavailable', 'rate limit is temporarily unavailable', { cause: error, retryable: true })\n }\n\n if (counter.count > max) throw rejection('rate limit exceeded', 429, Math.max(counter.resetAt - now, 1))\n return { key, remaining: max - counter.count, resetAt: counter.resetAt }\n }\n}\n\n// Counters live in one process, so this is for development and tests; replicas each enforce their own budget.\nexport function memoryRateLimitStore(options: { maxKeys?: number } = {}): RateLimitStore {\n const maxKeys = options.maxKeys ?? 10_000\n const counters = new Map<string, RateLimitCounter>()\n return {\n increment(key, windowSeconds, now) {\n const existing = counters.get(key)\n if (existing && existing.resetAt > now) {\n existing.count += 1\n return existing\n }\n if (counters.size >= maxKeys) {\n for (const [candidate, counter] of counters) if (counter.resetAt <= now) counters.delete(candidate)\n // Expiring nothing under a burst of distinct keys would otherwise grow the map without a bound.\n while (counters.size >= maxKeys) counters.delete(counters.keys().next().value!)\n }\n const counter = { count: 1, resetAt: now + windowSeconds }\n counters.set(key, counter)\n return counter\n },\n }\n}\n\n// Stores interpolate the table into SQL, and only better-sqlite3 lacks an identifier escape, so the name is validated for both.\nexport function rateLimitTable(name: string) {\n if (!/^[a-z_][a-z\\d_]*$/i.test(name)) throw new Error('rate limit table must be an unquoted SQL identifier')\n return name\n}\n\n// A forwarded address is only as trustworthy as the proxy that set it, so reading it stays opt-in.\nexport function forwardedClientAddress(request: Request, options: { trustForwardedHeaders?: boolean } = {}) {\n if (!options.trustForwardedHeaders) return undefined\n return request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || undefined\n}\n\nfunction rejection(message: string, status: number, retryAfterSeconds: number) {\n return new Response(message, { status, headers: { 'retry-after': String(retryAfterSeconds) } })\n}\n"]}