buckyos 0.7.180 → 0.7.183

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 (74) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +35 -0
  3. package/README.md +4 -0
  4. package/cli/deno.json +3 -2
  5. package/cli/dist/cli.mjs +1534 -216
  6. package/cli/dist/cli.mjs.map +1 -1
  7. package/cli/modules/aiws.ts +761 -58
  8. package/cli/modules/aiws_place.ts +383 -0
  9. package/cli/modules/aiws_schedule.ts +256 -0
  10. package/cli/runtime/host.ts +18 -0
  11. package/cli/runtime/host_deno.ts +34 -0
  12. package/cli/runtime/host_node.ts +32 -1
  13. package/cli/runtime/node_entry.ts +1 -0
  14. package/cli/system_bootstrap.ts +1 -0
  15. package/cli/system_launcher.ts +1 -0
  16. package/cli/version.ts +1 -1
  17. package/dist/aicc_client.d.ts +1 -1
  18. package/dist/aicc_client.d.ts.map +1 -1
  19. package/dist/aiworkspace_client.d.ts +253 -2
  20. package/dist/aiworkspace_client.d.ts.map +1 -1
  21. package/dist/aiws_bind-3b874f77.mjs +2235 -0
  22. package/dist/aiws_bind-3b874f77.mjs.map +1 -0
  23. package/dist/aiws_bind-82bace11.js +2 -0
  24. package/dist/aiws_bind-82bace11.js.map +1 -0
  25. package/dist/aiws_bind.d.ts +233 -0
  26. package/dist/aiws_bind.d.ts.map +1 -0
  27. package/dist/aiws_ext.cjs +1 -1
  28. package/dist/aiws_ext.cjs.map +1 -1
  29. package/dist/aiws_ext.d.ts +9 -5
  30. package/dist/aiws_ext.d.ts.map +1 -1
  31. package/dist/aiws_ext.mjs +146 -11
  32. package/dist/aiws_ext.mjs.map +1 -1
  33. package/dist/aiws_rrule.d.ts +121 -0
  34. package/dist/aiws_rrule.d.ts.map +1 -0
  35. package/dist/aiws_schedule.d.ts +324 -0
  36. package/dist/aiws_schedule.d.ts.map +1 -0
  37. package/dist/aiws_write-89b5cc2a.js +13 -0
  38. package/dist/aiws_write-89b5cc2a.js.map +1 -0
  39. package/dist/{executor_client-bfc8a1e1.mjs → aiws_write-c2de498e.mjs} +724 -285
  40. package/dist/aiws_write-c2de498e.mjs.map +1 -0
  41. package/dist/aiws_write.d.ts +178 -0
  42. package/dist/aiws_write.d.ts.map +1 -0
  43. package/dist/browser.cjs +1 -1
  44. package/dist/browser.cjs.map +1 -1
  45. package/dist/browser.d.ts +4 -0
  46. package/dist/browser.d.ts.map +1 -1
  47. package/dist/browser.mjs +112 -21
  48. package/dist/browser.mjs.map +1 -1
  49. package/dist/{content_objid-9232bcaf.mjs → content_objid-a2cafba9.mjs} +2 -2
  50. package/dist/{content_objid-9232bcaf.mjs.map → content_objid-a2cafba9.mjs.map} +1 -1
  51. package/dist/content_objid-dff803ff.js +2 -0
  52. package/dist/{content_objid-1aff74b6.js.map → content_objid-dff803ff.js.map} +1 -1
  53. package/dist/{did_object_client-7fa36f90.mjs → did_object_client-cb2f9aba.mjs} +2 -2
  54. package/dist/{did_object_client-7fa36f90.mjs.map → did_object_client-cb2f9aba.mjs.map} +1 -1
  55. package/dist/index.cjs +1 -1
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.ts +4 -0
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.mjs +113 -22
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/node.cjs +1 -1
  62. package/dist/node.cjs.map +1 -1
  63. package/dist/node.d.ts +5 -0
  64. package/dist/node.d.ts.map +1 -1
  65. package/dist/node.mjs +99 -6
  66. package/dist/node.mjs.map +1 -1
  67. package/dist/{object_url-f72c1704.mjs → object_url-376c5222.mjs} +4 -4
  68. package/dist/{object_url-f72c1704.mjs.map → object_url-376c5222.mjs.map} +1 -1
  69. package/dist/xllm.mjs +2 -2
  70. package/package.json +5 -4
  71. package/dist/content_objid-1aff74b6.js +0 -2
  72. package/dist/executor_client-7ce0ddc7.js +0 -13
  73. package/dist/executor_client-7ce0ddc7.js.map +0 -1
  74. package/dist/executor_client-bfc8a1e1.mjs.map +0 -1
@@ -39,7 +39,8 @@ import { R as RPCError, k as kRPCClient } from "./krpc_client-673448e5.mjs";
39
39
  import { s as DID, N as NODE_IDENTITY_SCHEMA_V2, e as isBuckyOSLocalNodeIdentityConfig, l as parseBuckyOSOwnerDocument, t as canonicalize, u as signJwtEdDSA, F as FileObject, A as ACTION_TYPE_DOWNLOAD, v as ACTION_TYPE_INSTALLED, w as ACTION_TYPE_LIKED, x as ACTION_TYPE_PURCHASED, y as ACTION_TYPE_SHARED, z as ACTION_TYPE_UNLIKED, B as ACTION_TYPE_VIEWED, C as BaseContentObject, E as CYFS_CONTENT_TYPE_NAMED_OBJECT_JSON, G as CYFS_CONTENT_TYPE_NAMED_OBJECT_JWT, H as ChunkId, I as ChunkType, J as DEFAULT_HASH_METHOD, K as DirObject, L as HashMethod, M as InclusionProof, O as KnownStandardObject, P as MSG_OBJECT_RESERVED_KEYS, Q as MSG_REACTION_KEY_MAX_BYTES, R as MSG_SESSION_ID_MAX_CHARS, S as NamedObjectBase, T as NdnError, U as OBJ_TYPE_ACTION, V as OBJ_TYPE_CHUNK_LIST, W as OBJ_TYPE_DIR, X as OBJ_TYPE_FILE, Y as OBJ_TYPE_INCLUSION_PROOF, Z as OBJ_TYPE_LIST, _ as OBJ_TYPE_MSG, $ as OBJ_TYPE_OBJMAP, a0 as OBJ_TYPE_PACK, a1 as OBJ_TYPE_PATH, a2 as OBJ_TYPE_PKG, a3 as OBJ_TYPE_RECEIPT, a4 as OBJ_TYPE_RELATION, a5 as ObjId, a6 as PathObject, a7 as RELATION_TYPE_PART_OF, a8 as RELATION_TYPE_SAME, a9 as RelationObject, aa as SimpleChunkList, ab as SimpleMapItem, ac as SimpleObjectMap, ad as actionObjectFromJson, ae as base32Decode, af as base32Encode, ag as buildNamedObjectByJson, ah as buildNamedObjectByJwt, ai as buildObjId, aj as bytesToHex$2, ak as calcPkgMetaObjId, al as canonicalizeJson, am as decodeMsgObjectJwt, an as extractObjIdByPath, ao as hexToBytes$1, ap as isCyfsNamedObjectContentType, aq as isValidMsgSessionId, ar as loadNamedObj, as as loadNamedObjAndVerify, at as loadNamedObjectFromObjStr, au as msgJwtKidDid, av as msgObjectFromJsonChecked, aw as namedObjectEncodingFromContentType, ax as normalizePackageMetaForObjId, ay as randomMsgNonce, az as receiptObjFromJson, aA as sha256Bytes, aB as sha256Utf8, aC as toCanonicalJsonString, aD as validateMsgObject, aE as varintDecode, aF as varintEncode, aG as verifyMsgObjectJwt, aH as verifyNamedObject, aI as verifyNamedObjectFromJwt, aJ as verifyNamedObjectFromStr } from "./ndn_types-0fac2499.mjs";
40
40
  import { s as sniffMagic, m as mediaTypeFromExtension, e as extensionOf, a as stripMediaTypeParams, h as heifImageSize, i as isoBoxes } from "./content_mime-e42d5f8d.mjs";
41
41
  import { g as getBrowserIdentityRaw, c as clearBrowserUserInfo, s as saveBrowserIdentity, a as saveBrowserUserInfo, b as getBrowserUserInfo, d as clearBrowserIdentity, h as hashPassword, e as saveLocalAccountInfo, f as cleanLocalAccountInfo } from "./account-7a7bde6f.mjs";
42
- import { e as encodeObjQueryComponent, c as canonicalJson, a as objServiceUrl, n as normalizeObjectUrl, p as parseObjectUrl, b as objectSegments, d as objEventKey } from "./object_url-f72c1704.mjs";
42
+ import { i as AiWorkspaceClient, A as AIWORKSPACE_SERVICE_NAME, Y as newRecordId, _ as insertRecordOp, Z as setValuesOps, $ as deleteRecordsOp, V as orderKeyBetween, g as commitOverLimit, M as AIWS_PROTOCOL_VERSION, a as AiwsFailure, h as commitWithParts } from "./aiws_bind-3b874f77.mjs";
43
+ import { a as objEventKey } from "./object_url-376c5222.mjs";
43
44
  function ensureSSOEnvironment() {
44
45
  if (typeof window === "undefined" || typeof window.location === "undefined") {
45
46
  throw new Error("AuthClient can only be created in browser SSO environments");
@@ -76,15 +77,15 @@ const DENY_REASONS = [
76
77
  "authorization_unavailable"
77
78
  ];
78
79
  const ACCESS_DENIED_ERROR_CODE = "access_denied";
79
- function isRecord$1(value) {
80
+ function isRecord$2(value) {
80
81
  return !!value && typeof value === "object" && !Array.isArray(value);
81
82
  }
82
83
  function parseAccessDenial(value) {
83
- if (!isRecord$1(value) || typeof value.reason !== "string")
84
+ if (!isRecord$2(value) || typeof value.reason !== "string")
84
85
  return null;
85
86
  if (!DENY_REASONS.includes(value.reason))
86
87
  return null;
87
- const adjust = isRecord$1(value.adjust) && typeof value.adjust.party === "string" ? value.adjust : null;
88
+ const adjust = isRecord$2(value.adjust) && typeof value.adjust.party === "string" ? value.adjust : null;
88
89
  if (!adjust)
89
90
  return null;
90
91
  return value;
@@ -96,7 +97,7 @@ function accessDenialOf(error) {
96
97
  }
97
98
  const ANONYMOUS_IDENTITY = { kind: "anonymous" };
98
99
  function parseCurrentIdentity(value) {
99
- if (!isRecord$1(value))
100
+ if (!isRecord$2(value))
100
101
  return null;
101
102
  if (value.kind === "anonymous")
102
103
  return ANONYMOUS_IDENTITY;
@@ -168,261 +169,6 @@ function buildJumpUrl(action, params, jumpBase = DEFAULT_JUMP_BASE_URL) {
168
169
  const fragment = new URLSearchParams(params).toString();
169
170
  return `${base.origin}${path}${fragment ? `#${fragment}` : ""}`;
170
171
  }
171
- const AIWORKSPACE_SERVICE_NAME = "aiworkspace";
172
- class AiwsFailure extends Error {
173
- constructor(error) {
174
- super(`${error.code}${error.sub_code ? `/${error.sub_code}` : ""}: ${error.detail}`);
175
- this.name = "AiwsFailure";
176
- this.code = error.code;
177
- this.subCode = error.sub_code;
178
- this.data = error.data;
179
- }
180
- }
181
- function aiwsReferenceUrl(reference, workspaceId) {
182
- const ws = reference.workspace_id ?? workspaceId;
183
- if (!ws)
184
- throw new Error("reference names no workspace");
185
- const query = [];
186
- if (reference.mode === "fixed")
187
- query.push("mode=fixed");
188
- if (reference.selector != null)
189
- query.push(`selector=${encodeObjQueryComponent(canonicalJson(reference.selector))}`);
190
- if (reference.version != null)
191
- query.push(`version=${encodeObjQueryComponent(canonicalJson(reference.version))}`);
192
- const base = objServiceUrl("aiworkspace", [ws, "entities", reference.entity_id]);
193
- return normalizeObjectUrl(query.length ? `${base}?${query.join("&")}` : base);
194
- }
195
- function parseAiwsReferenceUrl(url) {
196
- const parsed = parseObjectUrl(url);
197
- const segments = objectSegments(parsed);
198
- if (parsed.kind !== "obj" || parsed.host.name !== "aiworkspace" || segments.length !== 3 || segments[1] !== "entities") {
199
- throw new Error(`${url} is not an AI Workspace entity url`);
200
- }
201
- const reference = {
202
- workspace_id: segments[0],
203
- entity_id: segments[2],
204
- mode: parsed.query.mode === "fixed" ? "fixed" : "live"
205
- };
206
- if (parsed.query.selector !== void 0)
207
- reference.selector = JSON.parse(parsed.query.selector);
208
- if (parsed.query.version !== void 0)
209
- reference.version = JSON.parse(parsed.query.version);
210
- return reference;
211
- }
212
- const AIWS_COMMIT_PART_BYTES = 6 * 1024 * 1024;
213
- const AIWS_COMMIT_MAX_BYTES = 32 * 1024 * 1024;
214
- const AIWS_COMMIT_MAX_OPERATIONS = 5e4;
215
- const utf8 = new TextEncoder();
216
- function jsonBytes(value) {
217
- const text = JSON.stringify(value);
218
- return text.length + (/[^\x00-\x7f]/.test(text) ? utf8.encode(text).length - text.length : 0);
219
- }
220
- function splitCommitOperations(operations, partBytes = AIWS_COMMIT_PART_BYTES) {
221
- const parts = [];
222
- let current = [];
223
- let size = 2;
224
- for (const op of operations) {
225
- const bytes2 = jsonBytes(op) + 1;
226
- if (current.length > 0 && size + bytes2 > partBytes) {
227
- parts.push(current);
228
- current = [];
229
- size = 2;
230
- }
231
- current.push(op);
232
- size += bytes2;
233
- }
234
- if (current.length > 0 || parts.length === 0)
235
- parts.push(current);
236
- return parts;
237
- }
238
- function commitOverLimit(operations) {
239
- if (operations.length > AIWS_COMMIT_MAX_OPERATIONS)
240
- return { limit: "operations", value: operations.length, max: AIWS_COMMIT_MAX_OPERATIONS };
241
- let bytes2 = 2;
242
- for (const op of operations)
243
- bytes2 += jsonBytes(op) + 1;
244
- return bytes2 + 4096 > AIWS_COMMIT_MAX_BYTES ? { limit: "bytes", value: bytes2, max: AIWS_COMMIT_MAX_BYTES } : null;
245
- }
246
- async function commitWithParts(call, request, options = {}) {
247
- var _a2, _b2;
248
- const method = options.method ?? "doc.commit";
249
- const operations = Array.isArray(request.operations) ? request.operations : [];
250
- const parts = splitCommitOperations(operations, options.partBytes ?? AIWS_COMMIT_PART_BYTES);
251
- if (parts.length <= 1)
252
- return await call(method, request);
253
- const { workspace_id, epoch, idempotency_key } = request;
254
- for (let attempt2 = 0; ; attempt2++) {
255
- const staged = [];
256
- for (let part = 0; part < parts.length - 1; part++) {
257
- (_a2 = options.onPart) == null ? void 0 : _a2.call(options, part + 1, parts.length);
258
- const held = await call("doc.stage", { workspace_id, epoch, idempotency_key, part, operations: parts[part] });
259
- if (!held || held.ok === false || typeof held.digest !== "string") {
260
- const error = (held == null ? void 0 : held.error) ?? { code: "STORAGE_IO_ERROR", retryable: true, detail: "doc.stage returned no digest" };
261
- return { status: "rejected", code: error.code, retryable: error.retryable, detail: error.detail, ...error.sub_code ? { sub_code: error.sub_code } : {}, errors: [error] };
262
- }
263
- staged.push(held.digest);
264
- }
265
- (_b2 = options.onPart) == null ? void 0 : _b2.call(options, parts.length, parts.length);
266
- const result = await call(method, { ...request, staged, operations: parts[parts.length - 1] });
267
- if (attempt2 === 0 && (result == null ? void 0 : result.status) === "rejected" && result.sub_code === "STAGED_PARTS_MISSING")
268
- continue;
269
- return result;
270
- }
271
- }
272
- class AiWorkspaceClient {
273
- constructor(rpcClient) {
274
- this.rpcClient = rpcClient;
275
- this.raw = (method, params) => this.rpcClient.call(method, params);
276
- }
277
- async call(method, params) {
278
- const raw = await this.rpcClient.call(method, params);
279
- if (raw && typeof raw === "object" && raw.ok === false)
280
- throw new AiwsFailure(raw.error);
281
- return raw;
282
- }
283
- // ---- workspace
284
- list() {
285
- return this.call("ws.list", {});
286
- }
287
- info(workspace_id) {
288
- return this.call("ws.get_info", { workspace_id });
289
- }
290
- getUserState(workspace_id) {
291
- return this.call("ws.get_user_state", { workspace_id });
292
- }
293
- setUserState(workspace_id, entries, expect) {
294
- return this.call("ws.set_user_state", { workspace_id, entries, ...expect ? { expect } : {} });
295
- }
296
- // ---- document
297
- resolve(workspace_id, reference) {
298
- return this.call("doc.resolve", { workspace_id, reference });
299
- }
300
- resolvePath(workspace_id, path) {
301
- return this.call("doc.resolve", { workspace_id, path });
302
- }
303
- read(workspace_id, entity_id, selector) {
304
- return this.call("doc.read", { workspace_id, entity_id, ...selector ? { selector } : {} });
305
- }
306
- query(workspace_id, params) {
307
- return this.call("doc.query", { workspace_id, ...params });
308
- }
309
- outline(workspace_id) {
310
- return this.call("doc.outline", { workspace_id });
311
- }
312
- prepare(workspace_id, request) {
313
- return commitWithParts(this.raw, { workspace_id, ...request }, { method: "doc.prepare" });
314
- }
315
- /** The three-state commit result (`status: accepted | conflict | rejected`), never thrown. One call per Commit
316
- * whatever its size (up to `AIWS_COMMIT_MAX_BYTES` / `AIWS_COMMIT_MAX_OPERATIONS`): a large one is sent in parts. */
317
- commit(workspace_id, request, options = {}) {
318
- return commitWithParts(this.raw, { workspace_id, ...request }, options);
319
- }
320
- getSubmission(workspace_id, epoch, idempotency_key) {
321
- return this.call("doc.get_submission", { workspace_id, epoch, idempotency_key });
322
- }
323
- /** Changes after `after_seq` (`filter.detail: "touched"` for the touched entities only). */
324
- getChanges(workspace_id, epoch, after_seq, opts = {}) {
325
- return this.call("doc.get_changes", { workspace_id, epoch, after_seq, ...opts.limit ? { limit: opts.limit } : {}, ...opts.touchedOnly ? { filter: { detail: "touched" } } : {} });
326
- }
327
- /** Long poll until the head passes `after_seq` (or `timeout_ms`). */
328
- waitChanges(workspace_id, after_seq, opts = {}) {
329
- return this.call("doc.wait_changes", { workspace_id, after_seq, ...opts });
330
- }
331
- /** A whole-Workspace package (`.bcanvas`): `download` names it in the owner's exports bucket. */
332
- exportDoc(workspace_id, mode, self_contained, include_notes) {
333
- return this.call("doc.export", { workspace_id, mode, self_contained, ...include_notes === void 0 ? {} : { include_notes } });
334
- }
335
- // ---- assets
336
- /** Register a FileObject as a staged asset: `{ bucket_id, key }` (the uploader's binding) or `{ obj_id }`. */
337
- assetImportObject(workspace_id, source) {
338
- return this.call("asset.import_object", { workspace_id, ...source });
339
- }
340
- // ---- Block-controls (code-registered layouts such as the mind map)
341
- controlsList() {
342
- return this.call("control.list", {});
343
- }
344
- controlsDescribe(kind) {
345
- return this.call("control.describe", { kind });
346
- }
347
- controlsImport(workspace_id, params) {
348
- return this.call("control.import", { workspace_id, ...params });
349
- }
350
- controlsExport(workspace_id, entity_id, format) {
351
- return this.call("control.export", { workspace_id, entity_id, ...format ? { format } : {} });
352
- }
353
- // ---- extension controls (README “Extension controls”; buckyos-websdk src/aiws_ext.ts drives them)
354
- /** Build one control's source files into the Workspace; `BUILD_FAILED` carries `data.diagnostics`. */
355
- extBuild(workspace_id, params) {
356
- return this.call("ext.build", { workspace_id, ...params });
357
- }
358
- /** The bundle of definitions (`purpose: pull` needs read only and synthesizes the source of never-built ones). */
359
- extExport(workspace_id, entity_ids, purpose = "package") {
360
- return this.call("ext.export", { workspace_id, entity_ids, purpose });
361
- }
362
- /** Into the caller's library: a `.pikg` object or one bound into the caller's `exports` bucket (consumed), or
363
- * definitions of a Workspace (`from` + `package`). */
364
- extInstall(params) {
365
- return this.call("ext.install", params);
366
- }
367
- /** Pack definitions (and what they build on, and templates of the Workspace) as an `aiws` `.pikg` into the caller's
368
- * `exports` bucket (unsigned). */
369
- extPack(workspace_id, entity_ids, pkg, templates) {
370
- return this.call("ext.pack", { workspace_id, entity_ids, package: pkg, ...templates ? { templates } : {} });
371
- }
372
- /** Rebuild imported definitions from the caller's library (same Zone; across Zones `ext.build { provenance, upgrade }`):
373
- * `EXT_LOCAL_CHANGES` when the snapshot was built locally since, unless `force`. */
374
- extUpgrade(params) {
375
- return this.call("ext.upgrade", { ...params });
376
- }
377
- /** Chosen Surfaces as a template snapshot: the manifest item, the definitions it needs and the files (base64) of
378
- * `templates/<id>/`. */
379
- extExportTemplate(params) {
380
- return this.call("ext.export_template", { ...params });
381
- }
382
- /** A new Workspace from a template of the caller's library (installing a template never creates one). */
383
- extCreateFromTemplate(params) {
384
- return this.call("ext.create_from_template", params);
385
- }
386
- extListLibrary() {
387
- return this.call("ext.list_library", {});
388
- }
389
- extUninstall(pkg_id) {
390
- return this.call("ext.uninstall", { pkg_id });
391
- }
392
- /** A library package's controls with their bytes (base64): what a client relays into a Workspace of another Zone. */
393
- extLibraryBundle(pkg_id, idents) {
394
- return this.call("ext.library_bundle", { pkg_id, ...idents ? { idents } : {} });
395
- }
396
- /** Bring library controls into a Workspace of this Zone (one Commit). */
397
- extImport(workspace_id, items, opts = {}) {
398
- return this.call("ext.import", { workspace_id, items, ...opts });
399
- }
400
- // ---- runs (M3 executor protocol)
401
- runStart(workspace_id, program, params, idempotency_key) {
402
- return this.call("proc.start", { workspace_id, program, params, idempotency_key });
403
- }
404
- runGet(workspace_id, run_id, choices) {
405
- return this.call("proc.get", { workspace_id, run_id, ...choices ? { choices } : {} });
406
- }
407
- runList(workspace_id, wish_id, limit) {
408
- return this.call("proc.list", { workspace_id, ...wish_id ? { wish_id } : {}, ...limit ? { limit } : {} });
409
- }
410
- runClaim(workspace_id, run_id, claim_token, executor) {
411
- return this.call("proc.claim", { workspace_id, run_id, claim_token, ...executor ? { executor } : {} });
412
- }
413
- runHeartbeat(workspace_id, run_id, attempt2, progress) {
414
- return this.call("proc.heartbeat", { workspace_id, run_id, attempt: attempt2, ...progress ? { progress } : {} });
415
- }
416
- runReport(workspace_id, report) {
417
- return this.call("proc.report", { workspace_id, ...report });
418
- }
419
- runApply(workspace_id, run_id, plan_digest, session_id) {
420
- return this.call("proc.apply", { workspace_id, run_id, plan_digest, ...session_id ? { session_id } : {} });
421
- }
422
- runCancel(workspace_id, run_id) {
423
- return this.call("proc.cancel", { workspace_id, run_id });
424
- }
425
- }
426
172
  const BUCKET_SERVICE_NAME = "nfs-server";
427
173
  const BUCKET_DATA_PATH = "/bucket/v1/";
428
174
  const BUCKET_MAX_PUT_BYTES = 32 * 1024 * 1024;
@@ -5222,12 +4968,12 @@ const APP_LOGIN_ISSUE_METHOD = "user.app_login.issue";
5222
4968
  const APP_LOGIN_EXCHANGE_METHOD = "auth.app_login.exchange";
5223
4969
  const APP_LOGIN_SETTINGS_GET_METHOD = "apps.app_login.get";
5224
4970
  const APP_LOGIN_SETTINGS_SET_METHOD = "apps.app_login.set";
5225
- function isRecord(value) {
4971
+ function isRecord$1(value) {
5226
4972
  return typeof value === "object" && value !== null && !Array.isArray(value);
5227
4973
  }
5228
4974
  async function issue(client, params, kind) {
5229
4975
  const result = await client.call(APP_LOGIN_ISSUE_METHOD, { ...params, kind });
5230
- if (!isRecord(result) || typeof result[kind] !== "string" || typeof result.user_id !== "string") {
4976
+ if (!isRecord$1(result) || typeof result[kind] !== "string" || typeof result.user_id !== "string") {
5231
4977
  throw new Error(`invalid ${APP_LOGIN_ISSUE_METHOD} response`);
5232
4978
  }
5233
4979
  return result;
@@ -5239,7 +4985,7 @@ async function issueAppLoginCode(client, params) {
5239
4985
  code: result.code,
5240
4986
  expires_at: Number(result.expires_at ?? 0),
5241
4987
  new_account: result.new_account === true,
5242
- invite: isRecord(result.invite) ? result.invite : {}
4988
+ invite: isRecord$1(result.invite) ? result.invite : {}
5243
4989
  };
5244
4990
  }
5245
4991
  async function issueAppCustomerLink(client, params) {
@@ -5249,11 +4995,11 @@ async function issueAppCustomerLink(client, params) {
5249
4995
  link: result.link,
5250
4996
  expires_at: Number(result.expires_at ?? 0),
5251
4997
  new_account: result.new_account === true,
5252
- invite: isRecord(result.invite) ? result.invite : {}
4998
+ invite: isRecord$1(result.invite) ? result.invite : {}
5253
4999
  };
5254
5000
  }
5255
5001
  function parseAppLoginExchangeResult(value) {
5256
- if (!isRecord(value))
5002
+ if (!isRecord$1(value))
5257
5003
  return null;
5258
5004
  if (value.status === "ready") {
5259
5005
  if (typeof value.callback_url !== "string" || typeof value.user_id !== "string")
@@ -30581,10 +30327,10 @@ async function doUpload(session, concurrency) {
30581
30327
  const states = [...session.objectStates.values()];
30582
30328
  const chunkTasks = /* @__PURE__ */ new Map();
30583
30329
  let index = 0;
30584
- let failure;
30330
+ let failure2;
30585
30331
  const workers = Array.from({ length: Math.min(concurrency, states.length) }, async () => {
30586
30332
  var _a3, _b2;
30587
- while (index < states.length && !failure) {
30333
+ while (index < states.length && !failure2) {
30588
30334
  const state = states[index++];
30589
30335
  try {
30590
30336
  throwIfCancelled((_a3 = session.abortController) == null ? void 0 : _a3.signal);
@@ -30609,13 +30355,13 @@ async function doUpload(session, concurrency) {
30609
30355
  state.state = "completed";
30610
30356
  } catch (error) {
30611
30357
  state.state = "failed";
30612
- failure = error;
30358
+ failure2 = error;
30613
30359
  }
30614
30360
  }
30615
30361
  });
30616
30362
  await Promise.all(workers);
30617
- if (failure)
30618
- throw failure;
30363
+ if (failure2)
30364
+ throw failure2;
30619
30365
  throwIfCancelled((_a2 = session.abortController) == null ? void 0 : _a2.signal);
30620
30366
  session.objectStatus = "finalizing";
30621
30367
  emitProgress(session);
@@ -31600,6 +31346,695 @@ class ExecutorCommandStream {
31600
31346
  return this.request("cancel", { store_id: locator.store_id, op_id: locator.op_id });
31601
31347
  }
31602
31348
  }
31349
+ const isRecord = (v) => !!v && typeof v === "object" && !Array.isArray(v);
31350
+ function failure(detail, code = "INVALID_SCHEMA") {
31351
+ return new AiwsFailure({ code, retryable: false, detail });
31352
+ }
31353
+ const idOf = (x) => typeof x === "string" ? x : x.entity_id;
31354
+ function fieldsOf(table) {
31355
+ var _a2;
31356
+ const fields = ((_a2 = table.content) == null ? void 0 : _a2.fields) ?? table.fields;
31357
+ if (!Array.isArray(fields))
31358
+ throw failure(`table ${table.entity_id}: pass it as doc.read answers it (content.fields)`, "INVALID_OPERATION");
31359
+ return fields;
31360
+ }
31361
+ function fieldNamed(table, key) {
31362
+ const fields = fieldsOf(table);
31363
+ const f2 = fields.find((x) => x.name === key) ?? fields.find((x) => x.field_id === key);
31364
+ if (!f2)
31365
+ throw failure(`table ${table.entity_id} has no field "${key}" (fields: ${fields.map((x) => x.name).join(", ")})`);
31366
+ return f2;
31367
+ }
31368
+ function optionOf(field, value) {
31369
+ const options = field.options ?? [];
31370
+ const o = options.find((x) => x.label === value) ?? options.find((x) => x.option_id === value);
31371
+ if (!o)
31372
+ throw failure(`field "${field.name}" has no option "${value}" (options: ${options.map((x) => x.label).join(", ")})`);
31373
+ return o.option_id;
31374
+ }
31375
+ function cellValue(field, value) {
31376
+ if (value === null || value === void 0)
31377
+ return null;
31378
+ if (isRecord(value) && "$formula" in value)
31379
+ return value;
31380
+ const bad = (what) => failure(`field "${field.name}" (${field.type}) takes ${what}, not ${JSON.stringify(value)}`);
31381
+ switch (field.type) {
31382
+ case "text":
31383
+ if (typeof value === "string")
31384
+ return value;
31385
+ if (typeof value === "number" || typeof value === "boolean")
31386
+ return String(value);
31387
+ throw bad("a text");
31388
+ case "number": {
31389
+ const n2 = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
31390
+ if (Number.isFinite(n2))
31391
+ return n2;
31392
+ throw bad("a number");
31393
+ }
31394
+ case "decimal":
31395
+ if (typeof value === "string" && value.trim())
31396
+ return value.trim();
31397
+ if (typeof value === "number" && Number.isFinite(value))
31398
+ return String(value);
31399
+ throw bad("a decimal string");
31400
+ case "boolean":
31401
+ if (typeof value === "boolean")
31402
+ return value;
31403
+ if (value === 1 || value === 0)
31404
+ return value === 1;
31405
+ if (typeof value === "string" && /^(true|false|1|0)$/i.test(value.trim()))
31406
+ return /^(true|1)$/i.test(value.trim());
31407
+ throw bad("true or false");
31408
+ case "date":
31409
+ case "datetime":
31410
+ if (typeof value === "string")
31411
+ return value.trim();
31412
+ throw bad(field.type === "date" ? "YYYY-MM-DD" : "an RFC 3339 datetime");
31413
+ case "select":
31414
+ if (typeof value === "string")
31415
+ return optionOf(field, value);
31416
+ throw bad("an option label");
31417
+ case "multi_select": {
31418
+ let items = value;
31419
+ if (typeof value === "string")
31420
+ items = value.trim().startsWith("[") ? JSON.parse(value) : value.split(";").map((s) => s.trim()).filter(Boolean);
31421
+ if (!Array.isArray(items))
31422
+ throw bad("option labels");
31423
+ return [...new Set(items.map((x) => {
31424
+ if (typeof x !== "string")
31425
+ throw bad("option labels");
31426
+ return optionOf(field, x);
31427
+ }))];
31428
+ }
31429
+ case "object_ref": {
31430
+ if (isRecord(value))
31431
+ return value;
31432
+ const id2 = typeof value === "string" && value.startsWith("~") ? value.slice(1) : value;
31433
+ if (typeof id2 === "string" && id2 && !id2.includes("/"))
31434
+ return { entity_id: id2 };
31435
+ throw bad("a reference { entity_id } or an entity id (resolve a path with doc.resolve first)");
31436
+ }
31437
+ case "currency": {
31438
+ if (isRecord(value))
31439
+ return value;
31440
+ if (typeof value === "number")
31441
+ return value;
31442
+ if (typeof value !== "string" || !value.trim())
31443
+ throw bad('{ amount, currency }, an amount or "USD 12.50"');
31444
+ const before = /^\s*([A-Z]{3})\s+(\S+)\s*$/.exec(value);
31445
+ if (before)
31446
+ return { amount: before[2], currency: before[1] };
31447
+ const after = /^\s*(\S+)\s+([A-Z]{3})\s*$/.exec(value);
31448
+ if (after)
31449
+ return { amount: after[1], currency: after[2] };
31450
+ return value.trim();
31451
+ }
31452
+ case "json": {
31453
+ let v = value;
31454
+ if (typeof value === "string") {
31455
+ try {
31456
+ v = JSON.parse(value);
31457
+ } catch {
31458
+ throw bad("a JSON object");
31459
+ }
31460
+ }
31461
+ if (isRecord(v))
31462
+ return v;
31463
+ throw bad("a JSON object");
31464
+ }
31465
+ default:
31466
+ return value;
31467
+ }
31468
+ }
31469
+ function recordOf(read) {
31470
+ const r = typeof read === "string" ? JSON.parse(read) : read;
31471
+ const row = isRecord(r) && isRecord(r.content) && typeof r.content.record_id === "string" ? r.content : r;
31472
+ if (!isRecord(row) || typeof row.record_id !== "string")
31473
+ throw failure("a record as doc.read (table_record) or the SQL _record column answers it", "INVALID_OPERATION");
31474
+ return row;
31475
+ }
31476
+ function valuesById(table, values) {
31477
+ const out = {};
31478
+ for (const [key, v] of Object.entries(values)) {
31479
+ const f2 = fieldNamed(table, key);
31480
+ out[f2.field_id] = cellValue(f2, v);
31481
+ }
31482
+ return out;
31483
+ }
31484
+ function tableInsert(table, rows, opts = {}) {
31485
+ if (rows.length === 0)
31486
+ return [];
31487
+ const fields = fieldsOf(table);
31488
+ const idKey = fields.some((f2) => f2.name === "_id") ? null : "_id";
31489
+ const records = rows.map((row) => {
31490
+ const values = { ...row };
31491
+ let record_id;
31492
+ if (idKey && values._id !== void 0) {
31493
+ record_id = String(values._id);
31494
+ delete values._id;
31495
+ }
31496
+ return { record_id: record_id || (opts.newRecordId ?? (() => newRecordId()))(), values: valuesById(table, values) };
31497
+ });
31498
+ return [insertRecordOp(table.entity_id, records)];
31499
+ }
31500
+ function tableSet(table, recordId, values, read) {
31501
+ const row = recordOf(read);
31502
+ if (row.record_id !== recordId)
31503
+ throw failure(`the read is of record ${row.record_id}, not ${recordId}`, "INVALID_OPERATION");
31504
+ return setValuesOps(table.entity_id, row, valuesById(table, values));
31505
+ }
31506
+ function tableDelete(table, recordIds, reads) {
31507
+ if (recordIds.length === 0)
31508
+ return [];
31509
+ const byId = new Map(reads.map(recordOf).map((r) => [r.record_id, r]));
31510
+ return [deleteRecordsOp(idOf(table), recordIds.map((id2) => {
31511
+ const row = byId.get(id2);
31512
+ if (!row)
31513
+ throw failure(`record ${id2} was not read`, "NOT_FOUND");
31514
+ return row;
31515
+ }))];
31516
+ }
31517
+ function newId(label, prefix) {
31518
+ const slug = label.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 24);
31519
+ const tail = Math.floor(Math.random() * 36 ** 6).toString(36).padStart(6, "0");
31520
+ return /^[a-z0-9]/.test(slug) ? `${slug}_${tail}` : `${prefix}${tail}`;
31521
+ }
31522
+ function fieldAdd(table, def, opts = {}) {
31523
+ const fields = fieldsOf(table);
31524
+ const { options, field_id, ...rest } = def;
31525
+ const field = { field_id: field_id ?? newId(def.name, "f"), ...rest };
31526
+ if (options) {
31527
+ const used = /* @__PURE__ */ new Set();
31528
+ field.options = options.map((o) => {
31529
+ const label = typeof o === "string" ? o : o.label;
31530
+ let option_id = typeof o === "string" ? void 0 : o.option_id;
31531
+ while (!option_id || used.has(option_id))
31532
+ option_id = newId(label, "o");
31533
+ used.add(option_id);
31534
+ return { option_id, label };
31535
+ });
31536
+ }
31537
+ const last = fields.map((f2) => f2.order_key).filter((k) => typeof k === "string" && k.length > 0).sort().pop();
31538
+ const op = { op: "table.add_field", source_id: table.entity_id, field, ...last ? { order_key: orderKeyBetween(last, null) } : {} };
31539
+ if (opts.backfill !== void 0)
31540
+ op.backfill = cellValue(field, opts.backfill);
31541
+ return op;
31542
+ }
31543
+ function optionAdd(table, field, label, opts = {}) {
31544
+ var _a2;
31545
+ const f2 = fieldNamed(table, field);
31546
+ if (f2.type !== "select" && f2.type !== "multi_select")
31547
+ throw failure(`field "${f2.name}" is ${f2.type}, not a select`, "INVALID_OPERATION");
31548
+ if ((_a2 = f2.options) == null ? void 0 : _a2.some((o) => o.label === label))
31549
+ throw failure(`field "${f2.name}" already has the option "${label}"`, "INVALID_OPERATION");
31550
+ if (typeof f2.def_rev !== "number")
31551
+ throw failure(`field "${f2.name}": pass the table as doc.read answers it (fields carry def_rev)`, "INVALID_OPERATION");
31552
+ const used = new Set((f2.options ?? []).map((o) => o.option_id));
31553
+ let option_id = opts.option_id;
31554
+ while (!option_id || used.has(option_id))
31555
+ option_id = newId(label, "o");
31556
+ return { op: "table.add_option", source_id: table.entity_id, field_id: f2.field_id, option: { option_id, label }, ...opts.index !== void 0 ? { index: opts.index } : {}, expect: { rev: f2.def_rev } };
31557
+ }
31558
+ function blockState(doc, blockId, reads) {
31559
+ var _a2, _b2;
31560
+ for (const r of reads === void 0 ? [] : Array.isArray(reads) ? reads : [reads]) {
31561
+ const b2 = "content" in r ? r.content : r;
31562
+ if (b2.block_id === blockId)
31563
+ return b2;
31564
+ }
31565
+ const known = typeof doc === "string" ? void 0 : (_b2 = (_a2 = doc.content) == null ? void 0 : _a2.blocks) == null ? void 0 : _b2[blockId];
31566
+ if (!known)
31567
+ throw failure(`block ${blockId} is not in the rich text as read`, "NOT_FOUND");
31568
+ return { block_id: blockId, ...known };
31569
+ }
31570
+ function textAppend(doc, markdown, opts = {}) {
31571
+ return [{ op: "richtext.insert_blocks", entity_id: idOf(doc), position: { end: true }, blocks: markdownToBlocks(markdown, opts.prefix) }];
31572
+ }
31573
+ function textReplaceBlock(doc, blockId, markdown, read, opts = {}) {
31574
+ const { hash: hash2 } = blockState(doc, blockId, read);
31575
+ const [first, ...rest] = markdownToBlocks(markdown, opts.prefix);
31576
+ const node = { ...first, attrs: { ...first.attrs ?? {}, block_id: blockId } };
31577
+ const ops = [{ op: "richtext.replace_block", entity_id: doc.entity_id, block_id: blockId, expect: { hash: hash2 }, node }];
31578
+ if (rest.length > 0)
31579
+ ops.push({ op: "richtext.insert_blocks", entity_id: doc.entity_id, position: { after: blockId }, blocks: rest });
31580
+ return ops;
31581
+ }
31582
+ function textDeleteBlocks(doc, blockIds, reads) {
31583
+ if (blockIds.length === 0)
31584
+ return [];
31585
+ return [{
31586
+ op: "richtext.delete_blocks",
31587
+ entity_id: doc.entity_id,
31588
+ blocks: blockIds.map((b2) => {
31589
+ const s = blockState(doc, b2, reads);
31590
+ return { block_id: b2, expect: { hash: s.hash, struct_rev: s.struct_rev } };
31591
+ })
31592
+ }];
31593
+ }
31594
+ function rename(entity, name) {
31595
+ var _a2;
31596
+ const rev = entity.meta_rev ?? ((_a2 = entity.version) == null ? void 0 : _a2.meta_rev);
31597
+ if (typeof rev !== "number")
31598
+ throw failure(`entity ${entity.entity_id}: pass it as doc.read answers it (meta_rev)`, "INVALID_OPERATION");
31599
+ return { op: "entity.rename", entity_id: entity.entity_id, name, expect: { rev } };
31600
+ }
31601
+ function move(entity, parentId, after, before) {
31602
+ var _a2;
31603
+ const rev = typeof entity === "string" ? void 0 : entity.struct_rev ?? ((_a2 = entity.version) == null ? void 0 : _a2.struct_rev);
31604
+ return { op: "tree.move", entity_id: idOf(entity), new_parent_id: parentId, order_key: orderKeyBetween(after ?? null, before ?? null), ...typeof rev === "number" ? { expect: { rev } } : {} };
31605
+ }
31606
+ function setProps(entity, key, props, read) {
31607
+ var _a2, _b2;
31608
+ const revs = (_b2 = (_a2 = read ?? (typeof entity === "string" ? void 0 : entity)) == null ? void 0 : _a2.content) == null ? void 0 : _b2.key_revs;
31609
+ return {
31610
+ op: "entity.set_props",
31611
+ entity_id: idOf(entity),
31612
+ key,
31613
+ props,
31614
+ ...revs ? { expect: Object.fromEntries(Object.keys(props).map((n2) => [n2, revs[`p:${key}.${n2}`] ?? 0])) } : {}
31615
+ };
31616
+ }
31617
+ function settle(result) {
31618
+ var _a2;
31619
+ if ((result == null ? void 0 : result.status) === "accepted")
31620
+ return result;
31621
+ if ((result == null ? void 0 : result.status) === "conflict") {
31622
+ throw new AiwsFailure({ code: result.code ?? "REVISION_CONFLICT", retryable: true, detail: "changed meanwhile: read it again", data: { conflicts: result.conflicts ?? [] } });
31623
+ }
31624
+ const first = ((_a2 = result == null ? void 0 : result.errors) == null ? void 0 : _a2[0]) ?? (result == null ? void 0 : result.error);
31625
+ throw new AiwsFailure({
31626
+ code: (result == null ? void 0 : result.code) ?? (first == null ? void 0 : first.code) ?? "REJECTED",
31627
+ sub_code: (result == null ? void 0 : result.sub_code) ?? (first == null ? void 0 : first.sub_code),
31628
+ retryable: (result == null ? void 0 : result.retryable) === true,
31629
+ detail: (first == null ? void 0 : first.detail) ?? (result == null ? void 0 : result.detail) ?? `commit ${(result == null ? void 0 : result.status) ?? "failed"}`,
31630
+ data: { errors: (result == null ? void 0 : result.errors) ?? [] }
31631
+ });
31632
+ }
31633
+ async function commitOps(client, workspace_id, ops, opts = {}) {
31634
+ if (ops.length === 0)
31635
+ throw failure("nothing to commit", "INVALID_OPERATION");
31636
+ const over = commitOverLimit(ops);
31637
+ if (over)
31638
+ throw failure(`a Commit holds at most ${over.max} ${over.limit} (this one: ${over.value})`, "LIMIT_EXCEEDED");
31639
+ const epoch = opts.epoch ?? (await client.call("ws.get_info", { workspace_id })).epoch;
31640
+ const idempotency_key = opts.idempotencyKey ?? `aiws-${newRecordId("k")}`;
31641
+ const request = { protocol_version: AIWS_PROTOCOL_VERSION, workspace_id, epoch, idempotency_key, ...opts.message ? { message: opts.message } : {}, operations: ops };
31642
+ const call = (method, params) => client.call(method, params);
31643
+ const unknown = opts.isUnknown ?? ((error) => !(error instanceof AiwsFailure));
31644
+ const attempts = Math.max(1, opts.attempts ?? 3);
31645
+ for (let attempt2 = 1; ; attempt2++) {
31646
+ try {
31647
+ return settle(await commitWithParts(call, request, opts.partBytes ? { partBytes: opts.partBytes } : {}));
31648
+ } catch (error) {
31649
+ if (!unknown(error) || attempt2 >= attempts)
31650
+ throw error;
31651
+ }
31652
+ await new Promise((resolve) => setTimeout(resolve, (opts.retryDelayMs ?? 500) * attempt2));
31653
+ const found = await client.call("doc.get_submission", { workspace_id, epoch, idempotency_key }).catch(() => null);
31654
+ if ((found == null ? void 0 : found.status) === "accepted")
31655
+ return settle(found.result ?? { status: "accepted" });
31656
+ }
31657
+ }
31658
+ const FENCE_OPEN = /^( {0,3})(`{3,}|~{3,})[ \t]*([^\s`]*)[^`]*$/;
31659
+ const ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
31660
+ const HR = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
31661
+ const QUOTE = /^ {0,3}> ?(.*)$/;
31662
+ const BULLET = /^( {0,3})([-*+])([ \t]+|$)(.*)$/;
31663
+ const ORDERED = /^( {0,3})(\d{1,9})([.)])([ \t]+|$)(.*)$/;
31664
+ const TABLE_DELIM = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
31665
+ const SETEXT = /^ {0,3}(=+|-+)[ \t]*$/;
31666
+ const ESCAPABLE = /[!-/:-@[-`{-~]/;
31667
+ const ALLOWED_HREF = /^(https?:|mailto:|#)/;
31668
+ const ENTITY_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
31669
+ function listMarker(line) {
31670
+ if (HR.test(line))
31671
+ return null;
31672
+ const b2 = BULLET.exec(line);
31673
+ if (b2)
31674
+ return { ordered: false, start: 1, indent: b2[1].length + 1 + (b2[4] ? Math.min(Math.max(b2[3].length, 1), 4) : 1), text: b2[4] };
31675
+ const o = ORDERED.exec(line);
31676
+ if (o)
31677
+ return { ordered: true, start: Number(o[2]), indent: o[1].length + o[2].length + 1 + (o[5] ? Math.min(Math.max(o[4].length, 1), 4) : 1), text: o[5] };
31678
+ return null;
31679
+ }
31680
+ function interrupts(line) {
31681
+ if (FENCE_OPEN.test(line) || ATX.test(line) || HR.test(line) || QUOTE.test(line))
31682
+ return true;
31683
+ const m = listMarker(line);
31684
+ return !!m && m.text.trim() !== "" && (!m.ordered || m.start === 1);
31685
+ }
31686
+ const indentOf = (line) => /^ */.exec(line)[0].length;
31687
+ function tableCells(line) {
31688
+ let s = line.trim();
31689
+ if (s.startsWith("|"))
31690
+ s = s.slice(1);
31691
+ if (s.endsWith("|") && !s.endsWith("\\|"))
31692
+ s = s.slice(0, -1);
31693
+ const cells = [];
31694
+ let cur = "";
31695
+ for (let i = 0; i < s.length; i++) {
31696
+ if (s[i] === "\\" && s[i + 1] === "|") {
31697
+ cur += "|";
31698
+ i++;
31699
+ } else if (s[i] === "|") {
31700
+ cells.push(cur.trim());
31701
+ cur = "";
31702
+ } else
31703
+ cur += s[i];
31704
+ }
31705
+ cells.push(cur.trim());
31706
+ return cells;
31707
+ }
31708
+ function textNode(text, marks) {
31709
+ return marks.length ? { type: "text", text, marks } : { type: "text", text };
31710
+ }
31711
+ function closingRun(src, from, run) {
31712
+ for (let j = src.indexOf(run, from); j >= 0; j = src.indexOf(run, j + 1)) {
31713
+ if (src[j - 1] !== "`" && src[j + run.length] !== "`")
31714
+ return j;
31715
+ while (src[j + 1] === "`")
31716
+ j++;
31717
+ }
31718
+ return -1;
31719
+ }
31720
+ function linkAt(src, i) {
31721
+ let depth = 0;
31722
+ let j = i;
31723
+ for (; j < src.length; j++) {
31724
+ if (src[j] === "\\") {
31725
+ j++;
31726
+ continue;
31727
+ }
31728
+ if (src[j] === "[")
31729
+ depth++;
31730
+ else if (src[j] === "]" && --depth === 0)
31731
+ break;
31732
+ }
31733
+ if (j >= src.length || src[j + 1] !== "(")
31734
+ return null;
31735
+ const m = /^\(\s*(?:<([^<>\n]*)>|((?:[^\s()]|\([^\s()]*\))*))(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)/.exec(src.slice(j + 1));
31736
+ if (!m)
31737
+ return null;
31738
+ return { label: src.slice(i + 1, j), href: m[1] ?? m[2] ?? "", end: j + 1 + m[0].length };
31739
+ }
31740
+ function inline(src, marks, out) {
31741
+ let buf = "";
31742
+ const flush = () => {
31743
+ if (buf) {
31744
+ out.push(textNode(buf, marks));
31745
+ buf = "";
31746
+ }
31747
+ };
31748
+ const alnum = (c) => !!c && /[\p{L}\p{N}]/u.test(c);
31749
+ for (let i = 0; i < src.length; ) {
31750
+ const c = src[i];
31751
+ if (c === "\\" && i + 1 < src.length && ESCAPABLE.test(src[i + 1])) {
31752
+ buf += src[i + 1];
31753
+ i += 2;
31754
+ continue;
31755
+ }
31756
+ if (c === "\n") {
31757
+ flush();
31758
+ out.push({ type: "hard_break" });
31759
+ i++;
31760
+ continue;
31761
+ }
31762
+ if (c === "`") {
31763
+ const run = /^`+/.exec(src.slice(i))[0];
31764
+ const close = closingRun(src, i + run.length, run);
31765
+ if (close < 0) {
31766
+ buf += run;
31767
+ i += run.length;
31768
+ continue;
31769
+ }
31770
+ let code = src.slice(i + run.length, close).replace(/\n/g, " ");
31771
+ if (code.length > 2 && code.startsWith(" ") && code.endsWith(" ") && code.trim())
31772
+ code = code.slice(1, -1);
31773
+ flush();
31774
+ if (code)
31775
+ out.push(textNode(code, [{ type: "code" }]));
31776
+ i = close + run.length;
31777
+ continue;
31778
+ }
31779
+ if (c === "[" || c === "!" && src[i + 1] === "[") {
31780
+ const link = linkAt(src, c === "!" ? i + 1 : i);
31781
+ if (link) {
31782
+ flush();
31783
+ const entity = /^entity:(.+)$/.exec(link.href);
31784
+ if (entity && ENTITY_ID.test(entity[1])) {
31785
+ const label = [];
31786
+ inline(link.label, [], label);
31787
+ out.push({ type: "object_link", attrs: { ref: { entity_id: entity[1] }, label: label.map((n2) => n2.text ?? "").join("") } });
31788
+ } else {
31789
+ const href = ALLOWED_HREF.test(link.href) && !/[\u0000-\u001f\u007f]/.test(link.href) ? link.href : null;
31790
+ inline(link.label, href ? [...marks.filter((m) => m.type !== "link"), { type: "link", attrs: { href } }] : marks, out);
31791
+ }
31792
+ i = link.end;
31793
+ continue;
31794
+ }
31795
+ }
31796
+ if (c === "<") {
31797
+ const auto = /^<((?:https?|mailto):[^\s<>]+)>/.exec(src.slice(i));
31798
+ if (auto) {
31799
+ flush();
31800
+ out.push(textNode(auto[1], [...marks.filter((m) => m.type !== "link"), { type: "link", attrs: { href: auto[1] } }]));
31801
+ i += auto[0].length;
31802
+ continue;
31803
+ }
31804
+ }
31805
+ if (c === "*" || c === "_" || c === "~") {
31806
+ const double = src[i + 1] === c;
31807
+ const delim = double ? c + c : c;
31808
+ const opens = (c !== "~" || double) && src[i + delim.length] !== void 0 && !/\s/.test(src[i + delim.length]) && !(c === "_" && alnum(src[i - 1]));
31809
+ if (opens) {
31810
+ let close = -1;
31811
+ for (let j = i + delim.length + 1; j < src.length; j++) {
31812
+ if (src[j] === "\\") {
31813
+ j++;
31814
+ continue;
31815
+ }
31816
+ if (src[j] !== c)
31817
+ continue;
31818
+ let run = 1;
31819
+ while (src[j + run] === c)
31820
+ run++;
31821
+ if (!/\s/.test(src[j - 1]) && !(c === "_" && alnum(src[j + run]))) {
31822
+ if (double && run >= 2) {
31823
+ close = j + run - 2;
31824
+ break;
31825
+ }
31826
+ if (!double && run !== 2) {
31827
+ close = j + run - 1;
31828
+ break;
31829
+ }
31830
+ }
31831
+ j += run - 1;
31832
+ }
31833
+ if (close > 0) {
31834
+ flush();
31835
+ const type = c === "~" ? "strike" : double ? "strong" : "em";
31836
+ inline(src.slice(i + delim.length, close), marks.some((m) => m.type === type) ? marks : [...marks, { type }], out);
31837
+ i = close + delim.length;
31838
+ continue;
31839
+ }
31840
+ }
31841
+ buf += delim;
31842
+ i += delim.length;
31843
+ continue;
31844
+ }
31845
+ buf += c;
31846
+ i++;
31847
+ }
31848
+ flush();
31849
+ }
31850
+ function inlineNodes(text) {
31851
+ const out = [];
31852
+ inline(text, [], out);
31853
+ const merged = [];
31854
+ for (const n2 of out) {
31855
+ const last = merged[merged.length - 1];
31856
+ if (last && n2.type === "text" && last.type === "text" && JSON.stringify(last.marks ?? []) === JSON.stringify(n2.marks ?? []))
31857
+ last.text += n2.text ?? "";
31858
+ else
31859
+ merged.push(n2);
31860
+ }
31861
+ return merged;
31862
+ }
31863
+ function paragraphText(lines) {
31864
+ return lines.map((l, k) => {
31865
+ const t = l.replace(/^[ \t]+/, "");
31866
+ if (k === lines.length - 1)
31867
+ return t.trimEnd();
31868
+ if (/( {2,}|\\)$/.test(t))
31869
+ return `${t.replace(/( {2,}|\\)$/, "")}
31870
+ `;
31871
+ return `${t.trimEnd()} `;
31872
+ }).join("");
31873
+ }
31874
+ class MarkdownBlocks {
31875
+ constructor(prefix) {
31876
+ this.prefix = prefix;
31877
+ this.n = 0;
31878
+ }
31879
+ id() {
31880
+ return `${this.prefix}-${++this.n}`;
31881
+ }
31882
+ textblock(type, text, attrs = {}) {
31883
+ const node = { type, attrs: { block_id: this.id(), ...attrs } };
31884
+ const content = inlineNodes(text);
31885
+ if (content.length)
31886
+ node.content = content;
31887
+ return node;
31888
+ }
31889
+ empty() {
31890
+ return { type: "paragraph", attrs: { block_id: this.id() } };
31891
+ }
31892
+ blocks(lines) {
31893
+ const out = [];
31894
+ let i = 0;
31895
+ while (i < lines.length) {
31896
+ const line = lines[i];
31897
+ if (!line.trim()) {
31898
+ i++;
31899
+ continue;
31900
+ }
31901
+ let m;
31902
+ if (m = FENCE_OPEN.exec(line)) {
31903
+ const [, indent, fence, lang] = m;
31904
+ const body = [];
31905
+ i++;
31906
+ while (i < lines.length) {
31907
+ const close = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(lines[i]);
31908
+ if (close && close[1][0] === fence[0] && close[1].length >= fence.length) {
31909
+ i++;
31910
+ break;
31911
+ }
31912
+ body.push(lines[i].slice(Math.min(indent.length, indentOf(lines[i]))));
31913
+ i++;
31914
+ }
31915
+ const node = { type: "code_block", attrs: { block_id: this.id(), ...lang ? { language: lang.slice(0, 32) } : {} } };
31916
+ const text = body.join("\n");
31917
+ if (text)
31918
+ node.content = [{ type: "text", text }];
31919
+ out.push(node);
31920
+ } else if (m = ATX.exec(line)) {
31921
+ const level = Math.min(m[1].length, 3);
31922
+ out.push(this.textblock("heading", m[2] ?? "", level === 1 ? {} : { level }));
31923
+ i++;
31924
+ } else if (HR.test(line)) {
31925
+ out.push({ type: "horizontal_rule", attrs: { block_id: this.id() } });
31926
+ i++;
31927
+ } else if (QUOTE.test(line)) {
31928
+ const id2 = this.id();
31929
+ const inner = [];
31930
+ while (i < lines.length) {
31931
+ const q = QUOTE.exec(lines[i]);
31932
+ if (q)
31933
+ inner.push(q[1]);
31934
+ else if (lines[i].trim() && inner.length && inner[inner.length - 1].trim() && !interrupts(lines[i]))
31935
+ inner.push(lines[i]);
31936
+ else
31937
+ break;
31938
+ i++;
31939
+ }
31940
+ const content = this.blocks(inner).flatMap((b2) => b2.type === "blockquote" ? b2.content ?? [] : [b2]).filter((b2) => ["paragraph", "heading", "bullet_list", "ordered_list", "code_block"].includes(b2.type));
31941
+ out.push({ type: "blockquote", attrs: { block_id: id2 }, content: content.length ? content : [this.empty()] });
31942
+ } else if (listMarker(line)) {
31943
+ i = this.list(lines, i, out);
31944
+ } else if (line.includes("|") && i + 1 < lines.length && lines[i + 1].includes("-") && TABLE_DELIM.test(lines[i + 1]) && tableCells(line).length === tableCells(lines[i + 1]).length) {
31945
+ const header = tableCells(line);
31946
+ const id2 = this.id();
31947
+ const row = (cells, head) => ({
31948
+ type: "table_row",
31949
+ content: header.map((_, k) => {
31950
+ const cell = { type: "table_cell", ...head ? { attrs: { header: 1 } } : {} };
31951
+ const content = inlineNodes(cells[k] ?? "");
31952
+ if (content.length)
31953
+ cell.content = content;
31954
+ return cell;
31955
+ })
31956
+ });
31957
+ const rows = [row(header, true)];
31958
+ i += 2;
31959
+ while (i < lines.length && lines[i].trim() && !interrupts(lines[i]))
31960
+ rows.push(row(tableCells(lines[i++]), false));
31961
+ out.push({ type: "table", attrs: { block_id: id2 }, content: rows });
31962
+ } else {
31963
+ const para = [line];
31964
+ i++;
31965
+ let level = 0;
31966
+ while (i < lines.length && lines[i].trim()) {
31967
+ const setext = SETEXT.exec(lines[i]);
31968
+ if (setext) {
31969
+ level = setext[1][0] === "=" ? 1 : 2;
31970
+ i++;
31971
+ break;
31972
+ }
31973
+ if (interrupts(lines[i]))
31974
+ break;
31975
+ para.push(lines[i++]);
31976
+ }
31977
+ out.push(level ? this.textblock("heading", paragraphText(para).replace(/\n/g, " "), level === 1 ? {} : { level }) : this.textblock("paragraph", paragraphText(para)));
31978
+ }
31979
+ }
31980
+ return out;
31981
+ }
31982
+ /** A list from `lines[i]`: its items while the marker kind stays; returns the index after it. */
31983
+ list(lines, i, out) {
31984
+ const first = listMarker(lines[i]);
31985
+ const list = { type: first.ordered ? "ordered_list" : "bullet_list", attrs: { block_id: this.id(), ...first.ordered && first.start !== 1 ? { start: Math.max(1, first.start) } : {} }, content: [] };
31986
+ while (i < lines.length) {
31987
+ const mk = listMarker(lines[i]);
31988
+ if (!mk || mk.ordered !== first.ordered)
31989
+ break;
31990
+ const item = [mk.text];
31991
+ i++;
31992
+ while (i < lines.length) {
31993
+ const l = lines[i];
31994
+ if (!l.trim())
31995
+ item.push("");
31996
+ else if (indentOf(l) >= mk.indent)
31997
+ item.push(l.slice(mk.indent));
31998
+ else if (item[item.length - 1].trim() && !interrupts(l) && !listMarker(l))
31999
+ item.push(l.trim());
32000
+ else
32001
+ break;
32002
+ i++;
32003
+ }
32004
+ while (item.length && !item[item.length - 1].trim())
32005
+ item.pop();
32006
+ list.content.push(this.item(item));
32007
+ }
32008
+ out.push(list);
32009
+ return i;
32010
+ }
32011
+ /** A list item holds one paragraph, then paragraphs and lists only (as the core's converter makes it). */
32012
+ item(lines) {
32013
+ var _a2;
32014
+ const id2 = this.id();
32015
+ const task = /^\[([ xX])\][ \t]+/.exec(lines[0] ?? "");
32016
+ if (task)
32017
+ lines = [`${task[1] === " " ? "☐" : "☑"} ${lines[0].slice(task[0].length)}`, ...lines.slice(1)];
32018
+ const content = [];
32019
+ for (const b2 of this.blocks(lines)) {
32020
+ if (b2.type === "paragraph" || b2.type === "bullet_list" || b2.type === "ordered_list")
32021
+ content.push(b2);
32022
+ else if (b2.type === "heading" || b2.type === "code_block")
32023
+ content.push({ type: "paragraph", attrs: { block_id: b2.attrs.block_id }, ...b2.content ? { content: b2.content } : {} });
32024
+ else if (b2.type === "blockquote")
32025
+ content.push(...(b2.content ?? []).filter((c) => c.type === "paragraph"));
32026
+ }
32027
+ if (((_a2 = content[0]) == null ? void 0 : _a2.type) !== "paragraph")
32028
+ content.unshift(this.empty());
32029
+ return { type: "list_item", attrs: { block_id: id2 }, content };
32030
+ }
32031
+ }
32032
+ function markdownToBlocks(markdown, prefix) {
32033
+ const b2 = new MarkdownBlocks(prefix ?? `m${Math.floor(Math.random() * 36 ** 8).toString(36).padStart(8, "0")}`);
32034
+ const lines = markdown.replace(/\r\n?/g, "\n").split("\n").map((l) => l.replace(/^[ \t]+/, (ws) => ws.replace(/\t/g, " ")));
32035
+ const blocks = b2.blocks(lines);
32036
+ return blocks.length ? blocks : [b2.empty()];
32037
+ }
31603
32038
  export {
31604
32039
  CONTACT_TAG_ZONE_AGENT as $,
31605
32040
  NOTIFY_ACTION_ANSWER as A,
@@ -31770,13 +32205,17 @@ export {
31770
32205
  parseAppInstanceId as c7,
31771
32206
  BNS_EVM_DEFAULT_GAS_LIMIT as c8,
31772
32207
  BNS_EVM_DEFAULT_MAX_FEE_PER_GAS as c9,
31773
- splitCommitOperations as cA,
31774
- commitOverLimit as cB,
31775
- commitWithParts as cC,
31776
- AiWorkspaceClient as cD,
31777
- importFiles as cE,
31778
- ensureUploaded as cF,
31779
- releaseImportSession as cG,
32208
+ textAppend as cA,
32209
+ textReplaceBlock as cB,
32210
+ textDeleteBlocks as cC,
32211
+ rename as cD,
32212
+ move as cE,
32213
+ setProps as cF,
32214
+ commitOps as cG,
32215
+ markdownToBlocks as cH,
32216
+ importFiles as cI,
32217
+ ensureUploaded as cJ,
32218
+ releaseImportSession as cK,
31780
32219
  BNS_EVM_DEFAULT_MAX_PRIORITY_FEE_PER_GAS as ca,
31781
32220
  BNS_MAX_INLINE_DOCUMENT_BYTES as cb,
31782
32221
  BNS_DNS_TXT_DEFAULT_TTL as cc,
@@ -31796,13 +32235,13 @@ export {
31796
32235
  ExecutorStreamError as cq,
31797
32236
  encodeExecutorControl as cr,
31798
32237
  ExecutorCommandStream as cs,
31799
- AIWORKSPACE_SERVICE_NAME as ct,
31800
- AiwsFailure as cu,
31801
- aiwsReferenceUrl as cv,
31802
- parseAiwsReferenceUrl as cw,
31803
- AIWS_COMMIT_PART_BYTES as cx,
31804
- AIWS_COMMIT_MAX_BYTES as cy,
31805
- AIWS_COMMIT_MAX_OPERATIONS as cz,
32238
+ fieldNamed as ct,
32239
+ cellValue as cu,
32240
+ tableInsert as cv,
32241
+ tableSet as cw,
32242
+ tableDelete as cx,
32243
+ fieldAdd as cy,
32244
+ optionAdd as cz,
31806
32245
  ndm_proxy as d,
31807
32246
  bucket_client as e,
31808
32247
  BS_SERVICE_TASK_MANAGER as f,
@@ -31827,4 +32266,4 @@ export {
31827
32266
  NOTIFY_CHOICE_CONTROL_ID as y,
31828
32267
  NOTIFY_TEXT_CONTROL_ID as z
31829
32268
  };
31830
- //# sourceMappingURL=executor_client-bfc8a1e1.mjs.map
32269
+ //# sourceMappingURL=aiws_write-c2de498e.mjs.map