@deepraxis/sdk 0.0.0-stage → 0.1.0-dev.086e3bf

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 (64) hide show
  1. package/LICENSE +202 -0
  2. package/METHODS.md +1211 -0
  3. package/README.md +279 -2
  4. package/dist/automation.d.ts +151 -0
  5. package/dist/automation.js +8 -0
  6. package/dist/core/bindings.d.ts +25 -0
  7. package/dist/core/bindings.js +45 -0
  8. package/dist/core/client.d.ts +15 -0
  9. package/dist/core/client.js +15 -0
  10. package/dist/core/credentials.d.ts +14 -0
  11. package/dist/core/credentials.js +33 -0
  12. package/dist/core/errors.d.ts +38 -0
  13. package/dist/core/errors.js +60 -0
  14. package/dist/core/multipart.d.ts +2 -0
  15. package/dist/core/multipart.js +25 -0
  16. package/dist/core/pagination.d.ts +12 -0
  17. package/dist/core/pagination.js +26 -0
  18. package/dist/core/retry.d.ts +13 -0
  19. package/dist/core/retry.js +56 -0
  20. package/dist/core/sse.d.ts +13 -0
  21. package/dist/core/sse.js +67 -0
  22. package/dist/core/transport.d.ts +36 -0
  23. package/dist/core/transport.js +121 -0
  24. package/dist/generated/client/client.gen.d.ts +2 -0
  25. package/dist/generated/client/client.gen.js +216 -0
  26. package/dist/generated/client/index.d.ts +10 -0
  27. package/dist/generated/client/index.js +6 -0
  28. package/dist/generated/client/types.gen.d.ts +120 -0
  29. package/dist/generated/client/types.gen.js +2 -0
  30. package/dist/generated/client/utils.gen.d.ts +37 -0
  31. package/dist/generated/client/utils.gen.js +228 -0
  32. package/dist/generated/client.gen.d.ts +12 -0
  33. package/dist/generated/client.gen.js +3 -0
  34. package/dist/generated/core/auth.gen.d.ts +25 -0
  35. package/dist/generated/core/auth.gen.js +14 -0
  36. package/dist/generated/core/bodySerializer.gen.d.ts +25 -0
  37. package/dist/generated/core/bodySerializer.gen.js +57 -0
  38. package/dist/generated/core/params.gen.d.ts +43 -0
  39. package/dist/generated/core/params.gen.js +109 -0
  40. package/dist/generated/core/pathSerializer.gen.d.ts +33 -0
  41. package/dist/generated/core/pathSerializer.gen.js +106 -0
  42. package/dist/generated/core/queryKeySerializer.gen.d.ts +18 -0
  43. package/dist/generated/core/queryKeySerializer.gen.js +92 -0
  44. package/dist/generated/core/serverSentEvents.gen.d.ts +71 -0
  45. package/dist/generated/core/serverSentEvents.gen.js +132 -0
  46. package/dist/generated/core/types.gen.d.ts +83 -0
  47. package/dist/generated/core/types.gen.js +2 -0
  48. package/dist/generated/core/utils.gen.d.ts +19 -0
  49. package/dist/generated/core/utils.gen.js +87 -0
  50. package/dist/generated/index.d.ts +2 -0
  51. package/dist/generated/index.js +2 -0
  52. package/dist/generated/sdk.gen.d.ts +2316 -0
  53. package/dist/generated/sdk.gen.js +6953 -0
  54. package/dist/generated/types.gen.d.ts +60343 -0
  55. package/dist/generated/types.gen.js +2 -0
  56. package/dist/helpers/application-publish.d.ts +61 -0
  57. package/dist/helpers/application-publish.js +166 -0
  58. package/dist/index.d.ts +9 -0
  59. package/dist/index.js +5 -0
  60. package/dist/operations.generated.d.ts +11393 -0
  61. package/dist/operations.generated.js +14372 -0
  62. package/dist/resources.generated.d.ts +4571 -0
  63. package/dist/resources.generated.js +770 -0
  64. package/package.json +50 -4
@@ -0,0 +1,2 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export {};
@@ -0,0 +1,61 @@
1
+ import type { Praxis } from '../core/client.js';
2
+ import type { ApplicationAssetsConfig, ApplicationBinding, ApplicationVersion } from '../generated/types.gen.js';
3
+ export type AssetsConfig = ApplicationAssetsConfig;
4
+ export interface PublishInput {
5
+ /** 应用名;存在同名应用时复用。 */
6
+ name: string;
7
+ /** 站点路径到 UTF-8 文本或字节内容;自动补前导 /。 */
8
+ files: Record<string, string | Uint8Array>;
9
+ /** 可选 Worker 入口脚本;省略时发布纯静态站点。 */
10
+ main?: {
11
+ name: string;
12
+ content: string;
13
+ content_type?: string;
14
+ };
15
+ /** 运行时兼容日期,默认当天 UTC(YYYY-MM-DD)。 */
16
+ compatibility_date?: string;
17
+ /** 运行时兼容标志,原样传递;平台固定附加 global_fetch_strictly_public。 */
18
+ compatibility_flags?: string[];
19
+ /** 绑定声明(d1、kv_namespace、r2_bucket、secret_text、plain_text、json 等),原样传递。 */
20
+ bindings?: ApplicationBinding[];
21
+ /** 静态资源路由配置,原样传递。 */
22
+ assets_config?: AssetsConfig;
23
+ /** Register an upload session to plan changes; do not upload content or publish. Requires an existing application. */
24
+ dryRun?: boolean;
25
+ /** Preserve current paths omitted from files. Defaults to false (whole-site replacement). */
26
+ keepExisting?: boolean;
27
+ /** 是否等待部署完成,默认 true。 */
28
+ wait?: boolean;
29
+ /** 部署等待上限(毫秒),默认 120000。超时不会撤销部署。 */
30
+ timeout_ms?: number;
31
+ }
32
+ export interface PublishResult {
33
+ /** True when a static-only publication matches the active version. */
34
+ unchanged?: boolean;
35
+ /** Current version when unchanged or planning an existing deployment. */
36
+ version?: ApplicationVersion;
37
+ /** dryRun compares against the active version; counts are distinct content hashes. */
38
+ plan?: {
39
+ added: string[];
40
+ changed: string[];
41
+ removed: string[];
42
+ upload_hashes: number;
43
+ existing_hashes: number;
44
+ };
45
+ url: string;
46
+ worker_id: string;
47
+ version_id: string | null;
48
+ deployment_id: string | null;
49
+ status: string;
50
+ created: boolean;
51
+ /** 本次上传的不同内容 hash 数量。 */
52
+ uploaded: number;
53
+ /** 服务端已存在的不同内容 hash 数量。 */
54
+ reused: number;
55
+ }
56
+ /** Publish with whole-site replacement by default; keepExisting preserves omitted paths.
57
+ * dryRun registers an idempotent upload session (stores its manifest), but uploads no content and does not publish.
58
+ * The platform does not support gradual rollout. Roll back using workers.deployments.create with
59
+ * strategy: 'percentage', versions: [{ version_id: previousVersionId, percentage: 100 }], while artifacts are retained.
60
+ */
61
+ export declare function publish(client: Pick<Praxis, 'application'>, input: PublishInput): Promise<PublishResult>;
@@ -0,0 +1,166 @@
1
+ import { PraxisError } from "../core/errors.js";
2
+ // Application contract: 100k paths, 25 MiB/file; session buckets: 50 files / 40 MiB.
3
+ const FILE_BYTES = 25 * 1024 * 1024;
4
+ function base64(bytes) {
5
+ const chunks = [];
6
+ for (let offset = 0; offset < bytes.length; offset += 8192) {
7
+ chunks.push(String.fromCharCode(...bytes.subarray(offset, offset + 8192)));
8
+ }
9
+ return btoa(chunks.join(''));
10
+ }
11
+ /** Publish with whole-site replacement by default; keepExisting preserves omitted paths.
12
+ * dryRun registers an idempotent upload session (stores its manifest), but uploads no content and does not publish.
13
+ * The platform does not support gradual rollout. Roll back using workers.deployments.create with
14
+ * strategy: 'percentage', versions: [{ version_id: previousVersionId, percentage: 100 }], while artifacts are retained.
15
+ */
16
+ export async function publish(client, input) {
17
+ const rolloutFields = ['gradual', 'gradualRollout', 'gradual_rollout', 'canary', 'rollout', 'percentage', 'percent', 'traffic', 'traffic_percentage', 'strategy', 'versions'];
18
+ if (Object.keys(input).some(key => rolloutFields.includes(key) || /percentage|percent|canary|gradual|rollout|灰度/i.test(key))) {
19
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: '平台不支持灰度 (gradual rollout is not supported). Roll back with praxis.application.workers.deployments.create({ path: { worker_id }, body: { strategy: "percentage", versions: [{ version_id: previousVersionId, percentage: 100 }] } }); the previous version artifacts must still be retained.' });
20
+ }
21
+ const timeout = input.timeout_ms ?? 120_000;
22
+ if (!Number.isFinite(timeout) || timeout < 0)
23
+ throw new RangeError('timeout_ms must be non-negative and finite');
24
+ const contentType = ['application/javascript+module', 'text/javascript', 'application/javascript', 'application/json',
25
+ 'text/plain', 'application/wasm', 'application/octet-stream', 'application/x-python']
26
+ .find(type => type === (input.main?.content_type ?? 'application/javascript+module'));
27
+ if (!contentType)
28
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: `Unsupported module content_type: ${input.main?.content_type}` });
29
+ const files = Object.entries(input.files);
30
+ if (files.length > 100_000)
31
+ throw new PraxisError({ code: 'LIMIT_EXCEEDED', message: 'At most 100000 asset paths can be published' });
32
+ let manifest = {};
33
+ const contents = new Map();
34
+ for (const [path, content] of files) {
35
+ const normalized = path.startsWith('/') ? path : `/${path}`;
36
+ if (Object.hasOwn(manifest, normalized))
37
+ throw new PraxisError({ code: 'INVALID_PARAMS', message: `Duplicate asset path: ${normalized}` });
38
+ const bytes = typeof content === 'string' ? new TextEncoder().encode(content) : new Uint8Array(content);
39
+ if (bytes.length > FILE_BYTES)
40
+ throw new PraxisError({ code: 'LIMIT_EXCEEDED', message: `Asset ${normalized} exceeds 25 MiB` });
41
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
42
+ const hash = Array.from(digest.subarray(0, 16), byte => byte.toString(16).padStart(2, '0')).join('');
43
+ manifest[normalized] = { hash, size: bytes.length };
44
+ contents.set(hash, bytes);
45
+ }
46
+ const { workers, assets } = client.application;
47
+ let worker;
48
+ for await (const candidate of await workers.list()) {
49
+ if (candidate.name === input.name) {
50
+ worker = candidate;
51
+ break;
52
+ }
53
+ }
54
+ const created = !worker;
55
+ if (!worker && input.dryRun)
56
+ throw new PraxisError({ code: 'NOT_FOUND', message: '请先创建应用 (create the application before dryRun)' });
57
+ worker ??= await workers.create({ body: { name: input.name, subdomain: { enabled: true } } });
58
+ const path = { worker_id: worker.id };
59
+ let currentVersion;
60
+ let currentDeployment;
61
+ let previous = {};
62
+ if (worker.praxis?.current_deployment_id) {
63
+ currentDeployment = await workers.deployments.retrieve({ path: { ...path, deployment_id: worker.praxis.current_deployment_id } });
64
+ const active = currentDeployment.versions[0];
65
+ if (!active)
66
+ throw new PraxisError({ code: 'INVALID_RESPONSE', message: 'Current deployment has no version' });
67
+ currentVersion = await workers.versions.retrieve({ path: { ...path, version_id: active.version_id } });
68
+ previous = (await workers.versions.assets.retrieveManifest({ path: { ...path, version_id: active.version_id } })).manifest;
69
+ }
70
+ // Keep the stored path order: the service hashes JSON.stringify(manifest), including property order.
71
+ // Reordered input with identical paths must still hash to the active version's manifest_hash.
72
+ manifest = {
73
+ ...Object.fromEntries(Object.entries(previous).filter(([key]) => input.keepExisting || Object.hasOwn(manifest, key))),
74
+ ...manifest,
75
+ };
76
+ if (Object.keys(manifest).length > 100_000)
77
+ throw new PraxisError({ code: 'LIMIT_EXCEEDED', message: 'At most 100000 asset paths can be published' });
78
+ const added = Object.keys(manifest).filter(key => !Object.hasOwn(previous, key));
79
+ const changed = Object.keys(manifest).filter(key => previous[key] && (previous[key].hash !== manifest[key].hash || previous[key].size !== manifest[key].size));
80
+ const removed = Object.keys(previous).filter(key => !Object.hasOwn(manifest, key));
81
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(manifest))));
82
+ const manifestHash = Array.from(digest, byte => byte.toString(16).padStart(2, '0')).join('');
83
+ const staticOnly = !['main', 'bindings', 'compatibility_date', 'compatibility_flags', 'assets_config'].some(key => Object.hasOwn(input, key));
84
+ const unchanged = staticOnly && !!currentVersion && manifestHash === currentVersion.praxis.assets_manifest?.manifest_hash;
85
+ const hashes = new Set(Object.values(manifest).map(entry => entry.hash));
86
+ const currentResult = { url: worker.subdomain.url, worker_id: worker.id, version_id: currentVersion?.id ?? null,
87
+ deployment_id: currentDeployment?.id ?? null, status: currentDeployment?.praxis.status ?? 'draft', created,
88
+ ...(currentVersion ? { version: currentVersion } : {}), unchanged, uploaded: 0, reused: hashes.size };
89
+ if (unchanged && !input.dryRun)
90
+ return currentResult;
91
+ // dryRun intentionally registers the content-addressed session manifest, but never uploads or publishes.
92
+ const session = await workers.assetsUploadSession.create({ path, body: { manifest } });
93
+ if (input.dryRun) {
94
+ const missing = new Set(session.buckets.flat());
95
+ if ([...missing].some(hash => !hashes.has(hash)))
96
+ throw new PraxisError({ code: 'INVALID_RESPONSE', message: 'Upload session requested an unknown hash' });
97
+ return { ...currentResult, reused: hashes.size - missing.size,
98
+ plan: { added, changed, removed, upload_hashes: missing.size, existing_hashes: hashes.size - missing.size } };
99
+ }
100
+ let jwt = session.buckets.length ? null : session.jwt;
101
+ const uploaded = new Set();
102
+ for (const bucket of session.buckets) {
103
+ const batch = {};
104
+ let size = 0;
105
+ for (const hash of bucket) {
106
+ const bytes = contents.get(hash);
107
+ if (!bytes)
108
+ throw new PraxisError({ code: 'INVALID_RESPONSE', message: `Upload session requested unknown hash ${hash}` });
109
+ size += bytes.length;
110
+ batch[hash] = base64(bytes);
111
+ }
112
+ if (bucket.length > 50 || size > 40 * 1024 * 1024)
113
+ throw new PraxisError({ code: 'INVALID_RESPONSE', message: 'Upload session bucket exceeds 50 files or 40 MiB' });
114
+ const result = await assets.upload.create({ body: { jwt: session.jwt, files: batch } });
115
+ jwt = result.jwt;
116
+ for (const hash of bucket)
117
+ uploaded.add(hash);
118
+ }
119
+ if (!jwt)
120
+ throw new PraxisError({ code: 'INVALID_RESPONSE', message: 'Asset upload did not return a completion JWT' });
121
+ // The service contract accepts jwt instead of manifest. Its generated OpenAPI
122
+ // type currently omits jwt; keep this explicit shape until that schema catches up.
123
+ const versionAssets = { jwt, ...(input.assets_config ? { config: input.assets_config } : {}) };
124
+ const result = await workers.versions.create({ path, body: {
125
+ deploy: true,
126
+ compatibility_date: input.compatibility_date ?? new Date().toISOString().slice(0, 10),
127
+ assets: versionAssets,
128
+ ...(input.compatibility_flags ? { compatibility_flags: input.compatibility_flags } : {}),
129
+ ...(input.bindings ? { bindings: input.bindings } : {}),
130
+ ...(input.main ? { main_module: input.main.name, modules: [{ name: input.main.name,
131
+ content_type: contentType,
132
+ content_base64: base64(new TextEncoder().encode(input.main.content)) }] } : {}),
133
+ } });
134
+ let deployment = result.deployment;
135
+ if (!deployment)
136
+ throw new PraxisError({ code: 'INVALID_RESPONSE', message: 'Version creation did not return a deployment' });
137
+ if (input.wait ?? true) {
138
+ const deadline = Date.now() + timeout;
139
+ const timedOut = () => new PraxisError({ code: 'DEPLOY_TIMEOUT', message: `Deployment ${deployment.id} did not become active within ${timeout} ms; deployment may still be running` });
140
+ let interval = 500;
141
+ while (deployment.praxis.status !== 'active') {
142
+ if (deployment.praxis.status === 'failed') {
143
+ const error = deployment.praxis.error;
144
+ throw new PraxisError({ code: error?.code ?? 'DEPLOYMENT_FAILED', message: error?.message ?? `Deployment ${deployment.id} failed`, raw: error });
145
+ }
146
+ const remaining = deadline - Date.now();
147
+ if (remaining <= 0)
148
+ throw timedOut();
149
+ await new Promise(resolve => setTimeout(resolve, Math.min(interval, remaining)));
150
+ if (Date.now() >= deadline)
151
+ throw timedOut();
152
+ try {
153
+ deployment = await workers.deployments.retrieve({ path: { ...path, deployment_id: deployment.id }, timeoutMs: deadline - Date.now() });
154
+ }
155
+ catch (error) {
156
+ if (error instanceof PraxisError && error.code === 'TIMEOUT')
157
+ throw timedOut();
158
+ throw error;
159
+ }
160
+ interval = Math.min(interval * 2, 2000);
161
+ }
162
+ }
163
+ return { url: worker.subdomain.url, worker_id: worker.id, version_id: result.version.id,
164
+ deployment_id: deployment.id, status: deployment.praxis.status, created,
165
+ uploaded: uploaded.size, reused: hashes.size - uploaded.size };
166
+ }
@@ -0,0 +1,9 @@
1
+ export { Praxis } from './core/client.js';
2
+ export type { PraxisOptions, RequestOptions } from './core/client.js';
3
+ export { PraxisError, PraxisConnectionError, PraxisTimeoutError } from './core/errors.js';
4
+ export type { ProblemDetails } from './core/errors.js';
5
+ export { Page } from './core/pagination.js';
6
+ export { parseSSE } from './core/sse.js';
7
+ export type { SSEEvent, SSEOptions } from './core/sse.js';
8
+ export { publish } from './helpers/application-publish.js';
9
+ export type { PublishInput, PublishResult, AssetsConfig } from './helpers/application-publish.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { Praxis } from "./core/client.js";
2
+ export { PraxisError, PraxisConnectionError, PraxisTimeoutError } from "./core/errors.js";
3
+ export { Page } from "./core/pagination.js";
4
+ export { parseSSE } from "./core/sse.js";
5
+ export { publish } from "./helpers/application-publish.js";